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