summaryrefslogtreecommitdiffstats
path: root/audio_utils/spdif/SPDIFEncoder.cpp
blob: 60b84256592001f1b1ec7757bedcfe5ede74f375 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
 * Copyright 2014, 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 <stdint.h>
#include <string.h>

#define LOG_TAG "AudioSPDIF"
#include <log/log.h>
#include <audio_utils/spdif/SPDIFEncoder.h>

#include "AC3FrameScanner.h"
#include "DTSFrameScanner.h"

namespace android {

// Burst Preamble defined in IEC61937-1
const uint16_t SPDIFEncoder::kSPDIFSync1 = 0xF872; // Pa
const uint16_t SPDIFEncoder::kSPDIFSync2 = 0x4E1F; // Pb

static int32_t sEndianDetector = 1;
#define isLittleEndian()  (*((uint8_t *)&sEndianDetector))

SPDIFEncoder::SPDIFEncoder(audio_format_t format)
  : mFramer(NULL)
  , mSampleRate(48000)
  , mBurstBuffer(NULL)
  , mBurstBufferSizeBytes(0)
  , mRateMultiplier(1)
  , mBurstFrames(0)
  , mByteCursor(0)
  , mBitstreamNumber(0)
  , mPayloadBytesPending(0)
  , mScanning(true)
{
    switch(format) {
        case AUDIO_FORMAT_AC3:
        case AUDIO_FORMAT_E_AC3:
        case AUDIO_FORMAT_E_AC3_JOC:
            mFramer = new AC3FrameScanner(format);
            break;
        case AUDIO_FORMAT_DTS:
        case AUDIO_FORMAT_DTS_HD:
            mFramer = new DTSFrameScanner();
            break;
        default:
            break;
    }

    // This a programmer error. Call isFormatSupported() first.
    LOG_ALWAYS_FATAL_IF((mFramer == NULL),
        "SPDIFEncoder: invalid audio format = 0x%08X", format);

    mBurstBufferSizeBytes = sizeof(uint16_t)
            * SPDIF_ENCODED_CHANNEL_COUNT
            * mFramer->getMaxSampleFramesPerSyncFrame();

    ALOGI("SPDIFEncoder: mBurstBufferSizeBytes = %zu, littleEndian = %d",
            mBurstBufferSizeBytes, isLittleEndian());
    mBurstBuffer = new uint16_t[mBurstBufferSizeBytes >> 1];
    clearBurstBuffer();
}

SPDIFEncoder::SPDIFEncoder()
    : SPDIFEncoder(AUDIO_FORMAT_AC3)
{
}

SPDIFEncoder::~SPDIFEncoder()
{
    delete[] mBurstBuffer;
    delete mFramer;
}

bool SPDIFEncoder::isFormatSupported(audio_format_t format)
{
    switch(format) {
        case AUDIO_FORMAT_AC3:
        case AUDIO_FORMAT_E_AC3:
        case AUDIO_FORMAT_E_AC3_JOC:
        case AUDIO_FORMAT_DTS:
        case AUDIO_FORMAT_DTS_HD:
            return true;
        default:
            return false;
    }
}

int SPDIFEncoder::getBytesPerOutputFrame()
{
    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 (wouldOverflowBuffer(bytesToWrite)) {
        ALOGE("SPDIFEncoder::%s() Burst buffer overflow!", __func__);
        reset();
        return;
    }
    memcpy(&mBurstBuffer[mByteCursor >> 1], buffer, bytesToWrite);
    mByteCursor += bytesToWrite;
}

// Pack the bytes into the short buffer in the order:
//   byte[0] -> short[0] MSB
//   byte[1] -> short[0] LSB
//   byte[2] -> short[1] MSB
//   byte[3] -> short[1] LSB
//   etcetera
// This way they should come out in the correct order for SPDIF on both
// Big and Little Endian CPUs.
void SPDIFEncoder::writeBurstBufferBytes(const uint8_t *buffer, size_t numBytes)
{
    if (wouldOverflowBuffer(numBytes)) {
        ALOGE("SPDIFEncoder::%s() Burst buffer overflow!", __func__);
        clearBurstBuffer();
        return;
    }

    // Avoid reading first word past end of mBurstBuffer.
    if (numBytes == 0) {
        return;
    }
    // Pack bytes into short buffer.
    uint16_t pad = mBurstBuffer[mByteCursor >> 1];
    for (size_t i = 0; i < numBytes; i++) {
        if (mByteCursor & 1 ) {
            pad |= *buffer++; // put second byte in LSB
            mBurstBuffer[mByteCursor >> 1] = pad;
            pad = 0;
        } else {
            pad |= (*buffer++) << 8; // put first byte in MSB
        }
        mByteCursor++;
    }
    // Save partially filled short.
    if (mByteCursor & 1 ){
        mBurstBuffer[mByteCursor >> 1] = pad;
    }
}

void SPDIFEncoder::sendZeroPad()
{
    // Pad remainder of burst with zeros.
    size_t burstSize = mFramer->getSampleFramesPerSyncFrame() * sizeof(uint16_t)
            * SPDIF_ENCODED_CHANNEL_COUNT;
    if (mByteCursor > burstSize) {
        ALOGE("SPDIFEncoder: Burst buffer, contents too large!");
        clearBurstBuffer();
    } else {
        // We don't have to write zeros because buffer already set to zero
        // by clearBurstBuffer(). Just pretend we wrote zeros by
        // incrementing cursor.
        mByteCursor = burstSize;
    }
}

void SPDIFEncoder::reset()
{
    ALOGV("SPDIFEncoder: reset()");
    clearBurstBuffer();
    if (mFramer != NULL) {
        mFramer->resetBurst();
    }
    mPayloadBytesPending = 0;
    mScanning = true;
}

void SPDIFEncoder::flushBurstBuffer()
{
    const int preambleSize = 4 * sizeof(uint16_t);
    if (mByteCursor > preambleSize) {
        // Set lengthCode for valid payload before zeroPad.
        uint16_t numBytes = (mByteCursor - preambleSize);
        mBurstBuffer[3] = mFramer->convertBytesToLengthCode(numBytes);

        sendZeroPad();
        writeOutput(mBurstBuffer, mByteCursor);
    }
    reset();
}

void SPDIFEncoder::clearBurstBuffer()
{
    if (mBurstBuffer) {
        memset(mBurstBuffer, 0, mBurstBufferSizeBytes);
    }
    mByteCursor = 0;
}

void SPDIFEncoder::startDataBurst()
{
    // Encode IEC61937-1 Burst Preamble
    uint16_t preamble[4];

    uint16_t burstInfo = (mBitstreamNumber << 13)
        | (mFramer->getDataTypeInfo() << 8)
        | mFramer->getDataType();

    mRateMultiplier = mFramer->getRateMultiplier();

    preamble[0] = kSPDIFSync1;
    preamble[1] = kSPDIFSync2;
    preamble[2] = burstInfo;
    preamble[3] = 0; // lengthCode - This will get set after the buffer is full.
    writeBurstBufferShorts(preamble, 4);
}

size_t SPDIFEncoder::startSyncFrame()
{
    // Write start of encoded frame that was buffered in frame detector.
    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.
ssize_t SPDIFEncoder::write( const void *buffer, size_t numBytes )
{
    size_t bytesLeft = numBytes;
    const uint8_t *data = (const uint8_t *)buffer;
    ALOGV("SPDIFEncoder: mScanning = %d, write(buffer[0] = 0x%02X, numBytes = %zu)",
        mScanning, (uint) *data, numBytes);
    while (bytesLeft > 0) {
        if (mScanning) {
        // Look for beginning of next encoded frame.
            if (mFramer->scan(*data)) {
                if (mByteCursor == 0) {
                    startDataBurst();
                } else if (mFramer->isFirstInBurst()) {
                    // Make sure that this frame is at the beginning of the data burst.
                    flushBurstBuffer();
                    startDataBurst();
                }
                mPayloadBytesPending = startSyncFrame();
                mScanning = false;
            }
            data++;
            bytesLeft--;
        } else {
            // Write payload until we hit end of frame.
            size_t bytesToWrite = bytesLeft;
            // Only write as many as we need to finish the frame.
            if (bytesToWrite > mPayloadBytesPending) {
                bytesToWrite = mPayloadBytesPending;
            }
            writeBurstBufferBytes(data, bytesToWrite);

            data += bytesToWrite;
            bytesLeft -= bytesToWrite;
            mPayloadBytesPending -= bytesToWrite;

            // If we have all the payload then send a data burst.
            if (mPayloadBytesPending == 0) {
                if (mFramer->isLastInBurst()) {
                    flushBurstBuffer();
                }
                mScanning = true;
            }
        }
    }
    return numBytes;
}

}  // namespace android