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