Home | History | Annotate | Download | only in spdif
      1 /*
      2 **
      3 ** Copyright 2014, The Android Open Source Project
      4 **
      5 ** Licensed under the Apache License, Version 2.0 (the "License");
      6 ** you may not use this file except in compliance with the License.
      7 ** You may obtain a copy of the License at
      8 **
      9 **     http://www.apache.org/licenses/LICENSE-2.0
     10 **
     11 ** Unless required by applicable law or agreed to in writing, software
     12 ** distributed under the License is distributed on an "AS IS" BASIS,
     13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14 ** See the License for the specific language governing permissions and
     15 ** limitations under the License.
     16 */
     17 
     18 
     19 #include <stdint.h>
     20 
     21 #define LOG_TAG "AudioSPDIF"
     22 #include <utils/Log.h>
     23 #include <audio_utils/spdif/SPDIFEncoder.h>
     24 
     25 namespace android {
     26 
     27 // Burst Preamble defined in IEC61937-1
     28 const unsigned short SPDIFEncoder::kSPDIFSync1 = 0xF872; // Pa
     29 const unsigned short SPDIFEncoder::kSPDIFSync2 = 0x4E1F; // Pb
     30 
     31 static int32_t sEndianDetector = 1;
     32 #define isLittleEndian()  (*((uint8_t *)&sEndianDetector))
     33 
     34 SPDIFEncoder::SPDIFEncoder()
     35   : mState(STATE_IDLE)
     36   , mSampleRate(48000)
     37   , mBurstBuffer(NULL)
     38   , mBurstBufferSizeBytes(0)
     39   , mRateMultiplier(1)
     40   , mBurstFrames(0)
     41   , mByteCursor(0)
     42   , mBitstreamNumber(0)
     43   , mPayloadBytesPending(0)
     44 {
     45     // TODO support other compressed audio formats
     46     mFramer = new AC3FrameScanner();
     47 
     48     mBurstBufferSizeBytes = sizeof(uint16_t)
     49             * SPDIF_ENCODED_CHANNEL_COUNT
     50             * mFramer->getMaxSampleFramesPerSyncFrame();
     51 
     52     ALOGI("SPDIFEncoder: mBurstBufferSizeBytes = %d, littleEndian = %d",
     53             mBurstBufferSizeBytes, isLittleEndian());
     54     mBurstBuffer = new uint16_t[mBurstBufferSizeBytes >> 1];
     55     clearBurstBuffer();
     56 }
     57 
     58 SPDIFEncoder::~SPDIFEncoder()
     59 {
     60     delete[] mBurstBuffer;
     61 }
     62 
     63 int SPDIFEncoder::getBytesPerOutputFrame()
     64 {
     65     return SPDIF_ENCODED_CHANNEL_COUNT * sizeof(int16_t);
     66 }
     67 
     68 void SPDIFEncoder::writeBurstBufferShorts(const uint16_t *buffer, size_t numShorts)
     69 {
     70     mByteCursor = (mByteCursor + 1) & ~1; // round up to even byte
     71     size_t bytesToWrite = numShorts * sizeof(uint16_t);
     72     if ((mByteCursor + bytesToWrite) > mBurstBufferSizeBytes) {
     73         ALOGE("SPDIFEncoder: Burst buffer overflow!\n");
     74         clearBurstBuffer();
     75         return;
     76     }
     77     memcpy(&mBurstBuffer[mByteCursor >> 1], buffer, bytesToWrite);
     78     mByteCursor += bytesToWrite;
     79 }
     80 
     81 // Pack the bytes into the short buffer in the order:
     82 //   byte[0] -> short[0] MSB
     83 //   byte[1] -> short[0] LSB
     84 //   byte[2] -> short[1] MSB
     85 //   byte[3] -> short[1] LSB
     86 //   etcetera
     87 // This way they should come out in the correct order for SPDIF on both
     88 // Big and Little Endian CPUs.
     89 void SPDIFEncoder::writeBurstBufferBytes(const uint8_t *buffer, size_t numBytes)
     90 {
     91     size_t bytesToWrite = numBytes;
     92     if ((mByteCursor + bytesToWrite) > mBurstBufferSizeBytes) {
     93         ALOGE("SPDIFEncoder: Burst buffer overflow!\n");
     94         clearBurstBuffer();
     95         return;
     96     }
     97     uint16_t pad = mBurstBuffer[mByteCursor >> 1];
     98     for (size_t i = 0; i < bytesToWrite; i++) {
     99         if (mByteCursor & 1 ) {
    100             pad |= *buffer++; // put second byte in LSB
    101             mBurstBuffer[mByteCursor >> 1] = pad;
    102             pad = 0;
    103         } else {
    104             pad |= (*buffer++) << 8; // put first byte in MSB
    105         }
    106         mByteCursor++;
    107     }
    108     // Save partially filled short.
    109     if (mByteCursor & 1 ){
    110         mBurstBuffer[mByteCursor >> 1] = pad;
    111     }
    112 }
    113 
    114 void SPDIFEncoder::sendZeroPad()
    115 {
    116     // Pad remainder of burst with zeros.
    117     size_t burstSize = mFramer->getSampleFramesPerSyncFrame() * sizeof(uint16_t)
    118             * SPDIF_ENCODED_CHANNEL_COUNT;
    119     if (mByteCursor > burstSize) {
    120         ALOGE("SPDIFEncoder: Burst buffer, contents too large!");
    121         clearBurstBuffer();
    122     } else {
    123         // We don't have to write zeros because buffer already set to zero
    124         // by clearBurstBuffer(). Just pretend we wrote zeros by
    125         // incrementing cursor.
    126         mByteCursor = burstSize;
    127     }
    128 }
    129 
    130 void SPDIFEncoder::flushBurstBuffer()
    131 {
    132     const int preambleSize = 4 * sizeof(uint16_t);
    133     if (mByteCursor > preambleSize) {
    134         // Set number of bits for valid payload before zeroPad.
    135         uint16_t lengthCode = (mByteCursor - preambleSize) * 8;
    136         mBurstBuffer[3] = lengthCode;
    137 
    138         sendZeroPad();
    139         writeOutput(mBurstBuffer, mByteCursor);
    140     }
    141     clearBurstBuffer();
    142     mFramer->resetBurst();
    143 }
    144 
    145 void SPDIFEncoder::clearBurstBuffer()
    146 {
    147     if (mBurstBuffer) {
    148         memset(mBurstBuffer, 0, mBurstBufferSizeBytes);
    149     }
    150     mByteCursor = 0;
    151 }
    152 
    153 void SPDIFEncoder::startDataBurst()
    154 {
    155     // Encode IEC61937-1 Burst Preamble
    156     uint16_t preamble[4];
    157 
    158     uint16_t burstInfo = (mBitstreamNumber << 13)
    159         | (mFramer->getDataTypeInfo() << 8)
    160         | mFramer->getDataType();
    161 
    162     mRateMultiplier = mFramer->getRateMultiplier();
    163 
    164     preamble[0] = kSPDIFSync1;
    165     preamble[1] = kSPDIFSync2;
    166     preamble[2] = burstInfo;
    167     preamble[3] = 0; // lengthCode - This will get set after the buffer is full.
    168     writeBurstBufferShorts(preamble, 4);
    169 }
    170 
    171 size_t SPDIFEncoder::startSyncFrame()
    172 {
    173     // Write start of encoded frame that was buffered in frame detector.
    174     size_t syncSize = mFramer->getHeaderSizeBytes();
    175     writeBurstBufferBytes(mFramer->getHeaderAddress(), syncSize);
    176     return mFramer->getFrameSizeBytes() - syncSize;
    177 }
    178 
    179 // Wraps raw encoded data into a data burst.
    180 ssize_t SPDIFEncoder::write( const void *buffer, size_t numBytes )
    181 {
    182     size_t bytesLeft = numBytes;
    183     const uint8_t *data = (const uint8_t *)buffer;
    184     ALOGV("SPDIFEncoder: state = %d, write(buffer[0] = 0x%02X, numBytes = %u)",
    185         mState, (uint) *data, numBytes);
    186     while (bytesLeft > 0) {
    187         State nextState = mState;
    188         switch (mState) {
    189         // Look for beginning of next encoded frame.
    190         case STATE_IDLE:
    191             if (mFramer->scan(*data)) {
    192                 if (mByteCursor == 0) {
    193                     startDataBurst();
    194                 } else if (mFramer->isFirstInBurst()) {
    195                     // Make sure that this frame is at the beginning of the data burst.
    196                     flushBurstBuffer();
    197                     startDataBurst();
    198                 }
    199                 mPayloadBytesPending = startSyncFrame();
    200                 nextState = STATE_BURST;
    201             }
    202             data++;
    203             bytesLeft--;
    204             break;
    205 
    206         // Write payload until we hit end of frame.
    207         case STATE_BURST:
    208             {
    209                 size_t bytesToWrite = bytesLeft;
    210                 // Only write as many as we need to finish the frame.
    211                 if (bytesToWrite > mPayloadBytesPending) {
    212                     bytesToWrite = mPayloadBytesPending;
    213                 }
    214                 writeBurstBufferBytes(data, bytesToWrite);
    215 
    216                 data += bytesToWrite;
    217                 bytesLeft -= bytesToWrite;
    218                 mPayloadBytesPending -= bytesToWrite;
    219 
    220                 // If we have all the payload then send a data burst.
    221                 if (mPayloadBytesPending == 0) {
    222                     if (mFramer->isLastInBurst()) {
    223                         flushBurstBuffer();
    224                     }
    225                     nextState = STATE_IDLE;
    226                 }
    227             }
    228             break;
    229 
    230         default:
    231             ALOGE("SPDIFEncoder: illegal state = %d\n", mState);
    232             nextState = STATE_IDLE;
    233             break;
    234         }
    235         mState = nextState;
    236     }
    237     return numBytes;
    238 }
    239 
    240 }  // namespace android
    241