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 "MPEG2TSExtractor"
19
20 #include <inttypes.h>
21 #include <utils/Log.h>
22
23 #include <android-base/macros.h>
24
25 #include "MPEG2TSExtractor.h"
26
27 #include <media/IStreamSource.h>
28 #include <media/stagefright/foundation/ABuffer.h>
29 #include <media/stagefright/foundation/ADebug.h>
30 #include <media/stagefright/foundation/ALooper.h>
31 #include <media/stagefright/foundation/AUtils.h>
32 #include <media/stagefright/foundation/MediaKeys.h>
33 #include <media/stagefright/DataSourceBase.h>
34 #include <media/stagefright/MediaDefs.h>
35 #include <media/stagefright/MediaErrors.h>
36 #include <media/stagefright/MetaData.h>
37 #include <media/stagefright/Utils.h>
38 #include <mpeg2ts/AnotherPacketSource.h>
39 #include <utils/String8.h>
40
41 #include <hidl/HybridInterface.h>
42 #include <android/hardware/cas/1.0/ICas.h>
43
44 namespace android {
45
46 using hardware::cas::V1_0::ICas;
47
48 static const size_t kTSPacketSize = 188;
49 static const int kMaxDurationReadSize = 250000LL;
50 static const int kMaxDurationRetry = 6;
51
52 struct MPEG2TSSource : public MediaTrackHelper {
53 MPEG2TSSource(
54 MPEG2TSExtractor *extractor,
55 const sp<AnotherPacketSource> &impl,
56 bool doesSeek);
57 virtual ~MPEG2TSSource();
58
59 virtual media_status_t start();
60 virtual media_status_t stop();
61 virtual media_status_t getFormat(AMediaFormat *);
62
63 virtual media_status_t read(
64 MediaBufferHelper **buffer, const ReadOptions *options = NULL);
65
66 private:
67 MPEG2TSExtractor *mExtractor;
68 sp<AnotherPacketSource> mImpl;
69
70 // If there are both audio and video streams, only the video stream
71 // will signal seek on the extractor; otherwise the single stream will seek.
72 bool mDoesSeek;
73
74 DISALLOW_EVIL_CONSTRUCTORS(MPEG2TSSource);
75 };
76
MPEG2TSSource(MPEG2TSExtractor * extractor,const sp<AnotherPacketSource> & impl,bool doesSeek)77 MPEG2TSSource::MPEG2TSSource(
78 MPEG2TSExtractor *extractor,
79 const sp<AnotherPacketSource> &impl,
80 bool doesSeek)
81 : mExtractor(extractor),
82 mImpl(impl),
83 mDoesSeek(doesSeek) {
84 }
85
~MPEG2TSSource()86 MPEG2TSSource::~MPEG2TSSource() {
87 }
88
start()89 media_status_t MPEG2TSSource::start() {
90 // initialize with one small buffer, but allow growth
91 mBufferGroup->init(1 /* one buffer */, 256 /* buffer size */, 64 /* max number of buffers */);
92
93 if (!mImpl->start(NULL)) { // AnotherPacketSource::start() doesn't use its argument
94 return AMEDIA_OK;
95 }
96 return AMEDIA_ERROR_UNKNOWN;
97 }
98
stop()99 media_status_t MPEG2TSSource::stop() {
100 if (!mImpl->stop()) {
101 return AMEDIA_OK;
102 }
103 return AMEDIA_ERROR_UNKNOWN;
104 }
105
copyAMessageToAMediaFormat(AMediaFormat * format,sp<AMessage> msg)106 void copyAMessageToAMediaFormat(AMediaFormat *format, sp<AMessage> msg) {
107 size_t numEntries = msg->countEntries();
108 for (size_t i = 0; i < numEntries; i++) {
109 AMessage::Type type;
110 const char *name = msg->getEntryNameAt(i, &type);
111 AMessage::ItemData id = msg->getEntryAt(i);
112
113 switch (type) {
114 case AMessage::kTypeInt32:
115 int32_t val32;
116 if (id.find(&val32)) {
117 AMediaFormat_setInt32(format, name, val32);
118 }
119 break;
120 case AMessage::kTypeInt64:
121 int64_t val64;
122 if (id.find(&val64)) {
123 AMediaFormat_setInt64(format, name, val64);
124 }
125 break;
126 case AMessage::kTypeFloat:
127 float valfloat;
128 if (id.find(&valfloat)) {
129 AMediaFormat_setFloat(format, name, valfloat);
130 }
131 break;
132 case AMessage::kTypeDouble:
133 double valdouble;
134 if (id.find(&valdouble)) {
135 AMediaFormat_setDouble(format, name, valdouble);
136 }
137 break;
138 case AMessage::kTypeString:
139 if (AString s; id.find(&s)) {
140 AMediaFormat_setString(format, name, s.c_str());
141 }
142 break;
143 case AMessage::kTypeBuffer:
144 {
145 sp<ABuffer> buffer;
146 if (id.find(&buffer)) {
147 AMediaFormat_setBuffer(format, name, buffer->data(), buffer->size());
148 }
149 break;
150 }
151 default:
152 ALOGW("ignoring unsupported type %d '%s'", type, name);
153 }
154 }
155 }
156
getFormat(AMediaFormat * meta)157 media_status_t MPEG2TSSource::getFormat(AMediaFormat *meta) {
158 sp<MetaData> implMeta = mImpl->getFormat();
159 sp<AMessage> msg;
160 convertMetaDataToMessage(implMeta, &msg);
161 copyAMessageToAMediaFormat(meta, msg);
162 return AMEDIA_OK;
163 }
164
read(MediaBufferHelper ** out,const ReadOptions * options)165 media_status_t MPEG2TSSource::read(
166 MediaBufferHelper **out, const ReadOptions *options) {
167 *out = NULL;
168
169 int64_t seekTimeUs;
170 ReadOptions::SeekMode seekMode;
171 if (mDoesSeek && options && options->getSeekTo(&seekTimeUs, &seekMode)) {
172 // seek is needed
173 status_t err = mExtractor->seek(seekTimeUs, (ReadOptions::SeekMode)seekMode);
174 if (err == ERROR_END_OF_STREAM) {
175 return AMEDIA_ERROR_END_OF_STREAM;
176 } else if (err != OK) {
177 return AMEDIA_ERROR_UNKNOWN;
178 }
179 }
180
181 if (mExtractor->feedUntilBufferAvailable(mImpl) != OK) {
182 return AMEDIA_ERROR_END_OF_STREAM;
183 }
184
185 MediaBufferBase *mbuf;
186 mImpl->read(&mbuf, (MediaTrack::ReadOptions*) options);
187 size_t length = mbuf->range_length();
188 MediaBufferHelper *outbuf;
189 mBufferGroup->acquire_buffer(&outbuf, false, length);
190 memcpy(outbuf->data(), mbuf->data(), length);
191 outbuf->set_range(0, length);
192 *out = outbuf;
193 MetaDataBase &inMeta = mbuf->meta_data();
194 AMediaFormat *outMeta = outbuf->meta_data();
195 AMediaFormat_clear(outMeta);
196 int64_t val64;
197 if (inMeta.findInt64(kKeyTime, &val64)) {
198 AMediaFormat_setInt64(outMeta, AMEDIAFORMAT_KEY_TIME_US, val64);
199 }
200 int32_t val32;
201 if (inMeta.findInt32(kKeyIsSyncFrame, &val32)) {
202 AMediaFormat_setInt32(outMeta, AMEDIAFORMAT_KEY_IS_SYNC_FRAME, val32);
203 }
204 if (inMeta.findInt32(kKeyCryptoMode, &val32)) {
205 AMediaFormat_setInt32(outMeta, AMEDIAFORMAT_KEY_CRYPTO_MODE, val32);
206 }
207 uint32_t bufType;
208 const void *bufData;
209 size_t bufSize;
210 if (inMeta.findData(kKeyCryptoIV, &bufType, &bufData, &bufSize)) {
211 AMediaFormat_setBuffer(outMeta, AMEDIAFORMAT_KEY_CRYPTO_IV, bufData, bufSize);
212 }
213 if (inMeta.findData(kKeyCryptoKey, &bufType, &bufData, &bufSize)) {
214 AMediaFormat_setBuffer(outMeta, AMEDIAFORMAT_KEY_CRYPTO_KEY, bufData, bufSize);
215 }
216 if (inMeta.findData(kKeyPlainSizes, &bufType, &bufData, &bufSize)) {
217 AMediaFormat_setBuffer(outMeta, AMEDIAFORMAT_KEY_CRYPTO_PLAIN_SIZES, bufData, bufSize);
218 }
219 if (inMeta.findData(kKeyEncryptedSizes, &bufType, &bufData, &bufSize)) {
220 AMediaFormat_setBuffer(outMeta, AMEDIAFORMAT_KEY_CRYPTO_ENCRYPTED_SIZES, bufData, bufSize);
221 }
222 if (inMeta.findData(kKeySEI, &bufType, &bufData, &bufSize)) {
223 AMediaFormat_setBuffer(outMeta, AMEDIAFORMAT_KEY_SEI, bufData, bufSize);
224 }
225 if (inMeta.findData(kKeyAudioPresentationInfo, &bufType, &bufData, &bufSize)) {
226 AMediaFormat_setBuffer(outMeta, AMEDIAFORMAT_KEY_AUDIO_PRESENTATION_INFO, bufData, bufSize);
227 }
228 mbuf->release();
229 return AMEDIA_OK;
230 }
231
232 ////////////////////////////////////////////////////////////////////////////////
233
MPEG2TSExtractor(DataSourceHelper * source)234 MPEG2TSExtractor::MPEG2TSExtractor(DataSourceHelper *source)
235 : mDataSource(source),
236 mParser(new ATSParser),
237 mLastSyncEvent(0),
238 mOffset(0) {
239 char header;
240 if (source->readAt(0, &header, 1) == 1 && header == 0x47) {
241 mHeaderSkip = 0;
242 } else {
243 mHeaderSkip = 4;
244 }
245 init();
246 }
247
~MPEG2TSExtractor()248 MPEG2TSExtractor::~MPEG2TSExtractor() {
249 delete mDataSource;
250 }
251
countTracks()252 size_t MPEG2TSExtractor::countTracks() {
253 return mSourceImpls.size();
254 }
255
getTrack(size_t index)256 MediaTrackHelper *MPEG2TSExtractor::getTrack(size_t index) {
257 if (index >= mSourceImpls.size()) {
258 return NULL;
259 }
260
261 // The seek reference track (video if present; audio otherwise) performs
262 // seek requests, while other tracks ignore requests.
263 return new MPEG2TSSource(this, mSourceImpls.editItemAt(index),
264 (mSeekSyncPoints == &mSyncPoints.editItemAt(index)));
265 }
266
getTrackMetaData(AMediaFormat * meta,size_t index,uint32_t)267 media_status_t MPEG2TSExtractor::getTrackMetaData(
268 AMediaFormat *meta,
269 size_t index, uint32_t /* flags */) {
270 if (meta == nullptr) {
271 return AMEDIA_ERROR_INVALID_PARAMETER;
272 }
273 sp<MetaData> implMeta = index < mSourceImpls.size()
274 ? mSourceImpls.editItemAt(index)->getFormat() : NULL;
275 if (implMeta == NULL) {
276 return AMEDIA_ERROR_UNKNOWN;
277 }
278 sp<AMessage> msg = new AMessage;
279 convertMetaDataToMessage(implMeta, &msg);
280 copyAMessageToAMediaFormat(meta, msg);
281 return AMEDIA_OK;
282 }
283
getMetaData(AMediaFormat * meta)284 media_status_t MPEG2TSExtractor::getMetaData(AMediaFormat *meta) {
285 AMediaFormat_setString(meta, AMEDIAFORMAT_KEY_MIME, MEDIA_MIMETYPE_CONTAINER_MPEG2TS);
286 return AMEDIA_OK;
287 }
288
289 //static
isScrambledFormat(MetaDataBase & format)290 bool MPEG2TSExtractor::isScrambledFormat(MetaDataBase &format) {
291 const char *mime;
292 return format.findCString(kKeyMIMEType, &mime)
293 && (!strcasecmp(MEDIA_MIMETYPE_VIDEO_SCRAMBLED, mime)
294 || !strcasecmp(MEDIA_MIMETYPE_AUDIO_SCRAMBLED, mime));
295 }
296
setMediaCas(const uint8_t * casToken,size_t size)297 media_status_t MPEG2TSExtractor::setMediaCas(const uint8_t* casToken, size_t size) {
298 HalToken halToken;
299 halToken.setToExternal((uint8_t*)casToken, size);
300 sp<ICas> cas = ICas::castFrom(retrieveHalInterface(halToken));
301 ALOGD("setMediaCas: %p", cas.get());
302
303 status_t err = mParser->setMediaCas(cas);
304 if (err == OK) {
305 ALOGI("All tracks now have descramblers");
306 init();
307 return AMEDIA_OK;
308 }
309 return AMEDIA_ERROR_UNKNOWN;
310 }
311
findIndexOfSource(const sp<AnotherPacketSource> & impl,size_t * index)312 status_t MPEG2TSExtractor::findIndexOfSource(const sp<AnotherPacketSource> &impl, size_t *index) {
313 for (size_t i = 0; i < mSourceImpls.size(); i++) {
314 if (mSourceImpls[i] == impl) {
315 *index = i;
316 return OK;
317 }
318 }
319 return NAME_NOT_FOUND;
320 }
321
addSource(const sp<AnotherPacketSource> & impl)322 void MPEG2TSExtractor::addSource(const sp<AnotherPacketSource> &impl) {
323 size_t index;
324 if (findIndexOfSource(impl, &index) != OK) {
325 mSourceImpls.push(impl);
326 mSyncPoints.push();
327 }
328 }
329
init()330 void MPEG2TSExtractor::init() {
331 bool haveAudio = false;
332 bool haveVideo = false;
333 int64_t startTime = ALooper::GetNowUs();
334 size_t index;
335
336 status_t err;
337 while ((err = feedMore(true /* isInit */)) == OK
338 || err == ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED) {
339 if (haveAudio && haveVideo) {
340 addSyncPoint_l(mLastSyncEvent);
341 mLastSyncEvent.reset();
342 break;
343 }
344 if (!haveVideo) {
345 sp<AnotherPacketSource> impl = mParser->getSource(ATSParser::VIDEO);
346
347 if (impl != NULL) {
348 sp<MetaData> format = impl->getFormat();
349 if (format != NULL) {
350 haveVideo = true;
351 addSource(impl);
352 if (!isScrambledFormat(*(format.get()))) {
353 if (findIndexOfSource(impl, &index) == OK) {
354 mSeekSyncPoints = &mSyncPoints.editItemAt(index);
355 }
356 }
357 }
358 }
359 }
360
361 if (!haveAudio) {
362 sp<AnotherPacketSource> impl = mParser->getSource(ATSParser::AUDIO);
363
364 if (impl != NULL) {
365 sp<MetaData> format = impl->getFormat();
366 if (format != NULL) {
367 haveAudio = true;
368 addSource(impl);
369 if (!isScrambledFormat(*(format.get())) && !haveVideo) {
370 if (findIndexOfSource(impl, &index) == OK) {
371 mSeekSyncPoints = &mSyncPoints.editItemAt(index);
372 }
373 }
374 }
375 }
376 }
377
378 addSyncPoint_l(mLastSyncEvent);
379 mLastSyncEvent.reset();
380
381 // ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED is returned when the mpeg2ts
382 // is scrambled but we don't have a MediaCas object set. The extraction
383 // will only continue when setMediaCas() is called successfully.
384 if (err == ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED) {
385 ALOGI("stopped parsing scrambled content, "
386 "haveAudio=%d, haveVideo=%d, elaspedTime=%" PRId64,
387 haveAudio, haveVideo, ALooper::GetNowUs() - startTime);
388 return;
389 }
390
391 // Wait only for 2 seconds to detect audio/video streams.
392 if (ALooper::GetNowUs() - startTime > 2000000LL) {
393 break;
394 }
395 }
396
397 off64_t size;
398 if (mDataSource->getSize(&size) == OK && (haveAudio || haveVideo)) {
399 size_t prevSyncSize = 1;
400 int64_t durationUs = -1;
401 List<int64_t> durations;
402 // Estimate duration --- stabilize until you get <500ms deviation.
403 while (feedMore() == OK
404 && ALooper::GetNowUs() - startTime <= 2000000LL) {
405 if (mSeekSyncPoints->size() > prevSyncSize) {
406 prevSyncSize = mSeekSyncPoints->size();
407 int64_t diffUs = mSeekSyncPoints->keyAt(prevSyncSize - 1)
408 - mSeekSyncPoints->keyAt(0);
409 off64_t diffOffset = mSeekSyncPoints->valueAt(prevSyncSize - 1)
410 - mSeekSyncPoints->valueAt(0);
411 int64_t currentDurationUs = size * diffUs / diffOffset;
412 durations.push_back(currentDurationUs);
413 if (durations.size() > 5) {
414 durations.erase(durations.begin());
415 int64_t min = *durations.begin();
416 int64_t max = *durations.begin();
417 for (auto duration : durations) {
418 if (min > duration) {
419 min = duration;
420 }
421 if (max < duration) {
422 max = duration;
423 }
424 }
425 if (max - min < 500 * 1000) {
426 durationUs = currentDurationUs;
427 break;
428 }
429 }
430 }
431 }
432
433 bool found = false;
434 for (int i = 0; i < ATSParser::NUM_SOURCE_TYPES; ++i) {
435 ATSParser::SourceType type = static_cast<ATSParser::SourceType>(i);
436 sp<AnotherPacketSource> impl = mParser->getSource(type);
437 if (impl == NULL) {
438 continue;
439 }
440
441 int64_t trackDurationUs = durationUs;
442
443 status_t err;
444 int64_t bufferedDurationUs = impl->getBufferedDurationUs(&err);
445 if (err == ERROR_END_OF_STREAM) {
446 trackDurationUs = bufferedDurationUs;
447 }
448 if (trackDurationUs > 0) {
449 ALOGV("[SourceType%d] durationUs=%" PRId64 "", type, trackDurationUs);
450 const sp<MetaData> meta = impl->getFormat();
451 meta->setInt64(kKeyDuration, trackDurationUs);
452 impl->setFormat(meta);
453
454 found = true;
455 }
456 }
457 if (!found) {
458 estimateDurationsFromTimesUsAtEnd();
459 }
460 }
461
462 ALOGI("haveAudio=%d, haveVideo=%d, elaspedTime=%" PRId64,
463 haveAudio, haveVideo, ALooper::GetNowUs() - startTime);
464 }
465
feedMore(bool isInit)466 status_t MPEG2TSExtractor::feedMore(bool isInit) {
467 Mutex::Autolock autoLock(mLock);
468
469 uint8_t packet[kTSPacketSize];
470 ssize_t n = mDataSource->readAt(mOffset + mHeaderSkip, packet, kTSPacketSize);
471
472 if (n < (ssize_t)kTSPacketSize) {
473 if (n >= 0) {
474 mParser->signalEOS(ERROR_END_OF_STREAM);
475 }
476 return (n < 0) ? (status_t)n : ERROR_END_OF_STREAM;
477 }
478
479 ATSParser::SyncEvent event(mOffset);
480 mOffset += mHeaderSkip + n;
481 status_t err = mParser->feedTSPacket(packet, kTSPacketSize, &event);
482 if (event.hasReturnedData()) {
483 if (isInit) {
484 mLastSyncEvent = event;
485 } else {
486 addSyncPoint_l(event);
487 }
488 }
489 return err;
490 }
491
addSyncPoint_l(const ATSParser::SyncEvent & event)492 void MPEG2TSExtractor::addSyncPoint_l(const ATSParser::SyncEvent &event) {
493 if (!event.hasReturnedData()) {
494 return;
495 }
496
497 for (size_t i = 0; i < mSourceImpls.size(); ++i) {
498 if (mSourceImpls[i].get() == event.getMediaSource().get()) {
499 KeyedVector<int64_t, off64_t> *syncPoints = &mSyncPoints.editItemAt(i);
500 syncPoints->add(event.getTimeUs(), event.getOffset());
501 // We're keeping the size of the sync points at most 5mb per a track.
502 size_t size = syncPoints->size();
503 if (size >= 327680) {
504 int64_t firstTimeUs = syncPoints->keyAt(0);
505 int64_t lastTimeUs = syncPoints->keyAt(size - 1);
506 if (event.getTimeUs() - firstTimeUs > lastTimeUs - event.getTimeUs()) {
507 syncPoints->removeItemsAt(0, 4096);
508 } else {
509 syncPoints->removeItemsAt(size - 4096, 4096);
510 }
511 }
512 break;
513 }
514 }
515 }
516
estimateDurationsFromTimesUsAtEnd()517 status_t MPEG2TSExtractor::estimateDurationsFromTimesUsAtEnd() {
518 if (!(mDataSource->flags() & DataSourceBase::kIsLocalFileSource)) {
519 return ERROR_UNSUPPORTED;
520 }
521
522 off64_t size = 0;
523 status_t err = mDataSource->getSize(&size);
524 if (err != OK) {
525 return err;
526 }
527
528 uint8_t packet[kTSPacketSize];
529 const off64_t zero = 0;
530 off64_t offset = max(zero, size - kMaxDurationReadSize);
531 if (mDataSource->readAt(offset, &packet, 0) < 0) {
532 return ERROR_IO;
533 }
534
535 int retry = 0;
536 bool allDurationsFound = false;
537 int64_t timeAnchorUs = mParser->getFirstPTSTimeUs();
538 do {
539 int bytesRead = 0;
540 sp<ATSParser> parser = new ATSParser(ATSParser::TS_TIMESTAMPS_ARE_ABSOLUTE);
541 ATSParser::SyncEvent ev(0);
542 offset = max(zero, size - (kMaxDurationReadSize << retry));
543 offset = (offset / kTSPacketSize) * kTSPacketSize;
544 for (;;) {
545 if (bytesRead >= kMaxDurationReadSize << max(0, retry - 1)) {
546 break;
547 }
548
549 ssize_t n = mDataSource->readAt(offset+mHeaderSkip, packet, kTSPacketSize);
550 if (n < 0) {
551 return n;
552 } else if (n < (ssize_t)kTSPacketSize) {
553 break;
554 }
555
556 offset += kTSPacketSize + mHeaderSkip;
557 bytesRead += kTSPacketSize + mHeaderSkip;
558 err = parser->feedTSPacket(packet, kTSPacketSize, &ev);
559 if (err != OK) {
560 return err;
561 }
562
563 if (ev.hasReturnedData()) {
564 int64_t durationUs = ev.getTimeUs();
565 ATSParser::SourceType type = ev.getType();
566 ev.reset();
567
568 int64_t firstTimeUs;
569 sp<AnotherPacketSource> src = mParser->getSource(type);
570 if (src == NULL || src->nextBufferTime(&firstTimeUs) != OK) {
571 continue;
572 }
573 durationUs += src->getEstimatedBufferDurationUs();
574 durationUs -= timeAnchorUs;
575 durationUs -= firstTimeUs;
576 if (durationUs > 0) {
577 int64_t origDurationUs, lastDurationUs;
578 const sp<MetaData> meta = src->getFormat();
579 const uint32_t kKeyLastDuration = 'ldur';
580 // Require two consecutive duration calculations to be within 1 sec before
581 // updating; use MetaData to store previous duration estimate in per-stream
582 // context.
583 if (!meta->findInt64(kKeyDuration, &origDurationUs)
584 || !meta->findInt64(kKeyLastDuration, &lastDurationUs)
585 || (origDurationUs < durationUs
586 && abs(durationUs - lastDurationUs) < 60000000)) {
587 meta->setInt64(kKeyDuration, durationUs);
588 }
589 meta->setInt64(kKeyLastDuration, durationUs);
590 }
591 }
592 }
593
594 if (!allDurationsFound) {
595 allDurationsFound = true;
596 for (auto t: {ATSParser::VIDEO, ATSParser::AUDIO}) {
597 sp<AnotherPacketSource> src = mParser->getSource(t);
598 if (src == NULL) {
599 continue;
600 }
601 int64_t durationUs;
602 const sp<MetaData> meta = src->getFormat();
603 if (!meta->findInt64(kKeyDuration, &durationUs)) {
604 allDurationsFound = false;
605 break;
606 }
607 }
608 }
609
610 ++retry;
611 } while(!allDurationsFound && offset > 0 && retry <= kMaxDurationRetry);
612
613 return allDurationsFound? OK : ERROR_UNSUPPORTED;
614 }
615
flags() const616 uint32_t MPEG2TSExtractor::flags() const {
617 return CAN_PAUSE | CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD;
618 }
619
seek(int64_t seekTimeUs,const MediaTrackHelper::ReadOptions::SeekMode & seekMode)620 status_t MPEG2TSExtractor::seek(int64_t seekTimeUs,
621 const MediaTrackHelper::ReadOptions::SeekMode &seekMode) {
622 if (mSeekSyncPoints == NULL || mSeekSyncPoints->isEmpty()) {
623 ALOGW("No sync point to seek to.");
624 // ... and therefore we have nothing useful to do here.
625 return OK;
626 }
627
628 // Determine whether we're seeking beyond the known area.
629 bool shouldSeekBeyond =
630 (seekTimeUs > mSeekSyncPoints->keyAt(mSeekSyncPoints->size() - 1));
631
632 // Determine the sync point to seek.
633 size_t index = 0;
634 for (; index < mSeekSyncPoints->size(); ++index) {
635 int64_t timeUs = mSeekSyncPoints->keyAt(index);
636 if (timeUs > seekTimeUs) {
637 break;
638 }
639 }
640
641 switch (seekMode) {
642 case MediaTrackHelper::ReadOptions::SEEK_NEXT_SYNC:
643 if (index == mSeekSyncPoints->size()) {
644 ALOGW("Next sync not found; starting from the latest sync.");
645 --index;
646 }
647 break;
648 case MediaTrackHelper::ReadOptions::SEEK_CLOSEST_SYNC:
649 case MediaTrackHelper::ReadOptions::SEEK_CLOSEST:
650 ALOGW("seekMode not supported: %d; falling back to PREVIOUS_SYNC",
651 seekMode);
652 FALLTHROUGH_INTENDED;
653 case MediaTrackHelper::ReadOptions::SEEK_PREVIOUS_SYNC:
654 if (index == 0) {
655 ALOGW("Previous sync not found; starting from the earliest "
656 "sync.");
657 } else {
658 --index;
659 }
660 break;
661 default:
662 return ERROR_UNSUPPORTED;
663 }
664 if (!shouldSeekBeyond || mOffset <= mSeekSyncPoints->valueAt(index)) {
665 int64_t actualSeekTimeUs = mSeekSyncPoints->keyAt(index);
666 mOffset = mSeekSyncPoints->valueAt(index);
667 status_t err = queueDiscontinuityForSeek(actualSeekTimeUs);
668 if (err != OK) {
669 return err;
670 }
671 }
672
673 if (shouldSeekBeyond) {
674 status_t err = seekBeyond(seekTimeUs);
675 if (err != OK) {
676 return err;
677 }
678 }
679
680 // Fast-forward to sync frame.
681 for (size_t i = 0; i < mSourceImpls.size(); ++i) {
682 const sp<AnotherPacketSource> &impl = mSourceImpls[i];
683 status_t err;
684 feedUntilBufferAvailable(impl);
685 while (impl->hasBufferAvailable(&err)) {
686 sp<AMessage> meta = impl->getMetaAfterLastDequeued(0);
687 sp<ABuffer> buffer;
688 if (meta == NULL) {
689 return UNKNOWN_ERROR;
690 }
691 int32_t sync;
692 if (meta->findInt32("isSync", &sync) && sync) {
693 break;
694 }
695 err = impl->dequeueAccessUnit(&buffer);
696 if (err != OK) {
697 return err;
698 }
699 feedUntilBufferAvailable(impl);
700 }
701 }
702
703 return OK;
704 }
705
queueDiscontinuityForSeek(int64_t actualSeekTimeUs)706 status_t MPEG2TSExtractor::queueDiscontinuityForSeek(int64_t actualSeekTimeUs) {
707 // Signal discontinuity
708 sp<AMessage> extra(new AMessage);
709 extra->setInt64(kATSParserKeyMediaTimeUs, actualSeekTimeUs);
710 mParser->signalDiscontinuity(ATSParser::DISCONTINUITY_TIME, extra);
711
712 // After discontinuity, impl should only have discontinuities
713 // with the last being what we queued. Dequeue them all here.
714 for (size_t i = 0; i < mSourceImpls.size(); ++i) {
715 const sp<AnotherPacketSource> &impl = mSourceImpls.itemAt(i);
716 sp<ABuffer> buffer;
717 status_t err;
718 while (impl->hasBufferAvailable(&err)) {
719 if (err != OK) {
720 return err;
721 }
722 err = impl->dequeueAccessUnit(&buffer);
723 // If the source contains anything but discontinuity, that's
724 // a programming mistake.
725 CHECK(err == INFO_DISCONTINUITY);
726 }
727 }
728
729 // Feed until we have a buffer for each source.
730 for (size_t i = 0; i < mSourceImpls.size(); ++i) {
731 const sp<AnotherPacketSource> &impl = mSourceImpls.itemAt(i);
732 sp<ABuffer> buffer;
733 status_t err = feedUntilBufferAvailable(impl);
734 if (err != OK) {
735 return err;
736 }
737 }
738
739 return OK;
740 }
741
seekBeyond(int64_t seekTimeUs)742 status_t MPEG2TSExtractor::seekBeyond(int64_t seekTimeUs) {
743 // If we're seeking beyond where we know --- read until we reach there.
744 size_t syncPointsSize = mSeekSyncPoints->size();
745
746 while (seekTimeUs > mSeekSyncPoints->keyAt(
747 mSeekSyncPoints->size() - 1)) {
748 status_t err;
749 if (syncPointsSize < mSeekSyncPoints->size()) {
750 syncPointsSize = mSeekSyncPoints->size();
751 int64_t syncTimeUs = mSeekSyncPoints->keyAt(syncPointsSize - 1);
752 // Dequeue buffers before sync point in order to avoid too much
753 // cache building up.
754 sp<ABuffer> buffer;
755 for (size_t i = 0; i < mSourceImpls.size(); ++i) {
756 const sp<AnotherPacketSource> &impl = mSourceImpls[i];
757 int64_t timeUs;
758 while ((err = impl->nextBufferTime(&timeUs)) == OK) {
759 if (timeUs < syncTimeUs) {
760 impl->dequeueAccessUnit(&buffer);
761 } else {
762 break;
763 }
764 }
765 if (err != OK && err != -EWOULDBLOCK) {
766 return err;
767 }
768 }
769 }
770 if (feedMore() != OK) {
771 return ERROR_END_OF_STREAM;
772 }
773 }
774
775 return OK;
776 }
777
feedUntilBufferAvailable(const sp<AnotherPacketSource> & impl)778 status_t MPEG2TSExtractor::feedUntilBufferAvailable(
779 const sp<AnotherPacketSource> &impl) {
780 status_t finalResult;
781 while (!impl->hasBufferAvailable(&finalResult)) {
782 if (finalResult != OK) {
783 return finalResult;
784 }
785
786 status_t err = feedMore();
787 if (err != OK) {
788 impl->signalEOS(err);
789 }
790 }
791 return OK;
792 }
793
794 ////////////////////////////////////////////////////////////////////////////////
795
SniffMPEG2TS(DataSourceHelper * source,float * confidence)796 bool SniffMPEG2TS(DataSourceHelper *source, float *confidence) {
797 for (int i = 0; i < 5; ++i) {
798 char header;
799 if (source->readAt(kTSPacketSize * i, &header, 1) != 1
800 || header != 0x47) {
801 // not ts file, check if m2ts file
802 for (int j = 0; j < 5; ++j) {
803 char headers[5];
804 if (source->readAt((kTSPacketSize + 4) * j, &headers, 5) != 5
805 || headers[4] != 0x47) {
806 // not m2ts file too, return
807 return false;
808 }
809 }
810 ALOGV("this is m2ts file\n");
811 break;
812 }
813 }
814
815 *confidence = 0.1f;
816
817 return true;
818 }
819
820 } // namespace android
821