Merge "LiveSession: Add support for block-by-block fetchFile."
diff --git a/camera/CameraParameters.cpp b/camera/CameraParameters.cpp
index c51f265..af091f4 100644
--- a/camera/CameraParameters.cpp
+++ b/camera/CameraParameters.cpp
@@ -470,7 +470,7 @@
     const size_t SIZE = 256;
     char buffer[SIZE];
     String8 result;
-    snprintf(buffer, 255, "CameraParameters::dump: mMap.size = %d\n", mMap.size());
+    snprintf(buffer, 255, "CameraParameters::dump: mMap.size = %zu\n", mMap.size());
     result.append(buffer);
     for (size_t i = 0; i < mMap.size(); i++) {
         String8 k, v;
diff --git a/cmds/stagefright/SineSource.cpp b/cmds/stagefright/SineSource.cpp
index 14b4306..587077a 100644
--- a/cmds/stagefright/SineSource.cpp
+++ b/cmds/stagefright/SineSource.cpp
@@ -24,7 +24,7 @@
     }
 }
 
-status_t SineSource::start(MetaData *params) {
+status_t SineSource::start(MetaData * /* params */) {
     CHECK(!mStarted);
 
     mGroup = new MediaBufferGroup;
@@ -58,7 +58,7 @@
 }
 
 status_t SineSource::read(
-        MediaBuffer **out, const ReadOptions *options) {
+        MediaBuffer **out, const ReadOptions * /* options */) {
     *out = NULL;
 
     MediaBuffer *buffer;
diff --git a/cmds/stagefright/codec.cpp b/cmds/stagefright/codec.cpp
index 098c899..fd02bcc 100644
--- a/cmds/stagefright/codec.cpp
+++ b/cmds/stagefright/codec.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "codec"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include "SimplePlayer.h"
@@ -292,13 +293,13 @@
         CHECK_EQ((status_t)OK, state->mCodec->release());
 
         if (state->mIsAudio) {
-            printf("track %d: %lld bytes received. %.2f KB/sec\n",
+            printf("track %zu: %" PRId64 " bytes received. %.2f KB/sec\n",
                    i,
                    state->mNumBytesDecoded,
                    state->mNumBytesDecoded * 1E6 / 1024 / elapsedTimeUs);
         } else {
-            printf("track %d: %lld frames decoded, %.2f fps. %lld bytes "
-                   "received. %.2f KB/sec\n",
+            printf("track %zu: %" PRId64 " frames decoded, %.2f fps. %" PRId64
+                    " bytes received. %.2f KB/sec\n",
                    i,
                    state->mNumBuffersDecoded,
                    state->mNumBuffersDecoded * 1E6 / elapsedTimeUs,
diff --git a/cmds/stagefright/muxer.cpp b/cmds/stagefright/muxer.cpp
index c0747f8..f4a33e8 100644
--- a/cmds/stagefright/muxer.cpp
+++ b/cmds/stagefright/muxer.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "muxer"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include <binder/ProcessState.h>
@@ -199,7 +200,7 @@
     trackIndexMap.clear();
 
     int64_t elapsedTimeUs = ALooper::GetNowUs() - muxerStartTimeUs;
-    fprintf(stderr, "SUCCESS: muxer generate the video in %lld ms\n",
+    fprintf(stderr, "SUCCESS: muxer generate the video in %" PRId64 " ms\n",
             elapsedTimeUs / 1000);
 
     return 0;
diff --git a/cmds/stagefright/record.cpp b/cmds/stagefright/record.cpp
index b7a40c2..fdc352e 100644
--- a/cmds/stagefright/record.cpp
+++ b/cmds/stagefright/record.cpp
@@ -296,7 +296,7 @@
 }
 #else
 
-int main(int argc, char **argv) {
+int main(int /* argc */, char ** /* argv */) {
     android::ProcessState::self()->startThreadPool();
 
     OMXClient client;
diff --git a/cmds/stagefright/recordvideo.cpp b/cmds/stagefright/recordvideo.cpp
index c30c122..1d267f9 100644
--- a/cmds/stagefright/recordvideo.cpp
+++ b/cmds/stagefright/recordvideo.cpp
@@ -16,6 +16,7 @@
 
 #include "SineSource.h"
 
+#include <inttypes.h>
 #include <binder/ProcessState.h>
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/AudioPlayer.h>
@@ -312,7 +313,7 @@
         fprintf(stderr, "record failed: %d\n", err);
         return 1;
     }
-    fprintf(stderr, "encoding %d frames in %lld us\n", nFrames, (end-start)/1000);
+    fprintf(stderr, "encoding %d frames in %" PRId64 " us\n", nFrames, (end-start)/1000);
     fprintf(stderr, "encoding speed is: %.2f fps\n", (nFrames * 1E9) / (end-start));
     return 0;
 }
diff --git a/cmds/stagefright/sf2.cpp b/cmds/stagefright/sf2.cpp
index 627610f..3c0c7ec 100644
--- a/cmds/stagefright/sf2.cpp
+++ b/cmds/stagefright/sf2.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "sf2"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include <signal.h>
@@ -80,17 +81,18 @@
 
     virtual void printStatistics() {
         int64_t delayUs = ALooper::GetNowUs() - mStartTimeUs;
+
         if (mDecodeAudio) {
-            printf("%lld bytes received. %.2f KB/sec\n",
-                   mTotalBytesReceived,
-                   mTotalBytesReceived * 1E6 / 1024 / delayUs);
+            printf("%" PRId64 " bytes received. %.2f KB/sec\n",
+            mTotalBytesReceived,
+            mTotalBytesReceived * 1E6 / 1024 / delayUs);
         } else {
-            printf("%d frames decoded, %.2f fps. %lld bytes "
-                   "received. %.2f KB/sec\n",
-                   mNumOutputBuffersReceived,
-                   mNumOutputBuffersReceived * 1E6 / delayUs,
-                   mTotalBytesReceived,
-                   mTotalBytesReceived * 1E6 / 1024 / delayUs);
+            printf("%d frames decoded, %.2f fps. %" PRId64 " bytes "
+                    "received. %.2f KB/sec\n",
+            mNumOutputBuffersReceived,
+            mNumOutputBuffersReceived * 1E6 / delayUs,
+            mTotalBytesReceived,
+            mTotalBytesReceived * 1E6 / 1024 / delayUs);
         }
     }
 
diff --git a/cmds/stagefright/stagefright.cpp b/cmds/stagefright/stagefright.cpp
index eb1db4b..daaea27 100644
--- a/cmds/stagefright/stagefright.cpp
+++ b/cmds/stagefright/stagefright.cpp
@@ -22,6 +22,7 @@
 
 #include <stdlib.h>
 #include <string.h>
+#include <inttypes.h>
 
 #include "jpeg.h"
 #include "SineSource.h"
@@ -90,8 +91,8 @@
     int64_t minUs = decodeTimesUs->itemAt(0);
     int64_t maxUs = decodeTimesUs->itemAt(n - 1);
 
-    printf("min decode time %lld us (%.2f secs)\n", minUs, minUs / 1E6);
-    printf("max decode time %lld us (%.2f secs)\n", maxUs, maxUs / 1E6);
+    printf("min decode time %" PRId64 " us (%.2f secs)\n", minUs, minUs / 1E6);
+    printf("max decode time %" PRId64 " us (%.2f secs)\n", maxUs, maxUs / 1E6);
 
     size_t counts[100];
     for (size_t i = 0; i < 100; ++i) {
@@ -111,7 +112,7 @@
         int64_t slotUs = minUs + (i * (maxUs - minUs) / 100);
 
         double fps = 1E6 / slotUs;
-        printf("[%.2f fps]: %d\n", fps, counts[i]);
+        printf("[%.2f fps]: %zu\n", fps, counts[i]);
     }
 }
 
@@ -263,7 +264,7 @@
                     }
                 }
 
-                printf("buffer has timestamp %lld us (%.2f secs)\n",
+                printf("buffer has timestamp %" PRId64 " us (%.2f secs)\n",
                        timestampUs, timestampUs / 1E6);
 
                 buffer->release();
@@ -286,7 +287,7 @@
                 seekTimeUs = (rand() * (float)durationUs) / RAND_MAX;
                 options.setSeekTo(seekTimeUs);
 
-                printf("seeking to %lld us (%.2f secs)\n",
+                printf("seeking to %" PRId64 " us (%.2f secs)\n",
                        seekTimeUs, seekTimeUs / 1E6);
             }
         }
@@ -389,7 +390,7 @@
         // sizes may be different across decoders.
         printf("avg. %.2f KB/sec\n", totalBytes / 1024 * 1E6 / delay);
 
-        printf("decoded a total of %lld bytes\n", totalBytes);
+        printf("decoded a total of %" PRId64 " bytes\n", totalBytes);
     }
 }
 
@@ -575,7 +576,8 @@
             int64_t timeUs;
             CHECK(buffer->meta_data()->findInt64(kKeyTime, &timeUs));
 
-            printf("%lld\t%lld\t%lld\n", seekTimeUs, timeUs, seekTimeUs - timeUs);
+            printf("%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n",
+                   seekTimeUs, timeUs, seekTimeUs - timeUs);
 
             buffer->release();
             buffer = NULL;
@@ -1073,7 +1075,7 @@
 
                 int64_t thumbTimeUs;
                 if (meta->findInt64(kKeyThumbnailTime, &thumbTimeUs)) {
-                    printf("thumbnailTime: %lld us (%.2f secs)\n",
+                    printf("thumbnailTime: %" PRId64 " us (%.2f secs)\n",
                            thumbTimeUs, thumbTimeUs / 1E6);
                 }
 
diff --git a/drm/mediadrm/plugins/mock/MockDrmCryptoPlugin.cpp b/drm/mediadrm/plugins/mock/MockDrmCryptoPlugin.cpp
index f2cadf7..69fa7a0fc 100644
--- a/drm/mediadrm/plugins/mock/MockDrmCryptoPlugin.cpp
+++ b/drm/mediadrm/plugins/mock/MockDrmCryptoPlugin.cpp
@@ -695,7 +695,7 @@
     {
         String8 result;
         for (size_t i = 0; i < numSubSamples; i++) {
-            result.appendFormat("[%d] {clear:%d, encrypted:%d} ", i,
+            result.appendFormat("[%zu] {clear:%zu, encrypted:%zu} ", i,
                                 subSamples[i].mNumBytesOfClearData,
                                 subSamples[i].mNumBytesOfEncryptedData);
         }
diff --git a/include/media/AudioEffect.h b/include/media/AudioEffect.h
index 05d834d..f3024b7 100644
--- a/include/media/AudioEffect.h
+++ b/include/media/AudioEffect.h
@@ -36,7 +36,7 @@
 
 // ----------------------------------------------------------------------------
 
-class effect_param_cblk_t;
+struct effect_param_cblk_t;
 
 // ----------------------------------------------------------------------------
 
diff --git a/include/media/AudioRecord.h b/include/media/AudioRecord.h
index 33fa121..7054fd4 100644
--- a/include/media/AudioRecord.h
+++ b/include/media/AudioRecord.h
@@ -26,7 +26,7 @@
 
 // ----------------------------------------------------------------------------
 
-class audio_track_cblk_t;
+struct audio_track_cblk_t;
 class AudioRecordClientProxy;
 
 // ----------------------------------------------------------------------------
diff --git a/include/media/AudioSystem.h b/include/media/AudioSystem.h
index 5abab8a..fd86737 100644
--- a/include/media/AudioSystem.h
+++ b/include/media/AudioSystem.h
@@ -133,16 +133,16 @@
     // NOTE: this feature is not supported on all hardware platforms and it is
     // necessary to check returned status before using the returned values.
     static status_t getRenderPosition(audio_io_handle_t output,
-                                      size_t *halFrames,
-                                      size_t *dspFrames,
+                                      uint32_t *halFrames,
+                                      uint32_t *dspFrames,
                                       audio_stream_type_t stream = AUDIO_STREAM_DEFAULT);
 
     // return the number of input frames lost by HAL implementation, or 0 if the handle is invalid
     static uint32_t getInputFramesLost(audio_io_handle_t ioHandle);
 
     static int newAudioSessionId();
-    static void acquireAudioSessionId(int audioSession);
-    static void releaseAudioSessionId(int audioSession);
+    static void acquireAudioSessionId(int audioSession, pid_t pid);
+    static void releaseAudioSessionId(int audioSession, pid_t pid);
 
     // types of io configuration change events received with ioConfigChanged()
     enum io_config_event {
diff --git a/include/media/AudioTrack.h b/include/media/AudioTrack.h
index 3a60217..d0df710 100644
--- a/include/media/AudioTrack.h
+++ b/include/media/AudioTrack.h
@@ -27,7 +27,7 @@
 
 // ----------------------------------------------------------------------------
 
-class audio_track_cblk_t;
+struct audio_track_cblk_t;
 class AudioTrackClientProxy;
 class StaticAudioTrackClientProxy;
 
@@ -190,7 +190,8 @@
                                     int sessionId        = AUDIO_SESSION_ALLOCATE,
                                     transfer_type transferType = TRANSFER_DEFAULT,
                                     const audio_offload_info_t *offloadInfo = NULL,
-                                    int uid = -1);
+                                    int uid = -1,
+                                    pid_t pid = -1);
 
     /* Creates an audio track and registers it with AudioFlinger.
      * With this constructor, the track is configured for static buffer mode.
@@ -215,7 +216,8 @@
                                     int sessionId       = AUDIO_SESSION_ALLOCATE,
                                     transfer_type transferType = TRANSFER_DEFAULT,
                                     const audio_offload_info_t *offloadInfo = NULL,
-                                    int uid = -1);
+                                    int uid = -1,
+                                    pid_t pid = -1);
 
     /* Terminates the AudioTrack and unregisters it from AudioFlinger.
      * Also destroys all resources associated with the AudioTrack.
@@ -253,7 +255,8 @@
                             int sessionId       = AUDIO_SESSION_ALLOCATE,
                             transfer_type transferType = TRANSFER_DEFAULT,
                             const audio_offload_info_t *offloadInfo = NULL,
-                            int uid = -1);
+                            int uid = -1,
+                            pid_t pid = -1);
 
     /* Result of constructing the AudioTrack. This must be checked for successful initialization
      * before using any AudioTrack API (except for set()), because using
@@ -757,6 +760,7 @@
     sp<DeathNotifier>       mDeathNotifier;
     uint32_t                mSequence;              // incremented for each new IAudioTrack attempt
     int                     mClientUid;
+    pid_t                   mClientPid;
 };
 
 class TimedAudioTrack : public AudioTrack
diff --git a/include/media/IAudioFlinger.h b/include/media/IAudioFlinger.h
index 4bd111a..7f53bfc 100644
--- a/include/media/IAudioFlinger.h
+++ b/include/media/IAudioFlinger.h
@@ -173,15 +173,15 @@
 
     virtual status_t setVoiceVolume(float volume) = 0;
 
-    virtual status_t getRenderPosition(size_t *halFrames, size_t *dspFrames,
+    virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
                                     audio_io_handle_t output) const = 0;
 
     virtual uint32_t getInputFramesLost(audio_io_handle_t ioHandle) const = 0;
 
     virtual int newAudioSessionId() = 0;
 
-    virtual void acquireAudioSessionId(int audioSession) = 0;
-    virtual void releaseAudioSessionId(int audioSession) = 0;
+    virtual void acquireAudioSessionId(int audioSession, pid_t pid) = 0;
+    virtual void releaseAudioSessionId(int audioSession, pid_t pid) = 0;
 
     virtual status_t queryNumberEffects(uint32_t *numEffects) const = 0;
 
diff --git a/include/media/stagefright/DataURISource.h b/include/media/stagefright/DataURISource.h
new file mode 100644
index 0000000..693562e
--- /dev/null
+++ b/include/media/stagefright/DataURISource.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2014 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 DATA_URI_SOURCE_H_
+
+#define DATA_URI_SOURCE_H_
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/foundation/ABase.h>
+
+namespace android {
+
+struct ABuffer;
+
+struct DataURISource : public DataSource {
+    static sp<DataURISource> Create(const char *uri);
+
+    virtual status_t initCheck() const;
+    virtual ssize_t readAt(off64_t offset, void *data, size_t size);
+    virtual status_t getSize(off64_t *size);
+
+protected:
+    virtual ~DataURISource();
+
+private:
+    sp<ABuffer> mBuffer;
+
+    DataURISource(const sp<ABuffer> &buffer);
+
+    DISALLOW_EVIL_CONSTRUCTORS(DataURISource);
+};
+
+}  // namespace android
+
+#endif  // DATA_URI_SOURCE_H_
+
diff --git a/include/media/stagefright/MediaSource.h b/include/media/stagefright/MediaSource.h
index 3818e63..204d1c6 100644
--- a/include/media/stagefright/MediaSource.h
+++ b/include/media/stagefright/MediaSource.h
@@ -105,7 +105,7 @@
     // This will be called after a successful start() and before the
     // first read() call.
     // Callee assumes ownership of the buffers if no error is returned.
-    virtual status_t setBuffers(const Vector<MediaBuffer *> &buffers) {
+    virtual status_t setBuffers(const Vector<MediaBuffer *> & /* buffers */) {
         return ERROR_UNSUPPORTED;
     }
 
diff --git a/libvideoeditor/lvpp/VideoEditorAudioPlayer.cpp b/libvideoeditor/lvpp/VideoEditorAudioPlayer.cpp
index 176f8e9..e503936 100755
--- a/libvideoeditor/lvpp/VideoEditorAudioPlayer.cpp
+++ b/libvideoeditor/lvpp/VideoEditorAudioPlayer.cpp
@@ -671,8 +671,9 @@
 
 
                         M4OSA_Void* ptr;
-                        ptr = (M4OSA_Void*)((unsigned int)mInputBuffer->data() +
-                        mInputBuffer->range_offset());
+                        ptr = reinterpret_cast<M4OSA_Void*>(
+                                reinterpret_cast<uintptr_t>(mInputBuffer->data()) +
+                                mInputBuffer->range_offset());
 
                         M4OSA_UInt32 len = mInputBuffer->range_length();
                         M4OSA_Context fp = M4OSA_NULL;
diff --git a/libvideoeditor/lvpp/VideoEditorSRC.cpp b/libvideoeditor/lvpp/VideoEditorSRC.cpp
index 36d0812..6beabfa 100755
--- a/libvideoeditor/lvpp/VideoEditorSRC.cpp
+++ b/libvideoeditor/lvpp/VideoEditorSRC.cpp
@@ -284,7 +284,7 @@
 
 
 void VideoEditorSRC::releaseBuffer(AudioBufferProvider::Buffer *pBuffer) {
-    ALOGV("releaseBuffer: %p", pBuffers);
+    ALOGV("releaseBuffer: %p", pBuffer);
     free(pBuffer->raw);
     pBuffer->raw = NULL;
     pBuffer->frameCount = 0;
diff --git a/libvideoeditor/vss/src/M4DECODER_Null.c b/libvideoeditor/vss/src/M4DECODER_Null.c
index a0dad30..ce260e5 100755
--- a/libvideoeditor/vss/src/M4DECODER_Null.c
+++ b/libvideoeditor/vss/src/M4DECODER_Null.c
@@ -210,7 +210,7 @@
             break;

 

         case M4DECODER_kOptionID_EnableYuvWithEffect:

-            pStreamContext->bYuvWithEffectSet = (M4OSA_Bool)pValue;

+            pStreamContext->bYuvWithEffectSet = (M4OSA_Bool)(intptr_t)pValue;

             break;

 

         case M4DECODER_kOptionID_YuvWithEffectNonContiguous:

diff --git a/libvideoeditor/vss/stagefrightshells/src/VideoEditorUtils.cpp b/libvideoeditor/vss/stagefrightshells/src/VideoEditorUtils.cpp
index 5a7237d..d264a2e 100755
--- a/libvideoeditor/vss/stagefrightshells/src/VideoEditorUtils.cpp
+++ b/libvideoeditor/vss/stagefrightshells/src/VideoEditorUtils.cpp
@@ -84,17 +84,17 @@
         LOG1("displayMetaData kKeyBitRate %d", int32Data);
     }
     if (meta->findData(kKeyESDS, &type, &data, &size)) {
-        LOG1("displayMetaData kKeyESDS type=%d size=%d", type, size);
+        LOG1("displayMetaData kKeyESDS type=%d size=%zu", type, size);
     }
     if (meta->findData(kKeyAVCC, &type, &data, &size)) {
-        LOG1("displayMetaData kKeyAVCC data=0x%X type=%d size=%d",
+        LOG1("displayMetaData kKeyAVCC data=0x%X type=%d size=%zu",
             *((unsigned int*)data), type, size);
     }
     if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) {
-        LOG1("displayMetaData kKeyVorbisInfo type=%d size=%d", type, size);
+        LOG1("displayMetaData kKeyVorbisInfo type=%d size=%zu", type, size);
     }
     if (meta->findData(kKeyVorbisBooks, &type, &data, &size)) {
-        LOG1("displayMetaData kKeyVorbisBooks type=%d size=%d", type, size);
+        LOG1("displayMetaData kKeyVorbisBooks type=%d size=%zu", type, size);
     }
     if (meta->findInt32(kKeyWantsNALFragments, &int32Data)) {
         LOG1("displayMetaData kKeyWantsNALFragments %d", int32Data);
@@ -115,7 +115,7 @@
         LOG1("displayMetaData kKeyColorFormat %d", int32Data);
     }
     if (meta->findPointer(kKeyPlatformPrivate, &ptr)) {
-        LOG1("displayMetaData kKeyPlatformPrivate pointer=0x%x", (int32_t) ptr);
+        LOG1("displayMetaData kKeyPlatformPrivate pointer=%p", ptr);
     }
     if (meta->findCString(kKeyDecoderComponent, &charData)) {
         LOG1("displayMetaData kKeyDecoderComponent %s", charData);
@@ -151,7 +151,7 @@
         LOG1("displayMetaData kKeyYear %s", charData);
     }
     if (meta->findData(kKeyAlbumArt, &type, &data, &size)) {
-        LOG1("displayMetaData kKeyAlbumArt type=%d size=%d", type, size);
+        LOG1("displayMetaData kKeyAlbumArt type=%d size=%zu", type, size);
     }
     if (meta->findCString(kKeyAlbumArtMIME, &charData)) {
         LOG1("displayMetaData kKeyAlbumArtMIME %s", charData);
@@ -277,7 +277,7 @@
     }
 
     if (size < 4) {
-        ALOGE("Codec specific data length too short: %d", size);
+        ALOGE("Codec specific data length too short: %zu", size);
         return ERROR_MALFORMED;
     }
 
@@ -286,7 +286,7 @@
         // 2 bytes for each of the parameter set length field
         // plus the 7 bytes for the header
         if (size < 4 + 7) {
-            ALOGE("Codec specific data length too short: %d", size);
+            ALOGE("Codec specific data length too short: %zu", size);
             return ERROR_MALFORMED;
         }
 
@@ -355,7 +355,7 @@
         }
 
         if (nSeqParamSets > 0x1F) {
-            ALOGE("Too many seq parameter sets (%d) found", nSeqParamSets);
+            ALOGE("Too many seq parameter sets (%zu) found", nSeqParamSets);
             return ERROR_MALFORMED;
         }
     }
@@ -368,7 +368,7 @@
             return ERROR_MALFORMED;
         }
         if (nPicParamSets > 0xFF) {
-            ALOGE("Too many pic parameter sets (%d) found", nPicParamSets);
+            ALOGE("Too many pic parameter sets (%zu) found", nPicParamSets);
             return ERROR_MALFORMED;
         }
     }
diff --git a/media/libeffects/downmix/EffectDownmix.c b/media/libeffects/downmix/EffectDownmix.c
index f779876..4ee05f2 100644
--- a/media/libeffects/downmix/EffectDownmix.c
+++ b/media/libeffects/downmix/EffectDownmix.c
@@ -707,7 +707,7 @@
 
       case DOWNMIX_PARAM_TYPE:
         if (size != sizeof(downmix_type_t)) {
-            ALOGE("Downmix_setParameter(DOWNMIX_PARAM_TYPE) invalid size %d, should be %d",
+            ALOGE("Downmix_setParameter(DOWNMIX_PARAM_TYPE) invalid size %zu, should be %zu",
                     size, sizeof(downmix_type_t));
             return -EINVAL;
         }
@@ -760,7 +760,7 @@
 
     case DOWNMIX_PARAM_TYPE:
       if (*pSize < sizeof(int16_t)) {
-          ALOGE("Downmix_getParameter invalid parameter size %d for DOWNMIX_PARAM_TYPE", *pSize);
+          ALOGE("Downmix_getParameter invalid parameter size %zu for DOWNMIX_PARAM_TYPE", *pSize);
           return -EINVAL;
       }
       pValue16 = (int16_t *)pValue;
diff --git a/media/libeffects/factory/Android.mk b/media/libeffects/factory/Android.mk
index 60a6ce5..a932af7 100644
--- a/media/libeffects/factory/Android.mk
+++ b/media/libeffects/factory/Android.mk
@@ -9,7 +9,6 @@
 LOCAL_SHARED_LIBRARIES := \
 	libcutils liblog
 
-LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)
 LOCAL_MODULE:= libeffects
 
 LOCAL_SHARED_LIBRARIES += libdl
diff --git a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Init.c b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Init.c
index c4767a8..e01c1c5 100644
--- a/media/libeffects/lvm/lib/Eq/src/LVEQNB_Init.c
+++ b/media/libeffects/lvm/lib/Eq/src/LVEQNB_Init.c
@@ -25,6 +25,7 @@
 #include "LVEQNB.h"
 #include "LVEQNB_Private.h"
 #include "InstAlloc.h"
+#include <string.h> /* For memset */
 
 /****************************************************************************************/
 /*                                                                                      */
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
index 28d239a..58d7767 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
@@ -138,22 +138,22 @@
 int  BassBoost_setParameter    (EffectContext *pContext, void *pParam, void *pValue);
 int  BassBoost_getParameter    (EffectContext *pContext,
                                void           *pParam,
-                               size_t         *pValueSize,
+                               uint32_t       *pValueSize,
                                void           *pValue);
 int  Virtualizer_setParameter  (EffectContext *pContext, void *pParam, void *pValue);
 int  Virtualizer_getParameter  (EffectContext *pContext,
                                void           *pParam,
-                               size_t         *pValueSize,
+                               uint32_t       *pValueSize,
                                void           *pValue);
 int  Equalizer_setParameter    (EffectContext *pContext, void *pParam, void *pValue);
 int  Equalizer_getParameter    (EffectContext *pContext,
                                 void          *pParam,
-                                size_t        *pValueSize,
+                                uint32_t      *pValueSize,
                                 void          *pValue);
 int  Volume_setParameter       (EffectContext *pContext, void *pParam, void *pValue);
 int  Volume_getParameter       (EffectContext *pContext,
                                 void          *pParam,
-                                size_t        *pValueSize,
+                                uint32_t      *pValueSize,
                                 void          *pValue);
 int Effect_setEnabled(EffectContext *pContext, bool enabled);
 
@@ -1758,7 +1758,7 @@
 
 int BassBoost_getParameter(EffectContext     *pContext,
                            void              *pParam,
-                           size_t            *pValueSize,
+                           uint32_t          *pValueSize,
                            void              *pValue){
     int status = 0;
     int32_t *pParamTemp = (int32_t *)pParam;
@@ -1876,7 +1876,7 @@
 
 int Virtualizer_getParameter(EffectContext        *pContext,
                              void                 *pParam,
-                             size_t               *pValueSize,
+                             uint32_t             *pValueSize,
                              void                 *pValue){
     int status = 0;
     int32_t *pParamTemp = (int32_t *)pParam;
@@ -1994,7 +1994,7 @@
 //----------------------------------------------------------------------------
 int Equalizer_getParameter(EffectContext     *pContext,
                            void              *pParam,
-                           size_t            *pValueSize,
+                           uint32_t          *pValueSize,
                            void              *pValue){
     int status = 0;
     int bMute = 0;
@@ -2252,7 +2252,7 @@
 
 int Volume_getParameter(EffectContext     *pContext,
                         void              *pParam,
-                        size_t            *pValueSize,
+                        uint32_t          *pValueSize,
                         void              *pValue){
     int status = 0;
     int bMute = 0;
@@ -2830,7 +2830,7 @@
 
                 p->status = android::BassBoost_getParameter(pContext,
                                                             p->data,
-                                                            (size_t  *)&p->vsize,
+                                                            &p->vsize,
                                                             p->data + voffset);
 
                 *replySize = sizeof(effect_param_t) + voffset + p->vsize;
@@ -2860,8 +2860,8 @@
                 int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
 
                 p->status = android::Virtualizer_getParameter(pContext,
-                                                             (void *)p->data,
-                                                             (size_t  *)&p->vsize,
+                                                              (void *)p->data,
+                                                              &p->vsize,
                                                               p->data + voffset);
 
                 *replySize = sizeof(effect_param_t) + voffset + p->vsize;
@@ -2925,7 +2925,7 @@
 
                 p->status = android::Volume_getParameter(pContext,
                                                          (void *)p->data,
-                                                         (size_t  *)&p->vsize,
+                                                         &p->vsize,
                                                          p->data + voffset);
 
                 *replySize = sizeof(effect_param_t) + voffset + p->vsize;
diff --git a/media/libeffects/preprocessing/PreProcessing.cpp b/media/libeffects/preprocessing/PreProcessing.cpp
index d72eaf5..c56ff72 100644
--- a/media/libeffects/preprocessing/PreProcessing.cpp
+++ b/media/libeffects/preprocessing/PreProcessing.cpp
@@ -1233,8 +1233,8 @@
             if (session->framesIn < session->frameCount) {
                 return 0;
             }
-            size_t frIn = session->framesIn;
-            size_t frOut = session->apmFrameCount;
+            spx_uint32_t frIn = session->framesIn;
+            spx_uint32_t frOut = session->apmFrameCount;
             if (session->inChannelCount == 1) {
                 speex_resampler_process_int(session->inResampler,
                                             0,
@@ -1290,8 +1290,8 @@
         }
 
         if (session->outResampler != NULL) {
-            size_t frIn = session->apmFrameCount;
-            size_t frOut = session->frameCount;
+            spx_uint32_t frIn = session->apmFrameCount;
+            spx_uint32_t frOut = session->frameCount;
             if (session->inChannelCount == 1) {
                 speex_resampler_process_int(session->outResampler,
                                     0,
@@ -1754,8 +1754,8 @@
             if (session->framesRev < session->frameCount) {
                 return 0;
             }
-            size_t frIn = session->framesRev;
-            size_t frOut = session->apmFrameCount;
+            spx_uint32_t frIn = session->framesRev;
+            spx_uint32_t frOut = session->apmFrameCount;
             if (session->inChannelCount == 1) {
                 speex_resampler_process_int(session->revResampler,
                                             0,
diff --git a/media/libmedia/AudioRecord.cpp b/media/libmedia/AudioRecord.cpp
index a9ba154..6ca499b 100644
--- a/media/libmedia/AudioRecord.cpp
+++ b/media/libmedia/AudioRecord.cpp
@@ -52,7 +52,7 @@
     }
 
     if (size == 0) {
-        ALOGE("Unsupported configuration: sampleRate %u, format %d, channelMask %#x",
+        ALOGE("Unsupported configuration: sampleRate %u, format %#x, channelMask %#x",
             sampleRate, format, channelMask);
         return BAD_VALUE;
     }
@@ -115,7 +115,7 @@
             mAudioRecord.clear();
         }
         IPCThreadState::self()->flushCommands();
-        AudioSystem::releaseAudioSessionId(mSessionId);
+        AudioSystem::releaseAudioSessionId(mSessionId, -1);
     }
 }
 
@@ -191,12 +191,12 @@
 
     // validate parameters
     if (!audio_is_valid_format(format)) {
-        ALOGE("Invalid format %d", format);
+        ALOGE("Invalid format %#x", format);
         return BAD_VALUE;
     }
     // Temporary restriction: AudioFlinger currently supports 16-bit PCM only
     if (format != AUDIO_FORMAT_PCM_16_BIT) {
-        ALOGE("Format %d is not supported", format);
+        ALOGE("Format %#x is not supported", format);
         return BAD_VALUE;
     }
     mFormat = format;
@@ -266,7 +266,7 @@
     mMarkerReached = false;
     mNewPosition = 0;
     mUpdatePeriod = 0;
-    AudioSystem::acquireAudioSessionId(mSessionId);
+    AudioSystem::acquireAudioSessionId(mSessionId, -1);
     mSequence = 1;
     mObservedSequence = mSequence;
     mInOverrun = false;
diff --git a/media/libmedia/AudioSystem.cpp b/media/libmedia/AudioSystem.cpp
index e224d20..140fb66 100644
--- a/media/libmedia/AudioSystem.cpp
+++ b/media/libmedia/AudioSystem.cpp
@@ -374,7 +374,7 @@
         }
         inBuffSize = af->getInputBufferSize(sampleRate, format, channelMask);
         if (inBuffSize == 0) {
-            ALOGE("AudioSystem::getInputBufferSize failed sampleRate %d format %x channelMask %x",
+            ALOGE("AudioSystem::getInputBufferSize failed sampleRate %d format %#x channelMask %x",
                     sampleRate, format, channelMask);
             return BAD_VALUE;
         }
@@ -400,8 +400,8 @@
     return af->setVoiceVolume(value);
 }
 
-status_t AudioSystem::getRenderPosition(audio_io_handle_t output, size_t *halFrames,
-                                        size_t *dspFrames, audio_stream_type_t stream)
+status_t AudioSystem::getRenderPosition(audio_io_handle_t output, uint32_t *halFrames,
+                                        uint32_t *dspFrames, audio_stream_type_t stream)
 {
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af == 0) return PERMISSION_DENIED;
@@ -435,19 +435,19 @@
     return af->newAudioSessionId();
 }
 
-void AudioSystem::acquireAudioSessionId(int audioSession)
+void AudioSystem::acquireAudioSessionId(int audioSession, pid_t pid)
 {
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af != 0) {
-        af->acquireAudioSessionId(audioSession);
+        af->acquireAudioSessionId(audioSession, pid);
     }
 }
 
-void AudioSystem::releaseAudioSessionId(int audioSession)
+void AudioSystem::releaseAudioSessionId(int audioSession, pid_t pid)
 {
     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
     if (af != 0) {
-        af->releaseAudioSessionId(audioSession);
+        af->releaseAudioSessionId(audioSession, pid);
     }
 }
 
@@ -490,7 +490,7 @@
 
         OutputDescriptor *outputDesc =  new OutputDescriptor(*desc);
         gOutputs.add(ioHandle, outputDesc);
-        ALOGV("ioConfigChanged() new output samplingRate %u, format %d channel mask %#x frameCount %u "
+        ALOGV("ioConfigChanged() new output samplingRate %u, format %#x channel mask %#x frameCount %u "
                 "latency %d",
                 outputDesc->samplingRate, outputDesc->format, outputDesc->channelMask,
                 outputDesc->frameCount, outputDesc->latency);
@@ -514,7 +514,7 @@
         if (param2 == NULL) break;
         desc = (const OutputDescriptor *)param2;
 
-        ALOGV("ioConfigChanged() new config for output %d samplingRate %u, format %d channel mask %#x "
+        ALOGV("ioConfigChanged() new config for output %d samplingRate %u, format %#x channel mask %#x "
                 "frameCount %d latency %d",
                 ioHandle, desc->samplingRate, desc->format,
                 desc->channelMask, desc->frameCount, desc->latency);
diff --git a/media/libmedia/AudioTrack.cpp b/media/libmedia/AudioTrack.cpp
index cfd79bc..5c62260 100644
--- a/media/libmedia/AudioTrack.cpp
+++ b/media/libmedia/AudioTrack.cpp
@@ -116,7 +116,8 @@
         int sessionId,
         transfer_type transferType,
         const audio_offload_info_t *offloadInfo,
-        int uid)
+        int uid,
+        pid_t pid)
     : mStatus(NO_INIT),
       mIsTimed(false),
       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
@@ -125,7 +126,7 @@
     mStatus = set(streamType, sampleRate, format, channelMask,
             frameCount, flags, cbf, user, notificationFrames,
             0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
-            offloadInfo, uid);
+            offloadInfo, uid, pid);
 }
 
 AudioTrack::AudioTrack(
@@ -141,7 +142,8 @@
         int sessionId,
         transfer_type transferType,
         const audio_offload_info_t *offloadInfo,
-        int uid)
+        int uid,
+        pid_t pid)
     : mStatus(NO_INIT),
       mIsTimed(false),
       mPreviousPriority(ANDROID_PRIORITY_NORMAL),
@@ -149,7 +151,8 @@
 {
     mStatus = set(streamType, sampleRate, format, channelMask,
             0 /*frameCount*/, flags, cbf, user, notificationFrames,
-            sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo, uid);
+            sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
+            uid, pid);
 }
 
 AudioTrack::~AudioTrack()
@@ -168,7 +171,9 @@
         mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
         mAudioTrack.clear();
         IPCThreadState::self()->flushCommands();
-        AudioSystem::releaseAudioSessionId(mSessionId);
+        ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
+                IPCThreadState::self()->getCallingPid(), mClientPid);
+        AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
     }
 }
 
@@ -187,7 +192,8 @@
         int sessionId,
         transfer_type transferType,
         const audio_offload_info_t *offloadInfo,
-        int uid)
+        int uid,
+        pid_t pid)
 {
     switch (transferType) {
     case TRANSFER_DEFAULT:
@@ -273,7 +279,7 @@
 
     // validate parameters
     if (!audio_is_valid_format(format)) {
-        ALOGE("Invalid format %d", format);
+        ALOGE("Invalid format %#x", format);
         return BAD_VALUE;
     }
     mFormat = format;
@@ -335,11 +341,18 @@
     mNotificationFramesReq = notificationFrames;
     mNotificationFramesAct = 0;
     mSessionId = sessionId;
-    if (uid == -1 || (IPCThreadState::self()->getCallingPid() != getpid())) {
+    int callingpid = IPCThreadState::self()->getCallingPid();
+    int mypid = getpid();
+    if (uid == -1 || (callingpid != mypid)) {
         mClientUid = IPCThreadState::self()->getCallingUid();
     } else {
         mClientUid = uid;
     }
+    if (pid == -1 || (callingpid != mypid)) {
+        mClientPid = callingpid;
+    } else {
+        mClientPid = pid;
+    }
     mAuxEffectId = 0;
     mFlags = flags;
     mCbf = cbf;
@@ -379,7 +392,7 @@
     mMarkerReached = false;
     mNewPosition = 0;
     mUpdatePeriod = 0;
-    AudioSystem::acquireAudioSessionId(mSessionId);
+    AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
     mSequence = 1;
     mObservedSequence = mSequence;
     mInUnderrun = false;
@@ -773,7 +786,7 @@
     return NO_ERROR;
 }
 
-status_t AudioTrack::getBufferPosition(size_t *position)
+status_t AudioTrack::getBufferPosition(uint32_t *position)
 {
     if (mSharedBuffer == 0 || mIsTimed) {
         return INVALID_OPERATION;
@@ -871,12 +884,14 @@
 
     // Client decides whether the track is TIMED (see below), but can only express a preference
     // for FAST.  Server will perform additional tests.
-    if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !(
+    if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
             // either of these use cases:
             // use case 1: shared buffer
             (mSharedBuffer != 0) ||
             // use case 2: callback handler
-            (mCbf != NULL))) {
+            (mCbf != NULL)) &&
+            // matching sample rate
+            (mSampleRate == afSampleRate))) {
         ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
         // once denied, do not request again if IAudioTrack is re-created
         mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
@@ -915,7 +930,7 @@
             // More than 2 channels does not require stronger alignment than stereo
             alignment <<= 1;
         }
-        if (((size_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
+        if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
             ALOGE("Invalid buffer alignment: address %p, channel count %u",
                     mSharedBuffer->pointer(), mChannelCount);
             status = BAD_VALUE;
@@ -1264,7 +1279,7 @@
     if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
         // Sanity-check: user is most-likely passing an error code, and it would
         // make the return value ambiguous (actualSize vs error).
-        ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)", buffer, userSize, userSize);
+        ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
         return BAD_VALUE;
     }
 
@@ -1809,7 +1824,7 @@
     snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
             mVolume[0], mVolume[1]);
     result.append(buffer);
-    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%d)\n", mFormat,
+    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%zu)\n", mFormat,
             mChannelCount, mFrameCount);
     result.append(buffer);
     snprintf(buffer, 255, "  sample rate(%u), status(%d)\n", mSampleRate, mStatus);
diff --git a/media/libmedia/IAudioFlinger.cpp b/media/libmedia/IAudioFlinger.cpp
index f3f3e15..7b15e68 100644
--- a/media/libmedia/IAudioFlinger.cpp
+++ b/media/libmedia/IAudioFlinger.cpp
@@ -564,7 +564,7 @@
         return reply.readInt32();
     }
 
-    virtual status_t getRenderPosition(size_t *halFrames, size_t *dspFrames,
+    virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
             audio_io_handle_t output) const
     {
         Parcel data, reply;
@@ -609,19 +609,21 @@
         return id;
     }
 
-    virtual void acquireAudioSessionId(int audioSession)
+    virtual void acquireAudioSessionId(int audioSession, int pid)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32(audioSession);
+        data.writeInt32(pid);
         remote()->transact(ACQUIRE_AUDIO_SESSION_ID, data, &reply);
     }
 
-    virtual void releaseAudioSessionId(int audioSession)
+    virtual void releaseAudioSessionId(int audioSession, int pid)
     {
         Parcel data, reply;
         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
         data.writeInt32(audioSession);
+        data.writeInt32(pid);
         remote()->transact(RELEASE_AUDIO_SESSION_ID, data, &reply);
     }
 
@@ -1058,8 +1060,8 @@
         case GET_RENDER_POSITION: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             audio_io_handle_t output = (audio_io_handle_t) data.readInt32();
-            size_t halFrames;
-            size_t dspFrames;
+            uint32_t halFrames;
+            uint32_t dspFrames;
             status_t status = getRenderPosition(&halFrames, &dspFrames, output);
             reply->writeInt32(status);
             if (status == NO_ERROR) {
@@ -1082,13 +1084,15 @@
         case ACQUIRE_AUDIO_SESSION_ID: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int audioSession = data.readInt32();
-            acquireAudioSessionId(audioSession);
+            int pid = data.readInt32();
+            acquireAudioSessionId(audioSession, pid);
             return NO_ERROR;
         } break;
         case RELEASE_AUDIO_SESSION_ID: {
             CHECK_INTERFACE(IAudioFlinger, data, reply);
             int audioSession = data.readInt32();
-            releaseAudioSessionId(audioSession);
+            int pid = data.readInt32();
+            releaseAudioSessionId(audioSession, pid);
             return NO_ERROR;
         } break;
         case QUERY_NUM_EFFECTS: {
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index 24663ad..d94c7c5 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -58,7 +58,7 @@
     mVideoWidth = mVideoHeight = 0;
     mLockThreadId = 0;
     mAudioSessionId = AudioSystem::newAudioSessionId();
-    AudioSystem::acquireAudioSessionId(mAudioSessionId);
+    AudioSystem::acquireAudioSessionId(mAudioSessionId, -1);
     mSendLevel = 0;
     mRetransmitEndpointValid = false;
 }
@@ -66,7 +66,7 @@
 MediaPlayer::~MediaPlayer()
 {
     ALOGV("destructor");
-    AudioSystem::releaseAudioSessionId(mAudioSessionId);
+    AudioSystem::releaseAudioSessionId(mAudioSessionId, -1);
     disconnect();
     IPCThreadState::self()->flushCommands();
 }
@@ -576,8 +576,8 @@
         return BAD_VALUE;
     }
     if (sessionId != mAudioSessionId) {
-        AudioSystem::acquireAudioSessionId(sessionId);
-        AudioSystem::releaseAudioSessionId(mAudioSessionId);
+        AudioSystem::acquireAudioSessionId(sessionId, -1);
+        AudioSystem::releaseAudioSessionId(mAudioSessionId, -1);
         mAudioSessionId = sessionId;
     }
     return NO_ERROR;
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index f1bc79c..142788d 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -315,7 +315,7 @@
 
     result.append(" AudioCache\n");
     if (mHeap != 0) {
-        snprintf(buffer, 255, "  heap base(%p), size(%d), flags(%d)\n",
+        snprintf(buffer, 255, "  heap base(%p), size(%zu), flags(%d)\n",
                 mHeap->getBase(), mHeap->getSize(), mHeap->getFlags());
         result.append(buffer);
     }
@@ -586,7 +586,8 @@
     }
 
     if (!p->hardwareOutput()) {
-        mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid());
+        mAudioOutput = new AudioOutput(mAudioSessionId, IPCThreadState::self()->getCallingUid(),
+                mPid);
         static_cast<MediaPlayerInterface*>(p.get())->setAudioSink(mAudioOutput);
     }
 
@@ -1299,13 +1300,14 @@
 
 #undef LOG_TAG
 #define LOG_TAG "AudioSink"
-MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid)
+MediaPlayerService::AudioOutput::AudioOutput(int sessionId, int uid, int pid)
     : mCallback(NULL),
       mCallbackCookie(NULL),
       mCallbackData(NULL),
       mBytesWritten(0),
       mSessionId(sessionId),
       mUid(uid),
+      mPid(pid),
       mFlags(AUDIO_OUTPUT_FLAG_NONE) {
     ALOGV("AudioOutput(%d)", sessionId);
     mStreamType = AUDIO_STREAM_MUSIC;
@@ -1554,7 +1556,8 @@
                     mSessionId,
                     AudioTrack::TRANSFER_CALLBACK,
                     offloadInfo,
-                    mUid);
+                    mUid,
+                    mPid);
         } else {
             t = new AudioTrack(
                     mStreamType,
@@ -1569,7 +1572,8 @@
                     mSessionId,
                     AudioTrack::TRANSFER_DEFAULT,
                     NULL, // offload info
-                    mUid);
+                    mUid,
+                    mPid);
         }
 
         if ((t == 0) || (t->initCheck() != NO_ERROR)) {
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index fc355b0..448f27a 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -72,7 +72,7 @@
         class CallbackData;
 
      public:
-                                AudioOutput(int sessionId, int uid);
+                                AudioOutput(int sessionId, int uid, int pid);
         virtual                 ~AudioOutput();
 
         virtual bool            ready() const { return mTrack != 0; }
@@ -140,6 +140,7 @@
         float                   mMsecsPerFrame;
         int                     mSessionId;
         int                     mUid;
+        int                     mPid;
         float                   mSendLevel;
         int                     mAuxEffectId;
         static bool             mIsOnEmulator;
diff --git a/media/libmediaplayerservice/StagefrightPlayer.cpp b/media/libmediaplayerservice/StagefrightPlayer.cpp
index b19e8bf..b37aee3 100644
--- a/media/libmediaplayerservice/StagefrightPlayer.cpp
+++ b/media/libmediaplayerservice/StagefrightPlayer.cpp
@@ -189,7 +189,7 @@
 }
 
 status_t StagefrightPlayer::getMetadata(
-        const media::Metadata::Filter& ids, Parcel *records) {
+        const media::Metadata::Filter& /* ids */, Parcel *records) {
     using media::Metadata;
 
     uint32_t flags = mPlayer->flags();
diff --git a/media/libmediaplayerservice/StagefrightRecorder.cpp b/media/libmediaplayerservice/StagefrightRecorder.cpp
index 1ee0ee4..d377acd 100644
--- a/media/libmediaplayerservice/StagefrightRecorder.cpp
+++ b/media/libmediaplayerservice/StagefrightRecorder.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "StagefrightRecorder"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include "StagefrightRecorder.h"
@@ -242,7 +243,7 @@
     return OK;
 }
 
-status_t StagefrightRecorder::setOutputFile(const char *path) {
+status_t StagefrightRecorder::setOutputFile(const char * /* path */) {
     ALOGE("setOutputFile(const char*) must not be called");
     // We don't actually support this at all, as the media_server process
     // no longer has permissions to create files.
@@ -1745,15 +1746,15 @@
     result.append(buffer);
     snprintf(buffer, SIZE, "     File format: %d\n", mOutputFormat);
     result.append(buffer);
-    snprintf(buffer, SIZE, "     Max file size (bytes): %lld\n", mMaxFileSizeBytes);
+    snprintf(buffer, SIZE, "     Max file size (bytes): %" PRId64 "\n", mMaxFileSizeBytes);
     result.append(buffer);
-    snprintf(buffer, SIZE, "     Max file duration (us): %lld\n", mMaxFileDurationUs);
+    snprintf(buffer, SIZE, "     Max file duration (us): %" PRId64 "\n", mMaxFileDurationUs);
     result.append(buffer);
     snprintf(buffer, SIZE, "     File offset length (bits): %d\n", mUse64BitFileOffset? 64: 32);
     result.append(buffer);
     snprintf(buffer, SIZE, "     Interleave duration (us): %d\n", mInterleaveDurationUs);
     result.append(buffer);
-    snprintf(buffer, SIZE, "     Progress notification: %lld us\n", mTrackEveryTimeDurationUs);
+    snprintf(buffer, SIZE, "     Progress notification: %" PRId64 " us\n", mTrackEveryTimeDurationUs);
     result.append(buffer);
     snprintf(buffer, SIZE, "   Audio\n");
     result.append(buffer);
diff --git a/media/libmediaplayerservice/nuplayer/Android.mk b/media/libmediaplayerservice/nuplayer/Android.mk
index f946c1c..f97ba57 100644
--- a/media/libmediaplayerservice/nuplayer/Android.mk
+++ b/media/libmediaplayerservice/nuplayer/Android.mk
@@ -11,7 +11,6 @@
         NuPlayerStreamListener.cpp      \
         RTSPSource.cpp                  \
         StreamingSource.cpp             \
-        mp4/MP4Source.cpp               \
 
 LOCAL_C_INCLUDES := \
 	$(TOP)/frameworks/av/media/libstagefright/httplive            \
diff --git a/media/libmediaplayerservice/nuplayer/HTTPLiveSource.cpp b/media/libmediaplayerservice/nuplayer/HTTPLiveSource.cpp
index ac2aab8..cbedf5c 100644
--- a/media/libmediaplayerservice/nuplayer/HTTPLiveSource.cpp
+++ b/media/libmediaplayerservice/nuplayer/HTTPLiveSource.cpp
@@ -139,7 +139,7 @@
     // LiveSession::selectTrack returns BAD_VALUE when selecting the currently
     // selected track, or unselecting a non-selected track. In this case it's an
     // no-op so we return OK.
-    return (err == OK || err == BAD_VALUE) ? OK : err;
+    return (err == OK || err == BAD_VALUE) ? (status_t)OK : err;
 }
 
 status_t NuPlayer::HTTPLiveSource::seekTo(int64_t seekTimeUs) {
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index 817395a..d47ac98 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -28,13 +28,11 @@
 #include "RTSPSource.h"
 #include "StreamingSource.h"
 #include "GenericSource.h"
-#include "mp4/MP4Source.h"
 
 #include "ATSParser.h"
 
 #include "SoftwareRenderer.h"
 
-#include <cutils/properties.h> // for property_get
 #include <media/stagefright/foundation/hexdump.h>
 #include <media/stagefright/foundation/ABuffer.h>
 #include <media/stagefright/foundation/ADebug.h>
@@ -183,14 +181,7 @@
 
     sp<AMessage> notify = new AMessage(kWhatSourceNotify, id());
 
-    char prop[PROPERTY_VALUE_MAX];
-    if (property_get("media.stagefright.use-mp4source", prop, NULL)
-            && (!strcmp(prop, "1") || !strcasecmp(prop, "true"))) {
-        msg->setObject("source", new MP4Source(notify, source));
-    } else {
-        msg->setObject("source", new StreamingSource(notify, source));
-    }
-
+    msg->setObject("source", new StreamingSource(notify, source));
     msg->post();
 }
 
@@ -1528,7 +1519,7 @@
     notify->post();
 }
 
-void NuPlayer::Source::onMessageReceived(const sp<AMessage> &msg) {
+void NuPlayer::Source::onMessageReceived(const sp<AMessage> & /* msg */) {
     TRESPASS();
 }
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
index d35d1df..e4850f0 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerDriver.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "NuPlayerDriver"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include "NuPlayerDriver.h"
@@ -366,7 +367,7 @@
     return OK;
 }
 
-status_t NuPlayerDriver::setLooping(int loop) {
+status_t NuPlayerDriver::setLooping(int /* loop */) {
     return INVALID_OPERATION;
 }
 
@@ -422,16 +423,17 @@
     mPlayer->setAudioSink(audioSink);
 }
 
-status_t NuPlayerDriver::setParameter(int key, const Parcel &request) {
+status_t NuPlayerDriver::setParameter(
+        int /* key */, const Parcel & /* request */) {
     return INVALID_OPERATION;
 }
 
-status_t NuPlayerDriver::getParameter(int key, Parcel *reply) {
+status_t NuPlayerDriver::getParameter(int /* key */, Parcel * /* reply */) {
     return INVALID_OPERATION;
 }
 
 status_t NuPlayerDriver::getMetadata(
-        const media::Metadata::Filter& ids, Parcel *records) {
+        const media::Metadata::Filter& /* ids */, Parcel *records) {
     Mutex::Autolock autoLock(mLock);
 
     using media::Metadata;
@@ -495,13 +497,14 @@
     mNumFramesDropped = numFramesDropped;
 }
 
-status_t NuPlayerDriver::dump(int fd, const Vector<String16> &args) const {
+status_t NuPlayerDriver::dump(
+        int fd, const Vector<String16> & /* args */) const {
     Mutex::Autolock autoLock(mLock);
 
     FILE *out = fdopen(dup(fd), "w");
 
     fprintf(out, " NuPlayer\n");
-    fprintf(out, "  numFramesTotal(%lld), numFramesDropped(%lld), "
+    fprintf(out, "  numFramesTotal(%" PRId64 "), numFramesDropped(%" PRId64 "), "
                  "percentageDropped(%.2f)\n",
                  mNumFramesTotal,
                  mNumFramesDropped,
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerSource.h b/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
index e50533a..11279fc 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
@@ -68,19 +68,19 @@
     virtual status_t dequeueAccessUnit(
             bool audio, sp<ABuffer> *accessUnit) = 0;
 
-    virtual status_t getDuration(int64_t *durationUs) {
+    virtual status_t getDuration(int64_t * /* durationUs */) {
         return INVALID_OPERATION;
     }
 
-    virtual status_t getTrackInfo(Parcel* reply) const {
+    virtual status_t getTrackInfo(Parcel* /* reply */) const {
         return INVALID_OPERATION;
     }
 
-    virtual status_t selectTrack(size_t trackIndex, bool select) {
+    virtual status_t selectTrack(size_t /* trackIndex */, bool /* select */) {
         return INVALID_OPERATION;
     }
 
-    virtual status_t seekTo(int64_t seekTimeUs) {
+    virtual status_t seekTo(int64_t /* seekTimeUs */) {
         return INVALID_OPERATION;
     }
 
@@ -93,7 +93,7 @@
 
     virtual void onMessageReceived(const sp<AMessage> &msg);
 
-    virtual sp<MetaData> getFormatMeta(bool audio) { return NULL; }
+    virtual sp<MetaData> getFormatMeta(bool /* audio */) { return NULL; }
 
     sp<AMessage> dupNotify() const { return mNotify->dup(); }
 
diff --git a/media/libmediaplayerservice/nuplayer/mp4/MP4Source.cpp b/media/libmediaplayerservice/nuplayer/mp4/MP4Source.cpp
deleted file mode 100644
index d31d947..0000000
--- a/media/libmediaplayerservice/nuplayer/mp4/MP4Source.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2012 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 "MP4Source.h"
-
-#include "FragmentedMP4Parser.h"
-#include "../NuPlayerStreamListener.h"
-
-#include <media/IStreamSource.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MetaData.h>
-
-namespace android {
-
-struct StreamSource : public FragmentedMP4Parser::Source {
-    StreamSource(const sp<IStreamSource> &source)
-        : mListener(new NuPlayer::NuPlayerStreamListener(source, 0)),
-          mPosition(0) {
-        mListener->start();
-    }
-
-    virtual ssize_t readAt(off64_t offset, void *data, size_t size) {
-        if (offset < mPosition) {
-            return -EPIPE;
-        }
-
-        while (offset > mPosition) {
-            char buffer[1024];
-            off64_t skipBytes = offset - mPosition;
-            if (skipBytes > sizeof(buffer)) {
-                skipBytes = sizeof(buffer);
-            }
-
-            sp<AMessage> extra;
-            ssize_t n;
-            for (;;) {
-                n = mListener->read(buffer, skipBytes, &extra);
-
-                if (n == -EWOULDBLOCK) {
-                    usleep(10000);
-                    continue;
-                }
-
-                break;
-            }
-
-            ALOGV("skipped %ld bytes at offset %lld", n, mPosition);
-
-            if (n < 0) {
-                return n;
-            }
-
-            mPosition += n;
-        }
-
-        sp<AMessage> extra;
-        size_t total = 0;
-        while (total < size) {
-            ssize_t n = mListener->read(
-                    (uint8_t *)data + total, size - total, &extra);
-
-            if (n == -EWOULDBLOCK) {
-                usleep(10000);
-                continue;
-            } else if (n == 0) {
-                break;
-            } else if (n < 0) {
-                mPosition += total;
-                return n;
-            }
-
-            total += n;
-        }
-
-        ALOGV("read %ld bytes at offset %lld", n, mPosition);
-
-        mPosition += total;
-
-        return total;
-    }
-
-    bool isSeekable() {
-        return false;
-    }
-
-private:
-    sp<NuPlayer::NuPlayerStreamListener> mListener;
-    off64_t mPosition;
-
-    DISALLOW_EVIL_CONSTRUCTORS(StreamSource);
-};
-
-MP4Source::MP4Source(
-        const sp<AMessage> &notify, const sp<IStreamSource> &source)
-    : Source(notify),
-      mSource(source),
-      mLooper(new ALooper),
-      mParser(new FragmentedMP4Parser),
-      mEOS(false) {
-    mLooper->registerHandler(mParser);
-}
-
-MP4Source::~MP4Source() {
-}
-
-void MP4Source::prepareAsync() {
-    notifyVideoSizeChanged(0, 0);
-    notifyFlagsChanged(0);
-    notifyPrepared();
-}
-
-void MP4Source::start() {
-    mLooper->start(false /* runOnCallingThread */);
-    mParser->start(new StreamSource(mSource));
-}
-
-status_t MP4Source::feedMoreTSData() {
-    return mEOS ? ERROR_END_OF_STREAM : (status_t)OK;
-}
-
-sp<AMessage> MP4Source::getFormat(bool audio) {
-    return mParser->getFormat(audio);
-}
-
-status_t MP4Source::dequeueAccessUnit(
-        bool audio, sp<ABuffer> *accessUnit) {
-    return mParser->dequeueAccessUnit(audio, accessUnit);
-}
-
-}  // namespace android
diff --git a/media/libmediaplayerservice/nuplayer/mp4/MP4Source.h b/media/libmediaplayerservice/nuplayer/mp4/MP4Source.h
deleted file mode 100644
index a6ef622..0000000
--- a/media/libmediaplayerservice/nuplayer/mp4/MP4Source.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2012 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 MP4_SOURCE_H
-#define MP4_SOURCE_H
-
-#include "NuPlayerSource.h"
-
-namespace android {
-
-struct FragmentedMP4Parser;
-
-struct MP4Source : public NuPlayer::Source {
-    MP4Source(const sp<AMessage> &notify, const sp<IStreamSource> &source);
-
-    virtual void prepareAsync();
-    virtual void start();
-
-    virtual status_t feedMoreTSData();
-
-    virtual sp<AMessage> getFormat(bool audio);
-
-    virtual status_t dequeueAccessUnit(
-            bool audio, sp<ABuffer> *accessUnit);
-
-protected:
-    virtual ~MP4Source();
-
-private:
-    sp<IStreamSource> mSource;
-    sp<ALooper> mLooper;
-    sp<FragmentedMP4Parser> mParser;
-    bool mEOS;
-
-    DISALLOW_EVIL_CONSTRUCTORS(MP4Source);
-};
-
-}  // namespace android
-
-#endif // MP4_SOURCE_H
diff --git a/media/libnbaio/NBLog.cpp b/media/libnbaio/NBLog.cpp
index ba8d0b4..190824d 100644
--- a/media/libnbaio/NBLog.cpp
+++ b/media/libnbaio/NBLog.cpp
@@ -340,7 +340,7 @@
     if (i > 0) {
         lost += i;
         if (fd >= 0) {
-            fdprintf(fd, "%*swarning: lost %u bytes worth of events\n", indent, "", lost);
+            fdprintf(fd, "%*swarning: lost %zu bytes worth of events\n", indent, "", lost);
         } else {
             ALOGI("%*swarning: lost %u bytes worth of events\n", indent, "", lost);
         }
diff --git a/media/libstagefright/AACExtractor.cpp b/media/libstagefright/AACExtractor.cpp
index 4d1072f..196f6ee 100644
--- a/media/libstagefright/AACExtractor.cpp
+++ b/media/libstagefright/AACExtractor.cpp
@@ -219,7 +219,7 @@
     return new AACSource(mDataSource, mMeta, mOffsetVector, mFrameDurationUs);
 }
 
-sp<MetaData> AACExtractor::getTrackMetaData(size_t index, uint32_t flags) {
+sp<MetaData> AACExtractor::getTrackMetaData(size_t index, uint32_t /* flags */) {
     if (mInitCheck != OK || index != 0) {
         return NULL;
     }
@@ -252,7 +252,7 @@
     }
 }
 
-status_t AACSource::start(MetaData *params) {
+status_t AACSource::start(MetaData * /* params */) {
     CHECK(!mStarted);
 
     if (mOffsetVector.empty()) {
diff --git a/media/libstagefright/AACWriter.cpp b/media/libstagefright/AACWriter.cpp
index a6f7cfb..deee8e7 100644
--- a/media/libstagefright/AACWriter.cpp
+++ b/media/libstagefright/AACWriter.cpp
@@ -111,7 +111,7 @@
     return OK;
 }
 
-status_t AACWriter::start(MetaData *params) {
+status_t AACWriter::start(MetaData * /* params */) {
     if (mInitCheck != OK) {
         return mInitCheck;
     }
@@ -171,7 +171,7 @@
     void *dummy;
     pthread_join(mThread, &dummy);
 
-    status_t err = (status_t) dummy;
+    status_t err = static_cast<status_t>(reinterpret_cast<uintptr_t>(dummy));
     {
         status_t status = mSource->stop();
         if (err == OK &&
@@ -200,7 +200,7 @@
 
 // static
 void *AACWriter::ThreadWrapper(void *me) {
-    return (void *) static_cast<AACWriter *>(me)->threadFunc();
+    return (void *)(uintptr_t)static_cast<AACWriter *>(me)->threadFunc();
 }
 
 /*
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index f2354b4..ac78d6c 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -1171,7 +1171,7 @@
             if (canDoAdaptivePlayback &&
                 msg->findInt32("max-width", &maxWidth) &&
                 msg->findInt32("max-height", &maxHeight)) {
-                ALOGV("[%s] prepareForAdaptivePlayback(%ldx%ld)",
+                ALOGV("[%s] prepareForAdaptivePlayback(%dx%d)",
                       mComponentName.c_str(), maxWidth, maxHeight);
 
                 err = mOMX->prepareForAdaptivePlayback(
@@ -2967,7 +2967,8 @@
       mCodec(codec) {
 }
 
-ACodec::BaseState::PortMode ACodec::BaseState::getPortMode(OMX_U32 portIndex) {
+ACodec::BaseState::PortMode ACodec::BaseState::getPortMode(
+        OMX_U32 /* portIndex */) {
     return KEEP_BUFFERS;
 }
 
@@ -3376,8 +3377,8 @@
         size_t rangeOffset, size_t rangeLength,
         OMX_U32 flags,
         int64_t timeUs,
-        void *platformPrivate,
-        void *dataPtr) {
+        void * /* platformPrivate */,
+        void * /* dataPtr */) {
     ALOGV("[%s] onOMXFillBufferDone %p time %lld us, flags = 0x%08lx",
          mCodec->mComponentName.c_str(), bufferID, timeUs, flags);
 
@@ -3910,7 +3911,7 @@
 }
 
 void ACodec::LoadedState::onCreateInputSurface(
-        const sp<AMessage> &msg) {
+        const sp<AMessage> & /* msg */) {
     ALOGV("onCreateInputSurface");
 
     sp<AMessage> notify = mCodec->mNotify->dup();
@@ -4154,7 +4155,7 @@
 }
 
 ACodec::BaseState::PortMode ACodec::ExecutingState::getPortMode(
-        OMX_U32 portIndex) {
+        OMX_U32 /* portIndex */) {
     return RESUBMIT_BUFFERS;
 }
 
diff --git a/media/libstagefright/AMRExtractor.cpp b/media/libstagefright/AMRExtractor.cpp
index 03dcbf9..3f592ed 100644
--- a/media/libstagefright/AMRExtractor.cpp
+++ b/media/libstagefright/AMRExtractor.cpp
@@ -189,7 +189,7 @@
             mOffsetTable, mOffsetTableLength);
 }
 
-sp<MetaData> AMRExtractor::getTrackMetaData(size_t index, uint32_t flags) {
+sp<MetaData> AMRExtractor::getTrackMetaData(size_t index, uint32_t /* flags */) {
     if (mInitCheck != OK || index != 0) {
         return NULL;
     }
@@ -221,7 +221,7 @@
     }
 }
 
-status_t AMRSource::start(MetaData *params) {
+status_t AMRSource::start(MetaData * /* params */) {
     CHECK(!mStarted);
 
     mOffset = mIsWide ? 9 : 6;
@@ -258,7 +258,7 @@
         int64_t seekFrame = seekTimeUs / 20000ll;  // 20ms per frame.
         mCurrentTimeUs = seekFrame * 20000ll;
 
-        int index = seekFrame / 50;
+        size_t index = seekFrame < 0 ? 0 : seekFrame / 50;
         if (index >= mOffsetTableLength) {
             index = mOffsetTableLength - 1;
         }
diff --git a/media/libstagefright/AMRWriter.cpp b/media/libstagefright/AMRWriter.cpp
index 8d5eec8..653ca36 100644
--- a/media/libstagefright/AMRWriter.cpp
+++ b/media/libstagefright/AMRWriter.cpp
@@ -105,7 +105,7 @@
     return OK;
 }
 
-status_t AMRWriter::start(MetaData *params) {
+status_t AMRWriter::start(MetaData * /* params */) {
     if (mInitCheck != OK) {
         return mInitCheck;
     }
@@ -162,7 +162,7 @@
     void *dummy;
     pthread_join(mThread, &dummy);
 
-    status_t err = (status_t) dummy;
+    status_t err = static_cast<status_t>(reinterpret_cast<uintptr_t>(dummy));
     {
         status_t status = mSource->stop();
         if (err == OK &&
@@ -191,7 +191,7 @@
 
 // static
 void *AMRWriter::ThreadWrapper(void *me) {
-    return (void *) static_cast<AMRWriter *>(me)->threadFunc();
+    return (void *)(uintptr_t) static_cast<AMRWriter *>(me)->threadFunc();
 }
 
 status_t AMRWriter::threadFunc() {
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index 63f9399..0636dcc 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -15,6 +15,7 @@
         CameraSource.cpp                  \
         CameraSourceTimeLapse.cpp         \
         DataSource.cpp                    \
+        DataURISource.cpp                 \
         DRMExtractor.cpp                  \
         ESDS.cpp                          \
         FileSource.cpp                    \
@@ -57,8 +58,6 @@
         WVMExtractor.cpp                  \
         XINGSeeker.cpp                    \
         avc_utils.cpp                     \
-        mp4/FragmentedMP4Parser.cpp       \
-        mp4/TrackFragment.cpp             \
 
 LOCAL_C_INCLUDES:= \
         $(TOP)/frameworks/av/include/media/stagefright/timedtext \
diff --git a/media/libstagefright/AudioPlayer.cpp b/media/libstagefright/AudioPlayer.cpp
index 05ee34e..8623100 100644
--- a/media/libstagefright/AudioPlayer.cpp
+++ b/media/libstagefright/AudioPlayer.cpp
@@ -410,7 +410,7 @@
 
 // static
 size_t AudioPlayer::AudioSinkCallback(
-        MediaPlayerBase::AudioSink *audioSink,
+        MediaPlayerBase::AudioSink * /* audioSink */,
         void *buffer, size_t size, void *cookie,
         MediaPlayerBase::AudioSink::cb_event_t event) {
     AudioPlayer *me = (AudioPlayer *)cookie;
diff --git a/media/libstagefright/AudioSource.cpp b/media/libstagefright/AudioSource.cpp
index cadadc8..df7da0a 100644
--- a/media/libstagefright/AudioSource.cpp
+++ b/media/libstagefright/AudioSource.cpp
@@ -68,7 +68,7 @@
         int frameCount = kMaxBufferSize / sizeof(int16_t) / channelCount;
 
         // make sure that the AudioRecord total buffer size is large enough
-        int bufCount = 2;
+        size_t bufCount = 2;
         while ((bufCount * frameCount) < minFrameCount) {
             bufCount++;
         }
@@ -208,7 +208,7 @@
 }
 
 status_t AudioSource::read(
-        MediaBuffer **out, const ReadOptions *options) {
+        MediaBuffer **out, const ReadOptions * /* options */) {
     Mutex::Autolock autoLock(mLock);
     *out = NULL;
 
@@ -308,7 +308,7 @@
     if (numLostBytes > 0) {
         // Loss of audio frames should happen rarely; thus the LOGW should
         // not cause a logging spam
-        ALOGW("Lost audio record data: %d bytes", numLostBytes);
+        ALOGW("Lost audio record data: %zu bytes", numLostBytes);
     }
 
     while (numLostBytes > 0) {
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index 67ea052..e83ec62 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -19,6 +19,7 @@
 //#define LOG_NDEBUG 0
 #define LOG_TAG "AwesomePlayer"
 #define ATRACE_TAG ATRACE_TAG_VIDEO
+#include <inttypes.h>
 #include <utils/Log.h>
 #include <utils/Trace.h>
 
@@ -85,7 +86,7 @@
 protected:
     virtual ~AwesomeEvent() {}
 
-    virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) {
+    virtual void fire(TimedEventQueue * /* queue */, int64_t /* now_us */) {
         (mPlayer->*mMethod)();
     }
 
@@ -734,7 +735,7 @@
 
                 if ((mFlags & PLAYING) && !eos
                         && (cachedDataRemaining < kLowWaterMarkBytes)) {
-                    ALOGI("cache is running low (< %d) , pausing.",
+                    ALOGI("cache is running low (< %zu) , pausing.",
                          kLowWaterMarkBytes);
                     modifyFlags(CACHE_UNDERRUN, SET);
                     pause_l();
@@ -743,12 +744,12 @@
                     notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START);
                 } else if (eos || cachedDataRemaining > kHighWaterMarkBytes) {
                     if (mFlags & CACHE_UNDERRUN) {
-                        ALOGI("cache has filled up (> %d), resuming.",
+                        ALOGI("cache has filled up (> %zu), resuming.",
                              kHighWaterMarkBytes);
                         modifyFlags(CACHE_UNDERRUN, CLEAR);
                         play_l();
                     } else if (mFlags & PREPARING) {
-                        ALOGV("cache has filled up (> %d), prepare is done",
+                        ALOGV("cache has filled up (> %zu), prepare is done",
                              kHighWaterMarkBytes);
                         finishAsyncPrepare_l();
                     }
@@ -2303,8 +2304,8 @@
                         sniffedMIME = tmp.string();
 
                         if (meta == NULL
-                                || !meta->findInt64(
-                                    "meta-data-size", &metaDataSize)) {
+                                || !meta->findInt64("meta-data-size",
+                                     reinterpret_cast<int64_t*>(&metaDataSize))) {
                             metaDataSize = kHighWaterMarkBytes;
                         }
 
@@ -2592,12 +2593,12 @@
 status_t AwesomePlayer::selectAudioTrack_l(
         const sp<MediaSource>& source, size_t trackIndex) {
 
-    ALOGI("selectAudioTrack_l: trackIndex=%d, mFlags=0x%x", trackIndex, mFlags);
+    ALOGI("selectAudioTrack_l: trackIndex=%zu, mFlags=0x%x", trackIndex, mFlags);
 
     {
         Mutex::Autolock autoLock(mStatsLock);
         if ((ssize_t)trackIndex == mActiveAudioTrackIndex) {
-            ALOGI("Track %d is active. Does nothing.", trackIndex);
+            ALOGI("Track %zu is active. Does nothing.", trackIndex);
             return OK;
         }
         //mStats.mFlags = mFlags;
@@ -2670,7 +2671,7 @@
         trackCount += mTextDriver->countExternalTracks();
     }
     if (trackIndex >= trackCount) {
-        ALOGE("Track index (%d) is out of range [0, %d)", trackIndex, trackCount);
+        ALOGE("Track index (%zu) is out of range [0, %zu)", trackIndex, trackCount);
         return ERROR_OUT_OF_RANGE;
     }
 
@@ -2682,14 +2683,14 @@
         isAudioTrack = !strncasecmp(mime, "audio/", 6);
 
         if (!isAudioTrack && strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) != 0) {
-            ALOGE("Track %d is not either audio or timed text", trackIndex);
+            ALOGE("Track %zu is not either audio or timed text", trackIndex);
             return ERROR_UNSUPPORTED;
         }
     }
 
     if (isAudioTrack) {
         if (!select) {
-            ALOGE("Deselect an audio track (%d) is not supported", trackIndex);
+            ALOGE("Deselect an audio track (%zu) is not supported", trackIndex);
             return ERROR_UNSUPPORTED;
         }
         return selectAudioTrack_l(mExtractor->getTrack(trackIndex), trackIndex);
@@ -2812,7 +2813,8 @@
     return mCachedSource != NULL || mWVMExtractor != NULL;
 }
 
-status_t AwesomePlayer::dump(int fd, const Vector<String16> &args) const {
+status_t AwesomePlayer::dump(
+        int fd, const Vector<String16> & /* args */) const {
     Mutex::Autolock autoLock(mStatsLock);
 
     FILE *out = fdopen(dup(fd), "w");
@@ -2827,7 +2829,7 @@
     fprintf(out, ", flags(0x%08x)", mStats.mFlags);
 
     if (mStats.mBitrate >= 0) {
-        fprintf(out, ", bitrate(%lld bps)", mStats.mBitrate);
+        fprintf(out, ", bitrate(%" PRId64 " bps)", mStats.mBitrate);
     }
 
     fprintf(out, "\n");
@@ -2835,7 +2837,7 @@
     for (size_t i = 0; i < mStats.mTracks.size(); ++i) {
         const TrackStat &stat = mStats.mTracks.itemAt(i);
 
-        fprintf(out, "  Track %d\n", i + 1);
+        fprintf(out, "  Track %zu\n", i + 1);
         fprintf(out, "   MIME(%s)", stat.mMIME.string());
 
         if (!stat.mDecoderName.isEmpty()) {
@@ -2847,8 +2849,8 @@
         if ((ssize_t)i == mStats.mVideoTrackIndex) {
             fprintf(out,
                     "   videoDimensions(%d x %d), "
-                    "numVideoFramesDecoded(%lld), "
-                    "numVideoFramesDropped(%lld)\n",
+                    "numVideoFramesDecoded(%" PRId64 "), "
+                    "numVideoFramesDropped(%" PRId64 ")\n",
                     mStats.mVideoWidth,
                     mStats.mVideoHeight,
                     mStats.mNumVideoFramesDecoded,
diff --git a/media/libstagefright/CameraSource.cpp b/media/libstagefright/CameraSource.cpp
index 3017fe7..f3ff792 100644
--- a/media/libstagefright/CameraSource.cpp
+++ b/media/libstagefright/CameraSource.cpp
@@ -31,6 +31,12 @@
 #include <utils/String8.h>
 #include <cutils/properties.h>
 
+#if LOG_NDEBUG
+#define UNUSED_UNLESS_VERBOSE(x) (void)(x)
+#else
+#define UNUSED_UNLESS_VERBOSE(x)
+#endif
+
 namespace android {
 
 static const int64_t CAMERA_SOURCE_TIMEOUT_NS = 3000000000LL;
@@ -63,11 +69,14 @@
 }
 
 void CameraSourceListener::notify(int32_t msgType, int32_t ext1, int32_t ext2) {
+    UNUSED_UNLESS_VERBOSE(msgType);
+    UNUSED_UNLESS_VERBOSE(ext1);
+    UNUSED_UNLESS_VERBOSE(ext2);
     ALOGV("notify(%d, %d, %d)", msgType, ext1, ext2);
 }
 
 void CameraSourceListener::postData(int32_t msgType, const sp<IMemory> &dataPtr,
-                                    camera_frame_metadata_t *metadata) {
+                                    camera_frame_metadata_t * /* metadata */) {
     ALOGV("postData(%d, ptr:%p, size:%d)",
          msgType, dataPtr->pointer(), dataPtr->size());
 
diff --git a/media/libstagefright/CameraSourceTimeLapse.cpp b/media/libstagefright/CameraSourceTimeLapse.cpp
index 86844b8..60cdf66 100644
--- a/media/libstagefright/CameraSourceTimeLapse.cpp
+++ b/media/libstagefright/CameraSourceTimeLapse.cpp
@@ -232,7 +232,7 @@
     return newMemory;
 }
 
-bool CameraSourceTimeLapse::skipCurrentFrame(int64_t timestampUs) {
+bool CameraSourceTimeLapse::skipCurrentFrame(int64_t /* timestampUs */) {
     ALOGV("skipCurrentFrame");
     if (mSkipCurrentFrame) {
         mSkipCurrentFrame = false;
diff --git a/media/libstagefright/DataSource.cpp b/media/libstagefright/DataSource.cpp
index 2704b74..6e0f37a 100644
--- a/media/libstagefright/DataSource.cpp
+++ b/media/libstagefright/DataSource.cpp
@@ -35,6 +35,7 @@
 #include <media/IMediaHTTPService.h>
 #include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/DataSource.h>
+#include <media/stagefright/DataURISource.h>
 #include <media/stagefright/FileSource.h>
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MediaHTTP.h>
@@ -221,6 +222,8 @@
             // in the widevine:// case.
             source = httpSource;
         }
+    } else if (!strncasecmp("data:", uri, 5)) {
+        source = DataURISource::Create(uri);
     } else {
         // Assume it's a filename.
         source = new FileSource(uri);
diff --git a/media/libstagefright/DataURISource.cpp b/media/libstagefright/DataURISource.cpp
new file mode 100644
index 0000000..377bc85
--- /dev/null
+++ b/media/libstagefright/DataURISource.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2014 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 <media/stagefright/DataURISource.h>
+
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/AString.h>
+#include <media/stagefright/foundation/base64.h>
+
+namespace android {
+
+// static
+sp<DataURISource> DataURISource::Create(const char *uri) {
+    if (strncasecmp("data:", uri, 5)) {
+        return NULL;
+    }
+
+    char *commaPos = strrchr(uri, ',');
+
+    if (commaPos == NULL) {
+        return NULL;
+    }
+
+    sp<ABuffer> buffer;
+
+    AString tmp(&uri[5], commaPos - &uri[5]);
+
+    if (tmp.endsWith(";base64")) {
+        AString encoded(commaPos + 1);
+
+        // Strip CR and LF...
+        for (size_t i = encoded.size(); i-- > 0;) {
+            if (encoded.c_str()[i] == '\r' || encoded.c_str()[i] == '\n') {
+                encoded.erase(i, 1);
+            }
+        }
+
+        buffer = decodeBase64(encoded);
+
+        if (buffer == NULL) {
+            ALOGE("Malformed base64 encoded content found.");
+            return NULL;
+        }
+    } else {
+#if 0
+        size_t dataLen = strlen(uri) - tmp.size() - 6;
+        buffer = new ABuffer(dataLen);
+        memcpy(buffer->data(), commaPos + 1, dataLen);
+
+        // unescape
+#else
+        // MediaPlayer doesn't care for this right now as we don't
+        // play any text-based media.
+        return NULL;
+#endif
+    }
+
+    // We don't really care about charset or mime type.
+
+    return new DataURISource(buffer);
+}
+
+DataURISource::DataURISource(const sp<ABuffer> &buffer)
+    : mBuffer(buffer) {
+}
+
+DataURISource::~DataURISource() {
+}
+
+status_t DataURISource::initCheck() const {
+    return OK;
+}
+
+ssize_t DataURISource::readAt(off64_t offset, void *data, size_t size) {
+    if (offset >= mBuffer->size()) {
+        return 0;
+    }
+
+    size_t copy = mBuffer->size() - offset;
+    if (copy > size) {
+        copy = size;
+    }
+
+    memcpy(data, mBuffer->data() + offset, copy);
+
+    return copy;
+}
+
+status_t DataURISource::getSize(off64_t *size) {
+    *size = mBuffer->size();
+
+    return OK;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/FLACExtractor.cpp b/media/libstagefright/FLACExtractor.cpp
index 098fcf9..fa7251c 100644
--- a/media/libstagefright/FLACExtractor.cpp
+++ b/media/libstagefright/FLACExtractor.cpp
@@ -208,55 +208,55 @@
 // with the same parameter list, but discard redundant information.
 
 FLAC__StreamDecoderReadStatus FLACParser::read_callback(
-        const FLAC__StreamDecoder *decoder, FLAC__byte buffer[],
+        const FLAC__StreamDecoder * /* decoder */, FLAC__byte buffer[],
         size_t *bytes, void *client_data)
 {
     return ((FLACParser *) client_data)->readCallback(buffer, bytes);
 }
 
 FLAC__StreamDecoderSeekStatus FLACParser::seek_callback(
-        const FLAC__StreamDecoder *decoder,
+        const FLAC__StreamDecoder * /* decoder */,
         FLAC__uint64 absolute_byte_offset, void *client_data)
 {
     return ((FLACParser *) client_data)->seekCallback(absolute_byte_offset);
 }
 
 FLAC__StreamDecoderTellStatus FLACParser::tell_callback(
-        const FLAC__StreamDecoder *decoder,
+        const FLAC__StreamDecoder * /* decoder */,
         FLAC__uint64 *absolute_byte_offset, void *client_data)
 {
     return ((FLACParser *) client_data)->tellCallback(absolute_byte_offset);
 }
 
 FLAC__StreamDecoderLengthStatus FLACParser::length_callback(
-        const FLAC__StreamDecoder *decoder,
+        const FLAC__StreamDecoder * /* decoder */,
         FLAC__uint64 *stream_length, void *client_data)
 {
     return ((FLACParser *) client_data)->lengthCallback(stream_length);
 }
 
 FLAC__bool FLACParser::eof_callback(
-        const FLAC__StreamDecoder *decoder, void *client_data)
+        const FLAC__StreamDecoder * /* decoder */, void *client_data)
 {
     return ((FLACParser *) client_data)->eofCallback();
 }
 
 FLAC__StreamDecoderWriteStatus FLACParser::write_callback(
-        const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame,
+        const FLAC__StreamDecoder * /* decoder */, const FLAC__Frame *frame,
         const FLAC__int32 * const buffer[], void *client_data)
 {
     return ((FLACParser *) client_data)->writeCallback(frame, buffer);
 }
 
 void FLACParser::metadata_callback(
-        const FLAC__StreamDecoder *decoder,
+        const FLAC__StreamDecoder * /* decoder */,
         const FLAC__StreamMetadata *metadata, void *client_data)
 {
     ((FLACParser *) client_data)->metadataCallback(metadata);
 }
 
 void FLACParser::error_callback(
-        const FLAC__StreamDecoder *decoder,
+        const FLAC__StreamDecoder * /* decoder */,
         FLAC__StreamDecoderErrorStatus status, void *client_data)
 {
     ((FLACParser *) client_data)->errorCallback(status);
@@ -380,15 +380,21 @@
 // Copy samples from FLAC native 32-bit non-interleaved to 16-bit interleaved.
 // These are candidates for optimization if needed.
 
-static void copyMono8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
-{
+static void copyMono8(
+        short *dst,
+        const int *const *src,
+        unsigned nSamples,
+        unsigned /* nChannels */) {
     for (unsigned i = 0; i < nSamples; ++i) {
         *dst++ = src[0][i] << 8;
     }
 }
 
-static void copyStereo8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
-{
+static void copyStereo8(
+        short *dst,
+        const int *const *src,
+        unsigned nSamples,
+        unsigned /* nChannels */) {
     for (unsigned i = 0; i < nSamples; ++i) {
         *dst++ = src[0][i] << 8;
         *dst++ = src[1][i] << 8;
@@ -404,15 +410,21 @@
     }
 }
 
-static void copyMono16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
-{
+static void copyMono16(
+        short *dst,
+        const int *const *src,
+        unsigned nSamples,
+        unsigned /* nChannels */) {
     for (unsigned i = 0; i < nSamples; ++i) {
         *dst++ = src[0][i];
     }
 }
 
-static void copyStereo16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
-{
+static void copyStereo16(
+        short *dst,
+        const int *const *src,
+        unsigned nSamples,
+        unsigned /* nChannels */) {
     for (unsigned i = 0; i < nSamples; ++i) {
         *dst++ = src[0][i];
         *dst++ = src[1][i];
@@ -430,15 +442,21 @@
 
 // 24-bit versions should do dithering or noise-shaping, here or in AudioFlinger
 
-static void copyMono24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
-{
+static void copyMono24(
+        short *dst,
+        const int *const *src,
+        unsigned nSamples,
+        unsigned /* nChannels */) {
     for (unsigned i = 0; i < nSamples; ++i) {
         *dst++ = src[0][i] >> 8;
     }
 }
 
-static void copyStereo24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
-{
+static void copyStereo24(
+        short *dst,
+        const int *const *src,
+        unsigned nSamples,
+        unsigned /* nChannels */) {
     for (unsigned i = 0; i < nSamples; ++i) {
         *dst++ = src[0][i] >> 8;
         *dst++ = src[1][i] >> 8;
@@ -454,8 +472,11 @@
     }
 }
 
-static void copyTrespass(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
-{
+static void copyTrespass(
+        short * /* dst */,
+        const int *const * /* src */,
+        unsigned /* nSamples */,
+        unsigned /* nChannels */) {
     TRESPASS();
 }
 
@@ -700,7 +721,7 @@
     }
 }
 
-status_t FLACSource::start(MetaData *params)
+status_t FLACSource::start(MetaData * /* params */)
 {
     ALOGV("FLACSource::start");
 
@@ -792,8 +813,7 @@
 }
 
 sp<MetaData> FLACExtractor::getTrackMetaData(
-        size_t index, uint32_t flags)
-{
+        size_t index, uint32_t /* flags */) {
     if (mInitCheck != OK || index > 0) {
         return NULL;
     }
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/libstagefright/MP3Extractor.cpp
index 380dab4..4a63152 100644
--- a/media/libstagefright/MP3Extractor.cpp
+++ b/media/libstagefright/MP3Extractor.cpp
@@ -398,7 +398,8 @@
             mSeeker);
 }
 
-sp<MetaData> MP3Extractor::getTrackMetaData(size_t index, uint32_t flags) {
+sp<MetaData> MP3Extractor::getTrackMetaData(
+        size_t index, uint32_t /* flags */) {
     if (mInitCheck != OK || index != 0) {
         return NULL;
     }
diff --git a/media/libstagefright/MPEG2TSWriter.cpp b/media/libstagefright/MPEG2TSWriter.cpp
index c9ed5bb..78c12e1 100644
--- a/media/libstagefright/MPEG2TSWriter.cpp
+++ b/media/libstagefright/MPEG2TSWriter.cpp
@@ -555,7 +555,7 @@
     return OK;
 }
 
-status_t MPEG2TSWriter::start(MetaData *param) {
+status_t MPEG2TSWriter::start(MetaData * /* param */) {
     CHECK(!mStarted);
 
     mStarted = true;
@@ -596,7 +596,8 @@
     return !mStarted || (mNumSourcesDone == mSources.size() ? true : false);
 }
 
-status_t MPEG2TSWriter::dump(int fd, const Vector<String16> &args) {
+status_t MPEG2TSWriter::dump(
+        int /* fd */, const Vector<String16> & /* args */) {
     return OK;
 }
 
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp
index dfb5c04..4756b3e 100644
--- a/media/libstagefright/MPEG4Extractor.cpp
+++ b/media/libstagefright/MPEG4Extractor.cpp
@@ -260,7 +260,7 @@
     const uint8_t *data = (const uint8_t *)_data;
     size_t offset = 0;
     while (offset < size) {
-        printf("0x%04x  ", offset);
+        printf("0x%04zx  ", offset);
 
         size_t n = size - offset;
         if (n > 16) {
@@ -571,7 +571,8 @@
     return size;
 }
 
-status_t MPEG4Extractor::parseDrmSINF(off64_t *offset, off64_t data_offset) {
+status_t MPEG4Extractor::parseDrmSINF(
+        off64_t * /* offset */, off64_t data_offset) {
     uint8_t updateIdTag;
     if (mDataSource->readAt(data_offset, &updateIdTag, 1) < 1) {
         return ERROR_IO;
@@ -2959,7 +2960,8 @@
     return OK;
 }
 
-status_t MPEG4Source::parseSampleAuxiliaryInformationSizes(off64_t offset, off64_t size) {
+status_t MPEG4Source::parseSampleAuxiliaryInformationSizes(
+        off64_t offset, off64_t /* size */) {
     ALOGV("parseSampleAuxiliaryInformationSizes");
     // 14496-12 8.7.12
     uint8_t version;
@@ -3021,7 +3023,8 @@
     return OK;
 }
 
-status_t MPEG4Source::parseSampleAuxiliaryInformationOffsets(off64_t offset, off64_t size) {
+status_t MPEG4Source::parseSampleAuxiliaryInformationOffsets(
+        off64_t offset, off64_t /* size */) {
     ALOGV("parseSampleAuxiliaryInformationOffsets");
     // 14496-12 8.7.13
     uint8_t version;
@@ -3732,7 +3735,7 @@
     }
 
     off64_t offset = 0;
-    size_t size;
+    size_t size = 0;
     uint32_t cts = 0;
     bool isSyncSample = false;
     bool newBuffer = false;
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
index 0fa3b2d..c839560 100644
--- a/media/libstagefright/MPEG4Writer.cpp
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "MPEG4Writer"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include <arpa/inet.h>
@@ -43,7 +44,9 @@
 namespace android {
 
 static const int64_t kMinStreamableFileSizeInBytes = 5 * 1024 * 1024;
-static const int64_t kMax32BitFileSize = 0x007fffffffLL;
+static const int64_t kMax32BitFileSize = 0x00ffffffffLL; // 2^32-1 : max FAT32
+                                                         // filesystem file size
+                                                         // used by most SD cards
 static const uint8_t kNalUnitTypeSeqParamSet = 0x07;
 static const uint8_t kNalUnitTypePicParamSet = 0x08;
 static const int64_t kInitialDelayTimeUs     = 700000LL;
@@ -406,7 +409,7 @@
 }
 
 status_t MPEG4Writer::Track::dump(
-        int fd, const Vector<String16>& args) const {
+        int fd, const Vector<String16>& /* args */) const {
     const size_t SIZE = 256;
     char buffer[SIZE];
     String8 result;
@@ -417,7 +420,7 @@
     result.append(buffer);
     snprintf(buffer, SIZE, "       frames encoded : %d\n", mStszTableEntries->count());
     result.append(buffer);
-    snprintf(buffer, SIZE, "       duration encoded : %lld us\n", mTrackDurationUs);
+    snprintf(buffer, SIZE, "       duration encoded : %" PRId64 " us\n", mTrackDurationUs);
     result.append(buffer);
     ::write(fd, result.string(), result.size());
     return OK;
@@ -860,11 +863,11 @@
     // Fix up the size of the 'mdat' chunk.
     if (mUse32BitOffset) {
         lseek64(mFd, mMdatOffset, SEEK_SET);
-        int32_t size = htonl(static_cast<int32_t>(mOffset - mMdatOffset));
+        uint32_t size = htonl(static_cast<uint32_t>(mOffset - mMdatOffset));
         ::write(mFd, &size, 4);
     } else {
         lseek64(mFd, mMdatOffset + 8, SEEK_SET);
-        int64_t size = mOffset - mMdatOffset;
+        uint64_t size = mOffset - mMdatOffset;
         size = hton64(size);
         ::write(mFd, &size, 8);
     }
@@ -1407,7 +1410,7 @@
         size_t sampleCount, int32_t duration) {
 
     if (duration == 0) {
-        ALOGW("0-duration samples found: %d", sampleCount);
+        ALOGW("0-duration samples found: %zu", sampleCount);
     }
     mSttsTableEntries->add(htonl(sampleCount));
     mSttsTableEntries->add(htonl(duration));
@@ -1587,7 +1590,7 @@
     sendSessionSummary();
 
     mChunkInfos.clear();
-    ALOGD("%d chunks are written in the last batch", outstandingChunks);
+    ALOGD("%zu chunks are written in the last batch", outstandingChunks);
 }
 
 bool MPEG4Writer::findChunkToWrite(Chunk *chunk) {
@@ -1780,7 +1783,7 @@
 
     void *dummy;
     pthread_join(mThread, &dummy);
-    status_t err = (status_t) dummy;
+    status_t err = static_cast<status_t>(reinterpret_cast<uintptr_t>(dummy));
 
     ALOGD("%s track stopped", mIsAudio? "Audio": "Video");
     return err;
@@ -1795,7 +1798,7 @@
     Track *track = static_cast<Track *>(me);
 
     status_t err = track->threadEntry();
-    return (void *) err;
+    return (void *)(uintptr_t)err;
 }
 
 static void getNalUnitType(uint8_t byte, uint8_t* type) {
@@ -1867,7 +1870,7 @@
     // 2 bytes for each of the parameter set length field
     // plus the 7 bytes for the header
     if (size < 4 + 7) {
-        ALOGE("Codec specific data length too short: %d", size);
+        ALOGE("Codec specific data length too short: %zu", size);
         return ERROR_MALFORMED;
     }
 
@@ -1936,7 +1939,7 @@
         }
 
         if (nSeqParamSets > 0x1F) {
-            ALOGE("Too many seq parameter sets (%d) found", nSeqParamSets);
+            ALOGE("Too many seq parameter sets (%zu) found", nSeqParamSets);
             return ERROR_MALFORMED;
         }
     }
@@ -1949,7 +1952,7 @@
             return ERROR_MALFORMED;
         }
         if (nPicParamSets > 0xFF) {
-            ALOGE("Too many pic parameter sets (%d) found", nPicParamSets);
+            ALOGE("Too many pic parameter sets (%zd) found", nPicParamSets);
             return ERROR_MALFORMED;
         }
     }
@@ -1979,7 +1982,7 @@
     }
 
     if (size < 4) {
-        ALOGE("Codec specific data length too short: %d", size);
+        ALOGE("Codec specific data length too short: %zu", size);
         return ERROR_MALFORMED;
     }
 
@@ -2277,6 +2280,22 @@
             return UNKNOWN_ERROR;
         }
 
+        // if the duration is different for this sample, see if it is close enough to the previous
+        // duration that we can fudge it and use the same value, to avoid filling the stts table
+        // with lots of near-identical entries.
+        // "close enough" here means that the current duration needs to be adjusted by less
+        // than 0.1 milliseconds
+        if (lastDurationTicks && (currDurationTicks != lastDurationTicks)) {
+            int64_t deltaUs = ((lastDurationTicks - currDurationTicks) * 1000000LL
+                    + (mTimeScale / 2)) / mTimeScale;
+            if (deltaUs > -100 && deltaUs < 100) {
+                // use previous ticks, and adjust timestamp as if it was actually that number
+                // of ticks
+                currDurationTicks = lastDurationTicks;
+                timestampUs += deltaUs;
+            }
+        }
+
         mStszTableEntries->add(htonl(sampleSize));
         if (mStszTableEntries->count() > 2) {
 
diff --git a/media/libstagefright/MediaAdapter.cpp b/media/libstagefright/MediaAdapter.cpp
index 2484212..d680e0c 100644
--- a/media/libstagefright/MediaAdapter.cpp
+++ b/media/libstagefright/MediaAdapter.cpp
@@ -36,7 +36,7 @@
     CHECK(mCurrentMediaBuffer == NULL);
 }
 
-status_t MediaAdapter::start(MetaData *params) {
+status_t MediaAdapter::start(MetaData * /* params */) {
     Mutex::Autolock autoLock(mAdapterLock);
     if (!mStarted) {
         mStarted = true;
@@ -75,7 +75,7 @@
 }
 
 status_t MediaAdapter::read(
-            MediaBuffer **buffer, const ReadOptions *options) {
+            MediaBuffer **buffer, const ReadOptions * /* options */) {
     Mutex::Autolock autoLock(mAdapterLock);
     if (!mStarted) {
         ALOGV("Read before even started!");
diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp
index c4c47b3..fe21296 100644
--- a/media/libstagefright/MediaCodec.cpp
+++ b/media/libstagefright/MediaCodec.cpp
@@ -115,7 +115,7 @@
         if (codecIdx >= 0) {
             Vector<AString> types;
             if (mcl->getSupportedTypes(codecIdx, &types) == OK) {
-                for (int i = 0; i < types.size(); i++) {
+                for (size_t i = 0; i < types.size(); i++) {
                     if (types[i].startsWith("video/")) {
                         needDedicatedLooper = true;
                         break;
diff --git a/media/libstagefright/MediaCodecSource.cpp b/media/libstagefright/MediaCodecSource.cpp
index 2c20d62..924173c 100644
--- a/media/libstagefright/MediaCodecSource.cpp
+++ b/media/libstagefright/MediaCodecSource.cpp
@@ -293,8 +293,8 @@
     return mGraphicBufferProducer;
 }
 
-status_t MediaCodecSource::read(MediaBuffer** buffer,
-        const ReadOptions* options) {
+status_t MediaCodecSource::read(
+        MediaBuffer** buffer, const ReadOptions* /* options */) {
     Mutex::Autolock autolock(mOutputBufferLock);
 
     *buffer = NULL;
diff --git a/media/libstagefright/MetaData.cpp b/media/libstagefright/MetaData.cpp
index 1daead7..74234a6 100644
--- a/media/libstagefright/MetaData.cpp
+++ b/media/libstagefright/MetaData.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "MetaData"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include <stdlib.h>
@@ -307,7 +308,7 @@
     const void *data = storage();
     switch(mType) {
         case TYPE_NONE:
-            out = String8::format("no type, size %d)", mSize);
+            out = String8::format("no type, size %zu)", mSize);
             break;
         case TYPE_C_STRING:
             out = String8::format("(char*) %s", (const char *)data);
@@ -316,7 +317,7 @@
             out = String8::format("(int32_t) %d", *(int32_t *)data);
             break;
         case TYPE_INT64:
-            out = String8::format("(int64_t) %lld", *(int64_t *)data);
+            out = String8::format("(int64_t) %" PRId64, *(int64_t *)data);
             break;
         case TYPE_FLOAT:
             out = String8::format("(float) %f", *(float *)data);
@@ -333,7 +334,7 @@
         }
 
         default:
-            out = String8::format("(unknown type %d, size %d)", mType, mSize);
+            out = String8::format("(unknown type %d, size %zu)", mType, mSize);
             if (mSize <= 48) { // if it's less than three lines of hex data, dump it
                 AString foo;
                 hexdump(data, mSize, 0, &foo);
diff --git a/media/libstagefright/NuCachedSource2.cpp b/media/libstagefright/NuCachedSource2.cpp
index 1287fb1..72ea32d 100644
--- a/media/libstagefright/NuCachedSource2.cpp
+++ b/media/libstagefright/NuCachedSource2.cpp
@@ -333,7 +333,7 @@
             mNumRetriesLeft = 0;
         }
 
-        ALOGE("source returned error %ld, %d retries left", n, mNumRetriesLeft);
+        ALOGE("source returned error %d, %d retries left", n, mNumRetriesLeft);
         mCache->releasePage(page);
     } else if (n == 0) {
         ALOGI("ERROR_END_OF_STREAM");
@@ -648,7 +648,7 @@
     ssize_t lowwaterMarkKb, highwaterMarkKb;
     int keepAliveSecs;
 
-    if (sscanf(s, "%ld/%ld/%d",
+    if (sscanf(s, "%d/%d/%d",
                &lowwaterMarkKb, &highwaterMarkKb, &keepAliveSecs) != 3) {
         ALOGE("Failed to parse cache parameters from '%s'.", s);
         return;
diff --git a/media/libstagefright/OggExtractor.cpp b/media/libstagefright/OggExtractor.cpp
index 5e79e78..f3eeb03 100644
--- a/media/libstagefright/OggExtractor.cpp
+++ b/media/libstagefright/OggExtractor.cpp
@@ -151,7 +151,7 @@
     return mExtractor->mImpl->getFormat();
 }
 
-status_t OggSource::start(MetaData *params) {
+status_t OggSource::start(MetaData * /* params */) {
     if (mStarted) {
         return INVALID_OPERATION;
     }
@@ -381,7 +381,7 @@
     ssize_t n;
     if ((n = mSource->readAt(offset, header, sizeof(header)))
             < (ssize_t)sizeof(header)) {
-        ALOGV("failed to read %d bytes at offset 0x%016llx, got %ld bytes",
+        ALOGV("failed to read %zu bytes at offset 0x%016llx, got %d bytes",
              sizeof(header), offset, n);
 
         if (n < 0) {
@@ -505,7 +505,7 @@
                     packetSize);
 
             if (n < (ssize_t)packetSize) {
-                ALOGV("failed to read %d bytes at 0x%016llx, got %ld bytes",
+                ALOGV("failed to read %zu bytes at 0x%016llx, got %d bytes",
                      packetSize, dataOffset, n);
                 return ERROR_IO;
             }
@@ -546,7 +546,7 @@
                 buffer = NULL;
             }
 
-            ALOGV("readPage returned %ld", n);
+            ALOGV("readPage returned %d", n);
 
             return n < 0 ? n : (status_t)ERROR_END_OF_STREAM;
         }
@@ -998,7 +998,7 @@
 }
 
 sp<MetaData> OggExtractor::getTrackMetaData(
-        size_t index, uint32_t flags) {
+        size_t index, uint32_t /* flags */) {
     if (index >= 1) {
         return NULL;
     }
diff --git a/media/libstagefright/StagefrightMediaScanner.cpp b/media/libstagefright/StagefrightMediaScanner.cpp
index edd12fc..fe20835 100644
--- a/media/libstagefright/StagefrightMediaScanner.cpp
+++ b/media/libstagefright/StagefrightMediaScanner.cpp
@@ -118,7 +118,7 @@
 }
 
 MediaScanResult StagefrightMediaScanner::processFileInternal(
-        const char *path, const char *mimeType,
+        const char *path, const char * /* mimeType */,
         MediaScannerClient &client) {
     const char *extension = strrchr(path, '.');
 
diff --git a/media/libstagefright/StagefrightMetadataRetriever.cpp b/media/libstagefright/StagefrightMetadataRetriever.cpp
index b4f906e..9475d05 100644
--- a/media/libstagefright/StagefrightMetadataRetriever.cpp
+++ b/media/libstagefright/StagefrightMetadataRetriever.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "StagefrightMetadataRetriever"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include "include/StagefrightMetadataRetriever.h"
@@ -491,7 +492,7 @@
     size_t numTracks = mExtractor->countTracks();
 
     char tmp[32];
-    sprintf(tmp, "%d", numTracks);
+    sprintf(tmp, "%zu", numTracks);
 
     mMetaData.add(METADATA_KEY_NUM_TRACKS, String8(tmp));
 
@@ -548,7 +549,7 @@
     }
 
     // The duration value is a string representing the duration in ms.
-    sprintf(tmp, "%lld", (maxDurationUs + 500) / 1000);
+    sprintf(tmp, "%" PRId64, (maxDurationUs + 500) / 1000);
     mMetaData.add(METADATA_KEY_DURATION, String8(tmp));
 
     if (hasAudio) {
@@ -576,7 +577,7 @@
         if (mSource->getSize(&sourceSize) == OK) {
             int64_t avgBitRate = (int64_t)(sourceSize * 8E6 / maxDurationUs);
 
-            sprintf(tmp, "%lld", avgBitRate);
+            sprintf(tmp, "%" PRId64, avgBitRate);
             mMetaData.add(METADATA_KEY_BITRATE, String8(tmp));
         }
     }
diff --git a/media/libstagefright/SurfaceMediaSource.cpp b/media/libstagefright/SurfaceMediaSource.cpp
index 6b934d4..10c00f4 100644
--- a/media/libstagefright/SurfaceMediaSource.cpp
+++ b/media/libstagefright/SurfaceMediaSource.cpp
@@ -99,8 +99,11 @@
     dump(result, "", buffer, 1024);
 }
 
-void SurfaceMediaSource::dump(String8& result, const char* prefix,
-        char* buffer, size_t SIZE) const
+void SurfaceMediaSource::dump(
+        String8& result,
+        const char* /* prefix */,
+        char* buffer,
+        size_t /* SIZE */) const
 {
     Mutex::Autolock lock(mMutex);
 
@@ -202,6 +205,9 @@
         return OK;
     }
 
+    mStarted = false;
+    mFrameAvailableCondition.signal();
+
     while (mNumPendingBuffers > 0) {
         ALOGI("Still waiting for %d buffers to be returned.",
                 mNumPendingBuffers);
@@ -215,8 +221,6 @@
         mMediaBuffersAvailableCondition.wait(mMutex);
     }
 
-    mStarted = false;
-    mFrameAvailableCondition.signal();
     mMediaBuffersAvailableCondition.signal();
 
     return mBufferQueue->consumerDisconnect();
@@ -269,9 +273,8 @@
             bufferHandle, (*buffer)->range_length(), (*buffer)->range_offset());
 }
 
-status_t SurfaceMediaSource::read( MediaBuffer **buffer,
-                                    const ReadOptions *options)
-{
+status_t SurfaceMediaSource::read(
+        MediaBuffer **buffer, const ReadOptions * /* options */) {
     ALOGV("read");
     Mutex::Autolock lock(mMutex);
 
diff --git a/media/libstagefright/TimedEventQueue.cpp b/media/libstagefright/TimedEventQueue.cpp
index 0afac69..3d2eb1f 100644
--- a/media/libstagefright/TimedEventQueue.cpp
+++ b/media/libstagefright/TimedEventQueue.cpp
@@ -376,8 +376,8 @@
     mPowerManager.clear();
 }
 
-void TimedEventQueue::PMDeathRecipient::binderDied(const wp<IBinder>& who)
-{
+void TimedEventQueue::PMDeathRecipient::binderDied(
+        const wp<IBinder>& /* who */) {
     mQueue->clearPowerManager();
 }
 
diff --git a/media/libstagefright/VBRISeeker.cpp b/media/libstagefright/VBRISeeker.cpp
index a245f2c..af858b9 100644
--- a/media/libstagefright/VBRISeeker.cpp
+++ b/media/libstagefright/VBRISeeker.cpp
@@ -119,7 +119,7 @@
 
         seeker->mSegments.push(numBytes);
 
-        ALOGV("entry #%d: %d offset 0x%08lx", i, numBytes, offset);
+        ALOGV("entry #%d: %u offset 0x%016llx", i, numBytes, offset);
         offset += numBytes;
     }
 
@@ -160,7 +160,7 @@
         *pos += mSegments.itemAt(segmentIndex++);
     }
 
-    ALOGV("getOffsetForTime %lld us => 0x%08lx", *timeUs, *pos);
+    ALOGV("getOffsetForTime %lld us => 0x%016llx", *timeUs, *pos);
 
     *timeUs = nowUs;
 
diff --git a/media/libstagefright/WAVExtractor.cpp b/media/libstagefright/WAVExtractor.cpp
index 22af6fb..fe9058b 100644
--- a/media/libstagefright/WAVExtractor.cpp
+++ b/media/libstagefright/WAVExtractor.cpp
@@ -127,7 +127,7 @@
 }
 
 sp<MetaData> WAVExtractor::getTrackMetaData(
-        size_t index, uint32_t flags) {
+        size_t index, uint32_t /* flags */) {
     if (mInitCheck != OK || index > 0) {
         return NULL;
     }
@@ -358,7 +358,7 @@
     }
 }
 
-status_t WAVSource::start(MetaData *params) {
+status_t WAVSource::start(MetaData * /* params */) {
     ALOGV("WAVSource::start");
 
     CHECK(!mStarted);
diff --git a/media/libstagefright/avc_utils.cpp b/media/libstagefright/avc_utils.cpp
index b822868..c6ac0da 100644
--- a/media/libstagefright/avc_utils.cpp
+++ b/media/libstagefright/avc_utils.cpp
@@ -251,9 +251,7 @@
     return OK;
 }
 
-static sp<ABuffer> FindNAL(
-        const uint8_t *data, size_t size, unsigned nalType,
-        size_t *stopOffset) {
+static sp<ABuffer> FindNAL(const uint8_t *data, size_t size, unsigned nalType) {
     const uint8_t *nalStart;
     size_t nalSize;
     while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
@@ -293,7 +291,7 @@
     const uint8_t *data = accessUnit->data();
     size_t size = accessUnit->size();
 
-    sp<ABuffer> seqParamSet = FindNAL(data, size, 7, NULL);
+    sp<ABuffer> seqParamSet = FindNAL(data, size, 7);
     if (seqParamSet == NULL) {
         return NULL;
     }
@@ -303,8 +301,7 @@
     FindAVCDimensions(
             seqParamSet, &width, &height, &sarWidth, &sarHeight);
 
-    size_t stopOffset;
-    sp<ABuffer> picParamSet = FindNAL(data, size, 8, &stopOffset);
+    sp<ABuffer> picParamSet = FindNAL(data, size, 8);
     CHECK(picParamSet != NULL);
 
     size_t csdSize =
diff --git a/media/libstagefright/codecs/aacdec/Android.mk b/media/libstagefright/codecs/aacdec/Android.mk
index ffa64f9..49ff238 100644
--- a/media/libstagefright/codecs/aacdec/Android.mk
+++ b/media/libstagefright/codecs/aacdec/Android.mk
@@ -17,6 +17,8 @@
 
 LOCAL_CFLAGS :=
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_STATIC_LIBRARIES := libFraunhoferAAC
 
 LOCAL_SHARED_LIBRARIES := \
diff --git a/media/libstagefright/codecs/aacdec/SoftAAC2.cpp b/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
index 2f5eff4..4ac8999 100644
--- a/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
+++ b/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
@@ -377,7 +377,7 @@
                 mNumSamplesOutput = 0;
             }
 
-            if (mIsADTS) {
+            if (mIsADTS && inHeader->nFilledLen) {
                 size_t adtsHeaderSize = 0;
                 // skip 30 bits, aac_frame_length follows.
                 // ssssssss ssssiiip ppffffPc ccohCCll llllllll lll?????
diff --git a/media/libstagefright/codecs/aacenc/Android.mk b/media/libstagefright/codecs/aacenc/Android.mk
index 057c69b..58ec3ba 100644
--- a/media/libstagefright/codecs/aacenc/Android.mk
+++ b/media/libstagefright/codecs/aacenc/Android.mk
@@ -82,6 +82,8 @@
 LOCAL_C_INCLUDES += $(LOCAL_PATH)/src/asm/ARMV7
 endif
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_STATIC_LIBRARY)
 
 ################################################################################
@@ -106,6 +108,8 @@
 
   LOCAL_CFLAGS :=
 
+  LOCAL_CFLAGS += -Werror
+
   LOCAL_STATIC_LIBRARIES := libFraunhoferAAC
 
   LOCAL_SHARED_LIBRARIES := \
@@ -128,6 +132,8 @@
 
   LOCAL_CFLAGS := -DOSCL_IMPORT_REF=
 
+  LOCAL_CFLAGS += -Werror
+
   LOCAL_STATIC_LIBRARIES := \
           libstagefright_aacenc
 
diff --git a/media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp b/media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp
index ff2b503..9a91579 100644
--- a/media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp
+++ b/media/libstagefright/codecs/aacenc/SoftAACEncoder2.cpp
@@ -338,7 +338,7 @@
     return OK;
 }
 
-void SoftAACEncoder2::onQueueFilled(OMX_U32 portIndex) {
+void SoftAACEncoder2::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError) {
         return;
     }
diff --git a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
index cc01927..1d029fc 100644
--- a/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
+++ b/media/libstagefright/codecs/aacenc/basic_op/oper_32b.c
@@ -24,6 +24,8 @@
 #include "basic_op.h"
 #include "oper_32b.h"
 
+#define UNUSED(x) (void)(x)
+
 /*****************************************************************************
  *                                                                           *
  *  Function L_Extract()                                                     *
@@ -243,6 +245,8 @@
 Word32 rsqrt(Word32 value,     /*!< Operand to square root (0.0 ... 1) */
              Word32 accuracy)  /*!< Number of valid bits that will be calculated */
 {
+    UNUSED(accuracy);
+
     Word32 root = 0;
 	Word32 scale;
 
diff --git a/media/libstagefright/codecs/aacenc/src/aacenc.c b/media/libstagefright/codecs/aacenc/src/aacenc.c
index d1c8621..40db92c 100644
--- a/media/libstagefright/codecs/aacenc/src/aacenc.c
+++ b/media/libstagefright/codecs/aacenc/src/aacenc.c
@@ -27,6 +27,8 @@
 #include "cmnMemory.h"
 #include "memalign.h"
 
+#define UNUSED(x) (void)(x)
+
 /**
 * Init the audio codec module and return codec handle
 * \param phCodec [OUT] Return the video codec handle
@@ -46,6 +48,8 @@
 	VO_MEM_OPERATOR *pMemOP;
 	int interMem;
 
+        UNUSED(vType);
+
 	interMem = 0;
 	error = 0;
 
@@ -471,6 +475,10 @@
 */
 VO_U32 VO_API voAACEncGetParam(VO_HANDLE hCodec, VO_S32 uParamID, VO_PTR pData)
 {
+        UNUSED(hCodec);
+        UNUSED(uParamID);
+        UNUSED(pData);
+
 	return VO_ERR_NONE;
 }
 
diff --git a/media/libstagefright/codecs/aacenc/src/adj_thr.c b/media/libstagefright/codecs/aacenc/src/adj_thr.c
index ccfe883..471631c 100644
--- a/media/libstagefright/codecs/aacenc/src/adj_thr.c
+++ b/media/libstagefright/codecs/aacenc/src/adj_thr.c
@@ -72,7 +72,7 @@
                           const Word16 nChannels)
 {
   Word16 ch, sfb, sfbGrp;
-  Word32 *pthrExp, *psfbThre;
+  Word32 *pthrExp = NULL, *psfbThre;
   for (ch=0; ch<nChannels; ch++) {
     PSY_OUT_CHANNEL *psyOutChan = &psyOutChannel[ch];
 	 for(sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt; sfbGrp+= psyOutChan->sfbPerGroup)
diff --git a/media/libstagefright/codecs/aacenc/src/bitenc.c b/media/libstagefright/codecs/aacenc/src/bitenc.c
index fcc12dd..d1fd647 100644
--- a/media/libstagefright/codecs/aacenc/src/bitenc.c
+++ b/media/libstagefright/codecs/aacenc/src/bitenc.c
@@ -26,6 +26,7 @@
 #include "qc_data.h"
 #include "interface.h"
 
+#define UNUSED(x) (void)(x)
 
 static const  Word16 globalGainOffset = 100;
 static const  Word16 icsReservedBit   = 0;
@@ -585,6 +586,8 @@
   Word16 elementUsedBits;
   Word16 frameBits=0;
 
+  UNUSED(ancBytes);
+
   /*   struct bitbuffer bsWriteCopy; */
   bitMarkUp = GetBitsAvail(hBitStream);
   if(qcOut->qcElement.adtsUsed)  /*  write adts header*/
diff --git a/media/libstagefright/codecs/aacenc/src/dyn_bits.c b/media/libstagefright/codecs/aacenc/src/dyn_bits.c
index 7769188..4d763d0 100644
--- a/media/libstagefright/codecs/aacenc/src/dyn_bits.c
+++ b/media/libstagefright/codecs/aacenc/src/dyn_bits.c
@@ -25,7 +25,6 @@
 #include "bit_cnt.h"
 #include "psy_const.h"
 
-
 /*****************************************************************************
 *
 * function name: buildBitLookUp
@@ -226,7 +225,7 @@
   }
 
   while (TRUE) {
-    Word16 maxMergeGain, maxNdx, maxNdxNext, maxNdxLast;
+    Word16 maxMergeGain, maxNdx = 0, maxNdxNext, maxNdxLast;
 
     maxMergeGain = findMaxMerge(mergeGainLookUp, sectionInfo, maxSfb, &maxNdx);
 
diff --git a/media/libstagefright/codecs/aacenc/src/psy_main.c b/media/libstagefright/codecs/aacenc/src/psy_main.c
index 4e9218c..6f0679c 100644
--- a/media/libstagefright/codecs/aacenc/src/psy_main.c
+++ b/media/libstagefright/codecs/aacenc/src/psy_main.c
@@ -38,6 +38,8 @@
 #include "tns_func.h"
 #include "memalign.h"
 
+#define UNUSED(x) (void)(x)
+
 /*                                    long       start       short       stop */
 static Word16 blockType2windowShape[] = {KBD_WINDOW,SINE_WINDOW,SINE_WINDOW,KBD_WINDOW};
 
@@ -170,7 +172,9 @@
 *****************************************************************************/
 Word16 PsyOutDelete(PSY_OUT *hPsyOut, VO_MEM_OPERATOR *pMemOP)
 {
-  hPsyOut=NULL;
+  UNUSED(hPsyOut);
+  UNUSED(pMemOP);
+
   return 0;
 }
 
diff --git a/media/libstagefright/codecs/aacenc/src/qc_main.c b/media/libstagefright/codecs/aacenc/src/qc_main.c
index 48ff300..e5d78aa 100644
--- a/media/libstagefright/codecs/aacenc/src/qc_main.c
+++ b/media/libstagefright/codecs/aacenc/src/qc_main.c
@@ -33,6 +33,7 @@
 #include "channel_map.h"
 #include "memalign.h"
 
+#define UNUSED(x) (void)(x)
 
 typedef enum{
   FRAME_LEN_BYTES_MODULO =  1,
@@ -204,11 +205,8 @@
 **********************************************************************************/
 void QCDelete(QC_STATE *hQC, VO_MEM_OPERATOR *pMemOP)
 {
-
-  /*
-     nothing to do
-  */
-  hQC=NULL;
+  UNUSED(hQC);
+  UNUSED(pMemOP);
 }
 
 /*********************************************************************************
diff --git a/media/libstagefright/codecs/aacenc/src/tns.c b/media/libstagefright/codecs/aacenc/src/tns.c
index 455a864..5172612 100644
--- a/media/libstagefright/codecs/aacenc/src/tns.c
+++ b/media/libstagefright/codecs/aacenc/src/tns.c
@@ -30,6 +30,8 @@
 #include "psy_configuration.h"
 #include "tns_func.h"
 
+#define UNUSED(x) (void)(x)
+
 #define TNS_MODIFY_BEGIN         2600  /* Hz */
 #define RATIO_PATCH_LOWER_BORDER 380   /* Hz */
 #define TNS_GAIN_THRESH			 141   /* 1.41*100 */
@@ -643,6 +645,8 @@
   Word32 i;
   Word32 tnsOrderPlus1 = tnsOrder + 1;
 
+  UNUSED(window);
+
   assert(tnsOrder <= TNS_MAX_ORDER);      /* remove asserts later? (btg) */
 
   for(i=0;i<tnsOrder;i++) {
diff --git a/media/libstagefright/codecs/amrnb/common/Android.mk b/media/libstagefright/codecs/amrnb/common/Android.mk
index 30ce29c..a2b3c8f 100644
--- a/media/libstagefright/codecs/amrnb/common/Android.mk
+++ b/media/libstagefright/codecs/amrnb/common/Android.mk
@@ -69,6 +69,8 @@
 LOCAL_CFLAGS := \
         -DOSCL_UNUSED_ARG= -DOSCL_IMPORT_REF= -DOSCL_EXPORT_REF=
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_MODULE := libstagefright_amrnb_common
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/amrnb/dec/Android.mk b/media/libstagefright/codecs/amrnb/dec/Android.mk
index 8d6c6f8..b067456 100644
--- a/media/libstagefright/codecs/amrnb/dec/Android.mk
+++ b/media/libstagefright/codecs/amrnb/dec/Android.mk
@@ -47,6 +47,8 @@
 LOCAL_CFLAGS := \
         -DOSCL_UNUSED_ARG= -DOSCL_IMPORT_REF=
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_MODULE := libstagefright_amrnbdec
 
 include $(BUILD_STATIC_LIBRARY)
@@ -68,6 +70,8 @@
 
 LOCAL_CFLAGS := -DOSCL_IMPORT_REF=
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_STATIC_LIBRARIES := \
         libstagefright_amrnbdec libstagefright_amrwbdec
 
diff --git a/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp b/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
index 3320688..d1b0f76 100644
--- a/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
+++ b/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
@@ -274,7 +274,7 @@
     return frameSize;
 }
 
-void SoftAMR::onQueueFilled(OMX_U32 portIndex) {
+void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) {
     List<BufferInfo *> &inQueue = getPortQueue(0);
     List<BufferInfo *> &outQueue = getPortQueue(1);
 
@@ -428,7 +428,7 @@
     }
 }
 
-void SoftAMR::onPortFlushCompleted(OMX_U32 portIndex) {
+void SoftAMR::onPortFlushCompleted(OMX_U32 /* portIndex */) {
 }
 
 void SoftAMR::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
diff --git a/media/libstagefright/codecs/amrnb/enc/Android.mk b/media/libstagefright/codecs/amrnb/enc/Android.mk
index f4e467a..afc0b89 100644
--- a/media/libstagefright/codecs/amrnb/enc/Android.mk
+++ b/media/libstagefright/codecs/amrnb/enc/Android.mk
@@ -69,6 +69,8 @@
 LOCAL_CFLAGS := \
         -DOSCL_UNUSED_ARG=
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_MODULE := libstagefright_amrnbenc
 
 include $(BUILD_STATIC_LIBRARY)
@@ -88,6 +90,8 @@
         $(LOCAL_PATH)/../common/include \
         $(LOCAL_PATH)/../common
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_STATIC_LIBRARIES := \
         libstagefright_amrnbenc
 
diff --git a/media/libstagefright/codecs/amrnb/enc/SoftAMRNBEncoder.cpp b/media/libstagefright/codecs/amrnb/enc/SoftAMRNBEncoder.cpp
index 50b739c..9489457 100644
--- a/media/libstagefright/codecs/amrnb/enc/SoftAMRNBEncoder.cpp
+++ b/media/libstagefright/codecs/amrnb/enc/SoftAMRNBEncoder.cpp
@@ -270,7 +270,7 @@
     }
 }
 
-void SoftAMRNBEncoder::onQueueFilled(OMX_U32 portIndex) {
+void SoftAMRNBEncoder::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError) {
         return;
     }
diff --git a/media/libstagefright/codecs/amrwb/Android.mk b/media/libstagefright/codecs/amrwb/Android.mk
index 677107f..efdf988 100644
--- a/media/libstagefright/codecs/amrwb/Android.mk
+++ b/media/libstagefright/codecs/amrwb/Android.mk
@@ -50,6 +50,8 @@
 LOCAL_CFLAGS := \
         -DOSCL_UNUSED_ARG= -DOSCL_IMPORT_REF=
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_MODULE := libstagefright_amrwbdec
 
 include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/codecs/amrwbenc/Android.mk b/media/libstagefright/codecs/amrwbenc/Android.mk
index c5b8e0c..64fe8d1 100644
--- a/media/libstagefright/codecs/amrwbenc/Android.mk
+++ b/media/libstagefright/codecs/amrwbenc/Android.mk
@@ -112,6 +112,8 @@
 LOCAL_C_INCLUDES += $(LOCAL_PATH)/src/asm/ARMV7
 endif
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_STATIC_LIBRARY)
 
 ################################################################################
@@ -126,6 +128,8 @@
 	frameworks/av/media/libstagefright/codecs/common/include \
 	frameworks/native/include/media/openmax
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_STATIC_LIBRARIES := \
         libstagefright_amrwbenc
 
diff --git a/media/libstagefright/codecs/amrwbenc/SoftAMRWBEncoder.cpp b/media/libstagefright/codecs/amrwbenc/SoftAMRWBEncoder.cpp
index 9ccb49c..91a512d 100644
--- a/media/libstagefright/codecs/amrwbenc/SoftAMRWBEncoder.cpp
+++ b/media/libstagefright/codecs/amrwbenc/SoftAMRWBEncoder.cpp
@@ -317,7 +317,7 @@
     }
 }
 
-void SoftAMRWBEncoder::onQueueFilled(OMX_U32 portIndex) {
+void SoftAMRWBEncoder::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError) {
         return;
     }
diff --git a/media/libstagefright/codecs/amrwbenc/src/autocorr.c b/media/libstagefright/codecs/amrwbenc/src/autocorr.c
index 8c477ca..0b2ea89 100644
--- a/media/libstagefright/codecs/amrwbenc/src/autocorr.c
+++ b/media/libstagefright/codecs/amrwbenc/src/autocorr.c
@@ -28,6 +28,8 @@
 #include "acelp.h"
 #include "ham_wind.tab"
 
+#define UNUSED(x) (void)(x)
+
 void Autocorr(
 		Word16 x[],                           /* (i)    : Input signal                      */
 		Word16 m,                             /* (i)    : LPC order                         */
@@ -40,6 +42,8 @@
 	Word32 L_sum, L_sum1, L_tmp, F_LEN;
 	Word16 *p1,*p2,*p3;
 	const Word16 *p4;
+        UNUSED(m);
+
 	/* Windowing of signal */
 	p1 = x;
 	p4 = vo_window;
diff --git a/media/libstagefright/codecs/amrwbenc/src/convolve.c b/media/libstagefright/codecs/amrwbenc/src/convolve.c
index acba532..4c1f7d4 100644
--- a/media/libstagefright/codecs/amrwbenc/src/convolve.c
+++ b/media/libstagefright/codecs/amrwbenc/src/convolve.c
@@ -25,6 +25,8 @@
 #include "typedef.h"
 #include "basic_op.h"
 
+#define UNUSED(x) (void)(x)
+
 void Convolve (
 		Word16 x[],        /* (i)     : input vector                           */
 		Word16 h[],        /* (i)     : impulse response                       */
@@ -35,6 +37,8 @@
 	Word32  i, n;
 	Word16 *tmpH,*tmpX;
 	Word32 s;
+        UNUSED(L);
+
 	for (n = 0; n < 64;)
 	{
 		tmpH = h+n;
diff --git a/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c b/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
index 0d66c31..b66b55e 100644
--- a/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
+++ b/media/libstagefright/codecs/amrwbenc/src/pitch_f4.c
@@ -31,6 +31,8 @@
 #define UP_SAMP      4
 #define L_INTERPOL1  4
 
+#define UNUSED(x) (void)(x)
+
 /* Local functions */
 
 #ifdef ASM_OPT
@@ -171,6 +173,7 @@
 	Word32 corr, exp_corr, norm, exp, scale;
 	Word16 exp_norm, excf[L_SUBFR], tmp;
 	Word32 L_tmp, L_tmp1, L_tmp2;
+        UNUSED(L_subfr);
 
 	/* compute the filtered excitation for the first delay t_min */
 	k = -t_min;
diff --git a/media/libstagefright/codecs/amrwbenc/src/syn_filt.c b/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
index 1bda05a..961aadc 100644
--- a/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
+++ b/media/libstagefright/codecs/amrwbenc/src/syn_filt.c
@@ -26,6 +26,8 @@
 #include "math_op.h"
 #include "cnst.h"
 
+#define UNUSED(x) (void)(x)
+
 void Syn_filt(
 		Word16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
 		Word16 x[],                           /* (i)     : input signal                             */
@@ -95,6 +97,8 @@
 	Word32 i,a0;
 	Word32 L_tmp, L_tmp1;
 	Word16 *p1, *p2, *p3;
+        UNUSED(m);
+
 	a0 = a[0] >> (4 + Qnew);          /* input / 16 and >>Qnew */
 	/* Do the filtering. */
 	for (i = 0; i < lg; i++)
diff --git a/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c b/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
index ea9da52..df7b9b3 100644
--- a/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
+++ b/media/libstagefright/codecs/amrwbenc/src/voAMRWBEnc.c
@@ -39,6 +39,8 @@
 #include "mem_align.h"
 #include "cmnMemory.h"
 
+#define UNUSED(x) (void)(x)
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -1602,6 +1604,8 @@
 	VO_MEM_OPERATOR voMemoprator;
 #endif
 	VO_MEM_OPERATOR *pMemOP;
+        UNUSED(vType);
+
 	int interMem = 0;
 
 	if(pUserData == NULL || pUserData->memflag != VO_IMF_USERMEMOPERATOR || pUserData->memData == NULL )
diff --git a/media/libstagefright/codecs/avc/common/Android.mk b/media/libstagefright/codecs/avc/common/Android.mk
index 22dee15..844ef0a 100644
--- a/media/libstagefright/codecs/avc/common/Android.mk
+++ b/media/libstagefright/codecs/avc/common/Android.mk
@@ -16,4 +16,6 @@
 	$(LOCAL_PATH)/src \
  	$(LOCAL_PATH)/include
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/avc/enc/Android.mk b/media/libstagefright/codecs/avc/enc/Android.mk
index 7d17c2a..537ba42 100644
--- a/media/libstagefright/codecs/avc/enc/Android.mk
+++ b/media/libstagefright/codecs/avc/enc/Android.mk
@@ -30,6 +30,8 @@
 LOCAL_CFLAGS := \
     -DOSCL_IMPORT_REF= -DOSCL_UNUSED_ARG= -DOSCL_EXPORT_REF=
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_STATIC_LIBRARY)
 
 ################################################################################
@@ -69,4 +71,6 @@
 LOCAL_MODULE := libstagefright_soft_h264enc
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/avc/enc/SoftAVCEncoder.cpp b/media/libstagefright/codecs/avc/enc/SoftAVCEncoder.cpp
index 4a21a3e..a15b040 100644
--- a/media/libstagefright/codecs/avc/enc/SoftAVCEncoder.cpp
+++ b/media/libstagefright/codecs/avc/enc/SoftAVCEncoder.cpp
@@ -34,6 +34,12 @@
 
 #include "SoftAVCEncoder.h"
 
+#if LOG_NDEBUG
+#define UNUSED_UNLESS_VERBOSE(x) (void)(x)
+#else
+#define UNUSED_UNLESS_VERBOSE(x)
+#endif
+
 namespace android {
 
 template<class T>
@@ -136,14 +142,14 @@
 }
 
 static void* MallocWrapper(
-        void *userData, int32_t size, int32_t attrs) {
+        void * /* userData */, int32_t size, int32_t /* attrs */) {
     void *ptr = malloc(size);
     if (ptr)
         memset(ptr, 0, size);
     return ptr;
 }
 
-static void FreeWrapper(void *userData, void* ptr) {
+static void FreeWrapper(void * /* userData */, void* ptr) {
     free(ptr);
 }
 
@@ -217,7 +223,7 @@
     mHandle->CBAVC_Free = FreeWrapper;
 
     CHECK(mEncParams != NULL);
-    memset(mEncParams, 0, sizeof(mEncParams));
+    memset(mEncParams, 0, sizeof(*mEncParams));
     mEncParams->rate_control = AVC_ON;
     mEncParams->initQP = 0;
     mEncParams->init_CBP_removal_delay = 1600;
@@ -593,6 +599,17 @@
                 mVideoHeight = def->format.video.nFrameHeight;
                 mVideoFrameRate = def->format.video.xFramerate >> 16;
                 mVideoColorFormat = def->format.video.eColorFormat;
+
+                OMX_PARAM_PORTDEFINITIONTYPE *portDef =
+                    &editPortInfo(0)->mDef;
+                portDef->format.video.nFrameWidth = mVideoWidth;
+                portDef->format.video.nFrameHeight = mVideoHeight;
+                portDef->format.video.xFramerate = def->format.video.xFramerate;
+                portDef->format.video.eColorFormat =
+                    (OMX_COLOR_FORMATTYPE) mVideoColorFormat;
+                portDef = &editPortInfo(1)->mDef;
+                portDef->format.video.nFrameWidth = mVideoWidth;
+                portDef->format.video.nFrameHeight = mVideoHeight;
             } else {
                 mVideoBitRate = def->format.video.nBitrate;
             }
@@ -711,7 +728,7 @@
     }
 }
 
-void SoftAVCEncoder::onQueueFilled(OMX_U32 portIndex) {
+void SoftAVCEncoder::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError || mSawInputEOS) {
         return;
     }
@@ -784,7 +801,7 @@
             }
         }
 
-        buffer_handle_t srcBuffer; // for MetaDataMode only
+        buffer_handle_t srcBuffer = NULL; // for MetaDataMode only
 
         // Get next input video frame
         if (mReadyForNextFrame) {
@@ -953,6 +970,7 @@
 }
 
 void SoftAVCEncoder::signalBufferReturned(MediaBuffer *buffer) {
+    UNUSED_UNLESS_VERBOSE(buffer);
     ALOGV("signalBufferReturned: %p", buffer);
 }
 
diff --git a/media/libstagefright/codecs/avc/enc/src/bitstream_io.cpp b/media/libstagefright/codecs/avc/enc/src/bitstream_io.cpp
index 0e3037f..d71c327 100644
--- a/media/libstagefright/codecs/avc/enc/src/bitstream_io.cpp
+++ b/media/libstagefright/codecs/avc/enc/src/bitstream_io.cpp
@@ -103,6 +103,15 @@
     {
         num_bits -= 8;
         byte = (current_word >> num_bits) & 0xFF;
+        if (stream->count_zeros == 2)
+        {   /* for num_bits = 32, this can add 2 more bytes extra for EPBS */
+            if (byte <= 3)
+            {
+                *write_pnt++ = 0x3;
+                stream->write_pos++;
+                stream->count_zeros = 0;
+            }
+        }
         if (byte != 0)
         {
             *write_pnt++ = byte;
@@ -114,12 +123,6 @@
             stream->count_zeros++;
             *write_pnt++ = byte;
             stream->write_pos++;
-            if (stream->count_zeros == 2)
-            {   /* for num_bits = 32, this can add 2 more bytes extra for EPBS */
-                *write_pnt++ = 0x3;
-                stream->write_pos++;
-                stream->count_zeros = 0;
-            }
         }
     }
 
diff --git a/media/libstagefright/codecs/common/Android.mk b/media/libstagefright/codecs/common/Android.mk
index a33cb92..b0010ff 100644
--- a/media/libstagefright/codecs/common/Android.mk
+++ b/media/libstagefright/codecs/common/Android.mk
@@ -14,6 +14,8 @@
 LOCAL_C_INCLUDES := \
 	$(LOCAL_PATH)/include
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
 
 
diff --git a/media/libstagefright/codecs/common/cmnMemory.c b/media/libstagefright/codecs/common/cmnMemory.c
index aa52bd9..5bb6cc4 100644
--- a/media/libstagefright/codecs/common/cmnMemory.c
+++ b/media/libstagefright/codecs/common/cmnMemory.c
@@ -26,8 +26,12 @@
 
 //VO_MEM_OPERATOR		g_memOP;
 
+#define UNUSED(x) (void)(x)
+
 VO_U32 cmnMemAlloc (VO_S32 uID,  VO_MEM_INFO * pMemInfo)
 {
+        UNUSED(uID);
+
 	if (!pMemInfo)
 		return VO_ERR_INVALID_ARG;
 
@@ -37,34 +41,48 @@
 
 VO_U32 cmnMemFree (VO_S32 uID, VO_PTR pMem)
 {
+        UNUSED(uID);
+
 	free (pMem);
 	return 0;
 }
 
 VO_U32	cmnMemSet (VO_S32 uID, VO_PTR pBuff, VO_U8 uValue, VO_U32 uSize)
 {
+        UNUSED(uID);
+
 	memset (pBuff, uValue, uSize);
 	return 0;
 }
 
 VO_U32	cmnMemCopy (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize)
 {
+        UNUSED(uID);
+
 	memcpy (pDest, pSource, uSize);
 	return 0;
 }
 
 VO_U32	cmnMemCheck (VO_S32 uID, VO_PTR pBuffer, VO_U32 uSize)
 {
+        UNUSED(uID);
+        UNUSED(pBuffer);
+        UNUSED(uSize);
+
 	return 0;
 }
 
 VO_S32 cmnMemCompare (VO_S32 uID, VO_PTR pBuffer1, VO_PTR pBuffer2, VO_U32 uSize)
 {
+        UNUSED(uID);
+
 	return memcmp(pBuffer1, pBuffer2, uSize);
 }
 
 VO_U32	cmnMemMove (VO_S32 uID, VO_PTR pDest, VO_PTR pSource, VO_U32 uSize)
 {
+        UNUSED(uID);
+
 	memmove (pDest, pSource, uSize);
 	return 0;
 }
diff --git a/media/libstagefright/codecs/flac/enc/Android.mk b/media/libstagefright/codecs/flac/enc/Android.mk
index f01d605..59a11de 100644
--- a/media/libstagefright/codecs/flac/enc/Android.mk
+++ b/media/libstagefright/codecs/flac/enc/Android.mk
@@ -9,6 +9,8 @@
         frameworks/native/include/media/openmax \
         external/flac/include
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_SHARED_LIBRARIES := \
         libstagefright libstagefright_omx libstagefright_foundation libutils liblog
 
diff --git a/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp b/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp
index e64fe72..40661e7 100644
--- a/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp
+++ b/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp
@@ -27,6 +27,12 @@
 #define FLAC_COMPRESSION_LEVEL_DEFAULT 5
 #define FLAC_COMPRESSION_LEVEL_MAX     8
 
+#if LOG_NDEBUG
+#define UNUSED_UNLESS_VERBOSE(x) (void)(x)
+#else
+#define UNUSED_UNLESS_VERBOSE(x)
+#endif
+
 namespace android {
 
 template<class T>
@@ -257,7 +263,7 @@
 }
 
 void SoftFlacEncoder::onQueueFilled(OMX_U32 portIndex) {
-
+    UNUSED_UNLESS_VERBOSE(portIndex);
     ALOGV("SoftFlacEncoder::onQueueFilled(portIndex=%ld)", portIndex);
 
     if (mSignalledError) {
@@ -343,10 +349,11 @@
     }
 }
 
-
 FLAC__StreamEncoderWriteStatus SoftFlacEncoder::onEncodedFlacAvailable(
             const FLAC__byte buffer[],
-            size_t bytes, unsigned samples, unsigned current_frame) {
+            size_t bytes, unsigned samples,
+            unsigned current_frame) {
+    UNUSED_UNLESS_VERBOSE(current_frame);
     ALOGV("SoftFlacEncoder::onEncodedFlacAvailable(bytes=%d, samples=%d, curr_frame=%d)",
             bytes, samples, current_frame);
 
@@ -444,8 +451,12 @@
 
 // static
 FLAC__StreamEncoderWriteStatus SoftFlacEncoder::flacEncoderWriteCallback(
-            const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[],
-            size_t bytes, unsigned samples, unsigned current_frame, void *client_data) {
+            const FLAC__StreamEncoder * /* encoder */,
+            const FLAC__byte buffer[],
+            size_t bytes,
+            unsigned samples,
+            unsigned current_frame,
+            void *client_data) {
     return ((SoftFlacEncoder*) client_data)->onEncodedFlacAvailable(
             buffer, bytes, samples, current_frame);
 }
diff --git a/media/libstagefright/codecs/g711/dec/Android.mk b/media/libstagefright/codecs/g711/dec/Android.mk
index 4c80da6..a0112e1 100644
--- a/media/libstagefright/codecs/g711/dec/Android.mk
+++ b/media/libstagefright/codecs/g711/dec/Android.mk
@@ -14,4 +14,6 @@
 LOCAL_MODULE := libstagefright_soft_g711dec
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/g711/dec/SoftG711.cpp b/media/libstagefright/codecs/g711/dec/SoftG711.cpp
index bcdd3c7..160ada0 100644
--- a/media/libstagefright/codecs/g711/dec/SoftG711.cpp
+++ b/media/libstagefright/codecs/g711/dec/SoftG711.cpp
@@ -182,7 +182,7 @@
     }
 }
 
-void SoftG711::onQueueFilled(OMX_U32 portIndex) {
+void SoftG711::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError) {
         return;
     }
diff --git a/media/libstagefright/codecs/gsm/dec/Android.mk b/media/libstagefright/codecs/gsm/dec/Android.mk
index 71613d2..30868d5 100644
--- a/media/libstagefright/codecs/gsm/dec/Android.mk
+++ b/media/libstagefright/codecs/gsm/dec/Android.mk
@@ -9,6 +9,8 @@
         frameworks/native/include/media/openmax \
         external/libgsm/inc
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_SHARED_LIBRARIES := \
         libstagefright libstagefright_omx libstagefright_foundation libutils liblog
 
diff --git a/media/libstagefright/codecs/gsm/dec/SoftGSM.cpp b/media/libstagefright/codecs/gsm/dec/SoftGSM.cpp
index 00e0c85..18f7d29 100644
--- a/media/libstagefright/codecs/gsm/dec/SoftGSM.cpp
+++ b/media/libstagefright/codecs/gsm/dec/SoftGSM.cpp
@@ -172,7 +172,7 @@
     }
 }
 
-void SoftGSM::onQueueFilled(OMX_U32 portIndex) {
+void SoftGSM::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError) {
         return;
     }
diff --git a/media/libstagefright/codecs/m4v_h263/dec/Android.mk b/media/libstagefright/codecs/m4v_h263/dec/Android.mk
index a3d5779..1d232c6 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/Android.mk
+++ b/media/libstagefright/codecs/m4v_h263/dec/Android.mk
@@ -46,6 +46,8 @@
 
 LOCAL_CFLAGS := -DOSCL_EXPORT_REF= -DOSCL_IMPORT_REF=
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_STATIC_LIBRARY)
 
 ################################################################################
@@ -72,4 +74,6 @@
 LOCAL_MODULE := libstagefright_soft_mpeg4dec
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp b/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
index fb2a430..0d1ab71 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
+++ b/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
@@ -91,7 +91,7 @@
     return OK;
 }
 
-void SoftMPEG4::onQueueFilled(OMX_U32 portIndex) {
+void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError || mOutputPortSettingsChange != NONE) {
         return;
     }
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp
index e23f23d..fe9e7dc 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp
@@ -96,7 +96,7 @@
     offset = width - B_SIZE; /* offset for prev */
     offset2 = (pred_width_rnd >> 1) - 4; /* offset for pred_block */
 
-    tmp = (uint32)prev & 0x3;
+    tmp = (uintptr_t)prev & 0x3;
     pred_block -= offset2; /* preset */
 
     if (tmp == 0)  /* word-aligned */
@@ -203,7 +203,7 @@
     /* Branch based on pixel location (half-pel or full-pel) for x and y */
     pred_block -= offset2; /* preset */
 
-    tmp = (uint32)prev & 3;
+    tmp = (uintptr_t)prev & 3;
     mask = 254;
     mask |= (mask << 8);
     mask |= (mask << 16); /* 0xFEFEFEFE */
@@ -532,7 +532,7 @@
     /* Branch based on pixel location (half-pel or full-pel) for x and y */
     pred_block -= offset2; /* preset */
 
-    tmp = (uint32)prev & 3;
+    tmp = (uintptr_t)prev & 3;
     mask = 254;
     mask |= (mask << 8);
     mask |= (mask << 16); /* 0xFEFEFEFE */
@@ -884,7 +884,7 @@
     mask |= (mask << 8);
     mask |= (mask << 16); /* 0x3f3f3f3f */
 
-    tmp = (uint32)prev & 3;
+    tmp = (uintptr_t)prev & 3;
 
     pred_block -= 4; /* preset */
 
diff --git a/media/libstagefright/codecs/m4v_h263/enc/Android.mk b/media/libstagefright/codecs/m4v_h263/enc/Android.mk
index 83a2dd2..c9006d9 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/Android.mk
+++ b/media/libstagefright/codecs/m4v_h263/enc/Android.mk
@@ -33,6 +33,8 @@
     $(TOP)/frameworks/av/media/libstagefright/include \
     $(TOP)/frameworks/native/include/media/openmax
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_STATIC_LIBRARY)
 
 ################################################################################
@@ -72,4 +74,6 @@
 LOCAL_MODULE := libstagefright_soft_mpeg4enc
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp b/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
index e02af90..2c73e57 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
+++ b/media/libstagefright/codecs/m4v_h263/enc/SoftMPEG4Encoder.cpp
@@ -620,7 +620,7 @@
     }
 }
 
-void SoftMPEG4Encoder::onQueueFilled(OMX_U32 portIndex) {
+void SoftMPEG4Encoder::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError || mSawInputEOS) {
         return;
     }
@@ -677,7 +677,7 @@
             mSawInputEOS = true;
         }
 
-        buffer_handle_t srcBuffer; // for MetaDataMode only
+        buffer_handle_t srcBuffer = NULL; // for MetaDataMode only
         if (inHeader->nFilledLen > 0) {
             uint8_t *inputData = NULL;
             if (mStoreMetaDataInBuffers) {
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/dct.cpp b/media/libstagefright/codecs/m4v_h263/enc/src/dct.cpp
index fa50eeb..fa4ae23 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/src/dct.cpp
+++ b/media/libstagefright/codecs/m4v_h263/enc/src/dct.cpp
@@ -250,7 +250,7 @@
             out[40] = k4 ;   /* row 5 */
             out++;
         }
-        while ((UInt)out < (UInt)dst) ;
+        while ((uintptr_t)out < (uintptr_t)dst) ;
 
         return ;
     }
@@ -455,7 +455,7 @@
             out[8] = k5 ;       /* row 1 */
             out++;
         }
-        while ((UInt)out < (UInt)dst) ;
+        while ((uintptr_t)out < (uintptr_t)dst) ;
 
         return ;
     }
@@ -635,7 +635,7 @@
             out[8] = k5 ;       /* row 1 */
             out++;
         }
-        while ((UInt)out < (UInt)dst) ;
+        while ((uintptr_t)out < (uintptr_t)dst) ;
 
         return ;
     }
@@ -846,7 +846,7 @@
             out[40] = k4 ;   /* row 5 */
             out++;
         }
-        while ((UInt)out < (UInt)dst) ;
+        while ((uintptr_t)out < (uintptr_t)dst) ;
 
         return ;
     }
@@ -1033,7 +1033,7 @@
             out[8] = k5 ;       /* row 1 */
             out++;
         }
-        while ((UInt)out < (UInt)dst) ;
+        while ((uintptr_t)out < (uintptr_t)dst) ;
 
         return ;
     }
@@ -1195,7 +1195,7 @@
             out[8] = k5 ;       /* row 1 */
             out++;
         }
-        while ((UInt)out < (UInt)dst) ;
+        while ((uintptr_t)out < (uintptr_t)dst) ;
 
         return ;
     }
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp b/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp
index 6fd41c3..0ad39a6 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp
+++ b/media/libstagefright/codecs/m4v_h263/enc/src/fastcodemb.cpp
@@ -572,7 +572,7 @@
         cur2    = cur2 & (mask << 8);   /* mask first and third bytes */
         sum2    = sum2 + ((UInt)cur2 >> 8);
     }
-    while ((UInt)curInt < (UInt)end);
+    while ((uintptr_t)curInt < (uintptr_t)end);
 
     cur1 = sum4 - (sum2 << 8);  /* get even-sum */
     cur1 = cur1 + sum2;         /* add 16 bit even-sum and odd-sum*/
@@ -611,7 +611,7 @@
         load2 = load2 & (mask << 8); /* even bytes */
         sum2 += ((UInt)load2 >> 8); /* sum even bytes, 16 bit */
     }
-    while ((UInt)curInt < (UInt)end);
+    while ((uintptr_t)curInt < (uintptr_t)end);
     load1 = sum4 - (sum2 << 8);     /* get even-sum */
     load1 = load1 + sum2;           /* add 16 bit even-sum and odd-sum*/
     load1 = load1 + (load1 << 16);  /* add upper and lower 16 bit sum */
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/motion_comp.cpp b/media/libstagefright/codecs/m4v_h263/enc/src/motion_comp.cpp
index b81d278..06e8926 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/src/motion_comp.cpp
+++ b/media/libstagefright/codecs/m4v_h263/enc/src/motion_comp.cpp
@@ -1959,7 +1959,7 @@
         dst += offset;
         src += offset;
     }
-    while ((UInt)src < (UInt)end);
+    while ((uintptr_t)src < (uintptr_t)end);
 
     return ;
 }
diff --git a/media/libstagefright/codecs/m4v_h263/enc/src/sad_inline.h b/media/libstagefright/codecs/m4v_h263/enc/src/sad_inline.h
index ba77dfd..b865f23 100644
--- a/media/libstagefright/codecs/m4v_h263/enc/src/sad_inline.h
+++ b/media/libstagefright/codecs/m4v_h263/enc/src/sad_inline.h
@@ -85,7 +85,7 @@
 
         x9 = 0x80808080; /* const. */
 
-        x8 = (uint32)ref & 0x3;
+        x8 = (uintptr_t)ref & 0x3;
         if (x8 == 3)
             goto SadMBOffset3;
         if (x8 == 2)
diff --git a/media/libstagefright/codecs/mp3dec/Android.mk b/media/libstagefright/codecs/mp3dec/Android.mk
index 135c715..8284490 100644
--- a/media/libstagefright/codecs/mp3dec/Android.mk
+++ b/media/libstagefright/codecs/mp3dec/Android.mk
@@ -50,6 +50,8 @@
 LOCAL_CFLAGS := \
         -DOSCL_UNUSED_ARG=
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_MODULE := libstagefright_mp3dec
 
 LOCAL_ARM_MODE := arm
@@ -69,6 +71,8 @@
         $(LOCAL_PATH)/src \
         $(LOCAL_PATH)/include
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_SHARED_LIBRARIES := \
         libstagefright libstagefright_omx libstagefright_foundation libutils liblog
 
diff --git a/media/libstagefright/codecs/mp3dec/SoftMP3.cpp b/media/libstagefright/codecs/mp3dec/SoftMP3.cpp
index 61df65e..a09ab7c 100644
--- a/media/libstagefright/codecs/mp3dec/SoftMP3.cpp
+++ b/media/libstagefright/codecs/mp3dec/SoftMP3.cpp
@@ -188,7 +188,7 @@
     }
 }
 
-void SoftMP3::onQueueFilled(OMX_U32 portIndex) {
+void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError || mOutputPortSettingsChange != NONE) {
         return;
     }
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp
index ee42dc5..499672b 100644
--- a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp
@@ -139,7 +139,7 @@
     int16 blocknumber = 0;
 
     granuleInfo *gr_info = &(si->ch[ch].gran[gr]);
-    uint32 scalefac_comp, int_scalefac_comp, new_slen[4];
+    uint32 scalefac_comp, int_scalefac_comp, new_slen[4] = { 0,0,0,0 };
 
     scalefac_comp =  gr_info->scalefac_compress;
 
diff --git a/media/libstagefright/codecs/on2/dec/Android.mk b/media/libstagefright/codecs/on2/dec/Android.mk
index 7f2c46d..93ff64c 100644
--- a/media/libstagefright/codecs/on2/dec/Android.mk
+++ b/media/libstagefright/codecs/on2/dec/Android.mk
@@ -20,4 +20,6 @@
 LOCAL_MODULE := libstagefright_soft_vpxdec
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/on2/dec/SoftVPX.cpp b/media/libstagefright/codecs/on2/dec/SoftVPX.cpp
index 476e986..423a057 100644
--- a/media/libstagefright/codecs/on2/dec/SoftVPX.cpp
+++ b/media/libstagefright/codecs/on2/dec/SoftVPX.cpp
@@ -85,7 +85,7 @@
     return OK;
 }
 
-void SoftVPX::onQueueFilled(OMX_U32 portIndex) {
+void SoftVPX::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mOutputPortSettingsChange != NONE) {
         return;
     }
diff --git a/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp b/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
index 8375cac..5efe022 100644
--- a/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
+++ b/media/libstagefright/codecs/on2/enc/SoftVPXEncoder.cpp
@@ -677,6 +677,9 @@
         def->format.video.nFrameHeight = mHeight;
         def->format.video.xFramerate = port->format.video.xFramerate;
         def->format.video.eColorFormat = mColorFormat;
+        def = &editPortInfo(kOutputPortIndex)->mDef;
+        def->format.video.nFrameWidth = mWidth;
+        def->format.video.nFrameHeight = mHeight;
 
         return OMX_ErrorNone;
     } else if (port->nPortIndex == kOutputPortIndex) {
diff --git a/media/libstagefright/codecs/on2/h264dec/SoftAVC.cpp b/media/libstagefright/codecs/on2/h264dec/SoftAVC.cpp
index 7ddb13c..a7bde97 100644
--- a/media/libstagefright/codecs/on2/h264dec/SoftAVC.cpp
+++ b/media/libstagefright/codecs/on2/h264dec/SoftAVC.cpp
@@ -98,7 +98,7 @@
     return UNKNOWN_ERROR;
 }
 
-void SoftAVC::onQueueFilled(OMX_U32 portIndex) {
+void SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError || mOutputPortSettingsChange != NONE) {
         return;
     }
diff --git a/media/libstagefright/codecs/on2/h264dec/source/H264SwDecApi.c b/media/libstagefright/codecs/on2/h264dec/source/H264SwDecApi.c
index 2bb4c4d..524a3f0 100644
--- a/media/libstagefright/codecs/on2/h264dec/source/H264SwDecApi.c
+++ b/media/libstagefright/codecs/on2/h264dec/source/H264SwDecApi.c
@@ -42,6 +42,8 @@
 #include "h264bsd_decoder.h"
 #include "h264bsd_util.h"
 
+#define UNUSED(x) (void)(x)
+
 /*------------------------------------------------------------------------------
        Version Information
 ------------------------------------------------------------------------------*/
@@ -73,6 +75,7 @@
 #endif
 
 void H264SwDecTrace(char *string) {
+    UNUSED(string);
 }
 
 void* H264SwDecMalloc(u32 size) {
diff --git a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_conceal.c b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_conceal.c
index 493fb9e..7a262ed 100755
--- a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_conceal.c
+++ b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_conceal.c
@@ -267,7 +267,7 @@
     i32 firstPhase[16];
     i32 *pTmp;
     /* neighbours above, below, left and right */
-    i32 a[4], b[4], l[4], r[4];
+    i32 a[4] = { 0,0,0,0 }, b[4], l[4] = { 0,0,0,0 }, r[4];
     u32 A, B, L, R;
 #ifdef H264DEC_OMXDL
     u8 fillBuff[32*21 + 15 + 32];
diff --git a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_reconstruct.c b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_reconstruct.c
index c948776..b409a06 100755
--- a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_reconstruct.c
+++ b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_reconstruct.c
@@ -42,6 +42,8 @@
 #include "armVC.h"
 #endif /* H264DEC_OMXDL */
 
+#define UNUSED(x) (void)(x)
+
 /*------------------------------------------------------------------------------
     2. External compiler flags
 --------------------------------------------------------------------------------
@@ -2136,7 +2138,8 @@
   i32 center,
   i32 right)
 {
-
+    UNUSED(left);
+    UNUSED(right);
     ASSERT(ref);
     ASSERT(fill);
 
diff --git a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_slice_header.c b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_slice_header.c
index a7c6f64..23401c6 100755
--- a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_slice_header.c
+++ b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_slice_header.c
@@ -47,6 +47,8 @@
 #include "h264bsd_nal_unit.h"
 #include "h264bsd_dpb.h"
 
+#define UNUSED(x) (void)(x)
+
 /*------------------------------------------------------------------------------
     2. External compiler flags
 --------------------------------------------------------------------------------
@@ -1407,6 +1409,7 @@
     u32 tmp, value, i;
     i32 ivalue;
     strmData_t tmpStrmData[1];
+    UNUSED(nalUnitType);
 
 /* Code */
 
diff --git a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.c b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.c
index cc838fd..fb97a28 100755
--- a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.c
+++ b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.c
@@ -186,7 +186,7 @@
         return(HANTRO_FALSE);
 
     if ( (bits > 8) ||
-         ((h264bsdShowBits32(pStrmData)>>(32-bits)) != (1 << (bits-1))) )
+         ((h264bsdShowBits32(pStrmData)>>(32-bits)) != (1ul << (bits-1))) )
         return(HANTRO_TRUE);
     else
         return(HANTRO_FALSE);
diff --git a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.h b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.h
index cb3adda..216ad04 100755
--- a/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.h
+++ b/media/libstagefright/codecs/on2/h264dec/source/h264bsd_util.h
@@ -42,6 +42,7 @@
 #include <stdio.h>
 #endif
 
+#include <stdint.h>
 #include "basetype.h"
 #include "h264bsd_stream.h"
 #include "h264bsd_image.h"
@@ -150,7 +151,7 @@
 }
 
 #define ALIGN(ptr, bytePos) \
-        (ptr + ( ((bytePos - (int)ptr) & (bytePos - 1)) / sizeof(*ptr) ))
+        (ptr + ( ((bytePos - (uintptr_t)ptr) & (bytePos - 1)) / sizeof(*ptr) ))
 
 extern const u32 h264bsdQpC[52];
 
diff --git a/media/libstagefright/codecs/raw/Android.mk b/media/libstagefright/codecs/raw/Android.mk
index fe90a03..87080e7 100644
--- a/media/libstagefright/codecs/raw/Android.mk
+++ b/media/libstagefright/codecs/raw/Android.mk
@@ -8,6 +8,8 @@
         frameworks/av/media/libstagefright/include \
         frameworks/native/include/media/openmax
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_SHARED_LIBRARIES := \
         libstagefright_omx libstagefright_foundation libutils liblog
 
diff --git a/media/libstagefright/codecs/raw/SoftRaw.cpp b/media/libstagefright/codecs/raw/SoftRaw.cpp
index 19d6f13..9d514a6 100644
--- a/media/libstagefright/codecs/raw/SoftRaw.cpp
+++ b/media/libstagefright/codecs/raw/SoftRaw.cpp
@@ -163,7 +163,7 @@
     }
 }
 
-void SoftRaw::onQueueFilled(OMX_U32 portIndex) {
+void SoftRaw::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError) {
         return;
     }
diff --git a/media/libstagefright/codecs/vorbis/dec/Android.mk b/media/libstagefright/codecs/vorbis/dec/Android.mk
index 2232353..217a6d2 100644
--- a/media/libstagefright/codecs/vorbis/dec/Android.mk
+++ b/media/libstagefright/codecs/vorbis/dec/Android.mk
@@ -16,4 +16,6 @@
 LOCAL_MODULE := libstagefright_soft_vorbisdec
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/foundation/ANetworkSession.cpp b/media/libstagefright/foundation/ANetworkSession.cpp
index e629588..08c4a87 100644
--- a/media/libstagefright/foundation/ANetworkSession.cpp
+++ b/media/libstagefright/foundation/ANetworkSession.cpp
@@ -521,7 +521,7 @@
     return err;
 }
 
-void ANetworkSession::Session::dumpFragmentStats(const Fragment &frag) {
+void ANetworkSession::Session::dumpFragmentStats(const Fragment & /* frag */) {
 #if 0
     int64_t nowUs = ALooper::GetNowUs();
     int64_t delayMs = (nowUs - frag.mTimeUs) / 1000ll;
diff --git a/media/libstagefright/foundation/Android.mk b/media/libstagefright/foundation/Android.mk
index ad2dab5..90a6a23 100644
--- a/media/libstagefright/foundation/Android.mk
+++ b/media/libstagefright/foundation/Android.mk
@@ -24,7 +24,7 @@
         libutils          \
         liblog
 
-LOCAL_CFLAGS += -Wno-multichar
+LOCAL_CFLAGS += -Wno-multichar -Werror
 
 LOCAL_MODULE:= libstagefright_foundation
 
diff --git a/media/libstagefright/foundation/base64.cpp b/media/libstagefright/foundation/base64.cpp
index d5fb4e0..dcf5bef 100644
--- a/media/libstagefright/foundation/base64.cpp
+++ b/media/libstagefright/foundation/base64.cpp
@@ -33,6 +33,10 @@
 
         if (n >= 2 && s.c_str()[n - 2] == '=') {
             padding = 2;
+
+            if (n >= 3 && s.c_str()[n - 3] == '=') {
+                padding = 3;
+            }
         }
     }
 
@@ -71,7 +75,7 @@
         if (((i + 1) % 4) == 0) {
             out[j++] = (accum >> 16);
 
-            if (j < outLen) { out[j++] = (accum >> 8) & 0xff; } 
+            if (j < outLen) { out[j++] = (accum >> 8) & 0xff; }
             if (j < outLen) { out[j++] = accum & 0xff; }
 
             accum = 0;
diff --git a/media/libstagefright/http/Android.mk b/media/libstagefright/http/Android.mk
index a6b481f..7f3307d 100644
--- a/media/libstagefright/http/Android.mk
+++ b/media/libstagefright/http/Android.mk
@@ -21,6 +21,8 @@
 
 LOCAL_CFLAGS += -Wno-multichar
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_SHARED_LIBRARY)
 
 endif
diff --git a/media/libstagefright/httplive/Android.mk b/media/libstagefright/httplive/Android.mk
index f3529f9..e8d558c 100644
--- a/media/libstagefright/httplive/Android.mk
+++ b/media/libstagefright/httplive/Android.mk
@@ -13,6 +13,8 @@
 	$(TOP)/frameworks/native/include/media/openmax \
 	$(TOP)/external/openssl/include
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_SHARED_LIBRARIES := \
         libbinder \
         libcrypto \
diff --git a/media/libstagefright/httplive/M3UParser.cpp b/media/libstagefright/httplive/M3UParser.cpp
index dd248cb..39d80fc 100644
--- a/media/libstagefright/httplive/M3UParser.cpp
+++ b/media/libstagefright/httplive/M3UParser.cpp
@@ -125,7 +125,7 @@
                 mSelectedIndex = strtoul(value, &end, 10);
                 CHECK(end > value && *end == '\0');
 
-                if (mSelectedIndex >= mMediaItems.size()) {
+                if (mSelectedIndex >= (ssize_t)mMediaItems.size()) {
                     mSelectedIndex = mMediaItems.size() - 1;
                 }
             } else {
@@ -165,14 +165,14 @@
             ALOGE("track %d does not exist", index);
             return INVALID_OPERATION;
         }
-        if (mSelectedIndex == index) {
+        if (mSelectedIndex == (ssize_t)index) {
             ALOGE("track %d already selected", index);
             return BAD_VALUE;
         }
         ALOGV("selected track %d", index);
         mSelectedIndex = index;
     } else {
-        if (mSelectedIndex != index) {
+        if (mSelectedIndex != (ssize_t)index) {
             ALOGE("track %d is not selected", index);
             return BAD_VALUE;
         }
@@ -416,22 +416,32 @@
     } else {
         // URL is a relative path
 
-        size_t n = strlen(baseURL);
-        if (baseURL[n - 1] == '/') {
-            out->setTo(baseURL);
-            out->append(url);
+        // Check for a possible query string
+        const char *qsPos = strchr(baseURL, '?');
+        size_t end;
+        if (qsPos != NULL) {
+            end = qsPos - baseURL;
         } else {
-            const char *slashPos = strrchr(baseURL, '/');
-
-            if (slashPos > &baseURL[6]) {
-                out->setTo(baseURL, slashPos - baseURL);
-            } else {
-                out->setTo(baseURL);
-            }
-
-            out->append("/");
-            out->append(url);
+            end = strlen(baseURL);
         }
+        // Check for the last slash before a potential query string
+        for (ssize_t pos = end - 1; pos >= 0; pos--) {
+            if (baseURL[pos] == '/') {
+                end = pos;
+                break;
+            }
+        }
+
+        // Check whether the found slash actually is part of the path
+        // and not part of the "http://".
+        if (end > 6) {
+            out->setTo(baseURL, end);
+        } else {
+            out->setTo(baseURL);
+        }
+
+        out->append("/");
+        out->append(url);
     }
 
     ALOGV("base:'%s', url:'%s' => '%s'", baseURL, url, out->c_str());
diff --git a/media/libstagefright/httplive/PlaylistFetcher.cpp b/media/libstagefright/httplive/PlaylistFetcher.cpp
index f095987..030cbde 100644
--- a/media/libstagefright/httplive/PlaylistFetcher.cpp
+++ b/media/libstagefright/httplive/PlaylistFetcher.cpp
@@ -170,7 +170,8 @@
 }
 
 status_t PlaylistFetcher::decryptBuffer(
-        size_t playlistIndex, const sp<ABuffer> &buffer) {
+        size_t playlistIndex, const sp<ABuffer> &buffer,
+        bool first) {
     sp<AMessage> itemMeta;
     bool found = false;
     AString method;
@@ -188,6 +189,7 @@
     if (!found) {
         method = "NONE";
     }
+    buffer->meta()->setString("cipher-method", method.c_str());
 
     if (method == "NONE") {
         return OK;
@@ -227,59 +229,77 @@
         return UNKNOWN_ERROR;
     }
 
-    unsigned char aes_ivec[16];
+    size_t n = buffer->size();
+    if (!n) {
+        return OK;
+    }
+    CHECK(n % 16 == 0);
 
-    AString iv;
-    if (itemMeta->findString("cipher-iv", &iv)) {
-        if ((!iv.startsWith("0x") && !iv.startsWith("0X"))
-                || iv.size() != 16 * 2 + 2) {
-            ALOGE("malformed cipher IV '%s'.", iv.c_str());
-            return ERROR_MALFORMED;
-        }
+    if (first) {
+        // If decrypting the first block in a file, read the iv from the manifest
+        // or derive the iv from the file's sequence number.
 
-        memset(aes_ivec, 0, sizeof(aes_ivec));
-        for (size_t i = 0; i < 16; ++i) {
-            char c1 = tolower(iv.c_str()[2 + 2 * i]);
-            char c2 = tolower(iv.c_str()[3 + 2 * i]);
-            if (!isxdigit(c1) || !isxdigit(c2)) {
+        AString iv;
+        if (itemMeta->findString("cipher-iv", &iv)) {
+            if ((!iv.startsWith("0x") && !iv.startsWith("0X"))
+                    || iv.size() != 16 * 2 + 2) {
                 ALOGE("malformed cipher IV '%s'.", iv.c_str());
                 return ERROR_MALFORMED;
             }
-            uint8_t nibble1 = isdigit(c1) ? c1 - '0' : c1 - 'a' + 10;
-            uint8_t nibble2 = isdigit(c2) ? c2 - '0' : c2 - 'a' + 10;
 
-            aes_ivec[i] = nibble1 << 4 | nibble2;
+            memset(mAESInitVec, 0, sizeof(mAESInitVec));
+            for (size_t i = 0; i < 16; ++i) {
+                char c1 = tolower(iv.c_str()[2 + 2 * i]);
+                char c2 = tolower(iv.c_str()[3 + 2 * i]);
+                if (!isxdigit(c1) || !isxdigit(c2)) {
+                    ALOGE("malformed cipher IV '%s'.", iv.c_str());
+                    return ERROR_MALFORMED;
+                }
+                uint8_t nibble1 = isdigit(c1) ? c1 - '0' : c1 - 'a' + 10;
+                uint8_t nibble2 = isdigit(c2) ? c2 - '0' : c2 - 'a' + 10;
+
+                mAESInitVec[i] = nibble1 << 4 | nibble2;
+            }
+        } else {
+            memset(mAESInitVec, 0, sizeof(mAESInitVec));
+            mAESInitVec[15] = mSeqNumber & 0xff;
+            mAESInitVec[14] = (mSeqNumber >> 8) & 0xff;
+            mAESInitVec[13] = (mSeqNumber >> 16) & 0xff;
+            mAESInitVec[12] = (mSeqNumber >> 24) & 0xff;
         }
-    } else {
-        memset(aes_ivec, 0, sizeof(aes_ivec));
-        aes_ivec[15] = mSeqNumber & 0xff;
-        aes_ivec[14] = (mSeqNumber >> 8) & 0xff;
-        aes_ivec[13] = (mSeqNumber >> 16) & 0xff;
-        aes_ivec[12] = (mSeqNumber >> 24) & 0xff;
     }
 
     AES_cbc_encrypt(
             buffer->data(), buffer->data(), buffer->size(),
-            &aes_key, aes_ivec, AES_DECRYPT);
+            &aes_key, mAESInitVec, AES_DECRYPT);
 
-    // hexdump(buffer->data(), buffer->size());
+    return OK;
+}
 
-    size_t n = buffer->size();
-    CHECK_GT(n, 0u);
-
-    size_t pad = buffer->data()[n - 1];
-
-    CHECK_GT(pad, 0u);
-    CHECK_LE(pad, 16u);
-    CHECK_GE((size_t)n, pad);
-    for (size_t i = 0; i < pad; ++i) {
-        CHECK_EQ((unsigned)buffer->data()[n - 1 - i], pad);
+status_t PlaylistFetcher::checkDecryptPadding(const sp<ABuffer> &buffer) {
+    status_t err;
+    AString method;
+    CHECK(buffer->meta()->findString("cipher-method", &method));
+    if (method == "NONE") {
+        return OK;
     }
 
-    n -= pad;
+    uint8_t padding = 0;
+    if (buffer->size() > 0) {
+        padding = buffer->data()[buffer->size() - 1];
+    }
 
-    buffer->setRange(buffer->offset(), n);
+    if (padding > 16) {
+        return ERROR_MALFORMED;
+    }
 
+    for (size_t i = buffer->size() - padding; i < padding; i++) {
+        if (buffer->data()[i] != padding) {
+            return ERROR_MALFORMED;
+        }
+    }
+
+    buffer->setRange(buffer->offset(), buffer->size() - padding);
     return OK;
 }
 
@@ -602,7 +622,7 @@
 
         if (mPlaylist->isComplete() || mPlaylist->isEvent()) {
             mSeqNumber = getSeqNumberForTime(mStartTimeUs);
-            ALOGV("Initial sequence number for time %lld is %ld from (%ld .. %ld)",
+            ALOGV("Initial sequence number for time %lld is %d from (%d .. %d)",
                     mStartTimeUs, mSeqNumber, firstSeqNumberInPlaylist,
                     lastSeqNumberInPlaylist);
         } else {
@@ -611,7 +631,7 @@
             if (mSeqNumber < firstSeqNumberInPlaylist) {
                 mSeqNumber = firstSeqNumberInPlaylist;
             }
-            ALOGV("Initial sequence number for live event %ld from (%ld .. %ld)",
+            ALOGV("Initial sequence number for live event %d from (%d .. %d)",
                     mSeqNumber, firstSeqNumberInPlaylist,
                     lastSeqNumberInPlaylist);
         }
@@ -635,7 +655,8 @@
                 if (delayUs > kMaxMonitorDelayUs) {
                     delayUs = kMaxMonitorDelayUs;
                 }
-                ALOGV("sequence number high: %ld from (%ld .. %ld), monitor in %lld (retry=%d)",
+                ALOGV("sequence number high: %d from (%d .. %d), "
+                      "monitor in %lld (retry=%d)",
                         mSeqNumber, firstSeqNumberInPlaylist,
                         lastSeqNumberInPlaylist, delayUs, mNumRetries);
                 postMonitorQueue(delayUs);
@@ -706,6 +727,9 @@
     CHECK(buffer != NULL);
 
     err = decryptBuffer(mSeqNumber - firstSeqNumberInPlaylist, buffer);
+    if (err == OK) {
+        err = checkDecryptPadding(buffer);
+    }
 
     if (err != OK) {
         ALOGE("decryptBuffer failed w/ error %d", err);
diff --git a/media/libstagefright/httplive/PlaylistFetcher.h b/media/libstagefright/httplive/PlaylistFetcher.h
index 78dea20..ac04a77 100644
--- a/media/libstagefright/httplive/PlaylistFetcher.h
+++ b/media/libstagefright/httplive/PlaylistFetcher.h
@@ -119,8 +119,23 @@
     uint64_t mFirstPTS;
     int64_t mAbsoluteTimeAnchorUs;
 
+    // Stores the initialization vector to decrypt the next block of cipher text, which can
+    // either be derived from the sequence number, read from the manifest, or copied from
+    // the last block of cipher text (cipher-block chaining).
+    unsigned char mAESInitVec[16];
+
+    // Set first to true if decrypting the first segment of a playlist segment. When
+    // first is true, reset the initialization vector based on the available
+    // information in the manifest; otherwise, use the initialization vector as
+    // updated by the last call to AES_cbc_encrypt.
+    //
+    // For the input to decrypt correctly, decryptBuffer must be called on
+    // consecutive byte ranges on block boundaries, e.g. 0..15, 16..47, 48..63,
+    // and so on.
     status_t decryptBuffer(
-            size_t playlistIndex, const sp<ABuffer> &buffer);
+            size_t playlistIndex, const sp<ABuffer> &buffer,
+            bool first = true);
+    status_t checkDecryptPadding(const sp<ABuffer> &buffer);
 
     void postMonitorQueue(int64_t delayUs = 0, int64_t minDelayUs = 0);
     void cancelMonitorQueue();
diff --git a/media/libstagefright/id3/Android.mk b/media/libstagefright/id3/Android.mk
index bf6f7bb..2194c38 100644
--- a/media/libstagefright/id3/Android.mk
+++ b/media/libstagefright/id3/Android.mk
@@ -4,6 +4,8 @@
 LOCAL_SRC_FILES := \
 	ID3.cpp
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_MODULE := libstagefright_id3
 
 include $(BUILD_STATIC_LIBRARY)
@@ -15,6 +17,8 @@
 LOCAL_SRC_FILES := \
 	testid3.cpp
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_SHARED_LIBRARIES := \
 	libstagefright libutils liblog libbinder libstagefright_foundation
 
diff --git a/media/libstagefright/id3/testid3.cpp b/media/libstagefright/id3/testid3.cpp
index bc4572c..b2f4188 100644
--- a/media/libstagefright/id3/testid3.cpp
+++ b/media/libstagefright/id3/testid3.cpp
@@ -33,7 +33,7 @@
     const uint8_t *data = (const uint8_t *)_data;
     size_t offset = 0;
     while (offset < size) {
-        printf("0x%04x  ", offset);
+        printf("0x%04zx  ", offset);
 
         size_t n = size - offset;
         if (n > 16) {
@@ -101,7 +101,7 @@
         const void *data = tag.getAlbumArt(&dataSize, &mime);
 
         if (data) {
-            printf("found album art: size=%d mime='%s'\n", dataSize,
+            printf("found album art: size=%zu mime='%s'\n", dataSize,
                    mime.string());
 
             hexdump(data, dataSize > 128 ? 128 : dataSize);
diff --git a/media/libstagefright/include/FragmentedMP4Parser.h b/media/libstagefright/include/FragmentedMP4Parser.h
deleted file mode 100644
index dbe02b8..0000000
--- a/media/libstagefright/include/FragmentedMP4Parser.h
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- * Copyright (C) 2012 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 PARSER_H_
-
-#define PARSER_H_
-
-#include <media/stagefright/foundation/AHandler.h>
-#include <media/stagefright/DataSource.h>
-#include <utils/Vector.h>
-
-namespace android {
-
-struct ABuffer;
-
-struct FragmentedMP4Parser : public AHandler {
-    struct Source : public RefBase {
-        Source() {}
-
-        virtual ssize_t readAt(off64_t offset, void *data, size_t size) = 0;
-        virtual bool isSeekable() = 0;
-
-        protected:
-        virtual ~Source() {}
-
-        private:
-        DISALLOW_EVIL_CONSTRUCTORS(Source);
-    };
-
-    FragmentedMP4Parser();
-
-    void start(const char *filename);
-    void start(const sp<Source> &source);
-    void start(sp<DataSource> &source);
-
-    sp<AMessage> getFormat(bool audio, bool synchronous = false);
-    status_t dequeueAccessUnit(bool audio, sp<ABuffer> *accessUnit, bool synchronous = false);
-    status_t seekTo(bool audio, int64_t timeUs);
-    bool isSeekable() const;
-
-    virtual void onMessageReceived(const sp<AMessage> &msg);
-
-protected:
-    virtual ~FragmentedMP4Parser();
-
-private:
-    enum {
-        kWhatStart,
-        kWhatProceed,
-        kWhatReadMore,
-        kWhatGetFormat,
-        kWhatDequeueAccessUnit,
-        kWhatSeekTo,
-    };
-
-    struct TrackFragment;
-    struct DynamicTrackFragment;
-    struct StaticTrackFragment;
-
-    struct DispatchEntry {
-        uint32_t mType;
-        uint32_t mParentType;
-        status_t (FragmentedMP4Parser::*mHandler)(uint32_t, size_t, uint64_t);
-    };
-
-    struct Container {
-        uint64_t mOffset;
-        uint64_t mBytesRemaining;
-        uint32_t mType;
-        bool mExtendsToEOF;
-    };
-
-    struct SampleDescription {
-        uint32_t mType;
-        uint16_t mDataRefIndex;
-
-        sp<AMessage> mFormat;
-    };
-
-    struct SampleInfo {
-        off64_t mOffset;
-        size_t mSize;
-        uint32_t mPresentationTime;
-        size_t mSampleDescIndex;
-        uint32_t mFlags;
-    };
-
-    struct MediaDataInfo {
-        sp<ABuffer> mBuffer;
-        off64_t mOffset;
-    };
-
-    struct SidxEntry {
-        size_t mSize;
-        uint32_t mDurationUs;
-    };
-
-    struct TrackInfo {
-        enum Flags {
-            kTrackEnabled     = 0x01,
-            kTrackInMovie     = 0x02,
-            kTrackInPreview   = 0x04,
-        };
-
-        uint32_t mTrackID;
-        uint32_t mFlags;
-        uint32_t mDuration;  // This is the duration in terms of movie timescale!
-        uint64_t mSidxDuration; // usec, from sidx box, which can use a different timescale
-
-        uint32_t mMediaTimeScale;
-
-        uint32_t mMediaHandlerType;
-        Vector<SampleDescription> mSampleDescs;
-
-        // from track extends:
-        uint32_t mDefaultSampleDescriptionIndex;
-        uint32_t mDefaultSampleDuration;
-        uint32_t mDefaultSampleSize;
-        uint32_t mDefaultSampleFlags;
-
-        uint32_t mDecodingTime;
-
-        Vector<SidxEntry> mSidx;
-        sp<StaticTrackFragment> mStaticFragment;
-        List<sp<TrackFragment> > mFragments;
-    };
-
-    struct TrackFragmentHeaderInfo {
-        enum Flags {
-            kBaseDataOffsetPresent         = 0x01,
-            kSampleDescriptionIndexPresent = 0x02,
-            kDefaultSampleDurationPresent  = 0x08,
-            kDefaultSampleSizePresent      = 0x10,
-            kDefaultSampleFlagsPresent     = 0x20,
-            kDurationIsEmpty               = 0x10000,
-        };
-
-        uint32_t mTrackID;
-        uint32_t mFlags;
-        uint64_t mBaseDataOffset;
-        uint32_t mSampleDescriptionIndex;
-        uint32_t mDefaultSampleDuration;
-        uint32_t mDefaultSampleSize;
-        uint32_t mDefaultSampleFlags;
-
-        uint64_t mDataOffset;
-    };
-
-    static const DispatchEntry kDispatchTable[];
-
-    sp<Source> mSource;
-    off_t mBufferPos;
-    bool mSuspended;
-    bool mDoneWithMoov;
-    off_t mFirstMoofOffset; // used as the starting point for offsets calculated from the sidx box
-    sp<ABuffer> mBuffer;
-    Vector<Container> mStack;
-    KeyedVector<uint32_t, TrackInfo> mTracks;  // TrackInfo by trackID
-    Vector<MediaDataInfo> mMediaData;
-
-    uint32_t mCurrentTrackID;
-
-    status_t mFinalResult;
-
-    TrackFragmentHeaderInfo mTrackFragmentHeaderInfo;
-
-    status_t onProceed();
-    status_t onDequeueAccessUnit(size_t trackIndex, sp<ABuffer> *accessUnit);
-    status_t onSeekTo(bool wantAudio, int64_t position);
-
-    void enter(off64_t offset, uint32_t type, uint64_t size);
-
-    uint16_t readU16(size_t offset);
-    uint32_t readU32(size_t offset);
-    uint64_t readU64(size_t offset);
-    void skip(off_t distance);
-    status_t need(size_t size);
-    bool fitsContainer(uint64_t size) const;
-
-    status_t parseTrackHeader(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseMediaHeader(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseMediaHandler(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseTrackExtends(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseTrackFragmentHeader(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseTrackFragmentRun(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseVisualSampleEntry(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseAudioSampleEntry(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseSampleSizes(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseCompactSampleSizes(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseSampleToChunk(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseChunkOffsets(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseChunkOffsets64(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseAVCCodecSpecificData(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseESDSCodecSpecificData(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseMediaData(
-            uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseSegmentIndex(
-            uint32_t type, size_t offset, uint64_t size);
-
-    TrackInfo *editTrack(uint32_t trackID, bool createIfNecessary = false);
-
-    ssize_t findTrack(bool wantAudio) const;
-
-    status_t makeAccessUnit(
-            TrackInfo *info,
-            const SampleInfo &sample,
-            const MediaDataInfo &mdatInfo,
-            sp<ABuffer> *accessUnit);
-
-    status_t getSample(
-            TrackInfo *info,
-            sp<TrackFragment> *fragment,
-            SampleInfo *sampleInfo);
-
-    static int CompareSampleLocation(
-        const SampleInfo &sample, const MediaDataInfo &mdatInfo);
-
-    void resumeIfNecessary();
-
-    void copyBuffer(
-            sp<ABuffer> *dst,
-            size_t offset, uint64_t size) const;
-
-    DISALLOW_EVIL_CONSTRUCTORS(FragmentedMP4Parser);
-};
-
-}  // namespace android
-
-#endif  // PARSER_H_
-
diff --git a/media/libstagefright/include/TimedEventQueue.h b/media/libstagefright/include/TimedEventQueue.h
index 3e84256..2963150 100644
--- a/media/libstagefright/include/TimedEventQueue.h
+++ b/media/libstagefright/include/TimedEventQueue.h
@@ -122,7 +122,7 @@
     };
 
     struct StopEvent : public TimedEventQueue::Event {
-        virtual void fire(TimedEventQueue *queue, int64_t now_us) {
+        virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) {
             queue->mStopped = true;
         }
     };
diff --git a/media/libstagefright/matroska/Android.mk b/media/libstagefright/matroska/Android.mk
index 2d8c1e1..446ff8c 100644
--- a/media/libstagefright/matroska/Android.mk
+++ b/media/libstagefright/matroska/Android.mk
@@ -8,7 +8,7 @@
         $(TOP)/external/libvpx/libwebm \
         $(TOP)/frameworks/native/include/media/openmax \
 
-LOCAL_CFLAGS += -Wno-multichar
+LOCAL_CFLAGS += -Wno-multichar -Werror
 
 LOCAL_MODULE:= libstagefright_matroska
 
diff --git a/media/libstagefright/matroska/MatroskaExtractor.cpp b/media/libstagefright/matroska/MatroskaExtractor.cpp
index dcb1cda..6f69d0b 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.cpp
+++ b/media/libstagefright/matroska/MatroskaExtractor.cpp
@@ -193,7 +193,7 @@
     clearPendingFrames();
 }
 
-status_t MatroskaSource::start(MetaData *params) {
+status_t MatroskaSource::start(MetaData * /* params */) {
     mBlockIter.reset();
 
     return OK;
@@ -410,7 +410,7 @@
             // Accept the first key frame
             *actualFrameTimeUs = (block()->GetTime(mCluster) + 500LL) / 1000LL;
             ALOGV("Requested seek point: %lld actual: %lld",
-                  seekTimeUs, actualFrameTimeUs);
+                  seekTimeUs, *actualFrameTimeUs);
             break;
         }
     }
diff --git a/media/libstagefright/mp4/FragmentedMP4Parser.cpp b/media/libstagefright/mp4/FragmentedMP4Parser.cpp
deleted file mode 100644
index 0102656..0000000
--- a/media/libstagefright/mp4/FragmentedMP4Parser.cpp
+++ /dev/null
@@ -1,1993 +0,0 @@
-/*
- * Copyright (C) 2012 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 "FragmentedMP4Parser"
-#include <utils/Log.h>
-
-#include "include/avc_utils.h"
-#include "include/ESDS.h"
-#include "include/FragmentedMP4Parser.h"
-#include "TrackFragment.h"
-
-
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/foundation/hexdump.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/Utils.h>
-
-
-namespace android {
-
-static const char *Fourcc2String(uint32_t fourcc) {
-    static char buffer[5];
-    buffer[4] = '\0';
-    buffer[0] = fourcc >> 24;
-    buffer[1] = (fourcc >> 16) & 0xff;
-    buffer[2] = (fourcc >> 8) & 0xff;
-    buffer[3] = fourcc & 0xff;
-
-    return buffer;
-}
-
-static const char *IndentString(size_t n) {
-    static const char kSpace[] = "                              ";
-    return kSpace + sizeof(kSpace) - 2 * n - 1;
-}
-
-// static
-const FragmentedMP4Parser::DispatchEntry FragmentedMP4Parser::kDispatchTable[] = {
-    { FOURCC('m', 'o', 'o', 'v'), 0, NULL },
-    { FOURCC('t', 'r', 'a', 'k'), FOURCC('m', 'o', 'o', 'v'), NULL },
-    { FOURCC('u', 'd', 't', 'a'), FOURCC('t', 'r', 'a', 'k'), NULL },
-    { FOURCC('u', 'd', 't', 'a'), FOURCC('m', 'o', 'o', 'v'), NULL },
-    { FOURCC('m', 'e', 't', 'a'), FOURCC('u', 'd', 't', 'a'), NULL },
-    { FOURCC('i', 'l', 's', 't'), FOURCC('m', 'e', 't', 'a'), NULL },
-
-    { FOURCC('t', 'k', 'h', 'd'), FOURCC('t', 'r', 'a', 'k'),
-        &FragmentedMP4Parser::parseTrackHeader
-    },
-
-    { FOURCC('m', 'v', 'e', 'x'), FOURCC('m', 'o', 'o', 'v'), NULL },
-
-    { FOURCC('t', 'r', 'e', 'x'), FOURCC('m', 'v', 'e', 'x'),
-        &FragmentedMP4Parser::parseTrackExtends
-    },
-
-    { FOURCC('e', 'd', 't', 's'), FOURCC('t', 'r', 'a', 'k'), NULL },
-    { FOURCC('m', 'd', 'i', 'a'), FOURCC('t', 'r', 'a', 'k'), NULL },
-
-    { FOURCC('m', 'd', 'h', 'd'), FOURCC('m', 'd', 'i', 'a'),
-        &FragmentedMP4Parser::parseMediaHeader
-    },
-
-    { FOURCC('h', 'd', 'l', 'r'), FOURCC('m', 'd', 'i', 'a'),
-        &FragmentedMP4Parser::parseMediaHandler
-    },
-
-    { FOURCC('m', 'i', 'n', 'f'), FOURCC('m', 'd', 'i', 'a'), NULL },
-    { FOURCC('d', 'i', 'n', 'f'), FOURCC('m', 'i', 'n', 'f'), NULL },
-    { FOURCC('s', 't', 'b', 'l'), FOURCC('m', 'i', 'n', 'f'), NULL },
-    { FOURCC('s', 't', 's', 'd'), FOURCC('s', 't', 'b', 'l'), NULL },
-
-    { FOURCC('s', 't', 's', 'z'), FOURCC('s', 't', 'b', 'l'),
-        &FragmentedMP4Parser::parseSampleSizes },
-
-    { FOURCC('s', 't', 'z', '2'), FOURCC('s', 't', 'b', 'l'),
-        &FragmentedMP4Parser::parseCompactSampleSizes },
-
-    { FOURCC('s', 't', 's', 'c'), FOURCC('s', 't', 'b', 'l'),
-        &FragmentedMP4Parser::parseSampleToChunk },
-
-    { FOURCC('s', 't', 'c', 'o'), FOURCC('s', 't', 'b', 'l'),
-        &FragmentedMP4Parser::parseChunkOffsets },
-
-    { FOURCC('c', 'o', '6', '4'), FOURCC('s', 't', 'b', 'l'),
-        &FragmentedMP4Parser::parseChunkOffsets64 },
-
-    { FOURCC('a', 'v', 'c', 'C'), FOURCC('a', 'v', 'c', '1'),
-        &FragmentedMP4Parser::parseAVCCodecSpecificData },
-
-    { FOURCC('e', 's', 'd', 's'), FOURCC('m', 'p', '4', 'a'),
-        &FragmentedMP4Parser::parseESDSCodecSpecificData },
-
-    { FOURCC('e', 's', 'd', 's'), FOURCC('m', 'p', '4', 'v'),
-        &FragmentedMP4Parser::parseESDSCodecSpecificData },
-
-    { FOURCC('m', 'd', 'a', 't'), 0, &FragmentedMP4Parser::parseMediaData },
-
-    { FOURCC('m', 'o', 'o', 'f'), 0, NULL },
-    { FOURCC('t', 'r', 'a', 'f'), FOURCC('m', 'o', 'o', 'f'), NULL },
-
-    { FOURCC('t', 'f', 'h', 'd'), FOURCC('t', 'r', 'a', 'f'),
-        &FragmentedMP4Parser::parseTrackFragmentHeader
-    },
-    { FOURCC('t', 'r', 'u', 'n'), FOURCC('t', 'r', 'a', 'f'),
-        &FragmentedMP4Parser::parseTrackFragmentRun
-    },
-
-    { FOURCC('m', 'f', 'r', 'a'), 0, NULL },
-
-    { FOURCC('s', 'i', 'd', 'x'), 0, &FragmentedMP4Parser::parseSegmentIndex },
-};
-
-struct FileSource : public FragmentedMP4Parser::Source {
-    FileSource(const char *filename)
-        : mFile(fopen(filename, "rb")) {
-            CHECK(mFile != NULL);
-        }
-
-    virtual ~FileSource() {
-        fclose(mFile);
-    }
-
-    virtual ssize_t readAt(off64_t offset, void *data, size_t size) {
-        fseek(mFile, offset, SEEK_SET);
-        return fread(data, 1, size, mFile);
-    }
-
-    virtual bool isSeekable() {
-        return true;
-    }
-
-    private:
-    FILE *mFile;
-
-    DISALLOW_EVIL_CONSTRUCTORS(FileSource);
-};
-
-struct ReadTracker : public RefBase {
-    ReadTracker(off64_t size) {
-        allocSize = 1 + size / 8192; // 1 bit per kilobyte
-        bitmap = (char*) calloc(1, allocSize);
-    }
-    virtual ~ReadTracker() {
-        dumpToLog();
-        free(bitmap);
-    }
-    void mark(off64_t offset, size_t size) {
-        int firstbit = offset / 1024;
-        int lastbit = (offset + size - 1) / 1024;
-        for (int i = firstbit; i <= lastbit; i++) {
-            bitmap[i/8] |= (0x80 >> (i & 7));
-        }
-    }
-
- private:
-    void dumpToLog() {
-        // 96 chars per line, each char represents one kilobyte, 1 kb per bit
-        int numlines = allocSize / 12;
-        char buf[97];
-        char *cur = bitmap;
-        for (int i = 0; i < numlines; i++ && cur) {
-            for (int j = 0; j < 12; j++) {
-                for (int k = 0; k < 8; k++) {
-                    buf[(j * 8) + k] = (*cur & (0x80 >> k)) ? 'X' : '.';
-                }
-                cur++;
-            }
-            buf[96] = '\0';
-            ALOGI("%5dk: %s", i * 96, buf);
-        }
-    }
-
-    size_t allocSize;
-    char *bitmap;
-};
-
-struct DataSourceSource : public FragmentedMP4Parser::Source {
-    DataSourceSource(sp<DataSource> &source)
-        : mDataSource(source) {
-            CHECK(mDataSource != NULL);
-#if 0
-            off64_t size;
-            if (source->getSize(&size) == OK) {
-                mReadTracker = new ReadTracker(size);
-            } else {
-                ALOGE("couldn't get data source size");
-            }
-#endif
-        }
-
-    virtual ssize_t readAt(off64_t offset, void *data, size_t size) {
-        if (mReadTracker != NULL) {
-            mReadTracker->mark(offset, size);
-        }
-        return mDataSource->readAt(offset, data, size);
-    }
-
-    virtual bool isSeekable() {
-        return true;
-    }
-
-    private:
-    sp<DataSource> mDataSource;
-    sp<ReadTracker> mReadTracker;
-
-    DISALLOW_EVIL_CONSTRUCTORS(DataSourceSource);
-};
-
-FragmentedMP4Parser::FragmentedMP4Parser()
-    : mBufferPos(0),
-      mSuspended(false),
-      mDoneWithMoov(false),
-      mFirstMoofOffset(0),
-      mFinalResult(OK) {
-}
-
-FragmentedMP4Parser::~FragmentedMP4Parser() {
-}
-
-void FragmentedMP4Parser::start(const char *filename) {
-    sp<AMessage> msg = new AMessage(kWhatStart, id());
-    msg->setObject("source", new FileSource(filename));
-    msg->post();
-    ALOGV("Parser::start(%s)", filename);
-}
-
-void FragmentedMP4Parser::start(const sp<Source> &source) {
-    sp<AMessage> msg = new AMessage(kWhatStart, id());
-    msg->setObject("source", source);
-    msg->post();
-    ALOGV("Parser::start(Source)");
-}
-
-void FragmentedMP4Parser::start(sp<DataSource> &source) {
-    sp<AMessage> msg = new AMessage(kWhatStart, id());
-    msg->setObject("source", new DataSourceSource(source));
-    msg->post();
-    ALOGV("Parser::start(DataSource)");
-}
-
-sp<AMessage> FragmentedMP4Parser::getFormat(bool audio, bool synchronous) {
-
-    while (true) {
-        bool moovDone = mDoneWithMoov;
-        sp<AMessage> msg = new AMessage(kWhatGetFormat, id());
-        msg->setInt32("audio", audio);
-
-        sp<AMessage> response;
-        status_t err = msg->postAndAwaitResponse(&response);
-
-        if (err != OK) {
-            ALOGV("getFormat post failed: %d", err);
-            return NULL;
-        }
-
-        if (response->findInt32("err", &err) && err != OK) {
-            if (synchronous && err == -EWOULDBLOCK && !moovDone) {
-                resumeIfNecessary();
-                ALOGV("@getFormat parser not ready yet, retrying");
-                usleep(10000);
-                continue;
-            }
-            ALOGV("getFormat failed: %d", err);
-            return NULL;
-        }
-
-        sp<AMessage> format;
-        CHECK(response->findMessage("format", &format));
-
-        ALOGV("returning format %s", format->debugString().c_str());
-        return format;
-    }
-}
-
-status_t FragmentedMP4Parser::seekTo(bool wantAudio, int64_t timeUs) {
-    sp<AMessage> msg = new AMessage(kWhatSeekTo, id());
-    msg->setInt32("audio", wantAudio);
-    msg->setInt64("position", timeUs);
-
-    sp<AMessage> response;
-    status_t err = msg->postAndAwaitResponse(&response);
-    return err;
-}
-
-bool FragmentedMP4Parser::isSeekable() const {
-    while (mFirstMoofOffset == 0 && mFinalResult == OK) {
-        usleep(10000);
-    }
-    bool seekable = mSource->isSeekable();
-    for (size_t i = 0; seekable && i < mTracks.size(); i++) {
-        const TrackInfo *info = &mTracks.valueAt(i);
-        seekable &= !info->mSidx.empty();
-    }
-    return seekable;
-}
-
-status_t FragmentedMP4Parser::onSeekTo(bool wantAudio, int64_t position) {
-    status_t err = -EINVAL;
-    ssize_t trackIndex = findTrack(wantAudio);
-    if (trackIndex < 0) {
-        err = trackIndex;
-    } else {
-        TrackInfo *info = &mTracks.editValueAt(trackIndex);
-
-        int numSidxEntries = info->mSidx.size();
-        int64_t totalTime = 0;
-        off_t totalOffset = mFirstMoofOffset;
-        for (int i = 0; i < numSidxEntries; i++) {
-            const SidxEntry *se = &info->mSidx[i];
-            if (totalTime + se->mDurationUs > position) {
-                mBuffer->setRange(0,0);
-                mBufferPos = totalOffset;
-                if (mFinalResult == ERROR_END_OF_STREAM) {
-                    mFinalResult = OK;
-                    mSuspended = true; // force resume
-                    resumeIfNecessary();
-                }
-                info->mFragments.clear();
-                info->mDecodingTime = totalTime * info->mMediaTimeScale / 1000000ll;
-                return OK;
-            }
-            totalTime += se->mDurationUs;
-            totalOffset += se->mSize;
-        }
-    }
-    ALOGV("seekTo out of range");
-    return err;
-}
-
-status_t FragmentedMP4Parser::dequeueAccessUnit(bool audio, sp<ABuffer> *accessUnit,
-                                                bool synchronous) {
-
-    while (true) {
-        sp<AMessage> msg = new AMessage(kWhatDequeueAccessUnit, id());
-        msg->setInt32("audio", audio);
-
-        sp<AMessage> response;
-        status_t err = msg->postAndAwaitResponse(&response);
-
-        if (err != OK) {
-            ALOGV("dequeue fail 1: %d", err);
-            return err;
-        }
-
-        if (response->findInt32("err", &err) && err != OK) {
-            if (synchronous && err == -EWOULDBLOCK) {
-                resumeIfNecessary();
-                ALOGV("Parser not ready yet, retrying");
-                usleep(10000);
-                continue;
-            }
-            ALOGV("dequeue fail 2: %d, %d", err, synchronous);
-            return err;
-        }
-
-        CHECK(response->findBuffer("accessUnit", accessUnit));
-
-        return OK;
-    }
-}
-
-ssize_t FragmentedMP4Parser::findTrack(bool wantAudio) const {
-    for (size_t i = 0; i < mTracks.size(); ++i) {
-        const TrackInfo *info = &mTracks.valueAt(i);
-
-        bool isAudio =
-            info->mMediaHandlerType == FOURCC('s', 'o', 'u', 'n');
-
-        bool isVideo =
-            info->mMediaHandlerType == FOURCC('v', 'i', 'd', 'e');
-
-        if ((wantAudio && isAudio) || (!wantAudio && !isAudio)) {
-            if (info->mSampleDescs.empty()) {
-                break;
-            }
-
-            return i;
-        }
-    }
-
-    return -EWOULDBLOCK;
-}
-
-void FragmentedMP4Parser::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatStart:
-        {
-            sp<RefBase> obj;
-            CHECK(msg->findObject("source", &obj));
-
-            mSource = static_cast<Source *>(obj.get());
-
-            mBuffer = new ABuffer(512 * 1024);
-            mBuffer->setRange(0, 0);
-
-            enter(0ll, 0, 0);
-
-            (new AMessage(kWhatProceed, id()))->post();
-            break;
-        }
-
-        case kWhatProceed:
-        {
-            CHECK(!mSuspended);
-
-            status_t err = onProceed();
-
-            if (err == OK) {
-                if (!mSuspended) {
-                    msg->post();
-                }
-            } else if (err != -EAGAIN) {
-                ALOGE("onProceed returned error %d", err);
-            }
-
-            break;
-        }
-
-        case kWhatReadMore:
-        {
-            size_t needed;
-            CHECK(msg->findSize("needed", &needed));
-
-            memmove(mBuffer->base(), mBuffer->data(), mBuffer->size());
-            mBufferPos += mBuffer->offset();
-            mBuffer->setRange(0, mBuffer->size());
-
-            size_t maxBytesToRead = mBuffer->capacity() - mBuffer->size();
-
-            if (maxBytesToRead < needed) {
-                ALOGV("resizing buffer.");
-
-                sp<ABuffer> newBuffer =
-                    new ABuffer((mBuffer->size() + needed + 1023) & ~1023);
-                memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
-                newBuffer->setRange(0, mBuffer->size());
-
-                mBuffer = newBuffer;
-                maxBytesToRead = mBuffer->capacity() - mBuffer->size();
-            }
-
-            CHECK_GE(maxBytesToRead, needed);
-
-            ssize_t n = mSource->readAt(
-                    mBufferPos + mBuffer->size(),
-                    mBuffer->data() + mBuffer->size(), needed);
-
-            if (n < (ssize_t)needed) {
-                ALOGV("Reached EOF when reading %d @ %d + %d", needed, mBufferPos, mBuffer->size());
-                if (n < 0) {
-                    mFinalResult = n;
-                } else if (n == 0) {
-                    mFinalResult = ERROR_END_OF_STREAM;
-                } else {
-                    mFinalResult = ERROR_IO;
-                }
-            } else {
-                mBuffer->setRange(0, mBuffer->size() + n);
-                (new AMessage(kWhatProceed, id()))->post();
-            }
-
-            break;
-        }
-
-        case kWhatGetFormat:
-        {
-            int32_t wantAudio;
-            CHECK(msg->findInt32("audio", &wantAudio));
-
-            status_t err = -EWOULDBLOCK;
-            sp<AMessage> response = new AMessage;
-
-            ssize_t trackIndex = findTrack(wantAudio);
-
-            if (trackIndex < 0) {
-                err = trackIndex;
-            } else {
-                TrackInfo *info = &mTracks.editValueAt(trackIndex);
-
-                sp<AMessage> format = info->mSampleDescs.itemAt(0).mFormat;
-                if (info->mSidxDuration) {
-                    format->setInt64("durationUs", info->mSidxDuration);
-                } else {
-                    // this is probably going to be zero. Oh well...
-                    format->setInt64("durationUs",
-                                     1000000ll * info->mDuration / info->mMediaTimeScale);
-                }
-                response->setMessage(
-                        "format", format);
-
-                err = OK;
-            }
-
-            response->setInt32("err", err);
-
-            uint32_t replyID;
-            CHECK(msg->senderAwaitsResponse(&replyID));
-
-            response->postReply(replyID);
-            break;
-        }
-
-        case kWhatDequeueAccessUnit:
-        {
-            int32_t wantAudio;
-            CHECK(msg->findInt32("audio", &wantAudio));
-
-            status_t err = -EWOULDBLOCK;
-            sp<AMessage> response = new AMessage;
-
-            ssize_t trackIndex = findTrack(wantAudio);
-
-            if (trackIndex < 0) {
-                err = trackIndex;
-            } else {
-                sp<ABuffer> accessUnit;
-                err = onDequeueAccessUnit(trackIndex, &accessUnit);
-
-                if (err == OK) {
-                    response->setBuffer("accessUnit", accessUnit);
-                }
-            }
-
-            response->setInt32("err", err);
-
-            uint32_t replyID;
-            CHECK(msg->senderAwaitsResponse(&replyID));
-
-            response->postReply(replyID);
-            break;
-        }
-
-        case kWhatSeekTo:
-        {
-            ALOGV("kWhatSeekTo");
-            int32_t wantAudio;
-            CHECK(msg->findInt32("audio", &wantAudio));
-            int64_t position;
-            CHECK(msg->findInt64("position", &position));
-
-            status_t err = -EWOULDBLOCK;
-            sp<AMessage> response = new AMessage;
-
-            ssize_t trackIndex = findTrack(wantAudio);
-
-            if (trackIndex < 0) {
-                err = trackIndex;
-            } else {
-                err = onSeekTo(wantAudio, position);
-            }
-            response->setInt32("err", err);
-            uint32_t replyID;
-            CHECK(msg->senderAwaitsResponse(&replyID));
-            response->postReply(replyID);
-            break;
-        }
-        default:
-            TRESPASS();
-    }
-}
-
-status_t FragmentedMP4Parser::onProceed() {
-    status_t err;
-
-    if ((err = need(8)) != OK) {
-        return err;
-    }
-
-    uint64_t size = readU32(0);
-    uint32_t type = readU32(4);
-
-    size_t offset = 8;
-
-    if (size == 1) {
-        if ((err = need(16)) != OK) {
-            return err;
-        }
-
-        size = readU64(offset);
-        offset += 8;
-    }
-
-    uint8_t userType[16];
-
-    if (type == FOURCC('u', 'u', 'i', 'd')) {
-        if ((err = need(offset + 16)) != OK) {
-            return err;
-        }
-
-        memcpy(userType, mBuffer->data() + offset, 16);
-        offset += 16;
-    }
-
-    CHECK(!mStack.isEmpty());
-    uint32_t ptype = mStack.itemAt(mStack.size() - 1).mType;
-
-    static const size_t kNumDispatchers =
-        sizeof(kDispatchTable) / sizeof(kDispatchTable[0]);
-
-    size_t i;
-    for (i = 0; i < kNumDispatchers; ++i) {
-        if (kDispatchTable[i].mType == type
-                && kDispatchTable[i].mParentType == ptype) {
-            break;
-        }
-    }
-
-    // SampleEntry boxes are container boxes that start with a variable
-    // amount of data depending on the media handler type.
-    // We don't look inside 'hint' type SampleEntry boxes.
-
-    bool isSampleEntryBox =
-        (ptype == FOURCC('s', 't', 's', 'd'))
-        && editTrack(mCurrentTrackID)->mMediaHandlerType
-        != FOURCC('h', 'i', 'n', 't');
-
-    if ((i < kNumDispatchers && kDispatchTable[i].mHandler == 0)
-            || isSampleEntryBox || ptype == FOURCC('i', 'l', 's', 't')) {
-        // This is a container box.
-        if (type == FOURCC('m', 'o', 'o', 'f')) {
-            if (mFirstMoofOffset == 0) {
-                ALOGV("first moof @ %08x", mBufferPos + offset);
-                mFirstMoofOffset = mBufferPos + offset - 8; // point at the size
-            }
-        }
-        if (type == FOURCC('m', 'e', 't', 'a')) {
-            if ((err = need(offset + 4)) < OK) {
-                return err;
-            }
-
-            if (readU32(offset) != 0) {
-                return -EINVAL;
-            }
-
-            offset += 4;
-        } else if (type == FOURCC('s', 't', 's', 'd')) {
-            if ((err = need(offset + 8)) < OK) {
-                return err;
-            }
-
-            if (readU32(offset) != 0) {
-                return -EINVAL;
-            }
-
-            if (readU32(offset + 4) == 0) {
-                // We need at least some entries.
-                return -EINVAL;
-            }
-
-            offset += 8;
-        } else if (isSampleEntryBox) {
-            size_t headerSize;
-
-            switch (editTrack(mCurrentTrackID)->mMediaHandlerType) {
-                case FOURCC('v', 'i', 'd', 'e'):
-                {
-                    // 8 bytes SampleEntry + 70 bytes VisualSampleEntry
-                    headerSize = 78;
-                    break;
-                }
-
-                case FOURCC('s', 'o', 'u', 'n'):
-                {
-                    // 8 bytes SampleEntry + 20 bytes AudioSampleEntry
-                    headerSize = 28;
-                    break;
-                }
-
-                case FOURCC('m', 'e', 't', 'a'):
-                {
-                    headerSize = 8;  // 8 bytes SampleEntry
-                    break;
-                }
-
-                default:
-                    TRESPASS();
-            }
-
-            if (offset + headerSize > size) {
-                return -EINVAL;
-            }
-
-            if ((err = need(offset + headerSize)) != OK) {
-                return err;
-            }
-
-            switch (editTrack(mCurrentTrackID)->mMediaHandlerType) {
-                case FOURCC('v', 'i', 'd', 'e'):
-                {
-                    err = parseVisualSampleEntry(
-                            type, offset, offset + headerSize);
-                    break;
-                }
-
-                case FOURCC('s', 'o', 'u', 'n'):
-                {
-                    err = parseAudioSampleEntry(
-                            type, offset, offset + headerSize);
-                    break;
-                }
-
-                case FOURCC('m', 'e', 't', 'a'):
-                {
-                    err = OK;
-                    break;
-                }
-
-                default:
-                    TRESPASS();
-            }
-
-            if (err != OK) {
-                return err;
-            }
-
-            offset += headerSize;
-        }
-
-        skip(offset);
-
-        ALOGV("%sentering box of type '%s'",
-                IndentString(mStack.size()), Fourcc2String(type));
-
-        enter(mBufferPos - offset, type, size - offset);
-    } else {
-        if (!fitsContainer(size)) {
-            return -EINVAL;
-        }
-
-        if (i < kNumDispatchers && kDispatchTable[i].mHandler != 0) {
-            // We have a handler for this box type.
-
-            if ((err = need(size)) != OK) {
-                return err;
-            }
-
-            ALOGV("%sparsing box of type '%s'",
-                    IndentString(mStack.size()), Fourcc2String(type));
-
-            if ((err = (this->*kDispatchTable[i].mHandler)(
-                            type, offset, size)) != OK) {
-                return err;
-            }
-        } else {
-            // Unknown box type
-
-            ALOGV("%sskipping box of type '%s', size %llu",
-                    IndentString(mStack.size()),
-                    Fourcc2String(type), size);
-
-        }
-
-        skip(size);
-    }
-
-    return OK;
-}
-
-// static
-int FragmentedMP4Parser::CompareSampleLocation(
-        const SampleInfo &sample, const MediaDataInfo &mdatInfo) {
-    if (sample.mOffset + sample.mSize < mdatInfo.mOffset) {
-        return -1;
-    }
-
-    if (sample.mOffset >= mdatInfo.mOffset + mdatInfo.mBuffer->size()) {
-        return 1;
-    }
-
-    // Otherwise make sure the sample is completely contained within this
-    // media data block.
-
-    CHECK_GE(sample.mOffset, mdatInfo.mOffset);
-
-    CHECK_LE(sample.mOffset + sample.mSize,
-             mdatInfo.mOffset + mdatInfo.mBuffer->size());
-
-    return 0;
-}
-
-void FragmentedMP4Parser::resumeIfNecessary() {
-    if (!mSuspended) {
-        return;
-    }
-
-    ALOGV("resuming.");
-
-    mSuspended = false;
-    (new AMessage(kWhatProceed, id()))->post();
-}
-
-status_t FragmentedMP4Parser::getSample(
-        TrackInfo *info, sp<TrackFragment> *fragment, SampleInfo *sampleInfo) {
-    for (;;) {
-        if (info->mFragments.empty()) {
-            if (mFinalResult != OK) {
-                return mFinalResult;
-            }
-
-            resumeIfNecessary();
-            return -EWOULDBLOCK;
-        }
-
-        *fragment = *info->mFragments.begin();
-
-        status_t err = (*fragment)->getSample(sampleInfo);
-
-        if (err == OK) {
-            return OK;
-        } else if (err != ERROR_END_OF_STREAM) {
-            return err;
-        }
-
-        // Really, end of this fragment...
-
-        info->mFragments.erase(info->mFragments.begin());
-    }
-}
-
-status_t FragmentedMP4Parser::onDequeueAccessUnit(
-        size_t trackIndex, sp<ABuffer> *accessUnit) {
-    TrackInfo *info = &mTracks.editValueAt(trackIndex);
-
-    sp<TrackFragment> fragment;
-    SampleInfo sampleInfo;
-    status_t err = getSample(info, &fragment, &sampleInfo);
-
-    if (err == -EWOULDBLOCK) {
-        resumeIfNecessary();
-        return err;
-    } else if (err != OK) {
-        return err;
-    }
-
-    err = -EWOULDBLOCK;
-
-    bool checkDroppable = false;
-
-    for (size_t i = 0; i < mMediaData.size(); ++i) {
-        const MediaDataInfo &mdatInfo = mMediaData.itemAt(i);
-
-        int cmp = CompareSampleLocation(sampleInfo, mdatInfo);
-
-        if (cmp < 0 && !mSource->isSeekable()) {
-            return -EPIPE;
-        } else if (cmp == 0) {
-            if (i > 0) {
-                checkDroppable = true;
-            }
-
-            err = makeAccessUnit(info, sampleInfo, mdatInfo, accessUnit);
-            break;
-        }
-    }
-
-    if (err != OK) {
-        return err;
-    }
-
-    fragment->advance();
-
-    if (!mMediaData.empty() && checkDroppable) {
-        size_t numDroppable = 0;
-        bool done = false;
-
-        // XXX FIXME: if one of the tracks is not advanced (e.g. if you play an audio+video
-        // file with sf2), then mMediaData will not be pruned and keeps growing
-        for (size_t i = 0; !done && i < mMediaData.size(); ++i) {
-            const MediaDataInfo &mdatInfo = mMediaData.itemAt(i);
-
-            for (size_t j = 0; j < mTracks.size(); ++j) {
-                TrackInfo *info = &mTracks.editValueAt(j);
-
-                sp<TrackFragment> fragment;
-                SampleInfo sampleInfo;
-                err = getSample(info, &fragment, &sampleInfo);
-
-                if (err != OK) {
-                    done = true;
-                    break;
-                }
-
-                int cmp = CompareSampleLocation(sampleInfo, mdatInfo);
-
-                if (cmp <= 0) {
-                    done = true;
-                    break;
-                }
-            }
-
-            if (!done) {
-                ++numDroppable;
-            }
-        }
-
-        if (numDroppable > 0) {
-            mMediaData.removeItemsAt(0, numDroppable);
-
-            if (mMediaData.size() < 5) {
-                resumeIfNecessary();
-            }
-        }
-    }
-
-    return err;
-}
-
-static size_t parseNALSize(size_t nalLengthSize, const uint8_t *data) {
-    switch (nalLengthSize) {
-        case 1:
-            return *data;
-        case 2:
-            return U16_AT(data);
-        case 3:
-            return ((size_t)data[0] << 16) | U16_AT(&data[1]);
-        case 4:
-            return U32_AT(data);
-    }
-
-    // This cannot happen, mNALLengthSize springs to life by adding 1 to
-    // a 2-bit integer.
-    TRESPASS();
-
-    return 0;
-}
-
-status_t FragmentedMP4Parser::makeAccessUnit(
-        TrackInfo *info,
-        const SampleInfo &sample,
-        const MediaDataInfo &mdatInfo,
-        sp<ABuffer> *accessUnit) {
-    if (sample.mSampleDescIndex < 1
-            || sample.mSampleDescIndex > info->mSampleDescs.size()) {
-        return ERROR_MALFORMED;
-    }
-
-    int64_t presentationTimeUs =
-        1000000ll * sample.mPresentationTime / info->mMediaTimeScale;
-
-    const SampleDescription &sampleDesc =
-        info->mSampleDescs.itemAt(sample.mSampleDescIndex - 1);
-
-    size_t nalLengthSize;
-    if (!sampleDesc.mFormat->findSize("nal-length-size", &nalLengthSize)) {
-        *accessUnit = new ABuffer(sample.mSize);
-
-        memcpy((*accessUnit)->data(),
-               mdatInfo.mBuffer->data() + (sample.mOffset - mdatInfo.mOffset),
-               sample.mSize);
-
-        (*accessUnit)->meta()->setInt64("timeUs", presentationTimeUs);
-        if (IsIDR(*accessUnit)) {
-            (*accessUnit)->meta()->setInt32("is-sync-frame", 1);
-        }
-
-        return OK;
-    }
-
-    const uint8_t *srcPtr =
-        mdatInfo.mBuffer->data() + (sample.mOffset - mdatInfo.mOffset);
-
-    for (int i = 0; i < 2 ; ++i) {
-        size_t srcOffset = 0;
-        size_t dstOffset = 0;
-
-        while (srcOffset < sample.mSize) {
-            if (srcOffset + nalLengthSize > sample.mSize) {
-                return ERROR_MALFORMED;
-            }
-
-            size_t nalSize = parseNALSize(nalLengthSize, &srcPtr[srcOffset]);
-            srcOffset += nalLengthSize;
-
-            if (srcOffset + nalSize > sample.mSize) {
-                return ERROR_MALFORMED;
-            }
-
-            if (i == 1) {
-                memcpy((*accessUnit)->data() + dstOffset,
-                       "\x00\x00\x00\x01",
-                       4);
-
-                memcpy((*accessUnit)->data() + dstOffset + 4,
-                       srcPtr + srcOffset,
-                       nalSize);
-            }
-
-            srcOffset += nalSize;
-            dstOffset += nalSize + 4;
-        }
-
-        if (i == 0) {
-            (*accessUnit) = new ABuffer(dstOffset);
-            (*accessUnit)->meta()->setInt64(
-                    "timeUs", presentationTimeUs);
-        }
-    }
-    if (IsIDR(*accessUnit)) {
-        (*accessUnit)->meta()->setInt32("is-sync-frame", 1);
-    }
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::need(size_t size) {
-    if (!fitsContainer(size)) {
-        return -EINVAL;
-    }
-
-    if (size <= mBuffer->size()) {
-        return OK;
-    }
-
-    sp<AMessage> msg = new AMessage(kWhatReadMore, id());
-    msg->setSize("needed", size - mBuffer->size());
-    msg->post();
-
-    // ALOGV("need(%d) returning -EAGAIN, only have %d", size, mBuffer->size());
-
-    return -EAGAIN;
-}
-
-void FragmentedMP4Parser::enter(off64_t offset, uint32_t type, uint64_t size) {
-    Container container;
-    container.mOffset = offset;
-    container.mType = type;
-    container.mExtendsToEOF = (size == 0);
-    container.mBytesRemaining = size;
-
-    mStack.push(container);
-}
-
-bool FragmentedMP4Parser::fitsContainer(uint64_t size) const {
-    CHECK(!mStack.isEmpty());
-    const Container &container = mStack.itemAt(mStack.size() - 1);
-
-    return container.mExtendsToEOF || size <= container.mBytesRemaining;
-}
-
-uint16_t FragmentedMP4Parser::readU16(size_t offset) {
-    CHECK_LE(offset + 2, mBuffer->size());
-
-    const uint8_t *ptr = mBuffer->data() + offset;
-    return (ptr[0] << 8) | ptr[1];
-}
-
-uint32_t FragmentedMP4Parser::readU32(size_t offset) {
-    CHECK_LE(offset + 4, mBuffer->size());
-
-    const uint8_t *ptr = mBuffer->data() + offset;
-    return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
-}
-
-uint64_t FragmentedMP4Parser::readU64(size_t offset) {
-    return (((uint64_t)readU32(offset)) << 32) | readU32(offset + 4);
-}
-
-void FragmentedMP4Parser::skip(off_t distance) {
-    CHECK(!mStack.isEmpty());
-    for (size_t i = mStack.size(); i-- > 0;) {
-        Container *container = &mStack.editItemAt(i);
-        if (!container->mExtendsToEOF) {
-            CHECK_LE(distance, (off_t)container->mBytesRemaining);
-
-            container->mBytesRemaining -= distance;
-
-            if (container->mBytesRemaining == 0) {
-                ALOGV("%sleaving box of type '%s'",
-                        IndentString(mStack.size() - 1),
-                        Fourcc2String(container->mType));
-
-#if 0
-                if (container->mType == FOURCC('s', 't', 's', 'd')) {
-                    TrackInfo *trackInfo = editTrack(mCurrentTrackID);
-                    for (size_t i = 0;
-                            i < trackInfo->mSampleDescs.size(); ++i) {
-                        ALOGI("format #%d: %s",
-                              i,
-                              trackInfo->mSampleDescs.itemAt(i)
-                                .mFormat->debugString().c_str());
-                    }
-                }
-#endif
-
-                if (container->mType == FOURCC('s', 't', 'b', 'l')) {
-                    TrackInfo *trackInfo = editTrack(mCurrentTrackID);
-
-                    trackInfo->mStaticFragment->signalCompletion();
-
-                    CHECK(trackInfo->mFragments.empty());
-                    trackInfo->mFragments.push_back(trackInfo->mStaticFragment);
-                    trackInfo->mStaticFragment.clear();
-                } else if (container->mType == FOURCC('t', 'r', 'a', 'f')) {
-                    TrackInfo *trackInfo =
-                        editTrack(mTrackFragmentHeaderInfo.mTrackID);
-
-                    const sp<TrackFragment> &fragment =
-                        *--trackInfo->mFragments.end();
-
-                    static_cast<DynamicTrackFragment *>(
-                            fragment.get())->signalCompletion();
-                } else if (container->mType == FOURCC('m', 'o', 'o', 'v')) {
-                    mDoneWithMoov = true;
-                }
-
-                container = NULL;
-                mStack.removeItemsAt(i);
-            }
-        }
-    }
-
-    if (distance < (off_t)mBuffer->size()) {
-        mBuffer->setRange(mBuffer->offset() + distance, mBuffer->size() - distance);
-        mBufferPos += distance;
-        return;
-    }
-
-    mBuffer->setRange(0, 0);
-    mBufferPos += distance;
-}
-
-status_t FragmentedMP4Parser::parseTrackHeader(
-        uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 4 > size) {
-        return -EINVAL;
-    }
-
-    uint32_t flags = readU32(offset);
-
-    uint32_t version = flags >> 24;
-    flags &= 0xffffff;
-
-    uint32_t trackID;
-    uint64_t duration;
-
-    if (version == 1) {
-        if (offset + 36 > size) {
-            return -EINVAL;
-        }
-
-        trackID = readU32(offset + 20);
-        duration = readU64(offset + 28);
-
-        offset += 36;
-    } else if (version == 0) {
-        if (offset + 24 > size) {
-            return -EINVAL;
-        }
-
-        trackID = readU32(offset + 12);
-        duration = readU32(offset + 20);
-
-        offset += 24;
-    } else {
-        return -EINVAL;
-    }
-
-    TrackInfo *info = editTrack(trackID, true /* createIfNecessary */);
-    info->mFlags = flags;
-    info->mDuration = duration;
-    if (info->mDuration == 0xffffffff) {
-        // ffmpeg sets this to -1, which is incorrect.
-        info->mDuration = 0;
-    }
-
-    info->mStaticFragment = new StaticTrackFragment;
-
-    mCurrentTrackID = trackID;
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseMediaHeader(
-        uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 4 > size) {
-        return -EINVAL;
-    }
-
-    uint32_t versionAndFlags = readU32(offset);
-
-    if (versionAndFlags & 0xffffff) {
-        return ERROR_MALFORMED;
-    }
-
-    uint32_t version = versionAndFlags >> 24;
-
-    TrackInfo *info = editTrack(mCurrentTrackID);
-
-    if (version == 1) {
-        if (offset + 4 + 32 > size) {
-            return -EINVAL;
-        }
-        info->mMediaTimeScale = U32_AT(mBuffer->data() + offset + 20);
-    } else if (version == 0) {
-        if (offset + 4 + 20 > size) {
-            return -EINVAL;
-        }
-        info->mMediaTimeScale = U32_AT(mBuffer->data() + offset + 12);
-    } else {
-        return ERROR_MALFORMED;
-    }
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseMediaHandler(
-        uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 12 > size) {
-        return -EINVAL;
-    }
-
-    if (readU32(offset) != 0) {
-        return -EINVAL;
-    }
-
-    uint32_t handlerType = readU32(offset + 8);
-
-    switch (handlerType) {
-        case FOURCC('v', 'i', 'd', 'e'):
-        case FOURCC('s', 'o', 'u', 'n'):
-        case FOURCC('h', 'i', 'n', 't'):
-        case FOURCC('m', 'e', 't', 'a'):
-            break;
-
-        default:
-            return -EINVAL;
-    }
-
-    editTrack(mCurrentTrackID)->mMediaHandlerType = handlerType;
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseVisualSampleEntry(
-        uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 78 > size) {
-        return -EINVAL;
-    }
-
-    TrackInfo *trackInfo = editTrack(mCurrentTrackID);
-
-    trackInfo->mSampleDescs.push();
-    SampleDescription *sampleDesc =
-        &trackInfo->mSampleDescs.editItemAt(
-                trackInfo->mSampleDescs.size() - 1);
-
-    sampleDesc->mType = type;
-    sampleDesc->mDataRefIndex = readU16(offset + 6);
-
-    sp<AMessage> format = new AMessage;
-
-    switch (type) {
-        case FOURCC('a', 'v', 'c', '1'):
-            format->setString("mime", MEDIA_MIMETYPE_VIDEO_AVC);
-            break;
-        case FOURCC('m', 'p', '4', 'v'):
-            format->setString("mime", MEDIA_MIMETYPE_VIDEO_MPEG4);
-            break;
-        case FOURCC('s', '2', '6', '3'):
-        case FOURCC('h', '2', '6', '3'):
-        case FOURCC('H', '2', '6', '3'):
-            format->setString("mime", MEDIA_MIMETYPE_VIDEO_H263);
-            break;
-        default:
-            format->setString("mime", "application/octet-stream");
-            break;
-    }
-
-    format->setInt32("width", readU16(offset + 8 + 16));
-    format->setInt32("height", readU16(offset + 8 + 18));
-
-    sampleDesc->mFormat = format;
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseAudioSampleEntry(
-        uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 28 > size) {
-        return -EINVAL;
-    }
-
-    TrackInfo *trackInfo = editTrack(mCurrentTrackID);
-
-    trackInfo->mSampleDescs.push();
-    SampleDescription *sampleDesc =
-        &trackInfo->mSampleDescs.editItemAt(
-                trackInfo->mSampleDescs.size() - 1);
-
-    sampleDesc->mType = type;
-    sampleDesc->mDataRefIndex = readU16(offset + 6);
-
-    sp<AMessage> format = new AMessage;
-
-    format->setInt32("channel-count", readU16(offset + 8 + 8));
-    format->setInt32("sample-size", readU16(offset + 8 + 10));
-    format->setInt32("sample-rate", readU32(offset + 8 + 16) / 65536.0f);
-
-    switch (type) {
-        case FOURCC('m', 'p', '4', 'a'):
-            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AAC);
-            break;
-
-        case FOURCC('s', 'a', 'm', 'r'):
-            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_NB);
-            format->setInt32("channel-count", 1);
-            format->setInt32("sample-rate", 8000);
-            break;
-
-        case FOURCC('s', 'a', 'w', 'b'):
-            format->setString("mime", MEDIA_MIMETYPE_AUDIO_AMR_WB);
-            format->setInt32("channel-count", 1);
-            format->setInt32("sample-rate", 16000);
-            break;
-        default:
-            format->setString("mime", "application/octet-stream");
-            break;
-    }
-
-    sampleDesc->mFormat = format;
-
-    return OK;
-}
-
-static void addCodecSpecificData(
-        const sp<AMessage> &format, int32_t index,
-        const void *data, size_t size,
-        bool insertStartCode = false) {
-    sp<ABuffer> csd = new ABuffer(insertStartCode ? size + 4 : size);
-
-    memcpy(csd->data() + (insertStartCode ? 4 : 0), data, size);
-
-    if (insertStartCode) {
-        memcpy(csd->data(), "\x00\x00\x00\x01", 4);
-    }
-
-    csd->meta()->setInt32("csd", true);
-    csd->meta()->setInt64("timeUs", 0ll);
-
-    format->setBuffer(StringPrintf("csd-%d", index).c_str(), csd);
-}
-
-status_t FragmentedMP4Parser::parseSampleSizes(
-        uint32_t type, size_t offset, uint64_t size) {
-    return editTrack(mCurrentTrackID)->mStaticFragment->parseSampleSizes(
-            this, type, offset, size);
-}
-
-status_t FragmentedMP4Parser::parseCompactSampleSizes(
-        uint32_t type, size_t offset, uint64_t size) {
-    return editTrack(mCurrentTrackID)->mStaticFragment->parseCompactSampleSizes(
-            this, type, offset, size);
-}
-
-status_t FragmentedMP4Parser::parseSampleToChunk(
-        uint32_t type, size_t offset, uint64_t size) {
-    return editTrack(mCurrentTrackID)->mStaticFragment->parseSampleToChunk(
-            this, type, offset, size);
-}
-
-status_t FragmentedMP4Parser::parseChunkOffsets(
-        uint32_t type, size_t offset, uint64_t size) {
-    return editTrack(mCurrentTrackID)->mStaticFragment->parseChunkOffsets(
-            this, type, offset, size);
-}
-
-status_t FragmentedMP4Parser::parseChunkOffsets64(
-        uint32_t type, size_t offset, uint64_t size) {
-    return editTrack(mCurrentTrackID)->mStaticFragment->parseChunkOffsets64(
-            this, type, offset, size);
-}
-
-status_t FragmentedMP4Parser::parseAVCCodecSpecificData(
-        uint32_t type, size_t offset, uint64_t size) {
-    TrackInfo *trackInfo = editTrack(mCurrentTrackID);
-
-    SampleDescription *sampleDesc =
-        &trackInfo->mSampleDescs.editItemAt(
-                trackInfo->mSampleDescs.size() - 1);
-
-    if (sampleDesc->mType != FOURCC('a', 'v', 'c', '1')) {
-        return -EINVAL;
-    }
-
-    const uint8_t *ptr = mBuffer->data() + offset;
-
-    size -= offset;
-    offset = 0;
-
-    if (size < 7 || ptr[0] != 0x01) {
-        return ERROR_MALFORMED;
-    }
-
-    sampleDesc->mFormat->setSize("nal-length-size", 1 + (ptr[4] & 3));
-
-    size_t numSPS = ptr[5] & 31;
-
-    ptr += 6;
-    size -= 6;
-
-    for (size_t i = 0; i < numSPS; ++i) {
-        if (size < 2) {
-            return ERROR_MALFORMED;
-        }
-
-        size_t length = U16_AT(ptr);
-
-        ptr += 2;
-        size -= 2;
-
-        if (size < length) {
-            return ERROR_MALFORMED;
-        }
-
-        addCodecSpecificData(
-                sampleDesc->mFormat, i, ptr, length,
-                true /* insertStartCode */);
-
-        ptr += length;
-        size -= length;
-    }
-
-    if (size < 1) {
-        return ERROR_MALFORMED;
-    }
-
-    size_t numPPS = *ptr;
-    ++ptr;
-    --size;
-
-    for (size_t i = 0; i < numPPS; ++i) {
-        if (size < 2) {
-            return ERROR_MALFORMED;
-        }
-
-        size_t length = U16_AT(ptr);
-
-        ptr += 2;
-        size -= 2;
-
-        if (size < length) {
-            return ERROR_MALFORMED;
-        }
-
-        addCodecSpecificData(
-                sampleDesc->mFormat, numSPS + i, ptr, length,
-                true /* insertStartCode */);
-
-        ptr += length;
-        size -= length;
-    }
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseESDSCodecSpecificData(
-        uint32_t type, size_t offset, uint64_t size) {
-    TrackInfo *trackInfo = editTrack(mCurrentTrackID);
-
-    SampleDescription *sampleDesc =
-        &trackInfo->mSampleDescs.editItemAt(
-                trackInfo->mSampleDescs.size() - 1);
-
-    if (sampleDesc->mType != FOURCC('m', 'p', '4', 'a')
-            && sampleDesc->mType != FOURCC('m', 'p', '4', 'v')) {
-        return -EINVAL;
-    }
-
-    const uint8_t *ptr = mBuffer->data() + offset;
-
-    size -= offset;
-    offset = 0;
-
-    if (size < 4) {
-        return -EINVAL;
-    }
-
-    if (U32_AT(ptr) != 0) {
-        return -EINVAL;
-    }
-
-    ptr += 4;
-    size -=4;
-
-    ESDS esds(ptr, size);
-
-    uint8_t objectTypeIndication;
-    if (esds.getObjectTypeIndication(&objectTypeIndication) != OK) {
-        return ERROR_MALFORMED;
-    }
-
-    const uint8_t *csd;
-    size_t csd_size;
-    if (esds.getCodecSpecificInfo(
-                (const void **)&csd, &csd_size) != OK) {
-        return ERROR_MALFORMED;
-    }
-
-    addCodecSpecificData(sampleDesc->mFormat, 0, csd, csd_size);
-
-    if (sampleDesc->mType != FOURCC('m', 'p', '4', 'a')) {
-        return OK;
-    }
-
-    if (csd_size == 0) {
-        // There's no further information, i.e. no codec specific data
-        // Let's assume that the information provided in the mpeg4 headers
-        // is accurate and hope for the best.
-
-        return OK;
-    }
-
-    if (csd_size < 2) {
-        return ERROR_MALFORMED;
-    }
-
-    uint32_t objectType = csd[0] >> 3;
-
-    if (objectType == 31) {
-        return ERROR_UNSUPPORTED;
-    }
-
-    uint32_t freqIndex = (csd[0] & 7) << 1 | (csd[1] >> 7);
-    int32_t sampleRate = 0;
-    int32_t numChannels = 0;
-    if (freqIndex == 15) {
-        if (csd_size < 5) {
-            return ERROR_MALFORMED;
-        }
-
-        sampleRate = (csd[1] & 0x7f) << 17
-                        | csd[2] << 9
-                        | csd[3] << 1
-                        | (csd[4] >> 7);
-
-        numChannels = (csd[4] >> 3) & 15;
-    } else {
-        static uint32_t kSamplingRate[] = {
-            96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
-            16000, 12000, 11025, 8000, 7350
-        };
-
-        if (freqIndex == 13 || freqIndex == 14) {
-            return ERROR_MALFORMED;
-        }
-
-        sampleRate = kSamplingRate[freqIndex];
-        numChannels = (csd[1] >> 3) & 15;
-    }
-
-    if (numChannels == 0) {
-        return ERROR_UNSUPPORTED;
-    }
-
-    sampleDesc->mFormat->setInt32("sample-rate", sampleRate);
-    sampleDesc->mFormat->setInt32("channel-count", numChannels);
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseMediaData(
-        uint32_t type, size_t offset, uint64_t size) {
-    ALOGV("skipping 'mdat' chunk at offsets 0x%08lx-0x%08llx.",
-          mBufferPos + offset, mBufferPos + size);
-
-    sp<ABuffer> buffer = new ABuffer(size - offset);
-    memcpy(buffer->data(), mBuffer->data() + offset, size - offset);
-
-    mMediaData.push();
-    MediaDataInfo *info = &mMediaData.editItemAt(mMediaData.size() - 1);
-    info->mBuffer = buffer;
-    info->mOffset = mBufferPos + offset;
-
-    if (mMediaData.size() > 10) {
-        ALOGV("suspending for now.");
-        mSuspended = true;
-    }
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseSegmentIndex(
-        uint32_t type, size_t offset, uint64_t size) {
-    ALOGV("sidx box type %d, offset %d, size %d", type, int(offset), int(size));
-//    AString sidxstr;
-//    hexdump(mBuffer->data() + offset, size, 0 /* indent */, &sidxstr);
-//    ALOGV("raw sidx:");
-//    ALOGV("%s", sidxstr.c_str());
-    if (offset + 12 > size) {
-        return -EINVAL;
-    }
-
-    uint32_t flags = readU32(offset);
-
-    uint32_t version = flags >> 24;
-    flags &= 0xffffff;
-
-    ALOGV("sidx version %d", version);
-
-    uint32_t referenceId = readU32(offset + 4);
-    uint32_t timeScale = readU32(offset + 8);
-    ALOGV("sidx refid/timescale: %d/%d", referenceId, timeScale);
-
-    uint64_t earliestPresentationTime;
-    uint64_t firstOffset;
-
-    offset += 12;
-
-    if (version == 0) {
-        if (offset + 8 > size) {
-            return -EINVAL;
-        }
-        earliestPresentationTime = readU32(offset);
-        firstOffset = readU32(offset + 4);
-        offset += 8;
-    } else {
-        if (offset + 16 > size) {
-            return -EINVAL;
-        }
-        earliestPresentationTime = readU64(offset);
-        firstOffset = readU64(offset + 8);
-        offset += 16;
-    }
-    ALOGV("sidx pres/off: %Ld/%Ld", earliestPresentationTime, firstOffset);
-
-    if (offset + 4 > size) {
-        return -EINVAL;
-    }
-    if (readU16(offset) != 0) { // reserved
-        return -EINVAL;
-    }
-    int32_t referenceCount = readU16(offset + 2);
-    offset += 4;
-    ALOGV("refcount: %d", referenceCount);
-
-    if (offset + referenceCount * 12 > size) {
-        return -EINVAL;
-    }
-
-    TrackInfo *info = editTrack(mCurrentTrackID);
-    uint64_t total_duration = 0;
-    for (int i = 0; i < referenceCount; i++) {
-        uint32_t d1 = readU32(offset);
-        uint32_t d2 = readU32(offset + 4);
-        uint32_t d3 = readU32(offset + 8);
-
-        if (d1 & 0x80000000) {
-            ALOGW("sub-sidx boxes not supported yet");
-        }
-        bool sap = d3 & 0x80000000;
-        bool saptype = d3 >> 28;
-        if (!sap || saptype > 2) {
-            ALOGW("not a stream access point, or unsupported type");
-        }
-        total_duration += d2;
-        offset += 12;
-        ALOGV(" item %d, %08x %08x %08x", i, d1, d2, d3);
-        SidxEntry se;
-        se.mSize = d1 & 0x7fffffff;
-        se.mDurationUs = 1000000LL * d2 / timeScale;
-        info->mSidx.add(se);
-    }
-
-    info->mSidxDuration = total_duration * 1000000 / timeScale;
-    ALOGV("duration: %lld", info->mSidxDuration);
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseTrackExtends(
-        uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 24 > size) {
-        return -EINVAL;
-    }
-
-    if (readU32(offset) != 0) {
-        return -EINVAL;
-    }
-
-    uint32_t trackID = readU32(offset + 4);
-
-    TrackInfo *info = editTrack(trackID, true /* createIfNecessary */);
-    info->mDefaultSampleDescriptionIndex = readU32(offset + 8);
-    info->mDefaultSampleDuration = readU32(offset + 12);
-    info->mDefaultSampleSize = readU32(offset + 16);
-    info->mDefaultSampleFlags = readU32(offset + 20);
-
-    return OK;
-}
-
-FragmentedMP4Parser::TrackInfo *FragmentedMP4Parser::editTrack(
-        uint32_t trackID, bool createIfNecessary) {
-    ssize_t i = mTracks.indexOfKey(trackID);
-
-    if (i >= 0) {
-        return &mTracks.editValueAt(i);
-    }
-
-    if (!createIfNecessary) {
-        return NULL;
-    }
-
-    TrackInfo info;
-    info.mTrackID = trackID;
-    info.mFlags = 0;
-    info.mDuration = 0xffffffff;
-    info.mSidxDuration = 0;
-    info.mMediaTimeScale = 0;
-    info.mMediaHandlerType = 0;
-    info.mDefaultSampleDescriptionIndex = 0;
-    info.mDefaultSampleDuration = 0;
-    info.mDefaultSampleSize = 0;
-    info.mDefaultSampleFlags = 0;
-
-    info.mDecodingTime = 0;
-
-    mTracks.add(trackID, info);
-    return &mTracks.editValueAt(mTracks.indexOfKey(trackID));
-}
-
-status_t FragmentedMP4Parser::parseTrackFragmentHeader(
-        uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 8 > size) {
-        return -EINVAL;
-    }
-
-    uint32_t flags = readU32(offset);
-
-    if (flags & 0xff000000) {
-        return -EINVAL;
-    }
-
-    mTrackFragmentHeaderInfo.mFlags = flags;
-
-    mTrackFragmentHeaderInfo.mTrackID = readU32(offset + 4);
-    offset += 8;
-
-    if (flags & TrackFragmentHeaderInfo::kBaseDataOffsetPresent) {
-        if (offset + 8 > size) {
-            return -EINVAL;
-        }
-
-        mTrackFragmentHeaderInfo.mBaseDataOffset = readU64(offset);
-        offset += 8;
-    }
-
-    if (flags & TrackFragmentHeaderInfo::kSampleDescriptionIndexPresent) {
-        if (offset + 4 > size) {
-            return -EINVAL;
-        }
-
-        mTrackFragmentHeaderInfo.mSampleDescriptionIndex = readU32(offset);
-        offset += 4;
-    }
-
-    if (flags & TrackFragmentHeaderInfo::kDefaultSampleDurationPresent) {
-        if (offset + 4 > size) {
-            return -EINVAL;
-        }
-
-        mTrackFragmentHeaderInfo.mDefaultSampleDuration = readU32(offset);
-        offset += 4;
-    }
-
-    if (flags & TrackFragmentHeaderInfo::kDefaultSampleSizePresent) {
-        if (offset + 4 > size) {
-            return -EINVAL;
-        }
-
-        mTrackFragmentHeaderInfo.mDefaultSampleSize = readU32(offset);
-        offset += 4;
-    }
-
-    if (flags & TrackFragmentHeaderInfo::kDefaultSampleFlagsPresent) {
-        if (offset + 4 > size) {
-            return -EINVAL;
-        }
-
-        mTrackFragmentHeaderInfo.mDefaultSampleFlags = readU32(offset);
-        offset += 4;
-    }
-
-    if (!(flags & TrackFragmentHeaderInfo::kBaseDataOffsetPresent)) {
-        // This should point to the position of the first byte of the
-        // enclosing 'moof' container for the first track and
-        // the end of the data of the preceding fragment for subsequent
-        // tracks.
-
-        CHECK_GE(mStack.size(), 2u);
-
-        mTrackFragmentHeaderInfo.mBaseDataOffset =
-            mStack.itemAt(mStack.size() - 2).mOffset;
-
-        // XXX TODO: This does not do the right thing for the 2nd and
-        // subsequent tracks yet.
-    }
-
-    mTrackFragmentHeaderInfo.mDataOffset =
-        mTrackFragmentHeaderInfo.mBaseDataOffset;
-
-    TrackInfo *trackInfo = editTrack(mTrackFragmentHeaderInfo.mTrackID);
-
-    if (trackInfo->mFragments.empty()
-            || (*trackInfo->mFragments.begin())->complete()) {
-        trackInfo->mFragments.push_back(new DynamicTrackFragment);
-    }
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::parseTrackFragmentRun(
-        uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 8 > size) {
-        return -EINVAL;
-    }
-
-    enum {
-        kDataOffsetPresent                  = 0x01,
-        kFirstSampleFlagsPresent            = 0x04,
-        kSampleDurationPresent              = 0x100,
-        kSampleSizePresent                  = 0x200,
-        kSampleFlagsPresent                 = 0x400,
-        kSampleCompositionTimeOffsetPresent = 0x800,
-    };
-
-    uint32_t flags = readU32(offset);
-
-    if (flags & 0xff000000) {
-        return -EINVAL;
-    }
-
-    if ((flags & kFirstSampleFlagsPresent) && (flags & kSampleFlagsPresent)) {
-        // These two shall not be used together.
-        return -EINVAL;
-    }
-
-    uint32_t sampleCount = readU32(offset + 4);
-    offset += 8;
-
-    uint64_t dataOffset = mTrackFragmentHeaderInfo.mDataOffset;
-
-    uint32_t firstSampleFlags = 0;
-
-    if (flags & kDataOffsetPresent) {
-        if (offset + 4 > size) {
-            return -EINVAL;
-        }
-
-        int32_t dataOffsetDelta = (int32_t)readU32(offset);
-
-        dataOffset = mTrackFragmentHeaderInfo.mBaseDataOffset + dataOffsetDelta;
-
-        offset += 4;
-    }
-
-    if (flags & kFirstSampleFlagsPresent) {
-        if (offset + 4 > size) {
-            return -EINVAL;
-        }
-
-        firstSampleFlags = readU32(offset);
-        offset += 4;
-    }
-
-    TrackInfo *info = editTrack(mTrackFragmentHeaderInfo.mTrackID);
-
-    if (info == NULL) {
-        return -EINVAL;
-    }
-
-    uint32_t sampleDuration = 0, sampleSize = 0, sampleFlags = 0,
-             sampleCtsOffset = 0;
-
-    size_t bytesPerSample = 0;
-    if (flags & kSampleDurationPresent) {
-        bytesPerSample += 4;
-    } else if (mTrackFragmentHeaderInfo.mFlags
-            & TrackFragmentHeaderInfo::kDefaultSampleDurationPresent) {
-        sampleDuration = mTrackFragmentHeaderInfo.mDefaultSampleDuration;
-    } else {
-        sampleDuration = info->mDefaultSampleDuration;
-    }
-
-    if (flags & kSampleSizePresent) {
-        bytesPerSample += 4;
-    } else if (mTrackFragmentHeaderInfo.mFlags
-            & TrackFragmentHeaderInfo::kDefaultSampleSizePresent) {
-        sampleSize = mTrackFragmentHeaderInfo.mDefaultSampleSize;
-    } else {
-        sampleSize = info->mDefaultSampleSize;
-    }
-
-    if (flags & kSampleFlagsPresent) {
-        bytesPerSample += 4;
-    } else if (mTrackFragmentHeaderInfo.mFlags
-            & TrackFragmentHeaderInfo::kDefaultSampleFlagsPresent) {
-        sampleFlags = mTrackFragmentHeaderInfo.mDefaultSampleFlags;
-    } else {
-        sampleFlags = info->mDefaultSampleFlags;
-    }
-
-    if (flags & kSampleCompositionTimeOffsetPresent) {
-        bytesPerSample += 4;
-    } else {
-        sampleCtsOffset = 0;
-    }
-
-    if (offset + sampleCount * bytesPerSample > size) {
-        return -EINVAL;
-    }
-
-    uint32_t sampleDescIndex =
-        (mTrackFragmentHeaderInfo.mFlags
-            & TrackFragmentHeaderInfo::kSampleDescriptionIndexPresent)
-            ? mTrackFragmentHeaderInfo.mSampleDescriptionIndex
-            : info->mDefaultSampleDescriptionIndex;
-
-    for (uint32_t i = 0; i < sampleCount; ++i) {
-        if (flags & kSampleDurationPresent) {
-            sampleDuration = readU32(offset);
-            offset += 4;
-        }
-
-        if (flags & kSampleSizePresent) {
-            sampleSize = readU32(offset);
-            offset += 4;
-        }
-
-        if (flags & kSampleFlagsPresent) {
-            sampleFlags = readU32(offset);
-            offset += 4;
-        }
-
-        if (flags & kSampleCompositionTimeOffsetPresent) {
-            sampleCtsOffset = readU32(offset);
-            offset += 4;
-        }
-
-        ALOGV("adding sample at offset 0x%08llx, size %u, duration %u, "
-              "sampleDescIndex=%u, flags 0x%08x",
-                dataOffset, sampleSize, sampleDuration,
-                sampleDescIndex,
-                (flags & kFirstSampleFlagsPresent) && i == 0
-                    ? firstSampleFlags : sampleFlags);
-
-        const sp<TrackFragment> &fragment = *--info->mFragments.end();
-
-        uint32_t decodingTime = info->mDecodingTime;
-        info->mDecodingTime += sampleDuration;
-        uint32_t presentationTime = decodingTime + sampleCtsOffset;
-
-        static_cast<DynamicTrackFragment *>(
-                fragment.get())->addSample(
-                    dataOffset,
-                    sampleSize,
-                    presentationTime,
-                    sampleDescIndex,
-                    ((flags & kFirstSampleFlagsPresent) && i == 0)
-                        ? firstSampleFlags : sampleFlags);
-
-        dataOffset += sampleSize;
-    }
-
-    mTrackFragmentHeaderInfo.mDataOffset = dataOffset;
-
-    return OK;
-}
-
-void FragmentedMP4Parser::copyBuffer(
-        sp<ABuffer> *dst, size_t offset, uint64_t size) const {
-    sp<ABuffer> buf = new ABuffer(size);
-    memcpy(buf->data(), mBuffer->data() + offset, size);
-
-    *dst = buf;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/mp4/TrackFragment.cpp b/media/libstagefright/mp4/TrackFragment.cpp
deleted file mode 100644
index 3699038..0000000
--- a/media/libstagefright/mp4/TrackFragment.cpp
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
- * Copyright (C) 2012 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 "TrackFragment"
-#include <utils/Log.h>
-
-#include "TrackFragment.h"
-
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/Utils.h>
-#include <media/stagefright/foundation/ABuffer.h>
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/foundation/hexdump.h>
-
-namespace android {
-
-FragmentedMP4Parser::DynamicTrackFragment::DynamicTrackFragment()
-    : mComplete(false),
-      mSampleIndex(0) {
-}
-
-FragmentedMP4Parser::DynamicTrackFragment::~DynamicTrackFragment() {
-}
-
-status_t FragmentedMP4Parser::DynamicTrackFragment::getSample(SampleInfo *info) {
-    if (mSampleIndex >= mSamples.size()) {
-        return mComplete ? ERROR_END_OF_STREAM : -EWOULDBLOCK;
-    }
-
-    *info = mSamples.itemAt(mSampleIndex);
-
-    return OK;
-}
-
-void FragmentedMP4Parser::DynamicTrackFragment::advance() {
-    ++mSampleIndex;
-}
-
-void FragmentedMP4Parser::DynamicTrackFragment::addSample(
-        off64_t dataOffset, size_t sampleSize,
-        uint32_t presentationTime,
-        size_t sampleDescIndex,
-        uint32_t flags) {
-    mSamples.push();
-    SampleInfo *sampleInfo = &mSamples.editItemAt(mSamples.size() - 1);
-
-    sampleInfo->mOffset = dataOffset;
-    sampleInfo->mSize = sampleSize;
-    sampleInfo->mPresentationTime = presentationTime;
-    sampleInfo->mSampleDescIndex = sampleDescIndex;
-    sampleInfo->mFlags = flags;
-}
-
-status_t FragmentedMP4Parser::DynamicTrackFragment::signalCompletion() {
-    mComplete = true;
-
-    return OK;
-}
-
-bool FragmentedMP4Parser::DynamicTrackFragment::complete() const {
-    return mComplete;
-}
-
-////////////////////////////////////////////////////////////////////////////////
-
-FragmentedMP4Parser::StaticTrackFragment::StaticTrackFragment()
-    : mSampleIndex(0),
-      mSampleCount(0),
-      mChunkIndex(0),
-      mSampleToChunkIndex(-1),
-      mSampleToChunkRemaining(0),
-      mPrevChunkIndex(0xffffffff),
-      mNextSampleOffset(0) {
-}
-
-FragmentedMP4Parser::StaticTrackFragment::~StaticTrackFragment() {
-}
-
-status_t FragmentedMP4Parser::StaticTrackFragment::getSample(SampleInfo *info) {
-    if (mSampleIndex >= mSampleCount) {
-        return ERROR_END_OF_STREAM;
-    }
-
-    *info = mSampleInfo;
-
-    ALOGV("returning sample %d at [0x%08llx, 0x%08llx)",
-          mSampleIndex,
-          info->mOffset, info->mOffset + info->mSize);
-
-    return OK;
-}
-
-void FragmentedMP4Parser::StaticTrackFragment::updateSampleInfo() {
-    if (mSampleIndex >= mSampleCount) {
-        return;
-    }
-
-    if (mSampleSizes != NULL) {
-        uint32_t defaultSampleSize = U32_AT(mSampleSizes->data() + 4);
-        if (defaultSampleSize > 0) {
-            mSampleInfo.mSize = defaultSampleSize;
-        } else {
-            mSampleInfo.mSize= U32_AT(mSampleSizes->data() + 12 + 4 * mSampleIndex);
-        }
-    } else {
-        CHECK(mCompactSampleSizes != NULL);
-
-        uint32_t fieldSize = U32_AT(mCompactSampleSizes->data() + 4);
-
-        switch (fieldSize) {
-            case 4:
-            {
-                unsigned byte = mCompactSampleSizes->data()[12 + mSampleIndex / 2];
-                mSampleInfo.mSize = (mSampleIndex & 1) ? byte & 0x0f : byte >> 4;
-                break;
-            }
-
-            case 8:
-            {
-                mSampleInfo.mSize = mCompactSampleSizes->data()[12 + mSampleIndex];
-                break;
-            }
-
-            default:
-            {
-                CHECK_EQ(fieldSize, 16);
-                mSampleInfo.mSize =
-                    U16_AT(mCompactSampleSizes->data() + 12 + mSampleIndex * 2);
-                break;
-            }
-        }
-    }
-
-    CHECK_GT(mSampleToChunkRemaining, 0);
-
-    // The sample desc index is 1-based... XXX
-    mSampleInfo.mSampleDescIndex =
-        U32_AT(mSampleToChunk->data() + 8 + 12 * mSampleToChunkIndex + 8);
-
-    if (mChunkIndex != mPrevChunkIndex) {
-        mPrevChunkIndex = mChunkIndex;
-
-        if (mChunkOffsets != NULL) {
-            uint32_t entryCount = U32_AT(mChunkOffsets->data() + 4);
-
-            if (mChunkIndex >= entryCount) {
-                mSampleIndex = mSampleCount;
-                return;
-            }
-
-            mNextSampleOffset =
-                U32_AT(mChunkOffsets->data() + 8 + 4 * mChunkIndex);
-        } else {
-            CHECK(mChunkOffsets64 != NULL);
-
-            uint32_t entryCount = U32_AT(mChunkOffsets64->data() + 4);
-
-            if (mChunkIndex >= entryCount) {
-                mSampleIndex = mSampleCount;
-                return;
-            }
-
-            mNextSampleOffset =
-                U64_AT(mChunkOffsets64->data() + 8 + 8 * mChunkIndex);
-        }
-    }
-
-    mSampleInfo.mOffset = mNextSampleOffset;
-
-    mSampleInfo.mPresentationTime = 0;
-    mSampleInfo.mFlags = 0;
-}
-
-void FragmentedMP4Parser::StaticTrackFragment::advance() {
-    mNextSampleOffset += mSampleInfo.mSize;
-
-    ++mSampleIndex;
-    if (--mSampleToChunkRemaining == 0) {
-        ++mChunkIndex;
-
-        uint32_t entryCount = U32_AT(mSampleToChunk->data() + 4);
-
-        // If this is the last entry in the sample to chunk table, we will
-        // stay on this entry.
-        if ((uint32_t)(mSampleToChunkIndex + 1) < entryCount) {
-            uint32_t nextChunkIndex =
-                U32_AT(mSampleToChunk->data() + 8 + 12 * (mSampleToChunkIndex + 1));
-
-            CHECK_GE(nextChunkIndex, 1u);
-            --nextChunkIndex;
-
-            if (mChunkIndex >= nextChunkIndex) {
-                CHECK_EQ(mChunkIndex, nextChunkIndex);
-                ++mSampleToChunkIndex;
-            }
-        }
-
-        mSampleToChunkRemaining =
-            U32_AT(mSampleToChunk->data() + 8 + 12 * mSampleToChunkIndex + 4);
-    }
-
-    updateSampleInfo();
-}
-
-static void setU32At(uint8_t *ptr, uint32_t x) {
-    ptr[0] = x >> 24;
-    ptr[1] = (x >> 16) & 0xff;
-    ptr[2] = (x >> 8) & 0xff;
-    ptr[3] = x & 0xff;
-}
-
-status_t FragmentedMP4Parser::StaticTrackFragment::signalCompletion() {
-    mSampleToChunkIndex = 0;
-
-    mSampleToChunkRemaining =
-        (mSampleToChunk == NULL)
-            ? 0
-            : U32_AT(mSampleToChunk->data() + 8 + 12 * mSampleToChunkIndex + 4);
-
-    updateSampleInfo();
-
-    return OK;
-}
-
-bool FragmentedMP4Parser::StaticTrackFragment::complete() const {
-    return true;
-}
-
-status_t FragmentedMP4Parser::StaticTrackFragment::parseSampleSizes(
-        FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 12 > size) {
-        return ERROR_MALFORMED;
-    }
-
-    if (parser->readU32(offset) != 0) {
-        return ERROR_MALFORMED;
-    }
-
-    uint32_t sampleSize = parser->readU32(offset + 4);
-    uint32_t sampleCount = parser->readU32(offset + 8);
-
-    if (sampleSize == 0 && offset + 12 + sampleCount * 4 != size) {
-        return ERROR_MALFORMED;
-    }
-
-    parser->copyBuffer(&mSampleSizes, offset, size);
-
-    mSampleCount = sampleCount;
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::StaticTrackFragment::parseCompactSampleSizes(
-        FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 12 > size) {
-        return ERROR_MALFORMED;
-    }
-
-    if (parser->readU32(offset) != 0) {
-        return ERROR_MALFORMED;
-    }
-
-    uint32_t fieldSize = parser->readU32(offset + 4);
-
-    if (fieldSize != 4 && fieldSize != 8 && fieldSize != 16) {
-        return ERROR_MALFORMED;
-    }
-
-    uint32_t sampleCount = parser->readU32(offset + 8);
-
-    if (offset + 12 + (sampleCount * fieldSize + 4) / 8 != size) {
-        return ERROR_MALFORMED;
-    }
-
-    parser->copyBuffer(&mCompactSampleSizes, offset, size);
-
-    mSampleCount = sampleCount;
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::StaticTrackFragment::parseSampleToChunk(
-        FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 8 > size) {
-        return ERROR_MALFORMED;
-    }
-
-    if (parser->readU32(offset) != 0) {
-        return ERROR_MALFORMED;
-    }
-
-    uint32_t entryCount = parser->readU32(offset + 4);
-
-    if (entryCount == 0) {
-        return OK;
-    }
-
-    if (offset + 8 + entryCount * 12 != size) {
-        return ERROR_MALFORMED;
-    }
-
-    parser->copyBuffer(&mSampleToChunk, offset, size);
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::StaticTrackFragment::parseChunkOffsets(
-        FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 8 > size) {
-        return ERROR_MALFORMED;
-    }
-
-    if (parser->readU32(offset) != 0) {
-        return ERROR_MALFORMED;
-    }
-
-    uint32_t entryCount = parser->readU32(offset + 4);
-
-    if (offset + 8 + entryCount * 4 != size) {
-        return ERROR_MALFORMED;
-    }
-
-    parser->copyBuffer(&mChunkOffsets, offset, size);
-
-    return OK;
-}
-
-status_t FragmentedMP4Parser::StaticTrackFragment::parseChunkOffsets64(
-        FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size) {
-    if (offset + 8 > size) {
-        return ERROR_MALFORMED;
-    }
-
-    if (parser->readU32(offset) != 0) {
-        return ERROR_MALFORMED;
-    }
-
-    uint32_t entryCount = parser->readU32(offset + 4);
-
-    if (offset + 8 + entryCount * 8 != size) {
-        return ERROR_MALFORMED;
-    }
-
-    parser->copyBuffer(&mChunkOffsets64, offset, size);
-
-    return OK;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/mp4/TrackFragment.h b/media/libstagefright/mp4/TrackFragment.h
deleted file mode 100644
index e1ad46e..0000000
--- a/media/libstagefright/mp4/TrackFragment.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2012 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 TRACK_FRAGMENT_H_
-
-#define TRACK_FRAGMENT_H_
-
-#include "include/FragmentedMP4Parser.h"
-
-namespace android {
-
-struct FragmentedMP4Parser::TrackFragment : public RefBase {
-    TrackFragment() {}
-
-    virtual status_t getSample(SampleInfo *info) = 0;
-    virtual void advance() = 0;
-
-    virtual status_t signalCompletion() = 0;
-    virtual bool complete() const = 0;
-
-protected:
-    virtual ~TrackFragment() {}
-
-private:
-    DISALLOW_EVIL_CONSTRUCTORS(TrackFragment);
-};
-
-struct FragmentedMP4Parser::DynamicTrackFragment : public FragmentedMP4Parser::TrackFragment {
-    DynamicTrackFragment();
-
-    virtual status_t getSample(SampleInfo *info);
-    virtual void advance();
-
-    void addSample(
-            off64_t dataOffset, size_t sampleSize,
-            uint32_t presentationTime,
-            size_t sampleDescIndex,
-            uint32_t flags);
-
-    // No more samples will be added to this fragment.
-    virtual status_t signalCompletion();
-
-    virtual bool complete() const;
-
-protected:
-    virtual ~DynamicTrackFragment();
-
-private:
-    bool mComplete;
-    size_t mSampleIndex;
-    Vector<SampleInfo> mSamples;
-
-    DISALLOW_EVIL_CONSTRUCTORS(DynamicTrackFragment);
-};
-
-struct FragmentedMP4Parser::StaticTrackFragment : public FragmentedMP4Parser::TrackFragment {
-    StaticTrackFragment();
-
-    virtual status_t getSample(SampleInfo *info);
-    virtual void advance();
-
-    virtual status_t signalCompletion();
-    virtual bool complete() const;
-
-    status_t parseSampleSizes(
-            FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseCompactSampleSizes(
-            FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseSampleToChunk(
-            FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseChunkOffsets(
-            FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size);
-
-    status_t parseChunkOffsets64(
-            FragmentedMP4Parser *parser, uint32_t type, size_t offset, uint64_t size);
-
-protected:
-    virtual ~StaticTrackFragment();
-
-private:
-    size_t mSampleIndex;
-    size_t mSampleCount;
-    uint32_t mChunkIndex;
-
-    SampleInfo mSampleInfo;
-
-    sp<ABuffer> mSampleSizes;
-    sp<ABuffer> mCompactSampleSizes;
-
-    sp<ABuffer> mSampleToChunk;
-    ssize_t mSampleToChunkIndex;
-    size_t mSampleToChunkRemaining;
-
-    sp<ABuffer> mChunkOffsets;
-    sp<ABuffer> mChunkOffsets64;
-    uint32_t mPrevChunkIndex;
-    uint64_t mNextSampleOffset;
-
-    void updateSampleInfo();
-
-    DISALLOW_EVIL_CONSTRUCTORS(StaticTrackFragment);
-};
-
-}  // namespace android
-
-#endif  // TRACK_FRAGMENT_H_
diff --git a/media/libstagefright/mpeg2ts/ATSParser.cpp b/media/libstagefright/mpeg2ts/ATSParser.cpp
index cb57a2f..d039f7d 100644
--- a/media/libstagefright/mpeg2ts/ATSParser.cpp
+++ b/media/libstagefright/mpeg2ts/ATSParser.cpp
@@ -862,7 +862,7 @@
 }
 
 void ATSParser::Stream::onPayloadData(
-        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
+        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t /* DTS */,
         const uint8_t *data, size_t size) {
 #if 0
     ALOGI("payload streamType 0x%02x, PTS = 0x%016llx, dPTS = %lld",
@@ -1267,7 +1267,7 @@
 }
 
 void ATSParser::updatePCR(
-        unsigned PID, uint64_t PCR, size_t byteOffsetFromStart) {
+        unsigned /* PID */, uint64_t PCR, size_t byteOffsetFromStart) {
     ALOGV("PCR 0x%016llx @ %d", PCR, byteOffsetFromStart);
 
     if (mNumPCRs == 2) {
diff --git a/media/libstagefright/mpeg2ts/Android.mk b/media/libstagefright/mpeg2ts/Android.mk
index c1a7a9d..c17a0b7 100644
--- a/media/libstagefright/mpeg2ts/Android.mk
+++ b/media/libstagefright/mpeg2ts/Android.mk
@@ -13,6 +13,8 @@
 	$(TOP)/frameworks/av/media/libstagefright \
 	$(TOP)/frameworks/native/include/media/openmax
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_MODULE:= libstagefright_mpeg2ts
 
 ifeq ($(TARGET_ARCH),arm)
diff --git a/media/libstagefright/mpeg2ts/AnotherPacketSource.cpp b/media/libstagefright/mpeg2ts/AnotherPacketSource.cpp
index 52fb2a5..6dfaa94 100644
--- a/media/libstagefright/mpeg2ts/AnotherPacketSource.cpp
+++ b/media/libstagefright/mpeg2ts/AnotherPacketSource.cpp
@@ -34,7 +34,8 @@
     : mIsAudio(false),
       mFormat(NULL),
       mLastQueuedTimeUs(0),
-      mEOSResult(OK) {
+      mEOSResult(OK),
+      mLatestEnqueuedMeta(NULL) {
     setFormat(meta);
 }
 
@@ -61,7 +62,7 @@
 AnotherPacketSource::~AnotherPacketSource() {
 }
 
-status_t AnotherPacketSource::start(MetaData *params) {
+status_t AnotherPacketSource::start(MetaData * /* params */) {
     return OK;
 }
 
@@ -182,12 +183,24 @@
         return;
     }
 
-    CHECK(buffer->meta()->findInt64("timeUs", &mLastQueuedTimeUs));
+    int64_t lastQueuedTimeUs;
+    CHECK(buffer->meta()->findInt64("timeUs", &lastQueuedTimeUs));
+    mLastQueuedTimeUs = lastQueuedTimeUs;
     ALOGV("queueAccessUnit timeUs=%lld us (%.2f secs)", mLastQueuedTimeUs, mLastQueuedTimeUs / 1E6);
 
     Mutex::Autolock autoLock(mLock);
     mBuffers.push_back(buffer);
     mCondition.signal();
+
+    if (!mLatestEnqueuedMeta.get()) {
+        mLatestEnqueuedMeta = buffer->meta();
+    } else {
+        int64_t latestTimeUs = 0;
+        CHECK(mLatestEnqueuedMeta->findInt64("timeUs", &latestTimeUs));
+        if (lastQueuedTimeUs > latestTimeUs) {
+            mLatestEnqueuedMeta = buffer->meta();
+        }
+    }
 }
 
 void AnotherPacketSource::clear() {
@@ -197,6 +210,7 @@
     mEOSResult = OK;
 
     mFormat = NULL;
+    mLatestEnqueuedMeta = NULL;
 }
 
 void AnotherPacketSource::queueDiscontinuity(
@@ -221,6 +235,7 @@
 
     mEOSResult = OK;
     mLastQueuedTimeUs = 0;
+    mLatestEnqueuedMeta = NULL;
 
     sp<ABuffer> buffer = new ABuffer(0);
     buffer->meta()->setInt32("discontinuity", static_cast<int32_t>(type));
@@ -308,4 +323,9 @@
     return (mEOSResult != OK);
 }
 
+sp<AMessage> AnotherPacketSource::getLatestMeta() {
+    Mutex::Autolock autoLock(mLock);
+    return mLatestEnqueuedMeta;
+}
+
 }  // namespace android
diff --git a/media/libstagefright/mpeg2ts/AnotherPacketSource.h b/media/libstagefright/mpeg2ts/AnotherPacketSource.h
index e16cf78..9b193a2 100644
--- a/media/libstagefright/mpeg2ts/AnotherPacketSource.h
+++ b/media/libstagefright/mpeg2ts/AnotherPacketSource.h
@@ -62,6 +62,8 @@
 
     bool isFinished(int64_t duration) const;
 
+    sp<AMessage> getLatestMeta();
+
 protected:
     virtual ~AnotherPacketSource();
 
@@ -74,6 +76,7 @@
     int64_t mLastQueuedTimeUs;
     List<sp<ABuffer> > mBuffers;
     status_t mEOSResult;
+    sp<AMessage> mLatestEnqueuedMeta;
 
     bool wasFormatChange(int32_t discontinuityType) const;
 
diff --git a/media/libstagefright/mpeg2ts/ESQueue.cpp b/media/libstagefright/mpeg2ts/ESQueue.cpp
index ea79885..c0c9717 100644
--- a/media/libstagefright/mpeg2ts/ESQueue.cpp
+++ b/media/libstagefright/mpeg2ts/ESQueue.cpp
@@ -60,7 +60,7 @@
 // update metadata only applicable, and return the payload size
 static unsigned parseAC3SyncFrame(
         const uint8_t *ptr, size_t size, sp<MetaData> *metaData) {
-    static const unsigned channelCountTable[] = {2, 1, 2, 3, 4, 4, 5, 6};
+    static const unsigned channelCountTable[] = {2, 1, 2, 3, 3, 4, 4, 5};
     static const unsigned samplingRateTable[] = {48000, 44100, 32000};
     static const unsigned rates[] = {32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256,
             320, 384, 448, 512, 576, 640};
@@ -794,7 +794,9 @@
                 dstOffset += pos.nalSize + 4;
             }
 
+#if !LOG_NDEBUG
             ALOGV("accessUnit contains nal types %s", out.c_str());
+#endif
 
             const NALPosition &pos = nals.itemAt(nals.size() - 1);
             size_t nextScan = pos.nalOffset + pos.nalSize;
diff --git a/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp b/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp
index dd714c99..bc2a16d 100644
--- a/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp
+++ b/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp
@@ -130,7 +130,8 @@
     return new WrappedTrack(this, mTracks.valueAt(index));
 }
 
-sp<MetaData> MPEG2PSExtractor::getTrackMetaData(size_t index, uint32_t flags) {
+sp<MetaData> MPEG2PSExtractor::getTrackMetaData(
+        size_t index, uint32_t /* flags */) {
     if (index >= mTracks.size()) {
         return NULL;
     }
@@ -625,7 +626,7 @@
 
 status_t MPEG2PSExtractor::Track::appendPESData(
         unsigned PTS_DTS_flags,
-        uint64_t PTS, uint64_t DTS,
+        uint64_t PTS, uint64_t /* DTS */,
         const uint8_t *data, size_t size) {
     if (mQueue == NULL) {
         return OK;
diff --git a/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp b/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp
index d449c34..35ca118 100644
--- a/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp
+++ b/media/libstagefright/mpeg2ts/MPEG2TSExtractor.cpp
@@ -141,7 +141,7 @@
 }
 
 sp<MetaData> MPEG2TSExtractor::getTrackMetaData(
-        size_t index, uint32_t flags) {
+        size_t index, uint32_t /* flags */) {
     return index < mSourceImpls.size()
         ? mSourceImpls.editItemAt(index)->getFormat() : NULL;
 }
diff --git a/media/libstagefright/omx/GraphicBufferSource.cpp b/media/libstagefright/omx/GraphicBufferSource.cpp
index 1e6de55..7672204 100644
--- a/media/libstagefright/omx/GraphicBufferSource.cpp
+++ b/media/libstagefright/omx/GraphicBufferSource.cpp
@@ -41,11 +41,11 @@
     mNumFramesAvailable(0),
     mEndOfStream(false),
     mEndOfStreamSent(false),
-    mRepeatAfterUs(-1ll),
     mMaxTimestampGapUs(-1ll),
     mPrevOriginalTimeUs(-1ll),
     mPrevModifiedTimeUs(-1ll),
     mSkipFramesBeforeNs(-1ll),
+    mRepeatAfterUs(-1ll),
     mRepeatLastFrameGeneration(0),
     mRepeatLastFrameTimestamp(-1ll),
     mLatestSubmittedBufferId(-1),
diff --git a/media/libstagefright/omx/OMX.cpp b/media/libstagefright/omx/OMX.cpp
index 84a0e10..a608479 100644
--- a/media/libstagefright/omx/OMX.cpp
+++ b/media/libstagefright/omx/OMX.cpp
@@ -185,7 +185,7 @@
     instance->onObserverDied(mMaster);
 }
 
-bool OMX::livesLocally(node_id node, pid_t pid) {
+bool OMX::livesLocally(node_id /* node */, pid_t pid) {
     return pid == getpid();
 }
 
@@ -424,7 +424,7 @@
         OMX_IN OMX_EVENTTYPE eEvent,
         OMX_IN OMX_U32 nData1,
         OMX_IN OMX_U32 nData2,
-        OMX_IN OMX_PTR pEventData) {
+        OMX_IN OMX_PTR /* pEventData */) {
     ALOGV("OnEvent(%d, %ld, %ld)", eEvent, nData1, nData2);
 
     // Forward to OMXNodeInstance.
@@ -479,7 +479,7 @@
 OMX::node_id OMX::makeNodeID(OMXNodeInstance *instance) {
     // mLock is already held.
 
-    node_id node = (node_id)++mNodeCounter;
+    node_id node = (node_id)(uintptr_t)++mNodeCounter;
     mNodeIDToInstance.add(node, instance);
 
     return node;
diff --git a/media/libstagefright/omx/OMXNodeInstance.cpp b/media/libstagefright/omx/OMXNodeInstance.cpp
index dba522f..aa96389 100644
--- a/media/libstagefright/omx/OMXNodeInstance.cpp
+++ b/media/libstagefright/omx/OMXNodeInstance.cpp
@@ -266,7 +266,7 @@
 }
 
 status_t OMXNodeInstance::getParameter(
-        OMX_INDEXTYPE index, void *params, size_t size) {
+        OMX_INDEXTYPE index, void *params, size_t /* size */) {
     Mutex::Autolock autoLock(mLock);
 
     OMX_ERRORTYPE err = OMX_GetParameter(mHandle, index, params);
@@ -275,7 +275,7 @@
 }
 
 status_t OMXNodeInstance::setParameter(
-        OMX_INDEXTYPE index, const void *params, size_t size) {
+        OMX_INDEXTYPE index, const void *params, size_t /* size */) {
     Mutex::Autolock autoLock(mLock);
 
     OMX_ERRORTYPE err = OMX_SetParameter(
@@ -285,7 +285,7 @@
 }
 
 status_t OMXNodeInstance::getConfig(
-        OMX_INDEXTYPE index, void *params, size_t size) {
+        OMX_INDEXTYPE index, void *params, size_t /* size */) {
     Mutex::Autolock autoLock(mLock);
 
     OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params);
@@ -293,7 +293,7 @@
 }
 
 status_t OMXNodeInstance::setConfig(
-        OMX_INDEXTYPE index, const void *params, size_t size) {
+        OMX_INDEXTYPE index, const void *params, size_t /* size */) {
     Mutex::Autolock autoLock(mLock);
 
     OMX_ERRORTYPE err = OMX_SetConfig(
@@ -610,7 +610,7 @@
 }
 
 status_t OMXNodeInstance::updateGraphicBufferInMeta(
-        OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
+        OMX_U32 /* portIndex */, const sp<GraphicBuffer>& graphicBuffer,
         OMX::buffer_id buffer) {
     Mutex::Autolock autoLock(mLock);
 
@@ -971,7 +971,7 @@
 
 // static
 OMX_ERRORTYPE OMXNodeInstance::OnEvent(
-        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_IN OMX_HANDLETYPE /* hComponent */,
         OMX_IN OMX_PTR pAppData,
         OMX_IN OMX_EVENTTYPE eEvent,
         OMX_IN OMX_U32 nData1,
@@ -987,7 +987,7 @@
 
 // static
 OMX_ERRORTYPE OMXNodeInstance::OnEmptyBufferDone(
-        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_IN OMX_HANDLETYPE /* hComponent */,
         OMX_IN OMX_PTR pAppData,
         OMX_IN OMX_BUFFERHEADERTYPE* pBuffer) {
     OMXNodeInstance *instance = static_cast<OMXNodeInstance *>(pAppData);
@@ -999,7 +999,7 @@
 
 // static
 OMX_ERRORTYPE OMXNodeInstance::OnFillBufferDone(
-        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_IN OMX_HANDLETYPE /* hComponent */,
         OMX_IN OMX_PTR pAppData,
         OMX_IN OMX_BUFFERHEADERTYPE* pBuffer) {
     OMXNodeInstance *instance = static_cast<OMXNodeInstance *>(pAppData);
diff --git a/media/libstagefright/omx/SoftOMXComponent.cpp b/media/libstagefright/omx/SoftOMXComponent.cpp
index b1c34dc..646cd32 100644
--- a/media/libstagefright/omx/SoftOMXComponent.cpp
+++ b/media/libstagefright/omx/SoftOMXComponent.cpp
@@ -257,69 +257,69 @@
 ////////////////////////////////////////////////////////////////////////////////
 
 OMX_ERRORTYPE SoftOMXComponent::sendCommand(
-        OMX_COMMANDTYPE cmd, OMX_U32 param, OMX_PTR data) {
+        OMX_COMMANDTYPE /* cmd */, OMX_U32 /* param */, OMX_PTR /* data */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::getParameter(
-        OMX_INDEXTYPE index, OMX_PTR params) {
+        OMX_INDEXTYPE /* index */, OMX_PTR /* params */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::setParameter(
-        OMX_INDEXTYPE index, const OMX_PTR params) {
+        OMX_INDEXTYPE /* index */, const OMX_PTR /* params */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::getConfig(
-        OMX_INDEXTYPE index, OMX_PTR params) {
+        OMX_INDEXTYPE /* index */, OMX_PTR /* params */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::setConfig(
-        OMX_INDEXTYPE index, const OMX_PTR params) {
+        OMX_INDEXTYPE /* index */, const OMX_PTR /* params */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::getExtensionIndex(
-        const char *name, OMX_INDEXTYPE *index) {
+        const char * /* name */, OMX_INDEXTYPE * /* index */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::useBuffer(
-        OMX_BUFFERHEADERTYPE **buffer,
-        OMX_U32 portIndex,
-        OMX_PTR appPrivate,
-        OMX_U32 size,
-        OMX_U8 *ptr) {
+        OMX_BUFFERHEADERTYPE ** /* buffer */,
+        OMX_U32 /* portIndex */,
+        OMX_PTR /* appPrivate */,
+        OMX_U32 /* size */,
+        OMX_U8 * /* ptr */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::allocateBuffer(
-        OMX_BUFFERHEADERTYPE **buffer,
-        OMX_U32 portIndex,
-        OMX_PTR appPrivate,
-        OMX_U32 size) {
+        OMX_BUFFERHEADERTYPE ** /* buffer */,
+        OMX_U32 /* portIndex */,
+        OMX_PTR /* appPrivate */,
+        OMX_U32 /* size */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::freeBuffer(
-        OMX_U32 portIndex,
-        OMX_BUFFERHEADERTYPE *buffer) {
+        OMX_U32 /* portIndex */,
+        OMX_BUFFERHEADERTYPE * /* buffer */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::emptyThisBuffer(
-        OMX_BUFFERHEADERTYPE *buffer) {
+        OMX_BUFFERHEADERTYPE * /* buffer */) {
     return OMX_ErrorUndefined;
 }
 
 OMX_ERRORTYPE SoftOMXComponent::fillThisBuffer(
-        OMX_BUFFERHEADERTYPE *buffer) {
+        OMX_BUFFERHEADERTYPE * /* buffer */) {
     return OMX_ErrorUndefined;
 }
 
-OMX_ERRORTYPE SoftOMXComponent::getState(OMX_STATETYPE *state) {
+OMX_ERRORTYPE SoftOMXComponent::getState(OMX_STATETYPE * /* state */) {
     return OMX_ErrorUndefined;
 }
 
diff --git a/media/libstagefright/omx/SoftOMXPlugin.cpp b/media/libstagefright/omx/SoftOMXPlugin.cpp
index d6cde73..d49e50b 100644
--- a/media/libstagefright/omx/SoftOMXPlugin.cpp
+++ b/media/libstagefright/omx/SoftOMXPlugin.cpp
@@ -154,7 +154,7 @@
 
 OMX_ERRORTYPE SoftOMXPlugin::enumerateComponents(
         OMX_STRING name,
-        size_t size,
+        size_t /* size */,
         OMX_U32 index) {
     if (index >= kNumComponents) {
         return OMX_ErrorNoMore;
diff --git a/media/libstagefright/omx/tests/Android.mk b/media/libstagefright/omx/tests/Android.mk
index 1061c39..8b79af4 100644
--- a/media/libstagefright/omx/tests/Android.mk
+++ b/media/libstagefright/omx/tests/Android.mk
@@ -11,6 +11,8 @@
 	$(TOP)/frameworks/av/media/libstagefright \
 	$(TOP)/frameworks/native/include/media/openmax
 
+LOCAL_CFLAGS += -Werror
+
 LOCAL_MODULE := omx_tests
 
 LOCAL_MODULE_TAGS := tests
diff --git a/media/libstagefright/omx/tests/OMXHarness.cpp b/media/libstagefright/omx/tests/OMXHarness.cpp
index 499545e..03725df 100644
--- a/media/libstagefright/omx/tests/OMXHarness.cpp
+++ b/media/libstagefright/omx/tests/OMXHarness.cpp
@@ -16,6 +16,7 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "OMXHarness"
+#include <inttypes.h>
 #include <utils/Log.h>
 
 #include "OMXHarness.h"
@@ -713,11 +714,11 @@
             int64_t bufferTimeUs;
             CHECK(buffer->meta_data()->findInt64(kKeyTime, &bufferTimeUs));
             if (!CloseEnough(bufferTimeUs, actualSeekTimeUs)) {
-                printf("\n  * Attempted seeking to %lld us (%.2f secs)",
+                printf("\n  * Attempted seeking to %" PRId64 " us (%.2f secs)",
                        requestedSeekTimeUs, requestedSeekTimeUs / 1E6);
-                printf("\n  * Nearest keyframe is at %lld us (%.2f secs)",
+                printf("\n  * Nearest keyframe is at %" PRId64 " us (%.2f secs)",
                        actualSeekTimeUs, actualSeekTimeUs / 1E6);
-                printf("\n  * Returned buffer was at %lld us (%.2f secs)\n\n",
+                printf("\n  * Returned buffer was at %" PRId64 " us (%.2f secs)\n\n",
                        bufferTimeUs, bufferTimeUs / 1E6);
 
                 buffer->release();
diff --git a/media/libstagefright/rtsp/AMPEG2TSAssembler.cpp b/media/libstagefright/rtsp/AMPEG2TSAssembler.cpp
index 4c9bf5b..dca5c89 100644
--- a/media/libstagefright/rtsp/AMPEG2TSAssembler.cpp
+++ b/media/libstagefright/rtsp/AMPEG2TSAssembler.cpp
@@ -34,7 +34,9 @@
 namespace android {
 
 AMPEG2TSAssembler::AMPEG2TSAssembler(
-        const sp<AMessage> &notify, const char *desc, const AString &params)
+        const sp<AMessage> &notify,
+        const char * /* desc */,
+        const AString & /* params */)
     : mNotifyMsg(notify),
       mNextExpectedSeqNoValid(false),
       mNextExpectedSeqNo(0) {
diff --git a/media/libstagefright/rtsp/ARTPWriter.cpp b/media/libstagefright/rtsp/ARTPWriter.cpp
index 0d07043..c46d16f 100644
--- a/media/libstagefright/rtsp/ARTPWriter.cpp
+++ b/media/libstagefright/rtsp/ARTPWriter.cpp
@@ -114,7 +114,7 @@
     return (mFlags & kFlagEOS) != 0;
 }
 
-status_t ARTPWriter::start(MetaData *params) {
+status_t ARTPWriter::start(MetaData * /* params */) {
     Mutex::Autolock autoLock(mLock);
     if (mFlags & kFlagStarted) {
         return INVALID_OPERATION;
diff --git a/media/libstagefright/rtsp/ARawAudioAssembler.cpp b/media/libstagefright/rtsp/ARawAudioAssembler.cpp
index 0da5dd2..167f7a4 100644
--- a/media/libstagefright/rtsp/ARawAudioAssembler.cpp
+++ b/media/libstagefright/rtsp/ARawAudioAssembler.cpp
@@ -34,7 +34,9 @@
 namespace android {
 
 ARawAudioAssembler::ARawAudioAssembler(
-        const sp<AMessage> &notify, const char *desc, const AString &params)
+        const sp<AMessage> &notify,
+        const char * /* desc */,
+        const AString & /* params */)
     : mNotifyMsg(notify),
       mNextExpectedSeqNoValid(false),
       mNextExpectedSeqNo(0) {
diff --git a/media/libstagefright/rtsp/Android.mk b/media/libstagefright/rtsp/Android.mk
index 02e44f4..39eedc0 100644
--- a/media/libstagefright/rtsp/Android.mk
+++ b/media/libstagefright/rtsp/Android.mk
@@ -30,6 +30,8 @@
     LOCAL_CFLAGS += -Wno-psabi
 endif
 
+LOCAL_CFLAGS += -Werror
+
 include $(BUILD_STATIC_LIBRARY)
 
 ################################################################################
diff --git a/media/libstagefright/rtsp/MyHandler.h b/media/libstagefright/rtsp/MyHandler.h
index cd77aa0..45470a3 100644
--- a/media/libstagefright/rtsp/MyHandler.h
+++ b/media/libstagefright/rtsp/MyHandler.h
@@ -19,7 +19,11 @@
 #define MY_HANDLER_H_
 
 //#define LOG_NDEBUG 0
+
+#ifndef LOG_TAG
 #define LOG_TAG "MyHandler"
+#endif
+
 #include <utils/Log.h>
 
 #include "APacketSource.h"
@@ -42,6 +46,12 @@
 
 #include "HTTPBase.h"
 
+#if LOG_NDEBUG
+#define UNUSED_UNLESS_VERBOSE(x) (void)(x)
+#else
+#define UNUSED_UNLESS_VERBOSE(x)
+#endif
+
 // If no access units are received within 5 secs, assume that the rtp
 // stream has ended and signal end of stream.
 static int64_t kAccessUnitTimeoutUs = 10000000ll;
@@ -178,7 +188,7 @@
         mConn->connect(mOriginalSessionURL.c_str(), reply);
     }
 
-    AString getControlURL(sp<ASessionDescription> desc) {
+    AString getControlURL() {
         AString sessionLevelControlURL;
         if (mSessionDesc->findAttribute(
                 0,
@@ -545,7 +555,7 @@
                                 mBaseURL = tmp;
                             }
 
-                            mControlURL = getControlURL(mSessionDesc);
+                            mControlURL = getControlURL();
 
                             if (mSessionDesc->countTracks() < 2) {
                                 // There's no actual tracks in this session.
@@ -591,7 +601,7 @@
 
                         mSeekable = !isLiveStream(mSessionDesc);
 
-                        mControlURL = getControlURL(mSessionDesc);
+                        mControlURL = getControlURL();
 
                         if (mSessionDesc->countTracks() < 2) {
                             // There's no actual tracks in this session.
@@ -1805,6 +1815,8 @@
     bool addMediaTimestamp(
             int32_t trackIndex, const TrackInfo *track,
             const sp<ABuffer> &accessUnit) {
+        UNUSED_UNLESS_VERBOSE(trackIndex);
+
         uint32_t rtpTime;
         CHECK(accessUnit->meta()->findInt32(
                     "rtp-time", (int32_t *)&rtpTime));
diff --git a/media/libstagefright/tests/DummyRecorder.cpp b/media/libstagefright/tests/DummyRecorder.cpp
index ac37b28..8f17088 100644
--- a/media/libstagefright/tests/DummyRecorder.cpp
+++ b/media/libstagefright/tests/DummyRecorder.cpp
@@ -61,7 +61,7 @@
     mSource->stop();
     void *dummy;
     pthread_join(mThread, &dummy);
-    status_t err = (status_t) dummy;
+    status_t err = static_cast<status_t>(reinterpret_cast<uintptr_t>(dummy));
 
     ALOGV("Ending the reading thread");
     return err;
diff --git a/media/libstagefright/tests/SurfaceMediaSource_test.cpp b/media/libstagefright/tests/SurfaceMediaSource_test.cpp
index ddedad7..aeecdbc 100644
--- a/media/libstagefright/tests/SurfaceMediaSource_test.cpp
+++ b/media/libstagefright/tests/SurfaceMediaSource_test.cpp
@@ -527,7 +527,8 @@
 }
 
 // Dequeuing and queuing the buffer without really filling it in.
-void SurfaceMediaSourceTest::oneBufferPassNoFill(int width, int height ) {
+void SurfaceMediaSourceTest::oneBufferPassNoFill(
+        int /* width */, int /* height  */) {
     ANativeWindowBuffer* anb;
     ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(), &anb));
     ASSERT_TRUE(anb != NULL);
diff --git a/media/libstagefright/timedtext/Android.mk b/media/libstagefright/timedtext/Android.mk
index f099bbd..6a8b9fc 100644
--- a/media/libstagefright/timedtext/Android.mk
+++ b/media/libstagefright/timedtext/Android.mk
@@ -9,7 +9,8 @@
         TimedTextSRTSource.cpp    \
         TimedTextPlayer.cpp
 
-LOCAL_CFLAGS += -Wno-multichar
+LOCAL_CFLAGS += -Wno-multichar -Werror
+
 LOCAL_C_INCLUDES:= \
         $(TOP)/frameworks/av/include/media/stagefright/timedtext \
         $(TOP)/frameworks/av/media/libstagefright
diff --git a/media/libstagefright/timedtext/TimedTextDriver.cpp b/media/libstagefright/timedtext/TimedTextDriver.cpp
index 05d6d02..71aa21e 100644
--- a/media/libstagefright/timedtext/TimedTextDriver.cpp
+++ b/media/libstagefright/timedtext/TimedTextDriver.cpp
@@ -45,6 +45,7 @@
         const sp<IMediaHTTPService> &httpService)
     : mLooper(new ALooper),
       mListener(listener),
+      mHTTPService(httpService),
       mState(UNINITIALIZED),
       mCurrentTrackIndex(UINT_MAX) {
     mLooper->setName("TimedTextDriver");
diff --git a/media/libstagefright/timedtext/TimedTextSource.h b/media/libstagefright/timedtext/TimedTextSource.h
index 756cc31..8c1c1cd 100644
--- a/media/libstagefright/timedtext/TimedTextSource.h
+++ b/media/libstagefright/timedtext/TimedTextSource.h
@@ -47,7 +47,7 @@
           int64_t *endTimeUs,
           Parcel *parcel,
           const MediaSource::ReadOptions *options = NULL) = 0;
-  virtual status_t extractGlobalDescriptions(Parcel *parcel) {
+  virtual status_t extractGlobalDescriptions(Parcel * /* parcel */) {
       return INVALID_OPERATION;
   }
   virtual sp<MetaData> getFormat();
diff --git a/media/libstagefright/wifi-display/rtp/RTPSender.cpp b/media/libstagefright/wifi-display/rtp/RTPSender.cpp
index 1887b8b..e88a3bd 100644
--- a/media/libstagefright/wifi-display/rtp/RTPSender.cpp
+++ b/media/libstagefright/wifi-display/rtp/RTPSender.cpp
@@ -685,9 +685,8 @@
     return OK;
 }
 
-status_t RTPSender::parseReceiverReport(const uint8_t *data, size_t size) {
-    // hexdump(data, size);
-
+status_t RTPSender::parseReceiverReport(
+        const uint8_t *data, size_t /* size */) {
     float fractionLost = data[12] / 256.0f;
 
     ALOGI("lost %.2f %% of packets during report interval.",
diff --git a/media/libstagefright/wifi-display/source/RepeaterSource.cpp b/media/libstagefright/wifi-display/source/RepeaterSource.cpp
index cc8dee3..59d7e6e 100644
--- a/media/libstagefright/wifi-display/source/RepeaterSource.cpp
+++ b/media/libstagefright/wifi-display/source/RepeaterSource.cpp
@@ -79,6 +79,8 @@
 
     ALOGV("stopping");
 
+    status_t err = mSource->stop();
+
     if (mLooper != NULL) {
         mLooper->stop();
         mLooper.clear();
@@ -92,7 +94,6 @@
         mBuffer = NULL;
     }
 
-    status_t err = mSource->stop();
 
     ALOGV("stopped");
 
diff --git a/media/libstagefright/wifi-display/source/TSPacketizer.cpp b/media/libstagefright/wifi-display/source/TSPacketizer.cpp
index eeb3700..50d317a 100644
--- a/media/libstagefright/wifi-display/source/TSPacketizer.cpp
+++ b/media/libstagefright/wifi-display/source/TSPacketizer.cpp
@@ -565,7 +565,7 @@
             }
         }
 
-        // size_t numPaddingBytes = sizeAvailableForPayload - numBytesOfPayload;
+        size_t numPaddingBytes = sizeAvailableForPayload - numBytesOfPayload;
         ALOGV("packet 1 contains %zd padding bytes and %zd bytes of payload",
               numPaddingBytes, numBytesOfPayload);
 
diff --git a/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp b/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp
index 05e4018..da405e2 100644
--- a/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp
+++ b/media/libstagefright/wifi-display/source/WifiDisplaySource.cpp
@@ -746,7 +746,7 @@
 }
 
 status_t WifiDisplaySource::onReceiveM1Response(
-        int32_t sessionID, const sp<ParsedMessage> &msg) {
+        int32_t /* sessionID */, const sp<ParsedMessage> &msg) {
     int32_t statusCode;
     if (!msg->getStatusCode(&statusCode)) {
         return ERROR_MALFORMED;
@@ -991,7 +991,7 @@
 }
 
 status_t WifiDisplaySource::onReceiveM5Response(
-        int32_t sessionID, const sp<ParsedMessage> &msg) {
+        int32_t /* sessionID */, const sp<ParsedMessage> &msg) {
     int32_t statusCode;
     if (!msg->getStatusCode(&statusCode)) {
         return ERROR_MALFORMED;
@@ -1005,7 +1005,7 @@
 }
 
 status_t WifiDisplaySource::onReceiveM16Response(
-        int32_t sessionID, const sp<ParsedMessage> &msg) {
+        int32_t sessionID, const sp<ParsedMessage> & /* msg */) {
     // If only the response was required to include a "Session:" header...
 
     CHECK_EQ(sessionID, mClientSessionID);
@@ -1680,7 +1680,7 @@
 }
 
 void WifiDisplaySource::HDCPObserver::notify(
-        int msg, int ext1, int ext2, const Parcel *obj) {
+        int msg, int ext1, int ext2, const Parcel * /* obj */) {
     sp<AMessage> notify = mNotify->dup();
     notify->setInt32("msg", msg);
     notify->setInt32("ext1", ext1);
diff --git a/media/libstagefright/yuv/Android.mk b/media/libstagefright/yuv/Android.mk
index b3f7b1b..bb86dfc 100644
--- a/media/libstagefright/yuv/Android.mk
+++ b/media/libstagefright/yuv/Android.mk
@@ -12,5 +12,7 @@
 LOCAL_MODULE:= libstagefright_yuv
 
 
+LOCAL_CFLAGS += -Werror
+
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/yuv/YUVImage.cpp b/media/libstagefright/yuv/YUVImage.cpp
index 7b9000b..bb3e2fd 100644
--- a/media/libstagefright/yuv/YUVImage.cpp
+++ b/media/libstagefright/yuv/YUVImage.cpp
@@ -226,8 +226,8 @@
             &ySrcOffsetIncrement, &uSrcOffsetIncrement, &vSrcOffsetIncrement);
 
     int32_t yDestOffsetIncrement;
-    int32_t uDestOffsetIncrement;
-    int32_t vDestOffsetIncrement;
+    int32_t uDestOffsetIncrement = 0;
+    int32_t vDestOffsetIncrement = 0;
     destImage.getOffsetIncrementsPerDataRow(
             &yDestOffsetIncrement, &uDestOffsetIncrement, &vDestOffsetIncrement);
 
@@ -309,7 +309,7 @@
 
     int32_t yDestOffsetIncrement;
     int32_t uDestOffsetIncrement;
-    int32_t vDestOffsetIncrement;
+    int32_t vDestOffsetIncrement = 0;
     destImage.getOffsetIncrementsPerDataRow(
             &yDestOffsetIncrement, &uDestOffsetIncrement, &vDestOffsetIncrement);
 
@@ -393,9 +393,9 @@
     fprintf(fp, "255\n");
     for (int32_t y = 0; y < mHeight; ++y) {
         for (int32_t x = 0; x < mWidth; ++x) {
-            uint8_t yValue;
-            uint8_t uValue;
-            uint8_t vValue;
+            uint8_t yValue = 0u;
+            uint8_t uValue = 0u;
+            uint8_t vValue = 0u;
             getPixelValue(x, y, &yValue, &uValue, & vValue);
 
             uint8_t rValue;
diff --git a/media/mtp/MtpProperty.cpp b/media/mtp/MtpProperty.cpp
index 64dd45b..375ed9a 100644
--- a/media/mtp/MtpProperty.cpp
+++ b/media/mtp/MtpProperty.cpp
@@ -16,6 +16,7 @@
 
 #define LOG_TAG "MtpProperty"
 
+#include <inttypes.h>
 #include "MtpDataPacket.h"
 #include "MtpDebug.h"
 #include "MtpProperty.h"
@@ -385,10 +386,10 @@
             buffer.appendFormat("%d", value.u.u32);
             break;
         case MTP_TYPE_INT64:
-            buffer.appendFormat("%lld", value.u.i64);
+            buffer.appendFormat("%" PRId64, value.u.i64);
             break;
         case MTP_TYPE_UINT64:
-            buffer.appendFormat("%lld", value.u.u64);
+            buffer.appendFormat("%" PRIu64, value.u.u64);
             break;
         case MTP_TYPE_INT128:
             buffer.appendFormat("%08X%08X%08X%08X", value.u.i128[0], value.u.i128[1],
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 81f046f..b74fa89 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -104,6 +104,27 @@
 
 // ----------------------------------------------------------------------------
 
+const char *formatToString(audio_format_t format) {
+    switch(format) {
+    case AUDIO_FORMAT_PCM_SUB_8_BIT: return "pcm8";
+    case AUDIO_FORMAT_PCM_SUB_16_BIT: return "pcm16";
+    case AUDIO_FORMAT_PCM_SUB_32_BIT: return "pcm32";
+    case AUDIO_FORMAT_PCM_SUB_8_24_BIT: return "pcm8.24";
+    case AUDIO_FORMAT_PCM_SUB_24_BIT_PACKED: return "pcm24";
+    case AUDIO_FORMAT_PCM_SUB_FLOAT: return "pcmfloat";
+    case AUDIO_FORMAT_MP3: return "mp3";
+    case AUDIO_FORMAT_AMR_NB: return "amr-nb";
+    case AUDIO_FORMAT_AMR_WB: return "amr-wb";
+    case AUDIO_FORMAT_AAC: return "aac";
+    case AUDIO_FORMAT_HE_AAC_V1: return "he-aac-v1";
+    case AUDIO_FORMAT_HE_AAC_V2: return "he-aac-v2";
+    case AUDIO_FORMAT_VORBIS: return "vorbis";
+    default:
+        break;
+    }
+    return "unknown";
+}
+
 static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
 {
     const hw_module_t *mod;
@@ -286,10 +307,10 @@
     }
 
     result.append("Global session refs:\n");
-    result.append(" session pid count\n");
+    result.append("  session   pid count\n");
     for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
         AudioSessionRef *r = mAudioSessionRefs[i];
-        snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
+        snprintf(buffer, SIZE, "  %7d %5d %5d\n", r->mSessionid, r->mPid, r->mCnt);
         result.append(buffer);
     }
     write(fd, result.string(), result.size());
@@ -508,7 +529,7 @@
     // client is responsible for conversion of 8-bit PCM to 16-bit PCM,
     // and we don't yet support 8.24 or 32-bit PCM
     if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) {
-        ALOGE("createTrack() invalid format %d", format);
+        ALOGE("createTrack() invalid format %#x", format);
         lStatus = BAD_VALUE;
         goto Exit;
     }
@@ -1091,7 +1112,7 @@
     return ret;
 }
 
-status_t AudioFlinger::getRenderPosition(size_t *halFrames, size_t *dspFrames,
+status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
         audio_io_handle_t output) const
 {
     status_t status;
@@ -1299,7 +1320,7 @@
     }
 
     if (format != AUDIO_FORMAT_PCM_16_BIT) {
-        ALOGE("openRecord() invalid format %d", format);
+        ALOGE("openRecord() invalid format %#x", format);
         lStatus = BAD_VALUE;
         goto Exit;
     }
@@ -1746,7 +1767,7 @@
     audio_stream_in_t *inStream = NULL;
     status_t status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
                                         &inStream);
-    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "
+    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %#x, Channels %x, "
             "status %d",
             inStream,
             config.sample_rate,
@@ -1908,18 +1929,21 @@
     return nextUniqueId();
 }
 
-void AudioFlinger::acquireAudioSessionId(int audioSession)
+void AudioFlinger::acquireAudioSessionId(int audioSession, pid_t pid)
 {
     Mutex::Autolock _l(mLock);
     pid_t caller = IPCThreadState::self()->getCallingPid();
-    ALOGV("acquiring %d from %d", audioSession, caller);
+    ALOGV("acquiring %d from %d, for %d", audioSession, caller, pid);
+    if (pid != -1 && (caller == getpid_cached)) {
+        caller = pid;
+    }
 
     // Ignore requests received from processes not known as notification client. The request
     // is likely proxied by mediaserver (e.g CameraService) and releaseAudioSessionId() can be
     // called from a different pid leaving a stale session reference.  Also we don't know how
     // to clear this reference if the client process dies.
     if (mNotificationClients.indexOfKey(caller) < 0) {
-        ALOGV("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
+        ALOGW("acquireAudioSessionId() unknown client %d for session %d", caller, audioSession);
         return;
     }
 
@@ -1936,11 +1960,14 @@
     ALOGV(" added new entry for %d", audioSession);
 }
 
-void AudioFlinger::releaseAudioSessionId(int audioSession)
+void AudioFlinger::releaseAudioSessionId(int audioSession, pid_t pid)
 {
     Mutex::Autolock _l(mLock);
     pid_t caller = IPCThreadState::self()->getCallingPid();
-    ALOGV("releasing %d from %d", audioSession, caller);
+    ALOGV("releasing %d from %d for %d", audioSession, caller, pid);
+    if (pid != -1 && (caller == getpid_cached)) {
+        caller = pid;
+    }
     size_t num = mAudioSessionRefs.size();
     for (size_t i = 0; i< num; i++) {
         AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index e0d1404..4799beb 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -60,8 +60,8 @@
 
 namespace android {
 
-class audio_track_cblk_t;
-class effect_param_cblk_t;
+struct audio_track_cblk_t;
+struct effect_param_cblk_t;
 class AudioMixer;
 class AudioBuffer;
 class AudioResampler;
@@ -186,16 +186,16 @@
 
     virtual status_t setVoiceVolume(float volume);
 
-    virtual status_t getRenderPosition(size_t *halFrames, size_t *dspFrames,
+    virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
                                        audio_io_handle_t output) const;
 
     virtual uint32_t getInputFramesLost(audio_io_handle_t ioHandle) const;
 
     virtual int newAudioSessionId();
 
-    virtual void acquireAudioSessionId(int audioSession);
+    virtual void acquireAudioSessionId(int audioSession, pid_t pid);
 
-    virtual void releaseAudioSessionId(int audioSession);
+    virtual void releaseAudioSessionId(int audioSession, pid_t pid);
 
     virtual status_t queryNumberEffects(uint32_t *numEffects) const;
 
@@ -655,6 +655,8 @@
 
 #undef INCLUDING_FROM_AUDIOFLINGER_H
 
+const char *formatToString(audio_format_t format);
+
 // ----------------------------------------------------------------------------
 
 }; // namespace android
diff --git a/services/audioflinger/AudioMixer.cpp b/services/audioflinger/AudioMixer.cpp
index f2af9b2..67d83b1 100644
--- a/services/audioflinger/AudioMixer.cpp
+++ b/services/audioflinger/AudioMixer.cpp
@@ -398,15 +398,16 @@
     ALOG_ASSERT(uint32_t(name) < MAX_NUM_TRACKS, "bad track name %d", name);
     track_t& track = mState.tracks[name];
 
-    int valueInt = (int)value;
-    int32_t *valueBuf = (int32_t *)value;
+    int valueInt = static_cast<int>(reinterpret_cast<uintptr_t>(value));
+    int32_t *valueBuf = reinterpret_cast<int32_t*>(value);
 
     switch (target) {
 
     case TRACK:
         switch (param) {
         case CHANNEL_MASK: {
-            audio_channel_mask_t mask = (audio_channel_mask_t) value;
+            audio_channel_mask_t mask =
+                static_cast<audio_channel_mask_t>(reinterpret_cast<uintptr_t>(value));
             if (track.channelMask != mask) {
                 uint32_t channelCount = popcount(mask);
                 ALOG_ASSERT((channelCount <= MAX_NUM_CHANNELS_TO_DOWNMIX) && channelCount);
diff --git a/services/audioflinger/AudioMixer.h b/services/audioflinger/AudioMixer.h
index d5c9da7..d286986 100644
--- a/services/audioflinger/AudioMixer.h
+++ b/services/audioflinger/AudioMixer.h
@@ -216,7 +216,7 @@
         NBLog::Writer*  mLog;
         int32_t         reserved[1];
         // FIXME allocate dynamically to save some memory when maxNumTracks < MAX_NUM_TRACKS
-        track_t         tracks[MAX_NUM_TRACKS]; __attribute__((aligned(32)));
+        track_t         tracks[MAX_NUM_TRACKS] __attribute__((aligned(32)));
     };
 
     // AudioBufferProvider that wraps a track AudioBufferProvider by a call to a downmix effect
diff --git a/services/audioflinger/AudioPolicyService.cpp b/services/audioflinger/AudioPolicyService.cpp
index 03a5390..9980344 100644
--- a/services/audioflinger/AudioPolicyService.cpp
+++ b/services/audioflinger/AudioPolicyService.cpp
@@ -1672,24 +1672,24 @@
 
 namespace {
     struct audio_policy_service_ops aps_ops = {
-        open_output           : aps_open_output,
-        open_duplicate_output : aps_open_dup_output,
-        close_output          : aps_close_output,
-        suspend_output        : aps_suspend_output,
-        restore_output        : aps_restore_output,
-        open_input            : aps_open_input,
-        close_input           : aps_close_input,
-        set_stream_volume     : aps_set_stream_volume,
-        set_stream_output     : aps_set_stream_output,
-        set_parameters        : aps_set_parameters,
-        get_parameters        : aps_get_parameters,
-        start_tone            : aps_start_tone,
-        stop_tone             : aps_stop_tone,
-        set_voice_volume      : aps_set_voice_volume,
-        move_effects          : aps_move_effects,
-        load_hw_module        : aps_load_hw_module,
-        open_output_on_module : aps_open_output_on_module,
-        open_input_on_module  : aps_open_input_on_module,
+        .open_output           = aps_open_output,
+        .open_duplicate_output = aps_open_dup_output,
+        .close_output          = aps_close_output,
+        .suspend_output        = aps_suspend_output,
+        .restore_output        = aps_restore_output,
+        .open_input            = aps_open_input,
+        .close_input           = aps_close_input,
+        .set_stream_volume     = aps_set_stream_volume,
+        .set_stream_output     = aps_set_stream_output,
+        .set_parameters        = aps_set_parameters,
+        .get_parameters        = aps_get_parameters,
+        .start_tone            = aps_start_tone,
+        .stop_tone             = aps_stop_tone,
+        .set_voice_volume      = aps_set_voice_volume,
+        .move_effects          = aps_move_effects,
+        .load_hw_module        = aps_load_hw_module,
+        .open_output_on_module = aps_open_output_on_module,
+        .open_input_on_module  = aps_open_input_on_module,
     };
 }; // namespace <unnamed>
 
diff --git a/services/audioflinger/AudioResampler.cpp b/services/audioflinger/AudioResampler.cpp
index 07574ab..b206116 100644
--- a/services/audioflinger/AudioResampler.cpp
+++ b/services/audioflinger/AudioResampler.cpp
@@ -78,6 +78,9 @@
     int mX0R;
 };
 
+/*static*/
+const double AudioResampler::kPhaseMultiplier = 1L << AudioResampler::kNumPhaseBits;
+
 bool AudioResampler::qualityIsSupported(src_quality quality)
 {
     switch (quality) {
diff --git a/services/audioflinger/AudioResampler.h b/services/audioflinger/AudioResampler.h
index c341325..dc33f29 100644
--- a/services/audioflinger/AudioResampler.h
+++ b/services/audioflinger/AudioResampler.h
@@ -84,7 +84,7 @@
     static const uint32_t kPhaseMask = (1LU<<kNumPhaseBits)-1;
 
     // multiplier to calculate fixed point phase increment
-    static const double kPhaseMultiplier = 1L << kNumPhaseBits;
+    static const double kPhaseMultiplier;
 
     AudioResampler(int bitDepth, int inChannelCount, int32_t sampleRate, src_quality quality);
 
diff --git a/services/audioflinger/AudioResamplerDyn.cpp b/services/audioflinger/AudioResamplerDyn.cpp
index cd67df5..54c2309 100644
--- a/services/audioflinger/AudioResamplerDyn.cpp
+++ b/services/audioflinger/AudioResamplerDyn.cpp
@@ -283,17 +283,25 @@
             // 32b coefficients, 64 length
             useS32 = true;
             stopBandAtten = 98.;
-            halfLength = 32;
+            if (inSampleRate >= mSampleRate * 4) {
+                halfLength = 48;
+            } else if (inSampleRate >= mSampleRate * 2) {
+                halfLength = 40;
+            } else {
+                halfLength = 32;
+            }
         } else if (mFilterQuality == DYN_LOW_QUALITY) {
             // 16b coefficients, 16-32 length
             useS32 = false;
             stopBandAtten = 80.;
-            if (mSampleRate >= inSampleRate * 2) {
+            if (inSampleRate >= mSampleRate * 4) {
+                halfLength = 24;
+            } else if (inSampleRate >= mSampleRate * 2) {
                 halfLength = 16;
             } else {
                 halfLength = 8;
             }
-            if (mSampleRate >= inSampleRate) {
+            if (inSampleRate <= mSampleRate) {
                 tbwCheat = 1.05;
             } else {
                 tbwCheat = 1.03;
@@ -303,14 +311,14 @@
             // note: > 64 length filters with 16b coefs can have quantization noise problems
             useS32 = false;
             stopBandAtten = 84.;
-            if (mSampleRate >= inSampleRate * 4) {
+            if (inSampleRate >= mSampleRate * 4) {
                 halfLength = 32;
-            } else if (mSampleRate >= inSampleRate * 2) {
+            } else if (inSampleRate >= mSampleRate * 2) {
                 halfLength = 24;
             } else {
                 halfLength = 16;
             }
-            if (mSampleRate >= inSampleRate) {
+            if (inSampleRate <= mSampleRate) {
                 tbwCheat = 1.03;
             } else {
                 tbwCheat = 1.01;
diff --git a/services/audioflinger/Configuration.h b/services/audioflinger/Configuration.h
index bc2038a..0754d9d 100644
--- a/services/audioflinger/Configuration.h
+++ b/services/audioflinger/Configuration.h
@@ -32,9 +32,6 @@
 // uncomment to enable fast mixer to take performance samples for later statistical analysis
 #define FAST_MIXER_STATISTICS
 
-// uncomment to allow fast tracks at non-native sample rate
-//#define FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
-
 // uncomment for debugging timing problems related to StateQueue::push()
 //#define STATE_QUEUE_DUMP
 
diff --git a/services/audioflinger/Effects.cpp b/services/audioflinger/Effects.cpp
index 537c076..29b56db 100644
--- a/services/audioflinger/Effects.cpp
+++ b/services/audioflinger/Effects.cpp
@@ -805,6 +805,111 @@
     return mOffloaded;
 }
 
+String8 effectFlagsToString(uint32_t flags) {
+    String8 s;
+
+    s.append("conn. mode: ");
+    switch (flags & EFFECT_FLAG_TYPE_MASK) {
+    case EFFECT_FLAG_TYPE_INSERT: s.append("insert"); break;
+    case EFFECT_FLAG_TYPE_AUXILIARY: s.append("auxiliary"); break;
+    case EFFECT_FLAG_TYPE_REPLACE: s.append("replace"); break;
+    case EFFECT_FLAG_TYPE_PRE_PROC: s.append("preproc"); break;
+    case EFFECT_FLAG_TYPE_POST_PROC: s.append("postproc"); break;
+    default: s.append("unknown/reserved"); break;
+    }
+    s.append(", ");
+
+    s.append("insert pref: ");
+    switch (flags & EFFECT_FLAG_INSERT_MASK) {
+    case EFFECT_FLAG_INSERT_ANY: s.append("any"); break;
+    case EFFECT_FLAG_INSERT_FIRST: s.append("first"); break;
+    case EFFECT_FLAG_INSERT_LAST: s.append("last"); break;
+    case EFFECT_FLAG_INSERT_EXCLUSIVE: s.append("exclusive"); break;
+    default: s.append("unknown/reserved"); break;
+    }
+    s.append(", ");
+
+    s.append("volume mgmt: ");
+    switch (flags & EFFECT_FLAG_VOLUME_MASK) {
+    case EFFECT_FLAG_VOLUME_NONE: s.append("none"); break;
+    case EFFECT_FLAG_VOLUME_CTRL: s.append("implements control"); break;
+    case EFFECT_FLAG_VOLUME_IND: s.append("requires indication"); break;
+    default: s.append("unknown/reserved"); break;
+    }
+    s.append(", ");
+
+    uint32_t devind = flags & EFFECT_FLAG_DEVICE_MASK;
+    if (devind) {
+        s.append("device indication: ");
+        switch (devind) {
+        case EFFECT_FLAG_DEVICE_IND: s.append("requires updates"); break;
+        default: s.append("unknown/reserved"); break;
+        }
+        s.append(", ");
+    }
+
+    s.append("input mode: ");
+    switch (flags & EFFECT_FLAG_INPUT_MASK) {
+    case EFFECT_FLAG_INPUT_DIRECT: s.append("direct"); break;
+    case EFFECT_FLAG_INPUT_PROVIDER: s.append("provider"); break;
+    case EFFECT_FLAG_INPUT_BOTH: s.append("direct+provider"); break;
+    default: s.append("not set"); break;
+    }
+    s.append(", ");
+
+    s.append("output mode: ");
+    switch (flags & EFFECT_FLAG_OUTPUT_MASK) {
+    case EFFECT_FLAG_OUTPUT_DIRECT: s.append("direct"); break;
+    case EFFECT_FLAG_OUTPUT_PROVIDER: s.append("provider"); break;
+    case EFFECT_FLAG_OUTPUT_BOTH: s.append("direct+provider"); break;
+    default: s.append("not set"); break;
+    }
+    s.append(", ");
+
+    uint32_t accel = flags & EFFECT_FLAG_HW_ACC_MASK;
+    if (accel) {
+        s.append("hardware acceleration: ");
+        switch (accel) {
+        case EFFECT_FLAG_HW_ACC_SIMPLE: s.append("non-tunneled"); break;
+        case EFFECT_FLAG_HW_ACC_TUNNEL: s.append("tunneled"); break;
+        default: s.append("unknown/reserved"); break;
+        }
+        s.append(", ");
+    }
+
+    uint32_t modeind = flags & EFFECT_FLAG_AUDIO_MODE_MASK;
+    if (modeind) {
+        s.append("mode indication: ");
+        switch (modeind) {
+        case EFFECT_FLAG_AUDIO_MODE_IND: s.append("required"); break;
+        default: s.append("unknown/reserved"); break;
+        }
+        s.append(", ");
+    }
+
+    uint32_t srcind = flags & EFFECT_FLAG_AUDIO_SOURCE_MASK;
+    if (srcind) {
+        s.append("source indication: ");
+        switch (srcind) {
+        case EFFECT_FLAG_AUDIO_SOURCE_IND: s.append("required"); break;
+        default: s.append("unknown/reserved"); break;
+        }
+        s.append(", ");
+    }
+
+    if (flags & EFFECT_FLAG_OFFLOAD_MASK) {
+        s.append("offloadable, ");
+    }
+
+    int len = s.length();
+    if (s.length() > 2) {
+        char *str = s.lockBuffer(len);
+        s.unlockBuffer(len - 2);
+    }
+    return s;
+}
+
+
 void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args __unused)
 {
     const size_t SIZE = 256;
@@ -821,8 +926,8 @@
     }
 
     result.append("\t\tSession Status State Engine:\n");
-    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
-            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
+    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   %p\n",
+            mSessionId, mStatus, mState, mEffectInterface);
     result.append(buffer);
 
     result.append("\t\tDescriptor:\n");
@@ -839,9 +944,10 @@
                     mDescriptor.type.node[2],
                 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
     result.append(buffer);
-    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
+    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X (%s)\n",
             mDescriptor.apiVersion,
-            mDescriptor.flags);
+            mDescriptor.flags,
+            effectFlagsToString(mDescriptor.flags).string());
     result.append(buffer);
     snprintf(buffer, SIZE, "\t\t- name: %s\n",
             mDescriptor.name);
@@ -851,38 +957,38 @@
     result.append(buffer);
 
     result.append("\t\t- Input configuration:\n");
-    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
-    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
-            (uint32_t)mConfig.inputCfg.buffer.raw,
+    result.append("\t\t\tFrames  Smp rate Channels Format Buffer\n");
+    snprintf(buffer, SIZE, "\t\t\t%05zu   %05d    %08x %6d (%s) %p\n",
             mConfig.inputCfg.buffer.frameCount,
             mConfig.inputCfg.samplingRate,
             mConfig.inputCfg.channels,
-            mConfig.inputCfg.format);
+            mConfig.inputCfg.format,
+            formatToString((audio_format_t)mConfig.inputCfg.format),
+            mConfig.inputCfg.buffer.raw);
     result.append(buffer);
 
     result.append("\t\t- Output configuration:\n");
     result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
-    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
-            (uint32_t)mConfig.outputCfg.buffer.raw,
+    snprintf(buffer, SIZE, "\t\t\t%p %05zu   %05d    %08x %d (%s)\n",
+            mConfig.outputCfg.buffer.raw,
             mConfig.outputCfg.buffer.frameCount,
             mConfig.outputCfg.samplingRate,
             mConfig.outputCfg.channels,
-            mConfig.outputCfg.format);
+            mConfig.outputCfg.format,
+            formatToString((audio_format_t)mConfig.outputCfg.format));
     result.append(buffer);
 
-    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
+    snprintf(buffer, SIZE, "\t\t%zu Clients:\n", mHandles.size());
     result.append(buffer);
-    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
+    result.append("\t\t\t  Pid Priority Ctrl Locked client server\n");
     for (size_t i = 0; i < mHandles.size(); ++i) {
         EffectHandle *handle = mHandles[i];
         if (handle != NULL && !handle->destroyed_l()) {
-            handle->dump(buffer, SIZE);
+            handle->dumpToBuffer(buffer, SIZE);
             result.append(buffer);
         }
     }
 
-    result.append("\n");
-
     write(fd, result.string(), result.length());
 
     if (locked) {
@@ -1182,15 +1288,15 @@
 }
 
 
-void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
+void AudioFlinger::EffectHandle::dumpToBuffer(char* buffer, size_t size)
 {
     bool locked = mCblk != NULL && AudioFlinger::dumpTryLock(mCblk->lock);
 
-    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
+    snprintf(buffer, size, "\t\t\t%5d    %5d  %3s    %3s  %5u  %5u\n",
             (mClient == 0) ? getpid_cached : mClient->pid(),
             mPriority,
-            mHasControl,
-            !locked,
+            mHasControl ? "yes" : "no",
+            locked ? "yes" : "no",
             mCblk ? mCblk->clientIndex : 0,
             mCblk ? mCblk->serverIndex : 0
             );
@@ -1571,33 +1677,35 @@
     char buffer[SIZE];
     String8 result;
 
-    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
+    size_t numEffects = mEffects.size();
+    snprintf(buffer, SIZE, "    %d effects for session %d\n", numEffects, mSessionId);
     result.append(buffer);
 
-    bool locked = AudioFlinger::dumpTryLock(mLock);
-    // failed to lock - AudioFlinger is probably deadlocked
-    if (!locked) {
-        result.append("\tCould not lock mutex:\n");
-    }
-
-    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
-    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
-            mEffects.size(),
-            (uint32_t)mInBuffer,
-            (uint32_t)mOutBuffer,
-            mActiveTrackCnt);
-    result.append(buffer);
-    write(fd, result.string(), result.size());
-
-    for (size_t i = 0; i < mEffects.size(); ++i) {
-        sp<EffectModule> effect = mEffects[i];
-        if (effect != 0) {
-            effect->dump(fd, args);
+    if (numEffects) {
+        bool locked = AudioFlinger::dumpTryLock(mLock);
+        // failed to lock - AudioFlinger is probably deadlocked
+        if (!locked) {
+            result.append("\tCould not lock mutex:\n");
         }
-    }
 
-    if (locked) {
-        mLock.unlock();
+        result.append("\tIn buffer   Out buffer   Active tracks:\n");
+        snprintf(buffer, SIZE, "\t%p  %p   %d\n",
+                mInBuffer,
+                mOutBuffer,
+                mActiveTrackCnt);
+        result.append(buffer);
+        write(fd, result.string(), result.size());
+
+        for (size_t i = 0; i < numEffects; ++i) {
+            sp<EffectModule> effect = mEffects[i];
+            if (effect != 0) {
+                effect->dump(fd, args);
+            }
+        }
+
+        if (locked) {
+            mLock.unlock();
+        }
     }
 }
 
diff --git a/services/audioflinger/Effects.h b/services/audioflinger/Effects.h
index 50535a2..ccc4825 100644
--- a/services/audioflinger/Effects.h
+++ b/services/audioflinger/Effects.h
@@ -209,7 +209,7 @@
     // destroyed_l() must be called with the associated EffectModule mLock held
     bool destroyed_l() const { return mDestroyed; }
 
-    void dump(char* buffer, size_t size);
+    void dumpToBuffer(char* buffer, size_t size);
 
 protected:
     friend class AudioFlinger;          // for mEffect, mHasControl, mEnabled
diff --git a/services/audioflinger/FastMixer.cpp b/services/audioflinger/FastMixer.cpp
index 28b9d77..90122e0 100644
--- a/services/audioflinger/FastMixer.cpp
+++ b/services/audioflinger/FastMixer.cpp
@@ -236,7 +236,6 @@
                     sampleRate = Format_sampleRate(format);
                     ALOG_ASSERT(Format_channelCount(format) == FCC_2);
                 }
-                dumpState->mSampleRate = sampleRate;
             }
 
             if ((!Format_isEqual(format, previousFormat)) || (frameCount != previous->mFrameCount)) {
@@ -321,12 +320,8 @@
                         mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
                                 (void *) mixBuffer);
                         // newly allocated track names default to full scale volume
-                        if (fastTrack->mSampleRate != 0 && fastTrack->mSampleRate != sampleRate) {
-                            mixer->setParameter(name, AudioMixer::RESAMPLE,
-                                    AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
-                        }
                         mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
-                                (void *) fastTrack->mChannelMask);
+                                (void *)(uintptr_t)fastTrack->mChannelMask);
                         mixer->enable(name);
                     }
                     generations[i] = fastTrack->mGeneration;
@@ -353,16 +348,10 @@
                                 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
                                         (void *)0x1000);
                             }
-                            if (fastTrack->mSampleRate != 0 &&
-                                    fastTrack->mSampleRate != sampleRate) {
-                                mixer->setParameter(name, AudioMixer::RESAMPLE,
-                                        AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
-                            } else {
-                                mixer->setParameter(name, AudioMixer::RESAMPLE,
-                                        AudioMixer::REMOVE, NULL);
-                            }
+                            mixer->setParameter(name, AudioMixer::RESAMPLE,
+                                    AudioMixer::REMOVE, NULL);
                             mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
-                                    (void *) fastTrack->mChannelMask);
+                                    (void *)(uintptr_t) fastTrack->mChannelMask);
                             // already enabled
                         }
                         generations[i] = fastTrack->mGeneration;
@@ -392,16 +381,8 @@
 
                 // Refresh the per-track timestamp
                 if (timestampStatus == NO_ERROR) {
-                    uint32_t trackFramesWrittenButNotPresented;
-                    uint32_t trackSampleRate = fastTrack->mSampleRate;
-                    // There is currently no sample rate conversion for fast tracks currently
-                    if (trackSampleRate != 0 && trackSampleRate != sampleRate) {
-                        trackFramesWrittenButNotPresented =
-                                ((int64_t) nativeFramesWrittenButNotPresented * trackSampleRate) /
-                                sampleRate;
-                    } else {
-                        trackFramesWrittenButNotPresented = nativeFramesWrittenButNotPresented;
-                    }
+                    uint32_t trackFramesWrittenButNotPresented =
+                        nativeFramesWrittenButNotPresented;
                     uint32_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
                     // Can't provide an AudioTimestamp before first frame presented,
                     // or during the brief 32-bit wraparound window
@@ -419,9 +400,9 @@
                 if (fastTrack->mVolumeProvider != NULL) {
                     uint32_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
                     mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
-                            (void *)(vlr & 0xFFFF));
+                            (void *)(uintptr_t)(vlr & 0xFFFF));
                     mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
-                            (void *)(vlr >> 16));
+                            (void *)(uintptr_t)(vlr >> 16));
                 }
                 // FIXME The current implementation of framesReady() for fast tracks
                 // takes a tryLock, which can block
@@ -715,7 +696,7 @@
 void FastMixerDumpState::dump(int fd) const
 {
     if (mCommand == FastMixerState::INITIAL) {
-        fdprintf(fd, "FastMixer not initialized\n");
+        fdprintf(fd, "  FastMixer not initialized\n");
         return;
     }
 #define COMMAND_MAX 32
@@ -749,10 +730,10 @@
     double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
             (mMeasuredWarmupTs.tv_nsec / 1000000.0);
     double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
-    fdprintf(fd, "FastMixer command=%s writeSequence=%u framesWritten=%u\n"
-                 "          numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
-                 "          sampleRate=%u frameCount=%u measuredWarmup=%.3g ms, warmupCycles=%u\n"
-                 "          mixPeriod=%.2f ms\n",
+    fdprintf(fd, "  FastMixer command=%s writeSequence=%u framesWritten=%u\n"
+                 "            numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
+                 "            sampleRate=%u frameCount=%zu measuredWarmup=%.3g ms, warmupCycles=%u\n"
+                 "            mixPeriod=%.2f ms\n",
                  string, mWriteSequence, mFramesWritten,
                  mNumTracks, mWriteErrors, mUnderruns, mOverruns,
                  mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
@@ -803,14 +784,20 @@
         previousCpukHz = sampleCpukHz;
 #endif
     }
-    fdprintf(fd, "Simple moving statistics over last %.1f seconds:\n", wall.n() * mixPeriodSec);
-    fdprintf(fd, "  wall clock time in ms per mix cycle:\n"
-                 "    mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
-                 wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6, wall.stddev()*1e-6);
-    fdprintf(fd, "  raw CPU load in us per mix cycle:\n"
-                 "    mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
-                 loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
-                 loadNs.stddev()*1e-3);
+    if (n) {
+        fdprintf(fd, "  Simple moving statistics over last %.1f seconds:\n",
+                     wall.n() * mixPeriodSec);
+        fdprintf(fd, "    wall clock time in ms per mix cycle:\n"
+                     "      mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
+                     wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6,
+                     wall.stddev()*1e-6);
+        fdprintf(fd, "    raw CPU load in us per mix cycle:\n"
+                     "      mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
+                     loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
+                     loadNs.stddev()*1e-3);
+    } else {
+        fdprintf(fd, "  No FastMixer statistics available currently\n");
+    }
 #ifdef CPU_FREQUENCY_STATISTICS
     fdprintf(fd, "  CPU clock frequency in MHz:\n"
                  "    mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
@@ -828,9 +815,9 @@
             left.sample(tail[i]);
             right.sample(tail[n - (i + 1)]);
         }
-        fdprintf(fd, "Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
-                     "  left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
-                     "  right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
+        fdprintf(fd, "  Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
+                     "    left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
+                     "    right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
                      left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6,
                      right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6,
                      right.stddev()*1e-6);
@@ -843,9 +830,9 @@
     // Instead we always display all tracks, with an indication
     // of whether we think the track is active.
     uint32_t trackMask = mTrackMask;
-    fdprintf(fd, "Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
+    fdprintf(fd, "  Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
             FastMixerState::kMaxFastTracks, trackMask);
-    fdprintf(fd, "Index Active Full Partial Empty  Recent Ready\n");
+    fdprintf(fd, "  Index Active Full Partial Empty  Recent Ready\n");
     for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) {
         bool isActive = trackMask & 1;
         const FastTrackDump *ftDump = &mTracks[i];
@@ -865,7 +852,7 @@
             mostRecent = "?";
             break;
         }
-        fdprintf(fd, "%5u %6s %4u %7u %5u %7s %5u\n", i, isActive ? "yes" : "no",
+        fdprintf(fd, "  %5u %6s %4u %7u %5u %7s %5zu\n", i, isActive ? "yes" : "no",
                 (underruns.mBitFields.mFull) & UNDERRUN_MASK,
                 (underruns.mBitFields.mPartial) & UNDERRUN_MASK,
                 (underruns.mBitFields.mEmpty) & UNDERRUN_MASK,
diff --git a/services/audioflinger/FastMixerState.cpp b/services/audioflinger/FastMixerState.cpp
index 737de97..43ff233 100644
--- a/services/audioflinger/FastMixerState.cpp
+++ b/services/audioflinger/FastMixerState.cpp
@@ -20,7 +20,7 @@
 namespace android {
 
 FastTrack::FastTrack() :
-    mBufferProvider(NULL), mVolumeProvider(NULL), mSampleRate(0),
+    mBufferProvider(NULL), mVolumeProvider(NULL),
     mChannelMask(AUDIO_CHANNEL_OUT_STEREO), mGeneration(0)
 {
 }
diff --git a/services/audioflinger/FastMixerState.h b/services/audioflinger/FastMixerState.h
index f6e7903..9739fe9 100644
--- a/services/audioflinger/FastMixerState.h
+++ b/services/audioflinger/FastMixerState.h
@@ -43,7 +43,6 @@
 
     ExtendedAudioBufferProvider* mBufferProvider; // must be NULL if inactive, or non-NULL if active
     VolumeProvider*         mVolumeProvider; // optional; if NULL then full-scale
-    unsigned                mSampleRate;     // optional; if zero then use mixer sample rate
     audio_channel_mask_t    mChannelMask;    // AUDIO_CHANNEL_OUT_MONO or AUDIO_CHANNEL_OUT_STEREO
     int                     mGeneration;     // increment when any field is assigned
 };
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index 6600161..b5e763d 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -37,7 +37,7 @@
     virtual status_t    initCheck() const;
 
     static  void        appendDumpHeader(String8& result);
-            void        dump(char* buffer, size_t size);
+            void        dump(char* buffer, size_t size, bool active);
     virtual status_t    start(AudioSystem::sync_event_t event =
                                     AudioSystem::SYNC_EVENT_NONE,
                              int triggerSession = 0);
diff --git a/services/audioflinger/RecordTracks.h b/services/audioflinger/RecordTracks.h
index 5ef6f58..fc3171f 100644
--- a/services/audioflinger/RecordTracks.h
+++ b/services/audioflinger/RecordTracks.h
@@ -45,7 +45,7 @@
                                                 return tmp; }
 
     static  void        appendDumpHeader(String8& result);
-            void        dump(char* buffer, size_t size);
+            void        dump(char* buffer, size_t size, bool active);
 
 private:
     friend class AudioFlinger;  // for mState
diff --git a/services/audioflinger/StateQueue.cpp b/services/audioflinger/StateQueue.cpp
index c2d3bbd..48399c0 100644
--- a/services/audioflinger/StateQueue.cpp
+++ b/services/audioflinger/StateQueue.cpp
@@ -58,7 +58,11 @@
 
 template<typename T> const T* StateQueue<T>::poll()
 {
+#ifdef __LP64__
+    const T *next = (const T *) android_atomic_acquire_load64((volatile int64_t *) &mNext);
+#else
     const T *next = (const T *) android_atomic_acquire_load((volatile int32_t *) &mNext);
+#endif
     if (next != mCurrent) {
         mAck = next;    // no additional barrier needed
         mCurrent = next;
@@ -140,7 +144,11 @@
         }
 
         // publish
+#ifdef __LP64__
+        android_atomic_release_store64((int64_t) mMutating, (volatile int64_t *) &mNext);
+#else
         android_atomic_release_store((int32_t) mMutating, (volatile int32_t *) &mNext);
+#endif
         mExpecting = mMutating;
 
         // copy with circular wraparound
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index 7751b08..b064e89 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -425,6 +425,53 @@
     }
 }
 
+String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
+    String8 s;
+    if (output) {
+        if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
+        if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
+        if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
+        if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
+        if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
+        if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
+        if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
+        if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
+        if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
+        if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
+        if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
+        if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
+        if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
+        if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
+        if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
+        if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
+        if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
+        if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
+        if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown,  ");
+    } else {
+        if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
+        if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
+        if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
+        if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
+        if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
+        if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
+        if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
+        if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
+        if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
+        if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
+        if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
+        if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
+        if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
+        if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
+        if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown,  ");
+    }
+    int len = s.length();
+    if (s.length() > 2) {
+        char *str = s.lockBuffer(len);
+        s.unlockBuffer(len - 2);
+    }
+    return s;
+}
+
 void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
 {
     const size_t SIZE = 256;
@@ -433,49 +480,43 @@
 
     bool locked = AudioFlinger::dumpTryLock(mLock);
     if (!locked) {
-        snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
-        write(fd, buffer, strlen(buffer));
+        fdprintf(fd, "thread %p maybe dead locked\n", this);
     }
 
-    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: %u\n", mSampleRate);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "HAL buffer size: %u bytes\n", mBufferSize);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "Channel Count: %u\n", mChannelCount);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "Format: %d\n", mFormat);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
-    result.append(buffer);
-
-    snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
-    result.append(buffer);
-    result.append(" Index Command");
-    for (size_t i = 0; i < mNewParameters.size(); ++i) {
-        snprintf(buffer, SIZE, "\n %02d    ", i);
-        result.append(buffer);
-        result.append(mNewParameters[i]);
+    fdprintf(fd, "  I/O handle: %d\n", mId);
+    fdprintf(fd, "  TID: %d\n", getTid());
+    fdprintf(fd, "  Standby: %s\n", mStandby ? "yes" : "no");
+    fdprintf(fd, "  Sample rate: %u\n", mSampleRate);
+    fdprintf(fd, "  HAL frame count: %zu\n", mFrameCount);
+    fdprintf(fd, "  HAL buffer size: %u bytes\n", mBufferSize);
+    fdprintf(fd, "  Channel Count: %u\n", mChannelCount);
+    fdprintf(fd, "  Channel Mask: 0x%08x (%s)\n", mChannelMask,
+            channelMaskToString(mChannelMask, mType != RECORD).string());
+    fdprintf(fd, "  Format: 0x%x (%s)\n", mFormat, formatToString(mFormat));
+    fdprintf(fd, "  Frame size: %zu\n", mFrameSize);
+    fdprintf(fd, "  Pending setParameters commands:");
+    size_t numParams = mNewParameters.size();
+    if (numParams) {
+        fdprintf(fd, "\n   Index Command");
+        for (size_t i = 0; i < numParams; ++i) {
+            fdprintf(fd, "\n   %02zu    ", i);
+            fdprintf(fd, mNewParameters[i]);
+        }
+        fdprintf(fd, "\n");
+    } else {
+        fdprintf(fd, " none\n");
     }
-
-    snprintf(buffer, SIZE, "\n\nPending config events: \n");
-    result.append(buffer);
-    for (size_t i = 0; i < mConfigEvents.size(); i++) {
-        mConfigEvents[i]->dump(buffer, SIZE);
-        result.append(buffer);
+    fdprintf(fd, "  Pending config events:");
+    size_t numConfig = mConfigEvents.size();
+    if (numConfig) {
+        for (size_t i = 0; i < numConfig; i++) {
+            mConfigEvents[i]->dump(buffer, SIZE);
+            fdprintf(fd, "\n    %s", buffer);
+        }
+        fdprintf(fd, "\n");
+    } else {
+        fdprintf(fd, " none\n");
     }
-    result.append("\n");
-
-    write(fd, result.string(), result.size());
 
     if (locked) {
         mLock.unlock();
@@ -488,10 +529,11 @@
     char buffer[SIZE];
     String8 result;
 
-    snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
+    size_t numEffectChains = mEffectChains.size();
+    snprintf(buffer, SIZE, "  %zu Effect Chains\n", numEffectChains);
     write(fd, buffer, strlen(buffer));
 
-    for (size_t i = 0; i < mEffectChains.size(); ++i) {
+    for (size_t i = 0; i < numEffectChains; ++i) {
         sp<EffectChain> chain = mEffectChains[i];
         if (chain != 0) {
             chain->dump(fd, args);
@@ -1098,7 +1140,7 @@
     char buffer[SIZE];
     String8 result;
 
-    result.appendFormat("Output thread %p stream volumes in dB:\n    ", this);
+    result.appendFormat("  Stream volumes in dB: ");
     for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
         const stream_type_t *st = &mStreamTypes[i];
         if (i > 0) {
@@ -1113,60 +1155,62 @@
     write(fd, result.string(), result.length());
     result.clear();
 
-    snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
-    result.append(buffer);
-    Track::appendDumpHeader(result);
-    for (size_t i = 0; i < mTracks.size(); ++i) {
-        sp<Track> track = mTracks[i];
-        if (track != 0) {
-            track->dump(buffer, SIZE);
-            result.append(buffer);
-        }
-    }
-
-    snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
-    result.append(buffer);
-    Track::appendDumpHeader(result);
-    for (size_t i = 0; i < mActiveTracks.size(); ++i) {
-        sp<Track> track = mActiveTracks[i].promote();
-        if (track != 0) {
-            track->dump(buffer, SIZE);
-            result.append(buffer);
-        }
-    }
-    write(fd, result.string(), result.size());
-
     // These values are "raw"; they will wrap around.  See prepareTracks_l() for a better way.
     FastTrackUnderruns underruns = getFastTrackUnderruns(0);
-    fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
+    fdprintf(fd, "  Normal mixer raw underrun counters: partial=%u empty=%u\n",
             underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
+
+    size_t numtracks = mTracks.size();
+    size_t numactive = mActiveTracks.size();
+    fdprintf(fd, "  %d Tracks", numtracks);
+    size_t numactiveseen = 0;
+    if (numtracks) {
+        fdprintf(fd, " of which %d are active\n", numactive);
+        Track::appendDumpHeader(result);
+        for (size_t i = 0; i < numtracks; ++i) {
+            sp<Track> track = mTracks[i];
+            if (track != 0) {
+                bool active = mActiveTracks.indexOf(track) >= 0;
+                if (active) {
+                    numactiveseen++;
+                }
+                track->dump(buffer, SIZE, active);
+                result.append(buffer);
+            }
+        }
+    } else {
+        result.append("\n");
+    }
+    if (numactiveseen != numactive) {
+        // some tracks in the active list were not in the tracks list
+        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
+                " not in the track list\n");
+        result.append(buffer);
+        Track::appendDumpHeader(result);
+        for (size_t i = 0; i < numactive; ++i) {
+            sp<Track> track = mActiveTracks[i].promote();
+            if (track != 0 && mTracks.indexOf(track) < 0) {
+                track->dump(buffer, SIZE, true);
+                result.append(buffer);
+            }
+        }
+    }
+
+    write(fd, result.string(), result.size());
+
 }
 
 void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
 {
-    const size_t SIZE = 256;
-    char buffer[SIZE];
-    String8 result;
-
-    snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
-            ns2ms(systemTime() - mLastWriteTime));
-    result.append(buffer);
-    snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
-    result.append(buffer);
-    snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
-    result.append(buffer);
-    write(fd, result.string(), result.size());
-    fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
+    fdprintf(fd, "\nOutput thread %p:\n", this);
+    fdprintf(fd, "  Normal frame count: %zu\n", mNormalFrameCount);
+    fdprintf(fd, "  Last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
+    fdprintf(fd, "  Total writes: %d\n", mNumWrites);
+    fdprintf(fd, "  Delayed writes: %d\n", mNumDelayedWrites);
+    fdprintf(fd, "  Blocked in write: %s\n", mInWrite ? "yes" : "no");
+    fdprintf(fd, "  Suspend count: %d\n", mSuspended);
+    fdprintf(fd, "  Mix buffer : %p\n", mMixBuffer);
+    fdprintf(fd, "  Fast track availMask=%#x\n", mFastTrackAvailMask);
 
     dumpBase(fd, args);
 }
@@ -1231,10 +1275,8 @@
             // mono or stereo
             ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
               (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
-#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
             // hardware sample rate
             (sampleRate == mSampleRate) &&
-#endif
             // normal mixer has an associated fast mixer
             hasFastMixer() &&
             // there are sufficient fast track slots available
@@ -1276,8 +1318,8 @@
     if (mType == DIRECT) {
         if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
             if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
-                ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
-                        "for output %p with format %d",
+                ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
+                        "for output %p with format %#x",
                         sampleRate, format, channelMask, mOutput, mFormat);
                 lStatus = BAD_VALUE;
                 goto Exit;
@@ -1285,16 +1327,16 @@
         }
     } else if (mType == OFFLOAD) {
         if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
-            ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
-                    "for output %p with format %d",
+            ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
+                    "for output %p with format %#x",
                     sampleRate, format, channelMask, mOutput, mFormat);
             lStatus = BAD_VALUE;
             goto Exit;
         }
     } else {
         if ((format & AUDIO_FORMAT_MAIN_MASK) != AUDIO_FORMAT_PCM) {
-                ALOGE("createTrack_l() Bad parameter: format %d \""
-                        "for output %p with format %d",
+                ALOGE("createTrack_l() Bad parameter: format %#x \""
+                        "for output %p with format %#x",
                         format, mOutput, mFormat);
                 lStatus = BAD_VALUE;
                 goto Exit;
@@ -1650,10 +1692,10 @@
     mChannelCount = popcount(mChannelMask);
     mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
     if (!audio_is_valid_format(mFormat)) {
-        LOG_FATAL("HAL format %d not valid for output", mFormat);
+        LOG_FATAL("HAL format %#x not valid for output", mFormat);
     }
     if ((mType == MIXER || mType == DUPLICATING) && mFormat != AUDIO_FORMAT_PCM_16_BIT) {
-        LOG_FATAL("HAL format %d not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
+        LOG_FATAL("HAL format %#x not supported for mixed output; must be AUDIO_FORMAT_PCM_16_BIT",
                 mFormat);
     }
     mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
@@ -1734,7 +1776,7 @@
 }
 
 
-status_t AudioFlinger::PlaybackThread::getRenderPosition(size_t *halFrames, size_t *dspFrames)
+status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
 {
     if (halFrames == NULL || dspFrames == NULL) {
         return BAD_VALUE;
@@ -1752,7 +1794,11 @@
         *dspFrames = framesWritten >= latencyFrames ? framesWritten - latencyFrames : 0;
         return NO_ERROR;
     } else {
-        return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
+        status_t status;
+        uint32_t frames;
+        status = mOutput->stream->get_render_position(mOutput->stream, &frames);
+        *dspFrames = (size_t)frames;
+        return status;
     }
 }
 
@@ -2989,7 +3035,6 @@
                     VolumeProvider *vp = track;
                     fastTrack->mBufferProvider = eabp;
                     fastTrack->mVolumeProvider = vp;
-                    fastTrack->mSampleRate = track->mSampleRate;
                     fastTrack->mChannelMask = track->mChannelMask;
                     fastTrack->mGeneration++;
                     state->mTrackMask |= 1 << j;
@@ -3168,9 +3213,9 @@
             mAudioMixer->setBufferProvider(name, track);
             mAudioMixer->enable(name);
 
-            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
-            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
-            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
+            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)(uintptr_t)vl);
+            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)(uintptr_t)vr);
+            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)(uintptr_t)va);
             mAudioMixer->setParameter(
                 name,
                 AudioMixer::TRACK,
@@ -3178,7 +3223,7 @@
             mAudioMixer->setParameter(
                 name,
                 AudioMixer::TRACK,
-                AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
+                AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
             // limit track sample rate to 2 x output sample rate, which changes at re-configuration
             uint32_t maxSampleRate = mSampleRate * 2;
             uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
@@ -3191,7 +3236,7 @@
                 name,
                 AudioMixer::RESAMPLE,
                 AudioMixer::SAMPLE_RATE,
-                (void *)reqSampleRate);
+                (void *)(uintptr_t)reqSampleRate);
             mAudioMixer->setParameter(
                 name,
                 AudioMixer::TRACK,
@@ -3485,9 +3530,7 @@
 
     PlaybackThread::dumpInternals(fd, args);
 
-    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
-    result.append(buffer);
-    write(fd, result.string(), result.size());
+    fdprintf(fd, "  AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
 
     // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
     const FastMixerDumpState copy(mFastMixerDumpState);
@@ -5105,30 +5148,18 @@
 
 void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
 {
-    const size_t SIZE = 256;
-    char buffer[SIZE];
-    String8 result;
-
-    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
-    result.append(buffer);
+    fdprintf(fd, "\nInput thread %p:\n", this);
 
     if (mActiveTracks.size() > 0) {
-        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
-        result.append(buffer);
-        snprintf(buffer, SIZE, "Buffer size: %u bytes\n", mBufferSize);
-        result.append(buffer);
-        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
-        result.append(buffer);
-        snprintf(buffer, SIZE, "Out channel count: %u\n", mReqChannelCount);
-        result.append(buffer);
-        snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
-        result.append(buffer);
+        fdprintf(fd, "  In index: %zu\n", mRsmpInIndex);
+        fdprintf(fd, "  Buffer size: %zu bytes\n", mBufferSize);
+        fdprintf(fd, "  Resampling: %d\n", (mResampler != NULL));
+        fdprintf(fd, "  Out channel count: %u\n", mReqChannelCount);
+        fdprintf(fd, "  Out sample rate: %u\n", mReqSampleRate);
     } else {
-        result.append("No active record client\n");
+        fdprintf(fd, "  No active record client\n");
     }
 
-    write(fd, result.string(), result.size());
-
     dumpBase(fd, args);
 }
 
@@ -5138,26 +5169,39 @@
     char buffer[SIZE];
     String8 result;
 
-    snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
-    result.append(buffer);
-    RecordTrack::appendDumpHeader(result);
-    for (size_t i = 0; i < mTracks.size(); ++i) {
-        sp<RecordTrack> track = mTracks[i];
-        if (track != 0) {
-            track->dump(buffer, SIZE);
-            result.append(buffer);
+    size_t numtracks = mTracks.size();
+    size_t numactive = mActiveTracks.size();
+    size_t numactiveseen = 0;
+    fdprintf(fd, "  %d Tracks", numtracks);
+    if (numtracks) {
+        fdprintf(fd, " of which %d are active\n", numactive);
+        RecordTrack::appendDumpHeader(result);
+        for (size_t i = 0; i < numtracks ; ++i) {
+            sp<RecordTrack> track = mTracks[i];
+            if (track != 0) {
+                bool active = mActiveTracks.indexOf(track) >= 0;
+                if (active) {
+                    numactiveseen++;
+                }
+                track->dump(buffer, SIZE, active);
+                result.append(buffer);
+            }
         }
+    } else {
+        fdprintf(fd, "\n");
     }
 
-    size_t size = mActiveTracks.size();
-    if (size > 0) {
-        snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
+    if (numactiveseen != numactive) {
+        snprintf(buffer, SIZE, "  The following tracks are in the active list but"
+                " not in the track list\n");
         result.append(buffer);
         RecordTrack::appendDumpHeader(result);
-        for (size_t i = 0; i < size; ++i) {
+        for (size_t i = 0; i < numactive; ++i) {
             sp<RecordTrack> track = mActiveTracks[i];
-            track->dump(buffer, SIZE);
-            result.append(buffer);
+            if (mTracks.indexOf(track) < 0) {
+                track->dump(buffer, SIZE, true);
+                result.append(buffer);
+            }
         }
 
     }
@@ -5380,7 +5424,7 @@
     mChannelCount = popcount(mChannelMask);
     mFormat = mInput->stream->common.get_format(&mInput->stream->common);
     if (mFormat != AUDIO_FORMAT_PCM_16_BIT) {
-        ALOGE("HAL format %d not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
+        ALOGE("HAL format %#x not supported; must be AUDIO_FORMAT_PCM_16_BIT", mFormat);
     }
     mFrameSize = audio_stream_frame_size(&mInput->stream->common);
     mBufferSize = mInput->stream->common.get_buffer_size(&mInput->stream->common);
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index f5b5efd..999fea3 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -449,7 +449,7 @@
 
     virtual     String8     getParameters(const String8& keys);
     virtual     void        audioConfigChanged_l(int event, int param = 0);
-                status_t    getRenderPosition(size_t *halFrames, size_t *dspFrames);
+                status_t    getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
                 int16_t     *mixBuffer() const { return mMixBuffer; };
 
     virtual     void detachAuxEffect_l(int effectId);
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index d1c6a06..e5152b8 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -435,17 +435,19 @@
 
 /*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
 {
-    result.append("   Name Client Type      Fmt Chn mask Session fCount S F SRate  "
+    result.append("    Name Active Client Type      Fmt Chn mask Session fCount S F SRate  "
                   "L dB  R dB    Server Main buf  Aux Buf Flags UndFrmCnt\n");
 }
 
-void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
+void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
 {
     uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
     if (isFastTrack()) {
-        sprintf(buffer, "   F %2d", mFastIndex);
+        sprintf(buffer, "    F %2d", mFastIndex);
+    } else if (mName >= AudioMixer::TRACK0) {
+        sprintf(buffer, "    %4d", mName - AudioMixer::TRACK0);
     } else {
-        sprintf(buffer, "   %4d", mName - AudioMixer::TRACK0);
+        sprintf(buffer, "    none");
     }
     track_state state = mState;
     char stateChar;
@@ -500,8 +502,9 @@
         nowInUnderrun = '?';
         break;
     }
-    snprintf(&buffer[7], size-7, " %6u %4u %08X %08X %7u %6u %1c %1d %5u %5.2g %5.2g  "
-                                 "%08X %08X %08X 0x%03X %9u%c\n",
+    snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g  "
+                                 "%08X %p %p 0x%03X %9u%c\n",
+            active ? "yes" : "no",
             (mClient == 0) ? getpid_cached : mClient->pid(),
             mStreamType,
             mFormat,
@@ -514,8 +517,8 @@
             20.0 * log10((vlr & 0xFFFF) / 4096.0),
             20.0 * log10((vlr >> 16) / 4096.0),
             mCblk->mServer,
-            (int)mMainBuffer,
-            (int)mAuxBuffer,
+            mMainBuffer,
+            mAuxBuffer,
             mCblk->mFlags,
             mAudioTrackServerProxy->getUnderrunFrames(),
             nowInUnderrun);
@@ -1865,12 +1868,13 @@
 
 /*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
 {
-    result.append("Client Fmt Chn mask Session S   Server fCount\n");
+    result.append("    Active Client Fmt Chn mask Session S   Server fCount\n");
 }
 
-void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
+void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
 {
-    snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
+    snprintf(buffer, size, "    %6s %6u %3u %08X %7u %1d %08X %6zu\n",
+            active ? "yes" : "no",
             (mClient == 0) ? getpid_cached : mClient->pid(),
             mFormat,
             mChannelMask,
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index dcea760..79fbf76 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -1043,13 +1043,13 @@
 // ----------------------------------------------------------------------------
 
 Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
-    return gCameraService->getClientLockById((int) user);
+    return gCameraService->getClientLockById((int)(intptr_t) user);
 }
 
 // Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
 // be acquired for this to be safe
 CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
-    BasicClient *basicClient = gCameraService->getClientByIdUnsafe((int) user);
+    BasicClient *basicClient = gCameraService->getClientByIdUnsafe((int)(intptr_t) user);
     // OK: only CameraClient calls this, and they already cast anyway.
     Client* client = static_cast<Client*>(basicClient);
 
diff --git a/services/camera/libcameraservice/api1/Camera2Client.cpp b/services/camera/libcameraservice/api1/Camera2Client.cpp
index 2bb3ff8..0a88a75 100644
--- a/services/camera/libcameraservice/api1/Camera2Client.cpp
+++ b/services/camera/libcameraservice/api1/Camera2Client.cpp
@@ -18,6 +18,7 @@
 #define ATRACE_TAG ATRACE_TAG_CAMERA
 //#define LOG_NDEBUG 0
 
+#include <inttypes.h>
 #include <utils/Log.h>
 #include <utils/Trace.h>
 
@@ -193,7 +194,7 @@
         result.appendFormat("    GPS lat x long x alt: %f x %f x %f\n",
                 p.gpsCoordinates[0], p.gpsCoordinates[1],
                 p.gpsCoordinates[2]);
-        result.appendFormat("    GPS timestamp: %lld\n",
+        result.appendFormat("    GPS timestamp: %" PRId64 "\n",
                 p.gpsTimestamp);
         result.appendFormat("    GPS processing method: %s\n",
                 p.gpsProcessingMethod.string());
diff --git a/services/camera/libcameraservice/api1/CameraClient.cpp b/services/camera/libcameraservice/api1/CameraClient.cpp
index bd6805d..30b7bb8 100644
--- a/services/camera/libcameraservice/api1/CameraClient.cpp
+++ b/services/camera/libcameraservice/api1/CameraClient.cpp
@@ -85,7 +85,7 @@
     mHardware->setCallbacks(notifyCallback,
             dataCallback,
             dataCallbackTimestamp,
-            (void *)mCameraId);
+            (void *)(uintptr_t)mCameraId);
 
     // Enable zoom, error, focus, and metadata messages by default
     enableMsgType(CAMERA_MSG_ERROR | CAMERA_MSG_ZOOM | CAMERA_MSG_FOCUS |
diff --git a/services/camera/libcameraservice/api1/client2/ZslProcessor.cpp b/services/camera/libcameraservice/api1/client2/ZslProcessor.cpp
index 4207ba9..453d54c 100644
--- a/services/camera/libcameraservice/api1/client2/ZslProcessor.cpp
+++ b/services/camera/libcameraservice/api1/client2/ZslProcessor.cpp
@@ -540,7 +540,7 @@
             if (entry.count > 0) frameAeState = entry.data.u8[0];
         }
         String8 result =
-                String8::format("   %d: b: %lld\tf: %lld, AE state: %d", i,
+                String8::format("   %zu: b: %lld\tf: %lld, AE state: %d", i,
                         bufferTimestamp, frameTimestamp, frameAeState);
         ALOGV("%s", result.string());
         if (fd != -1) {
diff --git a/services/camera/libcameraservice/api1/client2/ZslProcessor3.cpp b/services/camera/libcameraservice/api1/client2/ZslProcessor3.cpp
index e17d05d..c1d0496 100644
--- a/services/camera/libcameraservice/api1/client2/ZslProcessor3.cpp
+++ b/services/camera/libcameraservice/api1/client2/ZslProcessor3.cpp
@@ -364,7 +364,7 @@
             if (entry.count > 0) frameAeState = entry.data.u8[0];
         }
         String8 result =
-                String8::format("   %d: b: %lld\tf: %lld, AE state: %d", i,
+                String8::format("   %zu: b: %lld\tf: %lld, AE state: %d", i,
                         bufferTimestamp, frameTimestamp, frameAeState);
         ALOGV("%s", result.string());
         if (fd != -1) {
diff --git a/services/camera/libcameraservice/device2/Camera2Device.cpp b/services/camera/libcameraservice/device2/Camera2Device.cpp
index 2bc1a8a..dc97c47 100644
--- a/services/camera/libcameraservice/device2/Camera2Device.cpp
+++ b/services/camera/libcameraservice/device2/Camera2Device.cpp
@@ -25,6 +25,7 @@
 #define ALOGVV(...) ((void)0)
 #endif
 
+#include <inttypes.h>
 #include <utils/Log.h>
 #include <utils/Trace.h>
 #include <utils/Timers.h>
@@ -822,7 +823,7 @@
         result.append("      Stream slot: Empty\n");
         write(fd, result.string(), result.size());
     } else {
-        result.appendFormat("      Stream slot: %d entries\n",
+        result.appendFormat("      Stream slot: %zu entries\n",
                 mStreamSlot.size());
         int i = 0;
         for (List<camera_metadata_t*>::iterator r = mStreamSlot.begin();
@@ -837,7 +838,7 @@
         result = "      Main queue is empty\n";
         write(fd, result.string(), result.size());
     } else {
-        result = String8::format("      Main queue has %d entries:\n",
+        result = String8::format("      Main queue has %zu entries:\n",
                 mEntries.size());
         int i = 0;
         for (List<camera_metadata_t*>::iterator r = mEntries.begin();
@@ -1214,11 +1215,11 @@
     ATRACE_CALL();
     String8 result = String8::format("      Stream %d: %d x %d, format 0x%x\n",
             mId, mWidth, mHeight, mFormat);
-    result.appendFormat("        size %d, usage 0x%x, requested format 0x%x\n",
+    result.appendFormat("        size %zu, usage 0x%x, requested format 0x%x\n",
             mSize, mUsage, mFormatRequested);
     result.appendFormat("        total buffers: %d, dequeued buffers: %d\n",
             mTotalBuffers, mActiveBuffers);
-    result.appendFormat("        frame count: %d, last timestamp %lld\n",
+    result.appendFormat("        frame count: %d, last timestamp %" PRId64 "\n",
             mFrameCount, mLastTimestamp);
     write(fd, result.string(), result.size());
     return OK;
diff --git a/services/camera/libcameraservice/device3/Camera3IOStreamBase.cpp b/services/camera/libcameraservice/device3/Camera3IOStreamBase.cpp
index da51228..42e02d8 100644
--- a/services/camera/libcameraservice/device3/Camera3IOStreamBase.cpp
+++ b/services/camera/libcameraservice/device3/Camera3IOStreamBase.cpp
@@ -70,12 +70,12 @@
     lines.appendFormat("      Dims: %d x %d, format 0x%x\n",
             camera3_stream::width, camera3_stream::height,
             camera3_stream::format);
-    lines.appendFormat("      Max size: %d\n", mMaxSize);
+    lines.appendFormat("      Max size: %zu\n", mMaxSize);
     lines.appendFormat("      Usage: %d, max HAL buffers: %d\n",
             camera3_stream::usage, camera3_stream::max_buffers);
     lines.appendFormat("      Frames produced: %d, last timestamp: %lld ns\n",
             mFrameCount, mLastTimestamp);
-    lines.appendFormat("      Total buffers: %d, currently dequeued: %d\n",
+    lines.appendFormat("      Total buffers: %zu, currently dequeued: %zu\n",
             mTotalBufferCount, mDequeuedBufferCount);
     write(fd, lines.string(), lines.size());
 }
diff --git a/services/camera/libcameraservice/device3/Camera3ZslStream.cpp b/services/camera/libcameraservice/device3/Camera3ZslStream.cpp
index 5f63a6e..e509350 100644
--- a/services/camera/libcameraservice/device3/Camera3ZslStream.cpp
+++ b/services/camera/libcameraservice/device3/Camera3ZslStream.cpp
@@ -271,7 +271,7 @@
     Camera3IOStreamBase::dump(fd, args);
 
     lines = String8();
-    lines.appendFormat("      Input buffers pending: %d, in flight %d\n",
+    lines.appendFormat("      Input buffers pending: %zu, in flight %zu\n",
             mInputBufferQueue.size(), mBuffersInFlight.size());
     write(fd, lines.string(), lines.size());
 }