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 #include "NuPlayerDrm.h"
22 
23 #include "AnotherPacketSource.h"
24 #include <binder/IServiceManager.h>
25 #include <cutils/properties.h>
26 #include <media/DataSource.h>
27 #include <media/MediaBufferHolder.h>
28 #include <media/MediaExtractor.h>
29 #include <media/MediaSource.h>
30 #include <media/IMediaExtractorService.h>
31 #include <media/IMediaHTTPService.h>
32 #include <media/stagefright/foundation/ABuffer.h>
33 #include <media/stagefright/foundation/ADebug.h>
34 #include <media/stagefright/foundation/AMessage.h>
35 #include <media/stagefright/DataSourceFactory.h>
36 #include <media/stagefright/FileSource.h>
37 #include <media/stagefright/InterfaceUtils.h>
38 #include <media/stagefright/MediaBuffer.h>
39 #include <media/stagefright/MediaClock.h>
40 #include <media/stagefright/MediaDefs.h>
41 #include <media/stagefright/MediaExtractorFactory.h>
42 #include <media/stagefright/MetaData.h>
43 #include <media/stagefright/Utils.h>
44 #include "../../libstagefright/include/NuCachedSource2.h"
45 #include "../../libstagefright/include/HTTPBase.h"
46 
47 namespace android {
48 
49 static const int kInitialMarkMs        = 5000;  // 5secs
50 
51 //static const int kPausePlaybackMarkMs  = 2000;  // 2secs
52 static const int kResumePlaybackMarkMs = 15000;  // 15secs
53 
GenericSource(const sp<AMessage> & notify,bool uidValid,uid_t uid,const sp<MediaClock> & mediaClock)54 NuPlayer::GenericSource::GenericSource(
55         const sp<AMessage> &notify,
56         bool uidValid,
57         uid_t uid,
58         const sp<MediaClock> &mediaClock)
59     : Source(notify),
60       mAudioTimeUs(0),
61       mAudioLastDequeueTimeUs(0),
62       mVideoTimeUs(0),
63       mVideoLastDequeueTimeUs(0),
64       mPrevBufferPercentage(-1),
65       mPollBufferingGeneration(0),
66       mSentPauseOnBuffering(false),
67       mAudioDataGeneration(0),
68       mVideoDataGeneration(0),
69       mFetchSubtitleDataGeneration(0),
70       mFetchTimedTextDataGeneration(0),
71       mDurationUs(-1ll),
72       mAudioIsVorbis(false),
73       mIsSecure(false),
74       mIsStreaming(false),
75       mUIDValid(uidValid),
76       mUID(uid),
77       mMediaClock(mediaClock),
78       mFd(-1),
79       mBitrate(-1ll),
80       mPendingReadBufferTypes(0) {
81     ALOGV("GenericSource");
82     CHECK(mediaClock != NULL);
83 
84     mBufferingSettings.mInitialMarkMs = kInitialMarkMs;
85     mBufferingSettings.mResumePlaybackMarkMs = kResumePlaybackMarkMs;
86     resetDataSource();
87 }
88 
resetDataSource()89 void NuPlayer::GenericSource::resetDataSource() {
90     ALOGV("resetDataSource");
91 
92     mHTTPService.clear();
93     mHttpSource.clear();
94     mDisconnected = false;
95     mUri.clear();
96     mUriHeaders.clear();
97     if (mFd >= 0) {
98         close(mFd);
99         mFd = -1;
100     }
101     mOffset = 0;
102     mLength = 0;
103     mStarted = false;
104     mPreparing = false;
105 
106     mIsDrmProtected = false;
107     mIsDrmReleased = false;
108     mIsSecure = false;
109     mMimes.clear();
110 }
111 
setDataSource(const sp<IMediaHTTPService> & httpService,const char * url,const KeyedVector<String8,String8> * headers)112 status_t NuPlayer::GenericSource::setDataSource(
113         const sp<IMediaHTTPService> &httpService,
114         const char *url,
115         const KeyedVector<String8, String8> *headers) {
116     Mutex::Autolock _l(mLock);
117     ALOGV("setDataSource url: %s", url);
118 
119     resetDataSource();
120 
121     mHTTPService = httpService;
122     mUri = url;
123 
124     if (headers) {
125         mUriHeaders = *headers;
126     }
127 
128     // delay data source creation to prepareAsync() to avoid blocking
129     // the calling thread in setDataSource for any significant time.
130     return OK;
131 }
132 
setDataSource(int fd,int64_t offset,int64_t length)133 status_t NuPlayer::GenericSource::setDataSource(
134         int fd, int64_t offset, int64_t length) {
135     Mutex::Autolock _l(mLock);
136     ALOGV("setDataSource %d/%lld/%lld", fd, (long long)offset, (long long)length);
137 
138     resetDataSource();
139 
140     mFd = dup(fd);
141     mOffset = offset;
142     mLength = length;
143 
144     // delay data source creation to prepareAsync() to avoid blocking
145     // the calling thread in setDataSource for any significant time.
146     return OK;
147 }
148 
setDataSource(const sp<DataSource> & source)149 status_t NuPlayer::GenericSource::setDataSource(const sp<DataSource>& source) {
150     Mutex::Autolock _l(mLock);
151     ALOGV("setDataSource (source: %p)", source.get());
152 
153     resetDataSource();
154     mDataSource = source;
155     return OK;
156 }
157 
getFileFormatMeta() const158 sp<MetaData> NuPlayer::GenericSource::getFileFormatMeta() const {
159     Mutex::Autolock _l(mLock);
160     return mFileMeta;
161 }
162 
initFromDataSource()163 status_t NuPlayer::GenericSource::initFromDataSource() {
164     sp<IMediaExtractor> extractor;
165     CHECK(mDataSource != NULL);
166     sp<DataSource> dataSource = mDataSource;
167 
168     mLock.unlock();
169     // This might take long time if data source is not reliable.
170     extractor = MediaExtractorFactory::Create(dataSource, NULL);
171 
172     if (extractor == NULL) {
173         ALOGE("initFromDataSource, cannot create extractor!");
174         return UNKNOWN_ERROR;
175     }
176 
177     sp<MetaData> fileMeta = extractor->getMetaData();
178 
179     size_t numtracks = extractor->countTracks();
180     if (numtracks == 0) {
181         ALOGE("initFromDataSource, source has no track!");
182         return UNKNOWN_ERROR;
183     }
184 
185     mLock.lock();
186     mFileMeta = fileMeta;
187     if (mFileMeta != NULL) {
188         int64_t duration;
189         if (mFileMeta->findInt64(kKeyDuration, &duration)) {
190             mDurationUs = duration;
191         }
192     }
193 
194     int32_t totalBitrate = 0;
195 
196     mMimes.clear();
197 
198     for (size_t i = 0; i < numtracks; ++i) {
199         sp<IMediaSource> track = extractor->getTrack(i);
200         if (track == NULL) {
201             continue;
202         }
203 
204         sp<MetaData> meta = extractor->getTrackMetaData(i);
205         if (meta == NULL) {
206             ALOGE("no metadata for track %zu", i);
207             return UNKNOWN_ERROR;
208         }
209 
210         const char *mime;
211         CHECK(meta->findCString(kKeyMIMEType, &mime));
212 
213         ALOGV("initFromDataSource track[%zu]: %s", i, mime);
214 
215         // Do the string compare immediately with "mime",
216         // we can't assume "mime" would stay valid after another
217         // extractor operation, some extractors might modify meta
218         // during getTrack() and make it invalid.
219         if (!strncasecmp(mime, "audio/", 6)) {
220             if (mAudioTrack.mSource == NULL) {
221                 mAudioTrack.mIndex = i;
222                 mAudioTrack.mSource = track;
223                 mAudioTrack.mPackets =
224                     new AnotherPacketSource(mAudioTrack.mSource->getFormat());
225 
226                 if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) {
227                     mAudioIsVorbis = true;
228                 } else {
229                     mAudioIsVorbis = false;
230                 }
231 
232                 mMimes.add(String8(mime));
233             }
234         } else if (!strncasecmp(mime, "video/", 6)) {
235             if (mVideoTrack.mSource == NULL) {
236                 mVideoTrack.mIndex = i;
237                 mVideoTrack.mSource = track;
238                 mVideoTrack.mPackets =
239                     new AnotherPacketSource(mVideoTrack.mSource->getFormat());
240 
241                 // video always at the beginning
242                 mMimes.insertAt(String8(mime), 0);
243             }
244         }
245 
246         mSources.push(track);
247         int64_t durationUs;
248         if (meta->findInt64(kKeyDuration, &durationUs)) {
249             if (durationUs > mDurationUs) {
250                 mDurationUs = durationUs;
251             }
252         }
253 
254         int32_t bitrate;
255         if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) {
256             totalBitrate += bitrate;
257         } else {
258             totalBitrate = -1;
259         }
260     }
261 
262     ALOGV("initFromDataSource mSources.size(): %zu  mIsSecure: %d  mime[0]: %s", mSources.size(),
263             mIsSecure, (mMimes.isEmpty() ? "NONE" : mMimes[0].string()));
264 
265     if (mSources.size() == 0) {
266         ALOGE("b/23705695");
267         return UNKNOWN_ERROR;
268     }
269 
270     // Modular DRM: The return value doesn't affect source initialization.
271     (void)checkDrmInfo();
272 
273     mBitrate = totalBitrate;
274 
275     return OK;
276 }
277 
getBufferingSettings(BufferingSettings * buffering)278 status_t NuPlayer::GenericSource::getBufferingSettings(
279         BufferingSettings* buffering /* nonnull */) {
280     {
281         Mutex::Autolock _l(mLock);
282         *buffering = mBufferingSettings;
283     }
284 
285     ALOGV("getBufferingSettings{%s}", buffering->toString().string());
286     return OK;
287 }
288 
setBufferingSettings(const BufferingSettings & buffering)289 status_t NuPlayer::GenericSource::setBufferingSettings(const BufferingSettings& buffering) {
290     ALOGV("setBufferingSettings{%s}", buffering.toString().string());
291 
292     Mutex::Autolock _l(mLock);
293     mBufferingSettings = buffering;
294     return OK;
295 }
296 
startSources()297 status_t NuPlayer::GenericSource::startSources() {
298     // Start the selected A/V tracks now before we start buffering.
299     // Widevine sources might re-initialize crypto when starting, if we delay
300     // this to start(), all data buffered during prepare would be wasted.
301     // (We don't actually start reading until start().)
302     //
303     // TODO: this logic may no longer be relevant after the removal of widevine
304     // support
305     if (mAudioTrack.mSource != NULL && mAudioTrack.mSource->start() != OK) {
306         ALOGE("failed to start audio track!");
307         return UNKNOWN_ERROR;
308     }
309 
310     if (mVideoTrack.mSource != NULL && mVideoTrack.mSource->start() != OK) {
311         ALOGE("failed to start video track!");
312         return UNKNOWN_ERROR;
313     }
314 
315     return OK;
316 }
317 
getLastReadPosition()318 int64_t NuPlayer::GenericSource::getLastReadPosition() {
319     if (mAudioTrack.mSource != NULL) {
320         return mAudioTimeUs;
321     } else if (mVideoTrack.mSource != NULL) {
322         return mVideoTimeUs;
323     } else {
324         return 0;
325     }
326 }
327 
isStreaming() const328 bool NuPlayer::GenericSource::isStreaming() const {
329     Mutex::Autolock _l(mLock);
330     return mIsStreaming;
331 }
332 
~GenericSource()333 NuPlayer::GenericSource::~GenericSource() {
334     ALOGV("~GenericSource");
335     if (mLooper != NULL) {
336         mLooper->unregisterHandler(id());
337         mLooper->stop();
338     }
339     resetDataSource();
340 }
341 
prepareAsync()342 void NuPlayer::GenericSource::prepareAsync() {
343     Mutex::Autolock _l(mLock);
344     ALOGV("prepareAsync: (looper: %d)", (mLooper != NULL));
345 
346     if (mLooper == NULL) {
347         mLooper = new ALooper;
348         mLooper->setName("generic");
349         mLooper->start();
350 
351         mLooper->registerHandler(this);
352     }
353 
354     sp<AMessage> msg = new AMessage(kWhatPrepareAsync, this);
355     msg->post();
356 }
357 
onPrepareAsync()358 void NuPlayer::GenericSource::onPrepareAsync() {
359     ALOGV("onPrepareAsync: mDataSource: %d", (mDataSource != NULL));
360 
361     // delayed data source creation
362     if (mDataSource == NULL) {
363         // set to false first, if the extractor
364         // comes back as secure, set it to true then.
365         mIsSecure = false;
366 
367         if (!mUri.empty()) {
368             const char* uri = mUri.c_str();
369             String8 contentType;
370 
371             if (!strncasecmp("http://", uri, 7) || !strncasecmp("https://", uri, 8)) {
372                 mHttpSource = DataSourceFactory::CreateMediaHTTP(mHTTPService);
373                 if (mHttpSource == NULL) {
374                     ALOGE("Failed to create http source!");
375                     notifyPreparedAndCleanup(UNKNOWN_ERROR);
376                     return;
377                 }
378             }
379 
380             mLock.unlock();
381             // This might take long time if connection has some issue.
382             sp<DataSource> dataSource = DataSourceFactory::CreateFromURI(
383                    mHTTPService, uri, &mUriHeaders, &contentType,
384                    static_cast<HTTPBase *>(mHttpSource.get()));
385             mLock.lock();
386             if (!mDisconnected) {
387                 mDataSource = dataSource;
388             }
389         } else {
390             if (property_get_bool("media.stagefright.extractremote", true) &&
391                     !FileSource::requiresDrm(mFd, mOffset, mLength, nullptr /* mime */)) {
392                 sp<IBinder> binder =
393                         defaultServiceManager()->getService(String16("media.extractor"));
394                 if (binder != nullptr) {
395                     ALOGD("FileSource remote");
396                     sp<IMediaExtractorService> mediaExService(
397                             interface_cast<IMediaExtractorService>(binder));
398                     sp<IDataSource> source =
399                             mediaExService->makeIDataSource(mFd, mOffset, mLength);
400                     ALOGV("IDataSource(FileSource): %p %d %lld %lld",
401                             source.get(), mFd, (long long)mOffset, (long long)mLength);
402                     if (source.get() != nullptr) {
403                         mDataSource = CreateDataSourceFromIDataSource(source);
404                         if (mDataSource != nullptr) {
405                             // Close the local file descriptor as it is not needed anymore.
406                             close(mFd);
407                             mFd = -1;
408                         }
409                     } else {
410                         ALOGW("extractor service cannot make data source");
411                     }
412                 } else {
413                     ALOGW("extractor service not running");
414                 }
415             }
416             if (mDataSource == nullptr) {
417                 ALOGD("FileSource local");
418                 mDataSource = new FileSource(mFd, mOffset, mLength);
419             }
420             // TODO: close should always be done on mFd, see the lines following
421             // CreateDataSourceFromIDataSource above,
422             // and the FileSource constructor should dup the mFd argument as needed.
423             mFd = -1;
424         }
425 
426         if (mDataSource == NULL) {
427             ALOGE("Failed to create data source!");
428             notifyPreparedAndCleanup(UNKNOWN_ERROR);
429             return;
430         }
431     }
432 
433     if (mDataSource->flags() & DataSource::kIsCachingDataSource) {
434         mCachedSource = static_cast<NuCachedSource2 *>(mDataSource.get());
435     }
436 
437     // For cached streaming cases, we need to wait for enough
438     // buffering before reporting prepared.
439     mIsStreaming = (mCachedSource != NULL);
440 
441     // init extractor from data source
442     status_t err = initFromDataSource();
443 
444     if (err != OK) {
445         ALOGE("Failed to init from data source!");
446         notifyPreparedAndCleanup(err);
447         return;
448     }
449 
450     if (mVideoTrack.mSource != NULL) {
451         sp<MetaData> meta = getFormatMeta_l(false /* audio */);
452         sp<AMessage> msg = new AMessage;
453         err = convertMetaDataToMessage(meta, &msg);
454         if(err != OK) {
455             notifyPreparedAndCleanup(err);
456             return;
457         }
458         notifyVideoSizeChanged(msg);
459     }
460 
461     notifyFlagsChanged(
462             // FLAG_SECURE will be known if/when prepareDrm is called by the app
463             // FLAG_PROTECTED will be known if/when prepareDrm is called by the app
464             FLAG_CAN_PAUSE |
465             FLAG_CAN_SEEK_BACKWARD |
466             FLAG_CAN_SEEK_FORWARD |
467             FLAG_CAN_SEEK);
468 
469     finishPrepareAsync();
470 
471     ALOGV("onPrepareAsync: Done");
472 }
473 
finishPrepareAsync()474 void NuPlayer::GenericSource::finishPrepareAsync() {
475     ALOGV("finishPrepareAsync");
476 
477     status_t err = startSources();
478     if (err != OK) {
479         ALOGE("Failed to init start data source!");
480         notifyPreparedAndCleanup(err);
481         return;
482     }
483 
484     if (mIsStreaming) {
485         mCachedSource->resumeFetchingIfNecessary();
486         mPreparing = true;
487         schedulePollBuffering();
488     } else {
489         notifyPrepared();
490     }
491 
492     if (mAudioTrack.mSource != NULL) {
493         postReadBuffer(MEDIA_TRACK_TYPE_AUDIO);
494     }
495 
496     if (mVideoTrack.mSource != NULL) {
497         postReadBuffer(MEDIA_TRACK_TYPE_VIDEO);
498     }
499 }
500 
notifyPreparedAndCleanup(status_t err)501 void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) {
502     if (err != OK) {
503         mDataSource.clear();
504         mCachedSource.clear();
505         mHttpSource.clear();
506 
507         mBitrate = -1;
508         mPrevBufferPercentage = -1;
509         ++mPollBufferingGeneration;
510     }
511     notifyPrepared(err);
512 }
513 
start()514 void NuPlayer::GenericSource::start() {
515     Mutex::Autolock _l(mLock);
516     ALOGI("start");
517 
518     if (mAudioTrack.mSource != NULL) {
519         postReadBuffer(MEDIA_TRACK_TYPE_AUDIO);
520     }
521 
522     if (mVideoTrack.mSource != NULL) {
523         postReadBuffer(MEDIA_TRACK_TYPE_VIDEO);
524     }
525 
526     mStarted = true;
527 }
528 
stop()529 void NuPlayer::GenericSource::stop() {
530     Mutex::Autolock _l(mLock);
531     mStarted = false;
532 }
533 
pause()534 void NuPlayer::GenericSource::pause() {
535     Mutex::Autolock _l(mLock);
536     mStarted = false;
537 }
538 
resume()539 void NuPlayer::GenericSource::resume() {
540     Mutex::Autolock _l(mLock);
541     mStarted = true;
542 }
543 
disconnect()544 void NuPlayer::GenericSource::disconnect() {
545     sp<DataSource> dataSource, httpSource;
546     {
547         Mutex::Autolock _l(mLock);
548         dataSource = mDataSource;
549         httpSource = mHttpSource;
550         mDisconnected = true;
551     }
552 
553     if (dataSource != NULL) {
554         // disconnect data source
555         if (dataSource->flags() & DataSource::kIsCachingDataSource) {
556             static_cast<NuCachedSource2 *>(dataSource.get())->disconnect();
557         }
558     } else if (httpSource != NULL) {
559         static_cast<HTTPBase *>(httpSource.get())->disconnect();
560     }
561 }
562 
feedMoreTSData()563 status_t NuPlayer::GenericSource::feedMoreTSData() {
564     return OK;
565 }
566 
sendCacheStats()567 void NuPlayer::GenericSource::sendCacheStats() {
568     int32_t kbps = 0;
569     status_t err = UNKNOWN_ERROR;
570 
571     if (mCachedSource != NULL) {
572         err = mCachedSource->getEstimatedBandwidthKbps(&kbps);
573     }
574 
575     if (err == OK) {
576         sp<AMessage> notify = dupNotify();
577         notify->setInt32("what", kWhatCacheStats);
578         notify->setInt32("bandwidth", kbps);
579         notify->post();
580     }
581 }
582 
onMessageReceived(const sp<AMessage> & msg)583 void NuPlayer::GenericSource::onMessageReceived(const sp<AMessage> &msg) {
584     Mutex::Autolock _l(mLock);
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 kWhatSendGlobalTimedTextData:
613       {
614           sendGlobalTextData(kWhatTimedTextData, mFetchTimedTextDataGeneration, msg);
615           break;
616       }
617       case kWhatSendTimedTextData:
618       {
619           sendTextData(kWhatTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT,
620                   mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg);
621           break;
622       }
623 
624       case kWhatChangeAVSource:
625       {
626           int32_t trackIndex;
627           CHECK(msg->findInt32("trackIndex", &trackIndex));
628           const sp<IMediaSource> source = mSources.itemAt(trackIndex);
629 
630           Track* track;
631           const char *mime;
632           media_track_type trackType, counterpartType;
633           sp<MetaData> meta = source->getFormat();
634           meta->findCString(kKeyMIMEType, &mime);
635           if (!strncasecmp(mime, "audio/", 6)) {
636               track = &mAudioTrack;
637               trackType = MEDIA_TRACK_TYPE_AUDIO;
638               counterpartType = MEDIA_TRACK_TYPE_VIDEO;;
639           } else {
640               CHECK(!strncasecmp(mime, "video/", 6));
641               track = &mVideoTrack;
642               trackType = MEDIA_TRACK_TYPE_VIDEO;
643               counterpartType = MEDIA_TRACK_TYPE_AUDIO;;
644           }
645 
646 
647           if (track->mSource != NULL) {
648               track->mSource->stop();
649           }
650           track->mSource = source;
651           track->mSource->start();
652           track->mIndex = trackIndex;
653           ++mAudioDataGeneration;
654           ++mVideoDataGeneration;
655 
656           int64_t timeUs, actualTimeUs;
657           const bool formatChange = true;
658           if (trackType == MEDIA_TRACK_TYPE_AUDIO) {
659               timeUs = mAudioLastDequeueTimeUs;
660           } else {
661               timeUs = mVideoLastDequeueTimeUs;
662           }
663           readBuffer(trackType, timeUs, MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC /* mode */,
664                   &actualTimeUs, formatChange);
665           readBuffer(counterpartType, -1, MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC /* mode */,
666                   NULL, !formatChange);
667           ALOGV("timeUs %lld actualTimeUs %lld", (long long)timeUs, (long long)actualTimeUs);
668 
669           break;
670       }
671 
672       case kWhatSeek:
673       {
674           onSeek(msg);
675           break;
676       }
677 
678       case kWhatReadBuffer:
679       {
680           onReadBuffer(msg);
681           break;
682       }
683 
684       case kWhatPollBuffering:
685       {
686           int32_t generation;
687           CHECK(msg->findInt32("generation", &generation));
688           if (generation == mPollBufferingGeneration) {
689               onPollBuffering();
690           }
691           break;
692       }
693 
694       default:
695           Source::onMessageReceived(msg);
696           break;
697     }
698 }
699 
fetchTextData(uint32_t sendWhat,media_track_type type,int32_t curGen,const sp<AnotherPacketSource> & packets,const sp<AMessage> & msg)700 void NuPlayer::GenericSource::fetchTextData(
701         uint32_t sendWhat,
702         media_track_type type,
703         int32_t curGen,
704         const sp<AnotherPacketSource>& packets,
705         const sp<AMessage>& msg) {
706     int32_t msgGeneration;
707     CHECK(msg->findInt32("generation", &msgGeneration));
708     if (msgGeneration != curGen) {
709         // stale
710         return;
711     }
712 
713     int32_t avail;
714     if (packets->hasBufferAvailable(&avail)) {
715         return;
716     }
717 
718     int64_t timeUs;
719     CHECK(msg->findInt64("timeUs", &timeUs));
720 
721     int64_t subTimeUs = 0;
722     readBuffer(type, timeUs, MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC /* mode */, &subTimeUs);
723 
724     status_t eosResult;
725     if (!packets->hasBufferAvailable(&eosResult)) {
726         return;
727     }
728 
729     if (msg->what() == kWhatFetchSubtitleData) {
730         subTimeUs -= 1000000ll;  // send subtile data one second earlier
731     }
732     sp<AMessage> msg2 = new AMessage(sendWhat, this);
733     msg2->setInt32("generation", msgGeneration);
734     mMediaClock->addTimer(msg2, subTimeUs);
735 }
736 
sendTextData(uint32_t what,media_track_type type,int32_t curGen,const sp<AnotherPacketSource> & packets,const sp<AMessage> & msg)737 void NuPlayer::GenericSource::sendTextData(
738         uint32_t what,
739         media_track_type type,
740         int32_t curGen,
741         const sp<AnotherPacketSource>& packets,
742         const sp<AMessage>& msg) {
743     int32_t msgGeneration;
744     CHECK(msg->findInt32("generation", &msgGeneration));
745     if (msgGeneration != curGen) {
746         // stale
747         return;
748     }
749 
750     int64_t subTimeUs;
751     if (packets->nextBufferTime(&subTimeUs) != OK) {
752         return;
753     }
754 
755     int64_t nextSubTimeUs;
756     readBuffer(type, -1, MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC /* mode */, &nextSubTimeUs);
757 
758     sp<ABuffer> buffer;
759     status_t dequeueStatus = packets->dequeueAccessUnit(&buffer);
760     if (dequeueStatus == OK) {
761         sp<AMessage> notify = dupNotify();
762         notify->setInt32("what", what);
763         notify->setBuffer("buffer", buffer);
764         notify->post();
765 
766         if (msg->what() == kWhatSendSubtitleData) {
767             nextSubTimeUs -= 1000000ll;  // send subtile data one second earlier
768         }
769         mMediaClock->addTimer(msg, nextSubTimeUs);
770     }
771 }
772 
sendGlobalTextData(uint32_t what,int32_t curGen,sp<AMessage> msg)773 void NuPlayer::GenericSource::sendGlobalTextData(
774         uint32_t what,
775         int32_t curGen,
776         sp<AMessage> msg) {
777     int32_t msgGeneration;
778     CHECK(msg->findInt32("generation", &msgGeneration));
779     if (msgGeneration != curGen) {
780         // stale
781         return;
782     }
783 
784     uint32_t textType;
785     const void *data;
786     size_t size = 0;
787     if (mTimedTextTrack.mSource->getFormat()->findData(
788                     kKeyTextFormatData, &textType, &data, &size)) {
789         mGlobalTimedText = new ABuffer(size);
790         if (mGlobalTimedText->data()) {
791             memcpy(mGlobalTimedText->data(), data, size);
792             sp<AMessage> globalMeta = mGlobalTimedText->meta();
793             globalMeta->setInt64("timeUs", 0);
794             globalMeta->setString("mime", MEDIA_MIMETYPE_TEXT_3GPP);
795             globalMeta->setInt32("global", 1);
796             sp<AMessage> notify = dupNotify();
797             notify->setInt32("what", what);
798             notify->setBuffer("buffer", mGlobalTimedText);
799             notify->post();
800         }
801     }
802 }
803 
getFormatMeta(bool audio)804 sp<MetaData> NuPlayer::GenericSource::getFormatMeta(bool audio) {
805     Mutex::Autolock _l(mLock);
806     return getFormatMeta_l(audio);
807 }
808 
getFormatMeta_l(bool audio)809 sp<MetaData> NuPlayer::GenericSource::getFormatMeta_l(bool audio) {
810     sp<IMediaSource> source = audio ? mAudioTrack.mSource : mVideoTrack.mSource;
811 
812     if (source == NULL) {
813         return NULL;
814     }
815 
816     return source->getFormat();
817 }
818 
dequeueAccessUnit(bool audio,sp<ABuffer> * accessUnit)819 status_t NuPlayer::GenericSource::dequeueAccessUnit(
820         bool audio, sp<ABuffer> *accessUnit) {
821     Mutex::Autolock _l(mLock);
822     // If has gone through stop/releaseDrm sequence, we no longer send down any buffer b/c
823     // the codec's crypto object has gone away (b/37960096).
824     // Note: This will be unnecessary when stop() changes behavior and releases codec (b/35248283).
825     if (!mStarted && mIsDrmReleased) {
826         return -EWOULDBLOCK;
827     }
828 
829     Track *track = audio ? &mAudioTrack : &mVideoTrack;
830 
831     if (track->mSource == NULL) {
832         return -EWOULDBLOCK;
833     }
834 
835     status_t finalResult;
836     if (!track->mPackets->hasBufferAvailable(&finalResult)) {
837         if (finalResult == OK) {
838             postReadBuffer(
839                     audio ? MEDIA_TRACK_TYPE_AUDIO : MEDIA_TRACK_TYPE_VIDEO);
840             return -EWOULDBLOCK;
841         }
842         return finalResult;
843     }
844 
845     status_t result = track->mPackets->dequeueAccessUnit(accessUnit);
846 
847     // start pulling in more buffers if cache is running low
848     // so that decoder has less chance of being starved
849     if (!mIsStreaming) {
850         if (track->mPackets->getAvailableBufferCount(&finalResult) < 2) {
851             postReadBuffer(audio? MEDIA_TRACK_TYPE_AUDIO : MEDIA_TRACK_TYPE_VIDEO);
852         }
853     } else {
854         int64_t durationUs = track->mPackets->getBufferedDurationUs(&finalResult);
855         // TODO: maxRebufferingMarkMs could be larger than
856         // mBufferingSettings.mResumePlaybackMarkMs
857         int64_t restartBufferingMarkUs =
858              mBufferingSettings.mResumePlaybackMarkMs * 1000ll / 2;
859         if (finalResult == OK) {
860             if (durationUs < restartBufferingMarkUs) {
861                 postReadBuffer(audio? MEDIA_TRACK_TYPE_AUDIO : MEDIA_TRACK_TYPE_VIDEO);
862             }
863             if (track->mPackets->getAvailableBufferCount(&finalResult) < 2
864                 && !mSentPauseOnBuffering && !mPreparing) {
865                 mCachedSource->resumeFetchingIfNecessary();
866                 sendCacheStats();
867                 mSentPauseOnBuffering = true;
868                 sp<AMessage> notify = dupNotify();
869                 notify->setInt32("what", kWhatPauseOnBufferingStart);
870                 notify->post();
871             }
872         }
873     }
874 
875     if (result != OK) {
876         if (mSubtitleTrack.mSource != NULL) {
877             mSubtitleTrack.mPackets->clear();
878             mFetchSubtitleDataGeneration++;
879         }
880         if (mTimedTextTrack.mSource != NULL) {
881             mTimedTextTrack.mPackets->clear();
882             mFetchTimedTextDataGeneration++;
883         }
884         return result;
885     }
886 
887     int64_t timeUs;
888     status_t eosResult; // ignored
889     CHECK((*accessUnit)->meta()->findInt64("timeUs", &timeUs));
890     if (audio) {
891         mAudioLastDequeueTimeUs = timeUs;
892     } else {
893         mVideoLastDequeueTimeUs = timeUs;
894     }
895 
896     if (mSubtitleTrack.mSource != NULL
897             && !mSubtitleTrack.mPackets->hasBufferAvailable(&eosResult)) {
898         sp<AMessage> msg = new AMessage(kWhatFetchSubtitleData, this);
899         msg->setInt64("timeUs", timeUs);
900         msg->setInt32("generation", mFetchSubtitleDataGeneration);
901         msg->post();
902     }
903 
904     if (mTimedTextTrack.mSource != NULL
905             && !mTimedTextTrack.mPackets->hasBufferAvailable(&eosResult)) {
906         sp<AMessage> msg = new AMessage(kWhatFetchTimedTextData, this);
907         msg->setInt64("timeUs", timeUs);
908         msg->setInt32("generation", mFetchTimedTextDataGeneration);
909         msg->post();
910     }
911 
912     return result;
913 }
914 
getDuration(int64_t * durationUs)915 status_t NuPlayer::GenericSource::getDuration(int64_t *durationUs) {
916     Mutex::Autolock _l(mLock);
917     *durationUs = mDurationUs;
918     return OK;
919 }
920 
getTrackCount() const921 size_t NuPlayer::GenericSource::getTrackCount() const {
922     Mutex::Autolock _l(mLock);
923     return mSources.size();
924 }
925 
getTrackInfo(size_t trackIndex) const926 sp<AMessage> NuPlayer::GenericSource::getTrackInfo(size_t trackIndex) const {
927     Mutex::Autolock _l(mLock);
928     size_t trackCount = mSources.size();
929     if (trackIndex >= trackCount) {
930         return NULL;
931     }
932 
933     sp<AMessage> format = new AMessage();
934     sp<MetaData> meta = mSources.itemAt(trackIndex)->getFormat();
935     if (meta == NULL) {
936         ALOGE("no metadata for track %zu", trackIndex);
937         format->setInt32("type", MEDIA_TRACK_TYPE_UNKNOWN);
938         format->setString("mime", "application/octet-stream");
939         format->setString("language", "und");
940 
941         return format;
942     }
943 
944     const char *mime;
945     CHECK(meta->findCString(kKeyMIMEType, &mime));
946     format->setString("mime", mime);
947 
948     int32_t trackType;
949     if (!strncasecmp(mime, "video/", 6)) {
950         trackType = MEDIA_TRACK_TYPE_VIDEO;
951     } else if (!strncasecmp(mime, "audio/", 6)) {
952         trackType = MEDIA_TRACK_TYPE_AUDIO;
953     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP)) {
954         trackType = MEDIA_TRACK_TYPE_TIMEDTEXT;
955     } else {
956         trackType = MEDIA_TRACK_TYPE_UNKNOWN;
957     }
958     format->setInt32("type", trackType);
959 
960     const char *lang;
961     if (!meta->findCString(kKeyMediaLanguage, &lang)) {
962         lang = "und";
963     }
964     format->setString("language", lang);
965 
966     if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
967         int32_t isAutoselect = 1, isDefault = 0, isForced = 0;
968         meta->findInt32(kKeyTrackIsAutoselect, &isAutoselect);
969         meta->findInt32(kKeyTrackIsDefault, &isDefault);
970         meta->findInt32(kKeyTrackIsForced, &isForced);
971 
972         format->setInt32("auto", !!isAutoselect);
973         format->setInt32("default", !!isDefault);
974         format->setInt32("forced", !!isForced);
975     }
976 
977     return format;
978 }
979 
getSelectedTrack(media_track_type type) const980 ssize_t NuPlayer::GenericSource::getSelectedTrack(media_track_type type) const {
981     Mutex::Autolock _l(mLock);
982     const Track *track = NULL;
983     switch (type) {
984     case MEDIA_TRACK_TYPE_VIDEO:
985         track = &mVideoTrack;
986         break;
987     case MEDIA_TRACK_TYPE_AUDIO:
988         track = &mAudioTrack;
989         break;
990     case MEDIA_TRACK_TYPE_TIMEDTEXT:
991         track = &mTimedTextTrack;
992         break;
993     case MEDIA_TRACK_TYPE_SUBTITLE:
994         track = &mSubtitleTrack;
995         break;
996     default:
997         break;
998     }
999 
1000     if (track != NULL && track->mSource != NULL) {
1001         return track->mIndex;
1002     }
1003 
1004     return -1;
1005 }
1006 
selectTrack(size_t trackIndex,bool select,int64_t timeUs)1007 status_t NuPlayer::GenericSource::selectTrack(size_t trackIndex, bool select, int64_t timeUs) {
1008     Mutex::Autolock _l(mLock);
1009     ALOGV("%s track: %zu", select ? "select" : "deselect", trackIndex);
1010 
1011     if (trackIndex >= mSources.size()) {
1012         return BAD_INDEX;
1013     }
1014 
1015     if (!select) {
1016         Track* track = NULL;
1017         if (mSubtitleTrack.mSource != NULL && trackIndex == mSubtitleTrack.mIndex) {
1018             track = &mSubtitleTrack;
1019             mFetchSubtitleDataGeneration++;
1020         } else if (mTimedTextTrack.mSource != NULL && trackIndex == mTimedTextTrack.mIndex) {
1021             track = &mTimedTextTrack;
1022             mFetchTimedTextDataGeneration++;
1023         }
1024         if (track == NULL) {
1025             return INVALID_OPERATION;
1026         }
1027         track->mSource->stop();
1028         track->mSource = NULL;
1029         track->mPackets->clear();
1030         return OK;
1031     }
1032 
1033     const sp<IMediaSource> source = mSources.itemAt(trackIndex);
1034     sp<MetaData> meta = source->getFormat();
1035     const char *mime;
1036     CHECK(meta->findCString(kKeyMIMEType, &mime));
1037     if (!strncasecmp(mime, "text/", 5)) {
1038         bool isSubtitle = strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP);
1039         Track *track = isSubtitle ? &mSubtitleTrack : &mTimedTextTrack;
1040         if (track->mSource != NULL && track->mIndex == trackIndex) {
1041             return OK;
1042         }
1043         track->mIndex = trackIndex;
1044         if (track->mSource != NULL) {
1045             track->mSource->stop();
1046         }
1047         track->mSource = mSources.itemAt(trackIndex);
1048         track->mSource->start();
1049         if (track->mPackets == NULL) {
1050             track->mPackets = new AnotherPacketSource(track->mSource->getFormat());
1051         } else {
1052             track->mPackets->clear();
1053             track->mPackets->setFormat(track->mSource->getFormat());
1054 
1055         }
1056 
1057         if (isSubtitle) {
1058             mFetchSubtitleDataGeneration++;
1059         } else {
1060             mFetchTimedTextDataGeneration++;
1061         }
1062 
1063         status_t eosResult; // ignored
1064         if (mSubtitleTrack.mSource != NULL
1065                 && !mSubtitleTrack.mPackets->hasBufferAvailable(&eosResult)) {
1066             sp<AMessage> msg = new AMessage(kWhatFetchSubtitleData, this);
1067             msg->setInt64("timeUs", timeUs);
1068             msg->setInt32("generation", mFetchSubtitleDataGeneration);
1069             msg->post();
1070         }
1071 
1072         sp<AMessage> msg2 = new AMessage(kWhatSendGlobalTimedTextData, this);
1073         msg2->setInt32("generation", mFetchTimedTextDataGeneration);
1074         msg2->post();
1075 
1076         if (mTimedTextTrack.mSource != NULL
1077                 && !mTimedTextTrack.mPackets->hasBufferAvailable(&eosResult)) {
1078             sp<AMessage> msg = new AMessage(kWhatFetchTimedTextData, this);
1079             msg->setInt64("timeUs", timeUs);
1080             msg->setInt32("generation", mFetchTimedTextDataGeneration);
1081             msg->post();
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, this);
1093         msg->setInt32("trackIndex", trackIndex);
1094         msg->post();
1095         return OK;
1096     }
1097 
1098     return INVALID_OPERATION;
1099 }
1100 
seekTo(int64_t seekTimeUs,MediaPlayerSeekMode mode)1101 status_t NuPlayer::GenericSource::seekTo(int64_t seekTimeUs, MediaPlayerSeekMode mode) {
1102     ALOGV("seekTo: %lld, %d", (long long)seekTimeUs, mode);
1103     sp<AMessage> msg = new AMessage(kWhatSeek, this);
1104     msg->setInt64("seekTimeUs", seekTimeUs);
1105     msg->setInt32("mode", mode);
1106 
1107     // Need to call readBuffer on |mLooper| to ensure the calls to
1108     // IMediaSource::read* are serialized. Note that IMediaSource::read*
1109     // is called without |mLock| acquired and MediaSource is not thread safe.
1110     sp<AMessage> response;
1111     status_t err = msg->postAndAwaitResponse(&response);
1112     if (err == OK && response != NULL) {
1113         CHECK(response->findInt32("err", &err));
1114     }
1115 
1116     return err;
1117 }
1118 
onSeek(const sp<AMessage> & msg)1119 void NuPlayer::GenericSource::onSeek(const sp<AMessage>& msg) {
1120     int64_t seekTimeUs;
1121     int32_t mode;
1122     CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
1123     CHECK(msg->findInt32("mode", &mode));
1124 
1125     sp<AMessage> response = new AMessage;
1126     status_t err = doSeek(seekTimeUs, (MediaPlayerSeekMode)mode);
1127     response->setInt32("err", err);
1128 
1129     sp<AReplyToken> replyID;
1130     CHECK(msg->senderAwaitsResponse(&replyID));
1131     response->postReply(replyID);
1132 }
1133 
doSeek(int64_t seekTimeUs,MediaPlayerSeekMode mode)1134 status_t NuPlayer::GenericSource::doSeek(int64_t seekTimeUs, MediaPlayerSeekMode mode) {
1135     if (mVideoTrack.mSource != NULL) {
1136         ++mVideoDataGeneration;
1137 
1138         int64_t actualTimeUs;
1139         readBuffer(MEDIA_TRACK_TYPE_VIDEO, seekTimeUs, mode, &actualTimeUs);
1140 
1141         if (mode != MediaPlayerSeekMode::SEEK_CLOSEST) {
1142             seekTimeUs = actualTimeUs;
1143         }
1144         mVideoLastDequeueTimeUs = actualTimeUs;
1145     }
1146 
1147     if (mAudioTrack.mSource != NULL) {
1148         ++mAudioDataGeneration;
1149         readBuffer(MEDIA_TRACK_TYPE_AUDIO, seekTimeUs, MediaPlayerSeekMode::SEEK_CLOSEST);
1150         mAudioLastDequeueTimeUs = seekTimeUs;
1151     }
1152 
1153     if (mSubtitleTrack.mSource != NULL) {
1154         mSubtitleTrack.mPackets->clear();
1155         mFetchSubtitleDataGeneration++;
1156     }
1157 
1158     if (mTimedTextTrack.mSource != NULL) {
1159         mTimedTextTrack.mPackets->clear();
1160         mFetchTimedTextDataGeneration++;
1161     }
1162 
1163     ++mPollBufferingGeneration;
1164     schedulePollBuffering();
1165     return OK;
1166 }
1167 
mediaBufferToABuffer(MediaBufferBase * mb,media_track_type trackType)1168 sp<ABuffer> NuPlayer::GenericSource::mediaBufferToABuffer(
1169         MediaBufferBase* mb,
1170         media_track_type trackType) {
1171     bool audio = trackType == MEDIA_TRACK_TYPE_AUDIO;
1172     size_t outLength = mb->range_length();
1173 
1174     if (audio && mAudioIsVorbis) {
1175         outLength += sizeof(int32_t);
1176     }
1177 
1178     sp<ABuffer> ab;
1179 
1180     if (mIsDrmProtected)   {
1181         // Modular DRM
1182         // Enabled for both video/audio so 1) media buffer is reused without extra copying
1183         // 2) meta data can be retrieved in onInputBufferFetched for calling queueSecureInputBuffer.
1184 
1185         // data is already provided in the buffer
1186         ab = new ABuffer(NULL, mb->range_length());
1187         ab->meta()->setObject("mediaBufferHolder", new MediaBufferHolder(mb));
1188 
1189         // Modular DRM: Required b/c of the above add_ref.
1190         // If ref>0, there must be an observer, or it'll crash at release().
1191         // TODO: MediaBuffer might need to be revised to ease such need.
1192         mb->setObserver(this);
1193         // Extra increment (since we want to keep mb alive and attached to ab beyond this function
1194         // call. This is to counter the effect of mb->release() towards the end.
1195         mb->add_ref();
1196 
1197     } else {
1198         ab = new ABuffer(outLength);
1199         memcpy(ab->data(),
1200                (const uint8_t *)mb->data() + mb->range_offset(),
1201                mb->range_length());
1202     }
1203 
1204     if (audio && mAudioIsVorbis) {
1205         int32_t numPageSamples;
1206         if (!mb->meta_data().findInt32(kKeyValidSamples, &numPageSamples)) {
1207             numPageSamples = -1;
1208         }
1209 
1210         uint8_t* abEnd = ab->data() + mb->range_length();
1211         memcpy(abEnd, &numPageSamples, sizeof(numPageSamples));
1212     }
1213 
1214     sp<AMessage> meta = ab->meta();
1215 
1216     int64_t timeUs;
1217     CHECK(mb->meta_data().findInt64(kKeyTime, &timeUs));
1218     meta->setInt64("timeUs", timeUs);
1219 
1220     if (trackType == MEDIA_TRACK_TYPE_VIDEO) {
1221         int32_t layerId;
1222         if (mb->meta_data().findInt32(kKeyTemporalLayerId, &layerId)) {
1223             meta->setInt32("temporal-layer-id", layerId);
1224         }
1225     }
1226 
1227     if (trackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1228         const char *mime;
1229         CHECK(mTimedTextTrack.mSource != NULL
1230                 && mTimedTextTrack.mSource->getFormat()->findCString(kKeyMIMEType, &mime));
1231         meta->setString("mime", mime);
1232     }
1233 
1234     int64_t durationUs;
1235     if (mb->meta_data().findInt64(kKeyDuration, &durationUs)) {
1236         meta->setInt64("durationUs", durationUs);
1237     }
1238 
1239     if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
1240         meta->setInt32("track-index", mSubtitleTrack.mIndex);
1241     }
1242 
1243     uint32_t dataType; // unused
1244     const void *seiData;
1245     size_t seiLength;
1246     if (mb->meta_data().findData(kKeySEI, &dataType, &seiData, &seiLength)) {
1247         sp<ABuffer> sei = ABuffer::CreateAsCopy(seiData, seiLength);;
1248         meta->setBuffer("sei", sei);
1249     }
1250 
1251     const void *mpegUserDataPointer;
1252     size_t mpegUserDataLength;
1253     if (mb->meta_data().findData(
1254             kKeyMpegUserData, &dataType, &mpegUserDataPointer, &mpegUserDataLength)) {
1255         sp<ABuffer> mpegUserData = ABuffer::CreateAsCopy(mpegUserDataPointer, mpegUserDataLength);
1256         meta->setBuffer("mpeg-user-data", mpegUserData);
1257     }
1258 
1259     mb->release();
1260     mb = NULL;
1261 
1262     return ab;
1263 }
1264 
getDataGeneration(media_track_type type) const1265 int32_t NuPlayer::GenericSource::getDataGeneration(media_track_type type) const {
1266     int32_t generation = -1;
1267     switch (type) {
1268     case MEDIA_TRACK_TYPE_VIDEO:
1269         generation = mVideoDataGeneration;
1270         break;
1271     case MEDIA_TRACK_TYPE_AUDIO:
1272         generation = mAudioDataGeneration;
1273         break;
1274     case MEDIA_TRACK_TYPE_TIMEDTEXT:
1275         generation = mFetchTimedTextDataGeneration;
1276         break;
1277     case MEDIA_TRACK_TYPE_SUBTITLE:
1278         generation = mFetchSubtitleDataGeneration;
1279         break;
1280     default:
1281         break;
1282     }
1283 
1284     return generation;
1285 }
1286 
postReadBuffer(media_track_type trackType)1287 void NuPlayer::GenericSource::postReadBuffer(media_track_type trackType) {
1288     if ((mPendingReadBufferTypes & (1 << trackType)) == 0) {
1289         mPendingReadBufferTypes |= (1 << trackType);
1290         sp<AMessage> msg = new AMessage(kWhatReadBuffer, this);
1291         msg->setInt32("trackType", trackType);
1292         msg->post();
1293     }
1294 }
1295 
onReadBuffer(const sp<AMessage> & msg)1296 void NuPlayer::GenericSource::onReadBuffer(const sp<AMessage>& msg) {
1297     int32_t tmpType;
1298     CHECK(msg->findInt32("trackType", &tmpType));
1299     media_track_type trackType = (media_track_type)tmpType;
1300     mPendingReadBufferTypes &= ~(1 << trackType);
1301     readBuffer(trackType);
1302 }
1303 
readBuffer(media_track_type trackType,int64_t seekTimeUs,MediaPlayerSeekMode mode,int64_t * actualTimeUs,bool formatChange)1304 void NuPlayer::GenericSource::readBuffer(
1305         media_track_type trackType, int64_t seekTimeUs, MediaPlayerSeekMode mode,
1306         int64_t *actualTimeUs, bool formatChange) {
1307     Track *track;
1308     size_t maxBuffers = 1;
1309     switch (trackType) {
1310         case MEDIA_TRACK_TYPE_VIDEO:
1311             track = &mVideoTrack;
1312             maxBuffers = 8;  // too large of a number may influence seeks
1313             break;
1314         case MEDIA_TRACK_TYPE_AUDIO:
1315             track = &mAudioTrack;
1316             maxBuffers = 64;
1317             break;
1318         case MEDIA_TRACK_TYPE_SUBTITLE:
1319             track = &mSubtitleTrack;
1320             break;
1321         case MEDIA_TRACK_TYPE_TIMEDTEXT:
1322             track = &mTimedTextTrack;
1323             break;
1324         default:
1325             TRESPASS();
1326     }
1327 
1328     if (track->mSource == NULL) {
1329         return;
1330     }
1331 
1332     if (actualTimeUs) {
1333         *actualTimeUs = seekTimeUs;
1334     }
1335 
1336     MediaSource::ReadOptions options;
1337 
1338     bool seeking = false;
1339     if (seekTimeUs >= 0) {
1340         options.setSeekTo(seekTimeUs, mode);
1341         seeking = true;
1342     }
1343 
1344     const bool couldReadMultiple = (track->mSource->supportReadMultiple());
1345 
1346     if (couldReadMultiple) {
1347         options.setNonBlocking();
1348     }
1349 
1350     int32_t generation = getDataGeneration(trackType);
1351     for (size_t numBuffers = 0; numBuffers < maxBuffers; ) {
1352         Vector<MediaBufferBase *> mediaBuffers;
1353         status_t err = NO_ERROR;
1354 
1355         sp<IMediaSource> source = track->mSource;
1356         mLock.unlock();
1357         if (couldReadMultiple) {
1358             err = source->readMultiple(
1359                     &mediaBuffers, maxBuffers - numBuffers, &options);
1360         } else {
1361             MediaBufferBase *mbuf = NULL;
1362             err = source->read(&mbuf, &options);
1363             if (err == OK && mbuf != NULL) {
1364                 mediaBuffers.push_back(mbuf);
1365             }
1366         }
1367         mLock.lock();
1368 
1369         options.clearNonPersistent();
1370 
1371         size_t id = 0;
1372         size_t count = mediaBuffers.size();
1373 
1374         // in case track has been changed since we don't have lock for some time.
1375         if (generation != getDataGeneration(trackType)) {
1376             for (; id < count; ++id) {
1377                 mediaBuffers[id]->release();
1378             }
1379             break;
1380         }
1381 
1382         for (; id < count; ++id) {
1383             int64_t timeUs;
1384             MediaBufferBase *mbuf = mediaBuffers[id];
1385             if (!mbuf->meta_data().findInt64(kKeyTime, &timeUs)) {
1386                 mbuf->meta_data().dumpToLog();
1387                 track->mPackets->signalEOS(ERROR_MALFORMED);
1388                 break;
1389             }
1390             if (trackType == MEDIA_TRACK_TYPE_AUDIO) {
1391                 mAudioTimeUs = timeUs;
1392             } else if (trackType == MEDIA_TRACK_TYPE_VIDEO) {
1393                 mVideoTimeUs = timeUs;
1394             }
1395 
1396             queueDiscontinuityIfNeeded(seeking, formatChange, trackType, track);
1397 
1398             sp<ABuffer> buffer = mediaBufferToABuffer(mbuf, trackType);
1399             if (numBuffers == 0 && actualTimeUs != nullptr) {
1400                 *actualTimeUs = timeUs;
1401             }
1402             if (seeking && buffer != nullptr) {
1403                 sp<AMessage> meta = buffer->meta();
1404                 if (meta != nullptr && mode == MediaPlayerSeekMode::SEEK_CLOSEST
1405                         && seekTimeUs > timeUs) {
1406                     sp<AMessage> extra = new AMessage;
1407                     extra->setInt64("resume-at-mediaTimeUs", seekTimeUs);
1408                     meta->setMessage("extra", extra);
1409                 }
1410             }
1411 
1412             track->mPackets->queueAccessUnit(buffer);
1413             formatChange = false;
1414             seeking = false;
1415             ++numBuffers;
1416         }
1417         if (id < count) {
1418             // Error, some mediaBuffer doesn't have kKeyTime.
1419             for (; id < count; ++id) {
1420                 mediaBuffers[id]->release();
1421             }
1422             break;
1423         }
1424 
1425         if (err == WOULD_BLOCK) {
1426             break;
1427         } else if (err == INFO_FORMAT_CHANGED) {
1428 #if 0
1429             track->mPackets->queueDiscontinuity(
1430                     ATSParser::DISCONTINUITY_FORMATCHANGE,
1431                     NULL,
1432                     false /* discard */);
1433 #endif
1434         } else if (err != OK) {
1435             queueDiscontinuityIfNeeded(seeking, formatChange, trackType, track);
1436             track->mPackets->signalEOS(err);
1437             break;
1438         }
1439     }
1440 
1441     if (mIsStreaming
1442         && (trackType == MEDIA_TRACK_TYPE_VIDEO || trackType == MEDIA_TRACK_TYPE_AUDIO)) {
1443         status_t finalResult;
1444         int64_t durationUs = track->mPackets->getBufferedDurationUs(&finalResult);
1445 
1446         // TODO: maxRebufferingMarkMs could be larger than
1447         // mBufferingSettings.mResumePlaybackMarkMs
1448         int64_t markUs = (mPreparing ? mBufferingSettings.mInitialMarkMs
1449             : mBufferingSettings.mResumePlaybackMarkMs) * 1000ll;
1450         if (finalResult == ERROR_END_OF_STREAM || durationUs >= markUs) {
1451             if (mPreparing || mSentPauseOnBuffering) {
1452                 Track *counterTrack =
1453                     (trackType == MEDIA_TRACK_TYPE_VIDEO ? &mAudioTrack : &mVideoTrack);
1454                 if (counterTrack->mSource != NULL) {
1455                     durationUs = counterTrack->mPackets->getBufferedDurationUs(&finalResult);
1456                 }
1457                 if (finalResult == ERROR_END_OF_STREAM || durationUs >= markUs) {
1458                     if (mPreparing) {
1459                         notifyPrepared();
1460                         mPreparing = false;
1461                     } else {
1462                         sendCacheStats();
1463                         mSentPauseOnBuffering = false;
1464                         sp<AMessage> notify = dupNotify();
1465                         notify->setInt32("what", kWhatResumeOnBufferingEnd);
1466                         notify->post();
1467                     }
1468                 }
1469             }
1470             return;
1471         }
1472 
1473         postReadBuffer(trackType);
1474     }
1475 }
1476 
queueDiscontinuityIfNeeded(bool seeking,bool formatChange,media_track_type trackType,Track * track)1477 void NuPlayer::GenericSource::queueDiscontinuityIfNeeded(
1478         bool seeking, bool formatChange, media_track_type trackType, Track *track) {
1479     // formatChange && seeking: track whose source is changed during selection
1480     // formatChange && !seeking: track whose source is not changed during selection
1481     // !formatChange: normal seek
1482     if ((seeking || formatChange)
1483             && (trackType == MEDIA_TRACK_TYPE_AUDIO
1484             || trackType == MEDIA_TRACK_TYPE_VIDEO)) {
1485         ATSParser::DiscontinuityType type = (formatChange && seeking)
1486                 ? ATSParser::DISCONTINUITY_FORMATCHANGE
1487                 : ATSParser::DISCONTINUITY_NONE;
1488         track->mPackets->queueDiscontinuity(type, NULL /* extra */, true /* discard */);
1489     }
1490 }
1491 
notifyBufferingUpdate(int32_t percentage)1492 void NuPlayer::GenericSource::notifyBufferingUpdate(int32_t percentage) {
1493     // Buffering percent could go backward as it's estimated from remaining
1494     // data and last access time. This could cause the buffering position
1495     // drawn on media control to jitter slightly. Remember previously reported
1496     // percentage and don't allow it to go backward.
1497     if (percentage < mPrevBufferPercentage) {
1498         percentage = mPrevBufferPercentage;
1499     } else if (percentage > 100) {
1500         percentage = 100;
1501     }
1502 
1503     mPrevBufferPercentage = percentage;
1504 
1505     ALOGV("notifyBufferingUpdate: buffering %d%%", percentage);
1506 
1507     sp<AMessage> notify = dupNotify();
1508     notify->setInt32("what", kWhatBufferingUpdate);
1509     notify->setInt32("percentage", percentage);
1510     notify->post();
1511 }
1512 
schedulePollBuffering()1513 void NuPlayer::GenericSource::schedulePollBuffering() {
1514     sp<AMessage> msg = new AMessage(kWhatPollBuffering, this);
1515     msg->setInt32("generation", mPollBufferingGeneration);
1516     // Enquires buffering status every second.
1517     msg->post(1000000ll);
1518 }
1519 
onPollBuffering()1520 void NuPlayer::GenericSource::onPollBuffering() {
1521     status_t finalStatus = UNKNOWN_ERROR;
1522     int64_t cachedDurationUs = -1ll;
1523     ssize_t cachedDataRemaining = -1;
1524 
1525     if (mCachedSource != NULL) {
1526         cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus);
1527 
1528         if (finalStatus == OK) {
1529             off64_t size;
1530             int64_t bitrate = 0ll;
1531             if (mDurationUs > 0 && mCachedSource->getSize(&size) == OK) {
1532                 // |bitrate| uses bits/second unit, while size is number of bytes.
1533                 bitrate = size * 8000000ll / mDurationUs;
1534             } else if (mBitrate > 0) {
1535                 bitrate = mBitrate;
1536             }
1537             if (bitrate > 0) {
1538                 cachedDurationUs = cachedDataRemaining * 8000000ll / bitrate;
1539             }
1540         }
1541     }
1542 
1543     if (finalStatus != OK) {
1544         ALOGV("onPollBuffering: EOS (finalStatus = %d)", finalStatus);
1545 
1546         if (finalStatus == ERROR_END_OF_STREAM) {
1547             notifyBufferingUpdate(100);
1548         }
1549 
1550         return;
1551     }
1552 
1553     if (cachedDurationUs >= 0ll) {
1554         if (mDurationUs > 0ll) {
1555             int64_t cachedPosUs = getLastReadPosition() + cachedDurationUs;
1556             int percentage = 100.0 * cachedPosUs / mDurationUs;
1557             if (percentage > 100) {
1558                 percentage = 100;
1559             }
1560 
1561             notifyBufferingUpdate(percentage);
1562         }
1563 
1564         ALOGV("onPollBuffering: cachedDurationUs %.1f sec", cachedDurationUs / 1000000.0f);
1565     }
1566 
1567     schedulePollBuffering();
1568 }
1569 
1570 // Modular DRM
prepareDrm(const uint8_t uuid[16],const Vector<uint8_t> & drmSessionId,sp<ICrypto> * outCrypto)1571 status_t NuPlayer::GenericSource::prepareDrm(
1572         const uint8_t uuid[16], const Vector<uint8_t> &drmSessionId, sp<ICrypto> *outCrypto) {
1573     Mutex::Autolock _l(mLock);
1574     ALOGV("prepareDrm");
1575 
1576     mIsDrmProtected = false;
1577     mIsDrmReleased = false;
1578     mIsSecure = false;
1579 
1580     status_t status = OK;
1581     sp<ICrypto> crypto = NuPlayerDrm::createCryptoAndPlugin(uuid, drmSessionId, status);
1582     if (crypto == NULL) {
1583         ALOGE("prepareDrm: createCrypto failed. status: %d", status);
1584         return status;
1585     }
1586     ALOGV("prepareDrm: createCryptoAndPlugin succeeded for uuid: %s",
1587             DrmUUID::toHexString(uuid).string());
1588 
1589     *outCrypto = crypto;
1590     // as long a there is an active crypto
1591     mIsDrmProtected = true;
1592 
1593     if (mMimes.size() == 0) {
1594         status = UNKNOWN_ERROR;
1595         ALOGE("prepareDrm: Unexpected. Must have at least one track. status: %d", status);
1596         return status;
1597     }
1598 
1599     // first mime in this list is either the video track, or the first audio track
1600     const char *mime = mMimes[0].string();
1601     mIsSecure = crypto->requiresSecureDecoderComponent(mime);
1602     ALOGV("prepareDrm: requiresSecureDecoderComponent mime: %s  isSecure: %d",
1603             mime, mIsSecure);
1604 
1605     // Checking the member flags while in the looper to send out the notification.
1606     // The legacy mDecryptHandle!=NULL check (for FLAG_PROTECTED) is equivalent to mIsDrmProtected.
1607     notifyFlagsChanged(
1608             (mIsSecure ? FLAG_SECURE : 0) |
1609             // Setting "protected screen" only for L1: b/38390836
1610             (mIsSecure ? FLAG_PROTECTED : 0) |
1611             FLAG_CAN_PAUSE |
1612             FLAG_CAN_SEEK_BACKWARD |
1613             FLAG_CAN_SEEK_FORWARD |
1614             FLAG_CAN_SEEK);
1615 
1616     if (status == OK) {
1617         ALOGV("prepareDrm: mCrypto: %p (%d)", outCrypto->get(),
1618                 (*outCrypto != NULL ? (*outCrypto)->getStrongCount() : 0));
1619         ALOGD("prepareDrm ret: %d ", status);
1620     } else {
1621         ALOGE("prepareDrm err: %d", status);
1622     }
1623     return status;
1624 }
1625 
releaseDrm()1626 status_t NuPlayer::GenericSource::releaseDrm() {
1627     Mutex::Autolock _l(mLock);
1628     ALOGV("releaseDrm");
1629 
1630     if (mIsDrmProtected) {
1631         mIsDrmProtected = false;
1632         // to prevent returning any more buffer after stop/releaseDrm (b/37960096)
1633         mIsDrmReleased = true;
1634         ALOGV("releaseDrm: mIsDrmProtected is reset.");
1635     } else {
1636         ALOGE("releaseDrm: mIsDrmProtected is already false.");
1637     }
1638 
1639     return OK;
1640 }
1641 
checkDrmInfo()1642 status_t NuPlayer::GenericSource::checkDrmInfo()
1643 {
1644     // clearing the flag at prepare in case the player is reused after stop/releaseDrm with the
1645     // same source without being reset (called by prepareAsync/initFromDataSource)
1646     mIsDrmReleased = false;
1647 
1648     if (mFileMeta == NULL) {
1649         ALOGI("checkDrmInfo: No metadata");
1650         return OK; // letting the caller responds accordingly
1651     }
1652 
1653     uint32_t type;
1654     const void *pssh;
1655     size_t psshsize;
1656 
1657     if (!mFileMeta->findData(kKeyPssh, &type, &pssh, &psshsize)) {
1658         ALOGV("checkDrmInfo: No PSSH");
1659         return OK; // source without DRM info
1660     }
1661 
1662     Parcel parcel;
1663     NuPlayerDrm::retrieveDrmInfo(pssh, psshsize, &parcel);
1664     ALOGV("checkDrmInfo: MEDIA_DRM_INFO PSSH size: %d  Parcel size: %d  objects#: %d",
1665           (int)psshsize, (int)parcel.dataSize(), (int)parcel.objectsCount());
1666 
1667     if (parcel.dataSize() == 0) {
1668         ALOGE("checkDrmInfo: Unexpected parcel size: 0");
1669         return UNKNOWN_ERROR;
1670     }
1671 
1672     // Can't pass parcel as a message to the player. Converting Parcel->ABuffer to pass it
1673     // to the Player's onSourceNotify then back to Parcel for calling driver's notifyListener.
1674     sp<ABuffer> drmInfoBuffer = ABuffer::CreateAsCopy(parcel.data(), parcel.dataSize());
1675     notifyDrmInfo(drmInfoBuffer);
1676 
1677     return OK;
1678 }
1679 
signalBufferReturned(MediaBufferBase * buffer)1680 void NuPlayer::GenericSource::signalBufferReturned(MediaBufferBase *buffer)
1681 {
1682     //ALOGV("signalBufferReturned %p  refCount: %d", buffer, buffer->localRefcount());
1683 
1684     buffer->setObserver(NULL);
1685     buffer->release(); // this leads to delete since that there is no observor
1686 }
1687 
1688 }  // namespace android
1689