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