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