Merge cherrypicks of [11816540, 11816001, 11816620, 11816559, 11816541, 11816621, 11815640, 11816506, 11816507, 11816508, 11816586, 11816587, 11816588, 11816589, 11816520, 11816173, 11816590, 11816591, 11816395, 11816003, 11816698, 11815507] into qt-qpr3-release

Change-Id: Id40569315a518af8623517fab688d8c4324285e2
diff --git a/audio_utils/include/audio_utils/spdif/SPDIFEncoder.h b/audio_utils/include/audio_utils/spdif/SPDIFEncoder.h
index 3c84d73..1a432d8 100644
--- a/audio_utils/include/audio_utils/spdif/SPDIFEncoder.h
+++ b/audio_utils/include/audio_utils/spdif/SPDIFEncoder.h
@@ -83,6 +83,7 @@
 
 protected:
     void   clearBurstBuffer();
+    bool   wouldOverflowBuffer(size_t numBytes) const; // Would this many bytes cause an overflow?
     void   writeBurstBufferShorts(const uint16_t* buffer, size_t numBytes);
     void   writeBurstBufferBytes(const uint8_t* buffer, size_t numBytes);
     void   sendZeroPad();
diff --git a/audio_utils/spdif/AC3FrameScanner.cpp b/audio_utils/spdif/AC3FrameScanner.cpp
index 6ebe9e3..3cd9d15 100644
--- a/audio_utils/spdif/AC3FrameScanner.cpp
+++ b/audio_utils/spdif/AC3FrameScanner.cpp
@@ -194,7 +194,13 @@
 
         // Frame size is explicit in EAC3. Paragraph E2.3.1.3
         uint32_t frmsiz = ((mHeaderBuffer[2] & 0x07) << 8) + mHeaderBuffer[3];
-        mFrameSizeBytes = (frmsiz + 1) * sizeof(int16_t);
+        uint32_t frameSizeBytes = (frmsiz + 1) * sizeof(int16_t);
+        if (frameSizeBytes < mHeaderLength) {
+            ALOGW("AC3 frame size = %d, less than header size = %d", frameSizeBytes, mHeaderLength);
+            android_errorWriteLog(0x534e4554, "145262423");
+            return false;
+        }
+        mFrameSizeBytes = frameSizeBytes;
 
         uint32_t numblkscod = 3; // 6 blocks default
         if (fscod == 3) {
diff --git a/audio_utils/spdif/FrameScanner.cpp b/audio_utils/spdif/FrameScanner.cpp
index 81de943..893dfca 100644
--- a/audio_utils/spdif/FrameScanner.cpp
+++ b/audio_utils/spdif/FrameScanner.cpp
@@ -36,7 +36,7 @@
  , mFormatDumpCount(0)
  , mSampleRate(0)
  , mRateMultiplier(1)
- , mFrameSizeBytes(0)
+ , mFrameSizeBytes(headerLength) // minimum
  , mDataType(dataType)
  , mDataTypeInfo(0)
 {
diff --git a/audio_utils/spdif/SPDIFEncoder.cpp b/audio_utils/spdif/SPDIFEncoder.cpp
index 250f961..8a1bf51 100644
--- a/audio_utils/spdif/SPDIFEncoder.cpp
+++ b/audio_utils/spdif/SPDIFEncoder.cpp
@@ -101,14 +101,21 @@
     return SPDIF_ENCODED_CHANNEL_COUNT * sizeof(int16_t);
 }
 
+bool SPDIFEncoder::wouldOverflowBuffer(size_t numBytes) const {
+    // Avoid numeric overflow when calculating whether the buffer would overflow.
+    return (numBytes > mBurstBufferSizeBytes)
+        || (mByteCursor > (mBurstBufferSizeBytes - numBytes));  // (max - n) won't overflow
+}
+
 void SPDIFEncoder::writeBurstBufferShorts(const uint16_t *buffer, size_t numShorts)
 {
     // avoid static analyser warning
     LOG_ALWAYS_FATAL_IF((mBurstBuffer == NULL), "mBurstBuffer never allocated");
+
     mByteCursor = (mByteCursor + 1) & ~1; // round up to even byte
     size_t bytesToWrite = numShorts * sizeof(uint16_t);
-    if ((mByteCursor + bytesToWrite) > mBurstBufferSizeBytes) {
-        ALOGE("SPDIFEncoder: Burst buffer overflow!");
+    if (wouldOverflowBuffer(bytesToWrite)) {
+        ALOGE("SPDIFEncoder::%s() Burst buffer overflow!", __func__);
         reset();
         return;
     }
@@ -126,14 +133,13 @@
 // Big and Little Endian CPUs.
 void SPDIFEncoder::writeBurstBufferBytes(const uint8_t *buffer, size_t numBytes)
 {
-    size_t bytesToWrite = numBytes;
-    if ((mByteCursor + bytesToWrite) > mBurstBufferSizeBytes) {
-        ALOGE("SPDIFEncoder: Burst buffer overflow!");
+    if (wouldOverflowBuffer(numBytes)) {
+        ALOGE("SPDIFEncoder::%s() Burst buffer overflow!", __func__);
         clearBurstBuffer();
         return;
     }
     uint16_t pad = mBurstBuffer[mByteCursor >> 1];
-    for (size_t i = 0; i < bytesToWrite; i++) {
+    for (size_t i = 0; i < numBytes; i++) {
         if (mByteCursor & 1 ) {
             pad |= *buffer++; // put second byte in LSB
             mBurstBuffer[mByteCursor >> 1] = pad;
@@ -219,9 +225,16 @@
 size_t SPDIFEncoder::startSyncFrame()
 {
     // Write start of encoded frame that was buffered in frame detector.
-    size_t syncSize = mFramer->getHeaderSizeBytes();
-    writeBurstBufferBytes(mFramer->getHeaderAddress(), syncSize);
-    return mFramer->getFrameSizeBytes() - syncSize;
+    size_t headerSize = mFramer->getHeaderSizeBytes();
+    writeBurstBufferBytes(mFramer->getHeaderAddress(), headerSize);
+    // This is provided by the encoded audio file and may be invalid.
+    size_t frameSize = mFramer->getFrameSizeBytes();
+    if (frameSize < headerSize) {
+        ALOGE("SPDIFEncoder: invalid frameSize = %zu", frameSize);
+        return 0;
+    }
+    // Calculate how many more bytes we need to complete the frame.
+    return frameSize - headerSize;
 }
 
 // Wraps raw encoded data into a data burst.
diff --git a/audio_utils/tests/Android.bp b/audio_utils/tests/Android.bp
index e104868..25357e0 100644
--- a/audio_utils/tests/Android.bp
+++ b/audio_utils/tests/Android.bp
@@ -369,3 +369,20 @@
         },
     }
 }
+
+cc_test {
+    name: "spdif_tests",
+
+    shared_libs: [
+        "libaudioutils",
+        "libaudiospdif",
+        "liblog",
+        "libcutils",
+    ],
+    srcs: ["spdif_tests.cpp"],
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+}
+
diff --git a/audio_utils/tests/spdif_tests.cpp b/audio_utils/tests/spdif_tests.cpp
new file mode 100644
index 0000000..96a8a16
--- /dev/null
+++ b/audio_utils/tests/spdif_tests.cpp
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <array>
+#include <climits>
+#include <math.h>
+#include <memory>
+#include <string.h>
+
+#include <gtest/gtest.h>
+
+#include <audio_utils/spdif/SPDIFEncoder.h>
+
+using namespace android;
+
+class MySPDIFEncoder : public SPDIFEncoder {
+public:
+
+    explicit MySPDIFEncoder(audio_format_t format)
+            : SPDIFEncoder(format)
+    {
+    }
+    // Defaults to AC3 format. Was in original API.
+    MySPDIFEncoder() = default;
+
+    ssize_t writeOutput( const void* /* buffer */, size_t numBytes ) override {
+        mOutputSizeBytes = numBytes;
+        return numBytes;
+    }
+
+    FrameScanner *getFramer() const { return mFramer; }
+    size_t        getByteCursor() const { return mByteCursor; }
+    size_t        getPayloadBytesPending() const { return mPayloadBytesPending; }
+    size_t        getBurstBufferSizeBytes() const { return mBurstBufferSizeBytes; }
+
+    size_t                     mOutputSizeBytes = 0;
+};
+
+// This is the beginning of the file voice1-48k-64kbps-15s.ac3
+static const uint8_t sVoice1ch48k_AC3[] = {
+    0x0b, 0x77, 0x44, 0xcd, 0x08, 0x40, 0x2f, 0x84, 0x29, 0xca, 0x6e, 0x44, 0xa4, 0xfd, 0xce, 0xf7,
+    0xc9, 0x9f, 0x3e, 0x74, 0xfa, 0x01, 0x0a, 0xda, 0xb3, 0x3e, 0xb0, 0x95, 0xf2, 0x5a, 0xef, 0x9e
+};
+
+// This is the beginning of the file channelcheck_48k6ch.eac3
+static const uint8_t sChannel6ch48k_EAC3[] = {
+    0x0b, 0x77, 0x01, 0xbf, 0x3f, 0x85, 0x7f, 0xe8, 0x1e, 0x40, 0x82, 0x10, 0x00, 0x00, 0x00, 0x01,
+    0x00, 0x00, 0x00, 0x03, 0xfc, 0x60, 0x80, 0x7e, 0x59, 0x00, 0xfc, 0xf3, 0xcf, 0x01, 0xf9, 0xe7
+};
+
+static const uint8_t sZeros[32] = { 0 };
+
+static constexpr int kBytesPerOutputFrame = 2 * sizeof(int16_t); // stereo
+
+TEST(audio_utils_spdif, SupportedFormats)
+{
+    ASSERT_FALSE(SPDIFEncoder::isFormatSupported(AUDIO_FORMAT_PCM_FLOAT));
+    ASSERT_FALSE(SPDIFEncoder::isFormatSupported(AUDIO_FORMAT_PCM_16_BIT));
+    ASSERT_FALSE(SPDIFEncoder::isFormatSupported(AUDIO_FORMAT_MP3));
+
+    ASSERT_TRUE(SPDIFEncoder::isFormatSupported(AUDIO_FORMAT_AC3));
+    ASSERT_TRUE(SPDIFEncoder::isFormatSupported(AUDIO_FORMAT_E_AC3));
+    ASSERT_TRUE(SPDIFEncoder::isFormatSupported(AUDIO_FORMAT_DTS));
+    ASSERT_TRUE(SPDIFEncoder::isFormatSupported(AUDIO_FORMAT_DTS_HD));
+}
+
+TEST(audio_utils_spdif, ScanAC3)
+{
+    MySPDIFEncoder encoder(AUDIO_FORMAT_AC3);
+    FrameScanner *scanner = encoder.getFramer();
+    // It should recognize the valid AC3 header.
+    int i = 0;
+    while (i < 5) {
+        ASSERT_FALSE(scanner->scan(sVoice1ch48k_AC3[i++]));
+    }
+    ASSERT_TRUE(scanner->scan(sVoice1ch48k_AC3[i++]));
+    ASSERT_FALSE(scanner->scan(sVoice1ch48k_AC3[i++]));
+}
+
+TEST(audio_utils_spdif, WriteAC3)
+{
+    MySPDIFEncoder encoder(AUDIO_FORMAT_AC3);
+    encoder.write(sVoice1ch48k_AC3, sizeof(sVoice1ch48k_AC3));
+    ASSERT_EQ(48000, encoder.getFramer()->getSampleRate());
+    ASSERT_EQ(kBytesPerOutputFrame, encoder.getBytesPerOutputFrame());
+    ASSERT_EQ(1, encoder.getRateMultiplier());
+
+    // Check to make sure that the pending bytes calculation did not overflow.
+    size_t burstBufferSizeBytes = encoder.getBurstBufferSizeBytes(); // allocated maximum size
+    size_t pendingBytes = encoder.getPayloadBytesPending();
+    ASSERT_GE(burstBufferSizeBytes, pendingBytes);
+
+    // Write some fake compressed audio to force an output data burst.
+    for (int i = 0; i < 7; i++) {
+        auto result = encoder.write(sZeros, sizeof(sZeros));
+        ASSERT_EQ(sizeof(sZeros), result);
+    }
+    // This value is calculated in SPDIFEncoder::sendZeroPad()
+    //    size_t burstSize = mFramer->getSampleFramesPerSyncFrame() * sizeof(uint16_t)
+    //        * SPDIF_ENCODED_CHANNEL_COUNT;
+    // If it changes then there is probably a regression.
+    const int kExpectedBurstSize = 6144;
+    ASSERT_EQ(kExpectedBurstSize, encoder.mOutputSizeBytes);
+}
+
+TEST(audio_utils_spdif, ValidEAC3)
+{
+    MySPDIFEncoder encoder(AUDIO_FORMAT_E_AC3);
+    auto result = encoder.write(sChannel6ch48k_EAC3, sizeof(sChannel6ch48k_EAC3));
+    ASSERT_EQ(sizeof(sChannel6ch48k_EAC3), result);
+    ASSERT_EQ(4, encoder.getRateMultiplier()); // EAC3_RATE_MULTIPLIER
+    ASSERT_EQ(48000, encoder.getFramer()->getSampleRate());
+    ASSERT_EQ(kBytesPerOutputFrame, encoder.getBytesPerOutputFrame());
+
+    // Check to make sure that the pending bytes calculation did not overflow.
+    size_t bufferSize = encoder.getBurstBufferSizeBytes();
+    size_t pendingBytes = encoder.getPayloadBytesPending();
+    ASSERT_GE(bufferSize, pendingBytes);
+}
+
+TEST(audio_utils_spdif, InvalidLengthEAC3)
+{
+    MySPDIFEncoder encoder(AUDIO_FORMAT_E_AC3);
+    // Mangle a valid header and try to force a numeric overflow.
+    uint8_t mangled[sizeof(sChannel6ch48k_EAC3)] = {0};
+    memcpy(mangled, sChannel6ch48k_EAC3, sizeof(sChannel6ch48k_EAC3));
+
+    // force frmsiz to zero!
+    mangled[2] = mangled[2] & 0xF8;
+    mangled[3] = 0;
+    auto result = encoder.write(mangled, sizeof(mangled));
+    ASSERT_EQ(sizeof(mangled), result);
+
+    // Check to make sure that the pending bytes calculation did not overflow.
+    size_t bufferSize = encoder.getBurstBufferSizeBytes();
+    size_t pendingBytes = encoder.getPayloadBytesPending();
+    ASSERT_GE(bufferSize, pendingBytes);
+
+}