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