blob: 35e20e8d111eb36c5e5409d5a57978009aad6027 [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
18#define LOG_TAG "NuPlayer2"
19
20#include <inttypes.h>
21
22#include <utils/Log.h>
23
24#include "NuPlayer2.h"
25
26#include "HTTPLiveSource.h"
Wei Jia53692fa2017-12-11 10:33:46 -080027#include "NuPlayer2CCDecoder.h"
28#include "NuPlayer2Decoder.h"
29#include "NuPlayer2DecoderBase.h"
30#include "NuPlayer2DecoderPassThrough.h"
31#include "NuPlayer2Driver.h"
32#include "NuPlayer2Renderer.h"
33#include "NuPlayer2Source.h"
34#include "RTSPSource.h"
35#include "StreamingSource.h"
36#include "GenericSource.h"
37#include "TextDescriptions.h"
38
39#include "ATSParser.h"
40
41#include <cutils/properties.h>
42
43#include <media/AudioParameter.h>
44#include <media/AudioResamplerPublic.h>
45#include <media/AVSyncSettings.h>
Wei Jiac2636032018-02-01 09:15:25 -080046#include <media/DataSourceDesc.h>
Wei Jia53692fa2017-12-11 10:33:46 -080047#include <media/MediaCodecBuffer.h>
Wei Jia28288fb2017-12-15 13:45:29 -080048#include <media/NdkWrapper.h>
Wei Jia53692fa2017-12-11 10:33:46 -080049
50#include <media/stagefright/foundation/hexdump.h>
51#include <media/stagefright/foundation/ABuffer.h>
52#include <media/stagefright/foundation/ADebug.h>
53#include <media/stagefright/foundation/AMessage.h>
54#include <media/stagefright/foundation/avc_utils.h>
55#include <media/stagefright/MediaBuffer.h>
56#include <media/stagefright/MediaClock.h>
57#include <media/stagefright/MediaDefs.h>
58#include <media/stagefright/MediaErrors.h>
59#include <media/stagefright/MetaData.h>
60
Wei Jia53692fa2017-12-11 10:33:46 -080061#include "ESDS.h"
62#include <media/stagefright/Utils.h>
63
Wei Jia28288fb2017-12-15 13:45:29 -080064#include <system/window.h>
65
Wei Jia53692fa2017-12-11 10:33:46 -080066namespace android {
67
Wei Jia33abcc72018-01-30 09:47:38 -080068static status_t sendMetaDataToHal(sp<MediaPlayer2Interface::AudioSink>& sink,
Wei Jia53692fa2017-12-11 10:33:46 -080069 const sp<MetaData>& meta) {
70 int32_t sampleRate = 0;
71 int32_t bitRate = 0;
72 int32_t channelMask = 0;
73 int32_t delaySamples = 0;
74 int32_t paddingSamples = 0;
75
76 AudioParameter param = AudioParameter();
77
78 if (meta->findInt32(kKeySampleRate, &sampleRate)) {
79 param.addInt(String8(AUDIO_OFFLOAD_CODEC_SAMPLE_RATE), sampleRate);
80 }
81 if (meta->findInt32(kKeyChannelMask, &channelMask)) {
82 param.addInt(String8(AUDIO_OFFLOAD_CODEC_NUM_CHANNEL), channelMask);
83 }
84 if (meta->findInt32(kKeyBitRate, &bitRate)) {
85 param.addInt(String8(AUDIO_OFFLOAD_CODEC_AVG_BIT_RATE), bitRate);
86 }
87 if (meta->findInt32(kKeyEncoderDelay, &delaySamples)) {
88 param.addInt(String8(AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES), delaySamples);
89 }
90 if (meta->findInt32(kKeyEncoderPadding, &paddingSamples)) {
91 param.addInt(String8(AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES), paddingSamples);
92 }
93
94 ALOGV("sendMetaDataToHal: bitRate %d, sampleRate %d, chanMask %d,"
95 "delaySample %d, paddingSample %d", bitRate, sampleRate,
96 channelMask, delaySamples, paddingSamples);
97
98 sink->setParameters(param.toString());
99 return OK;
100}
101
102
103struct NuPlayer2::Action : public RefBase {
104 Action() {}
105
106 virtual void execute(NuPlayer2 *player) = 0;
107
108private:
109 DISALLOW_EVIL_CONSTRUCTORS(Action);
110};
111
112struct NuPlayer2::SeekAction : public Action {
113 explicit SeekAction(int64_t seekTimeUs, MediaPlayer2SeekMode mode)
114 : mSeekTimeUs(seekTimeUs),
115 mMode(mode) {
116 }
117
118 virtual void execute(NuPlayer2 *player) {
119 player->performSeek(mSeekTimeUs, mMode);
120 }
121
122private:
123 int64_t mSeekTimeUs;
124 MediaPlayer2SeekMode mMode;
125
126 DISALLOW_EVIL_CONSTRUCTORS(SeekAction);
127};
128
129struct NuPlayer2::ResumeDecoderAction : public Action {
130 explicit ResumeDecoderAction(bool needNotify)
131 : mNeedNotify(needNotify) {
132 }
133
134 virtual void execute(NuPlayer2 *player) {
135 player->performResumeDecoders(mNeedNotify);
136 }
137
138private:
139 bool mNeedNotify;
140
141 DISALLOW_EVIL_CONSTRUCTORS(ResumeDecoderAction);
142};
143
144struct NuPlayer2::SetSurfaceAction : public Action {
Wei Jia28288fb2017-12-15 13:45:29 -0800145 explicit SetSurfaceAction(const sp<ANativeWindowWrapper> &nww)
146 : mNativeWindow(nww) {
Wei Jia53692fa2017-12-11 10:33:46 -0800147 }
148
149 virtual void execute(NuPlayer2 *player) {
Wei Jia28288fb2017-12-15 13:45:29 -0800150 player->performSetSurface(mNativeWindow);
Wei Jia53692fa2017-12-11 10:33:46 -0800151 }
152
153private:
Wei Jia28288fb2017-12-15 13:45:29 -0800154 sp<ANativeWindowWrapper> mNativeWindow;
Wei Jia53692fa2017-12-11 10:33:46 -0800155
156 DISALLOW_EVIL_CONSTRUCTORS(SetSurfaceAction);
157};
158
159struct NuPlayer2::FlushDecoderAction : public Action {
160 FlushDecoderAction(FlushCommand audio, FlushCommand video)
161 : mAudio(audio),
162 mVideo(video) {
163 }
164
165 virtual void execute(NuPlayer2 *player) {
166 player->performDecoderFlush(mAudio, mVideo);
167 }
168
169private:
170 FlushCommand mAudio;
171 FlushCommand mVideo;
172
173 DISALLOW_EVIL_CONSTRUCTORS(FlushDecoderAction);
174};
175
176struct NuPlayer2::PostMessageAction : public Action {
177 explicit PostMessageAction(const sp<AMessage> &msg)
178 : mMessage(msg) {
179 }
180
181 virtual void execute(NuPlayer2 *) {
182 mMessage->post();
183 }
184
185private:
186 sp<AMessage> mMessage;
187
188 DISALLOW_EVIL_CONSTRUCTORS(PostMessageAction);
189};
190
191// Use this if there's no state necessary to save in order to execute
192// the action.
193struct NuPlayer2::SimpleAction : public Action {
194 typedef void (NuPlayer2::*ActionFunc)();
195
196 explicit SimpleAction(ActionFunc func)
197 : mFunc(func) {
198 }
199
200 virtual void execute(NuPlayer2 *player) {
201 (player->*mFunc)();
202 }
203
204private:
205 ActionFunc mFunc;
206
207 DISALLOW_EVIL_CONSTRUCTORS(SimpleAction);
208};
209
210////////////////////////////////////////////////////////////////////////////////
211
212NuPlayer2::NuPlayer2(pid_t pid, const sp<MediaClock> &mediaClock)
213 : mUIDValid(false),
214 mPID(pid),
215 mMediaClock(mediaClock),
216 mSourceFlags(0),
217 mOffloadAudio(false),
218 mAudioDecoderGeneration(0),
219 mVideoDecoderGeneration(0),
220 mRendererGeneration(0),
221 mLastStartedPlayingTimeNs(0),
222 mPreviousSeekTimeUs(0),
223 mAudioEOS(false),
224 mVideoEOS(false),
225 mScanSourcesPending(false),
226 mScanSourcesGeneration(0),
227 mPollDurationGeneration(0),
228 mTimedTextGeneration(0),
229 mFlushingAudio(NONE),
230 mFlushingVideo(NONE),
231 mResumePending(false),
232 mVideoScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW),
233 mPlaybackSettings(AUDIO_PLAYBACK_RATE_DEFAULT),
234 mVideoFpsHint(-1.f),
235 mStarted(false),
236 mPrepared(false),
237 mResetting(false),
238 mSourceStarted(false),
239 mAudioDecoderError(false),
240 mVideoDecoderError(false),
241 mPaused(false),
242 mPausedByClient(true),
243 mPausedForBuffering(false),
244 mIsDrmProtected(false),
245 mDataSourceType(DATA_SOURCE_TYPE_NONE) {
246 CHECK(mediaClock != NULL);
247 clearFlushComplete();
248}
249
250NuPlayer2::~NuPlayer2() {
251}
252
253void NuPlayer2::setUID(uid_t uid) {
254 mUIDValid = true;
255 mUID = uid;
256}
257
258void NuPlayer2::setDriver(const wp<NuPlayer2Driver> &driver) {
259 mDriver = driver;
260}
261
Wei Jia53692fa2017-12-11 10:33:46 -0800262static bool IsHTTPLiveURL(const char *url) {
263 if (!strncasecmp("http://", url, 7)
264 || !strncasecmp("https://", url, 8)
265 || !strncasecmp("file://", url, 7)) {
266 size_t len = strlen(url);
267 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
268 return true;
269 }
270
271 if (strstr(url,"m3u8")) {
272 return true;
273 }
274 }
275
276 return false;
277}
278
Wei Jiac2636032018-02-01 09:15:25 -0800279void NuPlayer2::setDataSourceAsync(const sp<DataSourceDesc> &dsd) {
Wei Jia53692fa2017-12-11 10:33:46 -0800280 sp<AMessage> msg = new AMessage(kWhatSetDataSource, this);
Wei Jia53692fa2017-12-11 10:33:46 -0800281 sp<AMessage> notify = new AMessage(kWhatSourceNotify, this);
Wei Jia53692fa2017-12-11 10:33:46 -0800282 sp<Source> source;
Wei Jia53692fa2017-12-11 10:33:46 -0800283
Wei Jiac2636032018-02-01 09:15:25 -0800284 switch (dsd->mType) {
285 case DataSourceDesc::TYPE_URL:
286 {
287 const char *url = dsd->mUrl.c_str();
288 size_t len = strlen(url);
Wei Jia53692fa2017-12-11 10:33:46 -0800289
Wei Jiac2636032018-02-01 09:15:25 -0800290 const sp<MediaHTTPService> &httpService = dsd->mHttpService;
291 KeyedVector<String8, String8> *headers = &(dsd->mHeaders);
Wei Jia53692fa2017-12-11 10:33:46 -0800292
Wei Jiac2636032018-02-01 09:15:25 -0800293 if (IsHTTPLiveURL(url)) {
294 source = new HTTPLiveSource(notify, httpService, url, headers);
295 ALOGV("setDataSourceAsync HTTPLiveSource %s", url);
296 mDataSourceType = DATA_SOURCE_TYPE_HTTP_LIVE;
297 } else if (!strncasecmp(url, "rtsp://", 7)) {
298 source = new RTSPSource(
299 notify, httpService, url, headers, mUIDValid, mUID);
300 ALOGV("setDataSourceAsync RTSPSource %s", url);
301 mDataSourceType = DATA_SOURCE_TYPE_RTSP;
302 } else if ((!strncasecmp(url, "http://", 7)
303 || !strncasecmp(url, "https://", 8))
304 && ((len >= 4 && !strcasecmp(".sdp", &url[len - 4]))
305 || strstr(url, ".sdp?"))) {
306 source = new RTSPSource(
307 notify, httpService, url, headers, mUIDValid, mUID, true);
308 ALOGV("setDataSourceAsync RTSPSource http/https/.sdp %s", url);
309 mDataSourceType = DATA_SOURCE_TYPE_RTSP;
310 } else {
311 ALOGV("setDataSourceAsync GenericSource %s", url);
312
313 sp<GenericSource> genericSource =
314 new GenericSource(notify, mUIDValid, mUID, mMediaClock);
315
316 status_t err = genericSource->setDataSource(httpService, url, headers);
317
318 if (err == OK) {
319 source = genericSource;
320 } else {
321 ALOGE("Failed to set data source!");
322 }
323
324 // regardless of success/failure
325 mDataSourceType = DATA_SOURCE_TYPE_GENERIC_URL;
326 }
327 break;
Wei Jia53692fa2017-12-11 10:33:46 -0800328 }
329
Wei Jiac2636032018-02-01 09:15:25 -0800330 case DataSourceDesc::TYPE_FD:
331 {
332 sp<GenericSource> genericSource =
333 new GenericSource(notify, mUIDValid, mUID, mMediaClock);
Wei Jia53692fa2017-12-11 10:33:46 -0800334
Wei Jiac2636032018-02-01 09:15:25 -0800335 ALOGV("setDataSourceAsync fd %d/%lld/%lld source: %p",
336 dsd->mFD, (long long)dsd->mFDOffset, (long long)dsd->mFDLength, source.get());
Wei Jia53692fa2017-12-11 10:33:46 -0800337
Wei Jiac2636032018-02-01 09:15:25 -0800338 status_t err = genericSource->setDataSource(dsd->mFD, dsd->mFDOffset, dsd->mFDLength);
Wei Jia53692fa2017-12-11 10:33:46 -0800339
Wei Jiac2636032018-02-01 09:15:25 -0800340 if (err != OK) {
341 ALOGE("Failed to set data source!");
342 source = NULL;
343 } else {
344 source = genericSource;
345 }
Wei Jia53692fa2017-12-11 10:33:46 -0800346
Wei Jiac2636032018-02-01 09:15:25 -0800347 mDataSourceType = DATA_SOURCE_TYPE_GENERIC_FD;
348 break;
349 }
Wei Jia53692fa2017-12-11 10:33:46 -0800350
Wei Jiac2636032018-02-01 09:15:25 -0800351 case DataSourceDesc::TYPE_CALLBACK:
352 {
353 sp<GenericSource> genericSource =
354 new GenericSource(notify, mUIDValid, mUID, mMediaClock);
355 status_t err = genericSource->setDataSource(dsd->mCallbackSource);
Wei Jia53692fa2017-12-11 10:33:46 -0800356
Wei Jiac2636032018-02-01 09:15:25 -0800357 if (err != OK) {
358 ALOGE("Failed to set data source!");
359 source = NULL;
360 } else {
361 source = genericSource;
362 }
363
364 mDataSourceType = DATA_SOURCE_TYPE_MEDIA;
365 break;
366 }
367
368 default:
369 ALOGE("invalid data source type!");
370 break;
Wei Jia53692fa2017-12-11 10:33:46 -0800371 }
372
373 msg->setObject("source", source);
374 msg->post();
Wei Jia53692fa2017-12-11 10:33:46 -0800375}
376
377status_t NuPlayer2::getBufferingSettings(
378 BufferingSettings *buffering /* nonnull */) {
379 sp<AMessage> msg = new AMessage(kWhatGetBufferingSettings, this);
380 sp<AMessage> response;
381 status_t err = msg->postAndAwaitResponse(&response);
382 if (err == OK && response != NULL) {
383 CHECK(response->findInt32("err", &err));
384 if (err == OK) {
385 readFromAMessage(response, buffering);
386 }
387 }
388 return err;
389}
390
391status_t NuPlayer2::setBufferingSettings(const BufferingSettings& buffering) {
392 sp<AMessage> msg = new AMessage(kWhatSetBufferingSettings, this);
393 writeToAMessage(msg, buffering);
394 sp<AMessage> response;
395 status_t err = msg->postAndAwaitResponse(&response);
396 if (err == OK && response != NULL) {
397 CHECK(response->findInt32("err", &err));
398 }
399 return err;
400}
401
402void NuPlayer2::prepareAsync() {
403 ALOGV("prepareAsync");
404
405 (new AMessage(kWhatPrepare, this))->post();
406}
407
Wei Jia28288fb2017-12-15 13:45:29 -0800408void NuPlayer2::setVideoSurfaceTextureAsync(const sp<ANativeWindowWrapper> &nww) {
Wei Jia53692fa2017-12-11 10:33:46 -0800409 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
410
Wei Jia28288fb2017-12-15 13:45:29 -0800411 if (nww == NULL || nww->getANativeWindow() == NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -0800412 msg->setObject("surface", NULL);
413 } else {
Wei Jia28288fb2017-12-15 13:45:29 -0800414 msg->setObject("surface", nww);
Wei Jia53692fa2017-12-11 10:33:46 -0800415 }
416
417 msg->post();
418}
419
Wei Jia33abcc72018-01-30 09:47:38 -0800420void NuPlayer2::setAudioSink(const sp<MediaPlayer2Interface::AudioSink> &sink) {
Wei Jia53692fa2017-12-11 10:33:46 -0800421 sp<AMessage> msg = new AMessage(kWhatSetAudioSink, this);
422 msg->setObject("sink", sink);
423 msg->post();
424}
425
426void NuPlayer2::start() {
427 (new AMessage(kWhatStart, this))->post();
428}
429
430status_t NuPlayer2::setPlaybackSettings(const AudioPlaybackRate &rate) {
431 // do some cursory validation of the settings here. audio modes are
432 // only validated when set on the audiosink.
433 if ((rate.mSpeed != 0.f && rate.mSpeed < AUDIO_TIMESTRETCH_SPEED_MIN)
434 || rate.mSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
435 || rate.mPitch < AUDIO_TIMESTRETCH_SPEED_MIN
436 || rate.mPitch > AUDIO_TIMESTRETCH_SPEED_MAX) {
437 return BAD_VALUE;
438 }
439 sp<AMessage> msg = new AMessage(kWhatConfigPlayback, this);
440 writeToAMessage(msg, rate);
441 sp<AMessage> response;
442 status_t err = msg->postAndAwaitResponse(&response);
443 if (err == OK && response != NULL) {
444 CHECK(response->findInt32("err", &err));
445 }
446 return err;
447}
448
449status_t NuPlayer2::getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
450 sp<AMessage> msg = new AMessage(kWhatGetPlaybackSettings, this);
451 sp<AMessage> response;
452 status_t err = msg->postAndAwaitResponse(&response);
453 if (err == OK && response != NULL) {
454 CHECK(response->findInt32("err", &err));
455 if (err == OK) {
456 readFromAMessage(response, rate);
457 }
458 }
459 return err;
460}
461
462status_t NuPlayer2::setSyncSettings(const AVSyncSettings &sync, float videoFpsHint) {
463 sp<AMessage> msg = new AMessage(kWhatConfigSync, this);
464 writeToAMessage(msg, sync, videoFpsHint);
465 sp<AMessage> response;
466 status_t err = msg->postAndAwaitResponse(&response);
467 if (err == OK && response != NULL) {
468 CHECK(response->findInt32("err", &err));
469 }
470 return err;
471}
472
473status_t NuPlayer2::getSyncSettings(
474 AVSyncSettings *sync /* nonnull */, float *videoFps /* nonnull */) {
475 sp<AMessage> msg = new AMessage(kWhatGetSyncSettings, this);
476 sp<AMessage> response;
477 status_t err = msg->postAndAwaitResponse(&response);
478 if (err == OK && response != NULL) {
479 CHECK(response->findInt32("err", &err));
480 if (err == OK) {
481 readFromAMessage(response, sync, videoFps);
482 }
483 }
484 return err;
485}
486
487void NuPlayer2::pause() {
488 (new AMessage(kWhatPause, this))->post();
489}
490
491void NuPlayer2::resetAsync() {
492 sp<Source> source;
493 {
494 Mutex::Autolock autoLock(mSourceLock);
495 source = mSource;
496 }
497
498 if (source != NULL) {
499 // During a reset, the data source might be unresponsive already, we need to
500 // disconnect explicitly so that reads exit promptly.
501 // We can't queue the disconnect request to the looper, as it might be
502 // queued behind a stuck read and never gets processed.
503 // Doing a disconnect outside the looper to allows the pending reads to exit
504 // (either successfully or with error).
505 source->disconnect();
506 }
507
508 (new AMessage(kWhatReset, this))->post();
509}
510
511status_t NuPlayer2::notifyAt(int64_t mediaTimeUs) {
512 sp<AMessage> notify = new AMessage(kWhatNotifyTime, this);
513 notify->setInt64("timerUs", mediaTimeUs);
514 mMediaClock->addTimer(notify, mediaTimeUs);
515 return OK;
516}
517
518void NuPlayer2::seekToAsync(int64_t seekTimeUs, MediaPlayer2SeekMode mode, bool needNotify) {
519 sp<AMessage> msg = new AMessage(kWhatSeek, this);
520 msg->setInt64("seekTimeUs", seekTimeUs);
521 msg->setInt32("mode", mode);
522 msg->setInt32("needNotify", needNotify);
523 msg->post();
524}
525
526
527void NuPlayer2::writeTrackInfo(
528 Parcel* reply, const sp<AMessage>& format) const {
529 if (format == NULL) {
530 ALOGE("NULL format");
531 return;
532 }
533 int32_t trackType;
534 if (!format->findInt32("type", &trackType)) {
535 ALOGE("no track type");
536 return;
537 }
538
539 AString mime;
540 if (!format->findString("mime", &mime)) {
541 // Java MediaPlayer only uses mimetype for subtitle and timedtext tracks.
542 // If we can't find the mimetype here it means that we wouldn't be needing
543 // the mimetype on the Java end. We still write a placeholder mime to keep the
544 // (de)serialization logic simple.
545 if (trackType == MEDIA_TRACK_TYPE_AUDIO) {
546 mime = "audio/";
547 } else if (trackType == MEDIA_TRACK_TYPE_VIDEO) {
548 mime = "video/";
549 } else {
550 ALOGE("unknown track type: %d", trackType);
551 return;
552 }
553 }
554
555 AString lang;
556 if (!format->findString("language", &lang)) {
557 ALOGE("no language");
558 return;
559 }
560
561 reply->writeInt32(2); // write something non-zero
562 reply->writeInt32(trackType);
563 reply->writeString16(String16(mime.c_str()));
564 reply->writeString16(String16(lang.c_str()));
565
566 if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
567 int32_t isAuto, isDefault, isForced;
568 CHECK(format->findInt32("auto", &isAuto));
569 CHECK(format->findInt32("default", &isDefault));
570 CHECK(format->findInt32("forced", &isForced));
571
572 reply->writeInt32(isAuto);
573 reply->writeInt32(isDefault);
574 reply->writeInt32(isForced);
575 }
576}
577
578void NuPlayer2::onMessageReceived(const sp<AMessage> &msg) {
579 switch (msg->what()) {
580 case kWhatSetDataSource:
581 {
582 ALOGV("kWhatSetDataSource");
583
584 CHECK(mSource == NULL);
585
586 status_t err = OK;
587 sp<RefBase> obj;
588 CHECK(msg->findObject("source", &obj));
589 if (obj != NULL) {
590 Mutex::Autolock autoLock(mSourceLock);
591 mSource = static_cast<Source *>(obj.get());
592 } else {
593 err = UNKNOWN_ERROR;
594 }
595
596 CHECK(mDriver != NULL);
597 sp<NuPlayer2Driver> driver = mDriver.promote();
598 if (driver != NULL) {
599 driver->notifySetDataSourceCompleted(err);
600 }
601 break;
602 }
603
604 case kWhatGetBufferingSettings:
605 {
606 sp<AReplyToken> replyID;
607 CHECK(msg->senderAwaitsResponse(&replyID));
608
609 ALOGV("kWhatGetBufferingSettings");
610 BufferingSettings buffering;
611 status_t err = OK;
612 if (mSource != NULL) {
613 err = mSource->getBufferingSettings(&buffering);
614 } else {
615 err = INVALID_OPERATION;
616 }
617 sp<AMessage> response = new AMessage;
618 if (err == OK) {
619 writeToAMessage(response, buffering);
620 }
621 response->setInt32("err", err);
622 response->postReply(replyID);
623 break;
624 }
625
626 case kWhatSetBufferingSettings:
627 {
628 sp<AReplyToken> replyID;
629 CHECK(msg->senderAwaitsResponse(&replyID));
630
631 ALOGV("kWhatSetBufferingSettings");
632 BufferingSettings buffering;
633 readFromAMessage(msg, &buffering);
634 status_t err = OK;
635 if (mSource != NULL) {
636 err = mSource->setBufferingSettings(buffering);
637 } else {
638 err = INVALID_OPERATION;
639 }
640 sp<AMessage> response = new AMessage;
641 response->setInt32("err", err);
642 response->postReply(replyID);
643 break;
644 }
645
646 case kWhatPrepare:
647 {
648 ALOGV("onMessageReceived kWhatPrepare");
649
650 mSource->prepareAsync();
651 break;
652 }
653
654 case kWhatGetTrackInfo:
655 {
656 sp<AReplyToken> replyID;
657 CHECK(msg->senderAwaitsResponse(&replyID));
658
659 Parcel* reply;
660 CHECK(msg->findPointer("reply", (void**)&reply));
661
662 size_t inbandTracks = 0;
663 if (mSource != NULL) {
664 inbandTracks = mSource->getTrackCount();
665 }
666
667 size_t ccTracks = 0;
668 if (mCCDecoder != NULL) {
669 ccTracks = mCCDecoder->getTrackCount();
670 }
671
672 // total track count
673 reply->writeInt32(inbandTracks + ccTracks);
674
675 // write inband tracks
676 for (size_t i = 0; i < inbandTracks; ++i) {
677 writeTrackInfo(reply, mSource->getTrackInfo(i));
678 }
679
680 // write CC track
681 for (size_t i = 0; i < ccTracks; ++i) {
682 writeTrackInfo(reply, mCCDecoder->getTrackInfo(i));
683 }
684
685 sp<AMessage> response = new AMessage;
686 response->postReply(replyID);
687 break;
688 }
689
690 case kWhatGetSelectedTrack:
691 {
692 status_t err = INVALID_OPERATION;
693 if (mSource != NULL) {
694 err = OK;
695
696 int32_t type32;
697 CHECK(msg->findInt32("type", (int32_t*)&type32));
698 media_track_type type = (media_track_type)type32;
699 ssize_t selectedTrack = mSource->getSelectedTrack(type);
700
701 Parcel* reply;
702 CHECK(msg->findPointer("reply", (void**)&reply));
703 reply->writeInt32(selectedTrack);
704 }
705
706 sp<AMessage> response = new AMessage;
707 response->setInt32("err", err);
708
709 sp<AReplyToken> replyID;
710 CHECK(msg->senderAwaitsResponse(&replyID));
711 response->postReply(replyID);
712 break;
713 }
714
715 case kWhatSelectTrack:
716 {
717 sp<AReplyToken> replyID;
718 CHECK(msg->senderAwaitsResponse(&replyID));
719
720 size_t trackIndex;
721 int32_t select;
722 int64_t timeUs;
723 CHECK(msg->findSize("trackIndex", &trackIndex));
724 CHECK(msg->findInt32("select", &select));
725 CHECK(msg->findInt64("timeUs", &timeUs));
726
727 status_t err = INVALID_OPERATION;
728
729 size_t inbandTracks = 0;
730 if (mSource != NULL) {
731 inbandTracks = mSource->getTrackCount();
732 }
733 size_t ccTracks = 0;
734 if (mCCDecoder != NULL) {
735 ccTracks = mCCDecoder->getTrackCount();
736 }
737
738 if (trackIndex < inbandTracks) {
739 err = mSource->selectTrack(trackIndex, select, timeUs);
740
741 if (!select && err == OK) {
742 int32_t type;
743 sp<AMessage> info = mSource->getTrackInfo(trackIndex);
744 if (info != NULL
745 && info->findInt32("type", &type)
746 && type == MEDIA_TRACK_TYPE_TIMEDTEXT) {
747 ++mTimedTextGeneration;
748 }
749 }
750 } else {
751 trackIndex -= inbandTracks;
752
753 if (trackIndex < ccTracks) {
754 err = mCCDecoder->selectTrack(trackIndex, select);
755 }
756 }
757
758 sp<AMessage> response = new AMessage;
759 response->setInt32("err", err);
760
761 response->postReply(replyID);
762 break;
763 }
764
765 case kWhatPollDuration:
766 {
767 int32_t generation;
768 CHECK(msg->findInt32("generation", &generation));
769
770 if (generation != mPollDurationGeneration) {
771 // stale
772 break;
773 }
774
775 int64_t durationUs;
776 if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
777 sp<NuPlayer2Driver> driver = mDriver.promote();
778 if (driver != NULL) {
779 driver->notifyDuration(durationUs);
780 }
781 }
782
783 msg->post(1000000ll); // poll again in a second.
784 break;
785 }
786
787 case kWhatSetVideoSurface:
788 {
789
790 sp<RefBase> obj;
791 CHECK(msg->findObject("surface", &obj));
Wei Jia28288fb2017-12-15 13:45:29 -0800792 sp<ANativeWindowWrapper> nww = static_cast<ANativeWindowWrapper *>(obj.get());
Wei Jia53692fa2017-12-11 10:33:46 -0800793
794 ALOGD("onSetVideoSurface(%p, %s video decoder)",
Wei Jia28288fb2017-12-15 13:45:29 -0800795 (nww == NULL ? NULL : nww->getANativeWindow()),
Wei Jia53692fa2017-12-11 10:33:46 -0800796 (mSource != NULL && mStarted && mSource->getFormat(false /* audio */) != NULL
797 && mVideoDecoder != NULL) ? "have" : "no");
798
799 // Need to check mStarted before calling mSource->getFormat because NuPlayer2 might
800 // be in preparing state and it could take long time.
801 // When mStarted is true, mSource must have been set.
802 if (mSource == NULL || !mStarted || mSource->getFormat(false /* audio */) == NULL
Wei Jia28288fb2017-12-15 13:45:29 -0800803 // NOTE: mVideoDecoder's mNativeWindow is always non-null
804 || (mVideoDecoder != NULL && mVideoDecoder->setVideoSurface(nww) == OK)) {
805 performSetSurface(nww);
Wei Jia53692fa2017-12-11 10:33:46 -0800806 break;
807 }
808
809 mDeferredActions.push_back(
810 new FlushDecoderAction(
811 (obj != NULL ? FLUSH_CMD_FLUSH : FLUSH_CMD_NONE) /* audio */,
812 FLUSH_CMD_SHUTDOWN /* video */));
813
Wei Jia28288fb2017-12-15 13:45:29 -0800814 mDeferredActions.push_back(new SetSurfaceAction(nww));
Wei Jia53692fa2017-12-11 10:33:46 -0800815
816 if (obj != NULL) {
817 if (mStarted) {
818 // Issue a seek to refresh the video screen only if started otherwise
819 // the extractor may not yet be started and will assert.
820 // If the video decoder is not set (perhaps audio only in this case)
821 // do not perform a seek as it is not needed.
822 int64_t currentPositionUs = 0;
823 if (getCurrentPosition(&currentPositionUs) == OK) {
824 mDeferredActions.push_back(
825 new SeekAction(currentPositionUs,
826 MediaPlayer2SeekMode::SEEK_PREVIOUS_SYNC /* mode */));
827 }
828 }
829
830 // If there is a new surface texture, instantiate decoders
831 // again if possible.
832 mDeferredActions.push_back(
833 new SimpleAction(&NuPlayer2::performScanSources));
834
835 // After a flush without shutdown, decoder is paused.
836 // Don't resume it until source seek is done, otherwise it could
837 // start pulling stale data too soon.
838 mDeferredActions.push_back(
839 new ResumeDecoderAction(false /* needNotify */));
840 }
841
842 processDeferredActions();
843 break;
844 }
845
846 case kWhatSetAudioSink:
847 {
848 ALOGV("kWhatSetAudioSink");
849
850 sp<RefBase> obj;
851 CHECK(msg->findObject("sink", &obj));
852
Wei Jia33abcc72018-01-30 09:47:38 -0800853 mAudioSink = static_cast<MediaPlayer2Interface::AudioSink *>(obj.get());
Wei Jia53692fa2017-12-11 10:33:46 -0800854 break;
855 }
856
857 case kWhatStart:
858 {
859 ALOGV("kWhatStart");
860 if (mStarted) {
861 // do not resume yet if the source is still buffering
862 if (!mPausedForBuffering) {
863 onResume();
864 }
865 } else {
866 onStart();
867 }
868 mPausedByClient = false;
869 break;
870 }
871
872 case kWhatConfigPlayback:
873 {
874 sp<AReplyToken> replyID;
875 CHECK(msg->senderAwaitsResponse(&replyID));
876 AudioPlaybackRate rate /* sanitized */;
877 readFromAMessage(msg, &rate);
878 status_t err = OK;
879 if (mRenderer != NULL) {
880 // AudioSink allows only 1.f and 0.f for offload mode.
881 // For other speed, switch to non-offload mode.
882 if (mOffloadAudio && ((rate.mSpeed != 0.f && rate.mSpeed != 1.f)
883 || rate.mPitch != 1.f)) {
884 int64_t currentPositionUs;
885 if (getCurrentPosition(&currentPositionUs) != OK) {
886 currentPositionUs = mPreviousSeekTimeUs;
887 }
888
889 // Set mPlaybackSettings so that the new audio decoder can
890 // be created correctly.
891 mPlaybackSettings = rate;
892 if (!mPaused) {
893 mRenderer->pause();
894 }
895 restartAudio(
896 currentPositionUs, true /* forceNonOffload */,
897 true /* needsToCreateAudioDecoder */);
898 if (!mPaused) {
899 mRenderer->resume();
900 }
901 }
902
903 err = mRenderer->setPlaybackSettings(rate);
904 }
905 if (err == OK) {
906 if (rate.mSpeed == 0.f) {
907 onPause();
908 mPausedByClient = true;
909 // save all other settings (using non-paused speed)
910 // so we can restore them on start
911 AudioPlaybackRate newRate = rate;
912 newRate.mSpeed = mPlaybackSettings.mSpeed;
913 mPlaybackSettings = newRate;
914 } else { /* rate.mSpeed != 0.f */
915 mPlaybackSettings = rate;
916 if (mStarted) {
917 // do not resume yet if the source is still buffering
918 if (!mPausedForBuffering) {
919 onResume();
920 }
921 } else if (mPrepared) {
922 onStart();
923 }
924
925 mPausedByClient = false;
926 }
927 }
928
929 if (mVideoDecoder != NULL) {
930 sp<AMessage> params = new AMessage();
931 params->setFloat("playback-speed", mPlaybackSettings.mSpeed);
932 mVideoDecoder->setParameters(params);
933 }
934
935 sp<AMessage> response = new AMessage;
936 response->setInt32("err", err);
937 response->postReply(replyID);
938 break;
939 }
940
941 case kWhatGetPlaybackSettings:
942 {
943 sp<AReplyToken> replyID;
944 CHECK(msg->senderAwaitsResponse(&replyID));
945 AudioPlaybackRate rate = mPlaybackSettings;
946 status_t err = OK;
947 if (mRenderer != NULL) {
948 err = mRenderer->getPlaybackSettings(&rate);
949 }
950 if (err == OK) {
951 // get playback settings used by renderer, as it may be
952 // slightly off due to audiosink not taking small changes.
953 mPlaybackSettings = rate;
954 if (mPaused) {
955 rate.mSpeed = 0.f;
956 }
957 }
958 sp<AMessage> response = new AMessage;
959 if (err == OK) {
960 writeToAMessage(response, rate);
961 }
962 response->setInt32("err", err);
963 response->postReply(replyID);
964 break;
965 }
966
967 case kWhatConfigSync:
968 {
969 sp<AReplyToken> replyID;
970 CHECK(msg->senderAwaitsResponse(&replyID));
971
972 ALOGV("kWhatConfigSync");
973 AVSyncSettings sync;
974 float videoFpsHint;
975 readFromAMessage(msg, &sync, &videoFpsHint);
976 status_t err = OK;
977 if (mRenderer != NULL) {
978 err = mRenderer->setSyncSettings(sync, videoFpsHint);
979 }
980 if (err == OK) {
981 mSyncSettings = sync;
982 mVideoFpsHint = videoFpsHint;
983 }
984 sp<AMessage> response = new AMessage;
985 response->setInt32("err", err);
986 response->postReply(replyID);
987 break;
988 }
989
990 case kWhatGetSyncSettings:
991 {
992 sp<AReplyToken> replyID;
993 CHECK(msg->senderAwaitsResponse(&replyID));
994 AVSyncSettings sync = mSyncSettings;
995 float videoFps = mVideoFpsHint;
996 status_t err = OK;
997 if (mRenderer != NULL) {
998 err = mRenderer->getSyncSettings(&sync, &videoFps);
999 if (err == OK) {
1000 mSyncSettings = sync;
1001 mVideoFpsHint = videoFps;
1002 }
1003 }
1004 sp<AMessage> response = new AMessage;
1005 if (err == OK) {
1006 writeToAMessage(response, sync, videoFps);
1007 }
1008 response->setInt32("err", err);
1009 response->postReply(replyID);
1010 break;
1011 }
1012
1013 case kWhatScanSources:
1014 {
1015 int32_t generation;
1016 CHECK(msg->findInt32("generation", &generation));
1017 if (generation != mScanSourcesGeneration) {
1018 // Drop obsolete msg.
1019 break;
1020 }
1021
1022 mScanSourcesPending = false;
1023
1024 ALOGV("scanning sources haveAudio=%d, haveVideo=%d",
1025 mAudioDecoder != NULL, mVideoDecoder != NULL);
1026
1027 bool mHadAnySourcesBefore =
1028 (mAudioDecoder != NULL) || (mVideoDecoder != NULL);
1029 bool rescan = false;
1030
1031 // initialize video before audio because successful initialization of
1032 // video may change deep buffer mode of audio.
Wei Jia28288fb2017-12-15 13:45:29 -08001033 if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -08001034 if (instantiateDecoder(false, &mVideoDecoder) == -EWOULDBLOCK) {
1035 rescan = true;
1036 }
1037 }
1038
1039 // Don't try to re-open audio sink if there's an existing decoder.
1040 if (mAudioSink != NULL && mAudioDecoder == NULL) {
1041 if (instantiateDecoder(true, &mAudioDecoder) == -EWOULDBLOCK) {
1042 rescan = true;
1043 }
1044 }
1045
1046 if (!mHadAnySourcesBefore
1047 && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
1048 // This is the first time we've found anything playable.
1049
1050 if (mSourceFlags & Source::FLAG_DYNAMIC_DURATION) {
1051 schedulePollDuration();
1052 }
1053 }
1054
1055 status_t err;
1056 if ((err = mSource->feedMoreTSData()) != OK) {
1057 if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
1058 // We're not currently decoding anything (no audio or
1059 // video tracks found) and we just ran out of input data.
1060
1061 if (err == ERROR_END_OF_STREAM) {
1062 notifyListener(MEDIA2_PLAYBACK_COMPLETE, 0, 0);
1063 } else {
1064 notifyListener(MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
1065 }
1066 }
1067 break;
1068 }
1069
1070 if (rescan) {
1071 msg->post(100000ll);
1072 mScanSourcesPending = true;
1073 }
1074 break;
1075 }
1076
1077 case kWhatVideoNotify:
1078 case kWhatAudioNotify:
1079 {
1080 bool audio = msg->what() == kWhatAudioNotify;
1081
1082 int32_t currentDecoderGeneration =
1083 (audio? mAudioDecoderGeneration : mVideoDecoderGeneration);
1084 int32_t requesterGeneration = currentDecoderGeneration - 1;
1085 CHECK(msg->findInt32("generation", &requesterGeneration));
1086
1087 if (requesterGeneration != currentDecoderGeneration) {
1088 ALOGV("got message from old %s decoder, generation(%d:%d)",
1089 audio ? "audio" : "video", requesterGeneration,
1090 currentDecoderGeneration);
1091 sp<AMessage> reply;
1092 if (!(msg->findMessage("reply", &reply))) {
1093 return;
1094 }
1095
1096 reply->setInt32("err", INFO_DISCONTINUITY);
1097 reply->post();
1098 return;
1099 }
1100
1101 int32_t what;
1102 CHECK(msg->findInt32("what", &what));
1103
1104 if (what == DecoderBase::kWhatInputDiscontinuity) {
1105 int32_t formatChange;
1106 CHECK(msg->findInt32("formatChange", &formatChange));
1107
1108 ALOGV("%s discontinuity: formatChange %d",
1109 audio ? "audio" : "video", formatChange);
1110
1111 if (formatChange) {
1112 mDeferredActions.push_back(
1113 new FlushDecoderAction(
1114 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
1115 audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN));
1116 }
1117
1118 mDeferredActions.push_back(
1119 new SimpleAction(
1120 &NuPlayer2::performScanSources));
1121
1122 processDeferredActions();
1123 } else if (what == DecoderBase::kWhatEOS) {
1124 int32_t err;
1125 CHECK(msg->findInt32("err", &err));
1126
1127 if (err == ERROR_END_OF_STREAM) {
1128 ALOGV("got %s decoder EOS", audio ? "audio" : "video");
1129 } else {
1130 ALOGV("got %s decoder EOS w/ error %d",
1131 audio ? "audio" : "video",
1132 err);
1133 }
1134
1135 mRenderer->queueEOS(audio, err);
1136 } else if (what == DecoderBase::kWhatFlushCompleted) {
1137 ALOGV("decoder %s flush completed", audio ? "audio" : "video");
1138
1139 handleFlushComplete(audio, true /* isDecoder */);
1140 finishFlushIfPossible();
1141 } else if (what == DecoderBase::kWhatVideoSizeChanged) {
1142 sp<AMessage> format;
1143 CHECK(msg->findMessage("format", &format));
1144
1145 sp<AMessage> inputFormat =
1146 mSource->getFormat(false /* audio */);
1147
1148 setVideoScalingMode(mVideoScalingMode);
1149 updateVideoSize(inputFormat, format);
1150 } else if (what == DecoderBase::kWhatShutdownCompleted) {
1151 ALOGV("%s shutdown completed", audio ? "audio" : "video");
1152 if (audio) {
1153 mAudioDecoder.clear();
1154 mAudioDecoderError = false;
1155 ++mAudioDecoderGeneration;
1156
1157 CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
1158 mFlushingAudio = SHUT_DOWN;
1159 } else {
1160 mVideoDecoder.clear();
1161 mVideoDecoderError = false;
1162 ++mVideoDecoderGeneration;
1163
1164 CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
1165 mFlushingVideo = SHUT_DOWN;
1166 }
1167
1168 finishFlushIfPossible();
1169 } else if (what == DecoderBase::kWhatResumeCompleted) {
1170 finishResume();
1171 } else if (what == DecoderBase::kWhatError) {
1172 status_t err;
1173 if (!msg->findInt32("err", &err) || err == OK) {
1174 err = UNKNOWN_ERROR;
1175 }
1176
1177 // Decoder errors can be due to Source (e.g. from streaming),
1178 // or from decoding corrupted bitstreams, or from other decoder
1179 // MediaCodec operations (e.g. from an ongoing reset or seek).
1180 // They may also be due to openAudioSink failure at
1181 // decoder start or after a format change.
1182 //
1183 // We try to gracefully shut down the affected decoder if possible,
1184 // rather than trying to force the shutdown with something
1185 // similar to performReset(). This method can lead to a hang
1186 // if MediaCodec functions block after an error, but they should
1187 // typically return INVALID_OPERATION instead of blocking.
1188
1189 FlushStatus *flushing = audio ? &mFlushingAudio : &mFlushingVideo;
1190 ALOGE("received error(%#x) from %s decoder, flushing(%d), now shutting down",
1191 err, audio ? "audio" : "video", *flushing);
1192
1193 switch (*flushing) {
1194 case NONE:
1195 mDeferredActions.push_back(
1196 new FlushDecoderAction(
1197 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
1198 audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN));
1199 processDeferredActions();
1200 break;
1201 case FLUSHING_DECODER:
1202 *flushing = FLUSHING_DECODER_SHUTDOWN; // initiate shutdown after flush.
1203 break; // Wait for flush to complete.
1204 case FLUSHING_DECODER_SHUTDOWN:
1205 break; // Wait for flush to complete.
1206 case SHUTTING_DOWN_DECODER:
1207 break; // Wait for shutdown to complete.
1208 case FLUSHED:
1209 getDecoder(audio)->initiateShutdown(); // In the middle of a seek.
1210 *flushing = SHUTTING_DOWN_DECODER; // Shut down.
1211 break;
1212 case SHUT_DOWN:
1213 finishFlushIfPossible(); // Should not occur.
1214 break; // Finish anyways.
1215 }
1216 if (mSource != nullptr) {
1217 if (audio) {
1218 if (mVideoDecoderError || mSource->getFormat(false /* audio */) == NULL
Wei Jia28288fb2017-12-15 13:45:29 -08001219 || mNativeWindow == NULL || mNativeWindow->getANativeWindow() == NULL
1220 || mVideoDecoder == NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -08001221 // When both audio and video have error, or this stream has only audio
1222 // which has error, notify client of error.
1223 notifyListener(MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
1224 } else {
1225 // Only audio track has error. Video track could be still good to play.
1226 notifyListener(MEDIA2_INFO, MEDIA2_INFO_PLAY_AUDIO_ERROR, err);
1227 }
1228 mAudioDecoderError = true;
1229 } else {
1230 if (mAudioDecoderError || mSource->getFormat(true /* audio */) == NULL
1231 || mAudioSink == NULL || mAudioDecoder == NULL) {
1232 // When both audio and video have error, or this stream has only video
1233 // which has error, notify client of error.
1234 notifyListener(MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
1235 } else {
1236 // Only video track has error. Audio track could be still good to play.
1237 notifyListener(MEDIA2_INFO, MEDIA2_INFO_PLAY_VIDEO_ERROR, err);
1238 }
1239 mVideoDecoderError = true;
1240 }
1241 }
1242 } else {
1243 ALOGV("Unhandled decoder notification %d '%c%c%c%c'.",
1244 what,
1245 what >> 24,
1246 (what >> 16) & 0xff,
1247 (what >> 8) & 0xff,
1248 what & 0xff);
1249 }
1250
1251 break;
1252 }
1253
1254 case kWhatRendererNotify:
1255 {
1256 int32_t requesterGeneration = mRendererGeneration - 1;
1257 CHECK(msg->findInt32("generation", &requesterGeneration));
1258 if (requesterGeneration != mRendererGeneration) {
1259 ALOGV("got message from old renderer, generation(%d:%d)",
1260 requesterGeneration, mRendererGeneration);
1261 return;
1262 }
1263
1264 int32_t what;
1265 CHECK(msg->findInt32("what", &what));
1266
1267 if (what == Renderer::kWhatEOS) {
1268 int32_t audio;
1269 CHECK(msg->findInt32("audio", &audio));
1270
1271 int32_t finalResult;
1272 CHECK(msg->findInt32("finalResult", &finalResult));
1273
1274 if (audio) {
1275 mAudioEOS = true;
1276 } else {
1277 mVideoEOS = true;
1278 }
1279
1280 if (finalResult == ERROR_END_OF_STREAM) {
1281 ALOGV("reached %s EOS", audio ? "audio" : "video");
1282 } else {
1283 ALOGE("%s track encountered an error (%d)",
1284 audio ? "audio" : "video", finalResult);
1285
1286 notifyListener(
1287 MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, finalResult);
1288 }
1289
1290 if ((mAudioEOS || mAudioDecoder == NULL)
1291 && (mVideoEOS || mVideoDecoder == NULL)) {
1292 notifyListener(MEDIA2_PLAYBACK_COMPLETE, 0, 0);
1293 }
1294 } else if (what == Renderer::kWhatFlushComplete) {
1295 int32_t audio;
1296 CHECK(msg->findInt32("audio", &audio));
1297
1298 if (audio) {
1299 mAudioEOS = false;
1300 } else {
1301 mVideoEOS = false;
1302 }
1303
1304 ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
1305 if (audio && (mFlushingAudio == NONE || mFlushingAudio == FLUSHED
1306 || mFlushingAudio == SHUT_DOWN)) {
1307 // Flush has been handled by tear down.
1308 break;
1309 }
1310 handleFlushComplete(audio, false /* isDecoder */);
1311 finishFlushIfPossible();
1312 } else if (what == Renderer::kWhatVideoRenderingStart) {
1313 notifyListener(MEDIA2_INFO, MEDIA2_INFO_RENDERING_START, 0);
1314 } else if (what == Renderer::kWhatMediaRenderingStart) {
1315 ALOGV("media rendering started");
1316 notifyListener(MEDIA2_STARTED, 0, 0);
1317 } else if (what == Renderer::kWhatAudioTearDown) {
1318 int32_t reason;
1319 CHECK(msg->findInt32("reason", &reason));
1320 ALOGV("Tear down audio with reason %d.", reason);
1321 if (reason == Renderer::kDueToTimeout && !(mPaused && mOffloadAudio)) {
1322 // TimeoutWhenPaused is only for offload mode.
1323 ALOGW("Receive a stale message for teardown.");
1324 break;
1325 }
1326 int64_t positionUs;
1327 if (!msg->findInt64("positionUs", &positionUs)) {
1328 positionUs = mPreviousSeekTimeUs;
1329 }
1330
1331 restartAudio(
1332 positionUs, reason == Renderer::kForceNonOffload /* forceNonOffload */,
1333 reason != Renderer::kDueToTimeout /* needsToCreateAudioDecoder */);
1334 }
1335 break;
1336 }
1337
1338 case kWhatMoreDataQueued:
1339 {
1340 break;
1341 }
1342
1343 case kWhatReset:
1344 {
1345 ALOGV("kWhatReset");
1346
1347 mResetting = true;
1348 stopPlaybackTimer("kWhatReset");
1349 stopRebufferingTimer(true);
1350
1351 mDeferredActions.push_back(
1352 new FlushDecoderAction(
1353 FLUSH_CMD_SHUTDOWN /* audio */,
1354 FLUSH_CMD_SHUTDOWN /* video */));
1355
1356 mDeferredActions.push_back(
1357 new SimpleAction(&NuPlayer2::performReset));
1358
1359 processDeferredActions();
1360 break;
1361 }
1362
1363 case kWhatNotifyTime:
1364 {
1365 ALOGV("kWhatNotifyTime");
1366 int64_t timerUs;
1367 CHECK(msg->findInt64("timerUs", &timerUs));
1368
1369 notifyListener(MEDIA2_NOTIFY_TIME, timerUs, 0);
1370 break;
1371 }
1372
1373 case kWhatSeek:
1374 {
1375 int64_t seekTimeUs;
1376 int32_t mode;
1377 int32_t needNotify;
1378 CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
1379 CHECK(msg->findInt32("mode", &mode));
1380 CHECK(msg->findInt32("needNotify", &needNotify));
1381
1382 ALOGV("kWhatSeek seekTimeUs=%lld us, mode=%d, needNotify=%d",
1383 (long long)seekTimeUs, mode, needNotify);
1384
1385 if (!mStarted) {
1386 // Seek before the player is started. In order to preview video,
1387 // need to start the player and pause it. This branch is called
1388 // only once if needed. After the player is started, any seek
1389 // operation will go through normal path.
1390 // Audio-only cases are handled separately.
1391 onStart(seekTimeUs, (MediaPlayer2SeekMode)mode);
1392 if (mStarted) {
1393 onPause();
1394 mPausedByClient = true;
1395 }
1396 if (needNotify) {
1397 notifyDriverSeekComplete();
1398 }
1399 break;
1400 }
1401
1402 mDeferredActions.push_back(
1403 new FlushDecoderAction(FLUSH_CMD_FLUSH /* audio */,
1404 FLUSH_CMD_FLUSH /* video */));
1405
1406 mDeferredActions.push_back(
1407 new SeekAction(seekTimeUs, (MediaPlayer2SeekMode)mode));
1408
1409 // After a flush without shutdown, decoder is paused.
1410 // Don't resume it until source seek is done, otherwise it could
1411 // start pulling stale data too soon.
1412 mDeferredActions.push_back(
1413 new ResumeDecoderAction(needNotify));
1414
1415 processDeferredActions();
1416 break;
1417 }
1418
1419 case kWhatPause:
1420 {
1421 onPause();
1422 mPausedByClient = true;
1423 break;
1424 }
1425
1426 case kWhatSourceNotify:
1427 {
1428 onSourceNotify(msg);
1429 break;
1430 }
1431
1432 case kWhatClosedCaptionNotify:
1433 {
1434 onClosedCaptionNotify(msg);
1435 break;
1436 }
1437
1438 case kWhatPrepareDrm:
1439 {
1440 status_t status = onPrepareDrm(msg);
1441
1442 sp<AMessage> response = new AMessage;
1443 response->setInt32("status", status);
1444 sp<AReplyToken> replyID;
1445 CHECK(msg->senderAwaitsResponse(&replyID));
1446 response->postReply(replyID);
1447 break;
1448 }
1449
1450 case kWhatReleaseDrm:
1451 {
1452 status_t status = onReleaseDrm();
1453
1454 sp<AMessage> response = new AMessage;
1455 response->setInt32("status", status);
1456 sp<AReplyToken> replyID;
1457 CHECK(msg->senderAwaitsResponse(&replyID));
1458 response->postReply(replyID);
1459 break;
1460 }
1461
1462 default:
1463 TRESPASS();
1464 break;
1465 }
1466}
1467
1468void NuPlayer2::onResume() {
1469 if (!mPaused || mResetting) {
1470 ALOGD_IF(mResetting, "resetting, onResume discarded");
1471 return;
1472 }
1473 mPaused = false;
1474 if (mSource != NULL) {
1475 mSource->resume();
1476 } else {
1477 ALOGW("resume called when source is gone or not set");
1478 }
1479 // |mAudioDecoder| may have been released due to the pause timeout, so re-create it if
1480 // needed.
1481 if (audioDecoderStillNeeded() && mAudioDecoder == NULL) {
1482 instantiateDecoder(true /* audio */, &mAudioDecoder);
1483 }
1484 if (mRenderer != NULL) {
1485 mRenderer->resume();
1486 } else {
1487 ALOGW("resume called when renderer is gone or not set");
1488 }
1489
1490 startPlaybackTimer("onresume");
1491}
1492
1493status_t NuPlayer2::onInstantiateSecureDecoders() {
1494 status_t err;
1495 if (!(mSourceFlags & Source::FLAG_SECURE)) {
1496 return BAD_TYPE;
1497 }
1498
1499 if (mRenderer != NULL) {
1500 ALOGE("renderer should not be set when instantiating secure decoders");
1501 return UNKNOWN_ERROR;
1502 }
1503
1504 // TRICKY: We rely on mRenderer being null, so that decoder does not start requesting
1505 // data on instantiation.
Wei Jia28288fb2017-12-15 13:45:29 -08001506 if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -08001507 err = instantiateDecoder(false, &mVideoDecoder);
1508 if (err != OK) {
1509 return err;
1510 }
1511 }
1512
1513 if (mAudioSink != NULL) {
1514 err = instantiateDecoder(true, &mAudioDecoder);
1515 if (err != OK) {
1516 return err;
1517 }
1518 }
1519 return OK;
1520}
1521
1522void NuPlayer2::onStart(int64_t startPositionUs, MediaPlayer2SeekMode mode) {
1523 ALOGV("onStart: mCrypto: %p", mCrypto.get());
1524
1525 if (!mSourceStarted) {
1526 mSourceStarted = true;
1527 mSource->start();
1528 }
1529 if (startPositionUs > 0) {
1530 performSeek(startPositionUs, mode);
1531 if (mSource->getFormat(false /* audio */) == NULL) {
1532 return;
1533 }
1534 }
1535
1536 mOffloadAudio = false;
1537 mAudioEOS = false;
1538 mVideoEOS = false;
1539 mStarted = true;
1540 mPaused = false;
1541
1542 uint32_t flags = 0;
1543
1544 if (mSource->isRealTime()) {
1545 flags |= Renderer::FLAG_REAL_TIME;
1546 }
1547
1548 bool hasAudio = (mSource->getFormat(true /* audio */) != NULL);
1549 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
1550 if (!hasAudio && !hasVideo) {
1551 ALOGE("no metadata for either audio or video source");
1552 mSource->stop();
1553 mSourceStarted = false;
1554 notifyListener(MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, ERROR_MALFORMED);
1555 return;
1556 }
1557 ALOGV_IF(!hasAudio, "no metadata for audio source"); // video only stream
1558
1559 sp<MetaData> audioMeta = mSource->getFormatMeta(true /* audio */);
1560
1561 audio_stream_type_t streamType = AUDIO_STREAM_MUSIC;
1562 if (mAudioSink != NULL) {
1563 streamType = mAudioSink->getAudioStreamType();
1564 }
1565
1566 mOffloadAudio =
1567 canOffloadStream(audioMeta, hasVideo, mSource->isStreaming(), streamType)
1568 && (mPlaybackSettings.mSpeed == 1.f && mPlaybackSettings.mPitch == 1.f);
1569
1570 // Modular DRM: Disabling audio offload if the source is protected
1571 if (mOffloadAudio && mIsDrmProtected) {
1572 mOffloadAudio = false;
1573 ALOGV("onStart: Disabling mOffloadAudio now that the source is protected.");
1574 }
1575
1576 if (mOffloadAudio) {
1577 flags |= Renderer::FLAG_OFFLOAD_AUDIO;
1578 }
1579
1580 sp<AMessage> notify = new AMessage(kWhatRendererNotify, this);
1581 ++mRendererGeneration;
1582 notify->setInt32("generation", mRendererGeneration);
1583 mRenderer = new Renderer(mAudioSink, mMediaClock, notify, flags);
1584 mRendererLooper = new ALooper;
1585 mRendererLooper->setName("NuPlayerRenderer");
1586 mRendererLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
1587 mRendererLooper->registerHandler(mRenderer);
1588
1589 status_t err = mRenderer->setPlaybackSettings(mPlaybackSettings);
1590 if (err != OK) {
1591 mSource->stop();
1592 mSourceStarted = false;
1593 notifyListener(MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
1594 return;
1595 }
1596
1597 float rate = getFrameRate();
1598 if (rate > 0) {
1599 mRenderer->setVideoFrameRate(rate);
1600 }
1601
1602 if (mVideoDecoder != NULL) {
1603 mVideoDecoder->setRenderer(mRenderer);
1604 }
1605 if (mAudioDecoder != NULL) {
1606 mAudioDecoder->setRenderer(mRenderer);
1607 }
1608
1609 startPlaybackTimer("onstart");
1610
1611 postScanSources();
1612}
1613
1614void NuPlayer2::startPlaybackTimer(const char *where) {
1615 Mutex::Autolock autoLock(mPlayingTimeLock);
1616 if (mLastStartedPlayingTimeNs == 0) {
1617 mLastStartedPlayingTimeNs = systemTime();
1618 ALOGV("startPlaybackTimer() time %20" PRId64 " (%s)", mLastStartedPlayingTimeNs, where);
1619 }
1620}
1621
1622void NuPlayer2::stopPlaybackTimer(const char *where) {
1623 Mutex::Autolock autoLock(mPlayingTimeLock);
1624
1625 ALOGV("stopPlaybackTimer() time %20" PRId64 " (%s)", mLastStartedPlayingTimeNs, where);
1626
1627 if (mLastStartedPlayingTimeNs != 0) {
1628 sp<NuPlayer2Driver> driver = mDriver.promote();
1629 if (driver != NULL) {
1630 int64_t now = systemTime();
1631 int64_t played = now - mLastStartedPlayingTimeNs;
1632 ALOGV("stopPlaybackTimer() log %20" PRId64 "", played);
1633
1634 if (played > 0) {
1635 driver->notifyMorePlayingTimeUs((played+500)/1000);
1636 }
1637 }
1638 mLastStartedPlayingTimeNs = 0;
1639 }
1640}
1641
1642void NuPlayer2::startRebufferingTimer() {
1643 Mutex::Autolock autoLock(mPlayingTimeLock);
1644 if (mLastStartedRebufferingTimeNs == 0) {
1645 mLastStartedRebufferingTimeNs = systemTime();
1646 ALOGV("startRebufferingTimer() time %20" PRId64 "", mLastStartedRebufferingTimeNs);
1647 }
1648}
1649
1650void NuPlayer2::stopRebufferingTimer(bool exitingPlayback) {
1651 Mutex::Autolock autoLock(mPlayingTimeLock);
1652
1653 ALOGV("stopRebufferTimer() time %20" PRId64 " (exiting %d)", mLastStartedRebufferingTimeNs, exitingPlayback);
1654
1655 if (mLastStartedRebufferingTimeNs != 0) {
1656 sp<NuPlayer2Driver> driver = mDriver.promote();
1657 if (driver != NULL) {
1658 int64_t now = systemTime();
1659 int64_t rebuffered = now - mLastStartedRebufferingTimeNs;
1660 ALOGV("stopRebufferingTimer() log %20" PRId64 "", rebuffered);
1661
1662 if (rebuffered > 0) {
1663 driver->notifyMoreRebufferingTimeUs((rebuffered+500)/1000);
1664 if (exitingPlayback) {
1665 driver->notifyRebufferingWhenExit(true);
1666 }
1667 }
1668 }
1669 mLastStartedRebufferingTimeNs = 0;
1670 }
1671}
1672
1673void NuPlayer2::onPause() {
1674
1675 stopPlaybackTimer("onPause");
1676
1677 if (mPaused) {
1678 return;
1679 }
1680 mPaused = true;
1681 if (mSource != NULL) {
1682 mSource->pause();
1683 } else {
1684 ALOGW("pause called when source is gone or not set");
1685 }
1686 if (mRenderer != NULL) {
1687 mRenderer->pause();
1688 } else {
1689 ALOGW("pause called when renderer is gone or not set");
1690 }
1691
1692}
1693
1694bool NuPlayer2::audioDecoderStillNeeded() {
1695 // Audio decoder is no longer needed if it's in shut/shutting down status.
1696 return ((mFlushingAudio != SHUT_DOWN) && (mFlushingAudio != SHUTTING_DOWN_DECODER));
1697}
1698
1699void NuPlayer2::handleFlushComplete(bool audio, bool isDecoder) {
1700 // We wait for both the decoder flush and the renderer flush to complete
1701 // before entering either the FLUSHED or the SHUTTING_DOWN_DECODER state.
1702
1703 mFlushComplete[audio][isDecoder] = true;
1704 if (!mFlushComplete[audio][!isDecoder]) {
1705 return;
1706 }
1707
1708 FlushStatus *state = audio ? &mFlushingAudio : &mFlushingVideo;
1709 switch (*state) {
1710 case FLUSHING_DECODER:
1711 {
1712 *state = FLUSHED;
1713 break;
1714 }
1715
1716 case FLUSHING_DECODER_SHUTDOWN:
1717 {
1718 *state = SHUTTING_DOWN_DECODER;
1719
1720 ALOGV("initiating %s decoder shutdown", audio ? "audio" : "video");
1721 getDecoder(audio)->initiateShutdown();
1722 break;
1723 }
1724
1725 default:
1726 // decoder flush completes only occur in a flushing state.
1727 LOG_ALWAYS_FATAL_IF(isDecoder, "decoder flush in invalid state %d", *state);
1728 break;
1729 }
1730}
1731
1732void NuPlayer2::finishFlushIfPossible() {
1733 if (mFlushingAudio != NONE && mFlushingAudio != FLUSHED
1734 && mFlushingAudio != SHUT_DOWN) {
1735 return;
1736 }
1737
1738 if (mFlushingVideo != NONE && mFlushingVideo != FLUSHED
1739 && mFlushingVideo != SHUT_DOWN) {
1740 return;
1741 }
1742
1743 ALOGV("both audio and video are flushed now.");
1744
1745 mFlushingAudio = NONE;
1746 mFlushingVideo = NONE;
1747
1748 clearFlushComplete();
1749
1750 processDeferredActions();
1751}
1752
1753void NuPlayer2::postScanSources() {
1754 if (mScanSourcesPending) {
1755 return;
1756 }
1757
1758 sp<AMessage> msg = new AMessage(kWhatScanSources, this);
1759 msg->setInt32("generation", mScanSourcesGeneration);
1760 msg->post();
1761
1762 mScanSourcesPending = true;
1763}
1764
1765void NuPlayer2::tryOpenAudioSinkForOffload(
1766 const sp<AMessage> &format, const sp<MetaData> &audioMeta, bool hasVideo) {
1767 // Note: This is called early in NuPlayer2 to determine whether offloading
1768 // is possible; otherwise the decoders call the renderer openAudioSink directly.
1769
1770 status_t err = mRenderer->openAudioSink(
1771 format, true /* offloadOnly */, hasVideo,
1772 AUDIO_OUTPUT_FLAG_NONE, &mOffloadAudio, mSource->isStreaming());
1773 if (err != OK) {
1774 // Any failure we turn off mOffloadAudio.
1775 mOffloadAudio = false;
1776 } else if (mOffloadAudio) {
1777 sendMetaDataToHal(mAudioSink, audioMeta);
1778 }
1779}
1780
1781void NuPlayer2::closeAudioSink() {
1782 mRenderer->closeAudioSink();
1783}
1784
1785void NuPlayer2::restartAudio(
1786 int64_t currentPositionUs, bool forceNonOffload, bool needsToCreateAudioDecoder) {
1787 if (mAudioDecoder != NULL) {
1788 mAudioDecoder->pause();
1789 mAudioDecoder.clear();
1790 mAudioDecoderError = false;
1791 ++mAudioDecoderGeneration;
1792 }
1793 if (mFlushingAudio == FLUSHING_DECODER) {
1794 mFlushComplete[1 /* audio */][1 /* isDecoder */] = true;
1795 mFlushingAudio = FLUSHED;
1796 finishFlushIfPossible();
1797 } else if (mFlushingAudio == FLUSHING_DECODER_SHUTDOWN
1798 || mFlushingAudio == SHUTTING_DOWN_DECODER) {
1799 mFlushComplete[1 /* audio */][1 /* isDecoder */] = true;
1800 mFlushingAudio = SHUT_DOWN;
1801 finishFlushIfPossible();
1802 needsToCreateAudioDecoder = false;
1803 }
1804 if (mRenderer == NULL) {
1805 return;
1806 }
1807 closeAudioSink();
1808 mRenderer->flush(true /* audio */, false /* notifyComplete */);
1809 if (mVideoDecoder != NULL) {
1810 mRenderer->flush(false /* audio */, false /* notifyComplete */);
1811 }
1812
1813 performSeek(currentPositionUs, MediaPlayer2SeekMode::SEEK_PREVIOUS_SYNC /* mode */);
1814
1815 if (forceNonOffload) {
1816 mRenderer->signalDisableOffloadAudio();
1817 mOffloadAudio = false;
1818 }
1819 if (needsToCreateAudioDecoder) {
1820 instantiateDecoder(true /* audio */, &mAudioDecoder, !forceNonOffload);
1821 }
1822}
1823
1824void NuPlayer2::determineAudioModeChange(const sp<AMessage> &audioFormat) {
1825 if (mSource == NULL || mAudioSink == NULL) {
1826 return;
1827 }
1828
1829 if (mRenderer == NULL) {
1830 ALOGW("No renderer can be used to determine audio mode. Use non-offload for safety.");
1831 mOffloadAudio = false;
1832 return;
1833 }
1834
1835 sp<MetaData> audioMeta = mSource->getFormatMeta(true /* audio */);
1836 sp<AMessage> videoFormat = mSource->getFormat(false /* audio */);
1837 audio_stream_type_t streamType = mAudioSink->getAudioStreamType();
1838 const bool hasVideo = (videoFormat != NULL);
1839 bool canOffload = canOffloadStream(
1840 audioMeta, hasVideo, mSource->isStreaming(), streamType)
1841 && (mPlaybackSettings.mSpeed == 1.f && mPlaybackSettings.mPitch == 1.f);
1842
1843 // Modular DRM: Disabling audio offload if the source is protected
1844 if (canOffload && mIsDrmProtected) {
1845 canOffload = false;
1846 ALOGV("determineAudioModeChange: Disabling mOffloadAudio b/c the source is protected.");
1847 }
1848
1849 if (canOffload) {
1850 if (!mOffloadAudio) {
1851 mRenderer->signalEnableOffloadAudio();
1852 }
1853 // open audio sink early under offload mode.
1854 tryOpenAudioSinkForOffload(audioFormat, audioMeta, hasVideo);
1855 } else {
1856 if (mOffloadAudio) {
1857 mRenderer->signalDisableOffloadAudio();
1858 mOffloadAudio = false;
1859 }
1860 }
1861}
1862
1863status_t NuPlayer2::instantiateDecoder(
1864 bool audio, sp<DecoderBase> *decoder, bool checkAudioModeChange) {
1865 // The audio decoder could be cleared by tear down. If still in shut down
1866 // process, no need to create a new audio decoder.
1867 if (*decoder != NULL || (audio && mFlushingAudio == SHUT_DOWN)) {
1868 return OK;
1869 }
1870
1871 sp<AMessage> format = mSource->getFormat(audio);
1872
1873 if (format == NULL) {
1874 return UNKNOWN_ERROR;
1875 } else {
1876 status_t err;
1877 if (format->findInt32("err", &err) && err) {
1878 return err;
1879 }
1880 }
1881
1882 format->setInt32("priority", 0 /* realtime */);
1883
1884 if (!audio) {
1885 AString mime;
1886 CHECK(format->findString("mime", &mime));
1887
1888 sp<AMessage> ccNotify = new AMessage(kWhatClosedCaptionNotify, this);
1889 if (mCCDecoder == NULL) {
1890 mCCDecoder = new CCDecoder(ccNotify);
1891 }
1892
1893 if (mSourceFlags & Source::FLAG_SECURE) {
1894 format->setInt32("secure", true);
1895 }
1896
1897 if (mSourceFlags & Source::FLAG_PROTECTED) {
1898 format->setInt32("protected", true);
1899 }
1900
1901 float rate = getFrameRate();
1902 if (rate > 0) {
1903 format->setFloat("operating-rate", rate * mPlaybackSettings.mSpeed);
1904 }
1905 }
1906
1907 if (audio) {
1908 sp<AMessage> notify = new AMessage(kWhatAudioNotify, this);
1909 ++mAudioDecoderGeneration;
1910 notify->setInt32("generation", mAudioDecoderGeneration);
1911
1912 if (checkAudioModeChange) {
1913 determineAudioModeChange(format);
1914 }
1915 if (mOffloadAudio) {
1916 mSource->setOffloadAudio(true /* offload */);
1917
1918 const bool hasVideo = (mSource->getFormat(false /*audio */) != NULL);
1919 format->setInt32("has-video", hasVideo);
1920 *decoder = new DecoderPassThrough(notify, mSource, mRenderer);
1921 ALOGV("instantiateDecoder audio DecoderPassThrough hasVideo: %d", hasVideo);
1922 } else {
1923 mSource->setOffloadAudio(false /* offload */);
1924
1925 *decoder = new Decoder(notify, mSource, mPID, mUID, mRenderer);
1926 ALOGV("instantiateDecoder audio Decoder");
1927 }
1928 mAudioDecoderError = false;
1929 } else {
1930 sp<AMessage> notify = new AMessage(kWhatVideoNotify, this);
1931 ++mVideoDecoderGeneration;
1932 notify->setInt32("generation", mVideoDecoderGeneration);
1933
1934 *decoder = new Decoder(
Wei Jia28288fb2017-12-15 13:45:29 -08001935 notify, mSource, mPID, mUID, mRenderer, mNativeWindow, mCCDecoder);
Wei Jia53692fa2017-12-11 10:33:46 -08001936 mVideoDecoderError = false;
1937
1938 // enable FRC if high-quality AV sync is requested, even if not
1939 // directly queuing to display, as this will even improve textureview
1940 // playback.
1941 {
1942 if (property_get_bool("persist.sys.media.avsync", false)) {
1943 format->setInt32("auto-frc", 1);
1944 }
1945 }
1946 }
1947 (*decoder)->init();
1948
1949 // Modular DRM
1950 if (mIsDrmProtected) {
1951 format->setObject("crypto", mCrypto);
1952 ALOGV("instantiateDecoder: mCrypto: %p isSecure: %d", mCrypto.get(),
1953 (mSourceFlags & Source::FLAG_SECURE) != 0);
1954 }
1955
1956 (*decoder)->configure(format);
1957
1958 if (!audio) {
1959 sp<AMessage> params = new AMessage();
1960 float rate = getFrameRate();
1961 if (rate > 0) {
1962 params->setFloat("frame-rate-total", rate);
1963 }
1964
1965 sp<MetaData> fileMeta = getFileMeta();
1966 if (fileMeta != NULL) {
1967 int32_t videoTemporalLayerCount;
1968 if (fileMeta->findInt32(kKeyTemporalLayerCount, &videoTemporalLayerCount)
1969 && videoTemporalLayerCount > 0) {
1970 params->setInt32("temporal-layer-count", videoTemporalLayerCount);
1971 }
1972 }
1973
1974 if (params->countEntries() > 0) {
1975 (*decoder)->setParameters(params);
1976 }
1977 }
1978 return OK;
1979}
1980
1981void NuPlayer2::updateVideoSize(
1982 const sp<AMessage> &inputFormat,
1983 const sp<AMessage> &outputFormat) {
1984 if (inputFormat == NULL) {
1985 ALOGW("Unknown video size, reporting 0x0!");
1986 notifyListener(MEDIA2_SET_VIDEO_SIZE, 0, 0);
1987 return;
1988 }
1989 int32_t err = OK;
1990 inputFormat->findInt32("err", &err);
1991 if (err == -EWOULDBLOCK) {
1992 ALOGW("Video meta is not available yet!");
1993 return;
1994 }
1995 if (err != OK) {
1996 ALOGW("Something is wrong with video meta!");
1997 return;
1998 }
1999
2000 int32_t displayWidth, displayHeight;
2001 if (outputFormat != NULL) {
2002 int32_t width, height;
2003 CHECK(outputFormat->findInt32("width", &width));
2004 CHECK(outputFormat->findInt32("height", &height));
2005
2006 int32_t cropLeft, cropTop, cropRight, cropBottom;
2007 CHECK(outputFormat->findRect(
2008 "crop",
2009 &cropLeft, &cropTop, &cropRight, &cropBottom));
2010
2011 displayWidth = cropRight - cropLeft + 1;
2012 displayHeight = cropBottom - cropTop + 1;
2013
2014 ALOGV("Video output format changed to %d x %d "
2015 "(crop: %d x %d @ (%d, %d))",
2016 width, height,
2017 displayWidth,
2018 displayHeight,
2019 cropLeft, cropTop);
2020 } else {
2021 CHECK(inputFormat->findInt32("width", &displayWidth));
2022 CHECK(inputFormat->findInt32("height", &displayHeight));
2023
2024 ALOGV("Video input format %d x %d", displayWidth, displayHeight);
2025 }
2026
2027 // Take into account sample aspect ratio if necessary:
2028 int32_t sarWidth, sarHeight;
2029 if (inputFormat->findInt32("sar-width", &sarWidth)
2030 && inputFormat->findInt32("sar-height", &sarHeight)
2031 && sarWidth > 0 && sarHeight > 0) {
2032 ALOGV("Sample aspect ratio %d : %d", sarWidth, sarHeight);
2033
2034 displayWidth = (displayWidth * sarWidth) / sarHeight;
2035
2036 ALOGV("display dimensions %d x %d", displayWidth, displayHeight);
2037 } else {
2038 int32_t width, height;
2039 if (inputFormat->findInt32("display-width", &width)
2040 && inputFormat->findInt32("display-height", &height)
2041 && width > 0 && height > 0
2042 && displayWidth > 0 && displayHeight > 0) {
2043 if (displayHeight * (int64_t)width / height > (int64_t)displayWidth) {
2044 displayHeight = (int32_t)(displayWidth * (int64_t)height / width);
2045 } else {
2046 displayWidth = (int32_t)(displayHeight * (int64_t)width / height);
2047 }
2048 ALOGV("Video display width and height are overridden to %d x %d",
2049 displayWidth, displayHeight);
2050 }
2051 }
2052
2053 int32_t rotationDegrees;
2054 if (!inputFormat->findInt32("rotation-degrees", &rotationDegrees)) {
2055 rotationDegrees = 0;
2056 }
2057
2058 if (rotationDegrees == 90 || rotationDegrees == 270) {
2059 int32_t tmp = displayWidth;
2060 displayWidth = displayHeight;
2061 displayHeight = tmp;
2062 }
2063
2064 notifyListener(
2065 MEDIA2_SET_VIDEO_SIZE,
2066 displayWidth,
2067 displayHeight);
2068}
2069
2070void NuPlayer2::notifyListener(int msg, int ext1, int ext2, const Parcel *in) {
2071 if (mDriver == NULL) {
2072 return;
2073 }
2074
2075 sp<NuPlayer2Driver> driver = mDriver.promote();
2076
2077 if (driver == NULL) {
2078 return;
2079 }
2080
2081 driver->notifyListener(msg, ext1, ext2, in);
2082}
2083
2084void NuPlayer2::flushDecoder(bool audio, bool needShutdown) {
2085 ALOGV("[%s] flushDecoder needShutdown=%d",
2086 audio ? "audio" : "video", needShutdown);
2087
2088 const sp<DecoderBase> &decoder = getDecoder(audio);
2089 if (decoder == NULL) {
2090 ALOGI("flushDecoder %s without decoder present",
2091 audio ? "audio" : "video");
2092 return;
2093 }
2094
2095 // Make sure we don't continue to scan sources until we finish flushing.
2096 ++mScanSourcesGeneration;
2097 if (mScanSourcesPending) {
2098 if (!needShutdown) {
2099 mDeferredActions.push_back(
2100 new SimpleAction(&NuPlayer2::performScanSources));
2101 }
2102 mScanSourcesPending = false;
2103 }
2104
2105 decoder->signalFlush();
2106
2107 FlushStatus newStatus =
2108 needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
2109
2110 mFlushComplete[audio][false /* isDecoder */] = (mRenderer == NULL);
2111 mFlushComplete[audio][true /* isDecoder */] = false;
2112 if (audio) {
2113 ALOGE_IF(mFlushingAudio != NONE,
2114 "audio flushDecoder() is called in state %d", mFlushingAudio);
2115 mFlushingAudio = newStatus;
2116 } else {
2117 ALOGE_IF(mFlushingVideo != NONE,
2118 "video flushDecoder() is called in state %d", mFlushingVideo);
2119 mFlushingVideo = newStatus;
2120 }
2121}
2122
2123void NuPlayer2::queueDecoderShutdown(
2124 bool audio, bool video, const sp<AMessage> &reply) {
2125 ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video);
2126
2127 mDeferredActions.push_back(
2128 new FlushDecoderAction(
2129 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
2130 video ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE));
2131
2132 mDeferredActions.push_back(
2133 new SimpleAction(&NuPlayer2::performScanSources));
2134
2135 mDeferredActions.push_back(new PostMessageAction(reply));
2136
2137 processDeferredActions();
2138}
2139
2140status_t NuPlayer2::setVideoScalingMode(int32_t mode) {
2141 mVideoScalingMode = mode;
Wei Jia28288fb2017-12-15 13:45:29 -08002142 if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
2143 status_t ret = native_window_set_scaling_mode(
2144 mNativeWindow->getANativeWindow(), mVideoScalingMode);
Wei Jia53692fa2017-12-11 10:33:46 -08002145 if (ret != OK) {
2146 ALOGE("Failed to set scaling mode (%d): %s",
2147 -ret, strerror(-ret));
2148 return ret;
2149 }
2150 }
2151 return OK;
2152}
2153
2154status_t NuPlayer2::getTrackInfo(Parcel* reply) const {
2155 sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, this);
2156 msg->setPointer("reply", reply);
2157
2158 sp<AMessage> response;
2159 status_t err = msg->postAndAwaitResponse(&response);
2160 return err;
2161}
2162
2163status_t NuPlayer2::getSelectedTrack(int32_t type, Parcel* reply) const {
2164 sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, this);
2165 msg->setPointer("reply", reply);
2166 msg->setInt32("type", type);
2167
2168 sp<AMessage> response;
2169 status_t err = msg->postAndAwaitResponse(&response);
2170 if (err == OK && response != NULL) {
2171 CHECK(response->findInt32("err", &err));
2172 }
2173 return err;
2174}
2175
2176status_t NuPlayer2::selectTrack(size_t trackIndex, bool select, int64_t timeUs) {
2177 sp<AMessage> msg = new AMessage(kWhatSelectTrack, this);
2178 msg->setSize("trackIndex", trackIndex);
2179 msg->setInt32("select", select);
2180 msg->setInt64("timeUs", timeUs);
2181
2182 sp<AMessage> response;
2183 status_t err = msg->postAndAwaitResponse(&response);
2184
2185 if (err != OK) {
2186 return err;
2187 }
2188
2189 if (!response->findInt32("err", &err)) {
2190 err = OK;
2191 }
2192
2193 return err;
2194}
2195
2196status_t NuPlayer2::getCurrentPosition(int64_t *mediaUs) {
2197 sp<Renderer> renderer = mRenderer;
2198 if (renderer == NULL) {
2199 return NO_INIT;
2200 }
2201
2202 return renderer->getCurrentPosition(mediaUs);
2203}
2204
2205void NuPlayer2::getStats(Vector<sp<AMessage> > *mTrackStats) {
2206 CHECK(mTrackStats != NULL);
2207
2208 mTrackStats->clear();
2209 if (mVideoDecoder != NULL) {
2210 mTrackStats->push_back(mVideoDecoder->getStats());
2211 }
2212 if (mAudioDecoder != NULL) {
2213 mTrackStats->push_back(mAudioDecoder->getStats());
2214 }
2215}
2216
2217sp<MetaData> NuPlayer2::getFileMeta() {
2218 return mSource->getFileFormatMeta();
2219}
2220
2221float NuPlayer2::getFrameRate() {
2222 sp<MetaData> meta = mSource->getFormatMeta(false /* audio */);
2223 if (meta == NULL) {
2224 return 0;
2225 }
2226 int32_t rate;
2227 if (!meta->findInt32(kKeyFrameRate, &rate)) {
2228 // fall back to try file meta
2229 sp<MetaData> fileMeta = getFileMeta();
2230 if (fileMeta == NULL) {
2231 ALOGW("source has video meta but not file meta");
2232 return -1;
2233 }
2234 int32_t fileMetaRate;
2235 if (!fileMeta->findInt32(kKeyFrameRate, &fileMetaRate)) {
2236 return -1;
2237 }
2238 return fileMetaRate;
2239 }
2240 return rate;
2241}
2242
2243void NuPlayer2::schedulePollDuration() {
2244 sp<AMessage> msg = new AMessage(kWhatPollDuration, this);
2245 msg->setInt32("generation", mPollDurationGeneration);
2246 msg->post();
2247}
2248
2249void NuPlayer2::cancelPollDuration() {
2250 ++mPollDurationGeneration;
2251}
2252
2253void NuPlayer2::processDeferredActions() {
2254 while (!mDeferredActions.empty()) {
2255 // We won't execute any deferred actions until we're no longer in
2256 // an intermediate state, i.e. one more more decoders are currently
2257 // flushing or shutting down.
2258
2259 if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
2260 // We're currently flushing, postpone the reset until that's
2261 // completed.
2262
2263 ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
2264 mFlushingAudio, mFlushingVideo);
2265
2266 break;
2267 }
2268
2269 sp<Action> action = *mDeferredActions.begin();
2270 mDeferredActions.erase(mDeferredActions.begin());
2271
2272 action->execute(this);
2273 }
2274}
2275
2276void NuPlayer2::performSeek(int64_t seekTimeUs, MediaPlayer2SeekMode mode) {
2277 ALOGV("performSeek seekTimeUs=%lld us (%.2f secs), mode=%d",
2278 (long long)seekTimeUs, seekTimeUs / 1E6, mode);
2279
2280 if (mSource == NULL) {
2281 // This happens when reset occurs right before the loop mode
2282 // asynchronously seeks to the start of the stream.
2283 LOG_ALWAYS_FATAL_IF(mAudioDecoder != NULL || mVideoDecoder != NULL,
2284 "mSource is NULL and decoders not NULL audio(%p) video(%p)",
2285 mAudioDecoder.get(), mVideoDecoder.get());
2286 return;
2287 }
2288 mPreviousSeekTimeUs = seekTimeUs;
2289 mSource->seekTo(seekTimeUs, mode);
2290 ++mTimedTextGeneration;
2291
2292 // everything's flushed, continue playback.
2293}
2294
2295void NuPlayer2::performDecoderFlush(FlushCommand audio, FlushCommand video) {
2296 ALOGV("performDecoderFlush audio=%d, video=%d", audio, video);
2297
2298 if ((audio == FLUSH_CMD_NONE || mAudioDecoder == NULL)
2299 && (video == FLUSH_CMD_NONE || mVideoDecoder == NULL)) {
2300 return;
2301 }
2302
2303 if (audio != FLUSH_CMD_NONE && mAudioDecoder != NULL) {
2304 flushDecoder(true /* audio */, (audio == FLUSH_CMD_SHUTDOWN));
2305 }
2306
2307 if (video != FLUSH_CMD_NONE && mVideoDecoder != NULL) {
2308 flushDecoder(false /* audio */, (video == FLUSH_CMD_SHUTDOWN));
2309 }
2310}
2311
2312void NuPlayer2::performReset() {
2313 ALOGV("performReset");
2314
2315 CHECK(mAudioDecoder == NULL);
2316 CHECK(mVideoDecoder == NULL);
2317
2318 stopPlaybackTimer("performReset");
2319 stopRebufferingTimer(true);
2320
2321 cancelPollDuration();
2322
2323 ++mScanSourcesGeneration;
2324 mScanSourcesPending = false;
2325
2326 if (mRendererLooper != NULL) {
2327 if (mRenderer != NULL) {
2328 mRendererLooper->unregisterHandler(mRenderer->id());
2329 }
2330 mRendererLooper->stop();
2331 mRendererLooper.clear();
2332 }
2333 mRenderer.clear();
2334 ++mRendererGeneration;
2335
2336 if (mSource != NULL) {
2337 mSource->stop();
2338
2339 Mutex::Autolock autoLock(mSourceLock);
2340 mSource.clear();
2341 }
2342
2343 if (mDriver != NULL) {
2344 sp<NuPlayer2Driver> driver = mDriver.promote();
2345 if (driver != NULL) {
2346 driver->notifyResetComplete();
2347 }
2348 }
2349
2350 mStarted = false;
2351 mPrepared = false;
2352 mResetting = false;
2353 mSourceStarted = false;
2354
2355 // Modular DRM
2356 if (mCrypto != NULL) {
2357 // decoders will be flushed before this so their mCrypto would go away on their own
2358 // TODO change to ALOGV
2359 ALOGD("performReset mCrypto: %p", mCrypto.get());
2360 mCrypto.clear();
2361 }
2362 mIsDrmProtected = false;
2363}
2364
2365void NuPlayer2::performScanSources() {
2366 ALOGV("performScanSources");
2367
2368 if (!mStarted) {
2369 return;
2370 }
2371
2372 if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
2373 postScanSources();
2374 }
2375}
2376
Wei Jia28288fb2017-12-15 13:45:29 -08002377void NuPlayer2::performSetSurface(const sp<ANativeWindowWrapper> &nww) {
Wei Jia53692fa2017-12-11 10:33:46 -08002378 ALOGV("performSetSurface");
2379
Wei Jia28288fb2017-12-15 13:45:29 -08002380 mNativeWindow = nww;
Wei Jia53692fa2017-12-11 10:33:46 -08002381
2382 // XXX - ignore error from setVideoScalingMode for now
2383 setVideoScalingMode(mVideoScalingMode);
2384
2385 if (mDriver != NULL) {
2386 sp<NuPlayer2Driver> driver = mDriver.promote();
2387 if (driver != NULL) {
2388 driver->notifySetSurfaceComplete();
2389 }
2390 }
2391}
2392
2393void NuPlayer2::performResumeDecoders(bool needNotify) {
2394 if (needNotify) {
2395 mResumePending = true;
2396 if (mVideoDecoder == NULL) {
2397 // if audio-only, we can notify seek complete now,
2398 // as the resume operation will be relatively fast.
2399 finishResume();
2400 }
2401 }
2402
2403 if (mVideoDecoder != NULL) {
2404 // When there is continuous seek, MediaPlayer will cache the seek
2405 // position, and send down new seek request when previous seek is
2406 // complete. Let's wait for at least one video output frame before
2407 // notifying seek complete, so that the video thumbnail gets updated
2408 // when seekbar is dragged.
2409 mVideoDecoder->signalResume(needNotify);
2410 }
2411
2412 if (mAudioDecoder != NULL) {
2413 mAudioDecoder->signalResume(false /* needNotify */);
2414 }
2415}
2416
2417void NuPlayer2::finishResume() {
2418 if (mResumePending) {
2419 mResumePending = false;
2420 notifyDriverSeekComplete();
2421 }
2422}
2423
2424void NuPlayer2::notifyDriverSeekComplete() {
2425 if (mDriver != NULL) {
2426 sp<NuPlayer2Driver> driver = mDriver.promote();
2427 if (driver != NULL) {
2428 driver->notifySeekComplete();
2429 }
2430 }
2431}
2432
2433void NuPlayer2::onSourceNotify(const sp<AMessage> &msg) {
2434 int32_t what;
2435 CHECK(msg->findInt32("what", &what));
2436
2437 switch (what) {
2438 case Source::kWhatInstantiateSecureDecoders:
2439 {
2440 if (mSource == NULL) {
2441 // This is a stale notification from a source that was
2442 // asynchronously preparing when the client called reset().
2443 // We handled the reset, the source is gone.
2444 break;
2445 }
2446
2447 sp<AMessage> reply;
2448 CHECK(msg->findMessage("reply", &reply));
2449 status_t err = onInstantiateSecureDecoders();
2450 reply->setInt32("err", err);
2451 reply->post();
2452 break;
2453 }
2454
2455 case Source::kWhatPrepared:
2456 {
2457 ALOGV("NuPlayer2::onSourceNotify Source::kWhatPrepared source: %p", mSource.get());
2458 if (mSource == NULL) {
2459 // This is a stale notification from a source that was
2460 // asynchronously preparing when the client called reset().
2461 // We handled the reset, the source is gone.
2462 break;
2463 }
2464
2465 int32_t err;
2466 CHECK(msg->findInt32("err", &err));
2467
2468 if (err != OK) {
2469 // shut down potential secure codecs in case client never calls reset
2470 mDeferredActions.push_back(
2471 new FlushDecoderAction(FLUSH_CMD_SHUTDOWN /* audio */,
2472 FLUSH_CMD_SHUTDOWN /* video */));
2473 processDeferredActions();
2474 } else {
2475 mPrepared = true;
2476 }
2477
2478 sp<NuPlayer2Driver> driver = mDriver.promote();
2479 if (driver != NULL) {
2480 // notify duration first, so that it's definitely set when
2481 // the app received the "prepare complete" callback.
2482 int64_t durationUs;
2483 if (mSource->getDuration(&durationUs) == OK) {
2484 driver->notifyDuration(durationUs);
2485 }
2486 driver->notifyPrepareCompleted(err);
2487 }
2488
2489 break;
2490 }
2491
2492 // Modular DRM
2493 case Source::kWhatDrmInfo:
2494 {
2495 Parcel parcel;
2496 sp<ABuffer> drmInfo;
2497 CHECK(msg->findBuffer("drmInfo", &drmInfo));
2498 parcel.setData(drmInfo->data(), drmInfo->size());
2499
2500 ALOGV("onSourceNotify() kWhatDrmInfo MEDIA2_DRM_INFO drmInfo: %p parcel size: %zu",
2501 drmInfo.get(), parcel.dataSize());
2502
2503 notifyListener(MEDIA2_DRM_INFO, 0 /* ext1 */, 0 /* ext2 */, &parcel);
2504
2505 break;
2506 }
2507
2508 case Source::kWhatFlagsChanged:
2509 {
2510 uint32_t flags;
2511 CHECK(msg->findInt32("flags", (int32_t *)&flags));
2512
2513 sp<NuPlayer2Driver> driver = mDriver.promote();
2514 if (driver != NULL) {
2515
2516 ALOGV("onSourceNotify() kWhatFlagsChanged FLAG_CAN_PAUSE: %d "
2517 "FLAG_CAN_SEEK_BACKWARD: %d \n\t\t\t\t FLAG_CAN_SEEK_FORWARD: %d "
2518 "FLAG_CAN_SEEK: %d FLAG_DYNAMIC_DURATION: %d \n"
2519 "\t\t\t\t FLAG_SECURE: %d FLAG_PROTECTED: %d",
2520 (flags & Source::FLAG_CAN_PAUSE) != 0,
2521 (flags & Source::FLAG_CAN_SEEK_BACKWARD) != 0,
2522 (flags & Source::FLAG_CAN_SEEK_FORWARD) != 0,
2523 (flags & Source::FLAG_CAN_SEEK) != 0,
2524 (flags & Source::FLAG_DYNAMIC_DURATION) != 0,
2525 (flags & Source::FLAG_SECURE) != 0,
2526 (flags & Source::FLAG_PROTECTED) != 0);
2527
2528 if ((flags & NuPlayer2::Source::FLAG_CAN_SEEK) == 0) {
2529 driver->notifyListener(
2530 MEDIA2_INFO, MEDIA2_INFO_NOT_SEEKABLE, 0);
2531 }
2532 driver->notifyFlagsChanged(flags);
2533 }
2534
2535 if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
2536 && (!(flags & Source::FLAG_DYNAMIC_DURATION))) {
2537 cancelPollDuration();
2538 } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
2539 && (flags & Source::FLAG_DYNAMIC_DURATION)
2540 && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
2541 schedulePollDuration();
2542 }
2543
2544 mSourceFlags = flags;
2545 break;
2546 }
2547
2548 case Source::kWhatVideoSizeChanged:
2549 {
2550 sp<AMessage> format;
2551 CHECK(msg->findMessage("format", &format));
2552
2553 updateVideoSize(format);
2554 break;
2555 }
2556
2557 case Source::kWhatBufferingUpdate:
2558 {
2559 int32_t percentage;
2560 CHECK(msg->findInt32("percentage", &percentage));
2561
2562 notifyListener(MEDIA2_BUFFERING_UPDATE, percentage, 0);
2563 break;
2564 }
2565
2566 case Source::kWhatPauseOnBufferingStart:
2567 {
2568 // ignore if not playing
2569 if (mStarted) {
2570 ALOGI("buffer low, pausing...");
2571
2572 startRebufferingTimer();
2573 mPausedForBuffering = true;
2574 onPause();
2575 }
2576 notifyListener(MEDIA2_INFO, MEDIA2_INFO_BUFFERING_START, 0);
2577 break;
2578 }
2579
2580 case Source::kWhatResumeOnBufferingEnd:
2581 {
2582 // ignore if not playing
2583 if (mStarted) {
2584 ALOGI("buffer ready, resuming...");
2585
2586 stopRebufferingTimer(false);
2587 mPausedForBuffering = false;
2588
2589 // do not resume yet if client didn't unpause
2590 if (!mPausedByClient) {
2591 onResume();
2592 }
2593 }
2594 notifyListener(MEDIA2_INFO, MEDIA2_INFO_BUFFERING_END, 0);
2595 break;
2596 }
2597
2598 case Source::kWhatCacheStats:
2599 {
2600 int32_t kbps;
2601 CHECK(msg->findInt32("bandwidth", &kbps));
2602
2603 notifyListener(MEDIA2_INFO, MEDIA2_INFO_NETWORK_BANDWIDTH, kbps);
2604 break;
2605 }
2606
2607 case Source::kWhatSubtitleData:
2608 {
2609 sp<ABuffer> buffer;
2610 CHECK(msg->findBuffer("buffer", &buffer));
2611
2612 sendSubtitleData(buffer, 0 /* baseIndex */);
2613 break;
2614 }
2615
2616 case Source::kWhatTimedMetaData:
2617 {
2618 sp<ABuffer> buffer;
2619 if (!msg->findBuffer("buffer", &buffer)) {
2620 notifyListener(MEDIA2_INFO, MEDIA2_INFO_METADATA_UPDATE, 0);
2621 } else {
2622 sendTimedMetaData(buffer);
2623 }
2624 break;
2625 }
2626
2627 case Source::kWhatTimedTextData:
2628 {
2629 int32_t generation;
2630 if (msg->findInt32("generation", &generation)
2631 && generation != mTimedTextGeneration) {
2632 break;
2633 }
2634
2635 sp<ABuffer> buffer;
2636 CHECK(msg->findBuffer("buffer", &buffer));
2637
2638 sp<NuPlayer2Driver> driver = mDriver.promote();
2639 if (driver == NULL) {
2640 break;
2641 }
2642
2643 int posMs;
2644 int64_t timeUs, posUs;
2645 driver->getCurrentPosition(&posMs);
2646 posUs = (int64_t) posMs * 1000ll;
2647 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2648
2649 if (posUs < timeUs) {
2650 if (!msg->findInt32("generation", &generation)) {
2651 msg->setInt32("generation", mTimedTextGeneration);
2652 }
2653 msg->post(timeUs - posUs);
2654 } else {
2655 sendTimedTextData(buffer);
2656 }
2657 break;
2658 }
2659
2660 case Source::kWhatQueueDecoderShutdown:
2661 {
2662 int32_t audio, video;
2663 CHECK(msg->findInt32("audio", &audio));
2664 CHECK(msg->findInt32("video", &video));
2665
2666 sp<AMessage> reply;
2667 CHECK(msg->findMessage("reply", &reply));
2668
2669 queueDecoderShutdown(audio, video, reply);
2670 break;
2671 }
2672
2673 case Source::kWhatDrmNoLicense:
2674 {
2675 notifyListener(MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
2676 break;
2677 }
2678
2679 default:
2680 TRESPASS();
2681 }
2682}
2683
2684void NuPlayer2::onClosedCaptionNotify(const sp<AMessage> &msg) {
2685 int32_t what;
2686 CHECK(msg->findInt32("what", &what));
2687
2688 switch (what) {
2689 case NuPlayer2::CCDecoder::kWhatClosedCaptionData:
2690 {
2691 sp<ABuffer> buffer;
2692 CHECK(msg->findBuffer("buffer", &buffer));
2693
2694 size_t inbandTracks = 0;
2695 if (mSource != NULL) {
2696 inbandTracks = mSource->getTrackCount();
2697 }
2698
2699 sendSubtitleData(buffer, inbandTracks);
2700 break;
2701 }
2702
2703 case NuPlayer2::CCDecoder::kWhatTrackAdded:
2704 {
2705 notifyListener(MEDIA2_INFO, MEDIA2_INFO_METADATA_UPDATE, 0);
2706
2707 break;
2708 }
2709
2710 default:
2711 TRESPASS();
2712 }
2713
2714
2715}
2716
2717void NuPlayer2::sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex) {
2718 int32_t trackIndex;
2719 int64_t timeUs, durationUs;
2720 CHECK(buffer->meta()->findInt32("trackIndex", &trackIndex));
2721 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2722 CHECK(buffer->meta()->findInt64("durationUs", &durationUs));
2723
2724 Parcel in;
2725 in.writeInt32(trackIndex + baseIndex);
2726 in.writeInt64(timeUs);
2727 in.writeInt64(durationUs);
2728 in.writeInt32(buffer->size());
2729 in.writeInt32(buffer->size());
2730 in.write(buffer->data(), buffer->size());
2731
2732 notifyListener(MEDIA2_SUBTITLE_DATA, 0, 0, &in);
2733}
2734
2735void NuPlayer2::sendTimedMetaData(const sp<ABuffer> &buffer) {
2736 int64_t timeUs;
2737 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2738
2739 Parcel in;
2740 in.writeInt64(timeUs);
2741 in.writeInt32(buffer->size());
2742 in.writeInt32(buffer->size());
2743 in.write(buffer->data(), buffer->size());
2744
2745 notifyListener(MEDIA2_META_DATA, 0, 0, &in);
2746}
2747
2748void NuPlayer2::sendTimedTextData(const sp<ABuffer> &buffer) {
2749 const void *data;
2750 size_t size = 0;
2751 int64_t timeUs;
2752 int32_t flag = TextDescriptions::IN_BAND_TEXT_3GPP;
2753
2754 AString mime;
2755 CHECK(buffer->meta()->findString("mime", &mime));
2756 CHECK(strcasecmp(mime.c_str(), MEDIA_MIMETYPE_TEXT_3GPP) == 0);
2757
2758 data = buffer->data();
2759 size = buffer->size();
2760
2761 Parcel parcel;
2762 if (size > 0) {
2763 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2764 int32_t global = 0;
2765 if (buffer->meta()->findInt32("global", &global) && global) {
2766 flag |= TextDescriptions::GLOBAL_DESCRIPTIONS;
2767 } else {
2768 flag |= TextDescriptions::LOCAL_DESCRIPTIONS;
2769 }
2770 TextDescriptions::getParcelOfDescriptions(
2771 (const uint8_t *)data, size, flag, timeUs / 1000, &parcel);
2772 }
2773
2774 if ((parcel.dataSize() > 0)) {
2775 notifyListener(MEDIA2_TIMED_TEXT, 0, 0, &parcel);
2776 } else { // send an empty timed text
2777 notifyListener(MEDIA2_TIMED_TEXT, 0, 0);
2778 }
2779}
2780
2781const char *NuPlayer2::getDataSourceType() {
2782 switch (mDataSourceType) {
2783 case DATA_SOURCE_TYPE_HTTP_LIVE:
2784 return "HTTPLive";
2785
2786 case DATA_SOURCE_TYPE_RTSP:
2787 return "RTSP";
2788
2789 case DATA_SOURCE_TYPE_GENERIC_URL:
2790 return "GenURL";
2791
2792 case DATA_SOURCE_TYPE_GENERIC_FD:
2793 return "GenFD";
2794
2795 case DATA_SOURCE_TYPE_MEDIA:
2796 return "Media";
2797
2798 case DATA_SOURCE_TYPE_STREAM:
2799 return "Stream";
2800
2801 case DATA_SOURCE_TYPE_NONE:
2802 default:
2803 return "None";
2804 }
2805 }
2806
2807// Modular DRM begin
2808status_t NuPlayer2::prepareDrm(const uint8_t uuid[16], const Vector<uint8_t> &drmSessionId)
2809{
2810 ALOGV("prepareDrm ");
2811
2812 // Passing to the looper anyway; called in a pre-config prepared state so no race on mCrypto
2813 sp<AMessage> msg = new AMessage(kWhatPrepareDrm, this);
2814 // synchronous call so just passing the address but with local copies of "const" args
2815 uint8_t UUID[16];
2816 memcpy(UUID, uuid, sizeof(UUID));
2817 Vector<uint8_t> sessionId = drmSessionId;
2818 msg->setPointer("uuid", (void*)UUID);
2819 msg->setPointer("drmSessionId", (void*)&sessionId);
2820
2821 sp<AMessage> response;
2822 status_t status = msg->postAndAwaitResponse(&response);
2823
2824 if (status == OK && response != NULL) {
2825 CHECK(response->findInt32("status", &status));
2826 ALOGV("prepareDrm ret: %d ", status);
2827 } else {
2828 ALOGE("prepareDrm err: %d", status);
2829 }
2830
2831 return status;
2832}
2833
2834status_t NuPlayer2::releaseDrm()
2835{
2836 ALOGV("releaseDrm ");
2837
2838 sp<AMessage> msg = new AMessage(kWhatReleaseDrm, this);
2839
2840 sp<AMessage> response;
2841 status_t status = msg->postAndAwaitResponse(&response);
2842
2843 if (status == OK && response != NULL) {
2844 CHECK(response->findInt32("status", &status));
2845 ALOGV("releaseDrm ret: %d ", status);
2846 } else {
2847 ALOGE("releaseDrm err: %d", status);
2848 }
2849
2850 return status;
2851}
2852
2853status_t NuPlayer2::onPrepareDrm(const sp<AMessage> &msg)
2854{
2855 // TODO change to ALOGV
2856 ALOGD("onPrepareDrm ");
2857
2858 status_t status = INVALID_OPERATION;
2859 if (mSource == NULL) {
2860 ALOGE("onPrepareDrm: No source. onPrepareDrm failed with %d.", status);
2861 return status;
2862 }
2863
2864 uint8_t *uuid;
2865 Vector<uint8_t> *drmSessionId;
2866 CHECK(msg->findPointer("uuid", (void**)&uuid));
2867 CHECK(msg->findPointer("drmSessionId", (void**)&drmSessionId));
2868
2869 status = OK;
2870 sp<AMediaCryptoWrapper> crypto = NULL;
2871
2872 status = mSource->prepareDrm(uuid, *drmSessionId, &crypto);
2873 if (crypto == NULL) {
2874 ALOGE("onPrepareDrm: mSource->prepareDrm failed. status: %d", status);
2875 return status;
2876 }
2877 ALOGV("onPrepareDrm: mSource->prepareDrm succeeded");
2878
2879 if (mCrypto != NULL) {
2880 ALOGE("onPrepareDrm: Unexpected. Already having mCrypto: %p", mCrypto.get());
2881 mCrypto.clear();
2882 }
2883
2884 mCrypto = crypto;
2885 mIsDrmProtected = true;
2886 // TODO change to ALOGV
2887 ALOGD("onPrepareDrm: mCrypto: %p", mCrypto.get());
2888
2889 return status;
2890}
2891
2892status_t NuPlayer2::onReleaseDrm()
2893{
2894 // TODO change to ALOGV
2895 ALOGD("onReleaseDrm ");
2896
2897 if (!mIsDrmProtected) {
2898 ALOGW("onReleaseDrm: Unexpected. mIsDrmProtected is already false.");
2899 }
2900
2901 mIsDrmProtected = false;
2902
2903 status_t status;
2904 if (mCrypto != NULL) {
2905 // notifying the source first before removing crypto from codec
2906 if (mSource != NULL) {
2907 mSource->releaseDrm();
2908 }
2909
2910 status=OK;
2911 // first making sure the codecs have released their crypto reference
2912 const sp<DecoderBase> &videoDecoder = getDecoder(false/*audio*/);
2913 if (videoDecoder != NULL) {
2914 status = videoDecoder->releaseCrypto();
2915 ALOGV("onReleaseDrm: video decoder ret: %d", status);
2916 }
2917
2918 const sp<DecoderBase> &audioDecoder = getDecoder(true/*audio*/);
2919 if (audioDecoder != NULL) {
2920 status_t status_audio = audioDecoder->releaseCrypto();
2921 if (status == OK) { // otherwise, returning the first error
2922 status = status_audio;
2923 }
2924 ALOGV("onReleaseDrm: audio decoder ret: %d", status_audio);
2925 }
2926
2927 // TODO change to ALOGV
2928 ALOGD("onReleaseDrm: mCrypto: %p", mCrypto.get());
2929 mCrypto.clear();
2930 } else { // mCrypto == NULL
2931 ALOGE("onReleaseDrm: Unexpected. There is no crypto.");
2932 status = INVALID_OPERATION;
2933 }
2934
2935 return status;
2936}
2937// Modular DRM end
2938////////////////////////////////////////////////////////////////////////////////
2939
2940sp<AMessage> NuPlayer2::Source::getFormat(bool audio) {
2941 sp<MetaData> meta = getFormatMeta(audio);
2942
2943 if (meta == NULL) {
2944 return NULL;
2945 }
2946
2947 sp<AMessage> msg = new AMessage;
2948
2949 if(convertMetaDataToMessage(meta, &msg) == OK) {
2950 return msg;
2951 }
2952 return NULL;
2953}
2954
2955void NuPlayer2::Source::notifyFlagsChanged(uint32_t flags) {
2956 sp<AMessage> notify = dupNotify();
2957 notify->setInt32("what", kWhatFlagsChanged);
2958 notify->setInt32("flags", flags);
2959 notify->post();
2960}
2961
2962void NuPlayer2::Source::notifyVideoSizeChanged(const sp<AMessage> &format) {
2963 sp<AMessage> notify = dupNotify();
2964 notify->setInt32("what", kWhatVideoSizeChanged);
2965 notify->setMessage("format", format);
2966 notify->post();
2967}
2968
2969void NuPlayer2::Source::notifyPrepared(status_t err) {
2970 ALOGV("Source::notifyPrepared %d", err);
2971 sp<AMessage> notify = dupNotify();
2972 notify->setInt32("what", kWhatPrepared);
2973 notify->setInt32("err", err);
2974 notify->post();
2975}
2976
2977void NuPlayer2::Source::notifyDrmInfo(const sp<ABuffer> &drmInfoBuffer)
2978{
2979 ALOGV("Source::notifyDrmInfo");
2980
2981 sp<AMessage> notify = dupNotify();
2982 notify->setInt32("what", kWhatDrmInfo);
2983 notify->setBuffer("drmInfo", drmInfoBuffer);
2984
2985 notify->post();
2986}
2987
2988void NuPlayer2::Source::notifyInstantiateSecureDecoders(const sp<AMessage> &reply) {
2989 sp<AMessage> notify = dupNotify();
2990 notify->setInt32("what", kWhatInstantiateSecureDecoders);
2991 notify->setMessage("reply", reply);
2992 notify->post();
2993}
2994
2995void NuPlayer2::Source::onMessageReceived(const sp<AMessage> & /* msg */) {
2996 TRESPASS();
2997}
2998
2999} // namespace android