ATSParser.cpp revision 6e4c5c499999c04c2477b987f9e64f3ff2bf1a06
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 "ATSParser"
19#include <utils/Log.h>
20
21#include "ATSParser.h"
22
23#include "AnotherPacketSource.h"
24#include "include/avc_utils.h"
25
26#include <media/stagefright/foundation/ABitReader.h>
27#include <media/stagefright/foundation/ABuffer.h>
28#include <media/stagefright/foundation/ADebug.h>
29#include <media/stagefright/foundation/AMessage.h>
30#include <media/stagefright/foundation/hexdump.h>
31#include <media/stagefright/MediaDefs.h>
32#include <media/stagefright/MediaErrors.h>
33#include <media/stagefright/MetaData.h>
34#include <utils/KeyedVector.h>
35
36namespace android {
37
38// I want the expression "y" evaluated even if verbose logging is off.
39#define MY_LOGV(x, y) \
40    do { unsigned tmp = y; LOGV(x, tmp); } while (0)
41
42static const size_t kTSPacketSize = 188;
43
44struct ATSParser::Program : public RefBase {
45    Program(unsigned programMapPID);
46
47    bool parsePID(
48            unsigned pid, unsigned payload_unit_start_indicator,
49            ABitReader *br);
50
51    sp<MediaSource> getSource(SourceType type);
52
53private:
54    unsigned mProgramMapPID;
55    KeyedVector<unsigned, sp<Stream> > mStreams;
56
57    void parseProgramMap(ABitReader *br);
58
59    DISALLOW_EVIL_CONSTRUCTORS(Program);
60};
61
62struct ATSParser::Stream : public RefBase {
63    Stream(unsigned elementaryPID, unsigned streamType);
64
65    void parse(
66            unsigned payload_unit_start_indicator,
67            ABitReader *br);
68
69    sp<MediaSource> getSource(SourceType type);
70
71protected:
72    virtual ~Stream();
73
74private:
75    unsigned mElementaryPID;
76    unsigned mStreamType;
77
78    sp<ABuffer> mBuffer;
79    sp<AnotherPacketSource> mSource;
80    bool mPayloadStarted;
81
82    void flush();
83    void parsePES(ABitReader *br);
84
85    void onPayloadData(
86            unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
87            const uint8_t *data, size_t size);
88
89    void extractAACFrames(const sp<ABuffer> &buffer);
90
91    DISALLOW_EVIL_CONSTRUCTORS(Stream);
92};
93
94////////////////////////////////////////////////////////////////////////////////
95
96ATSParser::Program::Program(unsigned programMapPID)
97    : mProgramMapPID(programMapPID) {
98}
99
100bool ATSParser::Program::parsePID(
101        unsigned pid, unsigned payload_unit_start_indicator,
102        ABitReader *br) {
103    if (pid == mProgramMapPID) {
104        if (payload_unit_start_indicator) {
105            unsigned skip = br->getBits(8);
106            br->skipBits(skip * 8);
107        }
108
109        parseProgramMap(br);
110        return true;
111    }
112
113    ssize_t index = mStreams.indexOfKey(pid);
114    if (index < 0) {
115        return false;
116    }
117
118    mStreams.editValueAt(index)->parse(
119            payload_unit_start_indicator, br);
120
121    return true;
122}
123
124void ATSParser::Program::parseProgramMap(ABitReader *br) {
125    unsigned table_id = br->getBits(8);
126    LOGV("  table_id = %u", table_id);
127    CHECK_EQ(table_id, 0x02u);
128
129    unsigned section_syntax_indicator = br->getBits(1);
130    LOGV("  section_syntax_indicator = %u", section_syntax_indicator);
131    CHECK_EQ(section_syntax_indicator, 1u);
132
133    CHECK_EQ(br->getBits(1), 0u);
134    MY_LOGV("  reserved = %u", br->getBits(2));
135
136    unsigned section_length = br->getBits(12);
137    LOGV("  section_length = %u", section_length);
138    CHECK((section_length & 0xc00) == 0);
139    CHECK_LE(section_length, 1021u);
140
141    MY_LOGV("  program_number = %u", br->getBits(16));
142    MY_LOGV("  reserved = %u", br->getBits(2));
143    MY_LOGV("  version_number = %u", br->getBits(5));
144    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
145    MY_LOGV("  section_number = %u", br->getBits(8));
146    MY_LOGV("  last_section_number = %u", br->getBits(8));
147    MY_LOGV("  reserved = %u", br->getBits(3));
148    MY_LOGV("  PCR_PID = 0x%04x", br->getBits(13));
149    MY_LOGV("  reserved = %u", br->getBits(4));
150
151    unsigned program_info_length = br->getBits(12);
152    LOGV("  program_info_length = %u", program_info_length);
153    CHECK((program_info_length & 0xc00) == 0);
154
155    br->skipBits(program_info_length * 8);  // skip descriptors
156
157    // infoBytesRemaining is the number of bytes that make up the
158    // variable length section of ES_infos. It does not include the
159    // final CRC.
160    size_t infoBytesRemaining = section_length - 9 - program_info_length - 4;
161
162    while (infoBytesRemaining > 0) {
163        CHECK_GE(infoBytesRemaining, 5u);
164
165        unsigned streamType = br->getBits(8);
166        LOGV("    stream_type = 0x%02x", streamType);
167
168        MY_LOGV("    reserved = %u", br->getBits(3));
169
170        unsigned elementaryPID = br->getBits(13);
171        LOGV("    elementary_PID = 0x%04x", elementaryPID);
172
173        MY_LOGV("    reserved = %u", br->getBits(4));
174
175        unsigned ES_info_length = br->getBits(12);
176        LOGV("    ES_info_length = %u", ES_info_length);
177        CHECK((ES_info_length & 0xc00) == 0);
178
179        CHECK_GE(infoBytesRemaining - 5, ES_info_length);
180
181#if 0
182        br->skipBits(ES_info_length * 8);  // skip descriptors
183#else
184        unsigned info_bytes_remaining = ES_info_length;
185        while (info_bytes_remaining >= 2) {
186            MY_LOGV("      tag = 0x%02x", br->getBits(8));
187
188            unsigned descLength = br->getBits(8);
189            LOGV("      len = %u", descLength);
190
191            CHECK_GE(info_bytes_remaining, 2 + descLength);
192
193            br->skipBits(descLength * 8);
194
195            info_bytes_remaining -= descLength + 2;
196        }
197        CHECK_EQ(info_bytes_remaining, 0u);
198#endif
199
200        ssize_t index = mStreams.indexOfKey(elementaryPID);
201#if 0  // XXX revisit
202        CHECK_LT(index, 0);
203        mStreams.add(elementaryPID, new Stream(elementaryPID, streamType));
204#else
205        if (index < 0) {
206            mStreams.add(elementaryPID, new Stream(elementaryPID, streamType));
207        }
208#endif
209
210        infoBytesRemaining -= 5 + ES_info_length;
211    }
212
213    CHECK_EQ(infoBytesRemaining, 0u);
214
215    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
216}
217
218sp<MediaSource> ATSParser::Program::getSource(SourceType type) {
219    for (size_t i = 0; i < mStreams.size(); ++i) {
220        sp<MediaSource> source = mStreams.editValueAt(i)->getSource(type);
221        if (source != NULL) {
222            return source;
223        }
224    }
225
226    return NULL;
227}
228
229////////////////////////////////////////////////////////////////////////////////
230
231ATSParser::Stream::Stream(unsigned elementaryPID, unsigned streamType)
232    : mElementaryPID(elementaryPID),
233      mStreamType(streamType),
234      mBuffer(new ABuffer(128 * 1024)),
235      mPayloadStarted(false) {
236    mBuffer->setRange(0, 0);
237}
238
239ATSParser::Stream::~Stream() {
240}
241
242void ATSParser::Stream::parse(
243        unsigned payload_unit_start_indicator, ABitReader *br) {
244    if (payload_unit_start_indicator) {
245        if (mPayloadStarted) {
246            // Otherwise we run the danger of receiving the trailing bytes
247            // of a PES packet that we never saw the start of and assuming
248            // we have a a complete PES packet.
249
250            flush();
251        }
252
253        mPayloadStarted = true;
254    }
255
256    if (!mPayloadStarted) {
257        return;
258    }
259
260    size_t payloadSizeBits = br->numBitsLeft();
261    CHECK((payloadSizeBits % 8) == 0);
262
263    CHECK_LE(mBuffer->size() + payloadSizeBits / 8, mBuffer->capacity());
264
265    memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
266    mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
267}
268
269void ATSParser::Stream::parsePES(ABitReader *br) {
270    unsigned packet_startcode_prefix = br->getBits(24);
271
272    LOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
273
274    CHECK_EQ(packet_startcode_prefix, 0x000001u);
275
276    unsigned stream_id = br->getBits(8);
277    LOGV("stream_id = 0x%02x", stream_id);
278
279    unsigned PES_packet_length = br->getBits(16);
280    LOGV("PES_packet_length = %u", PES_packet_length);
281
282    if (stream_id != 0xbc  // program_stream_map
283            && stream_id != 0xbe  // padding_stream
284            && stream_id != 0xbf  // private_stream_2
285            && stream_id != 0xf0  // ECM
286            && stream_id != 0xf1  // EMM
287            && stream_id != 0xff  // program_stream_directory
288            && stream_id != 0xf2  // DSMCC
289            && stream_id != 0xf8) {  // H.222.1 type E
290        CHECK_EQ(br->getBits(2), 2u);
291
292        MY_LOGV("PES_scrambling_control = %u", br->getBits(2));
293        MY_LOGV("PES_priority = %u", br->getBits(1));
294        MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
295        MY_LOGV("copyright = %u", br->getBits(1));
296        MY_LOGV("original_or_copy = %u", br->getBits(1));
297
298        unsigned PTS_DTS_flags = br->getBits(2);
299        LOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
300
301        unsigned ESCR_flag = br->getBits(1);
302        LOGV("ESCR_flag = %u", ESCR_flag);
303
304        unsigned ES_rate_flag = br->getBits(1);
305        LOGV("ES_rate_flag = %u", ES_rate_flag);
306
307        unsigned DSM_trick_mode_flag = br->getBits(1);
308        LOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
309
310        unsigned additional_copy_info_flag = br->getBits(1);
311        LOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
312
313        MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
314        MY_LOGV("PES_extension_flag = %u", br->getBits(1));
315
316        unsigned PES_header_data_length = br->getBits(8);
317        LOGV("PES_header_data_length = %u", PES_header_data_length);
318
319        unsigned optional_bytes_remaining = PES_header_data_length;
320
321        uint64_t PTS = 0, DTS = 0;
322
323        if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
324            CHECK_GE(optional_bytes_remaining, 5u);
325
326            CHECK_EQ(br->getBits(4), PTS_DTS_flags);
327
328            PTS = ((uint64_t)br->getBits(3)) << 30;
329            CHECK_EQ(br->getBits(1), 1u);
330            PTS |= ((uint64_t)br->getBits(15)) << 15;
331            CHECK_EQ(br->getBits(1), 1u);
332            PTS |= br->getBits(15);
333            CHECK_EQ(br->getBits(1), 1u);
334
335            LOGV("PTS = %llu", PTS);
336            // LOGI("PTS = %.2f secs", PTS / 90000.0f);
337
338            optional_bytes_remaining -= 5;
339
340            if (PTS_DTS_flags == 3) {
341                CHECK_GE(optional_bytes_remaining, 5u);
342
343                CHECK_EQ(br->getBits(4), 1u);
344
345                DTS = ((uint64_t)br->getBits(3)) << 30;
346                CHECK_EQ(br->getBits(1), 1u);
347                DTS |= ((uint64_t)br->getBits(15)) << 15;
348                CHECK_EQ(br->getBits(1), 1u);
349                DTS |= br->getBits(15);
350                CHECK_EQ(br->getBits(1), 1u);
351
352                LOGV("DTS = %llu", DTS);
353
354                optional_bytes_remaining -= 5;
355            }
356        }
357
358        if (ESCR_flag) {
359            CHECK_GE(optional_bytes_remaining, 6u);
360
361            br->getBits(2);
362
363            uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
364            CHECK_EQ(br->getBits(1), 1u);
365            ESCR |= ((uint64_t)br->getBits(15)) << 15;
366            CHECK_EQ(br->getBits(1), 1u);
367            ESCR |= br->getBits(15);
368            CHECK_EQ(br->getBits(1), 1u);
369
370            LOGV("ESCR = %llu", ESCR);
371            MY_LOGV("ESCR_extension = %u", br->getBits(9));
372
373            CHECK_EQ(br->getBits(1), 1u);
374
375            optional_bytes_remaining -= 6;
376        }
377
378        if (ES_rate_flag) {
379            CHECK_GE(optional_bytes_remaining, 3u);
380
381            CHECK_EQ(br->getBits(1), 1u);
382            MY_LOGV("ES_rate = %u", br->getBits(22));
383            CHECK_EQ(br->getBits(1), 1u);
384
385            optional_bytes_remaining -= 3;
386        }
387
388        br->skipBits(optional_bytes_remaining * 8);
389
390        // ES data follows.
391
392        onPayloadData(
393                PTS_DTS_flags, PTS, DTS,
394                br->data(), br->numBitsLeft() / 8);
395
396        if (PES_packet_length != 0) {
397            CHECK_GE(PES_packet_length, PES_header_data_length + 3);
398
399            unsigned dataLength =
400                PES_packet_length - 3 - PES_header_data_length;
401
402            CHECK_EQ(br->numBitsLeft(), dataLength * 8);
403
404            br->skipBits(dataLength * 8);
405        } else {
406            size_t payloadSizeBits = br->numBitsLeft();
407            CHECK((payloadSizeBits % 8) == 0);
408
409            LOGV("There's %d bytes of payload.", payloadSizeBits / 8);
410        }
411    } else if (stream_id == 0xbe) {  // padding_stream
412        CHECK_NE(PES_packet_length, 0u);
413        br->skipBits(PES_packet_length * 8);
414    } else {
415        CHECK_NE(PES_packet_length, 0u);
416        br->skipBits(PES_packet_length * 8);
417    }
418}
419
420void ATSParser::Stream::flush() {
421    if (mBuffer->size() == 0) {
422        return;
423    }
424
425    LOGV("flushing stream 0x%04x size = %d", mElementaryPID, mBuffer->size());
426
427    ABitReader br(mBuffer->data(), mBuffer->size());
428    parsePES(&br);
429
430    mBuffer->setRange(0, 0);
431}
432
433static sp<ABuffer> FindNAL(
434        const uint8_t *data, size_t size, unsigned nalType,
435        size_t *stopOffset) {
436    bool foundStart = false;
437    size_t startOffset = 0;
438
439    size_t offset = 0;
440    for (;;) {
441        while (offset + 3 < size
442                && memcmp("\x00\x00\x00\x01", &data[offset], 4)) {
443            ++offset;
444        }
445
446        if (foundStart) {
447            size_t nalSize;
448            if (offset + 3 >= size) {
449                nalSize = size - startOffset;
450            } else {
451                nalSize = offset - startOffset;
452            }
453
454            sp<ABuffer> nal = new ABuffer(nalSize);
455            memcpy(nal->data(), &data[startOffset], nalSize);
456
457            if (stopOffset != NULL) {
458                *stopOffset = startOffset + nalSize;
459            }
460
461            return nal;
462        }
463
464        if (offset + 4 >= size) {
465            return NULL;
466        }
467
468        if ((data[offset + 4] & 0x1f) == nalType) {
469            foundStart = true;
470            startOffset = offset + 4;
471        }
472
473        offset += 4;
474    }
475}
476
477static sp<ABuffer> MakeAVCCodecSpecificData(
478        const sp<ABuffer> &buffer, int32_t *width, int32_t *height) {
479    const uint8_t *data = buffer->data();
480    size_t size = buffer->size();
481
482    sp<ABuffer> seqParamSet = FindNAL(data, size, 7, NULL);
483    if (seqParamSet == NULL) {
484        return NULL;
485    }
486
487    FindAVCDimensions(seqParamSet, width, height);
488
489    size_t stopOffset;
490    sp<ABuffer> picParamSet = FindNAL(data, size, 8, &stopOffset);
491    CHECK(picParamSet != NULL);
492
493    buffer->setRange(stopOffset, size - stopOffset);
494    LOGI("buffer has %d bytes left.", buffer->size());
495
496    size_t csdSize =
497        1 + 3 + 1 + 1
498        + 2 * 1 + seqParamSet->size()
499        + 1 + 2 * 1 + picParamSet->size();
500
501    sp<ABuffer> csd = new ABuffer(csdSize);
502    uint8_t *out = csd->data();
503
504    *out++ = 0x01;  // configurationVersion
505    memcpy(out, seqParamSet->data() + 1, 3);  // profile/level...
506    out += 3;
507    *out++ = (0x3f << 2) | 1;  // lengthSize == 2 bytes
508    *out++ = 0xe0 | 1;
509
510    *out++ = seqParamSet->size() >> 8;
511    *out++ = seqParamSet->size() & 0xff;
512    memcpy(out, seqParamSet->data(), seqParamSet->size());
513    out += seqParamSet->size();
514
515    *out++ = 1;
516
517    *out++ = picParamSet->size() >> 8;
518    *out++ = picParamSet->size() & 0xff;
519    memcpy(out, picParamSet->data(), picParamSet->size());
520
521    return csd;
522}
523
524static bool getNextNALUnit(
525        const uint8_t **_data, size_t *_size,
526        const uint8_t **nalStart, size_t *nalSize) {
527    const uint8_t *data = *_data;
528    size_t size = *_size;
529
530    *nalStart = NULL;
531    *nalSize = 0;
532
533    if (size == 0) {
534        return false;
535    }
536
537    size_t offset = 0;
538    for (;;) {
539        CHECK_LT(offset + 2, size);
540
541        if (!memcmp("\x00\x00\x01", &data[offset], 3)) {
542            break;
543        }
544
545        CHECK_EQ((unsigned)data[offset], 0x00u);
546        ++offset;
547    }
548
549    offset += 3;
550    size_t startOffset = offset;
551
552    while (offset + 2 < size
553            && memcmp("\x00\x00\x00", &data[offset], 3)
554            && memcmp("\x00\x00\x01", &data[offset], 3)) {
555        ++offset;
556    }
557
558    if (offset + 2 >= size) {
559        *nalStart = &data[startOffset];
560        *nalSize = size - startOffset;
561
562        *_data = NULL;
563        *_size = 0;
564
565        return true;
566    }
567
568    size_t endOffset = offset;
569
570    while (offset + 2 < size && memcmp("\x00\x00\x01", &data[offset], 3)) {
571        CHECK_EQ((unsigned)data[offset], 0x00u);
572        ++offset;
573    }
574
575    CHECK_LT(offset + 2, size);
576
577    *nalStart = &data[startOffset];
578    *nalSize = endOffset - startOffset;
579
580    *_data = &data[offset];
581    *_size = size - offset;
582
583    return true;
584}
585
586sp<ABuffer> MakeCleanAVCData(const uint8_t *data, size_t size) {
587    const uint8_t *tmpData = data;
588    size_t tmpSize = size;
589
590    size_t totalSize = 0;
591    const uint8_t *nalStart;
592    size_t nalSize;
593    while (getNextNALUnit(&tmpData, &tmpSize, &nalStart, &nalSize)) {
594        totalSize += 4 + nalSize;
595    }
596
597    sp<ABuffer> buffer = new ABuffer(totalSize);
598    size_t offset = 0;
599    while (getNextNALUnit(&data, &size, &nalStart, &nalSize)) {
600        memcpy(buffer->data() + offset, "\x00\x00\x00\x01", 4);
601        memcpy(buffer->data() + offset + 4, nalStart, nalSize);
602
603        offset += 4 + nalSize;
604    }
605
606    return buffer;
607}
608
609static sp<ABuffer> FindMPEG2ADTSConfig(
610        const sp<ABuffer> &buffer, int32_t *sampleRate, int32_t *channelCount) {
611    ABitReader br(buffer->data(), buffer->size());
612
613    CHECK_EQ(br.getBits(12), 0xfffu);
614    CHECK_EQ(br.getBits(1), 0u);
615    CHECK_EQ(br.getBits(2), 0u);
616    br.getBits(1);  // protection_absent
617    unsigned profile = br.getBits(2);
618    LOGI("profile = %u", profile);
619    CHECK_NE(profile, 3u);
620    unsigned sampling_freq_index = br.getBits(4);
621    br.getBits(1);  // private_bit
622    unsigned channel_configuration = br.getBits(3);
623    CHECK_NE(channel_configuration, 0u);
624
625    LOGI("sampling_freq_index = %u", sampling_freq_index);
626    LOGI("channel_configuration = %u", channel_configuration);
627
628    CHECK_LE(sampling_freq_index, 11u);
629    static const int32_t kSamplingFreq[] = {
630        96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
631        16000, 12000, 11025, 8000
632    };
633    *sampleRate = kSamplingFreq[sampling_freq_index];
634
635    *channelCount = channel_configuration;
636
637    static const uint8_t kStaticESDS[] = {
638        0x03, 22,
639        0x00, 0x00,     // ES_ID
640        0x00,           // streamDependenceFlag, URL_Flag, OCRstreamFlag
641
642        0x04, 17,
643        0x40,                       // Audio ISO/IEC 14496-3
644        0x00, 0x00, 0x00, 0x00,
645        0x00, 0x00, 0x00, 0x00,
646        0x00, 0x00, 0x00, 0x00,
647
648        0x05, 2,
649        // AudioSpecificInfo follows
650
651        // oooo offf fccc c000
652        // o - audioObjectType
653        // f - samplingFreqIndex
654        // c - channelConfig
655    };
656    sp<ABuffer> csd = new ABuffer(sizeof(kStaticESDS) + 2);
657    memcpy(csd->data(), kStaticESDS, sizeof(kStaticESDS));
658
659    csd->data()[sizeof(kStaticESDS)] =
660        ((profile + 1) << 3) | (sampling_freq_index >> 1);
661
662    csd->data()[sizeof(kStaticESDS) + 1] =
663        ((sampling_freq_index << 7) & 0x80) | (channel_configuration << 3);
664
665    // hexdump(csd->data(), csd->size());
666    return csd;
667}
668
669void ATSParser::Stream::onPayloadData(
670        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
671        const uint8_t *data, size_t size) {
672    LOGV("onPayloadData mStreamType=0x%02x", mStreamType);
673
674    sp<ABuffer> buffer;
675
676    if (mStreamType == 0x1b) {
677        buffer = MakeCleanAVCData(data, size);
678    } else {
679        // hexdump(data, size);
680
681        buffer = new ABuffer(size);
682        memcpy(buffer->data(), data, size);
683    }
684
685    if (mSource == NULL) {
686        sp<MetaData> meta = new MetaData;
687
688        if (mStreamType == 0x1b) {
689            meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
690
691            int32_t width, height;
692            sp<ABuffer> csd = MakeAVCCodecSpecificData(buffer, &width, &height);
693
694            if (csd == NULL) {
695                return;
696            }
697
698            meta->setData(kKeyAVCC, 0, csd->data(), csd->size());
699            meta->setInt32(kKeyWidth, width);
700            meta->setInt32(kKeyHeight, height);
701        } else {
702            CHECK_EQ(mStreamType, 0x0fu);
703
704            meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
705
706            int32_t sampleRate, channelCount;
707            sp<ABuffer> csd =
708                FindMPEG2ADTSConfig(buffer, &sampleRate, &channelCount);
709
710            LOGI("sampleRate = %d", sampleRate);
711            LOGI("channelCount = %d", channelCount);
712
713            meta->setInt32(kKeySampleRate, sampleRate);
714            meta->setInt32(kKeyChannelCount, channelCount);
715
716            meta->setData(kKeyESDS, 0, csd->data(), csd->size());
717        }
718
719        LOGI("created source!");
720        mSource = new AnotherPacketSource(meta);
721
722        // fall through
723    }
724
725    CHECK(PTS_DTS_flags == 2 || PTS_DTS_flags == 3);
726    buffer->meta()->setInt64("time", (PTS * 100) / 9);
727
728    if (mStreamType == 0x0f) {
729        extractAACFrames(buffer);
730    }
731
732    mSource->queueAccessUnit(buffer);
733}
734
735// Disassemble one or more ADTS frames into their constituent parts and
736// leave only the concatenated raw_data_blocks in the buffer.
737void ATSParser::Stream::extractAACFrames(const sp<ABuffer> &buffer) {
738    size_t dstOffset = 0;
739
740    size_t offset = 0;
741    while (offset < buffer->size()) {
742        CHECK_LE(offset + 7, buffer->size());
743
744        ABitReader bits(buffer->data() + offset, buffer->size() - offset);
745
746        // adts_fixed_header
747
748        CHECK_EQ(bits.getBits(12), 0xfffu);
749        bits.skipBits(3);  // ID, layer
750        bool protection_absent = bits.getBits(1) != 0;
751
752        // profile_ObjectType, sampling_frequency_index, private_bits,
753        // channel_configuration, original_copy, home
754        bits.skipBits(12);
755
756        // adts_variable_header
757
758        // copyright_identification_bit, copyright_identification_start
759        bits.skipBits(2);
760
761        unsigned aac_frame_length = bits.getBits(13);
762
763        bits.skipBits(11);  // adts_buffer_fullness
764
765        unsigned number_of_raw_data_blocks_in_frame = bits.getBits(2);
766
767        if (number_of_raw_data_blocks_in_frame == 0) {
768            size_t scan = offset + aac_frame_length;
769
770            offset += 7;
771            if (!protection_absent) {
772                offset += 2;
773            }
774
775            CHECK_LE(scan, buffer->size());
776
777            LOGV("found aac raw data block at [0x%08x ; 0x%08x)", offset, scan);
778
779            memmove(&buffer->data()[dstOffset], &buffer->data()[offset],
780                    scan - offset);
781
782            dstOffset += scan - offset;
783            offset = scan;
784        } else {
785            // To be implemented.
786            TRESPASS();
787        }
788    }
789    CHECK_EQ(offset, buffer->size());
790
791    buffer->setRange(buffer->offset(), dstOffset);
792}
793
794sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
795    if ((type == AVC_VIDEO && mStreamType == 0x1b)
796        || (type == MPEG2ADTS_AUDIO && mStreamType == 0x0f)) {
797        return mSource;
798    }
799
800    return NULL;
801}
802
803////////////////////////////////////////////////////////////////////////////////
804
805ATSParser::ATSParser() {
806}
807
808ATSParser::~ATSParser() {
809}
810
811void ATSParser::feedTSPacket(const void *data, size_t size) {
812    CHECK_EQ(size, kTSPacketSize);
813
814    ABitReader br((const uint8_t *)data, kTSPacketSize);
815    parseTS(&br);
816}
817
818void ATSParser::parseProgramAssociationTable(ABitReader *br) {
819    unsigned table_id = br->getBits(8);
820    LOGV("  table_id = %u", table_id);
821    CHECK_EQ(table_id, 0x00u);
822
823    unsigned section_syntax_indictor = br->getBits(1);
824    LOGV("  section_syntax_indictor = %u", section_syntax_indictor);
825    CHECK_EQ(section_syntax_indictor, 1u);
826
827    CHECK_EQ(br->getBits(1), 0u);
828    MY_LOGV("  reserved = %u", br->getBits(2));
829
830    unsigned section_length = br->getBits(12);
831    LOGV("  section_length = %u", section_length);
832    CHECK((section_length & 0xc00) == 0);
833
834    MY_LOGV("  transport_stream_id = %u", br->getBits(16));
835    MY_LOGV("  reserved = %u", br->getBits(2));
836    MY_LOGV("  version_number = %u", br->getBits(5));
837    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
838    MY_LOGV("  section_number = %u", br->getBits(8));
839    MY_LOGV("  last_section_number = %u", br->getBits(8));
840
841    size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
842    CHECK_EQ((numProgramBytes % 4), 0u);
843
844    for (size_t i = 0; i < numProgramBytes / 4; ++i) {
845        unsigned program_number = br->getBits(16);
846        LOGV("    program_number = %u", program_number);
847
848        MY_LOGV("    reserved = %u", br->getBits(3));
849
850        if (program_number == 0) {
851            MY_LOGV("    network_PID = 0x%04x", br->getBits(13));
852        } else {
853            unsigned programMapPID = br->getBits(13);
854
855            LOGV("    program_map_PID = 0x%04x", programMapPID);
856
857            mPrograms.push(new Program(programMapPID));
858        }
859    }
860
861    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
862}
863
864void ATSParser::parsePID(
865        ABitReader *br, unsigned PID,
866        unsigned payload_unit_start_indicator) {
867    if (PID == 0) {
868        if (payload_unit_start_indicator) {
869            unsigned skip = br->getBits(8);
870            br->skipBits(skip * 8);
871        }
872        parseProgramAssociationTable(br);
873        return;
874    }
875
876    bool handled = false;
877    for (size_t i = 0; i < mPrograms.size(); ++i) {
878        if (mPrograms.editItemAt(i)->parsePID(
879                    PID, payload_unit_start_indicator, br)) {
880            handled = true;
881            break;
882        }
883    }
884
885    if (!handled) {
886        LOGV("PID 0x%04x not handled.", PID);
887    }
888}
889
890void ATSParser::parseAdaptationField(ABitReader *br) {
891    unsigned adaptation_field_length = br->getBits(8);
892    if (adaptation_field_length > 0) {
893        br->skipBits(adaptation_field_length * 8);  // XXX
894    }
895}
896
897void ATSParser::parseTS(ABitReader *br) {
898    LOGV("---");
899
900    unsigned sync_byte = br->getBits(8);
901    CHECK_EQ(sync_byte, 0x47u);
902
903    MY_LOGV("transport_error_indicator = %u", br->getBits(1));
904
905    unsigned payload_unit_start_indicator = br->getBits(1);
906    LOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
907
908    MY_LOGV("transport_priority = %u", br->getBits(1));
909
910    unsigned PID = br->getBits(13);
911    LOGV("PID = 0x%04x", PID);
912
913    MY_LOGV("transport_scrambling_control = %u", br->getBits(2));
914
915    unsigned adaptation_field_control = br->getBits(2);
916    LOGV("adaptation_field_control = %u", adaptation_field_control);
917
918    MY_LOGV("continuity_counter = %u", br->getBits(4));
919
920    if (adaptation_field_control == 2 || adaptation_field_control == 3) {
921        parseAdaptationField(br);
922    }
923
924    if (adaptation_field_control == 1 || adaptation_field_control == 3) {
925        parsePID(br, PID, payload_unit_start_indicator);
926    }
927}
928
929sp<MediaSource> ATSParser::getSource(SourceType type) {
930    for (size_t i = 0; i < mPrograms.size(); ++i) {
931        sp<MediaSource> source = mPrograms.editItemAt(i)->getSource(type);
932
933        if (source != NULL) {
934            return source;
935        }
936    }
937
938    return NULL;
939}
940
941}  // namespace android
942