Merge "Switch to a thread pool for aio operations" am: dd946e87b8
am: ccf9b815fd

Change-Id: I9649a53e4b62ff7bc1968c9c00bbd37f3b0ad6da
diff --git a/camera/ndk/include/camera/NdkCameraCaptureSession.h b/camera/ndk/include/camera/NdkCameraCaptureSession.h
index 78e062a..9bf8247 100644
--- a/camera/ndk/include/camera/NdkCameraCaptureSession.h
+++ b/camera/ndk/include/camera/NdkCameraCaptureSession.h
@@ -45,8 +45,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraCaptureSession is an opaque type that manages frame captures of a camera device.
  *
@@ -434,7 +432,7 @@
  *
  */
 camera_status_t ACameraCaptureSession_getDevice(
-        ACameraCaptureSession* session, /*out*/ACameraDevice** device);
+        ACameraCaptureSession* session, /*out*/ACameraDevice** device) __INTRODUCED_IN(24);
 
 /**
  * Submit an array of requests to be captured in sequence as a burst in the minimum of time possible.
@@ -472,7 +470,7 @@
         ACameraCaptureSession* session,
         /*optional*/ACameraCaptureSession_captureCallbacks* callbacks,
         int numRequests, ACaptureRequest** requests,
-        /*optional*/int* captureSequenceId);
+        /*optional*/int* captureSequenceId) __INTRODUCED_IN(24);
 
 /**
  * Request endlessly repeating capture of a sequence of images by this capture session.
@@ -526,7 +524,7 @@
         ACameraCaptureSession* session,
         /*optional*/ACameraCaptureSession_captureCallbacks* callbacks,
         int numRequests, ACaptureRequest** requests,
-        /*optional*/int* captureSequenceId);
+        /*optional*/int* captureSequenceId) __INTRODUCED_IN(24);
 
 /**
  * Cancel any ongoing repeating capture set by {@link ACameraCaptureSession_setRepeatingRequest}.
@@ -549,7 +547,8 @@
  *         <li>{@link ACAMERA_ERROR_CAMERA_SERVICE} if the camera service encounters fatal error</li>
  *         <li>{@link ACAMERA_ERROR_UNKNOWN} if the method fails for some other reasons</li></ul>
  */
-camera_status_t ACameraCaptureSession_stopRepeating(ACameraCaptureSession* session);
+camera_status_t ACameraCaptureSession_stopRepeating(ACameraCaptureSession* session)
+        __INTRODUCED_IN(24);
 
 /**
  * Discard all captures currently pending and in-progress as fast as possible.
@@ -589,11 +588,8 @@
  *         <li>{@link ACAMERA_ERROR_CAMERA_SERVICE} if the camera service encounters fatal error</li>
  *         <li>{@link ACAMERA_ERROR_UNKNOWN} if the method fails for some other reasons</li></ul>
  */
-camera_status_t ACameraCaptureSession_abortCaptures(ACameraCaptureSession* session);
-
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
+camera_status_t ACameraCaptureSession_abortCaptures(ACameraCaptureSession* session)
+        __INTRODUCED_IN(24);
 
 typedef struct ACaptureSessionOutput ACaptureSessionOutput;
 
@@ -638,8 +634,7 @@
  *         <li>{@link ACAMERA_ERROR_UNKNOWN} if the method fails for some other reasons</li></ul>
  */
 camera_status_t ACameraCaptureSession_updateSharedOutput(ACameraCaptureSession* session,
-        ACaptureSessionOutput* output);
-#endif /* __ANDROID_API__ >= 28 */
+        ACaptureSessionOutput* output) __INTRODUCED_IN(28);
 
 __END_DECLS
 
diff --git a/camera/ndk/include/camera/NdkCameraDevice.h b/camera/ndk/include/camera/NdkCameraDevice.h
index b715b12..bdd27f9 100644
--- a/camera/ndk/include/camera/NdkCameraDevice.h
+++ b/camera/ndk/include/camera/NdkCameraDevice.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraDevice is opaque type that provides access to a camera device.
  *
@@ -176,7 +174,7 @@
  *         <li>{@link ACAMERA_OK} if the method call succeeds.</li>
  *         <li>{@link ACAMERA_ERROR_INVALID_PARAMETER} if device is NULL.</li></ul>
  */
-camera_status_t ACameraDevice_close(ACameraDevice* device);
+camera_status_t ACameraDevice_close(ACameraDevice* device) __INTRODUCED_IN(24);
 
 /**
  * Return the camera id associated with this camera device.
@@ -187,7 +185,7 @@
  * delete/free by the application. Also the returned string must not be used after the device
  * has been closed.
  */
-const char* ACameraDevice_getId(const ACameraDevice* device);
+const char* ACameraDevice_getId(const ACameraDevice* device) __INTRODUCED_IN(24);
 
 typedef enum {
     /**
@@ -290,7 +288,7 @@
  */
 camera_status_t ACameraDevice_createCaptureRequest(
         const ACameraDevice* device, ACameraDevice_request_template templateId,
-        /*out*/ACaptureRequest** request);
+        /*out*/ACaptureRequest** request) __INTRODUCED_IN(24);
 
 
 typedef struct ACaptureSessionOutputContainer ACaptureSessionOutputContainer;
@@ -313,7 +311,7 @@
  *         <li>{@link ACAMERA_ERROR_INVALID_PARAMETER} if container is NULL.</li></ul>
  */
 camera_status_t ACaptureSessionOutputContainer_create(
-        /*out*/ACaptureSessionOutputContainer** container);
+        /*out*/ACaptureSessionOutputContainer** container) __INTRODUCED_IN(24);
 
 /**
  * Free a capture session output container.
@@ -322,7 +320,8 @@
  *
  * @see ACaptureSessionOutputContainer_create
  */
-void            ACaptureSessionOutputContainer_free(ACaptureSessionOutputContainer* container);
+void            ACaptureSessionOutputContainer_free(ACaptureSessionOutputContainer* container)
+        __INTRODUCED_IN(24);
 
 /**
  * Create a ACaptureSessionOutput object.
@@ -344,7 +343,7 @@
  * @see ACaptureSessionOutputContainer_add
  */
 camera_status_t ACaptureSessionOutput_create(
-        ANativeWindow* anw, /*out*/ACaptureSessionOutput** output);
+        ANativeWindow* anw, /*out*/ACaptureSessionOutput** output) __INTRODUCED_IN(24);
 
 /**
  * Free a ACaptureSessionOutput object.
@@ -353,7 +352,7 @@
  *
  * @see ACaptureSessionOutput_create
  */
-void            ACaptureSessionOutput_free(ACaptureSessionOutput* output);
+void            ACaptureSessionOutput_free(ACaptureSessionOutput* output) __INTRODUCED_IN(24);
 
 /**
  * Add an {@link ACaptureSessionOutput} object to {@link ACaptureSessionOutputContainer}.
@@ -366,7 +365,8 @@
  *         <li>{@link ACAMERA_ERROR_INVALID_PARAMETER} if container or output is NULL.</li></ul>
  */
 camera_status_t ACaptureSessionOutputContainer_add(
-        ACaptureSessionOutputContainer* container, const ACaptureSessionOutput* output);
+        ACaptureSessionOutputContainer* container, const ACaptureSessionOutput* output)
+        __INTRODUCED_IN(24);
 
 /**
  * Remove an {@link ACaptureSessionOutput} object from {@link ACaptureSessionOutputContainer}.
@@ -382,7 +382,8 @@
  *         <li>{@link ACAMERA_ERROR_INVALID_PARAMETER} if container or output is NULL.</li></ul>
  */
 camera_status_t ACaptureSessionOutputContainer_remove(
-        ACaptureSessionOutputContainer* container, const ACaptureSessionOutput* output);
+        ACaptureSessionOutputContainer* container, const ACaptureSessionOutput* output)
+        __INTRODUCED_IN(24);
 
 /**
  * Create a new camera capture session by providing the target output set of {@link ANativeWindow}
@@ -663,11 +664,7 @@
         ACameraDevice* device,
         const ACaptureSessionOutputContainer*       outputs,
         const ACameraCaptureSession_stateCallbacks* callbacks,
-        /*out*/ACameraCaptureSession** session);
-
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
+        /*out*/ACameraCaptureSession** session) __INTRODUCED_IN(24);
 
 /**
  * Create a shared ACaptureSessionOutput object.
@@ -691,7 +688,7 @@
  * @see ACaptureSessionOutputContainer_add
  */
 camera_status_t ACaptureSessionSharedOutput_create(
-        ANativeWindow* anw, /*out*/ACaptureSessionOutput** output);
+        ANativeWindow* anw, /*out*/ACaptureSessionOutput** output) __INTRODUCED_IN(28);
 
 /**
  * Add a native window to shared ACaptureSessionOutput.
@@ -708,7 +705,8 @@
  *             window associated with ACaptureSessionOutput; or anw is already present inside
  *             ACaptureSessionOutput.</li></ul>
  */
-camera_status_t ACaptureSessionSharedOutput_add(ACaptureSessionOutput *output, ANativeWindow *anw);
+camera_status_t ACaptureSessionSharedOutput_add(ACaptureSessionOutput *output,
+        ANativeWindow *anw) __INTRODUCED_IN(28);
 
 /**
  * Remove a native window from shared ACaptureSessionOutput.
@@ -724,7 +722,7 @@
  *             ACaptureSessionOutput.</li></ul>
  */
 camera_status_t ACaptureSessionSharedOutput_remove(ACaptureSessionOutput *output,
-        ANativeWindow* anw);
+        ANativeWindow* anw) __INTRODUCED_IN(28);
 
 /**
  * Create a new camera capture session similar to {@link ACameraDevice_createCaptureSession}. This
@@ -757,9 +755,7 @@
         const ACaptureSessionOutputContainer* outputs,
         const ACaptureRequest* sessionParameters,
         const ACameraCaptureSession_stateCallbacks* callbacks,
-        /*out*/ACameraCaptureSession** session);
-
-#endif /* __ANDROID_API__ >= 28 */
+        /*out*/ACameraCaptureSession** session) __INTRODUCED_IN(28);
 
 __END_DECLS
 
diff --git a/camera/ndk/include/camera/NdkCameraError.h b/camera/ndk/include/camera/NdkCameraError.h
index 6b58155..e19ce36 100644
--- a/camera/ndk/include/camera/NdkCameraError.h
+++ b/camera/ndk/include/camera/NdkCameraError.h
@@ -40,8 +40,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 typedef enum {
     ACAMERA_OK = 0,
 
@@ -132,8 +130,6 @@
     ACAMERA_ERROR_PERMISSION_DENIED     = ACAMERA_ERROR_BASE - 13,
 } camera_status_t;
 
-#endif /* __ANDROID_API__ >= 24 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_ERROR_H */
diff --git a/camera/ndk/include/camera/NdkCameraManager.h b/camera/ndk/include/camera/NdkCameraManager.h
index e5b3ad8..a1cca4d 100644
--- a/camera/ndk/include/camera/NdkCameraManager.h
+++ b/camera/ndk/include/camera/NdkCameraManager.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraManager is opaque type that provides access to camera service.
  *
@@ -65,14 +63,14 @@
  * @return a {@link ACameraManager} instance.
  *
  */
-ACameraManager* ACameraManager_create();
+ACameraManager* ACameraManager_create() __INTRODUCED_IN(24);
 
 /**
  * <p>Delete the {@link ACameraManager} instance and free its resources. </p>
  *
  * @param manager the {@link ACameraManager} instance to be deleted.
  */
-void ACameraManager_delete(ACameraManager* manager);
+void ACameraManager_delete(ACameraManager* manager) __INTRODUCED_IN(24);
 
 /// Struct to hold list of camera devices
 typedef struct ACameraIdList {
@@ -102,14 +100,14 @@
  *         <li>{@link ACAMERA_ERROR_NOT_ENOUGH_MEMORY} if allocating memory fails.</li></ul>
  */
 camera_status_t ACameraManager_getCameraIdList(ACameraManager* manager,
-                                              /*out*/ACameraIdList** cameraIdList);
+        /*out*/ACameraIdList** cameraIdList) __INTRODUCED_IN(24);
 
 /**
  * Delete a list of camera devices allocated via {@link ACameraManager_getCameraIdList}.
  *
  * @param cameraIdList the {@link ACameraIdList} to be deleted.
  */
-void ACameraManager_deleteCameraIdList(ACameraIdList* cameraIdList);
+void ACameraManager_deleteCameraIdList(ACameraIdList* cameraIdList) __INTRODUCED_IN(24);
 
 /**
  * Definition of camera availability callbacks.
@@ -120,7 +118,8 @@
  *                 argument is owned by camera framework and will become invalid immediately after
  *                 this callback returns.
  */
-typedef void (*ACameraManager_AvailabilityCallback)(void* context, const char* cameraId);
+typedef void (*ACameraManager_AvailabilityCallback)(void* context,
+        const char* cameraId) __INTRODUCED_IN(24);
 
 /**
  * A listener for camera devices becoming available or unavailable to open.
@@ -168,7 +167,8 @@
  *                  {ACameraManager_AvailabilityCallbacks#onCameraUnavailable} is NULL.</li></ul>
  */
 camera_status_t ACameraManager_registerAvailabilityCallback(
-        ACameraManager* manager, const ACameraManager_AvailabilityCallbacks* callback);
+        ACameraManager* manager,
+        const ACameraManager_AvailabilityCallbacks* callback) __INTRODUCED_IN(24);
 
 /**
  * Unregister camera availability callbacks.
@@ -185,7 +185,8 @@
  *                  {ACameraManager_AvailabilityCallbacks#onCameraUnavailable} is NULL.</li></ul>
  */
 camera_status_t ACameraManager_unregisterAvailabilityCallback(
-        ACameraManager* manager, const ACameraManager_AvailabilityCallbacks* callback);
+        ACameraManager* manager,
+        const ACameraManager_AvailabilityCallbacks* callback) __INTRODUCED_IN(24);
 
 /**
  * Query the capabilities of a camera device. These capabilities are
@@ -211,7 +212,7 @@
  */
 camera_status_t ACameraManager_getCameraCharacteristics(
         ACameraManager* manager, const char* cameraId,
-        /*out*/ACameraMetadata** characteristics);
+        /*out*/ACameraMetadata** characteristics) __INTRODUCED_IN(24);
 
 /**
  * Open a connection to a camera with the given ID. The opened camera device will be
@@ -271,9 +272,7 @@
 camera_status_t ACameraManager_openCamera(
         ACameraManager* manager, const char* cameraId,
         ACameraDevice_StateCallbacks* callback,
-        /*out*/ACameraDevice** device);
-
-#endif /* __ANDROID_API__ >= 24 */
+        /*out*/ACameraDevice** device) __INTRODUCED_IN(24);
 
 __END_DECLS
 
diff --git a/camera/ndk/include/camera/NdkCameraMetadata.h b/camera/ndk/include/camera/NdkCameraMetadata.h
index bdb1587..2078da7 100644
--- a/camera/ndk/include/camera/NdkCameraMetadata.h
+++ b/camera/ndk/include/camera/NdkCameraMetadata.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 /**
  * ACameraMetadata is opaque type that provides access to read-only camera metadata like camera
  * characteristics (via {@link ACameraManager_getCameraCharacteristics}) or capture results (via
@@ -191,7 +189,8 @@
  *             of input tag value.</li></ul>
  */
 camera_status_t ACameraMetadata_getConstEntry(
-        const ACameraMetadata* metadata, uint32_t tag, /*out*/ACameraMetadata_const_entry* entry);
+        const ACameraMetadata* metadata,
+        uint32_t tag, /*out*/ACameraMetadata_const_entry* entry) __INTRODUCED_IN(24);
 
 /**
  * List all the entry tags in input {@link ACameraMetadata}.
@@ -208,7 +207,8 @@
  *         <li>{@link ACAMERA_ERROR_UNKNOWN} if the method fails for some other reasons.</li></ul>
  */
 camera_status_t ACameraMetadata_getAllTags(
-        const ACameraMetadata* metadata, /*out*/int32_t* numEntries, /*out*/const uint32_t** tags);
+        const ACameraMetadata* metadata,
+        /*out*/int32_t* numEntries, /*out*/const uint32_t** tags) __INTRODUCED_IN(24);
 
 /**
  * Create a copy of input {@link ACameraMetadata}.
@@ -220,16 +220,14 @@
  *
  * @return a valid ACameraMetadata pointer or NULL if the input metadata cannot be copied.
  */
-ACameraMetadata* ACameraMetadata_copy(const ACameraMetadata* src);
+ACameraMetadata* ACameraMetadata_copy(const ACameraMetadata* src) __INTRODUCED_IN(24);
 
 /**
  * Free a {@link ACameraMetadata} structure.
  *
  * @param metadata the {@link ACameraMetadata} to be freed.
  */
-void ACameraMetadata_free(ACameraMetadata* metadata);
-
-#endif /* __ANDROID_API__ >= 24 */
+void ACameraMetadata_free(ACameraMetadata* metadata) __INTRODUCED_IN(24);
 
 __END_DECLS
 
diff --git a/camera/ndk/include/camera/NdkCameraMetadataTags.h b/camera/ndk/include/camera/NdkCameraMetadataTags.h
index 3010646..7398f78 100644
--- a/camera/ndk/include/camera/NdkCameraMetadataTags.h
+++ b/camera/ndk/include/camera/NdkCameraMetadataTags.h
@@ -40,8 +40,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 typedef enum acamera_metadata_section {
     ACAMERA_COLOR_CORRECTION,
     ACAMERA_CONTROL,
@@ -479,11 +477,26 @@
      * Otherwise will always be present.</p>
      * <p>The maximum number of regions supported by the device is determined by the value
      * of android.control.maxRegionsAe.</p>
-     * <p>The coordinate system is based on the active pixel array,
-     * with (0,0) being the top-left pixel in the active pixel array, and
+     * <p>For devices not supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system always follows that of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with (0,0) being
+     * the top-left pixel in the active pixel array, and
      * (ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.width - 1,
-     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the
-     * bottom-right pixel in the active pixel array.</p>
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right pixel in the
+     * active pixel array.</p>
+     * <p>For devices supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system depends on the mode being set.
+     * When the distortion correction mode is OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the pre-correction active array, and
+     * (ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE.width - 1,
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right
+     * pixel in the pre-correction active pixel array.
+     * When the distortion correction mode is not OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the active array, and
+     * (ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.width - 1,
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right pixel in the
+     * active pixel array.</p>
      * <p>The weight must be within <code>[0, 1000]</code>, and represents a weight
      * for every pixel in the area. This means that a large metering area
      * with the same weight as a smaller area will have more effect in
@@ -504,8 +517,10 @@
      * The rectangle is defined to be inclusive on xmin and ymin, but exclusive on xmax and
      * ymax.</p>
      *
+     * @see ACAMERA_DISTORTION_CORRECTION_MODE
      * @see ACAMERA_SCALER_CROP_REGION
      * @see ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE
+     * @see ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     ACAMERA_CONTROL_AE_REGIONS =                                // int32[5*area_count]
             ACAMERA_CONTROL_START + 4,
@@ -641,11 +656,26 @@
      * Otherwise will always be present.</p>
      * <p>The maximum number of focus areas supported by the device is determined by the value
      * of android.control.maxRegionsAf.</p>
-     * <p>The coordinate system is based on the active pixel array,
-     * with (0,0) being the top-left pixel in the active pixel array, and
+     * <p>For devices not supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system always follows that of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with (0,0) being
+     * the top-left pixel in the active pixel array, and
      * (ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.width - 1,
-     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the
-     * bottom-right pixel in the active pixel array.</p>
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right pixel in the
+     * active pixel array.</p>
+     * <p>For devices supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system depends on the mode being set.
+     * When the distortion correction mode is OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the pre-correction active array, and
+     * (ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE.width - 1,
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right
+     * pixel in the pre-correction active pixel array.
+     * When the distortion correction mode is not OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the active array, and
+     * (ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.width - 1,
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right pixel in the
+     * active pixel array.</p>
      * <p>The weight must be within <code>[0, 1000]</code>, and represents a weight
      * for every pixel in the area. This means that a large metering area
      * with the same weight as a smaller area will have more effect in
@@ -667,8 +697,10 @@
      * The rectangle is defined to be inclusive on xmin and ymin, but exclusive on xmax and
      * ymax.</p>
      *
+     * @see ACAMERA_DISTORTION_CORRECTION_MODE
      * @see ACAMERA_SCALER_CROP_REGION
      * @see ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE
+     * @see ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     ACAMERA_CONTROL_AF_REGIONS =                                // int32[5*area_count]
             ACAMERA_CONTROL_START + 8,
@@ -800,11 +832,26 @@
      * Otherwise will always be present.</p>
      * <p>The maximum number of regions supported by the device is determined by the value
      * of android.control.maxRegionsAwb.</p>
-     * <p>The coordinate system is based on the active pixel array,
-     * with (0,0) being the top-left pixel in the active pixel array, and
+     * <p>For devices not supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system always follows that of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with (0,0) being
+     * the top-left pixel in the active pixel array, and
      * (ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.width - 1,
-     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the
-     * bottom-right pixel in the active pixel array.</p>
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right pixel in the
+     * active pixel array.</p>
+     * <p>For devices supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system depends on the mode being set.
+     * When the distortion correction mode is OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the pre-correction active array, and
+     * (ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE.width - 1,
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right
+     * pixel in the pre-correction active pixel array.
+     * When the distortion correction mode is not OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the active array, and
+     * (ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.width - 1,
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.height - 1) being the bottom-right pixel in the
+     * active pixel array.</p>
      * <p>The weight must range from 0 to 1000, and represents a weight
      * for every pixel in the area. This means that a large metering area
      * with the same weight as a smaller area will have more effect in
@@ -825,8 +872,10 @@
      * The rectangle is defined to be inclusive on xmin and ymin, but exclusive on xmax and
      * ymax.</p>
      *
+     * @see ACAMERA_DISTORTION_CORRECTION_MODE
      * @see ACAMERA_SCALER_CROP_REGION
      * @see ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE
+     * @see ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     ACAMERA_CONTROL_AWB_REGIONS =                               // int32[5*area_count]
             ACAMERA_CONTROL_START + 12,
@@ -2979,9 +3028,17 @@
      * </ul></p>
      *
      * <p>This control can be used to implement digital zoom.</p>
-     * <p>The crop region coordinate system is based off
-     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with <code>(0, 0)</code> being the
-     * top-left corner of the sensor active array.</p>
+     * <p>For devices not supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system always follows that of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with <code>(0, 0)</code> being
+     * the top-left pixel of the active array.</p>
+     * <p>For devices supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system depends on the mode being set.
+     * When the distortion correction mode is OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the pre-correction active array.
+     * When the distortion correction mode is not OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the active array.</p>
      * <p>Output streams use this rectangle to produce their output,
      * cropping to a smaller region if necessary to maintain the
      * stream's aspect ratio, then scaling the sensor input to
@@ -3000,18 +3057,26 @@
      * outputs will crop horizontally (pillarbox), and 16:9
      * streams will match exactly. These additional crops will
      * be centered within the crop region.</p>
-     * <p>The width and height of the crop region cannot
-     * be set to be smaller than
+     * <p>If the coordinate system is android.sensor.info.activeArraysSize, the width and height
+     * of the crop region cannot be set to be smaller than
      * <code>floor( activeArraySize.width / ACAMERA_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM )</code> and
      * <code>floor( activeArraySize.height / ACAMERA_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM )</code>, respectively.</p>
+     * <p>If the coordinate system is ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, the width
+     * and height of the crop region cannot be set to be smaller than
+     * <code>floor( preCorrectionActiveArraySize.width / ACAMERA_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM )</code>
+     * and
+     * <code>floor( preCorrectionActiveArraySize.height / ACAMERA_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM )</code>,
+     * respectively.</p>
      * <p>The camera device may adjust the crop region to account
      * for rounding and other hardware requirements; the final
      * crop region used will be included in the output capture
      * result.</p>
      * <p>The data representation is int[4], which maps to (left, top, width, height).</p>
      *
+     * @see ACAMERA_DISTORTION_CORRECTION_MODE
      * @see ACAMERA_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM
      * @see ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE
+     * @see ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     ACAMERA_SCALER_CROP_REGION =                                // int32[4]
             ACAMERA_SCALER_START,
@@ -3977,12 +4042,24 @@
      * ACAMERA_SCALER_CROP_REGION, is defined relative to the active array rectangle given in
      * this field, with <code>(0, 0)</code> being the top-left of this rectangle.</p>
      * <p>The active array may be smaller than the full pixel array, since the full array may
-     * include black calibration pixels or other inactive regions, and geometric correction
-     * resulting in scaling or cropping may have been applied.</p>
+     * include black calibration pixels or other inactive regions.</p>
+     * <p>For devices that do not support ACAMERA_DISTORTION_CORRECTION_MODE control, the active
+     * array must be the same as ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE.</p>
+     * <p>For devices that support ACAMERA_DISTORTION_CORRECTION_MODE control, the active array must
+     * be enclosed by ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE. The difference between
+     * pre-correction active array and active array accounts for scaling or cropping caused
+     * by lens geometric distortion correction.</p>
+     * <p>In general, application should always refer to active array size for controls like
+     * metering regions or crop region. Two exceptions are when the application is dealing with
+     * RAW image buffers (RAW_SENSOR, RAW10, RAW12 etc), or when application explicitly set
+     * ACAMERA_DISTORTION_CORRECTION_MODE to OFF. In these cases, application should refer
+     * to ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE.</p>
      * <p>The data representation is <code>int[4]</code>, which maps to <code>(left, top, width, height)</code>.</p>
      *
+     * @see ACAMERA_DISTORTION_CORRECTION_MODE
      * @see ACAMERA_SCALER_CROP_REGION
      * @see ACAMERA_SENSOR_INFO_PIXEL_ARRAY_SIZE
+     * @see ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE =                     // int32[4]
             ACAMERA_SENSOR_INFO_START,
@@ -4224,9 +4301,9 @@
      * <ol>
      * <li>ACAMERA_LENS_DISTORTION.</li>
      * </ol>
-     * <p>If all of the geometric distortion fields are no-ops, this rectangle will be the same
-     * as the post-distortion-corrected rectangle given in
-     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.</p>
+     * <p>If the camera device doesn't support geometric distortion correction, or all of the
+     * geometric distortion fields are no-ops, this rectangle will be the same as the
+     * post-distortion-corrected rectangle given in ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.</p>
      * <p>This rectangle is defined relative to the full pixel array; (0,0) is the top-left of
      * the full pixel array, and the size of the full pixel array is given by
      * ACAMERA_SENSOR_INFO_PIXEL_ARRAY_SIZE.</p>
@@ -4372,11 +4449,22 @@
      *   <li>ACameraMetadata from ACameraCaptureSession_captureCallback_result callbacks</li>
      * </ul></p>
      *
-     * <p>The coordinate system is that of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with
+     * <p>For devices not supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system always follows that of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with <code>(0, 0)</code> being
+     * the top-left pixel of the active array.</p>
+     * <p>For devices supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system depends on the mode being set.
+     * When the distortion correction mode is OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the pre-correction active array.
+     * When the distortion correction mode is not OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with
      * <code>(0, 0)</code> being the top-left pixel of the active array.</p>
      * <p>Only available if ACAMERA_STATISTICS_FACE_DETECT_MODE == FULL</p>
      *
+     * @see ACAMERA_DISTORTION_CORRECTION_MODE
      * @see ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE
+     * @see ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      * @see ACAMERA_STATISTICS_FACE_DETECT_MODE
      */
     ACAMERA_STATISTICS_FACE_LANDMARKS =                         // int32[n*6]
@@ -4392,12 +4480,23 @@
      *   <li>ACameraMetadata from ACameraCaptureSession_captureCallback_result callbacks</li>
      * </ul></p>
      *
-     * <p>The coordinate system is that of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with
+     * <p>For devices not supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system always follows that of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with <code>(0, 0)</code> being
+     * the top-left pixel of the active array.</p>
+     * <p>For devices supporting ACAMERA_DISTORTION_CORRECTION_MODE control, the coordinate
+     * system depends on the mode being set.
+     * When the distortion correction mode is OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, with
+     * <code>(0, 0)</code> being the top-left pixel of the pre-correction active array.
+     * When the distortion correction mode is not OFF, the coordinate system follows
+     * ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE, with
      * <code>(0, 0)</code> being the top-left pixel of the active array.</p>
      * <p>Only available if ACAMERA_STATISTICS_FACE_DETECT_MODE != OFF
-     * The data representation is <code>int[4]</code>, which maps to <code>(left, top, width, height)</code>.</p>
+     * The data representation is <code>int[4]</code>, which maps to <code>(left, top, right, bottom)</code>.</p>
      *
+     * @see ACAMERA_DISTORTION_CORRECTION_MODE
      * @see ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE
+     * @see ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      * @see ACAMERA_STATISTICS_FACE_DETECT_MODE
      */
     ACAMERA_STATISTICS_FACE_RECTANGLES =                        // int32[n*4]
@@ -5315,18 +5414,18 @@
      * any correction at all would slow down capture rate.  Every output stream will have a
      * similar amount of enhancement applied.</p>
      * <p>The correction only applies to processed outputs such as YUV, JPEG, or DEPTH16; it is not
-     * applied to any RAW output.  Metadata coordinates such as face rectangles or metering
+     * applied to any RAW output. Metadata coordinates such as face rectangles or metering
      * regions are also not affected by correction.</p>
-     * <p>Applications enabling distortion correction need to pay extra attention when converting
-     * image coordinates between corrected output buffers and the sensor array. For example, if
-     * the app supports tap-to-focus and enables correction, it then has to apply the distortion
-     * model described in ACAMERA_LENS_DISTORTION to the image buffer tap coordinates to properly
-     * calculate the tap position on the sensor active array to be used with
-     * ACAMERA_CONTROL_AF_REGIONS. The same applies in reverse to detected face rectangles if
-     * they need to be drawn on top of the corrected output buffers.</p>
+     * <p>This control will be on by default on devices that support this control. Applications
+     * disabling distortion correction need to pay extra attention with the coordinate system of
+     * metering regions, crop region, and face rectangles. When distortion correction is OFF,
+     * metadata coordinates follow the coordinate system of
+     * ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE. When distortion is not OFF, metadata
+     * coordinates follow the coordinate system of ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE.</p>
      *
-     * @see ACAMERA_CONTROL_AF_REGIONS
      * @see ACAMERA_LENS_DISTORTION
+     * @see ACAMERA_SENSOR_INFO_ACTIVE_ARRAY_SIZE
+     * @see ACAMERA_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
      */
     ACAMERA_DISTORTION_CORRECTION_MODE =                        // byte (acamera_metadata_enum_android_distortion_correction_mode_t)
             ACAMERA_DISTORTION_CORRECTION_START,
@@ -7779,9 +7878,6 @@
 
 } acamera_metadata_enum_android_distortion_correction_mode_t;
 
-
-#endif /* __ANDROID_API__ >= 24 */
-
 __END_DECLS
 
 #endif /* _NDK_CAMERA_METADATA_TAGS_H */
diff --git a/camera/ndk/include/camera/NdkCaptureRequest.h b/camera/ndk/include/camera/NdkCaptureRequest.h
index 4961ce3..2fb5d12 100644
--- a/camera/ndk/include/camera/NdkCaptureRequest.h
+++ b/camera/ndk/include/camera/NdkCaptureRequest.h
@@ -44,8 +44,6 @@
 
 __BEGIN_DECLS
 
-#if __ANDROID_API__ >= 24
-
 // Container for output targets
 typedef struct ACameraOutputTargets ACameraOutputTargets;
 
@@ -101,7 +99,8 @@
  *
  * @see ACaptureRequest_addTarget
  */
-camera_status_t ACameraOutputTarget_create(ANativeWindow* window, ACameraOutputTarget** output);
+camera_status_t ACameraOutputTarget_create(ANativeWindow* window,
+        ACameraOutputTarget** output) __INTRODUCED_IN(24);
 
 /**
  * Free a ACameraOutputTarget object.
@@ -110,7 +109,7 @@
  *
  * @see ACameraOutputTarget_create
  */
-void ACameraOutputTarget_free(ACameraOutputTarget* output);
+void ACameraOutputTarget_free(ACameraOutputTarget* output) __INTRODUCED_IN(24);
 
 /**
  * Add an {@link ACameraOutputTarget} object to {@link ACaptureRequest}.
@@ -123,7 +122,7 @@
  *         <li>{@link ACAMERA_ERROR_INVALID_PARAMETER} if request or output is NULL.</li></ul>
  */
 camera_status_t ACaptureRequest_addTarget(ACaptureRequest* request,
-        const ACameraOutputTarget* output);
+        const ACameraOutputTarget* output) __INTRODUCED_IN(24);
 
 /**
  * Remove an {@link ACameraOutputTarget} object from {@link ACaptureRequest}.
@@ -138,7 +137,7 @@
  *         <li>{@link ACAMERA_ERROR_INVALID_PARAMETER} if request or output is NULL.</li></ul>
  */
 camera_status_t ACaptureRequest_removeTarget(ACaptureRequest* request,
-        const ACameraOutputTarget* output);
+        const ACameraOutputTarget* output) __INTRODUCED_IN(24);
 
 /**
  * Get a metadata entry from input {@link ACaptureRequest}.
@@ -158,7 +157,7 @@
  *             entry of input tag value.</li></ul>
  */
 camera_status_t ACaptureRequest_getConstEntry(
-        const ACaptureRequest* request, uint32_t tag, ACameraMetadata_const_entry* entry);
+        const ACaptureRequest* request, uint32_t tag, ACameraMetadata_const_entry* entry) __INTRODUCED_IN(24);
 
 /*
  * List all the entry tags in input {@link ACaptureRequest}.
@@ -179,7 +178,7 @@
  *         <li>{@link ACAMERA_ERROR_UNKNOWN} if the method fails for some other reasons.</li></ul>
  */
 camera_status_t ACaptureRequest_getAllTags(
-        const ACaptureRequest* request, /*out*/int32_t* numTags, /*out*/const uint32_t** tags);
+        const ACaptureRequest* request, /*out*/int32_t* numTags, /*out*/const uint32_t** tags) __INTRODUCED_IN(24);
 
 /**
  * Set/change a camera capture control entry with unsigned 8 bits data type.
@@ -198,7 +197,7 @@
  *             the tag is not controllable by application.</li></ul>
  */
 camera_status_t ACaptureRequest_setEntry_u8(
-        ACaptureRequest* request, uint32_t tag, uint32_t count, const uint8_t* data);
+        ACaptureRequest* request, uint32_t tag, uint32_t count, const uint8_t* data) __INTRODUCED_IN(24);
 
 /**
  * Set/change a camera capture control entry with signed 32 bits data type.
@@ -217,7 +216,7 @@
  *             the tag is not controllable by application.</li></ul>
  */
 camera_status_t ACaptureRequest_setEntry_i32(
-        ACaptureRequest* request, uint32_t tag, uint32_t count, const int32_t* data);
+        ACaptureRequest* request, uint32_t tag, uint32_t count, const int32_t* data) __INTRODUCED_IN(24);
 
 /**
  * Set/change a camera capture control entry with float data type.
@@ -236,7 +235,7 @@
  *             the tag is not controllable by application.</li></ul>
  */
 camera_status_t ACaptureRequest_setEntry_float(
-        ACaptureRequest* request, uint32_t tag, uint32_t count, const float* data);
+        ACaptureRequest* request, uint32_t tag, uint32_t count, const float* data) __INTRODUCED_IN(24);
 
 /**
  * Set/change a camera capture control entry with signed 64 bits data type.
@@ -255,7 +254,7 @@
  *             the tag is not controllable by application.</li></ul>
  */
 camera_status_t ACaptureRequest_setEntry_i64(
-        ACaptureRequest* request, uint32_t tag, uint32_t count, const int64_t* data);
+        ACaptureRequest* request, uint32_t tag, uint32_t count, const int64_t* data) __INTRODUCED_IN(24);
 
 /**
  * Set/change a camera capture control entry with double data type.
@@ -274,7 +273,7 @@
  *             the tag is not controllable by application.</li></ul>
  */
 camera_status_t ACaptureRequest_setEntry_double(
-        ACaptureRequest* request, uint32_t tag, uint32_t count, const double* data);
+        ACaptureRequest* request, uint32_t tag, uint32_t count, const double* data) __INTRODUCED_IN(24);
 
 /**
  * Set/change a camera capture control entry with rational data type.
@@ -294,18 +293,14 @@
  */
 camera_status_t ACaptureRequest_setEntry_rational(
         ACaptureRequest* request, uint32_t tag, uint32_t count,
-        const ACameraMetadata_rational* data);
+        const ACameraMetadata_rational* data) __INTRODUCED_IN(24);
 
 /**
  * Free a {@link ACaptureRequest} structure.
  *
  * @param request the {@link ACaptureRequest} to be freed.
  */
-void ACaptureRequest_free(ACaptureRequest* request);
-
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 28
+void ACaptureRequest_free(ACaptureRequest* request) __INTRODUCED_IN(24);
 
 /**
  * Associate an arbitrary user context pointer to the {@link ACaptureRequest}
@@ -325,7 +320,7 @@
  *         <li>{@link ACAMERA_ERROR_INVALID_PARAMETER} if request is NULL.</li></ul>
  */
 camera_status_t ACaptureRequest_setUserContext(
-        ACaptureRequest* request, void* context);
+        ACaptureRequest* request, void* context) __INTRODUCED_IN(28);
 
 /**
  * Get the user context pointer of the {@link ACaptureRequest}
@@ -341,7 +336,7 @@
  *         <li>{@link ACAMERA_ERROR_INVALID_PARAMETER} if request is NULL.</li></ul>
  */
 camera_status_t ACaptureRequest_getUserContext(
-        const ACaptureRequest* request, /*out*/void** context);
+        const ACaptureRequest* request, /*out*/void** context) __INTRODUCED_IN(28);
 
 /**
  * Create a copy of input {@link ACaptureRequest}.
@@ -353,9 +348,7 @@
  *
  * @return a valid ACaptureRequest pointer or NULL if the input request cannot be copied.
  */
-ACaptureRequest* ACaptureRequest_copy(const ACaptureRequest* src);
-
-#endif /* __ANDROID_API__ >= 28 */
+ACaptureRequest* ACaptureRequest_copy(const ACaptureRequest* src) __INTRODUCED_IN(28);
 
 __END_DECLS
 
diff --git a/camera/ndk/libcamera2ndk.map.txt b/camera/ndk/libcamera2ndk.map.txt
index d179aa0..a29e96d 100644
--- a/camera/ndk/libcamera2ndk.map.txt
+++ b/camera/ndk/libcamera2ndk.map.txt
@@ -6,11 +6,11 @@
     ACameraCaptureSession_getDevice;
     ACameraCaptureSession_setRepeatingRequest;
     ACameraCaptureSession_stopRepeating;
-    ACameraCaptureSession_updateSharedOutput;
+    ACameraCaptureSession_updateSharedOutput; # introduced=28
     ACameraDevice_close;
     ACameraDevice_createCaptureRequest;
     ACameraDevice_createCaptureSession;
-    ACameraDevice_createCaptureSessionWithSessionParameters;
+    ACameraDevice_createCaptureSessionWithSessionParameters; # introduced=28
     ACameraDevice_getId;
     ACameraManager_create;
     ACameraManager_delete;
@@ -27,11 +27,11 @@
     ACameraOutputTarget_create;
     ACameraOutputTarget_free;
     ACaptureRequest_addTarget;
-    ACaptureRequest_copy;
+    ACaptureRequest_copy; # introduced=28
     ACaptureRequest_free;
     ACaptureRequest_getAllTags;
     ACaptureRequest_getConstEntry;
-    ACaptureRequest_getUserContext;
+    ACaptureRequest_getUserContext; # introduced=28
     ACaptureRequest_removeTarget;
     ACaptureRequest_setEntry_double;
     ACaptureRequest_setEntry_float;
@@ -39,15 +39,15 @@
     ACaptureRequest_setEntry_i64;
     ACaptureRequest_setEntry_rational;
     ACaptureRequest_setEntry_u8;
-    ACaptureRequest_setUserContext;
+    ACaptureRequest_setUserContext; # introduced=28
     ACaptureSessionOutputContainer_add;
     ACaptureSessionOutputContainer_create;
     ACaptureSessionOutputContainer_free;
     ACaptureSessionOutputContainer_remove;
     ACaptureSessionOutput_create;
-    ACaptureSessionSharedOutput_create;
-    ACaptureSessionSharedOutput_add;
-    ACaptureSessionSharedOutput_remove;
+    ACaptureSessionSharedOutput_create; # introduced=28
+    ACaptureSessionSharedOutput_add; # introduced=28
+    ACaptureSessionSharedOutput_remove; # introduced=28
     ACaptureSessionOutput_free;
   local:
     *;
diff --git a/media/extractors/midi/MidiExtractor.cpp b/media/extractors/midi/MidiExtractor.cpp
index 949fbe0..a30b6f8 100644
--- a/media/extractors/midi/MidiExtractor.cpp
+++ b/media/extractors/midi/MidiExtractor.cpp
@@ -247,8 +247,9 @@
         EAS_I32 numRendered;
         EAS_RESULT result = EAS_Render(mEasData, p, mEasConfig->mixBufferSize, &numRendered);
         if (result != EAS_SUCCESS) {
-            ALOGE("EAS_Render returned %ld", result);
-            break;
+            ALOGE("EAS_Render() returned %ld, numBytesOutput = %d", result, numBytesOutput);
+            buffer->release();
+            return NULL; // Stop processing to prevent infinite loops.
         }
         p += numRendered * mEasConfig->numChannels;
         numBytesOutput += numRendered * mEasConfig->numChannels * sizeof(EAS_PCM);
diff --git a/media/libaaudio/include/aaudio/AAudio.h b/media/libaaudio/include/aaudio/AAudio.h
index 5b29419..1493b26 100644
--- a/media/libaaudio/include/aaudio/AAudio.h
+++ b/media/libaaudio/include/aaudio/AAudio.h
@@ -423,7 +423,7 @@
  *
  * @return pointer to a text representation of an AAudio result code.
  */
-AAUDIO_API const char * AAudio_convertResultToText(aaudio_result_t returnCode);
+AAUDIO_API const char * AAudio_convertResultToText(aaudio_result_t returnCode) __INTRODUCED_IN(26);
 
 /**
  * The text is the ASCII symbol corresponding to the stream state,
@@ -433,7 +433,8 @@
  *
  * @return pointer to a text representation of an AAudio state.
  */
-AAUDIO_API const char * AAudio_convertStreamStateToText(aaudio_stream_state_t state);
+AAUDIO_API const char * AAudio_convertStreamStateToText(aaudio_stream_state_t state)
+        __INTRODUCED_IN(26);
 
 // ============================================================
 // StreamBuilder
@@ -451,7 +452,8 @@
  *
  * AAudioStreamBuilder_delete() must be called when you are done using the builder.
  */
-AAUDIO_API aaudio_result_t AAudio_createStreamBuilder(AAudioStreamBuilder** builder);
+AAUDIO_API aaudio_result_t AAudio_createStreamBuilder(AAudioStreamBuilder** builder)
+        __INTRODUCED_IN(26);
 
 /**
  * Request an audio device identified device using an ID.
@@ -464,7 +466,7 @@
  * @param deviceId device identifier or AAUDIO_UNSPECIFIED
  */
 AAUDIO_API void AAudioStreamBuilder_setDeviceId(AAudioStreamBuilder* builder,
-                                                     int32_t deviceId);
+                                                int32_t deviceId) __INTRODUCED_IN(26);
 
 /**
  * Request a sample rate in Hertz.
@@ -481,7 +483,7 @@
  * @param sampleRate frames per second. Common rates include 44100 and 48000 Hz.
  */
 AAUDIO_API void AAudioStreamBuilder_setSampleRate(AAudioStreamBuilder* builder,
-                                                       int32_t sampleRate);
+                                                  int32_t sampleRate) __INTRODUCED_IN(26);
 
 /**
  * Request a number of channels for the stream.
@@ -498,7 +500,7 @@
  * @param channelCount Number of channels desired.
  */
 AAUDIO_API void AAudioStreamBuilder_setChannelCount(AAudioStreamBuilder* builder,
-                                                   int32_t channelCount);
+                                                    int32_t channelCount) __INTRODUCED_IN(26);
 
 /**
  * Identical to AAudioStreamBuilder_setChannelCount().
@@ -507,7 +509,7 @@
  * @param samplesPerFrame Number of samples in a frame.
  */
 AAUDIO_API void AAudioStreamBuilder_setSamplesPerFrame(AAudioStreamBuilder* builder,
-                                                       int32_t samplesPerFrame);
+                                                       int32_t samplesPerFrame) __INTRODUCED_IN(26);
 
 /**
  * Request a sample data format, for example AAUDIO_FORMAT_PCM_I16.
@@ -524,7 +526,7 @@
  * @param format common formats are AAUDIO_FORMAT_PCM_FLOAT and AAUDIO_FORMAT_PCM_I16.
  */
 AAUDIO_API void AAudioStreamBuilder_setFormat(AAudioStreamBuilder* builder,
-                                                   aaudio_format_t format);
+                                              aaudio_format_t format) __INTRODUCED_IN(26);
 
 /**
  * Request a mode for sharing the device.
@@ -538,7 +540,7 @@
  * @param sharingMode AAUDIO_SHARING_MODE_SHARED or AAUDIO_SHARING_MODE_EXCLUSIVE
  */
 AAUDIO_API void AAudioStreamBuilder_setSharingMode(AAudioStreamBuilder* builder,
-                                                        aaudio_sharing_mode_t sharingMode);
+        aaudio_sharing_mode_t sharingMode) __INTRODUCED_IN(26);
 
 /**
  * Request the direction for a stream.
@@ -549,7 +551,7 @@
  * @param direction AAUDIO_DIRECTION_OUTPUT or AAUDIO_DIRECTION_INPUT
  */
 AAUDIO_API void AAudioStreamBuilder_setDirection(AAudioStreamBuilder* builder,
-                                                            aaudio_direction_t direction);
+        aaudio_direction_t direction) __INTRODUCED_IN(26);
 
 /**
  * Set the requested buffer capacity in frames.
@@ -561,7 +563,7 @@
  * @param numFrames the desired buffer capacity in frames or AAUDIO_UNSPECIFIED
  */
 AAUDIO_API void AAudioStreamBuilder_setBufferCapacityInFrames(AAudioStreamBuilder* builder,
-                                                                 int32_t numFrames);
+        int32_t numFrames) __INTRODUCED_IN(26);
 
 /**
  * Set the requested performance mode.
@@ -578,7 +580,7 @@
  * @param mode the desired performance mode, eg. AAUDIO_PERFORMANCE_MODE_LOW_LATENCY
  */
 AAUDIO_API void AAudioStreamBuilder_setPerformanceMode(AAudioStreamBuilder* builder,
-                                                aaudio_performance_mode_t mode);
+        aaudio_performance_mode_t mode) __INTRODUCED_IN(26);
 
 /**
  * Set the intended use case for the stream.
@@ -595,7 +597,7 @@
  * @param usage the desired usage, eg. AAUDIO_USAGE_GAME
  */
 AAUDIO_API void AAudioStreamBuilder_setUsage(AAudioStreamBuilder* builder,
-                                                       aaudio_usage_t usage);
+        aaudio_usage_t usage) __INTRODUCED_IN(28);
 
 /**
  * Set the type of audio data that the stream will carry.
@@ -612,7 +614,7 @@
  * @param contentType the type of audio data, eg. AAUDIO_CONTENT_TYPE_SPEECH
  */
 AAUDIO_API void AAudioStreamBuilder_setContentType(AAudioStreamBuilder* builder,
-                                             aaudio_content_type_t contentType);
+        aaudio_content_type_t contentType) __INTRODUCED_IN(28);
 
 /**
  * Set the input (capture) preset for the stream.
@@ -632,7 +634,7 @@
  * @param inputPreset the desired configuration for recording
  */
 AAUDIO_API void AAudioStreamBuilder_setInputPreset(AAudioStreamBuilder* builder,
-                                                   aaudio_input_preset_t inputPreset);
+        aaudio_input_preset_t inputPreset) __INTRODUCED_IN(28);
 
 /** Set the requested session ID.
  *
@@ -662,7 +664,7 @@
  * @param sessionId an allocated sessionID or AAUDIO_SESSION_ID_ALLOCATE
  */
 AAUDIO_API void AAudioStreamBuilder_setSessionId(AAudioStreamBuilder* builder,
-                                                aaudio_session_id_t sessionId);
+        aaudio_session_id_t sessionId) __INTRODUCED_IN(28);
 
 /**
  * Return one of these values from the data callback function.
@@ -760,8 +762,7 @@
  *          to the callback functions.
  */
 AAUDIO_API void AAudioStreamBuilder_setDataCallback(AAudioStreamBuilder* builder,
-                                                 AAudioStream_dataCallback callback,
-                                                 void *userData);
+        AAudioStream_dataCallback callback, void *userData) __INTRODUCED_IN(26);
 
 /**
  * Set the requested data callback buffer size in frames.
@@ -787,7 +788,7 @@
  * @param numFrames the desired buffer size in frames or AAUDIO_UNSPECIFIED
  */
 AAUDIO_API void AAudioStreamBuilder_setFramesPerDataCallback(AAudioStreamBuilder* builder,
-                                                             int32_t numFrames);
+                                                             int32_t numFrames) __INTRODUCED_IN(26);
 
 /**
  * Prototype for the callback function that is passed to
@@ -840,8 +841,7 @@
  *          to the callback functions.
  */
 AAUDIO_API void AAudioStreamBuilder_setErrorCallback(AAudioStreamBuilder* builder,
-                                                AAudioStream_errorCallback callback,
-                                                void *userData);
+        AAudioStream_errorCallback callback, void *userData) __INTRODUCED_IN(26);
 
 /**
  * Open a stream based on the options in the StreamBuilder.
@@ -854,7 +854,7 @@
  * @return AAUDIO_OK or a negative error.
  */
 AAUDIO_API aaudio_result_t  AAudioStreamBuilder_openStream(AAudioStreamBuilder* builder,
-                                                     AAudioStream** stream);
+        AAudioStream** stream) __INTRODUCED_IN(26);
 
 /**
  * Delete the resources associated with the StreamBuilder.
@@ -862,7 +862,8 @@
  * @param builder reference provided by AAudio_createStreamBuilder()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStreamBuilder_delete(AAudioStreamBuilder* builder);
+AAUDIO_API aaudio_result_t  AAudioStreamBuilder_delete(AAudioStreamBuilder* builder)
+    __INTRODUCED_IN(26);
 
 // ============================================================
 // Stream Control
@@ -874,7 +875,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_close(AAudioStream* stream);
+AAUDIO_API aaudio_result_t  AAudioStream_close(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Asynchronously request to start playing the stream. For output streams, one should
@@ -885,7 +886,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_requestStart(AAudioStream* stream);
+AAUDIO_API aaudio_result_t  AAudioStream_requestStart(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Asynchronous request for the stream to pause.
@@ -899,7 +900,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_requestPause(AAudioStream* stream);
+AAUDIO_API aaudio_result_t  AAudioStream_requestPause(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Asynchronous request for the stream to flush.
@@ -913,7 +914,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_requestFlush(AAudioStream* stream);
+AAUDIO_API aaudio_result_t  AAudioStream_requestFlush(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Asynchronous request for the stream to stop.
@@ -923,7 +924,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return AAUDIO_OK or a negative error.
  */
-AAUDIO_API aaudio_result_t  AAudioStream_requestStop(AAudioStream* stream);
+AAUDIO_API aaudio_result_t  AAudioStream_requestStop(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Query the current state of the client, eg. AAUDIO_STREAM_STATE_PAUSING
@@ -935,7 +936,7 @@
  *
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  */
-AAUDIO_API aaudio_stream_state_t AAudioStream_getState(AAudioStream* stream);
+AAUDIO_API aaudio_stream_state_t AAudioStream_getState(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Wait until the current state no longer matches the input state.
@@ -960,9 +961,8 @@
  * @return AAUDIO_OK or a negative error.
  */
 AAUDIO_API aaudio_result_t AAudioStream_waitForStateChange(AAudioStream* stream,
-                                            aaudio_stream_state_t inputState,
-                                            aaudio_stream_state_t *nextState,
-                                            int64_t timeoutNanoseconds);
+        aaudio_stream_state_t inputState, aaudio_stream_state_t *nextState,
+        int64_t timeoutNanoseconds) __INTRODUCED_IN(26);
 
 // ============================================================
 // Stream I/O
@@ -989,9 +989,7 @@
  * @return The number of frames actually read or a negative error.
  */
 AAUDIO_API aaudio_result_t AAudioStream_read(AAudioStream* stream,
-                               void *buffer,
-                               int32_t numFrames,
-                               int64_t timeoutNanoseconds);
+        void *buffer, int32_t numFrames, int64_t timeoutNanoseconds) __INTRODUCED_IN(26);
 
 /**
  * Write data to the stream.
@@ -1014,9 +1012,7 @@
  * @return The number of frames actually written or a negative error.
  */
 AAUDIO_API aaudio_result_t AAudioStream_write(AAudioStream* stream,
-                               const void *buffer,
-                               int32_t numFrames,
-                               int64_t timeoutNanoseconds);
+        const void *buffer, int32_t numFrames, int64_t timeoutNanoseconds) __INTRODUCED_IN(26);
 
 // ============================================================
 // Stream - queries
@@ -1039,7 +1035,7 @@
  * @return actual buffer size in frames or a negative error
  */
 AAUDIO_API aaudio_result_t AAudioStream_setBufferSizeInFrames(AAudioStream* stream,
-                                                      int32_t numFrames);
+        int32_t numFrames) __INTRODUCED_IN(26);
 
 /**
  * Query the maximum number of frames that can be filled without blocking.
@@ -1047,7 +1043,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return buffer size in frames.
  */
-AAUDIO_API int32_t AAudioStream_getBufferSizeInFrames(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getBufferSizeInFrames(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Query the number of frames that the application should read or write at
@@ -1062,7 +1058,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return burst size
  */
-AAUDIO_API int32_t AAudioStream_getFramesPerBurst(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getFramesPerBurst(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Query maximum buffer capacity in frames.
@@ -1070,7 +1066,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return  buffer capacity in frames
  */
-AAUDIO_API int32_t AAudioStream_getBufferCapacityInFrames(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getBufferCapacityInFrames(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Query the size of the buffer that will be passed to the dataProc callback
@@ -1091,7 +1087,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return callback buffer size in frames or AAUDIO_UNSPECIFIED
  */
-AAUDIO_API int32_t AAudioStream_getFramesPerDataCallback(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getFramesPerDataCallback(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * An XRun is an Underrun or an Overrun.
@@ -1108,13 +1104,13 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return the underrun or overrun count
  */
-AAUDIO_API int32_t AAudioStream_getXRunCount(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getXRunCount(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return actual sample rate
  */
-AAUDIO_API int32_t AAudioStream_getSampleRate(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getSampleRate(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * A stream has one or more channels of data.
@@ -1123,7 +1119,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return actual number of channels
  */
-AAUDIO_API int32_t AAudioStream_getChannelCount(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getChannelCount(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Identical to AAudioStream_getChannelCount().
@@ -1131,39 +1127,41 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return actual number of samples frame
  */
-AAUDIO_API int32_t AAudioStream_getSamplesPerFrame(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getSamplesPerFrame(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return actual device ID
  */
-AAUDIO_API int32_t AAudioStream_getDeviceId(AAudioStream* stream);
+AAUDIO_API int32_t AAudioStream_getDeviceId(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return actual data format
  */
-AAUDIO_API aaudio_format_t AAudioStream_getFormat(AAudioStream* stream);
+AAUDIO_API aaudio_format_t AAudioStream_getFormat(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Provide actual sharing mode.
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return  actual sharing mode
  */
-AAUDIO_API aaudio_sharing_mode_t AAudioStream_getSharingMode(AAudioStream* stream);
+AAUDIO_API aaudio_sharing_mode_t AAudioStream_getSharingMode(AAudioStream* stream)
+        __INTRODUCED_IN(26);
 
 /**
  * Get the performance mode used by the stream.
  *
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  */
-AAUDIO_API aaudio_performance_mode_t AAudioStream_getPerformanceMode(AAudioStream* stream);
+AAUDIO_API aaudio_performance_mode_t AAudioStream_getPerformanceMode(AAudioStream* stream)
+        __INTRODUCED_IN(26);
 
 /**
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return direction
  */
-AAUDIO_API aaudio_direction_t AAudioStream_getDirection(AAudioStream* stream);
+AAUDIO_API aaudio_direction_t AAudioStream_getDirection(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Passes back the number of frames that have been written since the stream was created.
@@ -1176,7 +1174,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return frames written
  */
-AAUDIO_API int64_t AAudioStream_getFramesWritten(AAudioStream* stream);
+AAUDIO_API int64_t AAudioStream_getFramesWritten(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Passes back the number of frames that have been read since the stream was created.
@@ -1189,7 +1187,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return frames read
  */
-AAUDIO_API int64_t AAudioStream_getFramesRead(AAudioStream* stream);
+AAUDIO_API int64_t AAudioStream_getFramesRead(AAudioStream* stream) __INTRODUCED_IN(26);
 
 /**
  * Passes back the session ID associated with this stream.
@@ -1213,7 +1211,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return session ID or AAUDIO_SESSION_ID_NONE
  */
-AAUDIO_API aaudio_session_id_t AAudioStream_getSessionId(AAudioStream* stream);
+AAUDIO_API aaudio_session_id_t AAudioStream_getSessionId(AAudioStream* stream) __INTRODUCED_IN(28);
 
 /**
  * Passes back the time at which a particular frame was presented.
@@ -1238,9 +1236,7 @@
  * @return AAUDIO_OK or a negative error
  */
 AAUDIO_API aaudio_result_t AAudioStream_getTimestamp(AAudioStream* stream,
-                                      clockid_t clockid,
-                                      int64_t *framePosition,
-                                      int64_t *timeNanoseconds);
+        clockid_t clockid, int64_t *framePosition, int64_t *timeNanoseconds) __INTRODUCED_IN(26);
 
 /**
  * Return the use case for the stream.
@@ -1250,7 +1246,7 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return frames read
  */
-AAUDIO_API aaudio_usage_t AAudioStream_getUsage(AAudioStream* stream);
+AAUDIO_API aaudio_usage_t AAudioStream_getUsage(AAudioStream* stream) __INTRODUCED_IN(28);
 
 /**
  * Return the content type for the stream.
@@ -1260,7 +1256,8 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return content type, for example AAUDIO_CONTENT_TYPE_MUSIC
  */
-AAUDIO_API aaudio_content_type_t AAudioStream_getContentType(AAudioStream* stream);
+AAUDIO_API aaudio_content_type_t AAudioStream_getContentType(AAudioStream* stream)
+        __INTRODUCED_IN(28);
 
 /**
  * Return the input preset for the stream.
@@ -1270,7 +1267,8 @@
  * @param stream reference provided by AAudioStreamBuilder_openStream()
  * @return input preset, for example AAUDIO_INPUT_PRESET_CAMCORDER
  */
-AAUDIO_API aaudio_input_preset_t AAudioStream_getInputPreset(AAudioStream* stream);
+AAUDIO_API aaudio_input_preset_t AAudioStream_getInputPreset(AAudioStream* stream)
+        __INTRODUCED_IN(28);
 
 #ifdef __cplusplus
 }
diff --git a/media/libmedia/include/media/MediaProfiles.h b/media/libmedia/include/media/MediaProfiles.h
index 6975581..0feb4f3 100644
--- a/media/libmedia/include/media/MediaProfiles.h
+++ b/media/libmedia/include/media/MediaProfiles.h
@@ -83,6 +83,7 @@
      * successful only when validation is successful.
      */
     static constexpr char const * const xmlFiles[] = {
+            "odm/etc/media_profiles_V1_0.xml",
             "vendor/etc/media_profiles_V1_0.xml",
             "system/etc/media_profiles.xml"
             };
diff --git a/media/libstagefright/FrameDecoder.cpp b/media/libstagefright/FrameDecoder.cpp
index 29a219f..6e94517 100644
--- a/media/libstagefright/FrameDecoder.cpp
+++ b/media/libstagefright/FrameDecoder.cpp
@@ -301,10 +301,13 @@
             err = mSource->read(&mediaBuffer, &mReadOptions);
             mReadOptions.clearSeekTo();
             if (err != OK) {
-                ALOGW("Input Error or EOS");
                 mHaveMoreInputs = false;
                 if (!mFirstSample && err == ERROR_END_OF_STREAM) {
+                    (void)mDecoder->queueInputBuffer(
+                            index, 0, 0, 0, MediaCodec::BUFFER_FLAG_EOS);
                     err = OK;
+                } else {
+                    ALOGW("Input Error: err=%d", err);
                 }
                 break;
             }
diff --git a/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp b/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
index e0d9662..f173e0f 100644
--- a/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
+++ b/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
@@ -23,43 +23,53 @@
 #include <OMX_AudioExt.h>
 #include <OMX_IndexExt.h>
 #include <cutils/properties.h>
+#include <math.h>
+#include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/hexdump.h>
-#include <media/stagefright/MediaErrors.h>
 #include <utils/misc.h>
-#include <math.h>
 
-#define DRC_DEFAULT_MOBILE_REF_LEVEL 64  /* 64*-0.25dB = -16 dB below full scale for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_CUT   127 /* maximum compression of dynamic range for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_BOOST 127 /* maximum compression of dynamic range for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_HEAVY 1   /* switch for heavy compression for mobile conf */
-#define DRC_DEFAULT_MOBILE_ENC_LEVEL (-1) /* encoder target level; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
-#define DRC_KEY_AAC_DRC_EFFECT_TYPE   (3)  /* Default Effect type is "Limited playback" */
+/* 64*-0.25dB = -16 dB below full scale for mobile conf */
+#define DRC_DEFAULT_MOBILE_REF_LEVEL 64
+/* maximum compression of dynamic range for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_CUT 127
+/* maximum compression of dynamic range for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_BOOST 127
+/* switch for heavy compression for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_HEAVY 1
+/* encoder target level; -1 => the value is unknown,
+ * otherwise dB step value (e.g. 64 for -16 dB) */
+#define DRC_DEFAULT_MOBILE_ENC_LEVEL (-1)
+
+/* Default Effect type is "Limited playback" */
+#define DRC_KEY_AAC_DRC_EFFECT_TYPE (3)
+
 /* REF_LEVEL of 64 pairs well with EFFECT_TYPE of 3. */
-#define DRC_DEFAULT_MOBILE_LOUDNESS_LEVEL (64)  /* Default loudness value for MPEG-D DRC */
+/* Default loudness value for MPEG-D DRC */
+#define DRC_DEFAULT_MOBILE_LOUDNESS_LEVEL (64)
 
-#define PROP_DRC_OVERRIDE_REF_LEVEL  "aac_drc_reference_level"
-#define PROP_DRC_OVERRIDE_CUT        "aac_drc_cut"
-#define PROP_DRC_OVERRIDE_BOOST      "aac_drc_boost"
-#define PROP_DRC_OVERRIDE_HEAVY      "aac_drc_heavy"
+#define PROP_DRC_OVERRIDE_REF_LEVEL "aac_drc_reference_level"
+#define PROP_DRC_OVERRIDE_CUT "aac_drc_cut"
+#define PROP_DRC_OVERRIDE_BOOST "aac_drc_boost"
+#define PROP_DRC_OVERRIDE_HEAVY "aac_drc_heavy"
 #define PROP_DRC_OVERRIDE_ENC_LEVEL "aac_drc_enc_target_level"
 #define PROP_DRC_OVERRIDE_EFFECT_TYPE "ro.aac_drc_effect_type"
 
-#define MAX_CHANNEL_COUNT            8  /* maximum number of audio channels that can be decoded */
+/* maximum number of audio channels that can be decoded */
+#define MAX_CHANNEL_COUNT 8
 
-
-#define RETURN_IF_FATAL(retval, str) \
-        if (retval & IA_FATAL_ERROR) { \
-            ALOGE("Error in %s: Returned: %d", str, retval); \
-            return retval; \
-        } else if (retval != IA_NO_ERROR) { \
-            ALOGW("Warning in %s: Returned: %d", str, retval); \
-        }
+#define RETURN_IF_FATAL(retval, str)                       \
+    if (retval & IA_FATAL_ERROR) {                         \
+        ALOGE("Error in %s: Returned: %d", str, retval);   \
+        return retval;                                     \
+    } else if (retval != IA_NO_ERROR) {                    \
+        ALOGW("Warning in %s: Returned: %d", str, retval); \
+    }
 
 namespace android {
 
-template<class T>
-static void InitOMXParams(T *params) {
+template <class T>
+static void InitOMXParams(T* params) {
     params->nSize = sizeof(T);
     params->nVersion.s.nVersionMajor = 1;
     params->nVersion.s.nVersionMinor = 0;
@@ -68,41 +78,35 @@
 }
 
 static const OMX_U32 kSupportedProfiles[] = {
-    OMX_AUDIO_AACObjectLC,
-    OMX_AUDIO_AACObjectHE,
-    OMX_AUDIO_AACObjectHE_PS,
-    OMX_AUDIO_AACObjectLD,
-    OMX_AUDIO_AACObjectELD,
+    OMX_AUDIO_AACObjectLC, OMX_AUDIO_AACObjectHE,  OMX_AUDIO_AACObjectHE_PS,
+    OMX_AUDIO_AACObjectLD, OMX_AUDIO_AACObjectELD,
 };
 
-SoftXAAC::SoftXAAC(
-        const char *name,
-        const OMX_CALLBACKTYPE *callbacks,
-        OMX_PTR appData,
-        OMX_COMPONENTTYPE **component)
+SoftXAAC::SoftXAAC(const char* name, const OMX_CALLBACKTYPE* callbacks, OMX_PTR appData,
+                   OMX_COMPONENTTYPE** component)
     : SimpleSoftOMXComponent(name, callbacks, appData, component),
-    mIsADTS(false),
-    mInputBufferCount(0),
-    mOutputBufferCount(0),
-    mSignalledError(false),
-    mLastInHeader(NULL),
-    mPrevTimestamp(0),
-    mCurrentTimestamp(0),
-    mOutputPortSettingsChange(NONE),
-    mXheaacCodecHandle(NULL),
-    mMpegDDrcHandle(NULL),
-    mInputBufferSize(0),
-    mOutputFrameLength(1024),
-    mInputBuffer(NULL),
-    mOutputBuffer(NULL),
-    mSampFreq(0),
-    mNumChannels(0),
-    mPcmWdSz(0),
-    mChannelMask(0),
-    mIsCodecInitialized(false),
-    mIsCodecConfigFlushRequired(false),
-    mMpegDDRCPresent(0),
-    mDRCFlag(0)
+      mIsADTS(false),
+      mInputBufferCount(0),
+      mOutputBufferCount(0),
+      mSignalledError(false),
+      mLastInHeader(NULL),
+      mPrevTimestamp(0),
+      mCurrentTimestamp(0),
+      mOutputPortSettingsChange(NONE),
+      mXheaacCodecHandle(NULL),
+      mMpegDDrcHandle(NULL),
+      mInputBufferSize(0),
+      mOutputFrameLength(1024),
+      mInputBuffer(NULL),
+      mOutputBuffer(NULL),
+      mSampFreq(0),
+      mNumChannels(0),
+      mPcmWdSz(0),
+      mChannelMask(0),
+      mIsCodecInitialized(false),
+      mIsCodecConfigFlushRequired(false),
+      mMpegDDRCPresent(0),
+      mDRCFlag(0)
 
 {
     initPorts();
@@ -112,7 +116,7 @@
 SoftXAAC::~SoftXAAC() {
     int errCode = deInitXAACDecoder();
     if (0 != errCode) {
-        ALOGE("deInitXAACDecoder() failed %d",errCode);
+        ALOGE("deInitXAACDecoder() failed %d", errCode);
     }
 
     mIsCodecInitialized = false;
@@ -134,7 +138,7 @@
     def.bBuffersContiguous = OMX_FALSE;
     def.nBufferAlignment = 1;
 
-    def.format.audio.cMIMEType = const_cast<char *>("audio/aac");
+    def.format.audio.cMIMEType = const_cast<char*>("audio/aac");
     def.format.audio.pNativeRender = NULL;
     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
     def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
@@ -152,7 +156,7 @@
     def.bBuffersContiguous = OMX_FALSE;
     def.nBufferAlignment = 2;
 
-    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
+    def.format.audio.cMIMEType = const_cast<char*>("audio/raw");
     def.format.audio.pNativeRender = NULL;
     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
     def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
@@ -168,24 +172,23 @@
     int loop = 0;
 
     err_code = initXAACDecoder();
-    if(err_code != IA_NO_ERROR) {
+    if (err_code != IA_NO_ERROR) {
         if (NULL == mXheaacCodecHandle) {
             ALOGE("AAC decoder handle is null");
         }
         if (NULL == mMpegDDrcHandle) {
             ALOGE("MPEG-D DRC decoder handle is null");
         }
-        for(loop= 1; loop < mMallocCount; loop++) {
+        for (loop = 1; loop < mMallocCount; loop++) {
             if (mMemoryArray[loop] == NULL) {
-                ALOGE(" memory allocation error %d\n",loop);
+                ALOGE(" memory allocation error %d\n", loop);
                 break;
             }
         }
         ALOGE("initXAACDecoder Failed");
 
-        for(loop = 0; loop < mMallocCount; loop++) {
-           if(mMemoryArray[loop])
-           free(mMemoryArray[loop]);
+        for (loop = 0; loop < mMallocCount; loop++) {
+            if (mMemoryArray[loop]) free(mMemoryArray[loop]);
         }
         mMallocCount = 0;
         return status;
@@ -197,105 +200,76 @@
     mEndOfOutput = false;
 
     char value[PROPERTY_VALUE_MAX];
-    if (property_get(PROP_DRC_OVERRIDE_REF_LEVEL, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_REF_LEVEL, value, NULL)) {
         ui_drc_val = atoi(value);
-        ALOGV("AAC decoder using desired DRC target reference level of %d instead of %d",ui_drc_val,
-                DRC_DEFAULT_MOBILE_REF_LEVEL);
-    }
-    else
-    {
-        ui_drc_val= DRC_DEFAULT_MOBILE_REF_LEVEL;
+        ALOGV("AAC decoder using desired DRC target reference level of %d instead of %d",
+              ui_drc_val, DRC_DEFAULT_MOBILE_REF_LEVEL);
+    } else {
+        ui_drc_val = DRC_DEFAULT_MOBILE_REF_LEVEL;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL,
-                                &ui_drc_val);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL, &ui_drc_val);
 
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL");
-#ifdef     ENABLE_MPEG_D_DRC
-
+#ifdef ENABLE_MPEG_D_DRC
     /* Use ui_drc_val from PROP_DRC_OVERRIDE_REF_LEVEL or DRC_DEFAULT_MOBILE_REF_LEVEL
      * for IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS too */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS,
-                                &ui_drc_val);
 
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS, &ui_drc_val);
 
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS");
 #endif
 
-
-    if (property_get(PROP_DRC_OVERRIDE_CUT, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_CUT, value, NULL)) {
         ui_drc_val = atoi(value);
         ALOGV("AAC decoder using desired DRC attenuation factor of %d instead of %d", ui_drc_val,
-                DRC_DEFAULT_MOBILE_DRC_CUT);
-    }
-    else
-    {
-        ui_drc_val=DRC_DEFAULT_MOBILE_DRC_CUT;
+              DRC_DEFAULT_MOBILE_DRC_CUT);
+    } else {
+        ui_drc_val = DRC_DEFAULT_MOBILE_DRC_CUT;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT,
-                                &ui_drc_val);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT, &ui_drc_val);
 
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT");
 
-    if (property_get(PROP_DRC_OVERRIDE_BOOST, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_BOOST, value, NULL)) {
         ui_drc_val = atoi(value);
         ALOGV("AAC decoder using desired DRC boost factor of %d instead of %d", ui_drc_val,
-                DRC_DEFAULT_MOBILE_DRC_BOOST);
-    }
-    else
-    {
+              DRC_DEFAULT_MOBILE_DRC_BOOST);
+    } else {
         ui_drc_val = DRC_DEFAULT_MOBILE_DRC_BOOST;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST,
-                                &ui_drc_val);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST, &ui_drc_val);
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST");
 
-    if (property_get(PROP_DRC_OVERRIDE_HEAVY, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_HEAVY, value, NULL)) {
         ui_drc_val = atoi(value);
         ALOGV("AAC decoder using desired Heavy compression factor of %d instead of %d", ui_drc_val,
-                DRC_DEFAULT_MOBILE_DRC_HEAVY);
-    }
-    else
-    {
+              DRC_DEFAULT_MOBILE_DRC_HEAVY);
+    } else {
         ui_drc_val = DRC_DEFAULT_MOBILE_DRC_HEAVY;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP,
-                                &ui_drc_val);
-   RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP, &ui_drc_val);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP");
 
 #ifdef ENABLE_MPEG_D_DRC
-    if (property_get(PROP_DRC_OVERRIDE_EFFECT_TYPE, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_EFFECT_TYPE, value, NULL)) {
         ui_drc_val = atoi(value);
         ALOGV("AAC decoder using desired DRC effect type of %d instead of %d", ui_drc_val,
-                DRC_KEY_AAC_DRC_EFFECT_TYPE);
-    }
-    else
-    {
+              DRC_KEY_AAC_DRC_EFFECT_TYPE);
+    } else {
         ui_drc_val = DRC_KEY_AAC_DRC_EFFECT_TYPE;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                              IA_API_CMD_SET_CONFIG_PARAM,
-                              IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE,
-                              &ui_drc_val);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE, &ui_drc_val);
 
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE");
 
@@ -303,15 +277,10 @@
     return status;
 }
 
-OMX_ERRORTYPE SoftXAAC::internalGetParameter(
-        OMX_INDEXTYPE index, OMX_PTR params) {
-
-    switch ((OMX_U32) index) {
-
-        case OMX_IndexParamAudioPortFormat:
-        {
-            OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
-                (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
+OMX_ERRORTYPE SoftXAAC::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params) {
+    switch ((OMX_U32)index) {
+        case OMX_IndexParamAudioPortFormat: {
+            OMX_AUDIO_PARAM_PORTFORMATTYPE* formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE*)params;
 
             if (!isValidOMXParam(formatParams)) {
                 return OMX_ErrorBadParameter;
@@ -326,16 +295,13 @@
             }
 
             formatParams->eEncoding =
-                (formatParams->nPortIndex == 0)
-                    ? OMX_AUDIO_CodingAAC : OMX_AUDIO_CodingPCM;
+                (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingAAC : OMX_AUDIO_CodingPCM;
 
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioAac:
-        {
-            OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
-                (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
+        case OMX_IndexParamAudioAac: {
+            OMX_AUDIO_PARAM_AACPROFILETYPE* aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE*)params;
 
             if (!isValidOMXParam(aacParams)) {
                 return OMX_ErrorBadParameter;
@@ -352,9 +318,7 @@
             aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
 
             aacParams->eAACStreamFormat =
-                mIsADTS
-                    ? OMX_AUDIO_AACStreamFormatMP4ADTS
-                    : OMX_AUDIO_AACStreamFormatMP4FF;
+                mIsADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF;
 
             aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
 
@@ -371,10 +335,8 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioPcm:
-        {
-            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
-                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
+        case OMX_IndexParamAudioPcm: {
+            OMX_AUDIO_PARAM_PCMMODETYPE* pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE*)params;
 
             if (!isValidOMXParam(pcmParams)) {
                 return OMX_ErrorBadParameter;
@@ -407,10 +369,9 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioProfileQuerySupported:
-        {
-            OMX_AUDIO_PARAM_ANDROID_PROFILETYPE *profileParams =
-                (OMX_AUDIO_PARAM_ANDROID_PROFILETYPE *)params;
+        case OMX_IndexParamAudioProfileQuerySupported: {
+            OMX_AUDIO_PARAM_ANDROID_PROFILETYPE* profileParams =
+                (OMX_AUDIO_PARAM_ANDROID_PROFILETYPE*)params;
 
             if (!isValidOMXParam(profileParams)) {
                 return OMX_ErrorBadParameter;
@@ -424,8 +385,7 @@
                 return OMX_ErrorNoMore;
             }
 
-            profileParams->eProfile =
-                kSupportedProfiles[profileParams->nProfileIndex];
+            profileParams->eProfile = kSupportedProfiles[profileParams->nProfileIndex];
 
             return OMX_ErrorNone;
         }
@@ -435,21 +395,17 @@
     }
 }
 
-OMX_ERRORTYPE SoftXAAC::internalSetParameter(
-        OMX_INDEXTYPE index, const OMX_PTR params) {
-
+OMX_ERRORTYPE SoftXAAC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) {
     switch ((int)index) {
-        case OMX_IndexParamStandardComponentRole:
-        {
-            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
-                (const OMX_PARAM_COMPONENTROLETYPE *)params;
+        case OMX_IndexParamStandardComponentRole: {
+            const OMX_PARAM_COMPONENTROLETYPE* roleParams =
+                (const OMX_PARAM_COMPONENTROLETYPE*)params;
 
             if (!isValidOMXParam(roleParams)) {
                 return OMX_ErrorBadParameter;
             }
 
-            if (strncmp((const char *)roleParams->cRole,
-                        "audio_decoder.aac",
+            if (strncmp((const char*)roleParams->cRole, "audio_decoder.aac",
                         OMX_MAX_STRINGNAME_SIZE - 1)) {
                 return OMX_ErrorUndefined;
             }
@@ -457,10 +413,9 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioPortFormat:
-        {
-            const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
-                (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
+        case OMX_IndexParamAudioPortFormat: {
+            const OMX_AUDIO_PARAM_PORTFORMATTYPE* formatParams =
+                (const OMX_AUDIO_PARAM_PORTFORMATTYPE*)params;
 
             if (!isValidOMXParam(formatParams)) {
                 return OMX_ErrorBadParameter;
@@ -470,20 +425,17 @@
                 return OMX_ErrorUndefined;
             }
 
-            if ((formatParams->nPortIndex == 0
-                        && formatParams->eEncoding != OMX_AUDIO_CodingAAC)
-                || (formatParams->nPortIndex == 1
-                        && formatParams->eEncoding != OMX_AUDIO_CodingPCM)) {
+            if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingAAC) ||
+                (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingPCM)) {
                 return OMX_ErrorUndefined;
             }
 
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioAac:
-        {
-            const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
-                (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
+        case OMX_IndexParamAudioAac: {
+            const OMX_AUDIO_PARAM_AACPROFILETYPE* aacParams =
+                (const OMX_AUDIO_PARAM_AACPROFILETYPE*)params;
 
             if (!isValidOMXParam(aacParams)) {
                 return OMX_ErrorBadParameter;
@@ -495,8 +447,7 @@
 
             if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) {
                 mIsADTS = false;
-            } else if (aacParams->eAACStreamFormat
-                        == OMX_AUDIO_AACStreamFormatMP4ADTS) {
+            } else if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4ADTS) {
                 mIsADTS = true;
             } else {
                 return OMX_ErrorUndefined;
@@ -505,10 +456,9 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioAndroidAacDrcPresentation:
-        {
-            const OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE *aacPresParams =
-                    (const OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE *)params;
+        case OMX_IndexParamAudioAndroidAacDrcPresentation: {
+            const OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE* aacPresParams =
+                (const OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE*)params;
 
             if (!isValidOMXParam(aacPresParams)) {
                 ALOGE("set OMX_ErrorBadParameter");
@@ -525,23 +475,26 @@
             //   nEncodedTargetLevel      idem
             if (aacPresParams->nMaxOutputChannels >= 0) {
                 int max;
-                if (aacPresParams->nMaxOutputChannels >= 8) { max = 8; }
-                else if (aacPresParams->nMaxOutputChannels >= 6) { max = 6; }
-                else if (aacPresParams->nMaxOutputChannels >= 2) { max = 2; }
-                else {
+                if (aacPresParams->nMaxOutputChannels >= 8) {
+                    max = 8;
+                } else if (aacPresParams->nMaxOutputChannels >= 6) {
+                    max = 6;
+                } else if (aacPresParams->nMaxOutputChannels >= 2) {
+                    max = 2;
+                } else {
                     // -1 or 0: disable downmix,  1: mono
                     max = aacPresParams->nMaxOutputChannels;
                 }
             }
             /* Apply DRC Changes */
-            IA_ERRORCODE err_code = setXAACDRCInfo(aacPresParams->nDrcCut,
-                           aacPresParams->nDrcBoost,
-                           aacPresParams->nTargetReferenceLevel,
-                           aacPresParams->nHeavyCompression
+            IA_ERRORCODE err_code = setXAACDRCInfo(aacPresParams->nDrcCut, aacPresParams->nDrcBoost,
+                                                   aacPresParams->nTargetReferenceLevel,
+                                                   aacPresParams->nHeavyCompression
 #ifdef ENABLE_MPEG_D_DRC
-                           ,aacPresParams->nDrcEffectType
+                                                   ,
+                                                   aacPresParams->nDrcEffectType
 #endif
-                           );    // TOD0 : Revert this change
+            );  // TOD0 : Revert this change
             if (err_code != IA_NO_ERROR) {
                 ALOGE("Error in OMX_IndexParamAudioAndroidAacDrcPresentation");
                 return OMX_ErrorBadParameter;
@@ -550,10 +503,8 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioPcm:
-        {
-            const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
-                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
+        case OMX_IndexParamAudioPcm: {
+            const OMX_AUDIO_PARAM_PCMMODETYPE* pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE*)params;
 
             if (!isValidOMXParam(pcmParams)) {
                 return OMX_ErrorBadParameter;
@@ -577,15 +528,15 @@
 
 void SoftXAAC::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError || mOutputPortSettingsChange != NONE) {
-        ALOGE("onQueueFilled do not process %d %d",mSignalledError,mOutputPortSettingsChange);
+        ALOGE("onQueueFilled do not process %d %d", mSignalledError, mOutputPortSettingsChange);
         return;
     }
 
-    uint8_t*  inBuffer        = NULL;
-    uint32_t  inBufferLength  = 0;
+    uint8_t* inBuffer = NULL;
+    uint32_t inBufferLength = 0;
 
-    List<BufferInfo *> &inQueue = getPortQueue(0);
-    List<BufferInfo *> &outQueue = getPortQueue(1);
+    List<BufferInfo*>& inQueue = getPortQueue(0);
+    List<BufferInfo*>& outQueue = getPortQueue(1);
 
     signed int numOutBytes = 0;
 
@@ -595,16 +546,16 @@
     /* Note: entire buffer logic to save and retrieve assumes 2 bytes per*/
     /* sample currently                                                  */
     if (mIsCodecInitialized) {
-        numOutBytes = mOutputFrameLength * (mPcmWdSz/8) * mNumChannels;
-        if ((mPcmWdSz/8) != 2) {
-            ALOGE("XAAC assumes 2 bytes per sample! mPcmWdSz %d",mPcmWdSz);
+        numOutBytes = mOutputFrameLength * (mPcmWdSz / 8) * mNumChannels;
+        if ((mPcmWdSz / 8) != 2) {
+            ALOGE("XAAC assumes 2 bytes per sample! mPcmWdSz %d", mPcmWdSz);
         }
     }
 
     while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) {
         if (!inQueue.empty()) {
-            BufferInfo *inInfo = *inQueue.begin();
-            OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
+            BufferInfo* inInfo = *inQueue.begin();
+            OMX_BUFFERHEADERTYPE* inHeader = inInfo->mHeader;
 
             /* No need to check inHeader != NULL, as inQueue is not empty */
             mEndOfInput = (inHeader->nFlags & OMX_BUFFERFLAG_EOS) != 0;
@@ -618,7 +569,7 @@
                 inBufferLength = inHeader->nFilledLen;
 
                 /* GA header configuration sent to Decoder! */
-                int err_code = configXAACDecoder(inBuffer,inBufferLength);
+                int err_code = configXAACDecoder(inBuffer, inBufferLength);
                 if (0 != err_code) {
                     ALOGW("configXAACDecoder err_code = %d", err_code);
                     mSignalledError = true;
@@ -626,7 +577,8 @@
                     return;
                 }
                 mInputBufferCount++;
-                mOutputBufferCount++; // fake increase of outputBufferCount to keep the counters aligned
+                mOutputBufferCount++;  // fake increase of outputBufferCount to keep the counters
+                                       // aligned
 
                 inInfo->mOwnedByUs = false;
                 inQueue.erase(inQueue.begin());
@@ -657,34 +609,35 @@
             }
 
             // Restore Offset and Length for Port reconfig case
-            size_t tempOffset =  inHeader->nOffset;
+            size_t tempOffset = inHeader->nOffset;
             size_t tempFilledLen = inHeader->nFilledLen;
             if (mIsADTS) {
-                 size_t adtsHeaderSize = 0;
+                size_t adtsHeaderSize = 0;
                 // skip 30 bits, aac_frame_length follows.
                 // ssssssss ssssiiip ppffffPc ccohCCll llllllll lll?????
 
-                const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset;
+                const uint8_t* adtsHeader = inHeader->pBuffer + inHeader->nOffset;
 
                 bool signalError = false;
                 if (inHeader->nFilledLen < 7) {
-                    ALOGE("Audio data too short to contain even the ADTS header. "
-                            "Got %d bytes.", inHeader->nFilledLen);
+                    ALOGE(
+                        "Audio data too short to contain even the ADTS header. "
+                        "Got %d bytes.",
+                        inHeader->nFilledLen);
                     hexdump(adtsHeader, inHeader->nFilledLen);
                     signalError = true;
                 } else {
                     bool protectionAbsent = (adtsHeader[1] & 1);
 
                     unsigned aac_frame_length =
-                        ((adtsHeader[3] & 3) << 11)
-                        | (adtsHeader[4] << 3)
-                        | (adtsHeader[5] >> 5);
+                        ((adtsHeader[3] & 3) << 11) | (adtsHeader[4] << 3) | (adtsHeader[5] >> 5);
 
                     if (inHeader->nFilledLen < aac_frame_length) {
-                        ALOGE("Not enough audio data for the complete frame. "
-                                "Got %d bytes, frame size according to the ADTS "
-                                "header is %u bytes.",
-                                inHeader->nFilledLen, aac_frame_length);
+                        ALOGE(
+                            "Not enough audio data for the complete frame. "
+                            "Got %d bytes, frame size according to the ADTS "
+                            "header is %u bytes.",
+                            inHeader->nFilledLen, aac_frame_length);
                         hexdump(adtsHeader, inHeader->nFilledLen);
                         signalError = true;
                     } else {
@@ -692,7 +645,7 @@
                         if (aac_frame_length < adtsHeaderSize) {
                             signalError = true;
                         } else {
-                            inBuffer = (uint8_t *)adtsHeader + adtsHeaderSize;
+                            inBuffer = (uint8_t*)adtsHeader + adtsHeaderSize;
                             inBufferLength = aac_frame_length - adtsHeaderSize;
 
                             inHeader->nOffset += adtsHeaderSize;
@@ -712,8 +665,7 @@
                     mCurrentTimestamp = inHeader->nTimeStamp;
                     mLastInHeader = inHeader;
                 } else {
-                    mCurrentTimestamp = mPrevTimestamp +
-                        mOutputFrameLength  * 1000000ll / mSampFreq;
+                    mCurrentTimestamp = mPrevTimestamp + mOutputFrameLength * 1000000ll / mSampFreq;
                 }
             } else {
                 inBuffer = inHeader->pBuffer + inHeader->nOffset;
@@ -730,7 +682,7 @@
             /* which should initialize the codec. Once this state is reached, call the  */
             /* decodeXAACStream API with same frame to decode!                        */
             if (!mIsCodecInitialized) {
-                int err_code = configXAACDecoder(inBuffer,inBufferLength);
+                int err_code = configXAACDecoder(inBuffer, inBufferLength);
                 if (0 != err_code) {
                     ALOGW("configXAACDecoder Failed 2 err_code = %d", err_code);
                     mSignalledError = true;
@@ -743,15 +695,14 @@
             if (!mSampFreq || !mNumChannels) {
                 if ((mInputBufferCount > 2) && (mOutputBufferCount <= 1)) {
                     ALOGW("Invalid AAC stream");
-                    ALOGW("mSampFreq %d mNumChannels %d ",mSampFreq,mNumChannels);
+                    ALOGW("mSampFreq %d mNumChannels %d ", mSampFreq, mNumChannels);
                     mSignalledError = true;
                     notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
                     return;
                 }
-            } else if ((mSampFreq != prevSampleRate) ||
-                       (mNumChannels != prevNumChannels)) {
-                ALOGV("Reconfiguring decoder: %d->%d Hz, %d->%d channels",
-                      prevSampleRate, mSampFreq, prevNumChannels, mNumChannels);
+            } else if ((mSampFreq != prevSampleRate) || (mNumChannels != prevNumChannels)) {
+                ALOGV("Reconfiguring decoder: %d->%d Hz, %d->%d channels", prevSampleRate,
+                      mSampFreq, prevNumChannels, mNumChannels);
                 inHeader->nOffset = tempOffset;
                 inHeader->nFilledLen = tempFilledLen;
                 notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
@@ -762,7 +713,8 @@
             signed int bytesConsumed = 0;
             int errorCode = 0;
             if (mIsCodecInitialized) {
-                errorCode = decodeXAACStream(inBuffer,inBufferLength, &bytesConsumed, &numOutBytes);
+                errorCode =
+                    decodeXAACStream(inBuffer, inBufferLength, &bytesConsumed, &numOutBytes);
             } else {
                 ALOGW("Assumption that first frame after header initializes decoder failed!");
             }
@@ -775,7 +727,7 @@
 
             /* In case of error, decoder would have given out empty buffer */
             if ((0 != errorCode) && (0 == numOutBytes) && mIsCodecInitialized) {
-                numOutBytes = mOutputFrameLength * (mPcmWdSz/8) * mNumChannels;
+                numOutBytes = mOutputFrameLength * (mPcmWdSz / 8) * mNumChannels;
             }
             numLoops++;
 
@@ -786,7 +738,7 @@
             if (errorCode) {
                 /* Clear buffer for output buffer is done inside XAAC codec */
                 /* TODO - Check if below memset is on top of reset inside codec */
-                memset(mOutputBuffer, 0, numOutBytes); // TODO: check for overflow, ASAN
+                memset(mOutputBuffer, 0, numOutBytes);  // TODO: check for overflow, ASAN
                 // Discard input buffer.
                 inHeader->nFilledLen = 0;
                 // fall through
@@ -805,8 +757,8 @@
             }
 
             if (!outQueue.empty() && numOutBytes) {
-                BufferInfo *outInfo = *outQueue.begin();
-                OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
+                BufferInfo* outInfo = *outQueue.begin();
+                OMX_BUFFERHEADERTYPE* outHeader = outInfo->mHeader;
 
                 if (outHeader->nOffset != 0) {
                     ALOGE("outHeader->nOffset != 0 is not handled");
@@ -815,12 +767,10 @@
                     return;
                 }
 
-                signed short *outBuffer =
-                        reinterpret_cast<signed short *>(outHeader->pBuffer + outHeader->nOffset);
+                signed short* outBuffer =
+                    reinterpret_cast<signed short*>(outHeader->pBuffer + outHeader->nOffset);
                 int samplesize = mNumChannels * sizeof(int16_t);
-                if (outHeader->nOffset
-                        + mOutputFrameLength * samplesize
-                        > outHeader->nAllocLen) {
+                if (outHeader->nOffset + mOutputFrameLength * samplesize > outHeader->nAllocLen) {
                     ALOGE("buffer overflow");
                     mSignalledError = true;
                     notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
@@ -853,12 +803,12 @@
                     ALOGV(" empty block signaling EOS");
                     // send partial or empty block signaling EOS
                     mEndOfOutput = true;
-                    BufferInfo *outInfo = *outQueue.begin();
-                    OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
+                    BufferInfo* outInfo = *outQueue.begin();
+                    OMX_BUFFERHEADERTYPE* outHeader = outInfo->mHeader;
 
                     outHeader->nFilledLen = 0;
                     outHeader->nFlags = OMX_BUFFERFLAG_EOS;
-                    outHeader->nTimeStamp = mPrevTimestamp ;
+                    outHeader->nTimeStamp = mPrevTimestamp;
 
                     mOutputBufferCount++;
                     outInfo->mOwnedByUs = false;
@@ -867,7 +817,7 @@
                     notifyFillBufferDone(outHeader);
                     outHeader = NULL;
                 }
-                break; // if outQueue not empty but no more output
+                break;  // if outQueue not empty but no more output
             }
         }
     }
@@ -895,48 +845,36 @@
 int SoftXAAC::configflushDecode() {
     IA_ERRORCODE err_code;
     UWORD32 ui_init_done;
-    uint32_t inBufferLength=8203;
+    uint32_t inBufferLength = 8203;
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_FLUSH_MEM,
-                                NULL);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_FLUSH_MEM, NULL);
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_FLUSH_MEM");
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_INPUT_BYTES,
-                                0,
-                                &inBufferLength);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_INPUT_BYTES, 0, &inBufferLength);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_FLUSH_MEM,
-                                NULL);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_FLUSH_MEM, NULL);
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_FLUSH_MEM");
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_DONE_QUERY,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_INIT_DONE_QUERY,
                                 &ui_init_done);
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_DONE_QUERY");
 
-
     if (ui_init_done) {
         err_code = getXAACStreamInfo();
         RETURN_IF_FATAL(err_code, "getXAACStreamInfo");
 
-        ALOGV("Found Codec with below config---\nsampFreq %d\nnumChannels %d\npcmWdSz %d\nchannelMask %d\noutputFrameLength %d",
-                                    mSampFreq,mNumChannels,mPcmWdSz,mChannelMask,mOutputFrameLength);
-        if(mNumChannels > MAX_CHANNEL_COUNT) {
+        ALOGV(
+            "Found Codec with below config---\nsampFreq %d\nnumChannels %d\npcmWdSz "
+            "%d\nchannelMask %d\noutputFrameLength %d",
+            mSampFreq, mNumChannels, mPcmWdSz, mChannelMask, mOutputFrameLength);
+        if (mNumChannels > MAX_CHANNEL_COUNT) {
             ALOGE(" No of channels are more than max channels\n");
             mIsCodecInitialized = false;
-        }
-        else
+        } else
             mIsCodecInitialized = true;
     }
     return err_code;
-
 }
 int SoftXAAC::drainDecoder() {
     return 0;
@@ -965,15 +903,13 @@
         case NONE:
             break;
 
-        case AWAITING_DISABLED:
-        {
+        case AWAITING_DISABLED: {
             CHECK(!enabled);
             mOutputPortSettingsChange = AWAITING_ENABLED;
             break;
         }
 
-        default:
-        {
+        default: {
             CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
             CHECK(enabled);
             mOutputPortSettingsChange = NONE;
@@ -1012,10 +948,7 @@
     /* ******************************************************************/
 
     /* Get the API size */
-    err_code = ixheaacd_dec_api(NULL,
-                                IA_API_CMD_GET_API_SIZE,
-                                0,
-                                &pui_api_size);
+    err_code = ixheaacd_dec_api(NULL, IA_API_CMD_GET_API_SIZE, 0, &pui_api_size);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_API_SIZE");
 
     if (mMallocCount == MAX_MEM_ALLOCS) {
@@ -1026,19 +959,16 @@
     /* Allocate memory for API */
     mMemoryArray[mMallocCount] = memalign(4, pui_api_size);
     if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE("malloc for pui_api_size + 4 >> %d Failed",pui_api_size + 4);
+        ALOGE("malloc for pui_api_size + 4 >> %d Failed", pui_api_size + 4);
         return IA_FATAL_ERROR;
     }
     /* Set API object with the memory allocated */
-    mXheaacCodecHandle =
-        (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
+    mXheaacCodecHandle = (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
     mMallocCount++;
 
     /* Set the config params to default values */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS,
-                                NULL);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT,
+                                IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS, NULL);
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS");
 #ifdef ENABLE_MPEG_D_DRC
     /* Get the API size */
@@ -1051,28 +981,22 @@
         return IA_FATAL_ERROR;
     }
 
-   /* Allocate memory for API */
-   mMemoryArray[mMallocCount] = memalign(4, pui_api_size);
+    /* Allocate memory for API */
+    mMemoryArray[mMallocCount] = memalign(4, pui_api_size);
 
-   if(mMemoryArray[mMallocCount] == NULL)
-   {
-       ALOGE("malloc for drc api structure Failed");
-       return IA_FATAL_ERROR;
-   }
-   memset(mMemoryArray[mMallocCount],0,pui_api_size);
+    if (mMemoryArray[mMallocCount] == NULL) {
+        ALOGE("malloc for drc api structure Failed");
+        return IA_FATAL_ERROR;
+    }
+    memset(mMemoryArray[mMallocCount], 0, pui_api_size);
 
-   /* Set API object with the memory allocated */
-   mMpegDDrcHandle =
-       (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
+    /* Set API object with the memory allocated */
+    mMpegDDrcHandle = (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
     mMallocCount++;
 
-
     /* Set the config params to default values */
-    err_code = ia_drc_dec_api(
-       mMpegDDrcHandle,
-       IA_API_CMD_INIT,
-       IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS,
-       NULL);
+    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                              IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS, NULL);
 
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS");
 #endif
@@ -1081,10 +1005,8 @@
     /* Set config parameters                                            */
     /* ******************************************************************/
     UWORD32 ui_mp4_flag = 1;
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_ISMP4,
-                                &ui_mp4_flag);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_ISMP4, &ui_mp4_flag);
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_ISMP4");
 
     /* ******************************************************************/
@@ -1092,9 +1014,7 @@
     /* ******************************************************************/
 
     /* Get memory info tables size */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_MEMTABS_SIZE,
-                                0,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_MEMTABS_SIZE, 0,
                                 &ui_proc_mem_tabs_size);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEMTABS_SIZE");
 
@@ -1105,23 +1025,20 @@
 
     mMemoryArray[mMallocCount] = memalign(4, ui_proc_mem_tabs_size);
     if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE("Malloc for size (ui_proc_mem_tabs_size + 4) = %d failed!",ui_proc_mem_tabs_size + 4);
+        ALOGE("Malloc for size (ui_proc_mem_tabs_size + 4) = %d failed!",
+              ui_proc_mem_tabs_size + 4);
         return IA_FATAL_ERROR;
     }
     mMallocCount++;
     /* Set pointer for process memory tables    */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_MEMTABS_PTR,
-                                0,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_MEMTABS_PTR, 0,
                                 (pVOID)((WORD8*)mMemoryArray[mMallocCount - 1]));
     RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEMTABS_PTR");
 
 
     /* initialize the API, post config, fill memory tables  */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS,
-                                NULL);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT,
+                                IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS, NULL);
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS");
 
     /* ******************************************************************/
@@ -1129,75 +1046,59 @@
     /* ******************************************************************/
     /* There are four different types of memories, that needs to be allocated */
     /* persistent,scratch,input and output */
-    for(i = 0; i < 4; i++) {
+    for (i = 0; i < 4; i++) {
         int ui_size = 0, ui_alignment = 0, ui_type = 0;
         pVOID pv_alloc_ptr;
 
         /* Get memory size */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_GET_MEM_INFO_SIZE,
-                                    i,
-                                    &ui_size);
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_MEM_INFO_SIZE, i, &ui_size);
         RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_SIZE");
 
         /* Get memory alignment */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_GET_MEM_INFO_ALIGNMENT,
-                                    i,
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_MEM_INFO_ALIGNMENT, i,
                                     &ui_alignment);
         RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_ALIGNMENT");
 
         /* Get memory type */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_GET_MEM_INFO_TYPE,
-                                    i,
-                                    &ui_type);
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_MEM_INFO_TYPE, i, &ui_type);
         RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_TYPE");
 
         if (mMallocCount == MAX_MEM_ALLOCS) {
             ALOGE("mMemoryArray is full");
             return IA_FATAL_ERROR;
         }
-
-        mMemoryArray[mMallocCount] =
-            memalign(ui_alignment , ui_size);
+        mMemoryArray[mMallocCount] = memalign(ui_alignment, ui_size);
         if (mMemoryArray[mMallocCount] == NULL) {
-            ALOGE("Malloc for size (ui_size + ui_alignment) = %d failed!",ui_size + ui_alignment);
+            ALOGE("Malloc for size (ui_size + ui_alignment) = %d failed!", ui_size + ui_alignment);
             return IA_FATAL_ERROR;
         }
-        pv_alloc_ptr =
-            (pVOID )((WORD8*)mMemoryArray[mMallocCount]);
+        pv_alloc_ptr = (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
         mMallocCount++;
 
         /* Set the buffer pointer */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_MEM_PTR,
-                                    i,
-                                    pv_alloc_ptr);
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_MEM_PTR, i, pv_alloc_ptr);
         RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
         if (ui_type == IA_MEMTYPE_INPUT) {
             mInputBuffer = (pWORD8)pv_alloc_ptr;
             mInputBufferSize = ui_size;
-
         }
 
         if (ui_type == IA_MEMTYPE_OUTPUT) {
             mOutputBuffer = (pWORD8)pv_alloc_ptr;
         }
-
     }
     /* End first part */
 
-  return IA_NO_ERROR;
+    return IA_NO_ERROR;
 }
 
 int SoftXAAC::configXAACDecoder(uint8_t* inBuffer, uint32_t inBufferLength) {
-
     UWORD32 ui_init_done;
     int32_t i_bytes_consumed;
 
     if (mInputBufferSize < inBufferLength) {
-        ALOGE("Cannot config AAC, input buffer size %d < inBufferLength %d",mInputBufferSize,inBufferLength);
+        ALOGE("Cannot config AAC, input buffer size %d < inBufferLength %d", mInputBufferSize,
+              inBufferLength);
         return false;
     }
 
@@ -1205,51 +1106,41 @@
     memcpy(mInputBuffer, inBuffer, inBufferLength);
 
     /* Set number of bytes to be processed */
-    IA_ERRORCODE err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                             IA_API_CMD_SET_INPUT_BYTES,
-                                             0,
-                                             &inBufferLength);
+    IA_ERRORCODE err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_INPUT_BYTES, 0, &inBufferLength);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
 
     if (mIsCodecConfigFlushRequired) {
         /* If codec is already initialized, then GA header is passed again */
         /* Need to call the Flush API instead of INIT_PROCESS */
         mIsCodecInitialized = false; /* Codec needs to be Reinitialized after flush */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_GA_HDR,
-                                    NULL);
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_GA_HDR, NULL);
         RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_GA_HDR");
-    }
-    else {
+    } else {
         /* Initialize the process */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_INIT_PROCESS,
-                                    NULL);
+        err_code =
+            ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_INIT_PROCESS, NULL);
         RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_PROCESS");
     }
 
     /* Checking for end of initialization */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_DONE_QUERY,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_INIT_DONE_QUERY,
                                 &ui_init_done);
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_DONE_QUERY");
 
     /* How much buffer is used in input buffers */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CURIDX_INPUT_BUF,
-                                0,
-                                &i_bytes_consumed);
+    err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CURIDX_INPUT_BUF, 0, &i_bytes_consumed);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_CURIDX_INPUT_BUF");
 
-    if(ui_init_done){
+    if (ui_init_done) {
         err_code = getXAACStreamInfo();
         RETURN_IF_FATAL(err_code, "getXAACStreamInfo");
 
-        ALOGI("Found Codec with below config---\nsampFreq %d\nnumChannels %d\npcmWdSz %d\nchannelMask %d\noutputFrameLength %d",
-                                    mSampFreq,mNumChannels,mPcmWdSz,mChannelMask,mOutputFrameLength);
+        ALOGI(
+            "Found Codec with below config---\nsampFreq %d\nnumChannels %d\npcmWdSz "
+            "%d\nchannelMask %d\noutputFrameLength %d",
+            mSampFreq, mNumChannels, mPcmWdSz, mChannelMask, mOutputFrameLength);
         mIsCodecInitialized = true;
 
 #ifdef ENABLE_MPEG_D_DRC
@@ -1260,452 +1151,366 @@
 
     return IA_NO_ERROR;
 }
-int SoftXAAC::configMPEGDDrc()
-{
-   IA_ERRORCODE err_code = IA_NO_ERROR;
-   int i_effect_type;
-   int i_loud_norm;
-   int i_target_loudness;
-   unsigned int i_sbr_mode;
-   int n_mems;
-   int i;
+int SoftXAAC::configMPEGDDrc() {
+    IA_ERRORCODE err_code = IA_NO_ERROR;
+    int i_effect_type;
+    int i_loud_norm;
+    int i_target_loudness;
+    unsigned int i_sbr_mode;
+    int n_mems;
+    int i;
 
-#ifdef     ENABLE_MPEG_D_DRC
+#ifdef ENABLE_MPEG_D_DRC
     {
+        /* Sampling Frequency */
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_PARAM_SAMP_FREQ, &mSampFreq);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_SAMP_FREQ");
+        /* Total Number of Channels */
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS, &mNumChannels);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS");
 
-    /* Sampling Frequency */
-    {
-      err_code =
-          ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                         IA_DRC_DEC_CONFIG_PARAM_SAMP_FREQ, &mSampFreq);
-      RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_SAMP_FREQ");
-    }
-    /* Total Number of Channels */
-    {
-      err_code =
-          ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                         IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS, &mNumChannels);
-      RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS");
-    }
+        /* PCM word size  */
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_PARAM_PCM_WDSZ, &mPcmWdSz);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_PCM_WDSZ");
 
-    /* PCM word size  */
-    {
-      err_code =
-          ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                         IA_DRC_DEC_CONFIG_PARAM_PCM_WDSZ, &mPcmWdSz);
-      RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_PCM_WDSZ");
-    }
+        /*Set Effect Type*/
 
-    /*Set Effect Type*/
-
-    {
         err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE, &i_effect_type);
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE, &i_effect_type);
         RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE");
 
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE, &i_effect_type);
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE, &i_effect_type);
         RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE");
 
-    }
-
-/*Set target loudness */
-
-    {
-        err_code = ixheaacd_dec_api(
-            mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS, &i_target_loudness);
+        /*Set target loudness */
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS,
+                                    &i_target_loudness);
         RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS");
 
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS, &i_target_loudness);
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS, &i_target_loudness);
         RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS");
 
-    }
+        /*Set loud_norm_flag*/
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM, &i_loud_norm);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM");
 
-    /*Set loud_norm_flag*/
-    {
-        err_code = ixheaacd_dec_api(
-            mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM, &i_loud_norm);
-        RETURN_IF_FATAL(err_code,"IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM");
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_DRC_LOUD_NORM, &i_loud_norm);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_LOUD_NORM");
 
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE, &i_sbr_mode);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE");
 
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_LOUD_NORM, &i_loud_norm);
-        RETURN_IF_FATAL(err_code,"IA_DRC_DEC_CONFIG_DRC_LOUD_NORM");
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                  IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS, NULL);
 
-    }
+        RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS");
 
+        for (i = 0; i < (WORD32)2; i++) {
+            WORD32 ui_size, ui_alignment, ui_type;
+            pVOID pv_alloc_ptr;
 
+            /* Get memory size */
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_GET_MEM_INFO_SIZE, i, &ui_size);
 
-    err_code = ixheaacd_dec_api(
-        mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-        IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE, &i_sbr_mode);
-        RETURN_IF_FATAL(err_code,"IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE");
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_SIZE");
 
-    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                              IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS, NULL);
+            /* Get memory alignment */
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_GET_MEM_INFO_ALIGNMENT, i,
+                                      &ui_alignment);
 
-    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS");
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_ALIGNMENT");
 
+            /* Get memory type */
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_GET_MEM_INFO_TYPE, i, &ui_type);
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_TYPE");
+            if (mMallocCount == MAX_MEM_ALLOCS) {
+                ALOGE("mMemoryArray is full");
+                return IA_FATAL_ERROR;
+            }
 
+            mMemoryArray[mMallocCount] = memalign(4, ui_size);
+            if (mMemoryArray[mMallocCount] == NULL) {
+                ALOGE(" Cannot create requested memory  %d", ui_size);
+                return IA_FATAL_ERROR;
+            }
+            pv_alloc_ptr = (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
+            mMallocCount++;
 
-    for (i = 0; i < (WORD32)2; i++) {
-      WORD32 ui_size, ui_alignment, ui_type;
-      pVOID pv_alloc_ptr;
+            /* Set the buffer pointer */
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR, i, pv_alloc_ptr);
 
-      /* Get memory size */
-      err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                IA_API_CMD_GET_MEM_INFO_SIZE, i, &ui_size);
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
+        }
+        {
+            WORD32 ui_size;
+            ui_size = 8192 * 2;
+            if (mMallocCount == MAX_MEM_ALLOCS) {
+                ALOGE("mMemoryArray is full");
+                return IA_FATAL_ERROR;
+            }
 
-     RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_SIZE");
+            mMemoryArray[mMallocCount] = memalign(4, ui_size);
+            if (mMemoryArray[mMallocCount] == NULL) {
+                ALOGE(" Cannot create requested memory  %d", ui_size);
+                return IA_FATAL_ERROR;
+            }
 
-      /* Get memory alignment */
-      err_code =
-          ia_drc_dec_api(mMpegDDrcHandle,
-                         IA_API_CMD_GET_MEM_INFO_ALIGNMENT, i, &ui_alignment);
+            mDrcInBuf = (int8_t*)mMemoryArray[mMallocCount];
+            mMallocCount++;
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR, 2,
+                                      /*mOutputBuffer*/ mDrcInBuf);
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
 
-      RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_ALIGNMENT");
+            if (mMallocCount == MAX_MEM_ALLOCS) {
+                ALOGE("mMemoryArray is full");
+                return IA_FATAL_ERROR;
+            }
+            mMemoryArray[mMallocCount] = memalign(4, ui_size);
+            if (mMemoryArray[mMallocCount] == NULL) {
+                ALOGE(" Cannot create requested memory  %d", ui_size);
+                return IA_FATAL_ERROR;
+            }
 
-      /* Get memory type */
-      err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                IA_API_CMD_GET_MEM_INFO_TYPE, i, &ui_type);
-
-     RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_TYPE");
-
-      if (mMallocCount == MAX_MEM_ALLOCS) {
-            ALOGE("mMemoryArray is full");
-            return IA_FATAL_ERROR;
-      }
-      mMemoryArray[mMallocCount] = memalign(4, ui_size);
-      if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE(" Cannot create requested memory  %d",ui_size);
-        return IA_FATAL_ERROR;
-      }
-        pv_alloc_ptr =
-            (pVOID )((WORD8*)mMemoryArray[mMallocCount]);
-        mMallocCount++;
-
-           /* Set the buffer pointer */
-      err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                IA_API_CMD_SET_MEM_PTR, i, pv_alloc_ptr);
-
-      RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
-    }
-    {
-    WORD32 ui_size;
-    ui_size=8192*2;
-    if (mMallocCount == MAX_MEM_ALLOCS) {
-        ALOGE("mMemoryArray is full");
-        return IA_FATAL_ERROR;
-    }
-
-    mMemoryArray[mMallocCount]=memalign(4, ui_size);
-      if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE(" Cannot create requested memory  %d",ui_size);
-        return IA_FATAL_ERROR;
-      }
-
-    mDrcInBuf=(int8_t *)mMemoryArray[mMallocCount];
-    mMallocCount++;
-    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR,
-                              2, /*mOutputBuffer*/ mDrcInBuf);
-    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
-
-    if (mMallocCount == MAX_MEM_ALLOCS) {
-        ALOGE("mMemoryArray is full");
-        return IA_FATAL_ERROR;
-    }
-
-    mMemoryArray[mMallocCount]=memalign(4, ui_size);
-      if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE(" Cannot create requested memory  %d",ui_size);
-        return IA_FATAL_ERROR;
-      }
-
-    mDrcOutBuf=(int8_t *)mMemoryArray[mMallocCount];
-    mMallocCount++;
-    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR,
-                              3, /*mOutputBuffer*/ mDrcOutBuf);
-    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
-    }
-    /*ITTIAM: DRC buffers
+            mDrcOutBuf = (int8_t*)mMemoryArray[mMallocCount];
+            mMallocCount++;
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR, 3,
+                                      /*mOutputBuffer*/ mDrcOutBuf);
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
+        }
+        /* DRC buffers
             buf[0] - contains extension element pay load loudness related
             buf[1] - contains extension element pay load*/
-    {
-      VOID *p_array[2][16];
-      WORD32 ii;
-      WORD32 buf_sizes[2][16];
-      WORD32 num_elements;
-      WORD32 num_config_ext;
-      WORD32 bit_str_fmt = 1;
-
-
-
-      WORD32 uo_num_chan;
-
-      memset(buf_sizes, 0, 32 * sizeof(WORD32));
-
-      err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-          IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_BUF_SIZES, &buf_sizes[0][0]);
-      RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_BUF_SIZES");
-
-      err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-          IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_PTR, &p_array);
-      RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_PTR");
-
-      err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_SET_BUFF_PTR, 0);
-      RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_SET_BUFF_PTR");
-
-
-      err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-          IA_ENHAACPLUS_DEC_CONFIG_NUM_ELE, &num_elements);
-      RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_NUM_ELE");
-
-      err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-          IA_ENHAACPLUS_DEC_CONFIG_NUM_CONFIG_EXT, &num_config_ext);
-      RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_NUM_CONFIG_EXT");
-
-      for (ii = 0; ii < num_config_ext; ii++) {
-        /*copy loudness bitstream*/
-        if (buf_sizes[0][ii] > 0) {
-          memcpy(mDrcInBuf, p_array[0][ii], buf_sizes[0][ii]);
-
-          /*Set bitstream_split_format */
-          err_code = ia_drc_dec_api(
-              mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
-          RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
-
-          /* Set number of bytes to be processed */
-          err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                    IA_API_CMD_SET_INPUT_BYTES_IL_BS, 0,
-                                    &buf_sizes[0][ii]);
-          RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES_IL_BS");
-
-
-          /* Execute process */
-          err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_INIT_CPY_IL_BSF_BUFF, NULL);
-          RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IL_BSF_BUFF");
-
-
-          mDRCFlag = 1;
-        }
-      }
-
-      for (ii = 0; ii < num_elements; ii++) {
-        /*copy config bitstream*/
-        if (buf_sizes[1][ii] > 0) {
-          memcpy(mDrcInBuf, p_array[1][ii], buf_sizes[1][ii]);
-          /* Set number of bytes to be processed */
-
-          /*Set bitstream_split_format */
-          err_code = ia_drc_dec_api(
-              mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
-          RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
-
-          err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                    IA_API_CMD_SET_INPUT_BYTES_IC_BS, 0,
-                                    &buf_sizes[1][ii]);
-          RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES_IC_BS");
-
-
-          /* Execute process */
-          err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_INIT_CPY_IC_BSF_BUFF, NULL);
-
-          RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IC_BSF_BUFF");
-
-          mDRCFlag = 1;
-        }
-      }
-
-      if (mDRCFlag == 1) {
-        mMpegDDRCPresent = 1;
-      } else {
-        mMpegDDRCPresent = 0;
-      }
-
-
-      /*Read interface buffer config file bitstream*/
-      if(mMpegDDRCPresent==1){
-
-        WORD32 interface_is_present = 1;
-        WORD32 frame_length;
-
-        if(i_sbr_mode != 0)
         {
-            if (i_sbr_mode == 1)
-            {
-                frame_length = 2048;
+            VOID* p_array[2][16];
+            WORD32 ii;
+            WORD32 buf_sizes[2][16];
+            WORD32 num_elements;
+            WORD32 num_config_ext;
+            WORD32 bit_str_fmt = 1;
+
+            WORD32 uo_num_chan;
+
+            memset(buf_sizes, 0, 32 * sizeof(WORD32));
+
+            err_code =
+                ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                 IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_BUF_SIZES, &buf_sizes[0][0]);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_BUF_SIZES");
+
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_PTR, &p_array);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_PTR");
+
+            err_code =
+                ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT, IA_CMD_TYPE_INIT_SET_BUFF_PTR, 0);
+            RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_SET_BUFF_PTR");
+
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_NUM_ELE, &num_elements);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_NUM_ELE");
+
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_NUM_CONFIG_EXT, &num_config_ext);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_NUM_CONFIG_EXT");
+
+            for (ii = 0; ii < num_config_ext; ii++) {
+                /*copy loudness bitstream*/
+                if (buf_sizes[0][ii] > 0) {
+                    memcpy(mDrcInBuf, p_array[0][ii], buf_sizes[0][ii]);
+
+                    /*Set bitstream_split_format */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
+                    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
+
+                    /* Set number of bytes to be processed */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_INPUT_BYTES_IL_BS, 0,
+                                              &buf_sizes[0][ii]);
+                    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES_IL_BS");
+
+                    /* Execute process */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                              IA_CMD_TYPE_INIT_CPY_IL_BSF_BUFF, NULL);
+                    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IL_BSF_BUFF");
+
+                    mDRCFlag = 1;
+                }
             }
-            else if(i_sbr_mode == 3)
-            {
-                frame_length = 4096;
+
+            for (ii = 0; ii < num_elements; ii++) {
+                /*copy config bitstream*/
+                if (buf_sizes[1][ii] > 0) {
+                    memcpy(mDrcInBuf, p_array[1][ii], buf_sizes[1][ii]);
+                    /* Set number of bytes to be processed */
+
+                    /*Set bitstream_split_format */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
+                    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
+
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_INPUT_BYTES_IC_BS, 0,
+                                              &buf_sizes[1][ii]);
+                    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES_IC_BS");
+
+                    /* Execute process */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                              IA_CMD_TYPE_INIT_CPY_IC_BSF_BUFF, NULL);
+
+                    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IC_BSF_BUFF");
+
+                    mDRCFlag = 1;
+                }
             }
-            else
-            {
-                frame_length = 1024;
+
+            if (mDRCFlag == 1) {
+                mMpegDDRCPresent = 1;
+            } else {
+                mMpegDDRCPresent = 0;
+            }
+
+            /*Read interface buffer config file bitstream*/
+            if (mMpegDDRCPresent == 1) {
+                WORD32 interface_is_present = 1;
+                WORD32 frame_length;
+
+                if (i_sbr_mode != 0) {
+                    if (i_sbr_mode == 1) {
+                        frame_length = 2048;
+                    } else if (i_sbr_mode == 3) {
+                        frame_length = 4096;
+                    } else {
+                        frame_length = 1024;
+                    }
+                } else {
+                    frame_length = 4096;
+                }
+
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                          IA_DRC_DEC_CONFIG_PARAM_FRAME_SIZE, &frame_length);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_FRAME_SIZE");
+
+                err_code =
+                    ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                   IA_DRC_DEC_CONFIG_PARAM_INT_PRESENT, &interface_is_present);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_INT_PRESENT");
+
+                /* Execute process */
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                          IA_CMD_TYPE_INIT_CPY_IN_BSF_BUFF, NULL);
+                RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IN_BSF_BUFF");
+
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                          IA_CMD_TYPE_INIT_PROCESS, NULL);
+                RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_PROCESS");
+
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                          IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS, &uo_num_chan);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS");
             }
         }
-        else
-        {
-            frame_length = 4096;
-        }
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_PARAM_FRAME_SIZE, &frame_length);
-        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_FRAME_SIZE");
-
-
-
-        err_code = ia_drc_dec_api(
-            mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-            IA_DRC_DEC_CONFIG_PARAM_INT_PRESENT, &interface_is_present);
-        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_INT_PRESENT");
-
-
-        /* Execute process */
-        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                  IA_CMD_TYPE_INIT_CPY_IN_BSF_BUFF, NULL);
-        RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IN_BSF_BUFF");
-
-        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                  IA_CMD_TYPE_INIT_PROCESS, NULL);
-        RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_PROCESS");
-
-        err_code = ia_drc_dec_api(
-            mMpegDDrcHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS, &uo_num_chan);
-        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS");
-      }
     }
-  }
 #endif
 
-return err_code;
-
+    return err_code;
 }
-int SoftXAAC::decodeXAACStream(uint8_t* inBuffer,
-                               uint32_t inBufferLength,
-                               int32_t *bytesConsumed,
-                               int32_t *outBytes) {
+int SoftXAAC::decodeXAACStream(uint8_t* inBuffer, uint32_t inBufferLength, int32_t* bytesConsumed,
+                               int32_t* outBytes) {
     if (mInputBufferSize < inBufferLength) {
-        ALOGE("Cannot config AAC, input buffer size %d < inBufferLength %d",mInputBufferSize,inBufferLength);
+        ALOGE("Cannot config AAC, input buffer size %d < inBufferLength %d", mInputBufferSize,
+              inBufferLength);
         return -1;
     }
 
     /* Copy the buffer passed by Android plugin to codec input buffer */
-    memcpy(mInputBuffer,inBuffer,inBufferLength);
+    memcpy(mInputBuffer, inBuffer, inBufferLength);
 
     /* Set number of bytes to be processed */
-    IA_ERRORCODE err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                             IA_API_CMD_SET_INPUT_BYTES,
-                                             0,
-                                             &inBufferLength);
+    IA_ERRORCODE err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_INPUT_BYTES, 0, &inBufferLength);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
 
     /* Execute process */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_EXECUTE,
-                                IA_CMD_TYPE_DO_EXECUTE,
-                                NULL);
+    err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_EXECUTE, IA_CMD_TYPE_DO_EXECUTE, NULL);
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_DO_EXECUTE");
 
     UWORD32 ui_exec_done;
     /* Checking for end of processing */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_EXECUTE,
-                                IA_CMD_TYPE_DONE_QUERY,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_EXECUTE, IA_CMD_TYPE_DONE_QUERY,
                                 &ui_exec_done);
     RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_DONE_QUERY");
 
 #ifdef ENABLE_MPEG_D_DRC
-     {
-      if (ui_exec_done != 1) {
-        VOID *p_array;        // ITTIAM:buffer to handle gain payload
-        WORD32 buf_size = 0;  // ITTIAM:gain payload length
-        WORD32 bit_str_fmt = 1;
-        WORD32 gain_stream_flag = 1;
+    {
+        if (ui_exec_done != 1) {
+            VOID* p_array;        // ITTIAM:buffer to handle gain payload
+            WORD32 buf_size = 0;  // ITTIAM:gain payload length
+            WORD32 bit_str_fmt = 1;
+            WORD32 gain_stream_flag = 1;
 
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_LEN, &buf_size);
-        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_LEN");
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_LEN, &buf_size);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_LEN");
 
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_BUF, &p_array);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_BUF");
 
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_BUF, &p_array);
-        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_BUF");
+            if (buf_size > 0) {
+                /*Set bitstream_split_format */
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                          IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
 
+                memcpy(mDrcInBuf, p_array, buf_size);
+                /* Set number of bytes to be processed */
+                err_code =
+                    ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_INPUT_BYTES_BS, 0, &buf_size);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
 
-        if (buf_size > 0) {
-          /*Set bitstream_split_format */
-          err_code = ia_drc_dec_api(
-              mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
-          RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                          IA_DRC_DEC_CONFIG_GAIN_STREAM_FLAG, &gain_stream_flag);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
 
-          memcpy(mDrcInBuf, p_array, buf_size);
-          /* Set number of bytes to be processed */
-          err_code =
-              ia_drc_dec_api(mMpegDDrcHandle,
-                             IA_API_CMD_SET_INPUT_BYTES_BS, 0, &buf_size);
-          RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
+                /* Execute process */
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                          IA_CMD_TYPE_INIT_CPY_BSF_BUFF, NULL);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
 
-          err_code = ia_drc_dec_api(
-              mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-              IA_DRC_DEC_CONFIG_GAIN_STREAM_FLAG, &gain_stream_flag);
-          RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
-
-
-          /* Execute process */
-          err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_INIT_CPY_BSF_BUFF, NULL);
-          RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
-
-
-          mMpegDDRCPresent = 1;
+                mMpegDDRCPresent = 1;
+            }
         }
-      }
     }
 #endif
     /* How much buffer is used in input buffers */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CURIDX_INPUT_BUF,
-                                0,
-                                bytesConsumed);
+    err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CURIDX_INPUT_BUF, 0, bytesConsumed);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_CURIDX_INPUT_BUF");
 
     /* Get the output bytes */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_OUTPUT_BYTES,
-                                0,
-                                outBytes);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_OUTPUT_BYTES, 0, outBytes);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_OUTPUT_BYTES");
 #ifdef ENABLE_MPEG_D_DRC
 
     if (mMpegDDRCPresent == 1) {
-      memcpy(mDrcInBuf, mOutputBuffer, *outBytes);
-      err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                IA_API_CMD_SET_INPUT_BYTES, 0, outBytes);
-      RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
+        memcpy(mDrcInBuf, mOutputBuffer, *outBytes);
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_INPUT_BYTES, 0, outBytes);
+        RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
 
+        err_code =
+            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_EXECUTE, IA_CMD_TYPE_DO_EXECUTE, NULL);
+        RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_DO_EXECUTE");
 
-      err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_EXECUTE,
-                                IA_CMD_TYPE_DO_EXECUTE, NULL);
-      RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_DO_EXECUTE");
-
-      memcpy(mOutputBuffer, mDrcOutBuf, *outBytes);
+        memcpy(mOutputBuffer, mDrcOutBuf, *outBytes);
     }
 #endif
     return err_code;
@@ -1715,16 +1520,11 @@
     ALOGI("deInitXAACDecoder");
 
     /* Tell that the input is over in this buffer */
-    IA_ERRORCODE err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                             IA_API_CMD_INPUT_OVER,
-                                             0,
-                                             NULL);
+    IA_ERRORCODE err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INPUT_OVER, 0, NULL);
     RETURN_IF_FATAL(err_code, "IA_API_CMD_INPUT_OVER");
 
-    for(int i = 0; i < mMallocCount; i++)
-    {
-        if(mMemoryArray[i])
-            free(mMemoryArray[i]);
+    for (int i = 0; i < mMallocCount; i++) {
+        if (mMemoryArray[i]) free(mMemoryArray[i]);
     }
     mMallocCount = 0;
 
@@ -1735,59 +1535,47 @@
     IA_ERRORCODE err_code = IA_NO_ERROR;
 
     /* Sampling frequency */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_SAMP_FREQ,
-                                &mSampFreq);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_SAMP_FREQ, &mSampFreq);
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_SAMP_FREQ");
 
     /* Total Number of Channels */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_NUM_CHANNELS,
-                                &mNumChannels);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_NUM_CHANNELS, &mNumChannels);
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_NUM_CHANNELS");
 
     /* PCM word size */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_PCM_WDSZ,
-                                &mPcmWdSz);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_PCM_WDSZ, &mPcmWdSz);
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_PCM_WDSZ");
 
     /* channel mask to tell the arrangement of channels in bit stream */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MASK,
-                                &mChannelMask);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MASK, &mChannelMask);
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MASK");
 
     /* Channel mode to tell MONO/STEREO/DUAL-MONO/NONE_OF_THESE */
     UWORD32 ui_channel_mode;
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MODE,
-                                &ui_channel_mode);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MODE, &ui_channel_mode);
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MODE");
-    if(ui_channel_mode == 0)
+    if (ui_channel_mode == 0)
         ALOGV("Channel Mode: MONO_OR_PS\n");
-    else if(ui_channel_mode == 1)
+    else if (ui_channel_mode == 1)
         ALOGV("Channel Mode: STEREO\n");
-    else if(ui_channel_mode == 2)
+    else if (ui_channel_mode == 2)
         ALOGV("Channel Mode: DUAL-MONO\n");
     else
         ALOGV("Channel Mode: NONE_OF_THESE or MULTICHANNEL\n");
 
     /* Channel mode to tell SBR PRESENT/NOT_PRESENT */
     UWORD32 ui_sbr_mode;
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE,
-                                &ui_sbr_mode);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE, &ui_sbr_mode);
     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE");
-    if(ui_sbr_mode == 0)
+    if (ui_sbr_mode == 0)
         ALOGV("SBR Mode: NOT_PRESENT\n");
-    else if(ui_sbr_mode == 1)
+    else if (ui_sbr_mode == 1)
         ALOGV("SBR Mode: PRESENT\n");
     else
         ALOGV("SBR Mode: ILLEGAL\n");
@@ -1797,132 +1585,103 @@
     /* not yet added in codec                            */
     mOutputFrameLength = 1024 * (1 + ui_sbr_mode);
 
-    ALOGI("mOutputFrameLength %d ui_sbr_mode %d",mOutputFrameLength,ui_sbr_mode);
+    ALOGI("mOutputFrameLength %d ui_sbr_mode %d", mOutputFrameLength, ui_sbr_mode);
 
     return IA_NO_ERROR;
 }
 
-IA_ERRORCODE SoftXAAC::setXAACDRCInfo(int32_t drcCut,
-                                      int32_t drcBoost,
-                                      int32_t drcRefLevel,
+IA_ERRORCODE SoftXAAC::setXAACDRCInfo(int32_t drcCut, int32_t drcBoost, int32_t drcRefLevel,
                                       int32_t drcHeavyCompression
-                                #ifdef ENABLE_MPEG_D_DRC
-                                      ,int32_t drEffectType
-                                #endif
-                                      ) {
+#ifdef ENABLE_MPEG_D_DRC
+                                      ,
+                                      int32_t drEffectType
+#endif
+) {
     IA_ERRORCODE err_code = IA_NO_ERROR;
 
     int32_t ui_drc_enable = 1;
     int32_t i_effect_type, i_target_loudness, i_loud_norm;
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_ENABLE,
-                                &ui_drc_enable);
-     RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_ENABLE");
-    if (drcCut !=-1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT,
-                                    &drcCut);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_ENABLE, &ui_drc_enable);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_ENABLE");
+    if (drcCut != -1) {
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT, &drcCut);
         RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT");
     }
 
-    if (drcBoost !=-1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST,
-                                    &drcBoost);
+    if (drcBoost != -1) {
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST, &drcBoost);
         RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST");
     }
 
     if (drcRefLevel != -1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL,
-                                    &drcRefLevel);
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL, &drcRefLevel);
         RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL");
     }
 #ifdef ENABLE_MPEG_D_DRC
     if (drcRefLevel != -1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS,
-                                    &drcRefLevel);
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS, &drcRefLevel);
         RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS");
     }
 #endif
     if (drcHeavyCompression != -1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP,
-                                    &drcHeavyCompression);
+        err_code =
+            ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                             IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP, &drcHeavyCompression);
         RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP");
     }
 
 #ifdef ENABLE_MPEG_D_DRC
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE,
-                                    &drEffectType);
-        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE, &drEffectType);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE");
 #endif
 
 #ifdef ENABLE_MPEG_D_DRC
     /*Set Effect Type*/
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE, &i_effect_type);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE");
 
-    {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE, &i_effect_type);
-        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE");
+    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                              IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE, &i_effect_type);
 
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE, &i_effect_type);
+    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE");
 
-        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE");
+    /*Set target loudness */
+    err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                         IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS, &i_target_loudness);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS");
 
-    }
+    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                              IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS, &i_target_loudness);
+    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS");
 
-/*Set target loudness */
-
-    {
-        err_code = ixheaacd_dec_api(
-            mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS, &i_target_loudness);
-        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS");
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS, &i_target_loudness);
-        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS");
-
-    }
     /*Set loud_norm_flag*/
-    {
-        err_code = ixheaacd_dec_api(
-            mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM, &i_loud_norm);
-        RETURN_IF_FATAL(err_code,"IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM, &i_loud_norm);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM");
 
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_LOUD_NORM, &i_loud_norm);
+    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                              IA_DRC_DEC_CONFIG_DRC_LOUD_NORM, &i_loud_norm);
 
-        RETURN_IF_FATAL(err_code,"IA_DRC_DEC_CONFIG_DRC_LOUD_NORM");
-
-    }
+    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_LOUD_NORM");
 
 #endif
 
-
     return IA_NO_ERROR;
 }
 
 }  // namespace android
 
-android::SoftOMXComponent *createSoftOMXComponent(
-        const char *name, const OMX_CALLBACKTYPE *callbacks,
-        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
+android::SoftOMXComponent* createSoftOMXComponent(const char* name,
+                                                  const OMX_CALLBACKTYPE* callbacks,
+                                                  OMX_PTR appData, OMX_COMPONENTTYPE** component) {
     ALOGI("createSoftOMXComponent for SoftXAACDEC");
     return new android::SoftXAAC(name, callbacks, appData, component);
 }
diff --git a/media/libstagefright/codecs/xaacdec/SoftXAAC.h b/media/libstagefright/codecs/xaacdec/SoftXAAC.h
index 0b3a612..6176082 100644
--- a/media/libstagefright/codecs/xaacdec/SoftXAAC.h
+++ b/media/libstagefright/codecs/xaacdec/SoftXAAC.h
@@ -35,59 +35,49 @@
 
 #define MAX_MEM_ALLOCS 100
 
-extern "C" IA_ERRORCODE ixheaacd_dec_api(pVOID p_ia_module_obj,
-                        WORD32 i_cmd, WORD32 i_idx, pVOID pv_value);
-extern "C" IA_ERRORCODE ia_drc_dec_api(pVOID p_ia_module_obj,
-                        WORD32 i_cmd, WORD32 i_idx, pVOID pv_value);
-extern "C"  IA_ERRORCODE ixheaacd_get_config_param(pVOID p_ia_process_api_obj,
-                                       pWORD32 pi_samp_freq,
-                                       pWORD32 pi_num_chan,
-                                       pWORD32 pi_pcm_wd_sz,
-                                       pWORD32 pi_channel_mask);
+extern "C" IA_ERRORCODE ixheaacd_dec_api(pVOID p_ia_module_obj, WORD32 i_cmd, WORD32 i_idx,
+                                         pVOID pv_value);
+extern "C" IA_ERRORCODE ia_drc_dec_api(pVOID p_ia_module_obj, WORD32 i_cmd, WORD32 i_idx,
+                                       pVOID pv_value);
+extern "C" IA_ERRORCODE ixheaacd_get_config_param(pVOID p_ia_process_api_obj, pWORD32 pi_samp_freq,
+                                                  pWORD32 pi_num_chan, pWORD32 pi_pcm_wd_sz,
+                                                  pWORD32 pi_channel_mask);
 
 namespace android {
 
 struct SoftXAAC : public SimpleSoftOMXComponent {
-    SoftXAAC(const char *name,
-            const OMX_CALLBACKTYPE *callbacks,
-            OMX_PTR appData,
-            OMX_COMPONENTTYPE **component);
+    SoftXAAC(const char* name, const OMX_CALLBACKTYPE* callbacks, OMX_PTR appData,
+             OMX_COMPONENTTYPE** component);
 
-protected:
+   protected:
     virtual ~SoftXAAC();
 
-    virtual OMX_ERRORTYPE internalGetParameter(
-            OMX_INDEXTYPE index, OMX_PTR params);
+    virtual OMX_ERRORTYPE internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params);
 
-    virtual OMX_ERRORTYPE internalSetParameter(
-            OMX_INDEXTYPE index, const OMX_PTR params);
+    virtual OMX_ERRORTYPE internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params);
 
     virtual void onQueueFilled(OMX_U32 portIndex);
     virtual void onPortFlushCompleted(OMX_U32 portIndex);
     virtual void onPortEnableCompleted(OMX_U32 portIndex, bool enabled);
     virtual void onReset();
 
-private:
+   private:
     enum {
-        kNumInputBuffers        = 4,
-        kNumOutputBuffers       = 4,
-        kNumDelayBlocksMax      = 8,
+        kNumInputBuffers = 4,
+        kNumOutputBuffers = 4,
+        kNumDelayBlocksMax = 8,
     };
 
     bool mIsADTS;
     size_t mInputBufferCount;
     size_t mOutputBufferCount;
     bool mSignalledError;
-    OMX_BUFFERHEADERTYPE *mLastInHeader;
+    OMX_BUFFERHEADERTYPE* mLastInHeader;
     int64_t mPrevTimestamp;
     int64_t mCurrentTimestamp;
     uint32_t mBufSize;
 
-    enum {
-        NONE,
-        AWAITING_DISABLED,
-        AWAITING_ENABLED
-    } mOutputPortSettingsChange;
+    enum { NONE, AWAITING_DISABLED, AWAITING_ENABLED } mOutputPortSettingsChange;
 
     void initPorts();
     status_t initDecoder();
@@ -98,48 +88,43 @@
 
     int configXAACDecoder(uint8_t* inBuffer, uint32_t inBufferLength);
     int configMPEGDDrc();
-    int decodeXAACStream(uint8_t* inBuffer,
-                         uint32_t inBufferLength,
-                         int32_t *bytesConsumed,
-                         int32_t *outBytes);
+    int decodeXAACStream(uint8_t* inBuffer, uint32_t inBufferLength, int32_t* bytesConsumed,
+                         int32_t* outBytes);
 
     int configflushDecode();
     IA_ERRORCODE getXAACStreamInfo();
-    IA_ERRORCODE setXAACDRCInfo(int32_t drcCut,
-                                int32_t drcBoost,
-                                int32_t drcRefLevel,
+    IA_ERRORCODE setXAACDRCInfo(int32_t drcCut, int32_t drcBoost, int32_t drcRefLevel,
                                 int32_t drcHeavyCompression
 #ifdef ENABLE_MPEG_D_DRC
-                                ,int32_t drEffectType
+                                ,
+                                int32_t drEffectType
 #endif
-                               );
+    );
 
     bool mEndOfInput;
     bool mEndOfOutput;
 
-    void*       mXheaacCodecHandle;
-    void*       mMpegDDrcHandle;
-    uint32_t    mInputBufferSize;
-    uint32_t    mOutputFrameLength;
-    int8_t*     mInputBuffer;
-    int8_t*     mOutputBuffer;
-    int32_t     mSampFreq;
-    int32_t     mNumChannels;
-    int32_t     mPcmWdSz;
-    int32_t     mChannelMask;
-    bool        mIsCodecInitialized;
-    bool        mIsCodecConfigFlushRequired;
-    int8_t *mDrcInBuf;
-    int8_t *mDrcOutBuf;
+    void* mXheaacCodecHandle;
+    void* mMpegDDrcHandle;
+    uint32_t mInputBufferSize;
+    uint32_t mOutputFrameLength;
+    int8_t* mInputBuffer;
+    int8_t* mOutputBuffer;
+    int32_t mSampFreq;
+    int32_t mNumChannels;
+    int32_t mPcmWdSz;
+    int32_t mChannelMask;
+    bool mIsCodecInitialized;
+    bool mIsCodecConfigFlushRequired;
+    int8_t* mDrcInBuf;
+    int8_t* mDrcOutBuf;
     int32_t mMpegDDRCPresent;
     int32_t mDRCFlag;
 
-
-    void*       mMemoryArray[MAX_MEM_ALLOCS];
-    int32_t     mMallocCount;
+    void* mMemoryArray[MAX_MEM_ALLOCS];
+    int32_t mMallocCount;
 
     DISALLOW_EVIL_CONSTRUCTORS(SoftXAAC);
-
 };
 
 }  // namespace android
diff --git a/media/libstagefright/omx/OMXNodeInstance.cpp b/media/libstagefright/omx/OMXNodeInstance.cpp
index 7d2c2dd..32113c2 100644
--- a/media/libstagefright/omx/OMXNodeInstance.cpp
+++ b/media/libstagefright/omx/OMXNodeInstance.cpp
@@ -1085,7 +1085,8 @@
         }
 
         case OMXBuffer::kBufferTypeANWBuffer: {
-            if (mPortMode[portIndex] != IOMX::kPortModePresetANWBuffer) {
+            if (mPortMode[portIndex] != IOMX::kPortModePresetANWBuffer
+                    && mPortMode[portIndex] != IOMX::kPortModeDynamicANWBuffer) {
                 break;
             }
             return useGraphicBuffer_l(portIndex, omxBuffer.mGraphicBuffer, buffer);
@@ -1609,12 +1610,15 @@
     }
     BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
 
+    // Invalidate buffers in the client side first before calling OMX_FreeBuffer.
+    // If not, pending events in the client side might access the buffers after free.
+    invalidateBufferID(buffer);
+
     OMX_ERRORTYPE err = OMX_FreeBuffer(mHandle, portIndex, header);
     CLOG_IF_ERROR(freeBuffer, err, "%s:%u %#x", portString(portIndex), portIndex, buffer);
 
     delete buffer_meta;
     buffer_meta = NULL;
-    invalidateBufferID(buffer);
 
     return StatusFromOMXError(err);
 }
diff --git a/media/ndk/include/media/NdkImage.h b/media/ndk/include/media/NdkImage.h
index 19df760..38e12e3 100644
--- a/media/ndk/include/media/NdkImage.h
+++ b/media/ndk/include/media/NdkImage.h
@@ -516,8 +516,6 @@
     int32_t bottom;
 } AImageCropRect;
 
-#if __ANDROID_API__ >= 24
-
 /**
  * Return the image back the the system and delete the AImage object from memory.
  *
@@ -529,7 +527,7 @@
  *
  * @param image The {@link AImage} to be deleted.
  */
-void AImage_delete(AImage* image);
+void AImage_delete(AImage* image) __INTRODUCED_IN(24);
 
 /**
  * Query the width of the input {@link AImage}.
@@ -543,7 +541,7 @@
  *         <li>{@link AMEDIA_ERROR_INVALID_OBJECT} if the {@link AImageReader} generated this
  *                 image has been deleted.</li></ul>
  */
-media_status_t AImage_getWidth(const AImage* image, /*out*/int32_t* width);
+media_status_t AImage_getWidth(const AImage* image, /*out*/int32_t* width) __INTRODUCED_IN(24);
 
 /**
  * Query the height of the input {@link AImage}.
@@ -557,7 +555,7 @@
  *         <li>{@link AMEDIA_ERROR_INVALID_OBJECT} if the {@link AImageReader} generated this
  *                 image has been deleted.</li></ul>
  */
-media_status_t AImage_getHeight(const AImage* image, /*out*/int32_t* height);
+media_status_t AImage_getHeight(const AImage* image, /*out*/int32_t* height) __INTRODUCED_IN(24);
 
 /**
  * Query the format of the input {@link AImage}.
@@ -573,7 +571,7 @@
  *         <li>{@link AMEDIA_ERROR_INVALID_OBJECT} if the {@link AImageReader} generated this
  *                 image has been deleted.</li></ul>
  */
-media_status_t AImage_getFormat(const AImage* image, /*out*/int32_t* format);
+media_status_t AImage_getFormat(const AImage* image, /*out*/int32_t* format) __INTRODUCED_IN(24);
 
 /**
  * Query the cropped rectangle of the input {@link AImage}.
@@ -590,7 +588,7 @@
  *         <li>{@link AMEDIA_ERROR_INVALID_OBJECT} if the {@link AImageReader} generated this
  *                 image has been deleted.</li></ul>
  */
-media_status_t AImage_getCropRect(const AImage* image, /*out*/AImageCropRect* rect);
+media_status_t AImage_getCropRect(const AImage* image, /*out*/AImageCropRect* rect) __INTRODUCED_IN(24);
 
 /**
  * Query the timestamp of the input {@link AImage}.
@@ -614,7 +612,7 @@
  *         <li>{@link AMEDIA_ERROR_INVALID_OBJECT} if the {@link AImageReader} generated this
  *                 image has been deleted.</li></ul>
  */
-media_status_t AImage_getTimestamp(const AImage* image, /*out*/int64_t* timestampNs);
+media_status_t AImage_getTimestamp(const AImage* image, /*out*/int64_t* timestampNs) __INTRODUCED_IN(24);
 
 /**
  * Query the number of planes of the input {@link AImage}.
@@ -632,7 +630,7 @@
  *         <li>{@link AMEDIA_ERROR_INVALID_OBJECT} if the {@link AImageReader} generated this
  *                 image has been deleted.</li></ul>
  */
-media_status_t AImage_getNumberOfPlanes(const AImage* image, /*out*/int32_t* numPlanes);
+media_status_t AImage_getNumberOfPlanes(const AImage* image, /*out*/int32_t* numPlanes) __INTRODUCED_IN(24);
 
 /**
  * Query the pixel stride of the input {@link AImage}.
@@ -660,7 +658,7 @@
  *                 for CPU access.</li></ul>
  */
 media_status_t AImage_getPlanePixelStride(
-        const AImage* image, int planeIdx, /*out*/int32_t* pixelStride);
+        const AImage* image, int planeIdx, /*out*/int32_t* pixelStride) __INTRODUCED_IN(24);
 
 /**
  * Query the row stride of the input {@link AImage}.
@@ -687,7 +685,7 @@
  *                 for CPU access.</li></ul>
  */
 media_status_t AImage_getPlaneRowStride(
-        const AImage* image, int planeIdx, /*out*/int32_t* rowStride);
+        const AImage* image, int planeIdx, /*out*/int32_t* rowStride) __INTRODUCED_IN(24);
 
 /**
  * Get the data pointer of the input image for direct application access.
@@ -712,11 +710,7 @@
  */
 media_status_t AImage_getPlaneData(
         const AImage* image, int planeIdx,
-        /*out*/uint8_t** data, /*out*/int* dataLength);
-
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 26
+        /*out*/uint8_t** data, /*out*/int* dataLength) __INTRODUCED_IN(24);
 
 /**
  * Return the image back the the system and delete the AImage object from memory asynchronously.
@@ -732,7 +726,7 @@
  *
  * @see sync.h
  */
-void AImage_deleteAsync(AImage* image, int releaseFenceFd);
+void AImage_deleteAsync(AImage* image, int releaseFenceFd) __INTRODUCED_IN(26);
 
 /**
  * Get the hardware buffer handle of the input image intended for GPU and/or hardware access.
@@ -760,9 +754,7 @@
  *
  * @see AImageReader_ImageCallback
  */
-media_status_t AImage_getHardwareBuffer(const AImage* image, /*out*/AHardwareBuffer** buffer);
-
-#endif /* __ANDROID_API__ >= 26 */
+media_status_t AImage_getHardwareBuffer(const AImage* image, /*out*/AHardwareBuffer** buffer) __INTRODUCED_IN(26);
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkImageReader.h b/media/ndk/include/media/NdkImageReader.h
index 571410b..eb1a44a 100644
--- a/media/ndk/include/media/NdkImageReader.h
+++ b/media/ndk/include/media/NdkImageReader.h
@@ -50,8 +50,6 @@
  */
 typedef struct AImageReader AImageReader;
 
-#if __ANDROID_API__ >= 24
-
 /**
  * Create a new reader for images of the desired size and format.
  *
@@ -88,7 +86,7 @@
  */
 media_status_t AImageReader_new(
         int32_t width, int32_t height, int32_t format, int32_t maxImages,
-        /*out*/AImageReader** reader);
+        /*out*/AImageReader** reader) __INTRODUCED_IN(24);
 
 /**
  * Delete an {@link AImageReader} and return all images generated by this reader to system.
@@ -100,7 +98,7 @@
  *
  * @param reader The image reader to be deleted.
  */
-void AImageReader_delete(AImageReader* reader);
+void AImageReader_delete(AImageReader* reader) __INTRODUCED_IN(24);
 
 /**
  * Get a {@link ANativeWindow} that can be used to produce {@link AImage} for this image reader.
@@ -114,7 +112,7 @@
  *         <li>{@link AMEDIA_OK} if the method call succeeds.</li>
  *         <li>{@link AMEDIA_ERROR_INVALID_PARAMETER} if reader or window is NULL.</li></ul>
  */
-media_status_t AImageReader_getWindow(AImageReader* reader, /*out*/ANativeWindow** window);
+media_status_t AImageReader_getWindow(AImageReader* reader, /*out*/ANativeWindow** window) __INTRODUCED_IN(24);
 
 /**
  * Query the default width of the {@link AImage} generated by this reader, in pixels.
@@ -130,7 +128,7 @@
  *         <li>{@link AMEDIA_OK} if the method call succeeds.</li>
  *         <li>{@link AMEDIA_ERROR_INVALID_PARAMETER} if reader or width is NULL.</li></ul>
  */
-media_status_t AImageReader_getWidth(const AImageReader* reader, /*out*/int32_t* width);
+media_status_t AImageReader_getWidth(const AImageReader* reader, /*out*/int32_t* width) __INTRODUCED_IN(24);
 
 /**
  * Query the default height of the {@link AImage} generated by this reader, in pixels.
@@ -146,7 +144,7 @@
  *         <li>{@link AMEDIA_OK} if the method call succeeds.</li>
  *         <li>{@link AMEDIA_ERROR_INVALID_PARAMETER} if reader or height is NULL.</li></ul>
  */
-media_status_t AImageReader_getHeight(const AImageReader* reader, /*out*/int32_t* height);
+media_status_t AImageReader_getHeight(const AImageReader* reader, /*out*/int32_t* height) __INTRODUCED_IN(24);
 
 /**
  * Query the format of the {@link AImage} generated by this reader.
@@ -159,7 +157,7 @@
  *         <li>{@link AMEDIA_OK} if the method call succeeds.</li>
  *         <li>{@link AMEDIA_ERROR_INVALID_PARAMETER} if reader or format is NULL.</li></ul>
  */
-media_status_t AImageReader_getFormat(const AImageReader* reader, /*out*/int32_t* format);
+media_status_t AImageReader_getFormat(const AImageReader* reader, /*out*/int32_t* format) __INTRODUCED_IN(24);
 
 /**
  * Query the maximum number of concurrently acquired {@link AImage}s of this reader.
@@ -172,7 +170,7 @@
  *         <li>{@link AMEDIA_OK} if the method call succeeds.</li>
  *         <li>{@link AMEDIA_ERROR_INVALID_PARAMETER} if reader or maxImages is NULL.</li></ul>
  */
-media_status_t AImageReader_getMaxImages(const AImageReader* reader, /*out*/int32_t* maxImages);
+media_status_t AImageReader_getMaxImages(const AImageReader* reader, /*out*/int32_t* maxImages) __INTRODUCED_IN(24);
 
 /**
  * Acquire the next {@link AImage} from the image reader's queue.
@@ -208,7 +206,7 @@
  *
  * @see AImageReader_acquireLatestImage
  */
-media_status_t AImageReader_acquireNextImage(AImageReader* reader, /*out*/AImage** image);
+media_status_t AImageReader_acquireNextImage(AImageReader* reader, /*out*/AImage** image) __INTRODUCED_IN(24);
 
 /**
 
@@ -252,7 +250,7 @@
  *
  * @see AImageReader_acquireNextImage
  */
-media_status_t AImageReader_acquireLatestImage(AImageReader* reader, /*out*/AImage** image);
+media_status_t AImageReader_acquireLatestImage(AImageReader* reader, /*out*/AImage** image) __INTRODUCED_IN(24);
 
 
 /**
@@ -296,11 +294,7 @@
  *         <li>{@link AMEDIA_ERROR_INVALID_PARAMETER} if reader is NULL.</li></ul>
  */
 media_status_t AImageReader_setImageListener(
-        AImageReader* reader, AImageReader_ImageListener* listener);
-
-#endif /* __ANDROID_API__ >= 24 */
-
-#if __ANDROID_API__ >= 26
+        AImageReader* reader, AImageReader_ImageListener* listener) __INTRODUCED_IN(24);
 
 /**
  * AImageReader constructor similar to {@link AImageReader_new} that takes an additional parameter
@@ -365,7 +359,7 @@
  */
 media_status_t AImageReader_newWithUsage(
         int32_t width, int32_t height, int32_t format, uint64_t usage, int32_t maxImages,
-        /*out*/ AImageReader** reader);
+        /*out*/ AImageReader** reader) __INTRODUCED_IN(26);
 
 /**
  * Acquire the next {@link AImage} from the image reader's queue asynchronously.
@@ -384,7 +378,7 @@
  * @see sync_get_fence_info
  */
 media_status_t AImageReader_acquireNextImageAsync(
-        AImageReader* reader, /*out*/AImage** image, /*out*/int* acquireFenceFd);
+        AImageReader* reader, /*out*/AImage** image, /*out*/int* acquireFenceFd) __INTRODUCED_IN(26);
 
 /**
  * Acquire the latest {@link AImage} from the image reader's queue asynchronously, dropping older
@@ -404,7 +398,7 @@
  * @see sync_get_fence_info
  */
 media_status_t AImageReader_acquireLatestImageAsync(
-        AImageReader* reader, /*out*/AImage** image, /*out*/int* acquireFenceFd);
+        AImageReader* reader, /*out*/AImage** image, /*out*/int* acquireFenceFd) __INTRODUCED_IN(26);
 /**
  * Signature of the callback which is called when {@link AImageReader} is about to remove a buffer.
  *
@@ -459,9 +453,7 @@
  * @see AImage_getHardwareBuffer
  */
 media_status_t AImageReader_setBufferRemovedListener(
-        AImageReader* reader, AImageReader_BufferRemovedListener* listener);
-
-#endif /* __ANDROID_API__ >= 26 */
+        AImageReader* reader, AImageReader_BufferRemovedListener* listener) __INTRODUCED_IN(26);
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaCodec.h b/media/ndk/include/media/NdkMediaCodec.h
index c49582d..b329b39 100644
--- a/media/ndk/include/media/NdkMediaCodec.h
+++ b/media/ndk/include/media/NdkMediaCodec.h
@@ -121,30 +121,28 @@
       AMediaCodecOnAsyncError           onAsyncError;
 };
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Create codec by name. Use this if you know the exact codec you want to use.
  * When configuring, you will need to specify whether to use the codec as an
  * encoder or decoder.
  */
-AMediaCodec* AMediaCodec_createCodecByName(const char *name);
+AMediaCodec* AMediaCodec_createCodecByName(const char *name) __INTRODUCED_IN(21);
 
 /**
  * Create codec by mime type. Most applications will use this, specifying a
  * mime type obtained from media extractor.
  */
-AMediaCodec* AMediaCodec_createDecoderByType(const char *mime_type);
+AMediaCodec* AMediaCodec_createDecoderByType(const char *mime_type) __INTRODUCED_IN(21);
 
 /**
  * Create encoder by name.
  */
-AMediaCodec* AMediaCodec_createEncoderByType(const char *mime_type);
+AMediaCodec* AMediaCodec_createEncoderByType(const char *mime_type) __INTRODUCED_IN(21);
 
 /**
  * delete the codec and free its resources
  */
-media_status_t AMediaCodec_delete(AMediaCodec*);
+media_status_t AMediaCodec_delete(AMediaCodec*) __INTRODUCED_IN(21);
 
 /**
  * Configure the codec. For decoding you would typically get the format from an extractor.
@@ -154,43 +152,43 @@
         const AMediaFormat* format,
         ANativeWindow* surface,
         AMediaCrypto *crypto,
-        uint32_t flags);
+        uint32_t flags) __INTRODUCED_IN(21);
 
 /**
  * Start the codec. A codec must be configured before it can be started, and must be started
  * before buffers can be sent to it.
  */
-media_status_t AMediaCodec_start(AMediaCodec*);
+media_status_t AMediaCodec_start(AMediaCodec*) __INTRODUCED_IN(21);
 
 /**
  * Stop the codec.
  */
-media_status_t AMediaCodec_stop(AMediaCodec*);
+media_status_t AMediaCodec_stop(AMediaCodec*) __INTRODUCED_IN(21);
 
 /*
  * Flush the codec's input and output. All indices previously returned from calls to
  * AMediaCodec_dequeueInputBuffer and AMediaCodec_dequeueOutputBuffer become invalid.
  */
-media_status_t AMediaCodec_flush(AMediaCodec*);
+media_status_t AMediaCodec_flush(AMediaCodec*) __INTRODUCED_IN(21);
 
 /**
  * Get an input buffer. The specified buffer index must have been previously obtained from
  * dequeueInputBuffer, and not yet queued.
  */
-uint8_t* AMediaCodec_getInputBuffer(AMediaCodec*, size_t idx, size_t *out_size);
+uint8_t* AMediaCodec_getInputBuffer(AMediaCodec*, size_t idx, size_t *out_size) __INTRODUCED_IN(21);
 
 /**
  * Get an output buffer. The specified buffer index must have been previously obtained from
  * dequeueOutputBuffer, and not yet queued.
  */
-uint8_t* AMediaCodec_getOutputBuffer(AMediaCodec*, size_t idx, size_t *out_size);
+uint8_t* AMediaCodec_getOutputBuffer(AMediaCodec*, size_t idx, size_t *out_size) __INTRODUCED_IN(21);
 
 /**
  * Get the index of the next available input buffer. An app will typically use this with
  * getInputBuffer() to get a pointer to the buffer, then copy the data to be encoded or decoded
  * into the buffer before passing it to the codec.
  */
-ssize_t AMediaCodec_dequeueInputBuffer(AMediaCodec*, int64_t timeoutUs);
+ssize_t AMediaCodec_dequeueInputBuffer(AMediaCodec*, int64_t timeoutUs) __INTRODUCED_IN(21);
 
 /*
  * __USE_FILE_OFFSET64 changes the type of off_t in LP32, which changes the ABI
@@ -221,7 +219,7 @@
  */
 media_status_t AMediaCodec_queueInputBuffer(AMediaCodec*, size_t idx,
                                             _off_t_compat offset, size_t size,
-                                            uint64_t time, uint32_t flags);
+                                            uint64_t time, uint32_t flags) __INTRODUCED_IN(21);
 
 /**
  * Send the specified buffer to the codec for processing.
@@ -229,7 +227,7 @@
 media_status_t AMediaCodec_queueSecureInputBuffer(AMediaCodec*, size_t idx,
                                                   _off_t_compat offset,
                                                   AMediaCodecCryptoInfo*,
-                                                  uint64_t time, uint32_t flags);
+                                                  uint64_t time, uint32_t flags) __INTRODUCED_IN(21);
 
 #undef _off_t_compat
 
@@ -237,21 +235,21 @@
  * Get the index of the next available buffer of processed data.
  */
 ssize_t AMediaCodec_dequeueOutputBuffer(AMediaCodec*, AMediaCodecBufferInfo *info,
-        int64_t timeoutUs);
-AMediaFormat* AMediaCodec_getOutputFormat(AMediaCodec*);
+        int64_t timeoutUs) __INTRODUCED_IN(21);
+AMediaFormat* AMediaCodec_getOutputFormat(AMediaCodec*) __INTRODUCED_IN(21);
 
 /**
  * Get format of the buffer. The specified buffer index must have been previously obtained from
  * dequeueOutputBuffer.
  */
-AMediaFormat* AMediaCodec_getBufferFormat(AMediaCodec*, size_t index);
+AMediaFormat* AMediaCodec_getBufferFormat(AMediaCodec*, size_t index) __INTRODUCED_IN(21);
 
 /**
  * If you are done with a buffer, use this call to return the buffer to
  * the codec. If you previously specified a surface when configuring this
  * video decoder you can optionally render the buffer.
  */
-media_status_t AMediaCodec_releaseOutputBuffer(AMediaCodec*, size_t idx, bool render);
+media_status_t AMediaCodec_releaseOutputBuffer(AMediaCodec*, size_t idx, bool render) __INTRODUCED_IN(21);
 
 /**
  * Dynamically sets the output surface of a codec.
@@ -263,7 +261,7 @@
  *
  * For more details, see the Java documentation for MediaCodec.setOutputSurface.
  */
-media_status_t AMediaCodec_setOutputSurface(AMediaCodec*, ANativeWindow* surface);
+media_status_t AMediaCodec_setOutputSurface(AMediaCodec*, ANativeWindow* surface) __INTRODUCED_IN(21);
 
 /**
  * If you are done with a buffer, use this call to update its surface timestamp
@@ -274,9 +272,7 @@
  * For more details, see the Java documentation for MediaCodec.releaseOutputBuffer.
  */
 media_status_t AMediaCodec_releaseOutputBufferAtTime(
-        AMediaCodec *mData, size_t idx, int64_t timestampNs);
-
-#if __ANDROID_API__ >= 26
+        AMediaCodec *mData, size_t idx, int64_t timestampNs) __INTRODUCED_IN(21);
 
 /**
  * Creates a Surface that can be used as the input to encoder, in place of input buffers
@@ -290,7 +286,7 @@
  * For more details, see the Java documentation for MediaCodec.createInputSurface.
  */
 media_status_t AMediaCodec_createInputSurface(
-        AMediaCodec *mData, ANativeWindow **surface);
+        AMediaCodec *mData, ANativeWindow **surface) __INTRODUCED_IN(26);
 
 /**
  * Creates a persistent Surface that can be used as the input to encoder
@@ -306,7 +302,7 @@
  * For more details, see the Java documentation for MediaCodec.createPersistentInputSurface.
  */
 media_status_t AMediaCodec_createPersistentInputSurface(
-        ANativeWindow **surface);
+        ANativeWindow **surface) __INTRODUCED_IN(26);
 
 /**
  * Set a persistent-surface that can be used as the input to encoder, in place of input buffers
@@ -319,7 +315,7 @@
  * For more details, see the Java documentation for MediaCodec.setInputSurface.
  */
 media_status_t AMediaCodec_setInputSurface(
-        AMediaCodec *mData, ANativeWindow *surface);
+        AMediaCodec *mData, ANativeWindow *surface) __INTRODUCED_IN(26);
 
 /**
  * Signal additional parameters to the codec instance.
@@ -330,7 +326,7 @@
  * NOTE: Some of these parameter changes may silently fail to apply.
  */
 media_status_t AMediaCodec_setParameters(
-        AMediaCodec *mData, const AMediaFormat* params);
+        AMediaCodec *mData, const AMediaFormat* params) __INTRODUCED_IN(26);
 
 /**
  * Signals end-of-stream on input. Equivalent to submitting an empty buffer with
@@ -346,23 +342,19 @@
  *
  * For more details, see the Java documentation for MediaCodec.signalEndOfInputStream.
  */
-media_status_t AMediaCodec_signalEndOfInputStream(AMediaCodec *mData);
-
-#endif /* __ANDROID_API__ >= 26 */
-
-#if __ANDROID_API__ >= 28
+media_status_t AMediaCodec_signalEndOfInputStream(AMediaCodec *mData) __INTRODUCED_IN(26);
 
 /**
  * Get the component name. If the codec was created by createDecoderByType
  * or createEncoderByType, what component is chosen is not known beforehand.
  * Caller shall call AMediaCodec_releaseName to free the returned pointer.
  */
-media_status_t AMediaCodec_getName(AMediaCodec*, char** out_name);
+media_status_t AMediaCodec_getName(AMediaCodec*, char** out_name) __INTRODUCED_IN(28);
 
 /**
  * Free the memory pointed by name which is returned by AMediaCodec_getName.
  */
-void AMediaCodec_releaseName(AMediaCodec*, char* name);
+void AMediaCodec_releaseName(AMediaCodec*, char* name) __INTRODUCED_IN(28);
 
 /**
  * Set an asynchronous callback for actionable AMediaCodec events.
@@ -386,34 +378,32 @@
 media_status_t AMediaCodec_setAsyncNotifyCallback(
         AMediaCodec*,
         AMediaCodecOnAsyncNotifyCallback callback,
-        void *userdata);
+        void *userdata) __INTRODUCED_IN(28);
 
 /**
  * Release the crypto if applicable.
  */
-media_status_t AMediaCodec_releaseCrypto(AMediaCodec*);
+media_status_t AMediaCodec_releaseCrypto(AMediaCodec*) __INTRODUCED_IN(28);
 
 /**
  * Call this after AMediaCodec_configure() returns successfully to get the input
  * format accepted by the codec. Do this to determine what optional configuration
  * parameters were supported by the codec.
  */
-AMediaFormat* AMediaCodec_getInputFormat(AMediaCodec*);
+AMediaFormat* AMediaCodec_getInputFormat(AMediaCodec*) __INTRODUCED_IN(28);
 
 /**
  * Returns true if the codec cannot proceed further, but can be recovered by stopping,
  * configuring, and starting again.
  */
-bool AMediaCodecActionCode_isRecoverable(int32_t actionCode);
+bool AMediaCodecActionCode_isRecoverable(int32_t actionCode) __INTRODUCED_IN(28);
 
 /**
  * Returns true if the codec error is a transient issue, perhaps due to
  * resource constraints, and that the method (or encoding/decoding) may be
  * retried at a later time.
  */
-bool AMediaCodecActionCode_isTransient(int32_t actionCode);
-
-#endif /* __ANDROID_API__ >= 28 */
+bool AMediaCodecActionCode_isTransient(int32_t actionCode) __INTRODUCED_IN(28);
 
 typedef enum {
     AMEDIACODECRYPTOINFO_MODE_CLEAR = 0,
@@ -447,53 +437,51 @@
         uint8_t iv[16],
         cryptoinfo_mode_t mode,
         size_t *clearbytes,
-        size_t *encryptedbytes);
+        size_t *encryptedbytes) __INTRODUCED_IN(21);
 
 /**
  * delete an AMediaCodecCryptoInfo created previously with AMediaCodecCryptoInfo_new, or
  * obtained from AMediaExtractor
  */
-media_status_t AMediaCodecCryptoInfo_delete(AMediaCodecCryptoInfo*);
+media_status_t AMediaCodecCryptoInfo_delete(AMediaCodecCryptoInfo*) __INTRODUCED_IN(21);
 
 /**
  * Set the crypto pattern on an AMediaCryptoInfo object
  */
 void AMediaCodecCryptoInfo_setPattern(
         AMediaCodecCryptoInfo *info,
-        cryptoinfo_pattern_t *pattern);
+        cryptoinfo_pattern_t *pattern) __INTRODUCED_IN(21);
 
 /**
  * The number of subsamples that make up the buffer's contents.
  */
-size_t AMediaCodecCryptoInfo_getNumSubSamples(AMediaCodecCryptoInfo*);
+size_t AMediaCodecCryptoInfo_getNumSubSamples(AMediaCodecCryptoInfo*) __INTRODUCED_IN(21);
 
 /**
  * A 16-byte opaque key
  */
-media_status_t AMediaCodecCryptoInfo_getKey(AMediaCodecCryptoInfo*, uint8_t *dst);
+media_status_t AMediaCodecCryptoInfo_getKey(AMediaCodecCryptoInfo*, uint8_t *dst) __INTRODUCED_IN(21);
 
 /**
  * A 16-byte initialization vector
  */
-media_status_t AMediaCodecCryptoInfo_getIV(AMediaCodecCryptoInfo*, uint8_t *dst);
+media_status_t AMediaCodecCryptoInfo_getIV(AMediaCodecCryptoInfo*, uint8_t *dst) __INTRODUCED_IN(21);
 
 /**
  * The type of encryption that has been applied,
  * one of AMEDIACODECRYPTOINFO_MODE_CLEAR or AMEDIACODECRYPTOINFO_MODE_AES_CTR.
  */
-cryptoinfo_mode_t AMediaCodecCryptoInfo_getMode(AMediaCodecCryptoInfo*);
+cryptoinfo_mode_t AMediaCodecCryptoInfo_getMode(AMediaCodecCryptoInfo*) __INTRODUCED_IN(21);
 
 /**
  * The number of leading unencrypted bytes in each subsample.
  */
-media_status_t AMediaCodecCryptoInfo_getClearBytes(AMediaCodecCryptoInfo*, size_t *dst);
+media_status_t AMediaCodecCryptoInfo_getClearBytes(AMediaCodecCryptoInfo*, size_t *dst) __INTRODUCED_IN(21);
 
 /**
  * The number of trailing encrypted bytes in each subsample.
  */
-media_status_t AMediaCodecCryptoInfo_getEncryptedBytes(AMediaCodecCryptoInfo*, size_t *dst);
-
-#endif /* __ANDROID_API__ >= 21 */
+media_status_t AMediaCodecCryptoInfo_getEncryptedBytes(AMediaCodecCryptoInfo*, size_t *dst) __INTRODUCED_IN(21);
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaCrypto.h b/media/ndk/include/media/NdkMediaCrypto.h
index 6f2926e..b673adc 100644
--- a/media/ndk/include/media/NdkMediaCrypto.h
+++ b/media/ndk/include/media/NdkMediaCrypto.h
@@ -47,17 +47,13 @@
 
 typedef uint8_t AMediaUUID[16];
 
-#if __ANDROID_API__ >= 21
+bool AMediaCrypto_isCryptoSchemeSupported(const AMediaUUID uuid) __INTRODUCED_IN(21);
 
-bool AMediaCrypto_isCryptoSchemeSupported(const AMediaUUID uuid);
+bool AMediaCrypto_requiresSecureDecoderComponent(const char *mime) __INTRODUCED_IN(21);
 
-bool AMediaCrypto_requiresSecureDecoderComponent(const char *mime);
+AMediaCrypto* AMediaCrypto_new(const AMediaUUID uuid, const void *initData, size_t initDataSize) __INTRODUCED_IN(21);
 
-AMediaCrypto* AMediaCrypto_new(const AMediaUUID uuid, const void *initData, size_t initDataSize);
-
-void AMediaCrypto_delete(AMediaCrypto* crypto);
-
-#endif /* __ANDROID_API__ >= 21 */
+void AMediaCrypto_delete(AMediaCrypto* crypto) __INTRODUCED_IN(21);
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaDataSource.h b/media/ndk/include/media/NdkMediaDataSource.h
index 9e2e351..3a4373c 100644
--- a/media/ndk/include/media/NdkMediaDataSource.h
+++ b/media/ndk/include/media/NdkMediaDataSource.h
@@ -38,8 +38,6 @@
 struct AMediaDataSource;
 typedef struct AMediaDataSource AMediaDataSource;
 
-#if __ANDROID_API__ >= 28
-
 /*
  * AMediaDataSource's callbacks will be invoked on an implementation-defined thread
  * or thread pool. No guarantees are provided about which thread(s) will be used for
@@ -84,19 +82,19 @@
  * Create new media data source. Returns NULL if memory allocation
  * for the new data source object fails.
  */
-AMediaDataSource* AMediaDataSource_new();
+AMediaDataSource* AMediaDataSource_new() __INTRODUCED_IN(28);
 
 /**
  * Delete a previously created media data source.
  */
-void AMediaDataSource_delete(AMediaDataSource*);
+void AMediaDataSource_delete(AMediaDataSource*) __INTRODUCED_IN(28);
 
 /**
  * Set an user provided opaque handle. This opaque handle is passed as
  * the first argument to the data source callbacks.
  */
 void AMediaDataSource_setUserdata(
-        AMediaDataSource*, void *userdata);
+        AMediaDataSource*, void *userdata) __INTRODUCED_IN(28);
 
 /**
  * Set a custom callback for supplying random access media data to the
@@ -111,7 +109,7 @@
  */
 void AMediaDataSource_setReadAt(
         AMediaDataSource*,
-        AMediaDataSourceReadAt);
+        AMediaDataSourceReadAt) __INTRODUCED_IN(28);
 
 /**
  * Set a custom callback for supplying the size of the data source to the
@@ -122,7 +120,7 @@
  */
 void AMediaDataSource_setGetSize(
         AMediaDataSource*,
-        AMediaDataSourceGetSize);
+        AMediaDataSourceGetSize) __INTRODUCED_IN(28);
 
 /**
  * Set a custom callback to receive signal from the NDK media framework
@@ -133,9 +131,7 @@
  */
 void AMediaDataSource_setClose(
         AMediaDataSource*,
-        AMediaDataSourceClose);
-
-#endif  /*__ANDROID_API__ >= 28 */
+        AMediaDataSourceClose) __INTRODUCED_IN(28);
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaDrm.h b/media/ndk/include/media/NdkMediaDrm.h
index d45dc20..24c0d6d 100644
--- a/media/ndk/include/media/NdkMediaDrm.h
+++ b/media/ndk/include/media/NdkMediaDrm.h
@@ -87,8 +87,6 @@
 typedef void (*AMediaDrmEventListener)(AMediaDrm *, const AMediaDrmSessionId *sessionId,
         AMediaDrmEventType eventType, int extra, const uint8_t *data, size_t dataSize);
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Query if the given scheme identified by its UUID is supported on this device, and
  * whether the drm plugin is able to handle the media container format specified by mimeType.
@@ -97,25 +95,27 @@
  * mimeType is the MIME type of the media container, e.g. "video/mp4".  If mimeType
  * is not known or required, it can be provided as NULL.
  */
-bool AMediaDrm_isCryptoSchemeSupported(const uint8_t *uuid, const char *mimeType);
+bool AMediaDrm_isCryptoSchemeSupported(const uint8_t *uuid,
+        const char *mimeType) __INTRODUCED_IN(21);
 
 /**
  * Create a MediaDrm instance from a UUID
  * uuid identifies the universal unique ID of the crypto scheme. uuid must be 16 bytes.
  */
-AMediaDrm* AMediaDrm_createByUUID(const uint8_t *uuid);
+AMediaDrm* AMediaDrm_createByUUID(const uint8_t *uuid) __INTRODUCED_IN(21);
 
 /**
  * Release a MediaDrm object
  */
-void AMediaDrm_release(AMediaDrm *);
+void AMediaDrm_release(AMediaDrm *) __INTRODUCED_IN(21);
 
 /**
  * Register a callback to be invoked when an event occurs
  *
  * listener is the callback that will be invoked on event
  */
-media_status_t AMediaDrm_setOnEventListener(AMediaDrm *, AMediaDrmEventListener listener);
+media_status_t AMediaDrm_setOnEventListener(AMediaDrm *,
+        AMediaDrmEventListener listener) __INTRODUCED_IN(21);
 
 /**
  * Open a new session with the MediaDrm object.  A session ID is returned.
@@ -123,13 +123,15 @@
  * returns MEDIADRM_NOT_PROVISIONED_ERROR if provisioning is needed
  * returns MEDIADRM_RESOURCE_BUSY_ERROR if required resources are in use
  */
-media_status_t AMediaDrm_openSession(AMediaDrm *, AMediaDrmSessionId *sessionId);
+media_status_t AMediaDrm_openSession(AMediaDrm *,
+        AMediaDrmSessionId *sessionId) __INTRODUCED_IN(21);
 
 /**
  * Close a session on the MediaDrm object that was previously opened
  * with AMediaDrm_openSession.
  */
-media_status_t AMediaDrm_closeSession(AMediaDrm *, const AMediaDrmSessionId *sessionId);
+media_status_t AMediaDrm_closeSession(AMediaDrm *,
+        const AMediaDrmSessionId *sessionId) __INTRODUCED_IN(21);
 
 typedef enum AMediaDrmKeyType {
     /**
@@ -208,7 +210,7 @@
 media_status_t AMediaDrm_getKeyRequest(AMediaDrm *, const AMediaDrmScope *scope,
         const uint8_t *init, size_t initSize, const char *mimeType, AMediaDrmKeyType keyType,
         const AMediaDrmKeyValue *optionalParameters, size_t numOptionalParameters,
-        const uint8_t **keyRequest, size_t *keyRequestSize);
+        const uint8_t **keyRequest, size_t *keyRequestSize) __INTRODUCED_IN(21);
 
 /**
  * A key response is received from the license server by the app, then it is
@@ -228,7 +230,8 @@
  */
 
 media_status_t AMediaDrm_provideKeyResponse(AMediaDrm *, const AMediaDrmScope *scope,
-        const uint8_t *response, size_t responseSize, AMediaDrmKeySetId *keySetId);
+        const uint8_t *response, size_t responseSize,
+        AMediaDrmKeySetId *keySetId) __INTRODUCED_IN(21);
 
 /**
  * Restore persisted offline keys into a new session.  keySetId identifies the
@@ -238,14 +241,15 @@
  * keySetId identifies the saved key set to restore
  */
 media_status_t AMediaDrm_restoreKeys(AMediaDrm *, const AMediaDrmSessionId *sessionId,
-        const AMediaDrmKeySetId *keySetId);
+        const AMediaDrmKeySetId *keySetId) __INTRODUCED_IN(21);
 
 /**
  * Remove the current keys from a session.
  *
  * keySetId identifies keys to remove
  */
-media_status_t AMediaDrm_removeKeys(AMediaDrm *, const AMediaDrmSessionId *keySetId);
+media_status_t AMediaDrm_removeKeys(AMediaDrm *,
+        const AMediaDrmSessionId *keySetId) __INTRODUCED_IN(21);
 
 /**
  * Request an informative description of the key status for the session.  The status is
@@ -261,7 +265,7 @@
  * and numPairs will be set to the number of pairs available.
  */
 media_status_t AMediaDrm_queryKeyStatus(AMediaDrm *, const AMediaDrmSessionId *sessionId,
-        AMediaDrmKeyValue *keyValuePairs, size_t *numPairs);
+        AMediaDrmKeyValue *keyValuePairs, size_t *numPairs) __INTRODUCED_IN(21);
 
 
 /**
@@ -280,7 +284,7 @@
  *       the next call to getProvisionRequest.
  */
 media_status_t AMediaDrm_getProvisionRequest(AMediaDrm *, const uint8_t **provisionRequest,
-        size_t *provisionRequestSize, const char **serverUrl);
+        size_t *provisionRequestSize, const char **serverUrl) __INTRODUCED_IN(21);
 
 
 /**
@@ -295,7 +299,7 @@
  * server rejected the request
  */
 media_status_t AMediaDrm_provideProvisionResponse(AMediaDrm *,
-        const uint8_t *response, size_t responseSize);
+        const uint8_t *response, size_t responseSize) __INTRODUCED_IN(21);
 
 
 /**
@@ -320,7 +324,7 @@
  * number required.
  */
 media_status_t AMediaDrm_getSecureStops(AMediaDrm *,
-        AMediaDrmSecureStop *secureStops, size_t *numSecureStops);
+        AMediaDrmSecureStop *secureStops, size_t *numSecureStops) __INTRODUCED_IN(21);
 
 /**
  * Process the SecureStop server response message ssRelease.  After authenticating
@@ -329,7 +333,7 @@
  * ssRelease is the server response indicating which secure stops to release
  */
 media_status_t AMediaDrm_releaseSecureStops(AMediaDrm *,
-        const AMediaDrmSecureStop *ssRelease);
+        const AMediaDrmSecureStop *ssRelease) __INTRODUCED_IN(21);
 
 /**
  * String property name: identifies the maker of the DRM engine plugin
@@ -362,7 +366,7 @@
  * will remain valid until the next call to AMediaDrm_getPropertyString.
  */
 media_status_t AMediaDrm_getPropertyString(AMediaDrm *, const char *propertyName,
-        const char **propertyValue);
+        const char **propertyValue) __INTRODUCED_IN(21);
 
 /**
  * Byte array property name: the device unique identifier is established during
@@ -377,19 +381,19 @@
  * will remain valid until the next call to AMediaDrm_getPropertyByteArray.
  */
 media_status_t AMediaDrm_getPropertyByteArray(AMediaDrm *, const char *propertyName,
-        AMediaDrmByteArray *propertyValue);
+        AMediaDrmByteArray *propertyValue) __INTRODUCED_IN(21);
 
 /**
  * Set a DRM engine plugin String property value.
  */
 media_status_t AMediaDrm_setPropertyString(AMediaDrm *, const char *propertyName,
-        const char *value);
+        const char *value) __INTRODUCED_IN(21);
 
 /**
  * Set a DRM engine plugin byte array property value.
  */
 media_status_t AMediaDrm_setPropertyByteArray(AMediaDrm *, const char *propertyName,
-        const uint8_t *value, size_t valueSize);
+        const uint8_t *value, size_t valueSize) __INTRODUCED_IN(21);
 
 /**
  * In addition to supporting decryption of DASH Common Encrypted Media, the
@@ -418,7 +422,7 @@
  */
 media_status_t AMediaDrm_encrypt(AMediaDrm *, const AMediaDrmSessionId *sessionId,
         const char *cipherAlgorithm, uint8_t *keyId, uint8_t *iv,
-        const uint8_t *input, uint8_t *output, size_t dataSize);
+        const uint8_t *input, uint8_t *output, size_t dataSize) __INTRODUCED_IN(21);
 
 /*
  * Decrypt the data referenced by input of length dataSize using algorithm specified
@@ -429,7 +433,7 @@
  */
 media_status_t AMediaDrm_decrypt(AMediaDrm *, const AMediaDrmSessionId *sessionId,
         const char *cipherAlgorithm, uint8_t *keyId, uint8_t *iv,
-        const uint8_t *input, uint8_t *output, size_t dataSize);
+        const uint8_t *input, uint8_t *output, size_t dataSize) __INTRODUCED_IN(21);
 
 /*
  * Generate a signature using the specified macAlgorithm over the message data
@@ -442,7 +446,7 @@
  */
 media_status_t AMediaDrm_sign(AMediaDrm *, const AMediaDrmSessionId *sessionId,
         const char *macAlgorithm, uint8_t *keyId, uint8_t *message, size_t messageSize,
-        uint8_t *signature, size_t *signatureSize);
+        uint8_t *signature, size_t *signatureSize) __INTRODUCED_IN(21);
 
 /*
  * Perform a signature verification using the specified macAlgorithm over the message
@@ -453,9 +457,7 @@
  */
 media_status_t AMediaDrm_verify(AMediaDrm *, const AMediaDrmSessionId *sessionId,
         const char *macAlgorithm, uint8_t *keyId, const uint8_t *message, size_t messageSize,
-        const uint8_t *signature, size_t signatureSize);
-
-#endif /* __ANDROID_API__ >= 21 */
+        const uint8_t *signature, size_t signatureSize) __INTRODUCED_IN(21);
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaExtractor.h b/media/ndk/include/media/NdkMediaExtractor.h
index 3452cc9..9f60891 100644
--- a/media/ndk/include/media/NdkMediaExtractor.h
+++ b/media/ndk/include/media/NdkMediaExtractor.h
@@ -49,48 +49,44 @@
 struct AMediaExtractor;
 typedef struct AMediaExtractor AMediaExtractor;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Create new media extractor
  */
-AMediaExtractor* AMediaExtractor_new();
+AMediaExtractor* AMediaExtractor_new() __INTRODUCED_IN(21);
 
 /**
  * Delete a previously created media extractor
  */
-media_status_t AMediaExtractor_delete(AMediaExtractor*);
+media_status_t AMediaExtractor_delete(AMediaExtractor*) __INTRODUCED_IN(21);
 
 /**
  *  Set the file descriptor from which the extractor will read.
  */
 media_status_t AMediaExtractor_setDataSourceFd(AMediaExtractor*, int fd, off64_t offset,
-        off64_t length);
+        off64_t length) __INTRODUCED_IN(21);
 
 /**
  * Set the URI from which the extractor will read.
  */
-media_status_t AMediaExtractor_setDataSource(AMediaExtractor*, const char *location);
+media_status_t AMediaExtractor_setDataSource(AMediaExtractor*,
+        const char *location) __INTRODUCED_IN(21);
         // TODO support headers
 
-#if __ANDROID_API__ >= 28
-
 /**
  * Set the custom data source implementation from which the extractor will read.
  */
-media_status_t AMediaExtractor_setDataSourceCustom(AMediaExtractor*, AMediaDataSource *src);
-
-#endif /* __ANDROID_API__ >= 28 */
+media_status_t AMediaExtractor_setDataSourceCustom(AMediaExtractor*,
+        AMediaDataSource *src) __INTRODUCED_IN(28);
 
 /**
  * Return the number of tracks in the previously specified media file
  */
-size_t AMediaExtractor_getTrackCount(AMediaExtractor*);
+size_t AMediaExtractor_getTrackCount(AMediaExtractor*) __INTRODUCED_IN(21);
 
 /**
  * Return the format of the specified track. The caller must free the returned format
  */
-AMediaFormat* AMediaExtractor_getTrackFormat(AMediaExtractor*, size_t idx);
+AMediaFormat* AMediaExtractor_getTrackFormat(AMediaExtractor*, size_t idx) __INTRODUCED_IN(21);
 
 /**
  * Select the specified track. Subsequent calls to readSampleData, getSampleTrackIndex and
@@ -98,41 +94,42 @@
  * Selecting the same track multiple times has no effect, the track is
  * only selected once.
  */
-media_status_t AMediaExtractor_selectTrack(AMediaExtractor*, size_t idx);
+media_status_t AMediaExtractor_selectTrack(AMediaExtractor*, size_t idx) __INTRODUCED_IN(21);
 
 /**
  * Unselect the specified track. Subsequent calls to readSampleData, getSampleTrackIndex and
  * getSampleTime only retrieve information for the subset of tracks selected..
  */
-media_status_t AMediaExtractor_unselectTrack(AMediaExtractor*, size_t idx);
+media_status_t AMediaExtractor_unselectTrack(AMediaExtractor*, size_t idx) __INTRODUCED_IN(21);
 
 /**
  * Read the current sample.
  */
-ssize_t AMediaExtractor_readSampleData(AMediaExtractor*, uint8_t *buffer, size_t capacity);
+ssize_t AMediaExtractor_readSampleData(AMediaExtractor*,
+        uint8_t *buffer, size_t capacity) __INTRODUCED_IN(21);
 
 /**
  * Read the current sample's flags.
  */
-uint32_t AMediaExtractor_getSampleFlags(AMediaExtractor*); // see definitions below
+uint32_t AMediaExtractor_getSampleFlags(AMediaExtractor*) __INTRODUCED_IN(21);
 
 /**
  * Returns the track index the current sample originates from (or -1
  * if no more samples are available)
  */
-int AMediaExtractor_getSampleTrackIndex(AMediaExtractor*);
+int AMediaExtractor_getSampleTrackIndex(AMediaExtractor*) __INTRODUCED_IN(21);
 
 /**
  * Returns the current sample's presentation time in microseconds.
  * or -1 if no more samples are available.
  */
-int64_t AMediaExtractor_getSampleTime(AMediaExtractor*);
+int64_t AMediaExtractor_getSampleTime(AMediaExtractor*) __INTRODUCED_IN(21);
 
 /**
  * Advance to the next sample. Returns false if no more sample data
  * is available (end of stream).
  */
-bool AMediaExtractor_advance(AMediaExtractor*);
+bool AMediaExtractor_advance(AMediaExtractor*) __INTRODUCED_IN(21);
 
 typedef enum {
     AMEDIAEXTRACTOR_SEEK_PREVIOUS_SYNC,
@@ -143,7 +140,8 @@
 /**
  *
  */
-media_status_t AMediaExtractor_seekTo(AMediaExtractor*, int64_t seekPosUs, SeekMode mode);
+media_status_t AMediaExtractor_seekTo(AMediaExtractor*,
+        int64_t seekPosUs, SeekMode mode) __INTRODUCED_IN(21);
 
 /**
  * mapping of crypto scheme uuid to the scheme specific data for that scheme
@@ -165,18 +163,16 @@
 /**
  * Get the PSSH info if present.
  */
-PsshInfo* AMediaExtractor_getPsshInfo(AMediaExtractor*);
+PsshInfo* AMediaExtractor_getPsshInfo(AMediaExtractor*) __INTRODUCED_IN(21);
 
 
-AMediaCodecCryptoInfo *AMediaExtractor_getSampleCryptoInfo(AMediaExtractor *);
+AMediaCodecCryptoInfo *AMediaExtractor_getSampleCryptoInfo(AMediaExtractor *) __INTRODUCED_IN(21);
 
 enum {
     AMEDIAEXTRACTOR_SAMPLE_FLAG_SYNC = 1,
     AMEDIAEXTRACTOR_SAMPLE_FLAG_ENCRYPTED = 2,
 };
 
-#if __ANDROID_API__ >= 28
-
 /**
  * Returns the format of the extractor. The caller must free the returned format
  * using AMediaFormat_delete(format).
@@ -184,7 +180,7 @@
  * This function will always return a format; however, the format could be empty
  * (no key-value pairs) if the media container does not provide format information.
  */
-AMediaFormat* AMediaExtractor_getFileFormat(AMediaExtractor*);
+AMediaFormat* AMediaExtractor_getFileFormat(AMediaExtractor*) __INTRODUCED_IN(28);
 
 /**
  * Returns the size of the current sample in bytes, or -1 when no samples are
@@ -196,7 +192,7 @@
  * AMediaExtractor_readSampleData(ex, buf, sampleSize);
  *
  */
-ssize_t AMediaExtractor_getSampleSize(AMediaExtractor*);
+ssize_t AMediaExtractor_getSampleSize(AMediaExtractor*) __INTRODUCED_IN(28);
 
 /**
  * Returns the duration of cached media samples downloaded from a network data source
@@ -209,7 +205,7 @@
  * cached duration cannot be calculated (bitrate, duration, and file size information
  * not available).
  */
-int64_t AMediaExtractor_getCachedDuration(AMediaExtractor *);
+int64_t AMediaExtractor_getCachedDuration(AMediaExtractor *) __INTRODUCED_IN(28);
 
 /**
  * Read the current sample's metadata format into |fmt|. Examples of sample metadata are
@@ -220,11 +216,8 @@
  * Existing key-value pairs in |fmt| would be removed if this API returns AMEDIA_OK.
  * The contents of |fmt| is undefined if this API returns AMEDIA_ERROR_*.
  */
-media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex, AMediaFormat *fmt);
-
-#endif /* __ANDROID_API__ >= 28 */
-
-#endif /* __ANDROID_API__ >= 21 */
+media_status_t AMediaExtractor_getSampleFormat(AMediaExtractor *ex,
+        AMediaFormat *fmt) __INTRODUCED_IN(28);
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaFormat.h b/media/ndk/include/media/NdkMediaFormat.h
index f510dff..8f37f7b 100644
--- a/media/ndk/include/media/NdkMediaFormat.h
+++ b/media/ndk/include/media/NdkMediaFormat.h
@@ -46,129 +46,123 @@
 struct AMediaFormat;
 typedef struct AMediaFormat AMediaFormat;
 
-#if __ANDROID_API__ >= 21
-
-AMediaFormat *AMediaFormat_new();
-media_status_t AMediaFormat_delete(AMediaFormat*);
+AMediaFormat *AMediaFormat_new() __INTRODUCED_IN(21);
+media_status_t AMediaFormat_delete(AMediaFormat*) __INTRODUCED_IN(21);
 
 /**
  * Human readable representation of the format. The returned string is owned by the format,
  * and remains valid until the next call to toString, or until the format is deleted.
  */
-const char* AMediaFormat_toString(AMediaFormat*);
+const char* AMediaFormat_toString(AMediaFormat*) __INTRODUCED_IN(21);
 
-bool AMediaFormat_getInt32(AMediaFormat*, const char *name, int32_t *out);
-bool AMediaFormat_getInt64(AMediaFormat*, const char *name, int64_t *out);
-bool AMediaFormat_getFloat(AMediaFormat*, const char *name, float *out);
-bool AMediaFormat_getSize(AMediaFormat*, const char *name, size_t *out);
+bool AMediaFormat_getInt32(AMediaFormat*, const char *name, int32_t *out) __INTRODUCED_IN(21);
+bool AMediaFormat_getInt64(AMediaFormat*, const char *name, int64_t *out) __INTRODUCED_IN(21);
+bool AMediaFormat_getFloat(AMediaFormat*, const char *name, float *out) __INTRODUCED_IN(21);
+bool AMediaFormat_getSize(AMediaFormat*, const char *name, size_t *out) __INTRODUCED_IN(21);
 /**
  * The returned data is owned by the format and remains valid as long as the named entry
  * is part of the format.
  */
-bool AMediaFormat_getBuffer(AMediaFormat*, const char *name, void** data, size_t *size);
+bool AMediaFormat_getBuffer(AMediaFormat*, const char *name, void** data, size_t *size) __INTRODUCED_IN(21);
 /**
  * The returned string is owned by the format, and remains valid until the next call to getString,
  * or until the format is deleted.
  */
-bool AMediaFormat_getString(AMediaFormat*, const char *name, const char **out);
+bool AMediaFormat_getString(AMediaFormat*, const char *name, const char **out) __INTRODUCED_IN(21);
 
 
-void AMediaFormat_setInt32(AMediaFormat*, const char* name, int32_t value);
-void AMediaFormat_setInt64(AMediaFormat*, const char* name, int64_t value);
-void AMediaFormat_setFloat(AMediaFormat*, const char* name, float value);
+void AMediaFormat_setInt32(AMediaFormat*, const char* name, int32_t value) __INTRODUCED_IN(21);
+void AMediaFormat_setInt64(AMediaFormat*, const char* name, int64_t value) __INTRODUCED_IN(21);
+void AMediaFormat_setFloat(AMediaFormat*, const char* name, float value) __INTRODUCED_IN(21);
 /**
  * The provided string is copied into the format.
  */
-void AMediaFormat_setString(AMediaFormat*, const char* name, const char* value);
+void AMediaFormat_setString(AMediaFormat*, const char* name, const char* value) __INTRODUCED_IN(21);
 /**
  * The provided data is copied into the format.
  */
-void AMediaFormat_setBuffer(AMediaFormat*, const char* name, void* data, size_t size);
+void AMediaFormat_setBuffer(AMediaFormat*, const char* name, void* data, size_t size) __INTRODUCED_IN(21);
 
 
 
 /**
  * XXX should these be ints/enums that we look up in a table as needed?
  */
-extern const char* AMEDIAFORMAT_KEY_AAC_DRC_ATTENUATION_FACTOR;
-extern const char* AMEDIAFORMAT_KEY_AAC_DRC_BOOST_FACTOR;
-extern const char* AMEDIAFORMAT_KEY_AAC_DRC_HEAVY_COMPRESSION;
-extern const char* AMEDIAFORMAT_KEY_AAC_DRC_TARGET_REFERENCE_LEVEL;
-extern const char* AMEDIAFORMAT_KEY_AAC_ENCODED_TARGET_LEVEL;
-extern const char* AMEDIAFORMAT_KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT;
-extern const char* AMEDIAFORMAT_KEY_AAC_PROFILE;
-extern const char* AMEDIAFORMAT_KEY_AAC_SBR_MODE;
-extern const char* AMEDIAFORMAT_KEY_AUDIO_SESSION_ID;
-extern const char* AMEDIAFORMAT_KEY_BITRATE_MODE;
-extern const char* AMEDIAFORMAT_KEY_BIT_RATE;
-extern const char* AMEDIAFORMAT_KEY_CAPTURE_RATE;
-extern const char* AMEDIAFORMAT_KEY_CHANNEL_COUNT;
-extern const char* AMEDIAFORMAT_KEY_CHANNEL_MASK;
-extern const char* AMEDIAFORMAT_KEY_COLOR_FORMAT;
-extern const char* AMEDIAFORMAT_KEY_COLOR_RANGE;
-extern const char* AMEDIAFORMAT_KEY_COLOR_STANDARD;
-extern const char* AMEDIAFORMAT_KEY_COLOR_TRANSFER;
-extern const char* AMEDIAFORMAT_KEY_COMPLEXITY;
-extern const char* AMEDIAFORMAT_KEY_CSD;
-extern const char* AMEDIAFORMAT_KEY_CSD_0;
-extern const char* AMEDIAFORMAT_KEY_CSD_1;
-extern const char* AMEDIAFORMAT_KEY_CSD_2;
-extern const char* AMEDIAFORMAT_KEY_DISPLAY_CROP;
-extern const char* AMEDIAFORMAT_KEY_DISPLAY_HEIGHT;
-extern const char* AMEDIAFORMAT_KEY_DISPLAY_WIDTH;
-extern const char* AMEDIAFORMAT_KEY_DURATION;
-extern const char* AMEDIAFORMAT_KEY_FLAC_COMPRESSION_LEVEL;
-extern const char* AMEDIAFORMAT_KEY_FRAME_RATE;
-extern const char* AMEDIAFORMAT_KEY_GRID_COLUMNS;
-extern const char* AMEDIAFORMAT_KEY_GRID_ROWS;
-extern const char* AMEDIAFORMAT_KEY_HDR_STATIC_INFO;
-extern const char* AMEDIAFORMAT_KEY_HEIGHT;
-extern const char* AMEDIAFORMAT_KEY_INTRA_REFRESH_PERIOD;
-extern const char* AMEDIAFORMAT_KEY_IS_ADTS;
-extern const char* AMEDIAFORMAT_KEY_IS_AUTOSELECT;
-extern const char* AMEDIAFORMAT_KEY_IS_DEFAULT;
-extern const char* AMEDIAFORMAT_KEY_IS_FORCED_SUBTITLE;
-extern const char* AMEDIAFORMAT_KEY_I_FRAME_INTERVAL;
-extern const char* AMEDIAFORMAT_KEY_LANGUAGE;
-extern const char* AMEDIAFORMAT_KEY_LATENCY;
-extern const char* AMEDIAFORMAT_KEY_LEVEL;
-extern const char* AMEDIAFORMAT_KEY_MAX_HEIGHT;
-extern const char* AMEDIAFORMAT_KEY_MAX_INPUT_SIZE;
-extern const char* AMEDIAFORMAT_KEY_MAX_WIDTH;
-extern const char* AMEDIAFORMAT_KEY_MIME;
-extern const char* AMEDIAFORMAT_KEY_MPEG_USER_DATA;
-extern const char* AMEDIAFORMAT_KEY_OPERATING_RATE;
-extern const char* AMEDIAFORMAT_KEY_PCM_ENCODING;
-extern const char* AMEDIAFORMAT_KEY_PRIORITY;
-extern const char* AMEDIAFORMAT_KEY_PROFILE;
-extern const char* AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP;
-extern const char* AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER;
-extern const char* AMEDIAFORMAT_KEY_ROTATION;
-extern const char* AMEDIAFORMAT_KEY_SAMPLE_RATE;
-extern const char* AMEDIAFORMAT_KEY_SEI;
-extern const char* AMEDIAFORMAT_KEY_SLICE_HEIGHT;
-extern const char* AMEDIAFORMAT_KEY_STRIDE;
-extern const char* AMEDIAFORMAT_KEY_TEMPORAL_LAYER_ID;
-extern const char* AMEDIAFORMAT_KEY_TEMPORAL_LAYERING;
-extern const char* AMEDIAFORMAT_KEY_TILE_HEIGHT;
-extern const char* AMEDIAFORMAT_KEY_TILE_WIDTH;
-extern const char* AMEDIAFORMAT_KEY_TIME_US;
-extern const char* AMEDIAFORMAT_KEY_TRACK_ID;
-extern const char* AMEDIAFORMAT_KEY_TRACK_INDEX;
-extern const char* AMEDIAFORMAT_KEY_WIDTH;
+extern const char* AMEDIAFORMAT_KEY_AAC_DRC_ATTENUATION_FACTOR __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_AAC_DRC_BOOST_FACTOR __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_AAC_DRC_HEAVY_COMPRESSION __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_AAC_DRC_TARGET_REFERENCE_LEVEL __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_AAC_ENCODED_TARGET_LEVEL __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_AAC_PROFILE __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_AAC_SBR_MODE __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_AUDIO_SESSION_ID __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_BITRATE_MODE __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_BIT_RATE __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_CAPTURE_RATE __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_CHANNEL_COUNT __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_CHANNEL_MASK __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_COLOR_FORMAT __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_COLOR_RANGE __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_COLOR_STANDARD __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_COLOR_TRANSFER __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_COMPLEXITY __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_CSD __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_CSD_0 __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_CSD_1 __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_CSD_2 __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_DISPLAY_CROP __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_DISPLAY_HEIGHT __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_DISPLAY_WIDTH __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_DURATION __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_FLAC_COMPRESSION_LEVEL __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_FRAME_RATE __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_GRID_COLUMNS __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_GRID_ROWS __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_HDR_STATIC_INFO __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_HEIGHT __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_INTRA_REFRESH_PERIOD __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_IS_ADTS __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_IS_AUTOSELECT __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_IS_DEFAULT __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_IS_FORCED_SUBTITLE __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_I_FRAME_INTERVAL __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_LANGUAGE __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_LATENCY __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_LEVEL __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_MAX_HEIGHT __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_MAX_INPUT_SIZE __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_MAX_WIDTH __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_MIME __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_MPEG_USER_DATA __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_OPERATING_RATE __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_PCM_ENCODING __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_PRIORITY __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_PROFILE __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_ROTATION __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_SAMPLE_RATE __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_SEI __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_SLICE_HEIGHT __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_STRIDE __INTRODUCED_IN(21);
+extern const char* AMEDIAFORMAT_KEY_TEMPORAL_LAYER_ID __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_TEMPORAL_LAYERING __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_TILE_HEIGHT __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_TILE_WIDTH __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_TIME_US __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_TRACK_ID __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_TRACK_INDEX __INTRODUCED_IN(28);
+extern const char* AMEDIAFORMAT_KEY_WIDTH __INTRODUCED_IN(21);
 
-#endif /* __ANDROID_API__ >= 21 */
-
-#if __ANDROID_API__ >= 28
-bool AMediaFormat_getDouble(AMediaFormat*, const char *name, double *out);
+bool AMediaFormat_getDouble(AMediaFormat*, const char *name, double *out) __INTRODUCED_IN(28);
 bool AMediaFormat_getRect(AMediaFormat*, const char *name,
-                          int32_t *left, int32_t *top, int32_t *right, int32_t *bottom);
+        int32_t *left, int32_t *top, int32_t *right, int32_t *bottom) __INTRODUCED_IN(28);
 
-void AMediaFormat_setDouble(AMediaFormat*, const char* name, double value);
-void AMediaFormat_setSize(AMediaFormat*, const char* name, size_t value);
+void AMediaFormat_setDouble(AMediaFormat*, const char* name, double value) __INTRODUCED_IN(28);
+void AMediaFormat_setSize(AMediaFormat*, const char* name, size_t value) __INTRODUCED_IN(28);
 void AMediaFormat_setRect(AMediaFormat*, const char* name,
-                          int32_t left, int32_t top, int32_t right, int32_t bottom);
-#endif /* __ANDROID_API__ >= 28 */
+        int32_t left, int32_t top, int32_t right, int32_t bottom) __INTRODUCED_IN(28);
 
 __END_DECLS
 
diff --git a/media/ndk/include/media/NdkMediaMuxer.h b/media/ndk/include/media/NdkMediaMuxer.h
index dc9e0ac..75c70ed 100644
--- a/media/ndk/include/media/NdkMediaMuxer.h
+++ b/media/ndk/include/media/NdkMediaMuxer.h
@@ -53,17 +53,15 @@
     AMEDIAMUXER_OUTPUT_FORMAT_WEBM   = 1,
 } OutputFormat;
 
-#if __ANDROID_API__ >= 21
-
 /**
  * Create new media muxer
  */
-AMediaMuxer* AMediaMuxer_new(int fd, OutputFormat format);
+AMediaMuxer* AMediaMuxer_new(int fd, OutputFormat format) __INTRODUCED_IN(21);
 
 /**
  * Delete a previously created media muxer
  */
-media_status_t AMediaMuxer_delete(AMediaMuxer*);
+media_status_t AMediaMuxer_delete(AMediaMuxer*) __INTRODUCED_IN(21);
 
 /**
  * Set and store the geodata (latitude and longitude) in the output file.
@@ -76,7 +74,8 @@
  * Latitude must be in the range [-90, 90].
  * Longitude must be in the range [-180, 180].
  */
-media_status_t AMediaMuxer_setLocation(AMediaMuxer*, float latitude, float longitude);
+media_status_t AMediaMuxer_setLocation(AMediaMuxer*,
+        float latitude, float longitude) __INTRODUCED_IN(21);
 
 /**
  * Sets the orientation hint for output video playback.
@@ -90,26 +89,26 @@
  * The angle is specified in degrees, clockwise.
  * The supported angles are 0, 90, 180, and 270 degrees.
  */
-media_status_t AMediaMuxer_setOrientationHint(AMediaMuxer*, int degrees);
+media_status_t AMediaMuxer_setOrientationHint(AMediaMuxer*, int degrees) __INTRODUCED_IN(21);
 
 /**
  * Adds a track with the specified format.
  * Returns the index of the new track or a negative value in case of failure,
  * which can be interpreted as a media_status_t.
  */
-ssize_t AMediaMuxer_addTrack(AMediaMuxer*, const AMediaFormat* format);
+ssize_t AMediaMuxer_addTrack(AMediaMuxer*, const AMediaFormat* format) __INTRODUCED_IN(21);
 
 /**
  * Start the muxer. Should be called after AMediaMuxer_addTrack and
  * before AMediaMuxer_writeSampleData.
  */
-media_status_t AMediaMuxer_start(AMediaMuxer*);
+media_status_t AMediaMuxer_start(AMediaMuxer*) __INTRODUCED_IN(21);
 
 /**
  * Stops the muxer.
  * Once the muxer stops, it can not be restarted.
  */
-media_status_t AMediaMuxer_stop(AMediaMuxer*);
+media_status_t AMediaMuxer_stop(AMediaMuxer*) __INTRODUCED_IN(21);
 
 /**
  * Writes an encoded sample into the muxer.
@@ -119,9 +118,8 @@
  * by the encoder.)
  */
 media_status_t AMediaMuxer_writeSampleData(AMediaMuxer *muxer,
-        size_t trackIdx, const uint8_t *data, const AMediaCodecBufferInfo *info);
-
-#endif /* __ANDROID_API__ >= 21 */
+        size_t trackIdx, const uint8_t *data,
+        const AMediaCodecBufferInfo *info) __INTRODUCED_IN(21);
 
 __END_DECLS
 
diff --git a/media/ndk/libmediandk.map.txt b/media/ndk/libmediandk.map.txt
index fb56694..d828d6a 100644
--- a/media/ndk/libmediandk.map.txt
+++ b/media/ndk/libmediandk.map.txt
@@ -32,55 +32,66 @@
     AMEDIAFORMAT_KEY_AAC_DRC_TARGET_REFERENCE_LEVEL; # var introduced=28
     AMEDIAFORMAT_KEY_AAC_ENCODED_TARGET_LEVEL; # var introduced=28
     AMEDIAFORMAT_KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT; # var introduced=28
-    AMEDIAFORMAT_KEY_AAC_PROFILE; # var
+    AMEDIAFORMAT_KEY_AAC_PROFILE; # var introduced=21
     AMEDIAFORMAT_KEY_AAC_SBR_MODE; # var introduced=28
     AMEDIAFORMAT_KEY_AUDIO_SESSION_ID; # var introduced=28
     AMEDIAFORMAT_KEY_BITRATE_MODE; # var introduced=28
-    AMEDIAFORMAT_KEY_BIT_RATE; # var
+    AMEDIAFORMAT_KEY_BIT_RATE; # var introduced=21
     AMEDIAFORMAT_KEY_CAPTURE_RATE; # var introduced=28
-    AMEDIAFORMAT_KEY_CHANNEL_COUNT; # var
-    AMEDIAFORMAT_KEY_CHANNEL_MASK; # var
-    AMEDIAFORMAT_KEY_COLOR_FORMAT; # var
+    AMEDIAFORMAT_KEY_CHANNEL_COUNT; # var introduced=21
+    AMEDIAFORMAT_KEY_CHANNEL_MASK; # var introduced=21
+    AMEDIAFORMAT_KEY_COLOR_FORMAT; # var introduced=21
     AMEDIAFORMAT_KEY_COLOR_RANGE; # var introduced=28
     AMEDIAFORMAT_KEY_COLOR_STANDARD; # var introduced=28
     AMEDIAFORMAT_KEY_COLOR_TRANSFER; # var introduced=28
     AMEDIAFORMAT_KEY_COMPLEXITY; # var introduced=28
+    AMEDIAFORMAT_KEY_CSD; # var introduced=28
+    AMEDIAFORMAT_KEY_CSD_0; # var introduced=28
+    AMEDIAFORMAT_KEY_CSD_1; # var introduced=28
+    AMEDIAFORMAT_KEY_CSD_2; # var introduced=28
     AMEDIAFORMAT_KEY_DISPLAY_CROP; # var introduced=28
-    AMEDIAFORMAT_KEY_DURATION; # var
-    AMEDIAFORMAT_KEY_FLAC_COMPRESSION_LEVEL; # var
-    AMEDIAFORMAT_KEY_FRAME_RATE; # var
+    AMEDIAFORMAT_KEY_DISPLAY_HEIGHT; # var introduced=28
+    AMEDIAFORMAT_KEY_DISPLAY_WIDTH; # var introduced=28
+    AMEDIAFORMAT_KEY_DURATION; # var introduced=21
+    AMEDIAFORMAT_KEY_FLAC_COMPRESSION_LEVEL; # var introduced=21
+    AMEDIAFORMAT_KEY_FRAME_RATE; # var introduced=21
     AMEDIAFORMAT_KEY_GRID_COLUMNS; # var introduced=28
     AMEDIAFORMAT_KEY_GRID_ROWS; # var introduced=28
     AMEDIAFORMAT_KEY_HDR_STATIC_INFO; # var introduced=28
-    AMEDIAFORMAT_KEY_HEIGHT; # var
+    AMEDIAFORMAT_KEY_HEIGHT; # var introduced=21
     AMEDIAFORMAT_KEY_INTRA_REFRESH_PERIOD; # var introduced=28
-    AMEDIAFORMAT_KEY_IS_ADTS; # var
-    AMEDIAFORMAT_KEY_IS_AUTOSELECT; # var
-    AMEDIAFORMAT_KEY_IS_DEFAULT; # var
-    AMEDIAFORMAT_KEY_IS_FORCED_SUBTITLE; # var
-    AMEDIAFORMAT_KEY_I_FRAME_INTERVAL; # var
-    AMEDIAFORMAT_KEY_LANGUAGE; # var
+    AMEDIAFORMAT_KEY_IS_ADTS; # var introduced=21
+    AMEDIAFORMAT_KEY_IS_AUTOSELECT; # var introduced=21
+    AMEDIAFORMAT_KEY_IS_DEFAULT; # var introduced=21
+    AMEDIAFORMAT_KEY_IS_FORCED_SUBTITLE; # var introduced=21
+    AMEDIAFORMAT_KEY_I_FRAME_INTERVAL; # var introduced=21
+    AMEDIAFORMAT_KEY_LANGUAGE; # var introduced=21
     AMEDIAFORMAT_KEY_LATENCY; # var introduced=28
     AMEDIAFORMAT_KEY_LEVEL; # var introduced=28
-    AMEDIAFORMAT_KEY_MAX_HEIGHT; # var
-    AMEDIAFORMAT_KEY_MAX_INPUT_SIZE; # var
-    AMEDIAFORMAT_KEY_MAX_WIDTH; # var
-    AMEDIAFORMAT_KEY_MIME; # var
+    AMEDIAFORMAT_KEY_MAX_HEIGHT; # var introduced=21
+    AMEDIAFORMAT_KEY_MAX_INPUT_SIZE; # var introduced=21
+    AMEDIAFORMAT_KEY_MAX_WIDTH; # var introduced=21
+    AMEDIAFORMAT_KEY_MIME; # var introduced=21
+    AMEDIAFORMAT_KEY_MPEG_USER_DATA; # var introduced=28
     AMEDIAFORMAT_KEY_OPERATING_RATE; # var introduced=28
     AMEDIAFORMAT_KEY_PCM_ENCODING; # var introduced=28
     AMEDIAFORMAT_KEY_PRIORITY; # var introduced=28
     AMEDIAFORMAT_KEY_PROFILE; # var introduced=28
-    AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP; # var
-    AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER; # var
+    AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP; # var introduced=21
+    AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER; # var introduced=21
     AMEDIAFORMAT_KEY_ROTATION; # var introduced=28
-    AMEDIAFORMAT_KEY_SAMPLE_RATE; # var
+    AMEDIAFORMAT_KEY_SAMPLE_RATE; # var introduced=21
+    AMEDIAFORMAT_KEY_SEI; # var introduced=28
     AMEDIAFORMAT_KEY_SLICE_HEIGHT; # var introduced=28
-    AMEDIAFORMAT_KEY_STRIDE; # var
+    AMEDIAFORMAT_KEY_STRIDE; # var introduced=21
+    AMEDIAFORMAT_KEY_TEMPORAL_LAYER_ID; # var introduced=28
     AMEDIAFORMAT_KEY_TEMPORAL_LAYERING; # var introduced=28
     AMEDIAFORMAT_KEY_TILE_HEIGHT; # var introduced=28
     AMEDIAFORMAT_KEY_TILE_WIDTH; # var introduced=28
+    AMEDIAFORMAT_KEY_TIME_US; # var introduced=28
+    AMEDIAFORMAT_KEY_TRACK_INDEX; # var introduced=28
     AMEDIAFORMAT_KEY_TRACK_ID; # var introduced=28
-    AMEDIAFORMAT_KEY_WIDTH; # var
+    AMEDIAFORMAT_KEY_WIDTH; # var introduced=21
     AMediaCodecActionCode_isRecoverable; # introduced=28
     AMediaCodecActionCode_isTransient; # introduced=28
     AMediaCodecCryptoInfo_delete;
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index 0318ffe..a546c8f 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -4877,11 +4877,15 @@
     //      use device for strategy DTMF
     // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
     //      use device for strategy t-t-s
+
+    // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
+    // with a refined rule considering mutually exclusive devices (using same backend)
+    // as opposed to all streams on the same audio HAL module.
     if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
         mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
     } else if (isInCall() ||
-                    isStrategyActive(outputDesc, STRATEGY_PHONE)) {
+               isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
     } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
@@ -5889,6 +5893,20 @@
     return false;
 }
 
+bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
+                                          routing_strategy strategy, uint32_t inPastMs,
+                                          nsecs_t sysTime) const
+{
+    for (size_t i = 0; i < mOutputs.size(); i++) {
+        sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
+        if (outputDesc->sharesHwModuleWith(desc)
+            && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
+            return true;
+        }
+    }
+    return false;
+}
+
 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
 {
     return mEngine->getForceUse(usage);
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h
index b954714..48e0472 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.h
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h
@@ -321,6 +321,10 @@
         bool isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc, routing_strategy strategy,
                               uint32_t inPastMs = 0, nsecs_t sysTime = 0) const;
 
+        bool isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
+                                                  routing_strategy strategy, uint32_t inPastMs = 0,
+                                                  nsecs_t sysTime = 0) const;
+
         // change the route of the specified output. Returns the number of ms we have slept to
         // allow new routing to take effect in certain cases.
         virtual uint32_t setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 282871b..c41de82 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -55,6 +55,7 @@
 #include <utils/Errors.h>
 #include <utils/Log.h>
 #include <utils/String16.h>
+#include <utils/SystemClock.h>
 #include <utils/Trace.h>
 #include <private/android_filesystem_config.h>
 #include <system/camera_vendor_tags.h>
@@ -2433,6 +2434,8 @@
     return isUidActiveLocked(uid, callingPackage);
 }
 
+static const int kPollUidActiveTimeoutMillis = 50;
+
 bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
     // Non-app UIDs are considered always active
     // If activity manager is unreachable, assume everything is active
@@ -2452,7 +2455,28 @@
         ActivityManager am;
         // Okay to access with a lock held as UID changes are dispatched without
         // a lock and we are a higher level component.
-        active = am.isUidActive(uid, callingPackage);
+        int64_t startTimeMillis = 0;
+        do {
+            // TODO: Fix this b/109950150!
+            // Okay this is a hack. There is a race between the UID turning active and
+            // activity being resumed. The proper fix is very risky, so we temporary add
+            // some polling which should happen pretty rarely anyway as the race is hard
+            // to hit.
+            active = am.isUidActive(uid, callingPackage);
+            if (active) {
+                break;
+            }
+            if (startTimeMillis <= 0) {
+                startTimeMillis = uptimeMillis();
+            }
+            int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
+            int64_t remainingTimeMillis = kPollUidActiveTimeoutMillis - ellapsedTimeMillis;
+            if (remainingTimeMillis <= 0) {
+                break;
+            }
+            usleep(remainingTimeMillis * 1000);
+        } while (true);
+
         if (active) {
             // Now that we found out the UID is actually active, cache that
             mActiveUids.insert(uid);
diff --git a/services/camera/libcameraservice/api1/Camera2Client.cpp b/services/camera/libcameraservice/api1/Camera2Client.cpp
index 65faac9..d59b313 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.cpp
+++ b/services/camera/libcameraservice/api1/Camera2Client.cpp
@@ -102,7 +102,7 @@
     {
         SharedParameters::Lock l(mParameters);
 
-        res = l.mParameters.initialize(&(mDevice->info()), mDeviceVersion);
+        res = l.mParameters.initialize(mDevice.get(), mDeviceVersion);
         if (res != OK) {
             ALOGE("%s: Camera %d: unable to build defaults: %s (%d)",
                     __FUNCTION__, mCameraId, strerror(-res), res);
@@ -250,6 +250,7 @@
     switch (p.sceneMode) {
         case ANDROID_CONTROL_SCENE_MODE_DISABLED:
             result.append("AUTO\n"); break;
+        CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY)
         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_ACTION)
         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PORTRAIT)
         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_LANDSCAPE)
diff --git a/services/camera/libcameraservice/api1/client2/Parameters.cpp b/services/camera/libcameraservice/api1/client2/Parameters.cpp
index d66dec4..28d186a 100644
--- a/services/camera/libcameraservice/api1/client2/Parameters.cpp
+++ b/services/camera/libcameraservice/api1/client2/Parameters.cpp
@@ -41,23 +41,29 @@
         int cameraFacing) :
         cameraId(cameraId),
         cameraFacing(cameraFacing),
-        info(NULL) {
+        info(NULL),
+        mDefaultSceneMode(ANDROID_CONTROL_SCENE_MODE_DISABLED) {
 }
 
 Parameters::~Parameters() {
 }
 
-status_t Parameters::initialize(const CameraMetadata *info, int deviceVersion) {
+status_t Parameters::initialize(CameraDeviceBase *device, int deviceVersion) {
     status_t res;
+    if (device == nullptr) {
+        ALOGE("%s: device is null!", __FUNCTION__);
+        return BAD_VALUE;
+    }
 
-    if (info->entryCount() == 0) {
+    const CameraMetadata& info = device->info();
+    if (info.entryCount() == 0) {
         ALOGE("%s: No static information provided!", __FUNCTION__);
         return BAD_VALUE;
     }
-    Parameters::info = info;
+    Parameters::info = &info;
     mDeviceVersion = deviceVersion;
 
-    res = buildFastInfo();
+    res = buildFastInfo(device);
     if (res != OK) return res;
 
     res = buildQuirks();
@@ -557,6 +563,10 @@
                     noSceneModes = true;
                     break;
                 case ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY:
+                    // Face priority can be used as alternate default if supported.
+                    // Per API contract it shouldn't override the user set flash,
+                    // white balance and focus modes.
+                    mDefaultSceneMode = availableSceneModes.data.u8[i];
                     // Not in old API
                     addComma = false;
                     break;
@@ -761,17 +771,7 @@
     focusingAreas.clear();
     focusingAreas.add(Parameters::Area(0,0,0,0,0));
 
-    if (fastInfo.isExternalCamera) {
-        params.setFloat(CameraParameters::KEY_FOCAL_LENGTH, -1.0);
-    } else {
-        camera_metadata_ro_entry_t availableFocalLengths =
-            staticInfo(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS, 0, 0, false);
-        if (!availableFocalLengths.count) return NO_INIT;
-
-        float minFocalLength = availableFocalLengths.data.f[0];
-        params.setFloat(CameraParameters::KEY_FOCAL_LENGTH, minFocalLength);
-    }
-
+    params.setFloat(CameraParameters::KEY_FOCAL_LENGTH, fastInfo.defaultFocalLength);
 
     float horizFov, vertFov;
     res = calculatePictureFovs(&horizFov, &vertFov);
@@ -993,7 +993,7 @@
     return paramsFlattened;
 }
 
-status_t Parameters::buildFastInfo() {
+status_t Parameters::buildFastInfo(CameraDeviceBase *device) {
 
     camera_metadata_ro_entry_t activeArraySize =
         staticInfo(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE, 2, 4);
@@ -1109,20 +1109,12 @@
             focusDistanceCalibration.data.u8[0] !=
             ANDROID_LENS_INFO_FOCUS_DISTANCE_CALIBRATION_UNCALIBRATED);
 
-
-    camera_metadata_ro_entry_t hwLevel = staticInfo(ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL);
-    if (!hwLevel.count) return NO_INIT;
-    fastInfo.isExternalCamera =
-            hwLevel.data.u8[0] == ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL;
-
-    camera_metadata_ro_entry_t availableFocalLengths =
-        staticInfo(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS, 0, 0, /*required*/false);
-    if (!availableFocalLengths.count && !fastInfo.isExternalCamera) return NO_INIT;
+    res = getDefaultFocalLength(device);
+    if (res != OK) return res;
 
     SortedVector<int32_t> availableFormats = getAvailableOutputFormats();
     if (!availableFormats.size()) return NO_INIT;
 
-
     if (sceneModeOverrides.count > 0) {
         // sceneModeOverrides is defined to have 3 entries for each scene mode,
         // which are AE, AWB, and AF override modes the HAL wants for that scene
@@ -1200,19 +1192,6 @@
     fastInfo.bestFaceDetectMode = bestFaceDetectMode;
     fastInfo.maxFaces = maxFaces;
 
-    // Find smallest (widest-angle) focal length to use as basis of still
-    // picture FOV reporting.
-    if (fastInfo.isExternalCamera) {
-        fastInfo.minFocalLength = -1.0;
-    } else {
-        fastInfo.minFocalLength = availableFocalLengths.data.f[0];
-        for (size_t i = 1; i < availableFocalLengths.count; i++) {
-            if (fastInfo.minFocalLength > availableFocalLengths.data.f[i]) {
-                fastInfo.minFocalLength = availableFocalLengths.data.f[i];
-            }
-        }
-    }
-
     // Check if the HAL supports HAL_PIXEL_FORMAT_YCbCr_420_888
     fastInfo.useFlexibleYuv = false;
     for (size_t i = 0; i < availableFormats.size(); i++) {
@@ -1760,7 +1739,7 @@
 
     // SCENE_MODE
     validatedParams.sceneMode = sceneModeStringToEnum(
-        newParams.get(CameraParameters::KEY_SCENE_MODE) );
+        newParams.get(CameraParameters::KEY_SCENE_MODE), mDefaultSceneMode);
     if (validatedParams.sceneMode != sceneMode &&
             validatedParams.sceneMode !=
             ANDROID_CONTROL_SCENE_MODE_DISABLED) {
@@ -1778,7 +1757,7 @@
         }
     }
     bool sceneModeSet =
-            validatedParams.sceneMode != ANDROID_CONTROL_SCENE_MODE_DISABLED;
+            validatedParams.sceneMode != mDefaultSceneMode;
 
     // FLASH_MODE
     if (sceneModeSet) {
@@ -2157,7 +2136,7 @@
     uint8_t reqSceneMode =
             sceneModeActive ? sceneMode :
             enableFaceDetect ? (uint8_t)ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY :
-            (uint8_t)ANDROID_CONTROL_SCENE_MODE_DISABLED;
+            mDefaultSceneMode;
     res = request->update(ANDROID_CONTROL_SCENE_MODE,
             &reqSceneMode, 1);
     if (res != OK) return res;
@@ -2446,6 +2425,50 @@
     return true;
 }
 
+status_t Parameters::getDefaultFocalLength(CameraDeviceBase *device) {
+    if (device == nullptr) {
+        ALOGE("%s: Camera device is nullptr", __FUNCTION__);
+        return BAD_VALUE;
+    }
+
+    camera_metadata_ro_entry_t hwLevel = staticInfo(ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL);
+    if (!hwLevel.count) return NO_INIT;
+    fastInfo.isExternalCamera =
+            hwLevel.data.u8[0] == ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL;
+
+    camera_metadata_ro_entry_t availableFocalLengths =
+        staticInfo(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS, 0, 0, /*required*/false);
+    if (!availableFocalLengths.count && !fastInfo.isExternalCamera) return NO_INIT;
+
+    // Find focal length in PREVIEW template to use as default focal length.
+    if (fastInfo.isExternalCamera) {
+        fastInfo.defaultFocalLength = -1.0;
+    } else {
+        // Find smallest (widest-angle) focal length to use as basis of still
+        // picture FOV reporting.
+        fastInfo.defaultFocalLength = availableFocalLengths.data.f[0];
+        for (size_t i = 1; i < availableFocalLengths.count; i++) {
+            if (fastInfo.defaultFocalLength > availableFocalLengths.data.f[i]) {
+                fastInfo.defaultFocalLength = availableFocalLengths.data.f[i];
+            }
+        }
+
+        // Use focal length in preview template if it exists
+        CameraMetadata previewTemplate;
+        status_t res = device->createDefaultRequest(CAMERA3_TEMPLATE_PREVIEW, &previewTemplate);
+        if (res != OK) {
+            ALOGE("%s: Failed to create default PREVIEW request: %s (%d)",
+                    __FUNCTION__, strerror(-res), res);
+            return res;
+        }
+        camera_metadata_entry entry = previewTemplate.find(ANDROID_LENS_FOCAL_LENGTH);
+        if (entry.count != 0) {
+            fastInfo.defaultFocalLength = entry.data.f[0];
+        }
+    }
+    return OK;
+}
+
 const char* Parameters::getStateName(State state) {
 #define CASE_ENUM_TO_CHAR(x) case x: return(#x); break;
     switch(state) {
@@ -2589,12 +2612,12 @@
         -1;
 }
 
-int Parameters::sceneModeStringToEnum(const char *sceneMode) {
+int Parameters::sceneModeStringToEnum(const char *sceneMode, uint8_t defaultSceneMode) {
     return
         !sceneMode ?
-            ANDROID_CONTROL_SCENE_MODE_DISABLED :
+            defaultSceneMode :
         !strcmp(sceneMode, CameraParameters::SCENE_MODE_AUTO) ?
-            ANDROID_CONTROL_SCENE_MODE_DISABLED :
+            defaultSceneMode :
         !strcmp(sceneMode, CameraParameters::SCENE_MODE_ACTION) ?
             ANDROID_CONTROL_SCENE_MODE_ACTION :
         !strcmp(sceneMode, CameraParameters::SCENE_MODE_PORTRAIT) ?
@@ -3241,12 +3264,12 @@
     if (horizFov != NULL) {
         *horizFov = 180 / M_PI * 2 *
                 atanf(horizCropFactor * sensorSize.data.f[0] /
-                        (2 * fastInfo.minFocalLength));
+                        (2 * fastInfo.defaultFocalLength));
     }
     if (vertFov != NULL) {
         *vertFov = 180 / M_PI * 2 *
                 atanf(vertCropFactor * sensorSize.data.f[1] /
-                        (2 * fastInfo.minFocalLength));
+                        (2 * fastInfo.defaultFocalLength));
     }
     return OK;
 }
diff --git a/services/camera/libcameraservice/api1/client2/Parameters.h b/services/camera/libcameraservice/api1/client2/Parameters.h
index 97f8ea7..42e7a47 100644
--- a/services/camera/libcameraservice/api1/client2/Parameters.h
+++ b/services/camera/libcameraservice/api1/client2/Parameters.h
@@ -30,6 +30,8 @@
 #include <camera/CameraParameters2.h>
 #include <camera/CameraMetadata.h>
 
+#include "common/CameraDeviceBase.h"
+
 namespace android {
 namespace camera2 {
 
@@ -241,7 +243,7 @@
         };
         DefaultKeyedVector<uint8_t, OverrideModes> sceneModeOverrides;
         bool isExternalCamera;
-        float minFocalLength;
+        float defaultFocalLength;
         bool useFlexibleYuv;
         Size maxJpegSize;
         Size maxZslSize;
@@ -264,10 +266,10 @@
     ~Parameters();
 
     // Sets up default parameters
-    status_t initialize(const CameraMetadata *info, int deviceVersion);
+    status_t initialize(CameraDeviceBase *device, int deviceVersion);
 
     // Build fast-access device static info from static info
-    status_t buildFastInfo();
+    status_t buildFastInfo(CameraDeviceBase *device);
     // Query for quirks from static info
     status_t buildQuirks();
 
@@ -300,6 +302,9 @@
     // whether zero shutter lag should be used for non-recording operation
     bool useZeroShutterLag() const;
 
+    // Get default focal length
+    status_t getDefaultFocalLength(CameraDeviceBase *camera);
+
     // Calculate the crop region rectangle, either tightly about the preview
     // resolution, or a region just based on the active array; both take
     // into account the current zoom level.
@@ -326,7 +331,7 @@
     static const char* wbModeEnumToString(uint8_t wbMode);
     static int effectModeStringToEnum(const char *effectMode);
     static int abModeStringToEnum(const char *abMode);
-    static int sceneModeStringToEnum(const char *sceneMode);
+    static int sceneModeStringToEnum(const char *sceneMode, uint8_t defaultScene);
     static flashMode_t flashModeStringToEnum(const char *flashMode);
     static const char* flashModeEnumToString(flashMode_t flashMode);
     static focusMode_t focusModeStringToEnum(const char *focusMode);
@@ -434,6 +439,7 @@
     Size getMaxSize(const Vector<Size>& sizes);
 
     int mDeviceVersion;
+    uint8_t mDefaultSceneMode;
 };
 
 // This class encapsulates the Parameters class so that it can only be accessed
diff --git a/services/camera/libcameraservice/device3/Camera3StreamSplitter.cpp b/services/camera/libcameraservice/device3/Camera3StreamSplitter.cpp
index 59ac636..8a9402e 100644
--- a/services/camera/libcameraservice/device3/Camera3StreamSplitter.cpp
+++ b/services/camera/libcameraservice/device3/Camera3StreamSplitter.cpp
@@ -493,6 +493,10 @@
     SP_LOGV("acquired buffer %" PRId64 " from input at slot %d",
             bufferItem.mGraphicBuffer->getId(), bufferItem.mSlot);
 
+    if (bufferItem.mTransformToDisplayInverse) {
+        bufferItem.mTransform |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
+    }
+
     // Attach and queue the buffer to each of the outputs
     BufferTracker& tracker = *(mBuffers[bufferId]);
 
diff --git a/services/camera/libcameraservice/device3/DistortionMapper.cpp b/services/camera/libcameraservice/device3/DistortionMapper.cpp
index eef6658..4dafefd 100644
--- a/services/camera/libcameraservice/device3/DistortionMapper.cpp
+++ b/services/camera/libcameraservice/device3/DistortionMapper.cpp
@@ -49,7 +49,7 @@
 };
 
 // Only for capture result
-constexpr std::array<uint32_t, 2> DistortionMapper::kResultPointsToCorrect = {
+constexpr std::array<uint32_t, 2> DistortionMapper::kResultPointsToCorrectNoClamp = {
     ANDROID_STATISTICS_FACE_RECTANGLES, // Says rectangles, is really points
     ANDROID_STATISTICS_FACE_LANDMARKS,
 };
@@ -79,12 +79,21 @@
     array = deviceInfo.find(ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE);
     if (array.count != 4) return BAD_VALUE;
 
-    mArrayWidth = array.data.i32[2];
-    mArrayHeight = array.data.i32[3];
+    float arrayX = static_cast<float>(array.data.i32[0]);
+    float arrayY = static_cast<float>(array.data.i32[1]);
+    mArrayWidth = static_cast<float>(array.data.i32[2]);
+    mArrayHeight = static_cast<float>(array.data.i32[3]);
 
     array = deviceInfo.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
-    mActiveWidth = array.data.i32[2];
-    mActiveHeight = array.data.i32[3];
+    if (array.count != 4) return BAD_VALUE;
+
+    float activeX = static_cast<float>(array.data.i32[0]);
+    float activeY = static_cast<float>(array.data.i32[1]);
+    mActiveWidth = static_cast<float>(array.data.i32[2]);
+    mActiveHeight = static_cast<float>(array.data.i32[3]);
+
+    mArrayDiffX = activeX - arrayX;
+    mArrayDiffY = activeY - arrayY;
 
     return updateCalibration(deviceInfo);
 }
@@ -111,22 +120,13 @@
                 if (weight == 0) {
                     continue;
                 }
-                res = mapCorrectedToRaw(e.data.i32 + j, 2);
+                res = mapCorrectedToRaw(e.data.i32 + j, 2, /*clamp*/true);
                 if (res != OK) return res;
-                for (size_t k = 0; k < 4; k+=2) {
-                    int32_t& x = e.data.i32[j + k];
-                    int32_t& y = e.data.i32[j + k + 1];
-                    // Clamp to within active array
-                    x = std::max(0, x);
-                    x = std::min(mActiveWidth - 1, x);
-                    y = std::max(0, y);
-                    y = std::min(mActiveHeight - 1, y);
-                }
             }
         }
         for (auto rect : kRequestRectsToCorrect) {
             e = request->find(rect);
-            res = mapCorrectedRectToRaw(e.data.i32, e.count / 4);
+            res = mapCorrectedRectToRaw(e.data.i32, e.count / 4, /*clamp*/true);
             if (res != OK) return res;
         }
     }
@@ -156,27 +156,18 @@
                 if (weight == 0) {
                     continue;
                 }
-                res = mapRawToCorrected(e.data.i32 + j, 2);
+                res = mapRawToCorrected(e.data.i32 + j, 2, /*clamp*/true);
                 if (res != OK) return res;
-                for (size_t k = 0; k < 4; k+=2) {
-                    int32_t& x = e.data.i32[j + k];
-                    int32_t& y = e.data.i32[j + k + 1];
-                    // Clamp to within active array
-                    x = std::max(0, x);
-                    x = std::min(mActiveWidth - 1, x);
-                    y = std::max(0, y);
-                    y = std::min(mActiveHeight - 1, y);
-                }
             }
         }
         for (auto rect : kResultRectsToCorrect) {
             e = result->find(rect);
-            res = mapRawRectToCorrected(e.data.i32, e.count / 4);
+            res = mapRawRectToCorrected(e.data.i32, e.count / 4, /*clamp*/true);
             if (res != OK) return res;
         }
-        for (auto pts : kResultPointsToCorrect) {
+        for (auto pts : kResultPointsToCorrectNoClamp) {
             e = result->find(pts);
-            res = mapRawToCorrected(e.data.i32, e.count / 2);
+            res = mapRawToCorrected(e.data.i32, e.count / 2, /*clamp*/false);
             if (res != OK) return res;
         }
     }
@@ -232,9 +223,12 @@
     return OK;
 }
 
-status_t DistortionMapper::mapRawToCorrected(int32_t *coordPairs, int coordCount) {
+status_t DistortionMapper::mapRawToCorrected(int32_t *coordPairs, int coordCount,
+        bool clamp, bool simple) {
     if (!mValidMapping) return INVALID_OPERATION;
 
+    if (simple) return mapRawToCorrectedSimple(coordPairs, coordCount, clamp);
+
     if (!mValidGrids) {
         status_t res = buildGrids();
         if (res != OK) return res;
@@ -275,6 +269,12 @@
         // Interpolate along left edge of corrected quad (which are axis-aligned) for y
         float corrY = corrQuad->coords[1] + v * (corrQuad->coords[7] - corrQuad->coords[1]);
 
+        // Clamp to within active array
+        if (clamp) {
+            corrX = std::min(mActiveWidth - 1, std::max(0.f, corrX));
+            corrY = std::min(mActiveHeight - 1, std::max(0.f, corrY));
+        }
+
         coordPairs[i] = static_cast<int32_t>(std::round(corrX));
         coordPairs[i + 1] = static_cast<int32_t>(std::round(corrY));
     }
@@ -282,7 +282,30 @@
     return OK;
 }
 
-status_t DistortionMapper::mapRawRectToCorrected(int32_t *rects, int rectCount) {
+status_t DistortionMapper::mapRawToCorrectedSimple(int32_t *coordPairs, int coordCount,
+        bool clamp) const {
+    if (!mValidMapping) return INVALID_OPERATION;
+
+    float scaleX = mActiveWidth / mArrayWidth;
+    float scaleY = mActiveHeight / mArrayHeight;
+    for (int i = 0; i < coordCount * 2; i += 2) {
+        float x = coordPairs[i];
+        float y = coordPairs[i + 1];
+        float corrX = x * scaleX;
+        float corrY = y * scaleY;
+        if (clamp) {
+            corrX = std::min(mActiveWidth - 1, std::max(0.f, corrX));
+            corrY = std::min(mActiveHeight - 1, std::max(0.f, corrY));
+        }
+        coordPairs[i] = static_cast<int32_t>(std::round(corrX));
+        coordPairs[i + 1] = static_cast<int32_t>(std::round(corrY));
+    }
+
+    return OK;
+}
+
+status_t DistortionMapper::mapRawRectToCorrected(int32_t *rects, int rectCount, bool clamp,
+        bool simple) {
     if (!mValidMapping) return INVALID_OPERATION;
     for (int i = 0; i < rectCount * 4; i += 4) {
         // Map from (l, t, width, height) to (l, t, r, b)
@@ -293,7 +316,7 @@
             rects[i + 1] + rects[i + 3]
         };
 
-        mapRawToCorrected(coords, 2);
+        mapRawToCorrected(coords, 2, clamp, simple);
 
         // Map back to (l, t, width, height)
         rects[i] = coords[0];
@@ -305,14 +328,24 @@
     return OK;
 }
 
+status_t DistortionMapper::mapCorrectedToRaw(int32_t *coordPairs, int coordCount, bool clamp,
+        bool simple) const {
+    return mapCorrectedToRawImpl(coordPairs, coordCount, clamp, simple);
+}
+
 template<typename T>
-status_t DistortionMapper::mapCorrectedToRaw(T *coordPairs, int coordCount) const {
+status_t DistortionMapper::mapCorrectedToRawImpl(T *coordPairs, int coordCount, bool clamp,
+        bool simple) const {
     if (!mValidMapping) return INVALID_OPERATION;
 
+    if (simple) return mapCorrectedToRawImplSimple(coordPairs, coordCount, clamp);
+
+    float activeCx = mCx - mArrayDiffX;
+    float activeCy = mCy - mArrayDiffY;
     for (int i = 0; i < coordCount * 2; i += 2) {
-        // Move to normalized space
-        float ywi = (coordPairs[i + 1] - mCy) * mInvFy;
-        float xwi = (coordPairs[i] - mCx - mS * ywi) * mInvFx;
+        // Move to normalized space from active array space
+        float ywi = (coordPairs[i + 1] - activeCy) * mInvFy;
+        float xwi = (coordPairs[i] - activeCx - mS * ywi) * mInvFx;
         // Apply distortion model to calculate raw image coordinates
         float rSq = xwi * xwi + ywi * ywi;
         float Fr = 1.f + (mK[0] * rSq) + (mK[1] * rSq * rSq) + (mK[2] * rSq * rSq * rSq);
@@ -321,6 +354,11 @@
         // Move back to image space
         float xr = mFx * xc + mS * yc + mCx;
         float yr = mFy * yc + mCy;
+        // Clamp to within pre-correction active array
+        if (clamp) {
+            xr = std::min(mArrayWidth - 1, std::max(0.f, xr));
+            yr = std::min(mArrayHeight - 1, std::max(0.f, yr));
+        }
 
         coordPairs[i] = static_cast<T>(std::round(xr));
         coordPairs[i + 1] = static_cast<T>(std::round(yr));
@@ -329,10 +367,32 @@
     return OK;
 }
 
-template status_t DistortionMapper::mapCorrectedToRaw(int32_t*, int) const;
-template status_t DistortionMapper::mapCorrectedToRaw(float*, int) const;
+template<typename T>
+status_t DistortionMapper::mapCorrectedToRawImplSimple(T *coordPairs, int coordCount,
+        bool clamp) const {
+    if (!mValidMapping) return INVALID_OPERATION;
 
-status_t DistortionMapper::mapCorrectedRectToRaw(int32_t *rects, int rectCount) const {
+    float scaleX = mArrayWidth / mActiveWidth;
+    float scaleY = mArrayHeight / mActiveHeight;
+    for (int i = 0; i < coordCount * 2; i += 2) {
+        float x = coordPairs[i];
+        float y = coordPairs[i + 1];
+        float rawX = x * scaleX;
+        float rawY = y * scaleY;
+        if (clamp) {
+            rawX = std::min(mArrayWidth - 1, std::max(0.f, rawX));
+            rawY = std::min(mArrayHeight - 1, std::max(0.f, rawY));
+        }
+        coordPairs[i] = static_cast<T>(std::round(rawX));
+        coordPairs[i + 1] = static_cast<T>(std::round(rawY));
+    }
+
+    return OK;
+}
+
+
+status_t DistortionMapper::mapCorrectedRectToRaw(int32_t *rects, int rectCount, bool clamp,
+        bool simple) const {
     if (!mValidMapping) return INVALID_OPERATION;
 
     for (int i = 0; i < rectCount * 4; i += 4) {
@@ -344,7 +404,7 @@
             rects[i + 1] + rects[i + 3]
         };
 
-        mapCorrectedToRaw(coords, 2);
+        mapCorrectedToRaw(coords, 2, clamp, simple);
 
         // Map back to (l, t, width, height)
         rects[i] = coords[0];
@@ -380,7 +440,8 @@
             };
             mDistortedGrid[index].src = &mCorrectedGrid[index];
             mDistortedGrid[index].coords = mCorrectedGrid[index].coords;
-            status_t res = mapCorrectedToRaw(mDistortedGrid[index].coords.data(), 4);
+            status_t res = mapCorrectedToRawImpl(mDistortedGrid[index].coords.data(), 4,
+                    /*clamp*/false, /*simple*/false);
             if (res != OK) return res;
         }
     }
diff --git a/services/camera/libcameraservice/device3/DistortionMapper.h b/services/camera/libcameraservice/device3/DistortionMapper.h
index 00cbd32..4c0a1a6 100644
--- a/services/camera/libcameraservice/device3/DistortionMapper.h
+++ b/services/camera/libcameraservice/device3/DistortionMapper.h
@@ -73,8 +73,11 @@
      *
      *   coordPairs: A pointer to an array of consecutive (x,y) points
      *   coordCount: Number of (x,y) pairs to transform
+     *   clamp: Whether to clamp the result to the bounds of the active array
+     *   simple: Whether to do complex correction or just a simple linear map
      */
-    status_t mapRawToCorrected(int32_t *coordPairs, int coordCount);
+    status_t mapRawToCorrected(int32_t *coordPairs, int coordCount, bool clamp,
+            bool simple = true);
 
     /**
      * Transform from distorted (original) to corrected (warped) coordinates.
@@ -82,8 +85,11 @@
      *
      *   rects: A pointer to an array of consecutive (x,y, w, h) rectangles
      *   rectCount: Number of rectangles to transform
+     *   clamp: Whether to clamp the result to the bounds of the active array
+     *   simple: Whether to do complex correction or just a simple linear map
      */
-    status_t mapRawRectToCorrected(int32_t *rects, int rectCount);
+    status_t mapRawRectToCorrected(int32_t *rects, int rectCount, bool clamp,
+            bool simple = true);
 
     /**
      * Transform from corrected (warped) to distorted (original) coordinates.
@@ -91,9 +97,11 @@
      *
      *   coordPairs: A pointer to an array of consecutive (x,y) points
      *   coordCount: Number of (x,y) pairs to transform
+     *   clamp: Whether to clamp the result to the bounds of the precorrection active array
+     *   simple: Whether to do complex correction or just a simple linear map
      */
-    template<typename T>
-    status_t mapCorrectedToRaw(T* coordPairs, int coordCount) const;
+    status_t mapCorrectedToRaw(int32_t* coordPairs, int coordCount, bool clamp,
+            bool simple = true) const;
 
     /**
      * Transform from corrected (warped) to distorted (original) coordinates.
@@ -101,8 +109,11 @@
      *
      *   rects: A pointer to an array of consecutive (x,y, w, h) rectangles
      *   rectCount: Number of rectangles to transform
+     *   clamp: Whether to clamp the result to the bounds of the precorrection active array
+     *   simple: Whether to do complex correction or just a simple linear map
      */
-    status_t mapCorrectedRectToRaw(int32_t *rects, int rectCount) const;
+    status_t mapCorrectedRectToRaw(int32_t *rects, int rectCount, bool clamp,
+            bool simple = true) const;
 
     struct GridQuad {
         // Source grid quad, or null
@@ -150,8 +161,18 @@
     // Only capture result
     static const std::array<uint32_t, 1> kResultRectsToCorrect;
 
-    // Only for capture results
-    static const std::array<uint32_t, 2> kResultPointsToCorrect;
+    // Only for capture results; don't clamp
+    static const std::array<uint32_t, 2> kResultPointsToCorrectNoClamp;
+
+    // Single implementation for various mapCorrectedToRaw methods
+    template<typename T>
+    status_t mapCorrectedToRawImpl(T* coordPairs, int coordCount, bool clamp, bool simple) const;
+
+    // Simple linear interpolation option
+    template<typename T>
+    status_t mapCorrectedToRawImplSimple(T* coordPairs, int coordCount, bool clamp) const;
+
+    status_t mapRawToCorrectedSimple(int32_t *coordPairs, int coordCount, bool clamp) const;
 
     // Utility to create reverse mapping grids
     status_t buildGrids();
@@ -168,9 +189,11 @@
     float mK[5];
 
     // pre-correction active array dimensions
-    int mArrayWidth, mArrayHeight;
+    float mArrayWidth, mArrayHeight;
     // active array dimensions
-    int mActiveWidth, mActiveHeight;
+    float mActiveWidth, mActiveHeight;
+    // corner offsets between pre-correction and active arrays
+    float mArrayDiffX, mArrayDiffY;
 
     std::vector<GridQuad> mCorrectedGrid;
     std::vector<GridQuad> mDistortedGrid;
diff --git a/services/camera/libcameraservice/tests/DistortionMapperTest.cpp b/services/camera/libcameraservice/tests/DistortionMapperTest.cpp
index b489931..2a689c6 100644
--- a/services/camera/libcameraservice/tests/DistortionMapperTest.cpp
+++ b/services/camera/libcameraservice/tests/DistortionMapperTest.cpp
@@ -30,6 +30,7 @@
 
 
 int32_t testActiveArray[] = {100, 100, 1000, 750};
+int32_t testPreCorrActiveArray[] = {90, 90, 1020, 770};
 
 float testICal[] = { 1000.f, 1000.f, 500.f, 500.f, 0.f };
 
@@ -45,14 +46,19 @@
 };
 
 
-void setupTestMapper(DistortionMapper *m, float distortion[5]) {
+void setupTestMapper(DistortionMapper *m,
+        float distortion[5], float intrinsics[5],
+        int32_t activeArray[4], int32_t preCorrectionActiveArray[4]) {
     CameraMetadata deviceInfo;
 
     deviceInfo.update(ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE,
-            testActiveArray, 4);
+            preCorrectionActiveArray, 4);
+
+    deviceInfo.update(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
+            activeArray, 4);
 
     deviceInfo.update(ANDROID_LENS_INTRINSIC_CALIBRATION,
-            testICal, 5);
+            intrinsics, 5);
 
     deviceInfo.update(ANDROID_LENS_DISTORTION,
             distortion, 5);
@@ -89,6 +95,9 @@
     ASSERT_FALSE(m.calibrationValid());
 
     deviceInfo.update(ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE,
+            testPreCorrActiveArray, 4);
+
+    deviceInfo.update(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
             testActiveArray, 4);
 
     deviceInfo.update(ANDROID_LENS_INTRINSIC_CALIBRATION,
@@ -118,17 +127,19 @@
     status_t res;
 
     DistortionMapper m;
-    setupTestMapper(&m, identityDistortion);
+    setupTestMapper(&m, identityDistortion, testICal,
+            /*activeArray*/ testActiveArray,
+            /*preCorrectionActiveArray*/ testActiveArray);
 
     auto coords = basicCoords;
-    res = m.mapCorrectedToRaw(coords.data(), 5);
+    res = m.mapCorrectedToRaw(coords.data(), 5,  /*clamp*/true);
     ASSERT_EQ(res, OK);
 
     for (size_t i = 0; i < coords.size(); i++) {
         EXPECT_EQ(coords[i], basicCoords[i]);
     }
 
-    res = m.mapRawToCorrected(coords.data(), 5);
+    res = m.mapRawToCorrected(coords.data(), 5, /*clamp*/true);
     ASSERT_EQ(res, OK);
 
     for (size_t i = 0; i < coords.size(); i++) {
@@ -137,18 +148,18 @@
 
     std::array<int32_t, 8> rects = {
         0, 0, 100, 100,
-        testActiveArray[2] - 100, testActiveArray[3]-100, 100, 100
+        testActiveArray[2] - 101, testActiveArray[3] - 101, 100, 100
     };
 
     auto rectsOrig = rects;
-    res = m.mapCorrectedRectToRaw(rects.data(), 2);
+    res = m.mapCorrectedRectToRaw(rects.data(), 2, /*clamp*/true);
     ASSERT_EQ(res, OK);
 
     for (size_t i = 0; i < rects.size(); i++) {
         EXPECT_EQ(rects[i], rectsOrig[i]);
     }
 
-    res = m.mapRawRectToCorrected(rects.data(), 2);
+    res = m.mapRawRectToCorrected(rects.data(), 2, /*clamp*/true);
     ASSERT_EQ(res, OK);
 
     for (size_t i = 0; i < rects.size(); i++) {
@@ -156,23 +167,39 @@
     }
 }
 
-TEST(DistortionMapperTest, LargeTransform) {
+TEST(DistortionMapperTest, SimpleTransform) {
+    status_t res;
+
+    DistortionMapper m;
+    setupTestMapper(&m, identityDistortion, testICal,
+            /*activeArray*/ testActiveArray,
+            /*preCorrectionActiveArray*/ testPreCorrActiveArray);
+
+    auto coords = basicCoords;
+    res = m.mapCorrectedToRaw(coords.data(), 5,  /*clamp*/true, /*simple*/true);
+    ASSERT_EQ(res, OK);
+
+    ASSERT_EQ(coords[0], 0); ASSERT_EQ(coords[1], 0);
+    ASSERT_EQ(coords[2], testPreCorrActiveArray[2] - 1); ASSERT_EQ(coords[3], 0);
+    ASSERT_EQ(coords[4], testPreCorrActiveArray[2] - 1); ASSERT_EQ(coords[5], testPreCorrActiveArray[3] - 1);
+    ASSERT_EQ(coords[6], 0); ASSERT_EQ(coords[7], testPreCorrActiveArray[3] - 1);
+    ASSERT_EQ(coords[8], testPreCorrActiveArray[2] / 2); ASSERT_EQ(coords[9], testPreCorrActiveArray[3] / 2);
+}
+
+
+void RandomTransformTest(::testing::Test *test,
+        int32_t* activeArray, DistortionMapper &m, bool clamp, bool simple) {
     status_t res;
     constexpr int maxAllowedPixelError = 2; // Maximum per-pixel error allowed
     constexpr int bucketsPerPixel = 3; // Histogram granularity
 
     unsigned int seed = 1234; // Ensure repeatability for debugging
-    const size_t coordCount = 1e6; // Number of random test points
-
-    float bigDistortion[] = {0.1, -0.003, 0.004, 0.02, 0.01};
-
-    DistortionMapper m;
-    setupTestMapper(&m, bigDistortion);
+    const size_t coordCount = 1e5; // Number of random test points
 
     std::default_random_engine gen(seed);
 
-    std::uniform_int_distribution<int> x_dist(0, testActiveArray[2] - 1);
-    std::uniform_int_distribution<int> y_dist(0, testActiveArray[3] - 1);
+    std::uniform_int_distribution<int> x_dist(0, activeArray[2] - 1);
+    std::uniform_int_distribution<int> y_dist(0, activeArray[3] - 1);
 
     std::vector<int32_t> randCoords(coordCount * 2);
 
@@ -186,12 +213,12 @@
     auto origCoords = randCoords;
 
     base::Timer correctedToRawTimer;
-    res = m.mapCorrectedToRaw(randCoords.data(), randCoords.size() / 2);
+    res = m.mapCorrectedToRaw(randCoords.data(), randCoords.size() / 2, clamp, simple);
     auto correctedToRawDurationMs = correctedToRawTimer.duration();
     EXPECT_EQ(res, OK);
 
     base::Timer rawToCorrectedTimer;
-    res = m.mapRawToCorrected(randCoords.data(), randCoords.size() / 2);
+    res = m.mapRawToCorrected(randCoords.data(), randCoords.size() / 2, clamp, simple);
     auto rawToCorrectedDurationMs = rawToCorrectedTimer.duration();
     EXPECT_EQ(res, OK);
 
@@ -202,9 +229,9 @@
             (std::chrono::duration_cast<std::chrono::duration<double, std::micro>>(
                 rawToCorrectedDurationMs) / (randCoords.size() / 2) ).count();
 
-    RecordProperty("CorrectedToRawDurationPerCoordUs",
+    test->RecordProperty("CorrectedToRawDurationPerCoordUs",
             base::StringPrintf("%f", correctedToRawDurationPerCoordUs));
-    RecordProperty("RawToCorrectedDurationPerCoordUs",
+    test->RecordProperty("RawToCorrectedDurationPerCoordUs",
             base::StringPrintf("%f", rawToCorrectedDurationPerCoordUs));
 
     // Calculate mapping errors after round trip
@@ -239,17 +266,61 @@
     }
 
     float rmsError = std::sqrt(totalErrorSq / randCoords.size());
-    RecordProperty("RmsError", base::StringPrintf("%f", rmsError));
+    test->RecordProperty("RmsError", base::StringPrintf("%f", rmsError));
     for (size_t i = 0; i < histogram.size(); i++) {
         std::string label = base::StringPrintf("HistogramBin[%f,%f)",
                 (float)i/bucketsPerPixel, (float)(i + 1)/bucketsPerPixel);
-        RecordProperty(label, histogram[i]);
+        test->RecordProperty(label, histogram[i]);
     }
-    RecordProperty("HistogramOutOfRange", outOfHistogram);
+    test->RecordProperty("HistogramOutOfRange", outOfHistogram);
+}
+
+// Test a realistic distortion function with matching calibration values, enforcing
+// clamping.
+TEST(DistortionMapperTest, DISABLED_SmallTransform) {
+    int32_t activeArray[] = {0, 8, 3278, 2450};
+    int32_t preCorrectionActiveArray[] = {0, 0, 3280, 2464};
+
+    float distortion[] = {0.06875723, -0.13922249, 0.02818312, -0.00032781, -0.00025431};
+    float intrinsics[] = {1812.50000000, 1812.50000000, 1645.59533691, 1229.23229980, 0.00000000};
+
+    DistortionMapper m;
+    setupTestMapper(&m, distortion, intrinsics, activeArray, preCorrectionActiveArray);
+
+    RandomTransformTest(this, activeArray, m, /*clamp*/true, /*simple*/false);
+}
+
+// Test a realistic distortion function with matching calibration values, enforcing
+// clamping, but using the simple linear transform
+TEST(DistortionMapperTest, SmallSimpleTransform) {
+    int32_t activeArray[] = {0, 8, 3278, 2450};
+    int32_t preCorrectionActiveArray[] = {0, 0, 3280, 2464};
+
+    float distortion[] = {0.06875723, -0.13922249, 0.02818312, -0.00032781, -0.00025431};
+    float intrinsics[] = {1812.50000000, 1812.50000000, 1645.59533691, 1229.23229980, 0.00000000};
+
+    DistortionMapper m;
+    setupTestMapper(&m, distortion, intrinsics, activeArray, preCorrectionActiveArray);
+
+    RandomTransformTest(this, activeArray, m, /*clamp*/true, /*simple*/true);
+}
+
+// Test a very large distortion function; the regions aren't valid for such a big transform,
+// so disable clamping.  This test is just to verify round-trip math accuracy for big transforms
+TEST(DistortionMapperTest, LargeTransform) {
+    float bigDistortion[] = {0.1, -0.003, 0.004, 0.02, 0.01};
+
+    DistortionMapper m;
+    setupTestMapper(&m, bigDistortion, testICal,
+            /*activeArray*/testActiveArray,
+            /*preCorrectionActiveArray*/testPreCorrActiveArray);
+
+    RandomTransformTest(this, testActiveArray, m, /*clamp*/false, /*simple*/false);
 }
 
 // Compare against values calculated by OpenCV
 // undistortPoints() method, which is the same as mapRawToCorrected
+// Ignore clamping
 // See script DistortionMapperComp.py
 #include "DistortionMapperTest_OpenCvData.h"
 
@@ -262,11 +333,14 @@
     const int32_t maxSqError = 2;
 
     DistortionMapper m;
-    setupTestMapper(&m, bigDistortion);
+    setupTestMapper(&m, bigDistortion, testICal,
+            /*activeArray*/testActiveArray,
+            /*preCorrectionActiveArray*/testActiveArray);
 
     using namespace openCvData;
 
-    res = m.mapRawToCorrected(rawCoords.data(), rawCoords.size() / 2);
+    res = m.mapRawToCorrected(rawCoords.data(), rawCoords.size() / 2, /*clamp*/false,
+            /*simple*/false);
 
     for (size_t i = 0; i < rawCoords.size(); i+=2) {
         int32_t dist = (rawCoords[i] - expCoords[i]) * (rawCoords[i] - expCoords[i]) +