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