Merge "Fix a bug on sending a message to retry in TimedText." into jb-dev
diff --git a/include/media/stagefright/ACodec.h b/include/media/stagefright/ACodec.h
index 7536d10..dd18e95 100644
--- a/include/media/stagefright/ACodec.h
+++ b/include/media/stagefright/ACodec.h
@@ -198,6 +198,9 @@
     status_t setupAMRCodec(bool encoder, bool isWAMR, int32_t bitRate);
     status_t setupG711Codec(bool encoder, int32_t numChannels);
 
+    status_t setupFlacCodec(
+            bool encoder, int32_t numChannels, int32_t sampleRate, int32_t compressionLevel);
+
     status_t setupRawAudioFormat(
             OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels);
 
diff --git a/include/media/stagefright/MediaCodec.h b/include/media/stagefright/MediaCodec.h
index d96007b..e46e8e9 100644
--- a/include/media/stagefright/MediaCodec.h
+++ b/include/media/stagefright/MediaCodec.h
@@ -210,6 +210,9 @@
     void extractCSD(const sp<AMessage> &format);
     status_t queueCSDInputBuffer(size_t bufferIndex);
 
+    status_t setNativeWindow(
+            const sp<SurfaceTextureClient> &surfaceTextureClient);
+
     DISALLOW_EVIL_CONSTRUCTORS(MediaCodec);
 };
 
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index 1e00c5d..3fd6cef 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -774,6 +774,8 @@
             "video_decoder.vpx", "video_encoder.vpx" },
         { MEDIA_MIMETYPE_AUDIO_RAW,
             "audio_decoder.raw", "audio_encoder.raw" },
+        { MEDIA_MIMETYPE_AUDIO_FLAC,
+            "audio_decoder.flac", "audio_encoder.flac" },
     };
 
     static const size_t kNumMimeToRole =
@@ -834,7 +836,9 @@
     }
 
     int32_t bitRate = 0;
-    if (encoder && !msg->findInt32("bitrate", &bitRate)) {
+    // FLAC encoder doesn't need a bitrate, other encoders do
+    if (encoder && strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_FLAC)
+            && !msg->findInt32("bitrate", &bitRate)) {
         return INVALID_OPERATION;
     }
 
@@ -882,6 +886,27 @@
         } else {
             err = setupG711Codec(encoder, numChannels);
         }
+    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_FLAC)) {
+        int32_t numChannels, sampleRate, compressionLevel = -1;
+        if (encoder &&
+                (!msg->findInt32("channel-count", &numChannels)
+                        || !msg->findInt32("sample-rate", &sampleRate))) {
+            ALOGE("missing channel count or sample rate for FLAC encoder");
+            err = INVALID_OPERATION;
+        } else {
+            if (encoder) {
+                if (!msg->findInt32("flac-compression-level", &compressionLevel)) {
+                    compressionLevel = 5;// default FLAC compression level
+                } else if (compressionLevel < 0) {
+                    ALOGW("compression level %d outside [0..8] range, using 0", compressionLevel);
+                    compressionLevel = 0;
+                } else if (compressionLevel > 8) {
+                    ALOGW("compression level %d outside [0..8] range, using 8", compressionLevel);
+                    compressionLevel = 8;
+                }
+            }
+            err = setupFlacCodec(encoder, numChannels, sampleRate, compressionLevel);
+        }
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) {
         int32_t numChannels, sampleRate;
         if (encoder
@@ -1163,6 +1188,34 @@
             kPortIndexInput, 8000 /* sampleRate */, numChannels);
 }
 
+status_t ACodec::setupFlacCodec(
+        bool encoder, int32_t numChannels, int32_t sampleRate, int32_t compressionLevel) {
+
+    if (encoder) {
+        OMX_AUDIO_PARAM_FLACTYPE def;
+        InitOMXParams(&def);
+        def.nPortIndex = kPortIndexOutput;
+
+        // configure compression level
+        status_t err = mOMX->getParameter(mNode, OMX_IndexParamAudioFlac, &def, sizeof(def));
+        if (err != OK) {
+            ALOGE("setupFlacCodec(): Error %d getting OMX_IndexParamAudioFlac parameter", err);
+            return err;
+        }
+        def.nCompressionLevel = compressionLevel;
+        err = mOMX->setParameter(mNode, OMX_IndexParamAudioFlac, &def, sizeof(def));
+        if (err != OK) {
+            ALOGE("setupFlacCodec(): Error %d setting OMX_IndexParamAudioFlac parameter", err);
+            return err;
+        }
+    }
+
+    return setupRawAudioFormat(
+            encoder ? kPortIndexInput : kPortIndexOutput,
+            sampleRate,
+            numChannels);
+}
+
 status_t ACodec::setupRawAudioFormat(
         OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
     OMX_PARAM_PORTDEFINITIONTYPE def;
diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp
index e032cfc..5b513a8 100644
--- a/media/libstagefright/MediaCodec.cpp
+++ b/media/libstagefright/MediaCodec.cpp
@@ -796,9 +796,6 @@
                 break;
             }
 
-            mReplyID = replyID;
-            setState(CONFIGURING);
-
             sp<RefBase> obj;
             if (!msg->findObject("native-window", &obj)) {
                 obj.clear();
@@ -810,15 +807,24 @@
             if (obj != NULL) {
                 format->setObject("native-window", obj);
 
-                if (mFlags & kFlagIsSoftwareCodec) {
-                    mNativeWindow =
-                        static_cast<NativeWindowWrapper *>(obj.get())
-                            ->getSurfaceTextureClient();
+                status_t err = setNativeWindow(
+                    static_cast<NativeWindowWrapper *>(obj.get())
+                        ->getSurfaceTextureClient());
+
+                if (err != OK) {
+                    sp<AMessage> response = new AMessage;
+                    response->setInt32("err", err);
+
+                    response->postReply(replyID);
+                    break;
                 }
             } else {
-                mNativeWindow.clear();
+                setNativeWindow(NULL);
             }
 
+            mReplyID = replyID;
+            setState(CONFIGURING);
+
             void *crypto;
             if (!msg->findPointer("crypto", &crypto)) {
                 crypto = NULL;
@@ -1180,12 +1186,12 @@
 }
 
 void MediaCodec::setState(State newState) {
-    if (newState == INITIALIZED) {
+    if (newState == INITIALIZED || newState == UNINITIALIZED) {
         delete mSoftRenderer;
         mSoftRenderer = NULL;
 
         mCrypto.clear();
-        mNativeWindow.clear();
+        setNativeWindow(NULL);
 
         mOutputFormat.clear();
         mFlags &= ~kFlagOutputFormatChanged;
@@ -1425,4 +1431,37 @@
     return index;
 }
 
+status_t MediaCodec::setNativeWindow(
+        const sp<SurfaceTextureClient> &surfaceTextureClient) {
+    status_t err;
+
+    if (mNativeWindow != NULL) {
+        err = native_window_api_disconnect(
+                mNativeWindow.get(), NATIVE_WINDOW_API_MEDIA);
+
+        if (err != OK) {
+            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
+                    strerror(-err), err);
+        }
+
+        mNativeWindow.clear();
+    }
+
+    if (surfaceTextureClient != NULL) {
+        err = native_window_api_connect(
+                surfaceTextureClient.get(), NATIVE_WINDOW_API_MEDIA);
+
+        if (err != OK) {
+            ALOGE("native_window_api_connect returned an error: %s (%d)",
+                    strerror(-err), err);
+
+            return err;
+        }
+
+        mNativeWindow = surfaceTextureClient;
+    }
+
+    return OK;
+}
+
 }  // namespace android
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index 604d0e0..6083cd410 100755
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -1364,6 +1364,8 @@
             "video_decoder.vpx", "video_encoder.vpx" },
         { MEDIA_MIMETYPE_AUDIO_RAW,
             "audio_decoder.raw", "audio_encoder.raw" },
+        { MEDIA_MIMETYPE_AUDIO_FLAC,
+            "audio_decoder.flac", "audio_encoder.flac" },
     };
 
     static const size_t kNumMimeToRole =
diff --git a/media/libstagefright/codecs/aacdec/SoftAAC2.cpp b/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
index bf7befd..e499a0b 100644
--- a/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
+++ b/media/libstagefright/codecs/aacdec/SoftAAC2.cpp
@@ -267,6 +267,15 @@
         inBuffer[0] = header->pBuffer + header->nOffset;
         inBufferLength[0] = header->nFilledLen;
 
+        // Make the decoder more robust by pruning explicit backward compatible
+        // extension for LC, HE-AACv1 (SBR), HE-AACv2 (SBR + PS). We'll depend
+        // on implicit configuration.
+        if (inBufferLength[0] > 2) {
+            UCHAR aot = inBuffer[0][0] >> 3;
+            if (aot == 2 | aot == 5 | aot == 29) {
+                inBufferLength[0] = 2;
+            }
+        }
         AAC_DECODER_ERROR decoderErr =
             aacDecoder_ConfigRaw(mAACDecoder,
                                  inBuffer,
diff --git a/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp b/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
index 796caa4..c5f733b 100644
--- a/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
+++ b/media/libstagefright/codecs/amrnb/dec/SoftAMR.cpp
@@ -258,10 +258,14 @@
 }
 
 static size_t getFrameSize(unsigned FT) {
-    static const size_t kFrameSizeWB[9] = {
-        132, 177, 253, 285, 317, 365, 397, 461, 477
+    static const size_t kFrameSizeWB[10] = {
+        132, 177, 253, 285, 317, 365, 397, 461, 477, 40
     };
 
+    if (FT >= 10) {
+        return 1;
+    }
+
     size_t frameSize = kFrameSizeWB[FT];
 
     // Round up bits to bytes and add 1 for the header byte.
@@ -336,30 +340,47 @@
             }
         } else {
             int16 mode = ((inputPtr[0] >> 3) & 0x0f);
+
+            if (mode >= 10 && mode <= 13) {
+                ALOGE("encountered illegal frame type %d in AMR WB content.",
+                      mode);
+
+                notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
+                mSignalledError = true;
+
+                return;
+            }
+
             size_t frameSize = getFrameSize(mode);
             CHECK_GE(inHeader->nFilledLen, frameSize);
 
-            int16 frameType;
-            RX_State_wb rx_state;
-            mime_unsorting(
-                    const_cast<uint8_t *>(&inputPtr[1]),
-                    mInputSampleBuffer,
-                    &frameType, &mode, 1, &rx_state);
-
             int16_t *outPtr = (int16_t *)outHeader->pBuffer;
 
-            int16_t numSamplesOutput;
-            pvDecoder_AmrWb(
-                    mode, mInputSampleBuffer,
-                    outPtr,
-                    &numSamplesOutput,
-                    mDecoderBuf, frameType, mDecoderCookie);
+            if (mode >= 9) {
+                // Produce silence instead of comfort noise and for
+                // speech lost/no data.
+                memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t));
+            } else if (mode < 9) {
+                int16 frameType;
+                RX_State_wb rx_state;
+                mime_unsorting(
+                        const_cast<uint8_t *>(&inputPtr[1]),
+                        mInputSampleBuffer,
+                        &frameType, &mode, 1, &rx_state);
 
-            CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB);
+                int16_t numSamplesOutput;
+                pvDecoder_AmrWb(
+                        mode, mInputSampleBuffer,
+                        outPtr,
+                        &numSamplesOutput,
+                        mDecoderBuf, frameType, mDecoderCookie);
 
-            for (int i = 0; i < kNumSamplesPerFrameWB; ++i) {
-                /* Delete the 2 LSBs (14-bit output) */
-                outPtr[i] &= 0xfffC;
+                CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB);
+
+                for (int i = 0; i < kNumSamplesPerFrameWB; ++i) {
+                    /* Delete the 2 LSBs (14-bit output) */
+                    outPtr[i] &= 0xfffC;
+                }
             }
 
             numBytesRead = frameSize;
diff --git a/media/libstagefright/codecs/flac/Android.mk b/media/libstagefright/codecs/flac/Android.mk
new file mode 100644
index 0000000..2e43120
--- /dev/null
+++ b/media/libstagefright/codecs/flac/Android.mk
@@ -0,0 +1,4 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/media/libstagefright/codecs/flac/enc/Android.mk b/media/libstagefright/codecs/flac/enc/Android.mk
new file mode 100644
index 0000000..546a357
--- /dev/null
+++ b/media/libstagefright/codecs/flac/enc/Android.mk
@@ -0,0 +1,21 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+        SoftFlacEncoder.cpp
+
+LOCAL_C_INCLUDES := \
+        frameworks/av/media/libstagefright/include \
+        frameworks/native/include/media/openmax \
+        external/flac/include
+
+LOCAL_SHARED_LIBRARIES := \
+        libstagefright libstagefright_omx libstagefright_foundation libutils
+
+LOCAL_STATIC_LIBRARIES := \
+        libFLAC \
+
+LOCAL_MODULE := libstagefright_soft_flacenc
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp b/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp
new file mode 100644
index 0000000..233aed3
--- /dev/null
+++ b/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.cpp
@@ -0,0 +1,444 @@
+/*
+ * 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 "SoftFlacEncoder"
+#include <utils/Log.h>
+
+#include "SoftFlacEncoder.h"
+
+#include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/MediaDefs.h>
+
+#define FLAC_COMPRESSION_LEVEL_MIN     0
+#define FLAC_COMPRESSION_LEVEL_DEFAULT 5
+#define FLAC_COMPRESSION_LEVEL_MAX     8
+
+namespace android {
+
+template<class T>
+static void InitOMXParams(T *params) {
+    params->nSize = sizeof(T);
+    params->nVersion.s.nVersionMajor = 1;
+    params->nVersion.s.nVersionMinor = 0;
+    params->nVersion.s.nRevision = 0;
+    params->nVersion.s.nStep = 0;
+}
+
+SoftFlacEncoder::SoftFlacEncoder(
+        const char *name,
+        const OMX_CALLBACKTYPE *callbacks,
+        OMX_PTR appData,
+        OMX_COMPONENTTYPE **component)
+    : SimpleSoftOMXComponent(name, callbacks, appData, component),
+      mSignalledError(false),
+      mNumChannels(1),
+      mSampleRate(44100),
+      mCompressionLevel(FLAC_COMPRESSION_LEVEL_DEFAULT),
+      mEncoderWriteData(false),
+      mEncoderReturnedEncodedData(false),
+      mEncoderReturnedNbBytes(0),
+      mInputBufferPcm32(NULL)
+#ifdef WRITE_FLAC_HEADER_IN_FIRST_BUFFER
+      , mHeaderOffset(0)
+      , mWroteHeader(false)
+#endif
+{
+    ALOGV("SoftFlacEncoder::SoftFlacEncoder(name=%s)", name);
+    initPorts();
+
+    mFlacStreamEncoder = FLAC__stream_encoder_new();
+    if (mFlacStreamEncoder == NULL) {
+        ALOGE("SoftFlacEncoder::SoftFlacEncoder(name=%s) error instantiating FLAC encoder", name);
+        mSignalledError = true;
+    }
+
+    if (!mSignalledError) { // no use allocating input buffer if we had an error above
+        mInputBufferPcm32 = (FLAC__int32*) malloc(sizeof(FLAC__int32) * 2 * kMaxNumSamplesPerFrame);
+        if (mInputBufferPcm32 == NULL) {
+            ALOGE("SoftFlacEncoder::SoftFlacEncoder(name=%s) error allocating internal input buffer", name);
+            mSignalledError = true;
+        }
+    }
+}
+
+SoftFlacEncoder::~SoftFlacEncoder() {
+    ALOGV("SoftFlacEncoder::~SoftFlacEncoder()");
+    if (mFlacStreamEncoder != NULL) {
+        FLAC__stream_encoder_delete(mFlacStreamEncoder);
+        mFlacStreamEncoder = NULL;
+    }
+    free(mInputBufferPcm32);
+    mInputBufferPcm32 = NULL;
+}
+
+OMX_ERRORTYPE SoftFlacEncoder::initCheck() const {
+    if (mSignalledError) {
+        if (mFlacStreamEncoder == NULL) {
+            ALOGE("initCheck() failed due to NULL encoder");
+        } else if (mInputBufferPcm32 == NULL) {
+            ALOGE("initCheck() failed due to error allocating internal input buffer");
+        }
+        return OMX_ErrorUndefined;
+    } else {
+        return SimpleSoftOMXComponent::initCheck();
+    }
+}
+
+void SoftFlacEncoder::initPorts() {
+    ALOGV("SoftFlacEncoder::initPorts()");
+
+    OMX_PARAM_PORTDEFINITIONTYPE def;
+    InitOMXParams(&def);
+
+    // configure input port of the encoder
+    def.nPortIndex = 0;
+    def.eDir = OMX_DirInput;
+    def.nBufferCountMin = kNumBuffers;// TODO verify that 1 is enough
+    def.nBufferCountActual = def.nBufferCountMin;
+    def.nBufferSize = kMaxNumSamplesPerFrame * sizeof(int16_t) * 2;
+    def.bEnabled = OMX_TRUE;
+    def.bPopulated = OMX_FALSE;
+    def.eDomain = OMX_PortDomainAudio;
+    def.bBuffersContiguous = OMX_FALSE;
+    def.nBufferAlignment = 2;
+
+    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
+    def.format.audio.pNativeRender = NULL;
+    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
+    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
+
+    addPort(def);
+
+    // configure output port of the encoder
+    def.nPortIndex = 1;
+    def.eDir = OMX_DirOutput;
+    def.nBufferCountMin = kNumBuffers;// TODO verify that 1 is enough
+    def.nBufferCountActual = def.nBufferCountMin;
+    def.nBufferSize = kMaxOutputBufferSize;
+    def.bEnabled = OMX_TRUE;
+    def.bPopulated = OMX_FALSE;
+    def.eDomain = OMX_PortDomainAudio;
+    def.bBuffersContiguous = OMX_FALSE;
+    def.nBufferAlignment = 1;
+
+    def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_FLAC);
+    def.format.audio.pNativeRender = NULL;
+    def.format.audio.bFlagErrorConcealment = OMX_FALSE;
+    def.format.audio.eEncoding = OMX_AUDIO_CodingFLAC;
+
+    addPort(def);
+}
+
+OMX_ERRORTYPE SoftFlacEncoder::internalGetParameter(
+        OMX_INDEXTYPE index, OMX_PTR params) {
+    ALOGV("SoftFlacEncoder::internalGetParameter(index=0x%x)", index);
+
+    switch (index) {
+        case OMX_IndexParamAudioPcm:
+        {
+            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
+                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
+
+            if (pcmParams->nPortIndex > 1) {
+                return OMX_ErrorUndefined;
+            }
+
+            pcmParams->eNumData = OMX_NumericalDataSigned;
+            pcmParams->eEndian = OMX_EndianBig;
+            pcmParams->bInterleaved = OMX_TRUE;
+            pcmParams->nBitPerSample = 16;
+            pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
+            pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
+            pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
+
+            pcmParams->nChannels = mNumChannels;
+            pcmParams->nSamplingRate = mSampleRate;
+
+            return OMX_ErrorNone;
+        }
+
+        case OMX_IndexParamAudioFlac:
+        {
+            OMX_AUDIO_PARAM_FLACTYPE *flacParams = (OMX_AUDIO_PARAM_FLACTYPE *)params;
+            flacParams->nCompressionLevel = mCompressionLevel;
+            flacParams->nChannels = mNumChannels;
+            flacParams->nSampleRate = mSampleRate;
+            return OMX_ErrorNone;
+        }
+
+        default:
+            return SimpleSoftOMXComponent::internalGetParameter(index, params);
+    }
+}
+
+OMX_ERRORTYPE SoftFlacEncoder::internalSetParameter(
+        OMX_INDEXTYPE index, const OMX_PTR params) {
+    switch (index) {
+        case OMX_IndexParamAudioPcm:
+        {
+            ALOGV("SoftFlacEncoder::internalSetParameter(OMX_IndexParamAudioPcm)");
+            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
+
+            if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
+                ALOGE("SoftFlacEncoder::internalSetParameter() Error #1");
+                return OMX_ErrorUndefined;
+            }
+
+            if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) {
+                return OMX_ErrorUndefined;
+            }
+
+            mNumChannels = pcmParams->nChannels;
+            mSampleRate = pcmParams->nSamplingRate;
+            ALOGV("will encode %ld channels at %ldHz", mNumChannels, mSampleRate);
+
+            return configureEncoder();
+        }
+
+        case OMX_IndexParamStandardComponentRole:
+        {
+            ALOGV("SoftFlacEncoder::internalSetParameter(OMX_IndexParamStandardComponentRole)");
+            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
+                (const OMX_PARAM_COMPONENTROLETYPE *)params;
+
+            if (strncmp((const char *)roleParams->cRole,
+                    "audio_encoder.flac",
+                    OMX_MAX_STRINGNAME_SIZE - 1)) {
+                ALOGE("SoftFlacEncoder::internalSetParameter(OMX_IndexParamStandardComponentRole)"
+                        "error");
+                return OMX_ErrorUndefined;
+            }
+
+            return OMX_ErrorNone;
+        }
+
+        case OMX_IndexParamAudioFlac:
+        {
+            // used only for setting the compression level
+            OMX_AUDIO_PARAM_FLACTYPE *flacParams = (OMX_AUDIO_PARAM_FLACTYPE *)params;
+            mCompressionLevel = flacParams->nCompressionLevel; // range clamping done inside encoder
+            return OMX_ErrorNone;
+        }
+
+        default:
+            ALOGV("SoftFlacEncoder::internalSetParameter(default)");
+            return SimpleSoftOMXComponent::internalSetParameter(index, params);
+    }
+}
+
+void SoftFlacEncoder::onQueueFilled(OMX_U32 portIndex) {
+
+    ALOGV("SoftFlacEncoder::onQueueFilled(portIndex=%ld)", portIndex);
+
+    if (mSignalledError) {
+        return;
+    }
+
+    List<BufferInfo *> &inQueue = getPortQueue(0);
+    List<BufferInfo *> &outQueue = getPortQueue(1);
+
+    while (!inQueue.empty() && !outQueue.empty()) {
+        BufferInfo *inInfo = *inQueue.begin();
+        OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
+
+        BufferInfo *outInfo = *outQueue.begin();
+        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
+
+        if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
+            inQueue.erase(inQueue.begin());
+            inInfo->mOwnedByUs = false;
+            notifyEmptyBufferDone(inHeader);
+
+            outHeader->nFilledLen = 0;
+            outHeader->nFlags = OMX_BUFFERFLAG_EOS;
+
+            outQueue.erase(outQueue.begin());
+            outInfo->mOwnedByUs = false;
+            notifyFillBufferDone(outHeader);
+
+            return;
+        }
+
+        if (inHeader->nFilledLen > kMaxNumSamplesPerFrame * sizeof(FLAC__int32) * 2) {
+            ALOGE("input buffer too large (%ld).", inHeader->nFilledLen);
+            mSignalledError = true;
+            notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
+            return;
+        }
+
+        assert(mNumChannels != 0);
+        mEncoderWriteData = true;
+        mEncoderReturnedEncodedData = false;
+        mEncoderReturnedNbBytes = 0;
+        mCurrentInputTimeStamp = inHeader->nTimeStamp;
+
+        const unsigned nbInputFrames = inHeader->nFilledLen / (2 * mNumChannels);
+        const unsigned nbInputSamples = inHeader->nFilledLen / 2;
+        const OMX_S16 * const pcm16 = reinterpret_cast<OMX_S16 *>(inHeader->pBuffer);
+
+        for (unsigned i=0 ; i < nbInputSamples ; i++) {
+            mInputBufferPcm32[i] = (FLAC__int32) pcm16[i];
+        }
+        ALOGV(" about to encode %u samples per channel", nbInputFrames);
+        FLAC__bool ok = FLAC__stream_encoder_process_interleaved(
+                        mFlacStreamEncoder,
+                        mInputBufferPcm32,
+                        nbInputFrames /*samples per channel*/ );
+
+        if (ok) {
+            if (mEncoderReturnedEncodedData && (mEncoderReturnedNbBytes != 0)) {
+                ALOGV(" dequeueing buffer on output port after writing data");
+                outInfo->mOwnedByUs = false;
+                outQueue.erase(outQueue.begin());
+                outInfo = NULL;
+                notifyFillBufferDone(outHeader);
+                outHeader = NULL;
+                mEncoderReturnedEncodedData = false;
+            } else {
+                ALOGV(" encoder process_interleaved returned without data to write");
+            }
+        } else {
+            ALOGE(" error encountered during encoding");
+            mSignalledError = true;
+            notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
+            return;
+        }
+
+        inInfo->mOwnedByUs = false;
+        inQueue.erase(inQueue.begin());
+        inInfo = NULL;
+        notifyEmptyBufferDone(inHeader);
+        inHeader = NULL;
+    }
+}
+
+
+FLAC__StreamEncoderWriteStatus SoftFlacEncoder::onEncodedFlacAvailable(
+            const FLAC__byte buffer[],
+            size_t bytes, unsigned samples, unsigned current_frame) {
+    ALOGV("SoftFlacEncoder::onEncodedFlacAvailable(bytes=%d, samples=%d, curr_frame=%d)",
+            bytes, samples, current_frame);
+
+#ifdef WRITE_FLAC_HEADER_IN_FIRST_BUFFER
+    if (samples == 0) {
+        ALOGI(" saving %d bytes of header", bytes);
+        memcpy(mHeader + mHeaderOffset, buffer, bytes);
+        mHeaderOffset += bytes;// will contain header size when finished receiving header
+        return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
+    }
+
+#endif
+
+    if ((samples == 0) || !mEncoderWriteData) {
+        // called by the encoder because there's header data to save, but it's not the role
+        // of this component (unless WRITE_FLAC_HEADER_IN_FIRST_BUFFER is defined)
+        ALOGV("ignoring %d bytes of header data (samples=%d)", bytes, samples);
+        return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
+    }
+
+    List<BufferInfo *> &outQueue = getPortQueue(1);
+    CHECK(!outQueue.empty());
+    BufferInfo *outInfo = *outQueue.begin();
+    OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
+
+#ifdef WRITE_FLAC_HEADER_IN_FIRST_BUFFER
+    if (!mWroteHeader) {
+        ALOGI(" writing %d bytes of header on output port", mHeaderOffset);
+        memcpy(outHeader->pBuffer + outHeader->nOffset + outHeader->nFilledLen,
+                mHeader, mHeaderOffset);
+        outHeader->nFilledLen += mHeaderOffset;
+        outHeader->nOffset    += mHeaderOffset;
+        mWroteHeader = true;
+    }
+#endif
+
+    // write encoded data
+    ALOGV(" writing %d bytes of encoded data on output port", bytes);
+    if (bytes > outHeader->nAllocLen - outHeader->nOffset - outHeader->nFilledLen) {
+        ALOGE(" not enough space left to write encoded data, dropping %u bytes", bytes);
+        // a fatal error would stop the encoding
+        return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
+    }
+    memcpy(outHeader->pBuffer + outHeader->nOffset, buffer, bytes);
+
+    outHeader->nTimeStamp = mCurrentInputTimeStamp;
+    outHeader->nOffset = 0;
+    outHeader->nFilledLen += bytes;
+    outHeader->nFlags = 0;
+
+    mEncoderReturnedEncodedData = true;
+    mEncoderReturnedNbBytes += bytes;
+
+    return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
+}
+
+
+OMX_ERRORTYPE SoftFlacEncoder::configureEncoder() {
+    ALOGV("SoftFlacEncoder::configureEncoder() numChannel=%ld, sampleRate=%ld",
+            mNumChannels, mSampleRate);
+
+    if (mSignalledError || (mFlacStreamEncoder == NULL)) {
+        ALOGE("can't configure encoder: no encoder or invalid state");
+        return OMX_ErrorInvalidState;
+    }
+
+    FLAC__bool ok = true;
+    FLAC__StreamEncoderInitStatus initStatus = FLAC__STREAM_ENCODER_INIT_STATUS_OK;
+    ok = ok && FLAC__stream_encoder_set_channels(mFlacStreamEncoder, mNumChannels);
+    ok = ok && FLAC__stream_encoder_set_sample_rate(mFlacStreamEncoder, mSampleRate);
+    ok = ok && FLAC__stream_encoder_set_bits_per_sample(mFlacStreamEncoder, 16);
+    ok = ok && FLAC__stream_encoder_set_compression_level(mFlacStreamEncoder,
+            (unsigned)mCompressionLevel);
+    ok = ok && FLAC__stream_encoder_set_verify(mFlacStreamEncoder, false);
+    if (!ok) { goto return_result; }
+
+    ok &= FLAC__STREAM_ENCODER_INIT_STATUS_OK ==
+            FLAC__stream_encoder_init_stream(mFlacStreamEncoder,
+                    flacEncoderWriteCallback    /*write_callback*/,
+                    NULL /*seek_callback*/,
+                    NULL /*tell_callback*/,
+                    NULL /*metadata_callback*/,
+                    (void *) this /*client_data*/);
+
+return_result:
+    if (ok) {
+        ALOGV("encoder successfully configured");
+        return OMX_ErrorNone;
+    } else {
+        ALOGE("unknown error when configuring encoder");
+        return OMX_ErrorUndefined;
+    }
+}
+
+
+// static
+FLAC__StreamEncoderWriteStatus SoftFlacEncoder::flacEncoderWriteCallback(
+            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);
+}
+
+}  // namespace android
+
+
+android::SoftOMXComponent *createSoftOMXComponent(
+        const char *name, const OMX_CALLBACKTYPE *callbacks,
+        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
+    return new android::SoftFlacEncoder(name, callbacks, appData, component);
+}
+
diff --git a/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.h b/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.h
new file mode 100644
index 0000000..1e0148a
--- /dev/null
+++ b/media/libstagefright/codecs/flac/enc/SoftFlacEncoder.h
@@ -0,0 +1,102 @@
+/*
+ * 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 SOFT_FLAC_ENC_H_
+
+#define SOFT_FLAC_ENC_H_
+
+#include "SimpleSoftOMXComponent.h"
+
+#include "FLAC/stream_encoder.h"
+
+// use this symbol to have the first output buffer start with FLAC frame header so a dump of
+// all the output buffers can be opened as a .flac file
+//#define WRITE_FLAC_HEADER_IN_FIRST_BUFFER
+
+namespace android {
+
+struct SoftFlacEncoder : public SimpleSoftOMXComponent {
+    SoftFlacEncoder(const char *name,
+            const OMX_CALLBACKTYPE *callbacks,
+            OMX_PTR appData,
+            OMX_COMPONENTTYPE **component);
+
+    virtual OMX_ERRORTYPE initCheck() const;
+
+protected:
+    virtual ~SoftFlacEncoder();
+
+    virtual OMX_ERRORTYPE internalGetParameter(
+            OMX_INDEXTYPE index, OMX_PTR params);
+
+    virtual OMX_ERRORTYPE internalSetParameter(
+            OMX_INDEXTYPE index, const OMX_PTR params);
+
+    virtual void onQueueFilled(OMX_U32 portIndex);
+
+private:
+
+    enum {
+        kNumBuffers = 2,
+        kMaxNumSamplesPerFrame = 1152,
+        kMaxOutputBufferSize = 65536,    //TODO check if this can be reduced
+    };
+
+    bool mSignalledError;
+
+    OMX_U32 mNumChannels;
+    OMX_U32 mSampleRate;
+    OMX_U32 mCompressionLevel;
+
+    // should the data received by the callback be written to the output port
+    bool        mEncoderWriteData;
+    bool        mEncoderReturnedEncodedData;
+    size_t      mEncoderReturnedNbBytes;
+    OMX_TICKS  mCurrentInputTimeStamp;
+
+    FLAC__StreamEncoder* mFlacStreamEncoder;
+
+    void initPorts();
+
+    OMX_ERRORTYPE configureEncoder();
+
+    // FLAC encoder callbacks
+    // maps to encoderEncodeFlac()
+    static FLAC__StreamEncoderWriteStatus flacEncoderWriteCallback(
+            const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[],
+            size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
+
+    FLAC__StreamEncoderWriteStatus onEncodedFlacAvailable(
+                const FLAC__byte buffer[],
+                size_t bytes, unsigned samples, unsigned current_frame);
+
+    // FLAC takes samples aligned on 32bit boundaries, use this buffer for the conversion
+    // before passing the input data to the encoder
+    FLAC__int32* mInputBufferPcm32;
+
+#ifdef WRITE_FLAC_HEADER_IN_FIRST_BUFFER
+    unsigned mHeaderOffset;
+    bool mWroteHeader;
+    char mHeader[128];
+#endif
+
+    DISALLOW_EVIL_CONSTRUCTORS(SoftFlacEncoder);
+};
+
+}  // namespace android
+
+#endif  // SOFT_FLAC_ENC_H_
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h b/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h
index 24a50ce..6d4868c 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h
+++ b/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h
@@ -20,7 +20,7 @@
 
 #include "m4vh263_decoder_pv_types.h"
 
-#define PV_TOLERATE_VOL_ERRORS
+// #define PV_TOLERATE_VOL_ERRORS
 #define PV_MEMORY_POOL
 
 #ifndef _PV_TYPES_
diff --git a/media/libstagefright/omx/SoftOMXPlugin.cpp b/media/libstagefright/omx/SoftOMXPlugin.cpp
index 6e53095..3747b3b 100644
--- a/media/libstagefright/omx/SoftOMXPlugin.cpp
+++ b/media/libstagefright/omx/SoftOMXPlugin.cpp
@@ -52,6 +52,7 @@
     { "OMX.google.vorbis.decoder", "vorbisdec", "audio_decoder.vorbis" },
     { "OMX.google.vpx.decoder", "vpxdec", "video_decoder.vpx" },
     { "OMX.google.raw.decoder", "rawdec", "audio_decoder.raw" },
+    { "OMX.google.flac.encoder", "flacenc", "audio_encoder.flac" },
 };
 
 static const size_t kNumComponents =
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 8b7a48b..56a9942 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -19,6 +19,8 @@
 #define LOG_TAG "AudioFlinger"
 //#define LOG_NDEBUG 0
 
+//#define ATRACE_TAG ATRACE_TAG_AUDIO
+
 #include <math.h>
 #include <signal.h>
 #include <sys/time.h>
@@ -27,6 +29,7 @@
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
 #include <utils/Log.h>
+#include <utils/Trace.h>
 #include <binder/Parcel.h>
 #include <binder/IPCThreadState.h>
 #include <utils/String16.h>
@@ -2498,6 +2501,7 @@
             if (!mStandby && delta > maxPeriod) {
                 mNumDelayedWrites++;
                 if ((now - lastWarning) > kWarningThrottleNs) {
+                    ScopedTrace st(ATRACE_TAG, "underrun");
                     ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
                             ns2ms(delta), mNumDelayedWrites, this);
                     lastWarning = now;
@@ -2593,7 +2597,9 @@
 
 #define mBitShift 2 // FIXME
     size_t count = mixBufferSize >> mBitShift;
+    Tracer::traceBegin(ATRACE_TAG, "write");
     ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
+    Tracer::traceEnd(ATRACE_TAG);
     if (framesWritten > 0) {
         size_t bytesWritten = framesWritten << mBitShift;
         mBytesWritten += bytesWritten;
diff --git a/services/audioflinger/FastMixer.cpp b/services/audioflinger/FastMixer.cpp
index bf264be..1492a36 100644
--- a/services/audioflinger/FastMixer.cpp
+++ b/services/audioflinger/FastMixer.cpp
@@ -17,12 +17,16 @@
 #define LOG_TAG "FastMixer"
 //#define LOG_NDEBUG 0
 
+//#define ATRACE_TAG ATRACE_TAG_AUDIO
+
 #include <sys/atomics.h>
 #include <time.h>
 #include <utils/Log.h>
+#include <utils/Trace.h>
 #include <system/audio.h>
 #ifdef FAST_MIXER_STATISTICS
 #include <cpustats/CentralTendencyStatistics.h>
+#include <cpustats/ThreadCpuUsage.h>
 #endif
 #include "AudioMixer.h"
 #include "FastMixer.h"
@@ -65,8 +69,11 @@
     FastMixerDumpState dummyDumpState, *dumpState = &dummyDumpState;
     bool ignoreNextOverrun = true;  // used to ignore initial overrun and first after an underrun
 #ifdef FAST_MIXER_STATISTICS
-    CentralTendencyStatistics cts;  // cycle times in seconds
-    static const unsigned kMaxSamples = 1000;
+    struct timespec oldLoad = {0, 0};    // previous value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
+    bool oldLoadValid = false;  // whether oldLoad is valid
+    uint32_t bounds = 0;
+    bool full = false;      // whether we have collected at least kSamplingN samples
+    ThreadCpuUsage tcu;     // for reading the current CPU clock frequency in kHz
 #endif
     unsigned coldGen = 0;   // last observed mColdGen
     bool isWarm = false;    // true means ready to mix, false means wait for warmup before mixing
@@ -116,6 +123,7 @@
                     preIdle = *current;
                     current = &preIdle;
                     oldTsValid = false;
+                    oldLoadValid = false;
                     ignoreNextOverrun = true;
                 }
                 previous = current;
@@ -151,6 +159,8 @@
                 warmupCycles = 0;
                 sleepNs = -1;
                 coldGen = current->mColdGen;
+                bounds = 0;
+                full = false;
             } else {
                 sleepNs = FAST_HOT_IDLE_NS;
             }
@@ -352,6 +362,7 @@
                 FastTrackDump *ftDump = &dumpState->mTracks[i];
                 uint32_t underruns = ftDump->mUnderruns;
                 if (framesReady < frameCount) {
+                    ATRACE_INT("underrun", i);
                     ftDump->mUnderruns = (underruns + 2) | 1;
                     if (framesReady == 0) {
                         mixer->disable(name);
@@ -380,7 +391,9 @@
             // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
             //       but this code should be modified to handle both non-blocking and blocking sinks
             dumpState->mWriteSequence++;
+            Tracer::traceBegin(ATRACE_TAG, "write");
             ssize_t framesWritten = outputSink->write(mixBuffer, frameCount);
+            Tracer::traceEnd(ATRACE_TAG);
             dumpState->mWriteSequence++;
             if (framesWritten >= 0) {
                 ALOG_ASSERT(framesWritten <= frameCount);
@@ -430,6 +443,7 @@
                     }
                 }
                 if (sec > 0 || nsec > underrunNs) {
+                    ScopedTrace st(ATRACE_TAG, "underrun");
                     // FIXME only log occasionally
                     ALOGV("underrun: time since last cycle %d.%03ld sec",
                             (int) sec, nsec / 1000000L);
@@ -451,15 +465,54 @@
                     ignoreNextOverrun = false;
                 }
 #ifdef FAST_MIXER_STATISTICS
-                // long-term statistics
-                cts.sample(sec + nsec * 1e-9);
-                if (cts.n() >= kMaxSamples) {
-                    dumpState->mMean = cts.mean();
-                    dumpState->mMinimum = cts.minimum();
-                    dumpState->mMaximum = cts.maximum();
-                    dumpState->mStddev = cts.stddev();
-                    cts.reset();
+                // advance the FIFO queue bounds
+                size_t i = bounds & (FastMixerDumpState::kSamplingN - 1);
+                bounds = (bounds + 1) & 0xFFFF;
+                if (full) {
+                    bounds += 0x10000;
+                } else if (!(bounds & (FastMixerDumpState::kSamplingN - 1))) {
+                    full = true;
                 }
+                // compute the delta value of clock_gettime(CLOCK_MONOTONIC)
+                uint32_t monotonicNs = nsec;
+                if (sec > 0 && sec < 4) {
+                    monotonicNs += sec * 1000000000;
+                }
+                // compute the raw CPU load = delta value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
+                uint32_t loadNs = 0;
+                struct timespec newLoad;
+                rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &newLoad);
+                if (rc == 0) {
+                    if (oldLoadValid) {
+                        sec = newLoad.tv_sec - oldLoad.tv_sec;
+                        nsec = newLoad.tv_nsec - oldLoad.tv_nsec;
+                        if (nsec < 0) {
+                            --sec;
+                            nsec += 1000000000;
+                        }
+                        loadNs = nsec;
+                        if (sec > 0 && sec < 4) {
+                            loadNs += sec * 1000000000;
+                        }
+                    } else {
+                        // first time through the loop
+                        oldLoadValid = true;
+                    }
+                    oldLoad = newLoad;
+                }
+                // get the absolute value of CPU clock frequency in kHz
+                int cpuNum = sched_getcpu();
+                uint32_t kHz = tcu.getCpukHz(cpuNum);
+                kHz = (kHz & ~0xF) | (cpuNum & 0xF);
+                // save values in FIFO queues for dumpsys
+                // these stores #1, #2, #3 are not atomic with respect to each other,
+                // or with respect to store #4 below
+                dumpState->mMonotonicNs[i] = monotonicNs;
+                dumpState->mLoadNs[i] = loadNs;
+                dumpState->mCpukHz[i] = kHz;
+                // this store #4 is not atomic with respect to stores #1, #2, #3 above, but
+                // the newest open and oldest closed halves are atomic with respect to each other
+                dumpState->mBounds = bounds;
 #endif
             } else {
                 // first time through the loop
@@ -474,6 +527,7 @@
             sleepNs = periodNs;
         }
 
+
     }   // for (;;)
 
     // never return 'true'; Thread::_threadLoop() locks mutex which can result in priority inversion
@@ -484,11 +538,16 @@
     mNumTracks(0), mWriteErrors(0), mUnderruns(0), mOverruns(0),
     mSampleRate(0), mFrameCount(0), /* mMeasuredWarmupTs({0, 0}), */ mWarmupCycles(0)
 #ifdef FAST_MIXER_STATISTICS
-    , mMean(0.0), mMinimum(0.0), mMaximum(0.0), mStddev(0.0)
+    , mBounds(0)
 #endif
 {
     mMeasuredWarmupTs.tv_sec = 0;
     mMeasuredWarmupTs.tv_nsec = 0;
+    // sample arrays aren't accessed atomically with respect to the bounds,
+    // so clearing reduces chance for dumpsys to read random uninitialized samples
+    memset(&mMonotonicNs, 0, sizeof(mMonotonicNs));
+    memset(&mLoadNs, 0, sizeof(mLoadNs));
+    memset(&mCpukHz, 0, sizeof(mCpukHz));
 }
 
 FastMixerDumpState::~FastMixerDumpState()
@@ -525,17 +584,63 @@
         snprintf(string, COMMAND_MAX, "%d", mCommand);
         break;
     }
-    double mMeasuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
+    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",
+                 "          sampleRate=%u frameCount=%u measuredWarmup=%.3g ms, warmupCycles=%u\n"
+                 "          mixPeriod=%.2f ms\n",
                  string, mWriteSequence, mFramesWritten,
                  mNumTracks, mWriteErrors, mUnderruns, mOverruns,
-                 mSampleRate, mFrameCount, mMeasuredWarmupMs, mWarmupCycles);
+                 mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
+                 mixPeriodSec * 1e3);
 #ifdef FAST_MIXER_STATISTICS
-    fdprintf(fd, "          cycle time in ms: mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
-                 mMean*1e3, mMinimum*1e3, mMaximum*1e3, mStddev*1e3);
+    // find the interval of valid samples
+    uint32_t bounds = mBounds;
+    uint32_t newestOpen = bounds & 0xFFFF;
+    uint32_t oldestClosed = bounds >> 16;
+    uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
+    if (n > kSamplingN) {
+        ALOGE("too many samples %u", n);
+        n = kSamplingN;
+    }
+    // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
+    // and adjusted CPU load in MHz normalized for CPU clock frequency
+    CentralTendencyStatistics wall, loadNs, kHz, loadMHz;
+    // only compute adjusted CPU load in Hz if current CPU number and CPU clock frequency are stable
+    bool valid = false;
+    uint32_t previousCpukHz = 0;
+    // loop over all the samples
+    for (; n > 0; --n) {
+        size_t i = oldestClosed++ & (kSamplingN - 1);
+        uint32_t wallNs = mMonotonicNs[i];
+        wall.sample(wallNs);
+        uint32_t sampleLoadNs = mLoadNs[i];
+        uint32_t sampleCpukHz = mCpukHz[i];
+        loadNs.sample(sampleLoadNs);
+        kHz.sample(sampleCpukHz & ~0xF);
+        if (sampleCpukHz == previousCpukHz) {
+            double megacycles = (double) sampleLoadNs * (double) sampleCpukHz;
+            double adjMHz = megacycles / mixPeriodSec;  // _not_ wallNs * 1e9
+            loadMHz.sample(adjMHz);
+        }
+        previousCpukHz = sampleCpukHz;
+    }
+    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);
+    fdprintf(fd, "  CPU clock frequency in MHz:\n"
+                 "    mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
+                 kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
+    fdprintf(fd, "  adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
+                 "    mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
+                 loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
 #endif
 }
 
diff --git a/services/audioflinger/FastMixer.h b/services/audioflinger/FastMixer.h
index a6dd310..e2ed553 100644
--- a/services/audioflinger/FastMixer.h
+++ b/services/audioflinger/FastMixer.h
@@ -64,7 +64,7 @@
     FastMixerDumpState();
     /*virtual*/ ~FastMixerDumpState();
 
-    void dump(int fd);
+    void dump(int fd);          // should only be called on a stable copy, not the original
 
     FastMixerState::Command mCommand;   // current command
     uint32_t mWriteSequence;    // incremented before and after each write()
@@ -78,12 +78,20 @@
     struct timespec mMeasuredWarmupTs;  // measured warmup time
     uint32_t mWarmupCycles;     // number of loop cycles required to warmup
     FastTrackDump   mTracks[FastMixerState::kMaxFastTracks];
+
 #ifdef FAST_MIXER_STATISTICS
-    // cycle times in seconds
-    float    mMean;
-    float    mMinimum;
-    float    mMaximum;
-    float    mStddev;
+    // Recently collected samples of per-cycle monotonic time, thread CPU time, and CPU frequency.
+    // kSamplingN is the size of the sampling frame, and must be a power of 2 <= 0x8000.
+    static const uint32_t kSamplingN = 0x1000;
+    // The bounds define the interval of valid samples, and are represented as follows:
+    //      newest open (excluded) endpoint   = lower 16 bits of bounds, modulo N
+    //      oldest closed (included) endpoint = upper 16 bits of bounds, modulo N
+    // Number of valid samples is newest - oldest.
+    uint32_t mBounds;                   // bounds for mMonotonicNs, mThreadCpuNs, and mCpukHz
+    // The elements in the *Ns arrays are in units of nanoseconds <= 3999999999.
+    uint32_t mMonotonicNs[kSamplingN];  // delta monotonic (wall clock) time
+    uint32_t mLoadNs[kSamplingN];       // delta CPU load in time
+    uint32_t mCpukHz[kSamplingN];       // absolute CPU clock frequency in kHz, bits 0-3 are CPU#
 #endif
 };