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