blob: 2f90825061871bc8758425d34e82d9f053b965b9 [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"
Dongwon Kanga0e816a2018-09-10 19:46:49 -070036#include "TextDescriptions2.h"
Wei Jia53692fa2017-12-11 10:33:46 -080037
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
Wei Jia57aeffd2018-02-15 16:01:14 -0800426void NuPlayer2::playNextDataSource(int64_t srcId) {
427 disconnectSource();
428
429 sp<AMessage> msg = new AMessage(kWhatPlayNextDataSource, this);
430 msg->setInt64("srcId", srcId);
431 msg->post();
432}
433
Wei Jia53692fa2017-12-11 10:33:46 -0800434status_t NuPlayer2::getBufferingSettings(
435 BufferingSettings *buffering /* nonnull */) {
436 sp<AMessage> msg = new AMessage(kWhatGetBufferingSettings, this);
437 sp<AMessage> response;
438 status_t err = msg->postAndAwaitResponse(&response);
439 if (err == OK && response != NULL) {
440 CHECK(response->findInt32("err", &err));
441 if (err == OK) {
442 readFromAMessage(response, buffering);
443 }
444 }
445 return err;
446}
447
448status_t NuPlayer2::setBufferingSettings(const BufferingSettings& buffering) {
449 sp<AMessage> msg = new AMessage(kWhatSetBufferingSettings, this);
450 writeToAMessage(msg, buffering);
451 sp<AMessage> response;
452 status_t err = msg->postAndAwaitResponse(&response);
453 if (err == OK && response != NULL) {
454 CHECK(response->findInt32("err", &err));
455 }
456 return err;
457}
458
459void NuPlayer2::prepareAsync() {
460 ALOGV("prepareAsync");
461
462 (new AMessage(kWhatPrepare, this))->post();
463}
464
Wei Jia28288fb2017-12-15 13:45:29 -0800465void NuPlayer2::setVideoSurfaceTextureAsync(const sp<ANativeWindowWrapper> &nww) {
Wei Jia53692fa2017-12-11 10:33:46 -0800466 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
467
Wei Jia28288fb2017-12-15 13:45:29 -0800468 if (nww == NULL || nww->getANativeWindow() == NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -0800469 msg->setObject("surface", NULL);
470 } else {
Wei Jia28288fb2017-12-15 13:45:29 -0800471 msg->setObject("surface", nww);
Wei Jia53692fa2017-12-11 10:33:46 -0800472 }
473
474 msg->post();
475}
476
Wei Jia33abcc72018-01-30 09:47:38 -0800477void NuPlayer2::setAudioSink(const sp<MediaPlayer2Interface::AudioSink> &sink) {
Wei Jia53692fa2017-12-11 10:33:46 -0800478 sp<AMessage> msg = new AMessage(kWhatSetAudioSink, this);
479 msg->setObject("sink", sink);
480 msg->post();
481}
482
483void NuPlayer2::start() {
484 (new AMessage(kWhatStart, this))->post();
485}
486
487status_t NuPlayer2::setPlaybackSettings(const AudioPlaybackRate &rate) {
488 // do some cursory validation of the settings here. audio modes are
489 // only validated when set on the audiosink.
490 if ((rate.mSpeed != 0.f && rate.mSpeed < AUDIO_TIMESTRETCH_SPEED_MIN)
491 || rate.mSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
492 || rate.mPitch < AUDIO_TIMESTRETCH_SPEED_MIN
493 || rate.mPitch > AUDIO_TIMESTRETCH_SPEED_MAX) {
494 return BAD_VALUE;
495 }
496 sp<AMessage> msg = new AMessage(kWhatConfigPlayback, this);
497 writeToAMessage(msg, rate);
498 sp<AMessage> response;
499 status_t err = msg->postAndAwaitResponse(&response);
500 if (err == OK && response != NULL) {
501 CHECK(response->findInt32("err", &err));
502 }
503 return err;
504}
505
506status_t NuPlayer2::getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
507 sp<AMessage> msg = new AMessage(kWhatGetPlaybackSettings, this);
508 sp<AMessage> response;
509 status_t err = msg->postAndAwaitResponse(&response);
510 if (err == OK && response != NULL) {
511 CHECK(response->findInt32("err", &err));
512 if (err == OK) {
513 readFromAMessage(response, rate);
514 }
515 }
516 return err;
517}
518
519status_t NuPlayer2::setSyncSettings(const AVSyncSettings &sync, float videoFpsHint) {
520 sp<AMessage> msg = new AMessage(kWhatConfigSync, this);
521 writeToAMessage(msg, sync, videoFpsHint);
522 sp<AMessage> response;
523 status_t err = msg->postAndAwaitResponse(&response);
524 if (err == OK && response != NULL) {
525 CHECK(response->findInt32("err", &err));
526 }
527 return err;
528}
529
530status_t NuPlayer2::getSyncSettings(
531 AVSyncSettings *sync /* nonnull */, float *videoFps /* nonnull */) {
532 sp<AMessage> msg = new AMessage(kWhatGetSyncSettings, this);
533 sp<AMessage> response;
534 status_t err = msg->postAndAwaitResponse(&response);
535 if (err == OK && response != NULL) {
536 CHECK(response->findInt32("err", &err));
537 if (err == OK) {
538 readFromAMessage(response, sync, videoFps);
539 }
540 }
541 return err;
542}
543
544void NuPlayer2::pause() {
545 (new AMessage(kWhatPause, this))->post();
546}
547
548void NuPlayer2::resetAsync() {
Wei Jia57aeffd2018-02-15 16:01:14 -0800549 disconnectSource();
550 (new AMessage(kWhatReset, this))->post();
551}
552
553void NuPlayer2::disconnectSource() {
Wei Jia53692fa2017-12-11 10:33:46 -0800554 sp<Source> source;
555 {
556 Mutex::Autolock autoLock(mSourceLock);
557 source = mSource;
558 }
559
560 if (source != NULL) {
561 // During a reset, the data source might be unresponsive already, we need to
562 // disconnect explicitly so that reads exit promptly.
563 // We can't queue the disconnect request to the looper, as it might be
564 // queued behind a stuck read and never gets processed.
565 // Doing a disconnect outside the looper to allows the pending reads to exit
566 // (either successfully or with error).
567 source->disconnect();
568 }
569
Wei Jia53692fa2017-12-11 10:33:46 -0800570}
571
572status_t NuPlayer2::notifyAt(int64_t mediaTimeUs) {
573 sp<AMessage> notify = new AMessage(kWhatNotifyTime, this);
574 notify->setInt64("timerUs", mediaTimeUs);
575 mMediaClock->addTimer(notify, mediaTimeUs);
576 return OK;
577}
578
579void NuPlayer2::seekToAsync(int64_t seekTimeUs, MediaPlayer2SeekMode mode, bool needNotify) {
580 sp<AMessage> msg = new AMessage(kWhatSeek, this);
581 msg->setInt64("seekTimeUs", seekTimeUs);
582 msg->setInt32("mode", mode);
583 msg->setInt32("needNotify", needNotify);
584 msg->post();
585}
586
Wei Jia53692fa2017-12-11 10:33:46 -0800587void NuPlayer2::writeTrackInfo(
Dongwon Kang9f631982018-07-10 12:34:41 -0700588 PlayerMessage* reply, const sp<AMessage>& format) const {
Wei Jia53692fa2017-12-11 10:33:46 -0800589 if (format == NULL) {
590 ALOGE("NULL format");
591 return;
592 }
593 int32_t trackType;
594 if (!format->findInt32("type", &trackType)) {
595 ALOGE("no track type");
596 return;
597 }
598
599 AString mime;
600 if (!format->findString("mime", &mime)) {
601 // Java MediaPlayer only uses mimetype for subtitle and timedtext tracks.
602 // If we can't find the mimetype here it means that we wouldn't be needing
603 // the mimetype on the Java end. We still write a placeholder mime to keep the
604 // (de)serialization logic simple.
605 if (trackType == MEDIA_TRACK_TYPE_AUDIO) {
606 mime = "audio/";
607 } else if (trackType == MEDIA_TRACK_TYPE_VIDEO) {
608 mime = "video/";
609 } else {
610 ALOGE("unknown track type: %d", trackType);
611 return;
612 }
613 }
614
615 AString lang;
616 if (!format->findString("language", &lang)) {
617 ALOGE("no language");
618 return;
619 }
620
Dongwon Kang9f631982018-07-10 12:34:41 -0700621 reply->add_values()->set_int32_value(trackType);
622 reply->add_values()->set_string_value(mime.c_str());
623 reply->add_values()->set_string_value(lang.c_str());
Wei Jia53692fa2017-12-11 10:33:46 -0800624
625 if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
626 int32_t isAuto, isDefault, isForced;
627 CHECK(format->findInt32("auto", &isAuto));
628 CHECK(format->findInt32("default", &isDefault));
629 CHECK(format->findInt32("forced", &isForced));
630
Dongwon Kang9f631982018-07-10 12:34:41 -0700631 reply->add_values()->set_int32_value(isAuto);
632 reply->add_values()->set_int32_value(isDefault);
633 reply->add_values()->set_int32_value(isForced);
Wei Jia53692fa2017-12-11 10:33:46 -0800634 }
635}
636
637void NuPlayer2::onMessageReceived(const sp<AMessage> &msg) {
638 switch (msg->what()) {
639 case kWhatSetDataSource:
640 {
641 ALOGV("kWhatSetDataSource");
642
643 CHECK(mSource == NULL);
644
645 status_t err = OK;
646 sp<RefBase> obj;
647 CHECK(msg->findObject("source", &obj));
648 if (obj != NULL) {
649 Mutex::Autolock autoLock(mSourceLock);
Wei Jia72bf2a02018-02-06 15:29:23 -0800650 CHECK(msg->findInt64("srcId", &mSrcId));
Wei Jia53692fa2017-12-11 10:33:46 -0800651 mSource = static_cast<Source *>(obj.get());
652 } else {
653 err = UNKNOWN_ERROR;
Wei Jia083e9092018-02-12 11:46:04 -0800654 ALOGE("kWhatSetDataSource, source should not be NULL");
Wei Jia53692fa2017-12-11 10:33:46 -0800655 }
656
657 CHECK(mDriver != NULL);
658 sp<NuPlayer2Driver> driver = mDriver.promote();
659 if (driver != NULL) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -0800660 driver->notifySetDataSourceCompleted(mSrcId, err);
Wei Jia53692fa2017-12-11 10:33:46 -0800661 }
662 break;
663 }
664
Wei Jia72bf2a02018-02-06 15:29:23 -0800665 case kWhatPrepareNextDataSource:
666 {
667 ALOGV("kWhatPrepareNextDataSource");
668
669 status_t err = OK;
670 sp<RefBase> obj;
671 CHECK(msg->findObject("source", &obj));
672 if (obj != NULL) {
673 Mutex::Autolock autoLock(mSourceLock);
674 CHECK(msg->findInt64("srcId", &mNextSrcId));
675 mNextSource = static_cast<Source *>(obj.get());
676 mNextSource->prepareAsync();
677 } else {
678 err = UNKNOWN_ERROR;
679 }
680
681 break;
682 }
683
Wei Jia57aeffd2018-02-15 16:01:14 -0800684 case kWhatPlayNextDataSource:
685 {
686 ALOGV("kWhatPlayNextDataSource");
687 int64_t srcId;
688 CHECK(msg->findInt64("srcId", &srcId));
689 if (srcId != mNextSrcId) {
690 notifyListener(srcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, 0);
691 return;
692 }
693
694 mResetting = true;
695 stopPlaybackTimer("kWhatPlayNextDataSource");
696 stopRebufferingTimer(true);
697
698 mDeferredActions.push_back(
699 new FlushDecoderAction(
700 FLUSH_CMD_SHUTDOWN /* audio */,
701 FLUSH_CMD_SHUTDOWN /* video */));
702
703 mDeferredActions.push_back(
704 new SimpleAction(&NuPlayer2::performPlayNextDataSource));
705
706 processDeferredActions();
707 break;
708 }
709
Wei Jia53692fa2017-12-11 10:33:46 -0800710 case kWhatGetBufferingSettings:
711 {
712 sp<AReplyToken> replyID;
713 CHECK(msg->senderAwaitsResponse(&replyID));
714
715 ALOGV("kWhatGetBufferingSettings");
716 BufferingSettings buffering;
717 status_t err = OK;
718 if (mSource != NULL) {
719 err = mSource->getBufferingSettings(&buffering);
720 } else {
721 err = INVALID_OPERATION;
722 }
723 sp<AMessage> response = new AMessage;
724 if (err == OK) {
725 writeToAMessage(response, buffering);
726 }
727 response->setInt32("err", err);
728 response->postReply(replyID);
729 break;
730 }
731
732 case kWhatSetBufferingSettings:
733 {
734 sp<AReplyToken> replyID;
735 CHECK(msg->senderAwaitsResponse(&replyID));
736
737 ALOGV("kWhatSetBufferingSettings");
738 BufferingSettings buffering;
739 readFromAMessage(msg, &buffering);
740 status_t err = OK;
741 if (mSource != NULL) {
742 err = mSource->setBufferingSettings(buffering);
743 } else {
744 err = INVALID_OPERATION;
745 }
746 sp<AMessage> response = new AMessage;
747 response->setInt32("err", err);
748 response->postReply(replyID);
749 break;
750 }
751
752 case kWhatPrepare:
753 {
754 ALOGV("onMessageReceived kWhatPrepare");
755
756 mSource->prepareAsync();
757 break;
758 }
759
760 case kWhatGetTrackInfo:
761 {
762 sp<AReplyToken> replyID;
763 CHECK(msg->senderAwaitsResponse(&replyID));
764
Dongwon Kang9f631982018-07-10 12:34:41 -0700765 PlayerMessage* reply;
Wei Jia53692fa2017-12-11 10:33:46 -0800766 CHECK(msg->findPointer("reply", (void**)&reply));
767
768 size_t inbandTracks = 0;
769 if (mSource != NULL) {
770 inbandTracks = mSource->getTrackCount();
771 }
772
773 size_t ccTracks = 0;
774 if (mCCDecoder != NULL) {
775 ccTracks = mCCDecoder->getTrackCount();
776 }
777
778 // total track count
Dongwon Kang9f631982018-07-10 12:34:41 -0700779 reply->add_values()->set_int32_value(inbandTracks + ccTracks);
Wei Jia53692fa2017-12-11 10:33:46 -0800780
781 // write inband tracks
782 for (size_t i = 0; i < inbandTracks; ++i) {
783 writeTrackInfo(reply, mSource->getTrackInfo(i));
784 }
785
786 // write CC track
787 for (size_t i = 0; i < ccTracks; ++i) {
788 writeTrackInfo(reply, mCCDecoder->getTrackInfo(i));
789 }
790
791 sp<AMessage> response = new AMessage;
792 response->postReply(replyID);
793 break;
794 }
795
796 case kWhatGetSelectedTrack:
797 {
798 status_t err = INVALID_OPERATION;
799 if (mSource != NULL) {
800 err = OK;
801
802 int32_t type32;
803 CHECK(msg->findInt32("type", (int32_t*)&type32));
804 media_track_type type = (media_track_type)type32;
805 ssize_t selectedTrack = mSource->getSelectedTrack(type);
806
Dongwon Kang9f631982018-07-10 12:34:41 -0700807 PlayerMessage* reply;
Wei Jia53692fa2017-12-11 10:33:46 -0800808 CHECK(msg->findPointer("reply", (void**)&reply));
Dongwon Kang9f631982018-07-10 12:34:41 -0700809 reply->add_values()->set_int32_value(selectedTrack);
Wei Jia53692fa2017-12-11 10:33:46 -0800810 }
811
812 sp<AMessage> response = new AMessage;
813 response->setInt32("err", err);
814
815 sp<AReplyToken> replyID;
816 CHECK(msg->senderAwaitsResponse(&replyID));
817 response->postReply(replyID);
818 break;
819 }
820
821 case kWhatSelectTrack:
822 {
823 sp<AReplyToken> replyID;
824 CHECK(msg->senderAwaitsResponse(&replyID));
825
826 size_t trackIndex;
827 int32_t select;
828 int64_t timeUs;
829 CHECK(msg->findSize("trackIndex", &trackIndex));
830 CHECK(msg->findInt32("select", &select));
831 CHECK(msg->findInt64("timeUs", &timeUs));
832
833 status_t err = INVALID_OPERATION;
834
835 size_t inbandTracks = 0;
836 if (mSource != NULL) {
837 inbandTracks = mSource->getTrackCount();
838 }
839 size_t ccTracks = 0;
840 if (mCCDecoder != NULL) {
841 ccTracks = mCCDecoder->getTrackCount();
842 }
843
844 if (trackIndex < inbandTracks) {
845 err = mSource->selectTrack(trackIndex, select, timeUs);
846
847 if (!select && err == OK) {
848 int32_t type;
849 sp<AMessage> info = mSource->getTrackInfo(trackIndex);
850 if (info != NULL
851 && info->findInt32("type", &type)
852 && type == MEDIA_TRACK_TYPE_TIMEDTEXT) {
853 ++mTimedTextGeneration;
854 }
855 }
856 } else {
857 trackIndex -= inbandTracks;
858
859 if (trackIndex < ccTracks) {
860 err = mCCDecoder->selectTrack(trackIndex, select);
861 }
862 }
863
864 sp<AMessage> response = new AMessage;
865 response->setInt32("err", err);
866
867 response->postReply(replyID);
868 break;
869 }
870
871 case kWhatPollDuration:
872 {
873 int32_t generation;
874 CHECK(msg->findInt32("generation", &generation));
875
876 if (generation != mPollDurationGeneration) {
877 // stale
878 break;
879 }
880
881 int64_t durationUs;
882 if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
883 sp<NuPlayer2Driver> driver = mDriver.promote();
884 if (driver != NULL) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -0800885 driver->notifyDuration(mSrcId, durationUs);
Wei Jia53692fa2017-12-11 10:33:46 -0800886 }
887 }
888
889 msg->post(1000000ll); // poll again in a second.
890 break;
891 }
892
893 case kWhatSetVideoSurface:
894 {
895
896 sp<RefBase> obj;
897 CHECK(msg->findObject("surface", &obj));
Wei Jia28288fb2017-12-15 13:45:29 -0800898 sp<ANativeWindowWrapper> nww = static_cast<ANativeWindowWrapper *>(obj.get());
Wei Jia53692fa2017-12-11 10:33:46 -0800899
900 ALOGD("onSetVideoSurface(%p, %s video decoder)",
Wei Jia28288fb2017-12-15 13:45:29 -0800901 (nww == NULL ? NULL : nww->getANativeWindow()),
Wei Jia53692fa2017-12-11 10:33:46 -0800902 (mSource != NULL && mStarted && mSource->getFormat(false /* audio */) != NULL
903 && mVideoDecoder != NULL) ? "have" : "no");
904
905 // Need to check mStarted before calling mSource->getFormat because NuPlayer2 might
906 // be in preparing state and it could take long time.
907 // When mStarted is true, mSource must have been set.
908 if (mSource == NULL || !mStarted || mSource->getFormat(false /* audio */) == NULL
Wei Jia28288fb2017-12-15 13:45:29 -0800909 // NOTE: mVideoDecoder's mNativeWindow is always non-null
910 || (mVideoDecoder != NULL && mVideoDecoder->setVideoSurface(nww) == OK)) {
911 performSetSurface(nww);
Wei Jia53692fa2017-12-11 10:33:46 -0800912 break;
913 }
914
915 mDeferredActions.push_back(
916 new FlushDecoderAction(
917 (obj != NULL ? FLUSH_CMD_FLUSH : FLUSH_CMD_NONE) /* audio */,
918 FLUSH_CMD_SHUTDOWN /* video */));
919
Wei Jia28288fb2017-12-15 13:45:29 -0800920 mDeferredActions.push_back(new SetSurfaceAction(nww));
Wei Jia53692fa2017-12-11 10:33:46 -0800921
922 if (obj != NULL) {
923 if (mStarted) {
924 // Issue a seek to refresh the video screen only if started otherwise
925 // the extractor may not yet be started and will assert.
926 // If the video decoder is not set (perhaps audio only in this case)
927 // do not perform a seek as it is not needed.
928 int64_t currentPositionUs = 0;
929 if (getCurrentPosition(&currentPositionUs) == OK) {
930 mDeferredActions.push_back(
931 new SeekAction(currentPositionUs,
932 MediaPlayer2SeekMode::SEEK_PREVIOUS_SYNC /* mode */));
933 }
934 }
935
936 // If there is a new surface texture, instantiate decoders
937 // again if possible.
938 mDeferredActions.push_back(
939 new SimpleAction(&NuPlayer2::performScanSources));
940
941 // After a flush without shutdown, decoder is paused.
942 // Don't resume it until source seek is done, otherwise it could
943 // start pulling stale data too soon.
944 mDeferredActions.push_back(
945 new ResumeDecoderAction(false /* needNotify */));
946 }
947
948 processDeferredActions();
949 break;
950 }
951
952 case kWhatSetAudioSink:
953 {
954 ALOGV("kWhatSetAudioSink");
955
956 sp<RefBase> obj;
957 CHECK(msg->findObject("sink", &obj));
958
Wei Jia33abcc72018-01-30 09:47:38 -0800959 mAudioSink = static_cast<MediaPlayer2Interface::AudioSink *>(obj.get());
Wei Jia53692fa2017-12-11 10:33:46 -0800960 break;
961 }
962
963 case kWhatStart:
964 {
965 ALOGV("kWhatStart");
966 if (mStarted) {
967 // do not resume yet if the source is still buffering
968 if (!mPausedForBuffering) {
969 onResume();
970 }
971 } else {
972 onStart();
973 }
974 mPausedByClient = false;
Wei Jiad2bb1bd2018-02-08 09:47:37 -0800975 notifyListener(mSrcId, MEDIA2_STARTED, 0, 0);
Wei Jia53692fa2017-12-11 10:33:46 -0800976 break;
977 }
978
979 case kWhatConfigPlayback:
980 {
981 sp<AReplyToken> replyID;
982 CHECK(msg->senderAwaitsResponse(&replyID));
983 AudioPlaybackRate rate /* sanitized */;
984 readFromAMessage(msg, &rate);
985 status_t err = OK;
986 if (mRenderer != NULL) {
987 // AudioSink allows only 1.f and 0.f for offload mode.
988 // For other speed, switch to non-offload mode.
989 if (mOffloadAudio && ((rate.mSpeed != 0.f && rate.mSpeed != 1.f)
990 || rate.mPitch != 1.f)) {
991 int64_t currentPositionUs;
992 if (getCurrentPosition(&currentPositionUs) != OK) {
993 currentPositionUs = mPreviousSeekTimeUs;
994 }
995
996 // Set mPlaybackSettings so that the new audio decoder can
997 // be created correctly.
998 mPlaybackSettings = rate;
999 if (!mPaused) {
1000 mRenderer->pause();
1001 }
1002 restartAudio(
1003 currentPositionUs, true /* forceNonOffload */,
1004 true /* needsToCreateAudioDecoder */);
1005 if (!mPaused) {
1006 mRenderer->resume();
1007 }
1008 }
1009
1010 err = mRenderer->setPlaybackSettings(rate);
1011 }
1012 if (err == OK) {
1013 if (rate.mSpeed == 0.f) {
1014 onPause();
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001015 notifyListener(mSrcId, MEDIA2_PAUSED, 0, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08001016 mPausedByClient = true;
1017 // save all other settings (using non-paused speed)
1018 // so we can restore them on start
1019 AudioPlaybackRate newRate = rate;
1020 newRate.mSpeed = mPlaybackSettings.mSpeed;
1021 mPlaybackSettings = newRate;
1022 } else { /* rate.mSpeed != 0.f */
1023 mPlaybackSettings = rate;
1024 if (mStarted) {
1025 // do not resume yet if the source is still buffering
1026 if (!mPausedForBuffering) {
1027 onResume();
1028 }
1029 } else if (mPrepared) {
1030 onStart();
1031 }
1032
1033 mPausedByClient = false;
1034 }
1035 }
1036
1037 if (mVideoDecoder != NULL) {
1038 sp<AMessage> params = new AMessage();
1039 params->setFloat("playback-speed", mPlaybackSettings.mSpeed);
1040 mVideoDecoder->setParameters(params);
1041 }
1042
1043 sp<AMessage> response = new AMessage;
1044 response->setInt32("err", err);
1045 response->postReply(replyID);
1046 break;
1047 }
1048
1049 case kWhatGetPlaybackSettings:
1050 {
1051 sp<AReplyToken> replyID;
1052 CHECK(msg->senderAwaitsResponse(&replyID));
1053 AudioPlaybackRate rate = mPlaybackSettings;
1054 status_t err = OK;
1055 if (mRenderer != NULL) {
1056 err = mRenderer->getPlaybackSettings(&rate);
1057 }
1058 if (err == OK) {
1059 // get playback settings used by renderer, as it may be
1060 // slightly off due to audiosink not taking small changes.
1061 mPlaybackSettings = rate;
1062 if (mPaused) {
1063 rate.mSpeed = 0.f;
1064 }
1065 }
1066 sp<AMessage> response = new AMessage;
1067 if (err == OK) {
1068 writeToAMessage(response, rate);
1069 }
1070 response->setInt32("err", err);
1071 response->postReply(replyID);
1072 break;
1073 }
1074
1075 case kWhatConfigSync:
1076 {
1077 sp<AReplyToken> replyID;
1078 CHECK(msg->senderAwaitsResponse(&replyID));
1079
1080 ALOGV("kWhatConfigSync");
1081 AVSyncSettings sync;
1082 float videoFpsHint;
1083 readFromAMessage(msg, &sync, &videoFpsHint);
1084 status_t err = OK;
1085 if (mRenderer != NULL) {
1086 err = mRenderer->setSyncSettings(sync, videoFpsHint);
1087 }
1088 if (err == OK) {
1089 mSyncSettings = sync;
1090 mVideoFpsHint = videoFpsHint;
1091 }
1092 sp<AMessage> response = new AMessage;
1093 response->setInt32("err", err);
1094 response->postReply(replyID);
1095 break;
1096 }
1097
1098 case kWhatGetSyncSettings:
1099 {
1100 sp<AReplyToken> replyID;
1101 CHECK(msg->senderAwaitsResponse(&replyID));
1102 AVSyncSettings sync = mSyncSettings;
1103 float videoFps = mVideoFpsHint;
1104 status_t err = OK;
1105 if (mRenderer != NULL) {
1106 err = mRenderer->getSyncSettings(&sync, &videoFps);
1107 if (err == OK) {
1108 mSyncSettings = sync;
1109 mVideoFpsHint = videoFps;
1110 }
1111 }
1112 sp<AMessage> response = new AMessage;
1113 if (err == OK) {
1114 writeToAMessage(response, sync, videoFps);
1115 }
1116 response->setInt32("err", err);
1117 response->postReply(replyID);
1118 break;
1119 }
1120
1121 case kWhatScanSources:
1122 {
1123 int32_t generation;
1124 CHECK(msg->findInt32("generation", &generation));
1125 if (generation != mScanSourcesGeneration) {
1126 // Drop obsolete msg.
1127 break;
1128 }
1129
1130 mScanSourcesPending = false;
1131
1132 ALOGV("scanning sources haveAudio=%d, haveVideo=%d",
1133 mAudioDecoder != NULL, mVideoDecoder != NULL);
1134
1135 bool mHadAnySourcesBefore =
1136 (mAudioDecoder != NULL) || (mVideoDecoder != NULL);
1137 bool rescan = false;
1138
1139 // initialize video before audio because successful initialization of
1140 // video may change deep buffer mode of audio.
Wei Jia28288fb2017-12-15 13:45:29 -08001141 if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -08001142 if (instantiateDecoder(false, &mVideoDecoder) == -EWOULDBLOCK) {
1143 rescan = true;
1144 }
1145 }
1146
1147 // Don't try to re-open audio sink if there's an existing decoder.
1148 if (mAudioSink != NULL && mAudioDecoder == NULL) {
1149 if (instantiateDecoder(true, &mAudioDecoder) == -EWOULDBLOCK) {
1150 rescan = true;
1151 }
1152 }
1153
1154 if (!mHadAnySourcesBefore
1155 && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
1156 // This is the first time we've found anything playable.
1157
1158 if (mSourceFlags & Source::FLAG_DYNAMIC_DURATION) {
1159 schedulePollDuration();
1160 }
1161 }
1162
1163 status_t err;
1164 if ((err = mSource->feedMoreTSData()) != OK) {
1165 if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
1166 // We're not currently decoding anything (no audio or
1167 // video tracks found) and we just ran out of input data.
1168
1169 if (err == ERROR_END_OF_STREAM) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001170 notifyListener(mSrcId, MEDIA2_PLAYBACK_COMPLETE, 0, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08001171 } else {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001172 notifyListener(mSrcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
Wei Jia53692fa2017-12-11 10:33:46 -08001173 }
1174 }
1175 break;
1176 }
1177
1178 if (rescan) {
1179 msg->post(100000ll);
1180 mScanSourcesPending = true;
1181 }
1182 break;
1183 }
1184
1185 case kWhatVideoNotify:
1186 case kWhatAudioNotify:
1187 {
1188 bool audio = msg->what() == kWhatAudioNotify;
1189
1190 int32_t currentDecoderGeneration =
1191 (audio? mAudioDecoderGeneration : mVideoDecoderGeneration);
1192 int32_t requesterGeneration = currentDecoderGeneration - 1;
1193 CHECK(msg->findInt32("generation", &requesterGeneration));
1194
1195 if (requesterGeneration != currentDecoderGeneration) {
1196 ALOGV("got message from old %s decoder, generation(%d:%d)",
1197 audio ? "audio" : "video", requesterGeneration,
1198 currentDecoderGeneration);
1199 sp<AMessage> reply;
1200 if (!(msg->findMessage("reply", &reply))) {
1201 return;
1202 }
1203
1204 reply->setInt32("err", INFO_DISCONTINUITY);
1205 reply->post();
1206 return;
1207 }
1208
1209 int32_t what;
1210 CHECK(msg->findInt32("what", &what));
1211
1212 if (what == DecoderBase::kWhatInputDiscontinuity) {
1213 int32_t formatChange;
1214 CHECK(msg->findInt32("formatChange", &formatChange));
1215
1216 ALOGV("%s discontinuity: formatChange %d",
1217 audio ? "audio" : "video", formatChange);
1218
1219 if (formatChange) {
1220 mDeferredActions.push_back(
1221 new FlushDecoderAction(
1222 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
1223 audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN));
1224 }
1225
1226 mDeferredActions.push_back(
1227 new SimpleAction(
1228 &NuPlayer2::performScanSources));
1229
1230 processDeferredActions();
1231 } else if (what == DecoderBase::kWhatEOS) {
1232 int32_t err;
1233 CHECK(msg->findInt32("err", &err));
1234
1235 if (err == ERROR_END_OF_STREAM) {
1236 ALOGV("got %s decoder EOS", audio ? "audio" : "video");
1237 } else {
1238 ALOGV("got %s decoder EOS w/ error %d",
1239 audio ? "audio" : "video",
1240 err);
1241 }
1242
1243 mRenderer->queueEOS(audio, err);
1244 } else if (what == DecoderBase::kWhatFlushCompleted) {
1245 ALOGV("decoder %s flush completed", audio ? "audio" : "video");
1246
1247 handleFlushComplete(audio, true /* isDecoder */);
1248 finishFlushIfPossible();
1249 } else if (what == DecoderBase::kWhatVideoSizeChanged) {
1250 sp<AMessage> format;
1251 CHECK(msg->findMessage("format", &format));
1252
1253 sp<AMessage> inputFormat =
1254 mSource->getFormat(false /* audio */);
1255
1256 setVideoScalingMode(mVideoScalingMode);
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001257 updateVideoSize(mSrcId, inputFormat, format);
Wei Jia53692fa2017-12-11 10:33:46 -08001258 } else if (what == DecoderBase::kWhatShutdownCompleted) {
1259 ALOGV("%s shutdown completed", audio ? "audio" : "video");
1260 if (audio) {
1261 mAudioDecoder.clear();
1262 mAudioDecoderError = false;
1263 ++mAudioDecoderGeneration;
1264
1265 CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
1266 mFlushingAudio = SHUT_DOWN;
1267 } else {
1268 mVideoDecoder.clear();
1269 mVideoDecoderError = false;
1270 ++mVideoDecoderGeneration;
1271
1272 CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
1273 mFlushingVideo = SHUT_DOWN;
1274 }
1275
1276 finishFlushIfPossible();
1277 } else if (what == DecoderBase::kWhatResumeCompleted) {
1278 finishResume();
1279 } else if (what == DecoderBase::kWhatError) {
1280 status_t err;
1281 if (!msg->findInt32("err", &err) || err == OK) {
1282 err = UNKNOWN_ERROR;
1283 }
1284
1285 // Decoder errors can be due to Source (e.g. from streaming),
1286 // or from decoding corrupted bitstreams, or from other decoder
1287 // MediaCodec operations (e.g. from an ongoing reset or seek).
1288 // They may also be due to openAudioSink failure at
1289 // decoder start or after a format change.
1290 //
1291 // We try to gracefully shut down the affected decoder if possible,
1292 // rather than trying to force the shutdown with something
1293 // similar to performReset(). This method can lead to a hang
1294 // if MediaCodec functions block after an error, but they should
1295 // typically return INVALID_OPERATION instead of blocking.
1296
1297 FlushStatus *flushing = audio ? &mFlushingAudio : &mFlushingVideo;
1298 ALOGE("received error(%#x) from %s decoder, flushing(%d), now shutting down",
1299 err, audio ? "audio" : "video", *flushing);
1300
1301 switch (*flushing) {
1302 case NONE:
1303 mDeferredActions.push_back(
1304 new FlushDecoderAction(
1305 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
1306 audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN));
1307 processDeferredActions();
1308 break;
1309 case FLUSHING_DECODER:
1310 *flushing = FLUSHING_DECODER_SHUTDOWN; // initiate shutdown after flush.
1311 break; // Wait for flush to complete.
1312 case FLUSHING_DECODER_SHUTDOWN:
1313 break; // Wait for flush to complete.
1314 case SHUTTING_DOWN_DECODER:
1315 break; // Wait for shutdown to complete.
1316 case FLUSHED:
1317 getDecoder(audio)->initiateShutdown(); // In the middle of a seek.
1318 *flushing = SHUTTING_DOWN_DECODER; // Shut down.
1319 break;
1320 case SHUT_DOWN:
1321 finishFlushIfPossible(); // Should not occur.
1322 break; // Finish anyways.
1323 }
1324 if (mSource != nullptr) {
1325 if (audio) {
1326 if (mVideoDecoderError || mSource->getFormat(false /* audio */) == NULL
Wei Jia28288fb2017-12-15 13:45:29 -08001327 || mNativeWindow == NULL || mNativeWindow->getANativeWindow() == NULL
1328 || mVideoDecoder == NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -08001329 // When both audio and video have error, or this stream has only audio
1330 // which has error, notify client of error.
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001331 notifyListener(mSrcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
Wei Jia53692fa2017-12-11 10:33:46 -08001332 } else {
1333 // Only audio track has error. Video track could be still good to play.
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001334 notifyListener(mSrcId, MEDIA2_INFO, MEDIA2_INFO_PLAY_AUDIO_ERROR, err);
Wei Jia53692fa2017-12-11 10:33:46 -08001335 }
1336 mAudioDecoderError = true;
1337 } else {
1338 if (mAudioDecoderError || mSource->getFormat(true /* audio */) == NULL
1339 || mAudioSink == NULL || mAudioDecoder == NULL) {
1340 // When both audio and video have error, or this stream has only video
1341 // which has error, notify client of error.
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001342 notifyListener(mSrcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
Wei Jia53692fa2017-12-11 10:33:46 -08001343 } else {
1344 // Only video track has error. Audio track could be still good to play.
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001345 notifyListener(mSrcId, MEDIA2_INFO, MEDIA2_INFO_PLAY_VIDEO_ERROR, err);
Wei Jia53692fa2017-12-11 10:33:46 -08001346 }
1347 mVideoDecoderError = true;
1348 }
1349 }
1350 } else {
1351 ALOGV("Unhandled decoder notification %d '%c%c%c%c'.",
1352 what,
1353 what >> 24,
1354 (what >> 16) & 0xff,
1355 (what >> 8) & 0xff,
1356 what & 0xff);
1357 }
1358
1359 break;
1360 }
1361
1362 case kWhatRendererNotify:
1363 {
1364 int32_t requesterGeneration = mRendererGeneration - 1;
1365 CHECK(msg->findInt32("generation", &requesterGeneration));
1366 if (requesterGeneration != mRendererGeneration) {
1367 ALOGV("got message from old renderer, generation(%d:%d)",
1368 requesterGeneration, mRendererGeneration);
1369 return;
1370 }
1371
1372 int32_t what;
1373 CHECK(msg->findInt32("what", &what));
1374
1375 if (what == Renderer::kWhatEOS) {
1376 int32_t audio;
1377 CHECK(msg->findInt32("audio", &audio));
1378
1379 int32_t finalResult;
1380 CHECK(msg->findInt32("finalResult", &finalResult));
1381
1382 if (audio) {
1383 mAudioEOS = true;
1384 } else {
1385 mVideoEOS = true;
1386 }
1387
1388 if (finalResult == ERROR_END_OF_STREAM) {
1389 ALOGV("reached %s EOS", audio ? "audio" : "video");
1390 } else {
1391 ALOGE("%s track encountered an error (%d)",
1392 audio ? "audio" : "video", finalResult);
1393
1394 notifyListener(
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001395 mSrcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, finalResult);
Wei Jia53692fa2017-12-11 10:33:46 -08001396 }
1397
1398 if ((mAudioEOS || mAudioDecoder == NULL)
1399 && (mVideoEOS || mVideoDecoder == NULL)) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001400 notifyListener(mSrcId, MEDIA2_PLAYBACK_COMPLETE, 0, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08001401 }
1402 } else if (what == Renderer::kWhatFlushComplete) {
1403 int32_t audio;
1404 CHECK(msg->findInt32("audio", &audio));
1405
1406 if (audio) {
1407 mAudioEOS = false;
1408 } else {
1409 mVideoEOS = false;
1410 }
1411
1412 ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
1413 if (audio && (mFlushingAudio == NONE || mFlushingAudio == FLUSHED
1414 || mFlushingAudio == SHUT_DOWN)) {
1415 // Flush has been handled by tear down.
1416 break;
1417 }
1418 handleFlushComplete(audio, false /* isDecoder */);
1419 finishFlushIfPossible();
1420 } else if (what == Renderer::kWhatVideoRenderingStart) {
Wei Jia57aeffd2018-02-15 16:01:14 -08001421 notifyListener(mSrcId, MEDIA2_INFO, MEDIA2_INFO_VIDEO_RENDERING_START, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08001422 } else if (what == Renderer::kWhatMediaRenderingStart) {
1423 ALOGV("media rendering started");
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001424 notifyListener(mSrcId, MEDIA2_STARTED, 0, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08001425 } else if (what == Renderer::kWhatAudioTearDown) {
1426 int32_t reason;
1427 CHECK(msg->findInt32("reason", &reason));
1428 ALOGV("Tear down audio with reason %d.", reason);
1429 if (reason == Renderer::kDueToTimeout && !(mPaused && mOffloadAudio)) {
1430 // TimeoutWhenPaused is only for offload mode.
1431 ALOGW("Receive a stale message for teardown.");
1432 break;
1433 }
1434 int64_t positionUs;
1435 if (!msg->findInt64("positionUs", &positionUs)) {
1436 positionUs = mPreviousSeekTimeUs;
1437 }
1438
1439 restartAudio(
1440 positionUs, reason == Renderer::kForceNonOffload /* forceNonOffload */,
1441 reason != Renderer::kDueToTimeout /* needsToCreateAudioDecoder */);
1442 }
1443 break;
1444 }
1445
1446 case kWhatMoreDataQueued:
1447 {
1448 break;
1449 }
1450
1451 case kWhatReset:
1452 {
1453 ALOGV("kWhatReset");
1454
1455 mResetting = true;
1456 stopPlaybackTimer("kWhatReset");
1457 stopRebufferingTimer(true);
1458
1459 mDeferredActions.push_back(
1460 new FlushDecoderAction(
1461 FLUSH_CMD_SHUTDOWN /* audio */,
1462 FLUSH_CMD_SHUTDOWN /* video */));
1463
1464 mDeferredActions.push_back(
1465 new SimpleAction(&NuPlayer2::performReset));
1466
1467 processDeferredActions();
1468 break;
1469 }
1470
1471 case kWhatNotifyTime:
1472 {
1473 ALOGV("kWhatNotifyTime");
1474 int64_t timerUs;
1475 CHECK(msg->findInt64("timerUs", &timerUs));
1476
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001477 notifyListener(mSrcId, MEDIA2_NOTIFY_TIME, timerUs, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08001478 break;
1479 }
1480
1481 case kWhatSeek:
1482 {
1483 int64_t seekTimeUs;
1484 int32_t mode;
1485 int32_t needNotify;
1486 CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
1487 CHECK(msg->findInt32("mode", &mode));
1488 CHECK(msg->findInt32("needNotify", &needNotify));
1489
1490 ALOGV("kWhatSeek seekTimeUs=%lld us, mode=%d, needNotify=%d",
1491 (long long)seekTimeUs, mode, needNotify);
1492
1493 if (!mStarted) {
Wei Jia083e9092018-02-12 11:46:04 -08001494 if (!mSourceStarted) {
1495 mSourceStarted = true;
1496 mSource->start();
Wei Jia53692fa2017-12-11 10:33:46 -08001497 }
Wei Jia083e9092018-02-12 11:46:04 -08001498 if (seekTimeUs > 0) {
1499 performSeek(seekTimeUs, (MediaPlayer2SeekMode)mode);
1500 }
1501
Wei Jia53692fa2017-12-11 10:33:46 -08001502 if (needNotify) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001503 notifyDriverSeekComplete(mSrcId);
Wei Jia53692fa2017-12-11 10:33:46 -08001504 }
1505 break;
1506 }
1507
Wei Jia083e9092018-02-12 11:46:04 -08001508 // seeks can take a while, so we essentially paused
1509 notifyListener(mSrcId, MEDIA2_PAUSED, 0, 0);
1510
Wei Jia53692fa2017-12-11 10:33:46 -08001511 mDeferredActions.push_back(
1512 new FlushDecoderAction(FLUSH_CMD_FLUSH /* audio */,
1513 FLUSH_CMD_FLUSH /* video */));
1514
1515 mDeferredActions.push_back(
1516 new SeekAction(seekTimeUs, (MediaPlayer2SeekMode)mode));
1517
1518 // After a flush without shutdown, decoder is paused.
1519 // Don't resume it until source seek is done, otherwise it could
1520 // start pulling stale data too soon.
1521 mDeferredActions.push_back(
1522 new ResumeDecoderAction(needNotify));
1523
1524 processDeferredActions();
1525 break;
1526 }
1527
1528 case kWhatPause:
1529 {
1530 onPause();
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001531 notifyListener(mSrcId, MEDIA2_PAUSED, 0, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08001532 mPausedByClient = true;
1533 break;
1534 }
1535
1536 case kWhatSourceNotify:
1537 {
1538 onSourceNotify(msg);
1539 break;
1540 }
1541
1542 case kWhatClosedCaptionNotify:
1543 {
1544 onClosedCaptionNotify(msg);
1545 break;
1546 }
1547
1548 case kWhatPrepareDrm:
1549 {
1550 status_t status = onPrepareDrm(msg);
1551
1552 sp<AMessage> response = new AMessage;
1553 response->setInt32("status", status);
1554 sp<AReplyToken> replyID;
1555 CHECK(msg->senderAwaitsResponse(&replyID));
1556 response->postReply(replyID);
1557 break;
1558 }
1559
1560 case kWhatReleaseDrm:
1561 {
1562 status_t status = onReleaseDrm();
1563
1564 sp<AMessage> response = new AMessage;
1565 response->setInt32("status", status);
1566 sp<AReplyToken> replyID;
1567 CHECK(msg->senderAwaitsResponse(&replyID));
1568 response->postReply(replyID);
1569 break;
1570 }
1571
1572 default:
1573 TRESPASS();
1574 break;
1575 }
1576}
1577
1578void NuPlayer2::onResume() {
1579 if (!mPaused || mResetting) {
1580 ALOGD_IF(mResetting, "resetting, onResume discarded");
1581 return;
1582 }
1583 mPaused = false;
1584 if (mSource != NULL) {
1585 mSource->resume();
1586 } else {
1587 ALOGW("resume called when source is gone or not set");
1588 }
1589 // |mAudioDecoder| may have been released due to the pause timeout, so re-create it if
1590 // needed.
1591 if (audioDecoderStillNeeded() && mAudioDecoder == NULL) {
1592 instantiateDecoder(true /* audio */, &mAudioDecoder);
1593 }
1594 if (mRenderer != NULL) {
1595 mRenderer->resume();
1596 } else {
1597 ALOGW("resume called when renderer is gone or not set");
1598 }
1599
1600 startPlaybackTimer("onresume");
1601}
1602
Wei Jia083e9092018-02-12 11:46:04 -08001603void NuPlayer2::onStart() {
Wei Jia53692fa2017-12-11 10:33:46 -08001604 ALOGV("onStart: mCrypto: %p", mCrypto.get());
1605
1606 if (!mSourceStarted) {
1607 mSourceStarted = true;
1608 mSource->start();
1609 }
Wei Jia53692fa2017-12-11 10:33:46 -08001610
1611 mOffloadAudio = false;
1612 mAudioEOS = false;
1613 mVideoEOS = false;
1614 mStarted = true;
1615 mPaused = false;
1616
1617 uint32_t flags = 0;
1618
1619 if (mSource->isRealTime()) {
1620 flags |= Renderer::FLAG_REAL_TIME;
1621 }
1622
1623 bool hasAudio = (mSource->getFormat(true /* audio */) != NULL);
1624 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
1625 if (!hasAudio && !hasVideo) {
1626 ALOGE("no metadata for either audio or video source");
1627 mSource->stop();
1628 mSourceStarted = false;
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001629 notifyListener(mSrcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, ERROR_MALFORMED);
Wei Jia53692fa2017-12-11 10:33:46 -08001630 return;
1631 }
1632 ALOGV_IF(!hasAudio, "no metadata for audio source"); // video only stream
1633
1634 sp<MetaData> audioMeta = mSource->getFormatMeta(true /* audio */);
1635
1636 audio_stream_type_t streamType = AUDIO_STREAM_MUSIC;
1637 if (mAudioSink != NULL) {
1638 streamType = mAudioSink->getAudioStreamType();
1639 }
1640
1641 mOffloadAudio =
1642 canOffloadStream(audioMeta, hasVideo, mSource->isStreaming(), streamType)
1643 && (mPlaybackSettings.mSpeed == 1.f && mPlaybackSettings.mPitch == 1.f);
1644
1645 // Modular DRM: Disabling audio offload if the source is protected
1646 if (mOffloadAudio && mIsDrmProtected) {
1647 mOffloadAudio = false;
1648 ALOGV("onStart: Disabling mOffloadAudio now that the source is protected.");
1649 }
1650
1651 if (mOffloadAudio) {
1652 flags |= Renderer::FLAG_OFFLOAD_AUDIO;
1653 }
1654
1655 sp<AMessage> notify = new AMessage(kWhatRendererNotify, this);
1656 ++mRendererGeneration;
1657 notify->setInt32("generation", mRendererGeneration);
1658 mRenderer = new Renderer(mAudioSink, mMediaClock, notify, flags);
1659 mRendererLooper = new ALooper;
1660 mRendererLooper->setName("NuPlayerRenderer");
1661 mRendererLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
1662 mRendererLooper->registerHandler(mRenderer);
1663
1664 status_t err = mRenderer->setPlaybackSettings(mPlaybackSettings);
1665 if (err != OK) {
1666 mSource->stop();
1667 mSourceStarted = false;
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001668 notifyListener(mSrcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
Wei Jia53692fa2017-12-11 10:33:46 -08001669 return;
1670 }
1671
1672 float rate = getFrameRate();
1673 if (rate > 0) {
1674 mRenderer->setVideoFrameRate(rate);
1675 }
1676
1677 if (mVideoDecoder != NULL) {
1678 mVideoDecoder->setRenderer(mRenderer);
1679 }
1680 if (mAudioDecoder != NULL) {
1681 mAudioDecoder->setRenderer(mRenderer);
1682 }
1683
1684 startPlaybackTimer("onstart");
Wei Jia975be2f2018-08-23 18:23:04 -07001685 notifyListener(mSrcId, MEDIA2_INFO, MEDIA2_INFO_DATA_SOURCE_START, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08001686
1687 postScanSources();
1688}
1689
1690void NuPlayer2::startPlaybackTimer(const char *where) {
1691 Mutex::Autolock autoLock(mPlayingTimeLock);
1692 if (mLastStartedPlayingTimeNs == 0) {
1693 mLastStartedPlayingTimeNs = systemTime();
1694 ALOGV("startPlaybackTimer() time %20" PRId64 " (%s)", mLastStartedPlayingTimeNs, where);
1695 }
1696}
1697
1698void NuPlayer2::stopPlaybackTimer(const char *where) {
1699 Mutex::Autolock autoLock(mPlayingTimeLock);
1700
1701 ALOGV("stopPlaybackTimer() time %20" PRId64 " (%s)", mLastStartedPlayingTimeNs, where);
1702
1703 if (mLastStartedPlayingTimeNs != 0) {
1704 sp<NuPlayer2Driver> driver = mDriver.promote();
1705 if (driver != NULL) {
1706 int64_t now = systemTime();
1707 int64_t played = now - mLastStartedPlayingTimeNs;
1708 ALOGV("stopPlaybackTimer() log %20" PRId64 "", played);
1709
1710 if (played > 0) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001711 driver->notifyMorePlayingTimeUs(mSrcId, (played+500)/1000);
Wei Jia53692fa2017-12-11 10:33:46 -08001712 }
1713 }
1714 mLastStartedPlayingTimeNs = 0;
1715 }
1716}
1717
1718void NuPlayer2::startRebufferingTimer() {
1719 Mutex::Autolock autoLock(mPlayingTimeLock);
1720 if (mLastStartedRebufferingTimeNs == 0) {
1721 mLastStartedRebufferingTimeNs = systemTime();
1722 ALOGV("startRebufferingTimer() time %20" PRId64 "", mLastStartedRebufferingTimeNs);
1723 }
1724}
1725
1726void NuPlayer2::stopRebufferingTimer(bool exitingPlayback) {
1727 Mutex::Autolock autoLock(mPlayingTimeLock);
1728
1729 ALOGV("stopRebufferTimer() time %20" PRId64 " (exiting %d)", mLastStartedRebufferingTimeNs, exitingPlayback);
1730
1731 if (mLastStartedRebufferingTimeNs != 0) {
1732 sp<NuPlayer2Driver> driver = mDriver.promote();
1733 if (driver != NULL) {
1734 int64_t now = systemTime();
1735 int64_t rebuffered = now - mLastStartedRebufferingTimeNs;
1736 ALOGV("stopRebufferingTimer() log %20" PRId64 "", rebuffered);
1737
1738 if (rebuffered > 0) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001739 driver->notifyMoreRebufferingTimeUs(mSrcId, (rebuffered+500)/1000);
Wei Jia53692fa2017-12-11 10:33:46 -08001740 if (exitingPlayback) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08001741 driver->notifyRebufferingWhenExit(mSrcId, true);
Wei Jia53692fa2017-12-11 10:33:46 -08001742 }
1743 }
1744 }
1745 mLastStartedRebufferingTimeNs = 0;
1746 }
1747}
1748
1749void NuPlayer2::onPause() {
1750
1751 stopPlaybackTimer("onPause");
1752
1753 if (mPaused) {
1754 return;
1755 }
1756 mPaused = true;
1757 if (mSource != NULL) {
1758 mSource->pause();
1759 } else {
1760 ALOGW("pause called when source is gone or not set");
1761 }
1762 if (mRenderer != NULL) {
1763 mRenderer->pause();
1764 } else {
1765 ALOGW("pause called when renderer is gone or not set");
1766 }
1767
1768}
1769
1770bool NuPlayer2::audioDecoderStillNeeded() {
1771 // Audio decoder is no longer needed if it's in shut/shutting down status.
1772 return ((mFlushingAudio != SHUT_DOWN) && (mFlushingAudio != SHUTTING_DOWN_DECODER));
1773}
1774
1775void NuPlayer2::handleFlushComplete(bool audio, bool isDecoder) {
1776 // We wait for both the decoder flush and the renderer flush to complete
1777 // before entering either the FLUSHED or the SHUTTING_DOWN_DECODER state.
1778
1779 mFlushComplete[audio][isDecoder] = true;
1780 if (!mFlushComplete[audio][!isDecoder]) {
1781 return;
1782 }
1783
1784 FlushStatus *state = audio ? &mFlushingAudio : &mFlushingVideo;
1785 switch (*state) {
1786 case FLUSHING_DECODER:
1787 {
1788 *state = FLUSHED;
1789 break;
1790 }
1791
1792 case FLUSHING_DECODER_SHUTDOWN:
1793 {
1794 *state = SHUTTING_DOWN_DECODER;
1795
1796 ALOGV("initiating %s decoder shutdown", audio ? "audio" : "video");
1797 getDecoder(audio)->initiateShutdown();
1798 break;
1799 }
1800
1801 default:
1802 // decoder flush completes only occur in a flushing state.
1803 LOG_ALWAYS_FATAL_IF(isDecoder, "decoder flush in invalid state %d", *state);
1804 break;
1805 }
1806}
1807
1808void NuPlayer2::finishFlushIfPossible() {
1809 if (mFlushingAudio != NONE && mFlushingAudio != FLUSHED
1810 && mFlushingAudio != SHUT_DOWN) {
1811 return;
1812 }
1813
1814 if (mFlushingVideo != NONE && mFlushingVideo != FLUSHED
1815 && mFlushingVideo != SHUT_DOWN) {
1816 return;
1817 }
1818
1819 ALOGV("both audio and video are flushed now.");
1820
1821 mFlushingAudio = NONE;
1822 mFlushingVideo = NONE;
1823
1824 clearFlushComplete();
1825
1826 processDeferredActions();
1827}
1828
1829void NuPlayer2::postScanSources() {
1830 if (mScanSourcesPending) {
1831 return;
1832 }
1833
1834 sp<AMessage> msg = new AMessage(kWhatScanSources, this);
1835 msg->setInt32("generation", mScanSourcesGeneration);
1836 msg->post();
1837
1838 mScanSourcesPending = true;
1839}
1840
1841void NuPlayer2::tryOpenAudioSinkForOffload(
1842 const sp<AMessage> &format, const sp<MetaData> &audioMeta, bool hasVideo) {
1843 // Note: This is called early in NuPlayer2 to determine whether offloading
1844 // is possible; otherwise the decoders call the renderer openAudioSink directly.
1845
1846 status_t err = mRenderer->openAudioSink(
1847 format, true /* offloadOnly */, hasVideo,
1848 AUDIO_OUTPUT_FLAG_NONE, &mOffloadAudio, mSource->isStreaming());
1849 if (err != OK) {
1850 // Any failure we turn off mOffloadAudio.
1851 mOffloadAudio = false;
1852 } else if (mOffloadAudio) {
1853 sendMetaDataToHal(mAudioSink, audioMeta);
1854 }
1855}
1856
1857void NuPlayer2::closeAudioSink() {
1858 mRenderer->closeAudioSink();
1859}
1860
1861void NuPlayer2::restartAudio(
1862 int64_t currentPositionUs, bool forceNonOffload, bool needsToCreateAudioDecoder) {
1863 if (mAudioDecoder != NULL) {
1864 mAudioDecoder->pause();
1865 mAudioDecoder.clear();
1866 mAudioDecoderError = false;
1867 ++mAudioDecoderGeneration;
1868 }
1869 if (mFlushingAudio == FLUSHING_DECODER) {
1870 mFlushComplete[1 /* audio */][1 /* isDecoder */] = true;
1871 mFlushingAudio = FLUSHED;
1872 finishFlushIfPossible();
1873 } else if (mFlushingAudio == FLUSHING_DECODER_SHUTDOWN
1874 || mFlushingAudio == SHUTTING_DOWN_DECODER) {
1875 mFlushComplete[1 /* audio */][1 /* isDecoder */] = true;
1876 mFlushingAudio = SHUT_DOWN;
1877 finishFlushIfPossible();
1878 needsToCreateAudioDecoder = false;
1879 }
1880 if (mRenderer == NULL) {
1881 return;
1882 }
1883 closeAudioSink();
1884 mRenderer->flush(true /* audio */, false /* notifyComplete */);
1885 if (mVideoDecoder != NULL) {
1886 mRenderer->flush(false /* audio */, false /* notifyComplete */);
1887 }
1888
1889 performSeek(currentPositionUs, MediaPlayer2SeekMode::SEEK_PREVIOUS_SYNC /* mode */);
1890
1891 if (forceNonOffload) {
1892 mRenderer->signalDisableOffloadAudio();
1893 mOffloadAudio = false;
1894 }
1895 if (needsToCreateAudioDecoder) {
1896 instantiateDecoder(true /* audio */, &mAudioDecoder, !forceNonOffload);
1897 }
1898}
1899
1900void NuPlayer2::determineAudioModeChange(const sp<AMessage> &audioFormat) {
1901 if (mSource == NULL || mAudioSink == NULL) {
1902 return;
1903 }
1904
1905 if (mRenderer == NULL) {
1906 ALOGW("No renderer can be used to determine audio mode. Use non-offload for safety.");
1907 mOffloadAudio = false;
1908 return;
1909 }
1910
1911 sp<MetaData> audioMeta = mSource->getFormatMeta(true /* audio */);
1912 sp<AMessage> videoFormat = mSource->getFormat(false /* audio */);
1913 audio_stream_type_t streamType = mAudioSink->getAudioStreamType();
1914 const bool hasVideo = (videoFormat != NULL);
1915 bool canOffload = canOffloadStream(
1916 audioMeta, hasVideo, mSource->isStreaming(), streamType)
1917 && (mPlaybackSettings.mSpeed == 1.f && mPlaybackSettings.mPitch == 1.f);
1918
1919 // Modular DRM: Disabling audio offload if the source is protected
1920 if (canOffload && mIsDrmProtected) {
1921 canOffload = false;
1922 ALOGV("determineAudioModeChange: Disabling mOffloadAudio b/c the source is protected.");
1923 }
1924
1925 if (canOffload) {
1926 if (!mOffloadAudio) {
1927 mRenderer->signalEnableOffloadAudio();
1928 }
1929 // open audio sink early under offload mode.
1930 tryOpenAudioSinkForOffload(audioFormat, audioMeta, hasVideo);
1931 } else {
1932 if (mOffloadAudio) {
1933 mRenderer->signalDisableOffloadAudio();
1934 mOffloadAudio = false;
1935 }
1936 }
1937}
1938
1939status_t NuPlayer2::instantiateDecoder(
1940 bool audio, sp<DecoderBase> *decoder, bool checkAudioModeChange) {
1941 // The audio decoder could be cleared by tear down. If still in shut down
1942 // process, no need to create a new audio decoder.
1943 if (*decoder != NULL || (audio && mFlushingAudio == SHUT_DOWN)) {
1944 return OK;
1945 }
1946
1947 sp<AMessage> format = mSource->getFormat(audio);
1948
1949 if (format == NULL) {
1950 return UNKNOWN_ERROR;
1951 } else {
1952 status_t err;
1953 if (format->findInt32("err", &err) && err) {
1954 return err;
1955 }
1956 }
1957
1958 format->setInt32("priority", 0 /* realtime */);
1959
1960 if (!audio) {
1961 AString mime;
1962 CHECK(format->findString("mime", &mime));
1963
1964 sp<AMessage> ccNotify = new AMessage(kWhatClosedCaptionNotify, this);
1965 if (mCCDecoder == NULL) {
1966 mCCDecoder = new CCDecoder(ccNotify);
1967 }
1968
1969 if (mSourceFlags & Source::FLAG_SECURE) {
1970 format->setInt32("secure", true);
1971 }
1972
1973 if (mSourceFlags & Source::FLAG_PROTECTED) {
1974 format->setInt32("protected", true);
1975 }
1976
1977 float rate = getFrameRate();
1978 if (rate > 0) {
1979 format->setFloat("operating-rate", rate * mPlaybackSettings.mSpeed);
1980 }
1981 }
1982
1983 if (audio) {
1984 sp<AMessage> notify = new AMessage(kWhatAudioNotify, this);
1985 ++mAudioDecoderGeneration;
1986 notify->setInt32("generation", mAudioDecoderGeneration);
1987
1988 if (checkAudioModeChange) {
1989 determineAudioModeChange(format);
1990 }
1991 if (mOffloadAudio) {
1992 mSource->setOffloadAudio(true /* offload */);
1993
1994 const bool hasVideo = (mSource->getFormat(false /*audio */) != NULL);
1995 format->setInt32("has-video", hasVideo);
1996 *decoder = new DecoderPassThrough(notify, mSource, mRenderer);
1997 ALOGV("instantiateDecoder audio DecoderPassThrough hasVideo: %d", hasVideo);
1998 } else {
1999 mSource->setOffloadAudio(false /* offload */);
2000
2001 *decoder = new Decoder(notify, mSource, mPID, mUID, mRenderer);
2002 ALOGV("instantiateDecoder audio Decoder");
2003 }
2004 mAudioDecoderError = false;
2005 } else {
2006 sp<AMessage> notify = new AMessage(kWhatVideoNotify, this);
2007 ++mVideoDecoderGeneration;
2008 notify->setInt32("generation", mVideoDecoderGeneration);
2009
2010 *decoder = new Decoder(
Wei Jia28288fb2017-12-15 13:45:29 -08002011 notify, mSource, mPID, mUID, mRenderer, mNativeWindow, mCCDecoder);
Wei Jia53692fa2017-12-11 10:33:46 -08002012 mVideoDecoderError = false;
2013
2014 // enable FRC if high-quality AV sync is requested, even if not
2015 // directly queuing to display, as this will even improve textureview
2016 // playback.
2017 {
2018 if (property_get_bool("persist.sys.media.avsync", false)) {
2019 format->setInt32("auto-frc", 1);
2020 }
2021 }
2022 }
2023 (*decoder)->init();
2024
2025 // Modular DRM
2026 if (mIsDrmProtected) {
2027 format->setObject("crypto", mCrypto);
2028 ALOGV("instantiateDecoder: mCrypto: %p isSecure: %d", mCrypto.get(),
2029 (mSourceFlags & Source::FLAG_SECURE) != 0);
2030 }
2031
2032 (*decoder)->configure(format);
2033
2034 if (!audio) {
2035 sp<AMessage> params = new AMessage();
2036 float rate = getFrameRate();
2037 if (rate > 0) {
2038 params->setFloat("frame-rate-total", rate);
2039 }
2040
2041 sp<MetaData> fileMeta = getFileMeta();
2042 if (fileMeta != NULL) {
2043 int32_t videoTemporalLayerCount;
2044 if (fileMeta->findInt32(kKeyTemporalLayerCount, &videoTemporalLayerCount)
2045 && videoTemporalLayerCount > 0) {
2046 params->setInt32("temporal-layer-count", videoTemporalLayerCount);
2047 }
2048 }
2049
2050 if (params->countEntries() > 0) {
2051 (*decoder)->setParameters(params);
2052 }
2053 }
2054 return OK;
2055}
2056
2057void NuPlayer2::updateVideoSize(
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002058 int64_t srcId,
Wei Jia53692fa2017-12-11 10:33:46 -08002059 const sp<AMessage> &inputFormat,
2060 const sp<AMessage> &outputFormat) {
2061 if (inputFormat == NULL) {
2062 ALOGW("Unknown video size, reporting 0x0!");
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002063 notifyListener(srcId, MEDIA2_SET_VIDEO_SIZE, 0, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08002064 return;
2065 }
2066 int32_t err = OK;
2067 inputFormat->findInt32("err", &err);
2068 if (err == -EWOULDBLOCK) {
2069 ALOGW("Video meta is not available yet!");
2070 return;
2071 }
2072 if (err != OK) {
2073 ALOGW("Something is wrong with video meta!");
2074 return;
2075 }
2076
2077 int32_t displayWidth, displayHeight;
2078 if (outputFormat != NULL) {
2079 int32_t width, height;
2080 CHECK(outputFormat->findInt32("width", &width));
2081 CHECK(outputFormat->findInt32("height", &height));
2082
2083 int32_t cropLeft, cropTop, cropRight, cropBottom;
2084 CHECK(outputFormat->findRect(
2085 "crop",
2086 &cropLeft, &cropTop, &cropRight, &cropBottom));
2087
2088 displayWidth = cropRight - cropLeft + 1;
2089 displayHeight = cropBottom - cropTop + 1;
2090
2091 ALOGV("Video output format changed to %d x %d "
2092 "(crop: %d x %d @ (%d, %d))",
2093 width, height,
2094 displayWidth,
2095 displayHeight,
2096 cropLeft, cropTop);
2097 } else {
2098 CHECK(inputFormat->findInt32("width", &displayWidth));
2099 CHECK(inputFormat->findInt32("height", &displayHeight));
2100
2101 ALOGV("Video input format %d x %d", displayWidth, displayHeight);
2102 }
2103
2104 // Take into account sample aspect ratio if necessary:
2105 int32_t sarWidth, sarHeight;
2106 if (inputFormat->findInt32("sar-width", &sarWidth)
2107 && inputFormat->findInt32("sar-height", &sarHeight)
2108 && sarWidth > 0 && sarHeight > 0) {
2109 ALOGV("Sample aspect ratio %d : %d", sarWidth, sarHeight);
2110
2111 displayWidth = (displayWidth * sarWidth) / sarHeight;
2112
2113 ALOGV("display dimensions %d x %d", displayWidth, displayHeight);
2114 } else {
2115 int32_t width, height;
2116 if (inputFormat->findInt32("display-width", &width)
2117 && inputFormat->findInt32("display-height", &height)
2118 && width > 0 && height > 0
2119 && displayWidth > 0 && displayHeight > 0) {
2120 if (displayHeight * (int64_t)width / height > (int64_t)displayWidth) {
2121 displayHeight = (int32_t)(displayWidth * (int64_t)height / width);
2122 } else {
2123 displayWidth = (int32_t)(displayHeight * (int64_t)width / height);
2124 }
2125 ALOGV("Video display width and height are overridden to %d x %d",
2126 displayWidth, displayHeight);
2127 }
2128 }
2129
2130 int32_t rotationDegrees;
2131 if (!inputFormat->findInt32("rotation-degrees", &rotationDegrees)) {
2132 rotationDegrees = 0;
2133 }
2134
2135 if (rotationDegrees == 90 || rotationDegrees == 270) {
2136 int32_t tmp = displayWidth;
2137 displayWidth = displayHeight;
2138 displayHeight = tmp;
2139 }
2140
2141 notifyListener(
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002142 srcId,
Wei Jia53692fa2017-12-11 10:33:46 -08002143 MEDIA2_SET_VIDEO_SIZE,
2144 displayWidth,
2145 displayHeight);
2146}
2147
Dongwon Kang41929fb2018-09-09 08:29:56 -07002148void NuPlayer2::notifyListener(
2149 int64_t srcId, int msg, int ext1, int ext2, const PlayerMessage *in) {
Wei Jia53692fa2017-12-11 10:33:46 -08002150 if (mDriver == NULL) {
2151 return;
2152 }
2153
2154 sp<NuPlayer2Driver> driver = mDriver.promote();
2155
2156 if (driver == NULL) {
2157 return;
2158 }
2159
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002160 driver->notifyListener(srcId, msg, ext1, ext2, in);
Wei Jia53692fa2017-12-11 10:33:46 -08002161}
2162
2163void NuPlayer2::flushDecoder(bool audio, bool needShutdown) {
2164 ALOGV("[%s] flushDecoder needShutdown=%d",
2165 audio ? "audio" : "video", needShutdown);
2166
2167 const sp<DecoderBase> &decoder = getDecoder(audio);
2168 if (decoder == NULL) {
2169 ALOGI("flushDecoder %s without decoder present",
2170 audio ? "audio" : "video");
2171 return;
2172 }
2173
2174 // Make sure we don't continue to scan sources until we finish flushing.
2175 ++mScanSourcesGeneration;
2176 if (mScanSourcesPending) {
2177 if (!needShutdown) {
2178 mDeferredActions.push_back(
2179 new SimpleAction(&NuPlayer2::performScanSources));
2180 }
2181 mScanSourcesPending = false;
2182 }
2183
2184 decoder->signalFlush();
2185
2186 FlushStatus newStatus =
2187 needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
2188
2189 mFlushComplete[audio][false /* isDecoder */] = (mRenderer == NULL);
2190 mFlushComplete[audio][true /* isDecoder */] = false;
2191 if (audio) {
2192 ALOGE_IF(mFlushingAudio != NONE,
2193 "audio flushDecoder() is called in state %d", mFlushingAudio);
2194 mFlushingAudio = newStatus;
2195 } else {
2196 ALOGE_IF(mFlushingVideo != NONE,
2197 "video flushDecoder() is called in state %d", mFlushingVideo);
2198 mFlushingVideo = newStatus;
2199 }
2200}
2201
2202void NuPlayer2::queueDecoderShutdown(
2203 bool audio, bool video, const sp<AMessage> &reply) {
2204 ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video);
2205
2206 mDeferredActions.push_back(
2207 new FlushDecoderAction(
2208 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
2209 video ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE));
2210
2211 mDeferredActions.push_back(
2212 new SimpleAction(&NuPlayer2::performScanSources));
2213
2214 mDeferredActions.push_back(new PostMessageAction(reply));
2215
2216 processDeferredActions();
2217}
2218
2219status_t NuPlayer2::setVideoScalingMode(int32_t mode) {
2220 mVideoScalingMode = mode;
Wei Jia28288fb2017-12-15 13:45:29 -08002221 if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
2222 status_t ret = native_window_set_scaling_mode(
2223 mNativeWindow->getANativeWindow(), mVideoScalingMode);
Wei Jia53692fa2017-12-11 10:33:46 -08002224 if (ret != OK) {
2225 ALOGE("Failed to set scaling mode (%d): %s",
2226 -ret, strerror(-ret));
2227 return ret;
2228 }
2229 }
2230 return OK;
2231}
2232
Dongwon Kang9f631982018-07-10 12:34:41 -07002233status_t NuPlayer2::getTrackInfo(PlayerMessage* reply) const {
Wei Jia53692fa2017-12-11 10:33:46 -08002234 sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, this);
2235 msg->setPointer("reply", reply);
2236
2237 sp<AMessage> response;
2238 status_t err = msg->postAndAwaitResponse(&response);
2239 return err;
2240}
2241
Dongwon Kang9f631982018-07-10 12:34:41 -07002242status_t NuPlayer2::getSelectedTrack(int32_t type, PlayerMessage* reply) const {
Wei Jia53692fa2017-12-11 10:33:46 -08002243 sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, this);
2244 msg->setPointer("reply", reply);
2245 msg->setInt32("type", type);
2246
2247 sp<AMessage> response;
2248 status_t err = msg->postAndAwaitResponse(&response);
2249 if (err == OK && response != NULL) {
2250 CHECK(response->findInt32("err", &err));
2251 }
2252 return err;
2253}
2254
2255status_t NuPlayer2::selectTrack(size_t trackIndex, bool select, int64_t timeUs) {
2256 sp<AMessage> msg = new AMessage(kWhatSelectTrack, this);
2257 msg->setSize("trackIndex", trackIndex);
2258 msg->setInt32("select", select);
2259 msg->setInt64("timeUs", timeUs);
2260
2261 sp<AMessage> response;
2262 status_t err = msg->postAndAwaitResponse(&response);
2263
2264 if (err != OK) {
2265 return err;
2266 }
2267
2268 if (!response->findInt32("err", &err)) {
2269 err = OK;
2270 }
2271
2272 return err;
2273}
2274
2275status_t NuPlayer2::getCurrentPosition(int64_t *mediaUs) {
2276 sp<Renderer> renderer = mRenderer;
2277 if (renderer == NULL) {
2278 return NO_INIT;
2279 }
2280
2281 return renderer->getCurrentPosition(mediaUs);
2282}
2283
2284void NuPlayer2::getStats(Vector<sp<AMessage> > *mTrackStats) {
2285 CHECK(mTrackStats != NULL);
2286
2287 mTrackStats->clear();
2288 if (mVideoDecoder != NULL) {
2289 mTrackStats->push_back(mVideoDecoder->getStats());
2290 }
2291 if (mAudioDecoder != NULL) {
2292 mTrackStats->push_back(mAudioDecoder->getStats());
2293 }
2294}
2295
2296sp<MetaData> NuPlayer2::getFileMeta() {
2297 return mSource->getFileFormatMeta();
2298}
2299
2300float NuPlayer2::getFrameRate() {
2301 sp<MetaData> meta = mSource->getFormatMeta(false /* audio */);
2302 if (meta == NULL) {
2303 return 0;
2304 }
2305 int32_t rate;
2306 if (!meta->findInt32(kKeyFrameRate, &rate)) {
2307 // fall back to try file meta
2308 sp<MetaData> fileMeta = getFileMeta();
2309 if (fileMeta == NULL) {
2310 ALOGW("source has video meta but not file meta");
2311 return -1;
2312 }
2313 int32_t fileMetaRate;
2314 if (!fileMeta->findInt32(kKeyFrameRate, &fileMetaRate)) {
2315 return -1;
2316 }
2317 return fileMetaRate;
2318 }
2319 return rate;
2320}
2321
2322void NuPlayer2::schedulePollDuration() {
2323 sp<AMessage> msg = new AMessage(kWhatPollDuration, this);
2324 msg->setInt32("generation", mPollDurationGeneration);
2325 msg->post();
2326}
2327
2328void NuPlayer2::cancelPollDuration() {
2329 ++mPollDurationGeneration;
2330}
2331
2332void NuPlayer2::processDeferredActions() {
2333 while (!mDeferredActions.empty()) {
2334 // We won't execute any deferred actions until we're no longer in
2335 // an intermediate state, i.e. one more more decoders are currently
2336 // flushing or shutting down.
2337
2338 if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
2339 // We're currently flushing, postpone the reset until that's
2340 // completed.
2341
2342 ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
2343 mFlushingAudio, mFlushingVideo);
2344
2345 break;
2346 }
2347
2348 sp<Action> action = *mDeferredActions.begin();
2349 mDeferredActions.erase(mDeferredActions.begin());
2350
2351 action->execute(this);
2352 }
2353}
2354
2355void NuPlayer2::performSeek(int64_t seekTimeUs, MediaPlayer2SeekMode mode) {
2356 ALOGV("performSeek seekTimeUs=%lld us (%.2f secs), mode=%d",
2357 (long long)seekTimeUs, seekTimeUs / 1E6, mode);
2358
2359 if (mSource == NULL) {
2360 // This happens when reset occurs right before the loop mode
2361 // asynchronously seeks to the start of the stream.
2362 LOG_ALWAYS_FATAL_IF(mAudioDecoder != NULL || mVideoDecoder != NULL,
2363 "mSource is NULL and decoders not NULL audio(%p) video(%p)",
2364 mAudioDecoder.get(), mVideoDecoder.get());
2365 return;
2366 }
2367 mPreviousSeekTimeUs = seekTimeUs;
2368 mSource->seekTo(seekTimeUs, mode);
2369 ++mTimedTextGeneration;
2370
2371 // everything's flushed, continue playback.
2372}
2373
2374void NuPlayer2::performDecoderFlush(FlushCommand audio, FlushCommand video) {
2375 ALOGV("performDecoderFlush audio=%d, video=%d", audio, video);
2376
2377 if ((audio == FLUSH_CMD_NONE || mAudioDecoder == NULL)
2378 && (video == FLUSH_CMD_NONE || mVideoDecoder == NULL)) {
2379 return;
2380 }
2381
2382 if (audio != FLUSH_CMD_NONE && mAudioDecoder != NULL) {
2383 flushDecoder(true /* audio */, (audio == FLUSH_CMD_SHUTDOWN));
2384 }
2385
2386 if (video != FLUSH_CMD_NONE && mVideoDecoder != NULL) {
2387 flushDecoder(false /* audio */, (video == FLUSH_CMD_SHUTDOWN));
2388 }
2389}
2390
2391void NuPlayer2::performReset() {
2392 ALOGV("performReset");
2393
2394 CHECK(mAudioDecoder == NULL);
2395 CHECK(mVideoDecoder == NULL);
2396
2397 stopPlaybackTimer("performReset");
2398 stopRebufferingTimer(true);
2399
2400 cancelPollDuration();
2401
2402 ++mScanSourcesGeneration;
2403 mScanSourcesPending = false;
2404
2405 if (mRendererLooper != NULL) {
2406 if (mRenderer != NULL) {
2407 mRendererLooper->unregisterHandler(mRenderer->id());
2408 }
2409 mRendererLooper->stop();
2410 mRendererLooper.clear();
2411 }
2412 mRenderer.clear();
2413 ++mRendererGeneration;
2414
2415 if (mSource != NULL) {
2416 mSource->stop();
2417
2418 Mutex::Autolock autoLock(mSourceLock);
2419 mSource.clear();
2420 }
2421
2422 if (mDriver != NULL) {
2423 sp<NuPlayer2Driver> driver = mDriver.promote();
2424 if (driver != NULL) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002425 driver->notifyResetComplete(mSrcId);
Wei Jia53692fa2017-12-11 10:33:46 -08002426 }
2427 }
2428
2429 mStarted = false;
2430 mPrepared = false;
2431 mResetting = false;
2432 mSourceStarted = false;
2433
2434 // Modular DRM
2435 if (mCrypto != NULL) {
2436 // decoders will be flushed before this so their mCrypto would go away on their own
2437 // TODO change to ALOGV
2438 ALOGD("performReset mCrypto: %p", mCrypto.get());
2439 mCrypto.clear();
2440 }
2441 mIsDrmProtected = false;
2442}
2443
Wei Jia57aeffd2018-02-15 16:01:14 -08002444void NuPlayer2::performPlayNextDataSource() {
2445 ALOGV("performPlayNextDataSource");
2446
2447 CHECK(mAudioDecoder == NULL);
2448 CHECK(mVideoDecoder == NULL);
2449
2450 stopPlaybackTimer("performPlayNextDataSource");
2451 stopRebufferingTimer(true);
2452
2453 cancelPollDuration();
2454
2455 ++mScanSourcesGeneration;
2456 mScanSourcesPending = false;
2457
2458 ++mRendererGeneration;
2459
2460 if (mSource != NULL) {
2461 mSource->stop();
2462 }
2463
2464 long previousSrcId;
2465 {
2466 Mutex::Autolock autoLock(mSourceLock);
2467 mSource = mNextSource;
2468 mNextSource = NULL;
2469 previousSrcId = mSrcId;
2470 mSrcId = mNextSrcId;
2471 ++mNextSrcId; // to distinguish the two sources.
2472 }
2473
2474 if (mDriver != NULL) {
2475 sp<NuPlayer2Driver> driver = mDriver.promote();
2476 if (driver != NULL) {
Wei Jiacad5a3a2018-07-31 17:03:56 -07002477 notifyListener(previousSrcId, MEDIA2_INFO, MEDIA2_INFO_DATA_SOURCE_END, 0);
2478 notifyListener(mSrcId, MEDIA2_INFO, MEDIA2_INFO_DATA_SOURCE_START, 0);
Wei Jia57aeffd2018-02-15 16:01:14 -08002479 }
2480 }
2481
2482 mStarted = false;
2483 mPrepared = true; // TODO: what if it's not prepared
2484 mResetting = false;
2485 mSourceStarted = false;
2486
2487 // Modular DRM
2488 if (mCrypto != NULL) {
2489 // decoders will be flushed before this so their mCrypto would go away on their own
2490 // TODO change to ALOGV
2491 ALOGD("performReset mCrypto: %p", mCrypto.get());
2492 mCrypto.clear();
2493 }
2494 mIsDrmProtected = false;
2495
2496 if (mRenderer != NULL) {
2497 mRenderer->resume();
2498 }
2499
2500 onStart();
2501 mPausedByClient = false;
2502 notifyListener(mSrcId, MEDIA2_STARTED, 0, 0);
2503}
2504
Wei Jia53692fa2017-12-11 10:33:46 -08002505void NuPlayer2::performScanSources() {
2506 ALOGV("performScanSources");
2507
2508 if (!mStarted) {
2509 return;
2510 }
2511
2512 if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
2513 postScanSources();
2514 }
2515}
2516
Wei Jia28288fb2017-12-15 13:45:29 -08002517void NuPlayer2::performSetSurface(const sp<ANativeWindowWrapper> &nww) {
Wei Jia53692fa2017-12-11 10:33:46 -08002518 ALOGV("performSetSurface");
2519
Wei Jia28288fb2017-12-15 13:45:29 -08002520 mNativeWindow = nww;
Wei Jia53692fa2017-12-11 10:33:46 -08002521
2522 // XXX - ignore error from setVideoScalingMode for now
2523 setVideoScalingMode(mVideoScalingMode);
2524
2525 if (mDriver != NULL) {
2526 sp<NuPlayer2Driver> driver = mDriver.promote();
2527 if (driver != NULL) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002528 driver->notifySetSurfaceComplete(mSrcId);
Wei Jia53692fa2017-12-11 10:33:46 -08002529 }
2530 }
2531}
2532
2533void NuPlayer2::performResumeDecoders(bool needNotify) {
2534 if (needNotify) {
2535 mResumePending = true;
2536 if (mVideoDecoder == NULL) {
2537 // if audio-only, we can notify seek complete now,
2538 // as the resume operation will be relatively fast.
2539 finishResume();
2540 }
2541 }
2542
2543 if (mVideoDecoder != NULL) {
2544 // When there is continuous seek, MediaPlayer will cache the seek
2545 // position, and send down new seek request when previous seek is
2546 // complete. Let's wait for at least one video output frame before
2547 // notifying seek complete, so that the video thumbnail gets updated
2548 // when seekbar is dragged.
2549 mVideoDecoder->signalResume(needNotify);
2550 }
2551
2552 if (mAudioDecoder != NULL) {
2553 mAudioDecoder->signalResume(false /* needNotify */);
2554 }
2555}
2556
2557void NuPlayer2::finishResume() {
2558 if (mResumePending) {
2559 mResumePending = false;
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002560 notifyDriverSeekComplete(mSrcId);
Wei Jia53692fa2017-12-11 10:33:46 -08002561 }
2562}
2563
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002564void NuPlayer2::notifyDriverSeekComplete(int64_t srcId) {
Wei Jia53692fa2017-12-11 10:33:46 -08002565 if (mDriver != NULL) {
2566 sp<NuPlayer2Driver> driver = mDriver.promote();
2567 if (driver != NULL) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002568 driver->notifySeekComplete(srcId);
Wei Jia53692fa2017-12-11 10:33:46 -08002569 }
2570 }
2571}
2572
2573void NuPlayer2::onSourceNotify(const sp<AMessage> &msg) {
2574 int32_t what;
2575 CHECK(msg->findInt32("what", &what));
2576
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002577 int64_t srcId;
2578 CHECK(msg->findInt64("srcId", &srcId));
Wei Jia53692fa2017-12-11 10:33:46 -08002579 switch (what) {
Wei Jia53692fa2017-12-11 10:33:46 -08002580 case Source::kWhatPrepared:
2581 {
2582 ALOGV("NuPlayer2::onSourceNotify Source::kWhatPrepared source: %p", mSource.get());
2583 if (mSource == NULL) {
2584 // This is a stale notification from a source that was
2585 // asynchronously preparing when the client called reset().
2586 // We handled the reset, the source is gone.
2587 break;
2588 }
2589
2590 int32_t err;
2591 CHECK(msg->findInt32("err", &err));
2592
2593 if (err != OK) {
2594 // shut down potential secure codecs in case client never calls reset
2595 mDeferredActions.push_back(
2596 new FlushDecoderAction(FLUSH_CMD_SHUTDOWN /* audio */,
2597 FLUSH_CMD_SHUTDOWN /* video */));
2598 processDeferredActions();
2599 } else {
2600 mPrepared = true;
2601 }
2602
2603 sp<NuPlayer2Driver> driver = mDriver.promote();
2604 if (driver != NULL) {
2605 // notify duration first, so that it's definitely set when
2606 // the app received the "prepare complete" callback.
2607 int64_t durationUs;
2608 if (mSource->getDuration(&durationUs) == OK) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002609 driver->notifyDuration(srcId, durationUs);
Wei Jia53692fa2017-12-11 10:33:46 -08002610 }
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002611 driver->notifyPrepareCompleted(srcId, err);
Wei Jia53692fa2017-12-11 10:33:46 -08002612 }
2613
2614 break;
2615 }
2616
2617 // Modular DRM
2618 case Source::kWhatDrmInfo:
2619 {
Dongwon Kang41929fb2018-09-09 08:29:56 -07002620 PlayerMessage playerMsg;
Wei Jia53692fa2017-12-11 10:33:46 -08002621 sp<ABuffer> drmInfo;
2622 CHECK(msg->findBuffer("drmInfo", &drmInfo));
Dongwon Kang41929fb2018-09-09 08:29:56 -07002623 playerMsg.ParseFromArray(drmInfo->data(), drmInfo->size());
Wei Jia53692fa2017-12-11 10:33:46 -08002624
Dongwon Kang41929fb2018-09-09 08:29:56 -07002625 ALOGV("onSourceNotify() kWhatDrmInfo MEDIA2_DRM_INFO drmInfo: %p playerMsg size: %d",
2626 drmInfo.get(), playerMsg.ByteSize());
Wei Jia53692fa2017-12-11 10:33:46 -08002627
Dongwon Kang41929fb2018-09-09 08:29:56 -07002628 notifyListener(srcId, MEDIA2_DRM_INFO, 0 /* ext1 */, 0 /* ext2 */, &playerMsg);
Wei Jia53692fa2017-12-11 10:33:46 -08002629
2630 break;
2631 }
2632
2633 case Source::kWhatFlagsChanged:
2634 {
2635 uint32_t flags;
2636 CHECK(msg->findInt32("flags", (int32_t *)&flags));
2637
2638 sp<NuPlayer2Driver> driver = mDriver.promote();
2639 if (driver != NULL) {
2640
2641 ALOGV("onSourceNotify() kWhatFlagsChanged FLAG_CAN_PAUSE: %d "
2642 "FLAG_CAN_SEEK_BACKWARD: %d \n\t\t\t\t FLAG_CAN_SEEK_FORWARD: %d "
2643 "FLAG_CAN_SEEK: %d FLAG_DYNAMIC_DURATION: %d \n"
2644 "\t\t\t\t FLAG_SECURE: %d FLAG_PROTECTED: %d",
2645 (flags & Source::FLAG_CAN_PAUSE) != 0,
2646 (flags & Source::FLAG_CAN_SEEK_BACKWARD) != 0,
2647 (flags & Source::FLAG_CAN_SEEK_FORWARD) != 0,
2648 (flags & Source::FLAG_CAN_SEEK) != 0,
2649 (flags & Source::FLAG_DYNAMIC_DURATION) != 0,
2650 (flags & Source::FLAG_SECURE) != 0,
2651 (flags & Source::FLAG_PROTECTED) != 0);
2652
2653 if ((flags & NuPlayer2::Source::FLAG_CAN_SEEK) == 0) {
2654 driver->notifyListener(
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002655 srcId, MEDIA2_INFO, MEDIA2_INFO_NOT_SEEKABLE, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08002656 }
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002657 driver->notifyFlagsChanged(srcId, flags);
Wei Jia53692fa2017-12-11 10:33:46 -08002658 }
2659
2660 if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
2661 && (!(flags & Source::FLAG_DYNAMIC_DURATION))) {
2662 cancelPollDuration();
2663 } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
2664 && (flags & Source::FLAG_DYNAMIC_DURATION)
2665 && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
2666 schedulePollDuration();
2667 }
2668
2669 mSourceFlags = flags;
2670 break;
2671 }
2672
2673 case Source::kWhatVideoSizeChanged:
2674 {
2675 sp<AMessage> format;
2676 CHECK(msg->findMessage("format", &format));
2677
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002678 updateVideoSize(srcId, format);
Wei Jia53692fa2017-12-11 10:33:46 -08002679 break;
2680 }
2681
2682 case Source::kWhatBufferingUpdate:
2683 {
2684 int32_t percentage;
2685 CHECK(msg->findInt32("percentage", &percentage));
2686
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002687 notifyListener(srcId, MEDIA2_BUFFERING_UPDATE, percentage, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08002688 break;
2689 }
2690
2691 case Source::kWhatPauseOnBufferingStart:
2692 {
2693 // ignore if not playing
2694 if (mStarted) {
2695 ALOGI("buffer low, pausing...");
2696
2697 startRebufferingTimer();
2698 mPausedForBuffering = true;
2699 onPause();
2700 }
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002701 notifyListener(srcId, MEDIA2_INFO, MEDIA2_INFO_BUFFERING_START, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08002702 break;
2703 }
2704
2705 case Source::kWhatResumeOnBufferingEnd:
2706 {
2707 // ignore if not playing
2708 if (mStarted) {
2709 ALOGI("buffer ready, resuming...");
2710
2711 stopRebufferingTimer(false);
2712 mPausedForBuffering = false;
2713
2714 // do not resume yet if client didn't unpause
2715 if (!mPausedByClient) {
2716 onResume();
2717 }
2718 }
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002719 notifyListener(srcId, MEDIA2_INFO, MEDIA2_INFO_BUFFERING_END, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08002720 break;
2721 }
2722
2723 case Source::kWhatCacheStats:
2724 {
2725 int32_t kbps;
2726 CHECK(msg->findInt32("bandwidth", &kbps));
2727
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002728 notifyListener(srcId, MEDIA2_INFO, MEDIA2_INFO_NETWORK_BANDWIDTH, kbps);
Wei Jia53692fa2017-12-11 10:33:46 -08002729 break;
2730 }
2731
2732 case Source::kWhatSubtitleData:
2733 {
2734 sp<ABuffer> buffer;
2735 CHECK(msg->findBuffer("buffer", &buffer));
2736
2737 sendSubtitleData(buffer, 0 /* baseIndex */);
2738 break;
2739 }
2740
2741 case Source::kWhatTimedMetaData:
2742 {
2743 sp<ABuffer> buffer;
2744 if (!msg->findBuffer("buffer", &buffer)) {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002745 notifyListener(srcId, MEDIA2_INFO, MEDIA2_INFO_METADATA_UPDATE, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08002746 } else {
2747 sendTimedMetaData(buffer);
2748 }
2749 break;
2750 }
2751
2752 case Source::kWhatTimedTextData:
2753 {
2754 int32_t generation;
2755 if (msg->findInt32("generation", &generation)
2756 && generation != mTimedTextGeneration) {
2757 break;
2758 }
2759
2760 sp<ABuffer> buffer;
2761 CHECK(msg->findBuffer("buffer", &buffer));
2762
2763 sp<NuPlayer2Driver> driver = mDriver.promote();
2764 if (driver == NULL) {
2765 break;
2766 }
2767
Wei Jia800fe372018-02-20 15:00:45 -08002768 int64_t posMs;
Wei Jia53692fa2017-12-11 10:33:46 -08002769 int64_t timeUs, posUs;
2770 driver->getCurrentPosition(&posMs);
Wei Jia800fe372018-02-20 15:00:45 -08002771 posUs = posMs * 1000ll;
Wei Jia53692fa2017-12-11 10:33:46 -08002772 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2773
2774 if (posUs < timeUs) {
2775 if (!msg->findInt32("generation", &generation)) {
2776 msg->setInt32("generation", mTimedTextGeneration);
2777 }
2778 msg->post(timeUs - posUs);
2779 } else {
2780 sendTimedTextData(buffer);
2781 }
2782 break;
2783 }
2784
2785 case Source::kWhatQueueDecoderShutdown:
2786 {
2787 int32_t audio, video;
2788 CHECK(msg->findInt32("audio", &audio));
2789 CHECK(msg->findInt32("video", &video));
2790
2791 sp<AMessage> reply;
2792 CHECK(msg->findMessage("reply", &reply));
2793
2794 queueDecoderShutdown(audio, video, reply);
2795 break;
2796 }
2797
2798 case Source::kWhatDrmNoLicense:
2799 {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002800 notifyListener(srcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
Wei Jia53692fa2017-12-11 10:33:46 -08002801 break;
2802 }
2803
2804 default:
2805 TRESPASS();
2806 }
2807}
2808
2809void NuPlayer2::onClosedCaptionNotify(const sp<AMessage> &msg) {
2810 int32_t what;
2811 CHECK(msg->findInt32("what", &what));
2812
2813 switch (what) {
2814 case NuPlayer2::CCDecoder::kWhatClosedCaptionData:
2815 {
2816 sp<ABuffer> buffer;
2817 CHECK(msg->findBuffer("buffer", &buffer));
2818
2819 size_t inbandTracks = 0;
2820 if (mSource != NULL) {
2821 inbandTracks = mSource->getTrackCount();
2822 }
2823
2824 sendSubtitleData(buffer, inbandTracks);
2825 break;
2826 }
2827
2828 case NuPlayer2::CCDecoder::kWhatTrackAdded:
2829 {
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002830 notifyListener(mSrcId, MEDIA2_INFO, MEDIA2_INFO_METADATA_UPDATE, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08002831
2832 break;
2833 }
2834
2835 default:
2836 TRESPASS();
2837 }
2838
2839
2840}
2841
2842void NuPlayer2::sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex) {
2843 int32_t trackIndex;
2844 int64_t timeUs, durationUs;
Robert Shihd83d4f42018-02-24 19:02:46 -08002845 CHECK(buffer->meta()->findInt32(AMEDIAFORMAT_KEY_TRACK_INDEX, &trackIndex));
Wei Jia53692fa2017-12-11 10:33:46 -08002846 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2847 CHECK(buffer->meta()->findInt64("durationUs", &durationUs));
2848
Dongwon Kang41929fb2018-09-09 08:29:56 -07002849 PlayerMessage playerMsg;
2850 playerMsg.add_values()->set_int32_value(trackIndex + baseIndex);
2851 playerMsg.add_values()->set_int64_value(timeUs);
2852 playerMsg.add_values()->set_int64_value(durationUs);
2853 playerMsg.add_values()->set_bytes_value(buffer->data(), buffer->size());
Wei Jia53692fa2017-12-11 10:33:46 -08002854
Dongwon Kang41929fb2018-09-09 08:29:56 -07002855 notifyListener(mSrcId, MEDIA2_SUBTITLE_DATA, 0, 0, &playerMsg);
Wei Jia53692fa2017-12-11 10:33:46 -08002856}
2857
2858void NuPlayer2::sendTimedMetaData(const sp<ABuffer> &buffer) {
2859 int64_t timeUs;
2860 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2861
Dongwon Kang41929fb2018-09-09 08:29:56 -07002862 PlayerMessage playerMsg;
2863 playerMsg.add_values()->set_int64_value(timeUs);
2864 playerMsg.add_values()->set_bytes_value(buffer->data(), buffer->size());
Wei Jia53692fa2017-12-11 10:33:46 -08002865
Dongwon Kang41929fb2018-09-09 08:29:56 -07002866 notifyListener(mSrcId, MEDIA2_META_DATA, 0, 0, &playerMsg);
Wei Jia53692fa2017-12-11 10:33:46 -08002867}
2868
2869void NuPlayer2::sendTimedTextData(const sp<ABuffer> &buffer) {
2870 const void *data;
2871 size_t size = 0;
2872 int64_t timeUs;
Dongwon Kanga0e816a2018-09-10 19:46:49 -07002873 int32_t flag = TextDescriptions2::IN_BAND_TEXT_3GPP;
Wei Jia53692fa2017-12-11 10:33:46 -08002874
2875 AString mime;
2876 CHECK(buffer->meta()->findString("mime", &mime));
2877 CHECK(strcasecmp(mime.c_str(), MEDIA_MIMETYPE_TEXT_3GPP) == 0);
2878
2879 data = buffer->data();
2880 size = buffer->size();
2881
Dongwon Kanga0e816a2018-09-10 19:46:49 -07002882 PlayerMessage playerMsg;
Wei Jia53692fa2017-12-11 10:33:46 -08002883 if (size > 0) {
2884 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2885 int32_t global = 0;
2886 if (buffer->meta()->findInt32("global", &global) && global) {
Dongwon Kanga0e816a2018-09-10 19:46:49 -07002887 flag |= TextDescriptions2::GLOBAL_DESCRIPTIONS;
Wei Jia53692fa2017-12-11 10:33:46 -08002888 } else {
Dongwon Kanga0e816a2018-09-10 19:46:49 -07002889 flag |= TextDescriptions2::LOCAL_DESCRIPTIONS;
Wei Jia53692fa2017-12-11 10:33:46 -08002890 }
Dongwon Kanga0e816a2018-09-10 19:46:49 -07002891 TextDescriptions2::getPlayerMessageOfDescriptions(
2892 (const uint8_t *)data, size, flag, timeUs / 1000, &playerMsg);
Wei Jia53692fa2017-12-11 10:33:46 -08002893 }
2894
Dongwon Kanga0e816a2018-09-10 19:46:49 -07002895 if (playerMsg.values_size() > 0) {
2896 notifyListener(mSrcId, MEDIA2_TIMED_TEXT, 0, 0, &playerMsg);
Wei Jia53692fa2017-12-11 10:33:46 -08002897 } else { // send an empty timed text
Wei Jiad2bb1bd2018-02-08 09:47:37 -08002898 notifyListener(mSrcId, MEDIA2_TIMED_TEXT, 0, 0);
Wei Jia53692fa2017-12-11 10:33:46 -08002899 }
2900}
2901
2902const char *NuPlayer2::getDataSourceType() {
2903 switch (mDataSourceType) {
2904 case DATA_SOURCE_TYPE_HTTP_LIVE:
2905 return "HTTPLive";
2906
2907 case DATA_SOURCE_TYPE_RTSP:
2908 return "RTSP";
2909
2910 case DATA_SOURCE_TYPE_GENERIC_URL:
2911 return "GenURL";
2912
2913 case DATA_SOURCE_TYPE_GENERIC_FD:
2914 return "GenFD";
2915
2916 case DATA_SOURCE_TYPE_MEDIA:
2917 return "Media";
2918
Wei Jia53692fa2017-12-11 10:33:46 -08002919 case DATA_SOURCE_TYPE_NONE:
2920 default:
2921 return "None";
2922 }
2923 }
2924
2925// Modular DRM begin
2926status_t NuPlayer2::prepareDrm(const uint8_t uuid[16], const Vector<uint8_t> &drmSessionId)
2927{
2928 ALOGV("prepareDrm ");
2929
2930 // Passing to the looper anyway; called in a pre-config prepared state so no race on mCrypto
2931 sp<AMessage> msg = new AMessage(kWhatPrepareDrm, this);
2932 // synchronous call so just passing the address but with local copies of "const" args
2933 uint8_t UUID[16];
2934 memcpy(UUID, uuid, sizeof(UUID));
2935 Vector<uint8_t> sessionId = drmSessionId;
2936 msg->setPointer("uuid", (void*)UUID);
2937 msg->setPointer("drmSessionId", (void*)&sessionId);
2938
2939 sp<AMessage> response;
2940 status_t status = msg->postAndAwaitResponse(&response);
2941
2942 if (status == OK && response != NULL) {
2943 CHECK(response->findInt32("status", &status));
2944 ALOGV("prepareDrm ret: %d ", status);
2945 } else {
2946 ALOGE("prepareDrm err: %d", status);
2947 }
2948
2949 return status;
2950}
2951
2952status_t NuPlayer2::releaseDrm()
2953{
2954 ALOGV("releaseDrm ");
2955
2956 sp<AMessage> msg = new AMessage(kWhatReleaseDrm, this);
2957
2958 sp<AMessage> response;
2959 status_t status = msg->postAndAwaitResponse(&response);
2960
2961 if (status == OK && response != NULL) {
2962 CHECK(response->findInt32("status", &status));
2963 ALOGV("releaseDrm ret: %d ", status);
2964 } else {
2965 ALOGE("releaseDrm err: %d", status);
2966 }
2967
2968 return status;
2969}
2970
2971status_t NuPlayer2::onPrepareDrm(const sp<AMessage> &msg)
2972{
2973 // TODO change to ALOGV
2974 ALOGD("onPrepareDrm ");
2975
2976 status_t status = INVALID_OPERATION;
2977 if (mSource == NULL) {
2978 ALOGE("onPrepareDrm: No source. onPrepareDrm failed with %d.", status);
2979 return status;
2980 }
2981
2982 uint8_t *uuid;
2983 Vector<uint8_t> *drmSessionId;
2984 CHECK(msg->findPointer("uuid", (void**)&uuid));
2985 CHECK(msg->findPointer("drmSessionId", (void**)&drmSessionId));
2986
2987 status = OK;
2988 sp<AMediaCryptoWrapper> crypto = NULL;
2989
2990 status = mSource->prepareDrm(uuid, *drmSessionId, &crypto);
2991 if (crypto == NULL) {
2992 ALOGE("onPrepareDrm: mSource->prepareDrm failed. status: %d", status);
2993 return status;
2994 }
2995 ALOGV("onPrepareDrm: mSource->prepareDrm succeeded");
2996
2997 if (mCrypto != NULL) {
2998 ALOGE("onPrepareDrm: Unexpected. Already having mCrypto: %p", mCrypto.get());
2999 mCrypto.clear();
3000 }
3001
3002 mCrypto = crypto;
3003 mIsDrmProtected = true;
3004 // TODO change to ALOGV
3005 ALOGD("onPrepareDrm: mCrypto: %p", mCrypto.get());
3006
3007 return status;
3008}
3009
3010status_t NuPlayer2::onReleaseDrm()
3011{
3012 // TODO change to ALOGV
3013 ALOGD("onReleaseDrm ");
3014
3015 if (!mIsDrmProtected) {
3016 ALOGW("onReleaseDrm: Unexpected. mIsDrmProtected is already false.");
3017 }
3018
3019 mIsDrmProtected = false;
3020
3021 status_t status;
3022 if (mCrypto != NULL) {
3023 // notifying the source first before removing crypto from codec
3024 if (mSource != NULL) {
3025 mSource->releaseDrm();
3026 }
3027
3028 status=OK;
3029 // first making sure the codecs have released their crypto reference
3030 const sp<DecoderBase> &videoDecoder = getDecoder(false/*audio*/);
3031 if (videoDecoder != NULL) {
3032 status = videoDecoder->releaseCrypto();
3033 ALOGV("onReleaseDrm: video decoder ret: %d", status);
3034 }
3035
3036 const sp<DecoderBase> &audioDecoder = getDecoder(true/*audio*/);
3037 if (audioDecoder != NULL) {
3038 status_t status_audio = audioDecoder->releaseCrypto();
3039 if (status == OK) { // otherwise, returning the first error
3040 status = status_audio;
3041 }
3042 ALOGV("onReleaseDrm: audio decoder ret: %d", status_audio);
3043 }
3044
3045 // TODO change to ALOGV
3046 ALOGD("onReleaseDrm: mCrypto: %p", mCrypto.get());
3047 mCrypto.clear();
3048 } else { // mCrypto == NULL
3049 ALOGE("onReleaseDrm: Unexpected. There is no crypto.");
3050 status = INVALID_OPERATION;
3051 }
3052
3053 return status;
3054}
3055// Modular DRM end
3056////////////////////////////////////////////////////////////////////////////////
3057
3058sp<AMessage> NuPlayer2::Source::getFormat(bool audio) {
3059 sp<MetaData> meta = getFormatMeta(audio);
3060
3061 if (meta == NULL) {
3062 return NULL;
3063 }
3064
3065 sp<AMessage> msg = new AMessage;
3066
3067 if(convertMetaDataToMessage(meta, &msg) == OK) {
3068 return msg;
3069 }
3070 return NULL;
3071}
3072
3073void NuPlayer2::Source::notifyFlagsChanged(uint32_t flags) {
3074 sp<AMessage> notify = dupNotify();
3075 notify->setInt32("what", kWhatFlagsChanged);
3076 notify->setInt32("flags", flags);
3077 notify->post();
3078}
3079
3080void NuPlayer2::Source::notifyVideoSizeChanged(const sp<AMessage> &format) {
3081 sp<AMessage> notify = dupNotify();
3082 notify->setInt32("what", kWhatVideoSizeChanged);
3083 notify->setMessage("format", format);
3084 notify->post();
3085}
3086
3087void NuPlayer2::Source::notifyPrepared(status_t err) {
3088 ALOGV("Source::notifyPrepared %d", err);
3089 sp<AMessage> notify = dupNotify();
3090 notify->setInt32("what", kWhatPrepared);
3091 notify->setInt32("err", err);
3092 notify->post();
3093}
3094
3095void NuPlayer2::Source::notifyDrmInfo(const sp<ABuffer> &drmInfoBuffer)
3096{
3097 ALOGV("Source::notifyDrmInfo");
3098
3099 sp<AMessage> notify = dupNotify();
3100 notify->setInt32("what", kWhatDrmInfo);
3101 notify->setBuffer("drmInfo", drmInfoBuffer);
3102
3103 notify->post();
3104}
3105
Wei Jia53692fa2017-12-11 10:33:46 -08003106void NuPlayer2::Source::onMessageReceived(const sp<AMessage> & /* msg */) {
3107 TRESPASS();
3108}
3109
3110} // namespace android