1 /*
2 * Copyright 2014 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 "NuPlayerDecoder"
19 #include <utils/Log.h>
20 #include <inttypes.h>
21
22 #include <algorithm>
23
24 #include "NuPlayerCCDecoder.h"
25 #include "NuPlayerDecoder.h"
26 #include "NuPlayerDrm.h"
27 #include "NuPlayerRenderer.h"
28 #include "NuPlayerSource.h"
29
30 #include <cutils/properties.h>
31 #include <mediadrm/ICrypto.h>
32 #include <media/MediaBufferHolder.h>
33 #include <media/MediaCodecBuffer.h>
34 #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/MediaCodec.h>
40 #include <media/stagefright/MediaDefs.h>
41 #include <media/stagefright/MediaErrors.h>
42 #include <media/stagefright/SurfaceUtils.h>
43 #include <gui/Surface.h>
44
45 #include "ATSParser.h"
46
47 namespace android {
48
49 static 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.
53 static float kDefaultVideoFrameRateTotal = 30.f;
54
getAudioDeepBufferSetting()55 static inline bool getAudioDeepBufferSetting() {
56 return property_get_bool("media.stagefright.audio.deep", false /* default_value */);
57 }
58
Decoder(const sp<AMessage> & notify,const sp<Source> & source,pid_t pid,uid_t uid,const sp<Renderer> & renderer,const sp<Surface> & surface,const sp<CCDecoder> & ccDecoder)59 NuPlayer::Decoder::Decoder(
60 const sp<AMessage> ¬ify,
61 const sp<Source> &source,
62 pid_t pid,
63 uid_t uid,
64 const sp<Renderer> &renderer,
65 const sp<Surface> &surface,
66 const sp<CCDecoder> &ccDecoder)
67 : DecoderBase(notify),
68 mSurface(surface),
69 mSource(source),
70 mRenderer(renderer),
71 mCCDecoder(ccDecoder),
72 mPid(pid),
73 mUid(uid),
74 mSkipRenderingUntilMediaTimeUs(-1LL),
75 mNumFramesTotal(0LL),
76 mNumInputFramesDropped(0LL),
77 mNumOutputFramesDropped(0LL),
78 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 mCodecLooper = new ALooper;
95 mCodecLooper->setName("NPDecoder-CL");
96 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
97 mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
98 }
99
~Decoder()100 NuPlayer::Decoder::~Decoder() {
101 // Need to stop looper first since mCodec could be accessed on the mDecoderLooper.
102 stopLooper();
103 if (mCodec != NULL) {
104 mCodec->release();
105 }
106 releaseAndResetMediaBuffers();
107 }
108
getStats()109 sp<AMessage> NuPlayer::Decoder::getStats() {
110
111 Mutex::Autolock autolock(mStatsLock);
112 mStats->setInt64("frames-total", mNumFramesTotal);
113 mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
114 mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
115 mStats->setFloat("frame-rate-total", mFrameRateTotal);
116
117 // make our own copy, so we aren't victim to any later changes.
118 sp<AMessage> copiedStats = mStats->dup();
119
120 return copiedStats;
121 }
122
setVideoSurface(const sp<Surface> & surface)123 status_t NuPlayer::Decoder::setVideoSurface(const sp<Surface> &surface) {
124 if (surface == NULL || ADebug::isExperimentEnabled("legacy-setsurface")) {
125 return BAD_VALUE;
126 }
127
128 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
129
130 msg->setObject("surface", surface);
131 sp<AMessage> response;
132 status_t err = msg->postAndAwaitResponse(&response);
133 if (err == OK && response != NULL) {
134 CHECK(response->findInt32("err", &err));
135 }
136 return err;
137 }
138
onMessageReceived(const sp<AMessage> & msg)139 void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
140 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
141
142 switch (msg->what()) {
143 case kWhatCodecNotify:
144 {
145 int32_t cbID;
146 CHECK(msg->findInt32("callbackID", &cbID));
147
148 ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
149 mIsAudio ? "audio" : "video", cbID, mPaused);
150
151 if (mPaused) {
152 break;
153 }
154
155 switch (cbID) {
156 case MediaCodec::CB_INPUT_AVAILABLE:
157 {
158 int32_t index;
159 CHECK(msg->findInt32("index", &index));
160
161 handleAnInputBuffer(index);
162 break;
163 }
164
165 case MediaCodec::CB_OUTPUT_AVAILABLE:
166 {
167 int32_t index;
168 size_t offset;
169 size_t size;
170 int64_t timeUs;
171 int32_t flags;
172
173 CHECK(msg->findInt32("index", &index));
174 CHECK(msg->findSize("offset", &offset));
175 CHECK(msg->findSize("size", &size));
176 CHECK(msg->findInt64("timeUs", &timeUs));
177 CHECK(msg->findInt32("flags", &flags));
178
179 handleAnOutputBuffer(index, offset, size, timeUs, flags);
180 break;
181 }
182
183 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED:
184 {
185 sp<AMessage> format;
186 CHECK(msg->findMessage("format", &format));
187
188 handleOutputFormatChange(format);
189 break;
190 }
191
192 case MediaCodec::CB_ERROR:
193 {
194 status_t err;
195 CHECK(msg->findInt32("err", &err));
196 ALOGE("Decoder (%s) reported error : 0x%x",
197 mIsAudio ? "audio" : "video", err);
198
199 handleError(err);
200 break;
201 }
202
203 default:
204 {
205 TRESPASS();
206 break;
207 }
208 }
209
210 break;
211 }
212
213 case kWhatRenderBuffer:
214 {
215 if (!isStaleReply(msg)) {
216 onRenderBuffer(msg);
217 }
218 break;
219 }
220
221 case kWhatAudioOutputFormatChanged:
222 {
223 if (!isStaleReply(msg)) {
224 status_t err;
225 if (msg->findInt32("err", &err) && err != OK) {
226 ALOGE("Renderer reported 0x%x when changing audio output format", err);
227 handleError(err);
228 }
229 }
230 break;
231 }
232
233 case kWhatSetVideoSurface:
234 {
235 sp<AReplyToken> replyID;
236 CHECK(msg->senderAwaitsResponse(&replyID));
237
238 sp<RefBase> obj;
239 CHECK(msg->findObject("surface", &obj));
240 sp<Surface> surface = static_cast<Surface *>(obj.get()); // non-null
241 int32_t err = INVALID_OPERATION;
242 // NOTE: in practice mSurface is always non-null, but checking here for completeness
243 if (mCodec != NULL && mSurface != NULL) {
244 // TODO: once AwesomePlayer is removed, remove this automatic connecting
245 // to the surface by MediaPlayerService.
246 //
247 // at this point MediaPlayerService::client has already connected to the
248 // surface, which MediaCodec does not expect
249 err = nativeWindowDisconnect(surface.get(), "kWhatSetVideoSurface(surface)");
250 if (err == OK) {
251 err = mCodec->setSurface(surface);
252 ALOGI_IF(err, "codec setSurface 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.
256 (void)nativeWindowConnect(mSurface.get(), "kWhatSetVideoSurface(mSurface)");
257 mSurface = surface;
258 }
259 }
260 if (err != OK) {
261 // reconnect to the new surface on error as MPS::Client will expect to
262 // be able to disconnect from it.
263 (void)nativeWindowConnect(surface.get(), "kWhatSetVideoSurface(err)");
264 }
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
onConfigure(const sp<AMessage> & format)286 void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
287 CHECK(mCodec == NULL);
288
289 mFormatChangePending = false;
290 mTimeChangePending = false;
291
292 ++mBufferGeneration;
293
294 AString mime;
295 CHECK(format->findString("mime", &mime));
296
297 mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
298 mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
299
300 mComponentName = mime;
301 mComponentName.append(" decoder");
302 ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), mSurface.get());
303
304 mCodec = MediaCodec::CreateByType(
305 mCodecLooper, mime.c_str(), false /* encoder */, NULL /* err */, mPid, mUid, format);
306 int32_t secure = 0;
307 if (format->findInt32("secure", &secure) && secure != 0) {
308 if (mCodec != NULL) {
309 mCodec->getName(&mComponentName);
310 mComponentName.append(".secure");
311 mCodec->release();
312 ALOGI("[%s] creating", mComponentName.c_str());
313 mCodec = MediaCodec::CreateByComponentName(
314 mCodecLooper, mComponentName.c_str(), NULL /* err */, mPid, mUid);
315 }
316 }
317 if (mCodec == NULL) {
318 ALOGE("Failed to create %s%s decoder",
319 (secure ? "secure " : ""), mime.c_str());
320 handleError(UNKNOWN_ERROR);
321 return;
322 }
323 mIsSecure = secure;
324
325 mCodec->getName(&mComponentName);
326
327 status_t err;
328 if (mSurface != NULL) {
329 // disconnect from surface as MediaCodec will reconnect
330 err = nativeWindowDisconnect(mSurface.get(), "onConfigure");
331 // We treat this as a warning, as this is a preparatory step.
332 // Codec will try to connect to the surface, which is where
333 // any error signaling will occur.
334 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
335 }
336
337 // Modular DRM
338 void *pCrypto;
339 if (!format->findPointer("crypto", &pCrypto)) {
340 pCrypto = NULL;
341 }
342 sp<ICrypto> crypto = (ICrypto*)pCrypto;
343 // non-encrypted source won't have a crypto
344 mIsEncrypted = (crypto != NULL);
345 // configure is called once; still using OR in case the behavior changes.
346 mIsEncryptedObservedEarlier = mIsEncryptedObservedEarlier || mIsEncrypted;
347 ALOGV("onConfigure mCrypto: %p (%d) mIsSecure: %d",
348 crypto.get(), (crypto != NULL ? crypto->getStrongCount() : 0), mIsSecure);
349
350 err = mCodec->configure(
351 format, mSurface, crypto, 0 /* flags */);
352
353 if (err != OK) {
354 ALOGE("Failed to configure [%s] decoder (err=%d)", mComponentName.c_str(), err);
355 mCodec->release();
356 mCodec.clear();
357 handleError(err);
358 return;
359 }
360 rememberCodecSpecificData(format);
361
362 // the following should work in configured state
363 CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
364 CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
365
366 {
367 Mutex::Autolock autolock(mStatsLock);
368 mStats->setString("mime", mime.c_str());
369 mStats->setString("component-name", mComponentName.c_str());
370 }
371
372 if (!mIsAudio) {
373 int32_t width, height;
374 if (mOutputFormat->findInt32("width", &width)
375 && mOutputFormat->findInt32("height", &height)) {
376 Mutex::Autolock autolock(mStatsLock);
377 mStats->setInt32("width", width);
378 mStats->setInt32("height", height);
379 }
380 }
381
382 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
383 mCodec->setCallback(reply);
384
385 err = mCodec->start();
386 if (err != OK) {
387 ALOGE("Failed to start [%s] decoder (err=%d)", mComponentName.c_str(), err);
388 mCodec->release();
389 mCodec.clear();
390 handleError(err);
391 return;
392 }
393
394 releaseAndResetMediaBuffers();
395
396 mPaused = false;
397 mResumePending = false;
398 }
399
onSetParameters(const sp<AMessage> & params)400 void NuPlayer::Decoder::onSetParameters(const sp<AMessage> ¶ms) {
401 bool needAdjustLayers = false;
402 float frameRateTotal;
403 if (params->findFloat("frame-rate-total", &frameRateTotal)
404 && mFrameRateTotal != frameRateTotal) {
405 needAdjustLayers = true;
406 mFrameRateTotal = frameRateTotal;
407 }
408
409 int32_t numVideoTemporalLayerTotal;
410 if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
411 && numVideoTemporalLayerTotal >= 0
412 && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
413 && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
414 needAdjustLayers = true;
415 mNumVideoTemporalLayerTotal = std::max(numVideoTemporalLayerTotal, 1);
416 }
417
418 if (needAdjustLayers && mNumVideoTemporalLayerTotal > 1) {
419 // TODO: For now, layer fps is calculated for some specific architectures.
420 // But it really should be extracted from the stream.
421 mVideoTemporalLayerAggregateFps[0] =
422 mFrameRateTotal / (float)(1LL << (mNumVideoTemporalLayerTotal - 1));
423 for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
424 mVideoTemporalLayerAggregateFps[i] =
425 mFrameRateTotal / (float)(1LL << (mNumVideoTemporalLayerTotal - i))
426 + mVideoTemporalLayerAggregateFps[i - 1];
427 }
428 }
429
430 float playbackSpeed;
431 if (params->findFloat("playback-speed", &playbackSpeed)
432 && mPlaybackSpeed != playbackSpeed) {
433 needAdjustLayers = true;
434 mPlaybackSpeed = playbackSpeed;
435 }
436
437 if (needAdjustLayers) {
438 float decodeFrameRate = mFrameRateTotal;
439 // enable temporal layering optimization only if we know the layering depth
440 if (mNumVideoTemporalLayerTotal > 1) {
441 int32_t layerId;
442 for (layerId = 0; layerId < mNumVideoTemporalLayerTotal - 1; ++layerId) {
443 if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
444 >= kDisplayRefreshingRate * 0.9) {
445 break;
446 }
447 }
448 mNumVideoTemporalLayerAllowed = layerId + 1;
449 decodeFrameRate = mVideoTemporalLayerAggregateFps[layerId];
450 }
451 ALOGV("onSetParameters: allowed layers=%d, decodeFps=%g",
452 mNumVideoTemporalLayerAllowed, decodeFrameRate);
453
454 if (mCodec == NULL) {
455 ALOGW("onSetParameters called before codec is created.");
456 return;
457 }
458
459 sp<AMessage> codecParams = new AMessage();
460 codecParams->setFloat("operating-rate", decodeFrameRate * mPlaybackSpeed);
461 mCodec->setParameters(codecParams);
462 }
463 }
464
onSetRenderer(const sp<Renderer> & renderer)465 void NuPlayer::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
466 mRenderer = renderer;
467 }
468
onResume(bool notifyComplete)469 void NuPlayer::Decoder::onResume(bool notifyComplete) {
470 mPaused = false;
471
472 if (notifyComplete) {
473 mResumePending = true;
474 }
475
476 if (mCodec == NULL) {
477 ALOGE("[%s] onResume without a valid codec", mComponentName.c_str());
478 handleError(NO_INIT);
479 return;
480 }
481 mCodec->start();
482 }
483
doFlush(bool notifyComplete)484 void NuPlayer::Decoder::doFlush(bool notifyComplete) {
485 if (mCCDecoder != NULL) {
486 mCCDecoder->flush();
487 }
488
489 if (mRenderer != NULL) {
490 mRenderer->flush(mIsAudio, notifyComplete);
491 mRenderer->signalTimeDiscontinuity();
492 }
493
494 status_t err = OK;
495 if (mCodec != NULL) {
496 err = mCodec->flush();
497 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
498 ++mBufferGeneration;
499 }
500
501 if (err != OK) {
502 ALOGE("failed to flush [%s] (err=%d)", mComponentName.c_str(), err);
503 handleError(err);
504 // finish with posting kWhatFlushCompleted.
505 // we attempt to release the buffers even if flush fails.
506 }
507 releaseAndResetMediaBuffers();
508 mPaused = true;
509 }
510
511
onFlush()512 void NuPlayer::Decoder::onFlush() {
513 doFlush(true);
514
515 if (isDiscontinuityPending()) {
516 // This could happen if the client starts seeking/shutdown
517 // after we queued an EOS for discontinuities.
518 // We can consider discontinuity handled.
519 finishHandleDiscontinuity(false /* flushOnTimeChange */);
520 }
521
522 sp<AMessage> notify = mNotify->dup();
523 notify->setInt32("what", kWhatFlushCompleted);
524 notify->post();
525 }
526
onShutdown(bool notifyComplete)527 void NuPlayer::Decoder::onShutdown(bool notifyComplete) {
528 status_t err = OK;
529
530 // if there is a pending resume request, notify complete now
531 notifyResumeCompleteIfNecessary();
532
533 if (mCodec != NULL) {
534 err = mCodec->release();
535 mCodec = NULL;
536 ++mBufferGeneration;
537
538 if (mSurface != NULL) {
539 // reconnect to surface as MediaCodec disconnected from it
540 status_t error = nativeWindowConnect(mSurface.get(), "onShutdown");
541 ALOGW_IF(error != NO_ERROR,
542 "[%s] failed to connect to native window, error=%d",
543 mComponentName.c_str(), error);
544 }
545 mComponentName = "decoder";
546 }
547
548 releaseAndResetMediaBuffers();
549
550 if (err != OK) {
551 ALOGE("failed to release [%s] (err=%d)", mComponentName.c_str(), err);
552 handleError(err);
553 // finish with posting kWhatShutdownCompleted.
554 }
555
556 if (notifyComplete) {
557 sp<AMessage> notify = mNotify->dup();
558 notify->setInt32("what", kWhatShutdownCompleted);
559 notify->post();
560 mPaused = true;
561 }
562 }
563
564 /*
565 * returns true if we should request more data
566 */
doRequestBuffers()567 bool NuPlayer::Decoder::doRequestBuffers() {
568 if (isDiscontinuityPending()) {
569 return false;
570 }
571 status_t err = OK;
572 while (err == OK && !mDequeuedInputBuffers.empty()) {
573 size_t bufferIx = *mDequeuedInputBuffers.begin();
574 sp<AMessage> msg = new AMessage();
575 msg->setSize("buffer-ix", bufferIx);
576 err = fetchInputData(msg);
577 if (err != OK && err != ERROR_END_OF_STREAM) {
578 // if EOS, need to queue EOS buffer
579 break;
580 }
581 mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
582
583 if (!mPendingInputMessages.empty()
584 || !onInputBufferFetched(msg)) {
585 mPendingInputMessages.push_back(msg);
586 }
587 }
588
589 return err == -EWOULDBLOCK
590 && mSource->feedMoreTSData() == OK;
591 }
592
handleError(int32_t err)593 void NuPlayer::Decoder::handleError(int32_t err)
594 {
595 // We cannot immediately release the codec due to buffers still outstanding
596 // in the renderer. We signal to the player the error so it can shutdown/release the
597 // decoder after flushing and increment the generation to discard unnecessary messages.
598
599 ++mBufferGeneration;
600
601 sp<AMessage> notify = mNotify->dup();
602 notify->setInt32("what", kWhatError);
603 notify->setInt32("err", err);
604 notify->post();
605 }
606
releaseCrypto()607 status_t NuPlayer::Decoder::releaseCrypto()
608 {
609 ALOGV("releaseCrypto");
610
611 sp<AMessage> msg = new AMessage(kWhatDrmReleaseCrypto, this);
612
613 sp<AMessage> response;
614 status_t status = msg->postAndAwaitResponse(&response);
615 if (status == OK && response != NULL) {
616 CHECK(response->findInt32("status", &status));
617 ALOGV("releaseCrypto ret: %d ", status);
618 } else {
619 ALOGE("releaseCrypto err: %d", status);
620 }
621
622 return status;
623 }
624
onReleaseCrypto(const sp<AMessage> & msg)625 void NuPlayer::Decoder::onReleaseCrypto(const sp<AMessage>& msg)
626 {
627 status_t status = INVALID_OPERATION;
628 if (mCodec != NULL) {
629 status = mCodec->releaseCrypto();
630 } else {
631 // returning OK if the codec has been already released
632 status = OK;
633 ALOGE("onReleaseCrypto No mCodec. err: %d", status);
634 }
635
636 sp<AMessage> response = new AMessage;
637 response->setInt32("status", status);
638 // Clearing the state as it's tied to crypto. mIsEncryptedObservedEarlier is sticky though
639 // and lasts for the lifetime of this codec. See its use in fetchInputData.
640 mIsEncrypted = false;
641
642 sp<AReplyToken> replyID;
643 CHECK(msg->senderAwaitsResponse(&replyID));
644 response->postReply(replyID);
645 }
646
handleAnInputBuffer(size_t index)647 bool NuPlayer::Decoder::handleAnInputBuffer(size_t index) {
648 if (isDiscontinuityPending()) {
649 return false;
650 }
651
652 if (mCodec == NULL) {
653 ALOGE("[%s] handleAnInputBuffer without a valid codec", mComponentName.c_str());
654 handleError(NO_INIT);
655 return false;
656 }
657
658 sp<MediaCodecBuffer> buffer;
659 mCodec->getInputBuffer(index, &buffer);
660
661 if (buffer == NULL) {
662 ALOGE("[%s] handleAnInputBuffer, failed to get input buffer", mComponentName.c_str());
663 handleError(UNKNOWN_ERROR);
664 return false;
665 }
666
667 if (index >= mInputBuffers.size()) {
668 for (size_t i = mInputBuffers.size(); i <= index; ++i) {
669 mInputBuffers.add();
670 mMediaBuffers.add();
671 mInputBufferIsDequeued.add();
672 mMediaBuffers.editItemAt(i) = NULL;
673 mInputBufferIsDequeued.editItemAt(i) = false;
674 }
675 }
676 mInputBuffers.editItemAt(index) = buffer;
677
678 //CHECK_LT(bufferIx, mInputBuffers.size());
679
680 if (mMediaBuffers[index] != NULL) {
681 mMediaBuffers[index]->release();
682 mMediaBuffers.editItemAt(index) = NULL;
683 }
684 mInputBufferIsDequeued.editItemAt(index) = true;
685
686 if (!mCSDsToSubmit.isEmpty()) {
687 sp<AMessage> msg = new AMessage();
688 msg->setSize("buffer-ix", index);
689
690 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
691 ALOGV("[%s] resubmitting CSD", mComponentName.c_str());
692 msg->setBuffer("buffer", buffer);
693 mCSDsToSubmit.removeAt(0);
694 if (!onInputBufferFetched(msg)) {
695 handleError(UNKNOWN_ERROR);
696 return false;
697 }
698 return true;
699 }
700
701 while (!mPendingInputMessages.empty()) {
702 sp<AMessage> msg = *mPendingInputMessages.begin();
703 if (!onInputBufferFetched(msg)) {
704 break;
705 }
706 mPendingInputMessages.erase(mPendingInputMessages.begin());
707 }
708
709 if (!mInputBufferIsDequeued.editItemAt(index)) {
710 return true;
711 }
712
713 mDequeuedInputBuffers.push_back(index);
714
715 onRequestInputBuffers();
716 return true;
717 }
718
handleAnOutputBuffer(size_t index,size_t offset,size_t size,int64_t timeUs,int32_t flags)719 bool NuPlayer::Decoder::handleAnOutputBuffer(
720 size_t index,
721 size_t offset,
722 size_t size,
723 int64_t timeUs,
724 int32_t flags) {
725 if (mCodec == NULL) {
726 ALOGE("[%s] handleAnOutputBuffer without a valid codec", mComponentName.c_str());
727 handleError(NO_INIT);
728 return false;
729 }
730
731 // CHECK_LT(bufferIx, mOutputBuffers.size());
732 sp<MediaCodecBuffer> buffer;
733 mCodec->getOutputBuffer(index, &buffer);
734
735 if (buffer == NULL) {
736 ALOGE("[%s] handleAnOutputBuffer, failed to get output buffer", mComponentName.c_str());
737 handleError(UNKNOWN_ERROR);
738 return false;
739 }
740
741 if (index >= mOutputBuffers.size()) {
742 for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
743 mOutputBuffers.add();
744 }
745 }
746
747 mOutputBuffers.editItemAt(index) = buffer;
748
749 int64_t frameIndex;
750 bool frameIndexFound = buffer->meta()->findInt64("frameIndex", &frameIndex);
751
752 buffer->setRange(offset, size);
753 buffer->meta()->clear();
754 buffer->meta()->setInt64("timeUs", timeUs);
755 if (frameIndexFound) {
756 buffer->meta()->setInt64("frameIndex", frameIndex);
757 }
758
759 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
760 // we do not expect CODECCONFIG or SYNCFRAME for decoder
761
762 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
763 reply->setSize("buffer-ix", index);
764 reply->setInt32("generation", mBufferGeneration);
765 reply->setSize("size", size);
766
767 if (eos) {
768 ALOGV("[%s] saw output EOS", mIsAudio ? "audio" : "video");
769
770 buffer->meta()->setInt32("eos", true);
771 reply->setInt32("eos", true);
772 }
773
774 mNumFramesTotal += !mIsAudio;
775
776 if (mSkipRenderingUntilMediaTimeUs >= 0) {
777 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
778 ALOGV("[%s] dropping buffer at time %lld as requested.",
779 mComponentName.c_str(), (long long)timeUs);
780
781 reply->post();
782 if (eos) {
783 notifyResumeCompleteIfNecessary();
784 if (mRenderer != NULL && !isDiscontinuityPending()) {
785 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
786 }
787 }
788 return true;
789 }
790
791 mSkipRenderingUntilMediaTimeUs = -1;
792 }
793
794 // wait until 1st frame comes out to signal resume complete
795 notifyResumeCompleteIfNecessary();
796
797 if (mRenderer != NULL) {
798 // send the buffer to renderer.
799 mRenderer->queueBuffer(mIsAudio, buffer, reply);
800 if (eos && !isDiscontinuityPending()) {
801 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
802 }
803 }
804
805 return true;
806 }
807
handleOutputFormatChange(const sp<AMessage> & format)808 void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
809 if (!mIsAudio) {
810 int32_t width, height;
811 if (format->findInt32("width", &width)
812 && format->findInt32("height", &height)) {
813 Mutex::Autolock autolock(mStatsLock);
814 mStats->setInt32("width", width);
815 mStats->setInt32("height", height);
816 }
817 sp<AMessage> notify = mNotify->dup();
818 notify->setInt32("what", kWhatVideoSizeChanged);
819 notify->setMessage("format", format);
820 notify->post();
821 } else if (mRenderer != NULL) {
822 uint32_t flags;
823 int64_t durationUs;
824 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
825 if (getAudioDeepBufferSetting() // override regardless of source duration
826 || (mSource->getDuration(&durationUs) == OK
827 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
828 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
829 } else {
830 flags = AUDIO_OUTPUT_FLAG_NONE;
831 }
832
833 sp<AMessage> reply = new AMessage(kWhatAudioOutputFormatChanged, this);
834 reply->setInt32("generation", mBufferGeneration);
835 mRenderer->changeAudioFormat(
836 format, false /* offloadOnly */, hasVideo,
837 flags, mSource->isStreaming(), reply);
838 }
839 }
840
releaseAndResetMediaBuffers()841 void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
842 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
843 if (mMediaBuffers[i] != NULL) {
844 mMediaBuffers[i]->release();
845 mMediaBuffers.editItemAt(i) = NULL;
846 }
847 }
848 mMediaBuffers.resize(mInputBuffers.size());
849 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
850 mMediaBuffers.editItemAt(i) = NULL;
851 }
852 mInputBufferIsDequeued.clear();
853 mInputBufferIsDequeued.resize(mInputBuffers.size());
854 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
855 mInputBufferIsDequeued.editItemAt(i) = false;
856 }
857
858 mPendingInputMessages.clear();
859 mDequeuedInputBuffers.clear();
860 mSkipRenderingUntilMediaTimeUs = -1;
861 }
862
requestCodecNotification()863 void NuPlayer::Decoder::requestCodecNotification() {
864 if (mCodec != NULL) {
865 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
866 reply->setInt32("generation", mBufferGeneration);
867 mCodec->requestActivityNotification(reply);
868 }
869 }
870
isStaleReply(const sp<AMessage> & msg)871 bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
872 int32_t generation;
873 CHECK(msg->findInt32("generation", &generation));
874 return generation != mBufferGeneration;
875 }
876
fetchInputData(sp<AMessage> & reply)877 status_t NuPlayer::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
onInputBufferFetched(const sp<AMessage> & msg)1000 bool NuPlayer::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 MediaCodec::BUFFER_FLAG_EOS);
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 ALOGV("[%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, cvo;
1060 // we do not expect SYNCFRAME for decoder
1061 if (buffer->meta()->findInt32("eos", &eos) && eos) {
1062 flags |= MediaCodec::BUFFER_FLAG_EOS;
1063 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
1064 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
1065 }
1066
1067 if (buffer->meta()->findInt32("cvo", (int32_t*)&cvo)) {
1068 ALOGV("[%s] cvo(%d) found at %lld us", mComponentName.c_str(), cvo, (long long)timeUs);
1069 switch (cvo) {
1070 case 0:
1071 codecBuffer->meta()->setInt32("cvo", MediaCodec::CVO_DEGREE_0);
1072 break;
1073 case 1:
1074 codecBuffer->meta()->setInt32("cvo", MediaCodec::CVO_DEGREE_90);
1075 break;
1076 case 2:
1077 codecBuffer->meta()->setInt32("cvo", MediaCodec::CVO_DEGREE_180);
1078 break;
1079 case 3:
1080 codecBuffer->meta()->setInt32("cvo", MediaCodec::CVO_DEGREE_270);
1081 break;
1082 }
1083 }
1084
1085 // Modular DRM
1086 MediaBufferBase *mediaBuf = NULL;
1087 NuPlayerDrm::CryptoInfo *cryptInfo = NULL;
1088
1089 // copy into codec buffer
1090 if (needsCopy) {
1091 if (buffer->size() > codecBuffer->capacity()) {
1092 handleError(ERROR_BUFFER_TOO_SMALL);
1093 mDequeuedInputBuffers.push_back(bufferIx);
1094 return false;
1095 }
1096
1097 if (buffer->data() != NULL) {
1098 codecBuffer->setRange(0, buffer->size());
1099 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
1100 } else { // No buffer->data()
1101 //Modular DRM
1102 sp<RefBase> holder;
1103 if (buffer->meta()->findObject("mediaBufferHolder", &holder)) {
1104 mediaBuf = (holder != nullptr) ?
1105 static_cast<MediaBufferHolder*>(holder.get())->mediaBuffer() : nullptr;
1106 }
1107 if (mediaBuf != NULL) {
1108 if (mediaBuf->size() > codecBuffer->capacity()) {
1109 handleError(ERROR_BUFFER_TOO_SMALL);
1110 mDequeuedInputBuffers.push_back(bufferIx);
1111 return false;
1112 }
1113
1114 codecBuffer->setRange(0, mediaBuf->size());
1115 memcpy(codecBuffer->data(), mediaBuf->data(), mediaBuf->size());
1116
1117 MetaDataBase &meta_data = mediaBuf->meta_data();
1118 cryptInfo = NuPlayerDrm::getSampleCryptoInfo(meta_data);
1119 } else { // No mediaBuf
1120 ALOGE("onInputBufferFetched: buffer->data()/mediaBuf are NULL for %p",
1121 buffer.get());
1122 handleError(UNKNOWN_ERROR);
1123 return false;
1124 }
1125 } // buffer->data()
1126 } // needsCopy
1127
1128 status_t err;
1129 AString errorDetailMsg;
1130 if (cryptInfo != NULL) {
1131 err = mCodec->queueSecureInputBuffer(
1132 bufferIx,
1133 codecBuffer->offset(),
1134 cryptInfo->subSamples,
1135 cryptInfo->numSubSamples,
1136 cryptInfo->key,
1137 cryptInfo->iv,
1138 cryptInfo->mode,
1139 cryptInfo->pattern,
1140 timeUs,
1141 flags,
1142 &errorDetailMsg);
1143 // synchronous call so done with cryptInfo here
1144 free(cryptInfo);
1145 } else {
1146 err = mCodec->queueInputBuffer(
1147 bufferIx,
1148 codecBuffer->offset(),
1149 codecBuffer->size(),
1150 timeUs,
1151 flags,
1152 &errorDetailMsg);
1153 } // no cryptInfo
1154
1155 if (err != OK) {
1156 ALOGE("onInputBufferFetched: queue%sInputBuffer failed for [%s] (err=%d, %s)",
1157 (cryptInfo != NULL ? "Secure" : ""),
1158 mComponentName.c_str(), err, errorDetailMsg.c_str());
1159 handleError(err);
1160 } else {
1161 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
1162 }
1163
1164 } // buffer != NULL
1165 return true;
1166 }
1167
onRenderBuffer(const sp<AMessage> & msg)1168 void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
1169 status_t err;
1170 int32_t render;
1171 size_t bufferIx;
1172 int32_t eos;
1173 size_t size;
1174 CHECK(msg->findSize("buffer-ix", &bufferIx));
1175
1176 if (!mIsAudio) {
1177 int64_t timeUs;
1178 sp<MediaCodecBuffer> buffer = mOutputBuffers[bufferIx];
1179 buffer->meta()->findInt64("timeUs", &timeUs);
1180
1181 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1182 mCCDecoder->display(timeUs);
1183 }
1184 }
1185
1186 if (mCodec == NULL) {
1187 err = NO_INIT;
1188 } else if (msg->findInt32("render", &render) && render) {
1189 int64_t timestampNs;
1190 CHECK(msg->findInt64("timestampNs", ×tampNs));
1191 err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
1192 } else {
1193 if (!msg->findInt32("eos", &eos) || !eos ||
1194 !msg->findSize("size", &size) || size) {
1195 mNumOutputFramesDropped += !mIsAudio;
1196 }
1197 err = mCodec->releaseOutputBuffer(bufferIx);
1198 }
1199 if (err != OK) {
1200 ALOGE("failed to release output buffer for [%s] (err=%d)",
1201 mComponentName.c_str(), err);
1202 handleError(err);
1203 }
1204 if (msg->findInt32("eos", &eos) && eos
1205 && isDiscontinuityPending()) {
1206 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1207 }
1208 }
1209
isDiscontinuityPending() const1210 bool NuPlayer::Decoder::isDiscontinuityPending() const {
1211 return mFormatChangePending || mTimeChangePending;
1212 }
1213
finishHandleDiscontinuity(bool flushOnTimeChange)1214 void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1215 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1216 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1217
1218 // If we have format change, pause and wait to be killed;
1219 // If we have time change only, flush and restart fetching.
1220
1221 if (mFormatChangePending) {
1222 mPaused = true;
1223 } else if (mTimeChangePending) {
1224 if (flushOnTimeChange) {
1225 doFlush(false /* notifyComplete */);
1226 signalResume(false /* notifyComplete */);
1227 }
1228 }
1229
1230 // Notify NuPlayer to either shutdown decoder, or rescan sources
1231 sp<AMessage> msg = mNotify->dup();
1232 msg->setInt32("what", kWhatInputDiscontinuity);
1233 msg->setInt32("formatChange", mFormatChangePending);
1234 msg->post();
1235
1236 mFormatChangePending = false;
1237 mTimeChangePending = false;
1238 }
1239
supportsSeamlessAudioFormatChange(const sp<AMessage> & targetFormat) const1240 bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
1241 const sp<AMessage> &targetFormat) const {
1242 if (targetFormat == NULL) {
1243 return true;
1244 }
1245
1246 AString mime;
1247 if (!targetFormat->findString("mime", &mime)) {
1248 return false;
1249 }
1250
1251 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1252 // field-by-field comparison
1253 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1254 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1255 int32_t oldVal, newVal;
1256 if (!mInputFormat->findInt32(keys[i], &oldVal) ||
1257 !targetFormat->findInt32(keys[i], &newVal) ||
1258 oldVal != newVal) {
1259 return false;
1260 }
1261 }
1262
1263 sp<ABuffer> oldBuf, newBuf;
1264 if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
1265 targetFormat->findBuffer("csd-0", &newBuf)) {
1266 if (oldBuf->size() != newBuf->size()) {
1267 return false;
1268 }
1269 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
1270 }
1271 }
1272 return false;
1273 }
1274
supportsSeamlessFormatChange(const sp<AMessage> & targetFormat) const1275 bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
1276 if (mInputFormat == NULL) {
1277 return false;
1278 }
1279
1280 if (targetFormat == NULL) {
1281 return true;
1282 }
1283
1284 AString oldMime, newMime;
1285 if (!mInputFormat->findString("mime", &oldMime)
1286 || !targetFormat->findString("mime", &newMime)
1287 || !(oldMime == newMime)) {
1288 return false;
1289 }
1290
1291 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1292 bool seamless;
1293 if (audio) {
1294 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1295 } else {
1296 int32_t isAdaptive;
1297 seamless = (mCodec != NULL &&
1298 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
1299 isAdaptive);
1300 }
1301
1302 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1303 return seamless;
1304 }
1305
rememberCodecSpecificData(const sp<AMessage> & format)1306 void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1307 if (format == NULL) {
1308 return;
1309 }
1310 mCSDsForCurrentFormat.clear();
1311 for (int32_t i = 0; ; ++i) {
1312 AString tag = "csd-";
1313 tag.append(i);
1314 sp<ABuffer> buffer;
1315 if (!format->findBuffer(tag.c_str(), &buffer)) {
1316 break;
1317 }
1318 mCSDsForCurrentFormat.push(buffer);
1319 }
1320 }
1321
notifyResumeCompleteIfNecessary()1322 void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
1323 if (mResumePending) {
1324 mResumePending = false;
1325
1326 sp<AMessage> notify = mNotify->dup();
1327 notify->setInt32("what", kWhatResumeCompleted);
1328 notify->post();
1329 }
1330 }
1331
1332 } // namespace android
1333
1334