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