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
21 #include "ATSParser.h"
22
23 #include "AnotherPacketSource.h"
24 #include "ESQueue.h"
25 #include "include/avc_utils.h"
26
27 #include <media/stagefright/foundation/ABitReader.h>
28 #include <media/stagefright/foundation/ABuffer.h>
29 #include <media/stagefright/foundation/ADebug.h>
30 #include <media/stagefright/foundation/AMessage.h>
31 #include <media/stagefright/foundation/hexdump.h>
32 #include <media/stagefright/MediaDefs.h>
33 #include <media/stagefright/MediaErrors.h>
34 #include <media/stagefright/MetaData.h>
35 #include <media/stagefright/Utils.h>
36 #include <media/IStreamSource.h>
37 #include <utils/KeyedVector.h>
38 #include <utils/Vector.h>
39
40 #include <inttypes.h>
41
42 namespace android {
43
44 // I want the expression "y" evaluated even if verbose logging is off.
45 #define MY_LOGV(x, y) \
46 do { unsigned tmp = y; ALOGV(x, tmp); } while (0)
47
48 static const size_t kTSPacketSize = 188;
49
50 struct ATSParser::Program : public RefBase {
51 Program(ATSParser *parser, unsigned programNumber, unsigned programMapPID,
52 int64_t lastRecoveredPTS);
53
54 bool parsePSISection(
55 unsigned pid, ABitReader *br, status_t *err);
56
57 // Pass to appropriate stream according to pid, and set event if it's a PES
58 // with a sync frame.
59 // Note that the method itself does not touch event.
60 bool parsePID(
61 unsigned pid, unsigned continuity_counter,
62 unsigned payload_unit_start_indicator,
63 ABitReader *br, status_t *err, SyncEvent *event);
64
65 void signalDiscontinuity(
66 DiscontinuityType type, const sp<AMessage> &extra);
67
68 void signalEOS(status_t finalResult);
69
70 sp<MediaSource> getSource(SourceType type);
71 bool hasSource(SourceType type) const;
72
73 int64_t convertPTSToTimestamp(uint64_t PTS);
74
PTSTimeDeltaEstablishedandroid::ATSParser::Program75 bool PTSTimeDeltaEstablished() const {
76 return mFirstPTSValid;
77 }
78
numberandroid::ATSParser::Program79 unsigned number() const { return mProgramNumber; }
80
updateProgramMapPIDandroid::ATSParser::Program81 void updateProgramMapPID(unsigned programMapPID) {
82 mProgramMapPID = programMapPID;
83 }
84
programMapPIDandroid::ATSParser::Program85 unsigned programMapPID() const {
86 return mProgramMapPID;
87 }
88
parserFlagsandroid::ATSParser::Program89 uint32_t parserFlags() const {
90 return mParser->mFlags;
91 }
92
93 private:
94 struct StreamInfo {
95 unsigned mType;
96 unsigned mPID;
97 };
98
99 ATSParser *mParser;
100 unsigned mProgramNumber;
101 unsigned mProgramMapPID;
102 KeyedVector<unsigned, sp<Stream> > mStreams;
103 bool mFirstPTSValid;
104 uint64_t mFirstPTS;
105 int64_t mLastRecoveredPTS;
106
107 status_t parseProgramMap(ABitReader *br);
108 int64_t recoverPTS(uint64_t PTS_33bit);
109 bool switchPIDs(const Vector<StreamInfo> &infos);
110
111 DISALLOW_EVIL_CONSTRUCTORS(Program);
112 };
113
114 struct ATSParser::Stream : public RefBase {
115 Stream(Program *program,
116 unsigned elementaryPID,
117 unsigned streamType,
118 unsigned PCR_PID);
119
typeandroid::ATSParser::Stream120 unsigned type() const { return mStreamType; }
pidandroid::ATSParser::Stream121 unsigned pid() const { return mElementaryPID; }
setPIDandroid::ATSParser::Stream122 void setPID(unsigned pid) { mElementaryPID = pid; }
123
124 // Parse the payload and set event when PES with a sync frame is detected.
125 // This method knows when a PES starts; so record mPesStartOffsets in that
126 // case.
127 status_t parse(
128 unsigned continuity_counter,
129 unsigned payload_unit_start_indicator,
130 ABitReader *br,
131 SyncEvent *event);
132
133 void signalDiscontinuity(
134 DiscontinuityType type, const sp<AMessage> &extra);
135
136 void signalEOS(status_t finalResult);
137
138 sp<MediaSource> getSource(SourceType type);
139
140 bool isAudio() const;
141 bool isVideo() const;
142 bool isMeta() const;
143
144 protected:
145 virtual ~Stream();
146
147 private:
148 Program *mProgram;
149 unsigned mElementaryPID;
150 unsigned mStreamType;
151 unsigned mPCR_PID;
152 int32_t mExpectedContinuityCounter;
153
154 sp<ABuffer> mBuffer;
155 sp<AnotherPacketSource> mSource;
156 bool mPayloadStarted;
157 bool mEOSReached;
158
159 uint64_t mPrevPTS;
160 List<off64_t> mPesStartOffsets;
161
162 ElementaryStreamQueue *mQueue;
163
164 // Flush accumulated payload if necessary --- i.e. at EOS or at the start of
165 // another payload. event is set if the flushed payload is PES with a sync
166 // frame.
167 status_t flush(SyncEvent *event);
168 // Strip and parse PES headers and pass remaining payload into onPayload
169 // with parsed metadata. event is set if the PES contains a sync frame.
170 status_t parsePES(ABitReader *br, SyncEvent *event);
171
172 // Feed the payload into mQueue and if a packet is identified, queue it
173 // into mSource. If the packet is a sync frame. set event with start offset
174 // and timestamp of the packet.
175 void onPayloadData(
176 unsigned PTS_DTS_flags, uint64_t PTS, uint64_t DTS,
177 const uint8_t *data, size_t size, SyncEvent *event);
178
179 DISALLOW_EVIL_CONSTRUCTORS(Stream);
180 };
181
182 struct ATSParser::PSISection : public RefBase {
183 PSISection();
184
185 status_t append(const void *data, size_t size);
186 void setSkipBytes(uint8_t skip);
187 void clear();
188
189 bool isComplete() const;
190 bool isEmpty() const;
191 bool isCRCOkay() const;
192
193 const uint8_t *data() const;
194 size_t size() const;
195
196 protected:
197 virtual ~PSISection();
198
199 private:
200 sp<ABuffer> mBuffer;
201 uint8_t mSkipBytes;
202 static uint32_t CRC_TABLE[];
203
204 DISALLOW_EVIL_CONSTRUCTORS(PSISection);
205 };
206
SyncEvent(off64_t offset)207 ATSParser::SyncEvent::SyncEvent(off64_t offset)
208 : mHasReturnedData(false), mOffset(offset), mTimeUs(0) {}
209
init(off64_t offset,const sp<MediaSource> & source,int64_t timeUs)210 void ATSParser::SyncEvent::init(off64_t offset, const sp<MediaSource> &source,
211 int64_t timeUs) {
212 mHasReturnedData = true;
213 mOffset = offset;
214 mMediaSource = source;
215 mTimeUs = timeUs;
216 }
217
reset()218 void ATSParser::SyncEvent::reset() {
219 mHasReturnedData = false;
220 }
221 ////////////////////////////////////////////////////////////////////////////////
222
Program(ATSParser * parser,unsigned programNumber,unsigned programMapPID,int64_t lastRecoveredPTS)223 ATSParser::Program::Program(
224 ATSParser *parser, unsigned programNumber, unsigned programMapPID,
225 int64_t lastRecoveredPTS)
226 : mParser(parser),
227 mProgramNumber(programNumber),
228 mProgramMapPID(programMapPID),
229 mFirstPTSValid(false),
230 mFirstPTS(0),
231 mLastRecoveredPTS(lastRecoveredPTS) {
232 ALOGV("new program number %u", programNumber);
233 }
234
parsePSISection(unsigned pid,ABitReader * br,status_t * err)235 bool ATSParser::Program::parsePSISection(
236 unsigned pid, ABitReader *br, status_t *err) {
237 *err = OK;
238
239 if (pid != mProgramMapPID) {
240 return false;
241 }
242
243 *err = parseProgramMap(br);
244
245 return true;
246 }
247
parsePID(unsigned pid,unsigned continuity_counter,unsigned payload_unit_start_indicator,ABitReader * br,status_t * err,SyncEvent * event)248 bool ATSParser::Program::parsePID(
249 unsigned pid, unsigned continuity_counter,
250 unsigned payload_unit_start_indicator,
251 ABitReader *br, status_t *err, SyncEvent *event) {
252 *err = OK;
253
254 ssize_t index = mStreams.indexOfKey(pid);
255 if (index < 0) {
256 return false;
257 }
258
259 *err = mStreams.editValueAt(index)->parse(
260 continuity_counter, payload_unit_start_indicator, br, event);
261
262 return true;
263 }
264
signalDiscontinuity(DiscontinuityType type,const sp<AMessage> & extra)265 void ATSParser::Program::signalDiscontinuity(
266 DiscontinuityType type, const sp<AMessage> &extra) {
267 int64_t mediaTimeUs;
268 if ((type & DISCONTINUITY_TIME)
269 && extra != NULL
270 && extra->findInt64(
271 IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
272 mFirstPTSValid = false;
273 }
274
275 for (size_t i = 0; i < mStreams.size(); ++i) {
276 mStreams.editValueAt(i)->signalDiscontinuity(type, extra);
277 }
278 }
279
signalEOS(status_t finalResult)280 void ATSParser::Program::signalEOS(status_t finalResult) {
281 for (size_t i = 0; i < mStreams.size(); ++i) {
282 mStreams.editValueAt(i)->signalEOS(finalResult);
283 }
284 }
285
switchPIDs(const Vector<StreamInfo> & infos)286 bool ATSParser::Program::switchPIDs(const Vector<StreamInfo> &infos) {
287 bool success = false;
288
289 if (mStreams.size() == infos.size()) {
290 // build type->PIDs map for old and new mapping
291 size_t i;
292 KeyedVector<int32_t, Vector<int32_t> > oldType2PIDs, newType2PIDs;
293 for (i = 0; i < mStreams.size(); ++i) {
294 ssize_t index = oldType2PIDs.indexOfKey(mStreams[i]->type());
295 if (index < 0) {
296 oldType2PIDs.add(mStreams[i]->type(), Vector<int32_t>());
297 }
298 oldType2PIDs.editValueFor(mStreams[i]->type()).push_back(mStreams[i]->pid());
299 }
300 for (i = 0; i < infos.size(); ++i) {
301 ssize_t index = newType2PIDs.indexOfKey(infos[i].mType);
302 if (index < 0) {
303 newType2PIDs.add(infos[i].mType, Vector<int32_t>());
304 }
305 newType2PIDs.editValueFor(infos[i].mType).push_back(infos[i].mPID);
306 }
307
308 // we can recover if the number of streams for each type hasn't changed
309 if (oldType2PIDs.size() == newType2PIDs.size()) {
310 success = true;
311 for (i = 0; i < oldType2PIDs.size(); ++i) {
312 // KeyedVector is sorted, we just compare key and size of each index
313 if (oldType2PIDs.keyAt(i) != newType2PIDs.keyAt(i)
314 || oldType2PIDs[i].size() != newType2PIDs[i].size()) {
315 success = false;
316 break;
317 }
318 }
319 }
320
321 if (success) {
322 // save current streams to temp
323 KeyedVector<int32_t, sp<Stream> > temp;
324 for (i = 0; i < mStreams.size(); ++i) {
325 temp.add(mStreams.keyAt(i), mStreams.editValueAt(i));
326 }
327
328 mStreams.clear();
329 for (i = 0; i < temp.size(); ++i) {
330 // The two checks below shouldn't happen,
331 // we already checked above the stream count matches
332 ssize_t index = newType2PIDs.indexOfKey(temp[i]->type());
333 if (index < 0) {
334 return false;
335 }
336 Vector<int32_t> &newPIDs = newType2PIDs.editValueAt(index);
337 if (newPIDs.isEmpty()) {
338 return false;
339 }
340
341 // get the next PID for temp[i]->type() in the new PID map
342 Vector<int32_t>::iterator it = newPIDs.begin();
343
344 // change the PID of the stream, and add it back
345 temp.editValueAt(i)->setPID(*it);
346 mStreams.add(temp[i]->pid(), temp.editValueAt(i));
347
348 // removed the used PID
349 newPIDs.erase(it);
350 }
351 }
352 }
353 return success;
354 }
355
parseProgramMap(ABitReader * br)356 status_t ATSParser::Program::parseProgramMap(ABitReader *br) {
357 unsigned table_id = br->getBits(8);
358 ALOGV(" table_id = %u", table_id);
359 if (table_id != 0x02u) {
360 ALOGE("PMT data error!");
361 return ERROR_MALFORMED;
362 }
363 unsigned section_syntax_indicator = br->getBits(1);
364 ALOGV(" section_syntax_indicator = %u", section_syntax_indicator);
365 if (section_syntax_indicator != 1u) {
366 ALOGE("PMT data error!");
367 return ERROR_MALFORMED;
368 }
369
370 br->skipBits(1); // '0'
371 MY_LOGV(" reserved = %u", br->getBits(2));
372
373 unsigned section_length = br->getBits(12);
374 ALOGV(" section_length = %u", section_length);
375
376 MY_LOGV(" program_number = %u", br->getBits(16));
377 MY_LOGV(" reserved = %u", br->getBits(2));
378 MY_LOGV(" version_number = %u", br->getBits(5));
379 MY_LOGV(" current_next_indicator = %u", br->getBits(1));
380 MY_LOGV(" section_number = %u", br->getBits(8));
381 MY_LOGV(" last_section_number = %u", br->getBits(8));
382 MY_LOGV(" reserved = %u", br->getBits(3));
383
384 unsigned PCR_PID = br->getBits(13);
385 ALOGV(" PCR_PID = 0x%04x", PCR_PID);
386
387 MY_LOGV(" reserved = %u", br->getBits(4));
388
389 unsigned program_info_length = br->getBits(12);
390 ALOGV(" program_info_length = %u", program_info_length);
391
392 br->skipBits(program_info_length * 8); // skip descriptors
393
394 Vector<StreamInfo> infos;
395
396 // infoBytesRemaining is the number of bytes that make up the
397 // variable length section of ES_infos. It does not include the
398 // final CRC.
399 size_t infoBytesRemaining = section_length - 9 - program_info_length - 4;
400
401 while (infoBytesRemaining >= 5) {
402
403 unsigned streamType = br->getBits(8);
404 ALOGV(" stream_type = 0x%02x", streamType);
405
406 MY_LOGV(" reserved = %u", br->getBits(3));
407
408 unsigned elementaryPID = br->getBits(13);
409 ALOGV(" elementary_PID = 0x%04x", elementaryPID);
410
411 MY_LOGV(" reserved = %u", br->getBits(4));
412
413 unsigned ES_info_length = br->getBits(12);
414 ALOGV(" ES_info_length = %u", ES_info_length);
415
416 #if 0
417 br->skipBits(ES_info_length * 8); // skip descriptors
418 #else
419 unsigned info_bytes_remaining = ES_info_length;
420 while (info_bytes_remaining >= 2) {
421 MY_LOGV(" tag = 0x%02x", br->getBits(8));
422
423 unsigned descLength = br->getBits(8);
424 ALOGV(" len = %u", descLength);
425
426 if (info_bytes_remaining < descLength) {
427 return ERROR_MALFORMED;
428 }
429 br->skipBits(descLength * 8);
430
431 info_bytes_remaining -= descLength + 2;
432 }
433 #endif
434
435 StreamInfo info;
436 info.mType = streamType;
437 info.mPID = elementaryPID;
438 infos.push(info);
439
440 infoBytesRemaining -= 5 + ES_info_length;
441 }
442
443 if (infoBytesRemaining != 0) {
444 ALOGW("Section data remains unconsumed");
445 }
446 MY_LOGV(" CRC = 0x%08x", br->getBits(32));
447
448 bool PIDsChanged = false;
449 for (size_t i = 0; i < infos.size(); ++i) {
450 StreamInfo &info = infos.editItemAt(i);
451
452 ssize_t index = mStreams.indexOfKey(info.mPID);
453
454 if (index >= 0 && mStreams.editValueAt(index)->type() != info.mType) {
455 ALOGI("uh oh. stream PIDs have changed.");
456 PIDsChanged = true;
457 break;
458 }
459 }
460
461 if (PIDsChanged) {
462 #if 0
463 ALOGI("before:");
464 for (size_t i = 0; i < mStreams.size(); ++i) {
465 sp<Stream> stream = mStreams.editValueAt(i);
466
467 ALOGI("PID 0x%08x => type 0x%02x", stream->pid(), stream->type());
468 }
469
470 ALOGI("after:");
471 for (size_t i = 0; i < infos.size(); ++i) {
472 StreamInfo &info = infos.editItemAt(i);
473
474 ALOGI("PID 0x%08x => type 0x%02x", info.mPID, info.mType);
475 }
476 #endif
477
478 // we can recover if number of streams for each type remain the same
479 bool success = switchPIDs(infos);
480
481 if (!success) {
482 ALOGI("Stream PIDs changed and we cannot recover.");
483 return ERROR_MALFORMED;
484 }
485 }
486
487 for (size_t i = 0; i < infos.size(); ++i) {
488 StreamInfo &info = infos.editItemAt(i);
489
490 ssize_t index = mStreams.indexOfKey(info.mPID);
491
492 if (index < 0) {
493 sp<Stream> stream = new Stream(
494 this, info.mPID, info.mType, PCR_PID);
495
496 mStreams.add(info.mPID, stream);
497 }
498 }
499
500 return OK;
501 }
502
recoverPTS(uint64_t PTS_33bit)503 int64_t ATSParser::Program::recoverPTS(uint64_t PTS_33bit) {
504 // We only have the lower 33-bit of the PTS. It could overflow within a
505 // reasonable amount of time. To handle the wrap-around, use fancy math
506 // to get an extended PTS that is within [-0xffffffff, 0xffffffff]
507 // of the latest recovered PTS.
508 if (mLastRecoveredPTS < 0ll) {
509 // Use the original 33bit number for 1st frame, the reason is that
510 // if 1st frame wraps to negative that's far away from 0, we could
511 // never start. Only start wrapping around from 2nd frame.
512 mLastRecoveredPTS = static_cast<int64_t>(PTS_33bit);
513 } else {
514 mLastRecoveredPTS = static_cast<int64_t>(
515 ((mLastRecoveredPTS - static_cast<int64_t>(PTS_33bit) + 0x100000000ll)
516 & 0xfffffffe00000000ull) | PTS_33bit);
517 // We start from 0, but recovered PTS could be slightly below 0.
518 // Clamp it to 0 as rest of the pipeline doesn't take negative pts.
519 // (eg. video is read first and starts at 0, but audio starts at 0xfffffff0)
520 if (mLastRecoveredPTS < 0ll) {
521 ALOGI("Clamping negative recovered PTS (%" PRId64 ") to 0", mLastRecoveredPTS);
522 mLastRecoveredPTS = 0ll;
523 }
524 }
525
526 return mLastRecoveredPTS;
527 }
528
getSource(SourceType type)529 sp<MediaSource> ATSParser::Program::getSource(SourceType type) {
530 for (size_t i = 0; i < mStreams.size(); ++i) {
531 sp<MediaSource> source = mStreams.editValueAt(i)->getSource(type);
532 if (source != NULL) {
533 return source;
534 }
535 }
536
537 return NULL;
538 }
539
hasSource(SourceType type) const540 bool ATSParser::Program::hasSource(SourceType type) const {
541 for (size_t i = 0; i < mStreams.size(); ++i) {
542 const sp<Stream> &stream = mStreams.valueAt(i);
543 if (type == AUDIO && stream->isAudio()) {
544 return true;
545 } else if (type == VIDEO && stream->isVideo()) {
546 return true;
547 } else if (type == META && stream->isMeta()) {
548 return true;
549 }
550 }
551
552 return false;
553 }
554
convertPTSToTimestamp(uint64_t PTS)555 int64_t ATSParser::Program::convertPTSToTimestamp(uint64_t PTS) {
556 PTS = recoverPTS(PTS);
557
558 if (!(mParser->mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)) {
559 if (!mFirstPTSValid) {
560 mFirstPTSValid = true;
561 mFirstPTS = PTS;
562 PTS = 0;
563 } else if (PTS < mFirstPTS) {
564 PTS = 0;
565 } else {
566 PTS -= mFirstPTS;
567 }
568 }
569
570 int64_t timeUs = (PTS * 100) / 9;
571
572 if (mParser->mAbsoluteTimeAnchorUs >= 0ll) {
573 timeUs += mParser->mAbsoluteTimeAnchorUs;
574 }
575
576 if (mParser->mTimeOffsetValid) {
577 timeUs += mParser->mTimeOffsetUs;
578 }
579
580 return timeUs;
581 }
582
583 ////////////////////////////////////////////////////////////////////////////////
584
Stream(Program * program,unsigned elementaryPID,unsigned streamType,unsigned PCR_PID)585 ATSParser::Stream::Stream(
586 Program *program,
587 unsigned elementaryPID,
588 unsigned streamType,
589 unsigned PCR_PID)
590 : mProgram(program),
591 mElementaryPID(elementaryPID),
592 mStreamType(streamType),
593 mPCR_PID(PCR_PID),
594 mExpectedContinuityCounter(-1),
595 mPayloadStarted(false),
596 mEOSReached(false),
597 mPrevPTS(0),
598 mQueue(NULL) {
599 switch (mStreamType) {
600 case STREAMTYPE_H264:
601 mQueue = new ElementaryStreamQueue(
602 ElementaryStreamQueue::H264,
603 (mProgram->parserFlags() & ALIGNED_VIDEO_DATA)
604 ? ElementaryStreamQueue::kFlag_AlignedData : 0);
605 break;
606 case STREAMTYPE_MPEG2_AUDIO_ADTS:
607 mQueue = new ElementaryStreamQueue(ElementaryStreamQueue::AAC);
608 break;
609 case STREAMTYPE_MPEG1_AUDIO:
610 case STREAMTYPE_MPEG2_AUDIO:
611 mQueue = new ElementaryStreamQueue(
612 ElementaryStreamQueue::MPEG_AUDIO);
613 break;
614
615 case STREAMTYPE_MPEG1_VIDEO:
616 case STREAMTYPE_MPEG2_VIDEO:
617 mQueue = new ElementaryStreamQueue(
618 ElementaryStreamQueue::MPEG_VIDEO);
619 break;
620
621 case STREAMTYPE_MPEG4_VIDEO:
622 mQueue = new ElementaryStreamQueue(
623 ElementaryStreamQueue::MPEG4_VIDEO);
624 break;
625
626 case STREAMTYPE_LPCM_AC3:
627 case STREAMTYPE_AC3:
628 mQueue = new ElementaryStreamQueue(
629 ElementaryStreamQueue::AC3);
630 break;
631
632 case STREAMTYPE_METADATA:
633 mQueue = new ElementaryStreamQueue(
634 ElementaryStreamQueue::METADATA);
635 break;
636
637 default:
638 break;
639 }
640
641 ALOGV("new stream PID 0x%02x, type 0x%02x", elementaryPID, streamType);
642
643 if (mQueue != NULL) {
644 mBuffer = new ABuffer(192 * 1024);
645 mBuffer->setRange(0, 0);
646 }
647 }
648
~Stream()649 ATSParser::Stream::~Stream() {
650 delete mQueue;
651 mQueue = NULL;
652 }
653
parse(unsigned continuity_counter,unsigned payload_unit_start_indicator,ABitReader * br,SyncEvent * event)654 status_t ATSParser::Stream::parse(
655 unsigned continuity_counter,
656 unsigned payload_unit_start_indicator, ABitReader *br,
657 SyncEvent *event) {
658 if (mQueue == NULL) {
659 return OK;
660 }
661
662 if (mExpectedContinuityCounter >= 0
663 && (unsigned)mExpectedContinuityCounter != continuity_counter) {
664 ALOGI("discontinuity on stream pid 0x%04x", mElementaryPID);
665
666 mPayloadStarted = false;
667 mPesStartOffsets.clear();
668 mBuffer->setRange(0, 0);
669 mExpectedContinuityCounter = -1;
670
671 #if 0
672 // Uncomment this if you'd rather see no corruption whatsoever on
673 // screen and suspend updates until we come across another IDR frame.
674
675 if (mStreamType == STREAMTYPE_H264) {
676 ALOGI("clearing video queue");
677 mQueue->clear(true /* clearFormat */);
678 }
679 #endif
680
681 if (!payload_unit_start_indicator) {
682 return OK;
683 }
684 }
685
686 mExpectedContinuityCounter = (continuity_counter + 1) & 0x0f;
687
688 if (payload_unit_start_indicator) {
689 off64_t offset = (event != NULL) ? event->getOffset() : 0;
690 if (mPayloadStarted) {
691 // Otherwise we run the danger of receiving the trailing bytes
692 // of a PES packet that we never saw the start of and assuming
693 // we have a a complete PES packet.
694
695 status_t err = flush(event);
696
697 if (err != OK) {
698 ALOGW("Error (%08x) happened while flushing; we simply discard "
699 "the PES packet and continue.", err);
700 }
701 }
702
703 mPayloadStarted = true;
704 // There should be at most 2 elements in |mPesStartOffsets|.
705 while (mPesStartOffsets.size() >= 2) {
706 mPesStartOffsets.erase(mPesStartOffsets.begin());
707 }
708 mPesStartOffsets.push_back(offset);
709 }
710
711 if (!mPayloadStarted) {
712 return OK;
713 }
714
715 size_t payloadSizeBits = br->numBitsLeft();
716 if (payloadSizeBits % 8 != 0u) {
717 ALOGE("Wrong value");
718 return BAD_VALUE;
719 }
720
721 size_t neededSize = mBuffer->size() + payloadSizeBits / 8;
722 if (mBuffer->capacity() < neededSize) {
723 // Increment in multiples of 64K.
724 neededSize = (neededSize + 65535) & ~65535;
725
726 ALOGI("resizing buffer to %zu bytes", neededSize);
727
728 sp<ABuffer> newBuffer = new ABuffer(neededSize);
729 memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
730 newBuffer->setRange(0, mBuffer->size());
731 mBuffer = newBuffer;
732 }
733
734 memcpy(mBuffer->data() + mBuffer->size(), br->data(), payloadSizeBits / 8);
735 mBuffer->setRange(0, mBuffer->size() + payloadSizeBits / 8);
736
737 return OK;
738 }
739
isVideo() const740 bool ATSParser::Stream::isVideo() const {
741 switch (mStreamType) {
742 case STREAMTYPE_H264:
743 case STREAMTYPE_MPEG1_VIDEO:
744 case STREAMTYPE_MPEG2_VIDEO:
745 case STREAMTYPE_MPEG4_VIDEO:
746 return true;
747
748 default:
749 return false;
750 }
751 }
752
isAudio() const753 bool ATSParser::Stream::isAudio() const {
754 switch (mStreamType) {
755 case STREAMTYPE_MPEG1_AUDIO:
756 case STREAMTYPE_MPEG2_AUDIO:
757 case STREAMTYPE_MPEG2_AUDIO_ADTS:
758 case STREAMTYPE_LPCM_AC3:
759 case STREAMTYPE_AC3:
760 return true;
761
762 default:
763 return false;
764 }
765 }
766
isMeta() const767 bool ATSParser::Stream::isMeta() const {
768 if (mStreamType == STREAMTYPE_METADATA) {
769 return true;
770 }
771 return false;
772 }
773
signalDiscontinuity(DiscontinuityType type,const sp<AMessage> & extra)774 void ATSParser::Stream::signalDiscontinuity(
775 DiscontinuityType type, const sp<AMessage> &extra) {
776 mExpectedContinuityCounter = -1;
777
778 if (mQueue == NULL) {
779 return;
780 }
781
782 mPayloadStarted = false;
783 mPesStartOffsets.clear();
784 mEOSReached = false;
785 mBuffer->setRange(0, 0);
786
787 bool clearFormat = false;
788 if (isAudio()) {
789 if (type & DISCONTINUITY_AUDIO_FORMAT) {
790 clearFormat = true;
791 }
792 } else {
793 if (type & DISCONTINUITY_VIDEO_FORMAT) {
794 clearFormat = true;
795 }
796 }
797
798 mQueue->clear(clearFormat);
799
800 if (type & DISCONTINUITY_TIME) {
801 uint64_t resumeAtPTS;
802 if (extra != NULL
803 && extra->findInt64(
804 IStreamListener::kKeyResumeAtPTS,
805 (int64_t *)&resumeAtPTS)) {
806 int64_t resumeAtMediaTimeUs =
807 mProgram->convertPTSToTimestamp(resumeAtPTS);
808
809 extra->setInt64("resume-at-mediaTimeUs", resumeAtMediaTimeUs);
810 }
811 }
812
813 if (mSource != NULL) {
814 mSource->queueDiscontinuity(type, extra, true);
815 }
816 }
817
signalEOS(status_t finalResult)818 void ATSParser::Stream::signalEOS(status_t finalResult) {
819 if (mSource != NULL) {
820 mSource->signalEOS(finalResult);
821 }
822 mEOSReached = true;
823 flush(NULL);
824 }
825
parsePES(ABitReader * br,SyncEvent * event)826 status_t ATSParser::Stream::parsePES(ABitReader *br, SyncEvent *event) {
827 unsigned packet_startcode_prefix = br->getBits(24);
828
829 ALOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
830
831 if (packet_startcode_prefix != 1) {
832 ALOGV("Supposedly payload_unit_start=1 unit does not start "
833 "with startcode.");
834
835 return ERROR_MALFORMED;
836 }
837
838 unsigned stream_id = br->getBits(8);
839 ALOGV("stream_id = 0x%02x", stream_id);
840
841 unsigned PES_packet_length = br->getBits(16);
842 ALOGV("PES_packet_length = %u", PES_packet_length);
843
844 if (stream_id != 0xbc // program_stream_map
845 && stream_id != 0xbe // padding_stream
846 && stream_id != 0xbf // private_stream_2
847 && stream_id != 0xf0 // ECM
848 && stream_id != 0xf1 // EMM
849 && stream_id != 0xff // program_stream_directory
850 && stream_id != 0xf2 // DSMCC
851 && stream_id != 0xf8) { // H.222.1 type E
852 if (br->getBits(2) != 2u) {
853 return ERROR_MALFORMED;
854 }
855
856 MY_LOGV("PES_scrambling_control = %u", br->getBits(2));
857 MY_LOGV("PES_priority = %u", br->getBits(1));
858 MY_LOGV("data_alignment_indicator = %u", br->getBits(1));
859 MY_LOGV("copyright = %u", br->getBits(1));
860 MY_LOGV("original_or_copy = %u", br->getBits(1));
861
862 unsigned PTS_DTS_flags = br->getBits(2);
863 ALOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
864
865 unsigned ESCR_flag = br->getBits(1);
866 ALOGV("ESCR_flag = %u", ESCR_flag);
867
868 unsigned ES_rate_flag = br->getBits(1);
869 ALOGV("ES_rate_flag = %u", ES_rate_flag);
870
871 unsigned DSM_trick_mode_flag = br->getBits(1);
872 ALOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
873
874 unsigned additional_copy_info_flag = br->getBits(1);
875 ALOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
876
877 MY_LOGV("PES_CRC_flag = %u", br->getBits(1));
878 MY_LOGV("PES_extension_flag = %u", br->getBits(1));
879
880 unsigned PES_header_data_length = br->getBits(8);
881 ALOGV("PES_header_data_length = %u", PES_header_data_length);
882
883 unsigned optional_bytes_remaining = PES_header_data_length;
884
885 uint64_t PTS = 0, DTS = 0;
886
887 if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
888 if (optional_bytes_remaining < 5u) {
889 return ERROR_MALFORMED;
890 }
891
892 if (br->getBits(4) != PTS_DTS_flags) {
893 return ERROR_MALFORMED;
894 }
895 PTS = ((uint64_t)br->getBits(3)) << 30;
896 if (br->getBits(1) != 1u) {
897 return ERROR_MALFORMED;
898 }
899 PTS |= ((uint64_t)br->getBits(15)) << 15;
900 if (br->getBits(1) != 1u) {
901 return ERROR_MALFORMED;
902 }
903 PTS |= br->getBits(15);
904 if (br->getBits(1) != 1u) {
905 return ERROR_MALFORMED;
906 }
907
908 ALOGV("PTS = 0x%016" PRIx64 " (%.2f)", PTS, PTS / 90000.0);
909
910 optional_bytes_remaining -= 5;
911
912 if (PTS_DTS_flags == 3) {
913 if (optional_bytes_remaining < 5u) {
914 return ERROR_MALFORMED;
915 }
916
917 if (br->getBits(4) != 1u) {
918 return ERROR_MALFORMED;
919 }
920
921 DTS = ((uint64_t)br->getBits(3)) << 30;
922 if (br->getBits(1) != 1u) {
923 return ERROR_MALFORMED;
924 }
925 DTS |= ((uint64_t)br->getBits(15)) << 15;
926 if (br->getBits(1) != 1u) {
927 return ERROR_MALFORMED;
928 }
929 DTS |= br->getBits(15);
930 if (br->getBits(1) != 1u) {
931 return ERROR_MALFORMED;
932 }
933
934 ALOGV("DTS = %" PRIu64, DTS);
935
936 optional_bytes_remaining -= 5;
937 }
938 }
939
940 if (ESCR_flag) {
941 if (optional_bytes_remaining < 6u) {
942 return ERROR_MALFORMED;
943 }
944
945 br->getBits(2);
946
947 uint64_t ESCR = ((uint64_t)br->getBits(3)) << 30;
948 if (br->getBits(1) != 1u) {
949 return ERROR_MALFORMED;
950 }
951 ESCR |= ((uint64_t)br->getBits(15)) << 15;
952 if (br->getBits(1) != 1u) {
953 return ERROR_MALFORMED;
954 }
955 ESCR |= br->getBits(15);
956 if (br->getBits(1) != 1u) {
957 return ERROR_MALFORMED;
958 }
959
960 ALOGV("ESCR = %" PRIu64, ESCR);
961 MY_LOGV("ESCR_extension = %u", br->getBits(9));
962
963 if (br->getBits(1) != 1u) {
964 return ERROR_MALFORMED;
965 }
966
967 optional_bytes_remaining -= 6;
968 }
969
970 if (ES_rate_flag) {
971 if (optional_bytes_remaining < 3u) {
972 return ERROR_MALFORMED;
973 }
974
975 if (br->getBits(1) != 1u) {
976 return ERROR_MALFORMED;
977 }
978 MY_LOGV("ES_rate = %u", br->getBits(22));
979 if (br->getBits(1) != 1u) {
980 return ERROR_MALFORMED;
981 }
982
983 optional_bytes_remaining -= 3;
984 }
985
986 br->skipBits(optional_bytes_remaining * 8);
987
988 // ES data follows.
989
990 if (PES_packet_length != 0) {
991 if (PES_packet_length < PES_header_data_length + 3) {
992 return ERROR_MALFORMED;
993 }
994
995 unsigned dataLength =
996 PES_packet_length - 3 - PES_header_data_length;
997
998 if (br->numBitsLeft() < dataLength * 8) {
999 ALOGE("PES packet does not carry enough data to contain "
1000 "payload. (numBitsLeft = %zu, required = %u)",
1001 br->numBitsLeft(), dataLength * 8);
1002
1003 return ERROR_MALFORMED;
1004 }
1005
1006 onPayloadData(
1007 PTS_DTS_flags, PTS, DTS, br->data(), dataLength, event);
1008
1009 br->skipBits(dataLength * 8);
1010 } else {
1011 onPayloadData(
1012 PTS_DTS_flags, PTS, DTS,
1013 br->data(), br->numBitsLeft() / 8, event);
1014
1015 size_t payloadSizeBits = br->numBitsLeft();
1016 if (payloadSizeBits % 8 != 0u) {
1017 return ERROR_MALFORMED;
1018 }
1019
1020 ALOGV("There's %zu bytes of payload.", payloadSizeBits / 8);
1021 }
1022 } else if (stream_id == 0xbe) { // padding_stream
1023 if (PES_packet_length == 0u) {
1024 return ERROR_MALFORMED;
1025 }
1026 br->skipBits(PES_packet_length * 8);
1027 } else {
1028 if (PES_packet_length == 0u) {
1029 return ERROR_MALFORMED;
1030 }
1031 br->skipBits(PES_packet_length * 8);
1032 }
1033
1034 return OK;
1035 }
1036
flush(SyncEvent * event)1037 status_t ATSParser::Stream::flush(SyncEvent *event) {
1038 if (mBuffer == NULL || mBuffer->size() == 0) {
1039 return OK;
1040 }
1041
1042 ALOGV("flushing stream 0x%04x size = %zu", mElementaryPID, mBuffer->size());
1043
1044 ABitReader br(mBuffer->data(), mBuffer->size());
1045
1046 status_t err = parsePES(&br, event);
1047
1048 mBuffer->setRange(0, 0);
1049
1050 return err;
1051 }
1052
onPayloadData(unsigned PTS_DTS_flags,uint64_t PTS,uint64_t,const uint8_t * data,size_t size,SyncEvent * event)1053 void ATSParser::Stream::onPayloadData(
1054 unsigned PTS_DTS_flags, uint64_t PTS, uint64_t /* DTS */,
1055 const uint8_t *data, size_t size, SyncEvent *event) {
1056 #if 0
1057 ALOGI("payload streamType 0x%02x, PTS = 0x%016llx, dPTS = %lld",
1058 mStreamType,
1059 PTS,
1060 (int64_t)PTS - mPrevPTS);
1061 mPrevPTS = PTS;
1062 #endif
1063
1064 ALOGV("onPayloadData mStreamType=0x%02x", mStreamType);
1065
1066 int64_t timeUs = 0ll; // no presentation timestamp available.
1067 if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
1068 timeUs = mProgram->convertPTSToTimestamp(PTS);
1069 }
1070
1071 status_t err = mQueue->appendData(data, size, timeUs);
1072
1073 if (mEOSReached) {
1074 mQueue->signalEOS();
1075 }
1076
1077 if (err != OK) {
1078 return;
1079 }
1080
1081 sp<ABuffer> accessUnit;
1082 bool found = false;
1083 while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
1084 if (mSource == NULL) {
1085 sp<MetaData> meta = mQueue->getFormat();
1086
1087 if (meta != NULL) {
1088 ALOGV("Stream PID 0x%08x of type 0x%02x now has data.",
1089 mElementaryPID, mStreamType);
1090
1091 const char *mime;
1092 if (meta->findCString(kKeyMIMEType, &mime)
1093 && !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)
1094 && !IsIDR(accessUnit)) {
1095 continue;
1096 }
1097 mSource = new AnotherPacketSource(meta);
1098 mSource->queueAccessUnit(accessUnit);
1099 }
1100 } else if (mQueue->getFormat() != NULL) {
1101 // After a discontinuity we invalidate the queue's format
1102 // and won't enqueue any access units to the source until
1103 // the queue has reestablished the new format.
1104
1105 if (mSource->getFormat() == NULL) {
1106 mSource->setFormat(mQueue->getFormat());
1107 }
1108 mSource->queueAccessUnit(accessUnit);
1109 }
1110
1111 // Every access unit has a pesStartOffset queued in |mPesStartOffsets|.
1112 off64_t pesStartOffset = -1;
1113 if (!mPesStartOffsets.empty()) {
1114 pesStartOffset = *mPesStartOffsets.begin();
1115 mPesStartOffsets.erase(mPesStartOffsets.begin());
1116 }
1117
1118 if (pesStartOffset >= 0 && (event != NULL) && !found && mQueue->getFormat() != NULL) {
1119 int32_t sync = 0;
1120 if (accessUnit->meta()->findInt32("isSync", &sync) && sync) {
1121 int64_t timeUs;
1122 if (accessUnit->meta()->findInt64("timeUs", &timeUs)) {
1123 found = true;
1124 event->init(pesStartOffset, mSource, timeUs);
1125 }
1126 }
1127 }
1128 }
1129 }
1130
getSource(SourceType type)1131 sp<MediaSource> ATSParser::Stream::getSource(SourceType type) {
1132 switch (type) {
1133 case VIDEO:
1134 {
1135 if (isVideo()) {
1136 return mSource;
1137 }
1138 break;
1139 }
1140
1141 case AUDIO:
1142 {
1143 if (isAudio()) {
1144 return mSource;
1145 }
1146 break;
1147 }
1148
1149 case META:
1150 {
1151 if (isMeta()) {
1152 return mSource;
1153 }
1154 break;
1155 }
1156
1157 default:
1158 break;
1159 }
1160
1161 return NULL;
1162 }
1163
1164 ////////////////////////////////////////////////////////////////////////////////
1165
ATSParser(uint32_t flags)1166 ATSParser::ATSParser(uint32_t flags)
1167 : mFlags(flags),
1168 mAbsoluteTimeAnchorUs(-1ll),
1169 mTimeOffsetValid(false),
1170 mTimeOffsetUs(0ll),
1171 mLastRecoveredPTS(-1ll),
1172 mNumTSPacketsParsed(0),
1173 mNumPCRs(0) {
1174 mPSISections.add(0 /* PID */, new PSISection);
1175 }
1176
~ATSParser()1177 ATSParser::~ATSParser() {
1178 }
1179
feedTSPacket(const void * data,size_t size,SyncEvent * event)1180 status_t ATSParser::feedTSPacket(const void *data, size_t size,
1181 SyncEvent *event) {
1182 if (size != kTSPacketSize) {
1183 ALOGE("Wrong TS packet size");
1184 return BAD_VALUE;
1185 }
1186
1187 ABitReader br((const uint8_t *)data, kTSPacketSize);
1188 return parseTS(&br, event);
1189 }
1190
signalDiscontinuity(DiscontinuityType type,const sp<AMessage> & extra)1191 void ATSParser::signalDiscontinuity(
1192 DiscontinuityType type, const sp<AMessage> &extra) {
1193 int64_t mediaTimeUs;
1194 if ((type & DISCONTINUITY_TIME) && extra != NULL) {
1195 if (extra->findInt64(IStreamListener::kKeyMediaTimeUs, &mediaTimeUs)) {
1196 mAbsoluteTimeAnchorUs = mediaTimeUs;
1197 }
1198 if ((mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)
1199 && extra->findInt64(
1200 IStreamListener::kKeyRecentMediaTimeUs, &mediaTimeUs)) {
1201 if (mAbsoluteTimeAnchorUs >= 0ll) {
1202 mediaTimeUs -= mAbsoluteTimeAnchorUs;
1203 }
1204 if (mTimeOffsetValid) {
1205 mediaTimeUs -= mTimeOffsetUs;
1206 }
1207 mLastRecoveredPTS = (mediaTimeUs * 9) / 100;
1208 }
1209 } else if (type == DISCONTINUITY_ABSOLUTE_TIME) {
1210 int64_t timeUs;
1211 if (!extra->findInt64("timeUs", &timeUs)) {
1212 ALOGE("timeUs not found");
1213 return;
1214 }
1215
1216 if (!mPrograms.empty()) {
1217 ALOGE("mPrograms is not empty");
1218 return;
1219 }
1220 mAbsoluteTimeAnchorUs = timeUs;
1221 return;
1222 } else if (type == DISCONTINUITY_TIME_OFFSET) {
1223 int64_t offset;
1224 if (!extra->findInt64("offset", &offset)) {
1225 ALOGE("offset not found");
1226 return;
1227 }
1228
1229 mTimeOffsetValid = true;
1230 mTimeOffsetUs = offset;
1231 return;
1232 }
1233
1234 for (size_t i = 0; i < mPrograms.size(); ++i) {
1235 mPrograms.editItemAt(i)->signalDiscontinuity(type, extra);
1236 }
1237 }
1238
signalEOS(status_t finalResult)1239 void ATSParser::signalEOS(status_t finalResult) {
1240 if (finalResult == (status_t) OK) {
1241 ALOGE("finalResult not OK");
1242 return;
1243 }
1244
1245 for (size_t i = 0; i < mPrograms.size(); ++i) {
1246 mPrograms.editItemAt(i)->signalEOS(finalResult);
1247 }
1248 }
1249
parseProgramAssociationTable(ABitReader * br)1250 void ATSParser::parseProgramAssociationTable(ABitReader *br) {
1251 unsigned table_id = br->getBits(8);
1252 ALOGV(" table_id = %u", table_id);
1253 if (table_id != 0x00u) {
1254 ALOGE("PAT data error!");
1255 return ;
1256 }
1257 unsigned section_syntax_indictor = br->getBits(1);
1258 ALOGV(" section_syntax_indictor = %u", section_syntax_indictor);
1259
1260 br->skipBits(1); // '0'
1261 MY_LOGV(" reserved = %u", br->getBits(2));
1262
1263 unsigned section_length = br->getBits(12);
1264 ALOGV(" section_length = %u", section_length);
1265
1266 MY_LOGV(" transport_stream_id = %u", br->getBits(16));
1267 MY_LOGV(" reserved = %u", br->getBits(2));
1268 MY_LOGV(" version_number = %u", br->getBits(5));
1269 MY_LOGV(" current_next_indicator = %u", br->getBits(1));
1270 MY_LOGV(" section_number = %u", br->getBits(8));
1271 MY_LOGV(" last_section_number = %u", br->getBits(8));
1272
1273 size_t numProgramBytes = (section_length - 5 /* header */ - 4 /* crc */);
1274
1275 for (size_t i = 0; i < numProgramBytes / 4; ++i) {
1276 unsigned program_number = br->getBits(16);
1277 ALOGV(" program_number = %u", program_number);
1278
1279 MY_LOGV(" reserved = %u", br->getBits(3));
1280
1281 if (program_number == 0) {
1282 MY_LOGV(" network_PID = 0x%04x", br->getBits(13));
1283 } else {
1284 unsigned programMapPID = br->getBits(13);
1285
1286 ALOGV(" program_map_PID = 0x%04x", programMapPID);
1287
1288 bool found = false;
1289 for (size_t index = 0; index < mPrograms.size(); ++index) {
1290 const sp<Program> &program = mPrograms.itemAt(index);
1291
1292 if (program->number() == program_number) {
1293 program->updateProgramMapPID(programMapPID);
1294 found = true;
1295 break;
1296 }
1297 }
1298
1299 if (!found) {
1300 mPrograms.push(
1301 new Program(this, program_number, programMapPID, mLastRecoveredPTS));
1302 }
1303
1304 if (mPSISections.indexOfKey(programMapPID) < 0) {
1305 mPSISections.add(programMapPID, new PSISection);
1306 }
1307 }
1308 }
1309
1310 MY_LOGV(" CRC = 0x%08x", br->getBits(32));
1311 }
1312
parsePID(ABitReader * br,unsigned PID,unsigned continuity_counter,unsigned payload_unit_start_indicator,SyncEvent * event)1313 status_t ATSParser::parsePID(
1314 ABitReader *br, unsigned PID,
1315 unsigned continuity_counter,
1316 unsigned payload_unit_start_indicator,
1317 SyncEvent *event) {
1318 ssize_t sectionIndex = mPSISections.indexOfKey(PID);
1319
1320 if (sectionIndex >= 0) {
1321 sp<PSISection> section = mPSISections.valueAt(sectionIndex);
1322
1323 if (payload_unit_start_indicator) {
1324 if (!section->isEmpty()) {
1325 ALOGW("parsePID encounters payload_unit_start_indicator when section is not empty");
1326 section->clear();
1327 }
1328
1329 unsigned skip = br->getBits(8);
1330 section->setSkipBytes(skip + 1); // skip filler bytes + pointer field itself
1331 br->skipBits(skip * 8);
1332 }
1333
1334 if (br->numBitsLeft() % 8 != 0) {
1335 return ERROR_MALFORMED;
1336 }
1337 status_t err = section->append(br->data(), br->numBitsLeft() / 8);
1338
1339 if (err != OK) {
1340 return err;
1341 }
1342
1343 if (!section->isComplete()) {
1344 return OK;
1345 }
1346
1347 if (!section->isCRCOkay()) {
1348 return BAD_VALUE;
1349 }
1350 ABitReader sectionBits(section->data(), section->size());
1351
1352 if (PID == 0) {
1353 parseProgramAssociationTable(§ionBits);
1354 } else {
1355 bool handled = false;
1356 for (size_t i = 0; i < mPrograms.size(); ++i) {
1357 status_t err;
1358 if (!mPrograms.editItemAt(i)->parsePSISection(
1359 PID, §ionBits, &err)) {
1360 continue;
1361 }
1362
1363 if (err != OK) {
1364 return err;
1365 }
1366
1367 handled = true;
1368 break;
1369 }
1370
1371 if (!handled) {
1372 mPSISections.removeItem(PID);
1373 section.clear();
1374 }
1375 }
1376
1377 if (section != NULL) {
1378 section->clear();
1379 }
1380
1381 return OK;
1382 }
1383
1384 bool handled = false;
1385 for (size_t i = 0; i < mPrograms.size(); ++i) {
1386 status_t err;
1387 if (mPrograms.editItemAt(i)->parsePID(
1388 PID, continuity_counter, payload_unit_start_indicator,
1389 br, &err, event)) {
1390 if (err != OK) {
1391 return err;
1392 }
1393
1394 handled = true;
1395 break;
1396 }
1397 }
1398
1399 if (!handled) {
1400 ALOGV("PID 0x%04x not handled.", PID);
1401 }
1402
1403 return OK;
1404 }
1405
parseAdaptationField(ABitReader * br,unsigned PID)1406 status_t ATSParser::parseAdaptationField(ABitReader *br, unsigned PID) {
1407 unsigned adaptation_field_length = br->getBits(8);
1408
1409 if (adaptation_field_length > 0) {
1410 if (adaptation_field_length * 8 > br->numBitsLeft()) {
1411 ALOGV("Adaptation field should be included in a single TS packet.");
1412 return ERROR_MALFORMED;
1413 }
1414
1415 unsigned discontinuity_indicator = br->getBits(1);
1416
1417 if (discontinuity_indicator) {
1418 ALOGV("PID 0x%04x: discontinuity_indicator = 1 (!!!)", PID);
1419 }
1420
1421 br->skipBits(2);
1422 unsigned PCR_flag = br->getBits(1);
1423
1424 size_t numBitsRead = 4;
1425
1426 if (PCR_flag) {
1427 if (adaptation_field_length * 8 < 52) {
1428 return ERROR_MALFORMED;
1429 }
1430 br->skipBits(4);
1431 uint64_t PCR_base = br->getBits(32);
1432 PCR_base = (PCR_base << 1) | br->getBits(1);
1433
1434 br->skipBits(6);
1435 unsigned PCR_ext = br->getBits(9);
1436
1437 // The number of bytes from the start of the current
1438 // MPEG2 transport stream packet up and including
1439 // the final byte of this PCR_ext field.
1440 size_t byteOffsetFromStartOfTSPacket =
1441 (188 - br->numBitsLeft() / 8);
1442
1443 uint64_t PCR = PCR_base * 300 + PCR_ext;
1444
1445 ALOGV("PID 0x%04x: PCR = 0x%016" PRIx64 " (%.2f)",
1446 PID, PCR, PCR / 27E6);
1447
1448 // The number of bytes received by this parser up to and
1449 // including the final byte of this PCR_ext field.
1450 uint64_t byteOffsetFromStart =
1451 uint64_t(mNumTSPacketsParsed) * 188 + byteOffsetFromStartOfTSPacket;
1452
1453 for (size_t i = 0; i < mPrograms.size(); ++i) {
1454 updatePCR(PID, PCR, byteOffsetFromStart);
1455 }
1456
1457 numBitsRead += 52;
1458 }
1459
1460 br->skipBits(adaptation_field_length * 8 - numBitsRead);
1461 }
1462 return OK;
1463 }
1464
parseTS(ABitReader * br,SyncEvent * event)1465 status_t ATSParser::parseTS(ABitReader *br, SyncEvent *event) {
1466 ALOGV("---");
1467
1468 unsigned sync_byte = br->getBits(8);
1469 if (sync_byte != 0x47u) {
1470 ALOGE("[error] parseTS: return error as sync_byte=0x%x", sync_byte);
1471 return BAD_VALUE;
1472 }
1473
1474 if (br->getBits(1)) { // transport_error_indicator
1475 // silently ignore.
1476 return OK;
1477 }
1478
1479 unsigned payload_unit_start_indicator = br->getBits(1);
1480 ALOGV("payload_unit_start_indicator = %u", payload_unit_start_indicator);
1481
1482 MY_LOGV("transport_priority = %u", br->getBits(1));
1483
1484 unsigned PID = br->getBits(13);
1485 ALOGV("PID = 0x%04x", PID);
1486
1487 MY_LOGV("transport_scrambling_control = %u", br->getBits(2));
1488
1489 unsigned adaptation_field_control = br->getBits(2);
1490 ALOGV("adaptation_field_control = %u", adaptation_field_control);
1491
1492 unsigned continuity_counter = br->getBits(4);
1493 ALOGV("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1494
1495 // ALOGI("PID = 0x%04x, continuity_counter = %u", PID, continuity_counter);
1496
1497 status_t err = OK;
1498
1499 if (adaptation_field_control == 2 || adaptation_field_control == 3) {
1500 err = parseAdaptationField(br, PID);
1501 }
1502 if (err == OK) {
1503 if (adaptation_field_control == 1 || adaptation_field_control == 3) {
1504 err = parsePID(br, PID, continuity_counter,
1505 payload_unit_start_indicator, event);
1506 }
1507 }
1508
1509 ++mNumTSPacketsParsed;
1510
1511 return err;
1512 }
1513
getSource(SourceType type)1514 sp<MediaSource> ATSParser::getSource(SourceType type) {
1515 sp<MediaSource> firstSourceFound;
1516 for (size_t i = 0; i < mPrograms.size(); ++i) {
1517 const sp<Program> &program = mPrograms.editItemAt(i);
1518 sp<MediaSource> source = program->getSource(type);
1519 if (source == NULL) {
1520 continue;
1521 }
1522 if (firstSourceFound == NULL) {
1523 firstSourceFound = source;
1524 }
1525 // Prefer programs with both audio/video
1526 switch (type) {
1527 case VIDEO: {
1528 if (program->hasSource(AUDIO)) {
1529 return source;
1530 }
1531 break;
1532 }
1533
1534 case AUDIO: {
1535 if (program->hasSource(VIDEO)) {
1536 return source;
1537 }
1538 break;
1539 }
1540
1541 default:
1542 return source;
1543 }
1544 }
1545
1546 return firstSourceFound;
1547 }
1548
hasSource(SourceType type) const1549 bool ATSParser::hasSource(SourceType type) const {
1550 for (size_t i = 0; i < mPrograms.size(); ++i) {
1551 const sp<Program> &program = mPrograms.itemAt(i);
1552 if (program->hasSource(type)) {
1553 return true;
1554 }
1555 }
1556
1557 return false;
1558 }
1559
PTSTimeDeltaEstablished()1560 bool ATSParser::PTSTimeDeltaEstablished() {
1561 if (mPrograms.isEmpty()) {
1562 return false;
1563 }
1564
1565 return mPrograms.editItemAt(0)->PTSTimeDeltaEstablished();
1566 }
1567
1568 __attribute__((no_sanitize("integer")))
updatePCR(unsigned,uint64_t PCR,uint64_t byteOffsetFromStart)1569 void ATSParser::updatePCR(
1570 unsigned /* PID */, uint64_t PCR, uint64_t byteOffsetFromStart) {
1571 ALOGV("PCR 0x%016" PRIx64 " @ %" PRIx64, PCR, byteOffsetFromStart);
1572
1573 if (mNumPCRs == 2) {
1574 mPCR[0] = mPCR[1];
1575 mPCRBytes[0] = mPCRBytes[1];
1576 mSystemTimeUs[0] = mSystemTimeUs[1];
1577 mNumPCRs = 1;
1578 }
1579
1580 mPCR[mNumPCRs] = PCR;
1581 mPCRBytes[mNumPCRs] = byteOffsetFromStart;
1582 mSystemTimeUs[mNumPCRs] = ALooper::GetNowUs();
1583
1584 ++mNumPCRs;
1585
1586 if (mNumPCRs == 2) {
1587 /* Unsigned overflow here */
1588 double transportRate =
1589 (mPCRBytes[1] - mPCRBytes[0]) * 27E6 / (mPCR[1] - mPCR[0]);
1590
1591 ALOGV("transportRate = %.2f bytes/sec", transportRate);
1592 }
1593 }
1594
1595 ////////////////////////////////////////////////////////////////////////////////
1596
1597
1598 // CRC32 used for PSI section. The table was generated by following command:
1599 // $ python pycrc.py --model crc-32-mpeg --algorithm table-driven --generate c
1600 // Visit http://www.tty1.net/pycrc/index_en.html for more details.
1601 uint32_t ATSParser::PSISection::CRC_TABLE[] = {
1602 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
1603 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
1604 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
1605 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
1606 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
1607 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
1608 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
1609 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
1610 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
1611 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
1612 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
1613 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
1614 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
1615 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
1616 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
1617 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
1618 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
1619 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
1620 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
1621 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
1622 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
1623 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
1624 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
1625 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
1626 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
1627 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
1628 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
1629 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
1630 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
1631 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
1632 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
1633 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
1634 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
1635 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
1636 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
1637 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
1638 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
1639 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
1640 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
1641 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
1642 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
1643 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
1644 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
1645 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
1646 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
1647 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
1648 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
1649 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
1650 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
1651 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
1652 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
1653 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
1654 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
1655 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
1656 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
1657 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
1658 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
1659 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
1660 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
1661 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
1662 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
1663 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
1664 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
1665 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
1666 };
1667
PSISection()1668 ATSParser::PSISection::PSISection() :
1669 mSkipBytes(0) {
1670 }
1671
~PSISection()1672 ATSParser::PSISection::~PSISection() {
1673 }
1674
append(const void * data,size_t size)1675 status_t ATSParser::PSISection::append(const void *data, size_t size) {
1676 if (mBuffer == NULL || mBuffer->size() + size > mBuffer->capacity()) {
1677 size_t newCapacity =
1678 (mBuffer == NULL) ? size : mBuffer->capacity() + size;
1679
1680 newCapacity = (newCapacity + 1023) & ~1023;
1681
1682 sp<ABuffer> newBuffer = new ABuffer(newCapacity);
1683
1684 if (mBuffer != NULL) {
1685 memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
1686 newBuffer->setRange(0, mBuffer->size());
1687 } else {
1688 newBuffer->setRange(0, 0);
1689 }
1690
1691 mBuffer = newBuffer;
1692 }
1693
1694 memcpy(mBuffer->data() + mBuffer->size(), data, size);
1695 mBuffer->setRange(0, mBuffer->size() + size);
1696
1697 return OK;
1698 }
1699
setSkipBytes(uint8_t skip)1700 void ATSParser::PSISection::setSkipBytes(uint8_t skip) {
1701 mSkipBytes = skip;
1702 }
1703
clear()1704 void ATSParser::PSISection::clear() {
1705 if (mBuffer != NULL) {
1706 mBuffer->setRange(0, 0);
1707 }
1708 mSkipBytes = 0;
1709 }
1710
isComplete() const1711 bool ATSParser::PSISection::isComplete() const {
1712 if (mBuffer == NULL || mBuffer->size() < 3) {
1713 return false;
1714 }
1715
1716 unsigned sectionLength = U16_AT(mBuffer->data() + 1) & 0xfff;
1717 return mBuffer->size() >= sectionLength + 3;
1718 }
1719
isEmpty() const1720 bool ATSParser::PSISection::isEmpty() const {
1721 return mBuffer == NULL || mBuffer->size() == 0;
1722 }
1723
data() const1724 const uint8_t *ATSParser::PSISection::data() const {
1725 return mBuffer == NULL ? NULL : mBuffer->data();
1726 }
1727
size() const1728 size_t ATSParser::PSISection::size() const {
1729 return mBuffer == NULL ? 0 : mBuffer->size();
1730 }
1731
isCRCOkay() const1732 bool ATSParser::PSISection::isCRCOkay() const {
1733 if (!isComplete()) {
1734 return false;
1735 }
1736 uint8_t* data = mBuffer->data();
1737
1738 // Return true if section_syntax_indicator says no section follows the field section_length.
1739 if ((data[1] & 0x80) == 0) {
1740 return true;
1741 }
1742
1743 unsigned sectionLength = U16_AT(data + 1) & 0xfff;
1744 ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes);
1745
1746
1747 if(sectionLength < mSkipBytes) {
1748 ALOGE("b/28333006");
1749 android_errorWriteLog(0x534e4554, "28333006");
1750 return false;
1751 }
1752
1753 // Skip the preceding field present when payload start indicator is on.
1754 sectionLength -= mSkipBytes;
1755
1756 uint32_t crc = 0xffffffff;
1757 for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) {
1758 uint8_t b = data[i];
1759 int index = ((crc >> 24) ^ (b & 0xff)) & 0xff;
1760 crc = CRC_TABLE[index] ^ (crc << 8);
1761 }
1762 ALOGV("crc: %08x\n", crc);
1763 return (crc == 0);
1764 }
1765 } // namespace android
1766