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