blob: 300a8eab32d1e4e40a165f92584844153e1bf944 [file] [log] [blame]
Andreas Huberf9334412010-12-15 15:17:42 -08001/*
Chong Zhang7137ec72014-11-12 16:41:05 -08002 * Copyright 2014 The Android Open Source Project
Andreas Huberf9334412010-12-15 15:17:42 -08003 *
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>
Lajos Molnar1cd13982014-01-17 15:12:51 -080020#include <inttypes.h>
Andreas Huberf9334412010-12-15 15:17:42 -080021
Lajos Molnar9fb81522016-07-14 07:33:43 -070022#include <algorithm>
23
Chong Zhang7137ec72014-11-12 16:41:05 -080024#include "NuPlayerCCDecoder.h"
Andreas Huberf9334412010-12-15 15:17:42 -080025#include "NuPlayerDecoder.h"
Hassan Shojaniacefac142017-02-06 21:02:02 -080026#include "NuPlayerDrm.h"
Wei Jiac6cfd702014-11-11 16:33:20 -080027#include "NuPlayerRenderer.h"
28#include "NuPlayerSource.h"
29
Andy Hung288da022015-05-31 22:55:59 -070030#include <cutils/properties.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080031#include <media/ICrypto.h>
Wonsik Kim7e34bf52016-08-23 00:09:18 +090032#include <media/MediaCodecBuffer.h>
Andreas Huberf9334412010-12-15 15:17:42 -080033#include <media/stagefright/foundation/ABuffer.h>
34#include <media/stagefright/foundation/ADebug.h>
Andreas Huber5bc087c2010-12-23 10:27:40 -080035#include <media/stagefright/foundation/AMessage.h>
Lajos Molnar09524832014-07-17 14:29:51 -070036#include <media/stagefright/MediaBuffer.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080037#include <media/stagefright/MediaCodec.h>
Andreas Huberf9334412010-12-15 15:17:42 -080038#include <media/stagefright/MediaDefs.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080039#include <media/stagefright/MediaErrors.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080040#include <media/stagefright/SurfaceUtils.h>
Lajos Molnar1de1e252015-04-30 18:18:34 -070041#include <gui/Surface.h>
42
Chong Zhang7137ec72014-11-12 16:41:05 -080043#include "avc_utils.h"
44#include "ATSParser.h"
45
Andreas Huberf9334412010-12-15 15:17:42 -080046namespace android {
47
Lajos Molnar9fb81522016-07-14 07:33:43 -070048static float kDisplayRefreshingRate = 60.f; // TODO: get this from the display
Praveen Chavanbbaa1442016-04-08 13:33:49 -070049
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
Andy Hung288da022015-05-31 22:55:59 -070054static inline bool getAudioDeepBufferSetting() {
55 return property_get_bool("media.stagefright.audio.deep", false /* default_value */);
56}
57
Andreas Huberf9334412010-12-15 15:17:42 -080058NuPlayer::Decoder::Decoder(
Glenn Kasten11731182011-02-08 17:26:17 -080059 const sp<AMessage> &notify,
Wei Jiac6cfd702014-11-11 16:33:20 -080060 const sp<Source> &source,
Ronghua Wu68845c12015-07-21 09:50:48 -070061 pid_t pid,
Wei Jiaf2ae3e12016-10-27 17:10:59 -070062 uid_t uid,
Wei Jiac6cfd702014-11-11 16:33:20 -080063 const sp<Renderer> &renderer,
Lajos Molnar1de1e252015-04-30 18:18:34 -070064 const sp<Surface> &surface,
Chong Zhang7137ec72014-11-12 16:41:05 -080065 const sp<CCDecoder> &ccDecoder)
Andy Hung202bce12014-12-03 11:47:36 -080066 : DecoderBase(notify),
Lajos Molnar1de1e252015-04-30 18:18:34 -070067 mSurface(surface),
Wei Jiac6cfd702014-11-11 16:33:20 -080068 mSource(source),
69 mRenderer(renderer),
Chong Zhang7137ec72014-11-12 16:41:05 -080070 mCCDecoder(ccDecoder),
Ronghua Wu68845c12015-07-21 09:50:48 -070071 mPid(pid),
Wei Jiaf2ae3e12016-10-27 17:10:59 -070072 mUid(uid),
Wei Jiac6cfd702014-11-11 16:33:20 -080073 mSkipRenderingUntilMediaTimeUs(-1ll),
Chong Zhang7137ec72014-11-12 16:41:05 -080074 mNumFramesTotal(0ll),
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070075 mNumInputFramesDropped(0ll),
76 mNumOutputFramesDropped(0ll),
77 mVideoWidth(0),
78 mVideoHeight(0),
Chong Zhang7137ec72014-11-12 16:41:05 -080079 mIsAudio(true),
80 mIsVideoAVC(false),
81 mIsSecure(false),
82 mFormatChangePending(false),
Chong Zhang66704af2015-03-03 19:32:35 -080083 mTimeChangePending(false),
Praveen Chavanbbaa1442016-04-08 13:33:49 -070084 mFrameRateTotal(kDefaultVideoFrameRateTotal),
85 mPlaybackSpeed(1.0f),
Lajos Molnar9fb81522016-07-14 07:33:43 -070086 mNumVideoTemporalLayerTotal(1), // decode all layers
Praveen Chavanbbaa1442016-04-08 13:33:49 -070087 mNumVideoTemporalLayerAllowed(1),
88 mCurrentMaxVideoTemporalLayerId(0),
Chong Zhangf8d71772014-11-26 15:08:34 -080089 mResumePending(false),
Lajos Molnar1cd13982014-01-17 15:12:51 -080090 mComponentName("decoder") {
Lajos Molnar1cd13982014-01-17 15:12:51 -080091 mCodecLooper = new ALooper;
Marco Nelissen9e2b7912014-08-18 16:13:03 -070092 mCodecLooper->setName("NPDecoder-CL");
Lajos Molnar1cd13982014-01-17 15:12:51 -080093 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
Praveen Chavanbbaa1442016-04-08 13:33:49 -070094 mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
Andreas Huberf9334412010-12-15 15:17:42 -080095}
96
97NuPlayer::Decoder::~Decoder() {
Ronghua Wufaeb0f22015-05-21 12:20:21 -070098 mCodec->release();
Wei Jia4923cee2014-09-24 14:25:19 -070099 releaseAndResetMediaBuffers();
Andreas Huberf9334412010-12-15 15:17:42 -0800100}
101
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700102sp<AMessage> NuPlayer::Decoder::getStats() const {
103 mStats->setInt64("frames-total", mNumFramesTotal);
104 mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
105 mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
106 return mStats;
Lajos Molnar09524832014-07-17 14:29:51 -0700107}
108
Lajos Molnara81c6222015-07-10 19:17:45 -0700109status_t NuPlayer::Decoder::setVideoSurface(const sp<Surface> &surface) {
110 if (surface == NULL || ADebug::isExperimentEnabled("legacy-setsurface")) {
111 return BAD_VALUE;
112 }
113
114 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
115
116 msg->setObject("surface", surface);
117 sp<AMessage> response;
118 status_t err = msg->postAndAwaitResponse(&response);
119 if (err == OK && response != NULL) {
120 CHECK(response->findInt32("err", &err));
121 }
122 return err;
123}
124
Chong Zhang7137ec72014-11-12 16:41:05 -0800125void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
126 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
127
128 switch (msg->what()) {
129 case kWhatCodecNotify:
130 {
Chong Zhang3b032b32015-04-17 15:49:06 -0700131 int32_t cbID;
132 CHECK(msg->findInt32("callbackID", &cbID));
133
134 ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
135 mIsAudio ? "audio" : "video", cbID, mPaused);
136
Marco Nelissen421f47c2015-03-25 14:40:32 -0700137 if (mPaused) {
138 break;
Chong Zhang7137ec72014-11-12 16:41:05 -0800139 }
140
Marco Nelissen421f47c2015-03-25 14:40:32 -0700141 switch (cbID) {
142 case MediaCodec::CB_INPUT_AVAILABLE:
143 {
144 int32_t index;
145 CHECK(msg->findInt32("index", &index));
146
147 handleAnInputBuffer(index);
148 break;
149 }
150
151 case MediaCodec::CB_OUTPUT_AVAILABLE:
152 {
153 int32_t index;
154 size_t offset;
155 size_t size;
156 int64_t timeUs;
157 int32_t flags;
158
159 CHECK(msg->findInt32("index", &index));
160 CHECK(msg->findSize("offset", &offset));
161 CHECK(msg->findSize("size", &size));
162 CHECK(msg->findInt64("timeUs", &timeUs));
163 CHECK(msg->findInt32("flags", &flags));
164
165 handleAnOutputBuffer(index, offset, size, timeUs, flags);
166 break;
167 }
168
169 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED:
170 {
171 sp<AMessage> format;
172 CHECK(msg->findMessage("format", &format));
173
174 handleOutputFormatChange(format);
175 break;
176 }
177
178 case MediaCodec::CB_ERROR:
179 {
180 status_t err;
181 CHECK(msg->findInt32("err", &err));
182 ALOGE("Decoder (%s) reported error : 0x%x",
183 mIsAudio ? "audio" : "video", err);
184
185 handleError(err);
186 break;
187 }
188
189 default:
190 {
191 TRESPASS();
192 break;
193 }
194 }
195
Lajos Molnar87603c02014-08-20 19:25:30 -0700196 break;
197 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800198
199 case kWhatRenderBuffer:
200 {
201 if (!isStaleReply(msg)) {
202 onRenderBuffer(msg);
203 }
204 break;
205 }
206
Wei Jia9a3101b2016-11-08 14:34:24 -0800207 case kWhatAudioOutputFormatChanged:
208 {
209 if (!isStaleReply(msg)) {
210 status_t err;
211 if (msg->findInt32("err", &err) && err != OK) {
212 ALOGE("Renderer reported 0x%x when changing audio output format", err);
213 handleError(err);
214 }
215 }
216 break;
217 }
218
Lajos Molnara81c6222015-07-10 19:17:45 -0700219 case kWhatSetVideoSurface:
220 {
221 sp<AReplyToken> replyID;
222 CHECK(msg->senderAwaitsResponse(&replyID));
223
224 sp<RefBase> obj;
225 CHECK(msg->findObject("surface", &obj));
226 sp<Surface> surface = static_cast<Surface *>(obj.get()); // non-null
227 int32_t err = INVALID_OPERATION;
228 // NOTE: in practice mSurface is always non-null, but checking here for completeness
229 if (mCodec != NULL && mSurface != NULL) {
230 // TODO: once AwesomePlayer is removed, remove this automatic connecting
231 // to the surface by MediaPlayerService.
232 //
233 // at this point MediaPlayerService::client has already connected to the
234 // surface, which MediaCodec does not expect
Chong Zhang181fd9b2017-02-16 15:53:03 -0800235 err = nativeWindowDisconnect(surface.get(), "kWhatSetVideoSurface(surface)");
Lajos Molnara81c6222015-07-10 19:17:45 -0700236 if (err == OK) {
237 err = mCodec->setSurface(surface);
238 ALOGI_IF(err, "codec setSurface returned: %d", err);
239 if (err == OK) {
240 // reconnect to the old surface as MPS::Client will expect to
241 // be able to disconnect from it.
Chong Zhang181fd9b2017-02-16 15:53:03 -0800242 (void)nativeWindowConnect(mSurface.get(), "kWhatSetVideoSurface(mSurface)");
Lajos Molnara81c6222015-07-10 19:17:45 -0700243 mSurface = surface;
244 }
245 }
246 if (err != OK) {
247 // reconnect to the new surface on error as MPS::Client will expect to
248 // be able to disconnect from it.
Chong Zhang181fd9b2017-02-16 15:53:03 -0800249 (void)nativeWindowConnect(surface.get(), "kWhatSetVideoSurface(err)");
Lajos Molnara81c6222015-07-10 19:17:45 -0700250 }
251 }
252
253 sp<AMessage> response = new AMessage;
254 response->setInt32("err", err);
255 response->postReply(replyID);
256 break;
257 }
258
Hassan Shojaniacefac142017-02-06 21:02:02 -0800259 case kWhatDrmReleaseCrypto:
260 {
261 ALOGV("kWhatDrmReleaseCrypto");
262 onReleaseCrypto(msg);
263 break;
264 }
265
Chong Zhang7137ec72014-11-12 16:41:05 -0800266 default:
267 DecoderBase::onMessageReceived(msg);
268 break;
Lajos Molnar87603c02014-08-20 19:25:30 -0700269 }
270}
271
Lajos Molnar1cd13982014-01-17 15:12:51 -0800272void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
Andreas Huberf9334412010-12-15 15:17:42 -0800273 CHECK(mCodec == NULL);
Andreas Huberf9334412010-12-15 15:17:42 -0800274
Chong Zhang7137ec72014-11-12 16:41:05 -0800275 mFormatChangePending = false;
Chong Zhang66704af2015-03-03 19:32:35 -0800276 mTimeChangePending = false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800277
Lajos Molnar1cd13982014-01-17 15:12:51 -0800278 ++mBufferGeneration;
279
Andreas Huber84066782011-08-16 09:34:26 -0700280 AString mime;
281 CHECK(format->findString("mime", &mime));
Andreas Huberf9334412010-12-15 15:17:42 -0800282
Chong Zhang7137ec72014-11-12 16:41:05 -0800283 mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
284 mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
285
Lajos Molnar1cd13982014-01-17 15:12:51 -0800286 mComponentName = mime;
287 mComponentName.append(" decoder");
Lajos Molnar1de1e252015-04-30 18:18:34 -0700288 ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), mSurface.get());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800289
Ronghua Wu68845c12015-07-21 09:50:48 -0700290 mCodec = MediaCodec::CreateByType(
Wei Jiaf2ae3e12016-10-27 17:10:59 -0700291 mCodecLooper, mime.c_str(), false /* encoder */, NULL /* err */, mPid, mUid);
Lajos Molnar09524832014-07-17 14:29:51 -0700292 int32_t secure = 0;
293 if (format->findInt32("secure", &secure) && secure != 0) {
294 if (mCodec != NULL) {
295 mCodec->getName(&mComponentName);
296 mComponentName.append(".secure");
297 mCodec->release();
298 ALOGI("[%s] creating", mComponentName.c_str());
299 mCodec = MediaCodec::CreateByComponentName(
Wei Jiaf2ae3e12016-10-27 17:10:59 -0700300 mCodecLooper, mComponentName.c_str(), NULL /* err */, mPid, mUid);
Lajos Molnar09524832014-07-17 14:29:51 -0700301 }
302 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800303 if (mCodec == NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700304 ALOGE("Failed to create %s%s decoder",
305 (secure ? "secure " : ""), mime.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800306 handleError(UNKNOWN_ERROR);
307 return;
308 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800309 mIsSecure = secure;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800310
311 mCodec->getName(&mComponentName);
312
Lajos Molnar14986f62014-09-15 11:04:44 -0700313 status_t err;
Lajos Molnar1de1e252015-04-30 18:18:34 -0700314 if (mSurface != NULL) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800315 // disconnect from surface as MediaCodec will reconnect
Chong Zhang181fd9b2017-02-16 15:53:03 -0800316 err = nativeWindowDisconnect(mSurface.get(), "onConfigure");
Lajos Molnar14986f62014-09-15 11:04:44 -0700317 // We treat this as a warning, as this is a preparatory step.
318 // Codec will try to connect to the surface, which is where
319 // any error signaling will occur.
320 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800321 }
Hassan Shojaniacefac142017-02-06 21:02:02 -0800322
323 // Modular DRM
324 void *pCrypto;
325 if (!format->findPointer("crypto", &pCrypto)) {
326 pCrypto = NULL;
327 }
328 sp<ICrypto> crypto = (ICrypto*)pCrypto;
329 ALOGV("onConfigure mCrypto: %p (%d) mIsSecure: %d",
330 crypto.get(), (crypto != NULL ? crypto->getStrongCount() : 0), mIsSecure);
331
Lajos Molnar14986f62014-09-15 11:04:44 -0700332 err = mCodec->configure(
Hassan Shojaniacefac142017-02-06 21:02:02 -0800333 format, mSurface, crypto, 0 /* flags */);
334
Lajos Molnar1cd13982014-01-17 15:12:51 -0800335 if (err != OK) {
336 ALOGE("Failed to configure %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700337 mCodec->release();
338 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800339 handleError(err);
340 return;
341 }
Lajos Molnar87603c02014-08-20 19:25:30 -0700342 rememberCodecSpecificData(format);
343
Lajos Molnar1cd13982014-01-17 15:12:51 -0800344 // the following should work in configured state
345 CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
346 CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
347
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700348 mStats->setString("mime", mime.c_str());
349 mStats->setString("component-name", mComponentName.c_str());
350
351 if (!mIsAudio) {
352 int32_t width, height;
353 if (mOutputFormat->findInt32("width", &width)
354 && mOutputFormat->findInt32("height", &height)) {
355 mStats->setInt32("width", width);
356 mStats->setInt32("height", height);
357 }
358 }
359
Marco Nelissen421f47c2015-03-25 14:40:32 -0700360 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
361 mCodec->setCallback(reply);
362
Lajos Molnar1cd13982014-01-17 15:12:51 -0800363 err = mCodec->start();
364 if (err != OK) {
365 ALOGE("Failed to start %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700366 mCodec->release();
367 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800368 handleError(err);
369 return;
Andreas Huberf9334412010-12-15 15:17:42 -0800370 }
371
Lajos Molnar09524832014-07-17 14:29:51 -0700372 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700373
Wei Jia704e7262014-06-04 16:21:56 -0700374 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800375 mResumePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800376}
Andreas Huber078cfcf2011-09-15 12:25:04 -0700377
Ronghua Wu8db88132015-04-22 13:51:35 -0700378void NuPlayer::Decoder::onSetParameters(const sp<AMessage> &params) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700379 bool needAdjustLayers = false;
380 float frameRateTotal;
381 if (params->findFloat("frame-rate-total", &frameRateTotal)
382 && mFrameRateTotal != frameRateTotal) {
383 needAdjustLayers = true;
384 mFrameRateTotal = frameRateTotal;
Ronghua Wu8db88132015-04-22 13:51:35 -0700385 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700386
387 int32_t numVideoTemporalLayerTotal;
388 if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
Lajos Molnar9fb81522016-07-14 07:33:43 -0700389 && numVideoTemporalLayerTotal >= 0
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700390 && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
391 && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
392 needAdjustLayers = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700393 mNumVideoTemporalLayerTotal = std::max(numVideoTemporalLayerTotal, 1);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700394 }
395
Lajos Molnar9fb81522016-07-14 07:33:43 -0700396 if (needAdjustLayers && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700397 // TODO: For now, layer fps is calculated for some specific architectures.
398 // But it really should be extracted from the stream.
399 mVideoTemporalLayerAggregateFps[0] =
400 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - 1));
401 for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
402 mVideoTemporalLayerAggregateFps[i] =
403 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - i))
404 + mVideoTemporalLayerAggregateFps[i - 1];
405 }
406 }
407
408 float playbackSpeed;
409 if (params->findFloat("playback-speed", &playbackSpeed)
410 && mPlaybackSpeed != playbackSpeed) {
411 needAdjustLayers = true;
412 mPlaybackSpeed = playbackSpeed;
413 }
414
415 if (needAdjustLayers) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700416 float decodeFrameRate = mFrameRateTotal;
417 // enable temporal layering optimization only if we know the layering depth
418 if (mNumVideoTemporalLayerTotal > 1) {
419 int32_t layerId;
420 for (layerId = 0; layerId < mNumVideoTemporalLayerTotal - 1; ++layerId) {
421 if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
422 >= kDisplayRefreshingRate * 0.9) {
423 break;
424 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700425 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700426 mNumVideoTemporalLayerAllowed = layerId + 1;
427 decodeFrameRate = mVideoTemporalLayerAggregateFps[layerId];
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700428 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700429 ALOGV("onSetParameters: allowed layers=%d, decodeFps=%g",
430 mNumVideoTemporalLayerAllowed, decodeFrameRate);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700431
432 if (mCodec == NULL) {
433 ALOGW("onSetParameters called before codec is created.");
434 return;
435 }
436
437 sp<AMessage> codecParams = new AMessage();
Lajos Molnar9fb81522016-07-14 07:33:43 -0700438 codecParams->setFloat("operating-rate", decodeFrameRate * mPlaybackSpeed);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700439 mCodec->setParameters(codecParams);
440 }
Ronghua Wu8db88132015-04-22 13:51:35 -0700441}
442
Chong Zhang7137ec72014-11-12 16:41:05 -0800443void NuPlayer::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800444 mRenderer = renderer;
Chong Zhang7137ec72014-11-12 16:41:05 -0800445}
446
Chong Zhangf8d71772014-11-26 15:08:34 -0800447void NuPlayer::Decoder::onResume(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800448 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800449
450 if (notifyComplete) {
451 mResumePending = true;
452 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700453 mCodec->start();
Chong Zhang7137ec72014-11-12 16:41:05 -0800454}
455
Chong Zhang66704af2015-03-03 19:32:35 -0800456void NuPlayer::Decoder::doFlush(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800457 if (mCCDecoder != NULL) {
458 mCCDecoder->flush();
459 }
460
461 if (mRenderer != NULL) {
462 mRenderer->flush(mIsAudio, notifyComplete);
463 mRenderer->signalTimeDiscontinuity();
464 }
465
466 status_t err = OK;
467 if (mCodec != NULL) {
468 err = mCodec->flush();
469 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
470 ++mBufferGeneration;
471 }
472
473 if (err != OK) {
474 ALOGE("failed to flush %s (err=%d)", mComponentName.c_str(), err);
475 handleError(err);
476 // finish with posting kWhatFlushCompleted.
477 // we attempt to release the buffers even if flush fails.
478 }
479 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700480 mPaused = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800481}
Chong Zhang7137ec72014-11-12 16:41:05 -0800482
Marco Nelissen421f47c2015-03-25 14:40:32 -0700483
Chong Zhang66704af2015-03-03 19:32:35 -0800484void NuPlayer::Decoder::onFlush() {
485 doFlush(true);
486
487 if (isDiscontinuityPending()) {
488 // This could happen if the client starts seeking/shutdown
489 // after we queued an EOS for discontinuities.
490 // We can consider discontinuity handled.
491 finishHandleDiscontinuity(false /* flushOnTimeChange */);
Chong Zhang7137ec72014-11-12 16:41:05 -0800492 }
Chong Zhang66704af2015-03-03 19:32:35 -0800493
494 sp<AMessage> notify = mNotify->dup();
495 notify->setInt32("what", kWhatFlushCompleted);
496 notify->post();
Chong Zhang7137ec72014-11-12 16:41:05 -0800497}
498
499void NuPlayer::Decoder::onShutdown(bool notifyComplete) {
500 status_t err = OK;
Chong Zhangf8d71772014-11-26 15:08:34 -0800501
502 // if there is a pending resume request, notify complete now
503 notifyResumeCompleteIfNecessary();
504
Chong Zhang7137ec72014-11-12 16:41:05 -0800505 if (mCodec != NULL) {
506 err = mCodec->release();
507 mCodec = NULL;
508 ++mBufferGeneration;
509
Lajos Molnar1de1e252015-04-30 18:18:34 -0700510 if (mSurface != NULL) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800511 // reconnect to surface as MediaCodec disconnected from it
Chong Zhang181fd9b2017-02-16 15:53:03 -0800512 status_t error = nativeWindowConnect(mSurface.get(), "onShutdown");
Chong Zhang7137ec72014-11-12 16:41:05 -0800513 ALOGW_IF(error != NO_ERROR,
514 "[%s] failed to connect to native window, error=%d",
515 mComponentName.c_str(), error);
516 }
517 mComponentName = "decoder";
518 }
519
520 releaseAndResetMediaBuffers();
521
522 if (err != OK) {
523 ALOGE("failed to release %s (err=%d)", mComponentName.c_str(), err);
524 handleError(err);
525 // finish with posting kWhatShutdownCompleted.
526 }
527
528 if (notifyComplete) {
529 sp<AMessage> notify = mNotify->dup();
530 notify->setInt32("what", kWhatShutdownCompleted);
531 notify->post();
532 mPaused = true;
533 }
534}
535
Chong Zhang3b032b32015-04-17 15:49:06 -0700536/*
537 * returns true if we should request more data
538 */
539bool NuPlayer::Decoder::doRequestBuffers() {
Jeff Tinker29b7dcf2016-10-24 10:28:30 -0700540 if (isDiscontinuityPending()) {
Chong Zhang3b032b32015-04-17 15:49:06 -0700541 return false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800542 }
543 status_t err = OK;
Chong Zhang66704af2015-03-03 19:32:35 -0800544 while (err == OK && !mDequeuedInputBuffers.empty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800545 size_t bufferIx = *mDequeuedInputBuffers.begin();
546 sp<AMessage> msg = new AMessage();
547 msg->setSize("buffer-ix", bufferIx);
548 err = fetchInputData(msg);
Chong Zhang66704af2015-03-03 19:32:35 -0800549 if (err != OK && err != ERROR_END_OF_STREAM) {
550 // if EOS, need to queue EOS buffer
Chong Zhang7137ec72014-11-12 16:41:05 -0800551 break;
552 }
553 mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
554
555 if (!mPendingInputMessages.empty()
556 || !onInputBufferFetched(msg)) {
557 mPendingInputMessages.push_back(msg);
Lajos Molnar09524832014-07-17 14:29:51 -0700558 }
559 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800560
Chong Zhang3b032b32015-04-17 15:49:06 -0700561 return err == -EWOULDBLOCK
562 && mSource->feedMoreTSData() == OK;
Lajos Molnar09524832014-07-17 14:29:51 -0700563}
564
Marco Nelissen421f47c2015-03-25 14:40:32 -0700565void NuPlayer::Decoder::handleError(int32_t err)
566{
567 // We cannot immediately release the codec due to buffers still outstanding
568 // in the renderer. We signal to the player the error so it can shutdown/release the
569 // decoder after flushing and increment the generation to discard unnecessary messages.
570
571 ++mBufferGeneration;
572
573 sp<AMessage> notify = mNotify->dup();
574 notify->setInt32("what", kWhatError);
575 notify->setInt32("err", err);
576 notify->post();
577}
578
Hassan Shojaniacefac142017-02-06 21:02:02 -0800579status_t NuPlayer::Decoder::releaseCrypto()
580{
581 ALOGV("releaseCrypto");
582
583 sp<AMessage> msg = new AMessage(kWhatDrmReleaseCrypto, this);
584
585 sp<AMessage> response;
586 status_t status = msg->postAndAwaitResponse(&response);
587 if (status == OK && response != NULL) {
588 CHECK(response->findInt32("status", &status));
589 ALOGV("releaseCrypto ret: %d ", status);
590 } else {
591 ALOGE("releaseCrypto err: %d", status);
592 }
593
594 return status;
595}
596
597void NuPlayer::Decoder::onReleaseCrypto(const sp<AMessage>& msg)
598{
599 status_t status = INVALID_OPERATION;
600 if (mCodec != NULL) {
601 status = mCodec->releaseCrypto();
602 } else {
603 // returning OK if the codec has been already released
604 status = OK;
605 ALOGE("onReleaseCrypto No mCodec. err: %d", status);
606 }
607
608 sp<AMessage> response = new AMessage;
609 response->setInt32("status", status);
610
611 sp<AReplyToken> replyID;
612 CHECK(msg->senderAwaitsResponse(&replyID));
613 response->postReply(replyID);
614}
615
Marco Nelissen421f47c2015-03-25 14:40:32 -0700616bool NuPlayer::Decoder::handleAnInputBuffer(size_t index) {
Chong Zhang66704af2015-03-03 19:32:35 -0800617 if (isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800618 return false;
619 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700620
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900621 sp<MediaCodecBuffer> buffer;
Marco Nelissen421f47c2015-03-25 14:40:32 -0700622 mCodec->getInputBuffer(index, &buffer);
623
Wei Jia6301a5e2015-05-13 13:15:18 -0700624 if (buffer == NULL) {
625 handleError(UNKNOWN_ERROR);
626 return false;
627 }
628
Marco Nelissen421f47c2015-03-25 14:40:32 -0700629 if (index >= mInputBuffers.size()) {
630 for (size_t i = mInputBuffers.size(); i <= index; ++i) {
631 mInputBuffers.add();
632 mMediaBuffers.add();
633 mInputBufferIsDequeued.add();
634 mMediaBuffers.editItemAt(i) = NULL;
635 mInputBufferIsDequeued.editItemAt(i) = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800636 }
Andreas Huber078cfcf2011-09-15 12:25:04 -0700637 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700638 mInputBuffers.editItemAt(index) = buffer;
Andreas Huber078cfcf2011-09-15 12:25:04 -0700639
Marco Nelissen421f47c2015-03-25 14:40:32 -0700640 //CHECK_LT(bufferIx, mInputBuffers.size());
Andreas Huberf9334412010-12-15 15:17:42 -0800641
Marco Nelissen421f47c2015-03-25 14:40:32 -0700642 if (mMediaBuffers[index] != NULL) {
643 mMediaBuffers[index]->release();
644 mMediaBuffers.editItemAt(index) = NULL;
Lajos Molnar09524832014-07-17 14:29:51 -0700645 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700646 mInputBufferIsDequeued.editItemAt(index) = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700647
Lajos Molnar87603c02014-08-20 19:25:30 -0700648 if (!mCSDsToSubmit.isEmpty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800649 sp<AMessage> msg = new AMessage();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700650 msg->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800651
Lajos Molnar87603c02014-08-20 19:25:30 -0700652 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
653 ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
Chong Zhang7137ec72014-11-12 16:41:05 -0800654 msg->setBuffer("buffer", buffer);
Lajos Molnar87603c02014-08-20 19:25:30 -0700655 mCSDsToSubmit.removeAt(0);
Wei Jia56097a82016-01-07 16:03:03 -0800656 if (!onInputBufferFetched(msg)) {
657 handleError(UNKNOWN_ERROR);
658 return false;
659 }
Wei Jia2245fc62014-10-02 15:12:25 -0700660 return true;
661 }
662
663 while (!mPendingInputMessages.empty()) {
664 sp<AMessage> msg = *mPendingInputMessages.begin();
Chong Zhang7137ec72014-11-12 16:41:05 -0800665 if (!onInputBufferFetched(msg)) {
Wei Jia2245fc62014-10-02 15:12:25 -0700666 break;
667 }
668 mPendingInputMessages.erase(mPendingInputMessages.begin());
669 }
670
Marco Nelissen421f47c2015-03-25 14:40:32 -0700671 if (!mInputBufferIsDequeued.editItemAt(index)) {
Lajos Molnar87603c02014-08-20 19:25:30 -0700672 return true;
673 }
674
Marco Nelissen421f47c2015-03-25 14:40:32 -0700675 mDequeuedInputBuffers.push_back(index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800676
677 onRequestInputBuffers();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800678 return true;
679}
680
Marco Nelissen421f47c2015-03-25 14:40:32 -0700681bool NuPlayer::Decoder::handleAnOutputBuffer(
682 size_t index,
683 size_t offset,
684 size_t size,
685 int64_t timeUs,
686 int32_t flags) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700687// CHECK_LT(bufferIx, mOutputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900688 sp<MediaCodecBuffer> buffer;
Marco Nelissen421f47c2015-03-25 14:40:32 -0700689 mCodec->getOutputBuffer(index, &buffer);
690
Santhosh Behara3539def2015-10-09 17:32:58 -0700691 if (buffer == NULL) {
692 handleError(UNKNOWN_ERROR);
693 return false;
694 }
695
Marco Nelissen421f47c2015-03-25 14:40:32 -0700696 if (index >= mOutputBuffers.size()) {
697 for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
698 mOutputBuffers.add();
699 }
700 }
701
702 mOutputBuffers.editItemAt(index) = buffer;
703
Chong Zhang7137ec72014-11-12 16:41:05 -0800704 buffer->setRange(offset, size);
705 buffer->meta()->clear();
706 buffer->meta()->setInt64("timeUs", timeUs);
Chong Zhang66704af2015-03-03 19:32:35 -0800707
708 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
Chong Zhang7137ec72014-11-12 16:41:05 -0800709 // we do not expect CODECCONFIG or SYNCFRAME for decoder
710
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800711 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700712 reply->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800713 reply->setInt32("generation", mBufferGeneration);
714
Chong Zhang66704af2015-03-03 19:32:35 -0800715 if (eos) {
716 ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
717
718 buffer->meta()->setInt32("eos", true);
719 reply->setInt32("eos", true);
720 } else if (mSkipRenderingUntilMediaTimeUs >= 0) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800721 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
722 ALOGV("[%s] dropping buffer at time %lld as requested.",
723 mComponentName.c_str(), (long long)timeUs);
724
725 reply->post();
726 return true;
727 }
728
729 mSkipRenderingUntilMediaTimeUs = -1;
730 }
731
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700732 mNumFramesTotal += !mIsAudio;
733
Chong Zhangf8d71772014-11-26 15:08:34 -0800734 // wait until 1st frame comes out to signal resume complete
735 notifyResumeCompleteIfNecessary();
736
Chong Zhang7137ec72014-11-12 16:41:05 -0800737 if (mRenderer != NULL) {
738 // send the buffer to renderer.
739 mRenderer->queueBuffer(mIsAudio, buffer, reply);
Chong Zhang66704af2015-03-03 19:32:35 -0800740 if (eos && !isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800741 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
742 }
743 }
744
745 return true;
746}
747
Marco Nelissen421f47c2015-03-25 14:40:32 -0700748void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
749 if (!mIsAudio) {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700750 int32_t width, height;
751 if (format->findInt32("width", &width)
752 && format->findInt32("height", &height)) {
753 mStats->setInt32("width", width);
754 mStats->setInt32("height", height);
755 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700756 sp<AMessage> notify = mNotify->dup();
757 notify->setInt32("what", kWhatVideoSizeChanged);
758 notify->setMessage("format", format);
759 notify->post();
760 } else if (mRenderer != NULL) {
761 uint32_t flags;
762 int64_t durationUs;
763 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
Andy Hung288da022015-05-31 22:55:59 -0700764 if (getAudioDeepBufferSetting() // override regardless of source duration
Andy Hung71c8e5c2017-04-03 15:50:27 -0700765 || (mSource->getDuration(&durationUs) == OK
Andy Hung288da022015-05-31 22:55:59 -0700766 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700767 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
768 } else {
769 flags = AUDIO_OUTPUT_FLAG_NONE;
770 }
771
Wei Jia9a3101b2016-11-08 14:34:24 -0800772 sp<AMessage> reply = new AMessage(kWhatAudioOutputFormatChanged, this);
773 reply->setInt32("generation", mBufferGeneration);
774 mRenderer->changeAudioFormat(
775 format, false /* offloadOnly */, hasVideo, flags, reply);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700776 }
777}
778
Chong Zhang7137ec72014-11-12 16:41:05 -0800779void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
780 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
781 if (mMediaBuffers[i] != NULL) {
782 mMediaBuffers[i]->release();
783 mMediaBuffers.editItemAt(i) = NULL;
784 }
785 }
786 mMediaBuffers.resize(mInputBuffers.size());
787 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
788 mMediaBuffers.editItemAt(i) = NULL;
789 }
790 mInputBufferIsDequeued.clear();
791 mInputBufferIsDequeued.resize(mInputBuffers.size());
792 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
793 mInputBufferIsDequeued.editItemAt(i) = false;
794 }
795
796 mPendingInputMessages.clear();
797 mDequeuedInputBuffers.clear();
798 mSkipRenderingUntilMediaTimeUs = -1;
799}
800
801void NuPlayer::Decoder::requestCodecNotification() {
Chong Zhang7137ec72014-11-12 16:41:05 -0800802 if (mCodec != NULL) {
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800803 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
Chong Zhang7137ec72014-11-12 16:41:05 -0800804 reply->setInt32("generation", mBufferGeneration);
805 mCodec->requestActivityNotification(reply);
806 }
807}
808
809bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
810 int32_t generation;
811 CHECK(msg->findInt32("generation", &generation));
812 return generation != mBufferGeneration;
813}
814
815status_t NuPlayer::Decoder::fetchInputData(sp<AMessage> &reply) {
816 sp<ABuffer> accessUnit;
Robert Shih59e9ca72016-10-20 13:51:42 -0700817 bool dropAccessUnit = true;
Chong Zhang7137ec72014-11-12 16:41:05 -0800818 do {
819 status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
820
821 if (err == -EWOULDBLOCK) {
822 return err;
823 } else if (err != OK) {
824 if (err == INFO_DISCONTINUITY) {
825 int32_t type;
826 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
827
828 bool formatChange =
829 (mIsAudio &&
830 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
831 || (!mIsAudio &&
832 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
833
834 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
835
836 ALOGI("%s discontinuity (format=%d, time=%d)",
837 mIsAudio ? "audio" : "video", formatChange, timeChange);
838
839 bool seamlessFormatChange = false;
840 sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
841 if (formatChange) {
842 seamlessFormatChange =
843 supportsSeamlessFormatChange(newFormat);
844 // treat seamless format change separately
845 formatChange = !seamlessFormatChange;
846 }
847
Chong Zhang66704af2015-03-03 19:32:35 -0800848 // For format or time change, return EOS to queue EOS input,
849 // then wait for EOS on output.
Chong Zhang7137ec72014-11-12 16:41:05 -0800850 if (formatChange /* not seamless */) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800851 mFormatChangePending = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800852 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800853 } else if (timeChange) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800854 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800855 mTimeChangePending = true;
856 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800857 } else if (seamlessFormatChange) {
858 // reuse existing decoder and don't flush
859 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800860 continue;
Chong Zhang7137ec72014-11-12 16:41:05 -0800861 } else {
862 // This stream is unaffected by the discontinuity
863 return -EWOULDBLOCK;
864 }
865 }
866
Chong Zhang66704af2015-03-03 19:32:35 -0800867 // reply should only be returned without a buffer set
868 // when there is an error (including EOS)
869 CHECK(err != OK);
870
Chong Zhang7137ec72014-11-12 16:41:05 -0800871 reply->setInt32("err", err);
Chong Zhang66704af2015-03-03 19:32:35 -0800872 return ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800873 }
874
Chong Zhang7137ec72014-11-12 16:41:05 -0800875 dropAccessUnit = false;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700876 if (!mIsAudio && !mIsSecure) {
877 int32_t layerId = 0;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700878 bool haveLayerId = accessUnit->meta()->findInt32("temporal-layer-id", &layerId);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700879 if (mRenderer->getVideoLateByUs() > 100000ll
880 && mIsVideoAVC
881 && !IsAVCReferenceFrame(accessUnit)) {
882 dropAccessUnit = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700883 } else if (haveLayerId && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700884 // Add only one layer each time.
885 if (layerId > mCurrentMaxVideoTemporalLayerId + 1
886 || layerId >= mNumVideoTemporalLayerAllowed) {
887 dropAccessUnit = true;
888 ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
889 layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
890 mCurrentMaxVideoTemporalLayerId);
891 } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
892 mCurrentMaxVideoTemporalLayerId = layerId;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700893 } else if (layerId == 0 && mNumVideoTemporalLayerTotal > 1 && IsIDR(accessUnit)) {
894 mCurrentMaxVideoTemporalLayerId = mNumVideoTemporalLayerTotal - 1;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700895 }
896 }
897 if (dropAccessUnit) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700898 if (layerId <= mCurrentMaxVideoTemporalLayerId && layerId > 0) {
899 mCurrentMaxVideoTemporalLayerId = layerId - 1;
900 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700901 ++mNumInputFramesDropped;
902 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800903 }
904 } while (dropAccessUnit);
905
906 // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
907#if 0
908 int64_t mediaTimeUs;
909 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
Chong Zhang5abbd3d2015-04-20 16:03:00 -0700910 ALOGV("[%s] feeding input buffer at media time %.3f",
Chong Zhang7137ec72014-11-12 16:41:05 -0800911 mIsAudio ? "audio" : "video",
912 mediaTimeUs / 1E6);
913#endif
914
915 if (mCCDecoder != NULL) {
916 mCCDecoder->decode(accessUnit);
917 }
918
919 reply->setBuffer("buffer", accessUnit);
920
921 return OK;
922}
923
924bool NuPlayer::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800925 size_t bufferIx;
926 CHECK(msg->findSize("buffer-ix", &bufferIx));
927 CHECK_LT(bufferIx, mInputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900928 sp<MediaCodecBuffer> codecBuffer = mInputBuffers[bufferIx];
Lajos Molnar1cd13982014-01-17 15:12:51 -0800929
930 sp<ABuffer> buffer;
931 bool hasBuffer = msg->findBuffer("buffer", &buffer);
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900932 bool needsCopy = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700933
Lajos Molnar1cd13982014-01-17 15:12:51 -0800934 if (buffer == NULL /* includes !hasBuffer */) {
935 int32_t streamErr = ERROR_END_OF_STREAM;
936 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
937
Chong Zhang66704af2015-03-03 19:32:35 -0800938 CHECK(streamErr != OK);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800939
940 // attempt to queue EOS
941 status_t err = mCodec->queueInputBuffer(
942 bufferIx,
943 0,
944 0,
945 0,
946 MediaCodec::BUFFER_FLAG_EOS);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700947 if (err == OK) {
948 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
949 } else if (streamErr == ERROR_END_OF_STREAM) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800950 streamErr = err;
951 // err will not be ERROR_END_OF_STREAM
952 }
953
954 if (streamErr != ERROR_END_OF_STREAM) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700955 ALOGE("Stream error for %s (err=%d), EOS %s queued",
956 mComponentName.c_str(),
957 streamErr,
958 err == OK ? "successfully" : "unsuccessfully");
Lajos Molnar1cd13982014-01-17 15:12:51 -0800959 handleError(streamErr);
960 }
961 } else {
Wei Jiac6cfd702014-11-11 16:33:20 -0800962 sp<AMessage> extra;
963 if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
964 int64_t resumeAtMediaTimeUs;
965 if (extra->findInt64(
966 "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
967 ALOGI("[%s] suppressing rendering until %lld us",
968 mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
969 mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
970 }
971 }
972
Lajos Molnar1cd13982014-01-17 15:12:51 -0800973 int64_t timeUs = 0;
974 uint32_t flags = 0;
975 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
976
Lajos Molnar87603c02014-08-20 19:25:30 -0700977 int32_t eos, csd;
978 // we do not expect SYNCFRAME for decoder
Lajos Molnar1cd13982014-01-17 15:12:51 -0800979 if (buffer->meta()->findInt32("eos", &eos) && eos) {
980 flags |= MediaCodec::BUFFER_FLAG_EOS;
Lajos Molnar87603c02014-08-20 19:25:30 -0700981 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
982 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800983 }
984
Hassan Shojaniacefac142017-02-06 21:02:02 -0800985 // Modular DRM
986 MediaBuffer *mediaBuf = NULL;
987 NuPlayerDrm::CryptoInfo *cryptInfo = NULL;
988
Lajos Molnar1cd13982014-01-17 15:12:51 -0800989 // copy into codec buffer
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900990 if (needsCopy) {
Wei Jia56097a82016-01-07 16:03:03 -0800991 if (buffer->size() > codecBuffer->capacity()) {
992 handleError(ERROR_BUFFER_TOO_SMALL);
993 mDequeuedInputBuffers.push_back(bufferIx);
994 return false;
995 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800996
Hassan Shojaniacefac142017-02-06 21:02:02 -0800997 if (buffer->data() != NULL) {
998 codecBuffer->setRange(0, buffer->size());
999 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
1000 } else { // No buffer->data()
1001 //Modular DRM
1002 mediaBuf = (MediaBuffer*)buffer->getMediaBufferBase();
1003 if (mediaBuf != NULL) {
1004 codecBuffer->setRange(0, mediaBuf->size());
1005 memcpy(codecBuffer->data(), mediaBuf->data(), mediaBuf->size());
1006
1007 sp<MetaData> meta_data = mediaBuf->meta_data();
1008 cryptInfo = NuPlayerDrm::getSampleCryptoInfo(meta_data);
1009
1010 // since getMediaBuffer() has incremented the refCount
1011 mediaBuf->release();
1012 } else { // No mediaBuf
1013 ALOGE("onInputBufferFetched: buffer->data()/mediaBuf are NULL for %p",
1014 buffer.get());
1015 handleError(UNKNOWN_ERROR);
1016 return false;
1017 }
1018 } // buffer->data()
1019 } // needsCopy
1020
1021 status_t err;
1022 AString errorDetailMsg;
1023 if (cryptInfo != NULL) {
1024 err = mCodec->queueSecureInputBuffer(
1025 bufferIx,
1026 codecBuffer->offset(),
1027 cryptInfo->subSamples,
1028 cryptInfo->numSubSamples,
1029 cryptInfo->key,
1030 cryptInfo->iv,
1031 cryptInfo->mode,
1032 cryptInfo->pattern,
1033 timeUs,
1034 flags,
1035 &errorDetailMsg);
1036 // synchronous call so done with cryptInfo here
1037 free(cryptInfo);
1038 } else {
1039 err = mCodec->queueInputBuffer(
1040 bufferIx,
1041 codecBuffer->offset(),
1042 codecBuffer->size(),
1043 timeUs,
1044 flags,
1045 &errorDetailMsg);
1046 } // no cryptInfo
1047
Lajos Molnar1cd13982014-01-17 15:12:51 -08001048 if (err != OK) {
Hassan Shojaniacefac142017-02-06 21:02:02 -08001049 ALOGE("onInputBufferFetched: queue%sInputBuffer failed for %s (err=%d, %s)",
1050 (cryptInfo != NULL ? "Secure" : ""),
1051 mComponentName.c_str(), err, errorDetailMsg.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -08001052 handleError(err);
Andy Hungcf31f1e2014-09-23 14:59:01 -07001053 } else {
1054 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
Lajos Molnar09524832014-07-17 14:29:51 -07001055 }
Hassan Shojaniacefac142017-02-06 21:02:02 -08001056
1057 } // buffer != NULL
Wei Jia2245fc62014-10-02 15:12:25 -07001058 return true;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001059}
1060
Lajos Molnar1cd13982014-01-17 15:12:51 -08001061void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
1062 status_t err;
1063 int32_t render;
1064 size_t bufferIx;
Chong Zhang66704af2015-03-03 19:32:35 -08001065 int32_t eos;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001066 CHECK(msg->findSize("buffer-ix", &bufferIx));
Wei Jiac6cfd702014-11-11 16:33:20 -08001067
Chong Zhang7137ec72014-11-12 16:41:05 -08001068 if (!mIsAudio) {
Wei Jiac6cfd702014-11-11 16:33:20 -08001069 int64_t timeUs;
Wonsik Kim7e34bf52016-08-23 00:09:18 +09001070 sp<MediaCodecBuffer> buffer = mOutputBuffers[bufferIx];
Wei Jiac6cfd702014-11-11 16:33:20 -08001071 buffer->meta()->findInt64("timeUs", &timeUs);
Chong Zhang7137ec72014-11-12 16:41:05 -08001072
1073 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1074 mCCDecoder->display(timeUs);
1075 }
Wei Jiac6cfd702014-11-11 16:33:20 -08001076 }
1077
Lajos Molnar1cd13982014-01-17 15:12:51 -08001078 if (msg->findInt32("render", &render) && render) {
Lajos Molnardc43dfa2014-05-07 15:33:04 -07001079 int64_t timestampNs;
1080 CHECK(msg->findInt64("timestampNs", &timestampNs));
1081 err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001082 } else {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -07001083 mNumOutputFramesDropped += !mIsAudio;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001084 err = mCodec->releaseOutputBuffer(bufferIx);
1085 }
1086 if (err != OK) {
1087 ALOGE("failed to release output buffer for %s (err=%d)",
1088 mComponentName.c_str(), err);
1089 handleError(err);
1090 }
Chong Zhang66704af2015-03-03 19:32:35 -08001091 if (msg->findInt32("eos", &eos) && eos
1092 && isDiscontinuityPending()) {
1093 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1094 }
1095}
1096
1097bool NuPlayer::Decoder::isDiscontinuityPending() const {
1098 return mFormatChangePending || mTimeChangePending;
1099}
1100
1101void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1102 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1103 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1104
1105 // If we have format change, pause and wait to be killed;
1106 // If we have time change only, flush and restart fetching.
1107
1108 if (mFormatChangePending) {
1109 mPaused = true;
1110 } else if (mTimeChangePending) {
1111 if (flushOnTimeChange) {
Marco Nelissen421f47c2015-03-25 14:40:32 -07001112 doFlush(false /* notifyComplete */);
1113 signalResume(false /* notifyComplete */);
Chong Zhang66704af2015-03-03 19:32:35 -08001114 }
Chong Zhang66704af2015-03-03 19:32:35 -08001115 }
1116
1117 // Notify NuPlayer to either shutdown decoder, or rescan sources
1118 sp<AMessage> msg = mNotify->dup();
1119 msg->setInt32("what", kWhatInputDiscontinuity);
1120 msg->setInt32("formatChange", mFormatChangePending);
1121 msg->post();
1122
1123 mFormatChangePending = false;
1124 mTimeChangePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001125}
1126
Chong Zhang7137ec72014-11-12 16:41:05 -08001127bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
1128 const sp<AMessage> &targetFormat) const {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001129 if (targetFormat == NULL) {
1130 return true;
1131 }
1132
1133 AString mime;
1134 if (!targetFormat->findString("mime", &mime)) {
1135 return false;
1136 }
1137
1138 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1139 // field-by-field comparison
1140 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1141 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1142 int32_t oldVal, newVal;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001143 if (!mInputFormat->findInt32(keys[i], &oldVal) ||
Lajos Molnar1cd13982014-01-17 15:12:51 -08001144 !targetFormat->findInt32(keys[i], &newVal) ||
1145 oldVal != newVal) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001146 return false;
1147 }
1148 }
1149
1150 sp<ABuffer> oldBuf, newBuf;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001151 if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
Lajos Molnar1cd13982014-01-17 15:12:51 -08001152 targetFormat->findBuffer("csd-0", &newBuf)) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001153 if (oldBuf->size() != newBuf->size()) {
1154 return false;
1155 }
1156 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
1157 }
1158 }
1159 return false;
1160}
1161
1162bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
joakim johansson7abbd4c2015-01-30 14:16:03 +01001163 if (mInputFormat == NULL) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001164 return false;
1165 }
1166
1167 if (targetFormat == NULL) {
1168 return true;
1169 }
1170
1171 AString oldMime, newMime;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001172 if (!mInputFormat->findString("mime", &oldMime)
Robert Shih6d0a94e2014-01-23 16:18:22 -08001173 || !targetFormat->findString("mime", &newMime)
1174 || !(oldMime == newMime)) {
1175 return false;
1176 }
1177
1178 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1179 bool seamless;
1180 if (audio) {
1181 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1182 } else {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001183 int32_t isAdaptive;
1184 seamless = (mCodec != NULL &&
1185 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
1186 isAdaptive);
Robert Shih6d0a94e2014-01-23 16:18:22 -08001187 }
1188
1189 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1190 return seamless;
1191}
1192
Chong Zhang7137ec72014-11-12 16:41:05 -08001193void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1194 if (format == NULL) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001195 return;
1196 }
Chong Zhang7137ec72014-11-12 16:41:05 -08001197 mCSDsForCurrentFormat.clear();
1198 for (int32_t i = 0; ; ++i) {
1199 AString tag = "csd-";
1200 tag.append(i);
1201 sp<ABuffer> buffer;
1202 if (!format->findBuffer(tag.c_str(), &buffer)) {
1203 break;
1204 }
1205 mCSDsForCurrentFormat.push(buffer);
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001206 }
Chong Zhangb86e68f2014-08-01 13:46:53 -07001207}
1208
Chong Zhangf8d71772014-11-26 15:08:34 -08001209void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
1210 if (mResumePending) {
1211 mResumePending = false;
1212
1213 sp<AMessage> notify = mNotify->dup();
1214 notify->setInt32("what", kWhatResumeCompleted);
1215 notify->post();
1216 }
1217}
1218
Andreas Huberf9334412010-12-15 15:17:42 -08001219} // namespace android
1220