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