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 <log/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 uint16_t SPDIFEncoder::kSPDIFSync1 = 0xF872; // Pa
31 const uint16_t 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   : mFramer(NULL)
38   , mSampleRate(48000)
39   , mBurstBuffer(NULL)
40   , mBurstBufferSizeBytes(0)
41   , mRateMultiplier(1)
42   , mBurstFrames(0)
43   , mByteCursor(0)
44   , mBitstreamNumber(0)
45   , mPayloadBytesPending(0)
46   , mScanning(true)
47 {
48     switch(format) {
49         case AUDIO_FORMAT_AC3:
50         case AUDIO_FORMAT_E_AC3:
51         case AUDIO_FORMAT_E_AC3_JOC:
52             mFramer = new AC3FrameScanner(format);
53             break;
54         case AUDIO_FORMAT_DTS:
55         case AUDIO_FORMAT_DTS_HD:
56             mFramer = new DTSFrameScanner();
57             break;
58         default:
59             break;
60     }
61 
62     // This a programmer error. Call isFormatSupported() first.
63     LOG_ALWAYS_FATAL_IF((mFramer == NULL),
64         "SPDIFEncoder: invalid audio format = 0x%08X", format);
65 
66     mBurstBufferSizeBytes = sizeof(uint16_t)
67             * SPDIF_ENCODED_CHANNEL_COUNT
68             * mFramer->getMaxSampleFramesPerSyncFrame();
69 
70     ALOGI("SPDIFEncoder: mBurstBufferSizeBytes = %zu, littleEndian = %d",
71             mBurstBufferSizeBytes, isLittleEndian());
72     mBurstBuffer = new uint16_t[mBurstBufferSizeBytes >> 1];
73     clearBurstBuffer();
74 }
75 
SPDIFEncoder()76 SPDIFEncoder::SPDIFEncoder()
77     : SPDIFEncoder(AUDIO_FORMAT_AC3)
78 {
79 }
80 
~SPDIFEncoder()81 SPDIFEncoder::~SPDIFEncoder()
82 {
83     delete[] mBurstBuffer;
84     delete mFramer;
85 }
86 
isFormatSupported(audio_format_t format)87 bool SPDIFEncoder::isFormatSupported(audio_format_t format)
88 {
89     switch(format) {
90         case AUDIO_FORMAT_AC3:
91         case AUDIO_FORMAT_E_AC3:
92         case AUDIO_FORMAT_E_AC3_JOC:
93         case AUDIO_FORMAT_DTS:
94         case AUDIO_FORMAT_DTS_HD:
95             return true;
96         default:
97             return false;
98     }
99 }
100 
getBytesPerOutputFrame()101 int SPDIFEncoder::getBytesPerOutputFrame()
102 {
103     return SPDIF_ENCODED_CHANNEL_COUNT * sizeof(int16_t);
104 }
105 
wouldOverflowBuffer(size_t numBytes) const106 bool SPDIFEncoder::wouldOverflowBuffer(size_t numBytes) const {
107     // Avoid numeric overflow when calculating whether the buffer would overflow.
108     return (numBytes > mBurstBufferSizeBytes)
109         || (mByteCursor > (mBurstBufferSizeBytes - numBytes));  // (max - n) won't overflow
110 }
111 
writeBurstBufferShorts(const uint16_t * buffer,size_t numShorts)112 void SPDIFEncoder::writeBurstBufferShorts(const uint16_t *buffer, size_t numShorts)
113 {
114     // avoid static analyser warning
115     LOG_ALWAYS_FATAL_IF((mBurstBuffer == NULL), "mBurstBuffer never allocated");
116 
117     mByteCursor = (mByteCursor + 1) & ~1; // round up to even byte
118     size_t bytesToWrite = numShorts * sizeof(uint16_t);
119     if (wouldOverflowBuffer(bytesToWrite)) {
120         ALOGE("SPDIFEncoder::%s() Burst buffer overflow!", __func__);
121         reset();
122         return;
123     }
124     memcpy(&mBurstBuffer[mByteCursor >> 1], buffer, bytesToWrite);
125     mByteCursor += bytesToWrite;
126 }
127 
128 // Pack the bytes into the short buffer in the order:
129 //   byte[0] -> short[0] MSB
130 //   byte[1] -> short[0] LSB
131 //   byte[2] -> short[1] MSB
132 //   byte[3] -> short[1] LSB
133 //   etcetera
134 // This way they should come out in the correct order for SPDIF on both
135 // Big and Little Endian CPUs.
writeBurstBufferBytes(const uint8_t * buffer,size_t numBytes)136 void SPDIFEncoder::writeBurstBufferBytes(const uint8_t *buffer, size_t numBytes)
137 {
138     if (wouldOverflowBuffer(numBytes)) {
139         ALOGE("SPDIFEncoder::%s() Burst buffer overflow!", __func__);
140         clearBurstBuffer();
141         return;
142     }
143 
144     // Avoid reading first word past end of mBurstBuffer.
145     if (numBytes == 0) {
146         return;
147     }
148     // Pack bytes into short buffer.
149     uint16_t pad = mBurstBuffer[mByteCursor >> 1];
150     for (size_t i = 0; i < numBytes; i++) {
151         if (mByteCursor & 1 ) {
152             pad |= *buffer++; // put second byte in LSB
153             mBurstBuffer[mByteCursor >> 1] = pad;
154             pad = 0;
155         } else {
156             pad |= (*buffer++) << 8; // put first byte in MSB
157         }
158         mByteCursor++;
159     }
160     // Save partially filled short.
161     if (mByteCursor & 1 ){
162         mBurstBuffer[mByteCursor >> 1] = pad;
163     }
164 }
165 
sendZeroPad()166 void SPDIFEncoder::sendZeroPad()
167 {
168     // Pad remainder of burst with zeros.
169     size_t burstSize = mFramer->getSampleFramesPerSyncFrame() * sizeof(uint16_t)
170             * SPDIF_ENCODED_CHANNEL_COUNT;
171     if (mByteCursor > burstSize) {
172         ALOGE("SPDIFEncoder: Burst buffer, contents too large!");
173         clearBurstBuffer();
174     } else {
175         // We don't have to write zeros because buffer already set to zero
176         // by clearBurstBuffer(). Just pretend we wrote zeros by
177         // incrementing cursor.
178         mByteCursor = burstSize;
179     }
180 }
181 
reset()182 void SPDIFEncoder::reset()
183 {
184     ALOGV("SPDIFEncoder: reset()");
185     clearBurstBuffer();
186     if (mFramer != NULL) {
187         mFramer->resetBurst();
188     }
189     mPayloadBytesPending = 0;
190     mScanning = true;
191 }
192 
flushBurstBuffer()193 void SPDIFEncoder::flushBurstBuffer()
194 {
195     const int preambleSize = 4 * sizeof(uint16_t);
196     if (mByteCursor > preambleSize) {
197         // Set lengthCode for valid payload before zeroPad.
198         uint16_t numBytes = (mByteCursor - preambleSize);
199         mBurstBuffer[3] = mFramer->convertBytesToLengthCode(numBytes);
200 
201         sendZeroPad();
202         writeOutput(mBurstBuffer, mByteCursor);
203     }
204     reset();
205 }
206 
clearBurstBuffer()207 void SPDIFEncoder::clearBurstBuffer()
208 {
209     if (mBurstBuffer) {
210         memset(mBurstBuffer, 0, mBurstBufferSizeBytes);
211     }
212     mByteCursor = 0;
213 }
214 
startDataBurst()215 void SPDIFEncoder::startDataBurst()
216 {
217     // Encode IEC61937-1 Burst Preamble
218     uint16_t preamble[4];
219 
220     uint16_t burstInfo = (mBitstreamNumber << 13)
221         | (mFramer->getDataTypeInfo() << 8)
222         | mFramer->getDataType();
223 
224     mRateMultiplier = mFramer->getRateMultiplier();
225 
226     preamble[0] = kSPDIFSync1;
227     preamble[1] = kSPDIFSync2;
228     preamble[2] = burstInfo;
229     preamble[3] = 0; // lengthCode - This will get set after the buffer is full.
230     writeBurstBufferShorts(preamble, 4);
231 }
232 
startSyncFrame()233 size_t SPDIFEncoder::startSyncFrame()
234 {
235     // Write start of encoded frame that was buffered in frame detector.
236     size_t headerSize = mFramer->getHeaderSizeBytes();
237     writeBurstBufferBytes(mFramer->getHeaderAddress(), headerSize);
238     // This is provided by the encoded audio file and may be invalid.
239     size_t frameSize = mFramer->getFrameSizeBytes();
240     if (frameSize < headerSize) {
241         ALOGE("SPDIFEncoder: invalid frameSize = %zu", frameSize);
242         return 0;
243     }
244     // Calculate how many more bytes we need to complete the frame.
245     return frameSize - headerSize;
246 }
247 
248 // Wraps raw encoded data into a data burst.
write(const void * buffer,size_t numBytes)249 ssize_t SPDIFEncoder::write( const void *buffer, size_t numBytes )
250 {
251     size_t bytesLeft = numBytes;
252     const uint8_t *data = (const uint8_t *)buffer;
253     ALOGV("SPDIFEncoder: mScanning = %d, write(buffer[0] = 0x%02X, numBytes = %zu)",
254         mScanning, (uint) *data, numBytes);
255     while (bytesLeft > 0) {
256         if (mScanning) {
257         // Look for beginning of next encoded frame.
258             if (mFramer->scan(*data)) {
259                 if (mByteCursor == 0) {
260                     startDataBurst();
261                 } else if (mFramer->isFirstInBurst()) {
262                     // Make sure that this frame is at the beginning of the data burst.
263                     flushBurstBuffer();
264                     startDataBurst();
265                 }
266                 mPayloadBytesPending = startSyncFrame();
267                 mScanning = false;
268             }
269             data++;
270             bytesLeft--;
271         } else {
272             // Write payload until we hit end of frame.
273             size_t bytesToWrite = bytesLeft;
274             // Only write as many as we need to finish the frame.
275             if (bytesToWrite > mPayloadBytesPending) {
276                 bytesToWrite = mPayloadBytesPending;
277             }
278             writeBurstBufferBytes(data, bytesToWrite);
279 
280             data += bytesToWrite;
281             bytesLeft -= bytesToWrite;
282             mPayloadBytesPending -= bytesToWrite;
283 
284             // If we have all the payload then send a data burst.
285             if (mPayloadBytesPending == 0) {
286                 if (mFramer->isLastInBurst()) {
287                     flushBurstBuffer();
288                 }
289                 mScanning = true;
290             }
291         }
292     }
293     return numBytes;
294 }
295 
296 }  // namespace android
297