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