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