ATSParser.cpp revision e314c678ea0b53dd9296ba6b5c3272c702433b47
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#include <utils/Vector.h>
39
40#include <inttypes.h>
41
42namespace android {
43
44// I want the expression "y" evaluated even if verbose logging is off.
45#define MY_LOGV(x, y) \
46    do { unsigned tmp = y; ALOGV(x, tmp); } while (0)
47
48static const size_t kTSPacketSize = 188;
49
50struct ATSParser::Program : public RefBase {
51    Program(ATSParser *parser, unsigned programNumber, unsigned programMapPID,
52            int64_t lastRecoveredPTS);
53
54    bool parsePSISection(
55            unsigned pid, ABitReader *br, status_t *err);
56
57    bool parsePID(
58            unsigned pid, unsigned continuity_counter,
59            unsigned payload_unit_start_indicator,
60            ABitReader *br, status_t *err);
61
62    void signalDiscontinuity(
63            DiscontinuityType type, const sp<AMessage> &extra);
64
65    void signalEOS(status_t finalResult);
66
67    sp<MediaSource> getSource(SourceType type);
68    bool hasSource(SourceType type) const;
69
70    int64_t convertPTSToTimestamp(uint64_t PTS);
71
72    bool PTSTimeDeltaEstablished() const {
73        return mFirstPTSValid;
74    }
75
76    unsigned number() const { return mProgramNumber; }
77
78    void updateProgramMapPID(unsigned programMapPID) {
79        mProgramMapPID = programMapPID;
80    }
81
82    unsigned programMapPID() const {
83        return mProgramMapPID;
84    }
85
86    uint32_t parserFlags() const {
87        return mParser->mFlags;
88    }
89
90private:
91    struct StreamInfo {
92        unsigned mType;
93        unsigned mPID;
94    };
95
96    ATSParser *mParser;
97    unsigned mProgramNumber;
98    unsigned mProgramMapPID;
99    KeyedVector<unsigned, sp<Stream> > mStreams;
100    bool mFirstPTSValid;
101    uint64_t mFirstPTS;
102    int64_t mLastRecoveredPTS;
103
104    status_t parseProgramMap(ABitReader *br);
105    int64_t recoverPTS(uint64_t PTS_33bit);
106    bool switchPIDs(const Vector<StreamInfo> &infos);
107
108    DISALLOW_EVIL_CONSTRUCTORS(Program);
109};
110
111struct ATSParser::Stream : public RefBase {
112    Stream(Program *program,
113           unsigned elementaryPID,
114           unsigned streamType,
115           unsigned PCR_PID);
116
117    unsigned type() const { return mStreamType; }
118    unsigned pid() const { return mElementaryPID; }
119    void setPID(unsigned pid) { mElementaryPID = pid; }
120
121    status_t parse(
122            unsigned continuity_counter,
123            unsigned payload_unit_start_indicator,
124            ABitReader *br);
125
126    void signalDiscontinuity(
127            DiscontinuityType type, const sp<AMessage> &extra);
128
129    void signalEOS(status_t finalResult);
130
131    sp<MediaSource> getSource(SourceType type);
132
133    bool isAudio() const;
134    bool isVideo() const;
135    bool isMeta() const;
136
137protected:
138    virtual ~Stream();
139
140private:
141    Program *mProgram;
142    unsigned mElementaryPID;
143    unsigned mStreamType;
144    unsigned mPCR_PID;
145    int32_t mExpectedContinuityCounter;
146
147    sp<ABuffer> mBuffer;
148    sp<AnotherPacketSource> mSource;
149    bool mPayloadStarted;
150    bool mEOSReached;
151
152    uint64_t mPrevPTS;
153
154    ElementaryStreamQueue *mQueue;
155
156    status_t flush();
157    status_t parsePES(ABitReader *br);
158
159    void onPayloadData(
160            unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
161            const uint8_t *data, size_t size);
162
163    void extractAACFrames(const sp<ABuffer> &buffer);
164
165    DISALLOW_EVIL_CONSTRUCTORS(Stream);
166};
167
168struct ATSParser::PSISection : public RefBase {
169    PSISection();
170
171    status_t append(const void *data, size_t size);
172    void setSkipBytes(uint8_t skip);
173    void clear();
174
175    bool isComplete() const;
176    bool isEmpty() const;
177    bool isCRCOkay() const;
178
179    const uint8_t *data() const;
180    size_t size() const;
181
182protected:
183    virtual ~PSISection();
184
185private:
186    sp<ABuffer> mBuffer;
187    uint8_t mSkipBytes;
188    static uint32_t CRC_TABLE[];
189
190    DISALLOW_EVIL_CONSTRUCTORS(PSISection);
191};
192
193////////////////////////////////////////////////////////////////////////////////
194
195ATSParser::Program::Program(
196        ATSParser *parser, unsigned programNumber, unsigned programMapPID,
197        int64_t lastRecoveredPTS)
198    : mParser(parser),
199      mProgramNumber(programNumber),
200      mProgramMapPID(programMapPID),
201      mFirstPTSValid(false),
202      mFirstPTS(0),
203      mLastRecoveredPTS(lastRecoveredPTS) {
204    ALOGV("new program number %u", programNumber);
205}
206
207bool ATSParser::Program::parsePSISection(
208        unsigned pid, ABitReader *br, status_t *err) {
209    *err = OK;
210
211    if (pid != mProgramMapPID) {
212        return false;
213    }
214
215    *err = parseProgramMap(br);
216
217    return true;
218}
219
220bool ATSParser::Program::parsePID(
221        unsigned pid, unsigned continuity_counter,
222        unsigned payload_unit_start_indicator,
223        ABitReader *br, status_t *err) {
224    *err = OK;
225
226    ssize_t index = mStreams.indexOfKey(pid);
227    if (index < 0) {
228        return false;
229    }
230
231    *err = mStreams.editValueAt(index)->parse(
232            continuity_counter, payload_unit_start_indicator, br);
233
234    return true;
235}
236
237void ATSParser::Program::signalDiscontinuity(
238        DiscontinuityType type, const sp<AMessage> &extra) {
239    int64_t mediaTimeUs;
240    if ((type & DISCONTINUITY_TIME)
241            && extra != NULL
242            && extra->findInt64(
243                IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
244        mFirstPTSValid = false;
245    }
246
247    for (size_t i = 0; i < mStreams.size(); ++i) {
248        mStreams.editValueAt(i)->signalDiscontinuity(type, extra);
249    }
250}
251
252void ATSParser::Program::signalEOS(status_t finalResult) {
253    for (size_t i = 0; i < mStreams.size(); ++i) {
254        mStreams.editValueAt(i)->signalEOS(finalResult);
255    }
256}
257
258bool ATSParser::Program::switchPIDs(const Vector<StreamInfo> &infos) {
259    bool success = false;
260
261    if (mStreams.size() == infos.size()) {
262        // build type->PIDs map for old and new mapping
263        size_t i;
264        KeyedVector<int32_t, Vector<int32_t> > oldType2PIDs, newType2PIDs;
265        for (i = 0; i < mStreams.size(); ++i) {
266            ssize_t index = oldType2PIDs.indexOfKey(mStreams[i]->type());
267            if (index < 0) {
268                oldType2PIDs.add(mStreams[i]->type(), Vector<int32_t>());
269            }
270            oldType2PIDs.editValueFor(mStreams[i]->type()).push_back(mStreams[i]->pid());
271        }
272        for (i = 0; i < infos.size(); ++i) {
273            ssize_t index = newType2PIDs.indexOfKey(infos[i].mType);
274            if (index < 0) {
275                newType2PIDs.add(infos[i].mType, Vector<int32_t>());
276            }
277            newType2PIDs.editValueFor(infos[i].mType).push_back(infos[i].mPID);
278        }
279
280        // we can recover if the number of streams for each type hasn't changed
281        if (oldType2PIDs.size() == newType2PIDs.size()) {
282            success = true;
283            for (i = 0; i < oldType2PIDs.size(); ++i) {
284                // KeyedVector is sorted, we just compare key and size of each index
285                if (oldType2PIDs.keyAt(i) != newType2PIDs.keyAt(i)
286                        || oldType2PIDs[i].size() != newType2PIDs[i].size()) {
287                     success = false;
288                     break;
289                }
290            }
291        }
292
293        if (success) {
294            // save current streams to temp
295            KeyedVector<int32_t, sp<Stream> > temp;
296            for (i = 0; i < mStreams.size(); ++i) {
297                 temp.add(mStreams.keyAt(i), mStreams.editValueAt(i));
298            }
299
300            mStreams.clear();
301            for (i = 0; i < temp.size(); ++i) {
302                // The two checks below shouldn't happen,
303                // we already checked above the stream count matches
304                ssize_t index = newType2PIDs.indexOfKey(temp[i]->type());
305                if (index < 0) {
306                    return false;
307                }
308                Vector<int32_t> &newPIDs = newType2PIDs.editValueAt(index);
309                if (newPIDs.isEmpty()) {
310                    return false;
311                }
312
313                // get the next PID for temp[i]->type() in the new PID map
314                Vector<int32_t>::iterator it = newPIDs.begin();
315
316                // change the PID of the stream, and add it back
317                temp.editValueAt(i)->setPID(*it);
318                mStreams.add(temp[i]->pid(), temp.editValueAt(i));
319
320                // removed the used PID
321                newPIDs.erase(it);
322            }
323        }
324    }
325    return success;
326}
327
328status_t ATSParser::Program::parseProgramMap(ABitReader *br) {
329    unsigned table_id = br->getBits(8);
330    ALOGV("  table_id = %u", table_id);
331    if (table_id != 0x02u) {
332        ALOGE("PMT data error!");
333        return ERROR_MALFORMED;
334    }
335    unsigned section_syntax_indicator = br->getBits(1);
336    ALOGV("  section_syntax_indicator = %u", section_syntax_indicator);
337    if (section_syntax_indicator != 1u) {
338        ALOGE("PMT data error!");
339        return ERROR_MALFORMED;
340    }
341
342    br->skipBits(1);  // '0'
343    MY_LOGV("  reserved = %u", br->getBits(2));
344
345    unsigned section_length = br->getBits(12);
346    ALOGV("  section_length = %u", section_length);
347
348    MY_LOGV("  program_number = %u", br->getBits(16));
349    MY_LOGV("  reserved = %u", br->getBits(2));
350    MY_LOGV("  version_number = %u", br->getBits(5));
351    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
352    MY_LOGV("  section_number = %u", br->getBits(8));
353    MY_LOGV("  last_section_number = %u", br->getBits(8));
354    MY_LOGV("  reserved = %u", br->getBits(3));
355
356    unsigned PCR_PID = br->getBits(13);
357    ALOGV("  PCR_PID = 0x%04x", PCR_PID);
358
359    MY_LOGV("  reserved = %u", br->getBits(4));
360
361    unsigned program_info_length = br->getBits(12);
362    ALOGV("  program_info_length = %u", program_info_length);
363
364    br->skipBits(program_info_length * 8);  // skip descriptors
365
366    Vector<StreamInfo> infos;
367
368    // infoBytesRemaining is the number of bytes that make up the
369    // variable length section of ES_infos. It does not include the
370    // final CRC.
371    size_t infoBytesRemaining = section_length - 9 - program_info_length - 4;
372
373    while (infoBytesRemaining >= 5) {
374
375        unsigned streamType = br->getBits(8);
376        ALOGV("    stream_type = 0x%02x", streamType);
377
378        MY_LOGV("    reserved = %u", br->getBits(3));
379
380        unsigned elementaryPID = br->getBits(13);
381        ALOGV("    elementary_PID = 0x%04x", elementaryPID);
382
383        MY_LOGV("    reserved = %u", br->getBits(4));
384
385        unsigned ES_info_length = br->getBits(12);
386        ALOGV("    ES_info_length = %u", ES_info_length);
387
388#if 0
389        br->skipBits(ES_info_length * 8);  // skip descriptors
390#else
391        unsigned info_bytes_remaining = ES_info_length;
392        while (info_bytes_remaining >= 2) {
393            MY_LOGV("      tag = 0x%02x", br->getBits(8));
394
395            unsigned descLength = br->getBits(8);
396            ALOGV("      len = %u", descLength);
397
398            if (info_bytes_remaining < descLength) {
399                return ERROR_MALFORMED;
400            }
401            br->skipBits(descLength * 8);
402
403            info_bytes_remaining -= descLength + 2;
404        }
405#endif
406
407        StreamInfo info;
408        info.mType = streamType;
409        info.mPID = elementaryPID;
410        infos.push(info);
411
412        infoBytesRemaining -= 5 + ES_info_length;
413    }
414
415    if (infoBytesRemaining != 0) {
416        ALOGW("Section data remains unconsumed");
417    }
418    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
419
420    bool PIDsChanged = false;
421    for (size_t i = 0; i < infos.size(); ++i) {
422        StreamInfo &info = infos.editItemAt(i);
423
424        ssize_t index = mStreams.indexOfKey(info.mPID);
425
426        if (index >= 0 && mStreams.editValueAt(index)->type() != info.mType) {
427            ALOGI("uh oh. stream PIDs have changed.");
428            PIDsChanged = true;
429            break;
430        }
431    }
432
433    if (PIDsChanged) {
434#if 0
435        ALOGI("before:");
436        for (size_t i = 0; i < mStreams.size(); ++i) {
437            sp<Stream> stream = mStreams.editValueAt(i);
438
439            ALOGI("PID 0x%08x => type 0x%02x", stream->pid(), stream->type());
440        }
441
442        ALOGI("after:");
443        for (size_t i = 0; i < infos.size(); ++i) {
444            StreamInfo &info = infos.editItemAt(i);
445
446            ALOGI("PID 0x%08x => type 0x%02x", info.mPID, info.mType);
447        }
448#endif
449
450        // we can recover if number of streams for each type remain the same
451        bool success = switchPIDs(infos);
452
453        if (!success) {
454            ALOGI("Stream PIDs changed and we cannot recover.");
455            return ERROR_MALFORMED;
456        }
457    }
458
459    for (size_t i = 0; i < infos.size(); ++i) {
460        StreamInfo &info = infos.editItemAt(i);
461
462        ssize_t index = mStreams.indexOfKey(info.mPID);
463
464        if (index < 0) {
465            sp<Stream> stream = new Stream(
466                    this, info.mPID, info.mType, PCR_PID);
467
468            mStreams.add(info.mPID, stream);
469        }
470    }
471
472    return OK;
473}
474
475int64_t ATSParser::Program::recoverPTS(uint64_t PTS_33bit) {
476    // We only have the lower 33-bit of the PTS. It could overflow within a
477    // reasonable amount of time. To handle the wrap-around, use fancy math
478    // to get an extended PTS that is within [-0xffffffff, 0xffffffff]
479    // of the latest recovered PTS.
480    if (mLastRecoveredPTS < 0ll) {
481        // Use the original 33bit number for 1st frame, the reason is that
482        // if 1st frame wraps to negative that's far away from 0, we could
483        // never start. Only start wrapping around from 2nd frame.
484        mLastRecoveredPTS = static_cast<int64_t>(PTS_33bit);
485    } else {
486        mLastRecoveredPTS = static_cast<int64_t>(
487                ((mLastRecoveredPTS - PTS_33bit + 0x100000000ll)
488                & 0xfffffffe00000000ull) | PTS_33bit);
489        // We start from 0, but recovered PTS could be slightly below 0.
490        // Clamp it to 0 as rest of the pipeline doesn't take negative pts.
491        // (eg. video is read first and starts at 0, but audio starts at 0xfffffff0)
492        if (mLastRecoveredPTS < 0ll) {
493            ALOGI("Clamping negative recovered PTS (%" PRId64 ") to 0", mLastRecoveredPTS);
494            mLastRecoveredPTS = 0ll;
495        }
496    }
497
498    return mLastRecoveredPTS;
499}
500
501sp<MediaSource> ATSParser::Program::getSource(SourceType type) {
502    size_t index = (type == AUDIO) ? 0 : 0;
503
504    for (size_t i = 0; i < mStreams.size(); ++i) {
505        sp<MediaSource> source = mStreams.editValueAt(i)->getSource(type);
506        if (source != NULL) {
507            if (index == 0) {
508                return source;
509            }
510            --index;
511        }
512    }
513
514    return NULL;
515}
516
517bool ATSParser::Program::hasSource(SourceType type) const {
518    for (size_t i = 0; i < mStreams.size(); ++i) {
519        const sp<Stream> &stream = mStreams.valueAt(i);
520        if (type == AUDIO && stream->isAudio()) {
521            return true;
522        } else if (type == VIDEO && stream->isVideo()) {
523            return true;
524        }
525    }
526
527    return false;
528}
529
530int64_t ATSParser::Program::convertPTSToTimestamp(uint64_t PTS) {
531    PTS = recoverPTS(PTS);
532
533    if (!(mParser->mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)) {
534        if (!mFirstPTSValid) {
535            mFirstPTSValid = true;
536            mFirstPTS = PTS;
537            PTS = 0;
538        } else if (PTS < mFirstPTS) {
539            PTS = 0;
540        } else {
541            PTS -= mFirstPTS;
542        }
543    }
544
545    int64_t timeUs = (PTS * 100) / 9;
546
547    if (mParser->mAbsoluteTimeAnchorUs >= 0ll) {
548        timeUs += mParser->mAbsoluteTimeAnchorUs;
549    }
550
551    if (mParser->mTimeOffsetValid) {
552        timeUs += mParser->mTimeOffsetUs;
553    }
554
555    return timeUs;
556}
557
558////////////////////////////////////////////////////////////////////////////////
559
560ATSParser::Stream::Stream(
561        Program *program,
562        unsigned elementaryPID,
563        unsigned streamType,
564        unsigned PCR_PID)
565    : mProgram(program),
566      mElementaryPID(elementaryPID),
567      mStreamType(streamType),
568      mPCR_PID(PCR_PID),
569      mExpectedContinuityCounter(-1),
570      mPayloadStarted(false),
571      mEOSReached(false),
572      mPrevPTS(0),
573      mQueue(NULL) {
574    switch (mStreamType) {
575        case STREAMTYPE_H264:
576            mQueue = new ElementaryStreamQueue(
577                    ElementaryStreamQueue::H264,
578                    (mProgram->parserFlags() & ALIGNED_VIDEO_DATA)
579                        ? ElementaryStreamQueue::kFlag_AlignedData : 0);
580            break;
581        case STREAMTYPE_MPEG2_AUDIO_ADTS:
582            mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::AAC);
583            break;
584        case STREAMTYPE_MPEG1_AUDIO:
585        case STREAMTYPE_MPEG2_AUDIO:
586            mQueue = new ElementaryStreamQueue(
587                    ElementaryStreamQueue::MPEG_AUDIO);
588            break;
589
590        case STREAMTYPE_MPEG1_VIDEO:
591        case STREAMTYPE_MPEG2_VIDEO:
592            mQueue = new ElementaryStreamQueue(
593                    ElementaryStreamQueue::MPEG_VIDEO);
594            break;
595
596        case STREAMTYPE_MPEG4_VIDEO:
597            mQueue = new ElementaryStreamQueue(
598                    ElementaryStreamQueue::MPEG4_VIDEO);
599            break;
600
601        case STREAMTYPE_LPCM_AC3:
602        case STREAMTYPE_AC3:
603            mQueue = new ElementaryStreamQueue(
604                    ElementaryStreamQueue::AC3);
605            break;
606
607        case STREAMTYPE_METADATA:
608            mQueue = new ElementaryStreamQueue(
609                    ElementaryStreamQueue::METADATA);
610            break;
611
612        default:
613            break;
614    }
615
616    ALOGV("new stream PID 0x%02x, type 0x%02x", elementaryPID, streamType);
617
618    if (mQueue != NULL) {
619        mBuffer = new ABuffer(192 * 1024);
620        mBuffer->setRange(0, 0);
621    }
622}
623
624ATSParser::Stream::~Stream() {
625    delete mQueue;
626    mQueue = NULL;
627}
628
629status_t ATSParser::Stream::parse(
630        unsigned continuity_counter,
631        unsigned payload_unit_start_indicator, ABitReader *br) {
632    if (mQueue == NULL) {
633        return OK;
634    }
635
636    if (mExpectedContinuityCounter >= 0
637            && (unsigned)mExpectedContinuityCounter != continuity_counter) {
638        ALOGI("discontinuity on stream pid 0x%04x", mElementaryPID);
639
640        mPayloadStarted = false;
641        mBuffer->setRange(0, 0);
642        mExpectedContinuityCounter = -1;
643
644#if 0
645        // Uncomment this if you'd rather see no corruption whatsoever on
646        // screen and suspend updates until we come across another IDR frame.
647
648        if (mStreamType == STREAMTYPE_H264) {
649            ALOGI("clearing video queue");
650            mQueue->clear(true /* clearFormat */);
651        }
652#endif
653
654        if (!payload_unit_start_indicator) {
655            return OK;
656        }
657    }
658
659    mExpectedContinuityCounter = (continuity_counter + 1) & 0x0f;
660
661    if (payload_unit_start_indicator) {
662        if (mPayloadStarted) {
663            // Otherwise we run the danger of receiving the trailing bytes
664            // of a PES packet that we never saw the start of and assuming
665            // we have a a complete PES packet.
666
667            status_t err = flush();
668
669            if (err != OK) {
670                return err;
671            }
672        }
673
674        mPayloadStarted = true;
675    }
676
677    if (!mPayloadStarted) {
678        return OK;
679    }
680
681    size_t payloadSizeBits = br->numBitsLeft();
682    if (payloadSizeBits % 8 != 0u) {
683        ALOGE("Wrong value");
684        return BAD_VALUE;
685    }
686
687    size_t neededSize = mBuffer->size() + payloadSizeBits / 8;
688    if (mBuffer->capacity() < neededSize) {
689        // Increment in multiples of 64K.
690        neededSize = (neededSize + 65535) & ~65535;
691
692        ALOGI("resizing buffer to %zu bytes", neededSize);
693
694        sp<ABuffer> newBuffer = new ABuffer(neededSize);
695        memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
696        newBuffer->setRange(0, mBuffer->size());
697        mBuffer = newBuffer;
698    }
699
700    memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
701    mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
702
703    return OK;
704}
705
706bool ATSParser::Stream::isVideo() const {
707    switch (mStreamType) {
708        case STREAMTYPE_H264:
709        case STREAMTYPE_MPEG1_VIDEO:
710        case STREAMTYPE_MPEG2_VIDEO:
711        case STREAMTYPE_MPEG4_VIDEO:
712            return true;
713
714        default:
715            return false;
716    }
717}
718
719bool ATSParser::Stream::isAudio() const {
720    switch (mStreamType) {
721        case STREAMTYPE_MPEG1_AUDIO:
722        case STREAMTYPE_MPEG2_AUDIO:
723        case STREAMTYPE_MPEG2_AUDIO_ADTS:
724        case STREAMTYPE_LPCM_AC3:
725        case STREAMTYPE_AC3:
726            return true;
727
728        default:
729            return false;
730    }
731}
732
733bool ATSParser::Stream::isMeta() const {
734    if (mStreamType == STREAMTYPE_METADATA) {
735        return true;
736    }
737    return false;
738}
739
740void ATSParser::Stream::signalDiscontinuity(
741        DiscontinuityType type, const sp<AMessage> &extra) {
742    mExpectedContinuityCounter = -1;
743
744    if (mQueue == NULL) {
745        return;
746    }
747
748    mPayloadStarted = false;
749    mBuffer->setRange(0, 0);
750
751    bool clearFormat = false;
752    if (isAudio()) {
753        if (type & DISCONTINUITY_AUDIO_FORMAT) {
754            clearFormat = true;
755        }
756    } else {
757        if (type & DISCONTINUITY_VIDEO_FORMAT) {
758            clearFormat = true;
759        }
760    }
761
762    mQueue->clear(clearFormat);
763
764    if (type & DISCONTINUITY_TIME) {
765        uint64_t resumeAtPTS;
766        if (extra != NULL
767                && extra->findInt64(
768                    IStreamListener::kKeyResumeAtPTS,
769                    (int64_t *)&resumeAtPTS)) {
770            int64_t resumeAtMediaTimeUs =
771                mProgram->convertPTSToTimestamp(resumeAtPTS);
772
773            extra->setInt64("resume-at-mediaTimeUs", resumeAtMediaTimeUs);
774        }
775    }
776
777    if (mSource != NULL) {
778        mSource->queueDiscontinuity(type, extra, true);
779    }
780}
781
782void ATSParser::Stream::signalEOS(status_t finalResult) {
783    if (mSource != NULL) {
784        mSource->signalEOS(finalResult);
785    }
786    mEOSReached = true;
787    flush();
788}
789
790status_t ATSParser::Stream::parsePES(ABitReader *br) {
791    unsigned packet_startcode_prefix = br->getBits(24);
792
793    ALOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
794
795    if (packet_startcode_prefix != 1) {
796        ALOGV("Supposedly payload_unit_start=1 unit does not start "
797             "with startcode.");
798
799        return ERROR_MALFORMED;
800    }
801
802    unsigned stream_id = br->getBits(8);
803    ALOGV("stream_id = 0x%02x", stream_id);
804
805    unsigned PES_packet_length = br->getBits(16);
806    ALOGV("PES_packet_length = %u", PES_packet_length);
807
808    if (stream_id != 0xbc  // program_stream_map
809            && stream_id != 0xbe  // padding_stream
810            && stream_id != 0xbf  // private_stream_2
811            && stream_id != 0xf0  // ECM
812            && stream_id != 0xf1  // EMM
813            && stream_id != 0xff  // program_stream_directory
814            && stream_id != 0xf2  // DSMCC
815            && stream_id != 0xf8) {  // H.222.1 type E
816        if (br->getBits(2) != 2u) {
817            return ERROR_MALFORMED;
818        }
819
820        MY_LOGV("PES_scrambling_control = %u", br->getBits(2));
821        MY_LOGV("PES_priority = %u", br->getBits(1));
822        MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
823        MY_LOGV("copyright = %u", br->getBits(1));
824        MY_LOGV("original_or_copy = %u", br->getBits(1));
825
826        unsigned PTS_DTS_flags = br->getBits(2);
827        ALOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
828
829        unsigned ESCR_flag = br->getBits(1);
830        ALOGV("ESCR_flag = %u", ESCR_flag);
831
832        unsigned ES_rate_flag = br->getBits(1);
833        ALOGV("ES_rate_flag = %u", ES_rate_flag);
834
835        unsigned DSM_trick_mode_flag = br->getBits(1);
836        ALOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
837
838        unsigned additional_copy_info_flag = br->getBits(1);
839        ALOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
840
841        MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
842        MY_LOGV("PES_extension_flag = %u", br->getBits(1));
843
844        unsigned PES_header_data_length = br->getBits(8);
845        ALOGV("PES_header_data_length = %u", PES_header_data_length);
846
847        unsigned optional_bytes_remaining = PES_header_data_length;
848
849        uint64_t PTS = 0, DTS = 0;
850
851        if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
852            if (optional_bytes_remaining < 5u) {
853                return ERROR_MALFORMED;
854            }
855
856            if (br->getBits(4) != PTS_DTS_flags) {
857                return ERROR_MALFORMED;
858            }
859            PTS = ((uint64_t)br->getBits(3)) << 30;
860            if (br->getBits(1) != 1u) {
861                return ERROR_MALFORMED;
862            }
863            PTS |= ((uint64_t)br->getBits(15)) << 15;
864            if (br->getBits(1) != 1u) {
865                return ERROR_MALFORMED;
866            }
867            PTS |= br->getBits(15);
868            if (br->getBits(1) != 1u) {
869                return ERROR_MALFORMED;
870            }
871
872            ALOGV("PTS = 0x%016" PRIx64 " (%.2f)", PTS, PTS / 90000.0);
873
874            optional_bytes_remaining -= 5;
875
876            if (PTS_DTS_flags == 3) {
877                if (optional_bytes_remaining < 5u) {
878                    return ERROR_MALFORMED;
879                }
880
881                if (br->getBits(4) != 1u) {
882                    return ERROR_MALFORMED;
883                }
884
885                DTS = ((uint64_t)br->getBits(3)) << 30;
886                if (br->getBits(1) != 1u) {
887                    return ERROR_MALFORMED;
888                }
889                DTS |= ((uint64_t)br->getBits(15)) << 15;
890                if (br->getBits(1) != 1u) {
891                    return ERROR_MALFORMED;
892                }
893                DTS |= br->getBits(15);
894                if (br->getBits(1) != 1u) {
895                    return ERROR_MALFORMED;
896                }
897
898                ALOGV("DTS = %" PRIu64, DTS);
899
900                optional_bytes_remaining -= 5;
901            }
902        }
903
904        if (ESCR_flag) {
905            if (optional_bytes_remaining < 6u) {
906                return ERROR_MALFORMED;
907            }
908
909            br->getBits(2);
910
911            uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
912            if (br->getBits(1) != 1u) {
913                return ERROR_MALFORMED;
914            }
915            ESCR |= ((uint64_t)br->getBits(15)) << 15;
916            if (br->getBits(1) != 1u) {
917                return ERROR_MALFORMED;
918            }
919            ESCR |= br->getBits(15);
920            if (br->getBits(1) != 1u) {
921                return ERROR_MALFORMED;
922            }
923
924            ALOGV("ESCR = %" PRIu64, ESCR);
925            MY_LOGV("ESCR_extension = %u", br->getBits(9));
926
927            if (br->getBits(1) != 1u) {
928                return ERROR_MALFORMED;
929            }
930
931            optional_bytes_remaining -= 6;
932        }
933
934        if (ES_rate_flag) {
935            if (optional_bytes_remaining < 3u) {
936                return ERROR_MALFORMED;
937            }
938
939            if (br->getBits(1) != 1u) {
940                return ERROR_MALFORMED;
941            }
942            MY_LOGV("ES_rate = %u", br->getBits(22));
943            if (br->getBits(1) != 1u) {
944                return ERROR_MALFORMED;
945            }
946
947            optional_bytes_remaining -= 3;
948        }
949
950        br->skipBits(optional_bytes_remaining * 8);
951
952        // ES data follows.
953
954        if (PES_packet_length != 0) {
955            if (PES_packet_length < PES_header_data_length + 3) {
956                return ERROR_MALFORMED;
957            }
958
959            unsigned dataLength =
960                PES_packet_length - 3 - PES_header_data_length;
961
962            if (br->numBitsLeft() < dataLength * 8) {
963                ALOGE("PES packet does not carry enough data to contain "
964                     "payload. (numBitsLeft = %zu, required = %u)",
965                     br->numBitsLeft(), dataLength * 8);
966
967                return ERROR_MALFORMED;
968            }
969
970            if (br->numBitsLeft() < dataLength * 8) {
971                return ERROR_MALFORMED;
972            }
973
974            onPayloadData(
975                    PTS_DTS_flags, PTS, DTS, br->data(), dataLength);
976
977            br->skipBits(dataLength * 8);
978        } else {
979            onPayloadData(
980                    PTS_DTS_flags, PTS, DTS,
981                    br->data(), br->numBitsLeft() / 8);
982
983            size_t payloadSizeBits = br->numBitsLeft();
984            if (payloadSizeBits % 8 != 0u) {
985                return ERROR_MALFORMED;
986            }
987
988            ALOGV("There's %zu bytes of payload.", payloadSizeBits / 8);
989        }
990    } else if (stream_id == 0xbe) {  // padding_stream
991        if (PES_packet_length == 0u) {
992            return ERROR_MALFORMED;
993        }
994        br->skipBits(PES_packet_length * 8);
995    } else {
996        if (PES_packet_length == 0u) {
997            return ERROR_MALFORMED;
998        }
999        br->skipBits(PES_packet_length * 8);
1000    }
1001
1002    return OK;
1003}
1004
1005status_t ATSParser::Stream::flush() {
1006    if (mBuffer->size() == 0) {
1007        return OK;
1008    }
1009
1010    ALOGV("flushing stream 0x%04x size = %zu", mElementaryPID, mBuffer->size());
1011
1012    ABitReader br(mBuffer->data(), mBuffer->size());
1013
1014    status_t err = parsePES(&br);
1015
1016    mBuffer->setRange(0, 0);
1017
1018    return err;
1019}
1020
1021void ATSParser::Stream::onPayloadData(
1022        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t /* DTS */,
1023        const uint8_t *data, size_t size) {
1024#if 0
1025    ALOGI("payload streamType 0x%02x, PTS = 0x%016llx, dPTS = %lld",
1026          mStreamType,
1027          PTS,
1028          (int64_t)PTS - mPrevPTS);
1029    mPrevPTS = PTS;
1030#endif
1031
1032    ALOGV("onPayloadData mStreamType=0x%02x", mStreamType);
1033
1034    int64_t timeUs = 0ll;  // no presentation timestamp available.
1035    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
1036        timeUs = mProgram->convertPTSToTimestamp(PTS);
1037    }
1038
1039    status_t err = mQueue->appendData(data, size, timeUs);
1040
1041    if (mEOSReached) {
1042        mQueue->signalEOS();
1043    }
1044
1045    if (err != OK) {
1046        return;
1047    }
1048
1049    sp<ABuffer> accessUnit;
1050    while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
1051        if (mSource == NULL) {
1052            sp<MetaData> meta = mQueue->getFormat();
1053
1054            if (meta != NULL) {
1055                ALOGV("Stream PID 0x%08x of type 0x%02x now has data.",
1056                     mElementaryPID, mStreamType);
1057
1058                const char *mime;
1059                if (meta->findCString(kKeyMIMEType, &mime)
1060                        && !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)
1061                        && !IsIDR(accessUnit)) {
1062                    continue;
1063                }
1064                mSource = new AnotherPacketSource(meta);
1065                mSource->queueAccessUnit(accessUnit);
1066            }
1067        } else if (mQueue->getFormat() != NULL) {
1068            // After a discontinuity we invalidate the queue's format
1069            // and won't enqueue any access units to the source until
1070            // the queue has reestablished the new format.
1071
1072            if (mSource->getFormat() == NULL) {
1073                mSource->setFormat(mQueue->getFormat());
1074            }
1075            mSource->queueAccessUnit(accessUnit);
1076        }
1077    }
1078}
1079
1080sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
1081    switch (type) {
1082        case VIDEO:
1083        {
1084            if (isVideo()) {
1085                return mSource;
1086            }
1087            break;
1088        }
1089
1090        case AUDIO:
1091        {
1092            if (isAudio()) {
1093                return mSource;
1094            }
1095            break;
1096        }
1097
1098        case META:
1099        {
1100            if (isMeta()) {
1101                return mSource;
1102            }
1103            break;
1104        }
1105
1106        default:
1107            break;
1108    }
1109
1110    return NULL;
1111}
1112
1113////////////////////////////////////////////////////////////////////////////////
1114
1115ATSParser::ATSParser(uint32_t flags)
1116    : mFlags(flags),
1117      mAbsoluteTimeAnchorUs(-1ll),
1118      mTimeOffsetValid(false),
1119      mTimeOffsetUs(0ll),
1120      mLastRecoveredPTS(-1ll),
1121      mNumTSPacketsParsed(0),
1122      mNumPCRs(0) {
1123    mPSISections.add(0 /* PID */, new PSISection);
1124}
1125
1126ATSParser::~ATSParser() {
1127}
1128
1129status_t ATSParser::feedTSPacket(const void *data, size_t size) {
1130    if (size != kTSPacketSize) {
1131        ALOGE("Wrong TS packet size");
1132        return BAD_VALUE;
1133    }
1134
1135    ABitReader br((const uint8_t *)data, kTSPacketSize);
1136    return parseTS(&br);
1137}
1138
1139void ATSParser::signalDiscontinuity(
1140        DiscontinuityType type, const sp<AMessage> &extra) {
1141    int64_t mediaTimeUs;
1142    if ((type & DISCONTINUITY_TIME) && extra != NULL) {
1143        if (extra->findInt64(IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
1144            mAbsoluteTimeAnchorUs = mediaTimeUs;
1145        }
1146        if ((mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)
1147                && extra->findInt64(
1148                    IStreamListener::kKeyRecentMediaTimeUs, &mediaTimeUs)) {
1149            if (mAbsoluteTimeAnchorUs >= 0ll) {
1150                mediaTimeUs -= mAbsoluteTimeAnchorUs;
1151            }
1152            if (mTimeOffsetValid) {
1153                mediaTimeUs -= mTimeOffsetUs;
1154            }
1155            mLastRecoveredPTS = (mediaTimeUs * 9) / 100;
1156        }
1157    } else if (type == DISCONTINUITY_ABSOLUTE_TIME) {
1158        int64_t timeUs;
1159        if (!extra->findInt64("timeUs", &timeUs)) {
1160            ALOGE("timeUs not found");
1161            return;
1162        }
1163
1164        if (!mPrograms.empty()) {
1165            ALOGE("mPrograms is not empty");
1166            return;
1167        }
1168        mAbsoluteTimeAnchorUs = timeUs;
1169        return;
1170    } else if (type == DISCONTINUITY_TIME_OFFSET) {
1171        int64_t offset;
1172        if (!extra->findInt64("offset", &offset)) {
1173            ALOGE("offset not found");
1174            return;
1175        }
1176
1177        mTimeOffsetValid = true;
1178        mTimeOffsetUs = offset;
1179        return;
1180    }
1181
1182    for (size_t i = 0; i < mPrograms.size(); ++i) {
1183        mPrograms.editItemAt(i)->signalDiscontinuity(type, extra);
1184    }
1185}
1186
1187void ATSParser::signalEOS(status_t finalResult) {
1188    if (finalResult == (status_t) OK) {
1189        ALOGE("finalResult not OK");
1190        return;
1191    }
1192
1193    for (size_t i = 0; i < mPrograms.size(); ++i) {
1194        mPrograms.editItemAt(i)->signalEOS(finalResult);
1195    }
1196}
1197
1198void ATSParser::parseProgramAssociationTable(ABitReader *br) {
1199    unsigned table_id = br->getBits(8);
1200    ALOGV("  table_id = %u", table_id);
1201    if (table_id != 0x00u) {
1202        ALOGE("PAT data error!");
1203        return ;
1204    }
1205    unsigned section_syntax_indictor = br->getBits(1);
1206    ALOGV("  section_syntax_indictor = %u", section_syntax_indictor);
1207
1208    br->skipBits(1);  // '0'
1209    MY_LOGV("  reserved = %u", br->getBits(2));
1210
1211    unsigned section_length = br->getBits(12);
1212    ALOGV("  section_length = %u", section_length);
1213
1214    MY_LOGV("  transport_stream_id = %u", br->getBits(16));
1215    MY_LOGV("  reserved = %u", br->getBits(2));
1216    MY_LOGV("  version_number = %u", br->getBits(5));
1217    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
1218    MY_LOGV("  section_number = %u", br->getBits(8));
1219    MY_LOGV("  last_section_number = %u", br->getBits(8));
1220
1221    size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
1222
1223    for (size_t i = 0; i < numProgramBytes / 4; ++i) {
1224        unsigned program_number = br->getBits(16);
1225        ALOGV("    program_number = %u", program_number);
1226
1227        MY_LOGV("    reserved = %u", br->getBits(3));
1228
1229        if (program_number == 0) {
1230            MY_LOGV("    network_PID = 0x%04x", br->getBits(13));
1231        } else {
1232            unsigned programMapPID = br->getBits(13);
1233
1234            ALOGV("    program_map_PID = 0x%04x", programMapPID);
1235
1236            bool found = false;
1237            for (size_t index = 0; index < mPrograms.size(); ++index) {
1238                const sp<Program> &program = mPrograms.itemAt(index);
1239
1240                if (program->number() == program_number) {
1241                    program->updateProgramMapPID(programMapPID);
1242                    found = true;
1243                    break;
1244                }
1245            }
1246
1247            if (!found) {
1248                mPrograms.push(
1249                        new Program(this, program_number, programMapPID, mLastRecoveredPTS));
1250            }
1251
1252            if (mPSISections.indexOfKey(programMapPID) < 0) {
1253                mPSISections.add(programMapPID, new PSISection);
1254            }
1255        }
1256    }
1257
1258    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
1259}
1260
1261status_t ATSParser::parsePID(
1262        ABitReader *br, unsigned PID,
1263        unsigned continuity_counter,
1264        unsigned payload_unit_start_indicator) {
1265    ssize_t sectionIndex = mPSISections.indexOfKey(PID);
1266
1267    if (sectionIndex >= 0) {
1268        sp<PSISection> section = mPSISections.valueAt(sectionIndex);
1269
1270        if (payload_unit_start_indicator) {
1271            if (!section->isEmpty()) {
1272                ALOGW("parsePID encounters payload_unit_start_indicator when section is not empty");
1273                section->clear();
1274            }
1275
1276            unsigned skip = br->getBits(8);
1277            section->setSkipBytes(skip + 1);  // skip filler bytes + pointer field itself
1278            br->skipBits(skip * 8);
1279        }
1280
1281        if (br->numBitsLeft() % 8 != 0) {
1282            return ERROR_MALFORMED;
1283        }
1284        status_t err = section->append(br->data(), br->numBitsLeft() / 8);
1285
1286        if (err != OK) {
1287            return err;
1288        }
1289
1290        if (!section->isComplete()) {
1291            return OK;
1292        }
1293
1294        if (!section->isCRCOkay()) {
1295            return BAD_VALUE;
1296        }
1297        ABitReader sectionBits(section->data(), section->size());
1298
1299        if (PID == 0) {
1300            parseProgramAssociationTable(&sectionBits);
1301        } else {
1302            bool handled = false;
1303            for (size_t i = 0; i < mPrograms.size(); ++i) {
1304                status_t err;
1305                if (!mPrograms.editItemAt(i)->parsePSISection(
1306                            PID, &sectionBits, &err)) {
1307                    continue;
1308                }
1309
1310                if (err != OK) {
1311                    return err;
1312                }
1313
1314                handled = true;
1315                break;
1316            }
1317
1318            if (!handled) {
1319                mPSISections.removeItem(PID);
1320                section.clear();
1321            }
1322        }
1323
1324        if (section != NULL) {
1325            section->clear();
1326        }
1327
1328        return OK;
1329    }
1330
1331    bool handled = false;
1332    for (size_t i = 0; i < mPrograms.size(); ++i) {
1333        status_t err;
1334        if (mPrograms.editItemAt(i)->parsePID(
1335                    PID, continuity_counter, payload_unit_start_indicator,
1336                    br, &err)) {
1337            if (err != OK) {
1338                return err;
1339            }
1340
1341            handled = true;
1342            break;
1343        }
1344    }
1345
1346    if (!handled) {
1347        ALOGV("PID 0x%04x not handled.", PID);
1348    }
1349
1350    return OK;
1351}
1352
1353status_t ATSParser::parseAdaptationField(ABitReader *br, unsigned PID) {
1354    unsigned adaptation_field_length = br->getBits(8);
1355
1356    if (adaptation_field_length > 0) {
1357        unsigned discontinuity_indicator = br->getBits(1);
1358
1359        if (discontinuity_indicator) {
1360            ALOGV("PID 0x%04x: discontinuity_indicator = 1 (!!!)", PID);
1361        }
1362
1363        br->skipBits(2);
1364        unsigned PCR_flag = br->getBits(1);
1365
1366        size_t numBitsRead = 4;
1367
1368        if (PCR_flag) {
1369            if (adaptation_field_length * 8 < 52) {
1370                return ERROR_MALFORMED;
1371            }
1372            br->skipBits(4);
1373            uint64_t PCR_base = br->getBits(32);
1374            PCR_base = (PCR_base << 1) | br->getBits(1);
1375
1376            br->skipBits(6);
1377            unsigned PCR_ext = br->getBits(9);
1378
1379            // The number of bytes from the start of the current
1380            // MPEG2 transport stream packet up and including
1381            // the final byte of this PCR_ext field.
1382            size_t byteOffsetFromStartOfTSPacket =
1383                (188 - br->numBitsLeft() / 8);
1384
1385            uint64_t PCR = PCR_base * 300 + PCR_ext;
1386
1387            ALOGV("PID 0x%04x: PCR = 0x%016" PRIx64 " (%.2f)",
1388                  PID, PCR, PCR / 27E6);
1389
1390            // The number of bytes received by this parser up to and
1391            // including the final byte of this PCR_ext field.
1392            size_t byteOffsetFromStart =
1393                mNumTSPacketsParsed * 188 + byteOffsetFromStartOfTSPacket;
1394
1395            for (size_t i = 0; i < mPrograms.size(); ++i) {
1396                updatePCR(PID, PCR, byteOffsetFromStart);
1397            }
1398
1399            numBitsRead += 52;
1400        }
1401
1402        br->skipBits(adaptation_field_length * 8 - numBitsRead);
1403    }
1404    return OK;
1405}
1406
1407status_t ATSParser::parseTS(ABitReader *br) {
1408    ALOGV("---");
1409
1410    unsigned sync_byte = br->getBits(8);
1411    if (sync_byte != 0x47u) {
1412        ALOGE("[error] parseTS: return error as sync_byte=0x%x", sync_byte);
1413        return BAD_VALUE;
1414    }
1415
1416    if (br->getBits(1)) {  // transport_error_indicator
1417        // silently ignore.
1418        return OK;
1419    }
1420
1421    unsigned payload_unit_start_indicator = br->getBits(1);
1422    ALOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
1423
1424    MY_LOGV("transport_priority = %u", br->getBits(1));
1425
1426    unsigned PID = br->getBits(13);
1427    ALOGV("PID = 0x%04x", PID);
1428
1429    MY_LOGV("transport_scrambling_control = %u", br->getBits(2));
1430
1431    unsigned adaptation_field_control = br->getBits(2);
1432    ALOGV("adaptation_field_control = %u", adaptation_field_control);
1433
1434    unsigned continuity_counter = br->getBits(4);
1435    ALOGV("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1436
1437    // ALOGI("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1438
1439    status_t err = OK;
1440
1441    if (adaptation_field_control == 2 || adaptation_field_control == 3) {
1442        err = parseAdaptationField(br, PID);
1443    }
1444    if (err == OK) {
1445        if (adaptation_field_control == 1 || adaptation_field_control == 3) {
1446            err = parsePID(
1447                    br, PID, continuity_counter, payload_unit_start_indicator);
1448        }
1449    }
1450
1451    ++mNumTSPacketsParsed;
1452
1453    return err;
1454}
1455
1456sp<MediaSource> ATSParser::getSource(SourceType type) {
1457    int which = -1;  // any
1458
1459    for (size_t i = 0; i < mPrograms.size(); ++i) {
1460        const sp<Program> &program = mPrograms.editItemAt(i);
1461
1462        if (which >= 0 && (int)program->number() != which) {
1463            continue;
1464        }
1465
1466        sp<MediaSource> source = program->getSource(type);
1467
1468        if (source != NULL) {
1469            return source;
1470        }
1471    }
1472
1473    return NULL;
1474}
1475
1476bool ATSParser::hasSource(SourceType type) const {
1477    for (size_t i = 0; i < mPrograms.size(); ++i) {
1478        const sp<Program> &program = mPrograms.itemAt(i);
1479        if (program->hasSource(type)) {
1480            return true;
1481        }
1482    }
1483
1484    return false;
1485}
1486
1487bool ATSParser::PTSTimeDeltaEstablished() {
1488    if (mPrograms.isEmpty()) {
1489        return false;
1490    }
1491
1492    return mPrograms.editItemAt(0)->PTSTimeDeltaEstablished();
1493}
1494
1495void ATSParser::updatePCR(
1496        unsigned /* PID */, uint64_t PCR, size_t byteOffsetFromStart) {
1497    ALOGV("PCR 0x%016" PRIx64 " @ %zu", PCR, byteOffsetFromStart);
1498
1499    if (mNumPCRs == 2) {
1500        mPCR[0] = mPCR[1];
1501        mPCRBytes[0] = mPCRBytes[1];
1502        mSystemTimeUs[0] = mSystemTimeUs[1];
1503        mNumPCRs = 1;
1504    }
1505
1506    mPCR[mNumPCRs] = PCR;
1507    mPCRBytes[mNumPCRs] = byteOffsetFromStart;
1508    mSystemTimeUs[mNumPCRs] = ALooper::GetNowUs();
1509
1510    ++mNumPCRs;
1511
1512    if (mNumPCRs == 2) {
1513        double transportRate =
1514            (mPCRBytes[1] - mPCRBytes[0]) * 27E6 / (mPCR[1] - mPCR[0]);
1515
1516        ALOGV("transportRate = %.2f bytes/sec", transportRate);
1517    }
1518}
1519
1520////////////////////////////////////////////////////////////////////////////////
1521
1522
1523// CRC32 used for PSI section. The table was generated by following command:
1524// $ python pycrc.py --model crc-32-mpeg --algorithm table-driven --generate c
1525// Visit http://www.tty1.net/pycrc/index_en.html for more details.
1526uint32_t ATSParser::PSISection::CRC_TABLE[] = {
1527    0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
1528    0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
1529    0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
1530    0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
1531    0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
1532    0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
1533    0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
1534    0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
1535    0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
1536    0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
1537    0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
1538    0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
1539    0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
1540    0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
1541    0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
1542    0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
1543    0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
1544    0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
1545    0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
1546    0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
1547    0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
1548    0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
1549    0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
1550    0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
1551    0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
1552    0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
1553    0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
1554    0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
1555    0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
1556    0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
1557    0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
1558    0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
1559    0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
1560    0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
1561    0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
1562    0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
1563    0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
1564    0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
1565    0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
1566    0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
1567    0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
1568    0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
1569    0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
1570    0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
1571    0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
1572    0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
1573    0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
1574    0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
1575    0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
1576    0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
1577    0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
1578    0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
1579    0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
1580    0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
1581    0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
1582    0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
1583    0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
1584    0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
1585    0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
1586    0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
1587    0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
1588    0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
1589    0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
1590    0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
1591    };
1592
1593ATSParser::PSISection::PSISection() :
1594    mSkipBytes(0) {
1595}
1596
1597ATSParser::PSISection::~PSISection() {
1598}
1599
1600status_t ATSParser::PSISection::append(const void *data, size_t size) {
1601    if (mBuffer == NULL || mBuffer->size() + size > mBuffer->capacity()) {
1602        size_t newCapacity =
1603            (mBuffer == NULL) ? size : mBuffer->capacity() + size;
1604
1605        newCapacity = (newCapacity + 1023) & ~1023;
1606
1607        sp<ABuffer> newBuffer = new ABuffer(newCapacity);
1608
1609        if (mBuffer != NULL) {
1610            memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
1611            newBuffer->setRange(0, mBuffer->size());
1612        } else {
1613            newBuffer->setRange(0, 0);
1614        }
1615
1616        mBuffer = newBuffer;
1617    }
1618
1619    memcpy(mBuffer->data() + mBuffer->size(), data, size);
1620    mBuffer->setRange(0, mBuffer->size() + size);
1621
1622    return OK;
1623}
1624
1625void ATSParser::PSISection::setSkipBytes(uint8_t skip) {
1626    mSkipBytes = skip;
1627}
1628
1629void ATSParser::PSISection::clear() {
1630    if (mBuffer != NULL) {
1631        mBuffer->setRange(0, 0);
1632    }
1633    mSkipBytes = 0;
1634}
1635
1636bool ATSParser::PSISection::isComplete() const {
1637    if (mBuffer == NULL || mBuffer->size() < 3) {
1638        return false;
1639    }
1640
1641    unsigned sectionLength = U16_AT(mBuffer->data() + 1) & 0xfff;
1642    return mBuffer->size() >= sectionLength + 3;
1643}
1644
1645bool ATSParser::PSISection::isEmpty() const {
1646    return mBuffer == NULL || mBuffer->size() == 0;
1647}
1648
1649const uint8_t *ATSParser::PSISection::data() const {
1650    return mBuffer == NULL ? NULL : mBuffer->data();
1651}
1652
1653size_t ATSParser::PSISection::size() const {
1654    return mBuffer == NULL ? 0 : mBuffer->size();
1655}
1656
1657bool ATSParser::PSISection::isCRCOkay() const {
1658    if (!isComplete()) {
1659        return false;
1660    }
1661    uint8_t* data = mBuffer->data();
1662
1663    // Return true if section_syntax_indicator says no section follows the field section_length.
1664    if ((data[1] & 0x80) == 0) {
1665        return true;
1666    }
1667
1668    unsigned sectionLength = U16_AT(data + 1) & 0xfff;
1669    ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes);
1670
1671    // Skip the preceding field present when payload start indicator is on.
1672    sectionLength -= mSkipBytes;
1673
1674    uint32_t crc = 0xffffffff;
1675    for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) {
1676        uint8_t b = data[i];
1677        int index = ((crc >> 24) ^ (b & 0xff)) & 0xff;
1678        crc = CRC_TABLE[index] ^ (crc << 8);
1679    }
1680    ALOGV("crc: %08x\n", crc);
1681    return (crc == 0);
1682}
1683}  // namespace android
1684