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