Merge "Parse mp3 encoder padding/delay"
diff --git a/camera/Camera.cpp b/camera/Camera.cpp
index d43cb0b..b81fe86 100644
--- a/camera/Camera.cpp
+++ b/camera/Camera.cpp
@@ -116,13 +116,13 @@
     return cs->getCameraInfo(cameraId, cameraInfo);
 }
 
-sp<Camera> Camera::connect(int cameraId)
+sp<Camera> Camera::connect(int cameraId, bool force, bool keep)
 {
     ALOGV("connect");
     sp<Camera> c = new Camera();
     const sp<ICameraService>& cs = getCameraService();
     if (cs != 0) {
-        c->mCamera = cs->connect(c, cameraId);
+        c->mCamera = cs->connect(c, cameraId, force, keep);
     }
     if (c->mCamera != 0) {
         c->mCamera->asBinder()->linkToDeath(c);
diff --git a/camera/ICameraService.cpp b/camera/ICameraService.cpp
index 85f1a29..c74298a 100644
--- a/camera/ICameraService.cpp
+++ b/camera/ICameraService.cpp
@@ -56,12 +56,15 @@
     }
 
     // connect to camera service
-    virtual sp<ICamera> connect(const sp<ICameraClient>& cameraClient, int cameraId)
+    virtual sp<ICamera> connect(const sp<ICameraClient>& cameraClient, int cameraId,
+                                bool force, bool keep)
     {
         Parcel data, reply;
         data.writeInterfaceToken(ICameraService::getInterfaceDescriptor());
         data.writeStrongBinder(cameraClient->asBinder());
         data.writeInt32(cameraId);
+        data.writeInt32(force);
+        data.writeInt32(keep);
         remote()->transact(BnCameraService::CONNECT, data, &reply);
         return interface_cast<ICamera>(reply.readStrongBinder());
     }
@@ -93,7 +96,10 @@
         case CONNECT: {
             CHECK_INTERFACE(ICameraService, data, reply);
             sp<ICameraClient> cameraClient = interface_cast<ICameraClient>(data.readStrongBinder());
-            sp<ICamera> camera = connect(cameraClient, data.readInt32());
+            const int cameraId = data.readInt32();
+            const int force = data.readInt32();
+            const int keep = data.readInt32();
+            sp<ICamera> camera = connect(cameraClient, cameraId, force, keep);
             reply->writeStrongBinder(camera->asBinder());
             return NO_ERROR;
         } break;
@@ -105,4 +111,3 @@
 // ----------------------------------------------------------------------------
 
 }; // namespace android
-
diff --git a/cmds/stagefright/Android.mk b/cmds/stagefright/Android.mk
index e41b666..30be7fa 100644
--- a/cmds/stagefright/Android.mk
+++ b/cmds/stagefright/Android.mk
@@ -7,7 +7,7 @@
 	SineSource.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libstagefright libmedia libutils libbinder libstagefright_foundation \
+	libstagefright libmedia libmedia_native libutils libbinder libstagefright_foundation \
         libskia libgui
 
 LOCAL_C_INCLUDES:= \
@@ -108,7 +108,7 @@
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libgui \
-        libstagefright_foundation libmedia
+        libstagefright_foundation libmedia libmedia_native
 
 LOCAL_C_INCLUDES:= \
 	$(JNI_H_INCLUDE) \
@@ -132,7 +132,7 @@
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libstagefright_foundation \
-        libmedia libgui libcutils libui
+        libmedia libmedia_native libgui libcutils libui
 
 LOCAL_C_INCLUDES:= \
 	$(JNI_H_INCLUDE) \
@@ -157,7 +157,7 @@
 
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright liblog libutils libbinder libstagefright_foundation \
-        libmedia libgui libcutils libui
+        libmedia libmedia_native libgui libcutils libui
 
 LOCAL_C_INCLUDES:= \
 	$(JNI_H_INCLUDE) \
diff --git a/cmds/stagefright/SimplePlayer.cpp b/cmds/stagefright/SimplePlayer.cpp
index fac3a8c..0cfeb3e 100644
--- a/cmds/stagefright/SimplePlayer.cpp
+++ b/cmds/stagefright/SimplePlayer.cpp
@@ -583,8 +583,7 @@
                 AUDIO_STREAM_MUSIC,
                 sampleRate,
                 AUDIO_FORMAT_PCM_16_BIT,
-                (channelCount == 1)
-                    ? AUDIO_CHANNEL_OUT_MONO : AUDIO_CHANNEL_OUT_STEREO,
+                audio_channel_out_mask_from_count(channelCount),
                 0);
 
         state->mNumFramesWritten = 0;
diff --git a/cmds/stagefright/audioloop.cpp b/cmds/stagefright/audioloop.cpp
index a6362a4..ed7d6cb 100644
--- a/cmds/stagefright/audioloop.cpp
+++ b/cmds/stagefright/audioloop.cpp
@@ -32,9 +32,7 @@
     sp<MediaSource> source = new AudioSource(
             AUDIO_SOURCE_DEFAULT,
             kSampleRate,
-            kNumChannels == 1
-                ? AUDIO_CHANNEL_IN_MONO
-                : AUDIO_CHANNEL_IN_STEREO);
+            audio_channel_in_mask_from_count(kNumChannels));
 #endif
 
     sp<MetaData> meta = new MetaData;
diff --git a/cmds/stagefright/sf2.cpp b/cmds/stagefright/sf2.cpp
index 1d28793..e47cdc0 100644
--- a/cmds/stagefright/sf2.cpp
+++ b/cmds/stagefright/sf2.cpp
@@ -14,6 +14,10 @@
  * limitations under the License.
  */
 
+//#define LOG_NDEBUG 0
+#define LOG_TAG "sf2"
+#include <utils/Log.h>
+
 #include <binder/ProcessState.h>
 
 #include <media/stagefright/foundation/hexdump.h>
@@ -205,6 +209,12 @@
                     }
 
                     looper()->stop();
+                } else if (what == ACodec::kWhatError) {
+                    ALOGE("something went wrong, codec reported an error.");
+
+                    printf("E\n");
+
+                    (new AMessage(kWhatStop, id()))->post();
                 }
                 break;
             }
diff --git a/include/camera/Camera.h b/include/camera/Camera.h
index 234e165..3fedea0 100644
--- a/include/camera/Camera.h
+++ b/include/camera/Camera.h
@@ -72,7 +72,7 @@
     static  int32_t     getNumberOfCameras();
     static  status_t    getCameraInfo(int cameraId,
                                       struct CameraInfo* cameraInfo);
-    static  sp<Camera>  connect(int cameraId);
+    static  sp<Camera>  connect(int cameraId, bool force, bool keep);
             virtual     ~Camera();
             void        init();
 
diff --git a/include/camera/CameraParameters.h b/include/camera/CameraParameters.h
deleted file mode 100644
index 7edf6b4..0000000
--- a/include/camera/CameraParameters.h
+++ /dev/null
@@ -1,666 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_HARDWARE_CAMERA_PARAMETERS_H
-#define ANDROID_HARDWARE_CAMERA_PARAMETERS_H
-
-#include <utils/KeyedVector.h>
-#include <utils/String8.h>
-
-namespace android {
-
-struct Size {
-    int width;
-    int height;
-
-    Size() {
-        width = 0;
-        height = 0;
-    }
-
-    Size(int w, int h) {
-        width = w;
-        height = h;
-    }
-};
-
-class CameraParameters
-{
-public:
-    CameraParameters();
-    CameraParameters(const String8 &params) { unflatten(params); }
-    ~CameraParameters();
-
-    String8 flatten() const;
-    void unflatten(const String8 &params);
-
-    void set(const char *key, const char *value);
-    void set(const char *key, int value);
-    void setFloat(const char *key, float value);
-    const char *get(const char *key) const;
-    int getInt(const char *key) const;
-    float getFloat(const char *key) const;
-
-    void remove(const char *key);
-
-    void setPreviewSize(int width, int height);
-    void getPreviewSize(int *width, int *height) const;
-    void getSupportedPreviewSizes(Vector<Size> &sizes) const;
-
-    // Set the dimensions in pixels to the given width and height
-    // for video frames. The given width and height must be one
-    // of the supported dimensions returned from
-    // getSupportedVideoSizes(). Must not be called if
-    // getSupportedVideoSizes() returns an empty Vector of Size.
-    void setVideoSize(int width, int height);
-    // Retrieve the current dimensions (width and height)
-    // in pixels for video frames, which must be one of the
-    // supported dimensions returned from getSupportedVideoSizes().
-    // Must not be called if getSupportedVideoSizes() returns an
-    // empty Vector of Size.
-    void getVideoSize(int *width, int *height) const;
-    // Retrieve a Vector of supported dimensions (width and height)
-    // in pixels for video frames. If sizes returned from the method
-    // is empty, the camera does not support calls to setVideoSize()
-    // or getVideoSize(). In adddition, it also indicates that
-    // the camera only has a single output, and does not have
-    // separate output for video frames and preview frame.
-    void getSupportedVideoSizes(Vector<Size> &sizes) const;
-    // Retrieve the preferred preview size (width and height) in pixels
-    // for video recording. The given width and height must be one of
-    // supported preview sizes returned from getSupportedPreviewSizes().
-    // Must not be called if getSupportedVideoSizes() returns an empty
-    // Vector of Size. If getSupportedVideoSizes() returns an empty
-    // Vector of Size, the width and height returned from this method
-    // is invalid, and is "-1x-1".
-    void getPreferredPreviewSizeForVideo(int *width, int *height) const;
-
-    void setPreviewFrameRate(int fps);
-    int getPreviewFrameRate() const;
-    void getPreviewFpsRange(int *min_fps, int *max_fps) const;
-    void setPreviewFormat(const char *format);
-    const char *getPreviewFormat() const;
-    void setPictureSize(int width, int height);
-    void getPictureSize(int *width, int *height) const;
-    void getSupportedPictureSizes(Vector<Size> &sizes) const;
-    void setPictureFormat(const char *format);
-    const char *getPictureFormat() const;
-
-    void dump() const;
-    status_t dump(int fd, const Vector<String16>& args) const;
-
-    // Parameter keys to communicate between camera application and driver.
-    // The access (read/write, read only, or write only) is viewed from the
-    // perspective of applications, not driver.
-
-    // Preview frame size in pixels (width x height).
-    // Example value: "480x320". Read/Write.
-    static const char KEY_PREVIEW_SIZE[];
-    // Supported preview frame sizes in pixels.
-    // Example value: "800x600,480x320". Read only.
-    static const char KEY_SUPPORTED_PREVIEW_SIZES[];
-    // The current minimum and maximum preview fps. This controls the rate of
-    // preview frames received (CAMERA_MSG_PREVIEW_FRAME). The minimum and
-    // maximum fps must be one of the elements from
-    // KEY_SUPPORTED_PREVIEW_FPS_RANGE parameter.
-    // Example value: "10500,26623"
-    static const char KEY_PREVIEW_FPS_RANGE[];
-    // The supported preview fps (frame-per-second) ranges. Each range contains
-    // a minimum fps and maximum fps. If minimum fps equals to maximum fps, the
-    // camera outputs frames in fixed frame rate. If not, the camera outputs
-    // frames in auto frame rate. The actual frame rate fluctuates between the
-    // minimum and the maximum. The list has at least one element. The list is
-    // sorted from small to large (first by maximum fps and then minimum fps).
-    // Example value: "(10500,26623),(15000,26623),(30000,30000)"
-    static const char KEY_SUPPORTED_PREVIEW_FPS_RANGE[];
-    // The image format for preview frames. See CAMERA_MSG_PREVIEW_FRAME in
-    // frameworks/base/include/camera/Camera.h.
-    // Example value: "yuv420sp" or PIXEL_FORMAT_XXX constants. Read/write.
-    static const char KEY_PREVIEW_FORMAT[];
-    // Supported image formats for preview frames.
-    // Example value: "yuv420sp,yuv422i-yuyv". Read only.
-    static const char KEY_SUPPORTED_PREVIEW_FORMATS[];
-    // Number of preview frames per second. This is the target frame rate. The
-    // actual frame rate depends on the driver.
-    // Example value: "15". Read/write.
-    static const char KEY_PREVIEW_FRAME_RATE[];
-    // Supported number of preview frames per second.
-    // Example value: "24,15,10". Read.
-    static const char KEY_SUPPORTED_PREVIEW_FRAME_RATES[];
-    // The dimensions for captured pictures in pixels (width x height).
-    // Example value: "1024x768". Read/write.
-    static const char KEY_PICTURE_SIZE[];
-    // Supported dimensions for captured pictures in pixels.
-    // Example value: "2048x1536,1024x768". Read only.
-    static const char KEY_SUPPORTED_PICTURE_SIZES[];
-    // The image format for captured pictures. See CAMERA_MSG_COMPRESSED_IMAGE
-    // in frameworks/base/include/camera/Camera.h.
-    // Example value: "jpeg" or PIXEL_FORMAT_XXX constants. Read/write.
-    static const char KEY_PICTURE_FORMAT[];
-    // Supported image formats for captured pictures.
-    // Example value: "jpeg,rgb565". Read only.
-    static const char KEY_SUPPORTED_PICTURE_FORMATS[];
-    // The width (in pixels) of EXIF thumbnail in Jpeg picture.
-    // Example value: "512". Read/write.
-    static const char KEY_JPEG_THUMBNAIL_WIDTH[];
-    // The height (in pixels) of EXIF thumbnail in Jpeg picture.
-    // Example value: "384". Read/write.
-    static const char KEY_JPEG_THUMBNAIL_HEIGHT[];
-    // Supported EXIF thumbnail sizes (width x height). 0x0 means not thumbnail
-    // in EXIF.
-    // Example value: "512x384,320x240,0x0". Read only.
-    static const char KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES[];
-    // The quality of the EXIF thumbnail in Jpeg picture. The range is 1 to 100,
-    // with 100 being the best.
-    // Example value: "90". Read/write.
-    static const char KEY_JPEG_THUMBNAIL_QUALITY[];
-    // Jpeg quality of captured picture. The range is 1 to 100, with 100 being
-    // the best.
-    // Example value: "90". Read/write.
-    static const char KEY_JPEG_QUALITY[];
-    // The rotation angle in degrees relative to the orientation of the camera.
-    // This affects the pictures returned from CAMERA_MSG_COMPRESSED_IMAGE. The
-    // camera driver may set orientation in the EXIF header without rotating the
-    // picture. Or the driver may rotate the picture and the EXIF thumbnail. If
-    // the Jpeg picture is rotated, the orientation in the EXIF header will be
-    // missing or 1 (row #0 is top and column #0 is left side).
-    //
-    // Note that the JPEG pictures of front-facing cameras are not mirrored
-    // as in preview display.
-    //
-    // For example, suppose the natural orientation of the device is portrait.
-    // The device is rotated 270 degrees clockwise, so the device orientation is
-    // 270. Suppose a back-facing camera sensor is mounted in landscape and the
-    // top side of the camera sensor is aligned with the right edge of the
-    // display in natural orientation. So the camera orientation is 90. The
-    // rotation should be set to 0 (270 + 90).
-    //
-    // Example value: "0" or "90" or "180" or "270". Write only.
-    static const char KEY_ROTATION[];
-    // GPS latitude coordinate. GPSLatitude and GPSLatitudeRef will be stored in
-    // JPEG EXIF header.
-    // Example value: "25.032146" or "-33.462809". Write only.
-    static const char KEY_GPS_LATITUDE[];
-    // GPS longitude coordinate. GPSLongitude and GPSLongitudeRef will be stored
-    // in JPEG EXIF header.
-    // Example value: "121.564448" or "-70.660286". Write only.
-    static const char KEY_GPS_LONGITUDE[];
-    // GPS altitude. GPSAltitude and GPSAltitudeRef will be stored in JPEG EXIF
-    // header.
-    // Example value: "21.0" or "-5". Write only.
-    static const char KEY_GPS_ALTITUDE[];
-    // GPS timestamp (UTC in seconds since January 1, 1970). This should be
-    // stored in JPEG EXIF header.
-    // Example value: "1251192757". Write only.
-    static const char KEY_GPS_TIMESTAMP[];
-    // GPS Processing Method
-    // Example value: "GPS" or "NETWORK". Write only.
-    static const char KEY_GPS_PROCESSING_METHOD[];
-    // Current white balance setting.
-    // Example value: "auto" or WHITE_BALANCE_XXX constants. Read/write.
-    static const char KEY_WHITE_BALANCE[];
-    // Supported white balance settings.
-    // Example value: "auto,incandescent,daylight". Read only.
-    static const char KEY_SUPPORTED_WHITE_BALANCE[];
-    // Current color effect setting.
-    // Example value: "none" or EFFECT_XXX constants. Read/write.
-    static const char KEY_EFFECT[];
-    // Supported color effect settings.
-    // Example value: "none,mono,sepia". Read only.
-    static const char KEY_SUPPORTED_EFFECTS[];
-    // Current antibanding setting.
-    // Example value: "auto" or ANTIBANDING_XXX constants. Read/write.
-    static const char KEY_ANTIBANDING[];
-    // Supported antibanding settings.
-    // Example value: "auto,50hz,60hz,off". Read only.
-    static const char KEY_SUPPORTED_ANTIBANDING[];
-    // Current scene mode.
-    // Example value: "auto" or SCENE_MODE_XXX constants. Read/write.
-    static const char KEY_SCENE_MODE[];
-    // Supported scene mode settings.
-    // Example value: "auto,night,fireworks". Read only.
-    static const char KEY_SUPPORTED_SCENE_MODES[];
-    // Current flash mode.
-    // Example value: "auto" or FLASH_MODE_XXX constants. Read/write.
-    static const char KEY_FLASH_MODE[];
-    // Supported flash modes.
-    // Example value: "auto,on,off". Read only.
-    static const char KEY_SUPPORTED_FLASH_MODES[];
-    // Current focus mode. This will not be empty. Applications should call
-    // CameraHardwareInterface.autoFocus to start the focus if focus mode is
-    // FOCUS_MODE_AUTO or FOCUS_MODE_MACRO.
-    // Example value: "auto" or FOCUS_MODE_XXX constants. Read/write.
-    static const char KEY_FOCUS_MODE[];
-    // Supported focus modes.
-    // Example value: "auto,macro,fixed". Read only.
-    static const char KEY_SUPPORTED_FOCUS_MODES[];
-    // The maximum number of focus areas supported. This is the maximum length
-    // of KEY_FOCUS_AREAS.
-    // Example value: "0" or "2". Read only.
-    static const char KEY_MAX_NUM_FOCUS_AREAS[];
-    // Current focus areas.
-    //
-    // Before accessing this parameter, apps should check
-    // KEY_MAX_NUM_FOCUS_AREAS first to know the maximum number of focus areas
-    // first. If the value is 0, focus area is not supported.
-    //
-    // Each focus area is a five-element int array. The first four elements are
-    // the rectangle of the area (left, top, right, bottom). The direction is
-    // relative to the sensor orientation, that is, what the sensor sees. The
-    // direction is not affected by the rotation or mirroring of
-    // CAMERA_CMD_SET_DISPLAY_ORIENTATION. Coordinates range from -1000 to 1000.
-    // (-1000,-1000) is the upper left point. (1000, 1000) is the lower right
-    // point. The width and height of focus areas cannot be 0 or negative.
-    //
-    // The fifth element is the weight. Values for weight must range from 1 to
-    // 1000.  The weight should be interpreted as a per-pixel weight - all
-    // pixels in the area have the specified weight. This means a small area
-    // with the same weight as a larger area will have less influence on the
-    // focusing than the larger area. Focus areas can partially overlap and the
-    // driver will add the weights in the overlap region.
-    //
-    // A special case of single focus area (0,0,0,0,0) means driver to decide
-    // the focus area. For example, the driver may use more signals to decide
-    // focus areas and change them dynamically. Apps can set (0,0,0,0,0) if they
-    // want the driver to decide focus areas.
-    //
-    // Focus areas are relative to the current field of view (KEY_ZOOM). No
-    // matter what the zoom level is, (-1000,-1000) represents the top of the
-    // currently visible camera frame. The focus area cannot be set to be
-    // outside the current field of view, even when using zoom.
-    //
-    // Focus area only has effect if the current focus mode is FOCUS_MODE_AUTO,
-    // FOCUS_MODE_MACRO, FOCUS_MODE_CONTINUOUS_VIDEO, or
-    // FOCUS_MODE_CONTINUOUS_PICTURE.
-    // Example value: "(-10,-10,0,0,300),(0,0,10,10,700)". Read/write.
-    static const char KEY_FOCUS_AREAS[];
-    // Focal length in millimeter.
-    // Example value: "4.31". Read only.
-    static const char KEY_FOCAL_LENGTH[];
-    // Horizontal angle of view in degrees.
-    // Example value: "54.8". Read only.
-    static const char KEY_HORIZONTAL_VIEW_ANGLE[];
-    // Vertical angle of view in degrees.
-    // Example value: "42.5". Read only.
-    static const char KEY_VERTICAL_VIEW_ANGLE[];
-    // Exposure compensation index. 0 means exposure is not adjusted.
-    // Example value: "0" or "5". Read/write.
-    static const char KEY_EXPOSURE_COMPENSATION[];
-    // The maximum exposure compensation index (>=0).
-    // Example value: "6". Read only.
-    static const char KEY_MAX_EXPOSURE_COMPENSATION[];
-    // The minimum exposure compensation index (<=0).
-    // Example value: "-6". Read only.
-    static const char KEY_MIN_EXPOSURE_COMPENSATION[];
-    // The exposure compensation step. Exposure compensation index multiply by
-    // step eqals to EV. Ex: if exposure compensation index is 6 and step is
-    // 0.3333, EV is -2.
-    // Example value: "0.333333333" or "0.5". Read only.
-    static const char KEY_EXPOSURE_COMPENSATION_STEP[];
-    // The state of the auto-exposure lock. "true" means that
-    // auto-exposure is locked to its current value and will not
-    // change. "false" means the auto-exposure routine is free to
-    // change exposure values. If auto-exposure is already locked,
-    // setting this to true again has no effect (the driver will not
-    // recalculate exposure values). Changing exposure compensation
-    // settings will still affect the exposure settings while
-    // auto-exposure is locked. Stopping preview or taking a still
-    // image will not change the lock. In conjunction with
-    // exposure compensation, this allows for capturing multi-exposure
-    // brackets with known relative exposure values. Locking
-    // auto-exposure after open but before the first call to
-    // startPreview may result in severely over- or under-exposed
-    // images.  The driver will not change the AE lock after
-    // auto-focus completes.
-    static const char KEY_AUTO_EXPOSURE_LOCK[];
-    // Whether locking the auto-exposure is supported. "true" means it is, and
-    // "false" or this key not existing means it is not supported.
-    static const char KEY_AUTO_EXPOSURE_LOCK_SUPPORTED[];
-    // The state of the auto-white balance lock. "true" means that
-    // auto-white balance is locked to its current value and will not
-    // change. "false" means the auto-white balance routine is free to
-    // change white balance values. If auto-white balance is already
-    // locked, setting this to true again has no effect (the driver
-    // will not recalculate white balance values). Stopping preview or
-    // taking a still image will not change the lock. In conjunction
-    // with exposure compensation, this allows for capturing
-    // multi-exposure brackets with fixed white balance. Locking
-    // auto-white balance after open but before the first call to
-    // startPreview may result in severely incorrect color.  The
-    // driver will not change the AWB lock after auto-focus
-    // completes.
-    static const char KEY_AUTO_WHITEBALANCE_LOCK[];
-    // Whether locking the auto-white balance is supported. "true"
-    // means it is, and "false" or this key not existing means it is
-    // not supported.
-    static const char KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED[];
-
-    // The maximum number of metering areas supported. This is the maximum
-    // length of KEY_METERING_AREAS.
-    // Example value: "0" or "2". Read only.
-    static const char KEY_MAX_NUM_METERING_AREAS[];
-    // Current metering areas. Camera driver uses these areas to decide
-    // exposure.
-    //
-    // Before accessing this parameter, apps should check
-    // KEY_MAX_NUM_METERING_AREAS first to know the maximum number of metering
-    // areas first. If the value is 0, metering area is not supported.
-    //
-    // Each metering area is a rectangle with specified weight. The direction is
-    // relative to the sensor orientation, that is, what the sensor sees. The
-    // direction is not affected by the rotation or mirroring of
-    // CAMERA_CMD_SET_DISPLAY_ORIENTATION. Coordinates of the rectangle range
-    // from -1000 to 1000. (-1000, -1000) is the upper left point. (1000, 1000)
-    // is the lower right point. The width and height of metering areas cannot
-    // be 0 or negative.
-    //
-    // The fifth element is the weight. Values for weight must range from 1 to
-    // 1000.  The weight should be interpreted as a per-pixel weight - all
-    // pixels in the area have the specified weight. This means a small area
-    // with the same weight as a larger area will have less influence on the
-    // metering than the larger area. Metering areas can partially overlap and
-    // the driver will add the weights in the overlap region.
-    //
-    // A special case of all-zero single metering area means driver to decide
-    // the metering area. For example, the driver may use more signals to decide
-    // metering areas and change them dynamically. Apps can set all-zero if they
-    // want the driver to decide metering areas.
-    //
-    // Metering areas are relative to the current field of view (KEY_ZOOM).
-    // No matter what the zoom level is, (-1000,-1000) represents the top of the
-    // currently visible camera frame. The metering area cannot be set to be
-    // outside the current field of view, even when using zoom.
-    //
-    // No matter what metering areas are, the final exposure are compensated
-    // by KEY_EXPOSURE_COMPENSATION.
-    // Example value: "(-10,-10,0,0,300),(0,0,10,10,700)". Read/write.
-    static const char KEY_METERING_AREAS[];
-    // Current zoom value.
-    // Example value: "0" or "6". Read/write.
-    static const char KEY_ZOOM[];
-    // Maximum zoom value.
-    // Example value: "6". Read only.
-    static const char KEY_MAX_ZOOM[];
-    // The zoom ratios of all zoom values. The zoom ratio is in 1/100
-    // increments. Ex: a zoom of 3.2x is returned as 320. The number of list
-    // elements is KEY_MAX_ZOOM + 1. The first element is always 100. The last
-    // element is the zoom ratio of zoom value KEY_MAX_ZOOM.
-    // Example value: "100,150,200,250,300,350,400". Read only.
-    static const char KEY_ZOOM_RATIOS[];
-    // Whether zoom is supported. Zoom is supported if the value is "true". Zoom
-    // is not supported if the value is not "true" or the key does not exist.
-    // Example value: "true". Read only.
-    static const char KEY_ZOOM_SUPPORTED[];
-    // Whether if smooth zoom is supported. Smooth zoom is supported if the
-    // value is "true". It is not supported if the value is not "true" or the
-    // key does not exist.
-    // See CAMERA_CMD_START_SMOOTH_ZOOM, CAMERA_CMD_STOP_SMOOTH_ZOOM, and
-    // CAMERA_MSG_ZOOM in frameworks/base/include/camera/Camera.h.
-    // Example value: "true". Read only.
-    static const char KEY_SMOOTH_ZOOM_SUPPORTED[];
-
-    // The distances (in meters) from the camera to where an object appears to
-    // be in focus. The object is sharpest at the optimal focus distance. The
-    // depth of field is the far focus distance minus near focus distance.
-    //
-    // Focus distances may change after starting auto focus, canceling auto
-    // focus, or starting the preview. Applications can read this anytime to get
-    // the latest focus distances. If the focus mode is FOCUS_MODE_CONTINUOUS,
-    // focus distances may change from time to time.
-    //
-    // This is intended to estimate the distance between the camera and the
-    // subject. After autofocus, the subject distance may be within near and far
-    // focus distance. However, the precision depends on the camera hardware,
-    // autofocus algorithm, the focus area, and the scene. The error can be
-    // large and it should be only used as a reference.
-    //
-    // Far focus distance > optimal focus distance > near focus distance. If
-    // the far focus distance is infinity, the value should be "Infinity" (case
-    // sensitive). The format is three float values separated by commas. The
-    // first is near focus distance. The second is optimal focus distance. The
-    // third is far focus distance.
-    // Example value: "0.95,1.9,Infinity" or "0.049,0.05,0.051". Read only.
-    static const char KEY_FOCUS_DISTANCES[];
-
-    // The current dimensions in pixels (width x height) for video frames.
-    // The width and height must be one of the supported sizes retrieved
-    // via KEY_SUPPORTED_VIDEO_SIZES.
-    // Example value: "1280x720". Read/write.
-    static const char KEY_VIDEO_SIZE[];
-    // A list of the supported dimensions in pixels (width x height)
-    // for video frames. See CAMERA_MSG_VIDEO_FRAME for details in
-    // frameworks/base/include/camera/Camera.h.
-    // Example: "176x144,1280x720". Read only.
-    static const char KEY_SUPPORTED_VIDEO_SIZES[];
-
-    // The maximum number of detected faces supported by hardware face
-    // detection. If the value is 0, hardware face detection is not supported.
-    // Example: "5". Read only
-    static const char KEY_MAX_NUM_DETECTED_FACES_HW[];
-
-    // The maximum number of detected faces supported by software face
-    // detection. If the value is 0, software face detection is not supported.
-    // Example: "5". Read only
-    static const char KEY_MAX_NUM_DETECTED_FACES_SW[];
-
-    // Preferred preview frame size in pixels for video recording.
-    // The width and height must be one of the supported sizes retrieved
-    // via KEY_SUPPORTED_PREVIEW_SIZES. This key can be used only when
-    // getSupportedVideoSizes() does not return an empty Vector of Size.
-    // Camcorder applications are recommended to set the preview size
-    // to a value that is not larger than the preferred preview size.
-    // In other words, the product of the width and height of the
-    // preview size should not be larger than that of the preferred
-    // preview size. In addition, we recommend to choos a preview size
-    // that has the same aspect ratio as the resolution of video to be
-    // recorded.
-    // Example value: "800x600". Read only.
-    static const char KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO[];
-
-    // The image format for video frames. See CAMERA_MSG_VIDEO_FRAME in
-    // frameworks/base/include/camera/Camera.h.
-    // Example value: "yuv420sp" or PIXEL_FORMAT_XXX constants. Read only.
-    static const char KEY_VIDEO_FRAME_FORMAT[];
-
-    // Sets the hint of the recording mode. If this is true, MediaRecorder.start
-    // may be faster or has less glitches. This should be called before starting
-    // the preview for the best result. But it is allowed to change the hint
-    // while the preview is active. The default value is false.
-    //
-    // The apps can still call Camera.takePicture when the hint is true. The
-    // apps can call MediaRecorder.start when the hint is false. But the
-    // performance may be worse.
-    // Example value: "true" or "false". Read/write.
-    static const char KEY_RECORDING_HINT[];
-
-    // Returns true if video snapshot is supported. That is, applications
-    // can call Camera.takePicture during recording. Applications do not need to
-    // call Camera.startPreview after taking a picture. The preview will be
-    // still active. Other than that, taking a picture during recording is
-    // identical to taking a picture normally. All settings and methods related
-    // to takePicture work identically. Ex: KEY_PICTURE_SIZE,
-    // KEY_SUPPORTED_PICTURE_SIZES, KEY_JPEG_QUALITY, KEY_ROTATION, and etc.
-    // The picture will have an EXIF header. FLASH_MODE_AUTO and FLASH_MODE_ON
-    // also still work, but the video will record the flash.
-    //
-    // Applications can set shutter callback as null to avoid the shutter
-    // sound. It is also recommended to set raw picture and post view callbacks
-    // to null to avoid the interrupt of preview display.
-    //
-    // Field-of-view of the recorded video may be different from that of the
-    // captured pictures.
-    // Example value: "true" or "false". Read only.
-    static const char KEY_VIDEO_SNAPSHOT_SUPPORTED[];
-
-    // The state of the video stabilization. If set to true, both the
-    // preview stream and the recorded video stream are stabilized by
-    // the camera. Only valid to set if KEY_VIDEO_STABILIZATION_SUPPORTED is
-    // set to true.
-    //
-    // The value of this key can be changed any time the camera is
-    // open. If preview or recording is active, it is acceptable for
-    // there to be a slight video glitch when video stabilization is
-    // toggled on and off.
-    //
-    // This only stabilizes video streams (between-frames stabilization), and
-    // has no effect on still image capture.
-    static const char KEY_VIDEO_STABILIZATION[];
-
-    // Returns true if video stabilization is supported. That is, applications
-    // can set KEY_VIDEO_STABILIZATION to true and have a stabilized preview
-    // stream and record stabilized videos.
-    static const char KEY_VIDEO_STABILIZATION_SUPPORTED[];
-
-    // Value for KEY_ZOOM_SUPPORTED or KEY_SMOOTH_ZOOM_SUPPORTED.
-    static const char TRUE[];
-    static const char FALSE[];
-
-    // Value for KEY_FOCUS_DISTANCES.
-    static const char FOCUS_DISTANCE_INFINITY[];
-
-    // Values for white balance settings.
-    static const char WHITE_BALANCE_AUTO[];
-    static const char WHITE_BALANCE_INCANDESCENT[];
-    static const char WHITE_BALANCE_FLUORESCENT[];
-    static const char WHITE_BALANCE_WARM_FLUORESCENT[];
-    static const char WHITE_BALANCE_DAYLIGHT[];
-    static const char WHITE_BALANCE_CLOUDY_DAYLIGHT[];
-    static const char WHITE_BALANCE_TWILIGHT[];
-    static const char WHITE_BALANCE_SHADE[];
-
-    // Values for effect settings.
-    static const char EFFECT_NONE[];
-    static const char EFFECT_MONO[];
-    static const char EFFECT_NEGATIVE[];
-    static const char EFFECT_SOLARIZE[];
-    static const char EFFECT_SEPIA[];
-    static const char EFFECT_POSTERIZE[];
-    static const char EFFECT_WHITEBOARD[];
-    static const char EFFECT_BLACKBOARD[];
-    static const char EFFECT_AQUA[];
-
-    // Values for antibanding settings.
-    static const char ANTIBANDING_AUTO[];
-    static const char ANTIBANDING_50HZ[];
-    static const char ANTIBANDING_60HZ[];
-    static const char ANTIBANDING_OFF[];
-
-    // Values for flash mode settings.
-    // Flash will not be fired.
-    static const char FLASH_MODE_OFF[];
-    // Flash will be fired automatically when required. The flash may be fired
-    // during preview, auto-focus, or snapshot depending on the driver.
-    static const char FLASH_MODE_AUTO[];
-    // Flash will always be fired during snapshot. The flash may also be
-    // fired during preview or auto-focus depending on the driver.
-    static const char FLASH_MODE_ON[];
-    // Flash will be fired in red-eye reduction mode.
-    static const char FLASH_MODE_RED_EYE[];
-    // Constant emission of light during preview, auto-focus and snapshot.
-    // This can also be used for video recording.
-    static const char FLASH_MODE_TORCH[];
-
-    // Values for scene mode settings.
-    static const char SCENE_MODE_AUTO[];
-    static const char SCENE_MODE_ACTION[];
-    static const char SCENE_MODE_PORTRAIT[];
-    static const char SCENE_MODE_LANDSCAPE[];
-    static const char SCENE_MODE_NIGHT[];
-    static const char SCENE_MODE_NIGHT_PORTRAIT[];
-    static const char SCENE_MODE_THEATRE[];
-    static const char SCENE_MODE_BEACH[];
-    static const char SCENE_MODE_SNOW[];
-    static const char SCENE_MODE_SUNSET[];
-    static const char SCENE_MODE_STEADYPHOTO[];
-    static const char SCENE_MODE_FIREWORKS[];
-    static const char SCENE_MODE_SPORTS[];
-    static const char SCENE_MODE_PARTY[];
-    static const char SCENE_MODE_CANDLELIGHT[];
-    // Applications are looking for a barcode. Camera driver will be optimized
-    // for barcode reading.
-    static const char SCENE_MODE_BARCODE[];
-
-    // Pixel color formats for KEY_PREVIEW_FORMAT, KEY_PICTURE_FORMAT,
-    // and KEY_VIDEO_FRAME_FORMAT
-    static const char PIXEL_FORMAT_YUV422SP[];
-    static const char PIXEL_FORMAT_YUV420SP[]; // NV21
-    static const char PIXEL_FORMAT_YUV422I[]; // YUY2
-    static const char PIXEL_FORMAT_YUV420P[]; // YV12
-    static const char PIXEL_FORMAT_RGB565[];
-    static const char PIXEL_FORMAT_RGBA8888[];
-    static const char PIXEL_FORMAT_JPEG[];
-    // Raw bayer format used for images, which is 10 bit precision samples
-    // stored in 16 bit words. The filter pattern is RGGB.
-    static const char PIXEL_FORMAT_BAYER_RGGB[];
-
-    // Values for focus mode settings.
-    // Auto-focus mode. Applications should call
-    // CameraHardwareInterface.autoFocus to start the focus in this mode.
-    static const char FOCUS_MODE_AUTO[];
-    // Focus is set at infinity. Applications should not call
-    // CameraHardwareInterface.autoFocus in this mode.
-    static const char FOCUS_MODE_INFINITY[];
-    // Macro (close-up) focus mode. Applications should call
-    // CameraHardwareInterface.autoFocus to start the focus in this mode.
-    static const char FOCUS_MODE_MACRO[];
-    // Focus is fixed. The camera is always in this mode if the focus is not
-    // adjustable. If the camera has auto-focus, this mode can fix the
-    // focus, which is usually at hyperfocal distance. Applications should
-    // not call CameraHardwareInterface.autoFocus in this mode.
-    static const char FOCUS_MODE_FIXED[];
-    // Extended depth of field (EDOF). Focusing is done digitally and
-    // continuously. Applications should not call
-    // CameraHardwareInterface.autoFocus in this mode.
-    static const char FOCUS_MODE_EDOF[];
-    // Continuous auto focus mode intended for video recording. The camera
-    // continuously tries to focus. This is the best choice for video
-    // recording because the focus changes smoothly . Applications still can
-    // call CameraHardwareInterface.takePicture in this mode but the subject may
-    // not be in focus. Auto focus starts when the parameter is set.
-    //
-    // Applications can call CameraHardwareInterface.autoFocus in this mode. The
-    // focus callback will immediately return with a boolean that indicates
-    // whether the focus is sharp or not. The focus position is locked after
-    // autoFocus call. If applications want to resume the continuous focus,
-    // cancelAutoFocus must be called. Restarting the preview will not resume
-    // the continuous autofocus. To stop continuous focus, applications should
-    // change the focus mode to other modes.
-    static const char FOCUS_MODE_CONTINUOUS_VIDEO[];
-    // Continuous auto focus mode intended for taking pictures. The camera
-    // continuously tries to focus. The speed of focus change is more aggressive
-    // than FOCUS_MODE_CONTINUOUS_VIDEO. Auto focus starts when the parameter is
-    // set.
-    //
-    // Applications can call CameraHardwareInterface.autoFocus in this mode. If
-    // the autofocus is in the middle of scanning, the focus callback will
-    // return when it completes. If the autofocus is not scanning, focus
-    // callback will immediately return with a boolean that indicates whether
-    // the focus is sharp or not. The apps can then decide if they want to take
-    // a picture immediately or to change the focus mode to auto, and run a full
-    // autofocus cycle. The focus position is locked after autoFocus call. If
-    // applications want to resume the continuous focus, cancelAutoFocus must be
-    // called. Restarting the preview will not resume the continuous autofocus.
-    // To stop continuous focus, applications should change the focus mode to
-    // other modes.
-    static const char FOCUS_MODE_CONTINUOUS_PICTURE[];
-
-private:
-    DefaultKeyedVector<String8,String8>    mMap;
-};
-
-}; // namespace android
-
-#endif
diff --git a/include/camera/ICameraService.h b/include/camera/ICameraService.h
index 7d70c1e..97e3169 100644
--- a/include/camera/ICameraService.h
+++ b/include/camera/ICameraService.h
@@ -42,7 +42,7 @@
     virtual status_t        getCameraInfo(int cameraId,
                                           struct CameraInfo* cameraInfo) = 0;
     virtual sp<ICamera>     connect(const sp<ICameraClient>& cameraClient,
-                                    int cameraId) = 0;
+                                    int cameraId, bool force, bool keep) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/media/mediaplayer.h b/include/media/mediaplayer.h
index 662dd13..a68ab4e 100644
--- a/include/media/mediaplayer.h
+++ b/include/media/mediaplayer.h
@@ -120,6 +120,9 @@
     MEDIA_INFO_NOT_SEEKABLE = 801,
     // New media metadata is available.
     MEDIA_INFO_METADATA_UPDATE = 802,
+
+    //9xx
+    MEDIA_INFO_TIMED_TEXT_ERROR = 900,
 };
 
 
@@ -140,9 +143,6 @@
 // The same enum space is used for both set and get, in case there are future keys that
 // can be both set and get.  But as of now, all parameters are either set only or get only.
 enum media_parameter_keys {
-    KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX = 1000,                // set only
-    KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE = 1001,     // set only
-
     // Streaming/buffering parameters
     KEY_PARAMETER_CACHE_STAT_COLLECT_FREQ_MS = 1100,            // set only
 
@@ -155,6 +155,23 @@
     KEY_PARAMETER_PLAYBACK_RATE_PERMILLE = 1300,                // set only
 };
 
+// Keep INVOKE_ID_* in sync with MediaPlayer.java.
+enum media_player_invoke_ids {
+    INVOKE_ID_GET_TRACK_INFO = 1,
+    INVOKE_ID_ADD_EXTERNAL_SOURCE = 2,
+    INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3,
+    INVOKE_ID_SELECT_TRACK = 4,
+    INVOKE_ID_UNSELECT_TRACK = 5,
+};
+
+// Keep MEDIA_TRACK_TYPE_* in sync with MediaPlayer.java.
+enum media_track_type {
+    MEDIA_TRACK_TYPE_UNKNOWN = 0,
+    MEDIA_TRACK_TYPE_VIDEO = 1,
+    MEDIA_TRACK_TYPE_AUDIO = 2,
+    MEDIA_TRACK_TYPE_TIMEDTEXT = 3,
+};
+
 // ----------------------------------------------------------------------------
 // ref-counted object for callbacks
 class MediaPlayerListener: virtual public RefBase
diff --git a/include/media/stagefright/MediaDefs.h b/include/media/stagefright/MediaDefs.h
index 2eb259e..457d5d7 100644
--- a/include/media/stagefright/MediaDefs.h
+++ b/include/media/stagefright/MediaDefs.h
@@ -54,6 +54,7 @@
 extern const char *MEDIA_MIMETYPE_CONTAINER_WVM;
 
 extern const char *MEDIA_MIMETYPE_TEXT_3GPP;
+extern const char *MEDIA_MIMETYPE_TEXT_SUBRIP;
 
 }  // namespace android
 
diff --git a/include/media/stagefright/timedtext/TimedTextDriver.h b/include/media/stagefright/timedtext/TimedTextDriver.h
index efedb6e..b9752df 100644
--- a/include/media/stagefright/timedtext/TimedTextDriver.h
+++ b/include/media/stagefright/timedtext/TimedTextDriver.h
@@ -37,26 +37,26 @@
 
     ~TimedTextDriver();
 
-    // TODO: pause-resume pair seems equivalent to stop-start pair.
-    // Check if it is replaceable with stop-start.
     status_t start();
-    status_t stop();
     status_t pause();
-    status_t resume();
+    status_t selectTrack(int32_t index);
+    status_t unselectTrack(int32_t index);
 
     status_t seekToAsync(int64_t timeUs);
 
     status_t addInBandTextSource(const sp<MediaSource>& source);
-    status_t addOutOfBandTextSource(const Parcel &request);
+    status_t addOutOfBandTextSource(const char *uri, const char *mimeType);
+    // Caller owns the file desriptor and caller is responsible for closing it.
+    status_t addOutOfBandTextSource(
+            int fd, off64_t offset, size_t length, const char *mimeType);
 
-    status_t setTimedTextTrackIndex(int32_t index);
+    void getTrackInfo(Parcel *parcel);
 
 private:
     Mutex mLock;
 
     enum State {
         UNINITIALIZED,
-        STOPPED,
         PLAYING,
         PAUSED,
     };
@@ -67,11 +67,11 @@
 
     // Variables to be guarded by mLock.
     State mState;
-    Vector<sp<TimedTextSource> > mTextInBandVector;
-    Vector<sp<TimedTextSource> > mTextOutOfBandVector;
+    int32_t mCurrentTrackIndex;
+    Vector<sp<TimedTextSource> > mTextSourceVector;
     // -- End of variables to be guarded by mLock
 
-    status_t setTimedTextTrackIndex_l(int32_t index);
+    status_t selectTrack_l(int32_t index);
 
     DISALLOW_EVIL_CONSTRUCTORS(TimedTextDriver);
 };
diff --git a/media/libaah_rtp/Android.mk b/media/libaah_rtp/Android.mk
index 1e87cf0..6c927ba 100644
--- a/media/libaah_rtp/Android.mk
+++ b/media/libaah_rtp/Android.mk
@@ -29,6 +29,7 @@
     libcommon_time_client \
     libbinder \
     libmedia \
+    libmedia_native \
     libstagefright \
     libstagefright_foundation \
     libutils
@@ -37,4 +38,3 @@
     -lpthread
 
 include $(BUILD_SHARED_LIBRARY)
-
diff --git a/media/libaah_rtp/aah_decoder_pump.cpp b/media/libaah_rtp/aah_decoder_pump.cpp
index 28b8c7b..bebba54 100644
--- a/media/libaah_rtp/aah_decoder_pump.cpp
+++ b/media/libaah_rtp/aah_decoder_pump.cpp
@@ -105,9 +105,8 @@
                 AudioTrack::getMinFrameCount(&frameCount,
                         AUDIO_STREAM_DEFAULT,
                         static_cast<int>(format_sample_rate_));
-                int ch_format = (format_channels_ == 1)
-                    ? AUDIO_CHANNEL_OUT_MONO
-                    : AUDIO_CHANNEL_OUT_STEREO;
+                audio_channel_mask_t ch_format =
+                        audio_channel_out_mask_from_count(format_channels_);
 
                 res = renderer_->set(AUDIO_STREAM_DEFAULT,
                         format_sample_rate_,
diff --git a/media/libaah_rtp/aah_decoder_pump.h b/media/libaah_rtp/aah_decoder_pump.h
index f5a6529..4d57e49 100644
--- a/media/libaah_rtp/aah_decoder_pump.h
+++ b/media/libaah_rtp/aah_decoder_pump.h
@@ -75,7 +75,7 @@
     void stopAndCleanupRenderer();
 
     sp<MetaData>        format_;
-    int32_t             format_channels_;
+    int32_t             format_channels_;   // channel count, not channel mask
     int32_t             format_sample_rate_;
 
     sp<MediaSource>     decoder_;
diff --git a/media/libeffects/downmix/Android.mk b/media/libeffects/downmix/Android.mk
index 0348e1e..95ca6fd 100644
--- a/media/libeffects/downmix/Android.mk
+++ b/media/libeffects/downmix/Android.mk
@@ -20,8 +20,8 @@
 endif
 
 LOCAL_C_INCLUDES := \
-	system/media/audio_effects/include \
-	system/media/audio_utils/include
+	$(call include-path-for, audio-effects) \
+	$(call include-path-for, audio-utils)
 
 LOCAL_PRELINK_MODULE := false
 
diff --git a/media/libeffects/factory/Android.mk b/media/libeffects/factory/Android.mk
index 2f2b974..6e69151 100644
--- a/media/libeffects/factory/Android.mk
+++ b/media/libeffects/factory/Android.mk
@@ -15,6 +15,6 @@
 LOCAL_SHARED_LIBRARIES += libdl
 
 LOCAL_C_INCLUDES := \
-    system/media/audio_effects/include
+    $(call include-path-for, audio-effects)
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libeffects/lvm/wrapper/Android.mk b/media/libeffects/lvm/wrapper/Android.mk
index f097dd0..4313424 100644
--- a/media/libeffects/lvm/wrapper/Android.mk
+++ b/media/libeffects/lvm/wrapper/Android.mk
@@ -26,7 +26,7 @@
 	$(LOCAL_PATH)/Bundle \
 	$(LOCAL_PATH)/../lib/Common/lib/ \
 	$(LOCAL_PATH)/../lib/Bundle/lib/ \
-	system/media/audio_effects/include
+	$(call include-path-for, audio-effects)
 
 
 include $(BUILD_SHARED_LIBRARY)
@@ -55,6 +55,6 @@
     $(LOCAL_PATH)/Reverb \
     $(LOCAL_PATH)/../lib/Common/lib/ \
     $(LOCAL_PATH)/../lib/Reverb/lib/ \
-    system/media/audio_effects/include
+    $(call include-path-for, audio-effects)
 
-include $(BUILD_SHARED_LIBRARY)
\ No newline at end of file
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libeffects/preprocessing/Android.mk b/media/libeffects/preprocessing/Android.mk
index 7f7c7e1..c13b9d4 100755
--- a/media/libeffects/preprocessing/Android.mk
+++ b/media/libeffects/preprocessing/Android.mk
@@ -14,7 +14,7 @@
     external/webrtc/src \
     external/webrtc/src/modules/interface \
     external/webrtc/src/modules/audio_processing/interface \
-    system/media/audio_effects/include
+    $(call include-path-for, audio-effects)
 
 LOCAL_C_INCLUDES += $(call include-path-for, speex)
 
diff --git a/media/libeffects/preprocessing/PreProcessing.cpp b/media/libeffects/preprocessing/PreProcessing.cpp
index dc27d38..1d76f62 100755
--- a/media/libeffects/preprocessing/PreProcessing.cpp
+++ b/media/libeffects/preprocessing/PreProcessing.cpp
@@ -956,10 +956,9 @@
     memset(config, 0, sizeof(effect_config_t));
     config->inputCfg.samplingRate = config->outputCfg.samplingRate = session->samplingRate;
     config->inputCfg.format = config->outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
-    config->inputCfg.channels = session->inChannelCount == 1 ?
-                                    AUDIO_CHANNEL_IN_MONO : AUDIO_CHANNEL_IN_STEREO;
-    config->outputCfg.channels = session->outChannelCount == 1 ?
-                                    AUDIO_CHANNEL_IN_MONO : AUDIO_CHANNEL_IN_STEREO;
+    config->inputCfg.channels = audio_channel_in_mask_from_count(session->inChannelCount);
+    // "out" doesn't mean output device, so this is the correct API to convert channel count to mask
+    config->outputCfg.channels = audio_channel_in_mask_from_count(session->outChannelCount);
     config->inputCfg.mask = config->outputCfg.mask =
             (EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT);
 }
@@ -999,7 +998,7 @@
     config->inputCfg.samplingRate = config->outputCfg.samplingRate = session->samplingRate;
     config->inputCfg.format = config->outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
     config->inputCfg.channels = config->outputCfg.channels =
-            session->revChannelCount == 1 ? AUDIO_CHANNEL_IN_MONO : AUDIO_CHANNEL_IN_STEREO;
+            audio_channel_in_mask_from_count(session->revChannelCount);
     config->inputCfg.mask = config->outputCfg.mask =
             (EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT);
 }
diff --git a/media/libeffects/testlibs/Android.mk_ b/media/libeffects/testlibs/Android.mk_
index 249ebf4..2954908 100644
--- a/media/libeffects/testlibs/Android.mk_
+++ b/media/libeffects/testlibs/Android.mk_
@@ -23,7 +23,7 @@
 endif
 
 LOCAL_C_INCLUDES := \
-	system/media/audio_effects/include \
+	$(call include-path-for, audio-effects) \
 	$(call include-path-for, graphics corecg)
 
 LOCAL_MODULE_TAGS := optional
@@ -60,7 +60,7 @@
 
 LOCAL_C_INCLUDES := \
 	$(call include-path-for, graphics corecg) \
-	system/media/audio_effects/include
+	$(call include-path-for, audio-effects)
 
 LOCAL_MODULE_TAGS := optional
 
diff --git a/media/libeffects/visualizer/Android.mk b/media/libeffects/visualizer/Android.mk
index 2160177..76b5110 100644
--- a/media/libeffects/visualizer/Android.mk
+++ b/media/libeffects/visualizer/Android.mk
@@ -17,7 +17,7 @@
 
 LOCAL_C_INCLUDES := \
 	$(call include-path-for, graphics corecg) \
-	system/media/audio_effects/include
+	$(call include-path-for, audio-effects)
 
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk
index 5ecc8f5..21e8f29 100644
--- a/media/libmedia/Android.mk
+++ b/media/libmedia/Android.mk
@@ -48,7 +48,7 @@
 LOCAL_SHARED_LIBRARIES := \
 	libui libcutils libutils libbinder libsonivox libicuuc libexpat \
         libcamera_client libstagefright_foundation \
-        libgui libdl libaudioutils
+        libgui libdl libaudioutils libmedia_native
 
 LOCAL_WHOLE_STATIC_LIBRARY := libmedia_helper
 
@@ -60,7 +60,7 @@
     $(TOP)/frameworks/native/include/media/openmax \
     external/icu4c/common \
     external/expat/lib \
-    system/media/audio_effects/include \
-    system/media/audio_utils/include
+    $(call include-path-for, audio-effects) \
+    $(call include-path-for, audio-utils)
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libmedia/JetPlayer.cpp b/media/libmedia/JetPlayer.cpp
index 312a493..f1f62f7 100644
--- a/media/libmedia/JetPlayer.cpp
+++ b/media/libmedia/JetPlayer.cpp
@@ -92,7 +92,7 @@
     mAudioTrack->set(AUDIO_STREAM_MUSIC,  //TODO parametrize this
             pLibConfig->sampleRate,
             AUDIO_FORMAT_PCM_16_BIT,
-            (pLibConfig->numChannels == 2) ? AUDIO_CHANNEL_OUT_STEREO : AUDIO_CHANNEL_OUT_MONO,
+            audio_channel_out_mask_from_count(pLibConfig->numChannels),
             mTrackBufferSize,
             AUDIO_POLICY_OUTPUT_FLAG_NONE);
 
diff --git a/media/libmedia_native/Android.mk b/media/libmedia_native/Android.mk
new file mode 100644
index 0000000..065a90f
--- /dev/null
+++ b/media/libmedia_native/Android.mk
@@ -0,0 +1,11 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES :=
+
+LOCAL_MODULE:= libmedia_native
+
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libmediaplayerservice/Android.mk b/media/libmediaplayerservice/Android.mk
index 41bcab0..ba5c776 100644
--- a/media/libmediaplayerservice/Android.mk
+++ b/media/libmediaplayerservice/Android.mk
@@ -23,6 +23,7 @@
 	libvorbisidec         			\
 	libsonivox            			\
 	libmedia              			\
+	libmedia_native       			\
 	libcamera_client      			\
 	libandroid_runtime    			\
 	libstagefright        			\
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 1cc120c..8f62ee4 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -1514,7 +1514,7 @@
     frameCount = (sampleRate*afFrameCount*bufferCount)/afSampleRate;
 
     if (channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER) {
-        channelMask = audio_channel_mask_from_count(channelCount);
+        channelMask = audio_channel_out_mask_from_count(channelCount);
         if (0 == channelMask) {
             ALOGE("open() error, can\'t derive mask for %d audio channels", channelCount);
             return NO_INIT;
diff --git a/media/libmediaplayerservice/StagefrightPlayer.cpp b/media/libmediaplayerservice/StagefrightPlayer.cpp
index 052ebf0..619c149 100644
--- a/media/libmediaplayerservice/StagefrightPlayer.cpp
+++ b/media/libmediaplayerservice/StagefrightPlayer.cpp
@@ -166,7 +166,8 @@
 }
 
 status_t StagefrightPlayer::invoke(const Parcel &request, Parcel *reply) {
-    return INVALID_OPERATION;
+    ALOGV("invoke()");
+    return mPlayer->invoke(request, reply);
 }
 
 void StagefrightPlayer::setAudioSink(const sp<AudioSink> &audioSink) {
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index 09e4e45..e5ad4b7 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -746,6 +746,10 @@
             "audio_decoder.aac", "audio_encoder.aac" },
         { MEDIA_MIMETYPE_AUDIO_VORBIS,
             "audio_decoder.vorbis", "audio_encoder.vorbis" },
+        { MEDIA_MIMETYPE_AUDIO_G711_MLAW,
+            "audio_decoder.g711mlaw", "audio_encoder.g711mlaw" },
+        { MEDIA_MIMETYPE_AUDIO_G711_ALAW,
+            "audio_decoder.g711alaw", "audio_encoder.g711alaw" },
         { MEDIA_MIMETYPE_VIDEO_AVC,
             "video_decoder.avc", "video_encoder.avc" },
         { MEDIA_MIMETYPE_VIDEO_MPEG4,
@@ -855,10 +859,6 @@
         }
     }
 
-    if (err != OK) {
-        return err;
-    }
-
     int32_t maxInputSize;
     if (msg->findInt32("max-input-size", &maxInputSize)) {
         err = setMinBufferSize(kPortIndexInput, (size_t)maxInputSize);
@@ -2770,6 +2770,9 @@
     status_t err = mCodec->configureCodec(mime.c_str(), msg);
 
     if (err != OK) {
+        ALOGE("[%s] configureCodec returning error %d",
+              mCodec->mComponentName.c_str(), err);
+
         mCodec->signalError(OMX_ErrorUndefined, err);
         return false;
     }
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index 047b4cb..77714f3 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -79,6 +79,7 @@
         libicuuc \
         liblog \
         libmedia \
+        libmedia_native \
         libsonivox \
         libssl \
         libstagefright_omx \
diff --git a/media/libstagefright/AudioPlayer.cpp b/media/libstagefright/AudioPlayer.cpp
index 9db3c97..0f816e7 100644
--- a/media/libstagefright/AudioPlayer.cpp
+++ b/media/libstagefright/AudioPlayer.cpp
@@ -144,7 +144,7 @@
     } else {
         // playing to an AudioTrack, set up mask if necessary
         audio_channel_mask_t audioMask = channelMask == CHANNEL_MASK_USE_CHANNEL_ORDER ?
-                audio_channel_mask_from_count(numChannels) : channelMask;
+                audio_channel_out_mask_from_count(numChannels) : channelMask;
         if (0 == audioMask) {
             return BAD_VALUE;
         }
diff --git a/media/libstagefright/AudioSource.cpp b/media/libstagefright/AudioSource.cpp
index cbe709b..0f1d841 100644
--- a/media/libstagefright/AudioSource.cpp
+++ b/media/libstagefright/AudioSource.cpp
@@ -47,22 +47,22 @@
 }
 
 AudioSource::AudioSource(
-        audio_source_t inputSource, uint32_t sampleRate, uint32_t channels)
+        audio_source_t inputSource, uint32_t sampleRate, uint32_t channelCount)
     : mStarted(false),
       mSampleRate(sampleRate),
       mPrevSampleTimeUs(0),
       mNumFramesReceived(0),
       mNumClientOwnedBuffers(0) {
 
-    ALOGV("sampleRate: %d, channels: %d", sampleRate, channels);
-    CHECK(channels == 1 || channels == 2);
+    ALOGV("sampleRate: %d, channelCount: %d", sampleRate, channelCount);
+    CHECK(channelCount == 1 || channelCount == 2);
     AudioRecord::record_flags flags = (AudioRecord::record_flags)
                     (AudioRecord::RECORD_AGC_ENABLE |
                      AudioRecord::RECORD_NS_ENABLE  |
                      AudioRecord::RECORD_IIR_ENABLE);
     mRecord = new AudioRecord(
                 inputSource, sampleRate, AUDIO_FORMAT_PCM_16_BIT,
-                channels > 1? AUDIO_CHANNEL_IN_STEREO: AUDIO_CHANNEL_IN_MONO,
+                audio_channel_in_mask_from_count(channelCount),
                 4 * kMaxBufferSize / sizeof(int16_t), /* Enable ping-pong buffers */
                 flags,
                 AudioRecordCallbackFunction,
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index 9e00bb3..f96a4df 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -1114,7 +1114,7 @@
         modifyFlags(AUDIO_RUNNING, CLEAR);
     }
 
-    if (mFlags & TEXTPLAYER_STARTED) {
+    if (mFlags & TEXTPLAYER_INITIALIZED) {
         mTextDriver->pause();
         modifyFlags(TEXT_RUNNING, CLEAR);
     }
@@ -1268,32 +1268,6 @@
     return OK;
 }
 
-status_t AwesomePlayer::setTimedTextTrackIndex(int32_t index) {
-    if (mTextDriver != NULL) {
-        if (index >= 0) { // to turn on a text track
-            status_t err = mTextDriver->setTimedTextTrackIndex(index);
-            if (err != OK) {
-                return err;
-            }
-
-            modifyFlags(TEXT_RUNNING, SET);
-            modifyFlags(TEXTPLAYER_STARTED, SET);
-            return OK;
-        } else { // to turn off the text track display
-            if (mFlags  & TEXT_RUNNING) {
-                modifyFlags(TEXT_RUNNING, CLEAR);
-            }
-            if (mFlags  & TEXTPLAYER_STARTED) {
-                modifyFlags(TEXTPLAYER_STARTED, CLEAR);
-            }
-
-            return mTextDriver->setTimedTextTrackIndex(index);
-        }
-    } else {
-        return INVALID_OPERATION;
-    }
-}
-
 status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
     if (mFlags & CACHE_UNDERRUN) {
         modifyFlags(CACHE_UNDERRUN, CLEAR);
@@ -1315,7 +1289,7 @@
 
     seekAudioIfNecessary_l();
 
-    if (mFlags & TEXTPLAYER_STARTED) {
+    if (mFlags & TEXTPLAYER_INITIALIZED) {
         mTextDriver->seekToAsync(mSeekTimeUs);
     }
 
@@ -1691,8 +1665,8 @@
         }
     }
 
-    if ((mFlags & TEXTPLAYER_STARTED) && !(mFlags & (TEXT_RUNNING | SEEK_PREVIEW))) {
-        mTextDriver->resume();
+    if ((mFlags & TEXTPLAYER_INITIALIZED) && !(mFlags & (TEXT_RUNNING | SEEK_PREVIEW))) {
+        mTextDriver->start();
         modifyFlags(TEXT_RUNNING, SET);
     }
 
@@ -2232,20 +2206,6 @@
 
 status_t AwesomePlayer::setParameter(int key, const Parcel &request) {
     switch (key) {
-        case KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX:
-        {
-            Mutex::Autolock autoLock(mTimedTextLock);
-            return setTimedTextTrackIndex(request.readInt32());
-        }
-        case KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE:
-        {
-            Mutex::Autolock autoLock(mTimedTextLock);
-            if (mTextDriver == NULL) {
-                mTextDriver = new TimedTextDriver(mListener);
-            }
-
-            return mTextDriver->addOutOfBandTextSource(request);
-        }
         case KEY_PARAMETER_CACHE_STAT_COLLECT_FREQ_MS:
         {
             return setCacheStatCollectFreq(request);
@@ -2294,6 +2254,90 @@
     }
 }
 
+status_t AwesomePlayer::invoke(const Parcel &request, Parcel *reply) {
+    if (NULL == reply) {
+        return android::BAD_VALUE;
+    }
+    int32_t methodId;
+    status_t ret = request.readInt32(&methodId);
+    if (ret != android::OK) {
+        return ret;
+    }
+    switch(methodId) {
+        case INVOKE_ID_GET_TRACK_INFO:
+        {
+            Mutex::Autolock autoLock(mTimedTextLock);
+            if (mTextDriver == NULL) {
+                return INVALID_OPERATION;
+            }
+            mTextDriver->getTrackInfo(reply);
+            return OK;
+        }
+        case INVOKE_ID_ADD_EXTERNAL_SOURCE:
+        {
+            Mutex::Autolock autoLock(mTimedTextLock);
+            if (mTextDriver == NULL) {
+                mTextDriver = new TimedTextDriver(mListener);
+            }
+            // String values written in Parcel are UTF-16 values.
+            String8 uri(request.readString16());
+            String8 mimeType(request.readString16());
+            return mTextDriver->addOutOfBandTextSource(uri, mimeType);
+        }
+        case INVOKE_ID_ADD_EXTERNAL_SOURCE_FD:
+        {
+            Mutex::Autolock autoLock(mTimedTextLock);
+            if (mTextDriver == NULL) {
+                mTextDriver = new TimedTextDriver(mListener);
+            }
+            int fd         = request.readFileDescriptor();
+            off64_t offset = request.readInt64();
+            size_t length  = request.readInt64();
+            String8 mimeType(request.readString16());
+            return mTextDriver->addOutOfBandTextSource(
+                    fd, offset, length, mimeType);
+        }
+        case INVOKE_ID_SELECT_TRACK:
+        {
+            Mutex::Autolock autoLock(mTimedTextLock);
+            if (mTextDriver == NULL) {
+                return INVALID_OPERATION;
+            }
+
+            status_t err = mTextDriver->selectTrack(
+                    request.readInt32());
+            if (err == OK) {
+                modifyFlags(TEXTPLAYER_INITIALIZED, SET);
+                if (mFlags & PLAYING && !(mFlags & TEXT_RUNNING)) {
+                    mTextDriver->start();
+                    modifyFlags(TEXT_RUNNING, SET);
+                }
+            }
+            return err;
+        }
+        case INVOKE_ID_UNSELECT_TRACK:
+        {
+            Mutex::Autolock autoLock(mTimedTextLock);
+            if (mTextDriver == NULL) {
+                return INVALID_OPERATION;
+            }
+            status_t err = mTextDriver->unselectTrack(
+                    request.readInt32());
+            if (err == OK) {
+                modifyFlags(TEXTPLAYER_INITIALIZED, CLEAR);
+                modifyFlags(TEXT_RUNNING, CLEAR);
+            }
+            return err;
+        }
+        default:
+        {
+            return ERROR_UNSUPPORTED;
+        }
+    }
+    // It will not reach here.
+    return OK;
+}
+
 bool AwesomePlayer::isStreamingHTTP() const {
     return mCachedSource != NULL || mWVMExtractor != NULL;
 }
diff --git a/media/libstagefright/CameraSource.cpp b/media/libstagefright/CameraSource.cpp
index 2df5528..fd3f892 100755
--- a/media/libstagefright/CameraSource.cpp
+++ b/media/libstagefright/CameraSource.cpp
@@ -182,7 +182,7 @@
     int32_t cameraId) {
 
     if (camera == 0) {
-        mCamera = Camera::connect(cameraId);
+        mCamera = Camera::connect(cameraId, false, false);
         if (mCamera == 0) return -EBUSY;
         mCameraFlags &= ~FLAGS_HOT_CAMERA;
     } else {
@@ -515,9 +515,13 @@
         return err;
     }
 
-    // This CHECK is good, since we just passed the lock/unlock
-    // check earlier by calling mCamera->setParameters().
-    CHECK_EQ((status_t)OK, mCamera->setPreviewDisplay(mSurface));
+    // Set the preview display. Skip this if mSurface is null because
+    // applications may already set a surface to the camera.
+    if (mSurface != NULL) {
+        // This CHECK is good, since we just passed the lock/unlock
+        // check earlier by calling mCamera->setParameters().
+        CHECK_EQ((status_t)OK, mCamera->setPreviewDisplay(mSurface));
+    }
 
     // By default, do not store metadata in video buffers
     mIsMetaDataStoredInVideoBuffers = false;
diff --git a/media/libstagefright/MediaDefs.cpp b/media/libstagefright/MediaDefs.cpp
index 444e823..2549de6 100644
--- a/media/libstagefright/MediaDefs.cpp
+++ b/media/libstagefright/MediaDefs.cpp
@@ -52,5 +52,6 @@
 const char *MEDIA_MIMETYPE_CONTAINER_WVM = "video/wvm";
 
 const char *MEDIA_MIMETYPE_TEXT_3GPP = "text/3gpp-tt";
+const char *MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
 
 }  // namespace android
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index 278e3a2..d5e6bec 100755
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -1332,8 +1332,6 @@
             "audio_decoder.mp1", "audio_encoder.mp1" },
         { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II,
             "audio_decoder.mp2", "audio_encoder.mp2" },
-        { MEDIA_MIMETYPE_AUDIO_MPEG,
-            "audio_decoder.mp3", "audio_encoder.mp3" },
         { MEDIA_MIMETYPE_AUDIO_AMR_NB,
             "audio_decoder.amrnb", "audio_encoder.amrnb" },
         { MEDIA_MIMETYPE_AUDIO_AMR_WB,
@@ -1342,6 +1340,10 @@
             "audio_decoder.aac", "audio_encoder.aac" },
         { MEDIA_MIMETYPE_AUDIO_VORBIS,
             "audio_decoder.vorbis", "audio_encoder.vorbis" },
+        { MEDIA_MIMETYPE_AUDIO_G711_MLAW,
+            "audio_decoder.g711mlaw", "audio_encoder.g711mlaw" },
+        { MEDIA_MIMETYPE_AUDIO_G711_ALAW,
+            "audio_decoder.g711alaw", "audio_encoder.g711alaw" },
         { MEDIA_MIMETYPE_VIDEO_AVC,
             "video_decoder.avc", "video_encoder.avc" },
         { MEDIA_MIMETYPE_VIDEO_MPEG4,
diff --git a/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp b/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
index 7602f2d..796caa4 100644
--- a/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
+++ b/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
@@ -236,6 +236,18 @@
             return OMX_ErrorNone;
         }
 
+        case OMX_IndexParamAudioPcm:
+        {
+            const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
+                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
+
+            if (pcmParams->nPortIndex != 1) {
+                return OMX_ErrorUndefined;
+            }
+
+            return OMX_ErrorNone;
+        }
+
         default:
             return SimpleSoftOMXComponent::internalSetParameter(index, params);
     }
diff --git a/media/libstagefright/codecs/amrnb/enc/AMRNBEncoder.cpp b/media/libstagefright/codecs/amrnb/enc/AMRNBEncoder.cpp
deleted file mode 100644
index 27d7e4d..0000000
--- a/media/libstagefright/codecs/amrnb/enc/AMRNBEncoder.cpp
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "AMRNBEncoder.h"
-
-#include "gsmamr_enc.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/MediaBufferGroup.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MetaData.h>
-
-namespace android {
-
-static const int32_t kNumSamplesPerFrame = 160;
-static const int32_t kSampleRate = 8000;
-
-AMRNBEncoder::AMRNBEncoder(const sp<MediaSource> &source, const sp<MetaData> &meta)
-    : mSource(source),
-      mMeta(meta),
-      mStarted(false),
-      mBufferGroup(NULL),
-      mEncState(NULL),
-      mSidState(NULL),
-      mAnchorTimeUs(0),
-      mNumFramesOutput(0),
-      mInputBuffer(NULL),
-      mMode(MR475),
-      mNumInputSamples(0) {
-}
-
-AMRNBEncoder::~AMRNBEncoder() {
-    if (mStarted) {
-        stop();
-    }
-}
-
-static Mode PickModeFromBitrate(int32_t bps) {
-    if (bps <= 4750) {
-        return MR475;
-    } else if (bps <= 5150) {
-        return MR515;
-    } else if (bps <= 5900) {
-        return MR59;
-    } else if (bps <= 6700) {
-        return MR67;
-    } else if (bps <= 7400) {
-        return MR74;
-    } else if (bps <= 7950) {
-        return MR795;
-    } else if (bps <= 10200) {
-        return MR102;
-    } else {
-        return MR122;
-    }
-}
-
-status_t AMRNBEncoder::start(MetaData *params) {
-    if (mStarted) {
-        ALOGW("Call start() when encoder already started");
-        return OK;
-    }
-
-    mBufferGroup = new MediaBufferGroup;
-    mBufferGroup->add_buffer(new MediaBuffer(32));
-
-    CHECK_EQ(AMREncodeInit(
-                &mEncState, &mSidState, false /* dtx_enable */),
-             0);
-
-    status_t err = mSource->start(params);
-    if (err != OK) {
-        ALOGE("AudioSource is not available");
-        return err;
-    }
-
-    mAnchorTimeUs = 0;
-    mNumFramesOutput = 0;
-    mStarted = true;
-    mNumInputSamples = 0;
-
-    int32_t bitrate;
-    if (params && params->findInt32(kKeyBitRate, &bitrate)) {
-        mMode = PickModeFromBitrate(bitrate);
-    } else {
-        mMode = MR475;
-    }
-
-    return OK;
-}
-
-status_t AMRNBEncoder::stop() {
-    if (!mStarted) {
-        ALOGW("Call stop() when encoder has not started.");
-        return OK;
-    }
-
-    if (mInputBuffer) {
-        mInputBuffer->release();
-        mInputBuffer = NULL;
-    }
-
-    delete mBufferGroup;
-    mBufferGroup = NULL;
-
-    mSource->stop();
-
-    AMREncodeExit(&mEncState, &mSidState);
-    mEncState = mSidState = NULL;
-
-    mStarted = false;
-
-    return OK;
-}
-
-sp<MetaData> AMRNBEncoder::getFormat() {
-    sp<MetaData> srcFormat = mSource->getFormat();
-
-    mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
-
-    int64_t durationUs;
-    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
-        mMeta->setInt64(kKeyDuration, durationUs);
-    }
-
-    mMeta->setCString(kKeyDecoderComponent, "AMRNBEncoder");
-
-    return mMeta;
-}
-
-status_t AMRNBEncoder::read(
-        MediaBuffer **out, const ReadOptions *options) {
-    status_t err;
-
-    *out = NULL;
-
-    int64_t seekTimeUs;
-    ReadOptions::SeekMode mode;
-    CHECK(options == NULL || !options->getSeekTo(&seekTimeUs, &mode));
-    bool readFromSource = false;
-    int64_t wallClockTimeUs = -1;
-
-    while (mNumInputSamples < kNumSamplesPerFrame) {
-        if (mInputBuffer == NULL) {
-            err = mSource->read(&mInputBuffer, options);
-
-            if (err != OK) {
-                if (mNumInputSamples == 0) {
-                    return ERROR_END_OF_STREAM;
-                }
-                memset(&mInputFrame[mNumInputSamples],
-                       0,
-                       sizeof(int16_t)
-                            * (kNumSamplesPerFrame - mNumInputSamples));
-                mNumInputSamples = kNumSamplesPerFrame;
-                break;
-            }
-
-            size_t align = mInputBuffer->range_length() % sizeof(int16_t);
-            CHECK_EQ(align, 0);
-            readFromSource = true;
-
-            int64_t timeUs;
-            if (mInputBuffer->meta_data()->findInt64(kKeyDriftTime, &timeUs)) {
-                wallClockTimeUs = timeUs;
-            }
-            if (mInputBuffer->meta_data()->findInt64(kKeyAnchorTime, &timeUs)) {
-                mAnchorTimeUs = timeUs;
-            }
-        } else {
-            readFromSource = false;
-        }
-
-        size_t copy =
-            (kNumSamplesPerFrame - mNumInputSamples) * sizeof(int16_t);
-
-        if (copy > mInputBuffer->range_length()) {
-            copy = mInputBuffer->range_length();
-        }
-
-        memcpy(&mInputFrame[mNumInputSamples],
-               (const uint8_t *)mInputBuffer->data()
-                    + mInputBuffer->range_offset(),
-               copy);
-
-        mNumInputSamples += copy / sizeof(int16_t);
-
-        mInputBuffer->set_range(
-                mInputBuffer->range_offset() + copy,
-                mInputBuffer->range_length() - copy);
-
-        if (mInputBuffer->range_length() == 0) {
-            mInputBuffer->release();
-            mInputBuffer = NULL;
-        }
-    }
-
-    MediaBuffer *buffer;
-    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), (status_t)OK);
-
-    uint8_t *outPtr = (uint8_t *)buffer->data();
-
-    Frame_Type_3GPP frameType;
-    int res = AMREncode(
-            mEncState, mSidState, (Mode)mMode,
-            mInputFrame, outPtr, &frameType, AMR_TX_WMF);
-
-    CHECK(res >= 0);
-    CHECK((size_t)res < buffer->size());
-
-    // Convert header byte from WMF to IETF format.
-    outPtr[0] = ((outPtr[0] << 3) | 4) & 0x7c;
-
-    buffer->set_range(0, res);
-
-    // Each frame of 160 samples is 20ms long.
-    int64_t mediaTimeUs = mNumFramesOutput * 20000LL;
-    buffer->meta_data()->setInt64(
-            kKeyTime, mAnchorTimeUs + mediaTimeUs);
-
-    if (readFromSource && wallClockTimeUs != -1) {
-        buffer->meta_data()->setInt64(kKeyDriftTime,
-            mediaTimeUs - wallClockTimeUs);
-    }
-
-    ++mNumFramesOutput;
-
-    *out = buffer;
-
-    mNumInputSamples = 0;
-
-    return OK;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/codecs/amrnb/enc/Android.mk b/media/libstagefright/codecs/amrnb/enc/Android.mk
index 21937bf..28246ae 100644
--- a/media/libstagefright/codecs/amrnb/enc/Android.mk
+++ b/media/libstagefright/codecs/amrnb/enc/Android.mk
@@ -2,7 +2,6 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := \
-        AMRNBEncoder.cpp \
 	src/amrencode.cpp \
  	src/autocorr.cpp \
  	src/c1035pf.cpp \
diff --git a/media/libstagefright/codecs/amrwbenc/AMRWBEncoder.cpp b/media/libstagefright/codecs/amrwbenc/AMRWBEncoder.cpp
deleted file mode 100644
index 7fd3a95..0000000
--- a/media/libstagefright/codecs/amrwbenc/AMRWBEncoder.cpp
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "AMRWBEncoder"
-#include <utils/Log.h>
-
-#include "AMRWBEncoder.h"
-#include "voAMRWB.h"
-#include "cmnMemory.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/MediaBufferGroup.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MetaData.h>
-
-namespace android {
-
-static const int32_t kNumSamplesPerFrame = 320;
-static const int32_t kBitsPerSample = 16;
-static const int32_t kInputBufferSize = (kBitsPerSample / 8) * kNumSamplesPerFrame;
-static const int32_t kSampleRate = 16000;
-static const int32_t kNumChannels = 1;
-
-AMRWBEncoder::AMRWBEncoder(const sp<MediaSource> &source, const sp<MetaData> &meta)
-    : mSource(source),
-      mMeta(meta),
-      mStarted(false),
-      mBufferGroup(NULL),
-      mInputBuffer(NULL),
-      mEncoderHandle(NULL),
-      mApiHandle(NULL),
-      mMemOperator(NULL),
-      mAnchorTimeUs(0),
-      mNumFramesOutput(0),
-      mNumInputSamples(0) {
-}
-
-static VOAMRWBMODE pickModeFromBitRate(int32_t bps) {
-    CHECK(bps >= 0);
-    if (bps <= 6600) {
-        return VOAMRWB_MD66;
-    } else if (bps <= 8850) {
-        return VOAMRWB_MD885;
-    } else if (bps <= 12650) {
-        return VOAMRWB_MD1265;
-    } else if (bps <= 14250) {
-        return VOAMRWB_MD1425;
-    } else if (bps <= 15850) {
-        return VOAMRWB_MD1585;
-    } else if (bps <= 18250) {
-        return VOAMRWB_MD1825;
-    } else if (bps <= 19850) {
-        return VOAMRWB_MD1985;
-    } else if (bps <= 23050) {
-        return VOAMRWB_MD2305;
-    }
-    return VOAMRWB_MD2385;
-}
-
-status_t AMRWBEncoder::initCheck() {
-    CHECK(mApiHandle == NULL && mEncoderHandle == NULL);
-    CHECK(mMeta->findInt32(kKeyBitRate, &mBitRate));
-
-    mApiHandle = new VO_AUDIO_CODECAPI;
-    CHECK(mApiHandle);
-
-    if (VO_ERR_NONE != voGetAMRWBEncAPI(mApiHandle)) {
-        ALOGE("Failed to get api handle");
-        return UNKNOWN_ERROR;
-    }
-
-    mMemOperator = new VO_MEM_OPERATOR;
-    CHECK(mMemOperator != NULL);
-    mMemOperator->Alloc = cmnMemAlloc;
-    mMemOperator->Copy = cmnMemCopy;
-    mMemOperator->Free = cmnMemFree;
-    mMemOperator->Set = cmnMemSet;
-    mMemOperator->Check = cmnMemCheck;
-
-    VO_CODEC_INIT_USERDATA userData;
-    memset(&userData, 0, sizeof(userData));
-    userData.memflag = VO_IMF_USERMEMOPERATOR;
-    userData.memData = (VO_PTR) mMemOperator;
-    if (VO_ERR_NONE != mApiHandle->Init(&mEncoderHandle, VO_AUDIO_CodingAMRWB, &userData)) {
-        ALOGE("Failed to init AMRWB encoder");
-        return UNKNOWN_ERROR;
-    }
-
-    // Configure AMRWB encoder$
-    VOAMRWBMODE mode = pickModeFromBitRate(mBitRate);
-    if (VO_ERR_NONE != mApiHandle->SetParam(mEncoderHandle, VO_PID_AMRWB_MODE,  &mode)) {
-        ALOGE("Failed to set AMRWB encoder mode to %d", mode);
-        return UNKNOWN_ERROR;
-    }
-
-    VOAMRWBFRAMETYPE type = VOAMRWB_RFC3267;
-    if (VO_ERR_NONE != mApiHandle->SetParam(mEncoderHandle, VO_PID_AMRWB_FRAMETYPE, &type)) {
-        ALOGE("Failed to set AMRWB encoder frame type to %d", type);
-        return UNKNOWN_ERROR;
-    }
-
-    return OK;
-}
-
-AMRWBEncoder::~AMRWBEncoder() {
-    if (mStarted) {
-        stop();
-    }
-}
-
-status_t AMRWBEncoder::start(MetaData *params) {
-    if (mStarted) {
-        ALOGW("Call start() when encoder already started");
-        return OK;
-    }
-
-    mBufferGroup = new MediaBufferGroup;
-
-    // The largest buffer size is header + 477 bits
-    mBufferGroup->add_buffer(new MediaBuffer(1024));
-
-    CHECK_EQ((status_t)OK, initCheck());
-
-    mNumFramesOutput = 0;
-
-    status_t err = mSource->start(params);
-    if (err != OK) {
-        ALOGE("AudioSource is not available");
-        return err;
-    }
-    mStarted = true;
-
-    return OK;
-}
-
-status_t AMRWBEncoder::stop() {
-    if (!mStarted) {
-        ALOGW("Call stop() when encoder has not started");
-        return OK;
-    }
-
-    if (mInputBuffer) {
-        mInputBuffer->release();
-        mInputBuffer = NULL;
-    }
-
-    delete mBufferGroup;
-    mBufferGroup = NULL;
-
-
-    CHECK_EQ((VO_U32)VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
-    mEncoderHandle = NULL;
-
-    delete mApiHandle;
-    mApiHandle = NULL;
-
-    delete mMemOperator;
-    mMemOperator;
-
-    mStarted = false;
-
-    mSource->stop();
-    return OK;
-}
-
-sp<MetaData> AMRWBEncoder::getFormat() {
-    sp<MetaData> srcFormat = mSource->getFormat();
-
-    mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
-
-    int64_t durationUs;
-    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
-        mMeta->setInt64(kKeyDuration, durationUs);
-    }
-
-    mMeta->setCString(kKeyDecoderComponent, "AMRWBEncoder");
-
-    return mMeta;
-}
-
-status_t AMRWBEncoder::read(
-        MediaBuffer **out, const ReadOptions *options) {
-    status_t err;
-
-    *out = NULL;
-
-    int64_t seekTimeUs;
-    ReadOptions::SeekMode mode;
-    CHECK(options == NULL || !options->getSeekTo(&seekTimeUs, &mode));
-    bool readFromSource = false;
-    int64_t wallClockTimeUs = -1;
-
-    while (mNumInputSamples < kNumSamplesPerFrame) {
-        if (mInputBuffer == NULL) {
-            err = mSource->read(&mInputBuffer, options);
-
-            if (err != OK) {
-                if (mNumInputSamples == 0) {
-                    return ERROR_END_OF_STREAM;
-                }
-                memset(&mInputFrame[mNumInputSamples],
-                       0,
-                       sizeof(int16_t)
-                            * (kNumSamplesPerFrame - mNumInputSamples));
-                mNumInputSamples = 0;
-                break;
-            }
-
-            size_t align = mInputBuffer->range_length() % sizeof(int16_t);
-            CHECK_EQ(align, (size_t)0);
-
-            int64_t timeUs;
-            if (mInputBuffer->meta_data()->findInt64(kKeyDriftTime, &timeUs)) {
-                wallClockTimeUs = timeUs;
-            }
-            if (mInputBuffer->meta_data()->findInt64(kKeyAnchorTime, &timeUs)) {
-                mAnchorTimeUs = timeUs;
-            }
-            readFromSource = true;
-        } else {
-            readFromSource = false;
-        }
-
-        size_t copy =
-            (kNumSamplesPerFrame - mNumInputSamples) * sizeof(int16_t);
-
-        if (copy > mInputBuffer->range_length()) {
-            copy = mInputBuffer->range_length();
-        }
-
-        memcpy(&mInputFrame[mNumInputSamples],
-               (const uint8_t *)mInputBuffer->data()
-                    + mInputBuffer->range_offset(),
-               copy);
-
-        mInputBuffer->set_range(
-                mInputBuffer->range_offset() + copy,
-                mInputBuffer->range_length() - copy);
-
-        if (mInputBuffer->range_length() == 0) {
-            mInputBuffer->release();
-            mInputBuffer = NULL;
-        }
-
-        mNumInputSamples += copy / sizeof(int16_t);
-        if (mNumInputSamples >= kNumSamplesPerFrame) {
-            mNumInputSamples %= kNumSamplesPerFrame;
-            break;  // Get a whole input frame 640 bytes
-        }
-    }
-
-    VO_CODECBUFFER inputData;
-    memset(&inputData, 0, sizeof(inputData));
-    inputData.Buffer = (unsigned char*) mInputFrame;
-    inputData.Length = kInputBufferSize;
-    CHECK(VO_ERR_NONE == mApiHandle->SetInputData(mEncoderHandle,&inputData));
-
-    MediaBuffer *buffer;
-    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), (status_t)OK);
-    uint8_t *outPtr = (uint8_t *)buffer->data();
-
-    VO_CODECBUFFER outputData;
-    memset(&outputData, 0, sizeof(outputData));
-    VO_AUDIO_OUTPUTINFO outputInfo;
-    memset(&outputInfo, 0, sizeof(outputInfo));
-
-    VO_U32 ret = VO_ERR_NONE;
-    outputData.Buffer = outPtr;
-    outputData.Length = buffer->size();
-    ret = mApiHandle->GetOutputData(mEncoderHandle, &outputData, &outputInfo);
-    CHECK(ret == VO_ERR_NONE || ret == VO_ERR_INPUT_BUFFER_SMALL);
-
-    buffer->set_range(0, outputData.Length);
-    ++mNumFramesOutput;
-
-    int64_t mediaTimeUs = mNumFramesOutput * 20000LL;
-    buffer->meta_data()->setInt64(kKeyTime, mAnchorTimeUs + mediaTimeUs);
-    if (readFromSource && wallClockTimeUs != -1) {
-        buffer->meta_data()->setInt64(kKeyDriftTime, mediaTimeUs - wallClockTimeUs);
-    }
-
-    *out = buffer;
-    return OK;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/codecs/amrwbenc/Android.mk b/media/libstagefright/codecs/amrwbenc/Android.mk
index 3a46ec8..d3c3041 100644
--- a/media/libstagefright/codecs/amrwbenc/Android.mk
+++ b/media/libstagefright/codecs/amrwbenc/Android.mk
@@ -5,7 +5,6 @@
 
 
 LOCAL_SRC_FILES := \
-	AMRWBEncoder.cpp \
 	src/autocorr.c \
 	src/az_isp.c \
 	src/bits.c \
diff --git a/media/libstagefright/codecs/g711/dec/SoftG711.cpp b/media/libstagefright/codecs/g711/dec/SoftG711.cpp
index 32ef003..bcdd3c7 100644
--- a/media/libstagefright/codecs/g711/dec/SoftG711.cpp
+++ b/media/libstagefright/codecs/g711/dec/SoftG711.cpp
@@ -140,7 +140,7 @@
             OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
                 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
 
-            if (pcmParams->nPortIndex != 0) {
+            if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
                 return OMX_ErrorUndefined;
             }
 
@@ -148,7 +148,9 @@
                 return OMX_ErrorUndefined;
             }
 
-            mNumChannels = pcmParams->nChannels;
+            if(pcmParams->nPortIndex == 0) {
+                mNumChannels = pcmParams->nChannels;
+            }
 
             return OMX_ErrorNone;
         }
diff --git a/media/libstagefright/include/AACDecoder.h b/media/libstagefright/include/AACDecoder.h
deleted file mode 100644
index 886a3b7..0000000
--- a/media/libstagefright/include/AACDecoder.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef AAC_DECODER_H_
-
-#define AAC_DECODER_H_
-
-#include <media/stagefright/MediaSource.h>
-
-struct tPVMP4AudioDecoderExternal;
-
-namespace android {
-
-struct MediaBufferGroup;
-struct MetaData;
-
-struct AACDecoder : public MediaSource {
-    AACDecoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-protected:
-    virtual ~AACDecoder();
-
-private:
-    sp<MetaData>    mMeta;
-    sp<MediaSource> mSource;
-    bool mStarted;
-
-    MediaBufferGroup *mBufferGroup;
-
-    tPVMP4AudioDecoderExternal *mConfig;
-    void *mDecoderBuf;
-    int64_t mAnchorTimeUs;
-    int64_t mNumSamplesOutput;
-    status_t mInitCheck;
-    int64_t  mNumDecodedBuffers;
-    int32_t  mUpsamplingFactor;
-
-    MediaBuffer *mInputBuffer;
-
-    status_t initCheck();
-    AACDecoder(const AACDecoder &);
-    AACDecoder &operator=(const AACDecoder &);
-};
-
-}  // namespace android
-
-#endif  // AAC_DECODER_H_
diff --git a/media/libstagefright/include/AMRNBDecoder.h b/media/libstagefright/include/AMRNBDecoder.h
deleted file mode 100644
index cf24eda..0000000
--- a/media/libstagefright/include/AMRNBDecoder.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef AMR_NB_DECODER_H_
-
-#define AMR_NB_DECODER_H_
-
-#include <media/stagefright/MediaSource.h>
-
-namespace android {
-
-struct MediaBufferGroup;
-
-struct AMRNBDecoder : public MediaSource {
-    AMRNBDecoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-protected:
-    virtual ~AMRNBDecoder();
-
-private:
-    sp<MediaSource> mSource;
-    bool mStarted;
-
-    MediaBufferGroup *mBufferGroup;
-
-    void *mState;
-    int64_t mAnchorTimeUs;
-    int64_t mNumSamplesOutput;
-
-    MediaBuffer *mInputBuffer;
-
-    AMRNBDecoder(const AMRNBDecoder &);
-    AMRNBDecoder &operator=(const AMRNBDecoder &);
-};
-
-}  // namespace android
-
-#endif  // AMR_NB_DECODER_H_
diff --git a/media/libstagefright/include/AMRNBEncoder.h b/media/libstagefright/include/AMRNBEncoder.h
deleted file mode 100644
index 71160e6..0000000
--- a/media/libstagefright/include/AMRNBEncoder.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef AMR_NB_ENCODER_H_
-
-#define AMR_NB_ENCODER_H_
-
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-
-namespace android {
-
-struct MediaBufferGroup;
-
-struct AMRNBEncoder : public MediaSource {
-    AMRNBEncoder(const sp<MediaSource> &source, const sp<MetaData> &meta);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-protected:
-    virtual ~AMRNBEncoder();
-
-private:
-    sp<MediaSource> mSource;
-    sp<MetaData>    mMeta;
-    bool mStarted;
-
-    MediaBufferGroup *mBufferGroup;
-
-    void *mEncState;
-    void *mSidState;
-    int64_t mAnchorTimeUs;
-    int64_t mNumFramesOutput;
-
-    MediaBuffer *mInputBuffer;
-    int mMode;
-
-    int16_t mInputFrame[160];
-    int32_t mNumInputSamples;
-
-    AMRNBEncoder(const AMRNBEncoder &);
-    AMRNBEncoder &operator=(const AMRNBEncoder &);
-};
-
-}  // namespace android
-
-#endif  // AMR_NB_ENCODER_H_
diff --git a/media/libstagefright/include/AMRWBDecoder.h b/media/libstagefright/include/AMRWBDecoder.h
deleted file mode 100644
index 927c51c..0000000
--- a/media/libstagefright/include/AMRWBDecoder.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef AMR_WB_DECODER_H_
-
-#define AMR_WB_DECODER_H_
-
-#include <media/stagefright/MediaSource.h>
-
-namespace android {
-
-struct MediaBufferGroup;
-
-struct AMRWBDecoder : public MediaSource {
-    AMRWBDecoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-protected:
-    virtual ~AMRWBDecoder();
-
-private:
-    sp<MediaSource> mSource;
-    bool mStarted;
-
-    MediaBufferGroup *mBufferGroup;
-
-    void *mState;
-    void *mDecoderBuf;
-    int16_t *mDecoderCookie;
-    int64_t mAnchorTimeUs;
-    int64_t mNumSamplesOutput;
-    int16_t mInputSampleBuffer[477];
-
-    MediaBuffer *mInputBuffer;
-
-    AMRWBDecoder(const AMRWBDecoder &);
-    AMRWBDecoder &operator=(const AMRWBDecoder &);
-};
-
-}  // namespace android
-
-#endif  // AMR_WB_DECODER_H_
diff --git a/media/libstagefright/include/AMRWBEncoder.h b/media/libstagefright/include/AMRWBEncoder.h
deleted file mode 100644
index f2d155f..0000000
--- a/media/libstagefright/include/AMRWBEncoder.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef AMR_WB_ENCODER_H
-#define AMR_WB_ENCODER_H
-
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-
-struct VO_AUDIO_CODECAPI;
-struct VO_MEM_OPERATOR;
-
-namespace android {
-
-struct MediaBufferGroup;
-
-class AMRWBEncoder: public MediaSource {
-    public:
-        AMRWBEncoder(const sp<MediaSource> &source, const sp<MetaData> &meta);
-
-        virtual status_t start(MetaData *params);
-        virtual status_t stop();
-        virtual sp<MetaData> getFormat();
-        virtual status_t read(
-                MediaBuffer **buffer, const ReadOptions *options);
-
-
-    protected:
-        virtual ~AMRWBEncoder();
-
-    private:
-        sp<MediaSource>   mSource;
-        sp<MetaData>      mMeta;
-        bool              mStarted;
-        MediaBufferGroup *mBufferGroup;
-        MediaBuffer      *mInputBuffer;
-        status_t          mInitCheck;
-        int32_t           mBitRate;
-        void             *mEncoderHandle;
-        VO_AUDIO_CODECAPI *mApiHandle;
-        VO_MEM_OPERATOR  *mMemOperator;
-
-        int64_t mAnchorTimeUs;
-        int64_t mNumFramesOutput;
-
-        int16_t mInputFrame[320];
-        int32_t mNumInputSamples;
-
-        status_t initCheck();
-
-        AMRWBEncoder& operator=(const AMRWBEncoder &rhs);
-        AMRWBEncoder(const AMRWBEncoder& copy);
-
-};
-
-}
-
-#endif  //#ifndef AMR_WB_ENCODER_H
-
diff --git a/media/libstagefright/include/AVCDecoder.h b/media/libstagefright/include/AVCDecoder.h
deleted file mode 100644
index eb3b142..0000000
--- a/media/libstagefright/include/AVCDecoder.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef AVC_DECODER_H_
-
-#define AVC_DECODER_H_
-
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaSource.h>
-#include <utils/Vector.h>
-
-struct tagAVCHandle;
-
-namespace android {
-
-struct AVCDecoder : public MediaSource,
-                    public MediaBufferObserver {
-    AVCDecoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-    virtual void signalBufferReturned(MediaBuffer *buffer);
-
-protected:
-    virtual ~AVCDecoder();
-
-private:
-    sp<MediaSource> mSource;
-    bool mStarted;
-
-    sp<MetaData> mFormat;
-
-    Vector<MediaBuffer *> mCodecSpecificData;
-
-    tagAVCHandle *mHandle;
-    Vector<MediaBuffer *> mFrames;
-    MediaBuffer *mInputBuffer;
-
-    int64_t mAnchorTimeUs;
-    int64_t mNumSamplesOutput;
-    int64_t mPendingSeekTimeUs;
-    MediaSource::ReadOptions::SeekMode mPendingSeekMode;
-
-    int64_t mTargetTimeUs;
-
-    bool mSPSSeen;
-    bool mPPSSeen;
-
-    void addCodecSpecificData(const uint8_t *data, size_t size);
-
-    static int32_t ActivateSPSWrapper(
-            void *userData, unsigned int sizeInMbs, unsigned int numBuffers);
-
-    static int32_t BindFrameWrapper(
-            void *userData, int32_t index, uint8_t **yuv);
-
-    static void UnbindFrame(void *userData, int32_t index);
-
-    int32_t activateSPS(
-            unsigned int sizeInMbs, unsigned int numBuffers);
-
-    int32_t bindFrame(int32_t index, uint8_t **yuv);
-
-    void releaseFrames();
-
-    MediaBuffer *drainOutputBuffer();
-
-    AVCDecoder(const AVCDecoder &);
-    AVCDecoder &operator=(const AVCDecoder &);
-};
-
-}  // namespace android
-
-#endif  // AVC_DECODER_H_
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
index 4c7bfa6..06e9468 100644
--- a/media/libstagefright/include/AwesomePlayer.h
+++ b/media/libstagefright/include/AwesomePlayer.h
@@ -90,6 +90,7 @@
 
     status_t setParameter(int key, const Parcel &request);
     status_t getParameter(int key, Parcel *reply);
+    status_t invoke(const Parcel &request, Parcel *reply);
     status_t setCacheStatCollectFreq(const Parcel &request);
 
     status_t seekTo(int64_t timeUs);
@@ -100,8 +101,6 @@
     void postAudioEOS(int64_t delayUs = 0ll);
     void postAudioSeekComplete();
 
-    status_t setTimedTextTrackIndex(int32_t index);
-
     status_t dump(int fd, const Vector<String16> &args) const;
 
 private:
@@ -136,7 +135,7 @@
         INCOGNITO           = 0x8000,
 
         TEXT_RUNNING        = 0x10000,
-        TEXTPLAYER_STARTED  = 0x20000,
+        TEXTPLAYER_INITIALIZED  = 0x20000,
 
         SLOW_DECODER_HACK   = 0x40000,
     };
diff --git a/media/libstagefright/include/G711Decoder.h b/media/libstagefright/include/G711Decoder.h
deleted file mode 100644
index 8b5143a..0000000
--- a/media/libstagefright/include/G711Decoder.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef G711_DECODER_H_
-
-#define G711_DECODER_H_
-
-#include <media/stagefright/MediaSource.h>
-
-namespace android {
-
-struct MediaBufferGroup;
-
-struct G711Decoder : public MediaSource {
-    G711Decoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-protected:
-    virtual ~G711Decoder();
-
-private:
-    sp<MediaSource> mSource;
-    bool mStarted;
-    bool mIsMLaw;
-
-    MediaBufferGroup *mBufferGroup;
-
-    static void DecodeALaw(int16_t *out, const uint8_t *in, size_t inSize);
-    static void DecodeMLaw(int16_t *out, const uint8_t *in, size_t inSize);
-
-    G711Decoder(const G711Decoder &);
-    G711Decoder &operator=(const G711Decoder &);
-};
-
-}  // namespace android
-
-#endif  // G711_DECODER_H_
diff --git a/media/libstagefright/include/M4vH263Decoder.h b/media/libstagefright/include/M4vH263Decoder.h
deleted file mode 100644
index 7d73e30..0000000
--- a/media/libstagefright/include/M4vH263Decoder.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef M4V_H263_DECODER_H_
-
-#define M4V_H263_DECODER_H_
-
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaSource.h>
-
-struct tagvideoDecControls;
-
-namespace android {
-
-struct M4vH263Decoder : public MediaSource,
-                        public MediaBufferObserver {
-    M4vH263Decoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-    virtual void signalBufferReturned(MediaBuffer *buffer);
-
-protected:
-    virtual ~M4vH263Decoder();
-
-private:
-    sp<MediaSource> mSource;
-    bool mStarted;
-    int32_t mWidth, mHeight;
-
-    sp<MetaData> mFormat;
-
-    tagvideoDecControls *mHandle;
-    MediaBuffer *mFrames[2];
-    MediaBuffer *mInputBuffer;
-
-    int64_t mNumSamplesOutput;
-    int64_t mTargetTimeUs;
-
-    void allocateFrames(int32_t width, int32_t height);
-    void releaseFrames();
-
-    M4vH263Decoder(const M4vH263Decoder &);
-    M4vH263Decoder &operator=(const M4vH263Decoder &);
-};
-
-}  // namespace android
-
-#endif  // M4V_H263_DECODER_H_
diff --git a/media/libstagefright/include/MP3Decoder.h b/media/libstagefright/include/MP3Decoder.h
deleted file mode 100644
index 4086fb6..0000000
--- a/media/libstagefright/include/MP3Decoder.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef MP3_DECODER_H_
-
-#define MP3_DECODER_H_
-
-#include <media/stagefright/MediaSource.h>
-
-struct tPVMP3DecoderExternal;
-
-namespace android {
-
-struct MediaBufferGroup;
-
-struct MP3Decoder : public MediaSource {
-    MP3Decoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-protected:
-    virtual ~MP3Decoder();
-
-private:
-    sp<MediaSource> mSource;
-    sp<MetaData> mMeta;
-    int32_t mNumChannels;
-
-    bool mStarted;
-
-    MediaBufferGroup *mBufferGroup;
-
-    tPVMP3DecoderExternal *mConfig;
-    void *mDecoderBuf;
-    int64_t mAnchorTimeUs;
-    int64_t mNumFramesOutput;
-
-    MediaBuffer *mInputBuffer;
-
-    void init();
-
-    MP3Decoder(const MP3Decoder &);
-    MP3Decoder &operator=(const MP3Decoder &);
-};
-
-}  // namespace android
-
-#endif  // MP3_DECODER_H_
diff --git a/media/libstagefright/include/VPXDecoder.h b/media/libstagefright/include/VPXDecoder.h
deleted file mode 100644
index 3b8362d..0000000
--- a/media/libstagefright/include/VPXDecoder.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef VPX_DECODER_H_
-
-#define VPX_DECODER_H_
-
-#include <media/stagefright/MediaSource.h>
-#include <utils/Vector.h>
-
-namespace android {
-
-struct MediaBufferGroup;
-
-struct VPXDecoder : public MediaSource {
-    VPXDecoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-protected:
-    virtual ~VPXDecoder();
-
-private:
-    sp<MediaSource> mSource;
-    bool mStarted;
-    int32_t mWidth, mHeight;
-    size_t mBufferSize;
-
-    void *mCtx;
-    MediaBufferGroup *mBufferGroup;
-
-    int64_t mTargetTimeUs;
-
-    sp<MetaData> mFormat;
-
-    VPXDecoder(const VPXDecoder &);
-    VPXDecoder &operator=(const VPXDecoder &);
-};
-
-}  // namespace android
-
-#endif  // VPX_DECODER_H_
-
diff --git a/media/libstagefright/include/VorbisDecoder.h b/media/libstagefright/include/VorbisDecoder.h
deleted file mode 100644
index 13e8b77..0000000
--- a/media/libstagefright/include/VorbisDecoder.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef VORBIS_DECODER_H_
-
-#define VORBIS_DECODER_H_
-
-#include <media/stagefright/MediaSource.h>
-
-struct vorbis_dsp_state;
-struct vorbis_info;
-
-namespace android {
-
-struct MediaBufferGroup;
-
-struct VorbisDecoder : public MediaSource {
-    VorbisDecoder(const sp<MediaSource> &source);
-
-    virtual status_t start(MetaData *params);
-    virtual status_t stop();
-
-    virtual sp<MetaData> getFormat();
-
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options);
-
-protected:
-    virtual ~VorbisDecoder();
-
-private:
-    enum {
-        kMaxNumSamplesPerBuffer = 8192 * 2
-    };
-
-    sp<MediaSource> mSource;
-    bool mStarted;
-
-    MediaBufferGroup *mBufferGroup;
-
-    int32_t mNumChannels;
-    int32_t mSampleRate;
-    int64_t mAnchorTimeUs;
-    int64_t mNumFramesOutput;
-    int32_t mNumFramesLeftOnPage;
-
-    vorbis_dsp_state *mState;
-    vorbis_info *mVi;
-
-    int decodePacket(MediaBuffer *packet, MediaBuffer *out);
-
-    VorbisDecoder(const VorbisDecoder &);
-    VorbisDecoder &operator=(const VorbisDecoder &);
-};
-
-}  // namespace android
-
-#endif  // VORBIS_DECODER_H_
-
diff --git a/media/libstagefright/omx/Android.mk b/media/libstagefright/omx/Android.mk
index f587a9c..083c7ef 100644
--- a/media/libstagefright/omx/Android.mk
+++ b/media/libstagefright/omx/Android.mk
@@ -5,7 +5,6 @@
 
 LOCAL_SRC_FILES:=                     \
         OMX.cpp                       \
-        OMXComponentBase.cpp          \
         OMXMaster.cpp                 \
         OMXNodeInstance.cpp           \
         SimpleSoftOMXComponent.cpp    \
diff --git a/media/libstagefright/omx/OMXComponentBase.cpp b/media/libstagefright/omx/OMXComponentBase.cpp
deleted file mode 100644
index 7d11dce..0000000
--- a/media/libstagefright/omx/OMXComponentBase.cpp
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "OMXComponentBase.h"
-
-#include <stdlib.h>
-
-#include <media/stagefright/foundation/ADebug.h>
-
-namespace android {
-
-OMXComponentBase::OMXComponentBase(
-        const OMX_CALLBACKTYPE *callbacks,
-        OMX_PTR appData)
-    : mCallbacks(callbacks),
-      mAppData(appData),
-      mComponentHandle(NULL) {
-}
-
-OMXComponentBase::~OMXComponentBase() {}
-
-void OMXComponentBase::setComponentHandle(OMX_COMPONENTTYPE *handle) {
-    CHECK(mComponentHandle == NULL);
-    mComponentHandle = handle;
-}
-
-void OMXComponentBase::postEvent(
-        OMX_EVENTTYPE event, OMX_U32 param1, OMX_U32 param2) {
-    (*mCallbacks->EventHandler)(
-            mComponentHandle, mAppData, event, param1, param2, NULL);
-}
-
-void OMXComponentBase::postFillBufferDone(OMX_BUFFERHEADERTYPE *bufHdr) {
-    (*mCallbacks->FillBufferDone)(mComponentHandle, mAppData, bufHdr);
-}
-
-void OMXComponentBase::postEmptyBufferDone(OMX_BUFFERHEADERTYPE *bufHdr) {
-    (*mCallbacks->EmptyBufferDone)(mComponentHandle, mAppData, bufHdr);
-}
-
-static OMXComponentBase *getBase(OMX_HANDLETYPE hComponent) {
-    return (OMXComponentBase *)
-        ((OMX_COMPONENTTYPE *)hComponent)->pComponentPrivate;
-}
-
-static OMX_ERRORTYPE SendCommandWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent,
-        OMX_IN  OMX_COMMANDTYPE Cmd,
-        OMX_IN  OMX_U32 nParam1,
-        OMX_IN  OMX_PTR pCmdData) {
-    return getBase(hComponent)->sendCommand(Cmd, nParam1, pCmdData);
-}
-
-static OMX_ERRORTYPE GetParameterWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent, 
-        OMX_IN  OMX_INDEXTYPE nParamIndex,  
-        OMX_INOUT OMX_PTR pComponentParameterStructure) {
-    return getBase(hComponent)->getParameter(
-            nParamIndex, pComponentParameterStructure);
-}
-
-static OMX_ERRORTYPE SetParameterWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent, 
-        OMX_IN  OMX_INDEXTYPE nIndex,
-        OMX_IN  OMX_PTR pComponentParameterStructure) {
-    return getBase(hComponent)->getParameter(
-            nIndex, pComponentParameterStructure);
-}
-
-static OMX_ERRORTYPE GetConfigWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent,
-        OMX_IN  OMX_INDEXTYPE nIndex, 
-        OMX_INOUT OMX_PTR pComponentConfigStructure) {
-    return getBase(hComponent)->getConfig(nIndex, pComponentConfigStructure);
-}
-
-static OMX_ERRORTYPE SetConfigWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent,
-        OMX_IN  OMX_INDEXTYPE nIndex, 
-        OMX_IN  OMX_PTR pComponentConfigStructure) {
-    return getBase(hComponent)->setConfig(nIndex, pComponentConfigStructure);
-}
-
-static OMX_ERRORTYPE GetExtensionIndexWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent,
-        OMX_IN  OMX_STRING cParameterName,
-        OMX_OUT OMX_INDEXTYPE* pIndexType) {
-    return getBase(hComponent)->getExtensionIndex(cParameterName, pIndexType);
-}
-
-static OMX_ERRORTYPE GetStateWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent,
-        OMX_OUT OMX_STATETYPE* pState) {
-    return getBase(hComponent)->getState(pState);
-}
-
-static OMX_ERRORTYPE UseBufferWrapper(
-        OMX_IN OMX_HANDLETYPE hComponent,
-        OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr,
-        OMX_IN OMX_U32 nPortIndex,
-        OMX_IN OMX_PTR pAppPrivate,
-        OMX_IN OMX_U32 nSizeBytes,
-        OMX_IN OMX_U8* pBuffer) {
-    return getBase(hComponent)->useBuffer(
-            ppBufferHdr, nPortIndex, pAppPrivate, nSizeBytes, pBuffer);
-}
-
-static OMX_ERRORTYPE AllocateBufferWrapper(
-        OMX_IN OMX_HANDLETYPE hComponent,
-        OMX_INOUT OMX_BUFFERHEADERTYPE** ppBuffer,
-        OMX_IN OMX_U32 nPortIndex,
-        OMX_IN OMX_PTR pAppPrivate,
-        OMX_IN OMX_U32 nSizeBytes) {
-    return getBase(hComponent)->allocateBuffer(
-            ppBuffer, nPortIndex, pAppPrivate, nSizeBytes);
-}
-
-static OMX_ERRORTYPE FreeBufferWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent,
-        OMX_IN  OMX_U32 nPortIndex,
-        OMX_IN  OMX_BUFFERHEADERTYPE* pBuffer) {
-    return getBase(hComponent)->freeBuffer(nPortIndex, pBuffer);
-}
-
-static OMX_ERRORTYPE EmptyThisBufferWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent,
-        OMX_IN  OMX_BUFFERHEADERTYPE* pBuffer) {
-    return getBase(hComponent)->emptyThisBuffer(pBuffer);
-}
-
-static OMX_ERRORTYPE FillThisBufferWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent,
-        OMX_IN  OMX_BUFFERHEADERTYPE* pBuffer) {
-    return getBase(hComponent)->fillThisBuffer(pBuffer);
-}
-
-static OMX_ERRORTYPE ComponentDeInitWrapper(
-        OMX_IN  OMX_HANDLETYPE hComponent) {
-    delete getBase(hComponent);
-    delete (OMX_COMPONENTTYPE *)hComponent;
-
-    return OMX_ErrorNone;
-}
-
-static OMX_ERRORTYPE ComponentRoleEnumWrapper(
-        OMX_IN OMX_HANDLETYPE hComponent,
-        OMX_OUT OMX_U8 *cRole,
-        OMX_IN OMX_U32 nIndex) {
-    return getBase(hComponent)->enumerateRoles(cRole, nIndex);
-}
-
-// static
-OMX_COMPONENTTYPE *OMXComponentBase::MakeComponent(OMXComponentBase *base) {
-    OMX_COMPONENTTYPE *result = new OMX_COMPONENTTYPE;
-
-    result->nSize = sizeof(OMX_COMPONENTTYPE);
-    result->nVersion.s.nVersionMajor = 1;
-    result->nVersion.s.nVersionMinor = 0;
-    result->nVersion.s.nRevision = 0;
-    result->nVersion.s.nStep = 0;
-    result->pComponentPrivate = base;
-    result->pApplicationPrivate = NULL;
-
-    result->GetComponentVersion = NULL;
-    result->SendCommand = SendCommandWrapper;
-    result->GetParameter = GetParameterWrapper;
-    result->SetParameter = SetParameterWrapper;
-    result->GetConfig = GetConfigWrapper;
-    result->SetConfig = SetConfigWrapper;
-    result->GetExtensionIndex = GetExtensionIndexWrapper;
-    result->GetState = GetStateWrapper;
-    result->ComponentTunnelRequest = NULL;
-    result->UseBuffer = UseBufferWrapper;
-    result->AllocateBuffer = AllocateBufferWrapper;
-    result->FreeBuffer = FreeBufferWrapper;
-    result->EmptyThisBuffer = EmptyThisBufferWrapper;
-    result->FillThisBuffer = FillThisBufferWrapper;
-    result->SetCallbacks = NULL;
-    result->ComponentDeInit = ComponentDeInitWrapper;
-    result->UseEGLImage = NULL;
-    result->ComponentRoleEnum = ComponentRoleEnumWrapper;
-
-    base->setComponentHandle(result);
-
-    return result;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/omx/OMXComponentBase.h b/media/libstagefright/omx/OMXComponentBase.h
deleted file mode 100644
index fd0df0b..0000000
--- a/media/libstagefright/omx/OMXComponentBase.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef OMX_COMPONENT_BASE_H_
-
-#define OMX_COMPONENT_BASE_H_
-
-#include <OMX_Component.h>
-
-namespace android {
-
-struct OMXComponentBase {
-    OMXComponentBase(
-            const OMX_CALLBACKTYPE *callbacks,
-            OMX_PTR appData);
-
-    virtual ~OMXComponentBase();
-
-    virtual OMX_ERRORTYPE sendCommand(
-            OMX_COMMANDTYPE cmd, OMX_U32 param, OMX_PTR cmdData) = 0;
-
-    virtual OMX_ERRORTYPE getParameter(
-            OMX_INDEXTYPE index, OMX_PTR params) = 0;
-
-    virtual OMX_ERRORTYPE setParameter(
-            OMX_INDEXTYPE index, const OMX_PTR params) = 0;
-
-    virtual OMX_ERRORTYPE getConfig(
-            OMX_INDEXTYPE index, OMX_PTR config) = 0;
-
-    virtual OMX_ERRORTYPE setConfig(
-            OMX_INDEXTYPE index, const OMX_PTR config) = 0;
-
-    virtual OMX_ERRORTYPE getExtensionIndex(
-            const OMX_STRING name, OMX_INDEXTYPE *index) = 0;
-
-    virtual OMX_ERRORTYPE useBuffer(
-            OMX_BUFFERHEADERTYPE **bufHdr,
-            OMX_U32 portIndex,
-            OMX_PTR appPrivate,
-            OMX_U32 size,
-            OMX_U8 *buffer) = 0;
-
-    virtual OMX_ERRORTYPE allocateBuffer(
-            OMX_BUFFERHEADERTYPE **bufHdr,
-            OMX_U32 portIndex,
-            OMX_PTR appPrivate,
-            OMX_U32 size) = 0;
-
-    virtual OMX_ERRORTYPE freeBuffer(
-            OMX_U32 portIndex,
-            OMX_BUFFERHEADERTYPE *buffer) = 0;
-
-    virtual OMX_ERRORTYPE emptyThisBuffer(OMX_BUFFERHEADERTYPE *buffer) = 0;
-    virtual OMX_ERRORTYPE fillThisBuffer(OMX_BUFFERHEADERTYPE *buffer) = 0;
-
-    virtual OMX_ERRORTYPE enumerateRoles(OMX_U8 *role, OMX_U32 index) = 0;
-
-    virtual OMX_ERRORTYPE getState(OMX_STATETYPE *state) = 0;
-
-    // Wraps a given OMXComponentBase instance into an OMX_COMPONENTTYPE
-    // as required by OpenMAX APIs.
-    static OMX_COMPONENTTYPE *MakeComponent(OMXComponentBase *base);
-
-protected:
-    void postEvent(OMX_EVENTTYPE event, OMX_U32 param1, OMX_U32 param2);
-    void postFillBufferDone(OMX_BUFFERHEADERTYPE *bufHdr);
-    void postEmptyBufferDone(OMX_BUFFERHEADERTYPE *bufHdr);
-
-private:
-    void setComponentHandle(OMX_COMPONENTTYPE *handle);
-
-    const OMX_CALLBACKTYPE *mCallbacks;
-    OMX_PTR mAppData;
-    OMX_COMPONENTTYPE *mComponentHandle;
-
-    OMXComponentBase(const OMXComponentBase &);
-    OMXComponentBase &operator=(const OMXComponentBase &);
-};
-
-}  // namespace android
-
-#endif  // OMX_COMPONENT_BASE_H_
diff --git a/media/libstagefright/timedtext/TimedText3GPPSource.cpp b/media/libstagefright/timedtext/TimedText3GPPSource.cpp
index 4a3bfd3..c423ef0 100644
--- a/media/libstagefright/timedtext/TimedText3GPPSource.cpp
+++ b/media/libstagefright/timedtext/TimedText3GPPSource.cpp
@@ -110,4 +110,8 @@
     return OK;
 }
 
+sp<MetaData> TimedText3GPPSource::getFormat() {
+    return mSource->getFormat();
+}
+
 }  // namespace android
diff --git a/media/libstagefright/timedtext/TimedText3GPPSource.h b/media/libstagefright/timedtext/TimedText3GPPSource.h
index dfc6418..4ec3d8a 100644
--- a/media/libstagefright/timedtext/TimedText3GPPSource.h
+++ b/media/libstagefright/timedtext/TimedText3GPPSource.h
@@ -37,6 +37,7 @@
             Parcel *parcel,
             const MediaSource::ReadOptions *options = NULL);
     virtual status_t extractGlobalDescriptions(Parcel *parcel);
+    virtual sp<MetaData> getFormat();
 
 protected:
     virtual ~TimedText3GPPSource();
diff --git a/media/libstagefright/timedtext/TimedTextDriver.cpp b/media/libstagefright/timedtext/TimedTextDriver.cpp
index c70870e..8ee15f8 100644
--- a/media/libstagefright/timedtext/TimedTextDriver.cpp
+++ b/media/libstagefright/timedtext/TimedTextDriver.cpp
@@ -20,10 +20,13 @@
 
 #include <binder/IPCThreadState.h>
 
+#include <media/mediaplayer.h>
 #include <media/MediaPlayerInterface.h>
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MediaSource.h>
-#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MetaData.h>
 #include <media/stagefright/Utils.h>
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/ALooper.h>
@@ -47,24 +50,22 @@
 }
 
 TimedTextDriver::~TimedTextDriver() {
-    mTextInBandVector.clear();
-    mTextOutOfBandVector.clear();
+    mTextSourceVector.clear();
     mLooper->stop();
 }
 
-status_t TimedTextDriver::setTimedTextTrackIndex_l(int32_t index) {
-    if (index >=
-            (int)(mTextInBandVector.size() + mTextOutOfBandVector.size())) {
+status_t TimedTextDriver::selectTrack_l(int32_t index) {
+    if (index >= (int)(mTextSourceVector.size())) {
         return BAD_VALUE;
     }
 
     sp<TimedTextSource> source;
-    if (index < mTextInBandVector.size()) {
-        source = mTextInBandVector.itemAt(index);
-    } else {
-        source = mTextOutOfBandVector.itemAt(index - mTextInBandVector.size());
-    }
+    source = mTextSourceVector.itemAt(index);
     mPlayer->setDataSource(source);
+    if (mState == UNINITIALIZED) {
+        mState = PAUSED;
+    }
+    mCurrentTrackIndex = index;
     return OK;
 }
 
@@ -73,13 +74,10 @@
     switch (mState) {
         case UNINITIALIZED:
             return INVALID_OPERATION;
-        case STOPPED:
-            mPlayer->start();
-            break;
         case PLAYING:
             return OK;
         case PAUSED:
-            mPlayer->resume();
+            mPlayer->start();
             break;
         default:
             TRESPASS();
@@ -88,10 +86,6 @@
     return OK;
 }
 
-status_t TimedTextDriver::stop() {
-    return pause();
-}
-
 // TODO: Test if pause() works properly.
 // Scenario 1: start - pause - resume
 // Scenario 2: start - seek
@@ -101,8 +95,6 @@
     switch (mState) {
         case UNINITIALIZED:
             return INVALID_OPERATION;
-        case STOPPED:
-            return OK;
         case PLAYING:
             mPlayer->pause();
             break;
@@ -115,45 +107,17 @@
     return OK;
 }
 
-status_t TimedTextDriver::resume() {
-    return start();
-}
-
-status_t TimedTextDriver::seekToAsync(int64_t timeUs) {
-    mPlayer->seekToAsync(timeUs);
-    return OK;
-}
-
-status_t TimedTextDriver::setTimedTextTrackIndex(int32_t index) {
-    // TODO: This is current implementation for MediaPlayer::disableTimedText().
-    // Find better way for readability.
-    if (index < 0) {
-        mPlayer->pause();
-        return OK;
-    }
-
+status_t TimedTextDriver::selectTrack(int32_t index) {
     status_t ret = OK;
     Mutex::Autolock autoLock(mLock);
     switch (mState) {
         case UNINITIALIZED:
-            ret = INVALID_OPERATION;
-            break;
         case PAUSED:
-            ret = setTimedTextTrackIndex_l(index);
+            ret = selectTrack_l(index);
             break;
         case PLAYING:
             mPlayer->pause();
-            ret = setTimedTextTrackIndex_l(index);
-            if (ret != OK) {
-                break;
-            }
-            mPlayer->start();
-            break;
-        case STOPPED:
-            // TODO: The only difference between STOPPED and PAUSED is this
-            // part. Revise the flow from "MediaPlayer::enableTimedText()" and
-            // remove one of the status, PAUSED and STOPPED, if possible.
-            ret = setTimedTextTrackIndex_l(index);
+            ret = selectTrack_l(index);
             if (ret != OK) {
                 break;
             }
@@ -165,6 +129,24 @@
     return ret;
 }
 
+status_t TimedTextDriver::unselectTrack(int32_t index) {
+    if (mCurrentTrackIndex != index) {
+        return INVALID_OPERATION;
+    }
+    status_t err = pause();
+    if (err != OK) {
+        return err;
+    }
+    Mutex::Autolock autoLock(mLock);
+    mState = UNINITIALIZED;
+    return OK;
+}
+
+status_t TimedTextDriver::seekToAsync(int64_t timeUs) {
+    mPlayer->seekToAsync(timeUs);
+    return OK;
+}
+
 status_t TimedTextDriver::addInBandTextSource(
         const sp<MediaSource>& mediaSource) {
     sp<TimedTextSource> source =
@@ -173,25 +155,17 @@
         return ERROR_UNSUPPORTED;
     }
     Mutex::Autolock autoLock(mLock);
-    mTextInBandVector.add(source);
-    if (mState == UNINITIALIZED) {
-        mState = STOPPED;
-    }
+    mTextSourceVector.add(source);
     return OK;
 }
 
 status_t TimedTextDriver::addOutOfBandTextSource(
-        const Parcel &request) {
+        const char *uri, const char *mimeType) {
     // TODO: Define "TimedTextSource::CreateFromURI(uri)"
     // and move below lines there..?
 
-    // String values written in Parcel are UTF-16 values.
-    const String16 uri16 = request.readString16();
-    String8 uri = String8(request.readString16());
-
-    uri.toLower();
     // To support local subtitle file only for now
-    if (strncasecmp("file://", uri.string(), 7)) {
+    if (strncasecmp("file://", uri, 7)) {
         return ERROR_UNSUPPORTED;
     }
     sp<DataSource> dataSource =
@@ -201,7 +175,7 @@
     }
 
     sp<TimedTextSource> source;
-    if (uri.getPathExtension() == String8(".srt")) {
+    if (strcasecmp(mimeType, MEDIA_MIMETYPE_TEXT_SUBRIP) == 0) {
         source = TimedTextSource::CreateTimedTextSource(
                 dataSource, TimedTextSource::OUT_OF_BAND_FILE_SRT);
     }
@@ -211,12 +185,38 @@
     }
 
     Mutex::Autolock autoLock(mLock);
-
-    mTextOutOfBandVector.add(source);
-    if (mState == UNINITIALIZED) {
-        mState = STOPPED;
-    }
+    mTextSourceVector.add(source);
     return OK;
 }
 
+status_t TimedTextDriver::addOutOfBandTextSource(
+        int fd, off64_t offset, size_t length, const char *mimeType) {
+    // Not supported yet. This requires DataSource::sniff to detect various text
+    // formats such as srt/smi/ttml.
+    return ERROR_UNSUPPORTED;
+}
+
+void TimedTextDriver::getTrackInfo(Parcel *parcel) {
+    Mutex::Autolock autoLock(mLock);
+    Vector<sp<TimedTextSource> >::const_iterator iter;
+    parcel->writeInt32(mTextSourceVector.size());
+    for (iter = mTextSourceVector.begin();
+         iter != mTextSourceVector.end(); ++iter) {
+        sp<MetaData> meta = (*iter)->getFormat();
+        if (meta != NULL) {
+            // There are two fields.
+            parcel->writeInt32(2);
+
+            // track type.
+            parcel->writeInt32(MEDIA_TRACK_TYPE_TIMEDTEXT);
+
+            const char *lang = "und";
+            meta->findCString(kKeyMediaLanguage, &lang);
+            parcel->writeString16(String16(lang));
+        } else {
+            parcel->writeInt32(0);
+        }
+    }
+}
+
 }  // namespace android
diff --git a/media/libstagefright/timedtext/TimedTextPlayer.cpp b/media/libstagefright/timedtext/TimedTextPlayer.cpp
index bda7b46..8717914 100644
--- a/media/libstagefright/timedtext/TimedTextPlayer.cpp
+++ b/media/libstagefright/timedtext/TimedTextPlayer.cpp
@@ -56,10 +56,6 @@
     (new AMessage(kWhatPause, id()))->post();
 }
 
-void TimedTextPlayer::resume() {
-    start();
-}
-
 void TimedTextPlayer::seekToAsync(int64_t timeUs) {
     sp<AMessage> msg = new AMessage(kWhatSeek, id());
     msg->setInt64("seekTimeUs", timeUs);
@@ -104,9 +100,9 @@
             if (obj != NULL) {
                 sp<ParcelEvent> parcelEvent;
                 parcelEvent = static_cast<ParcelEvent*>(obj.get());
-                notifyListener(MEDIA_TIMED_TEXT, &(parcelEvent->parcel));
+                notifyListener(&(parcelEvent->parcel));
             } else {
-                notifyListener(MEDIA_TIMED_TEXT);
+                notifyListener();
             }
             doRead();
             break;
@@ -119,14 +115,18 @@
                 mSource->stop();
             }
             mSource = static_cast<TimedTextSource*>(obj.get());
-            mSource->start();
-            Parcel parcel;
-            if (mSource->extractGlobalDescriptions(&parcel) == OK &&
-                parcel.dataSize() > 0) {
-                notifyListener(MEDIA_TIMED_TEXT, &parcel);
-            } else {
-                notifyListener(MEDIA_TIMED_TEXT);
+            status_t err = mSource->start();
+            if (err != OK) {
+                notifyError(err);
+                break;
             }
+            Parcel parcel;
+            err = mSource->extractGlobalDescriptions(&parcel);
+            if (err != OK) {
+                notifyError(err);
+                break;
+            }
+            notifyListener(&parcel);
             break;
         }
     }
@@ -141,8 +141,12 @@
 void TimedTextPlayer::doRead(MediaSource::ReadOptions* options) {
     int64_t timeUs = 0;
     sp<ParcelEvent> parcelEvent = new ParcelEvent();
-    mSource->read(&timeUs, &(parcelEvent->parcel), options);
-    postTextEvent(parcelEvent, timeUs);
+    status_t err = mSource->read(&timeUs, &(parcelEvent->parcel), options);
+    if (err != OK) {
+        notifyError(err);
+    } else {
+        postTextEvent(parcelEvent, timeUs);
+    }
 }
 
 void TimedTextPlayer::postTextEvent(const sp<ParcelEvent>& parcel, int64_t timeUs) {
@@ -151,7 +155,7 @@
         int64_t positionUs, delayUs;
         int32_t positionMs = 0;
         listener->getCurrentPosition(&positionMs);
-        positionUs = positionMs * 1000;
+        positionUs = positionMs * 1000ll;
 
         if (timeUs <= positionUs + kAdjustmentProcessingTimeUs) {
             delayUs = 0;
@@ -167,13 +171,20 @@
     }
 }
 
-void TimedTextPlayer::notifyListener(int msg, const Parcel *parcel) {
+void TimedTextPlayer::notifyError(int error) {
+    sp<MediaPlayerBase> listener = mListener.promote();
+    if (listener != NULL) {
+        listener->sendEvent(MEDIA_INFO, MEDIA_INFO_TIMED_TEXT_ERROR, error);
+    }
+}
+
+void TimedTextPlayer::notifyListener(const Parcel *parcel) {
     sp<MediaPlayerBase> listener = mListener.promote();
     if (listener != NULL) {
         if (parcel != NULL && (parcel->dataSize() > 0)) {
-            listener->sendEvent(msg, 0, 0, parcel);
+            listener->sendEvent(MEDIA_TIMED_TEXT, 0, 0, parcel);
         } else {  // send an empty timed text to clear the screen
-            listener->sendEvent(msg);
+            listener->sendEvent(MEDIA_TIMED_TEXT);
         }
     }
 }
diff --git a/media/libstagefright/timedtext/TimedTextPlayer.h b/media/libstagefright/timedtext/TimedTextPlayer.h
index 837beeb..b869f18 100644
--- a/media/libstagefright/timedtext/TimedTextPlayer.h
+++ b/media/libstagefright/timedtext/TimedTextPlayer.h
@@ -40,7 +40,6 @@
 
     void start();
     void pause();
-    void resume();
     void seekToAsync(int64_t timeUs);
     void setDataSource(sp<TimedTextSource> source);
 
@@ -68,7 +67,8 @@
     void doRead(MediaSource::ReadOptions* options = NULL);
     void onTextEvent();
     void postTextEvent(const sp<ParcelEvent>& parcel = NULL, int64_t timeUs = -1);
-    void notifyListener(int msg, const Parcel *parcel = NULL);
+    void notifyError(int error = 0);
+    void notifyListener(const Parcel *parcel = NULL);
 
     DISALLOW_EVIL_CONSTRUCTORS(TimedTextPlayer);
 };
diff --git a/media/libstagefright/timedtext/TimedTextSRTSource.cpp b/media/libstagefright/timedtext/TimedTextSRTSource.cpp
index 3752d34..c44a99b 100644
--- a/media/libstagefright/timedtext/TimedTextSRTSource.cpp
+++ b/media/libstagefright/timedtext/TimedTextSRTSource.cpp
@@ -21,8 +21,10 @@
 #include <binder/Parcel.h>
 #include <media/stagefright/foundation/AString.h>
 #include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaDefs.h>  // for MEDIA_MIMETYPE_xxx
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
 
 #include "TimedTextSRTSource.h"
 #include "TextDescriptions.h"
@@ -31,6 +33,7 @@
 
 TimedTextSRTSource::TimedTextSRTSource(const sp<DataSource>& dataSource)
         : mSource(dataSource),
+          mMetaData(new MetaData),
           mIndex(0) {
 }
 
@@ -42,10 +45,14 @@
     if (err != OK) {
         reset();
     }
+    // TODO: Need to detect the language, because SRT doesn't give language
+    // information explicitly.
+    mMetaData->setCString(kKeyMediaLanguage, "");
     return err;
 }
 
 void TimedTextSRTSource::reset() {
+    mMetaData->clear();
     mTextVector.clear();
     mIndex = 0;
 }
@@ -272,4 +279,8 @@
     return OK;
 }
 
+sp<MetaData> TimedTextSRTSource::getFormat() {
+    return mMetaData;
+}
+
 }  // namespace android
diff --git a/media/libstagefright/timedtext/TimedTextSRTSource.h b/media/libstagefright/timedtext/TimedTextSRTSource.h
index acc01f9..62710a0 100644
--- a/media/libstagefright/timedtext/TimedTextSRTSource.h
+++ b/media/libstagefright/timedtext/TimedTextSRTSource.h
@@ -39,12 +39,14 @@
             int64_t *timeUs,
             Parcel *parcel,
             const MediaSource::ReadOptions *options = NULL);
+    virtual sp<MetaData> getFormat();
 
 protected:
     virtual ~TimedTextSRTSource();
 
 private:
     sp<DataSource> mSource;
+    sp<MetaData> mMetaData;
 
     struct TextInfo {
         int64_t endTimeUs;
diff --git a/media/libstagefright/timedtext/TimedTextSource.cpp b/media/libstagefright/timedtext/TimedTextSource.cpp
index ffbe1c3..953f7b5 100644
--- a/media/libstagefright/timedtext/TimedTextSource.cpp
+++ b/media/libstagefright/timedtext/TimedTextSource.cpp
@@ -59,4 +59,8 @@
     return NULL;
 }
 
+sp<MetaData> TimedTextSource::getFormat() {
+    return NULL;
+}
+
 }  // namespace android
diff --git a/media/libstagefright/timedtext/TimedTextSource.h b/media/libstagefright/timedtext/TimedTextSource.h
index 06bae71..9349342 100644
--- a/media/libstagefright/timedtext/TimedTextSource.h
+++ b/media/libstagefright/timedtext/TimedTextSource.h
@@ -25,6 +25,7 @@
 namespace android {
 
 class DataSource;
+class MetaData;
 class Parcel;
 
 class TimedTextSource : public RefBase {
@@ -48,6 +49,7 @@
   virtual status_t extractGlobalDescriptions(Parcel *parcel) {
       return INVALID_OPERATION;
   }
+  virtual sp<MetaData> getFormat();
 
  protected:
   virtual ~TimedTextSource() { }
diff --git a/services/audioflinger/Android.mk b/services/audioflinger/Android.mk
index 86692e7..1652cae 100644
--- a/services/audioflinger/Android.mk
+++ b/services/audioflinger/Android.mk
@@ -12,8 +12,8 @@
 #   AudioResamplerCubic.cpp.arm
 
 LOCAL_C_INCLUDES := \
-    system/media/audio_effects/include \
-    system/media/audio_utils/include
+    $(call include-path-for, audio-effects) \
+    $(call include-path-for, audio-utils)
 
 LOCAL_SHARED_LIBRARIES := \
     libaudioutils \
@@ -22,6 +22,7 @@
     libutils \
     libbinder \
     libmedia \
+    libmedia_native \
     libhardware \
     libhardware_legacy \
     libeffects \
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index bfa4a49..d83d19a 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -37,8 +37,12 @@
 #include <cutils/properties.h>
 #include <cutils/compiler.h>
 
+#undef ADD_BATTERY_DATA
+
+#ifdef ADD_BATTERY_DATA
 #include <media/IMediaPlayerService.h>
 #include <media/IMediaDeathNotifier.h>
+#endif
 
 #include <private/media/AudioTrackShared.h>
 #include <private/media/AudioEffectShared.h>
@@ -57,9 +61,13 @@
 
 #include <audio_utils/primitives.h>
 
-#include <cpustats/ThreadCpuUsage.h>
 #include <powermanager/PowerManager.h>
+
 // #define DEBUG_CPU_USAGE 10  // log statistics every n wall clock seconds
+#ifdef DEBUG_CPU_USAGE
+#include <cpustats/CentralTendencyStatistics.h>
+#include <cpustats/ThreadCpuUsage.h>
+#endif
 
 #include <common_time/cc_helper.h>
 #include <common_time/local_clock.h>
@@ -105,6 +113,7 @@
 
 // ----------------------------------------------------------------------------
 
+#ifdef ADD_BATTERY_DATA
 // To collect the amplifier usage
 static void addBatteryData(uint32_t params) {
     sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
@@ -115,6 +124,7 @@
 
     service->addBatteryData(params);
 }
+#endif
 
 static int load_audio_interface(const char *if_name, const hw_module_t **mod,
                                 audio_hw_device_t **dev)
@@ -1188,6 +1198,10 @@
         write(fd, buffer, strlen(buffer));
     }
 
+    snprintf(buffer, SIZE, "io handle: %d\n", mId);
+    result.append(buffer);
+    snprintf(buffer, SIZE, "TID: %d\n", getTid());
+    result.append(buffer);
     snprintf(buffer, SIZE, "standby: %d\n", mStandby);
     result.append(buffer);
     snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
@@ -1939,30 +1953,83 @@
 
 class CpuStats {
 public:
-    void sample();
+    CpuStats();
+    void sample(const String8 &title);
 #ifdef DEBUG_CPU_USAGE
 private:
-    ThreadCpuUsage mCpu;
+    ThreadCpuUsage mCpuUsage;           // instantaneous thread CPU usage in wall clock ns
+    CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
+
+    CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
+
+    int mCpuNum;                        // thread's current CPU number
+    int mCpukHz;                        // frequency of thread's current CPU in kHz
 #endif
 };
 
-void CpuStats::sample() {
+CpuStats::CpuStats()
 #ifdef DEBUG_CPU_USAGE
-    const CentralTendencyStatistics& stats = mCpu.statistics();
-    mCpu.sampleAndEnable();
-    unsigned n = stats.n();
-    // mCpu.elapsed() is expensive, so don't call it every loop
+    : mCpuNum(-1), mCpukHz(-1)
+#endif
+{
+}
+
+void CpuStats::sample(const String8 &title) {
+#ifdef DEBUG_CPU_USAGE
+    // get current thread's delta CPU time in wall clock ns
+    double wcNs;
+    bool valid = mCpuUsage.sampleAndEnable(wcNs);
+
+    // record sample for wall clock statistics
+    if (valid) {
+        mWcStats.sample(wcNs);
+    }
+
+    // get the current CPU number
+    int cpuNum = sched_getcpu();
+
+    // get the current CPU frequency in kHz
+    int cpukHz = mCpuUsage.getCpukHz(cpuNum);
+
+    // check if either CPU number or frequency changed
+    if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
+        mCpuNum = cpuNum;
+        mCpukHz = cpukHz;
+        // ignore sample for purposes of cycles
+        valid = false;
+    }
+
+    // if no change in CPU number or frequency, then record sample for cycle statistics
+    if (valid && mCpukHz > 0) {
+        double cycles = wcNs * cpukHz * 0.000001;
+        mHzStats.sample(cycles);
+    }
+
+    unsigned n = mWcStats.n();
+    // mCpuUsage.elapsed() is expensive, so don't call it every loop
     if ((n & 127) == 1) {
-        long long elapsed = mCpu.elapsed();
+        long long elapsed = mCpuUsage.elapsed();
         if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
             double perLoop = elapsed / (double) n;
             double perLoop100 = perLoop * 0.01;
-            double mean = stats.mean();
-            double stddev = stats.stddev();
-            double minimum = stats.minimum();
-            double maximum = stats.maximum();
-            mCpu.resetStatistics();
-            ALOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
+            double perLoop1k = perLoop * 0.001;
+            double mean = mWcStats.mean();
+            double stddev = mWcStats.stddev();
+            double minimum = mWcStats.minimum();
+            double maximum = mWcStats.maximum();
+            double meanCycles = mHzStats.mean();
+            double stddevCycles = mHzStats.stddev();
+            double minCycles = mHzStats.minimum();
+            double maxCycles = mHzStats.maximum();
+            mCpuUsage.resetElapsed();
+            mWcStats.reset();
+            mHzStats.reset();
+            ALOGD("CPU usage for %s over past %.1f secs\n"
+                "  (%u mixer loops at %.1f mean ms per loop):\n"
+                "  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
+                "  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
+                "  MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
+                    title.string(),
                     elapsed * .000000001, n, perLoop * .000001,
                     mean * .001,
                     stddev * .001,
@@ -1971,7 +2038,12 @@
                     mean / perLoop100,
                     stddev / perLoop100,
                     minimum / perLoop100,
-                    maximum / perLoop100);
+                    maximum / perLoop100,
+                    meanCycles / perLoop1k,
+                    stddevCycles / perLoop1k,
+                    minCycles / perLoop1k,
+                    maxCycles / perLoop1k);
+
         }
     }
 #endif
@@ -2017,16 +2089,14 @@
     sleepTimeShift = 0;
 }
 
-    // MIXER
     CpuStats cpuStats;
+    const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
 
     acquireWakeLock();
 
     while (!exitPending())
     {
-if (mType == MIXER) {
-        cpuStats.sample();
-}
+        cpuStats.sample(myName);
 
         Vector< sp<EffectChain> > effectChains;
 
@@ -2063,9 +2133,9 @@
 
                     releaseWakeLock_l();
                     // wait until we have something to do...
-                    ALOGV("Thread %p type %d TID %d going to sleep", this, mType, gettid());
+                    ALOGV("%s going to sleep", myName.string());
                     mWaitWorkCV.wait(mLock);
-                    ALOGV("Thread %p type %d TID %d waking up", this, mType, gettid());
+                    ALOGV("%s waking up", myName.string());
                     acquireWakeLock_l();
 
                     mPrevMixerStatus = MIXER_IDLE;
@@ -2612,6 +2682,7 @@
             }
         }
         if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
+#ifdef ADD_BATTERY_DATA
             // when changing the audio output device, call addBatteryData to notify
             // the change
             if ((int)mDevice != value) {
@@ -2632,6 +2703,7 @@
                     addBatteryData(params);
                 }
             }
+#endif
 
             // forward device change to effects that have requested to be
             // aware of attached audio device.
@@ -3454,8 +3526,10 @@
                 if (mState == ACTIVE || mState == RESUMING) {
                     AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
 
+#ifdef ADD_BATTERY_DATA
                     // to track the speaker usage
                     addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
+#endif
                 }
                 AudioSystem::releaseOutput(thread->id());
             }
@@ -3572,10 +3646,12 @@
             status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
             thread->mLock.lock();
 
+#ifdef ADD_BATTERY_DATA
             // to track the speaker usage
             if (status == NO_ERROR) {
                 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
             }
+#endif
         }
         if (status == NO_ERROR) {
             PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
@@ -3610,8 +3686,10 @@
             AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
             thread->mLock.lock();
 
+#ifdef ADD_BATTERY_DATA
             // to track the speaker usage
             addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
+#endif
         }
     }
 }
@@ -3630,8 +3708,10 @@
                 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
                 thread->mLock.lock();
 
+#ifdef ADD_BATTERY_DATA
                 // to track the speaker usage
                 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
+#endif
             }
         }
     }
diff --git a/services/camera/libcameraservice/Android.mk b/services/camera/libcameraservice/Android.mk
index e35435e..3cae1f5 100644
--- a/services/camera/libcameraservice/Android.mk
+++ b/services/camera/libcameraservice/Android.mk
@@ -15,6 +15,7 @@
     libbinder \
     libcutils \
     libmedia \
+    libmedia_native \
     libcamera_client \
     libgui \
     libhardware
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index adf1d49..22836e3 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -21,6 +21,7 @@
 #include <stdio.h>
 #include <sys/types.h>
 #include <pthread.h>
+#include <time.h>
 
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
@@ -33,6 +34,7 @@
 #include <hardware/hardware.h>
 #include <media/AudioSystem.h>
 #include <media/mediaplayer.h>
+#include <utils/Condition.h>
 #include <utils/Errors.h>
 #include <utils/Log.h>
 #include <utils/String16.h>
@@ -42,6 +44,8 @@
 
 namespace android {
 
+#define WAIT_RELEASE_TIMEOUT 250 // 250ms
+
 // ----------------------------------------------------------------------------
 // Logging support -- this is for debugging only
 // Use "adb shell dumpsys media.camera -v 1" to change it.
@@ -64,6 +68,13 @@
     return IPCThreadState::self()->getCallingUid();
 }
 
+static long long getTimeInMs() {
+    struct timeval t;
+    t.tv_sec = t.tv_usec = 0;
+    gettimeofday(&t, NULL);
+    return t.tv_sec * 1000LL + t.tv_usec / 1000;
+}
+
 // ----------------------------------------------------------------------------
 
 // This is ugly and only safe if we never re-create the CameraService, but
@@ -131,7 +142,7 @@
 }
 
 sp<ICamera> CameraService::connect(
-        const sp<ICameraClient>& cameraClient, int cameraId) {
+        const sp<ICameraClient>& cameraClient, int cameraId, bool force, bool keep) {
     int callingPid = getCallingPid();
     sp<CameraHardwareInterface> hardware = NULL;
 
@@ -157,27 +168,73 @@
         return NULL;
     }
 
-    Mutex::Autolock lock(mServiceLock);
-    if (mClient[cameraId] != 0) {
-        client = mClient[cameraId].promote();
-        if (client != 0) {
-            if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) {
-                LOG1("CameraService::connect X (pid %d) (the same client)",
-                    callingPid);
-                return client;
-            } else {
-                ALOGW("CameraService::connect X (pid %d) rejected (existing client).",
-                    callingPid);
-                return NULL;
-            }
-        }
-        mClient[cameraId].clear();
+    if (keep && !checkCallingPermission(String16("android.permission.KEEP_CAMERA"))) {
+        ALOGE("connect X (pid %d) rejected (no KEEP_CAMERA permission).", callingPid);
+        return NULL;
     }
 
-    if (mBusy[cameraId]) {
-        ALOGW("CameraService::connect X (pid %d) rejected"
-             " (camera %d is still busy).", callingPid, cameraId);
-        return NULL;
+    Mutex::Autolock lock(mServiceLock);
+    // Check if there is an existing client.
+    client = mClient[cameraId].promote();
+    if (client != 0 &&
+            cameraClient->asBinder() == client->getCameraClient()->asBinder()) {
+        LOG1("connect X (pid %d) (the same client)", callingPid);
+        return client;
+    }
+
+    if (!force) {
+        if (mClient[cameraId].promote() != 0) {
+            ALOGW("connect X (pid %d) rejected (existing client).", callingPid);
+            return NULL;
+        }
+        mClient[cameraId].clear();
+        if (mBusy[cameraId]) {
+            ALOGW("connect X (pid %d) rejected (camera %d is still busy).",
+                  callingPid, cameraId);
+            return NULL;
+        }
+    } else { // force == true
+        int i = 0;
+        long long start_time = getTimeInMs();
+        while (i < mNumberOfCameras) {
+            if (getTimeInMs() - start_time >= 3000LL) {
+                ALOGE("connect X (pid %d) rejected (timeout 3s)", callingPid);
+                return NULL;
+            }
+
+            client = mClient[i].promote();
+            if (client != 0) {
+                if (client->keep()) {
+                    ALOGW("connect X (pid %d) rejected (existing client wants to keeps the camera)",
+                          callingPid);
+                    return NULL;
+                } else {
+                    ALOGW("New client (pid %d, id=%d). Disconnect the existing client (id=%d).",
+                         callingPid, cameraId, i);
+                    // Do not hold mServiceLock because disconnect will try to get it.
+                    mServiceLock.unlock();
+                    client->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0, &i);
+                    client->waitRelease(WAIT_RELEASE_TIMEOUT);
+                    client->disconnectInternal(false);
+                    mServiceLock.lock();
+                    // Restart from the first client because a new client may have connected
+                    // when mServiceLock is unlocked.
+                    i = 0;
+                    continue;
+                }
+            }
+
+            if (mBusy[i]) {
+                // Give the client a chance to release the hardware.
+                mServiceLock.unlock();
+                usleep(10 * 1000);
+                mServiceLock.lock();
+                i = 0; // Restart from the first client
+                continue;
+            }
+
+            i++;
+        }
     }
 
     struct camera_info info;
@@ -195,9 +252,15 @@
         return NULL;
     }
 
-    client = new Client(this, cameraClient, hardware, cameraId, info.facing, callingPid);
+    client = new Client(this, cameraClient, hardware, cameraId, info.facing,
+                        callingPid, keep);
+    // We need to clear the hardware here. After the destructor of mServiceLock
+    // finishes, a new client may connect and disconnect this client. If this
+    // reference is not cleared, the destructor of CameraHardwareInterface
+    // cannot run. The new client will not be able to connect.
+    hardware.clear();
     mClient[cameraId] = client;
-    LOG1("CameraService::connect X");
+    LOG1("CameraService::connect X (id %d)", cameraId);
     return client;
 }
 
@@ -331,9 +394,9 @@
 CameraService::Client::Client(const sp<CameraService>& cameraService,
         const sp<ICameraClient>& cameraClient,
         const sp<CameraHardwareInterface>& hardware,
-        int cameraId, int cameraFacing, int clientPid) {
+        int cameraId, int cameraFacing, int clientPid, bool keep) {
     int callingPid = getCallingPid();
-    LOG1("Client::Client E (pid %d)", callingPid);
+    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
 
     mCameraService = cameraService;
     mCameraClient = cameraClient;
@@ -341,6 +404,7 @@
     mCameraId = cameraId;
     mCameraFacing = cameraFacing;
     mClientPid = clientPid;
+    mKeep = keep;
     mMsgEnabled = 0;
     mSurface = 0;
     mPreviewWindow = 0;
@@ -359,7 +423,7 @@
     mPlayShutterSound = true;
     cameraService->setCameraBusy(cameraId);
     cameraService->loadSound();
-    LOG1("Client::Client X (pid %d)", callingPid);
+    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
 }
 
 // tear down the client
@@ -468,18 +532,24 @@
 }
 
 void CameraService::Client::disconnect() {
+    disconnectInternal(true);
+}
+
+void CameraService::Client::disconnectInternal(bool needCheckPid) {
     int callingPid = getCallingPid();
-    LOG1("disconnect E (pid %d)", callingPid);
+    LOG1("disconnectInternal E (pid %d)", callingPid);
     Mutex::Autolock lock(mLock);
 
-    if (checkPid() != NO_ERROR) {
-        ALOGW("different client - don't disconnect");
-        return;
-    }
+    if (needCheckPid) {
+        if (checkPid() != NO_ERROR) {
+            ALOGW("different client - don't disconnect");
+            return;
+        }
 
-    if (mClientPid <= 0) {
-        LOG1("camera is unlocked (mClientPid = %d), don't tear down hardware", mClientPid);
-        return;
+        if (mClientPid <= 0) {
+            LOG1("camera is unlocked (mClientPid = %d), don't tear down hardware", mClientPid);
+            return;
+        }
     }
 
     // Make sure disconnect() is done once and once only, whether it is called
@@ -506,8 +576,16 @@
 
     mCameraService->removeClient(mCameraClient);
     mCameraService->setCameraFree(mCameraId);
+    mReleaseCondition.signal();
 
-    LOG1("disconnect X (pid %d)", callingPid);
+    LOG1("disconnectInternal X (pid %d)", callingPid);
+}
+
+void CameraService::Client::waitRelease(int ms) {
+    Mutex::Autolock lock(mLock);
+    if (mHardware != 0) {
+        mReleaseCondition.waitRelative(mLock, ms * 1000000);
+    }
 }
 
 // ----------------------------------------------------------------------------
@@ -874,6 +952,9 @@
         return OK;
     } else if (cmd == CAMERA_CMD_PLAY_RECORDING_SOUND) {
         mCameraService->playSound(SOUND_RECORDING);
+    } else if (cmd == CAMERA_CMD_PING) {
+        // If mHardware is 0, checkPidAndHardware will return error.
+        return OK;
     }
 
     return mHardware->sendCommand(cmd, arg1, arg2);
@@ -1217,6 +1298,10 @@
     return -1;
 }
 
+// Whether the client wants to keep the camera from taking
+bool CameraService::Client::keep() const {
+    return mKeep;
+}
 
 // ----------------------------------------------------------------------------
 
diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h
index bad41f5..457c79b 100644
--- a/services/camera/libcameraservice/CameraService.h
+++ b/services/camera/libcameraservice/CameraService.h
@@ -46,7 +46,8 @@
     virtual int32_t     getNumberOfCameras();
     virtual status_t    getCameraInfo(int cameraId,
                                       struct CameraInfo* cameraInfo);
-    virtual sp<ICamera> connect(const sp<ICameraClient>& cameraClient, int cameraId);
+    virtual sp<ICamera> connect(const sp<ICameraClient>& cameraClient, int cameraId,
+                                bool force, bool keep);
     virtual void        removeClient(const sp<ICameraClient>& cameraClient);
     virtual sp<Client>  getClientById(int cameraId);
 
@@ -114,7 +115,8 @@
                                        const sp<CameraHardwareInterface>& hardware,
                                        int cameraId,
                                        int cameraFacing,
-                                       int clientPid);
+                                       int clientPid,
+                                       bool keep);
                                 ~Client();
 
         // return our camera client
@@ -172,12 +174,19 @@
                                     const sp<IBinder>& binder,
                                     const sp<ANativeWindow>& window);
 
+        void                    disconnectInternal(bool needCheckPid);
+        bool                    keep() const;
+        void                    waitRelease(int ms);
+
+
         // these are initialized in the constructor.
         sp<CameraService>               mCameraService;  // immutable after constructor
         sp<ICameraClient>               mCameraClient;
         int                             mCameraId;       // immutable after constructor
         int                             mCameraFacing;   // immutable after constructor
         pid_t                           mClientPid;
+        // Client wants to keep the camera from taking by other clients.
+        bool                            mKeep;
         sp<CameraHardwareInterface>     mHardware;       // cleared after disconnect()
         int                             mPreviewCallbackFlag;
         int                             mOrientation;     // Current display orientation
@@ -185,6 +194,8 @@
 
         // Ensures atomicity among the public methods
         mutable Mutex                   mLock;
+        // This will get notified when the hardware is released.
+        Condition                       mReleaseCondition;
         // This is a binder of Surface or SurfaceTexture.
         sp<IBinder>                     mSurface;
         sp<ANativeWindow>               mPreviewWindow;