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