ATSParser.cpp revision 6e3d311b6631b12aac2879d1b08c3534aece78b1
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 "ESQueue.h"
25#include "include/avc_utils.h"
26
27#include <media/stagefright/foundation/ABitReader.h>
28#include <media/stagefright/foundation/ABuffer.h>
29#include <media/stagefright/foundation/ADebug.h>
30#include <media/stagefright/foundation/AMessage.h>
31#include <media/stagefright/foundation/hexdump.h>
32#include <media/stagefright/MediaDefs.h>
33#include <media/stagefright/MediaErrors.h>
34#include <media/stagefright/MetaData.h>
35#include <media/IStreamSource.h>
36#include <utils/KeyedVector.h>
37
38namespace android {
39
40// I want the expression "y" evaluated even if verbose logging is off.
41#define MY_LOGV(x, y) \
42    do { unsigned tmp = y; LOGV(x, tmp); } while (0)
43
44static const size_t kTSPacketSize = 188;
45
46struct ATSParser::Program : public RefBase {
47    Program(ATSParser *parser, unsigned programNumber, unsigned programMapPID);
48
49    bool parsePID(
50            unsigned pid, unsigned payload_unit_start_indicator,
51            ABitReader *br, status_t *err);
52
53    void signalDiscontinuity(
54            DiscontinuityType type, const sp<AMessage> &extra);
55
56    void signalEOS(status_t finalResult);
57
58    sp<MediaSource> getSource(SourceType type);
59
60    int64_t convertPTSToTimestamp(uint64_t PTS);
61
62    bool PTSTimeDeltaEstablished() const {
63        return mFirstPTSValid;
64    }
65
66    unsigned number() const { return mProgramNumber; }
67
68    void updateProgramMapPID(unsigned programMapPID) {
69        mProgramMapPID = programMapPID;
70    }
71
72private:
73    ATSParser *mParser;
74    unsigned mProgramNumber;
75    unsigned mProgramMapPID;
76    KeyedVector<unsigned, sp<Stream> > mStreams;
77    bool mFirstPTSValid;
78    uint64_t mFirstPTS;
79
80    status_t parseProgramMap(ABitReader *br);
81
82    DISALLOW_EVIL_CONSTRUCTORS(Program);
83};
84
85struct ATSParser::Stream : public RefBase {
86    Stream(Program *program, unsigned elementaryPID, unsigned streamType);
87
88    unsigned type() const { return mStreamType; }
89    unsigned pid() const { return mElementaryPID; }
90    void setPID(unsigned pid) { mElementaryPID = pid; }
91
92    status_t parse(
93            unsigned payload_unit_start_indicator,
94            ABitReader *br);
95
96    void signalDiscontinuity(
97            DiscontinuityType type, const sp<AMessage> &extra);
98
99    void signalEOS(status_t finalResult);
100
101    sp<MediaSource> getSource(SourceType type);
102
103protected:
104    virtual ~Stream();
105
106private:
107    Program *mProgram;
108    unsigned mElementaryPID;
109    unsigned mStreamType;
110
111    sp<ABuffer> mBuffer;
112    sp<AnotherPacketSource> mSource;
113    bool mPayloadStarted;
114
115    ElementaryStreamQueue *mQueue;
116
117    status_t flush();
118    status_t parsePES(ABitReader *br);
119
120    void onPayloadData(
121            unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
122            const uint8_t *data, size_t size);
123
124    void extractAACFrames(const sp<ABuffer> &buffer);
125
126    bool isAudio() const;
127    bool isVideo() const;
128
129    DISALLOW_EVIL_CONSTRUCTORS(Stream);
130};
131
132////////////////////////////////////////////////////////////////////////////////
133
134ATSParser::Program::Program(
135        ATSParser *parser, unsigned programNumber, unsigned programMapPID)
136    : mParser(parser),
137      mProgramNumber(programNumber),
138      mProgramMapPID(programMapPID),
139      mFirstPTSValid(false),
140      mFirstPTS(0) {
141    LOGV("new program number %u", programNumber);
142}
143
144bool ATSParser::Program::parsePID(
145        unsigned pid, unsigned payload_unit_start_indicator,
146        ABitReader *br, status_t *err) {
147    *err = OK;
148
149    if (pid == mProgramMapPID) {
150        if (payload_unit_start_indicator) {
151            unsigned skip = br->getBits(8);
152            br->skipBits(skip * 8);
153        }
154
155        *err = parseProgramMap(br);
156
157        return true;
158    }
159
160    ssize_t index = mStreams.indexOfKey(pid);
161    if (index < 0) {
162        return false;
163    }
164
165    *err = mStreams.editValueAt(index)->parse(
166            payload_unit_start_indicator, br);
167
168    return true;
169}
170
171void ATSParser::Program::signalDiscontinuity(
172        DiscontinuityType type, const sp<AMessage> &extra) {
173    for (size_t i = 0; i < mStreams.size(); ++i) {
174        mStreams.editValueAt(i)->signalDiscontinuity(type, extra);
175    }
176}
177
178void ATSParser::Program::signalEOS(status_t finalResult) {
179    for (size_t i = 0; i < mStreams.size(); ++i) {
180        mStreams.editValueAt(i)->signalEOS(finalResult);
181    }
182}
183
184struct StreamInfo {
185    unsigned mType;
186    unsigned mPID;
187};
188
189status_t ATSParser::Program::parseProgramMap(ABitReader *br) {
190    unsigned table_id = br->getBits(8);
191    LOGV("  table_id = %u", table_id);
192    CHECK_EQ(table_id, 0x02u);
193
194    unsigned section_syntax_indicator = br->getBits(1);
195    LOGV("  section_syntax_indicator = %u", section_syntax_indicator);
196    CHECK_EQ(section_syntax_indicator, 1u);
197
198    CHECK_EQ(br->getBits(1), 0u);
199    MY_LOGV("  reserved = %u", br->getBits(2));
200
201    unsigned section_length = br->getBits(12);
202    LOGV("  section_length = %u", section_length);
203    CHECK_EQ(section_length & 0xc00, 0u);
204    CHECK_LE(section_length, 1021u);
205
206    MY_LOGV("  program_number = %u", br->getBits(16));
207    MY_LOGV("  reserved = %u", br->getBits(2));
208    MY_LOGV("  version_number = %u", br->getBits(5));
209    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
210    MY_LOGV("  section_number = %u", br->getBits(8));
211    MY_LOGV("  last_section_number = %u", br->getBits(8));
212    MY_LOGV("  reserved = %u", br->getBits(3));
213    MY_LOGV("  PCR_PID = 0x%04x", br->getBits(13));
214    MY_LOGV("  reserved = %u", br->getBits(4));
215
216    unsigned program_info_length = br->getBits(12);
217    LOGV("  program_info_length = %u", program_info_length);
218    CHECK_EQ(program_info_length & 0xc00, 0u);
219
220    br->skipBits(program_info_length * 8);  // skip descriptors
221
222    Vector<StreamInfo> infos;
223
224    // infoBytesRemaining is the number of bytes that make up the
225    // variable length section of ES_infos. It does not include the
226    // final CRC.
227    size_t infoBytesRemaining = section_length - 9 - program_info_length - 4;
228
229    while (infoBytesRemaining > 0) {
230        CHECK_GE(infoBytesRemaining, 5u);
231
232        unsigned streamType = br->getBits(8);
233        LOGV("    stream_type = 0x%02x", streamType);
234
235        MY_LOGV("    reserved = %u", br->getBits(3));
236
237        unsigned elementaryPID = br->getBits(13);
238        LOGV("    elementary_PID = 0x%04x", elementaryPID);
239
240        MY_LOGV("    reserved = %u", br->getBits(4));
241
242        unsigned ES_info_length = br->getBits(12);
243        LOGV("    ES_info_length = %u", ES_info_length);
244        CHECK_EQ(ES_info_length & 0xc00, 0u);
245
246        CHECK_GE(infoBytesRemaining - 5, ES_info_length);
247
248#if 0
249        br->skipBits(ES_info_length * 8);  // skip descriptors
250#else
251        unsigned info_bytes_remaining = ES_info_length;
252        while (info_bytes_remaining >= 2) {
253            MY_LOGV("      tag = 0x%02x", br->getBits(8));
254
255            unsigned descLength = br->getBits(8);
256            LOGV("      len = %u", descLength);
257
258            CHECK_GE(info_bytes_remaining, 2 + descLength);
259
260            br->skipBits(descLength * 8);
261
262            info_bytes_remaining -= descLength + 2;
263        }
264        CHECK_EQ(info_bytes_remaining, 0u);
265#endif
266
267        StreamInfo info;
268        info.mType = streamType;
269        info.mPID = elementaryPID;
270        infos.push(info);
271
272        infoBytesRemaining -= 5 + ES_info_length;
273    }
274
275    CHECK_EQ(infoBytesRemaining, 0u);
276    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
277
278    bool PIDsChanged = false;
279    for (size_t i = 0; i < infos.size(); ++i) {
280        StreamInfo &info = infos.editItemAt(i);
281
282        ssize_t index = mStreams.indexOfKey(info.mPID);
283
284        if (index >= 0 && mStreams.editValueAt(index)->type() != info.mType) {
285            LOGI("uh oh. stream PIDs have changed.");
286            PIDsChanged = true;
287            break;
288        }
289    }
290
291    if (PIDsChanged) {
292#if 0
293        LOGI("before:");
294        for (size_t i = 0; i < mStreams.size(); ++i) {
295            sp<Stream> stream = mStreams.editValueAt(i);
296
297            LOGI("PID 0x%08x => type 0x%02x", stream->pid(), stream->type());
298        }
299
300        LOGI("after:");
301        for (size_t i = 0; i < infos.size(); ++i) {
302            StreamInfo &info = infos.editItemAt(i);
303
304            LOGI("PID 0x%08x => type 0x%02x", info.mPID, info.mType);
305        }
306#endif
307
308        // The only case we can recover from is if we have two streams
309        // and they switched PIDs.
310
311        bool success = false;
312
313        if (mStreams.size() == 2 && infos.size() == 2) {
314            const StreamInfo &info1 = infos.itemAt(0);
315            const StreamInfo &info2 = infos.itemAt(1);
316
317            sp<Stream> s1 = mStreams.editValueAt(0);
318            sp<Stream> s2 = mStreams.editValueAt(1);
319
320            bool caseA =
321                info1.mPID == s1->pid() && info1.mType == s2->type()
322                    && info2.mPID == s2->pid() && info2.mType == s1->type();
323
324            bool caseB =
325                info1.mPID == s2->pid() && info1.mType == s1->type()
326                    && info2.mPID == s1->pid() && info2.mType == s2->type();
327
328            if (caseA || caseB) {
329                unsigned pid1 = s1->pid();
330                unsigned pid2 = s2->pid();
331                s1->setPID(pid2);
332                s2->setPID(pid1);
333
334                mStreams.clear();
335                mStreams.add(s1->pid(), s1);
336                mStreams.add(s2->pid(), s2);
337
338                success = true;
339            }
340        }
341
342        if (!success) {
343            LOGI("Stream PIDs changed and we cannot recover.");
344            return ERROR_MALFORMED;
345        }
346    }
347
348    for (size_t i = 0; i < infos.size(); ++i) {
349        StreamInfo &info = infos.editItemAt(i);
350
351        ssize_t index = mStreams.indexOfKey(info.mPID);
352
353        if (index < 0) {
354            sp<Stream> stream = new Stream(this, info.mPID, info.mType);
355            mStreams.add(info.mPID, stream);
356        }
357    }
358
359    return OK;
360}
361
362sp<MediaSource> ATSParser::Program::getSource(SourceType type) {
363    size_t index = (type == AUDIO) ? 0 : 0;
364
365    for (size_t i = 0; i < mStreams.size(); ++i) {
366        sp<MediaSource> source = mStreams.editValueAt(i)->getSource(type);
367        if (source != NULL) {
368            if (index == 0) {
369                return source;
370            }
371            --index;
372        }
373    }
374
375    return NULL;
376}
377
378int64_t ATSParser::Program::convertPTSToTimestamp(uint64_t PTS) {
379    if (!(mParser->mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)) {
380        if (!mFirstPTSValid) {
381            mFirstPTSValid = true;
382            mFirstPTS = PTS;
383            PTS = 0;
384        } else if (PTS < mFirstPTS) {
385            PTS = 0;
386        } else {
387            PTS -= mFirstPTS;
388        }
389    }
390
391    return (PTS * 100) / 9;
392}
393
394////////////////////////////////////////////////////////////////////////////////
395
396ATSParser::Stream::Stream(
397        Program *program, unsigned elementaryPID, unsigned streamType)
398    : mProgram(program),
399      mElementaryPID(elementaryPID),
400      mStreamType(streamType),
401      mPayloadStarted(false),
402      mQueue(NULL) {
403    switch (mStreamType) {
404        case STREAMTYPE_H264:
405            mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::H264);
406            break;
407        case STREAMTYPE_MPEG2_AUDIO_ADTS:
408            mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::AAC);
409            break;
410        case STREAMTYPE_MPEG1_AUDIO:
411        case STREAMTYPE_MPEG2_AUDIO:
412            mQueue = new ElementaryStreamQueue(
413                    ElementaryStreamQueue::MPEG_AUDIO);
414            break;
415
416        case STREAMTYPE_MPEG1_VIDEO:
417        case STREAMTYPE_MPEG2_VIDEO:
418            mQueue = new ElementaryStreamQueue(
419                    ElementaryStreamQueue::MPEG_VIDEO);
420            break;
421
422        case STREAMTYPE_MPEG4_VIDEO:
423            mQueue = new ElementaryStreamQueue(
424                    ElementaryStreamQueue::MPEG4_VIDEO);
425            break;
426
427        default:
428            break;
429    }
430
431    LOGV("new stream PID 0x%02x, type 0x%02x", elementaryPID, streamType);
432
433    if (mQueue != NULL) {
434        mBuffer = new ABuffer(192 * 1024);
435        mBuffer->setRange(0, 0);
436    }
437}
438
439ATSParser::Stream::~Stream() {
440    delete mQueue;
441    mQueue = NULL;
442}
443
444status_t ATSParser::Stream::parse(
445        unsigned payload_unit_start_indicator, ABitReader *br) {
446    if (mQueue == NULL) {
447        return OK;
448    }
449
450    if (payload_unit_start_indicator) {
451        if (mPayloadStarted) {
452            // Otherwise we run the danger of receiving the trailing bytes
453            // of a PES packet that we never saw the start of and assuming
454            // we have a a complete PES packet.
455
456            status_t err = flush();
457
458            if (err != OK) {
459                return err;
460            }
461        }
462
463        mPayloadStarted = true;
464    }
465
466    if (!mPayloadStarted) {
467        return OK;
468    }
469
470    size_t payloadSizeBits = br->numBitsLeft();
471    CHECK_EQ(payloadSizeBits % 8, 0u);
472
473    size_t neededSize = mBuffer->size() + payloadSizeBits / 8;
474    if (mBuffer->capacity() < neededSize) {
475        // Increment in multiples of 64K.
476        neededSize = (neededSize + 65535) & ~65535;
477
478        LOGI("resizing buffer to %d bytes", neededSize);
479
480        sp<ABuffer> newBuffer = new ABuffer(neededSize);
481        memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
482        newBuffer->setRange(0, mBuffer->size());
483        mBuffer = newBuffer;
484    }
485
486    memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
487    mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
488
489    return OK;
490}
491
492bool ATSParser::Stream::isVideo() const {
493    switch (mStreamType) {
494        case STREAMTYPE_H264:
495        case STREAMTYPE_MPEG1_VIDEO:
496        case STREAMTYPE_MPEG2_VIDEO:
497        case STREAMTYPE_MPEG4_VIDEO:
498            return true;
499
500        default:
501            return false;
502    }
503}
504
505bool ATSParser::Stream::isAudio() const {
506    switch (mStreamType) {
507        case STREAMTYPE_MPEG1_AUDIO:
508        case STREAMTYPE_MPEG2_AUDIO:
509        case STREAMTYPE_MPEG2_AUDIO_ADTS:
510            return true;
511
512        default:
513            return false;
514    }
515}
516
517void ATSParser::Stream::signalDiscontinuity(
518        DiscontinuityType type, const sp<AMessage> &extra) {
519    if (mQueue == NULL) {
520        return;
521    }
522
523    mPayloadStarted = false;
524    mBuffer->setRange(0, 0);
525
526    bool clearFormat = false;
527    if (isAudio()) {
528        if (type & DISCONTINUITY_AUDIO_FORMAT) {
529            clearFormat = true;
530        }
531    } else {
532        if (type & DISCONTINUITY_VIDEO_FORMAT) {
533            clearFormat = true;
534        }
535    }
536
537    mQueue->clear(clearFormat);
538
539    if (type & DISCONTINUITY_TIME) {
540        uint64_t resumeAtPTS;
541        if (extra != NULL
542                && extra->findInt64(
543                    IStreamListener::kKeyResumeAtPTS,
544                    (int64_t *)&resumeAtPTS)) {
545            int64_t resumeAtMediaTimeUs =
546                mProgram->convertPTSToTimestamp(resumeAtPTS);
547
548            extra->setInt64("resume-at-mediatimeUs", resumeAtMediaTimeUs);
549        }
550    }
551
552    if (mSource != NULL) {
553        mSource->queueDiscontinuity(type, extra);
554    }
555}
556
557void ATSParser::Stream::signalEOS(status_t finalResult) {
558    if (mSource != NULL) {
559        mSource->signalEOS(finalResult);
560    }
561}
562
563status_t ATSParser::Stream::parsePES(ABitReader *br) {
564    unsigned packet_startcode_prefix = br->getBits(24);
565
566    LOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
567
568    if (packet_startcode_prefix != 1) {
569        LOGV("Supposedly payload_unit_start=1 unit does not start "
570             "with startcode.");
571
572        return ERROR_MALFORMED;
573    }
574
575    CHECK_EQ(packet_startcode_prefix, 0x000001u);
576
577    unsigned stream_id = br->getBits(8);
578    LOGV("stream_id = 0x%02x", stream_id);
579
580    unsigned PES_packet_length = br->getBits(16);
581    LOGV("PES_packet_length = %u", PES_packet_length);
582
583    if (stream_id != 0xbc  // program_stream_map
584            && stream_id != 0xbe  // padding_stream
585            && stream_id != 0xbf  // private_stream_2
586            && stream_id != 0xf0  // ECM
587            && stream_id != 0xf1  // EMM
588            && stream_id != 0xff  // program_stream_directory
589            && stream_id != 0xf2  // DSMCC
590            && stream_id != 0xf8) {  // H.222.1 type E
591        CHECK_EQ(br->getBits(2), 2u);
592
593        MY_LOGV("PES_scrambling_control = %u", br->getBits(2));
594        MY_LOGV("PES_priority = %u", br->getBits(1));
595        MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
596        MY_LOGV("copyright = %u", br->getBits(1));
597        MY_LOGV("original_or_copy = %u", br->getBits(1));
598
599        unsigned PTS_DTS_flags = br->getBits(2);
600        LOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
601
602        unsigned ESCR_flag = br->getBits(1);
603        LOGV("ESCR_flag = %u", ESCR_flag);
604
605        unsigned ES_rate_flag = br->getBits(1);
606        LOGV("ES_rate_flag = %u", ES_rate_flag);
607
608        unsigned DSM_trick_mode_flag = br->getBits(1);
609        LOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
610
611        unsigned additional_copy_info_flag = br->getBits(1);
612        LOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
613
614        MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
615        MY_LOGV("PES_extension_flag = %u", br->getBits(1));
616
617        unsigned PES_header_data_length = br->getBits(8);
618        LOGV("PES_header_data_length = %u", PES_header_data_length);
619
620        unsigned optional_bytes_remaining = PES_header_data_length;
621
622        uint64_t PTS = 0, DTS = 0;
623
624        if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
625            CHECK_GE(optional_bytes_remaining, 5u);
626
627            CHECK_EQ(br->getBits(4), PTS_DTS_flags);
628
629            PTS = ((uint64_t)br->getBits(3)) << 30;
630            CHECK_EQ(br->getBits(1), 1u);
631            PTS |= ((uint64_t)br->getBits(15)) << 15;
632            CHECK_EQ(br->getBits(1), 1u);
633            PTS |= br->getBits(15);
634            CHECK_EQ(br->getBits(1), 1u);
635
636            LOGV("PTS = %llu", PTS);
637            // LOGI("PTS = %.2f secs", PTS / 90000.0f);
638
639            optional_bytes_remaining -= 5;
640
641            if (PTS_DTS_flags == 3) {
642                CHECK_GE(optional_bytes_remaining, 5u);
643
644                CHECK_EQ(br->getBits(4), 1u);
645
646                DTS = ((uint64_t)br->getBits(3)) << 30;
647                CHECK_EQ(br->getBits(1), 1u);
648                DTS |= ((uint64_t)br->getBits(15)) << 15;
649                CHECK_EQ(br->getBits(1), 1u);
650                DTS |= br->getBits(15);
651                CHECK_EQ(br->getBits(1), 1u);
652
653                LOGV("DTS = %llu", DTS);
654
655                optional_bytes_remaining -= 5;
656            }
657        }
658
659        if (ESCR_flag) {
660            CHECK_GE(optional_bytes_remaining, 6u);
661
662            br->getBits(2);
663
664            uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
665            CHECK_EQ(br->getBits(1), 1u);
666            ESCR |= ((uint64_t)br->getBits(15)) << 15;
667            CHECK_EQ(br->getBits(1), 1u);
668            ESCR |= br->getBits(15);
669            CHECK_EQ(br->getBits(1), 1u);
670
671            LOGV("ESCR = %llu", ESCR);
672            MY_LOGV("ESCR_extension = %u", br->getBits(9));
673
674            CHECK_EQ(br->getBits(1), 1u);
675
676            optional_bytes_remaining -= 6;
677        }
678
679        if (ES_rate_flag) {
680            CHECK_GE(optional_bytes_remaining, 3u);
681
682            CHECK_EQ(br->getBits(1), 1u);
683            MY_LOGV("ES_rate = %u", br->getBits(22));
684            CHECK_EQ(br->getBits(1), 1u);
685
686            optional_bytes_remaining -= 3;
687        }
688
689        br->skipBits(optional_bytes_remaining * 8);
690
691        // ES data follows.
692
693        if (PES_packet_length != 0) {
694            CHECK_GE(PES_packet_length, PES_header_data_length + 3);
695
696            unsigned dataLength =
697                PES_packet_length - 3 - PES_header_data_length;
698
699            if (br->numBitsLeft() < dataLength * 8) {
700                LOGE("PES packet does not carry enough data to contain "
701                     "payload. (numBitsLeft = %d, required = %d)",
702                     br->numBitsLeft(), dataLength * 8);
703
704                return ERROR_MALFORMED;
705            }
706
707            CHECK_GE(br->numBitsLeft(), dataLength * 8);
708
709            onPayloadData(
710                    PTS_DTS_flags, PTS, DTS, br->data(), dataLength);
711
712            br->skipBits(dataLength * 8);
713        } else {
714            onPayloadData(
715                    PTS_DTS_flags, PTS, DTS,
716                    br->data(), br->numBitsLeft() / 8);
717
718            size_t payloadSizeBits = br->numBitsLeft();
719            CHECK_EQ(payloadSizeBits % 8, 0u);
720
721            LOGV("There's %d bytes of payload.", payloadSizeBits / 8);
722        }
723    } else if (stream_id == 0xbe) {  // padding_stream
724        CHECK_NE(PES_packet_length, 0u);
725        br->skipBits(PES_packet_length * 8);
726    } else {
727        CHECK_NE(PES_packet_length, 0u);
728        br->skipBits(PES_packet_length * 8);
729    }
730
731    return OK;
732}
733
734status_t ATSParser::Stream::flush() {
735    if (mBuffer->size() == 0) {
736        return OK;
737    }
738
739    LOGV("flushing stream 0x%04x size = %d", mElementaryPID, mBuffer->size());
740
741    ABitReader br(mBuffer->data(), mBuffer->size());
742
743    status_t err = parsePES(&br);
744
745    mBuffer->setRange(0, 0);
746
747    return err;
748}
749
750void ATSParser::Stream::onPayloadData(
751        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
752        const uint8_t *data, size_t size) {
753    LOGV("onPayloadData mStreamType=0x%02x", mStreamType);
754
755    int64_t timeUs = 0ll;  // no presentation timestamp available.
756    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
757        timeUs = mProgram->convertPTSToTimestamp(PTS);
758    }
759
760    status_t err = mQueue->appendData(data, size, timeUs);
761
762    if (err != OK) {
763        return;
764    }
765
766    sp<ABuffer> accessUnit;
767    while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
768        if (mSource == NULL) {
769            sp<MetaData> meta = mQueue->getFormat();
770
771            if (meta != NULL) {
772                LOGV("Stream PID 0x%08x of type 0x%02x now has data.",
773                     mElementaryPID, mStreamType);
774
775                mSource = new AnotherPacketSource(meta);
776                mSource->queueAccessUnit(accessUnit);
777            }
778        } else if (mQueue->getFormat() != NULL) {
779            // After a discontinuity we invalidate the queue's format
780            // and won't enqueue any access units to the source until
781            // the queue has reestablished the new format.
782
783            if (mSource->getFormat() == NULL) {
784                mSource->setFormat(mQueue->getFormat());
785            }
786            mSource->queueAccessUnit(accessUnit);
787        }
788    }
789}
790
791sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
792    switch (type) {
793        case VIDEO:
794        {
795            if (isVideo()) {
796                return mSource;
797            }
798            break;
799        }
800
801        case AUDIO:
802        {
803            if (isAudio()) {
804                return mSource;
805            }
806            break;
807        }
808
809        default:
810            break;
811    }
812
813    return NULL;
814}
815
816////////////////////////////////////////////////////////////////////////////////
817
818ATSParser::ATSParser(uint32_t flags)
819    : mFlags(flags) {
820}
821
822ATSParser::~ATSParser() {
823}
824
825status_t ATSParser::feedTSPacket(const void *data, size_t size) {
826    CHECK_EQ(size, kTSPacketSize);
827
828    ABitReader br((const uint8_t *)data, kTSPacketSize);
829    return parseTS(&br);
830}
831
832void ATSParser::signalDiscontinuity(
833        DiscontinuityType type, const sp<AMessage> &extra) {
834    for (size_t i = 0; i < mPrograms.size(); ++i) {
835        mPrograms.editItemAt(i)->signalDiscontinuity(type, extra);
836    }
837}
838
839void ATSParser::signalEOS(status_t finalResult) {
840    CHECK_NE(finalResult, (status_t)OK);
841
842    for (size_t i = 0; i < mPrograms.size(); ++i) {
843        mPrograms.editItemAt(i)->signalEOS(finalResult);
844    }
845}
846
847void ATSParser::parseProgramAssociationTable(ABitReader *br) {
848    unsigned table_id = br->getBits(8);
849    LOGV("  table_id = %u", table_id);
850    CHECK_EQ(table_id, 0x00u);
851
852    unsigned section_syntax_indictor = br->getBits(1);
853    LOGV("  section_syntax_indictor = %u", section_syntax_indictor);
854    CHECK_EQ(section_syntax_indictor, 1u);
855
856    CHECK_EQ(br->getBits(1), 0u);
857    MY_LOGV("  reserved = %u", br->getBits(2));
858
859    unsigned section_length = br->getBits(12);
860    LOGV("  section_length = %u", section_length);
861    CHECK_EQ(section_length & 0xc00, 0u);
862
863    MY_LOGV("  transport_stream_id = %u", br->getBits(16));
864    MY_LOGV("  reserved = %u", br->getBits(2));
865    MY_LOGV("  version_number = %u", br->getBits(5));
866    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
867    MY_LOGV("  section_number = %u", br->getBits(8));
868    MY_LOGV("  last_section_number = %u", br->getBits(8));
869
870    size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
871    CHECK_EQ((numProgramBytes % 4), 0u);
872
873    for (size_t i = 0; i < numProgramBytes / 4; ++i) {
874        unsigned program_number = br->getBits(16);
875        LOGV("    program_number = %u", program_number);
876
877        MY_LOGV("    reserved = %u", br->getBits(3));
878
879        if (program_number == 0) {
880            MY_LOGV("    network_PID = 0x%04x", br->getBits(13));
881        } else {
882            unsigned programMapPID = br->getBits(13);
883
884            LOGV("    program_map_PID = 0x%04x", programMapPID);
885
886            bool found = false;
887            for (size_t index = 0; index < mPrograms.size(); ++index) {
888                const sp<Program> &program = mPrograms.itemAt(index);
889
890                if (program->number() == program_number) {
891                    program->updateProgramMapPID(programMapPID);
892                    found = true;
893                    break;
894                }
895            }
896
897            if (!found) {
898                mPrograms.push(
899                        new Program(this, program_number, programMapPID));
900            }
901        }
902    }
903
904    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
905}
906
907status_t ATSParser::parsePID(
908        ABitReader *br, unsigned PID,
909        unsigned payload_unit_start_indicator) {
910    if (PID == 0) {
911        if (payload_unit_start_indicator) {
912            unsigned skip = br->getBits(8);
913            br->skipBits(skip * 8);
914        }
915        parseProgramAssociationTable(br);
916        return OK;
917    }
918
919    bool handled = false;
920    for (size_t i = 0; i < mPrograms.size(); ++i) {
921        status_t err;
922        if (mPrograms.editItemAt(i)->parsePID(
923                    PID, payload_unit_start_indicator, br, &err)) {
924            if (err != OK) {
925                return err;
926            }
927
928            handled = true;
929            break;
930        }
931    }
932
933    if (!handled) {
934        LOGV("PID 0x%04x not handled.", PID);
935    }
936
937    return OK;
938}
939
940void ATSParser::parseAdaptationField(ABitReader *br) {
941    unsigned adaptation_field_length = br->getBits(8);
942    if (adaptation_field_length > 0) {
943        br->skipBits(adaptation_field_length * 8);  // XXX
944    }
945}
946
947status_t ATSParser::parseTS(ABitReader *br) {
948    LOGV("---");
949
950    unsigned sync_byte = br->getBits(8);
951    CHECK_EQ(sync_byte, 0x47u);
952
953    MY_LOGV("transport_error_indicator = %u", br->getBits(1));
954
955    unsigned payload_unit_start_indicator = br->getBits(1);
956    LOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
957
958    MY_LOGV("transport_priority = %u", br->getBits(1));
959
960    unsigned PID = br->getBits(13);
961    LOGV("PID = 0x%04x", PID);
962
963    MY_LOGV("transport_scrambling_control = %u", br->getBits(2));
964
965    unsigned adaptation_field_control = br->getBits(2);
966    LOGV("adaptation_field_control = %u", adaptation_field_control);
967
968    unsigned continuity_counter = br->getBits(4);
969    LOGV("continuity_counter = %u", continuity_counter);
970
971    // LOGI("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
972
973    if (adaptation_field_control == 2 || adaptation_field_control == 3) {
974        parseAdaptationField(br);
975    }
976
977    if (adaptation_field_control == 1 || adaptation_field_control == 3) {
978        return parsePID(br, PID, payload_unit_start_indicator);
979    }
980
981    return OK;
982}
983
984sp<MediaSource> ATSParser::getSource(SourceType type) {
985    int which = -1;  // any
986
987    for (size_t i = 0; i < mPrograms.size(); ++i) {
988        const sp<Program> &program = mPrograms.editItemAt(i);
989
990        if (which >= 0 && (int)program->number() != which) {
991            continue;
992        }
993
994        sp<MediaSource> source = program->getSource(type);
995
996        if (source != NULL) {
997            return source;
998        }
999    }
1000
1001    return NULL;
1002}
1003
1004bool ATSParser::PTSTimeDeltaEstablished() {
1005    if (mPrograms.isEmpty()) {
1006        return false;
1007    }
1008
1009    return mPrograms.editItemAt(0)->PTSTimeDeltaEstablished();
1010}
1011
1012}  // namespace android
1013