ESQueue.cpp revision a44153c1a57202fb538659eb50706e60454d6273
1/*
2 * Copyright (C) 2010 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//#define LOG_NDEBUG 0
18#define LOG_TAG "ESQueue"
19#include <media/stagefright/foundation/ADebug.h>
20
21#include "ESQueue.h"
22
23#include <media/stagefright/foundation/hexdump.h>
24#include <media/stagefright/foundation/ABitReader.h>
25#include <media/stagefright/foundation/ABuffer.h>
26#include <media/stagefright/foundation/AMessage.h>
27#include <media/stagefright/MediaErrors.h>
28#include <media/stagefright/MediaDefs.h>
29#include <media/stagefright/MetaData.h>
30
31#include "include/avc_utils.h"
32
33namespace android {
34
35ElementaryStreamQueue::ElementaryStreamQueue(Mode mode)
36    : mMode(mode) {
37}
38
39sp<MetaData> ElementaryStreamQueue::getFormat() {
40    return mFormat;
41}
42
43void ElementaryStreamQueue::clear() {
44    if (mBuffer != NULL) {
45        mBuffer->setRange(0, 0);
46    }
47
48    mTimestamps.clear();
49    mFormat.clear();
50}
51
52static bool IsSeeminglyValidADTSHeader(const uint8_t *ptr, size_t size) {
53    if (size < 3) {
54        // Not enough data to verify header.
55        return false;
56    }
57
58    if (ptr[0] != 0xff || (ptr[1] >> 4) != 0x0f) {
59        return false;
60    }
61
62    unsigned layer = (ptr[1] >> 1) & 3;
63
64    if (layer != 0) {
65        return false;
66    }
67
68    unsigned ID = (ptr[1] >> 3) & 1;
69    unsigned profile_ObjectType = ptr[2] >> 6;
70
71    if (ID == 1 && profile_ObjectType == 3) {
72        // MPEG-2 profile 3 is reserved.
73        return false;
74    }
75
76    return true;
77}
78
79status_t ElementaryStreamQueue::appendData(
80        const void *data, size_t size, int64_t timeUs) {
81    if (mBuffer == NULL || mBuffer->size() == 0) {
82        switch (mMode) {
83            case H264:
84            {
85#if 0
86                if (size < 4 || memcmp("\x00\x00\x00\x01", data, 4)) {
87                    return ERROR_MALFORMED;
88                }
89#else
90                uint8_t *ptr = (uint8_t *)data;
91
92                ssize_t startOffset = -1;
93                for (size_t i = 0; i + 3 < size; ++i) {
94                    if (!memcmp("\x00\x00\x00\x01", &ptr[i], 4)) {
95                        startOffset = i;
96                        break;
97                    }
98                }
99
100                if (startOffset < 0) {
101                    return ERROR_MALFORMED;
102                }
103
104                if (startOffset > 0) {
105                    LOGI("found something resembling an H.264 syncword at "
106                         "offset %ld",
107                         startOffset);
108                }
109
110                data = &ptr[startOffset];
111                size -= startOffset;
112#endif
113                break;
114            }
115
116            case AAC:
117            {
118                uint8_t *ptr = (uint8_t *)data;
119
120#if 0
121                if (size < 2 || ptr[0] != 0xff || (ptr[1] >> 4) != 0x0f) {
122                    return ERROR_MALFORMED;
123                }
124#else
125                ssize_t startOffset = -1;
126                for (size_t i = 0; i < size; ++i) {
127                    if (IsSeeminglyValidADTSHeader(&ptr[i], size - i)) {
128                        startOffset = i;
129                        break;
130                    }
131                }
132
133                if (startOffset < 0) {
134                    return ERROR_MALFORMED;
135                }
136
137                if (startOffset > 0) {
138                    LOGI("found something resembling an AAC syncword at offset %ld",
139                         startOffset);
140                }
141
142                data = &ptr[startOffset];
143                size -= startOffset;
144#endif
145                break;
146            }
147
148            default:
149                TRESPASS();
150                break;
151        }
152    }
153
154    size_t neededSize = (mBuffer == NULL ? 0 : mBuffer->size()) + size;
155    if (mBuffer == NULL || neededSize > mBuffer->capacity()) {
156        neededSize = (neededSize + 65535) & ~65535;
157
158        LOGV("resizing buffer to size %d", neededSize);
159
160        sp<ABuffer> buffer = new ABuffer(neededSize);
161        if (mBuffer != NULL) {
162            memcpy(buffer->data(), mBuffer->data(), mBuffer->size());
163            buffer->setRange(0, mBuffer->size());
164        } else {
165            buffer->setRange(0, 0);
166        }
167
168        mBuffer = buffer;
169    }
170
171    memcpy(mBuffer->data() + mBuffer->size(), data, size);
172    mBuffer->setRange(0, mBuffer->size() + size);
173
174    mTimestamps.push_back(timeUs);
175
176    return OK;
177}
178
179sp<ABuffer> ElementaryStreamQueue::dequeueAccessUnit() {
180    if (mMode == H264) {
181        return dequeueAccessUnitH264();
182    } else {
183        CHECK_EQ((unsigned)mMode, (unsigned)AAC);
184        return dequeueAccessUnitAAC();
185    }
186}
187
188sp<ABuffer> ElementaryStreamQueue::dequeueAccessUnitAAC() {
189    Vector<size_t> frameOffsets;
190    Vector<size_t> frameSizes;
191    size_t auSize = 0;
192
193    size_t offset = 0;
194    while (offset + 7 <= mBuffer->size()) {
195        ABitReader bits(mBuffer->data() + offset, mBuffer->size() - offset);
196
197        // adts_fixed_header
198
199        CHECK_EQ(bits.getBits(12), 0xfffu);
200        bits.skipBits(3);  // ID, layer
201        bool protection_absent = bits.getBits(1) != 0;
202
203        if (mFormat == NULL) {
204            unsigned profile = bits.getBits(2);
205            CHECK_NE(profile, 3u);
206            unsigned sampling_freq_index = bits.getBits(4);
207            bits.getBits(1);  // private_bit
208            unsigned channel_configuration = bits.getBits(3);
209            CHECK_NE(channel_configuration, 0u);
210            bits.skipBits(2);  // original_copy, home
211
212            mFormat = MakeAACCodecSpecificData(
213                    profile, sampling_freq_index, channel_configuration);
214        } else {
215            // profile_ObjectType, sampling_frequency_index, private_bits,
216            // channel_configuration, original_copy, home
217            bits.skipBits(12);
218        }
219
220        // adts_variable_header
221
222        // copyright_identification_bit, copyright_identification_start
223        bits.skipBits(2);
224
225        unsigned aac_frame_length = bits.getBits(13);
226
227        bits.skipBits(11);  // adts_buffer_fullness
228
229        unsigned number_of_raw_data_blocks_in_frame = bits.getBits(2);
230
231        if (number_of_raw_data_blocks_in_frame != 0) {
232            // To be implemented.
233            TRESPASS();
234        }
235
236        if (offset + aac_frame_length > mBuffer->size()) {
237            break;
238        }
239
240        size_t headerSize = protection_absent ? 7 : 9;
241
242        frameOffsets.push(offset + headerSize);
243        frameSizes.push(aac_frame_length - headerSize);
244        auSize += aac_frame_length - headerSize;
245
246        offset += aac_frame_length;
247    }
248
249    if (offset == 0) {
250        return NULL;
251    }
252
253    sp<ABuffer> accessUnit = new ABuffer(auSize);
254    size_t dstOffset = 0;
255    for (size_t i = 0; i < frameOffsets.size(); ++i) {
256        memcpy(accessUnit->data() + dstOffset,
257               mBuffer->data() + frameOffsets.itemAt(i),
258               frameSizes.itemAt(i));
259
260        dstOffset += frameSizes.itemAt(i);
261    }
262
263    memmove(mBuffer->data(), mBuffer->data() + offset,
264            mBuffer->size() - offset);
265    mBuffer->setRange(0, mBuffer->size() - offset);
266
267    CHECK_GT(mTimestamps.size(), 0u);
268    int64_t timeUs = *mTimestamps.begin();
269    mTimestamps.erase(mTimestamps.begin());
270
271    accessUnit->meta()->setInt64("time", timeUs);
272
273    return accessUnit;
274}
275
276// static
277sp<MetaData> ElementaryStreamQueue::MakeAACCodecSpecificData(
278        unsigned profile, unsigned sampling_freq_index,
279        unsigned channel_configuration) {
280    sp<MetaData> meta = new MetaData;
281    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
282
283    CHECK_LE(sampling_freq_index, 11u);
284    static const int32_t kSamplingFreq[] = {
285        96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
286        16000, 12000, 11025, 8000
287    };
288    meta->setInt32(kKeySampleRate, kSamplingFreq[sampling_freq_index]);
289    meta->setInt32(kKeyChannelCount, channel_configuration);
290
291    static const uint8_t kStaticESDS[] = {
292        0x03, 22,
293        0x00, 0x00,     // ES_ID
294        0x00,           // streamDependenceFlag, URL_Flag, OCRstreamFlag
295
296        0x04, 17,
297        0x40,                       // Audio ISO/IEC 14496-3
298        0x00, 0x00, 0x00, 0x00,
299        0x00, 0x00, 0x00, 0x00,
300        0x00, 0x00, 0x00, 0x00,
301
302        0x05, 2,
303        // AudioSpecificInfo follows
304
305        // oooo offf fccc c000
306        // o - audioObjectType
307        // f - samplingFreqIndex
308        // c - channelConfig
309    };
310    sp<ABuffer> csd = new ABuffer(sizeof(kStaticESDS) + 2);
311    memcpy(csd->data(), kStaticESDS, sizeof(kStaticESDS));
312
313    csd->data()[sizeof(kStaticESDS)] =
314        ((profile + 1) << 3) | (sampling_freq_index >> 1);
315
316    csd->data()[sizeof(kStaticESDS) + 1] =
317        ((sampling_freq_index << 7) & 0x80) | (channel_configuration << 3);
318
319    meta->setData(kKeyESDS, 0, csd->data(), csd->size());
320
321    return meta;
322}
323
324struct NALPosition {
325    size_t nalOffset;
326    size_t nalSize;
327};
328
329sp<ABuffer> ElementaryStreamQueue::dequeueAccessUnitH264() {
330    const uint8_t *data = mBuffer->data();
331    size_t size = mBuffer->size();
332
333    Vector<NALPosition> nals;
334
335    size_t totalSize = 0;
336
337    status_t err;
338    const uint8_t *nalStart;
339    size_t nalSize;
340    bool foundSlice = false;
341    while ((err = getNextNALUnit(&data, &size, &nalStart, &nalSize)) == OK) {
342        CHECK_GT(nalSize, 0u);
343
344        unsigned nalType = nalStart[0] & 0x1f;
345        bool flush = false;
346
347        if (nalType == 1 || nalType == 5) {
348            if (foundSlice) {
349                ABitReader br(nalStart + 1, nalSize);
350                unsigned first_mb_in_slice = parseUE(&br);
351
352                if (first_mb_in_slice == 0) {
353                    // This slice starts a new frame.
354
355                    flush = true;
356                }
357            }
358
359            foundSlice = true;
360        } else if ((nalType == 9 || nalType == 7) && foundSlice) {
361            // Access unit delimiter and SPS will be associated with the
362            // next frame.
363
364            flush = true;
365        }
366
367        if (flush) {
368            // The access unit will contain all nal units up to, but excluding
369            // the current one, separated by 0x00 0x00 0x00 0x01 startcodes.
370
371            size_t auSize = 4 * nals.size() + totalSize;
372            sp<ABuffer> accessUnit = new ABuffer(auSize);
373
374#if !LOG_NDEBUG
375            AString out;
376#endif
377
378            size_t dstOffset = 0;
379            for (size_t i = 0; i < nals.size(); ++i) {
380                const NALPosition &pos = nals.itemAt(i);
381
382                unsigned nalType = mBuffer->data()[pos.nalOffset] & 0x1f;
383
384#if !LOG_NDEBUG
385                char tmp[128];
386                sprintf(tmp, "0x%02x", nalType);
387                if (i > 0) {
388                    out.append(", ");
389                }
390                out.append(tmp);
391#endif
392
393                memcpy(accessUnit->data() + dstOffset, "\x00\x00\x00\x01", 4);
394
395                memcpy(accessUnit->data() + dstOffset + 4,
396                       mBuffer->data() + pos.nalOffset,
397                       pos.nalSize);
398
399                dstOffset += pos.nalSize + 4;
400            }
401
402            LOGV("accessUnit contains nal types %s", out.c_str());
403
404            const NALPosition &pos = nals.itemAt(nals.size() - 1);
405            size_t nextScan = pos.nalOffset + pos.nalSize;
406
407            memmove(mBuffer->data(),
408                    mBuffer->data() + nextScan,
409                    mBuffer->size() - nextScan);
410
411            mBuffer->setRange(0, mBuffer->size() - nextScan);
412
413            CHECK_GT(mTimestamps.size(), 0u);
414            int64_t timeUs = *mTimestamps.begin();
415            mTimestamps.erase(mTimestamps.begin());
416
417            accessUnit->meta()->setInt64("time", timeUs);
418
419            if (mFormat == NULL) {
420                mFormat = MakeAVCCodecSpecificData(accessUnit);
421            }
422
423            return accessUnit;
424        }
425
426        NALPosition pos;
427        pos.nalOffset = nalStart - mBuffer->data();
428        pos.nalSize = nalSize;
429
430        nals.push(pos);
431
432        totalSize += nalSize;
433    }
434    CHECK_EQ(err, (status_t)-EAGAIN);
435
436    return NULL;
437}
438
439}  // namespace android
440