GenericSource.cpp revision 5c67ddcf987b1f07c9abc1d051a0c051e7c73ff7
1/*
2 * Copyright (C) 2012 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 "GenericSource"
19
20#include "GenericSource.h"
21
22#include "AnotherPacketSource.h"
23
24#include <media/IMediaHTTPService.h>
25#include <media/stagefright/foundation/ABuffer.h>
26#include <media/stagefright/foundation/ADebug.h>
27#include <media/stagefright/foundation/AMessage.h>
28#include <media/stagefright/DataSource.h>
29#include <media/stagefright/FileSource.h>
30#include <media/stagefright/MediaBuffer.h>
31#include <media/stagefright/MediaDefs.h>
32#include <media/stagefright/MediaExtractor.h>
33#include <media/stagefright/MediaSource.h>
34#include <media/stagefright/MetaData.h>
35#include <media/stagefright/Utils.h>
36#include "../../libstagefright/include/DRMExtractor.h"
37#include "../../libstagefright/include/NuCachedSource2.h"
38#include "../../libstagefright/include/WVMExtractor.h"
39#include "../../libstagefright/include/HTTPBase.h"
40
41namespace android {
42
43NuPlayer::GenericSource::GenericSource(
44        const sp<AMessage> &notify,
45        bool uidValid,
46        uid_t uid)
47    : Source(notify),
48      mAudioTimeUs(0),
49      mAudioLastDequeueTimeUs(0),
50      mVideoTimeUs(0),
51      mVideoLastDequeueTimeUs(0),
52      mFetchSubtitleDataGeneration(0),
53      mFetchTimedTextDataGeneration(0),
54      mDurationUs(0ll),
55      mAudioIsVorbis(false),
56      mIsWidevine(false),
57      mUIDValid(uidValid),
58      mUID(uid),
59      mDrmManagerClient(NULL),
60      mMetaDataSize(-1ll),
61      mBitrate(-1ll),
62      mPollBufferingGeneration(0),
63      mPendingReadBufferTypes(0) {
64    resetDataSource();
65    DataSource::RegisterDefaultSniffers();
66}
67
68void NuPlayer::GenericSource::resetDataSource() {
69    mHTTPService.clear();
70    mHttpSource.clear();
71    mUri.clear();
72    mUriHeaders.clear();
73    mFd = -1;
74    mOffset = 0;
75    mLength = 0;
76    setDrmPlaybackStatusIfNeeded(Playback::STOP, 0);
77    mDecryptHandle = NULL;
78    mDrmManagerClient = NULL;
79    mStarted = false;
80    mStopRead = true;
81}
82
83status_t NuPlayer::GenericSource::setDataSource(
84        const sp<IMediaHTTPService> &httpService,
85        const char *url,
86        const KeyedVector<String8, String8> *headers) {
87    resetDataSource();
88
89    mHTTPService = httpService;
90    mUri = url;
91
92    if (headers) {
93        mUriHeaders = *headers;
94    }
95
96    // delay data source creation to prepareAsync() to avoid blocking
97    // the calling thread in setDataSource for any significant time.
98    return OK;
99}
100
101status_t NuPlayer::GenericSource::setDataSource(
102        int fd, int64_t offset, int64_t length) {
103    resetDataSource();
104
105    mFd = dup(fd);
106    mOffset = offset;
107    mLength = length;
108
109    // delay data source creation to prepareAsync() to avoid blocking
110    // the calling thread in setDataSource for any significant time.
111    return OK;
112}
113
114sp<MetaData> NuPlayer::GenericSource::getFileFormatMeta() const {
115    return mFileMeta;
116}
117
118status_t NuPlayer::GenericSource::initFromDataSource() {
119    sp<MediaExtractor> extractor;
120
121    CHECK(mDataSource != NULL);
122
123    if (mIsWidevine) {
124        String8 mimeType;
125        float confidence;
126        sp<AMessage> dummy;
127        bool success;
128
129        success = SniffWVM(mDataSource, &mimeType, &confidence, &dummy);
130        if (!success
131                || strcasecmp(
132                    mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM)) {
133            ALOGE("unsupported widevine mime: %s", mimeType.string());
134            return UNKNOWN_ERROR;
135        }
136
137        mWVMExtractor = new WVMExtractor(mDataSource);
138        mWVMExtractor->setAdaptiveStreamingMode(true);
139        if (mUIDValid) {
140            mWVMExtractor->setUID(mUID);
141        }
142        extractor = mWVMExtractor;
143    } else {
144        extractor = MediaExtractor::Create(mDataSource,
145                mSniffedMIME.empty() ? NULL: mSniffedMIME.c_str());
146    }
147
148    if (extractor == NULL) {
149        return UNKNOWN_ERROR;
150    }
151
152    if (extractor->getDrmFlag()) {
153        checkDrmStatus(mDataSource);
154    }
155
156    mFileMeta = extractor->getMetaData();
157    if (mFileMeta != NULL) {
158        int64_t duration;
159        if (mFileMeta->findInt64(kKeyDuration, &duration)) {
160            mDurationUs = duration;
161        }
162    }
163
164    int32_t totalBitrate = 0;
165
166    size_t numtracks = extractor->countTracks();
167    if (numtracks == 0) {
168        return UNKNOWN_ERROR;
169    }
170
171    for (size_t i = 0; i < numtracks; ++i) {
172        sp<MediaSource> track = extractor->getTrack(i);
173
174        sp<MetaData> meta = extractor->getTrackMetaData(i);
175
176        const char *mime;
177        CHECK(meta->findCString(kKeyMIMEType, &mime));
178
179        // Do the string compare immediately with "mime",
180        // we can't assume "mime" would stay valid after another
181        // extractor operation, some extractors might modify meta
182        // during getTrack() and make it invalid.
183        if (!strncasecmp(mime, "audio/", 6)) {
184            if (mAudioTrack.mSource == NULL) {
185                mAudioTrack.mIndex = i;
186                mAudioTrack.mSource = track;
187                mAudioTrack.mPackets =
188                    new AnotherPacketSource(mAudioTrack.mSource->getFormat());
189
190                if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) {
191                    mAudioIsVorbis = true;
192                } else {
193                    mAudioIsVorbis = false;
194                }
195            }
196        } else if (!strncasecmp(mime, "video/", 6)) {
197            if (mVideoTrack.mSource == NULL) {
198                mVideoTrack.mIndex = i;
199                mVideoTrack.mSource = track;
200                mVideoTrack.mPackets =
201                    new AnotherPacketSource(mVideoTrack.mSource->getFormat());
202
203                // check if the source requires secure buffers
204                int32_t secure;
205                if (meta->findInt32(kKeyRequiresSecureBuffers, &secure)
206                        && secure) {
207                    mIsWidevine = true;
208                    if (mUIDValid) {
209                        extractor->setUID(mUID);
210                    }
211                }
212            }
213        }
214
215        if (track != NULL) {
216            mSources.push(track);
217            int64_t durationUs;
218            if (meta->findInt64(kKeyDuration, &durationUs)) {
219                if (durationUs > mDurationUs) {
220                    mDurationUs = durationUs;
221                }
222            }
223
224            int32_t bitrate;
225            if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) {
226                totalBitrate += bitrate;
227            } else {
228                totalBitrate = -1;
229            }
230        }
231    }
232
233    mBitrate = totalBitrate;
234
235    return OK;
236}
237
238void NuPlayer::GenericSource::checkDrmStatus(const sp<DataSource>& dataSource) {
239    dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient);
240    if (mDecryptHandle != NULL) {
241        CHECK(mDrmManagerClient);
242        if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) {
243            sp<AMessage> msg = dupNotify();
244            msg->setInt32("what", kWhatDrmNoLicense);
245            msg->post();
246        }
247    }
248}
249
250int64_t NuPlayer::GenericSource::getLastReadPosition() {
251    if (mAudioTrack.mSource != NULL) {
252        return mAudioTimeUs;
253    } else if (mVideoTrack.mSource != NULL) {
254        return mVideoTimeUs;
255    } else {
256        return 0;
257    }
258}
259
260status_t NuPlayer::GenericSource::setBuffers(
261        bool audio, Vector<MediaBuffer *> &buffers) {
262    if (mIsWidevine && !audio) {
263        return mVideoTrack.mSource->setBuffers(buffers);
264    }
265    return INVALID_OPERATION;
266}
267
268NuPlayer::GenericSource::~GenericSource() {
269    if (mLooper != NULL) {
270        mLooper->unregisterHandler(id());
271        mLooper->stop();
272    }
273}
274
275void NuPlayer::GenericSource::prepareAsync() {
276    if (mLooper == NULL) {
277        mLooper = new ALooper;
278        mLooper->setName("generic");
279        mLooper->start();
280
281        mLooper->registerHandler(this);
282    }
283
284    sp<AMessage> msg = new AMessage(kWhatPrepareAsync, id());
285    msg->post();
286}
287
288void NuPlayer::GenericSource::onPrepareAsync() {
289    // delayed data source creation
290    if (mDataSource == NULL) {
291        if (!mUri.empty()) {
292            const char* uri = mUri.c_str();
293            mIsWidevine = !strncasecmp(uri, "widevine://", 11);
294
295            if (!strncasecmp("http://", uri, 7)
296                    || !strncasecmp("https://", uri, 8)
297                    || mIsWidevine) {
298                mHttpSource = DataSource::CreateMediaHTTP(mHTTPService);
299                if (mHttpSource == NULL) {
300                    ALOGE("Failed to create http source!");
301                    notifyPreparedAndCleanup(UNKNOWN_ERROR);
302                    return;
303                }
304            }
305
306            mDataSource = DataSource::CreateFromURI(
307                   mHTTPService, uri, &mUriHeaders, &mContentType,
308                   static_cast<HTTPBase *>(mHttpSource.get()));
309        } else {
310            // set to false first, if the extractor
311            // comes back as secure, set it to true then.
312            mIsWidevine = false;
313
314            mDataSource = new FileSource(mFd, mOffset, mLength);
315        }
316
317        if (mDataSource == NULL) {
318            ALOGE("Failed to create data source!");
319            notifyPreparedAndCleanup(UNKNOWN_ERROR);
320            return;
321        }
322
323        if (mDataSource->flags() & DataSource::kIsCachingDataSource) {
324            mCachedSource = static_cast<NuCachedSource2 *>(mDataSource.get());
325        }
326
327        if (mIsWidevine || mCachedSource != NULL) {
328            schedulePollBuffering();
329        }
330    }
331
332    // check initial caching status
333    status_t err = prefillCacheIfNecessary();
334    if (err != OK) {
335        if (err == -EAGAIN) {
336            (new AMessage(kWhatPrepareAsync, id()))->post(200000);
337        } else {
338            ALOGE("Failed to prefill data cache!");
339            notifyPreparedAndCleanup(UNKNOWN_ERROR);
340        }
341        return;
342    }
343
344    // init extrator from data source
345    err = initFromDataSource();
346
347    if (err != OK) {
348        ALOGE("Failed to init from data source!");
349        notifyPreparedAndCleanup(err);
350        return;
351    }
352
353    if (mVideoTrack.mSource != NULL) {
354        sp<MetaData> meta = doGetFormatMeta(false /* audio */);
355        sp<AMessage> msg = new AMessage;
356        err = convertMetaDataToMessage(meta, &msg);
357        if(err != OK) {
358            notifyPreparedAndCleanup(err);
359            return;
360        }
361        notifyVideoSizeChanged(msg);
362    }
363
364    notifyFlagsChanged(
365            (mIsWidevine ? FLAG_SECURE : 0)
366            | FLAG_CAN_PAUSE
367            | FLAG_CAN_SEEK_BACKWARD
368            | FLAG_CAN_SEEK_FORWARD
369            | FLAG_CAN_SEEK);
370
371    notifyPrepared();
372}
373
374void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) {
375    if (err != OK) {
376        mMetaDataSize = -1ll;
377        mContentType = "";
378        mSniffedMIME = "";
379        mDataSource.clear();
380        mCachedSource.clear();
381        mHttpSource.clear();
382
383        cancelPollBuffering();
384    }
385    notifyPrepared(err);
386}
387
388status_t NuPlayer::GenericSource::prefillCacheIfNecessary() {
389    CHECK(mDataSource != NULL);
390
391    if (mCachedSource == NULL) {
392        // no prefill if the data source is not cached
393        return OK;
394    }
395
396    // We're not doing this for streams that appear to be audio-only
397    // streams to ensure that even low bandwidth streams start
398    // playing back fairly instantly.
399    if (!strncasecmp(mContentType.string(), "audio/", 6)) {
400        return OK;
401    }
402
403    // We're going to prefill the cache before trying to instantiate
404    // the extractor below, as the latter is an operation that otherwise
405    // could block on the datasource for a significant amount of time.
406    // During that time we'd be unable to abort the preparation phase
407    // without this prefill.
408
409    // Initially make sure we have at least 192 KB for the sniff
410    // to complete without blocking.
411    static const size_t kMinBytesForSniffing = 192 * 1024;
412    static const size_t kDefaultMetaSize = 200000;
413
414    status_t finalStatus;
415
416    size_t cachedDataRemaining =
417            mCachedSource->approxDataRemaining(&finalStatus);
418
419    if (finalStatus != OK || (mMetaDataSize >= 0
420            && (off64_t)cachedDataRemaining >= mMetaDataSize)) {
421        ALOGV("stop caching, status %d, "
422                "metaDataSize %lld, cachedDataRemaining %zu",
423                finalStatus, mMetaDataSize, cachedDataRemaining);
424        return OK;
425    }
426
427    ALOGV("now cached %zu bytes of data", cachedDataRemaining);
428
429    if (mMetaDataSize < 0
430            && cachedDataRemaining >= kMinBytesForSniffing) {
431        String8 tmp;
432        float confidence;
433        sp<AMessage> meta;
434        if (!mCachedSource->sniff(&tmp, &confidence, &meta)) {
435            return UNKNOWN_ERROR;
436        }
437
438        // We successfully identified the file's extractor to
439        // be, remember this mime type so we don't have to
440        // sniff it again when we call MediaExtractor::Create()
441        mSniffedMIME = tmp.string();
442
443        if (meta == NULL
444                || !meta->findInt64("meta-data-size",
445                        reinterpret_cast<int64_t*>(&mMetaDataSize))) {
446            mMetaDataSize = kDefaultMetaSize;
447        }
448
449        if (mMetaDataSize < 0ll) {
450            ALOGE("invalid metaDataSize = %lld bytes", mMetaDataSize);
451            return UNKNOWN_ERROR;
452        }
453    }
454
455    return -EAGAIN;
456}
457
458void NuPlayer::GenericSource::start() {
459    ALOGI("start");
460
461    mStopRead = false;
462    if (mAudioTrack.mSource != NULL) {
463        CHECK_EQ(mAudioTrack.mSource->start(), (status_t)OK);
464
465        postReadBuffer(MEDIA_TRACK_TYPE_AUDIO);
466    }
467
468    if (mVideoTrack.mSource != NULL) {
469        CHECK_EQ(mVideoTrack.mSource->start(), (status_t)OK);
470
471        postReadBuffer(MEDIA_TRACK_TYPE_VIDEO);
472    }
473
474    setDrmPlaybackStatusIfNeeded(Playback::START, getLastReadPosition() / 1000);
475    mStarted = true;
476}
477
478void NuPlayer::GenericSource::stop() {
479    // nothing to do, just account for DRM playback status
480    setDrmPlaybackStatusIfNeeded(Playback::STOP, 0);
481    mStarted = false;
482    if (mIsWidevine) {
483        // For a widevine source we need to prevent any further reads.
484        sp<AMessage> msg = new AMessage(kWhatStopWidevine, id());
485        sp<AMessage> response;
486        (void) msg->postAndAwaitResponse(&response);
487    }
488}
489
490void NuPlayer::GenericSource::pause() {
491    // nothing to do, just account for DRM playback status
492    setDrmPlaybackStatusIfNeeded(Playback::PAUSE, 0);
493    mStarted = false;
494}
495
496void NuPlayer::GenericSource::resume() {
497    // nothing to do, just account for DRM playback status
498    setDrmPlaybackStatusIfNeeded(Playback::START, getLastReadPosition() / 1000);
499    mStarted = true;
500}
501
502void NuPlayer::GenericSource::disconnect() {
503    if (mDataSource != NULL) {
504        // disconnect data source
505        if (mDataSource->flags() & DataSource::kIsCachingDataSource) {
506            static_cast<NuCachedSource2 *>(mDataSource.get())->disconnect();
507        }
508    } else if (mHttpSource != NULL) {
509        static_cast<HTTPBase *>(mHttpSource.get())->disconnect();
510    }
511}
512
513void NuPlayer::GenericSource::setDrmPlaybackStatusIfNeeded(int playbackStatus, int64_t position) {
514    if (mDecryptHandle != NULL) {
515        mDrmManagerClient->setPlaybackStatus(mDecryptHandle, playbackStatus, position);
516    }
517    mSubtitleTrack.mPackets = new AnotherPacketSource(NULL);
518    mTimedTextTrack.mPackets = new AnotherPacketSource(NULL);
519}
520
521status_t NuPlayer::GenericSource::feedMoreTSData() {
522    return OK;
523}
524
525void NuPlayer::GenericSource::schedulePollBuffering() {
526    sp<AMessage> msg = new AMessage(kWhatPollBuffering, id());
527    msg->setInt32("generation", mPollBufferingGeneration);
528    msg->post(1000000ll);
529}
530
531void NuPlayer::GenericSource::cancelPollBuffering() {
532    ++mPollBufferingGeneration;
533}
534
535void NuPlayer::GenericSource::notifyBufferingUpdate(int percentage) {
536    sp<AMessage> msg = dupNotify();
537    msg->setInt32("what", kWhatBufferingUpdate);
538    msg->setInt32("percentage", percentage);
539    msg->post();
540}
541
542void NuPlayer::GenericSource::onPollBuffering() {
543    status_t finalStatus = UNKNOWN_ERROR;
544    int64_t cachedDurationUs = 0ll;
545
546    if (mCachedSource != NULL) {
547        size_t cachedDataRemaining =
548                mCachedSource->approxDataRemaining(&finalStatus);
549
550        if (finalStatus == OK) {
551            off64_t size;
552            int64_t bitrate = 0ll;
553            if (mDurationUs > 0 && mCachedSource->getSize(&size) == OK) {
554                bitrate = size * 8000000ll / mDurationUs;
555            } else if (mBitrate > 0) {
556                bitrate = mBitrate;
557            }
558            if (bitrate > 0) {
559                cachedDurationUs = cachedDataRemaining * 8000000ll / bitrate;
560            }
561        }
562    } else if (mWVMExtractor != NULL) {
563        cachedDurationUs
564            = mWVMExtractor->getCachedDurationUs(&finalStatus);
565    }
566
567    if (finalStatus == ERROR_END_OF_STREAM) {
568        notifyBufferingUpdate(100);
569        cancelPollBuffering();
570        return;
571    } else if (cachedDurationUs > 0ll && mDurationUs > 0ll) {
572        int percentage = 100.0 * cachedDurationUs / mDurationUs;
573        if (percentage > 100) {
574            percentage = 100;
575        }
576
577        notifyBufferingUpdate(percentage);
578    }
579
580    schedulePollBuffering();
581}
582
583
584void NuPlayer::GenericSource::onMessageReceived(const sp<AMessage> &msg) {
585    switch (msg->what()) {
586      case kWhatPrepareAsync:
587      {
588          onPrepareAsync();
589          break;
590      }
591      case kWhatFetchSubtitleData:
592      {
593          fetchTextData(kWhatSendSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE,
594                  mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg);
595          break;
596      }
597
598      case kWhatFetchTimedTextData:
599      {
600          fetchTextData(kWhatSendTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT,
601                  mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg);
602          break;
603      }
604
605      case kWhatSendSubtitleData:
606      {
607          sendTextData(kWhatSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE,
608                  mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg);
609          break;
610      }
611
612      case kWhatSendTimedTextData:
613      {
614          sendTextData(kWhatTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT,
615                  mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg);
616          break;
617      }
618
619      case kWhatChangeAVSource:
620      {
621          int32_t trackIndex;
622          CHECK(msg->findInt32("trackIndex", &trackIndex));
623          const sp<MediaSource> source = mSources.itemAt(trackIndex);
624
625          Track* track;
626          const char *mime;
627          media_track_type trackType, counterpartType;
628          sp<MetaData> meta = source->getFormat();
629          meta->findCString(kKeyMIMEType, &mime);
630          if (!strncasecmp(mime, "audio/", 6)) {
631              track = &mAudioTrack;
632              trackType = MEDIA_TRACK_TYPE_AUDIO;
633              counterpartType = MEDIA_TRACK_TYPE_VIDEO;;
634          } else {
635              CHECK(!strncasecmp(mime, "video/", 6));
636              track = &mVideoTrack;
637              trackType = MEDIA_TRACK_TYPE_VIDEO;
638              counterpartType = MEDIA_TRACK_TYPE_AUDIO;;
639          }
640
641
642          if (track->mSource != NULL) {
643              track->mSource->stop();
644          }
645          track->mSource = source;
646          track->mSource->start();
647          track->mIndex = trackIndex;
648
649          int64_t timeUs, actualTimeUs;
650          const bool formatChange = true;
651          if (trackType == MEDIA_TRACK_TYPE_AUDIO) {
652              timeUs = mAudioLastDequeueTimeUs;
653          } else {
654              timeUs = mVideoLastDequeueTimeUs;
655          }
656          readBuffer(trackType, timeUs, &actualTimeUs, formatChange);
657          readBuffer(counterpartType, -1, NULL, formatChange);
658          ALOGV("timeUs %lld actualTimeUs %lld", timeUs, actualTimeUs);
659
660          break;
661      }
662      case kWhatPollBuffering:
663      {
664          int32_t generation;
665          CHECK(msg->findInt32("generation", &generation));
666          if (generation == mPollBufferingGeneration) {
667              onPollBuffering();
668          }
669          break;
670      }
671
672      case kWhatGetFormat:
673      {
674          onGetFormatMeta(msg);
675          break;
676      }
677
678      case kWhatGetSelectedTrack:
679      {
680          onGetSelectedTrack(msg);
681          break;
682      }
683
684      case kWhatSelectTrack:
685      {
686          onSelectTrack(msg);
687          break;
688      }
689
690      case kWhatSeek:
691      {
692          onSeek(msg);
693          break;
694      }
695
696      case kWhatReadBuffer:
697      {
698          onReadBuffer(msg);
699          break;
700      }
701
702      case kWhatStopWidevine:
703      {
704          // mStopRead is only used for Widevine to prevent the video source
705          // from being read while the associated video decoder is shutting down.
706          mStopRead = true;
707          if (mVideoTrack.mSource != NULL) {
708              mVideoTrack.mPackets->clear();
709          }
710          sp<AMessage> response = new AMessage;
711          uint32_t replyID;
712          CHECK(msg->senderAwaitsResponse(&replyID));
713          response->postReply(replyID);
714          break;
715      }
716      default:
717          Source::onMessageReceived(msg);
718          break;
719    }
720}
721
722void NuPlayer::GenericSource::fetchTextData(
723        uint32_t sendWhat,
724        media_track_type type,
725        int32_t curGen,
726        sp<AnotherPacketSource> packets,
727        sp<AMessage> msg) {
728    int32_t msgGeneration;
729    CHECK(msg->findInt32("generation", &msgGeneration));
730    if (msgGeneration != curGen) {
731        // stale
732        return;
733    }
734
735    int32_t avail;
736    if (packets->hasBufferAvailable(&avail)) {
737        return;
738    }
739
740    int64_t timeUs;
741    CHECK(msg->findInt64("timeUs", &timeUs));
742
743    int64_t subTimeUs;
744    readBuffer(type, timeUs, &subTimeUs);
745
746    int64_t delayUs = subTimeUs - timeUs;
747    if (msg->what() == kWhatFetchSubtitleData) {
748        const int64_t oneSecUs = 1000000ll;
749        delayUs -= oneSecUs;
750    }
751    sp<AMessage> msg2 = new AMessage(sendWhat, id());
752    msg2->setInt32("generation", msgGeneration);
753    msg2->post(delayUs < 0 ? 0 : delayUs);
754}
755
756void NuPlayer::GenericSource::sendTextData(
757        uint32_t what,
758        media_track_type type,
759        int32_t curGen,
760        sp<AnotherPacketSource> packets,
761        sp<AMessage> msg) {
762    int32_t msgGeneration;
763    CHECK(msg->findInt32("generation", &msgGeneration));
764    if (msgGeneration != curGen) {
765        // stale
766        return;
767    }
768
769    int64_t subTimeUs;
770    if (packets->nextBufferTime(&subTimeUs) != OK) {
771        return;
772    }
773
774    int64_t nextSubTimeUs;
775    readBuffer(type, -1, &nextSubTimeUs);
776
777    sp<ABuffer> buffer;
778    status_t dequeueStatus = packets->dequeueAccessUnit(&buffer);
779    if (dequeueStatus == OK) {
780        sp<AMessage> notify = dupNotify();
781        notify->setInt32("what", what);
782        notify->setBuffer("buffer", buffer);
783        notify->post();
784
785        const int64_t delayUs = nextSubTimeUs - subTimeUs;
786        msg->post(delayUs < 0 ? 0 : delayUs);
787    }
788}
789
790sp<MetaData> NuPlayer::GenericSource::getFormatMeta(bool audio) {
791    sp<AMessage> msg = new AMessage(kWhatGetFormat, id());
792    msg->setInt32("audio", audio);
793
794    sp<AMessage> response;
795    void *format;
796    status_t err = msg->postAndAwaitResponse(&response);
797    if (err == OK && response != NULL) {
798        CHECK(response->findPointer("format", &format));
799        return (MetaData *)format;
800    } else {
801        return NULL;
802    }
803}
804
805void NuPlayer::GenericSource::onGetFormatMeta(sp<AMessage> msg) const {
806    int32_t audio;
807    CHECK(msg->findInt32("audio", &audio));
808
809    sp<AMessage> response = new AMessage;
810    sp<MetaData> format = doGetFormatMeta(audio);
811    response->setPointer("format", format.get());
812
813    uint32_t replyID;
814    CHECK(msg->senderAwaitsResponse(&replyID));
815    response->postReply(replyID);
816}
817
818sp<MetaData> NuPlayer::GenericSource::doGetFormatMeta(bool audio) const {
819    sp<MediaSource> source = audio ? mAudioTrack.mSource : mVideoTrack.mSource;
820
821    if (source == NULL) {
822        return NULL;
823    }
824
825    return source->getFormat();
826}
827
828status_t NuPlayer::GenericSource::dequeueAccessUnit(
829        bool audio, sp<ABuffer> *accessUnit) {
830    Track *track = audio ? &mAudioTrack : &mVideoTrack;
831
832    if (track->mSource == NULL) {
833        return -EWOULDBLOCK;
834    }
835
836    if (mIsWidevine && !audio) {
837        // try to read a buffer as we may not have been able to the last time
838        postReadBuffer(MEDIA_TRACK_TYPE_VIDEO);
839    }
840
841    status_t finalResult;
842    if (!track->mPackets->hasBufferAvailable(&finalResult)) {
843        return (finalResult == OK ? -EWOULDBLOCK : finalResult);
844    }
845
846    status_t result = track->mPackets->dequeueAccessUnit(accessUnit);
847
848    if (!track->mPackets->hasBufferAvailable(&finalResult)) {
849        postReadBuffer(audio? MEDIA_TRACK_TYPE_AUDIO : MEDIA_TRACK_TYPE_VIDEO);
850    }
851
852    if (result != OK) {
853        if (mSubtitleTrack.mSource != NULL) {
854            mSubtitleTrack.mPackets->clear();
855            mFetchSubtitleDataGeneration++;
856        }
857        if (mTimedTextTrack.mSource != NULL) {
858            mTimedTextTrack.mPackets->clear();
859            mFetchTimedTextDataGeneration++;
860        }
861        return result;
862    }
863
864    int64_t timeUs;
865    status_t eosResult; // ignored
866    CHECK((*accessUnit)->meta()->findInt64("timeUs", &timeUs));
867    if (audio) {
868        mAudioLastDequeueTimeUs = timeUs;
869    } else {
870        mVideoLastDequeueTimeUs = timeUs;
871    }
872
873    if (mSubtitleTrack.mSource != NULL
874            && !mSubtitleTrack.mPackets->hasBufferAvailable(&eosResult)) {
875        sp<AMessage> msg = new AMessage(kWhatFetchSubtitleData, id());
876        msg->setInt64("timeUs", timeUs);
877        msg->setInt32("generation", mFetchSubtitleDataGeneration);
878        msg->post();
879    }
880
881    if (mTimedTextTrack.mSource != NULL
882            && !mTimedTextTrack.mPackets->hasBufferAvailable(&eosResult)) {
883        sp<AMessage> msg = new AMessage(kWhatFetchTimedTextData, id());
884        msg->setInt64("timeUs", timeUs);
885        msg->setInt32("generation", mFetchTimedTextDataGeneration);
886        msg->post();
887    }
888
889    return result;
890}
891
892status_t NuPlayer::GenericSource::getDuration(int64_t *durationUs) {
893    *durationUs = mDurationUs;
894    return OK;
895}
896
897size_t NuPlayer::GenericSource::getTrackCount() const {
898    return mSources.size();
899}
900
901sp<AMessage> NuPlayer::GenericSource::getTrackInfo(size_t trackIndex) const {
902    size_t trackCount = mSources.size();
903    if (trackIndex >= trackCount) {
904        return NULL;
905    }
906
907    sp<AMessage> format = new AMessage();
908    sp<MetaData> meta = mSources.itemAt(trackIndex)->getFormat();
909
910    const char *mime;
911    CHECK(meta->findCString(kKeyMIMEType, &mime));
912
913    int32_t trackType;
914    if (!strncasecmp(mime, "video/", 6)) {
915        trackType = MEDIA_TRACK_TYPE_VIDEO;
916    } else if (!strncasecmp(mime, "audio/", 6)) {
917        trackType = MEDIA_TRACK_TYPE_AUDIO;
918    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP)) {
919        trackType = MEDIA_TRACK_TYPE_TIMEDTEXT;
920    } else {
921        trackType = MEDIA_TRACK_TYPE_UNKNOWN;
922    }
923    format->setInt32("type", trackType);
924
925    const char *lang;
926    if (!meta->findCString(kKeyMediaLanguage, &lang)) {
927        lang = "und";
928    }
929    format->setString("language", lang);
930
931    if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
932        format->setString("mime", mime);
933
934        int32_t isAutoselect = 1, isDefault = 0, isForced = 0;
935        meta->findInt32(kKeyTrackIsAutoselect, &isAutoselect);
936        meta->findInt32(kKeyTrackIsDefault, &isDefault);
937        meta->findInt32(kKeyTrackIsForced, &isForced);
938
939        format->setInt32("auto", !!isAutoselect);
940        format->setInt32("default", !!isDefault);
941        format->setInt32("forced", !!isForced);
942    }
943
944    return format;
945}
946
947ssize_t NuPlayer::GenericSource::getSelectedTrack(media_track_type type) const {
948    sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, id());
949    msg->setInt32("type", type);
950
951    sp<AMessage> response;
952    int32_t index;
953    status_t err = msg->postAndAwaitResponse(&response);
954    if (err == OK && response != NULL) {
955        CHECK(response->findInt32("index", &index));
956        return index;
957    } else {
958        return -1;
959    }
960}
961
962void NuPlayer::GenericSource::onGetSelectedTrack(sp<AMessage> msg) const {
963    int32_t tmpType;
964    CHECK(msg->findInt32("type", &tmpType));
965    media_track_type type = (media_track_type)tmpType;
966
967    sp<AMessage> response = new AMessage;
968    ssize_t index = doGetSelectedTrack(type);
969    response->setInt32("index", index);
970
971    uint32_t replyID;
972    CHECK(msg->senderAwaitsResponse(&replyID));
973    response->postReply(replyID);
974}
975
976ssize_t NuPlayer::GenericSource::doGetSelectedTrack(media_track_type type) const {
977    const Track *track = NULL;
978    switch (type) {
979    case MEDIA_TRACK_TYPE_VIDEO:
980        track = &mVideoTrack;
981        break;
982    case MEDIA_TRACK_TYPE_AUDIO:
983        track = &mAudioTrack;
984        break;
985    case MEDIA_TRACK_TYPE_TIMEDTEXT:
986        track = &mTimedTextTrack;
987        break;
988    case MEDIA_TRACK_TYPE_SUBTITLE:
989        track = &mSubtitleTrack;
990        break;
991    default:
992        break;
993    }
994
995    if (track != NULL && track->mSource != NULL) {
996        return track->mIndex;
997    }
998
999    return -1;
1000}
1001
1002status_t NuPlayer::GenericSource::selectTrack(size_t trackIndex, bool select) {
1003    ALOGV("%s track: %zu", select ? "select" : "deselect", trackIndex);
1004    sp<AMessage> msg = new AMessage(kWhatSelectTrack, id());
1005    msg->setInt32("trackIndex", trackIndex);
1006    msg->setInt32("select", select);
1007
1008    sp<AMessage> response;
1009    status_t err = msg->postAndAwaitResponse(&response);
1010    if (err == OK && response != NULL) {
1011        CHECK(response->findInt32("err", &err));
1012    }
1013
1014    return err;
1015}
1016
1017void NuPlayer::GenericSource::onSelectTrack(sp<AMessage> msg) {
1018    int32_t trackIndex, select;
1019    CHECK(msg->findInt32("trackIndex", &trackIndex));
1020    CHECK(msg->findInt32("select", &select));
1021
1022    sp<AMessage> response = new AMessage;
1023    status_t err = doSelectTrack(trackIndex, select);
1024    response->setInt32("err", err);
1025
1026    uint32_t replyID;
1027    CHECK(msg->senderAwaitsResponse(&replyID));
1028    response->postReply(replyID);
1029}
1030
1031status_t NuPlayer::GenericSource::doSelectTrack(size_t trackIndex, bool select) {
1032    if (trackIndex >= mSources.size()) {
1033        return BAD_INDEX;
1034    }
1035
1036    if (!select) {
1037        Track* track = NULL;
1038        if (mSubtitleTrack.mSource != NULL && trackIndex == mSubtitleTrack.mIndex) {
1039            track = &mSubtitleTrack;
1040            mFetchSubtitleDataGeneration++;
1041        } else if (mTimedTextTrack.mSource != NULL && trackIndex == mTimedTextTrack.mIndex) {
1042            track = &mTimedTextTrack;
1043            mFetchTimedTextDataGeneration++;
1044        }
1045        if (track == NULL) {
1046            return INVALID_OPERATION;
1047        }
1048        track->mSource->stop();
1049        track->mSource = NULL;
1050        track->mPackets->clear();
1051        return OK;
1052    }
1053
1054    const sp<MediaSource> source = mSources.itemAt(trackIndex);
1055    sp<MetaData> meta = source->getFormat();
1056    const char *mime;
1057    CHECK(meta->findCString(kKeyMIMEType, &mime));
1058    if (!strncasecmp(mime, "text/", 5)) {
1059        bool isSubtitle = strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP);
1060        Track *track = isSubtitle ? &mSubtitleTrack : &mTimedTextTrack;
1061        if (track->mSource != NULL && track->mIndex == trackIndex) {
1062            return OK;
1063        }
1064        track->mIndex = trackIndex;
1065        if (track->mSource != NULL) {
1066            track->mSource->stop();
1067        }
1068        track->mSource = mSources.itemAt(trackIndex);
1069        track->mSource->start();
1070        if (track->mPackets == NULL) {
1071            track->mPackets = new AnotherPacketSource(track->mSource->getFormat());
1072        } else {
1073            track->mPackets->clear();
1074            track->mPackets->setFormat(track->mSource->getFormat());
1075
1076        }
1077
1078        if (isSubtitle) {
1079            mFetchSubtitleDataGeneration++;
1080        } else {
1081            mFetchTimedTextDataGeneration++;
1082        }
1083
1084        return OK;
1085    } else if (!strncasecmp(mime, "audio/", 6) || !strncasecmp(mime, "video/", 6)) {
1086        bool audio = !strncasecmp(mime, "audio/", 6);
1087        Track *track = audio ? &mAudioTrack : &mVideoTrack;
1088        if (track->mSource != NULL && track->mIndex == trackIndex) {
1089            return OK;
1090        }
1091
1092        sp<AMessage> msg = new AMessage(kWhatChangeAVSource, id());
1093        msg->setInt32("trackIndex", trackIndex);
1094        msg->post();
1095        return OK;
1096    }
1097
1098    return INVALID_OPERATION;
1099}
1100
1101status_t NuPlayer::GenericSource::seekTo(int64_t seekTimeUs) {
1102    sp<AMessage> msg = new AMessage(kWhatSeek, id());
1103    msg->setInt64("seekTimeUs", seekTimeUs);
1104
1105    sp<AMessage> response;
1106    status_t err = msg->postAndAwaitResponse(&response);
1107    if (err == OK && response != NULL) {
1108        CHECK(response->findInt32("err", &err));
1109    }
1110
1111    return err;
1112}
1113
1114void NuPlayer::GenericSource::onSeek(sp<AMessage> msg) {
1115    int64_t seekTimeUs;
1116    CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
1117
1118    sp<AMessage> response = new AMessage;
1119    status_t err = doSeek(seekTimeUs);
1120    response->setInt32("err", err);
1121
1122    uint32_t replyID;
1123    CHECK(msg->senderAwaitsResponse(&replyID));
1124    response->postReply(replyID);
1125}
1126
1127status_t NuPlayer::GenericSource::doSeek(int64_t seekTimeUs) {
1128    // If the Widevine source is stopped, do not attempt to read any
1129    // more buffers.
1130    if (mStopRead) {
1131        return INVALID_OPERATION;
1132    }
1133    if (mVideoTrack.mSource != NULL) {
1134        int64_t actualTimeUs;
1135        readBuffer(MEDIA_TRACK_TYPE_VIDEO, seekTimeUs, &actualTimeUs);
1136
1137        seekTimeUs = actualTimeUs;
1138        mVideoLastDequeueTimeUs = seekTimeUs;
1139    }
1140
1141    if (mAudioTrack.mSource != NULL) {
1142        readBuffer(MEDIA_TRACK_TYPE_AUDIO, seekTimeUs);
1143        mAudioLastDequeueTimeUs = seekTimeUs;
1144    }
1145
1146    setDrmPlaybackStatusIfNeeded(Playback::START, seekTimeUs / 1000);
1147    if (!mStarted) {
1148        setDrmPlaybackStatusIfNeeded(Playback::PAUSE, 0);
1149    }
1150    return OK;
1151}
1152
1153sp<ABuffer> NuPlayer::GenericSource::mediaBufferToABuffer(
1154        MediaBuffer* mb,
1155        media_track_type trackType,
1156        int64_t *actualTimeUs) {
1157    bool audio = trackType == MEDIA_TRACK_TYPE_AUDIO;
1158    size_t outLength = mb->range_length();
1159
1160    if (audio && mAudioIsVorbis) {
1161        outLength += sizeof(int32_t);
1162    }
1163
1164    sp<ABuffer> ab;
1165    if (mIsWidevine && !audio) {
1166        // data is already provided in the buffer
1167        ab = new ABuffer(NULL, mb->range_length());
1168        mb->add_ref();
1169        ab->setMediaBufferBase(mb);
1170    } else {
1171        ab = new ABuffer(outLength);
1172        memcpy(ab->data(),
1173               (const uint8_t *)mb->data() + mb->range_offset(),
1174               mb->range_length());
1175    }
1176
1177    if (audio && mAudioIsVorbis) {
1178        int32_t numPageSamples;
1179        if (!mb->meta_data()->findInt32(kKeyValidSamples, &numPageSamples)) {
1180            numPageSamples = -1;
1181        }
1182
1183        uint8_t* abEnd = ab->data() + mb->range_length();
1184        memcpy(abEnd, &numPageSamples, sizeof(numPageSamples));
1185    }
1186
1187    sp<AMessage> meta = ab->meta();
1188
1189    int64_t timeUs;
1190    CHECK(mb->meta_data()->findInt64(kKeyTime, &timeUs));
1191    meta->setInt64("timeUs", timeUs);
1192
1193    if (trackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1194        const char *mime;
1195        CHECK(mTimedTextTrack.mSource != NULL
1196                && mTimedTextTrack.mSource->getFormat()->findCString(kKeyMIMEType, &mime));
1197        meta->setString("mime", mime);
1198    }
1199
1200    int64_t durationUs;
1201    if (mb->meta_data()->findInt64(kKeyDuration, &durationUs)) {
1202        meta->setInt64("durationUs", durationUs);
1203    }
1204
1205    if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
1206        meta->setInt32("trackIndex", mSubtitleTrack.mIndex);
1207    }
1208
1209    if (actualTimeUs) {
1210        *actualTimeUs = timeUs;
1211    }
1212
1213    mb->release();
1214    mb = NULL;
1215
1216    return ab;
1217}
1218
1219void NuPlayer::GenericSource::postReadBuffer(media_track_type trackType) {
1220    Mutex::Autolock _l(mReadBufferLock);
1221
1222    if ((mPendingReadBufferTypes & (1 << trackType)) == 0) {
1223        mPendingReadBufferTypes |= (1 << trackType);
1224        sp<AMessage> msg = new AMessage(kWhatReadBuffer, id());
1225        msg->setInt32("trackType", trackType);
1226        msg->post();
1227    }
1228}
1229
1230void NuPlayer::GenericSource::onReadBuffer(sp<AMessage> msg) {
1231    int32_t tmpType;
1232    CHECK(msg->findInt32("trackType", &tmpType));
1233    media_track_type trackType = (media_track_type)tmpType;
1234    {
1235        // only protect the variable change, as readBuffer may
1236        // take considerable time.  This may result in one extra
1237        // read being processed, but that is benign.
1238        Mutex::Autolock _l(mReadBufferLock);
1239        mPendingReadBufferTypes &= ~(1 << trackType);
1240    }
1241    readBuffer(trackType);
1242}
1243
1244void NuPlayer::GenericSource::readBuffer(
1245        media_track_type trackType, int64_t seekTimeUs, int64_t *actualTimeUs, bool formatChange) {
1246    // Do not read data if Widevine source is stopped
1247    if (mStopRead) {
1248        return;
1249    }
1250    Track *track;
1251    size_t maxBuffers = 1;
1252    switch (trackType) {
1253        case MEDIA_TRACK_TYPE_VIDEO:
1254            track = &mVideoTrack;
1255            if (mIsWidevine) {
1256                maxBuffers = 2;
1257            }
1258            break;
1259        case MEDIA_TRACK_TYPE_AUDIO:
1260            track = &mAudioTrack;
1261            if (mIsWidevine) {
1262                maxBuffers = 8;
1263            } else {
1264                maxBuffers = 64;
1265            }
1266            break;
1267        case MEDIA_TRACK_TYPE_SUBTITLE:
1268            track = &mSubtitleTrack;
1269            break;
1270        case MEDIA_TRACK_TYPE_TIMEDTEXT:
1271            track = &mTimedTextTrack;
1272            break;
1273        default:
1274            TRESPASS();
1275    }
1276
1277    if (track->mSource == NULL) {
1278        return;
1279    }
1280
1281    if (actualTimeUs) {
1282        *actualTimeUs = seekTimeUs;
1283    }
1284
1285    MediaSource::ReadOptions options;
1286
1287    bool seeking = false;
1288
1289    if (seekTimeUs >= 0) {
1290        options.setSeekTo(seekTimeUs, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC);
1291        seeking = true;
1292    }
1293
1294    if (mIsWidevine && trackType != MEDIA_TRACK_TYPE_AUDIO) {
1295        options.setNonBlocking();
1296    }
1297
1298    for (size_t numBuffers = 0; numBuffers < maxBuffers; ) {
1299        MediaBuffer *mbuf;
1300        status_t err = track->mSource->read(&mbuf, &options);
1301
1302        options.clearSeekTo();
1303
1304        if (err == OK) {
1305            int64_t timeUs;
1306            CHECK(mbuf->meta_data()->findInt64(kKeyTime, &timeUs));
1307            if (trackType == MEDIA_TRACK_TYPE_AUDIO) {
1308                mAudioTimeUs = timeUs;
1309            } else if (trackType == MEDIA_TRACK_TYPE_VIDEO) {
1310                mVideoTimeUs = timeUs;
1311            }
1312
1313            // formatChange && seeking: track whose source is changed during selection
1314            // formatChange && !seeking: track whose source is not changed during selection
1315            // !formatChange: normal seek
1316            if ((seeking || formatChange)
1317                    && (trackType == MEDIA_TRACK_TYPE_AUDIO
1318                    || trackType == MEDIA_TRACK_TYPE_VIDEO)) {
1319                ATSParser::DiscontinuityType type = formatChange
1320                        ? (seeking
1321                                ? ATSParser::DISCONTINUITY_FORMATCHANGE
1322                                : ATSParser::DISCONTINUITY_NONE)
1323                        : ATSParser::DISCONTINUITY_SEEK;
1324                track->mPackets->queueDiscontinuity( type, NULL, true /* discard */);
1325            }
1326
1327            sp<ABuffer> buffer = mediaBufferToABuffer(mbuf, trackType, actualTimeUs);
1328            track->mPackets->queueAccessUnit(buffer);
1329            formatChange = false;
1330            seeking = false;
1331            ++numBuffers;
1332        } else if (err == WOULD_BLOCK) {
1333            break;
1334        } else if (err == INFO_FORMAT_CHANGED) {
1335#if 0
1336            track->mPackets->queueDiscontinuity(
1337                    ATSParser::DISCONTINUITY_FORMATCHANGE,
1338                    NULL,
1339                    false /* discard */);
1340#endif
1341        } else {
1342            track->mPackets->signalEOS(err);
1343            break;
1344        }
1345    }
1346}
1347
1348}  // namespace android
1349