ATSParser.cpp revision bc7aae4ff7e72e5bf0fa888f946835840a4357bb
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#include "ATSParser.h"
21#include "AnotherPacketSource.h"
22#include "CasManager.h"
23#include "ESQueue.h"
24#include "include/avc_utils.h"
25
26#include <android/media/IDescrambler.h>
27#include <binder/MemoryDealer.h>
28#include <media/stagefright/foundation/ABitReader.h>
29#include <media/stagefright/foundation/ABuffer.h>
30#include <media/stagefright/foundation/ADebug.h>
31#include <media/stagefright/foundation/AMessage.h>
32#include <media/stagefright/foundation/hexdump.h>
33#include <media/stagefright/MediaDefs.h>
34#include <media/stagefright/MediaErrors.h>
35#include <media/stagefright/MetaData.h>
36#include <media/stagefright/Utils.h>
37#include <media/IStreamSource.h>
38#include <utils/KeyedVector.h>
39#include <utils/Vector.h>
40
41#include <inttypes.h>
42
43namespace android {
44using binder::Status;
45using MediaDescrambler::DescrambleInfo;
46
47// I want the expression "y" evaluated even if verbose logging is off.
48#define MY_LOGV(x, y) \
49    do { unsigned tmp = y; ALOGV(x, tmp); } while (0)
50
51static const size_t kTSPacketSize = 188;
52
53struct ATSParser::Program : public RefBase {
54    Program(ATSParser *parser, unsigned programNumber, unsigned programMapPID,
55            int64_t lastRecoveredPTS);
56
57    bool parsePSISection(
58            unsigned pid, ABitReader *br, status_t *err);
59
60    // Pass to appropriate stream according to pid, and set event if it's a PES
61    // with a sync frame.
62    // Note that the method itself does not touch event.
63    bool parsePID(
64            unsigned pid, unsigned continuity_counter,
65            unsigned payload_unit_start_indicator,
66            unsigned transport_scrambling_control,
67            unsigned random_access_indicator,
68            ABitReader *br, status_t *err, SyncEvent *event);
69
70    void signalDiscontinuity(
71            DiscontinuityType type, const sp<AMessage> &extra);
72
73    void signalEOS(status_t finalResult);
74
75    sp<MediaSource> getSource(SourceType type);
76    bool hasSource(SourceType type) const;
77
78    int64_t convertPTSToTimestamp(uint64_t PTS);
79
80    bool PTSTimeDeltaEstablished() const {
81        return mFirstPTSValid;
82    }
83
84    unsigned number() const { return mProgramNumber; }
85
86    void updateProgramMapPID(unsigned programMapPID) {
87        mProgramMapPID = programMapPID;
88    }
89
90    unsigned programMapPID() const {
91        return mProgramMapPID;
92    }
93
94    uint32_t parserFlags() const {
95        return mParser->mFlags;
96    }
97
98    sp<CasManager> casManager() const {
99        return mParser->mCasManager;
100    }
101
102    uint64_t firstPTS() const {
103        return mFirstPTS;
104    }
105
106    void updateCasSessions();
107
108private:
109    struct StreamInfo {
110        unsigned mType;
111        unsigned mPID;
112        int32_t mCASystemId;
113    };
114
115    ATSParser *mParser;
116    unsigned mProgramNumber;
117    unsigned mProgramMapPID;
118    KeyedVector<unsigned, sp<Stream> > mStreams;
119    bool mFirstPTSValid;
120    uint64_t mFirstPTS;
121    int64_t mLastRecoveredPTS;
122
123    status_t parseProgramMap(ABitReader *br);
124    int64_t recoverPTS(uint64_t PTS_33bit);
125    bool findCADescriptor(
126            ABitReader *br, unsigned infoLength, CADescriptor *caDescriptor);
127    bool switchPIDs(const Vector<StreamInfo> &infos);
128
129    DISALLOW_EVIL_CONSTRUCTORS(Program);
130};
131
132struct ATSParser::Stream : public RefBase {
133    Stream(Program *program,
134           unsigned elementaryPID,
135           unsigned streamType,
136           unsigned PCR_PID,
137           int32_t CA_system_ID);
138
139    unsigned type() const { return mStreamType; }
140    unsigned pid() const { return mElementaryPID; }
141    void setPID(unsigned pid) { mElementaryPID = pid; }
142
143    void setCasInfo(
144            int32_t systemId,
145            const sp<IDescrambler> &descrambler,
146            const std::vector<uint8_t> &sessionId);
147
148    // Parse the payload and set event when PES with a sync frame is detected.
149    // This method knows when a PES starts; so record mPesStartOffsets in that
150    // case.
151    status_t parse(
152            unsigned continuity_counter,
153            unsigned payload_unit_start_indicator,
154            unsigned transport_scrambling_control,
155            unsigned random_access_indicator,
156            ABitReader *br,
157            SyncEvent *event);
158
159    void signalDiscontinuity(
160            DiscontinuityType type, const sp<AMessage> &extra);
161
162    void signalEOS(status_t finalResult);
163
164    SourceType getSourceType();
165    sp<MediaSource> getSource(SourceType type);
166
167    bool isAudio() const;
168    bool isVideo() const;
169    bool isMeta() const;
170
171protected:
172    virtual ~Stream();
173
174private:
175    struct SubSampleInfo {
176        size_t subSampleSize;
177        unsigned transport_scrambling_mode;
178        unsigned random_access_indicator;
179    };
180    Program *mProgram;
181    unsigned mElementaryPID;
182    unsigned mStreamType;
183    unsigned mPCR_PID;
184    int32_t mExpectedContinuityCounter;
185
186    sp<ABuffer> mBuffer;
187    sp<AnotherPacketSource> mSource;
188    bool mPayloadStarted;
189    bool mEOSReached;
190
191    uint64_t mPrevPTS;
192    List<off64_t> mPesStartOffsets;
193
194    ElementaryStreamQueue *mQueue;
195
196    bool mScrambled;
197    sp<IMemory> mMem;
198    sp<MemoryDealer> mDealer;
199    sp<ABuffer> mDescrambledBuffer;
200    List<SubSampleInfo> mSubSamples;
201    sp<IDescrambler> mDescrambler;
202
203    // Flush accumulated payload if necessary --- i.e. at EOS or at the start of
204    // another payload. event is set if the flushed payload is PES with a sync
205    // frame.
206    status_t flush(SyncEvent *event);
207
208    // Flush accumulated payload for scrambled streams if necessary --- i.e. at
209    // EOS or at the start of another payload. event is set if the flushed
210    // payload is PES with a sync frame.
211    status_t flushScrambled(SyncEvent *event);
212
213    // Check if a PES packet is scrambled at PES level.
214    uint32_t getPesScramblingControl(ABitReader *br, int32_t *pesOffset);
215
216    // Strip and parse PES headers and pass remaining payload into onPayload
217    // with parsed metadata. event is set if the PES contains a sync frame.
218    status_t parsePES(ABitReader *br, SyncEvent *event);
219
220    // Feed the payload into mQueue and if a packet is identified, queue it
221    // into mSource. If the packet is a sync frame. set event with start offset
222    // and timestamp of the packet.
223    void onPayloadData(
224            unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
225            unsigned PES_scrambling_control,
226            const uint8_t *data, size_t size,
227            int32_t payloadOffset, SyncEvent *event);
228
229    // Ensure internal buffers can hold specified size, and will re-allocate
230    // as needed.
231    void ensureBufferCapacity(size_t size);
232
233    DISALLOW_EVIL_CONSTRUCTORS(Stream);
234};
235
236struct ATSParser::PSISection : public RefBase {
237    PSISection();
238
239    status_t append(const void *data, size_t size);
240    void setSkipBytes(uint8_t skip);
241    void clear();
242
243    bool isComplete() const;
244    bool isEmpty() const;
245    bool isCRCOkay() const;
246
247    const uint8_t *data() const;
248    size_t size() const;
249
250protected:
251    virtual ~PSISection();
252
253private:
254    sp<ABuffer> mBuffer;
255    uint8_t mSkipBytes;
256    static uint32_t CRC_TABLE[];
257
258    DISALLOW_EVIL_CONSTRUCTORS(PSISection);
259};
260
261ATSParser::SyncEvent::SyncEvent(off64_t offset)
262    : mHasReturnedData(false), mOffset(offset), mTimeUs(0) {}
263
264void ATSParser::SyncEvent::init(off64_t offset, const sp<MediaSource> &source,
265        int64_t timeUs, SourceType type) {
266    mHasReturnedData = true;
267    mOffset = offset;
268    mMediaSource = source;
269    mTimeUs = timeUs;
270    mType = type;
271}
272
273void ATSParser::SyncEvent::reset() {
274    mHasReturnedData = false;
275}
276////////////////////////////////////////////////////////////////////////////////
277
278ATSParser::Program::Program(
279        ATSParser *parser, unsigned programNumber, unsigned programMapPID,
280        int64_t lastRecoveredPTS)
281    : mParser(parser),
282      mProgramNumber(programNumber),
283      mProgramMapPID(programMapPID),
284      mFirstPTSValid(false),
285      mFirstPTS(0),
286      mLastRecoveredPTS(lastRecoveredPTS) {
287    ALOGV("new program number %u", programNumber);
288}
289
290bool ATSParser::Program::parsePSISection(
291        unsigned pid, ABitReader *br, status_t *err) {
292    *err = OK;
293
294    if (pid != mProgramMapPID) {
295        return false;
296    }
297
298    *err = parseProgramMap(br);
299
300    return true;
301}
302
303bool ATSParser::Program::parsePID(
304        unsigned pid, unsigned continuity_counter,
305        unsigned payload_unit_start_indicator,
306        unsigned transport_scrambling_control,
307        unsigned random_access_indicator,
308        ABitReader *br, status_t *err, SyncEvent *event) {
309    *err = OK;
310
311    ssize_t index = mStreams.indexOfKey(pid);
312    if (index < 0) {
313        return false;
314    }
315
316    *err = mStreams.editValueAt(index)->parse(
317            continuity_counter,
318            payload_unit_start_indicator,
319            transport_scrambling_control,
320            random_access_indicator,
321            br, event);
322
323    return true;
324}
325
326void ATSParser::Program::signalDiscontinuity(
327        DiscontinuityType type, const sp<AMessage> &extra) {
328    int64_t mediaTimeUs;
329    if ((type & DISCONTINUITY_TIME)
330            && extra != NULL
331            && extra->findInt64(
332                IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
333        mFirstPTSValid = false;
334    }
335
336    for (size_t i = 0; i < mStreams.size(); ++i) {
337        mStreams.editValueAt(i)->signalDiscontinuity(type, extra);
338    }
339}
340
341void ATSParser::Program::signalEOS(status_t finalResult) {
342    for (size_t i = 0; i < mStreams.size(); ++i) {
343        mStreams.editValueAt(i)->signalEOS(finalResult);
344    }
345}
346
347bool ATSParser::Program::switchPIDs(const Vector<StreamInfo> &infos) {
348    bool success = false;
349
350    if (mStreams.size() == infos.size()) {
351        // build type->PIDs map for old and new mapping
352        size_t i;
353        KeyedVector<int32_t, Vector<int32_t> > oldType2PIDs, newType2PIDs;
354        for (i = 0; i < mStreams.size(); ++i) {
355            ssize_t index = oldType2PIDs.indexOfKey(mStreams[i]->type());
356            if (index < 0) {
357                oldType2PIDs.add(mStreams[i]->type(), Vector<int32_t>());
358            }
359            oldType2PIDs.editValueFor(mStreams[i]->type()).push_back(mStreams[i]->pid());
360        }
361        for (i = 0; i < infos.size(); ++i) {
362            ssize_t index = newType2PIDs.indexOfKey(infos[i].mType);
363            if (index < 0) {
364                newType2PIDs.add(infos[i].mType, Vector<int32_t>());
365            }
366            newType2PIDs.editValueFor(infos[i].mType).push_back(infos[i].mPID);
367        }
368
369        // we can recover if the number of streams for each type hasn't changed
370        if (oldType2PIDs.size() == newType2PIDs.size()) {
371            success = true;
372            for (i = 0; i < oldType2PIDs.size(); ++i) {
373                // KeyedVector is sorted, we just compare key and size of each index
374                if (oldType2PIDs.keyAt(i) != newType2PIDs.keyAt(i)
375                        || oldType2PIDs[i].size() != newType2PIDs[i].size()) {
376                     success = false;
377                     break;
378                }
379            }
380        }
381
382        if (success) {
383            // save current streams to temp
384            KeyedVector<int32_t, sp<Stream> > temp;
385            for (i = 0; i < mStreams.size(); ++i) {
386                 temp.add(mStreams.keyAt(i), mStreams.editValueAt(i));
387            }
388
389            mStreams.clear();
390            for (i = 0; i < temp.size(); ++i) {
391                // The two checks below shouldn't happen,
392                // we already checked above the stream count matches
393                ssize_t index = newType2PIDs.indexOfKey(temp[i]->type());
394                if (index < 0) {
395                    return false;
396                }
397                Vector<int32_t> &newPIDs = newType2PIDs.editValueAt(index);
398                if (newPIDs.isEmpty()) {
399                    return false;
400                }
401
402                // get the next PID for temp[i]->type() in the new PID map
403                Vector<int32_t>::iterator it = newPIDs.begin();
404
405                // change the PID of the stream, and add it back
406                temp.editValueAt(i)->setPID(*it);
407                mStreams.add(temp[i]->pid(), temp.editValueAt(i));
408
409                // removed the used PID
410                newPIDs.erase(it);
411            }
412        }
413    }
414    return success;
415}
416
417bool ATSParser::Program::findCADescriptor(
418        ABitReader *br, unsigned infoLength,
419        ATSParser::CADescriptor *caDescriptor) {
420    bool found = false;
421    while (infoLength > 2) {
422        unsigned descriptor_tag = br->getBits(8);
423        ALOGV("      tag = 0x%02x", descriptor_tag);
424
425        unsigned descriptor_length = br->getBits(8);
426        ALOGV("      len = %u", descriptor_length);
427
428        infoLength -= 2;
429        if (descriptor_length > infoLength) {
430            break;
431        }
432        if (descriptor_tag == 9 && descriptor_length >= 4) {
433            found = true;
434            caDescriptor->mSystemID = br->getBits(16);
435            caDescriptor->mPID = br->getBits(16) & 0x1fff;
436            infoLength -= 4;
437            caDescriptor->mPrivateData.assign(
438                    br->data(), br->data() + descriptor_length - 4);
439            break;
440        } else {
441            infoLength -= descriptor_length;
442            br->skipBits(descriptor_length * 8);
443        }
444    }
445    br->skipBits(infoLength * 8);
446    return found;
447}
448
449status_t ATSParser::Program::parseProgramMap(ABitReader *br) {
450    unsigned table_id = br->getBits(8);
451    ALOGV("  table_id = %u", table_id);
452    if (table_id != 0x02u) {
453        ALOGE("PMT data error!");
454        return ERROR_MALFORMED;
455    }
456    unsigned section_syntax_indicator = br->getBits(1);
457    ALOGV("  section_syntax_indicator = %u", section_syntax_indicator);
458    if (section_syntax_indicator != 1u) {
459        ALOGE("PMT data error!");
460        return ERROR_MALFORMED;
461    }
462
463    br->skipBits(1);  // '0'
464    MY_LOGV("  reserved = %u", br->getBits(2));
465
466    unsigned section_length = br->getBits(12);
467    ALOGV("  section_length = %u", section_length);
468
469    MY_LOGV("  program_number = %u", br->getBits(16));
470    MY_LOGV("  reserved = %u", br->getBits(2));
471    MY_LOGV("  version_number = %u", br->getBits(5));
472    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
473    MY_LOGV("  section_number = %u", br->getBits(8));
474    MY_LOGV("  last_section_number = %u", br->getBits(8));
475    MY_LOGV("  reserved = %u", br->getBits(3));
476
477    unsigned PCR_PID = br->getBits(13);
478    ALOGV("  PCR_PID = 0x%04x", PCR_PID);
479
480    MY_LOGV("  reserved = %u", br->getBits(4));
481
482    unsigned program_info_length = br->getBits(12);
483    ALOGV("  program_info_length = %u", program_info_length);
484
485    // descriptors
486    CADescriptor programCA;
487    bool hasProgramCA = findCADescriptor(br, program_info_length, &programCA);
488    if (hasProgramCA && !mParser->mCasManager->addProgram(
489            mProgramNumber, programCA)) {
490        return ERROR_MALFORMED;
491    }
492
493    Vector<StreamInfo> infos;
494
495    // infoBytesRemaining is the number of bytes that make up the
496    // variable length section of ES_infos. It does not include the
497    // final CRC.
498    size_t infoBytesRemaining = section_length - 9 - program_info_length - 4;
499
500    while (infoBytesRemaining >= 5) {
501
502        unsigned streamType = br->getBits(8);
503        ALOGV("    stream_type = 0x%02x", streamType);
504
505        MY_LOGV("    reserved = %u", br->getBits(3));
506
507        unsigned elementaryPID = br->getBits(13);
508        ALOGV("    elementary_PID = 0x%04x", elementaryPID);
509
510        MY_LOGV("    reserved = %u", br->getBits(4));
511
512        unsigned ES_info_length = br->getBits(12);
513        ALOGV("    ES_info_length = %u", ES_info_length);
514
515        CADescriptor streamCA;
516        bool hasStreamCA = findCADescriptor(br, ES_info_length, &streamCA);
517        if (hasStreamCA && !mParser->mCasManager->addStream(
518                mProgramNumber, elementaryPID, streamCA)) {
519            return ERROR_MALFORMED;
520        }
521        StreamInfo info;
522        info.mType = streamType;
523        info.mPID = elementaryPID;
524        info.mCASystemId = hasProgramCA ? programCA.mSystemID :
525                           hasStreamCA ? streamCA.mSystemID  : -1;
526        infos.push(info);
527
528        infoBytesRemaining -= 5 + ES_info_length;
529    }
530
531    if (infoBytesRemaining != 0) {
532        ALOGW("Section data remains unconsumed");
533    }
534    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
535
536    bool PIDsChanged = false;
537    for (size_t i = 0; i < infos.size(); ++i) {
538        StreamInfo &info = infos.editItemAt(i);
539
540        ssize_t index = mStreams.indexOfKey(info.mPID);
541
542        if (index >= 0 && mStreams.editValueAt(index)->type() != info.mType) {
543            ALOGI("uh oh. stream PIDs have changed.");
544            PIDsChanged = true;
545            break;
546        }
547    }
548
549    if (PIDsChanged) {
550#if 0
551        ALOGI("before:");
552        for (size_t i = 0; i < mStreams.size(); ++i) {
553            sp<Stream> stream = mStreams.editValueAt(i);
554
555            ALOGI("PID 0x%08x => type 0x%02x", stream->pid(), stream->type());
556        }
557
558        ALOGI("after:");
559        for (size_t i = 0; i < infos.size(); ++i) {
560            StreamInfo &info = infos.editItemAt(i);
561
562            ALOGI("PID 0x%08x => type 0x%02x", info.mPID, info.mType);
563        }
564#endif
565
566        // we can recover if number of streams for each type remain the same
567        bool success = switchPIDs(infos);
568
569        if (!success) {
570            ALOGI("Stream PIDs changed and we cannot recover.");
571            return ERROR_MALFORMED;
572        }
573    }
574
575    bool isAddingScrambledStream = false;
576    for (size_t i = 0; i < infos.size(); ++i) {
577        StreamInfo &info = infos.editItemAt(i);
578
579        if (mParser->mCasManager->isCAPid(info.mPID)) {
580            // skip CA streams (EMM/ECM)
581            continue;
582        }
583        ssize_t index = mStreams.indexOfKey(info.mPID);
584
585        if (index < 0) {
586            sp<Stream> stream = new Stream(
587                    this, info.mPID, info.mType, PCR_PID, info.mCASystemId);
588
589            isAddingScrambledStream |= info.mCASystemId >= 0;
590            mStreams.add(info.mPID, stream);
591        }
592    }
593
594    if (isAddingScrambledStream) {
595        ALOGI("Receiving scrambled streams without descrambler!");
596        return ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED;
597    }
598    return OK;
599}
600
601int64_t ATSParser::Program::recoverPTS(uint64_t PTS_33bit) {
602    // We only have the lower 33-bit of the PTS. It could overflow within a
603    // reasonable amount of time. To handle the wrap-around, use fancy math
604    // to get an extended PTS that is within [-0xffffffff, 0xffffffff]
605    // of the latest recovered PTS.
606    if (mLastRecoveredPTS < 0ll) {
607        // Use the original 33bit number for 1st frame, the reason is that
608        // if 1st frame wraps to negative that's far away from 0, we could
609        // never start. Only start wrapping around from 2nd frame.
610        mLastRecoveredPTS = static_cast<int64_t>(PTS_33bit);
611    } else {
612        mLastRecoveredPTS = static_cast<int64_t>(
613                ((mLastRecoveredPTS - static_cast<int64_t>(PTS_33bit) + 0x100000000ll)
614                & 0xfffffffe00000000ull) | PTS_33bit);
615        // We start from 0, but recovered PTS could be slightly below 0.
616        // Clamp it to 0 as rest of the pipeline doesn't take negative pts.
617        // (eg. video is read first and starts at 0, but audio starts at 0xfffffff0)
618        if (mLastRecoveredPTS < 0ll) {
619            ALOGI("Clamping negative recovered PTS (%" PRId64 ") to 0", mLastRecoveredPTS);
620            mLastRecoveredPTS = 0ll;
621        }
622    }
623
624    return mLastRecoveredPTS;
625}
626
627sp<MediaSource> ATSParser::Program::getSource(SourceType type) {
628    for (size_t i = 0; i < mStreams.size(); ++i) {
629        sp<MediaSource> source = mStreams.editValueAt(i)->getSource(type);
630        if (source != NULL) {
631            return source;
632        }
633    }
634
635    return NULL;
636}
637
638bool ATSParser::Program::hasSource(SourceType type) const {
639    for (size_t i = 0; i < mStreams.size(); ++i) {
640        const sp<Stream> &stream = mStreams.valueAt(i);
641        if (type == AUDIO && stream->isAudio()) {
642            return true;
643        } else if (type == VIDEO && stream->isVideo()) {
644            return true;
645        } else if (type == META && stream->isMeta()) {
646            return true;
647        }
648    }
649
650    return false;
651}
652
653int64_t ATSParser::Program::convertPTSToTimestamp(uint64_t PTS) {
654    PTS = recoverPTS(PTS);
655
656    if (!(mParser->mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)) {
657        if (!mFirstPTSValid) {
658            mFirstPTSValid = true;
659            mFirstPTS = PTS;
660            PTS = 0;
661        } else if (PTS < mFirstPTS) {
662            PTS = 0;
663        } else {
664            PTS -= mFirstPTS;
665        }
666    }
667
668    int64_t timeUs = (PTS * 100) / 9;
669
670    if (mParser->mAbsoluteTimeAnchorUs >= 0ll) {
671        timeUs += mParser->mAbsoluteTimeAnchorUs;
672    }
673
674    if (mParser->mTimeOffsetValid) {
675        timeUs += mParser->mTimeOffsetUs;
676    }
677
678    return timeUs;
679}
680
681void ATSParser::Program::updateCasSessions() {
682    for (size_t i = 0; i < mStreams.size(); ++i) {
683        sp<Stream> &stream = mStreams.editValueAt(i);
684        sp<IDescrambler> descrambler;
685        std::vector<uint8_t> sessionId;
686        int32_t systemId;
687        if (mParser->mCasManager->getCasInfo(mProgramNumber, stream->pid(),
688                &systemId, &descrambler, &sessionId)) {
689            stream->setCasInfo(systemId, descrambler, sessionId);
690        }
691    }
692}
693
694////////////////////////////////////////////////////////////////////////////////
695static const size_t kInitialStreamBufferSize = 192 * 1024;
696
697ATSParser::Stream::Stream(
698        Program *program,
699        unsigned elementaryPID,
700        unsigned streamType,
701        unsigned PCR_PID,
702        int32_t CA_system_ID)
703    : mProgram(program),
704      mElementaryPID(elementaryPID),
705      mStreamType(streamType),
706      mPCR_PID(PCR_PID),
707      mExpectedContinuityCounter(-1),
708      mPayloadStarted(false),
709      mEOSReached(false),
710      mPrevPTS(0),
711      mQueue(NULL),
712      mScrambled(CA_system_ID >= 0) {
713    ALOGV("new stream PID 0x%02x, type 0x%02x, scrambled %d",
714            elementaryPID, streamType, mScrambled);
715
716    uint32_t flags = (isVideo() && mScrambled) ?
717            ElementaryStreamQueue::kFlag_ScrambledData : 0;
718
719    ElementaryStreamQueue::Mode mode = ElementaryStreamQueue::INVALID;
720
721    switch (mStreamType) {
722        case STREAMTYPE_H264:
723            mode = ElementaryStreamQueue::H264;
724            flags |= (mProgram->parserFlags() & ALIGNED_VIDEO_DATA) ?
725                    ElementaryStreamQueue::kFlag_AlignedData : 0;
726            break;
727
728        case STREAMTYPE_MPEG2_AUDIO_ADTS:
729            mode = ElementaryStreamQueue::AAC;
730            break;
731
732        case STREAMTYPE_MPEG1_AUDIO:
733        case STREAMTYPE_MPEG2_AUDIO:
734            mode = ElementaryStreamQueue::MPEG_AUDIO;
735            break;
736
737        case STREAMTYPE_MPEG1_VIDEO:
738        case STREAMTYPE_MPEG2_VIDEO:
739            mode = ElementaryStreamQueue::MPEG_VIDEO;
740            break;
741
742        case STREAMTYPE_MPEG4_VIDEO:
743            mode = ElementaryStreamQueue::MPEG4_VIDEO;
744            break;
745
746        case STREAMTYPE_LPCM_AC3:
747        case STREAMTYPE_AC3:
748            mode = ElementaryStreamQueue::AC3;
749            break;
750
751        case STREAMTYPE_METADATA:
752            mode = ElementaryStreamQueue::METADATA;
753            break;
754
755        default:
756            ALOGE("stream PID 0x%02x has invalid stream type 0x%02x",
757                    elementaryPID, streamType);
758            return;
759    }
760
761    mQueue = new ElementaryStreamQueue(mode, flags);
762
763    if (mQueue != NULL) {
764        ensureBufferCapacity(kInitialStreamBufferSize);
765
766        if (mScrambled && (isAudio() || isVideo())) {
767            // Set initial format to scrambled
768            sp<MetaData> meta = new MetaData();
769            meta->setCString(kKeyMIMEType,
770                    isAudio() ? MEDIA_MIMETYPE_AUDIO_SCRAMBLED
771                              : MEDIA_MIMETYPE_VIDEO_SCRAMBLED);
772            // for MediaExtractor.CasInfo
773            meta->setInt32(kKeyCASystemID, CA_system_ID);
774            mSource = new AnotherPacketSource(meta);
775        }
776    }
777}
778
779ATSParser::Stream::~Stream() {
780    delete mQueue;
781    mQueue = NULL;
782}
783
784void ATSParser::Stream::ensureBufferCapacity(size_t neededSize) {
785    if (mBuffer != NULL && mBuffer->capacity() >= neededSize) {
786        return;
787    }
788
789    ALOGV("ensureBufferCapacity: current size %zu, new size %zu, scrambled %d",
790            mBuffer == NULL ? 0 : mBuffer->capacity(), neededSize, mScrambled);
791
792    sp<ABuffer> newBuffer, newScrambledBuffer;
793    sp<IMemory> newMem;
794    sp<MemoryDealer> newDealer;
795    if (mScrambled) {
796        size_t alignment = MemoryDealer::getAllocationAlignment();
797        neededSize = (neededSize + (alignment - 1)) & ~(alignment - 1);
798        // Align to multiples of 64K.
799        neededSize = (neededSize + 65535) & ~65535;
800        newDealer = new MemoryDealer(neededSize, "ATSParser");
801        newMem = newDealer->allocate(neededSize);
802        newScrambledBuffer = new ABuffer(newMem->pointer(), newMem->size());
803
804        if (mDescrambledBuffer != NULL) {
805            memcpy(newScrambledBuffer->data(),
806                    mDescrambledBuffer->data(), mDescrambledBuffer->size());
807            newScrambledBuffer->setRange(0, mDescrambledBuffer->size());
808        } else {
809            newScrambledBuffer->setRange(0, 0);
810        }
811        mMem = newMem;
812        mDealer = newDealer;
813        mDescrambledBuffer = newScrambledBuffer;
814    } else {
815        // Align to multiples of 64K.
816        neededSize = (neededSize + 65535) & ~65535;
817    }
818
819    newBuffer = new ABuffer(neededSize);
820    if (mBuffer != NULL) {
821        memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
822        newBuffer->setRange(0, mBuffer->size());
823    } else {
824        newBuffer->setRange(0, 0);
825    }
826    mBuffer = newBuffer;
827}
828
829status_t ATSParser::Stream::parse(
830        unsigned continuity_counter,
831        unsigned payload_unit_start_indicator,
832        unsigned transport_scrambling_control,
833        unsigned random_access_indicator,
834        ABitReader *br, SyncEvent *event) {
835    if (mQueue == NULL) {
836        return OK;
837    }
838
839    if (mExpectedContinuityCounter >= 0
840            && (unsigned)mExpectedContinuityCounter != continuity_counter) {
841        ALOGI("discontinuity on stream pid 0x%04x", mElementaryPID);
842
843        mPayloadStarted = false;
844        mPesStartOffsets.clear();
845        mBuffer->setRange(0, 0);
846        mSubSamples.clear();
847        mExpectedContinuityCounter = -1;
848
849#if 0
850        // Uncomment this if you'd rather see no corruption whatsoever on
851        // screen and suspend updates until we come across another IDR frame.
852
853        if (mStreamType == STREAMTYPE_H264) {
854            ALOGI("clearing video queue");
855            mQueue->clear(true /* clearFormat */);
856        }
857#endif
858
859        if (!payload_unit_start_indicator) {
860            return OK;
861        }
862    }
863
864    mExpectedContinuityCounter = (continuity_counter + 1) & 0x0f;
865
866    if (payload_unit_start_indicator) {
867        off64_t offset = (event != NULL) ? event->getOffset() : 0;
868        if (mPayloadStarted) {
869            // Otherwise we run the danger of receiving the trailing bytes
870            // of a PES packet that we never saw the start of and assuming
871            // we have a a complete PES packet.
872
873            status_t err = flush(event);
874
875            if (err != OK) {
876                ALOGW("Error (%08x) happened while flushing; we simply discard "
877                      "the PES packet and continue.", err);
878            }
879        }
880
881        mPayloadStarted = true;
882        // There should be at most 2 elements in |mPesStartOffsets|.
883        while (mPesStartOffsets.size() >= 2) {
884            mPesStartOffsets.erase(mPesStartOffsets.begin());
885        }
886        mPesStartOffsets.push_back(offset);
887    }
888
889    if (!mPayloadStarted) {
890        return OK;
891    }
892
893    size_t payloadSizeBits = br->numBitsLeft();
894    if (payloadSizeBits % 8 != 0u) {
895        ALOGE("Wrong value");
896        return BAD_VALUE;
897    }
898
899    size_t neededSize = mBuffer->size() + payloadSizeBits / 8;
900    ensureBufferCapacity(neededSize);
901
902    memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
903    mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
904
905    if (mScrambled) {
906        mSubSamples.push_back({payloadSizeBits / 8,
907                 transport_scrambling_control, random_access_indicator});
908    }
909
910    return OK;
911}
912
913bool ATSParser::Stream::isVideo() const {
914    switch (mStreamType) {
915        case STREAMTYPE_H264:
916        case STREAMTYPE_MPEG1_VIDEO:
917        case STREAMTYPE_MPEG2_VIDEO:
918        case STREAMTYPE_MPEG4_VIDEO:
919            return true;
920
921        default:
922            return false;
923    }
924}
925
926bool ATSParser::Stream::isAudio() const {
927    switch (mStreamType) {
928        case STREAMTYPE_MPEG1_AUDIO:
929        case STREAMTYPE_MPEG2_AUDIO:
930        case STREAMTYPE_MPEG2_AUDIO_ADTS:
931        case STREAMTYPE_LPCM_AC3:
932        case STREAMTYPE_AC3:
933            return true;
934
935        default:
936            return false;
937    }
938}
939
940bool ATSParser::Stream::isMeta() const {
941    if (mStreamType == STREAMTYPE_METADATA) {
942        return true;
943    }
944    return false;
945}
946
947void ATSParser::Stream::signalDiscontinuity(
948        DiscontinuityType type, const sp<AMessage> &extra) {
949    mExpectedContinuityCounter = -1;
950
951    if (mQueue == NULL) {
952        return;
953    }
954
955    mPayloadStarted = false;
956    mPesStartOffsets.clear();
957    mEOSReached = false;
958    mBuffer->setRange(0, 0);
959    mSubSamples.clear();
960
961    bool clearFormat = false;
962    if (isAudio()) {
963        if (type & DISCONTINUITY_AUDIO_FORMAT) {
964            clearFormat = true;
965        }
966    } else {
967        if (type & DISCONTINUITY_VIDEO_FORMAT) {
968            clearFormat = true;
969        }
970    }
971
972    mQueue->clear(clearFormat);
973
974    if (type & DISCONTINUITY_TIME) {
975        uint64_t resumeAtPTS;
976        if (extra != NULL
977                && extra->findInt64(
978                    IStreamListener::kKeyResumeAtPTS,
979                    (int64_t *)&resumeAtPTS)) {
980            int64_t resumeAtMediaTimeUs =
981                mProgram->convertPTSToTimestamp(resumeAtPTS);
982
983            extra->setInt64("resume-at-mediaTimeUs", resumeAtMediaTimeUs);
984        }
985    }
986
987    if (mSource != NULL) {
988        sp<MetaData> meta = mSource->getFormat();
989        const char* mime;
990        if (clearFormat && meta != NULL && meta->findCString(kKeyMIMEType, &mime)
991                && (!strncasecmp(mime, MEDIA_MIMETYPE_AUDIO_SCRAMBLED, 15)
992                 || !strncasecmp(mime, MEDIA_MIMETYPE_VIDEO_SCRAMBLED, 15))){
993            mSource->clear();
994        } else {
995            mSource->queueDiscontinuity(type, extra, true);
996        }
997    }
998}
999
1000void ATSParser::Stream::signalEOS(status_t finalResult) {
1001    if (mSource != NULL) {
1002        mSource->signalEOS(finalResult);
1003    }
1004    mEOSReached = true;
1005    flush(NULL);
1006}
1007
1008status_t ATSParser::Stream::parsePES(ABitReader *br, SyncEvent *event) {
1009    const uint8_t *basePtr = br->data();
1010
1011    unsigned packet_startcode_prefix = br->getBits(24);
1012
1013    ALOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
1014
1015    if (packet_startcode_prefix != 1) {
1016        ALOGV("Supposedly payload_unit_start=1 unit does not start "
1017             "with startcode.");
1018
1019        return ERROR_MALFORMED;
1020    }
1021
1022    unsigned stream_id = br->getBits(8);
1023    ALOGV("stream_id = 0x%02x", stream_id);
1024
1025    unsigned PES_packet_length = br->getBits(16);
1026    ALOGV("PES_packet_length = %u", PES_packet_length);
1027
1028    if (stream_id != 0xbc  // program_stream_map
1029            && stream_id != 0xbe  // padding_stream
1030            && stream_id != 0xbf  // private_stream_2
1031            && stream_id != 0xf0  // ECM
1032            && stream_id != 0xf1  // EMM
1033            && stream_id != 0xff  // program_stream_directory
1034            && stream_id != 0xf2  // DSMCC
1035            && stream_id != 0xf8) {  // H.222.1 type E
1036        if (br->getBits(2) != 2u) {
1037            return ERROR_MALFORMED;
1038        }
1039
1040        unsigned PES_scrambling_control = br->getBits(2);
1041        ALOGV("PES_scrambling_control = %u", PES_scrambling_control);
1042
1043        MY_LOGV("PES_priority = %u", br->getBits(1));
1044        MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
1045        MY_LOGV("copyright = %u", br->getBits(1));
1046        MY_LOGV("original_or_copy = %u", br->getBits(1));
1047
1048        unsigned PTS_DTS_flags = br->getBits(2);
1049        ALOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
1050
1051        unsigned ESCR_flag = br->getBits(1);
1052        ALOGV("ESCR_flag = %u", ESCR_flag);
1053
1054        unsigned ES_rate_flag = br->getBits(1);
1055        ALOGV("ES_rate_flag = %u", ES_rate_flag);
1056
1057        unsigned DSM_trick_mode_flag = br->getBits(1);
1058        ALOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
1059
1060        unsigned additional_copy_info_flag = br->getBits(1);
1061        ALOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
1062
1063        MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
1064        MY_LOGV("PES_extension_flag = %u", br->getBits(1));
1065
1066        unsigned PES_header_data_length = br->getBits(8);
1067        ALOGV("PES_header_data_length = %u", PES_header_data_length);
1068
1069        unsigned optional_bytes_remaining = PES_header_data_length;
1070
1071        uint64_t PTS = 0, DTS = 0;
1072
1073        if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
1074            if (optional_bytes_remaining < 5u) {
1075                return ERROR_MALFORMED;
1076            }
1077
1078            if (br->getBits(4) != PTS_DTS_flags) {
1079                return ERROR_MALFORMED;
1080            }
1081            PTS = ((uint64_t)br->getBits(3)) << 30;
1082            if (br->getBits(1) != 1u) {
1083                return ERROR_MALFORMED;
1084            }
1085            PTS |= ((uint64_t)br->getBits(15)) << 15;
1086            if (br->getBits(1) != 1u) {
1087                return ERROR_MALFORMED;
1088            }
1089            PTS |= br->getBits(15);
1090            if (br->getBits(1) != 1u) {
1091                return ERROR_MALFORMED;
1092            }
1093
1094            ALOGV("PTS = 0x%016" PRIx64 " (%.2f)", PTS, PTS / 90000.0);
1095
1096            optional_bytes_remaining -= 5;
1097
1098            if (PTS_DTS_flags == 3) {
1099                if (optional_bytes_remaining < 5u) {
1100                    return ERROR_MALFORMED;
1101                }
1102
1103                if (br->getBits(4) != 1u) {
1104                    return ERROR_MALFORMED;
1105                }
1106
1107                DTS = ((uint64_t)br->getBits(3)) << 30;
1108                if (br->getBits(1) != 1u) {
1109                    return ERROR_MALFORMED;
1110                }
1111                DTS |= ((uint64_t)br->getBits(15)) << 15;
1112                if (br->getBits(1) != 1u) {
1113                    return ERROR_MALFORMED;
1114                }
1115                DTS |= br->getBits(15);
1116                if (br->getBits(1) != 1u) {
1117                    return ERROR_MALFORMED;
1118                }
1119
1120                ALOGV("DTS = %" PRIu64, DTS);
1121
1122                optional_bytes_remaining -= 5;
1123            }
1124        }
1125
1126        if (ESCR_flag) {
1127            if (optional_bytes_remaining < 6u) {
1128                return ERROR_MALFORMED;
1129            }
1130
1131            br->getBits(2);
1132
1133            uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
1134            if (br->getBits(1) != 1u) {
1135                return ERROR_MALFORMED;
1136            }
1137            ESCR |= ((uint64_t)br->getBits(15)) << 15;
1138            if (br->getBits(1) != 1u) {
1139                return ERROR_MALFORMED;
1140            }
1141            ESCR |= br->getBits(15);
1142            if (br->getBits(1) != 1u) {
1143                return ERROR_MALFORMED;
1144            }
1145
1146            ALOGV("ESCR = %" PRIu64, ESCR);
1147            MY_LOGV("ESCR_extension = %u", br->getBits(9));
1148
1149            if (br->getBits(1) != 1u) {
1150                return ERROR_MALFORMED;
1151            }
1152
1153            optional_bytes_remaining -= 6;
1154        }
1155
1156        if (ES_rate_flag) {
1157            if (optional_bytes_remaining < 3u) {
1158                return ERROR_MALFORMED;
1159            }
1160
1161            if (br->getBits(1) != 1u) {
1162                return ERROR_MALFORMED;
1163            }
1164            MY_LOGV("ES_rate = %u", br->getBits(22));
1165            if (br->getBits(1) != 1u) {
1166                return ERROR_MALFORMED;
1167            }
1168
1169            optional_bytes_remaining -= 3;
1170        }
1171
1172        br->skipBits(optional_bytes_remaining * 8);
1173
1174        // ES data follows.
1175        int32_t pesOffset = br->data() - basePtr;
1176
1177        if (PES_packet_length != 0) {
1178            if (PES_packet_length < PES_header_data_length + 3) {
1179                return ERROR_MALFORMED;
1180            }
1181
1182            unsigned dataLength =
1183                PES_packet_length - 3 - PES_header_data_length;
1184
1185            if (br->numBitsLeft() < dataLength * 8) {
1186                ALOGE("PES packet does not carry enough data to contain "
1187                     "payload. (numBitsLeft = %zu, required = %u)",
1188                     br->numBitsLeft(), dataLength * 8);
1189
1190                return ERROR_MALFORMED;
1191            }
1192
1193            ALOGV("There's %u bytes of payload, PES_packet_length=%u, offset=%d",
1194                    dataLength, PES_packet_length, pesOffset);
1195
1196            onPayloadData(
1197                    PTS_DTS_flags, PTS, DTS, PES_scrambling_control,
1198                    br->data(), dataLength, pesOffset, event);
1199
1200            br->skipBits(dataLength * 8);
1201        } else {
1202            onPayloadData(
1203                    PTS_DTS_flags, PTS, DTS, PES_scrambling_control,
1204                    br->data(), br->numBitsLeft() / 8, pesOffset, event);
1205
1206            size_t payloadSizeBits = br->numBitsLeft();
1207            if (payloadSizeBits % 8 != 0u) {
1208                return ERROR_MALFORMED;
1209            }
1210
1211            ALOGV("There's %zu bytes of payload, offset=%d",
1212                    payloadSizeBits / 8, pesOffset);
1213        }
1214    } else if (stream_id == 0xbe) {  // padding_stream
1215        if (PES_packet_length == 0u) {
1216            return ERROR_MALFORMED;
1217        }
1218        br->skipBits(PES_packet_length * 8);
1219    } else {
1220        if (PES_packet_length == 0u) {
1221            return ERROR_MALFORMED;
1222        }
1223        br->skipBits(PES_packet_length * 8);
1224    }
1225
1226    return OK;
1227}
1228
1229uint32_t ATSParser::Stream::getPesScramblingControl(
1230        ABitReader *br, int32_t *pesOffset) {
1231    unsigned packet_startcode_prefix = br->getBits(24);
1232
1233    ALOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
1234
1235    if (packet_startcode_prefix != 1) {
1236        ALOGV("unit does not start with startcode.");
1237        return 0;
1238    }
1239
1240    if (br->numBitsLeft() < 48) {
1241        return 0;
1242    }
1243
1244    unsigned stream_id = br->getBits(8);
1245    ALOGV("stream_id = 0x%02x", stream_id);
1246
1247    br->skipBits(16); // PES_packet_length
1248
1249    if (stream_id != 0xbc  // program_stream_map
1250            && stream_id != 0xbe  // padding_stream
1251            && stream_id != 0xbf  // private_stream_2
1252            && stream_id != 0xf0  // ECM
1253            && stream_id != 0xf1  // EMM
1254            && stream_id != 0xff  // program_stream_directory
1255            && stream_id != 0xf2  // DSMCC
1256            && stream_id != 0xf8) {  // H.222.1 type E
1257        if (br->getBits(2) != 2u) {
1258            return 0;
1259        }
1260
1261        unsigned PES_scrambling_control = br->getBits(2);
1262        ALOGV("PES_scrambling_control = %u", PES_scrambling_control);
1263
1264        if (PES_scrambling_control == 0) {
1265            return 0;
1266        }
1267
1268        br->skipBits(12); // don't care
1269
1270        unsigned PES_header_data_length = br->getBits(8);
1271        ALOGV("PES_header_data_length = %u", PES_header_data_length);
1272
1273        if (PES_header_data_length * 8 > br->numBitsLeft()) {
1274            return 0;
1275        }
1276
1277        *pesOffset = 9 + PES_header_data_length;
1278        ALOGD("found PES_scrambling_control=%d, PES offset=%d",
1279                PES_scrambling_control, *pesOffset);
1280        return PES_scrambling_control;
1281    }
1282
1283    return 0;
1284}
1285
1286status_t ATSParser::Stream::flushScrambled(SyncEvent *event) {
1287    if (mDescrambler == NULL) {
1288        ALOGE("received scrambled packets without descrambler!");
1289        return UNKNOWN_ERROR;
1290    }
1291
1292    if (mDescrambledBuffer == NULL || mMem == NULL) {
1293        ALOGE("received scrambled packets without shared memory!");
1294
1295        return UNKNOWN_ERROR;
1296    }
1297
1298    int32_t pesOffset = 0;
1299    int32_t descrambleSubSamples = 0, descrambleBytes = 0;
1300    uint32_t tsScramblingControl = 0, pesScramblingControl = 0;
1301
1302    // First, go over subsamples to find TS-level scrambling key id, and
1303    // calculate how many subsample we need to descramble (assuming we don't
1304    // have PES-level scrambling).
1305    for (auto it = mSubSamples.begin(); it != mSubSamples.end(); it++) {
1306        if (it->transport_scrambling_mode != 0) {
1307            // TODO: handle keyId change, use the first non-zero keyId for now.
1308            if (tsScramblingControl == 0) {
1309                tsScramblingControl = it->transport_scrambling_mode;
1310            }
1311        }
1312        if (tsScramblingControl == 0 || descrambleSubSamples == 0
1313                || !mQueue->isScrambled()) {
1314            descrambleSubSamples++;
1315            descrambleBytes += it->subSampleSize;
1316        }
1317    }
1318    // If not scrambled at TS-level, check PES-level scrambling
1319    if (tsScramblingControl == 0) {
1320        ABitReader br(mBuffer->data(), mBuffer->size());
1321        pesScramblingControl = getPesScramblingControl(&br, &pesOffset);
1322        // If not scrambled at PES-level either, or scrambled at PES-level but
1323        // requires output to remain scrambled, we don't need to descramble
1324        // anything.
1325        if (pesScramblingControl == 0 || mQueue->isScrambled()) {
1326            descrambleSubSamples = 0;
1327            descrambleBytes = 0;
1328        }
1329    }
1330
1331    uint32_t sctrl = tsScramblingControl != 0 ?
1332            tsScramblingControl : pesScramblingControl;
1333
1334    // Perform the 1st pass descrambling if needed
1335    if (descrambleBytes > 0) {
1336        memcpy(mDescrambledBuffer->data(), mBuffer->data(), descrambleBytes);
1337        mDescrambledBuffer->setRange(0, descrambleBytes);
1338
1339        sp<ABuffer> subSamples = new ABuffer(
1340                sizeof(DescramblerPlugin::SubSample) * descrambleSubSamples);
1341
1342        DescrambleInfo info;
1343        info.dstType = DescrambleInfo::kDestinationTypeVmPointer;
1344        info.scramblingControl = (DescramblerPlugin::ScramblingControl)sctrl;
1345        info.numSubSamples = descrambleSubSamples;
1346        info.subSamples = (DescramblerPlugin::SubSample *)subSamples->data();
1347        info.srcMem = mMem;
1348        info.srcOffset = 0;
1349        info.dstPtr = NULL; // in-place descrambling into srcMem
1350        info.dstOffset = 0;
1351
1352        int32_t i = 0;
1353        for (auto it = mSubSamples.begin();
1354                it != mSubSamples.end() && i < descrambleSubSamples; it++, i++) {
1355            if (it->transport_scrambling_mode != 0 || pesScramblingControl != 0) {
1356                info.subSamples[i].mNumBytesOfClearData = 0;
1357                info.subSamples[i].mNumBytesOfEncryptedData = it->subSampleSize;
1358            } else {
1359                info.subSamples[i].mNumBytesOfClearData = it->subSampleSize;
1360                info.subSamples[i].mNumBytesOfEncryptedData = 0;
1361            }
1362        }
1363        // If scrambled at PES-level, PES header should be skipped
1364        if (pesScramblingControl != 0) {
1365            info.srcOffset = info.dstOffset = pesOffset;
1366            info.subSamples[0].mNumBytesOfEncryptedData -= pesOffset;
1367        }
1368
1369        int32_t result;
1370        Status status = mDescrambler->descramble(info, &result);
1371
1372        if (!status.isOk()) {
1373            ALOGE("[stream %d] descramble failed, exceptionCode=%d",
1374                    mElementaryPID, status.exceptionCode());
1375            return UNKNOWN_ERROR;
1376        }
1377
1378        ALOGV("[stream %d] descramble succeeded, %d bytes",
1379                mElementaryPID, result);
1380        memcpy(mBuffer->data(), mDescrambledBuffer->data(), descrambleBytes);
1381    }
1382
1383    if (mQueue->isScrambled()) {
1384        // Queue subSample info for scrambled queue
1385        sp<ABuffer> clearSizesBuffer = new ABuffer(mSubSamples.size() * 4);
1386        sp<ABuffer> encSizesBuffer = new ABuffer(mSubSamples.size() * 4);
1387        int32_t *clearSizePtr = (int32_t*)clearSizesBuffer->data();
1388        int32_t *encSizePtr = (int32_t*)encSizesBuffer->data();
1389        int32_t isSync = 0;
1390        int32_t i = 0;
1391        for (auto it = mSubSamples.begin();
1392                it != mSubSamples.end(); it++, i++) {
1393            if ((it->transport_scrambling_mode == 0
1394                    && pesScramblingControl == 0)
1395                    || i < descrambleSubSamples) {
1396                clearSizePtr[i] = it->subSampleSize;
1397                encSizePtr[i] = 0;
1398            } else {
1399                clearSizePtr[i] = 0;
1400                encSizePtr[i] = it->subSampleSize;
1401            }
1402            isSync |= it->random_access_indicator;
1403        }
1404        // Pass the original TS subsample size now. The PES header adjust
1405        // will be applied when the scrambled AU is dequeued.
1406        mQueue->appendScrambledData(
1407                mBuffer->data(), mBuffer->size(), sctrl,
1408                isSync, clearSizesBuffer, encSizesBuffer);
1409    }
1410
1411    ABitReader br(mBuffer->data(), mBuffer->size());
1412    status_t err = parsePES(&br, event);
1413
1414    if (err != OK) {
1415        ALOGE("[stream %d] failed to parse descrambled PES, err=%d",
1416                mElementaryPID, err);
1417    }
1418
1419    return err;
1420}
1421
1422
1423status_t ATSParser::Stream::flush(SyncEvent *event) {
1424    if (mBuffer == NULL || mBuffer->size() == 0) {
1425        return OK;
1426    }
1427
1428    ALOGV("flushing stream 0x%04x size = %zu", mElementaryPID, mBuffer->size());
1429
1430    status_t err = OK;
1431    if (mScrambled) {
1432        err = flushScrambled(event);
1433        mSubSamples.clear();
1434    } else {
1435        ABitReader br(mBuffer->data(), mBuffer->size());
1436        err = parsePES(&br, event);
1437    }
1438
1439    mBuffer->setRange(0, 0);
1440
1441    return err;
1442}
1443
1444void ATSParser::Stream::onPayloadData(
1445        unsigned PTS_DTS_flags, uint64_t PTS, uint64_t /* DTS */,
1446        unsigned PES_scrambling_control,
1447        const uint8_t *data, size_t size,
1448        int32_t payloadOffset, SyncEvent *event) {
1449#if 0
1450    ALOGI("payload streamType 0x%02x, PTS = 0x%016llx, dPTS = %lld",
1451          mStreamType,
1452          PTS,
1453          (int64_t)PTS - mPrevPTS);
1454    mPrevPTS = PTS;
1455#endif
1456
1457    ALOGV("onPayloadData mStreamType=0x%02x", mStreamType);
1458
1459    int64_t timeUs = 0ll;  // no presentation timestamp available.
1460    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
1461        timeUs = mProgram->convertPTSToTimestamp(PTS);
1462    }
1463
1464    status_t err = mQueue->appendData(
1465            data, size, timeUs, payloadOffset, PES_scrambling_control);
1466
1467    if (mEOSReached) {
1468        mQueue->signalEOS();
1469    }
1470
1471    if (err != OK) {
1472        return;
1473    }
1474
1475    sp<ABuffer> accessUnit;
1476    bool found = false;
1477    while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
1478        if (mSource == NULL) {
1479            sp<MetaData> meta = mQueue->getFormat();
1480
1481            if (meta != NULL) {
1482                ALOGV("Stream PID 0x%08x of type 0x%02x now has data.",
1483                     mElementaryPID, mStreamType);
1484
1485                const char *mime;
1486                if (meta->findCString(kKeyMIMEType, &mime)
1487                        && !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
1488                    int32_t sync = 0;
1489                    if (!accessUnit->meta()->findInt32("isSync", &sync) || !sync) {
1490                        continue;
1491                    }
1492                }
1493                mSource = new AnotherPacketSource(meta);
1494                mSource->queueAccessUnit(accessUnit);
1495            }
1496        } else if (mQueue->getFormat() != NULL) {
1497            // After a discontinuity we invalidate the queue's format
1498            // and won't enqueue any access units to the source until
1499            // the queue has reestablished the new format.
1500
1501            if (mSource->getFormat() == NULL) {
1502                mSource->setFormat(mQueue->getFormat());
1503            }
1504            mSource->queueAccessUnit(accessUnit);
1505        }
1506
1507        // Every access unit has a pesStartOffset queued in |mPesStartOffsets|.
1508        off64_t pesStartOffset = -1;
1509        if (!mPesStartOffsets.empty()) {
1510            pesStartOffset = *mPesStartOffsets.begin();
1511            mPesStartOffsets.erase(mPesStartOffsets.begin());
1512        }
1513
1514        if (pesStartOffset >= 0 && (event != NULL) && !found && mQueue->getFormat() != NULL) {
1515            int32_t sync = 0;
1516            if (accessUnit->meta()->findInt32("isSync", &sync) && sync) {
1517                int64_t timeUs;
1518                if (accessUnit->meta()->findInt64("timeUs", &timeUs)) {
1519                    found = true;
1520                    event->init(pesStartOffset, mSource, timeUs, getSourceType());
1521                }
1522            }
1523        }
1524    }
1525}
1526
1527ATSParser::SourceType ATSParser::Stream::getSourceType() {
1528    if (isVideo()) {
1529        return VIDEO;
1530    } else if (isAudio()) {
1531        return AUDIO;
1532    } else if (isMeta()) {
1533        return META;
1534    }
1535    return NUM_SOURCE_TYPES;
1536}
1537
1538sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
1539    switch (type) {
1540        case VIDEO:
1541        {
1542            if (isVideo()) {
1543                return mSource;
1544            }
1545            break;
1546        }
1547
1548        case AUDIO:
1549        {
1550            if (isAudio()) {
1551                return mSource;
1552            }
1553            break;
1554        }
1555
1556        case META:
1557        {
1558            if (isMeta()) {
1559                return mSource;
1560            }
1561            break;
1562        }
1563
1564        default:
1565            break;
1566    }
1567
1568    return NULL;
1569}
1570
1571void ATSParser::Stream::setCasInfo(
1572        int32_t systemId, const sp<IDescrambler> &descrambler,
1573        const std::vector<uint8_t> &sessionId) {
1574    if (mSource != NULL && mDescrambler == NULL && descrambler != NULL) {
1575        signalDiscontinuity(DISCONTINUITY_FORMAT_ONLY, NULL);
1576        mDescrambler = descrambler;
1577        if (mQueue->isScrambled()) {
1578            mQueue->setCasInfo(systemId, sessionId);
1579        }
1580    }
1581}
1582
1583////////////////////////////////////////////////////////////////////////////////
1584
1585ATSParser::ATSParser(uint32_t flags)
1586    : mFlags(flags),
1587      mAbsoluteTimeAnchorUs(-1ll),
1588      mTimeOffsetValid(false),
1589      mTimeOffsetUs(0ll),
1590      mLastRecoveredPTS(-1ll),
1591      mNumTSPacketsParsed(0),
1592      mNumPCRs(0) {
1593    mPSISections.add(0 /* PID */, new PSISection);
1594    mCasManager = new CasManager();
1595}
1596
1597ATSParser::~ATSParser() {
1598}
1599
1600status_t ATSParser::feedTSPacket(const void *data, size_t size,
1601        SyncEvent *event) {
1602    if (size != kTSPacketSize) {
1603        ALOGE("Wrong TS packet size");
1604        return BAD_VALUE;
1605    }
1606
1607    ABitReader br((const uint8_t *)data, kTSPacketSize);
1608    return parseTS(&br, event);
1609}
1610
1611status_t ATSParser::setMediaCas(const sp<ICas> &cas) {
1612    status_t err = mCasManager->setMediaCas(cas);
1613    if (err != OK) {
1614        return err;
1615    }
1616    for (size_t i = 0; i < mPrograms.size(); ++i) {
1617        mPrograms.editItemAt(i)->updateCasSessions();
1618    }
1619    return OK;
1620}
1621
1622void ATSParser::signalDiscontinuity(
1623        DiscontinuityType type, const sp<AMessage> &extra) {
1624    int64_t mediaTimeUs;
1625    if ((type & DISCONTINUITY_TIME) && extra != NULL) {
1626        if (extra->findInt64(IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
1627            mAbsoluteTimeAnchorUs = mediaTimeUs;
1628        }
1629        if ((mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)
1630                && extra->findInt64(
1631                    IStreamListener::kKeyRecentMediaTimeUs, &mediaTimeUs)) {
1632            if (mAbsoluteTimeAnchorUs >= 0ll) {
1633                mediaTimeUs -= mAbsoluteTimeAnchorUs;
1634            }
1635            if (mTimeOffsetValid) {
1636                mediaTimeUs -= mTimeOffsetUs;
1637            }
1638            mLastRecoveredPTS = (mediaTimeUs * 9) / 100;
1639        }
1640    } else if (type == DISCONTINUITY_ABSOLUTE_TIME) {
1641        int64_t timeUs;
1642        if (!extra->findInt64("timeUs", &timeUs)) {
1643            ALOGE("timeUs not found");
1644            return;
1645        }
1646
1647        if (!mPrograms.empty()) {
1648            ALOGE("mPrograms is not empty");
1649            return;
1650        }
1651        mAbsoluteTimeAnchorUs = timeUs;
1652        return;
1653    } else if (type == DISCONTINUITY_TIME_OFFSET) {
1654        int64_t offset;
1655        if (!extra->findInt64("offset", &offset)) {
1656            ALOGE("offset not found");
1657            return;
1658        }
1659
1660        mTimeOffsetValid = true;
1661        mTimeOffsetUs = offset;
1662        return;
1663    }
1664
1665    for (size_t i = 0; i < mPrograms.size(); ++i) {
1666        mPrograms.editItemAt(i)->signalDiscontinuity(type, extra);
1667    }
1668}
1669
1670void ATSParser::signalEOS(status_t finalResult) {
1671    if (finalResult == (status_t) OK) {
1672        ALOGE("finalResult not OK");
1673        return;
1674    }
1675
1676    for (size_t i = 0; i < mPrograms.size(); ++i) {
1677        mPrograms.editItemAt(i)->signalEOS(finalResult);
1678    }
1679}
1680
1681void ATSParser::parseProgramAssociationTable(ABitReader *br) {
1682    unsigned table_id = br->getBits(8);
1683    ALOGV("  table_id = %u", table_id);
1684    if (table_id != 0x00u) {
1685        ALOGE("PAT data error!");
1686        return ;
1687    }
1688    unsigned section_syntax_indictor = br->getBits(1);
1689    ALOGV("  section_syntax_indictor = %u", section_syntax_indictor);
1690
1691    br->skipBits(1);  // '0'
1692    MY_LOGV("  reserved = %u", br->getBits(2));
1693
1694    unsigned section_length = br->getBits(12);
1695    ALOGV("  section_length = %u", section_length);
1696
1697    MY_LOGV("  transport_stream_id = %u", br->getBits(16));
1698    MY_LOGV("  reserved = %u", br->getBits(2));
1699    MY_LOGV("  version_number = %u", br->getBits(5));
1700    MY_LOGV("  current_next_indicator = %u", br->getBits(1));
1701    MY_LOGV("  section_number = %u", br->getBits(8));
1702    MY_LOGV("  last_section_number = %u", br->getBits(8));
1703
1704    size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
1705
1706    for (size_t i = 0; i < numProgramBytes / 4; ++i) {
1707        unsigned program_number = br->getBits(16);
1708        ALOGV("    program_number = %u", program_number);
1709
1710        MY_LOGV("    reserved = %u", br->getBits(3));
1711
1712        if (program_number == 0) {
1713            MY_LOGV("    network_PID = 0x%04x", br->getBits(13));
1714        } else {
1715            unsigned programMapPID = br->getBits(13);
1716
1717            ALOGV("    program_map_PID = 0x%04x", programMapPID);
1718
1719            bool found = false;
1720            for (size_t index = 0; index < mPrograms.size(); ++index) {
1721                const sp<Program> &program = mPrograms.itemAt(index);
1722
1723                if (program->number() == program_number) {
1724                    program->updateProgramMapPID(programMapPID);
1725                    found = true;
1726                    break;
1727                }
1728            }
1729
1730            if (!found) {
1731                mPrograms.push(
1732                        new Program(this, program_number, programMapPID, mLastRecoveredPTS));
1733            }
1734
1735            if (mPSISections.indexOfKey(programMapPID) < 0) {
1736                mPSISections.add(programMapPID, new PSISection);
1737            }
1738        }
1739    }
1740
1741    MY_LOGV("  CRC = 0x%08x", br->getBits(32));
1742}
1743
1744status_t ATSParser::parsePID(
1745        ABitReader *br, unsigned PID,
1746        unsigned continuity_counter,
1747        unsigned payload_unit_start_indicator,
1748        unsigned transport_scrambling_control,
1749        unsigned random_access_indicator,
1750        SyncEvent *event) {
1751    ssize_t sectionIndex = mPSISections.indexOfKey(PID);
1752
1753    if (sectionIndex >= 0) {
1754        sp<PSISection> section = mPSISections.valueAt(sectionIndex);
1755
1756        if (payload_unit_start_indicator) {
1757            if (!section->isEmpty()) {
1758                ALOGW("parsePID encounters payload_unit_start_indicator when section is not empty");
1759                section->clear();
1760            }
1761
1762            unsigned skip = br->getBits(8);
1763            section->setSkipBytes(skip + 1);  // skip filler bytes + pointer field itself
1764            br->skipBits(skip * 8);
1765        }
1766
1767        if (br->numBitsLeft() % 8 != 0) {
1768            return ERROR_MALFORMED;
1769        }
1770        status_t err = section->append(br->data(), br->numBitsLeft() / 8);
1771
1772        if (err != OK) {
1773            return err;
1774        }
1775
1776        if (!section->isComplete()) {
1777            return OK;
1778        }
1779
1780        if (!section->isCRCOkay()) {
1781            return BAD_VALUE;
1782        }
1783        ABitReader sectionBits(section->data(), section->size());
1784
1785        if (PID == 0) {
1786            parseProgramAssociationTable(&sectionBits);
1787        } else {
1788            bool handled = false;
1789            for (size_t i = 0; i < mPrograms.size(); ++i) {
1790                status_t err;
1791                if (!mPrograms.editItemAt(i)->parsePSISection(
1792                            PID, &sectionBits, &err)) {
1793                    continue;
1794                }
1795
1796                if (err != OK) {
1797                    return err;
1798                }
1799
1800                handled = true;
1801                break;
1802            }
1803
1804            if (!handled) {
1805                mPSISections.removeItem(PID);
1806                section.clear();
1807            }
1808        }
1809
1810        if (section != NULL) {
1811            section->clear();
1812        }
1813
1814        return OK;
1815    }
1816
1817    bool handled = false;
1818    for (size_t i = 0; i < mPrograms.size(); ++i) {
1819        status_t err;
1820        if (mPrograms.editItemAt(i)->parsePID(
1821                    PID, continuity_counter,
1822                    payload_unit_start_indicator,
1823                    transport_scrambling_control,
1824                    random_access_indicator,
1825                    br, &err, event)) {
1826            if (err != OK) {
1827                return err;
1828            }
1829
1830            handled = true;
1831            break;
1832        }
1833    }
1834
1835    if (!handled) {
1836        handled = mCasManager->parsePID(br, PID);
1837    }
1838
1839    if (!handled) {
1840        ALOGV("PID 0x%04x not handled.", PID);
1841    }
1842
1843    return OK;
1844}
1845
1846status_t ATSParser::parseAdaptationField(
1847        ABitReader *br, unsigned PID, unsigned *random_access_indicator) {
1848    *random_access_indicator = 0;
1849    unsigned adaptation_field_length = br->getBits(8);
1850
1851    if (adaptation_field_length > 0) {
1852        if (adaptation_field_length * 8 > br->numBitsLeft()) {
1853            ALOGV("Adaptation field should be included in a single TS packet.");
1854            return ERROR_MALFORMED;
1855        }
1856
1857        unsigned discontinuity_indicator = br->getBits(1);
1858
1859        if (discontinuity_indicator) {
1860            ALOGV("PID 0x%04x: discontinuity_indicator = 1 (!!!)", PID);
1861        }
1862
1863        *random_access_indicator = br->getBits(1);
1864        if (*random_access_indicator) {
1865            ALOGV("PID 0x%04x: random_access_indicator = 1", PID);
1866        }
1867
1868        unsigned elementary_stream_priority_indicator = br->getBits(1);
1869        if (elementary_stream_priority_indicator) {
1870            ALOGV("PID 0x%04x: elementary_stream_priority_indicator = 1", PID);
1871        }
1872
1873        unsigned PCR_flag = br->getBits(1);
1874
1875        size_t numBitsRead = 4;
1876
1877        if (PCR_flag) {
1878            if (adaptation_field_length * 8 < 52) {
1879                return ERROR_MALFORMED;
1880            }
1881            br->skipBits(4);
1882            uint64_t PCR_base = br->getBits(32);
1883            PCR_base = (PCR_base << 1) | br->getBits(1);
1884
1885            br->skipBits(6);
1886            unsigned PCR_ext = br->getBits(9);
1887
1888            // The number of bytes from the start of the current
1889            // MPEG2 transport stream packet up and including
1890            // the final byte of this PCR_ext field.
1891            size_t byteOffsetFromStartOfTSPacket =
1892                (188 - br->numBitsLeft() / 8);
1893
1894            uint64_t PCR = PCR_base * 300 + PCR_ext;
1895
1896            ALOGV("PID 0x%04x: PCR = 0x%016" PRIx64 " (%.2f)",
1897                  PID, PCR, PCR / 27E6);
1898
1899            // The number of bytes received by this parser up to and
1900            // including the final byte of this PCR_ext field.
1901            uint64_t byteOffsetFromStart =
1902                uint64_t(mNumTSPacketsParsed) * 188 + byteOffsetFromStartOfTSPacket;
1903
1904            for (size_t i = 0; i < mPrograms.size(); ++i) {
1905                updatePCR(PID, PCR, byteOffsetFromStart);
1906            }
1907
1908            numBitsRead += 52;
1909        }
1910
1911        br->skipBits(adaptation_field_length * 8 - numBitsRead);
1912    }
1913    return OK;
1914}
1915
1916status_t ATSParser::parseTS(ABitReader *br, SyncEvent *event) {
1917    ALOGV("---");
1918
1919    unsigned sync_byte = br->getBits(8);
1920    if (sync_byte != 0x47u) {
1921        ALOGE("[error] parseTS: return error as sync_byte=0x%x", sync_byte);
1922        return BAD_VALUE;
1923    }
1924
1925    if (br->getBits(1)) {  // transport_error_indicator
1926        // silently ignore.
1927        return OK;
1928    }
1929
1930    unsigned payload_unit_start_indicator = br->getBits(1);
1931    ALOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
1932
1933    MY_LOGV("transport_priority = %u", br->getBits(1));
1934
1935    unsigned PID = br->getBits(13);
1936    ALOGV("PID = 0x%04x", PID);
1937
1938    unsigned transport_scrambling_control = br->getBits(2);
1939    ALOGV("transport_scrambling_control = %u", transport_scrambling_control);
1940
1941    unsigned adaptation_field_control = br->getBits(2);
1942    ALOGV("adaptation_field_control = %u", adaptation_field_control);
1943
1944    unsigned continuity_counter = br->getBits(4);
1945    ALOGV("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1946
1947    // ALOGI("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1948
1949    status_t err = OK;
1950
1951    unsigned random_access_indicator = 0;
1952    if (adaptation_field_control == 2 || adaptation_field_control == 3) {
1953        err = parseAdaptationField(br, PID, &random_access_indicator);
1954    }
1955    if (err == OK) {
1956        if (adaptation_field_control == 1 || adaptation_field_control == 3) {
1957            err = parsePID(br, PID, continuity_counter,
1958                    payload_unit_start_indicator,
1959                    transport_scrambling_control,
1960                    random_access_indicator,
1961                    event);
1962        }
1963    }
1964
1965    ++mNumTSPacketsParsed;
1966
1967    return err;
1968}
1969
1970sp<MediaSource> ATSParser::getSource(SourceType type) {
1971    sp<MediaSource> firstSourceFound;
1972    for (size_t i = 0; i < mPrograms.size(); ++i) {
1973        const sp<Program> &program = mPrograms.editItemAt(i);
1974        sp<MediaSource> source = program->getSource(type);
1975        if (source == NULL) {
1976            continue;
1977        }
1978        if (firstSourceFound == NULL) {
1979            firstSourceFound = source;
1980        }
1981        // Prefer programs with both audio/video
1982        switch (type) {
1983            case VIDEO: {
1984                if (program->hasSource(AUDIO)) {
1985                    return source;
1986                }
1987                break;
1988            }
1989
1990            case AUDIO: {
1991                if (program->hasSource(VIDEO)) {
1992                    return source;
1993                }
1994                break;
1995            }
1996
1997            default:
1998                return source;
1999        }
2000    }
2001
2002    return firstSourceFound;
2003}
2004
2005bool ATSParser::hasSource(SourceType type) const {
2006    for (size_t i = 0; i < mPrograms.size(); ++i) {
2007        const sp<Program> &program = mPrograms.itemAt(i);
2008        if (program->hasSource(type)) {
2009            return true;
2010        }
2011    }
2012
2013    return false;
2014}
2015
2016bool ATSParser::PTSTimeDeltaEstablished() {
2017    if (mPrograms.isEmpty()) {
2018        return false;
2019    }
2020
2021    return mPrograms.editItemAt(0)->PTSTimeDeltaEstablished();
2022}
2023
2024int64_t ATSParser::getFirstPTSTimeUs() {
2025    for (size_t i = 0; i < mPrograms.size(); ++i) {
2026        sp<ATSParser::Program> program = mPrograms.itemAt(i);
2027        if (program->PTSTimeDeltaEstablished()) {
2028            return (program->firstPTS() * 100) / 9;
2029        }
2030    }
2031    return -1;
2032}
2033
2034__attribute__((no_sanitize("integer")))
2035void ATSParser::updatePCR(
2036        unsigned /* PID */, uint64_t PCR, uint64_t byteOffsetFromStart) {
2037    ALOGV("PCR 0x%016" PRIx64 " @ %" PRIx64, PCR, byteOffsetFromStart);
2038
2039    if (mNumPCRs == 2) {
2040        mPCR[0] = mPCR[1];
2041        mPCRBytes[0] = mPCRBytes[1];
2042        mSystemTimeUs[0] = mSystemTimeUs[1];
2043        mNumPCRs = 1;
2044    }
2045
2046    mPCR[mNumPCRs] = PCR;
2047    mPCRBytes[mNumPCRs] = byteOffsetFromStart;
2048    mSystemTimeUs[mNumPCRs] = ALooper::GetNowUs();
2049
2050    ++mNumPCRs;
2051
2052    if (mNumPCRs == 2) {
2053        /* Unsigned overflow here */
2054        double transportRate =
2055            (mPCRBytes[1] - mPCRBytes[0]) * 27E6 / (mPCR[1] - mPCR[0]);
2056
2057        ALOGV("transportRate = %.2f bytes/sec", transportRate);
2058    }
2059}
2060
2061////////////////////////////////////////////////////////////////////////////////
2062
2063
2064// CRC32 used for PSI section. The table was generated by following command:
2065// $ python pycrc.py --model crc-32-mpeg --algorithm table-driven --generate c
2066// Visit http://www.tty1.net/pycrc/index_en.html for more details.
2067uint32_t ATSParser::PSISection::CRC_TABLE[] = {
2068    0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
2069    0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
2070    0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
2071    0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
2072    0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
2073    0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
2074    0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
2075    0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
2076    0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
2077    0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
2078    0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
2079    0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
2080    0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
2081    0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
2082    0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
2083    0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
2084    0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
2085    0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
2086    0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
2087    0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
2088    0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
2089    0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
2090    0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
2091    0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
2092    0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
2093    0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
2094    0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
2095    0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
2096    0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
2097    0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
2098    0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
2099    0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
2100    0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
2101    0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
2102    0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
2103    0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
2104    0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
2105    0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
2106    0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
2107    0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
2108    0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
2109    0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
2110    0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
2111    0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
2112    0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
2113    0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
2114    0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
2115    0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
2116    0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
2117    0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
2118    0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
2119    0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
2120    0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
2121    0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
2122    0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
2123    0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
2124    0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
2125    0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
2126    0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
2127    0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
2128    0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
2129    0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
2130    0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
2131    0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
2132    };
2133
2134ATSParser::PSISection::PSISection() :
2135    mSkipBytes(0) {
2136}
2137
2138ATSParser::PSISection::~PSISection() {
2139}
2140
2141status_t ATSParser::PSISection::append(const void *data, size_t size) {
2142    if (mBuffer == NULL || mBuffer->size() + size > mBuffer->capacity()) {
2143        size_t newCapacity =
2144            (mBuffer == NULL) ? size : mBuffer->capacity() + size;
2145
2146        newCapacity = (newCapacity + 1023) & ~1023;
2147
2148        sp<ABuffer> newBuffer = new ABuffer(newCapacity);
2149
2150        if (mBuffer != NULL) {
2151            memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
2152            newBuffer->setRange(0, mBuffer->size());
2153        } else {
2154            newBuffer->setRange(0, 0);
2155        }
2156
2157        mBuffer = newBuffer;
2158    }
2159
2160    memcpy(mBuffer->data() + mBuffer->size(), data, size);
2161    mBuffer->setRange(0, mBuffer->size() + size);
2162
2163    return OK;
2164}
2165
2166void ATSParser::PSISection::setSkipBytes(uint8_t skip) {
2167    mSkipBytes = skip;
2168}
2169
2170void ATSParser::PSISection::clear() {
2171    if (mBuffer != NULL) {
2172        mBuffer->setRange(0, 0);
2173    }
2174    mSkipBytes = 0;
2175}
2176
2177bool ATSParser::PSISection::isComplete() const {
2178    if (mBuffer == NULL || mBuffer->size() < 3) {
2179        return false;
2180    }
2181
2182    unsigned sectionLength = U16_AT(mBuffer->data() + 1) & 0xfff;
2183    return mBuffer->size() >= sectionLength + 3;
2184}
2185
2186bool ATSParser::PSISection::isEmpty() const {
2187    return mBuffer == NULL || mBuffer->size() == 0;
2188}
2189
2190const uint8_t *ATSParser::PSISection::data() const {
2191    return mBuffer == NULL ? NULL : mBuffer->data();
2192}
2193
2194size_t ATSParser::PSISection::size() const {
2195    return mBuffer == NULL ? 0 : mBuffer->size();
2196}
2197
2198bool ATSParser::PSISection::isCRCOkay() const {
2199    if (!isComplete()) {
2200        return false;
2201    }
2202    uint8_t* data = mBuffer->data();
2203
2204    // Return true if section_syntax_indicator says no section follows the field section_length.
2205    if ((data[1] & 0x80) == 0) {
2206        return true;
2207    }
2208
2209    unsigned sectionLength = U16_AT(data + 1) & 0xfff;
2210    ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes);
2211
2212
2213    if(sectionLength < mSkipBytes) {
2214        ALOGE("b/28333006");
2215        android_errorWriteLog(0x534e4554, "28333006");
2216        return false;
2217    }
2218
2219    // Skip the preceding field present when payload start indicator is on.
2220    sectionLength -= mSkipBytes;
2221
2222    uint32_t crc = 0xffffffff;
2223    for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) {
2224        uint8_t b = data[i];
2225        int index = ((crc >> 24) ^ (b & 0xff)) & 0xff;
2226        crc = CRC_TABLE[index] ^ (crc << 8);
2227    }
2228    ALOGV("crc: %08x\n", crc);
2229    return (crc == 0);
2230}
2231}  // namespace android
2232