Merge "transcoding: remove progress report logging." into sc-dev
diff --git a/media/codec2/core/include/C2Config.h b/media/codec2/core/include/C2Config.h
index 8ee5f33..6176646 100644
--- a/media/codec2/core/include/C2Config.h
+++ b/media/codec2/core/include/C2Config.h
@@ -75,6 +75,10 @@
     enum tiling_mode_t : uint32_t;          ///< tiling modes
 };
 
+struct C2PlatformConfig {
+    enum encoding_quality_level_t : uint32_t; ///< encoding quality level
+};
+
 namespace {
 
 enum C2ParamIndexKind : C2Param::type_index_t {
@@ -259,7 +263,11 @@
     kParamIndexTunnelHandle, // int32[]
     kParamIndexTunnelSystemTime, // int64
 
+    // dmabuf allocator
     kParamIndexStoreDmaBufUsage,  // store, struct
+
+    // encoding quality requirements
+    kParamIndexEncodingQualityLevel, // encoders, enum
 };
 
 }
@@ -2340,6 +2348,23 @@
         C2PortTunnelSystemTime;
 constexpr char C2_PARAMKEY_OUTPUT_RENDER_TIME[] = "output.render-time";
 
+C2ENUM(C2PlatformConfig::encoding_quality_level_t, uint32_t,
+    NONE,
+    S_HANDHELD,
+    S_HANDHELD_PC
+);
+
+namespace android {
+
+/**
+ * Encoding quality level signaling.
+ */
+typedef C2GlobalParam<C2Setting,
+        C2SimpleValueStruct<C2EasyEnum<C2PlatformConfig::encoding_quality_level_t>>,
+        kParamIndexEncodingQualityLevel> C2EncodingQualityLevel;
+
+}
+
 /// @}
 
 #endif  // C2CONFIG_H_
diff --git a/media/codec2/hidl/1.0/vts/functional/audio/VtsHalMediaC2V1_0TargetAudioDecTest.cpp b/media/codec2/hidl/1.0/vts/functional/audio/VtsHalMediaC2V1_0TargetAudioDecTest.cpp
index efc5813..5461544 100644
--- a/media/codec2/hidl/1.0/vts/functional/audio/VtsHalMediaC2V1_0TargetAudioDecTest.cpp
+++ b/media/codec2/hidl/1.0/vts/functional/audio/VtsHalMediaC2V1_0TargetAudioDecTest.cpp
@@ -34,10 +34,10 @@
 
 #include "media_c2_hidl_test_common.h"
 using DecodeTestParameters = std::tuple<std::string, std::string, uint32_t, bool>;
-static std::vector<DecodeTestParameters> kDecodeTestParameters;
+static std::vector<DecodeTestParameters> gDecodeTestParameters;
 
 using CsdFlushTestParameters = std::tuple<std::string, std::string, bool>;
-static std::vector<CsdFlushTestParameters> kCsdFlushTestParameters;
+static std::vector<CsdFlushTestParameters> gCsdFlushTestParameters;
 
 struct CompToURL {
     std::string mime;
@@ -45,7 +45,7 @@
     std::string info;
 };
 
-std::vector<CompToURL> kCompToURL = {
+std::vector<CompToURL> gCompToURL = {
         {"mp4a-latm", "bbb_aac_stereo_128kbps_48000hz.aac", "bbb_aac_stereo_128kbps_48000hz.info"},
         {"mp4a-latm", "bbb_aac_stereo_128kbps_48000hz.aac",
          "bbb_aac_stereo_128kbps_48000hz_multi_frame.info"},
@@ -290,11 +290,11 @@
 // LookUpTable of clips and metadata for component testing
 void Codec2AudioDecHidlTestBase::GetURLForComponent(char* mURL, char* info, size_t streamIndex) {
     int streamCount = 0;
-    for (size_t i = 0; i < kCompToURL.size(); ++i) {
-        if (mMime.find(kCompToURL[i].mime) != std::string::npos) {
+    for (size_t i = 0; i < gCompToURL.size(); ++i) {
+        if (mMime.find(gCompToURL[i].mime) != std::string::npos) {
             if (streamCount == streamIndex) {
-                strcat(mURL, kCompToURL[i].mURL.c_str());
-                strcat(info, kCompToURL[i].info.c_str());
+                strcat(mURL, gCompToURL[i].mURL.c_str());
+                strcat(info, gCompToURL[i].info.c_str());
                 return;
             }
             streamCount++;
@@ -859,36 +859,36 @@
     ASSERT_EQ(mComponent->stop(), C2_OK);
 }
 
-INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2AudioDecHidlTest, testing::ValuesIn(kTestParameters),
+INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2AudioDecHidlTest, testing::ValuesIn(gTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 // DecodeTest with StreamIndex and EOS / No EOS
 INSTANTIATE_TEST_SUITE_P(StreamIndexAndEOS, Codec2AudioDecDecodeTest,
-                         testing::ValuesIn(kDecodeTestParameters),
+                         testing::ValuesIn(gDecodeTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 INSTANTIATE_TEST_SUITE_P(CsdInputs, Codec2AudioDecCsdInputTests,
-                         testing::ValuesIn(kCsdFlushTestParameters),
+                         testing::ValuesIn(gCsdFlushTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 }  // anonymous namespace
 
 int main(int argc, char** argv) {
     parseArgs(argc, argv);
-    kTestParameters = getTestParameters(C2Component::DOMAIN_AUDIO, C2Component::KIND_DECODER);
-    for (auto params : kTestParameters) {
-        kDecodeTestParameters.push_back(
+    gTestParameters = getTestParameters(C2Component::DOMAIN_AUDIO, C2Component::KIND_DECODER);
+    for (auto params : gTestParameters) {
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 0, false));
-        kDecodeTestParameters.push_back(
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 0, true));
-        kDecodeTestParameters.push_back(
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 1, false));
-        kDecodeTestParameters.push_back(
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 1, true));
 
-        kCsdFlushTestParameters.push_back(
+        gCsdFlushTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), true));
-        kCsdFlushTestParameters.push_back(
+        gCsdFlushTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), false));
     }
 
diff --git a/media/codec2/hidl/1.0/vts/functional/audio/VtsHalMediaC2V1_0TargetAudioEncTest.cpp b/media/codec2/hidl/1.0/vts/functional/audio/VtsHalMediaC2V1_0TargetAudioEncTest.cpp
index 562c77f..2905cbf 100644
--- a/media/codec2/hidl/1.0/vts/functional/audio/VtsHalMediaC2V1_0TargetAudioEncTest.cpp
+++ b/media/codec2/hidl/1.0/vts/functional/audio/VtsHalMediaC2V1_0TargetAudioEncTest.cpp
@@ -37,7 +37,7 @@
 
 using EncodeTestParameters = std::tuple<std::string, std::string, bool, int32_t>;
 
-static std::vector<EncodeTestParameters> kEncodeTestParameters;
+static std::vector<EncodeTestParameters> gEncodeTestParameters;
 
 class LinearBuffer : public C2Buffer {
   public:
@@ -748,28 +748,28 @@
     }
 }
 
-INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2AudioEncHidlTest, testing::ValuesIn(kTestParameters),
+INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2AudioEncHidlTest, testing::ValuesIn(gTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 // EncodeTest with EOS / No EOS and inputMaxBufRatio
 // inputMaxBufRatio is ratio w.r.t. to mInputMaxBufSize
 INSTANTIATE_TEST_SUITE_P(EncodeTest, Codec2AudioEncEncodeTest,
-                         testing::ValuesIn(kEncodeTestParameters),
+                         testing::ValuesIn(gEncodeTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 }  // anonymous namespace
 
 int main(int argc, char** argv) {
     parseArgs(argc, argv);
-    kTestParameters = getTestParameters(C2Component::DOMAIN_AUDIO, C2Component::KIND_ENCODER);
-    for (auto params : kTestParameters) {
-        kEncodeTestParameters.push_back(
+    gTestParameters = getTestParameters(C2Component::DOMAIN_AUDIO, C2Component::KIND_ENCODER);
+    for (auto params : gTestParameters) {
+        gEncodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), false, 1));
-        kEncodeTestParameters.push_back(
+        gEncodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), false, 2));
-        kEncodeTestParameters.push_back(
+        gEncodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), true, 1));
-        kEncodeTestParameters.push_back(
+        gEncodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), true, 2));
     }
 
diff --git a/media/codec2/hidl/1.0/vts/functional/common/media_c2_hidl_test_common.h b/media/codec2/hidl/1.0/vts/functional/common/media_c2_hidl_test_common.h
index e74f247..2222aaf 100644
--- a/media/codec2/hidl/1.0/vts/functional/common/media_c2_hidl_test_common.h
+++ b/media/codec2/hidl/1.0/vts/functional/common/media_c2_hidl_test_common.h
@@ -41,7 +41,7 @@
 using namespace ::std::chrono;
 
 using TestParameters = std::tuple<std::string, std::string>;
-static std::vector<TestParameters> kTestParameters;
+static std::vector<TestParameters> gTestParameters;
 
 // Resource directory
 extern std::string sResourceDir;
diff --git a/media/codec2/hidl/1.0/vts/functional/component/VtsHalMediaC2V1_0TargetComponentTest.cpp b/media/codec2/hidl/1.0/vts/functional/component/VtsHalMediaC2V1_0TargetComponentTest.cpp
index 29acd33..ffec897 100644
--- a/media/codec2/hidl/1.0/vts/functional/component/VtsHalMediaC2V1_0TargetComponentTest.cpp
+++ b/media/codec2/hidl/1.0/vts/functional/component/VtsHalMediaC2V1_0TargetComponentTest.cpp
@@ -54,7 +54,7 @@
 
 namespace {
 using InputTestParameters = std::tuple<std::string, std::string, uint32_t, bool>;
-static std::vector<InputTestParameters> kInputTestParameters;
+static std::vector<InputTestParameters> gInputTestParameters;
 
 // google.codec2 Component test setup
 class Codec2ComponentHidlTestBase : public ::testing::Test {
@@ -345,28 +345,28 @@
     ASSERT_EQ(mComponent->reset(), C2_OK);
 }
 
-INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2ComponentHidlTest, testing::ValuesIn(kTestParameters),
+INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2ComponentHidlTest, testing::ValuesIn(gTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 INSTANTIATE_TEST_CASE_P(NonStdInputs, Codec2ComponentInputTests,
-                        testing::ValuesIn(kInputTestParameters), PrintInstanceTupleNameToString<>);
+                        testing::ValuesIn(gInputTestParameters), PrintInstanceTupleNameToString<>);
 }  // anonymous namespace
 
 // TODO: Add test for Invalid work,
 // TODO: Add test for Invalid states
 int main(int argc, char** argv) {
     parseArgs(argc, argv);
-    kTestParameters = getTestParameters();
-    for (auto params : kTestParameters) {
-        kInputTestParameters.push_back(
+    gTestParameters = getTestParameters();
+    for (auto params : gTestParameters) {
+        gInputTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 0, true));
-        kInputTestParameters.push_back(std::make_tuple(std::get<0>(params), std::get<1>(params),
+        gInputTestParameters.push_back(std::make_tuple(std::get<0>(params), std::get<1>(params),
                                                        C2FrameData::FLAG_END_OF_STREAM, true));
-        kInputTestParameters.push_back(
+        gInputTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 0, false));
-        kInputTestParameters.push_back(std::make_tuple(std::get<0>(params), std::get<1>(params),
+        gInputTestParameters.push_back(std::make_tuple(std::get<0>(params), std::get<1>(params),
                                                        C2FrameData::FLAG_CODEC_CONFIG, false));
-        kInputTestParameters.push_back(std::make_tuple(std::get<0>(params), std::get<1>(params),
+        gInputTestParameters.push_back(std::make_tuple(std::get<0>(params), std::get<1>(params),
                                                        C2FrameData::FLAG_END_OF_STREAM, false));
     }
 
diff --git a/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoDecTest.cpp b/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoDecTest.cpp
index d0a1c31..10298c3 100644
--- a/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoDecTest.cpp
+++ b/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoDecTest.cpp
@@ -41,10 +41,10 @@
 #include "media_c2_video_hidl_test_common.h"
 
 using DecodeTestParameters = std::tuple<std::string, std::string, uint32_t, bool>;
-static std::vector<DecodeTestParameters> kDecodeTestParameters;
+static std::vector<DecodeTestParameters> gDecodeTestParameters;
 
 using CsdFlushTestParameters = std::tuple<std::string, std::string, bool>;
-static std::vector<CsdFlushTestParameters> kCsdFlushTestParameters;
+static std::vector<CsdFlushTestParameters> gCsdFlushTestParameters;
 
 struct CompToURL {
     std::string mime;
@@ -52,7 +52,7 @@
     std::string info;
     std::string chksum;
 };
-std::vector<CompToURL> kCompToURL = {
+std::vector<CompToURL> gCompToURL = {
         {"avc", "bbb_avc_176x144_300kbps_60fps.h264", "bbb_avc_176x144_300kbps_60fps.info",
          "bbb_avc_176x144_300kbps_60fps_chksum.md5"},
         {"avc", "bbb_avc_640x360_768kbps_30fps.h264", "bbb_avc_640x360_768kbps_30fps.info",
@@ -365,12 +365,12 @@
 void Codec2VideoDecHidlTestBase::GetURLChksmForComponent(char* mURL, char* info, char* chksum,
                                                          size_t streamIndex) {
     int streamCount = 0;
-    for (size_t i = 0; i < kCompToURL.size(); ++i) {
-        if (mMime.find(kCompToURL[i].mime) != std::string::npos) {
+    for (size_t i = 0; i < gCompToURL.size(); ++i) {
+        if (mMime.find(gCompToURL[i].mime) != std::string::npos) {
             if (streamCount == streamIndex) {
-                strcat(mURL, kCompToURL[i].mURL.c_str());
-                strcat(info, kCompToURL[i].info.c_str());
-                strcat(chksum, kCompToURL[i].chksum.c_str());
+                strcat(mURL, gCompToURL[i].mURL.c_str());
+                strcat(info, gCompToURL[i].info.c_str());
+                strcat(chksum, gCompToURL[i].chksum.c_str());
                 return;
             }
             streamCount++;
@@ -1074,16 +1074,16 @@
     ASSERT_EQ(mComponent->stop(), C2_OK);
 }
 
-INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2VideoDecHidlTest, testing::ValuesIn(kTestParameters),
+INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2VideoDecHidlTest, testing::ValuesIn(gTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 // DecodeTest with StreamIndex and EOS / No EOS
 INSTANTIATE_TEST_SUITE_P(StreamIndexAndEOS, Codec2VideoDecDecodeTest,
-                         testing::ValuesIn(kDecodeTestParameters),
+                         testing::ValuesIn(gDecodeTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 INSTANTIATE_TEST_SUITE_P(CsdInputs, Codec2VideoDecCsdInputTests,
-                         testing::ValuesIn(kCsdFlushTestParameters),
+                         testing::ValuesIn(gCsdFlushTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 }  // anonymous namespace
@@ -1091,24 +1091,24 @@
 // TODO : Video specific configuration Test
 int main(int argc, char** argv) {
     parseArgs(argc, argv);
-    kTestParameters = getTestParameters(C2Component::DOMAIN_VIDEO, C2Component::KIND_DECODER);
-    for (auto params : kTestParameters) {
-        kDecodeTestParameters.push_back(
+    gTestParameters = getTestParameters(C2Component::DOMAIN_VIDEO, C2Component::KIND_DECODER);
+    for (auto params : gTestParameters) {
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 0, false));
-        kDecodeTestParameters.push_back(
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 0, true));
-        kDecodeTestParameters.push_back(
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 1, false));
-        kDecodeTestParameters.push_back(
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 1, true));
-        kDecodeTestParameters.push_back(
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 2, false));
-        kDecodeTestParameters.push_back(
+        gDecodeTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 2, true));
 
-        kCsdFlushTestParameters.push_back(
+        gCsdFlushTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), true));
-        kCsdFlushTestParameters.push_back(
+        gCsdFlushTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), false));
     }
 
diff --git a/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoEncTest.cpp b/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoEncTest.cpp
index 23ceff4..8b40353 100644
--- a/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoEncTest.cpp
+++ b/media/codec2/hidl/1.0/vts/functional/video/VtsHalMediaC2V1_0TargetVideoEncTest.cpp
@@ -42,10 +42,10 @@
 };
 
 using EncodeTestParameters = std::tuple<std::string, std::string, bool, bool, bool>;
-static std::vector<EncodeTestParameters> kEncodeTestParameters;
+static std::vector<EncodeTestParameters> gEncodeTestParameters;
 
 using EncodeResolutionTestParameters = std::tuple<std::string, std::string, int32_t, int32_t>;
-static std::vector<EncodeResolutionTestParameters> kEncodeResolutionTestParameters;
+static std::vector<EncodeResolutionTestParameters> gEncodeResolutionTestParameters;
 
 namespace {
 
@@ -706,16 +706,16 @@
     ASSERT_EQ(mComponent->reset(), C2_OK);
 }
 
-INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2VideoEncHidlTest, testing::ValuesIn(kTestParameters),
+INSTANTIATE_TEST_SUITE_P(PerInstance, Codec2VideoEncHidlTest, testing::ValuesIn(gTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 INSTANTIATE_TEST_SUITE_P(NonStdSizes, Codec2VideoEncResolutionTest,
-                         ::testing::ValuesIn(kEncodeResolutionTestParameters),
+                         ::testing::ValuesIn(gEncodeResolutionTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 // EncodeTest with EOS / No EOS
 INSTANTIATE_TEST_SUITE_P(EncodeTestwithEOS, Codec2VideoEncEncodeTest,
-                         ::testing::ValuesIn(kEncodeTestParameters),
+                         ::testing::ValuesIn(gEncodeTestParameters),
                          PrintInstanceTupleNameToString<>);
 
 TEST_P(Codec2VideoEncHidlTest, AdaptiveBitrateTest) {
@@ -808,24 +808,24 @@
 
 int main(int argc, char** argv) {
     parseArgs(argc, argv);
-    kTestParameters = getTestParameters(C2Component::DOMAIN_VIDEO, C2Component::KIND_ENCODER);
-    for (auto params : kTestParameters) {
+    gTestParameters = getTestParameters(C2Component::DOMAIN_VIDEO, C2Component::KIND_ENCODER);
+    for (auto params : gTestParameters) {
         for (size_t i = 0; i < 1 << 3; ++i) {
-            kEncodeTestParameters.push_back(std::make_tuple(
+            gEncodeTestParameters.push_back(std::make_tuple(
                     std::get<0>(params), std::get<1>(params), i & 1, (i >> 1) & 1, (i >> 2) & 1));
         }
 
-        kEncodeResolutionTestParameters.push_back(
+        gEncodeResolutionTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 52, 18));
-        kEncodeResolutionTestParameters.push_back(
+        gEncodeResolutionTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 365, 365));
-        kEncodeResolutionTestParameters.push_back(
+        gEncodeResolutionTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 484, 362));
-        kEncodeResolutionTestParameters.push_back(
+        gEncodeResolutionTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 244, 488));
-        kEncodeResolutionTestParameters.push_back(
+        gEncodeResolutionTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 852, 608));
-        kEncodeResolutionTestParameters.push_back(
+        gEncodeResolutionTestParameters.push_back(
                 std::make_tuple(std::get<0>(params), std::get<1>(params), 1400, 442));
     }
 
diff --git a/media/libaaudio/src/client/AudioStreamInternal.cpp b/media/libaaudio/src/client/AudioStreamInternal.cpp
index dc961ad..bf07abb 100644
--- a/media/libaaudio/src/client/AudioStreamInternal.cpp
+++ b/media/libaaudio/src/client/AudioStreamInternal.cpp
@@ -100,8 +100,9 @@
     const int32_t burstMinMicros = AAudioProperty_getHardwareBurstMinMicros();
     int32_t burstMicros = 0;
 
+    const audio_format_t requestedFormat = getFormat();
     // We have to do volume scaling. So we prefer FLOAT format.
-    if (getFormat() == AUDIO_FORMAT_DEFAULT) {
+    if (requestedFormat == AUDIO_FORMAT_DEFAULT) {
         setFormat(AUDIO_FORMAT_PCM_FLOAT);
     }
     // Request FLOAT for the shared mixer or the device.
@@ -156,6 +157,12 @@
     mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_STREAM)
             + std::to_string(mServiceStreamHandle);
 
+    android::mediametrics::LogItem(mMetricsId)
+            .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
+                 AudioGlobal_convertPerformanceModeToText(getPerformanceMode()))
+            .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT,
+                 android::toString(requestedFormat).c_str()).record();
+
     result = configurationOutput.validate();
     if (result != AAUDIO_OK) {
         goto error;
diff --git a/media/libaaudio/src/core/AudioStream.cpp b/media/libaaudio/src/core/AudioStream.cpp
index ef83c8e..91b8a4d 100644
--- a/media/libaaudio/src/core/AudioStream.cpp
+++ b/media/libaaudio/src/core/AudioStream.cpp
@@ -56,16 +56,6 @@
 
     ALOGE_IF(mHasThread, "%s() callback thread never join()ed", __func__);
 
-    if (!mMetricsId.empty()) {
-        android::mediametrics::LogItem(mMetricsId)
-                .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_ENDAAUDIOSTREAM)
-                .set(AMEDIAMETRICS_PROP_ENCODINGREQUESTED,
-                     android::toString(mDeviceFormat).c_str())
-                .set(AMEDIAMETRICS_PROP_PERFORMANCEMODEACTUAL,
-                     AudioGlobal_convertPerformanceModeToText(getPerformanceMode()))
-                .record();
-    }
-
     // If the stream is deleted when OPEN or in use then audio resources will leak.
     // This would indicate an internal error. So we want to find this ASAP.
     LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
@@ -121,11 +111,11 @@
     return AAUDIO_OK;
 }
 
-void AudioStream::logOpen() {
+void AudioStream::logOpenActual() {
     if (mMetricsId.size() > 0) {
         android::mediametrics::LogItem item(mMetricsId);
         item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_OPEN)
-            .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
+            .set(AMEDIAMETRICS_PROP_PERFORMANCEMODEACTUAL,
                 AudioGlobal_convertPerformanceModeToText(getPerformanceMode()))
             .set(AMEDIAMETRICS_PROP_SHARINGMODE,
                 AudioGlobal_convertSharingModeToText(getSharingMode()))
@@ -359,6 +349,7 @@
                 .set(AMEDIAMETRICS_PROP_FRAMESTRANSFERRED,
                         getDirection() == AAUDIO_DIRECTION_INPUT ? getFramesWritten()
                                                                  : getFramesRead())
+                .set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_ENDAAUDIOSTREAM)
                 .record();
     }
 }
diff --git a/media/libaaudio/src/core/AudioStream.h b/media/libaaudio/src/core/AudioStream.h
index 3930964..2b45ed3 100644
--- a/media/libaaudio/src/core/AudioStream.h
+++ b/media/libaaudio/src/core/AudioStream.h
@@ -118,7 +118,7 @@
     virtual aaudio_result_t open(const AudioStreamBuilder& builder);
 
     // log to MediaMetrics
-    virtual void logOpen();
+    virtual void logOpenActual();
     void logReleaseBufferState();
 
     /* Note about naming for "release"  and "close" related methods.
diff --git a/media/libaaudio/src/core/AudioStreamBuilder.cpp b/media/libaaudio/src/core/AudioStreamBuilder.cpp
index 207a8e3..2135c54 100644
--- a/media/libaaudio/src/core/AudioStreamBuilder.cpp
+++ b/media/libaaudio/src/core/AudioStreamBuilder.cpp
@@ -189,7 +189,7 @@
         }
         if (result == AAUDIO_OK) {
             audioStream->registerPlayerBase();
-            audioStream->logOpen();
+            audioStream->logOpenActual();
             *streamPtr = startUsingStream(audioStream);
         } // else audioStream will go out of scope and be deleted
     }
diff --git a/media/libaaudio/src/legacy/AudioStreamRecord.cpp b/media/libaaudio/src/legacy/AudioStreamRecord.cpp
index e3ac6ff..de8fe6a 100644
--- a/media/libaaudio/src/legacy/AudioStreamRecord.cpp
+++ b/media/libaaudio/src/legacy/AudioStreamRecord.cpp
@@ -26,6 +26,7 @@
 #include <media/AudioRecord.h>
 #include <utils/String16.h>
 
+#include "core/AudioGlobal.h"
 #include "legacy/AudioStreamLegacy.h"
 #include "legacy/AudioStreamRecord.h"
 #include "utility/AudioClock.h"
@@ -92,8 +93,9 @@
             break;
     }
 
+    const audio_format_t requestedFormat = getFormat();
     // Preserve behavior of API 26
-    if (getFormat() == AUDIO_FORMAT_DEFAULT) {
+    if (requestedFormat == AUDIO_FORMAT_DEFAULT) {
         setFormat(AUDIO_FORMAT_PCM_FLOAT);
     }
 
@@ -217,6 +219,10 @@
 
     mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_RECORD)
             + std::to_string(mAudioRecord->getPortId());
+    android::mediametrics::LogItem(mMetricsId)
+            .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
+                 AudioGlobal_convertPerformanceModeToText(getPerformanceMode()))
+            .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT, toString(requestedFormat).c_str()).record();
 
     // Get the actual values from the AudioRecord.
     setSamplesPerFrame(mAudioRecord->channelCount());
diff --git a/media/libaaudio/src/legacy/AudioStreamTrack.cpp b/media/libaaudio/src/legacy/AudioStreamTrack.cpp
index df97658..2ee5cdc 100644
--- a/media/libaaudio/src/legacy/AudioStreamTrack.cpp
+++ b/media/libaaudio/src/legacy/AudioStreamTrack.cpp
@@ -23,9 +23,11 @@
 
 #include <aaudio/AAudio.h>
 #include <system/audio.h>
-#include "utility/AudioClock.h"
+
+#include "core/AudioGlobal.h"
 #include "legacy/AudioStreamLegacy.h"
 #include "legacy/AudioStreamTrack.h"
+#include "utility/AudioClock.h"
 #include "utility/FixedBlockReader.h"
 
 using namespace android;
@@ -187,6 +189,10 @@
 
     mMetricsId = std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_TRACK)
             + std::to_string(mAudioTrack->getPortId());
+    android::mediametrics::LogItem(mMetricsId)
+            .set(AMEDIAMETRICS_PROP_PERFORMANCEMODE,
+                 AudioGlobal_convertPerformanceModeToText(getPerformanceMode()))
+            .set(AMEDIAMETRICS_PROP_ENCODINGCLIENT, toString(getFormat()).c_str()).record();
 
     doSetVolume();
 
diff --git a/media/libdatasource/DataSourceFactory.cpp b/media/libdatasource/DataSourceFactory.cpp
index bb6a08c..f91e3ea 100644
--- a/media/libdatasource/DataSourceFactory.cpp
+++ b/media/libdatasource/DataSourceFactory.cpp
@@ -65,6 +65,9 @@
         sp<HTTPBase> mediaHTTP = httpSource;
         if (mediaHTTP == NULL) {
             mediaHTTP = static_cast<HTTPBase *>(CreateMediaHTTP(httpService).get());
+            if (mediaHTTP == NULL) {
+                return NULL;
+            }
         }
 
         String8 cacheConfig;
diff --git a/media/libmediaformatshaper/CodecProperties.cpp b/media/libmediaformatshaper/CodecProperties.cpp
index 315b3ec..b118af6 100644
--- a/media/libmediaformatshaper/CodecProperties.cpp
+++ b/media/libmediaformatshaper/CodecProperties.cpp
@@ -60,6 +60,13 @@
     mTargetQpMax = qpMax;
 }
 
+void CodecProperties::setMissingQpBoost(double boost) {
+    mMissingQpBoost = boost;
+}
+void CodecProperties::setPhaseOut(double phaseout) {
+    mPhaseOut = phaseout;
+}
+
 // what API is this codec set up for (e.g. API of the associated partition)
 // vendor-side (OEM) codecs may be older, due to 'vendor freeze' and treble
 int CodecProperties::supportedApi() {
@@ -134,6 +141,22 @@
             setBpp(bpp);
             legal = true;
         }
+    } else if (!strcmp(key.c_str(), "vq-bitrate-phaseout")) {
+        const char *p = value.c_str();
+        char *q;
+        double phaseout = strtod(p, &q);
+        if (q != p) {
+            setPhaseOut(phaseout);
+            legal = true;
+        }
+    } else if (!strcmp(key.c_str(), "vq-boost-missing-qp")) {
+        const char *p = value.c_str();
+        char *q;
+        double boost = strtod(p, &q);
+        if (q != p) {
+            setMissingQpBoost(boost);
+            legal = true;
+        }
     } else {
         legal = true;
     }
diff --git a/media/libmediaformatshaper/CodecProperties.h b/media/libmediaformatshaper/CodecProperties.h
index ff7051f..98ab99e 100644
--- a/media/libmediaformatshaper/CodecProperties.h
+++ b/media/libmediaformatshaper/CodecProperties.h
@@ -82,6 +82,14 @@
     void setSupportsQp(bool supported) { mSupportsQp = supported;}
     bool supportsQp() { return mSupportsQp;}
 
+    // defines our range of operation -- multiplier on the floor bitrate
+    double getPhaseOut() { return mPhaseOut; }
+    void setPhaseOut(double overageMultiplier);
+
+    // how much (0.20 = +20%) do we add if Qp is requested but unsupported
+    double getMissingQpBoost() {return mMissingQpBoost; }
+    void setMissingQpBoost(double boost);
+
     int  supportedApi();
 
     // a codec is not usable until it has been registered with its
@@ -98,6 +106,11 @@
     bool mSupportsQp = false;
     double mBpp = 0.0;
 
+    // target bitrates above floor * mPhaseOut are left untouched
+    double mPhaseOut = 1.75;
+    // 20% bump if QP is configured but it is unavailable
+    double mMissingQpBoost = 0.20;
+
     // allow different target bits-per-pixel based on resolution
     // similar to codec 'performance points'
     // uses 'next largest' (by pixel count) point as minimum bpp
diff --git a/media/libmediaformatshaper/CodecSeeding.cpp b/media/libmediaformatshaper/CodecSeeding.cpp
index 7fe1075..292b6df 100644
--- a/media/libmediaformatshaper/CodecSeeding.cpp
+++ b/media/libmediaformatshaper/CodecSeeding.cpp
@@ -49,25 +49,28 @@
  */
 
 static preloadTuning_t featuresAvc[] = {
-      // {true, "vq-target-bpp", "2.45"},
-      {true, "vq-target-bpp-1080p", "2.40"},
-      {true, "vq-target-bpp-540p", "2.60"},
+      {true, "vq-target-bpp-1080p", "1.90"},
+      {true, "vq-target-bpp-720p", "2.25"},
+      {true, "vq-target-bpp-540p", "2.65"},
       {true, "vq-target-bpp-480p", "3.00"},
       {true, "vq-target-qpmax", "40"},
+      {true, "vq-bitrate-phaseout", "1.75"},
+      {true, "vq-boost-missing-qp", "0.20"},
       {true, nullptr, 0}
 };
 
 static preloadTuning_t featuresHevc[] = {
-      // {true, "vq-target-bpp", "1.80"},
       {true, "vq-target-bpp-1080p", "1.50"},
       {true, "vq-target-bpp-720p", "1.80"},
       {true, "vq-target-bpp-540p", "2.10"},
-      // no qp for hevc, at least for now
+      {true, "vq-target-qpmax", "40"},
+      {true, "vq-bitrate-phaseout", "1.75"},
+      {true, "vq-boost-missing-qp", "0.20"},
       {true, nullptr, 0}
 };
 
 static preloadTuning_t featuresGenericVideo[] = {
-      {true, "vq-target-bpp", "2.40"},
+      {true, "vq-target-bpp", "2.00"},
       {true, nullptr, 0}
 };
 
diff --git a/media/libmediaformatshaper/VQApply.cpp b/media/libmediaformatshaper/VQApply.cpp
index 4f6a6c3..28ce43f 100644
--- a/media/libmediaformatshaper/VQApply.cpp
+++ b/media/libmediaformatshaper/VQApply.cpp
@@ -49,14 +49,6 @@
 static const int BITRATE_MODE_VBR = 1;
 
 
-// constants we use within the calculations
-//
-constexpr double BITRATE_LEAVE_UNTOUCHED = 1.75;
-
-// 20% bump if QP is configured but it is unavailable
-constexpr double BITRATE_QP_UNAVAILABLE_BOOST = 0.20;
-
-
 //
 // Caller retains ownership of and responsibility for inFormat
 //
@@ -100,7 +92,7 @@
     double minimumBpp = codec->getBpp(width, height);
 
     int64_t bitrateFloor = pixels * minimumBpp;
-    int64_t bitrateCeiling = bitrateFloor * BITRATE_LEAVE_UNTOUCHED;
+    int64_t bitrateCeiling = bitrateFloor * codec->getPhaseOut();
     if (bitrateFloor > INT32_MAX) bitrateFloor = INT32_MAX;
     if (bitrateCeiling > INT32_MAX) bitrateCeiling = INT32_MAX;
 
@@ -144,8 +136,7 @@
     // if QP is desired but not supported, compensate with additional bits
     if (!codec->supportsQp()) {
         if (qpChosen != INT32_MAX) {
-            int64_t boost = 0;
-            boost = bitrateChosen * BITRATE_QP_UNAVAILABLE_BOOST;
+            int64_t boost = bitrateChosen * codec->getMissingQpBoost();
             ALOGD("minquality: requested QP unsupported, boost bitrate %" PRId64 " by %" PRId64,
                 bitrateChosen, boost);
             bitrateChosen =  bitrateChosen + boost;
@@ -165,7 +156,7 @@
 
     if (bitrateChosen != bitrateConfigured) {
         if (bitrateChosen > bitrateCeiling) {
-            ALOGD("minquality: bitrate clamped at ceiling %" PRId64,  bitrateCeiling);
+            ALOGD("minquality: bitrate increase clamped at ceiling %" PRId64,  bitrateCeiling);
             bitrateChosen = bitrateCeiling;
         }
         ALOGD("minquality/target bitrate raised from %" PRId64 " to %" PRId64 " bps",
diff --git a/media/libmediametrics/include/MediaMetricsConstants.h b/media/libmediametrics/include/MediaMetricsConstants.h
index 383bae8..66108df 100644
--- a/media/libmediametrics/include/MediaMetricsConstants.h
+++ b/media/libmediametrics/include/MediaMetricsConstants.h
@@ -160,9 +160,9 @@
 #define AMEDIAMETRICS_PROP_VOLUME_LEFT    "volume.left"    // double (AudioTrack)
 #define AMEDIAMETRICS_PROP_VOLUME_RIGHT   "volume.right"   // double (AudioTrack)
 #define AMEDIAMETRICS_PROP_WHERE          "where"          // string value
-// EncodingRequested is the encoding format requested by the app
-#define AMEDIAMETRICS_PROP_ENCODINGREQUESTED "encodingRequested" // string
-// PerformanceModeActual is the actual selected performance mode, could be "none', "loeLatency" or
+// EncodingClient is the encoding format requested by the client
+#define AMEDIAMETRICS_PROP_ENCODINGCLIENT "encodingClient" // string
+// PerformanceModeActual is the actual selected performance mode, could be "none', "lowLatency" or
 // "powerSaving"
 #define AMEDIAMETRICS_PROP_PERFORMANCEMODEACTUAL "performanceModeActual" // string
 #define AMEDIAMETRICS_PROP_FRAMESTRANSFERRED "framesTransferred" // int64_t, transferred frames
diff --git a/media/libstagefright/foundation/Android.bp b/media/libstagefright/foundation/Android.bp
index 7655d90..4bfc673 100644
--- a/media/libstagefright/foundation/Android.bp
+++ b/media/libstagefright/foundation/Android.bp
@@ -45,6 +45,9 @@
     ],
 
     header_libs: [
+        // this is only needed for the vendor variant that removes libbinder, but vendor
+        // target below does not allow adding header_libs.
+        "libbinder_headers",
         "libstagefright_foundation_headers",
         "media_ndk_headers",
         "media_plugin_headers",
@@ -98,6 +101,7 @@
 
     target: {
         vendor: {
+            // TODO: add libbinder_headers here instead of above when it becomes supported
             exclude_shared_libs: [
                 "libbinder",
             ],
diff --git a/services/audioflinger/RecordTracks.h b/services/audioflinger/RecordTracks.h
index b953c0b..451c198 100644
--- a/services/audioflinger/RecordTracks.h
+++ b/services/audioflinger/RecordTracks.h
@@ -70,7 +70,7 @@
                                 audio_input_flags_t flags,
                                 track_type type,
                                 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE,
-                                int64_t startTimeMs = -1);
+                                int32_t startFrames = -1);
     virtual             ~RecordTrack();
     virtual status_t    initCheck() const;
 
@@ -110,7 +110,7 @@
             status_t    setPreferredMicrophoneFieldDimension(float zoom);
             status_t    shareAudioHistory(const std::string& sharedAudioPackageName,
                                           int64_t sharedAudioStartMs);
-            int64_t     startTimeMs() { return mStartTimeMs; }
+            int32_t     startFrames() { return mStartFrames; }
 
     static  bool        checkServerLatencySupported(
                                 audio_format_t format, audio_input_flags_t flags) {
@@ -152,7 +152,7 @@
             // used to enforce OP_RECORD_AUDIO
             sp<OpRecordAudioMonitor>           mOpRecordAudioMonitor;
             std::string                        mSharedAudioPackageName = {};
-            int64_t                            mStartTimeMs = -1;
+            int32_t                            mStartFrames = -1;
 };
 
 // playback track, used by PatchPanel
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index 6da4543..51f3032 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -124,12 +124,26 @@
 // 50 * ~20msecs = 1 second
 static const int8_t kMaxTrackRetries = 50;
 static const int8_t kMaxTrackStartupRetries = 50;
+
 // allow less retry attempts on direct output thread.
 // direct outputs can be a scarce resource in audio hardware and should
 // be released as quickly as possible.
-static const int8_t kMaxTrackRetriesDirect = 2;
-
-
+// Notes:
+// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
+//    in case the data write is bursty for the AudioTrack.  The application
+//    should endeavor to write at least once every kMaxTrackRetriesDirectMs
+//    to prevent an underrun situation.  If the data is bursty, then
+//    the application can also throttle the data sent to be even.
+// 2) For compressed audio data, any data present in the AudioTrack buffer
+//    will be sent and reset the retry count.  This delivers data as
+//    it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
+// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
+//    of data to be available, then any remaining data is delivered.
+//    This is required to ensure the last bit of data is delivered before underrun.
+//
+// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
+// or the size of the HAL period for proportional / linear PCM tracks.
+static const int32_t kMaxTrackRetriesDirectMs = 200;
 
 // don't warn about blocked writes or record buffer overflows more often than this
 static const nsecs_t kWarningThrottleNs = seconds(5);
@@ -5931,11 +5945,19 @@
         // Allow draining the buffer in case the client
         // app does not call stop() and relies on underrun to stop:
         // hence the test on (track->mRetryCount > 1).
-        // If retryCount<=1 then track is about to underrun and be removed.
+        // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
+        // so we accept any nonzero amount of data delivered by the AudioTrack (which will
+        // reset the retry counter).
         // Do not use a high threshold for compressed audio.
+
+        // target retry count that we will use is based on the time we wait for retries.
+        const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
+        // the retry threshold is when we accept any size for PCM data.  This is slightly
+        // smaller than the retry count so we can push small bits of data without a glitch.
+        const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
         uint32_t minFrames;
         if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
-            && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
+            && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
             minFrames = mNormalFrameCount;
         } else {
             minFrames = 1;
@@ -5979,7 +6001,7 @@
                 mPreviousTrack = track;
 
                 // reset retry count
-                track->mRetryCount = kMaxTrackRetriesDirect;
+                track->mRetryCount = targetRetryCount;
                 mActiveTrack = t;
                 mixerStatus = MIXER_TRACKS_READY;
                 if (mHwPaused) {
@@ -6033,15 +6055,17 @@
                     // indicate to client process that the track was disabled because of underrun;
                     // it will then automatically call start() when data is available
                     track->disable();
-                } else if (last) {
+                    // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
+                    // unlike mixerthread, HAL can be paused for direct output
                     ALOGW("pause because of UNDERRUN, framesReady = %zu,"
                             "minFrames = %u, mFormat = %#x",
                             framesReady, minFrames, mFormat);
-                    mixerStatus = MIXER_TRACKS_ENABLED;
-                    if (mHwSupportsPause && !mHwPaused && !mStandby) {
+                    if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
                         doHwPause = true;
                         mHwPaused = true;
                     }
+                } else if (last) {
+                    mixerStatus = MIXER_TRACKS_ENABLED;
                 }
             }
         }
@@ -6113,16 +6137,13 @@
         mSleepTimeUs = mIdleSleepTimeUs;
         return;
     }
-    if (mSleepTimeUs == 0) {
-        if (mMixerStatus == MIXER_TRACKS_ENABLED) {
-            mSleepTimeUs = mActiveSleepTimeUs;
-        } else {
-            mSleepTimeUs = mIdleSleepTimeUs;
-        }
-    } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
-        memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
-        mSleepTimeUs = 0;
+    if (mMixerStatus == MIXER_TRACKS_ENABLED) {
+        mSleepTimeUs = mActiveSleepTimeUs;
+    } else {
+        mSleepTimeUs = mIdleSleepTimeUs;
     }
+    // Note: In S or later, we do not write zeroes for
+    // linear or proportional PCM direct tracks in underrun.
 }
 
 void AudioFlinger::DirectOutputThread::threadLoop_exit()
@@ -7932,18 +7953,18 @@
 
     { // scope for mLock
         Mutex::Autolock _l(mLock);
-        long startTimeMs = -1;
+        int32_t startFrames = -1;
         if (!mSharedAudioPackageName.empty()
                 && mSharedAudioPackageName == checkedIdentity.packageName
                 && mSharedAudioSessionId == sessionId
                 && captureHotwordAllowed(checkedIdentity)) {
-            startTimeMs = mSharedAudioStartMs;
+            startFrames = mSharedAudioStartFrames;
         }
 
         track = new RecordTrack(this, client, attr, sampleRate,
                       format, channelMask, frameCount,
                       nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
-                      checkedIdentity, *flags, TrackBase::TYPE_DEFAULT, portId, startTimeMs);
+                      checkedIdentity, *flags, TrackBase::TYPE_DEFAULT, portId, startFrames);
 
         lStatus = track->initCheck();
         if (lStatus != NO_ERROR) {
@@ -8200,17 +8221,32 @@
     if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
         return BAD_VALUE;
     }
-    if (sharedAudioStartMs < 0 || sharedAudioStartMs * mSampleRate / 1000 > mRsmpInRear) {
+
+    if (sharedAudioStartMs < 0
+        || sharedAudioStartMs > INT64_MAX / mSampleRate) {
         return BAD_VALUE;
     }
 
+    // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
+    // As we cannot detect more than one wraparound, only accept values up current write position
+    // after one wraparound
+    // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
+    // app waits several hours after the start time was computed.
+    const int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
+    const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
+          (int32_t)sharedAudioStartFrames);
+    if (sharedOffset < 0
+          || sharedOffset > mRsmpInFrames) {
+      return BAD_VALUE;
+    }
+
     mSharedAudioPackageName = sharedAudioPackageName;
     if (mSharedAudioPackageName.empty()) {
         mSharedAudioSessionId = AUDIO_SESSION_NONE;
-        mSharedAudioStartMs = -1;
+        mSharedAudioStartFrames = -1;
     } else {
         mSharedAudioSessionId = sharedSessionId;
-        mSharedAudioStartMs = sharedAudioStartMs;
+        mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
     }
     return NO_ERROR;
 }
@@ -8357,14 +8393,14 @@
     mRsmpInUnrel = 0;
     const int32_t rear = recordThread->mRsmpInRear;
     ssize_t deltaFrames = 0;
-    if (mRecordTrack->startTimeMs() >= 0) {
-        int32_t startFrames = mRecordTrack->startTimeMs() * recordThread->sampleRate()  / 1000;
-        // start frame has to be in the past
-        //TODO: b/185972521 fix in case rear or startFrames wrap around
-        if (startFrames > rear) {
-            startFrames = rear;
+    if (mRecordTrack->startFrames() >= 0) {
+        int32_t startFrames = mRecordTrack->startFrames();
+        // Accept a recent wraparound of mRsmpInRear
+        if (startFrames <= rear) {
+            deltaFrames = rear - startFrames;
+        } else {
+            deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
         }
-        deltaFrames = rear - startFrames;
         // start frame cannot be further in the past than start of resampling buffer
         if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
             deltaFrames = recordThread->mRsmpInFrames;
@@ -8826,17 +8862,22 @@
     if (mTracks.size() == 0) {
         return 0;
     }
-    //TODO: b/185972521 fix in case of wrap around on one track:
-    //  want the max(rear - front) for all tracks.
-    int32_t front = INT_MAX;
+    int32_t oldestFront = mRsmpInRear;
+    int32_t maxFilled = 0;
     for (size_t i = 0; i < mTracks.size(); i++) {
-        front = std::min(front, mTracks[i]->mResamplerBufferProvider->getFront());
+        int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
+        int32_t filled;
+        if (front <= mRsmpInRear) {
+            filled = mRsmpInRear - front;
+        } else {
+            filled = (int32_t)((int64_t)mRsmpInRear + UINT32_MAX + 1 - front);
+        }
+        if (filled > maxFilled) {
+            oldestFront = front;
+            maxFilled = filled;
+        }
     }
-    // discard any audio past the buffer size
-    if (audio_utils::safe_add_overflow(front, (int32_t)mRsmpInFrames) < mRsmpInRear) {
-        front = audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
-    }
-    return front;
+    return oldestFront;
 }
 
 void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index 03ed6fd..b6f7f24 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -1863,7 +1863,7 @@
             DeviceDescriptorBaseVector          mOutDevices;
 
             std::string                         mSharedAudioPackageName = {};
-            long                                mSharedAudioStartMs = 0;
+            int32_t                             mSharedAudioStartFrames = -1;
             audio_session_t                     mSharedAudioSessionId = AUDIO_SESSION_NONE;
 };
 
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index 6549236..3e04804 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -2378,7 +2378,7 @@
             audio_input_flags_t flags,
             track_type type,
             audio_port_handle_t portId,
-            int64_t startTimeMs)
+            int32_t startFrames)
     :   TrackBase(thread, client, attr, sampleRate, format,
                   channelMask, frameCount, buffer, bufferSize, sessionId,
                   creatorPid,
@@ -2396,7 +2396,7 @@
         mFlags(flags),
         mSilenced(false),
         mOpRecordAudioMonitor(OpRecordAudioMonitor::createIfNeeded(identity, attr)),
-        mStartTimeMs(startTimeMs)
+        mStartFrames(startFrames)
 {
     if (mCblk == NULL) {
         return;
diff --git a/services/mediametrics/AudioAnalytics.cpp b/services/mediametrics/AudioAnalytics.cpp
index dbc68b2..fe86264 100644
--- a/services/mediametrics/AudioAnalytics.cpp
+++ b/services/mediametrics/AudioAnalytics.cpp
@@ -987,7 +987,7 @@
 
     std::string formatAppStr;
     mAudioAnalytics.mAnalyticsState->timeMachine().get(
-            key, AMEDIAMETRICS_PROP_ENCODINGREQUESTED, &formatAppStr);
+            key, AMEDIAMETRICS_PROP_ENCODINGCLIENT, &formatAppStr);
     const auto formatApp = types::lookup<types::ENCODING, int32_t>(formatAppStr);
 
     std::string formatDeviceStr;
diff --git a/services/mediametrics/statsd_codec.cpp b/services/mediametrics/statsd_codec.cpp
index 4539ad5..2cfdf24 100644
--- a/services/mediametrics/statsd_codec.cpp
+++ b/services/mediametrics/statsd_codec.cpp
@@ -294,6 +294,12 @@
         metrics_proto.set_video_input_frames(inputFrames);
     }
 
+    // android.media.mediacodec.original.bitrate
+    int32_t originalBitrate = -1;
+    if ( item->getInt32("android.media.mediacodec.original.bitrate", &originalBitrate)) {
+        metrics_proto.set_original_bitrate(originalBitrate);
+    }
+
     std::string serialized;
     if (!metrics_proto.SerializeToString(&serialized)) {
         ALOGE("Failed to serialize codec metrics");