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