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