Merge "Factor out repeated code into function" into main
diff --git a/audio/aidl/Android.bp b/audio/aidl/Android.bp
index 0f2fe99..97577d1 100644
--- a/audio/aidl/Android.bp
+++ b/audio/aidl/Android.bp
@@ -60,7 +60,7 @@
         ndk: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.btservices",
+                "com.android.bt",
             ],
             min_sdk_version: "31",
         },
diff --git a/audio/aidl/android/hardware/audio/effect/Visualizer.aidl b/audio/aidl/android/hardware/audio/effect/Visualizer.aidl
index 0b37546..fe8fe97 100644
--- a/audio/aidl/android/hardware/audio/effect/Visualizer.aidl
+++ b/audio/aidl/android/hardware/audio/effect/Visualizer.aidl
@@ -20,10 +20,12 @@
 
 /**
  * Visualizer specific definitions. Visualizer enables application to retrieve part of the currently
- * playing audio for visualization purpose
+ * playing audio for visualization purpose. The output is identical to the input, while
+ * visualization data is generated separately based on scalingMode and captureSamples parameter
+ * values.
  *
  * All parameter settings must be inside the range of Capability.Range.visualizer definition if the
- * definition for the corresponding parameter tag exist. See more detals about Range in Range.aidl.
+ * definition for the corresponding parameter tag exist. See more details about Range in Range.aidl.
  *
  */
 @VintfStability
@@ -50,14 +52,24 @@
     enum ScalingMode {
         /**
          * Defines a capture mode where amplification is applied based on the content of the
-         * captured data. This is the default Visualizer mode, and is suitable for music
-         * visualization.
+         * captured data in order to normalize it to the unsigned 8 bit sample range. This is the
+         * default Visualizer mode, and is suitable for music visualization.
+         *
+         * For example,
+         * Input Range:[-0.5, 0.5] -> Visualization Data Range:[0, 255]
+         * Input Range:[-1,1]      -> Visualization Data Range:[0, 255]
+         *
          */
         NORMALIZED = 0,
         /**
-         * Defines a capture mode where the playback volume will affect (scale) the range of the
-         * captured data. A low playback volume will lead to low sample and fft values, and
-         * vice-versa.
+         * Defines a capture mode where no additional scaling is done on the input audio data thus
+         * the visualization data remains as close as possible to the input. The visualization
+         * directly reflects the actual loudness and waveform shape, rather than fitting everything
+         * into a normalized visual range.
+         *
+         * For example,
+         * Input Range:[-0.5, 0.5] -> Visualization Data Range:[64, 192]
+         * Input Range:[-1,1]      -> Visualization Data Range:[0, 255]
          */
         AS_PLAYED,
     }
@@ -93,7 +105,10 @@
     Measurement measurement;
 
     /**
-     * Get only parameter to get the latest captured samples of PCM samples (8 bits per sample).
+     * Get only parameter to get the latest captured samples of PCM samples (8 bits per sample). It
+     * represents the visualization data. The capture is intended for passing to applications, and
+     * it contains the same audio data as the input, but with intentionally lower sample resolution,
+     * and optionally normalized, depending on the scalingMode.
      */
     byte[] captureSampleBuffer;
 
diff --git a/audio/aidl/vts/EffectHelper.h b/audio/aidl/vts/EffectHelper.h
index 8ceb56b..754a08f 100644
--- a/audio/aidl/vts/EffectHelper.h
+++ b/audio/aidl/vts/EffectHelper.h
@@ -85,7 +85,9 @@
 }
 
 static constexpr float kMaxAudioSampleValue = 1;
+static constexpr int kNPointFFT = 16384;
 static constexpr int kSamplingFrequency = 44100;
+static constexpr int kDefaultChannelLayout = AudioChannelLayout::LAYOUT_STEREO;
 
 class EffectHelper {
   public:
@@ -259,13 +261,14 @@
         EXPECT_TRUE(efState & kEventFlagDataMqUpdate);
     }
 
-    Parameter::Common createParamCommon(int session = 0, int ioHandle = -1, int iSampleRate = 48000,
-                                        int oSampleRate = 48000, long iFrameCount = 0x100,
-                                        long oFrameCount = 0x100) {
-        AudioChannelLayout inputLayout = AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
-                AudioChannelLayout::LAYOUT_STEREO);
-        AudioChannelLayout outputLayout = inputLayout;
-
+    Parameter::Common createParamCommon(
+            int session = 0, int ioHandle = -1, int iSampleRate = 48000, int oSampleRate = 48000,
+            long iFrameCount = 0x100, long oFrameCount = 0x100,
+            AudioChannelLayout inputChannelLayout =
+                    AudioChannelLayout::make<AudioChannelLayout::layoutMask>(kDefaultChannelLayout),
+            AudioChannelLayout outputChannelLayout =
+                    AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
+                            kDefaultChannelLayout)) {
         // query supported input layout and use it as the default parameter in common
         if (mIsSpatializer && isRangeValid<Range::spatializer>(Spatializer::supportedChannelLayout,
                                                                mDescriptor.capability)) {
@@ -275,18 +278,10 @@
                 layoutRange &&
                 0 != (layouts = layoutRange->min.get<Spatializer::supportedChannelLayout>())
                                 .size()) {
-                inputLayout = layouts[0];
+                inputChannelLayout = layouts[0];
             }
         }
 
-        return createParamCommon(session, ioHandle, iSampleRate, oSampleRate, iFrameCount,
-                                 oFrameCount, inputLayout, outputLayout);
-    }
-
-    static Parameter::Common createParamCommon(int session, int ioHandle, int iSampleRate,
-                                               int oSampleRate, long iFrameCount, long oFrameCount,
-                                               AudioChannelLayout inputChannelLayout,
-                                               AudioChannelLayout outputChannelLayout) {
         Parameter::Common common;
         common.session = session;
         common.ioHandle = ioHandle;
@@ -463,43 +458,120 @@
 
     // Generate multitone input between -amplitude to +amplitude using testFrequencies
     // All test frequencies are considered having the same amplitude
+    // The function supports only mono and stereo channel layout
     void generateSineWave(const std::vector<int>& testFrequencies, std::vector<float>& input,
                           const float amplitude = 1.0,
-                          const int samplingFrequency = kSamplingFrequency) {
-        for (size_t i = 0; i < input.size(); i++) {
+                          const int samplingFrequency = kSamplingFrequency,
+                          int channelLayout = AudioChannelLayout::LAYOUT_STEREO) {
+        bool isStereo = (channelLayout == AudioChannelLayout::LAYOUT_STEREO);
+        if (isStereo) {
+            ASSERT_EQ(input.size() % 2, 0u)
+                    << "In case of stereo input, the input size value must be even";
+        }
+        for (size_t i = 0; i < input.size(); i += (isStereo ? 2 : 1)) {
             input[i] = 0;
 
             for (size_t j = 0; j < testFrequencies.size(); j++) {
-                input[i] += sin(2 * M_PI * testFrequencies[j] * i / samplingFrequency);
+                input[i] += sin(2 * M_PI * testFrequencies[j] * (i / (isStereo ? 2 : 1)) /
+                                samplingFrequency);
             }
             input[i] *= amplitude / testFrequencies.size();
+
+            if (isStereo) {
+                input[i + 1] = input[i];
+            }
         }
     }
 
     // Generate single tone input between -amplitude to +amplitude using testFrequency
+    // The function supports only mono and stereo channel layout
     void generateSineWave(const int testFrequency, std::vector<float>& input,
                           const float amplitude = 1.0,
-                          const int samplingFrequency = kSamplingFrequency) {
-        generateSineWave(std::vector<int>{testFrequency}, input, amplitude, samplingFrequency);
+                          const int samplingFrequency = kSamplingFrequency,
+                          int channelLayout = AudioChannelLayout::LAYOUT_STEREO) {
+        ASSERT_NO_FATAL_FAILURE(generateSineWave(std::vector<int>{testFrequency}, input, amplitude,
+                                                 samplingFrequency, channelLayout));
+    }
+
+    // PFFFT only supports transforms for inputs of length N of the form N = (2^a)*(3^b)*(5^c) where
+    // a >= 5, b >=0, c >= 0.
+    constexpr bool isFftInputSizeValid(size_t n) {
+        if (n == 0 || n & 0b11111) {
+            return false;
+        }
+        for (const int factor : {2, 3, 5}) {
+            while (n % factor == 0) {
+                n /= factor;
+            }
+        }
+        return n == 1;
     }
 
     // Use FFT transform to convert the buffer to frequency domain
     // Compute its magnitude at binOffsets
-    std::vector<float> calculateMagnitude(const std::vector<float>& buffer,
-                                          const std::vector<int>& binOffsets, const int nPointFFT) {
+    void calculateMagnitudeMono(std::vector<float>& bufferMag,       // Output parameter
+                                const std::vector<float>& buffer,    // Input parameter
+                                const std::vector<int>& binOffsets,  // Input parameter
+                                const int nPointFFT = kNPointFFT) {  // Input parameter
+        ASSERT_TRUE(isFftInputSizeValid(nPointFFT))
+                << "PFFFT only supports transforms for inputs of length N of the form N = (2 ^ a) "
+                   "* (3 ^ b) * (5 ^ c) where a >= 5, b >= 0, c >= 0. ";
+        ASSERT_GE((int)buffer.size(), nPointFFT)
+                << "The input(buffer) size must be greater than or equal to nPointFFT";
+        bufferMag.resize(binOffsets.size());
         std::vector<float> fftInput(nPointFFT);
         PFFFT_Setup* inputHandle = pffft_new_setup(nPointFFT, PFFFT_REAL);
         pffft_transform_ordered(inputHandle, buffer.data(), fftInput.data(), nullptr,
                                 PFFFT_FORWARD);
         pffft_destroy_setup(inputHandle);
-        std::vector<float> bufferMag(binOffsets.size());
         for (size_t i = 0; i < binOffsets.size(); i++) {
             size_t k = binOffsets[i];
             bufferMag[i] = sqrt((fftInput[k * 2] * fftInput[k * 2]) +
                                 (fftInput[k * 2 + 1] * fftInput[k * 2 + 1]));
         }
+    }
 
-        return bufferMag;
+    // Use FFT transform to convert the buffer to frequency domain
+    // Compute its magnitude at binOffsets
+    void calculateMagnitudeStereo(
+            std::pair<std::vector<float>, std::vector<float>>& bufferMag,  // Output parameter
+            const std::vector<float>& buffer,                              // Input parameter
+            const std::vector<int>& binOffsets,                            // Input parameter
+            const int nPointFFT = kNPointFFT) {                            // Input parameter
+        std::vector<float> leftChannelBuffer(buffer.size() / 2),
+                rightChannelBuffer(buffer.size() / 2);
+        for (size_t i = 0; i < buffer.size(); i += 2) {
+            leftChannelBuffer[i / 2] = buffer[i];
+            rightChannelBuffer[i / 2] = buffer[i + 1];
+        }
+        std::vector<float> leftMagnitude(binOffsets.size());
+        std::vector<float> rightMagnitude(binOffsets.size());
+
+        ASSERT_NO_FATAL_FAILURE(
+                calculateMagnitudeMono(leftMagnitude, leftChannelBuffer, binOffsets, nPointFFT));
+        ASSERT_NO_FATAL_FAILURE(
+                calculateMagnitudeMono(rightMagnitude, rightChannelBuffer, binOffsets, nPointFFT));
+
+        bufferMag = {leftMagnitude, rightMagnitude};
+    }
+
+    // Computes magnitude for mono and stereo inputs and verifies equal magnitude for left and right
+    // channel in case of stereo inputs
+    void calculateAndVerifyMagnitude(std::vector<float>& mag,             // Output parameter
+                                     const int channelLayout,             // Input parameter
+                                     const std::vector<float>& buffer,    // Input parameter
+                                     const std::vector<int>& binOffsets,  // Input parameter
+                                     const int nPointFFT = kNPointFFT) {  // Input parameter
+        if (channelLayout == AudioChannelLayout::LAYOUT_STEREO) {
+            std::pair<std::vector<float>, std::vector<float>> magStereo;
+            ASSERT_NO_FATAL_FAILURE(
+                    calculateMagnitudeStereo(magStereo, buffer, binOffsets, nPointFFT));
+            ASSERT_EQ(magStereo.first, magStereo.second);
+
+            mag = magStereo.first;
+        } else {
+            ASSERT_NO_FATAL_FAILURE(calculateMagnitudeMono(mag, buffer, binOffsets, nPointFFT));
+        }
     }
 
     void updateFrameSize(const Parameter::Common& common) {
diff --git a/audio/aidl/vts/VtsHalBassBoostTargetTest.cpp b/audio/aidl/vts/VtsHalBassBoostTargetTest.cpp
index 5a24be7..c3c1e9e 100644
--- a/audio/aidl/vts/VtsHalBassBoostTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalBassBoostTargetTest.cpp
@@ -48,7 +48,7 @@
 
 class BassBoostEffectHelper : public EffectHelper {
   public:
-    void SetUpBassBoost(int32_t layout = AudioChannelLayout::LAYOUT_STEREO) {
+    void SetUpBassBoost(int32_t layout = kDefaultChannelLayout) {
         ASSERT_NE(nullptr, mFactory);
         ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
         setFrameCounts(layout);
@@ -113,7 +113,7 @@
         }
     }
 
-    static constexpr int kDurationMilliSec = 720;
+    static constexpr int kDurationMilliSec = 1440;
     static constexpr int kInputSize = kSamplingFrequency * kDurationMilliSec / 1000;
     long mInputFrameCount, mOutputFrameCount;
     std::shared_ptr<IFactory> mFactory;
@@ -187,25 +187,6 @@
         }
     }
 
-    // Use FFT transform to convert the buffer to frequency domain
-    // Compute its magnitude at binOffsets
-    std::vector<float> calculateMagnitude(const std::vector<float>& buffer,
-                                          const std::vector<int>& binOffsets) {
-        std::vector<float> fftInput(kNPointFFT);
-        PFFFT_Setup* inputHandle = pffft_new_setup(kNPointFFT, PFFFT_REAL);
-        pffft_transform_ordered(inputHandle, buffer.data(), fftInput.data(), nullptr,
-                                PFFFT_FORWARD);
-        pffft_destroy_setup(inputHandle);
-        std::vector<float> bufferMag(binOffsets.size());
-        for (size_t i = 0; i < binOffsets.size(); i++) {
-            size_t k = binOffsets[i];
-            bufferMag[i] = sqrt((fftInput[k * 2] * fftInput[k * 2]) +
-                                (fftInput[k * 2 + 1] * fftInput[k * 2 + 1]));
-        }
-
-        return bufferMag;
-    }
-
     // Calculate gain difference between low frequency and high frequency magnitude
     float calculateGainDiff(const std::vector<float>& inputMag,
                             const std::vector<float>& outputMag) {
@@ -218,7 +199,6 @@
         return gains[0] - gains[1];
     }
 
-    static constexpr int kNPointFFT = 16384;
     static constexpr float kBinWidth = (float)kSamplingFrequency / kNPointFFT;
     std::set<int> mStrengthValues;
     int32_t mChannelLayout;
@@ -240,9 +220,11 @@
     roundToFreqCenteredToFftBin(testFrequencies, binOffsets);
 
     // Generate multitone input
-    generateSineWave(testFrequencies, input);
+    ASSERT_NO_FATAL_FAILURE(
+            generateSineWave(testFrequencies, input, 1.0, kSamplingFrequency, mChannelLayout));
 
-    inputMag = calculateMagnitude(input, binOffsets);
+    ASSERT_NO_FATAL_FAILURE(
+            calculateAndVerifyMagnitude(inputMag, mChannelLayout, input, binOffsets));
 
     if (isStrengthValid(0)) {
         ASSERT_NO_FATAL_FAILURE(setAndVerifyParameters(0, EX_NONE));
@@ -254,7 +236,10 @@
             processAndWriteToOutput(input, baseOutput, mEffect, &mOpenEffectReturn));
 
     std::vector<float> baseMag(testFrequencies.size());
-    baseMag = calculateMagnitude(baseOutput, binOffsets);
+
+    ASSERT_NO_FATAL_FAILURE(
+            calculateAndVerifyMagnitude(baseMag, mChannelLayout, baseOutput, binOffsets));
+
     float baseDiff = calculateGainDiff(inputMag, baseMag);
 
     for (int strength : mStrengthValues) {
@@ -271,7 +256,9 @@
         ASSERT_NO_FATAL_FAILURE(
                 processAndWriteToOutput(input, output, mEffect, &mOpenEffectReturn));
 
-        outputMag = calculateMagnitude(output, binOffsets);
+        ASSERT_NO_FATAL_FAILURE(
+                calculateAndVerifyMagnitude(outputMag, mChannelLayout, output, binOffsets));
+
         float diff = calculateGainDiff(inputMag, outputMag);
 
         ASSERT_GT(diff, prevGain);
diff --git a/audio/aidl/vts/VtsHalDownmixTargetTest.cpp b/audio/aidl/vts/VtsHalDownmixTargetTest.cpp
index 322fdc0..5c5be3a 100644
--- a/audio/aidl/vts/VtsHalDownmixTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalDownmixTargetTest.cpp
@@ -86,7 +86,7 @@
 
 class DownmixEffectHelper : public EffectHelper {
   public:
-    void SetUpDownmix(int32_t inputBufferLayout = AudioChannelLayout::LAYOUT_STEREO) {
+    void SetUpDownmix(int32_t inputBufferLayout = kDefaultChannelLayout) {
         ASSERT_NE(nullptr, mFactory);
         ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
 
diff --git a/audio/aidl/vts/VtsHalDynamicsProcessingTest.cpp b/audio/aidl/vts/VtsHalDynamicsProcessingTest.cpp
index 37441f0..09b6621 100644
--- a/audio/aidl/vts/VtsHalDynamicsProcessingTest.cpp
+++ b/audio/aidl/vts/VtsHalDynamicsProcessingTest.cpp
@@ -46,8 +46,8 @@
 class DynamicsProcessingTestHelper : public EffectHelper {
   public:
     DynamicsProcessingTestHelper(std::pair<std::shared_ptr<IFactory>, Descriptor> pair,
-                                 int32_t channelLayOut = AudioChannelLayout::LAYOUT_STEREO)
-        : mChannelLayout(channelLayOut),
+                                 int32_t channelLayout = kDefaultChannelLayout)
+        : mChannelLayout(channelLayout),
           mChannelCount(::aidl::android::hardware::audio::common::getChannelCount(
                   AudioChannelLayout::make<AudioChannelLayout::layoutMask>(mChannelLayout))) {
         std::tie(mFactory, mDescriptor) = pair;
@@ -162,11 +162,12 @@
     static const std::set<std::vector<DynamicsProcessing::InputGain>> kInputGainTestSet;
 
   private:
-    const int32_t mChannelLayout;
     std::vector<std::pair<DynamicsProcessing::Tag, DynamicsProcessing>> mTags;
 
   protected:
+    const int32_t mChannelLayout;
     const int mChannelCount;
+
     void CleanUp() {
         mTags.clear();
         mPreEqChannelEnable.clear();
@@ -397,6 +398,8 @@
     return true;
 }
 
+// This function calculates power for both and mono and stereo data as the total power for
+// interleaved multichannel data can be calculated by treating it as a continuous mono input.
 float DynamicsProcessingTestHelper::calculateDb(const std::vector<float>& input,
                                                 size_t startSamplePos = 0) {
     return audio_utils_compute_power_mono(input.data() + startSamplePos, AUDIO_FORMAT_PCM_FLOAT,
@@ -623,13 +626,14 @@
     DynamicsProcessingInputGainDataTest()
         : DynamicsProcessingTestHelper((GetParam()), AudioChannelLayout::LAYOUT_MONO) {
         mInput.resize(kFrameCount * mChannelCount);
-        generateSineWave(kInputFrequency /*Input Frequency*/, mInput);
-        mInputDb = calculateDb(mInput);
     }
 
     void SetUp() override {
         SetUpDynamicsProcessingEffect();
         SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+        ASSERT_NO_FATAL_FAILURE(generateSineWave(kInputFrequency /*Input Frequency*/, mInput, 1.0,
+                                                 kSamplingFrequency, mChannelLayout));
+        mInputDb = calculateDb(mInput);
     }
 
     void TearDown() override { TearDownDynamicsProcessingEffect(); }
@@ -758,13 +762,14 @@
         : DynamicsProcessingTestHelper(GetParam(), AudioChannelLayout::LAYOUT_MONO) {
         mBufferSize = kFrameCount * mChannelCount;
         mInput.resize(mBufferSize);
-        generateSineWave(1000 /*Input Frequency*/, mInput);
-        mInputDb = calculateDb(mInput);
     }
 
     void SetUp() override {
         SetUpDynamicsProcessingEffect();
         SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+        ASSERT_NO_FATAL_FAILURE(generateSineWave(1000 /*Input Frequency*/, mInput, 1.0,
+                                                 kSamplingFrequency, mChannelLayout));
+        mInputDb = calculateDb(mInput);
     }
 
     void TearDown() override { TearDownDynamicsProcessingEffect(); }
diff --git a/audio/aidl/vts/VtsHalEnvironmentalReverbTargetTest.cpp b/audio/aidl/vts/VtsHalEnvironmentalReverbTargetTest.cpp
index bf48a87..0222923 100644
--- a/audio/aidl/vts/VtsHalEnvironmentalReverbTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalEnvironmentalReverbTargetTest.cpp
@@ -139,6 +139,7 @@
 
     return valueTag;
 }
+
 /**
  * Tests do the following:
  * - Testing parameter range supported by the effect. Range is verified with IEffect.getDescriptor()
@@ -282,10 +283,10 @@
     static constexpr int kDurationMilliSec = 500;
     static constexpr int kBufferSize = kSamplingFrequency * kDurationMilliSec / 1000;
     static constexpr int kInputFrequency = 2000;
+    static constexpr int mChannelLayout = AudioChannelLayout::LAYOUT_STEREO;
 
-    int mStereoChannelCount =
-            getChannelCount(AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
-                    AudioChannelLayout::LAYOUT_STEREO));
+    int mStereoChannelCount = getChannelCount(
+            AudioChannelLayout::make<AudioChannelLayout::layoutMask>(mChannelLayout));
     int mFrameCount = kBufferSize / mStereoChannelCount;
 
     std::shared_ptr<IFactory> mFactory;
@@ -344,10 +345,11 @@
         : EnvironmentalReverbHelper(std::get<DESCRIPTOR_INDEX>(GetParam())) {
         std::tie(mTag, mParamValues) = std::get<TAG_VALUE_PAIR>(GetParam());
         mInput.resize(kBufferSize);
-        generateSineWave(kInputFrequency, mInput);
     }
     void SetUp() override {
         SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+        ASSERT_NO_FATAL_FAILURE(
+                generateSineWave(kInputFrequency, mInput, 1.0, kSamplingFrequency, mChannelLayout));
         SetUpReverb();
     }
     void TearDown() override {
@@ -434,7 +436,8 @@
 
 TEST_P(EnvironmentalReverbMinimumParamTest, MinimumValueTest) {
     std::vector<float> input(kBufferSize);
-    generateSineWave(kInputFrequency, input);
+    ASSERT_NO_FATAL_FAILURE(
+            generateSineWave(kInputFrequency, input, 1.0, kSamplingFrequency, mChannelLayout));
     std::vector<float> output(kBufferSize);
     setParameterAndProcess(input, output, mValue, mTag);
     float energy = computeOutputEnergy(input, output);
@@ -470,10 +473,11 @@
         : EnvironmentalReverbHelper(std::get<DESCRIPTOR_INDEX>(GetParam())) {
         std::tie(mTag, mParamValues) = std::get<TAG_VALUE_PAIR>(GetParam());
         mInput.resize(kBufferSize);
-        generateSineWave(kInputFrequency, mInput);
     }
     void SetUp() override {
         SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+        ASSERT_NO_FATAL_FAILURE(
+                generateSineWave(kInputFrequency, mInput, 1.0, kSamplingFrequency, mChannelLayout));
         SetUpReverb();
     }
     void TearDown() override {
@@ -546,14 +550,15 @@
         mParamValues = std::get<PARAM_DENSITY_VALUE>(GetParam());
         mIsInputMute = (std::get<IS_INPUT_MUTE>(GetParam()));
         mInput.resize(kBufferSize);
-        if (mIsInputMute) {
-            std::fill(mInput.begin(), mInput.end(), 0);
-        } else {
-            generateSineWave(kInputFrequency, mInput);
-        }
     }
     void SetUp() override {
         SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+        if (mIsInputMute) {
+            std::fill(mInput.begin(), mInput.end(), 0);
+        } else {
+            ASSERT_NO_FATAL_FAILURE(generateSineWave(kInputFrequency, mInput, 1.0,
+                                                     kSamplingFrequency, mChannelLayout));
+        }
         SetUpReverb();
     }
     void TearDown() override {
diff --git a/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp b/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
index 4c868a9..ace0597 100644
--- a/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
@@ -153,9 +153,8 @@
   public:
     LoudnessEnhancerDataTest() {
         std::tie(mFactory, mDescriptor) = GetParam();
-        size_t channelCount =
-                getChannelCount(AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
-                        AudioChannelLayout::LAYOUT_STEREO));
+        size_t channelCount = getChannelCount(
+                AudioChannelLayout::make<AudioChannelLayout::layoutMask>(kDefaultChannelLayout));
         mBufferSizeInFrames = kFrameCount * channelCount;
         mInputBuffer.resize(mBufferSizeInFrames);
         generateInputBuffer(mInputBuffer, 0, true, channelCount, kMaxAudioSampleValue);
diff --git a/audio/aidl/vts/VtsHalPresetReverbTargetTest.cpp b/audio/aidl/vts/VtsHalPresetReverbTargetTest.cpp
index 3ce9e53..f127c81 100644
--- a/audio/aidl/vts/VtsHalPresetReverbTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalPresetReverbTargetTest.cpp
@@ -133,11 +133,11 @@
     PresetReverbProcessTest() {
         std::tie(mFactory, mDescriptor) = GetParam();
         mInput.resize(kBufferSize);
-        generateSineWave(1000 /*Input Frequency*/, mInput);
     }
 
     void SetUp() override {
         SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
+        ASSERT_NO_FATAL_FAILURE(generateSineWave(1000 /*Input Frequency*/, mInput));
         ASSERT_NO_FATAL_FAILURE(SetUpPresetReverb());
     }
     void TearDown() override {
diff --git a/audio/aidl/vts/VtsHalVirtualizerTargetTest.cpp b/audio/aidl/vts/VtsHalVirtualizerTargetTest.cpp
index 3021370..c9c7172 100644
--- a/audio/aidl/vts/VtsHalVirtualizerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalVirtualizerTargetTest.cpp
@@ -94,7 +94,6 @@
         }
     }
 
-    static constexpr int kDefaultChannelLayout = AudioChannelLayout::LAYOUT_STEREO;
     static constexpr int kDurationMilliSec = 720;
     static constexpr int kBufferSize = kSamplingFrequency * kDurationMilliSec / 1000;
     int kChannelCount = getChannelCount(
@@ -159,14 +158,6 @@
         ASSERT_NO_FATAL_FAILURE(TearDownVirtualizer());
     }
 
-    void generateInput(std::vector<float>& buffer) {
-        if (mZeroInput) {
-            std::fill(buffer.begin(), buffer.end(), 0);
-        } else {
-            generateSineWave(1000 /*Input Frequency*/, buffer);
-        }
-    }
-
     static constexpr float kAbsError = 0.00001;
     bool mZeroInput;
 };
@@ -176,7 +167,11 @@
     std::vector<float> output(kBufferSize);
     std::vector<int> strengths = {250, 500, 750, 1000};
 
-    generateInput(input);
+    if (mZeroInput) {
+        std::fill(input.begin(), input.end(), 0);
+    } else {
+        ASSERT_NO_FATAL_FAILURE(generateSineWave(1000 /*Input Frequency*/, input));
+    }
 
     const float inputRmse =
             audio_utils_compute_energy_mono(input.data(), AUDIO_FORMAT_PCM_FLOAT, input.size());
diff --git a/audio/aidl/vts/VtsHalVisualizerTargetTest.cpp b/audio/aidl/vts/VtsHalVisualizerTargetTest.cpp
index 3b07809..f019e2a 100644
--- a/audio/aidl/vts/VtsHalVisualizerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalVisualizerTargetTest.cpp
@@ -68,9 +68,14 @@
         ASSERT_NE(nullptr, mFactory);
         ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mDescriptor));
 
+        AudioChannelLayout inputLayout = AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
+                AudioChannelLayout::LAYOUT_MONO);
+        AudioChannelLayout outputLayout = inputLayout;
+
         Parameter::Common common = createParamCommon(
-                0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
-                kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+                0 /* session */, 1 /* ioHandle */, mBufferSizeInFrames /* iSampleRate */,
+                mBufferSizeInFrames /* oSampleRate */, kInputFrameCount /* iFrameCount */,
+                kOutputFrameCount /* oFrameCount */, inputLayout, outputLayout);
         ASSERT_NO_FATAL_FAILURE(open(mEffect, common, std::nullopt, &mOpenEffectReturn, EX_NONE));
         ASSERT_NE(nullptr, mEffect);
         mVersion = EffectFactoryHelper::getHalVersion(mFactory);
@@ -261,7 +266,8 @@
 
     constexpr float kPowerToleranceDb = 0.5;
 
-    generateSineWave(std::vector<int>{1000}, mInputBuffer, 1.0, mBufferSizeInFrames);
+    ASSERT_NO_FATAL_FAILURE(generateSineWave(1000, mInputBuffer, 1.0, mBufferSizeInFrames,
+                                             AudioChannelLayout::LAYOUT_MONO));
     const float expectedPowerNormalized = audio_utils_compute_power_mono(
             mInputBuffer.data(), AUDIO_FORMAT_PCM_FLOAT, mInputBuffer.size());
 
@@ -281,8 +287,9 @@
         addLatencyParam(mLatency);
         ASSERT_NO_FATAL_FAILURE(SetAndGetParameters(&allParamsValid));
 
-        generateSineWave(std::vector<int>{1000}, mInputBuffer, maxAudioSampleValue,
-                         mBufferSizeInFrames);
+        ASSERT_NO_FATAL_FAILURE(generateSineWave(std::vector<int>{1000}, mInputBuffer,
+                                                 maxAudioSampleValue, mBufferSizeInFrames,
+                                                 AudioChannelLayout::LAYOUT_MONO));
 
         // The stop and reset calls to the effect are made towards the end in order to fetch the
         // captureSampleBuffer values
diff --git a/audio/aidl/vts/VtsHalVolumeTargetTest.cpp b/audio/aidl/vts/VtsHalVolumeTargetTest.cpp
index b58c1c6..0b68b02 100644
--- a/audio/aidl/vts/VtsHalVolumeTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalVolumeTargetTest.cpp
@@ -66,7 +66,7 @@
 
     void initFrameCount() {
         int channelCount = getChannelCount(
-                AudioChannelLayout::make<AudioChannelLayout::layoutMask>(kDefaultChannelLayout));
+                AudioChannelLayout::make<AudioChannelLayout::layoutMask>(mChannelLayout));
         mInputFrameCount = kBufferSize / channelCount;
         mOutputFrameCount = kBufferSize / channelCount;
     }
@@ -93,10 +93,10 @@
         }
     }
 
-    static constexpr int kDurationMilliSec = 720;
+    static constexpr int kDurationMilliSec = 1440;
     static constexpr int kBufferSize = kSamplingFrequency * kDurationMilliSec / 1000;
     static constexpr int kMinLevel = -96;
-    static constexpr int kDefaultChannelLayout = AudioChannelLayout::LAYOUT_STEREO;
+    static constexpr int mChannelLayout = kDefaultChannelLayout;
     long mInputFrameCount, mOutputFrameCount;
     std::shared_ptr<IFactory> mFactory;
     std::shared_ptr<IEffect> mEffect;
@@ -162,8 +162,6 @@
         mInputMag.resize(mTestFrequencies.size());
         mBinOffsets.resize(mTestFrequencies.size());
         roundToFreqCenteredToFftBin(mTestFrequencies, mBinOffsets, kBinWidth);
-        generateSineWave(mTestFrequencies, mInput);
-        mInputMag = calculateMagnitude(mInput, mBinOffsets, kNPointFFT);
     }
 
     std::vector<int> calculatePercentageDiff(const std::vector<float>& outputMag) {
@@ -183,6 +181,11 @@
         SKIP_TEST_IF_DATA_UNSUPPORTED(mDescriptor.common.flags);
         // Skips test fixture if api_level <= 34 (__ANDROID_API_U__).
         if (kVsrApiLevel <= __ANDROID_API_U__) GTEST_SKIP();
+        ASSERT_NO_FATAL_FAILURE(generateSineWave(mTestFrequencies, mInput, 1.0, kSamplingFrequency,
+                                                 mChannelLayout));
+        ASSERT_NO_FATAL_FAILURE(
+                calculateAndVerifyMagnitude(mInputMag, mChannelLayout, mInput, mBinOffsets));
+
         ASSERT_NO_FATAL_FAILURE(SetUpVolumeControl());
     }
     void TearDown() override {
@@ -194,7 +197,6 @@
     const int kVsrApiLevel;
     static constexpr int kMaxAudioSample = 1;
     static constexpr int kTransitionDuration = 300;
-    static constexpr int kNPointFFT = 16384;
     static constexpr float kBinWidth = (float)kSamplingFrequency / kNPointFFT;
     static constexpr size_t offset = kSamplingFrequency * kTransitionDuration / 1000;
     static constexpr float kBaseLevel = 0;
@@ -218,7 +220,9 @@
     ASSERT_NO_FATAL_FAILURE(setAndVerifyParameters(Volume::levelDb, kBaseLevel, EX_NONE));
     ASSERT_NO_FATAL_FAILURE(processAndWriteToOutput(mInput, output, mEffect, &mOpenEffectReturn));
 
-    outputMag = calculateMagnitude(output, mBinOffsets, kNPointFFT);
+    ASSERT_NO_FATAL_FAILURE(
+            calculateAndVerifyMagnitude(outputMag, mChannelLayout, output, mBinOffsets));
+
     diffs = calculatePercentageDiff(outputMag);
 
     for (size_t i = 0; i < diffs.size(); i++) {
@@ -231,7 +235,10 @@
     ASSERT_NO_FATAL_FAILURE(processAndWriteToOutput(mInput, output, mEffect, &mOpenEffectReturn));
 
     std::vector<float> subOutputMute(output.begin() + offset, output.end());
-    outputMag = calculateMagnitude(subOutputMute, mBinOffsets, kNPointFFT);
+
+    ASSERT_NO_FATAL_FAILURE(
+            calculateAndVerifyMagnitude(outputMag, mChannelLayout, subOutputMute, mBinOffsets));
+
     diffs = calculatePercentageDiff(outputMag);
 
     for (size_t i = 0; i < diffs.size(); i++) {
@@ -239,7 +246,9 @@
     }
 
     // Verifying Fade out
-    outputMag = calculateMagnitude(output, mBinOffsets, kNPointFFT);
+    ASSERT_NO_FATAL_FAILURE(
+            calculateAndVerifyMagnitude(outputMag, mChannelLayout, output, mBinOffsets));
+
     diffs = calculatePercentageDiff(outputMag);
 
     for (size_t i = 0; i < diffs.size(); i++) {
@@ -253,7 +262,9 @@
 
     std::vector<float> subOutputUnmute(output.begin() + offset, output.end());
 
-    outputMag = calculateMagnitude(subOutputUnmute, mBinOffsets, kNPointFFT);
+    ASSERT_NO_FATAL_FAILURE(
+            calculateAndVerifyMagnitude(outputMag, mChannelLayout, subOutputUnmute, mBinOffsets));
+
     diffs = calculatePercentageDiff(outputMag);
 
     for (size_t i = 0; i < diffs.size(); i++) {
@@ -261,7 +272,9 @@
     }
 
     // Verifying Fade in
-    outputMag = calculateMagnitude(output, mBinOffsets, kNPointFFT);
+    ASSERT_NO_FATAL_FAILURE(
+            calculateAndVerifyMagnitude(outputMag, mChannelLayout, output, mBinOffsets));
+
     diffs = calculatePercentageDiff(outputMag);
 
     for (size_t i = 0; i < diffs.size(); i++) {
@@ -283,7 +296,9 @@
     ASSERT_NO_FATAL_FAILURE(
             processAndWriteToOutput(mInput, baseOutput, mEffect, &mOpenEffectReturn));
 
-    outputMag = calculateMagnitude(baseOutput, mBinOffsets, kNPointFFT);
+    ASSERT_NO_FATAL_FAILURE(
+            calculateAndVerifyMagnitude(outputMag, mChannelLayout, baseOutput, mBinOffsets));
+
     baseDiffs = calculatePercentageDiff(outputMag);
 
     for (int level : decreasingLevels) {
@@ -298,7 +313,9 @@
         ASSERT_NO_FATAL_FAILURE(
                 processAndWriteToOutput(mInput, output, mEffect, &mOpenEffectReturn));
 
-        outputMag = calculateMagnitude(output, mBinOffsets, kNPointFFT);
+        ASSERT_NO_FATAL_FAILURE(
+                calculateAndVerifyMagnitude(outputMag, mChannelLayout, output, mBinOffsets));
+
         diffs = calculatePercentageDiff(outputMag);
 
         // Decrease in volume level results in greater magnitude difference
diff --git a/audio/common/5.0/Android.bp b/audio/common/5.0/Android.bp
index 02f66a3..d9c4f58 100644
--- a/audio/common/5.0/Android.bp
+++ b/audio/common/5.0/Android.bp
@@ -23,6 +23,6 @@
     gen_java_constants: true,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
     ],
 }
diff --git a/automotive/can/aidl/default/CanController.cpp b/automotive/can/aidl/default/CanController.cpp
index 1435a02..40332d5 100644
--- a/automotive/can/aidl/default/CanController.cpp
+++ b/automotive/can/aidl/default/CanController.cpp
@@ -20,10 +20,10 @@
 #include "CanBusSlcan.h"
 #include "CanBusVirtual.h"
 
-#include <android-base/format.h>
 #include <android-base/logging.h>
 
 #include <filesystem>
+#include <format>
 #include <fstream>
 #include <regex>
 
@@ -235,7 +235,7 @@
                                                    std::string* ifaceName) {
     *ifaceName = {};
     if (mBusesByName.find(busName) == mBusesByName.end()) {
-        return resultToStatus(Result::BAD_BUS_NAME, fmt::format("{} doesn't exist", busName));
+        return resultToStatus(Result::BAD_BUS_NAME, std::format("{} doesn't exist", busName));
     }
     *ifaceName = std::string(mBusesByName[busName]->getIfaceName());
     return ok();
@@ -245,11 +245,11 @@
     if (!isValidName(config.name)) {
         LOG(ERROR) << "Bus name " << config.name << " is invalid";
         return resultToStatus(Result::BAD_BUS_NAME,
-                              fmt::format("{} is not a valid bus name", config.name));
+                              std::format("{} is not a valid bus name", config.name));
     } else if (mBusesByName.find(config.name) != mBusesByName.end()) {
         LOG(ERROR) << "A bus named " << config.name << " already exists!";
         return resultToStatus(Result::INVALID_STATE,
-                              fmt::format("A bus named {} already exists", config.name));
+                              std::format("A bus named {} already exists", config.name));
     }
 
     if (config.interfaceId.getTag() == BusConfig::InterfaceId::Tag::virtualif) {
@@ -310,7 +310,7 @@
     if (result != Result::OK) {
         // the bus failed to come up, don't leave a broken entry in the map.
         mBusesByName.erase(config.name);
-        return resultToStatus(result, fmt::format("CanBus::up failed for {}", config.name));
+        return resultToStatus(result, std::format("CanBus::up failed for {}", config.name));
     }
 
     *ifaceName = mBusesByName[config.name]->getIfaceName();
@@ -321,11 +321,11 @@
     if (mBusesByName.find(busName) == mBusesByName.end()) {
         return resultToStatus(
                 Result::UNKNOWN_ERROR,
-                fmt::format("Couldn't bring down {}, because it doesn't exist", busName));
+                std::format("Couldn't bring down {}, because it doesn't exist", busName));
     }
     Result result = mBusesByName[busName]->down();
     if (result != Result::OK) {
-        return resultToStatus(result, fmt::format("Couldn't bring down {}!", busName));
+        return resultToStatus(result, std::format("Couldn't bring down {}!", busName));
     }
     mBusesByName.erase(busName);
     return ok();
diff --git a/automotive/can/aidl/default/service.cpp b/automotive/can/aidl/default/service.cpp
index eb45167..ef04cfd 100644
--- a/automotive/can/aidl/default/service.cpp
+++ b/automotive/can/aidl/default/service.cpp
@@ -20,12 +20,11 @@
 #include <android/binder_manager.h>
 #include <android/binder_process.h>
 
-namespace android::hardware::automotive::can {
-
 using namespace std::string_literals;
+using namespace android;
 using ::aidl::android::hardware::automotive::can::CanController;
 
-extern "C" int main() {
+int main() {
     base::SetDefaultTag("CanController");
     base::SetMinimumLogSeverity(base::VERBOSE);
 
@@ -40,4 +39,3 @@
     LOG(FATAL) << "CanController exited unexpectedly!";
     return EXIT_FAILURE;
 }
-}  // namespace android::hardware::automotive::can
diff --git a/automotive/can/aidl/default/tools/configurator/canhalconfigurator.cpp b/automotive/can/aidl/default/tools/configurator/canhalconfigurator.cpp
index 94e77b4..87a4497 100644
--- a/automotive/can/aidl/default/tools/configurator/canhalconfigurator.cpp
+++ b/automotive/can/aidl/default/tools/configurator/canhalconfigurator.cpp
@@ -98,7 +98,11 @@
     return true;
 }
 
-extern "C" int main(int argc, char* argv[]) {
+}  // namespace android::hardware::automotive::can
+
+int main(int argc, char* argv[]) {
+    using namespace android::hardware::automotive::can;
+
     std::string configFilepath = static_cast<std::string>(kDefaultConfigPath);
 
     // allow for CLI specification of a config file.
@@ -114,5 +118,3 @@
     }
     return 0;
 }
-
-}  // namespace android::hardware::automotive::can
diff --git a/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultVehicleHalServer.cpp b/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultVehicleHalServer.cpp
index 86fc70a..6c83339 100644
--- a/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultVehicleHalServer.cpp
+++ b/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultVehicleHalServer.cpp
@@ -16,10 +16,10 @@
 
 #define LOG_TAG "DefaultVehicleHalServer"
 
+#include <format>
 #include <fstream>
 #include <regex>
 
-#include <android-base/format.h>
 #include <android-base/logging.h>
 #include <android-base/parsedouble.h>
 #include <android-base/parseint.h>
@@ -237,7 +237,7 @@
         auto values = mServerSidePropStore.readAllValues();
         size_t i = 0;
         for (const auto& value : values) {
-            result.buffer += fmt::format("[{}]: {}\n", i, toString(value));
+            result.buffer += std::format("[{}]: {}\n", i, toString(value));
             i++;
         }
         return result;
diff --git a/automotive/vehicle/2.0/default/impl/vhal_v2_0/userhal/FakeUserHal.cpp b/automotive/vehicle/2.0/default/impl/vhal_v2_0/userhal/FakeUserHal.cpp
index e9ebcc6..c735b05 100644
--- a/automotive/vehicle/2.0/default/impl/vhal_v2_0/userhal/FakeUserHal.cpp
+++ b/automotive/vehicle/2.0/default/impl/vhal_v2_0/userhal/FakeUserHal.cpp
@@ -15,6 +15,8 @@
  */
 #define LOG_TAG "FakeUserHal"
 
+#include <format>
+
 #include <cutils/log.h>
 #include <utils/SystemClock.h>
 
@@ -312,34 +314,34 @@
 }
 
 std::string FakeUserHal::showDumpHelp() {
-    return fmt::format("{}: dumps state used for user management\n", kUserHalDumpOption);
+    return std::format("{}: dumps state used for user management\n", kUserHalDumpOption);
 }
 
 std::string FakeUserHal::dump(std::string indent) {
     std::string info;
     if (mInitialUserResponseFromCmd != nullptr) {
-        info += fmt::format("{}InitialUserInfo response: {}\n", indent.c_str(),
+        info += std::format("{}InitialUserInfo response: {}\n", indent.c_str(),
                             toString(*mInitialUserResponseFromCmd).c_str());
     } else {
-        info += fmt::format("{}No InitialUserInfo response\n", indent.c_str());
+        info += std::format("{}No InitialUserInfo response\n", indent.c_str());
     }
     if (mSwitchUserResponseFromCmd != nullptr) {
-        info += fmt::format("{}SwitchUser response: {}\n", indent.c_str(),
+        info += std::format("{}SwitchUser response: {}\n", indent.c_str(),
                             toString(*mSwitchUserResponseFromCmd).c_str());
     } else {
-        info += fmt::format("{}No SwitchUser response\n", indent.c_str());
+        info += std::format("{}No SwitchUser response\n", indent.c_str());
     }
     if (mCreateUserResponseFromCmd != nullptr) {
-        info += fmt::format("{}CreateUser response: {}\n", indent.c_str(),
+        info += std::format("{}CreateUser response: {}\n", indent.c_str(),
                             toString(*mCreateUserResponseFromCmd).c_str());
     } else {
-        info += fmt::format("{}No CreateUser response\n", indent.c_str());
+        info += std::format("{}No CreateUser response\n", indent.c_str());
     }
     if (mSetUserIdentificationAssociationResponseFromCmd != nullptr) {
-        info += fmt::format("{}SetUserIdentificationAssociation response: {}\n", indent.c_str(),
+        info += std::format("{}SetUserIdentificationAssociation response: {}\n", indent.c_str(),
                             toString(*mSetUserIdentificationAssociationResponseFromCmd).c_str());
     } else {
-        info += fmt::format("{}No SetUserIdentificationAssociation response\n", indent.c_str());
+        info += std::format("{}No SetUserIdentificationAssociation response\n", indent.c_str());
     }
     return info;
 }
diff --git a/automotive/vehicle/2.0/default/impl/vhal_v2_0/userhal/include/FakeUserHal.h b/automotive/vehicle/2.0/default/impl/vhal_v2_0/userhal/include/FakeUserHal.h
index 122aee8..33cef54 100644
--- a/automotive/vehicle/2.0/default/impl/vhal_v2_0/userhal/include/FakeUserHal.h
+++ b/automotive/vehicle/2.0/default/impl/vhal_v2_0/userhal/include/FakeUserHal.h
@@ -17,7 +17,6 @@
 #ifndef android_hardware_automotive_vehicle_V2_0_impl_FakeUserHal_H_
 #define android_hardware_automotive_vehicle_V2_0_impl_FakeUserHal_H_
 
-#include <android-base/format.h>
 #include <android-base/result.h>
 
 #include <android/hardware/automotive/vehicle/2.0/types.h>
diff --git a/automotive/vehicle/aidl/impl/fake_impl/userhal/include/FakeUserHal.h b/automotive/vehicle/aidl/impl/fake_impl/userhal/include/FakeUserHal.h
index fcbe8fd..1bf5ce1 100644
--- a/automotive/vehicle/aidl/impl/fake_impl/userhal/include/FakeUserHal.h
+++ b/automotive/vehicle/aidl/impl/fake_impl/userhal/include/FakeUserHal.h
@@ -17,7 +17,6 @@
 #ifndef android_hardware_automotive_vehicle_aidl_impl_fake_impl_userhal_include_FakeUserHal_H_
 #define android_hardware_automotive_vehicle_aidl_impl_fake_impl_userhal_include_FakeUserHal_H_
 
-#include <android-base/format.h>
 #include <android-base/result.h>
 #include <android-base/thread_annotations.h>
 
diff --git a/automotive/vehicle/aidl/impl/fake_impl/userhal/src/FakeUserHal.cpp b/automotive/vehicle/aidl/impl/fake_impl/userhal/src/FakeUserHal.cpp
index 878c2e7..309dd5f 100644
--- a/automotive/vehicle/aidl/impl/fake_impl/userhal/src/FakeUserHal.cpp
+++ b/automotive/vehicle/aidl/impl/fake_impl/userhal/src/FakeUserHal.cpp
@@ -19,6 +19,8 @@
 
 #include "UserHalHelper.h"
 
+#include <format>
+
 #include <VehicleUtils.h>
 #include <utils/Log.h>
 #include <utils/SystemClock.h>
@@ -336,7 +338,7 @@
 }
 
 std::string FakeUserHal::showDumpHelp() const {
-    return fmt::format("{}: dumps state used for user management\n", kUserHalDumpOption);
+    return std::format("{}: dumps state used for user management\n", kUserHalDumpOption);
 }
 
 std::string FakeUserHal::dump() const {
@@ -344,23 +346,23 @@
 
     std::string info;
     if (mInitialUserResponseFromCmd != nullptr) {
-        info += fmt::format("InitialUserInfo response: {}\n",
+        info += std::format("InitialUserInfo response: {}\n",
                             mInitialUserResponseFromCmd->toString());
     } else {
         info += "No InitialUserInfo response\n";
     }
     if (mSwitchUserResponseFromCmd != nullptr) {
-        info += fmt::format("SwitchUser response: {}\n", mSwitchUserResponseFromCmd->toString());
+        info += std::format("SwitchUser response: {}\n", mSwitchUserResponseFromCmd->toString());
     } else {
         info += "No SwitchUser response\n";
     }
     if (mCreateUserResponseFromCmd != nullptr) {
-        info += fmt::format("CreateUser response: {}\n", mCreateUserResponseFromCmd->toString());
+        info += std::format("CreateUser response: {}\n", mCreateUserResponseFromCmd->toString());
     } else {
         info += "No CreateUser response\n";
     }
     if (mSetUserIdentificationAssociationResponseFromCmd != nullptr) {
-        info += fmt::format("SetUserIdentificationAssociation response: {}\n",
+        info += std::format("SetUserIdentificationAssociation response: {}\n",
                             mSetUserIdentificationAssociationResponseFromCmd->toString());
     } else {
         info += "No SetUserIdentificationAssociation response\n";
diff --git a/automotive/vehicle/aidl/impl/grpc/utils/proto_message_converter/test/proto_message_converter_test.cpp b/automotive/vehicle/aidl/impl/grpc/utils/proto_message_converter/test/proto_message_converter_test.cpp
index 2efda5b..6fe40a6 100644
--- a/automotive/vehicle/aidl/impl/grpc/utils/proto_message_converter/test/proto_message_converter_test.cpp
+++ b/automotive/vehicle/aidl/impl/grpc/utils/proto_message_converter/test/proto_message_converter_test.cpp
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <format>
 #include <vector>
 
 #include <JsonConfigLoader.h>
@@ -21,7 +22,6 @@
 #include <VehicleHalTypes.h>
 
 #include <android-base/file.h>
-#include <android-base/format.h>
 #include <android/hardware/automotive/vehicle/SubscribeOptions.pb.h>
 #include <android/hardware/automotive/vehicle/VehiclePropConfig.pb.h>
 #include <android/hardware/automotive/vehicle/VehiclePropValue.pb.h>
@@ -106,13 +106,13 @@
 INSTANTIATE_TEST_SUITE_P(DefaultConfigs, PropConfigConversionTest,
                          ::testing::ValuesIn(prepareTestConfigs()),
                          [](const ::testing::TestParamInfo<aidl_vehicle::VehiclePropConfig>& info) {
-                             return ::fmt::format("property_{:d}", info.param.prop);
+                             return ::std::format("property_{:d}", info.param.prop);
                          });
 
 INSTANTIATE_TEST_SUITE_P(TestValues, PropValueConversionTest,
                          ::testing::ValuesIn(prepareTestValues()),
                          [](const ::testing::TestParamInfo<aidl_vehicle::VehiclePropValue>& info) {
-                             return ::fmt::format("property_{:d}", info.param.prop);
+                             return ::std::format("property_{:d}", info.param.prop);
                          });
 
 TEST_F(PropValueConversionTest, testConvertSubscribeOption) {
diff --git a/automotive/vehicle/aidl/impl/utils/common/include/VehicleUtils.h b/automotive/vehicle/aidl/impl/utils/common/include/VehicleUtils.h
index 90a7c46..2bb4ba8 100644
--- a/automotive/vehicle/aidl/impl/utils/common/include/VehicleUtils.h
+++ b/automotive/vehicle/aidl/impl/utils/common/include/VehicleUtils.h
@@ -17,9 +17,10 @@
 #ifndef android_hardware_automotive_vehicle_aidl_impl_utils_common_include_VehicleUtils_H_
 #define android_hardware_automotive_vehicle_aidl_impl_utils_common_include_VehicleUtils_H_
 
+#include <format>
+
 #include <VehicleHalTypes.h>
 
-#include <android-base/format.h>
 #include <android-base/result.h>
 #include <math/HashCombine.h>
 #include <utils/Log.h>
@@ -289,7 +290,7 @@
     }
     return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage(
             toInt(status),
-            fmt::format("{}, error: {}", additionalErrorMsg, getErrorMsg(result)).c_str());
+            std::format("{}, error: {}", additionalErrorMsg, getErrorMsg(result)).c_str());
 }
 
 template <class T, class E>
diff --git a/bluetooth/1.0/Android.bp b/bluetooth/1.0/Android.bp
index bd1ca69..3ffc203 100644
--- a/bluetooth/1.0/Android.bp
+++ b/bluetooth/1.0/Android.bp
@@ -23,6 +23,6 @@
     gen_java: true,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
     ],
 }
diff --git a/bluetooth/1.1/Android.bp b/bluetooth/1.1/Android.bp
index f8a05f1..9c65b62 100644
--- a/bluetooth/1.1/Android.bp
+++ b/bluetooth/1.1/Android.bp
@@ -23,6 +23,6 @@
     gen_java: true,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
     ],
 }
diff --git a/bluetooth/aidl/Android.bp b/bluetooth/aidl/Android.bp
index 721be73..0daecf7 100644
--- a/bluetooth/aidl/Android.bp
+++ b/bluetooth/aidl/Android.bp
@@ -32,7 +32,7 @@
         ndk: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.btservices",
+                "com.android.bt",
             ],
             min_sdk_version: "33",
         },
diff --git a/bluetooth/audio/2.0/Android.bp b/bluetooth/audio/2.0/Android.bp
index 725ec11..61f9a35 100644
--- a/bluetooth/audio/2.0/Android.bp
+++ b/bluetooth/audio/2.0/Android.bp
@@ -26,6 +26,6 @@
     gen_java: false,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
     ],
 }
diff --git a/bluetooth/audio/2.1/Android.bp b/bluetooth/audio/2.1/Android.bp
index 4ca0bef..4d01a00 100644
--- a/bluetooth/audio/2.1/Android.bp
+++ b/bluetooth/audio/2.1/Android.bp
@@ -25,7 +25,7 @@
     ],
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
     ],
     gen_java: false,
 }
diff --git a/bluetooth/audio/aidl/Android.bp b/bluetooth/audio/aidl/Android.bp
index dbff368..6d4edb1 100644
--- a/bluetooth/audio/aidl/Android.bp
+++ b/bluetooth/audio/aidl/Android.bp
@@ -48,7 +48,7 @@
         ndk: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.btservices",
+                "com.android.bt",
             ],
             min_sdk_version: "31",
         },
diff --git a/bluetooth/audio/utils/aidl_session/BluetoothLeAudioAseConfigurationSettingProvider.cpp b/bluetooth/audio/utils/aidl_session/BluetoothLeAudioAseConfigurationSettingProvider.cpp
index 5909c92..3e18de2 100644
--- a/bluetooth/audio/utils/aidl_session/BluetoothLeAudioAseConfigurationSettingProvider.cpp
+++ b/bluetooth/audio/utils/aidl_session/BluetoothLeAudioAseConfigurationSettingProvider.cpp
@@ -674,14 +674,14 @@
         configurationFlags.bitmask |=
             ConfigurationFlags::ALLOW_ASYMMETRIC_CONFIGURATIONS;
       }
+    }
+  } else {
+    if (codec_cfg == nullptr) {
+      LOG(ERROR) << "No codec config matching key " << codec_config_key.c_str()
+                 << " found";
     } else {
-      if (codec_cfg == nullptr) {
-        LOG(ERROR) << "No codec config matching key "
-                   << codec_config_key.c_str() << " found";
-      } else {
-        LOG(ERROR) << "Configuration '" << flat_cfg->name()->c_str()
-                   << "' has no valid subconfigurations.";
-      }
+      LOG(ERROR) << "Configuration '" << flat_cfg->name()->c_str()
+                 << "' has no valid subconfigurations.";
     }
   }
 }
diff --git a/bluetooth/hci/h4_protocol.cc b/bluetooth/hci/h4_protocol.cc
index 5f6d86e..109ca5c 100644
--- a/bluetooth/hci/h4_protocol.cc
+++ b/bluetooth/hci/h4_protocol.cc
@@ -45,29 +45,50 @@
 }
 
 size_t H4Protocol::Send(PacketType type, const uint8_t* data, size_t length) {
-  /* For HCI communication over USB dongle, multiple write results in
-   * response timeout as driver expect type + data at once to process
-   * the command, so using "writev"(for atomicity) here.
-   */
-  struct iovec iov[2];
-  ssize_t ret = 0;
-  iov[0].iov_base = &type;
-  iov[0].iov_len = sizeof(type);
-  iov[1].iov_base = (void*)data;
-  iov[1].iov_len = length;
-  while (1) {
-    ret = TEMP_FAILURE_RETRY(writev(uart_fd_, iov, 2));
+  struct iovec iov_array[] = {{&type, sizeof(type)},
+                              {const_cast<uint8_t*>(data), length}};
+  size_t iovcnt = sizeof(iov_array) / sizeof(iov_array[0]);
+  struct iovec* iov = iov_array;
+  size_t total_bytes = sizeof(type) + length;
+  size_t remaining_bytes = total_bytes;
+  size_t bytes_written = 0;
+
+  while (remaining_bytes > 0) {
+    ssize_t ret = TEMP_FAILURE_RETRY(writev(uart_fd_, iov, iovcnt));
     if (ret == -1) {
-      LOG_ALWAYS_FATAL("%s error writing to UART (%s)", __func__,
-                       strerror(errno));
+      if (errno == EAGAIN) continue;
+      ALOGE("Error writing to UART (%s)", strerror(errno));
+      break;
     } else if (ret == 0) {
       // Nothing written :(
       ALOGE("%s zero bytes written - something went wrong...", __func__);
       break;
+    } else if (ret == remaining_bytes) {
+      // Everything written
+      bytes_written += ret;
+      break;
     }
-    break;
+
+    // Updating counters for partial writes
+    bytes_written += ret;
+    remaining_bytes -= ret;
+
+    ALOGW("%s: %zu/%zu bytes written - retrying remaining %zu bytes", __func__,
+          bytes_written, total_bytes, remaining_bytes);
+
+    // Remove fully written iovs from the list
+    while (ret >= iov->iov_len) {
+      ret -= iov->iov_len;
+      ++iov;
+      --iovcnt;
+    }
+    // Adjust the iov to point to the remaining data that needs to be written
+    if (ret > 0) {
+      iov->iov_base = static_cast<uint8_t*>(iov->iov_base) + ret;
+      iov->iov_len -= ret;
+    }
   }
-  return ret;
+  return total_bytes - remaining_bytes;
 }
 
 size_t H4Protocol::OnPacketReady(const std::vector<uint8_t>& packet) {
diff --git a/bluetooth/ranging/aidl/Android.bp b/bluetooth/ranging/aidl/Android.bp
index 4096669..b5ae205 100644
--- a/bluetooth/ranging/aidl/Android.bp
+++ b/bluetooth/ranging/aidl/Android.bp
@@ -31,7 +31,7 @@
         ndk: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.btservices",
+                "com.android.bt",
             ],
             min_sdk_version: "33",
         },
diff --git a/bluetooth/socket/aidl/Android.bp b/bluetooth/socket/aidl/Android.bp
index 77679f8..7c03677 100644
--- a/bluetooth/socket/aidl/Android.bp
+++ b/bluetooth/socket/aidl/Android.bp
@@ -37,7 +37,7 @@
         ndk: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.btservices",
+                "com.android.bt",
             ],
             min_sdk_version: "33",
         },
diff --git a/boot/aidl/client/BootControlClient.cpp b/boot/aidl/client/BootControlClient.cpp
index 5cca183..7aab5b4 100644
--- a/boot/aidl/client/BootControlClient.cpp
+++ b/boot/aidl/client/BootControlClient.cpp
@@ -80,6 +80,7 @@
     explicit BootControlClientAidl(std::shared_ptr<IBootControl> module)
         : module_(module),
           boot_control_death_recipient(AIBinder_DeathRecipient_new(onBootControlServiceDied)) {
+        AIBinder_DeathRecipient_setOnUnlinked(boot_control_death_recipient, onCallbackUnlinked);
         binder_status_t status =
                 AIBinder_linkToDeath(module->asBinder().get(), boot_control_death_recipient, this);
         if (status != STATUS_OK) {
@@ -236,6 +237,11 @@
   private:
     std::shared_ptr<IBootControl> module_;
     AIBinder_DeathRecipient* boot_control_death_recipient;
+    static void onCallbackUnlinked(void* /*client*/) {
+        // this is an empty function needed to suppress the "AIBinder_linkToDeath is being called
+        // with a non-null cookie and no onUnlink callback set. This might not be intended.
+        // AIBinder_DeathRecipient_setOnUnlinked should be called first." warning
+    }
     static void onBootControlServiceDied(void* client) {
         BootControlClientAidl* self = static_cast<BootControlClientAidl*>(client);
         self->onBootControlServiceDied();
diff --git a/compatibility_matrices/bump.py b/compatibility_matrices/bump.py
index bcb0fa6..91f58d4 100755
--- a/compatibility_matrices/bump.py
+++ b/compatibility_matrices/bump.py
@@ -45,6 +45,7 @@
         self.current_level = cmdline_args.current_level
         self.current_letter = cmdline_args.current_letter
         self.current_version = cmdline_args.platform_version
+        self.next_version = cmdline_args.next_platform_version
         self.current_module_name = f"framework_compatibility_matrix.{self.current_level}.xml"
         self.current_xml = self.interfaces_dir / f"compatibility_matrices/compatibility_matrix.{self.current_level}.xml"
         self.device_module_name = "framework_compatibility_matrix.device.xml"
@@ -132,27 +133,27 @@
             return
         try:
             check_call(["grep", "-h",
-                        f"{self.current_letter.upper()} = {self.current_level}",
-                        "system/libvintf/include/vintf/Level.h"])
+                        f"{self.next_letter.upper()} = {self.next_level}",
+                        f"{self.top}/system/libvintf/include/vintf/Level.h"])
         except subprocess.CalledProcessError:
             print("Adding new API level to libvintf")
-            add_lines_above("system/libvintf/analyze_matrix/analyze_matrix.cpp",
+            add_lines_above(f"{self.top}/system/libvintf/analyze_matrix/analyze_matrix.cpp",
                             "        case Level::UNSPECIFIED:",
                             textwrap.indent(textwrap.dedent(f"""\
-                                    case Level::{self.current_letter.upper()}:
-                                        return "Android {self.current_version} ({self.current_letter.upper()})";"""),
+                                    case Level::{self.next_letter.upper()}:
+                                        return "Android {self.next_version} ({self.next_letter.upper()})";"""),
                             "    "*2))
-            add_lines_above("system/libvintf/include/vintf/Level.h",
+            add_lines_above(f"{self.top}/system/libvintf/include/vintf/Level.h",
                             "    // To add new values:",
-                            f"    {self.current_letter.upper()} = {self.current_level},")
-            add_lines_above("system/libvintf/include/vintf/Level.h",
+                            f"    {self.next_letter.upper()} = {self.next_level},")
+            add_lines_above(f"{self.top}/system/libvintf/include/vintf/Level.h",
                             "        Level::UNSPECIFIED,",
-                            f"        Level::{self.current_letter.upper()},")
-            add_lines_above("system/libvintf/RuntimeInfo.cpp",
+                            f"        Level::{self.next_letter.upper()},")
+            add_lines_above(f"{self.top}/system/libvintf/RuntimeInfo.cpp",
                             "            // Add more levels above this line.",
                             textwrap.indent(textwrap.dedent(f"""\
-                                        case {self.current_version}: {{
-                                            ret = Level::{self.current_letter.upper()};
+                                        case {self.next_version}: {{
+                                            ret = Level::{self.next_letter.upper()};
                                         }} break;"""),
                             "    "*3))
 
@@ -188,7 +189,11 @@
     parser.add_argument("platform_version",
                         type=str,
                         nargs="?",
-                        help="Android release version number number (e.g. 16)")
+                        help="Current Android release version number (e.g. 16)")
+    parser.add_argument("next_platform_version",
+                        type=str,
+                        nargs="?",
+                        help="Next Android release version number number (e.g. 17)")
     cmdline_args = parser.parse_args()
 
     Bump(cmdline_args).run()
diff --git a/contexthub/aidl/Android.bp b/contexthub/aidl/Android.bp
index 674f8af..b56537a 100644
--- a/contexthub/aidl/Android.bp
+++ b/contexthub/aidl/Android.bp
@@ -35,7 +35,7 @@
         ndk: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.btservices",
+                "com.android.bt",
             ],
             min_sdk_version: "33",
             apps_enabled: true,
diff --git a/graphics/bufferqueue/1.0/Android.bp b/graphics/bufferqueue/1.0/Android.bp
index c7c6453..87c3892 100644
--- a/graphics/bufferqueue/1.0/Android.bp
+++ b/graphics/bufferqueue/1.0/Android.bp
@@ -25,7 +25,7 @@
     gen_java: true,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
         "com.android.media",
         "com.android.media.swcodec",
     ],
diff --git a/graphics/bufferqueue/2.0/Android.bp b/graphics/bufferqueue/2.0/Android.bp
index e9f75c1..54f68c6 100644
--- a/graphics/bufferqueue/2.0/Android.bp
+++ b/graphics/bufferqueue/2.0/Android.bp
@@ -27,7 +27,7 @@
     gen_java: true,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
         "com.android.media",
         "com.android.media.swcodec",
     ],
diff --git a/graphics/common/1.0/Android.bp b/graphics/common/1.0/Android.bp
index b876bf3..1683c22 100644
--- a/graphics/common/1.0/Android.bp
+++ b/graphics/common/1.0/Android.bp
@@ -20,7 +20,7 @@
     gen_java_constants: true,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
         "com.android.media.swcodec",
         "test_com.android.media.swcodec",
     ],
diff --git a/graphics/common/1.1/Android.bp b/graphics/common/1.1/Android.bp
index ff6c9b7..81df887 100644
--- a/graphics/common/1.1/Android.bp
+++ b/graphics/common/1.1/Android.bp
@@ -23,7 +23,7 @@
     gen_java_constants: true,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
         "com.android.media.swcodec",
         "test_com.android.media.swcodec",
     ],
diff --git a/graphics/common/1.2/Android.bp b/graphics/common/1.2/Android.bp
index b4663e5..e1f4fe0 100644
--- a/graphics/common/1.2/Android.bp
+++ b/graphics/common/1.2/Android.bp
@@ -24,7 +24,7 @@
     gen_java_constants: true,
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
         "com.android.media.swcodec",
         "test_com.android.media.swcodec",
     ],
diff --git a/health/aidl/default/LinkedCallback.h b/health/aidl/default/LinkedCallback.h
index 8c9c997..6b17be0 100644
--- a/health/aidl/default/LinkedCallback.h
+++ b/health/aidl/default/LinkedCallback.h
@@ -36,7 +36,7 @@
     // cookie when it's unlinked.
     static ::android::base::Result<LinkedCallback*> Make(
             std::shared_ptr<Health> service, std::shared_ptr<IHealthInfoCallback> callback);
-    // On callback died, unreigster it from the service.
+    // On callback died, unregister it from the service.
     void OnCallbackDied();
 
   private:
diff --git a/macsec/aidl/default/MacsecPskPlugin.cpp b/macsec/aidl/default/MacsecPskPlugin.cpp
index 82d2545..8cb5283 100644
--- a/macsec/aidl/default/MacsecPskPlugin.cpp
+++ b/macsec/aidl/default/MacsecPskPlugin.cpp
@@ -18,7 +18,6 @@
 #include <openssl/cipher.h>
 #include <openssl/mem.h>
 
-#include <android-base/format.h>
 #include <android-base/logging.h>
 
 namespace aidl::android::hardware::macsec {
diff --git a/macsec/aidl/default/service.cpp b/macsec/aidl/default/service.cpp
index faf3a09..9d5d3bf 100644
--- a/macsec/aidl/default/service.cpp
+++ b/macsec/aidl/default/service.cpp
@@ -20,12 +20,11 @@
 #include <android/binder_manager.h>
 #include <android/binder_process.h>
 
-namespace android::hardware::macsec {
-
 using namespace std::string_literals;
+using namespace android;
 using ::aidl::android::hardware::macsec::MacsecPskPlugin;
 
-extern "C" int main() {
+int main() {
     base::SetDefaultTag("MacsecPskPlugin");
     base::SetMinimumLogSeverity(base::VERBOSE);
 
@@ -40,4 +39,3 @@
     LOG(FATAL) << "MacsecPskPlugin exited unexpectedly!";
     return EXIT_FAILURE;
 }
-}  // namespace android::hardware::macsec
diff --git a/nfc/aidl/vts/functional/VtsNfcBehaviorChangesTest.cpp b/nfc/aidl/vts/functional/VtsNfcBehaviorChangesTest.cpp
index ff2522c..a61f8ee 100644
--- a/nfc/aidl/vts/functional/VtsNfcBehaviorChangesTest.cpp
+++ b/nfc/aidl/vts/functional/VtsNfcBehaviorChangesTest.cpp
@@ -114,16 +114,26 @@
     }
 }
 
-void static nfaVSCallback(uint8_t event, uint16_t /* param_len */, uint8_t* p_param) {
+void static nfaVSCallback(uint8_t event, uint16_t param_len, uint8_t* p_param) {
     switch (event & NCI_OID_MASK) {
         case NCI_MSG_PROP_ANDROID: {
             uint8_t android_sub_opcode = p_param[3];
             switch (android_sub_opcode) {
                 case NCI_ANDROID_PASSIVE_OBSERVE: {
-                    sVSCmdStatus = p_param[4];
-                    LOG(INFO) << StringPrintf("Observe mode RSP: status: %x", sVSCmdStatus);
-                    SyncEventGuard guard(sNfaVsCommand);
-                    sNfaVsCommand.notifyOne();
+                    if (param_len == 5) {
+                        if ((p_param[0] & NCI_MT_MASK) == (NCI_MT_RSP << NCI_MT_SHIFT)) {
+                            sVSCmdStatus = p_param[4];
+                            LOG(INFO) << StringPrintf("Observe mode RSP: status: %x", sVSCmdStatus);
+                            SyncEventGuard guard(sNfaVsCommand);
+                            sNfaVsCommand.notifyOne();
+                        } else {
+                            LOG(WARNING) << StringPrintf(
+                                    "Observe Mode RSP has incorrect message type: %x", p_param[0]);
+                        }
+                    } else {
+                        LOG(WARNING) << StringPrintf("Observe Mode RSP has incorrect length: %d",
+                                                     param_len);
+                    }
                 } break;
                 case NCI_ANDROID_POLLING_FRAME_NTF: {
                     // TODO
@@ -152,12 +162,11 @@
         }
     }
 
-    uint8_t cmd[] = {(NCI_MT_CMD << NCI_MT_SHIFT) | NCI_GID_PROP, NCI_MSG_PROP_ANDROID,
-                     NCI_ANDROID_PASSIVE_OBSERVE_PARAM_SIZE, NCI_ANDROID_PASSIVE_OBSERVE,
+    uint8_t cmd[] = {NCI_ANDROID_PASSIVE_OBSERVE,
                      static_cast<uint8_t>(enable ? NCI_ANDROID_PASSIVE_OBSERVE_PARAM_ENABLE
                                                  : NCI_ANDROID_PASSIVE_OBSERVE_PARAM_DISABLE)};
 
-    status = NFA_SendRawVsCommand(sizeof(cmd), cmd, nfaVSCallback);
+    status = NFA_SendVsCommand(NCI_MSG_PROP_ANDROID, sizeof(cmd), cmd, nfaVSCallback);
 
     if (status == NFA_STATUS_OK) {
         if (!sNfaVsCommand.wait(1000)) {
diff --git a/radio/1.0/Android.bp b/radio/1.0/Android.bp
index e49a50d..09cf9aa 100644
--- a/radio/1.0/Android.bp
+++ b/radio/1.0/Android.bp
@@ -25,7 +25,7 @@
     ],
     apex_available: [
         "//apex_available:platform",
-        "com.android.btservices",
+        "com.android.bt",
     ],
     gen_java: true,
 }
diff --git a/radio/aidl/Android.bp b/radio/aidl/Android.bp
index 01c09d8..53ef145 100644
--- a/radio/aidl/Android.bp
+++ b/radio/aidl/Android.bp
@@ -227,7 +227,7 @@
         java: {
             apex_available: [
                 "//apex_available:platform",
-                "com.android.btservices",
+                "com.android.bt",
             ],
             sdk_version: "module_current",
             min_sdk_version: "Tiramisu",
diff --git a/security/keymint/aidl/Android.bp b/security/keymint/aidl/Android.bp
index a2e58ac..76aa604 100644
--- a/security/keymint/aidl/Android.bp
+++ b/security/keymint/aidl/Android.bp
@@ -99,3 +99,13 @@
         "android.hardware.security.keymint-V4-rust",
     ],
 }
+
+// java_defaults that includes the latest KeyMint AIDL library.
+// Modules that depend on KeyMint directly can include this java_defaults to avoid
+// managing dependency versions explicitly.
+java_defaults {
+    name: "keymint_use_latest_hal_aidl_java",
+    static_libs: [
+        "android.hardware.security.keymint-V4-java",
+    ],
+}
diff --git a/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl b/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
index cafec70..fc703e9 100644
--- a/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
+++ b/security/keymint/aidl/android/hardware/security/keymint/IKeyMintDevice.aidl
@@ -87,12 +87,14 @@
  *        SHA-2 256.
  *      - Unpadded, RSAES-OAEP and RSAES-PKCS1-v1_5 padding modes for RSA encryption.
  *
- * o   ECDSA
+ * o   ECDSA and ECDH
  *
+ *      - IKeyMintDevices must support elliptic curve signing (Purpose::SIGN, Purpose::ATTEST_KEY)
+ *        and key agreement operations (Purpose::AGREE_KEY).
  *      - TRUSTED_ENVIRONMENT IKeyMintDevices must support NIST curves P-224, P-256, P-384 and
  *        P-521.  STRONGBOX IKeyMintDevices must support NIST curve P-256.
- *      - TRUSTED_ENVIRONMENT IKeyMintDevices must support SHA1, SHA-2 224, SHA-2 256, SHA-2
- *        384 and SHA-2 512 digest modes.  STRONGBOX IKeyMintDevices must support SHA-2 256.
+ *      - For signing, TRUSTED_ENVIRONMENT IKeyMintDevices must support SHA1, SHA-2 224, SHA-2 256,
+ *        SHA-2 384 and SHA-2 512 digest modes.  STRONGBOX IKeyMintDevices must support SHA-2 256.
  *      - TRUSTED_ENVRIONMENT IKeyMintDevices must support curve 25519 for Purpose::SIGN (Ed25519,
  *        as specified in RFC 8032), Purpose::ATTEST_KEY (Ed25519) or for KeyPurpose::AGREE_KEY
  *        (X25519, as specified in RFC 7748).  However, a key must have exactly one of these
@@ -302,12 +304,12 @@
      *   PaddingMode::RSA_OAEP, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_ENCRYPT and
      *   PaddingMode::RSA_PKCS1_1_5_SIGN for RSA keys.
      *
-     * == ECDSA Keys ==
+     * == ECDSA/ECDH Keys ==
      *
-     * Tag::EC_CURVE must be provided to generate an ECDSA key.  If it is not provided, generateKey
-     * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE. TEE
-     * IKeyMintDevice implementations must support all required curves.  StrongBox implementations
-     * must support P_256 and no other curves.
+     * Tag::EC_CURVE must be provided to generate an elliptic curve key.  If it is not provided,
+     * generateKey must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
+     * TEE IKeyMintDevice implementations must support all required curves.  StrongBox
+     * implementations must support P_256 and no other curves.
      *
      * Tag::CERTIFICATE_NOT_BEFORE and Tag::CERTIFICATE_NOT_AFTER must be provided to specify the
      * valid date range for the returned X.509 certificate holding the public key. If omitted,
@@ -318,10 +320,10 @@
      * than one purpose should be rejected with ErrorCode::INCOMPATIBLE_PURPOSE.
      * StrongBox implementation do not support CURVE_25519.
      *
-     * Tag::DIGEST specifies digest algorithms that may be used with the new key.  TEE
-     * IKeyMintDevice implementations must support all Digest values (see Digest.aidl) for ECDSA
-     * keys; Ed25519 keys only support Digest::NONE. StrongBox IKeyMintDevice implementations must
-     * support SHA_2_256.
+     * Tag::DIGEST specifies digest algorithms that may be used with the new key when used for
+     * signing.  TEE IKeyMintDevice implementations must support all Digest values (see Digest.aidl)
+     * for ECDSA keys; Ed25519 keys only support Digest::NONE. StrongBox IKeyMintDevice
+     * implementations must support SHA_2_256.
      *
      * == AES Keys ==
      *
diff --git a/security/keymint/support/remote_prov_utils.cpp b/security/keymint/support/remote_prov_utils.cpp
index fbfe80b..ecf69e8 100644
--- a/security/keymint/support/remote_prov_utils.cpp
+++ b/security/keymint/support/remote_prov_utils.cpp
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <format>
 #include <iomanip>
 #include <iterator>
 #include <memory>
@@ -535,7 +536,7 @@
     switch (rpcHardwareInfo.versionNumber) {
         case 3:
             if (isTeeDeviceInfo(*parsed) && parsed->size() != kNumTeeDeviceInfoEntries) {
-                error += fmt::format(
+                error += std::format(
                         "Err: Incorrect number of device info entries. Expected {} but got "
                         "{}\n",
                         kNumTeeDeviceInfoEntries, parsed->size());
@@ -544,7 +545,7 @@
             // may omit `os_version`
             if (!isTeeDeviceInfo(*parsed) && (parsed->size() != kNumTeeDeviceInfoEntries &&
                                               parsed->size() != kNumTeeDeviceInfoEntries - 1)) {
-                error += fmt::format(
+                error += std::format(
                         "Err: Incorrect number of device info entries. Expected {} or {} but got "
                         "{}\n",
                         kNumTeeDeviceInfoEntries - 1, kNumTeeDeviceInfoEntries, parsed->size());
diff --git a/security/rkp/aidl/vts/functional/VtsRemotelyProvisionedComponentTests.cpp b/security/rkp/aidl/vts/functional/VtsRemotelyProvisionedComponentTests.cpp
index 66f7539..7ef445e 100644
--- a/security/rkp/aidl/vts/functional/VtsRemotelyProvisionedComponentTests.cpp
+++ b/security/rkp/aidl/vts/functional/VtsRemotelyProvisionedComponentTests.cpp
@@ -344,6 +344,53 @@
     ASSERT_TRUE(*result);
 }
 
+/**
+ * Check that ro.boot.vbmeta.device_state is not "locked" or ro.boot.verifiedbootstate
+ * is not "green" if and only if the mode on at least one certificate in the DICE chain
+ * is non-normal.
+ */
+TEST(NonParameterizedTests, unlockedBootloaderStatesImpliesNonnormalRkpVmDiceChain) {
+    if (!AServiceManager_isDeclared(RKPVM_INSTANCE_NAME.c_str())) {
+        GTEST_SKIP() << "The RKP VM (" << RKPVM_INSTANCE_NAME << ") is not present on this device.";
+    }
+
+    auto rpc = getHandle<IRemotelyProvisionedComponent>(RKPVM_INSTANCE_NAME);
+    ASSERT_NE(rpc, nullptr) << "The RKP VM (" << RKPVM_INSTANCE_NAME << ") RPC is unavailable.";
+
+    RpcHardwareInfo hardwareInfo;
+    auto status = rpc->getHardwareInfo(&hardwareInfo);
+    if (!status.isOk()) {
+        GTEST_SKIP() << "The RKP VM is not supported on this system.";
+    }
+
+    auto challenge = randomBytes(MAX_CHALLENGE_SIZE);
+    bytevec csr;
+    auto rkpVmStatus = rpc->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
+    ASSERT_TRUE(rkpVmStatus.isOk()) << status.getDescription();
+
+    auto isProper = isCsrWithProperDiceChain(csr, RKPVM_INSTANCE_NAME);
+    ASSERT_TRUE(isProper) << isProper.message();
+    if (!*isProper) {
+        GTEST_SKIP() << "Skipping test: Only a proper DICE chain has a mode set.";
+    }
+
+    auto nonNormalMode = hasNonNormalModeInDiceChain(csr, RKPVM_INSTANCE_NAME);
+    ASSERT_TRUE(nonNormalMode) << nonNormalMode.message();
+
+    auto deviceState = ::android::base::GetProperty("ro.boot.vbmeta.device_state", "");
+    auto verifiedBootState = ::android::base::GetProperty("ro.boot.verifiedbootstate", "");
+
+    ASSERT_TRUE(!deviceState.empty());
+    ASSERT_TRUE(!verifiedBootState.empty());
+
+    ASSERT_EQ(deviceState != "locked" || verifiedBootState != "green", *nonNormalMode)
+            << "ro.boot.vbmeta.device_state = '" << deviceState
+            << "' and ro.boot.verifiedbootstate = '" << verifiedBootState << "', but the DICE "
+            << " chain has a " << (*nonNormalMode ? "non-normal" : "normal") << " DICE mode."
+            << " Locked devices must report normal, and unlocked devices must report "
+            << " non-normal.";
+}
+
 using GetHardwareInfoTests = VtsRemotelyProvisionedComponentTests;
 
 INSTANTIATE_REM_PROV_AIDL_TEST(GetHardwareInfoTests);
@@ -849,37 +896,6 @@
 };
 
 /**
- * Check that ro.boot.vbmeta.device_state is not "locked" or ro.boot.verifiedbootstate
- * is not "green" if and only if the mode on at least one certificate in the DICE chain
- * is non-normal.
- */
-TEST_P(CertificateRequestV2Test, DISABLED_unlockedBootloaderStatesImpliesNonnormalDiceChain) {
-    auto challenge = randomBytes(MAX_CHALLENGE_SIZE);
-    bytevec csr;
-    auto status =
-            provisionable_->generateCertificateRequestV2({} /* keysToSign */, challenge, &csr);
-    ASSERT_TRUE(status.isOk()) << status.getDescription();
-
-    auto isProper = isCsrWithProperDiceChain(csr, GetParam());
-    ASSERT_TRUE(isProper) << isProper.message();
-    if (!*isProper) {
-        GTEST_SKIP() << "Skipping test: Only a proper DICE chain has a mode set.";
-    }
-
-    auto nonNormalMode = hasNonNormalModeInDiceChain(csr, GetParam());
-    ASSERT_TRUE(nonNormalMode) << nonNormalMode.message();
-
-    auto deviceState = ::android::base::GetProperty("ro.boot.vbmeta.device_state", "");
-    auto verifiedBootState = ::android::base::GetProperty("ro.boot.verifiedbootstate", "");
-
-    ASSERT_EQ(deviceState != "locked" || verifiedBootState != "green", *nonNormalMode)
-            << "ro.boot.vbmeta.device_state = '" << deviceState
-            << "' and ro.boot.verifiedbootstate = '" << verifiedBootState << "', but it is "
-            << *nonNormalMode
-            << " that the DICE chain has a certificate with a non-normal mode set.";
-}
-
-/**
  * Generate an empty certificate request with all possible length of challenge, and decrypt and
  * verify the structure and content.
  */
diff --git a/security/see/storage/aidl/android/hardware/security/see/storage/IStorageSession.aidl b/security/see/storage/aidl/android/hardware/security/see/storage/IStorageSession.aidl
index 9a8d0d7..b5762aa 100644
--- a/security/see/storage/aidl/android/hardware/security/see/storage/IStorageSession.aidl
+++ b/security/see/storage/aidl/android/hardware/security/see/storage/IStorageSession.aidl
@@ -103,7 +103,8 @@
     /**
      * Renames an existing file.
      *
-     * The file must not already be opened. (If it is, use `IFile::rename`.)
+     * Will return `ILLEGAL_STATE` if the file is already opened. In that case, use `IFile::rename`
+     * instead.
      *
      * @currentPath:
      *     path to the file, relative to filesystem root