ATSParser.cpp revision 9b132a7bdde8388f124e4db5ff54a88a93f8cdb6
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                return err;
698            }
699        }
700
701        mPayloadStarted = true;
702        mPesStartOffset = offset;
703    }
704
705    if (!mPayloadStarted) {
706        return OK;
707    }
708
709    size_t payloadSizeBits = br->numBitsLeft();
710    if (payloadSizeBits % 8 != 0u) {
711        ALOGE("Wrong value");
712        return BAD_VALUE;
713    }
714
715    size_t neededSize = mBuffer->size() + payloadSizeBits / 8;
716    if (mBuffer->capacity() < neededSize) {
717        // Increment in multiples of 64K.
718        neededSize = (neededSize + 65535) & ~65535;
719
720        ALOGI("resizing buffer to %zu bytes", neededSize);
721
722        sp<ABuffer> newBuffer = new ABuffer(neededSize);
723        memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
724        newBuffer->setRange(0, mBuffer->size());
725        mBuffer = newBuffer;
726    }
727
728    memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
729    mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
730
731    return OK;
732}
733
734bool ATSParser::Stream::isVideo() const {
735    switch (mStreamType) {
736        case STREAMTYPE_H264:
737        case STREAMTYPE_MPEG1_VIDEO:
738        case STREAMTYPE_MPEG2_VIDEO:
739        case STREAMTYPE_MPEG4_VIDEO:
740            return true;
741
742        default:
743            return false;
744    }
745}
746
747bool ATSParser::Stream::isAudio() const {
748    switch (mStreamType) {
749        case STREAMTYPE_MPEG1_AUDIO:
750        case STREAMTYPE_MPEG2_AUDIO:
751        case STREAMTYPE_MPEG2_AUDIO_ADTS:
752        case STREAMTYPE_LPCM_AC3:
753        case STREAMTYPE_AC3:
754            return true;
755
756        default:
757            return false;
758    }
759}
760
761bool ATSParser::Stream::isMeta() const {
762    if (mStreamType == STREAMTYPE_METADATA) {
763        return true;
764    }
765    return false;
766}
767
768void ATSParser::Stream::signalDiscontinuity(
769        DiscontinuityType type, const sp<AMessage> &extra) {
770    mExpectedContinuityCounter = -1;
771
772    if (mQueue == NULL) {
773        return;
774    }
775
776    mPayloadStarted = false;
777    mEOSReached = false;
778    mBuffer->setRange(0, 0);
779
780    bool clearFormat = false;
781    if (isAudio()) {
782        if (type & DISCONTINUITY_AUDIO_FORMAT) {
783            clearFormat = true;
784        }
785    } else {
786        if (type & DISCONTINUITY_VIDEO_FORMAT) {
787            clearFormat = true;
788        }
789    }
790
791    mQueue->clear(clearFormat);
792
793    if (type & DISCONTINUITY_TIME) {
794        uint64_t resumeAtPTS;
795        if (extra != NULL
796                && extra->findInt64(
797                    IStreamListener::kKeyResumeAtPTS,
798                    (int64_t *)&resumeAtPTS)) {
799            int64_t resumeAtMediaTimeUs =
800                mProgram->convertPTSToTimestamp(resumeAtPTS);
801
802            extra->setInt64("resume-at-mediaTimeUs", resumeAtMediaTimeUs);
803        }
804    }
805
806    if (mSource != NULL) {
807        mSource->queueDiscontinuity(type, extra, true);
808    }
809}
810
811void ATSParser::Stream::signalEOS(status_t finalResult) {
812    if (mSource != NULL) {
813        mSource->signalEOS(finalResult);
814    }
815    mEOSReached = true;
816    flush(NULL);
817}
818
819status_t ATSParser::Stream::parsePES(ABitReader *br, SyncEvent *event) {
820    unsigned packet_startcode_prefix = br->getBits(24);
821
822    ALOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
823
824    if (packet_startcode_prefix != 1) {
825        ALOGV("Supposedly payload_unit_start=1 unit does not start "
826             "with startcode.");
827
828        return ERROR_MALFORMED;
829    }
830
831    unsigned stream_id = br->getBits(8);
832    ALOGV("stream_id = 0x%02x", stream_id);
833
834    unsigned PES_packet_length = br->getBits(16);
835    ALOGV("PES_packet_length = %u", PES_packet_length);
836
837    if (stream_id != 0xbc  // program_stream_map
838            && stream_id != 0xbe  // padding_stream
839            && stream_id != 0xbf  // private_stream_2
840            && stream_id != 0xf0  // ECM
841            && stream_id != 0xf1  // EMM
842            && stream_id != 0xff  // program_stream_directory
843            && stream_id != 0xf2  // DSMCC
844            && stream_id != 0xf8) {  // H.222.1 type E
845        if (br->getBits(2) != 2u) {
846            return ERROR_MALFORMED;
847        }
848
849        MY_LOGV("PES_scrambling_control = %u", br->getBits(2));
850        MY_LOGV("PES_priority = %u", br->getBits(1));
851        MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
852        MY_LOGV("copyright = %u", br->getBits(1));
853        MY_LOGV("original_or_copy = %u", br->getBits(1));
854
855        unsigned PTS_DTS_flags = br->getBits(2);
856        ALOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
857
858        unsigned ESCR_flag = br->getBits(1);
859        ALOGV("ESCR_flag = %u", ESCR_flag);
860
861        unsigned ES_rate_flag = br->getBits(1);
862        ALOGV("ES_rate_flag = %u", ES_rate_flag);
863
864        unsigned DSM_trick_mode_flag = br->getBits(1);
865        ALOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
866
867        unsigned additional_copy_info_flag = br->getBits(1);
868        ALOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
869
870        MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
871        MY_LOGV("PES_extension_flag = %u", br->getBits(1));
872
873        unsigned PES_header_data_length = br->getBits(8);
874        ALOGV("PES_header_data_length = %u", PES_header_data_length);
875
876        unsigned optional_bytes_remaining = PES_header_data_length;
877
878        uint64_t PTS = 0, DTS = 0;
879
880        if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
881            if (optional_bytes_remaining < 5u) {
882                return ERROR_MALFORMED;
883            }
884
885            if (br->getBits(4) != PTS_DTS_flags) {
886                return ERROR_MALFORMED;
887            }
888            PTS = ((uint64_t)br->getBits(3)) << 30;
889            if (br->getBits(1) != 1u) {
890                return ERROR_MALFORMED;
891            }
892            PTS |= ((uint64_t)br->getBits(15)) << 15;
893            if (br->getBits(1) != 1u) {
894                return ERROR_MALFORMED;
895            }
896            PTS |= br->getBits(15);
897            if (br->getBits(1) != 1u) {
898                return ERROR_MALFORMED;
899            }
900
901            ALOGV("PTS = 0x%016" PRIx64 " (%.2f)", PTS, PTS / 90000.0);
902
903            optional_bytes_remaining -= 5;
904
905            if (PTS_DTS_flags == 3) {
906                if (optional_bytes_remaining < 5u) {
907                    return ERROR_MALFORMED;
908                }
909
910                if (br->getBits(4) != 1u) {
911                    return ERROR_MALFORMED;
912                }
913
914                DTS = ((uint64_t)br->getBits(3)) << 30;
915                if (br->getBits(1) != 1u) {
916                    return ERROR_MALFORMED;
917                }
918                DTS |= ((uint64_t)br->getBits(15)) << 15;
919                if (br->getBits(1) != 1u) {
920                    return ERROR_MALFORMED;
921                }
922                DTS |= br->getBits(15);
923                if (br->getBits(1) != 1u) {
924                    return ERROR_MALFORMED;
925                }
926
927                ALOGV("DTS = %" PRIu64, DTS);
928
929                optional_bytes_remaining -= 5;
930            }
931        }
932
933        if (ESCR_flag) {
934            if (optional_bytes_remaining < 6u) {
935                return ERROR_MALFORMED;
936            }
937
938            br->getBits(2);
939
940            uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
941            if (br->getBits(1) != 1u) {
942                return ERROR_MALFORMED;
943            }
944            ESCR |= ((uint64_t)br->getBits(15)) << 15;
945            if (br->getBits(1) != 1u) {
946                return ERROR_MALFORMED;
947            }
948            ESCR |= br->getBits(15);
949            if (br->getBits(1) != 1u) {
950                return ERROR_MALFORMED;
951            }
952
953            ALOGV("ESCR = %" PRIu64, ESCR);
954            MY_LOGV("ESCR_extension = %u", br->getBits(9));
955
956            if (br->getBits(1) != 1u) {
957                return ERROR_MALFORMED;
958            }
959
960            optional_bytes_remaining -= 6;
961        }
962
963        if (ES_rate_flag) {
964            if (optional_bytes_remaining < 3u) {
965                return ERROR_MALFORMED;
966            }
967
968            if (br->getBits(1) != 1u) {
969                return ERROR_MALFORMED;
970            }
971            MY_LOGV("ES_rate = %u", br->getBits(22));
972            if (br->getBits(1) != 1u) {
973                return ERROR_MALFORMED;
974            }
975
976            optional_bytes_remaining -= 3;
977        }
978
979        br->skipBits(optional_bytes_remaining * 8);
980
981        // ES data follows.
982
983        if (PES_packet_length != 0) {
984            if (PES_packet_length < PES_header_data_length + 3) {
985                return ERROR_MALFORMED;
986            }
987
988            unsigned dataLength =
989                PES_packet_length - 3 - PES_header_data_length;
990
991            if (br->numBitsLeft() < dataLength * 8) {
992                ALOGE("PES packet does not carry enough data to contain "
993                     "payload. (numBitsLeft = %zu, required = %u)",
994                     br->numBitsLeft(), dataLength * 8);
995
996                return ERROR_MALFORMED;
997            }
998
999            if (br->numBitsLeft() < dataLength * 8) {
1000                return ERROR_MALFORMED;
1001            }
1002
1003            onPayloadData(
1004                    PTS_DTS_flags, PTS, DTS, br->data(), dataLength, event);
1005
1006            br->skipBits(dataLength * 8);
1007        } else {
1008            onPayloadData(
1009                    PTS_DTS_flags, PTS, DTS,
1010                    br->data(), br->numBitsLeft() / 8, event);
1011
1012            size_t payloadSizeBits = br->numBitsLeft();
1013            if (payloadSizeBits % 8 != 0u) {
1014                return ERROR_MALFORMED;
1015            }
1016
1017            ALOGV("There's %zu bytes of payload.", payloadSizeBits / 8);
1018        }
1019    } else if (stream_id == 0xbe) {  // padding_stream
1020        if (PES_packet_length == 0u) {
1021            return ERROR_MALFORMED;
1022        }
1023        br->skipBits(PES_packet_length * 8);
1024    } else {
1025        if (PES_packet_length == 0u) {
1026            return ERROR_MALFORMED;
1027        }
1028        br->skipBits(PES_packet_length * 8);
1029    }
1030
1031    return OK;
1032}
1033
1034status_t ATSParser::Stream::flush(SyncEvent *event) {
1035    if (mBuffer == NULL || mBuffer->size() == 0) {
1036        return OK;
1037    }
1038
1039    ALOGV("flushing stream 0x%04x size = %zu", mElementaryPID, mBuffer->size());
1040
1041    ABitReader br(mBuffer->data(), mBuffer->size());
1042
1043    status_t err = parsePES(&br, event);
1044
1045    mBuffer->setRange(0, 0);
1046
1047    return err;
1048}
1049
1050void ATSParser::Stream::onPayloadData(
1051        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t /* DTS */,
1052        const uint8_t *data, size_t size, SyncEvent *event) {
1053#if 0
1054    ALOGI("payload streamType 0x%02x, PTS = 0x%016llx, dPTS = %lld",
1055          mStreamType,
1056          PTS,
1057          (int64_t)PTS - mPrevPTS);
1058    mPrevPTS = PTS;
1059#endif
1060
1061    ALOGV("onPayloadData mStreamType=0x%02x", mStreamType);
1062
1063    int64_t timeUs = 0ll;  // no presentation timestamp available.
1064    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
1065        timeUs = mProgram->convertPTSToTimestamp(PTS);
1066    }
1067
1068    status_t err = mQueue->appendData(data, size, timeUs);
1069
1070    if (mEOSReached) {
1071        mQueue->signalEOS();
1072    }
1073
1074    if (err != OK) {
1075        return;
1076    }
1077
1078    sp<ABuffer> accessUnit;
1079    bool found = false;
1080    while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
1081        if (mSource == NULL) {
1082            sp<MetaData> meta = mQueue->getFormat();
1083
1084            if (meta != NULL) {
1085                ALOGV("Stream PID 0x%08x of type 0x%02x now has data.",
1086                     mElementaryPID, mStreamType);
1087
1088                const char *mime;
1089                if (meta->findCString(kKeyMIMEType, &mime)
1090                        && !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)
1091                        && !IsIDR(accessUnit)) {
1092                    continue;
1093                }
1094                mSource = new AnotherPacketSource(meta);
1095                mSource->queueAccessUnit(accessUnit);
1096            }
1097        } else if (mQueue->getFormat() != NULL) {
1098            // After a discontinuity we invalidate the queue's format
1099            // and won't enqueue any access units to the source until
1100            // the queue has reestablished the new format.
1101
1102            if (mSource->getFormat() == NULL) {
1103                mSource->setFormat(mQueue->getFormat());
1104            }
1105            mSource->queueAccessUnit(accessUnit);
1106        }
1107
1108        if ((event != NULL) && !found && mQueue->getFormat() != NULL) {
1109            int32_t sync = 0;
1110            if (accessUnit->meta()->findInt32("isSync", &sync) && sync) {
1111                int64_t timeUs;
1112                if (accessUnit->meta()->findInt64("timeUs", &timeUs)) {
1113                    found = true;
1114                    event->init(mPesStartOffset, mSource, timeUs);
1115                }
1116            }
1117        }
1118    }
1119}
1120
1121sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
1122    switch (type) {
1123        case VIDEO:
1124        {
1125            if (isVideo()) {
1126                return mSource;
1127            }
1128            break;
1129        }
1130
1131        case AUDIO:
1132        {
1133            if (isAudio()) {
1134                return mSource;
1135            }
1136            break;
1137        }
1138
1139        case META:
1140        {
1141            if (isMeta()) {
1142                return mSource;
1143            }
1144            break;
1145        }
1146
1147        default:
1148            break;
1149    }
1150
1151    return NULL;
1152}
1153
1154////////////////////////////////////////////////////////////////////////////////
1155
1156ATSParser::ATSParser(uint32_t flags)
1157    : mFlags(flags),
1158      mAbsoluteTimeAnchorUs(-1ll),
1159      mTimeOffsetValid(false),
1160      mTimeOffsetUs(0ll),
1161      mLastRecoveredPTS(-1ll),
1162      mNumTSPacketsParsed(0),
1163      mNumPCRs(0) {
1164    mPSISections.add(0 /* PID */, new PSISection);
1165}
1166
1167ATSParser::~ATSParser() {
1168}
1169
1170status_t ATSParser::feedTSPacket(const void *data, size_t size,
1171        SyncEvent *event) {
1172    if (size != kTSPacketSize) {
1173        ALOGE("Wrong TS packet size");
1174        return BAD_VALUE;
1175    }
1176
1177    ABitReader br((const uint8_t *)data, kTSPacketSize);
1178    return parseTS(&br, event);
1179}
1180
1181void ATSParser::signalDiscontinuity(
1182        DiscontinuityType type, const sp<AMessage> &extra) {
1183    int64_t mediaTimeUs;
1184    if ((type & DISCONTINUITY_TIME) && extra != NULL) {
1185        if (extra->findInt64(IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
1186            mAbsoluteTimeAnchorUs = mediaTimeUs;
1187        }
1188        if ((mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)
1189                && extra->findInt64(
1190                    IStreamListener::kKeyRecentMediaTimeUs, &mediaTimeUs)) {
1191            if (mAbsoluteTimeAnchorUs >= 0ll) {
1192                mediaTimeUs -= mAbsoluteTimeAnchorUs;
1193            }
1194            if (mTimeOffsetValid) {
1195                mediaTimeUs -= mTimeOffsetUs;
1196            }
1197            mLastRecoveredPTS = (mediaTimeUs * 9) / 100;
1198        }
1199    } else if (type == DISCONTINUITY_ABSOLUTE_TIME) {
1200        int64_t timeUs;
1201        if (!extra->findInt64("timeUs", &timeUs)) {
1202            ALOGE("timeUs not found");
1203            return;
1204        }
1205
1206        if (!mPrograms.empty()) {
1207            ALOGE("mPrograms is not empty");
1208            return;
1209        }
1210        mAbsoluteTimeAnchorUs = timeUs;
1211        return;
1212    } else if (type == DISCONTINUITY_TIME_OFFSET) {
1213        int64_t offset;
1214        if (!extra->findInt64("offset", &offset)) {
1215            ALOGE("offset not found");
1216            return;
1217        }
1218
1219        mTimeOffsetValid = true;
1220        mTimeOffsetUs = offset;
1221        return;
1222    }
1223
1224    for (size_t i = 0; i < mPrograms.size(); ++i) {
1225        mPrograms.editItemAt(i)->signalDiscontinuity(type, extra);
1226    }
1227}
1228
1229void ATSParser::signalEOS(status_t finalResult) {
1230    if (finalResult == (status_t) OK) {
1231        ALOGE("finalResult not OK");
1232        return;
1233    }
1234
1235    for (size_t i = 0; i < mPrograms.size(); ++i) {
1236        mPrograms.editItemAt(i)->signalEOS(finalResult);
1237    }
1238}
1239
1240void ATSParser::parseProgramAssociationTable(ABitReader *br) {
1241    unsigned table_id = br->getBits(8);
1242    ALOGV("  table_id = %u", table_id);
1243    if (table_id != 0x00u) {
1244        ALOGE("PAT data error!");
1245        return ;
1246    }
1247    unsigned section_syntax_indictor = br->getBits(1);
1248    ALOGV("  section_syntax_indictor = %u", section_syntax_indictor);
1249
1250    br->skipBits(1);  // '0'
1251    MY_LOGV("  reserved = %u", br->getBits(2));
1252
1253    unsigned section_length = br->getBits(12);
1254    ALOGV("  section_length = %u", section_length);
1255
1256    MY_LOGV("  transport_stream_id = %u", br->getBits(16));
1257    MY_LOGV("  reserved = %u", br->getBits(2));
1258    MY_LOGV("  version_number = %u", br->getBits(5));
1259    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
1260    MY_LOGV("  section_number = %u", br->getBits(8));
1261    MY_LOGV("  last_section_number = %u", br->getBits(8));
1262
1263    size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
1264
1265    for (size_t i = 0; i < numProgramBytes / 4; ++i) {
1266        unsigned program_number = br->getBits(16);
1267        ALOGV("    program_number = %u", program_number);
1268
1269        MY_LOGV("    reserved = %u", br->getBits(3));
1270
1271        if (program_number == 0) {
1272            MY_LOGV("    network_PID = 0x%04x", br->getBits(13));
1273        } else {
1274            unsigned programMapPID = br->getBits(13);
1275
1276            ALOGV("    program_map_PID = 0x%04x", programMapPID);
1277
1278            bool found = false;
1279            for (size_t index = 0; index < mPrograms.size(); ++index) {
1280                const sp<Program> &program = mPrograms.itemAt(index);
1281
1282                if (program->number() == program_number) {
1283                    program->updateProgramMapPID(programMapPID);
1284                    found = true;
1285                    break;
1286                }
1287            }
1288
1289            if (!found) {
1290                mPrograms.push(
1291                        new Program(this, program_number, programMapPID, mLastRecoveredPTS));
1292            }
1293
1294            if (mPSISections.indexOfKey(programMapPID) < 0) {
1295                mPSISections.add(programMapPID, new PSISection);
1296            }
1297        }
1298    }
1299
1300    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
1301}
1302
1303status_t ATSParser::parsePID(
1304        ABitReader *br, unsigned PID,
1305        unsigned continuity_counter,
1306        unsigned payload_unit_start_indicator,
1307        SyncEvent *event) {
1308    ssize_t sectionIndex = mPSISections.indexOfKey(PID);
1309
1310    if (sectionIndex >= 0) {
1311        sp<PSISection> section = mPSISections.valueAt(sectionIndex);
1312
1313        if (payload_unit_start_indicator) {
1314            if (!section->isEmpty()) {
1315                ALOGW("parsePID encounters payload_unit_start_indicator when section is not empty");
1316                section->clear();
1317            }
1318
1319            unsigned skip = br->getBits(8);
1320            section->setSkipBytes(skip + 1);  // skip filler bytes + pointer field itself
1321            br->skipBits(skip * 8);
1322        }
1323
1324        if (br->numBitsLeft() % 8 != 0) {
1325            return ERROR_MALFORMED;
1326        }
1327        status_t err = section->append(br->data(), br->numBitsLeft() / 8);
1328
1329        if (err != OK) {
1330            return err;
1331        }
1332
1333        if (!section->isComplete()) {
1334            return OK;
1335        }
1336
1337        if (!section->isCRCOkay()) {
1338            return BAD_VALUE;
1339        }
1340        ABitReader sectionBits(section->data(), section->size());
1341
1342        if (PID == 0) {
1343            parseProgramAssociationTable(&sectionBits);
1344        } else {
1345            bool handled = false;
1346            for (size_t i = 0; i < mPrograms.size(); ++i) {
1347                status_t err;
1348                if (!mPrograms.editItemAt(i)->parsePSISection(
1349                            PID, &sectionBits, &err)) {
1350                    continue;
1351                }
1352
1353                if (err != OK) {
1354                    return err;
1355                }
1356
1357                handled = true;
1358                break;
1359            }
1360
1361            if (!handled) {
1362                mPSISections.removeItem(PID);
1363                section.clear();
1364            }
1365        }
1366
1367        if (section != NULL) {
1368            section->clear();
1369        }
1370
1371        return OK;
1372    }
1373
1374    bool handled = false;
1375    for (size_t i = 0; i < mPrograms.size(); ++i) {
1376        status_t err;
1377        if (mPrograms.editItemAt(i)->parsePID(
1378                    PID, continuity_counter, payload_unit_start_indicator,
1379                    br, &err, event)) {
1380            if (err != OK) {
1381                return err;
1382            }
1383
1384            handled = true;
1385            break;
1386        }
1387    }
1388
1389    if (!handled) {
1390        ALOGV("PID 0x%04x not handled.", PID);
1391    }
1392
1393    return OK;
1394}
1395
1396status_t ATSParser::parseAdaptationField(ABitReader *br, unsigned PID) {
1397    unsigned adaptation_field_length = br->getBits(8);
1398
1399    if (adaptation_field_length > 0) {
1400        if (adaptation_field_length * 8 > br->numBitsLeft()) {
1401            ALOGV("Adaptation field should be included in a single TS packet.");
1402            return ERROR_MALFORMED;
1403        }
1404
1405        unsigned discontinuity_indicator = br->getBits(1);
1406
1407        if (discontinuity_indicator) {
1408            ALOGV("PID 0x%04x: discontinuity_indicator = 1 (!!!)", PID);
1409        }
1410
1411        br->skipBits(2);
1412        unsigned PCR_flag = br->getBits(1);
1413
1414        size_t numBitsRead = 4;
1415
1416        if (PCR_flag) {
1417            if (adaptation_field_length * 8 < 52) {
1418                return ERROR_MALFORMED;
1419            }
1420            br->skipBits(4);
1421            uint64_t PCR_base = br->getBits(32);
1422            PCR_base = (PCR_base << 1) | br->getBits(1);
1423
1424            br->skipBits(6);
1425            unsigned PCR_ext = br->getBits(9);
1426
1427            // The number of bytes from the start of the current
1428            // MPEG2 transport stream packet up and including
1429            // the final byte of this PCR_ext field.
1430            size_t byteOffsetFromStartOfTSPacket =
1431                (188 - br->numBitsLeft() / 8);
1432
1433            uint64_t PCR = PCR_base * 300 + PCR_ext;
1434
1435            ALOGV("PID 0x%04x: PCR = 0x%016" PRIx64 " (%.2f)",
1436                  PID, PCR, PCR / 27E6);
1437
1438            // The number of bytes received by this parser up to and
1439            // including the final byte of this PCR_ext field.
1440            size_t byteOffsetFromStart =
1441                mNumTSPacketsParsed * 188 + byteOffsetFromStartOfTSPacket;
1442
1443            for (size_t i = 0; i < mPrograms.size(); ++i) {
1444                updatePCR(PID, PCR, byteOffsetFromStart);
1445            }
1446
1447            numBitsRead += 52;
1448        }
1449
1450        br->skipBits(adaptation_field_length * 8 - numBitsRead);
1451    }
1452    return OK;
1453}
1454
1455status_t ATSParser::parseTS(ABitReader *br, SyncEvent *event) {
1456    ALOGV("---");
1457
1458    unsigned sync_byte = br->getBits(8);
1459    if (sync_byte != 0x47u) {
1460        ALOGE("[error] parseTS: return error as sync_byte=0x%x", sync_byte);
1461        return BAD_VALUE;
1462    }
1463
1464    if (br->getBits(1)) {  // transport_error_indicator
1465        // silently ignore.
1466        return OK;
1467    }
1468
1469    unsigned payload_unit_start_indicator = br->getBits(1);
1470    ALOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
1471
1472    MY_LOGV("transport_priority = %u", br->getBits(1));
1473
1474    unsigned PID = br->getBits(13);
1475    ALOGV("PID = 0x%04x", PID);
1476
1477    MY_LOGV("transport_scrambling_control = %u", br->getBits(2));
1478
1479    unsigned adaptation_field_control = br->getBits(2);
1480    ALOGV("adaptation_field_control = %u", adaptation_field_control);
1481
1482    unsigned continuity_counter = br->getBits(4);
1483    ALOGV("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1484
1485    // ALOGI("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1486
1487    status_t err = OK;
1488
1489    if (adaptation_field_control == 2 || adaptation_field_control == 3) {
1490        err = parseAdaptationField(br, PID);
1491    }
1492    if (err == OK) {
1493        if (adaptation_field_control == 1 || adaptation_field_control == 3) {
1494            err = parsePID(br, PID, continuity_counter,
1495                    payload_unit_start_indicator, event);
1496        }
1497    }
1498
1499    ++mNumTSPacketsParsed;
1500
1501    return err;
1502}
1503
1504sp<MediaSource> ATSParser::getSource(SourceType type) {
1505    int which = -1;  // any
1506
1507    for (size_t i = 0; i < mPrograms.size(); ++i) {
1508        const sp<Program> &program = mPrograms.editItemAt(i);
1509
1510        if (which >= 0 && (int)program->number() != which) {
1511            continue;
1512        }
1513
1514        sp<MediaSource> source = program->getSource(type);
1515
1516        if (source != NULL) {
1517            return source;
1518        }
1519    }
1520
1521    return NULL;
1522}
1523
1524bool ATSParser::hasSource(SourceType type) const {
1525    for (size_t i = 0; i < mPrograms.size(); ++i) {
1526        const sp<Program> &program = mPrograms.itemAt(i);
1527        if (program->hasSource(type)) {
1528            return true;
1529        }
1530    }
1531
1532    return false;
1533}
1534
1535bool ATSParser::PTSTimeDeltaEstablished() {
1536    if (mPrograms.isEmpty()) {
1537        return false;
1538    }
1539
1540    return mPrograms.editItemAt(0)->PTSTimeDeltaEstablished();
1541}
1542
1543void ATSParser::updatePCR(
1544        unsigned /* PID */, uint64_t PCR, size_t byteOffsetFromStart) {
1545    ALOGV("PCR 0x%016" PRIx64 " @ %zu", PCR, byteOffsetFromStart);
1546
1547    if (mNumPCRs == 2) {
1548        mPCR[0] = mPCR[1];
1549        mPCRBytes[0] = mPCRBytes[1];
1550        mSystemTimeUs[0] = mSystemTimeUs[1];
1551        mNumPCRs = 1;
1552    }
1553
1554    mPCR[mNumPCRs] = PCR;
1555    mPCRBytes[mNumPCRs] = byteOffsetFromStart;
1556    mSystemTimeUs[mNumPCRs] = ALooper::GetNowUs();
1557
1558    ++mNumPCRs;
1559
1560    if (mNumPCRs == 2) {
1561        double transportRate =
1562            (mPCRBytes[1] - mPCRBytes[0]) * 27E6 / (mPCR[1] - mPCR[0]);
1563
1564        ALOGV("transportRate = %.2f bytes/sec", transportRate);
1565    }
1566}
1567
1568////////////////////////////////////////////////////////////////////////////////
1569
1570
1571// CRC32 used for PSI section. The table was generated by following command:
1572// $ python pycrc.py --model crc-32-mpeg --algorithm table-driven --generate c
1573// Visit http://www.tty1.net/pycrc/index_en.html for more details.
1574uint32_t ATSParser::PSISection::CRC_TABLE[] = {
1575    0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
1576    0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
1577    0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
1578    0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
1579    0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
1580    0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
1581    0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
1582    0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
1583    0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
1584    0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
1585    0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
1586    0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
1587    0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
1588    0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
1589    0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
1590    0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
1591    0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
1592    0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
1593    0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
1594    0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
1595    0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
1596    0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
1597    0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
1598    0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
1599    0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
1600    0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
1601    0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
1602    0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
1603    0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
1604    0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
1605    0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
1606    0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
1607    0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
1608    0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
1609    0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
1610    0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
1611    0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
1612    0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
1613    0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
1614    0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
1615    0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
1616    0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
1617    0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
1618    0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
1619    0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
1620    0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
1621    0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
1622    0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
1623    0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
1624    0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
1625    0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
1626    0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
1627    0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
1628    0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
1629    0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
1630    0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
1631    0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
1632    0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
1633    0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
1634    0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
1635    0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
1636    0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
1637    0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
1638    0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
1639    };
1640
1641ATSParser::PSISection::PSISection() :
1642    mSkipBytes(0) {
1643}
1644
1645ATSParser::PSISection::~PSISection() {
1646}
1647
1648status_t ATSParser::PSISection::append(const void *data, size_t size) {
1649    if (mBuffer == NULL || mBuffer->size() + size > mBuffer->capacity()) {
1650        size_t newCapacity =
1651            (mBuffer == NULL) ? size : mBuffer->capacity() + size;
1652
1653        newCapacity = (newCapacity + 1023) & ~1023;
1654
1655        sp<ABuffer> newBuffer = new ABuffer(newCapacity);
1656
1657        if (mBuffer != NULL) {
1658            memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
1659            newBuffer->setRange(0, mBuffer->size());
1660        } else {
1661            newBuffer->setRange(0, 0);
1662        }
1663
1664        mBuffer = newBuffer;
1665    }
1666
1667    memcpy(mBuffer->data() + mBuffer->size(), data, size);
1668    mBuffer->setRange(0, mBuffer->size() + size);
1669
1670    return OK;
1671}
1672
1673void ATSParser::PSISection::setSkipBytes(uint8_t skip) {
1674    mSkipBytes = skip;
1675}
1676
1677void ATSParser::PSISection::clear() {
1678    if (mBuffer != NULL) {
1679        mBuffer->setRange(0, 0);
1680    }
1681    mSkipBytes = 0;
1682}
1683
1684bool ATSParser::PSISection::isComplete() const {
1685    if (mBuffer == NULL || mBuffer->size() < 3) {
1686        return false;
1687    }
1688
1689    unsigned sectionLength = U16_AT(mBuffer->data() + 1) & 0xfff;
1690    return mBuffer->size() >= sectionLength + 3;
1691}
1692
1693bool ATSParser::PSISection::isEmpty() const {
1694    return mBuffer == NULL || mBuffer->size() == 0;
1695}
1696
1697const uint8_t *ATSParser::PSISection::data() const {
1698    return mBuffer == NULL ? NULL : mBuffer->data();
1699}
1700
1701size_t ATSParser::PSISection::size() const {
1702    return mBuffer == NULL ? 0 : mBuffer->size();
1703}
1704
1705bool ATSParser::PSISection::isCRCOkay() const {
1706    if (!isComplete()) {
1707        return false;
1708    }
1709    uint8_t* data = mBuffer->data();
1710
1711    // Return true if section_syntax_indicator says no section follows the field section_length.
1712    if ((data[1] & 0x80) == 0) {
1713        return true;
1714    }
1715
1716    unsigned sectionLength = U16_AT(data + 1) & 0xfff;
1717    ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes);
1718
1719    // Skip the preceding field present when payload start indicator is on.
1720    sectionLength -= mSkipBytes;
1721
1722    uint32_t crc = 0xffffffff;
1723    for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) {
1724        uint8_t b = data[i];
1725        int index = ((crc >> 24) ^ (b & 0xff)) & 0xff;
1726        crc = CRC_TABLE[index] ^ (crc << 8);
1727    }
1728    ALOGV("crc: %08x\n", crc);
1729    return (crc == 0);
1730}
1731}  // namespace android
1732