ATSParser.cpp revision b4a7a2df4c28c3f32b5d877b54831d2cc5d78f81
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/stagefright/Utils.h>
36#include <media/IStreamSource.h>
37#include <utils/KeyedVector.h>
38
39#include <inttypes.h>
40
41namespace android {
42
43// I want the expression "y" evaluated even if verbose logging is off.
44#define MY_LOGV(x, y) \
45    do { unsigned tmp = y; ALOGV(x, tmp); } while (0)
46
47static const size_t kTSPacketSize = 188;
48
49struct ATSParser::Program : public RefBase {
50    Program(ATSParser *parser, unsigned programNumber, unsigned programMapPID);
51
52    bool parsePSISection(
53            unsigned pid, ABitReader *br, status_t *err);
54
55    bool parsePID(
56            unsigned pid, unsigned continuity_counter,
57            unsigned payload_unit_start_indicator,
58            ABitReader *br, status_t *err);
59
60    void signalDiscontinuity(
61            DiscontinuityType type, const sp<AMessage> &extra);
62
63    void signalEOS(status_t finalResult);
64
65    sp<MediaSource> getSource(SourceType type);
66
67    int64_t convertPTSToTimestamp(uint64_t PTS);
68
69    bool PTSTimeDeltaEstablished() const {
70        return mFirstPTSValid;
71    }
72
73    unsigned number() const { return mProgramNumber; }
74
75    void updateProgramMapPID(unsigned programMapPID) {
76        mProgramMapPID = programMapPID;
77    }
78
79    unsigned programMapPID() const {
80        return mProgramMapPID;
81    }
82
83    uint32_t parserFlags() const {
84        return mParser->mFlags;
85    }
86
87private:
88    ATSParser *mParser;
89    unsigned mProgramNumber;
90    unsigned mProgramMapPID;
91    KeyedVector<unsigned, sp<Stream> > mStreams;
92    bool mFirstPTSValid;
93    uint64_t mFirstPTS;
94
95    status_t parseProgramMap(ABitReader *br);
96
97    DISALLOW_EVIL_CONSTRUCTORS(Program);
98};
99
100struct ATSParser::Stream : public RefBase {
101    Stream(Program *program,
102           unsigned elementaryPID,
103           unsigned streamType,
104           unsigned PCR_PID);
105
106    unsigned type() const { return mStreamType; }
107    unsigned pid() const { return mElementaryPID; }
108    void setPID(unsigned pid) { mElementaryPID = pid; }
109
110    status_t parse(
111            unsigned continuity_counter,
112            unsigned payload_unit_start_indicator,
113            ABitReader *br);
114
115    void signalDiscontinuity(
116            DiscontinuityType type, const sp<AMessage> &extra);
117
118    void signalEOS(status_t finalResult);
119
120    sp<MediaSource> getSource(SourceType type);
121
122protected:
123    virtual ~Stream();
124
125private:
126    Program *mProgram;
127    unsigned mElementaryPID;
128    unsigned mStreamType;
129    unsigned mPCR_PID;
130    int32_t mExpectedContinuityCounter;
131
132    sp<ABuffer> mBuffer;
133    sp<AnotherPacketSource> mSource;
134    bool mPayloadStarted;
135
136    uint64_t mPrevPTS;
137
138    ElementaryStreamQueue *mQueue;
139
140    status_t flush();
141    status_t parsePES(ABitReader *br);
142
143    void onPayloadData(
144            unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
145            const uint8_t *data, size_t size);
146
147    void extractAACFrames(const sp<ABuffer> &buffer);
148
149    bool isAudio() const;
150    bool isVideo() const;
151
152    DISALLOW_EVIL_CONSTRUCTORS(Stream);
153};
154
155struct ATSParser::PSISection : public RefBase {
156    PSISection();
157
158    status_t append(const void *data, size_t size);
159    void clear();
160
161    bool isComplete() const;
162    bool isEmpty() const;
163
164    const uint8_t *data() const;
165    size_t size() const;
166
167protected:
168    virtual ~PSISection();
169
170private:
171    sp<ABuffer> mBuffer;
172
173    DISALLOW_EVIL_CONSTRUCTORS(PSISection);
174};
175
176////////////////////////////////////////////////////////////////////////////////
177
178ATSParser::Program::Program(
179        ATSParser *parser, unsigned programNumber, unsigned programMapPID)
180    : mParser(parser),
181      mProgramNumber(programNumber),
182      mProgramMapPID(programMapPID),
183      mFirstPTSValid(false),
184      mFirstPTS(0) {
185    ALOGV("new program number %u", programNumber);
186}
187
188bool ATSParser::Program::parsePSISection(
189        unsigned pid, ABitReader *br, status_t *err) {
190    *err = OK;
191
192    if (pid != mProgramMapPID) {
193        return false;
194    }
195
196    *err = parseProgramMap(br);
197
198    return true;
199}
200
201bool ATSParser::Program::parsePID(
202        unsigned pid, unsigned continuity_counter,
203        unsigned payload_unit_start_indicator,
204        ABitReader *br, status_t *err) {
205    *err = OK;
206
207    ssize_t index = mStreams.indexOfKey(pid);
208    if (index < 0) {
209        return false;
210    }
211
212    *err = mStreams.editValueAt(index)->parse(
213            continuity_counter, payload_unit_start_indicator, br);
214
215    return true;
216}
217
218void ATSParser::Program::signalDiscontinuity(
219        DiscontinuityType type, const sp<AMessage> &extra) {
220    int64_t mediaTimeUs;
221    if ((type & DISCONTINUITY_TIME)
222            && extra != NULL
223            && extra->findInt64(
224                IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
225        mFirstPTSValid = false;
226    }
227
228    for (size_t i = 0; i < mStreams.size(); ++i) {
229        mStreams.editValueAt(i)->signalDiscontinuity(type, extra);
230    }
231}
232
233void ATSParser::Program::signalEOS(status_t finalResult) {
234    for (size_t i = 0; i < mStreams.size(); ++i) {
235        mStreams.editValueAt(i)->signalEOS(finalResult);
236    }
237}
238
239struct StreamInfo {
240    unsigned mType;
241    unsigned mPID;
242};
243
244status_t ATSParser::Program::parseProgramMap(ABitReader *br) {
245    unsigned table_id = br->getBits(8);
246    ALOGV("  table_id = %u", table_id);
247    CHECK_EQ(table_id, 0x02u);
248
249    unsigned section_syntax_indicator = br->getBits(1);
250    ALOGV("  section_syntax_indicator = %u", section_syntax_indicator);
251    CHECK_EQ(section_syntax_indicator, 1u);
252
253    CHECK_EQ(br->getBits(1), 0u);
254    MY_LOGV("  reserved = %u", br->getBits(2));
255
256    unsigned section_length = br->getBits(12);
257    ALOGV("  section_length = %u", section_length);
258    CHECK_EQ(section_length & 0xc00, 0u);
259    CHECK_LE(section_length, 1021u);
260
261    MY_LOGV("  program_number = %u", br->getBits(16));
262    MY_LOGV("  reserved = %u", br->getBits(2));
263    MY_LOGV("  version_number = %u", br->getBits(5));
264    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
265    MY_LOGV("  section_number = %u", br->getBits(8));
266    MY_LOGV("  last_section_number = %u", br->getBits(8));
267    MY_LOGV("  reserved = %u", br->getBits(3));
268
269    unsigned PCR_PID = br->getBits(13);
270    ALOGV("  PCR_PID = 0x%04x", PCR_PID);
271
272    MY_LOGV("  reserved = %u", br->getBits(4));
273
274    unsigned program_info_length = br->getBits(12);
275    ALOGV("  program_info_length = %u", program_info_length);
276    CHECK_EQ(program_info_length & 0xc00, 0u);
277
278    br->skipBits(program_info_length * 8);  // skip descriptors
279
280    Vector<StreamInfo> infos;
281
282    // infoBytesRemaining is the number of bytes that make up the
283    // variable length section of ES_infos. It does not include the
284    // final CRC.
285    size_t infoBytesRemaining = section_length - 9 - program_info_length - 4;
286
287    while (infoBytesRemaining > 0) {
288        CHECK_GE(infoBytesRemaining, 5u);
289
290        unsigned streamType = br->getBits(8);
291        ALOGV("    stream_type = 0x%02x", streamType);
292
293        MY_LOGV("    reserved = %u", br->getBits(3));
294
295        unsigned elementaryPID = br->getBits(13);
296        ALOGV("    elementary_PID = 0x%04x", elementaryPID);
297
298        MY_LOGV("    reserved = %u", br->getBits(4));
299
300        unsigned ES_info_length = br->getBits(12);
301        ALOGV("    ES_info_length = %u", ES_info_length);
302        CHECK_EQ(ES_info_length & 0xc00, 0u);
303
304        CHECK_GE(infoBytesRemaining - 5, ES_info_length);
305
306#if 0
307        br->skipBits(ES_info_length * 8);  // skip descriptors
308#else
309        unsigned info_bytes_remaining = ES_info_length;
310        while (info_bytes_remaining >= 2) {
311            MY_LOGV("      tag = 0x%02x", br->getBits(8));
312
313            unsigned descLength = br->getBits(8);
314            ALOGV("      len = %u", descLength);
315
316            CHECK_GE(info_bytes_remaining, 2 + descLength);
317
318            br->skipBits(descLength * 8);
319
320            info_bytes_remaining -= descLength + 2;
321        }
322        CHECK_EQ(info_bytes_remaining, 0u);
323#endif
324
325        StreamInfo info;
326        info.mType = streamType;
327        info.mPID = elementaryPID;
328        infos.push(info);
329
330        infoBytesRemaining -= 5 + ES_info_length;
331    }
332
333    CHECK_EQ(infoBytesRemaining, 0u);
334    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
335
336    bool PIDsChanged = false;
337    for (size_t i = 0; i < infos.size(); ++i) {
338        StreamInfo &info = infos.editItemAt(i);
339
340        ssize_t index = mStreams.indexOfKey(info.mPID);
341
342        if (index >= 0 && mStreams.editValueAt(index)->type() != info.mType) {
343            ALOGI("uh oh. stream PIDs have changed.");
344            PIDsChanged = true;
345            break;
346        }
347    }
348
349    if (PIDsChanged) {
350#if 0
351        ALOGI("before:");
352        for (size_t i = 0; i < mStreams.size(); ++i) {
353            sp<Stream> stream = mStreams.editValueAt(i);
354
355            ALOGI("PID 0x%08x => type 0x%02x", stream->pid(), stream->type());
356        }
357
358        ALOGI("after:");
359        for (size_t i = 0; i < infos.size(); ++i) {
360            StreamInfo &info = infos.editItemAt(i);
361
362            ALOGI("PID 0x%08x => type 0x%02x", info.mPID, info.mType);
363        }
364#endif
365
366        // The only case we can recover from is if we have two streams
367        // and they switched PIDs.
368
369        bool success = false;
370
371        if (mStreams.size() == 2 && infos.size() == 2) {
372            const StreamInfo &info1 = infos.itemAt(0);
373            const StreamInfo &info2 = infos.itemAt(1);
374
375            sp<Stream> s1 = mStreams.editValueAt(0);
376            sp<Stream> s2 = mStreams.editValueAt(1);
377
378            bool caseA =
379                info1.mPID == s1->pid() && info1.mType == s2->type()
380                    && info2.mPID == s2->pid() && info2.mType == s1->type();
381
382            bool caseB =
383                info1.mPID == s2->pid() && info1.mType == s1->type()
384                    && info2.mPID == s1->pid() && info2.mType == s2->type();
385
386            if (caseA || caseB) {
387                unsigned pid1 = s1->pid();
388                unsigned pid2 = s2->pid();
389                s1->setPID(pid2);
390                s2->setPID(pid1);
391
392                mStreams.clear();
393                mStreams.add(s1->pid(), s1);
394                mStreams.add(s2->pid(), s2);
395
396                success = true;
397            }
398        }
399
400        if (!success) {
401            ALOGI("Stream PIDs changed and we cannot recover.");
402            return ERROR_MALFORMED;
403        }
404    }
405
406    for (size_t i = 0; i < infos.size(); ++i) {
407        StreamInfo &info = infos.editItemAt(i);
408
409        ssize_t index = mStreams.indexOfKey(info.mPID);
410
411        if (index < 0) {
412            sp<Stream> stream = new Stream(
413                    this, info.mPID, info.mType, PCR_PID);
414
415            mStreams.add(info.mPID, stream);
416        }
417    }
418
419    return OK;
420}
421
422sp<MediaSource> ATSParser::Program::getSource(SourceType type) {
423    size_t index = (type == AUDIO) ? 0 : 0;
424
425    for (size_t i = 0; i < mStreams.size(); ++i) {
426        sp<MediaSource> source = mStreams.editValueAt(i)->getSource(type);
427        if (source != NULL) {
428            if (index == 0) {
429                return source;
430            }
431            --index;
432        }
433    }
434
435    return NULL;
436}
437
438int64_t ATSParser::Program::convertPTSToTimestamp(uint64_t PTS) {
439    if (!(mParser->mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)) {
440        if (!mFirstPTSValid) {
441            mFirstPTSValid = true;
442            mFirstPTS = PTS;
443            PTS = 0;
444        } else if (PTS < mFirstPTS) {
445            PTS = 0;
446        } else {
447            PTS -= mFirstPTS;
448        }
449    }
450
451    int64_t timeUs = (PTS * 100) / 9;
452
453    if (mParser->mAbsoluteTimeAnchorUs >= 0ll) {
454        timeUs += mParser->mAbsoluteTimeAnchorUs;
455    }
456
457    if (mParser->mTimeOffsetValid) {
458        timeUs += mParser->mTimeOffsetUs;
459    }
460
461    return timeUs;
462}
463
464////////////////////////////////////////////////////////////////////////////////
465
466ATSParser::Stream::Stream(
467        Program *program,
468        unsigned elementaryPID,
469        unsigned streamType,
470        unsigned PCR_PID)
471    : mProgram(program),
472      mElementaryPID(elementaryPID),
473      mStreamType(streamType),
474      mPCR_PID(PCR_PID),
475      mExpectedContinuityCounter(-1),
476      mPayloadStarted(false),
477      mPrevPTS(0),
478      mQueue(NULL) {
479    switch (mStreamType) {
480        case STREAMTYPE_H264:
481            mQueue = new ElementaryStreamQueue(
482                    ElementaryStreamQueue::H264,
483                    (mProgram->parserFlags() & ALIGNED_VIDEO_DATA)
484                        ? ElementaryStreamQueue::kFlag_AlignedData : 0);
485            break;
486        case STREAMTYPE_MPEG2_AUDIO_ADTS:
487            mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::AAC);
488            break;
489        case STREAMTYPE_MPEG1_AUDIO:
490        case STREAMTYPE_MPEG2_AUDIO:
491            mQueue = new ElementaryStreamQueue(
492                    ElementaryStreamQueue::MPEG_AUDIO);
493            break;
494
495        case STREAMTYPE_MPEG1_VIDEO:
496        case STREAMTYPE_MPEG2_VIDEO:
497            mQueue = new ElementaryStreamQueue(
498                    ElementaryStreamQueue::MPEG_VIDEO);
499            break;
500
501        case STREAMTYPE_MPEG4_VIDEO:
502            mQueue = new ElementaryStreamQueue(
503                    ElementaryStreamQueue::MPEG4_VIDEO);
504            break;
505
506        case STREAMTYPE_PCM_AUDIO:
507            mQueue = new ElementaryStreamQueue(
508                    ElementaryStreamQueue::PCM_AUDIO);
509            break;
510
511        case STREAMTYPE_AC3:
512            mQueue = new ElementaryStreamQueue(
513                    ElementaryStreamQueue::AC3);
514            break;
515
516        default:
517            break;
518    }
519
520    ALOGV("new stream PID 0x%02x, type 0x%02x", elementaryPID, streamType);
521
522    if (mQueue != NULL) {
523        mBuffer = new ABuffer(192 * 1024);
524        mBuffer->setRange(0, 0);
525    }
526}
527
528ATSParser::Stream::~Stream() {
529    delete mQueue;
530    mQueue = NULL;
531}
532
533status_t ATSParser::Stream::parse(
534        unsigned continuity_counter,
535        unsigned payload_unit_start_indicator, ABitReader *br) {
536    if (mQueue == NULL) {
537        return OK;
538    }
539
540    if (mExpectedContinuityCounter >= 0
541            && (unsigned)mExpectedContinuityCounter != continuity_counter) {
542        ALOGI("discontinuity on stream pid 0x%04x", mElementaryPID);
543
544        mPayloadStarted = false;
545        mBuffer->setRange(0, 0);
546        mExpectedContinuityCounter = -1;
547
548#if 0
549        // Uncomment this if you'd rather see no corruption whatsoever on
550        // screen and suspend updates until we come across another IDR frame.
551
552        if (mStreamType == STREAMTYPE_H264) {
553            ALOGI("clearing video queue");
554            mQueue->clear(true /* clearFormat */);
555        }
556#endif
557
558        return OK;
559    }
560
561    mExpectedContinuityCounter = (continuity_counter + 1) & 0x0f;
562
563    if (payload_unit_start_indicator) {
564        if (mPayloadStarted) {
565            // Otherwise we run the danger of receiving the trailing bytes
566            // of a PES packet that we never saw the start of and assuming
567            // we have a a complete PES packet.
568
569            status_t err = flush();
570
571            if (err != OK) {
572                return err;
573            }
574        }
575
576        mPayloadStarted = true;
577    }
578
579    if (!mPayloadStarted) {
580        return OK;
581    }
582
583    size_t payloadSizeBits = br->numBitsLeft();
584    CHECK_EQ(payloadSizeBits % 8, 0u);
585
586    size_t neededSize = mBuffer->size() + payloadSizeBits / 8;
587    if (mBuffer->capacity() < neededSize) {
588        // Increment in multiples of 64K.
589        neededSize = (neededSize + 65535) & ~65535;
590
591        ALOGI("resizing buffer to %zu bytes", neededSize);
592
593        sp<ABuffer> newBuffer = new ABuffer(neededSize);
594        memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
595        newBuffer->setRange(0, mBuffer->size());
596        mBuffer = newBuffer;
597    }
598
599    memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
600    mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
601
602    return OK;
603}
604
605bool ATSParser::Stream::isVideo() const {
606    switch (mStreamType) {
607        case STREAMTYPE_H264:
608        case STREAMTYPE_MPEG1_VIDEO:
609        case STREAMTYPE_MPEG2_VIDEO:
610        case STREAMTYPE_MPEG4_VIDEO:
611            return true;
612
613        default:
614            return false;
615    }
616}
617
618bool ATSParser::Stream::isAudio() const {
619    switch (mStreamType) {
620        case STREAMTYPE_MPEG1_AUDIO:
621        case STREAMTYPE_MPEG2_AUDIO:
622        case STREAMTYPE_MPEG2_AUDIO_ADTS:
623        case STREAMTYPE_PCM_AUDIO:
624        case STREAMTYPE_AC3:
625            return true;
626
627        default:
628            return false;
629    }
630}
631
632void ATSParser::Stream::signalDiscontinuity(
633        DiscontinuityType type, const sp<AMessage> &extra) {
634    mExpectedContinuityCounter = -1;
635
636    if (mQueue == NULL) {
637        return;
638    }
639
640    mPayloadStarted = false;
641    mBuffer->setRange(0, 0);
642
643    bool clearFormat = false;
644    if (isAudio()) {
645        if (type & DISCONTINUITY_AUDIO_FORMAT) {
646            clearFormat = true;
647        }
648    } else {
649        if (type & DISCONTINUITY_VIDEO_FORMAT) {
650            clearFormat = true;
651        }
652    }
653
654    mQueue->clear(clearFormat);
655
656    if (type & DISCONTINUITY_TIME) {
657        uint64_t resumeAtPTS;
658        if (extra != NULL
659                && extra->findInt64(
660                    IStreamListener::kKeyResumeAtPTS,
661                    (int64_t *)&resumeAtPTS)) {
662            int64_t resumeAtMediaTimeUs =
663                mProgram->convertPTSToTimestamp(resumeAtPTS);
664
665            extra->setInt64("resume-at-mediatimeUs", resumeAtMediaTimeUs);
666        }
667    }
668
669    if (mSource != NULL) {
670        mSource->queueDiscontinuity(type, extra);
671    }
672}
673
674void ATSParser::Stream::signalEOS(status_t finalResult) {
675    if (mSource != NULL) {
676        mSource->signalEOS(finalResult);
677    }
678}
679
680status_t ATSParser::Stream::parsePES(ABitReader *br) {
681    unsigned packet_startcode_prefix = br->getBits(24);
682
683    ALOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
684
685    if (packet_startcode_prefix != 1) {
686        ALOGV("Supposedly payload_unit_start=1 unit does not start "
687             "with startcode.");
688
689        return ERROR_MALFORMED;
690    }
691
692    CHECK_EQ(packet_startcode_prefix, 0x000001u);
693
694    unsigned stream_id = br->getBits(8);
695    ALOGV("stream_id = 0x%02x", stream_id);
696
697    unsigned PES_packet_length = br->getBits(16);
698    ALOGV("PES_packet_length = %u", PES_packet_length);
699
700    if (stream_id != 0xbc  // program_stream_map
701            && stream_id != 0xbe  // padding_stream
702            && stream_id != 0xbf  // private_stream_2
703            && stream_id != 0xf0  // ECM
704            && stream_id != 0xf1  // EMM
705            && stream_id != 0xff  // program_stream_directory
706            && stream_id != 0xf2  // DSMCC
707            && stream_id != 0xf8) {  // H.222.1 type E
708        CHECK_EQ(br->getBits(2), 2u);
709
710        MY_LOGV("PES_scrambling_control = %u", br->getBits(2));
711        MY_LOGV("PES_priority = %u", br->getBits(1));
712        MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
713        MY_LOGV("copyright = %u", br->getBits(1));
714        MY_LOGV("original_or_copy = %u", br->getBits(1));
715
716        unsigned PTS_DTS_flags = br->getBits(2);
717        ALOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
718
719        unsigned ESCR_flag = br->getBits(1);
720        ALOGV("ESCR_flag = %u", ESCR_flag);
721
722        unsigned ES_rate_flag = br->getBits(1);
723        ALOGV("ES_rate_flag = %u", ES_rate_flag);
724
725        unsigned DSM_trick_mode_flag = br->getBits(1);
726        ALOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
727
728        unsigned additional_copy_info_flag = br->getBits(1);
729        ALOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
730
731        MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
732        MY_LOGV("PES_extension_flag = %u", br->getBits(1));
733
734        unsigned PES_header_data_length = br->getBits(8);
735        ALOGV("PES_header_data_length = %u", PES_header_data_length);
736
737        unsigned optional_bytes_remaining = PES_header_data_length;
738
739        uint64_t PTS = 0, DTS = 0;
740
741        if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
742            CHECK_GE(optional_bytes_remaining, 5u);
743
744            CHECK_EQ(br->getBits(4), PTS_DTS_flags);
745
746            PTS = ((uint64_t)br->getBits(3)) << 30;
747            CHECK_EQ(br->getBits(1), 1u);
748            PTS |= ((uint64_t)br->getBits(15)) << 15;
749            CHECK_EQ(br->getBits(1), 1u);
750            PTS |= br->getBits(15);
751            CHECK_EQ(br->getBits(1), 1u);
752
753            ALOGV("PTS = 0x%016" PRIx64 " (%.2f)", PTS, PTS / 90000.0);
754
755            optional_bytes_remaining -= 5;
756
757            if (PTS_DTS_flags == 3) {
758                CHECK_GE(optional_bytes_remaining, 5u);
759
760                CHECK_EQ(br->getBits(4), 1u);
761
762                DTS = ((uint64_t)br->getBits(3)) << 30;
763                CHECK_EQ(br->getBits(1), 1u);
764                DTS |= ((uint64_t)br->getBits(15)) << 15;
765                CHECK_EQ(br->getBits(1), 1u);
766                DTS |= br->getBits(15);
767                CHECK_EQ(br->getBits(1), 1u);
768
769                ALOGV("DTS = %" PRIu64, DTS);
770
771                optional_bytes_remaining -= 5;
772            }
773        }
774
775        if (ESCR_flag) {
776            CHECK_GE(optional_bytes_remaining, 6u);
777
778            br->getBits(2);
779
780            uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
781            CHECK_EQ(br->getBits(1), 1u);
782            ESCR |= ((uint64_t)br->getBits(15)) << 15;
783            CHECK_EQ(br->getBits(1), 1u);
784            ESCR |= br->getBits(15);
785            CHECK_EQ(br->getBits(1), 1u);
786
787            ALOGV("ESCR = %" PRIu64, ESCR);
788            MY_LOGV("ESCR_extension = %u", br->getBits(9));
789
790            CHECK_EQ(br->getBits(1), 1u);
791
792            optional_bytes_remaining -= 6;
793        }
794
795        if (ES_rate_flag) {
796            CHECK_GE(optional_bytes_remaining, 3u);
797
798            CHECK_EQ(br->getBits(1), 1u);
799            MY_LOGV("ES_rate = %u", br->getBits(22));
800            CHECK_EQ(br->getBits(1), 1u);
801
802            optional_bytes_remaining -= 3;
803        }
804
805        br->skipBits(optional_bytes_remaining * 8);
806
807        // ES data follows.
808
809        if (PES_packet_length != 0) {
810            CHECK_GE(PES_packet_length, PES_header_data_length + 3);
811
812            unsigned dataLength =
813                PES_packet_length - 3 - PES_header_data_length;
814
815            if (br->numBitsLeft() < dataLength * 8) {
816                ALOGE("PES packet does not carry enough data to contain "
817                     "payload. (numBitsLeft = %zu, required = %u)",
818                     br->numBitsLeft(), dataLength * 8);
819
820                return ERROR_MALFORMED;
821            }
822
823            CHECK_GE(br->numBitsLeft(), dataLength * 8);
824
825            onPayloadData(
826                    PTS_DTS_flags, PTS, DTS, br->data(), dataLength);
827
828            br->skipBits(dataLength * 8);
829        } else {
830            onPayloadData(
831                    PTS_DTS_flags, PTS, DTS,
832                    br->data(), br->numBitsLeft() / 8);
833
834            size_t payloadSizeBits = br->numBitsLeft();
835            CHECK_EQ(payloadSizeBits % 8, 0u);
836
837            ALOGV("There's %zu bytes of payload.", payloadSizeBits / 8);
838        }
839    } else if (stream_id == 0xbe) {  // padding_stream
840        CHECK_NE(PES_packet_length, 0u);
841        br->skipBits(PES_packet_length * 8);
842    } else {
843        CHECK_NE(PES_packet_length, 0u);
844        br->skipBits(PES_packet_length * 8);
845    }
846
847    return OK;
848}
849
850status_t ATSParser::Stream::flush() {
851    if (mBuffer->size() == 0) {
852        return OK;
853    }
854
855    ALOGV("flushing stream 0x%04x size = %zu", mElementaryPID, mBuffer->size());
856
857    ABitReader br(mBuffer->data(), mBuffer->size());
858
859    status_t err = parsePES(&br);
860
861    mBuffer->setRange(0, 0);
862
863    return err;
864}
865
866void ATSParser::Stream::onPayloadData(
867        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t /* DTS */,
868        const uint8_t *data, size_t size) {
869#if 0
870    ALOGI("payload streamType 0x%02x, PTS = 0x%016llx, dPTS = %lld",
871          mStreamType,
872          PTS,
873          (int64_t)PTS - mPrevPTS);
874    mPrevPTS = PTS;
875#endif
876
877    ALOGV("onPayloadData mStreamType=0x%02x", mStreamType);
878
879    int64_t timeUs = 0ll;  // no presentation timestamp available.
880    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
881        timeUs = mProgram->convertPTSToTimestamp(PTS);
882    }
883
884    status_t err = mQueue->appendData(data, size, timeUs);
885
886    if (err != OK) {
887        return;
888    }
889
890    sp<ABuffer> accessUnit;
891    while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
892        if (mSource == NULL) {
893            sp<MetaData> meta = mQueue->getFormat();
894
895            if (meta != NULL) {
896                ALOGV("Stream PID 0x%08x of type 0x%02x now has data.",
897                     mElementaryPID, mStreamType);
898
899                mSource = new AnotherPacketSource(meta);
900                mSource->queueAccessUnit(accessUnit);
901            }
902        } else if (mQueue->getFormat() != NULL) {
903            // After a discontinuity we invalidate the queue's format
904            // and won't enqueue any access units to the source until
905            // the queue has reestablished the new format.
906
907            if (mSource->getFormat() == NULL) {
908                mSource->setFormat(mQueue->getFormat());
909            }
910            mSource->queueAccessUnit(accessUnit);
911        }
912    }
913}
914
915sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
916    switch (type) {
917        case VIDEO:
918        {
919            if (isVideo()) {
920                return mSource;
921            }
922            break;
923        }
924
925        case AUDIO:
926        {
927            if (isAudio()) {
928                return mSource;
929            }
930            break;
931        }
932
933        default:
934            break;
935    }
936
937    return NULL;
938}
939
940////////////////////////////////////////////////////////////////////////////////
941
942ATSParser::ATSParser(uint32_t flags)
943    : mFlags(flags),
944      mAbsoluteTimeAnchorUs(-1ll),
945      mTimeOffsetValid(false),
946      mTimeOffsetUs(0ll),
947      mNumTSPacketsParsed(0),
948      mNumPCRs(0) {
949    mPSISections.add(0 /* PID */, new PSISection);
950}
951
952ATSParser::~ATSParser() {
953}
954
955status_t ATSParser::feedTSPacket(const void *data, size_t size) {
956    CHECK_EQ(size, kTSPacketSize);
957
958    ABitReader br((const uint8_t *)data, kTSPacketSize);
959    return parseTS(&br);
960}
961
962void ATSParser::signalDiscontinuity(
963        DiscontinuityType type, const sp<AMessage> &extra) {
964    int64_t mediaTimeUs;
965    if ((type & DISCONTINUITY_TIME)
966            && extra != NULL
967            && extra->findInt64(
968                IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
969        mAbsoluteTimeAnchorUs = mediaTimeUs;
970    } else if (type == DISCONTINUITY_ABSOLUTE_TIME) {
971        int64_t timeUs;
972        CHECK(extra->findInt64("timeUs", &timeUs));
973
974        CHECK(mPrograms.empty());
975        mAbsoluteTimeAnchorUs = timeUs;
976        return;
977    } else if (type == DISCONTINUITY_TIME_OFFSET) {
978        int64_t offset;
979        CHECK(extra->findInt64("offset", &offset));
980
981        mTimeOffsetValid = true;
982        mTimeOffsetUs = offset;
983        return;
984    }
985
986    for (size_t i = 0; i < mPrograms.size(); ++i) {
987        mPrograms.editItemAt(i)->signalDiscontinuity(type, extra);
988    }
989}
990
991void ATSParser::signalEOS(status_t finalResult) {
992    CHECK_NE(finalResult, (status_t)OK);
993
994    for (size_t i = 0; i < mPrograms.size(); ++i) {
995        mPrograms.editItemAt(i)->signalEOS(finalResult);
996    }
997}
998
999void ATSParser::parseProgramAssociationTable(ABitReader *br) {
1000    unsigned table_id = br->getBits(8);
1001    ALOGV("  table_id = %u", table_id);
1002    CHECK_EQ(table_id, 0x00u);
1003
1004    unsigned section_syntax_indictor = br->getBits(1);
1005    ALOGV("  section_syntax_indictor = %u", section_syntax_indictor);
1006    CHECK_EQ(section_syntax_indictor, 1u);
1007
1008    CHECK_EQ(br->getBits(1), 0u);
1009    MY_LOGV("  reserved = %u", br->getBits(2));
1010
1011    unsigned section_length = br->getBits(12);
1012    ALOGV("  section_length = %u", section_length);
1013    CHECK_EQ(section_length & 0xc00, 0u);
1014
1015    MY_LOGV("  transport_stream_id = %u", br->getBits(16));
1016    MY_LOGV("  reserved = %u", br->getBits(2));
1017    MY_LOGV("  version_number = %u", br->getBits(5));
1018    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
1019    MY_LOGV("  section_number = %u", br->getBits(8));
1020    MY_LOGV("  last_section_number = %u", br->getBits(8));
1021
1022    size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
1023    CHECK_EQ((numProgramBytes % 4), 0u);
1024
1025    for (size_t i = 0; i < numProgramBytes / 4; ++i) {
1026        unsigned program_number = br->getBits(16);
1027        ALOGV("    program_number = %u", program_number);
1028
1029        MY_LOGV("    reserved = %u", br->getBits(3));
1030
1031        if (program_number == 0) {
1032            MY_LOGV("    network_PID = 0x%04x", br->getBits(13));
1033        } else {
1034            unsigned programMapPID = br->getBits(13);
1035
1036            ALOGV("    program_map_PID = 0x%04x", programMapPID);
1037
1038            bool found = false;
1039            for (size_t index = 0; index < mPrograms.size(); ++index) {
1040                const sp<Program> &program = mPrograms.itemAt(index);
1041
1042                if (program->number() == program_number) {
1043                    program->updateProgramMapPID(programMapPID);
1044                    found = true;
1045                    break;
1046                }
1047            }
1048
1049            if (!found) {
1050                mPrograms.push(
1051                        new Program(this, program_number, programMapPID));
1052            }
1053
1054            if (mPSISections.indexOfKey(programMapPID) < 0) {
1055                mPSISections.add(programMapPID, new PSISection);
1056            }
1057        }
1058    }
1059
1060    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
1061}
1062
1063status_t ATSParser::parsePID(
1064        ABitReader *br, unsigned PID,
1065        unsigned continuity_counter,
1066        unsigned payload_unit_start_indicator) {
1067    ssize_t sectionIndex = mPSISections.indexOfKey(PID);
1068
1069    if (sectionIndex >= 0) {
1070        sp<PSISection> section = mPSISections.valueAt(sectionIndex);
1071
1072        if (payload_unit_start_indicator) {
1073            CHECK(section->isEmpty());
1074
1075            unsigned skip = br->getBits(8);
1076            br->skipBits(skip * 8);
1077        }
1078
1079        CHECK((br->numBitsLeft() % 8) == 0);
1080        status_t err = section->append(br->data(), br->numBitsLeft() / 8);
1081
1082        if (err != OK) {
1083            return err;
1084        }
1085
1086        if (!section->isComplete()) {
1087            return OK;
1088        }
1089
1090        ABitReader sectionBits(section->data(), section->size());
1091
1092        if (PID == 0) {
1093            parseProgramAssociationTable(&sectionBits);
1094        } else {
1095            bool handled = false;
1096            for (size_t i = 0; i < mPrograms.size(); ++i) {
1097                status_t err;
1098                if (!mPrograms.editItemAt(i)->parsePSISection(
1099                            PID, &sectionBits, &err)) {
1100                    continue;
1101                }
1102
1103                if (err != OK) {
1104                    return err;
1105                }
1106
1107                handled = true;
1108                break;
1109            }
1110
1111            if (!handled) {
1112                mPSISections.removeItem(PID);
1113                section.clear();
1114            }
1115        }
1116
1117        if (section != NULL) {
1118            section->clear();
1119        }
1120
1121        return OK;
1122    }
1123
1124    bool handled = false;
1125    for (size_t i = 0; i < mPrograms.size(); ++i) {
1126        status_t err;
1127        if (mPrograms.editItemAt(i)->parsePID(
1128                    PID, continuity_counter, payload_unit_start_indicator,
1129                    br, &err)) {
1130            if (err != OK) {
1131                return err;
1132            }
1133
1134            handled = true;
1135            break;
1136        }
1137    }
1138
1139    if (!handled) {
1140        ALOGV("PID 0x%04x not handled.", PID);
1141    }
1142
1143    return OK;
1144}
1145
1146void ATSParser::parseAdaptationField(ABitReader *br, unsigned PID) {
1147    unsigned adaptation_field_length = br->getBits(8);
1148
1149    if (adaptation_field_length > 0) {
1150        unsigned discontinuity_indicator = br->getBits(1);
1151
1152        if (discontinuity_indicator) {
1153            ALOGV("PID 0x%04x: discontinuity_indicator = 1 (!!!)", PID);
1154        }
1155
1156        br->skipBits(2);
1157        unsigned PCR_flag = br->getBits(1);
1158
1159        size_t numBitsRead = 4;
1160
1161        if (PCR_flag) {
1162            br->skipBits(4);
1163            uint64_t PCR_base = br->getBits(32);
1164            PCR_base = (PCR_base << 1) | br->getBits(1);
1165
1166            br->skipBits(6);
1167            unsigned PCR_ext = br->getBits(9);
1168
1169            // The number of bytes from the start of the current
1170            // MPEG2 transport stream packet up and including
1171            // the final byte of this PCR_ext field.
1172            size_t byteOffsetFromStartOfTSPacket =
1173                (188 - br->numBitsLeft() / 8);
1174
1175            uint64_t PCR = PCR_base * 300 + PCR_ext;
1176
1177            ALOGV("PID 0x%04x: PCR = 0x%016" PRIx64 " (%.2f)",
1178                  PID, PCR, PCR / 27E6);
1179
1180            // The number of bytes received by this parser up to and
1181            // including the final byte of this PCR_ext field.
1182            size_t byteOffsetFromStart =
1183                mNumTSPacketsParsed * 188 + byteOffsetFromStartOfTSPacket;
1184
1185            for (size_t i = 0; i < mPrograms.size(); ++i) {
1186                updatePCR(PID, PCR, byteOffsetFromStart);
1187            }
1188
1189            numBitsRead += 52;
1190        }
1191
1192        CHECK_GE(adaptation_field_length * 8, numBitsRead);
1193
1194        br->skipBits(adaptation_field_length * 8 - numBitsRead);
1195    }
1196}
1197
1198status_t ATSParser::parseTS(ABitReader *br) {
1199    ALOGV("---");
1200
1201    unsigned sync_byte = br->getBits(8);
1202    CHECK_EQ(sync_byte, 0x47u);
1203
1204    if (br->getBits(1)) {  // transport_error_indicator
1205        // silently ignore.
1206        return OK;
1207    }
1208
1209    unsigned payload_unit_start_indicator = br->getBits(1);
1210    ALOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
1211
1212    MY_LOGV("transport_priority = %u", br->getBits(1));
1213
1214    unsigned PID = br->getBits(13);
1215    ALOGV("PID = 0x%04x", PID);
1216
1217    MY_LOGV("transport_scrambling_control = %u", br->getBits(2));
1218
1219    unsigned adaptation_field_control = br->getBits(2);
1220    ALOGV("adaptation_field_control = %u", adaptation_field_control);
1221
1222    unsigned continuity_counter = br->getBits(4);
1223    ALOGV("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1224
1225    // ALOGI("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1226
1227    if (adaptation_field_control == 2 || adaptation_field_control == 3) {
1228        parseAdaptationField(br, PID);
1229    }
1230
1231    status_t err = OK;
1232
1233    if (adaptation_field_control == 1 || adaptation_field_control == 3) {
1234        err = parsePID(
1235                br, PID, continuity_counter, payload_unit_start_indicator);
1236    }
1237
1238    ++mNumTSPacketsParsed;
1239
1240    return err;
1241}
1242
1243sp<MediaSource> ATSParser::getSource(SourceType type) {
1244    int which = -1;  // any
1245
1246    for (size_t i = 0; i < mPrograms.size(); ++i) {
1247        const sp<Program> &program = mPrograms.editItemAt(i);
1248
1249        if (which >= 0 && (int)program->number() != which) {
1250            continue;
1251        }
1252
1253        sp<MediaSource> source = program->getSource(type);
1254
1255        if (source != NULL) {
1256            return source;
1257        }
1258    }
1259
1260    return NULL;
1261}
1262
1263bool ATSParser::PTSTimeDeltaEstablished() {
1264    if (mPrograms.isEmpty()) {
1265        return false;
1266    }
1267
1268    return mPrograms.editItemAt(0)->PTSTimeDeltaEstablished();
1269}
1270
1271void ATSParser::updatePCR(
1272        unsigned /* PID */, uint64_t PCR, size_t byteOffsetFromStart) {
1273    ALOGV("PCR 0x%016" PRIx64 " @ %zu", PCR, byteOffsetFromStart);
1274
1275    if (mNumPCRs == 2) {
1276        mPCR[0] = mPCR[1];
1277        mPCRBytes[0] = mPCRBytes[1];
1278        mSystemTimeUs[0] = mSystemTimeUs[1];
1279        mNumPCRs = 1;
1280    }
1281
1282    mPCR[mNumPCRs] = PCR;
1283    mPCRBytes[mNumPCRs] = byteOffsetFromStart;
1284    mSystemTimeUs[mNumPCRs] = ALooper::GetNowUs();
1285
1286    ++mNumPCRs;
1287
1288    if (mNumPCRs == 2) {
1289        double transportRate =
1290            (mPCRBytes[1] - mPCRBytes[0]) * 27E6 / (mPCR[1] - mPCR[0]);
1291
1292        ALOGV("transportRate = %.2f bytes/sec", transportRate);
1293    }
1294}
1295
1296////////////////////////////////////////////////////////////////////////////////
1297
1298ATSParser::PSISection::PSISection() {
1299}
1300
1301ATSParser::PSISection::~PSISection() {
1302}
1303
1304status_t ATSParser::PSISection::append(const void *data, size_t size) {
1305    if (mBuffer == NULL || mBuffer->size() + size > mBuffer->capacity()) {
1306        size_t newCapacity =
1307            (mBuffer == NULL) ? size : mBuffer->capacity() + size;
1308
1309        newCapacity = (newCapacity + 1023) & ~1023;
1310
1311        sp<ABuffer> newBuffer = new ABuffer(newCapacity);
1312
1313        if (mBuffer != NULL) {
1314            memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
1315            newBuffer->setRange(0, mBuffer->size());
1316        } else {
1317            newBuffer->setRange(0, 0);
1318        }
1319
1320        mBuffer = newBuffer;
1321    }
1322
1323    memcpy(mBuffer->data() + mBuffer->size(), data, size);
1324    mBuffer->setRange(0, mBuffer->size() + size);
1325
1326    return OK;
1327}
1328
1329void ATSParser::PSISection::clear() {
1330    if (mBuffer != NULL) {
1331        mBuffer->setRange(0, 0);
1332    }
1333}
1334
1335bool ATSParser::PSISection::isComplete() const {
1336    if (mBuffer == NULL || mBuffer->size() < 3) {
1337        return false;
1338    }
1339
1340    unsigned sectionLength = U16_AT(mBuffer->data() + 1) & 0xfff;
1341    return mBuffer->size() >= sectionLength + 3;
1342}
1343
1344bool ATSParser::PSISection::isEmpty() const {
1345    return mBuffer == NULL || mBuffer->size() == 0;
1346}
1347
1348const uint8_t *ATSParser::PSISection::data() const {
1349    return mBuffer == NULL ? NULL : mBuffer->data();
1350}
1351
1352size_t ATSParser::PSISection::size() const {
1353    return mBuffer == NULL ? 0 : mBuffer->size();
1354}
1355
1356}  // namespace android
1357