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