[go: nahoru, domu]

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