blob: 9729d86964be750f88e847a5676cd1aec91e4fdb [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 "NuPlayer2Decoder"
19#include <utils/Log.h>
20#include <inttypes.h>
21
22#include <algorithm>
23
Wei Jia53692fa2017-12-11 10:33:46 -080024#include "NuPlayer2CCDecoder.h"
25#include "NuPlayer2Decoder.h"
26#include "NuPlayer2Drm.h"
27#include "NuPlayer2Renderer.h"
28#include "NuPlayer2Source.h"
29
30#include <cutils/properties.h>
Dongwon Kangbc8f53b2018-01-25 17:01:44 -080031#include <media/MediaBufferHolder.h>
Wei Jia53692fa2017-12-11 10:33:46 -080032#include <media/MediaCodecBuffer.h>
33#include <media/NdkMediaCodec.h>
Wei Jia28288fb2017-12-15 13:45:29 -080034#include <media/NdkWrapper.h>
Wei Jia53692fa2017-12-11 10:33:46 -080035#include <media/stagefright/foundation/ABuffer.h>
36#include <media/stagefright/foundation/ADebug.h>
37#include <media/stagefright/foundation/AMessage.h>
38#include <media/stagefright/foundation/avc_utils.h>
39#include <media/stagefright/MediaBuffer.h>
40#include <media/stagefright/MediaDefs.h>
41#include <media/stagefright/MediaErrors.h>
42#include <media/stagefright/SurfaceUtils.h>
Wei Jia53692fa2017-12-11 10:33:46 -080043
Wei Jia4049f132018-01-22 10:37:31 -080044#include <system/window.h>
Wei Jia53692fa2017-12-11 10:33:46 -080045#include "ATSParser.h"
46
47namespace android {
48
49static float kDisplayRefreshingRate = 60.f; // TODO: get this from the display
50
51// The default total video frame rate of a stream when that info is not available from
52// the source.
53static float kDefaultVideoFrameRateTotal = 30.f;
54
55static inline bool getAudioDeepBufferSetting() {
56 return property_get_bool("media.stagefright.audio.deep", false /* default_value */);
57}
58
59NuPlayer2::Decoder::Decoder(
60 const sp<AMessage> &notify,
61 const sp<Source> &source,
62 pid_t pid,
63 uid_t uid,
64 const sp<Renderer> &renderer,
Wei Jia28288fb2017-12-15 13:45:29 -080065 const sp<ANativeWindowWrapper> &nww,
Wei Jia53692fa2017-12-11 10:33:46 -080066 const sp<CCDecoder> &ccDecoder)
67 : DecoderBase(notify),
Wei Jia28288fb2017-12-15 13:45:29 -080068 mNativeWindow(nww),
Wei Jia53692fa2017-12-11 10:33:46 -080069 mSource(source),
70 mRenderer(renderer),
71 mCCDecoder(ccDecoder),
72 mPid(pid),
73 mUid(uid),
Chih-Hung Hsiehd42529d2018-12-11 13:53:10 -080074 mSkipRenderingUntilMediaTimeUs(-1LL),
75 mNumFramesTotal(0LL),
76 mNumInputFramesDropped(0LL),
77 mNumOutputFramesDropped(0LL),
Wei Jia53692fa2017-12-11 10:33:46 -080078 mVideoWidth(0),
79 mVideoHeight(0),
80 mIsAudio(true),
81 mIsVideoAVC(false),
82 mIsSecure(false),
83 mIsEncrypted(false),
84 mIsEncryptedObservedEarlier(false),
85 mFormatChangePending(false),
86 mTimeChangePending(false),
87 mFrameRateTotal(kDefaultVideoFrameRateTotal),
88 mPlaybackSpeed(1.0f),
89 mNumVideoTemporalLayerTotal(1), // decode all layers
90 mNumVideoTemporalLayerAllowed(1),
91 mCurrentMaxVideoTemporalLayerId(0),
92 mResumePending(false),
93 mComponentName("decoder") {
94 mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
95}
96
97NuPlayer2::Decoder::~Decoder() {
98 // Need to stop looper first since mCodec could be accessed on the mDecoderLooper.
99 stopLooper();
100 if (mCodec != NULL) {
101 mCodec->release();
102 }
103 releaseAndResetMediaBuffers();
104}
105
106sp<AMessage> NuPlayer2::Decoder::getStats() const {
107 mStats->setInt64("frames-total", mNumFramesTotal);
108 mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
109 mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
Ray Essick89269d62019-01-20 14:46:19 -0800110 mStats->setFloat("frame-rate-total", mFrameRateTotal);
111
Wei Jia53692fa2017-12-11 10:33:46 -0800112 return mStats;
113}
114
Wei Jia28288fb2017-12-15 13:45:29 -0800115status_t NuPlayer2::Decoder::setVideoSurface(const sp<ANativeWindowWrapper> &nww) {
116 if (nww == NULL || nww->getANativeWindow() == NULL
117 || ADebug::isExperimentEnabled("legacy-setsurface")) {
Wei Jia53692fa2017-12-11 10:33:46 -0800118 return BAD_VALUE;
119 }
120
121 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
122
Wei Jia28288fb2017-12-15 13:45:29 -0800123 msg->setObject("surface", nww);
Wei Jia53692fa2017-12-11 10:33:46 -0800124 sp<AMessage> response;
125 status_t err = msg->postAndAwaitResponse(&response);
126 if (err == OK && response != NULL) {
127 CHECK(response->findInt32("err", &err));
128 }
129 return err;
130}
131
132void NuPlayer2::Decoder::onMessageReceived(const sp<AMessage> &msg) {
133 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
134
135 switch (msg->what()) {
136 case kWhatCodecNotify:
137 {
138 int32_t cbID;
139 CHECK(msg->findInt32("callbackID", &cbID));
140
141 ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
142 mIsAudio ? "audio" : "video", cbID, mPaused);
143
144 if (mPaused) {
145 break;
146 }
147
148 switch (cbID) {
149 case AMediaCodecWrapper::CB_INPUT_AVAILABLE:
150 {
151 int32_t index;
152 CHECK(msg->findInt32("index", &index));
153
154 handleAnInputBuffer(index);
155 break;
156 }
157
158 case AMediaCodecWrapper::CB_OUTPUT_AVAILABLE:
159 {
160 int32_t index;
161 size_t offset;
162 size_t size;
163 int64_t timeUs;
164 int32_t flags;
165
166 CHECK(msg->findInt32("index", &index));
167 CHECK(msg->findSize("offset", &offset));
168 CHECK(msg->findSize("size", &size));
169 CHECK(msg->findInt64("timeUs", &timeUs));
170 CHECK(msg->findInt32("flags", &flags));
171
172 handleAnOutputBuffer(index, offset, size, timeUs, flags);
173 break;
174 }
175
176 case AMediaCodecWrapper::CB_OUTPUT_FORMAT_CHANGED:
177 {
178 sp<AMessage> format;
179 CHECK(msg->findMessage("format", &format));
180
181 handleOutputFormatChange(format);
182 break;
183 }
184
185 case AMediaCodecWrapper::CB_ERROR:
186 {
187 status_t err;
188 CHECK(msg->findInt32("err", &err));
189 ALOGE("Decoder (%s) reported error : 0x%x",
190 mIsAudio ? "audio" : "video", err);
191
192 handleError(err);
193 break;
194 }
195
196 default:
197 {
198 TRESPASS();
199 break;
200 }
201 }
202
203 break;
204 }
205
206 case kWhatRenderBuffer:
207 {
208 if (!isStaleReply(msg)) {
209 onRenderBuffer(msg);
210 }
211 break;
212 }
213
214 case kWhatAudioOutputFormatChanged:
215 {
216 if (!isStaleReply(msg)) {
217 status_t err;
218 if (msg->findInt32("err", &err) && err != OK) {
219 ALOGE("Renderer reported 0x%x when changing audio output format", err);
220 handleError(err);
221 }
222 }
223 break;
224 }
225
226 case kWhatSetVideoSurface:
227 {
228 sp<AReplyToken> replyID;
229 CHECK(msg->senderAwaitsResponse(&replyID));
230
231 sp<RefBase> obj;
232 CHECK(msg->findObject("surface", &obj));
Wei Jia28288fb2017-12-15 13:45:29 -0800233 sp<ANativeWindowWrapper> nww =
234 static_cast<ANativeWindowWrapper *>(obj.get()); // non-null
235 if (nww == NULL || nww->getANativeWindow() == NULL) {
236 break;
237 }
Wei Jia53692fa2017-12-11 10:33:46 -0800238 int32_t err = INVALID_OPERATION;
Wei Jia28288fb2017-12-15 13:45:29 -0800239 // NOTE: in practice mNativeWindow is always non-null,
240 // but checking here for completeness
241 if (mCodec != NULL
242 && mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -0800243 // TODO: once AwesomePlayer is removed, remove this automatic connecting
244 // to the surface by MediaPlayerService.
245 //
Wei Jia28288fb2017-12-15 13:45:29 -0800246 // at this point MediaPlayer2Manager::client has already connected to the
Wei Jia53692fa2017-12-11 10:33:46 -0800247 // surface, which MediaCodec does not expect
Wei Jia4049f132018-01-22 10:37:31 -0800248 err = native_window_api_disconnect(nww->getANativeWindow(),
249 NATIVE_WINDOW_API_MEDIA);
Wei Jia53692fa2017-12-11 10:33:46 -0800250 if (err == OK) {
Wei Jia28288fb2017-12-15 13:45:29 -0800251 err = mCodec->setOutputSurface(nww);
Wei Jia53692fa2017-12-11 10:33:46 -0800252 ALOGI_IF(err, "codec setOutputSurface returned: %d", err);
253 if (err == OK) {
254 // reconnect to the old surface as MPS::Client will expect to
255 // be able to disconnect from it.
Wei Jia4049f132018-01-22 10:37:31 -0800256 (void)native_window_api_connect(mNativeWindow->getANativeWindow(),
257 NATIVE_WINDOW_API_MEDIA);
258
Wei Jia28288fb2017-12-15 13:45:29 -0800259 mNativeWindow = nww;
Wei Jia53692fa2017-12-11 10:33:46 -0800260 }
261 }
262 if (err != OK) {
263 // reconnect to the new surface on error as MPS::Client will expect to
264 // be able to disconnect from it.
Wei Jia4049f132018-01-22 10:37:31 -0800265 (void)native_window_api_connect(nww->getANativeWindow(),
266 NATIVE_WINDOW_API_MEDIA);
Wei Jia53692fa2017-12-11 10:33:46 -0800267 }
268 }
269
270 sp<AMessage> response = new AMessage;
271 response->setInt32("err", err);
272 response->postReply(replyID);
273 break;
274 }
275
276 case kWhatDrmReleaseCrypto:
277 {
278 ALOGV("kWhatDrmReleaseCrypto");
279 onReleaseCrypto(msg);
280 break;
281 }
282
283 default:
284 DecoderBase::onMessageReceived(msg);
285 break;
286 }
287}
288
289void NuPlayer2::Decoder::onConfigure(const sp<AMessage> &format) {
290 ALOGV("[%s] onConfigure (format=%s)", mComponentName.c_str(), format->debugString().c_str());
291 CHECK(mCodec == NULL);
292
293 mFormatChangePending = false;
294 mTimeChangePending = false;
295
296 ++mBufferGeneration;
297
298 AString mime;
299 CHECK(format->findString("mime", &mime));
300
301 mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
302 mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
303
304 mComponentName = mime;
305 mComponentName.append(" decoder");
Wei Jia28288fb2017-12-15 13:45:29 -0800306 ALOGV("[%s] onConfigure (nww=%p)", mComponentName.c_str(),
307 (mNativeWindow == NULL ? NULL : mNativeWindow->getANativeWindow()));
Wei Jia53692fa2017-12-11 10:33:46 -0800308
309 mCodec = AMediaCodecWrapper::CreateDecoderByType(mime);
310 int32_t secure = 0;
311 if (format->findInt32("secure", &secure) && secure != 0) {
312 if (mCodec != NULL) {
313 if (mCodec->getName(&mComponentName) == OK) {
314 mComponentName.append(".secure");
315 mCodec->release();
316 ALOGI("[%s] creating", mComponentName.c_str());
317 mCodec = AMediaCodecWrapper::CreateCodecByName(mComponentName);
318 } else {
319 mCodec = NULL;
320 }
321 }
322 }
323 if (mCodec == NULL) {
324 ALOGE("Failed to create %s%s decoder",
325 (secure ? "secure " : ""), mime.c_str());
326 handleError(NO_INIT);
327 return;
328 }
329 mIsSecure = secure;
330
331 mCodec->getName(&mComponentName);
332
333 status_t err;
Wei Jia28288fb2017-12-15 13:45:29 -0800334 if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -0800335 // disconnect from surface as MediaCodec will reconnect
Wei Jia4049f132018-01-22 10:37:31 -0800336 err = native_window_api_disconnect(mNativeWindow->getANativeWindow(),
337 NATIVE_WINDOW_API_MEDIA);
Wei Jia53692fa2017-12-11 10:33:46 -0800338 // We treat this as a warning, as this is a preparatory step.
339 // Codec will try to connect to the surface, which is where
340 // any error signaling will occur.
341 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
342 }
343
344 // Modular DRM
345 sp<RefBase> objCrypto;
346 format->findObject("crypto", &objCrypto);
347 sp<AMediaCryptoWrapper> crypto = static_cast<AMediaCryptoWrapper *>(objCrypto.get());
348 // non-encrypted source won't have a crypto
349 mIsEncrypted = (crypto != NULL);
350 // configure is called once; still using OR in case the behavior changes.
351 mIsEncryptedObservedEarlier = mIsEncryptedObservedEarlier || mIsEncrypted;
352 ALOGV("onConfigure mCrypto: %p, mIsSecure: %d", crypto.get(), mIsSecure);
353
354 err = mCodec->configure(
355 AMediaFormatWrapper::Create(format),
Wei Jia28288fb2017-12-15 13:45:29 -0800356 mNativeWindow,
Wei Jia53692fa2017-12-11 10:33:46 -0800357 crypto,
358 0 /* flags */);
359
360 if (err != OK) {
361 ALOGE("Failed to configure [%s] decoder (err=%d)", mComponentName.c_str(), err);
362 mCodec->release();
363 mCodec.clear();
364 handleError(err);
365 return;
366 }
367 rememberCodecSpecificData(format);
368
369 // the following should work in configured state
370 sp<AMediaFormatWrapper> outputFormat = mCodec->getOutputFormat();
371 if (outputFormat == NULL) {
372 handleError(INVALID_OPERATION);
373 return;
374 }
375 mInputFormat = mCodec->getInputFormat();
376 if (mInputFormat == NULL) {
377 handleError(INVALID_OPERATION);
378 return;
379 }
380
381 mStats->setString("mime", mime.c_str());
382 mStats->setString("component-name", mComponentName.c_str());
383
384 if (!mIsAudio) {
385 int32_t width, height;
386 if (outputFormat->getInt32("width", &width)
387 && outputFormat->getInt32("height", &height)) {
388 mStats->setInt32("width", width);
389 mStats->setInt32("height", height);
390 }
391 }
392
393 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
394 mCodec->setCallback(reply);
395
396 err = mCodec->start();
397 if (err != OK) {
398 ALOGE("Failed to start [%s] decoder (err=%d)", mComponentName.c_str(), err);
399 mCodec->release();
400 mCodec.clear();
401 handleError(err);
402 return;
403 }
404
405 releaseAndResetMediaBuffers();
406
407 mPaused = false;
408 mResumePending = false;
409}
410
411void NuPlayer2::Decoder::onSetParameters(const sp<AMessage> &params) {
412 bool needAdjustLayers = false;
413 float frameRateTotal;
414 if (params->findFloat("frame-rate-total", &frameRateTotal)
415 && mFrameRateTotal != frameRateTotal) {
416 needAdjustLayers = true;
417 mFrameRateTotal = frameRateTotal;
418 }
419
420 int32_t numVideoTemporalLayerTotal;
421 if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
422 && numVideoTemporalLayerTotal >= 0
423 && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
424 && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
425 needAdjustLayers = true;
426 mNumVideoTemporalLayerTotal = std::max(numVideoTemporalLayerTotal, 1);
427 }
428
429 if (needAdjustLayers && mNumVideoTemporalLayerTotal > 1) {
430 // TODO: For now, layer fps is calculated for some specific architectures.
431 // But it really should be extracted from the stream.
432 mVideoTemporalLayerAggregateFps[0] =
Chih-Hung Hsiehd42529d2018-12-11 13:53:10 -0800433 mFrameRateTotal / (float)(1LL << (mNumVideoTemporalLayerTotal - 1));
Wei Jia53692fa2017-12-11 10:33:46 -0800434 for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
435 mVideoTemporalLayerAggregateFps[i] =
Chih-Hung Hsiehd42529d2018-12-11 13:53:10 -0800436 mFrameRateTotal / (float)(1LL << (mNumVideoTemporalLayerTotal - i))
Wei Jia53692fa2017-12-11 10:33:46 -0800437 + mVideoTemporalLayerAggregateFps[i - 1];
438 }
439 }
440
441 float playbackSpeed;
442 if (params->findFloat("playback-speed", &playbackSpeed)
443 && mPlaybackSpeed != playbackSpeed) {
444 needAdjustLayers = true;
445 mPlaybackSpeed = playbackSpeed;
446 }
447
448 if (needAdjustLayers) {
449 float decodeFrameRate = mFrameRateTotal;
450 // enable temporal layering optimization only if we know the layering depth
451 if (mNumVideoTemporalLayerTotal > 1) {
452 int32_t layerId;
453 for (layerId = 0; layerId < mNumVideoTemporalLayerTotal - 1; ++layerId) {
454 if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
455 >= kDisplayRefreshingRate * 0.9) {
456 break;
457 }
458 }
459 mNumVideoTemporalLayerAllowed = layerId + 1;
460 decodeFrameRate = mVideoTemporalLayerAggregateFps[layerId];
461 }
462 ALOGV("onSetParameters: allowed layers=%d, decodeFps=%g",
463 mNumVideoTemporalLayerAllowed, decodeFrameRate);
464
465 if (mCodec == NULL) {
466 ALOGW("onSetParameters called before codec is created.");
467 return;
468 }
469
470 sp<AMediaFormatWrapper> codecParams = new AMediaFormatWrapper();
471 codecParams->setFloat("operating-rate", decodeFrameRate * mPlaybackSpeed);
472 mCodec->setParameters(codecParams);
473 }
474}
475
476void NuPlayer2::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
477 mRenderer = renderer;
478}
479
480void NuPlayer2::Decoder::onResume(bool notifyComplete) {
481 mPaused = false;
482
483 if (notifyComplete) {
484 mResumePending = true;
485 }
486
487 if (mCodec == NULL) {
488 ALOGE("[%s] onResume without a valid codec", mComponentName.c_str());
489 handleError(NO_INIT);
490 return;
491 }
492 mCodec->start();
493}
494
495void NuPlayer2::Decoder::doFlush(bool notifyComplete) {
496 if (mCCDecoder != NULL) {
497 mCCDecoder->flush();
498 }
499
500 if (mRenderer != NULL) {
501 mRenderer->flush(mIsAudio, notifyComplete);
502 mRenderer->signalTimeDiscontinuity();
503 }
504
505 status_t err = OK;
506 if (mCodec != NULL) {
507 err = mCodec->flush();
508 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
509 ++mBufferGeneration;
510 }
511
512 if (err != OK) {
513 ALOGE("failed to flush [%s] (err=%d)", mComponentName.c_str(), err);
514 handleError(err);
515 // finish with posting kWhatFlushCompleted.
516 // we attempt to release the buffers even if flush fails.
517 }
518 releaseAndResetMediaBuffers();
519 mPaused = true;
520}
521
522
523void NuPlayer2::Decoder::onFlush() {
524 doFlush(true);
525
526 if (isDiscontinuityPending()) {
527 // This could happen if the client starts seeking/shutdown
528 // after we queued an EOS for discontinuities.
529 // We can consider discontinuity handled.
530 finishHandleDiscontinuity(false /* flushOnTimeChange */);
531 }
532
533 sp<AMessage> notify = mNotify->dup();
534 notify->setInt32("what", kWhatFlushCompleted);
535 notify->post();
536}
537
538void NuPlayer2::Decoder::onShutdown(bool notifyComplete) {
539 status_t err = OK;
540
541 // if there is a pending resume request, notify complete now
542 notifyResumeCompleteIfNecessary();
543
544 if (mCodec != NULL) {
545 err = mCodec->release();
546 mCodec = NULL;
547 ++mBufferGeneration;
548
Wei Jia28288fb2017-12-15 13:45:29 -0800549 if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
Wei Jia53692fa2017-12-11 10:33:46 -0800550 // reconnect to surface as MediaCodec disconnected from it
Wei Jia4049f132018-01-22 10:37:31 -0800551 status_t error = native_window_api_connect(mNativeWindow->getANativeWindow(),
552 NATIVE_WINDOW_API_MEDIA);
Wei Jia53692fa2017-12-11 10:33:46 -0800553 ALOGW_IF(error != NO_ERROR,
554 "[%s] failed to connect to native window, error=%d",
555 mComponentName.c_str(), error);
556 }
557 mComponentName = "decoder";
558 }
559
560 releaseAndResetMediaBuffers();
561
562 if (err != OK) {
563 ALOGE("failed to release [%s] (err=%d)", mComponentName.c_str(), err);
564 handleError(err);
565 // finish with posting kWhatShutdownCompleted.
566 }
567
568 if (notifyComplete) {
569 sp<AMessage> notify = mNotify->dup();
570 notify->setInt32("what", kWhatShutdownCompleted);
571 notify->post();
572 mPaused = true;
573 }
574}
575
576/*
577 * returns true if we should request more data
578 */
579bool NuPlayer2::Decoder::doRequestBuffers() {
580 if (isDiscontinuityPending()) {
581 return false;
582 }
583 status_t err = OK;
584 while (err == OK && !mDequeuedInputBuffers.empty()) {
585 size_t bufferIx = *mDequeuedInputBuffers.begin();
586 sp<AMessage> msg = new AMessage();
587 msg->setSize("buffer-ix", bufferIx);
588 err = fetchInputData(msg);
589 if (err != OK && err != ERROR_END_OF_STREAM) {
590 // if EOS, need to queue EOS buffer
591 break;
592 }
593 mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
594
595 if (!mPendingInputMessages.empty()
596 || !onInputBufferFetched(msg)) {
597 mPendingInputMessages.push_back(msg);
598 }
599 }
600
601 return err == -EWOULDBLOCK
602 && mSource->feedMoreTSData() == OK;
603}
604
605void NuPlayer2::Decoder::handleError(int32_t err)
606{
607 // We cannot immediately release the codec due to buffers still outstanding
608 // in the renderer. We signal to the player the error so it can shutdown/release the
609 // decoder after flushing and increment the generation to discard unnecessary messages.
610
611 ++mBufferGeneration;
612
613 sp<AMessage> notify = mNotify->dup();
614 notify->setInt32("what", kWhatError);
615 notify->setInt32("err", err);
616 notify->post();
617}
618
619status_t NuPlayer2::Decoder::releaseCrypto()
620{
621 ALOGV("releaseCrypto");
622
623 sp<AMessage> msg = new AMessage(kWhatDrmReleaseCrypto, this);
624
625 sp<AMessage> response;
626 status_t status = msg->postAndAwaitResponse(&response);
627 if (status == OK && response != NULL) {
628 CHECK(response->findInt32("status", &status));
629 ALOGV("releaseCrypto ret: %d ", status);
630 } else {
631 ALOGE("releaseCrypto err: %d", status);
632 }
633
634 return status;
635}
636
637void NuPlayer2::Decoder::onReleaseCrypto(const sp<AMessage>& msg)
638{
639 status_t status = INVALID_OPERATION;
640 if (mCodec != NULL) {
641 status = mCodec->releaseCrypto();
642 } else {
643 // returning OK if the codec has been already released
644 status = OK;
645 ALOGE("onReleaseCrypto No mCodec. err: %d", status);
646 }
647
648 sp<AMessage> response = new AMessage;
649 response->setInt32("status", status);
650 // Clearing the state as it's tied to crypto. mIsEncryptedObservedEarlier is sticky though
651 // and lasts for the lifetime of this codec. See its use in fetchInputData.
652 mIsEncrypted = false;
653
654 sp<AReplyToken> replyID;
655 CHECK(msg->senderAwaitsResponse(&replyID));
656 response->postReply(replyID);
657}
658
659bool NuPlayer2::Decoder::handleAnInputBuffer(size_t index) {
660 if (isDiscontinuityPending()) {
661 return false;
662 }
663
664 if (mCodec == NULL) {
665 ALOGE("[%s] handleAnInputBuffer without a valid codec", mComponentName.c_str());
666 handleError(NO_INIT);
667 return false;
668 }
669
670 size_t bufferSize = 0;
671 uint8_t *bufferBase = mCodec->getInputBuffer(index, &bufferSize);
672
673 if (bufferBase == NULL) {
674 ALOGE("[%s] handleAnInputBuffer, failed to get input buffer", mComponentName.c_str());
675 handleError(UNKNOWN_ERROR);
676 return false;
677 }
678
679 sp<MediaCodecBuffer> buffer =
680 new MediaCodecBuffer(NULL /* format */, new ABuffer(bufferBase, bufferSize));
681
682 if (index >= mInputBuffers.size()) {
683 for (size_t i = mInputBuffers.size(); i <= index; ++i) {
684 mInputBuffers.add();
685 mMediaBuffers.add();
686 mInputBufferIsDequeued.add();
687 mMediaBuffers.editItemAt(i) = NULL;
688 mInputBufferIsDequeued.editItemAt(i) = false;
689 }
690 }
691 mInputBuffers.editItemAt(index) = buffer;
692
693 //CHECK_LT(bufferIx, mInputBuffers.size());
694
695 if (mMediaBuffers[index] != NULL) {
696 mMediaBuffers[index]->release();
697 mMediaBuffers.editItemAt(index) = NULL;
698 }
699 mInputBufferIsDequeued.editItemAt(index) = true;
700
701 if (!mCSDsToSubmit.isEmpty()) {
702 sp<AMessage> msg = new AMessage();
703 msg->setSize("buffer-ix", index);
704
705 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
706 ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
707 msg->setBuffer("buffer", buffer);
708 mCSDsToSubmit.removeAt(0);
709 if (!onInputBufferFetched(msg)) {
710 handleError(UNKNOWN_ERROR);
711 return false;
712 }
713 return true;
714 }
715
716 while (!mPendingInputMessages.empty()) {
717 sp<AMessage> msg = *mPendingInputMessages.begin();
718 if (!onInputBufferFetched(msg)) {
719 break;
720 }
721 mPendingInputMessages.erase(mPendingInputMessages.begin());
722 }
723
724 if (!mInputBufferIsDequeued.editItemAt(index)) {
725 return true;
726 }
727
728 mDequeuedInputBuffers.push_back(index);
729
730 onRequestInputBuffers();
731 return true;
732}
733
734bool NuPlayer2::Decoder::handleAnOutputBuffer(
735 size_t index,
736 size_t offset,
737 size_t size,
738 int64_t timeUs,
739 int32_t flags) {
740 if (mCodec == NULL) {
741 ALOGE("[%s] handleAnOutputBuffer without a valid codec", mComponentName.c_str());
742 handleError(NO_INIT);
743 return false;
744 }
745
746// CHECK_LT(bufferIx, mOutputBuffers.size());
747
748 size_t bufferSize = 0;
749 uint8_t *bufferBase = mCodec->getOutputBuffer(index, &bufferSize);
750
751 if (bufferBase == NULL) {
752 ALOGE("[%s] handleAnOutputBuffer, failed to get output buffer", mComponentName.c_str());
753 handleError(UNKNOWN_ERROR);
754 return false;
755 }
756
757 sp<MediaCodecBuffer> buffer =
758 new MediaCodecBuffer(NULL /* format */, new ABuffer(bufferBase, bufferSize));
759
760 if (index >= mOutputBuffers.size()) {
761 for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
762 mOutputBuffers.add();
763 }
764 }
765
766 mOutputBuffers.editItemAt(index) = buffer;
767
768 buffer->setRange(offset, size);
769 buffer->meta()->clear();
770 buffer->meta()->setInt64("timeUs", timeUs);
771
772 bool eos = flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM;
773 // we do not expect CODECCONFIG or SYNCFRAME for decoder
774
775 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
776 reply->setSize("buffer-ix", index);
777 reply->setInt32("generation", mBufferGeneration);
778
779 if (eos) {
780 ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
781
782 buffer->meta()->setInt32("eos", true);
783 reply->setInt32("eos", true);
784 }
785
Wei Jia5ed2faf2017-12-14 16:07:21 -0800786 mNumFramesTotal += !mIsAudio;
787
Wei Jia53692fa2017-12-11 10:33:46 -0800788 if (mSkipRenderingUntilMediaTimeUs >= 0) {
789 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
790 ALOGV("[%s] dropping buffer at time %lld as requested.",
791 mComponentName.c_str(), (long long)timeUs);
792
793 reply->post();
794 if (eos) {
795 notifyResumeCompleteIfNecessary();
796 if (mRenderer != NULL && !isDiscontinuityPending()) {
797 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
798 }
799 }
800 return true;
801 }
802
803 mSkipRenderingUntilMediaTimeUs = -1;
804 }
805
Wei Jia53692fa2017-12-11 10:33:46 -0800806 // wait until 1st frame comes out to signal resume complete
807 notifyResumeCompleteIfNecessary();
808
809 if (mRenderer != NULL) {
810 // send the buffer to renderer.
811 mRenderer->queueBuffer(mIsAudio, buffer, reply);
812 if (eos && !isDiscontinuityPending()) {
813 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
814 }
815 }
816
817 return true;
818}
819
820void NuPlayer2::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
821 if (!mIsAudio) {
822 int32_t width, height;
823 if (format->findInt32("width", &width)
824 && format->findInt32("height", &height)) {
825 mStats->setInt32("width", width);
826 mStats->setInt32("height", height);
827 }
828 sp<AMessage> notify = mNotify->dup();
829 notify->setInt32("what", kWhatVideoSizeChanged);
830 notify->setMessage("format", format);
831 notify->post();
832 } else if (mRenderer != NULL) {
833 uint32_t flags;
834 int64_t durationUs;
835 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
836 if (getAudioDeepBufferSetting() // override regardless of source duration
837 || (mSource->getDuration(&durationUs) == OK
838 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
839 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
840 } else {
841 flags = AUDIO_OUTPUT_FLAG_NONE;
842 }
843
844 sp<AMessage> reply = new AMessage(kWhatAudioOutputFormatChanged, this);
845 reply->setInt32("generation", mBufferGeneration);
846 mRenderer->changeAudioFormat(
847 format, false /* offloadOnly */, hasVideo,
848 flags, mSource->isStreaming(), reply);
849 }
850}
851
852void NuPlayer2::Decoder::releaseAndResetMediaBuffers() {
853 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
854 if (mMediaBuffers[i] != NULL) {
855 mMediaBuffers[i]->release();
856 mMediaBuffers.editItemAt(i) = NULL;
857 }
858 }
859 mMediaBuffers.resize(mInputBuffers.size());
860 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
861 mMediaBuffers.editItemAt(i) = NULL;
862 }
863 mInputBufferIsDequeued.clear();
864 mInputBufferIsDequeued.resize(mInputBuffers.size());
865 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
866 mInputBufferIsDequeued.editItemAt(i) = false;
867 }
868
869 mPendingInputMessages.clear();
870 mDequeuedInputBuffers.clear();
871 mSkipRenderingUntilMediaTimeUs = -1;
872}
873
874bool NuPlayer2::Decoder::isStaleReply(const sp<AMessage> &msg) {
875 int32_t generation;
876 CHECK(msg->findInt32("generation", &generation));
877 return generation != mBufferGeneration;
878}
879
880status_t NuPlayer2::Decoder::fetchInputData(sp<AMessage> &reply) {
881 sp<ABuffer> accessUnit;
882 bool dropAccessUnit = true;
883 do {
884 status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
885
886 if (err == -EWOULDBLOCK) {
887 return err;
888 } else if (err != OK) {
889 if (err == INFO_DISCONTINUITY) {
890 int32_t type;
891 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
892
893 bool formatChange =
894 (mIsAudio &&
895 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
896 || (!mIsAudio &&
897 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
898
899 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
900
901 ALOGI("%s discontinuity (format=%d, time=%d)",
902 mIsAudio ? "audio" : "video", formatChange, timeChange);
903
904 bool seamlessFormatChange = false;
905 sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
906 if (formatChange) {
907 seamlessFormatChange =
908 supportsSeamlessFormatChange(newFormat);
909 // treat seamless format change separately
910 formatChange = !seamlessFormatChange;
911 }
912
913 // For format or time change, return EOS to queue EOS input,
914 // then wait for EOS on output.
915 if (formatChange /* not seamless */) {
916 mFormatChangePending = true;
917 err = ERROR_END_OF_STREAM;
918 } else if (timeChange) {
919 rememberCodecSpecificData(newFormat);
920 mTimeChangePending = true;
921 err = ERROR_END_OF_STREAM;
922 } else if (seamlessFormatChange) {
923 // reuse existing decoder and don't flush
924 rememberCodecSpecificData(newFormat);
925 continue;
926 } else {
927 // This stream is unaffected by the discontinuity
928 return -EWOULDBLOCK;
929 }
930 }
931
932 // reply should only be returned without a buffer set
933 // when there is an error (including EOS)
934 CHECK(err != OK);
935
936 reply->setInt32("err", err);
937 return ERROR_END_OF_STREAM;
938 }
939
940 dropAccessUnit = false;
941 if (!mIsAudio && !mIsEncrypted) {
942 // Extra safeguard if higher-level behavior changes. Otherwise, not required now.
943 // Preventing the buffer from being processed (and sent to codec) if this is a later
944 // round of playback but this time without prepareDrm. Or if there is a race between
945 // stop (which is not blocking) and releaseDrm allowing buffers being processed after
946 // Crypto has been released (GenericSource currently prevents this race though).
947 // Particularly doing this check before IsAVCReferenceFrame call to prevent parsing
948 // of encrypted data.
949 if (mIsEncryptedObservedEarlier) {
950 ALOGE("fetchInputData: mismatched mIsEncrypted/mIsEncryptedObservedEarlier (0/1)");
951
952 return INVALID_OPERATION;
953 }
954
955 int32_t layerId = 0;
956 bool haveLayerId = accessUnit->meta()->findInt32("temporal-layer-id", &layerId);
Chih-Hung Hsiehd42529d2018-12-11 13:53:10 -0800957 if (mRenderer->getVideoLateByUs() > 100000LL
Wei Jia53692fa2017-12-11 10:33:46 -0800958 && mIsVideoAVC
959 && !IsAVCReferenceFrame(accessUnit)) {
960 dropAccessUnit = true;
961 } else if (haveLayerId && mNumVideoTemporalLayerTotal > 1) {
962 // Add only one layer each time.
963 if (layerId > mCurrentMaxVideoTemporalLayerId + 1
964 || layerId >= mNumVideoTemporalLayerAllowed) {
965 dropAccessUnit = true;
966 ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
967 layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
968 mCurrentMaxVideoTemporalLayerId);
969 } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
970 mCurrentMaxVideoTemporalLayerId = layerId;
971 } else if (layerId == 0 && mNumVideoTemporalLayerTotal > 1
972 && IsIDR(accessUnit->data(), accessUnit->size())) {
973 mCurrentMaxVideoTemporalLayerId = mNumVideoTemporalLayerTotal - 1;
974 }
975 }
976 if (dropAccessUnit) {
977 if (layerId <= mCurrentMaxVideoTemporalLayerId && layerId > 0) {
978 mCurrentMaxVideoTemporalLayerId = layerId - 1;
979 }
980 ++mNumInputFramesDropped;
981 }
982 }
983 } while (dropAccessUnit);
984
985 // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
986#if 0
987 int64_t mediaTimeUs;
988 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
989 ALOGV("[%s] feeding input buffer at media time %.3f",
990 mIsAudio ? "audio" : "video",
991 mediaTimeUs / 1E6);
992#endif
993
994 if (mCCDecoder != NULL) {
995 mCCDecoder->decode(accessUnit);
996 }
997
998 reply->setBuffer("buffer", accessUnit);
999
1000 return OK;
1001}
1002
1003bool NuPlayer2::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
1004 if (mCodec == NULL) {
1005 ALOGE("[%s] onInputBufferFetched without a valid codec", mComponentName.c_str());
1006 handleError(NO_INIT);
1007 return false;
1008 }
1009
1010 size_t bufferIx;
1011 CHECK(msg->findSize("buffer-ix", &bufferIx));
1012 CHECK_LT(bufferIx, mInputBuffers.size());
1013 sp<MediaCodecBuffer> codecBuffer = mInputBuffers[bufferIx];
1014
1015 sp<ABuffer> buffer;
1016 bool hasBuffer = msg->findBuffer("buffer", &buffer);
1017 bool needsCopy = true;
1018
1019 if (buffer == NULL /* includes !hasBuffer */) {
1020 int32_t streamErr = ERROR_END_OF_STREAM;
1021 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
1022
1023 CHECK(streamErr != OK);
1024
1025 // attempt to queue EOS
1026 status_t err = mCodec->queueInputBuffer(
1027 bufferIx,
1028 0,
1029 0,
1030 0,
1031 AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM);
1032 if (err == OK) {
1033 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
1034 } else if (streamErr == ERROR_END_OF_STREAM) {
1035 streamErr = err;
1036 // err will not be ERROR_END_OF_STREAM
1037 }
1038
1039 if (streamErr != ERROR_END_OF_STREAM) {
1040 ALOGE("Stream error for [%s] (err=%d), EOS %s queued",
1041 mComponentName.c_str(),
1042 streamErr,
1043 err == OK ? "successfully" : "unsuccessfully");
1044 handleError(streamErr);
1045 }
1046 } else {
1047 sp<AMessage> extra;
1048 if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
1049 int64_t resumeAtMediaTimeUs;
1050 if (extra->findInt64(
1051 "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
1052 ALOGI("[%s] suppressing rendering until %lld us",
1053 mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
1054 mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
1055 }
1056 }
1057
1058 int64_t timeUs = 0;
1059 uint32_t flags = 0;
1060 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1061
1062 int32_t eos, csd;
1063 // we do not expect SYNCFRAME for decoder
1064 if (buffer->meta()->findInt32("eos", &eos) && eos) {
1065 flags |= AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM;
1066 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
1067 flags |= AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG;
1068 }
1069
1070 // Modular DRM
Dongwon Kang1889c3e2018-02-01 13:44:57 -08001071 MediaBufferBase *mediaBuf = NULL;
Wei Jia53692fa2017-12-11 10:33:46 -08001072 sp<AMediaCodecCryptoInfoWrapper> cryptInfo;
1073
1074 // copy into codec buffer
1075 if (needsCopy) {
1076 if (buffer->size() > codecBuffer->capacity()) {
1077 handleError(ERROR_BUFFER_TOO_SMALL);
1078 mDequeuedInputBuffers.push_back(bufferIx);
1079 return false;
1080 }
1081
1082 if (buffer->data() != NULL) {
1083 codecBuffer->setRange(0, buffer->size());
1084 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
1085 } else { // No buffer->data()
1086 //Modular DRM
Dongwon Kangbc8f53b2018-01-25 17:01:44 -08001087 sp<RefBase> holder;
1088 if (buffer->meta()->findObject("mediaBufferHolder", &holder)) {
1089 mediaBuf = (holder != nullptr) ?
1090 static_cast<MediaBufferHolder*>(holder.get())->mediaBuffer() : nullptr;
1091 }
Wei Jia53692fa2017-12-11 10:33:46 -08001092 if (mediaBuf != NULL) {
Wei Jia9b5a7ad2018-07-27 17:33:24 -07001093 if (mediaBuf->size() > codecBuffer->capacity()) {
1094 handleError(ERROR_BUFFER_TOO_SMALL);
1095 mDequeuedInputBuffers.push_back(bufferIx);
1096 return false;
1097 }
1098
Wei Jia53692fa2017-12-11 10:33:46 -08001099 codecBuffer->setRange(0, mediaBuf->size());
1100 memcpy(codecBuffer->data(), mediaBuf->data(), mediaBuf->size());
1101
Marco Nelissen3d21ae32018-02-16 08:24:08 -08001102 MetaDataBase &meta_data = mediaBuf->meta_data();
Wei Jia53692fa2017-12-11 10:33:46 -08001103 cryptInfo = AMediaCodecCryptoInfoWrapper::Create(meta_data);
Wei Jia53692fa2017-12-11 10:33:46 -08001104 } else { // No mediaBuf
1105 ALOGE("onInputBufferFetched: buffer->data()/mediaBuf are NULL for %p",
1106 buffer.get());
1107 handleError(UNKNOWN_ERROR);
1108 return false;
1109 }
1110 } // buffer->data()
1111 } // needsCopy
1112
Robert Shihf60cbe52018-12-21 13:32:36 -08001113 sp<RefBase> cryptInfoObj;
1114 if (buffer->meta()->findObject("cryptInfo", &cryptInfoObj)) {
1115 cryptInfo = static_cast<AMediaCodecCryptoInfoWrapper *>(cryptInfoObj.get());
1116 }
1117
Wei Jia53692fa2017-12-11 10:33:46 -08001118 status_t err;
1119 if (cryptInfo != NULL) {
1120 err = mCodec->queueSecureInputBuffer(
1121 bufferIx,
1122 codecBuffer->offset(),
1123 cryptInfo,
1124 timeUs,
1125 flags);
1126 // synchronous call so done with cryptInfo here
1127 } else {
1128 err = mCodec->queueInputBuffer(
1129 bufferIx,
1130 codecBuffer->offset(),
1131 codecBuffer->size(),
1132 timeUs,
1133 flags);
1134 } // no cryptInfo
1135
1136 if (err != OK) {
1137 ALOGE("onInputBufferFetched: queue%sInputBuffer failed for [%s] (err=%d)",
1138 (cryptInfo != NULL ? "Secure" : ""),
1139 mComponentName.c_str(), err);
1140 handleError(err);
1141 } else {
1142 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
1143 }
1144
1145 } // buffer != NULL
1146 return true;
1147}
1148
1149void NuPlayer2::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
1150 status_t err;
1151 int32_t render;
1152 size_t bufferIx;
1153 int32_t eos;
1154 CHECK(msg->findSize("buffer-ix", &bufferIx));
1155
1156 if (!mIsAudio) {
1157 int64_t timeUs;
1158 sp<MediaCodecBuffer> buffer = mOutputBuffers[bufferIx];
1159 buffer->meta()->findInt64("timeUs", &timeUs);
1160
1161 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1162 mCCDecoder->display(timeUs);
1163 }
1164 }
1165
1166 if (mCodec == NULL) {
1167 err = NO_INIT;
1168 } else if (msg->findInt32("render", &render) && render) {
1169 int64_t timestampNs;
1170 CHECK(msg->findInt64("timestampNs", &timestampNs));
1171 err = mCodec->releaseOutputBufferAtTime(bufferIx, timestampNs);
1172 } else {
1173 mNumOutputFramesDropped += !mIsAudio;
1174 err = mCodec->releaseOutputBuffer(bufferIx, false /* render */);
1175 }
1176 if (err != OK) {
1177 ALOGE("failed to release output buffer for [%s] (err=%d)",
1178 mComponentName.c_str(), err);
1179 handleError(err);
1180 }
1181 if (msg->findInt32("eos", &eos) && eos
1182 && isDiscontinuityPending()) {
1183 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1184 }
1185}
1186
1187bool NuPlayer2::Decoder::isDiscontinuityPending() const {
1188 return mFormatChangePending || mTimeChangePending;
1189}
1190
1191void NuPlayer2::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1192 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1193 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1194
1195 // If we have format change, pause and wait to be killed;
1196 // If we have time change only, flush and restart fetching.
1197
1198 if (mFormatChangePending) {
1199 mPaused = true;
1200 } else if (mTimeChangePending) {
1201 if (flushOnTimeChange) {
1202 doFlush(false /* notifyComplete */);
1203 signalResume(false /* notifyComplete */);
1204 }
1205 }
1206
1207 // Notify NuPlayer2 to either shutdown decoder, or rescan sources
1208 sp<AMessage> msg = mNotify->dup();
1209 msg->setInt32("what", kWhatInputDiscontinuity);
1210 msg->setInt32("formatChange", mFormatChangePending);
1211 msg->post();
1212
1213 mFormatChangePending = false;
1214 mTimeChangePending = false;
1215}
1216
1217bool NuPlayer2::Decoder::supportsSeamlessAudioFormatChange(
1218 const sp<AMessage> &targetFormat) const {
1219 if (targetFormat == NULL) {
1220 return true;
1221 }
1222
1223 AString mime;
1224 if (!targetFormat->findString("mime", &mime)) {
1225 return false;
1226 }
1227
1228 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1229 // field-by-field comparison
1230 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1231 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1232 int32_t oldVal, newVal;
1233 if (!mInputFormat->getInt32(keys[i], &oldVal) ||
1234 !targetFormat->findInt32(keys[i], &newVal) ||
1235 oldVal != newVal) {
1236 return false;
1237 }
1238 }
1239
1240 sp<ABuffer> newBuf;
1241 uint8_t *oldBufData = NULL;
1242 size_t oldBufSize = 0;
1243 if (mInputFormat->getBuffer("csd-0", (void**)&oldBufData, &oldBufSize) &&
1244 targetFormat->findBuffer("csd-0", &newBuf)) {
1245 if (oldBufSize != newBuf->size()) {
1246 return false;
1247 }
1248 return !memcmp(oldBufData, newBuf->data(), oldBufSize);
1249 }
1250 }
1251 return false;
1252}
1253
1254bool NuPlayer2::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
1255 if (mInputFormat == NULL) {
1256 return false;
1257 }
1258
1259 if (targetFormat == NULL) {
1260 return true;
1261 }
1262
1263 AString oldMime, newMime;
1264 if (!mInputFormat->getString("mime", &oldMime)
1265 || !targetFormat->findString("mime", &newMime)
1266 || !(oldMime == newMime)) {
1267 return false;
1268 }
1269
1270 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1271 bool seamless;
1272 if (audio) {
1273 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1274 } else {
1275 int32_t isAdaptive;
1276 seamless = (mCodec != NULL &&
1277 mInputFormat->getInt32("adaptive-playback", &isAdaptive) &&
1278 isAdaptive);
1279 }
1280
1281 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1282 return seamless;
1283}
1284
1285void NuPlayer2::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1286 if (format == NULL) {
1287 return;
1288 }
1289 mCSDsForCurrentFormat.clear();
1290 for (int32_t i = 0; ; ++i) {
1291 AString tag = "csd-";
1292 tag.append(i);
1293 sp<ABuffer> buffer;
1294 if (!format->findBuffer(tag.c_str(), &buffer)) {
1295 break;
1296 }
1297 mCSDsForCurrentFormat.push(buffer);
1298 }
1299}
1300
1301void NuPlayer2::Decoder::notifyResumeCompleteIfNecessary() {
1302 if (mResumePending) {
1303 mResumePending = false;
1304
1305 sp<AMessage> notify = mNotify->dup();
1306 notify->setInt32("what", kWhatResumeCompleted);
1307 notify->post();
1308 }
1309}
1310
1311} // namespace android
1312