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