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