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