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 "MPEG2TSExtractor.h"
24 
25 #include <media/DataSourceBase.h>
26 #include <media/IStreamSource.h>
27 #include <media/MediaTrack.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/MediaDefs.h>
34 #include <media/stagefright/MediaErrors.h>
35 #include <media/stagefright/MetaData.h>
36 #include <utils/String8.h>
37 
38 #include "mpeg2ts/AnotherPacketSource.h"
39 #include "mpeg2ts/ATSParser.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 MediaTrack {
53     MPEG2TSSource(
54             MPEG2TSExtractor *extractor,
55             const sp<AnotherPacketSource> &impl,
56             bool doesSeek);
57     virtual ~MPEG2TSSource();
58 
59     virtual status_t start(MetaDataBase *params = NULL);
60     virtual status_t stop();
61     virtual status_t getFormat(MetaDataBase &);
62 
63     virtual status_t read(
64             MediaBufferBase **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(MetaDataBase *)89 status_t MPEG2TSSource::start(MetaDataBase *) {
90     return mImpl->start(NULL); // AnotherPacketSource::start() doesn't use its argument
91 }
92 
stop()93 status_t MPEG2TSSource::stop() {
94     return mImpl->stop();
95 }
96 
getFormat(MetaDataBase & meta)97 status_t MPEG2TSSource::getFormat(MetaDataBase &meta) {
98     sp<MetaData> implMeta = mImpl->getFormat();
99     meta = *implMeta;
100     return OK;
101 }
102 
read(MediaBufferBase ** out,const ReadOptions * options)103 status_t MPEG2TSSource::read(
104         MediaBufferBase **out, const ReadOptions *options) {
105     *out = NULL;
106 
107     int64_t seekTimeUs;
108     ReadOptions::SeekMode seekMode;
109     if (mDoesSeek && options && options->getSeekTo(&seekTimeUs, &seekMode)) {
110         // seek is needed
111         status_t err = mExtractor->seek(seekTimeUs, seekMode);
112         if (err != OK) {
113             return err;
114         }
115     }
116 
117     if (mExtractor->feedUntilBufferAvailable(mImpl) != OK) {
118         return ERROR_END_OF_STREAM;
119     }
120 
121     return mImpl->read(out, options);
122 }
123 
124 ////////////////////////////////////////////////////////////////////////////////
125 
MPEG2TSExtractor(DataSourceBase * source)126 MPEG2TSExtractor::MPEG2TSExtractor(DataSourceBase *source)
127     : mDataSource(source),
128       mParser(new ATSParser),
129       mLastSyncEvent(0),
130       mOffset(0) {
131     init();
132 }
133 
countTracks()134 size_t MPEG2TSExtractor::countTracks() {
135     return mSourceImpls.size();
136 }
137 
getTrack(size_t index)138 MediaTrack *MPEG2TSExtractor::getTrack(size_t index) {
139     if (index >= mSourceImpls.size()) {
140         return NULL;
141     }
142 
143     // The seek reference track (video if present; audio otherwise) performs
144     // seek requests, while other tracks ignore requests.
145     return new MPEG2TSSource(this, mSourceImpls.editItemAt(index),
146             (mSeekSyncPoints == &mSyncPoints.editItemAt(index)));
147 }
148 
getTrackMetaData(MetaDataBase & meta,size_t index,uint32_t)149 status_t MPEG2TSExtractor::getTrackMetaData(
150         MetaDataBase &meta,
151         size_t index, uint32_t /* flags */) {
152     sp<MetaData> implMeta = index < mSourceImpls.size()
153         ? mSourceImpls.editItemAt(index)->getFormat() : NULL;
154     if (implMeta == NULL) {
155         return UNKNOWN_ERROR;
156     }
157     meta = *implMeta;
158     return OK;
159 }
160 
getMetaData(MetaDataBase & meta)161 status_t MPEG2TSExtractor::getMetaData(MetaDataBase &meta) {
162     meta.setCString(kKeyMIMEType, MEDIA_MIMETYPE_CONTAINER_MPEG2TS);
163 
164     return OK;
165 }
166 
167 //static
isScrambledFormat(MetaDataBase & format)168 bool MPEG2TSExtractor::isScrambledFormat(MetaDataBase &format) {
169     const char *mime;
170     return format.findCString(kKeyMIMEType, &mime)
171             && (!strcasecmp(MEDIA_MIMETYPE_VIDEO_SCRAMBLED, mime)
172                     || !strcasecmp(MEDIA_MIMETYPE_AUDIO_SCRAMBLED, mime));
173 }
174 
setMediaCas(const uint8_t * casToken,size_t size)175 status_t MPEG2TSExtractor::setMediaCas(const uint8_t* casToken, size_t size) {
176     HalToken halToken;
177     halToken.setToExternal((uint8_t*)casToken, size);
178     sp<ICas> cas = ICas::castFrom(retrieveHalInterface(halToken));
179     ALOGD("setMediaCas: %p", cas.get());
180 
181     status_t err = mParser->setMediaCas(cas);
182     if (err == OK) {
183         ALOGI("All tracks now have descramblers");
184         init();
185     }
186     return err;
187 }
188 
addSource(const sp<AnotherPacketSource> & impl)189 void MPEG2TSExtractor::addSource(const sp<AnotherPacketSource> &impl) {
190     bool found = false;
191     for (size_t i = 0; i < mSourceImpls.size(); i++) {
192         if (mSourceImpls[i] == impl) {
193             found = true;
194             break;
195         }
196     }
197     if (!found) {
198         mSourceImpls.push(impl);
199     }
200 }
201 
init()202 void MPEG2TSExtractor::init() {
203     bool haveAudio = false;
204     bool haveVideo = false;
205     int64_t startTime = ALooper::GetNowUs();
206 
207     status_t err;
208     while ((err = feedMore(true /* isInit */)) == OK
209             || err == ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED) {
210         if (haveAudio && haveVideo) {
211             addSyncPoint_l(mLastSyncEvent);
212             mLastSyncEvent.reset();
213             break;
214         }
215         if (!haveVideo) {
216             sp<AnotherPacketSource> impl = mParser->getSource(ATSParser::VIDEO);
217 
218             if (impl != NULL) {
219                 sp<MetaData> format = impl->getFormat();
220                 if (format != NULL) {
221                     haveVideo = true;
222                     addSource(impl);
223                     if (!isScrambledFormat(*(format.get()))) {
224                         mSyncPoints.push();
225                         mSeekSyncPoints = &mSyncPoints.editTop();
226                     }
227                 }
228             }
229         }
230 
231         if (!haveAudio) {
232             sp<AnotherPacketSource> impl = mParser->getSource(ATSParser::AUDIO);
233 
234             if (impl != NULL) {
235                 sp<MetaData> format = impl->getFormat();
236                 if (format != NULL) {
237                     haveAudio = true;
238                     addSource(impl);
239                     if (!isScrambledFormat(*(format.get()))) {
240                         mSyncPoints.push();
241                         if (!haveVideo) {
242                             mSeekSyncPoints = &mSyncPoints.editTop();
243                         }
244                     }
245                 }
246             }
247         }
248 
249         addSyncPoint_l(mLastSyncEvent);
250         mLastSyncEvent.reset();
251 
252         // ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED is returned when the mpeg2ts
253         // is scrambled but we don't have a MediaCas object set. The extraction
254         // will only continue when setMediaCas() is called successfully.
255         if (err == ERROR_DRM_DECRYPT_UNIT_NOT_INITIALIZED) {
256             ALOGI("stopped parsing scrambled content, "
257                   "haveAudio=%d, haveVideo=%d, elaspedTime=%" PRId64,
258                     haveAudio, haveVideo, ALooper::GetNowUs() - startTime);
259             return;
260         }
261 
262         // Wait only for 2 seconds to detect audio/video streams.
263         if (ALooper::GetNowUs() - startTime > 2000000ll) {
264             break;
265         }
266     }
267 
268     off64_t size;
269     if (mDataSource->getSize(&size) == OK && (haveAudio || haveVideo)) {
270         sp<AnotherPacketSource> impl = haveVideo
271                 ? mParser->getSource(ATSParser::VIDEO)
272                 : mParser->getSource(ATSParser::AUDIO);
273         size_t prevSyncSize = 1;
274         int64_t durationUs = -1;
275         List<int64_t> durations;
276         // Estimate duration --- stabilize until you get <500ms deviation.
277         while (feedMore() == OK
278                 && ALooper::GetNowUs() - startTime <= 2000000ll) {
279             if (mSeekSyncPoints->size() > prevSyncSize) {
280                 prevSyncSize = mSeekSyncPoints->size();
281                 int64_t diffUs = mSeekSyncPoints->keyAt(prevSyncSize - 1)
282                         - mSeekSyncPoints->keyAt(0);
283                 off64_t diffOffset = mSeekSyncPoints->valueAt(prevSyncSize - 1)
284                         - mSeekSyncPoints->valueAt(0);
285                 int64_t currentDurationUs = size * diffUs / diffOffset;
286                 durations.push_back(currentDurationUs);
287                 if (durations.size() > 5) {
288                     durations.erase(durations.begin());
289                     int64_t min = *durations.begin();
290                     int64_t max = *durations.begin();
291                     for (auto duration : durations) {
292                         if (min > duration) {
293                             min = duration;
294                         }
295                         if (max < duration) {
296                             max = duration;
297                         }
298                     }
299                     if (max - min < 500 * 1000) {
300                         durationUs = currentDurationUs;
301                         break;
302                     }
303                 }
304             }
305         }
306         status_t err;
307         int64_t bufferedDurationUs;
308         bufferedDurationUs = impl->getBufferedDurationUs(&err);
309         if (err == ERROR_END_OF_STREAM) {
310             durationUs = bufferedDurationUs;
311         }
312         if (durationUs > 0) {
313             const sp<MetaData> meta = impl->getFormat();
314             meta->setInt64(kKeyDuration, durationUs);
315             impl->setFormat(meta);
316         } else {
317             estimateDurationsFromTimesUsAtEnd();
318         }
319     }
320 
321     ALOGI("haveAudio=%d, haveVideo=%d, elaspedTime=%" PRId64,
322             haveAudio, haveVideo, ALooper::GetNowUs() - startTime);
323 }
324 
feedMore(bool isInit)325 status_t MPEG2TSExtractor::feedMore(bool isInit) {
326     Mutex::Autolock autoLock(mLock);
327 
328     uint8_t packet[kTSPacketSize];
329     ssize_t n = mDataSource->readAt(mOffset, packet, kTSPacketSize);
330 
331     if (n < (ssize_t)kTSPacketSize) {
332         if (n >= 0) {
333             mParser->signalEOS(ERROR_END_OF_STREAM);
334         }
335         return (n < 0) ? (status_t)n : ERROR_END_OF_STREAM;
336     }
337 
338     ATSParser::SyncEvent event(mOffset);
339     mOffset += n;
340     status_t err = mParser->feedTSPacket(packet, kTSPacketSize, &event);
341     if (event.hasReturnedData()) {
342         if (isInit) {
343             mLastSyncEvent = event;
344         } else {
345             addSyncPoint_l(event);
346         }
347     }
348     return err;
349 }
350 
addSyncPoint_l(const ATSParser::SyncEvent & event)351 void MPEG2TSExtractor::addSyncPoint_l(const ATSParser::SyncEvent &event) {
352     if (!event.hasReturnedData()) {
353         return;
354     }
355 
356     for (size_t i = 0; i < mSourceImpls.size(); ++i) {
357         if (mSourceImpls[i].get() == event.getMediaSource().get()) {
358             KeyedVector<int64_t, off64_t> *syncPoints = &mSyncPoints.editItemAt(i);
359             syncPoints->add(event.getTimeUs(), event.getOffset());
360             // We're keeping the size of the sync points at most 5mb per a track.
361             size_t size = syncPoints->size();
362             if (size >= 327680) {
363                 int64_t firstTimeUs = syncPoints->keyAt(0);
364                 int64_t lastTimeUs = syncPoints->keyAt(size - 1);
365                 if (event.getTimeUs() - firstTimeUs > lastTimeUs - event.getTimeUs()) {
366                     syncPoints->removeItemsAt(0, 4096);
367                 } else {
368                     syncPoints->removeItemsAt(size - 4096, 4096);
369                 }
370             }
371             break;
372         }
373     }
374 }
375 
estimateDurationsFromTimesUsAtEnd()376 status_t MPEG2TSExtractor::estimateDurationsFromTimesUsAtEnd()  {
377     if (!(mDataSource->flags() & DataSourceBase::kIsLocalFileSource)) {
378         return ERROR_UNSUPPORTED;
379     }
380 
381     off64_t size = 0;
382     status_t err = mDataSource->getSize(&size);
383     if (err != OK) {
384         return err;
385     }
386 
387     uint8_t packet[kTSPacketSize];
388     const off64_t zero = 0;
389     off64_t offset = max(zero, size - kMaxDurationReadSize);
390     if (mDataSource->readAt(offset, &packet, 0) < 0) {
391         return ERROR_IO;
392     }
393 
394     int retry = 0;
395     bool allDurationsFound = false;
396     int64_t timeAnchorUs = mParser->getFirstPTSTimeUs();
397     do {
398         int bytesRead = 0;
399         sp<ATSParser> parser = new ATSParser(ATSParser::TS_TIMESTAMPS_ARE_ABSOLUTE);
400         ATSParser::SyncEvent ev(0);
401         offset = max(zero, size - (kMaxDurationReadSize << retry));
402         offset = (offset / kTSPacketSize) * kTSPacketSize;
403         for (;;) {
404             if (bytesRead >= kMaxDurationReadSize << max(0, retry - 1)) {
405                 break;
406             }
407 
408             ssize_t n = mDataSource->readAt(offset, packet, kTSPacketSize);
409             if (n < 0) {
410                 return n;
411             } else if (n < (ssize_t)kTSPacketSize) {
412                 break;
413             }
414 
415             offset += kTSPacketSize;
416             bytesRead += kTSPacketSize;
417             err = parser->feedTSPacket(packet, kTSPacketSize, &ev);
418             if (err != OK) {
419                 return err;
420             }
421 
422             if (ev.hasReturnedData()) {
423                 int64_t durationUs = ev.getTimeUs();
424                 ATSParser::SourceType type = ev.getType();
425                 ev.reset();
426 
427                 int64_t firstTimeUs;
428                 sp<AnotherPacketSource> src = mParser->getSource(type);
429                 if (src == NULL || src->nextBufferTime(&firstTimeUs) != OK) {
430                     continue;
431                 }
432                 durationUs += src->getEstimatedBufferDurationUs();
433                 durationUs -= timeAnchorUs;
434                 durationUs -= firstTimeUs;
435                 if (durationUs > 0) {
436                     int64_t origDurationUs, lastDurationUs;
437                     const sp<MetaData> meta = src->getFormat();
438                     const uint32_t kKeyLastDuration = 'ldur';
439                     // Require two consecutive duration calculations to be within 1 sec before
440                     // updating; use MetaData to store previous duration estimate in per-stream
441                     // context.
442                     if (!meta->findInt64(kKeyDuration, &origDurationUs)
443                             || !meta->findInt64(kKeyLastDuration, &lastDurationUs)
444                             || (origDurationUs < durationUs
445                              && abs(durationUs - lastDurationUs) < 60000000)) {
446                         meta->setInt64(kKeyDuration, durationUs);
447                     }
448                     meta->setInt64(kKeyLastDuration, durationUs);
449                 }
450             }
451         }
452 
453         if (!allDurationsFound) {
454             allDurationsFound = true;
455             for (auto t: {ATSParser::VIDEO, ATSParser::AUDIO}) {
456                 sp<AnotherPacketSource> src = mParser->getSource(t);
457                 if (src == NULL) {
458                     continue;
459                 }
460                 int64_t durationUs;
461                 const sp<MetaData> meta = src->getFormat();
462                 if (!meta->findInt64(kKeyDuration, &durationUs)) {
463                     allDurationsFound = false;
464                     break;
465                 }
466             }
467         }
468 
469         ++retry;
470     } while(!allDurationsFound && offset > 0 && retry <= kMaxDurationRetry);
471 
472     return allDurationsFound? OK : ERROR_UNSUPPORTED;
473 }
474 
flags() const475 uint32_t MPEG2TSExtractor::flags() const {
476     return CAN_PAUSE | CAN_SEEK_BACKWARD | CAN_SEEK_FORWARD;
477 }
478 
seek(int64_t seekTimeUs,const MediaTrack::ReadOptions::SeekMode & seekMode)479 status_t MPEG2TSExtractor::seek(int64_t seekTimeUs,
480         const MediaTrack::ReadOptions::SeekMode &seekMode) {
481     if (mSeekSyncPoints == NULL || mSeekSyncPoints->isEmpty()) {
482         ALOGW("No sync point to seek to.");
483         // ... and therefore we have nothing useful to do here.
484         return OK;
485     }
486 
487     // Determine whether we're seeking beyond the known area.
488     bool shouldSeekBeyond =
489             (seekTimeUs > mSeekSyncPoints->keyAt(mSeekSyncPoints->size() - 1));
490 
491     // Determine the sync point to seek.
492     size_t index = 0;
493     for (; index < mSeekSyncPoints->size(); ++index) {
494         int64_t timeUs = mSeekSyncPoints->keyAt(index);
495         if (timeUs > seekTimeUs) {
496             break;
497         }
498     }
499 
500     switch (seekMode) {
501         case MediaTrack::ReadOptions::SEEK_NEXT_SYNC:
502             if (index == mSeekSyncPoints->size()) {
503                 ALOGW("Next sync not found; starting from the latest sync.");
504                 --index;
505             }
506             break;
507         case MediaTrack::ReadOptions::SEEK_CLOSEST_SYNC:
508         case MediaTrack::ReadOptions::SEEK_CLOSEST:
509             ALOGW("seekMode not supported: %d; falling back to PREVIOUS_SYNC",
510                     seekMode);
511             // fall-through
512         case MediaTrack::ReadOptions::SEEK_PREVIOUS_SYNC:
513             if (index == 0) {
514                 ALOGW("Previous sync not found; starting from the earliest "
515                         "sync.");
516             } else {
517                 --index;
518             }
519             break;
520         default:
521             return ERROR_UNSUPPORTED;
522     }
523     if (!shouldSeekBeyond || mOffset <= mSeekSyncPoints->valueAt(index)) {
524         int64_t actualSeekTimeUs = mSeekSyncPoints->keyAt(index);
525         mOffset = mSeekSyncPoints->valueAt(index);
526         status_t err = queueDiscontinuityForSeek(actualSeekTimeUs);
527         if (err != OK) {
528             return err;
529         }
530     }
531 
532     if (shouldSeekBeyond) {
533         status_t err = seekBeyond(seekTimeUs);
534         if (err != OK) {
535             return err;
536         }
537     }
538 
539     // Fast-forward to sync frame.
540     for (size_t i = 0; i < mSourceImpls.size(); ++i) {
541         const sp<AnotherPacketSource> &impl = mSourceImpls[i];
542         status_t err;
543         feedUntilBufferAvailable(impl);
544         while (impl->hasBufferAvailable(&err)) {
545             sp<AMessage> meta = impl->getMetaAfterLastDequeued(0);
546             sp<ABuffer> buffer;
547             if (meta == NULL) {
548                 return UNKNOWN_ERROR;
549             }
550             int32_t sync;
551             if (meta->findInt32("isSync", &sync) && sync) {
552                 break;
553             }
554             err = impl->dequeueAccessUnit(&buffer);
555             if (err != OK) {
556                 return err;
557             }
558             feedUntilBufferAvailable(impl);
559         }
560     }
561 
562     return OK;
563 }
564 
queueDiscontinuityForSeek(int64_t actualSeekTimeUs)565 status_t MPEG2TSExtractor::queueDiscontinuityForSeek(int64_t actualSeekTimeUs) {
566     // Signal discontinuity
567     sp<AMessage> extra(new AMessage);
568     extra->setInt64(kATSParserKeyMediaTimeUs, actualSeekTimeUs);
569     mParser->signalDiscontinuity(ATSParser::DISCONTINUITY_TIME, extra);
570 
571     // After discontinuity, impl should only have discontinuities
572     // with the last being what we queued. Dequeue them all here.
573     for (size_t i = 0; i < mSourceImpls.size(); ++i) {
574         const sp<AnotherPacketSource> &impl = mSourceImpls.itemAt(i);
575         sp<ABuffer> buffer;
576         status_t err;
577         while (impl->hasBufferAvailable(&err)) {
578             if (err != OK) {
579                 return err;
580             }
581             err = impl->dequeueAccessUnit(&buffer);
582             // If the source contains anything but discontinuity, that's
583             // a programming mistake.
584             CHECK(err == INFO_DISCONTINUITY);
585         }
586     }
587 
588     // Feed until we have a buffer for each source.
589     for (size_t i = 0; i < mSourceImpls.size(); ++i) {
590         const sp<AnotherPacketSource> &impl = mSourceImpls.itemAt(i);
591         sp<ABuffer> buffer;
592         status_t err = feedUntilBufferAvailable(impl);
593         if (err != OK) {
594             return err;
595         }
596     }
597 
598     return OK;
599 }
600 
seekBeyond(int64_t seekTimeUs)601 status_t MPEG2TSExtractor::seekBeyond(int64_t seekTimeUs) {
602     // If we're seeking beyond where we know --- read until we reach there.
603     size_t syncPointsSize = mSeekSyncPoints->size();
604 
605     while (seekTimeUs > mSeekSyncPoints->keyAt(
606             mSeekSyncPoints->size() - 1)) {
607         status_t err;
608         if (syncPointsSize < mSeekSyncPoints->size()) {
609             syncPointsSize = mSeekSyncPoints->size();
610             int64_t syncTimeUs = mSeekSyncPoints->keyAt(syncPointsSize - 1);
611             // Dequeue buffers before sync point in order to avoid too much
612             // cache building up.
613             sp<ABuffer> buffer;
614             for (size_t i = 0; i < mSourceImpls.size(); ++i) {
615                 const sp<AnotherPacketSource> &impl = mSourceImpls[i];
616                 int64_t timeUs;
617                 while ((err = impl->nextBufferTime(&timeUs)) == OK) {
618                     if (timeUs < syncTimeUs) {
619                         impl->dequeueAccessUnit(&buffer);
620                     } else {
621                         break;
622                     }
623                 }
624                 if (err != OK && err != -EWOULDBLOCK) {
625                     return err;
626                 }
627             }
628         }
629         if (feedMore() != OK) {
630             return ERROR_END_OF_STREAM;
631         }
632     }
633 
634     return OK;
635 }
636 
feedUntilBufferAvailable(const sp<AnotherPacketSource> & impl)637 status_t MPEG2TSExtractor::feedUntilBufferAvailable(
638         const sp<AnotherPacketSource> &impl) {
639     status_t finalResult;
640     while (!impl->hasBufferAvailable(&finalResult)) {
641         if (finalResult != OK) {
642             return finalResult;
643         }
644 
645         status_t err = feedMore();
646         if (err != OK) {
647             impl->signalEOS(err);
648         }
649     }
650     return OK;
651 }
652 
653 ////////////////////////////////////////////////////////////////////////////////
654 
SniffMPEG2TS(DataSourceBase * source,float * confidence)655 bool SniffMPEG2TS(DataSourceBase *source, float *confidence) {
656     for (int i = 0; i < 5; ++i) {
657         char header;
658         if (source->readAt(kTSPacketSize * i, &header, 1) != 1
659                 || header != 0x47) {
660             return false;
661         }
662     }
663 
664     *confidence = 0.1f;
665 
666     return true;
667 }
668 
669 }  // namespace android
670