blob: 69cd82e2df6808fc73d7b0a7378a0dbbbccda257 [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>
Dongwon Kangbc8f53b2018-01-25 17:01:44 -080032#include <media/MediaBufferHolder.h>
Wonsik Kim7e34bf52016-08-23 00:09:18 +090033#include <media/MediaCodecBuffer.h>
Andreas Huberf9334412010-12-15 15:17:42 -080034#include <media/stagefright/foundation/ABuffer.h>
35#include <media/stagefright/foundation/ADebug.h>
Andreas Huber5bc087c2010-12-23 10:27:40 -080036#include <media/stagefright/foundation/AMessage.h>
Dongwon Kangd91dc5a2017-10-10 00:07:09 -070037#include <media/stagefright/foundation/avc_utils.h>
Lajos Molnar09524832014-07-17 14:29:51 -070038#include <media/stagefright/MediaBuffer.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080039#include <media/stagefright/MediaCodec.h>
Andreas Huberf9334412010-12-15 15:17:42 -080040#include <media/stagefright/MediaDefs.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080041#include <media/stagefright/MediaErrors.h>
Chong Zhang181fd9b2017-02-16 15:53:03 -080042#include <media/stagefright/SurfaceUtils.h>
Lajos Molnar1de1e252015-04-30 18:18:34 -070043#include <gui/Surface.h>
44
Chong Zhang7137ec72014-11-12 16:41:05 -080045#include "ATSParser.h"
46
Andreas Huberf9334412010-12-15 15:17:42 -080047namespace android {
48
Lajos Molnar9fb81522016-07-14 07:33:43 -070049static float kDisplayRefreshingRate = 60.f; // TODO: get this from the display
Praveen Chavanbbaa1442016-04-08 13:33:49 -070050
51// The default total video frame rate of a stream when that info is not available from
52// the source.
53static float kDefaultVideoFrameRateTotal = 30.f;
54
Andy Hung288da022015-05-31 22:55:59 -070055static inline bool getAudioDeepBufferSetting() {
56 return property_get_bool("media.stagefright.audio.deep", false /* default_value */);
57}
58
Andreas Huberf9334412010-12-15 15:17:42 -080059NuPlayer::Decoder::Decoder(
Glenn Kasten11731182011-02-08 17:26:17 -080060 const sp<AMessage> &notify,
Wei Jiac6cfd702014-11-11 16:33:20 -080061 const sp<Source> &source,
Ronghua Wu68845c12015-07-21 09:50:48 -070062 pid_t pid,
Wei Jiaf2ae3e12016-10-27 17:10:59 -070063 uid_t uid,
Wei Jiac6cfd702014-11-11 16:33:20 -080064 const sp<Renderer> &renderer,
Lajos Molnar1de1e252015-04-30 18:18:34 -070065 const sp<Surface> &surface,
Chong Zhang7137ec72014-11-12 16:41:05 -080066 const sp<CCDecoder> &ccDecoder)
Andy Hung202bce12014-12-03 11:47:36 -080067 : DecoderBase(notify),
Lajos Molnar1de1e252015-04-30 18:18:34 -070068 mSurface(surface),
Wei Jiac6cfd702014-11-11 16:33:20 -080069 mSource(source),
70 mRenderer(renderer),
Chong Zhang7137ec72014-11-12 16:41:05 -080071 mCCDecoder(ccDecoder),
Ronghua Wu68845c12015-07-21 09:50:48 -070072 mPid(pid),
Wei Jiaf2ae3e12016-10-27 17:10:59 -070073 mUid(uid),
Wei Jiac6cfd702014-11-11 16:33:20 -080074 mSkipRenderingUntilMediaTimeUs(-1ll),
Chong Zhang7137ec72014-11-12 16:41:05 -080075 mNumFramesTotal(0ll),
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070076 mNumInputFramesDropped(0ll),
77 mNumOutputFramesDropped(0ll),
78 mVideoWidth(0),
79 mVideoHeight(0),
Chong Zhang7137ec72014-11-12 16:41:05 -080080 mIsAudio(true),
81 mIsVideoAVC(false),
82 mIsSecure(false),
Hassan Shojania62dec952017-05-18 10:45:27 -070083 mIsEncrypted(false),
84 mIsEncryptedObservedEarlier(false),
Chong Zhang7137ec72014-11-12 16:41:05 -080085 mFormatChangePending(false),
Chong Zhang66704af2015-03-03 19:32:35 -080086 mTimeChangePending(false),
Praveen Chavanbbaa1442016-04-08 13:33:49 -070087 mFrameRateTotal(kDefaultVideoFrameRateTotal),
88 mPlaybackSpeed(1.0f),
Lajos Molnar9fb81522016-07-14 07:33:43 -070089 mNumVideoTemporalLayerTotal(1), // decode all layers
Praveen Chavanbbaa1442016-04-08 13:33:49 -070090 mNumVideoTemporalLayerAllowed(1),
91 mCurrentMaxVideoTemporalLayerId(0),
Chong Zhangf8d71772014-11-26 15:08:34 -080092 mResumePending(false),
Lajos Molnar1cd13982014-01-17 15:12:51 -080093 mComponentName("decoder") {
Lajos Molnar1cd13982014-01-17 15:12:51 -080094 mCodecLooper = new ALooper;
Marco Nelissen9e2b7912014-08-18 16:13:03 -070095 mCodecLooper->setName("NPDecoder-CL");
Lajos Molnar1cd13982014-01-17 15:12:51 -080096 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
Praveen Chavanbbaa1442016-04-08 13:33:49 -070097 mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
Andreas Huberf9334412010-12-15 15:17:42 -080098}
99
100NuPlayer::Decoder::~Decoder() {
Wei Jia37ff0e62017-04-21 11:24:45 -0700101 // Need to stop looper first since mCodec could be accessed on the mDecoderLooper.
102 stopLooper();
103 if (mCodec != NULL) {
104 mCodec->release();
105 }
Wei Jia4923cee2014-09-24 14:25:19 -0700106 releaseAndResetMediaBuffers();
Andreas Huberf9334412010-12-15 15:17:42 -0800107}
108
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700109sp<AMessage> NuPlayer::Decoder::getStats() const {
110 mStats->setInt64("frames-total", mNumFramesTotal);
111 mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
112 mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
113 return mStats;
Lajos Molnar09524832014-07-17 14:29:51 -0700114}
115
Lajos Molnara81c6222015-07-10 19:17:45 -0700116status_t NuPlayer::Decoder::setVideoSurface(const sp<Surface> &surface) {
117 if (surface == NULL || ADebug::isExperimentEnabled("legacy-setsurface")) {
118 return BAD_VALUE;
119 }
120
121 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
122
123 msg->setObject("surface", surface);
124 sp<AMessage> response;
125 status_t err = msg->postAndAwaitResponse(&response);
126 if (err == OK && response != NULL) {
127 CHECK(response->findInt32("err", &err));
128 }
129 return err;
130}
131
Chong Zhang7137ec72014-11-12 16:41:05 -0800132void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
133 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
134
135 switch (msg->what()) {
136 case kWhatCodecNotify:
137 {
Chong Zhang3b032b32015-04-17 15:49:06 -0700138 int32_t cbID;
139 CHECK(msg->findInt32("callbackID", &cbID));
140
141 ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
142 mIsAudio ? "audio" : "video", cbID, mPaused);
143
Marco Nelissen421f47c2015-03-25 14:40:32 -0700144 if (mPaused) {
145 break;
Chong Zhang7137ec72014-11-12 16:41:05 -0800146 }
147
Marco Nelissen421f47c2015-03-25 14:40:32 -0700148 switch (cbID) {
149 case MediaCodec::CB_INPUT_AVAILABLE:
150 {
151 int32_t index;
152 CHECK(msg->findInt32("index", &index));
153
154 handleAnInputBuffer(index);
155 break;
156 }
157
158 case MediaCodec::CB_OUTPUT_AVAILABLE:
159 {
160 int32_t index;
161 size_t offset;
162 size_t size;
163 int64_t timeUs;
164 int32_t flags;
165
166 CHECK(msg->findInt32("index", &index));
167 CHECK(msg->findSize("offset", &offset));
168 CHECK(msg->findSize("size", &size));
169 CHECK(msg->findInt64("timeUs", &timeUs));
170 CHECK(msg->findInt32("flags", &flags));
171
172 handleAnOutputBuffer(index, offset, size, timeUs, flags);
173 break;
174 }
175
176 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED:
177 {
178 sp<AMessage> format;
179 CHECK(msg->findMessage("format", &format));
180
181 handleOutputFormatChange(format);
182 break;
183 }
184
185 case MediaCodec::CB_ERROR:
186 {
187 status_t err;
188 CHECK(msg->findInt32("err", &err));
189 ALOGE("Decoder (%s) reported error : 0x%x",
190 mIsAudio ? "audio" : "video", err);
191
192 handleError(err);
193 break;
194 }
195
196 default:
197 {
198 TRESPASS();
199 break;
200 }
201 }
202
Lajos Molnar87603c02014-08-20 19:25:30 -0700203 break;
204 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800205
206 case kWhatRenderBuffer:
207 {
208 if (!isStaleReply(msg)) {
209 onRenderBuffer(msg);
210 }
211 break;
212 }
213
Wei Jia9a3101b2016-11-08 14:34:24 -0800214 case kWhatAudioOutputFormatChanged:
215 {
216 if (!isStaleReply(msg)) {
217 status_t err;
218 if (msg->findInt32("err", &err) && err != OK) {
219 ALOGE("Renderer reported 0x%x when changing audio output format", err);
220 handleError(err);
221 }
222 }
223 break;
224 }
225
Lajos Molnara81c6222015-07-10 19:17:45 -0700226 case kWhatSetVideoSurface:
227 {
228 sp<AReplyToken> replyID;
229 CHECK(msg->senderAwaitsResponse(&replyID));
230
231 sp<RefBase> obj;
232 CHECK(msg->findObject("surface", &obj));
233 sp<Surface> surface = static_cast<Surface *>(obj.get()); // non-null
234 int32_t err = INVALID_OPERATION;
235 // NOTE: in practice mSurface is always non-null, but checking here for completeness
236 if (mCodec != NULL && mSurface != NULL) {
237 // TODO: once AwesomePlayer is removed, remove this automatic connecting
238 // to the surface by MediaPlayerService.
239 //
240 // at this point MediaPlayerService::client has already connected to the
241 // surface, which MediaCodec does not expect
Chong Zhang181fd9b2017-02-16 15:53:03 -0800242 err = nativeWindowDisconnect(surface.get(), "kWhatSetVideoSurface(surface)");
Lajos Molnara81c6222015-07-10 19:17:45 -0700243 if (err == OK) {
244 err = mCodec->setSurface(surface);
245 ALOGI_IF(err, "codec setSurface returned: %d", err);
246 if (err == OK) {
247 // reconnect to the old surface as MPS::Client will expect to
248 // be able to disconnect from it.
Chong Zhang181fd9b2017-02-16 15:53:03 -0800249 (void)nativeWindowConnect(mSurface.get(), "kWhatSetVideoSurface(mSurface)");
Lajos Molnara81c6222015-07-10 19:17:45 -0700250 mSurface = surface;
251 }
252 }
253 if (err != OK) {
254 // reconnect to the new surface on error as MPS::Client will expect to
255 // be able to disconnect from it.
Chong Zhang181fd9b2017-02-16 15:53:03 -0800256 (void)nativeWindowConnect(surface.get(), "kWhatSetVideoSurface(err)");
Lajos Molnara81c6222015-07-10 19:17:45 -0700257 }
258 }
259
260 sp<AMessage> response = new AMessage;
261 response->setInt32("err", err);
262 response->postReply(replyID);
263 break;
264 }
265
Hassan Shojaniacefac142017-02-06 21:02:02 -0800266 case kWhatDrmReleaseCrypto:
267 {
268 ALOGV("kWhatDrmReleaseCrypto");
269 onReleaseCrypto(msg);
270 break;
271 }
272
Chong Zhang7137ec72014-11-12 16:41:05 -0800273 default:
274 DecoderBase::onMessageReceived(msg);
275 break;
Lajos Molnar87603c02014-08-20 19:25:30 -0700276 }
277}
278
Lajos Molnar1cd13982014-01-17 15:12:51 -0800279void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
Andreas Huberf9334412010-12-15 15:17:42 -0800280 CHECK(mCodec == NULL);
Andreas Huberf9334412010-12-15 15:17:42 -0800281
Chong Zhang7137ec72014-11-12 16:41:05 -0800282 mFormatChangePending = false;
Chong Zhang66704af2015-03-03 19:32:35 -0800283 mTimeChangePending = false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800284
Lajos Molnar1cd13982014-01-17 15:12:51 -0800285 ++mBufferGeneration;
286
Andreas Huber84066782011-08-16 09:34:26 -0700287 AString mime;
288 CHECK(format->findString("mime", &mime));
Andreas Huberf9334412010-12-15 15:17:42 -0800289
Chong Zhang7137ec72014-11-12 16:41:05 -0800290 mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
291 mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
292
Lajos Molnar1cd13982014-01-17 15:12:51 -0800293 mComponentName = mime;
294 mComponentName.append(" decoder");
Lajos Molnar1de1e252015-04-30 18:18:34 -0700295 ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), mSurface.get());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800296
Ronghua Wu68845c12015-07-21 09:50:48 -0700297 mCodec = MediaCodec::CreateByType(
Wei Jiaf2ae3e12016-10-27 17:10:59 -0700298 mCodecLooper, mime.c_str(), false /* encoder */, NULL /* err */, mPid, mUid);
Lajos Molnar09524832014-07-17 14:29:51 -0700299 int32_t secure = 0;
300 if (format->findInt32("secure", &secure) && secure != 0) {
301 if (mCodec != NULL) {
302 mCodec->getName(&mComponentName);
303 mComponentName.append(".secure");
304 mCodec->release();
305 ALOGI("[%s] creating", mComponentName.c_str());
306 mCodec = MediaCodec::CreateByComponentName(
Wei Jiaf2ae3e12016-10-27 17:10:59 -0700307 mCodecLooper, mComponentName.c_str(), NULL /* err */, mPid, mUid);
Lajos Molnar09524832014-07-17 14:29:51 -0700308 }
309 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800310 if (mCodec == NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700311 ALOGE("Failed to create %s%s decoder",
312 (secure ? "secure " : ""), mime.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800313 handleError(UNKNOWN_ERROR);
314 return;
315 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800316 mIsSecure = secure;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800317
318 mCodec->getName(&mComponentName);
319
Lajos Molnar14986f62014-09-15 11:04:44 -0700320 status_t err;
Lajos Molnar1de1e252015-04-30 18:18:34 -0700321 if (mSurface != NULL) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800322 // disconnect from surface as MediaCodec will reconnect
Chong Zhang181fd9b2017-02-16 15:53:03 -0800323 err = nativeWindowDisconnect(mSurface.get(), "onConfigure");
Lajos Molnar14986f62014-09-15 11:04:44 -0700324 // We treat this as a warning, as this is a preparatory step.
325 // Codec will try to connect to the surface, which is where
326 // any error signaling will occur.
327 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800328 }
Hassan Shojaniacefac142017-02-06 21:02:02 -0800329
330 // Modular DRM
331 void *pCrypto;
332 if (!format->findPointer("crypto", &pCrypto)) {
333 pCrypto = NULL;
334 }
335 sp<ICrypto> crypto = (ICrypto*)pCrypto;
Hassan Shojania62dec952017-05-18 10:45:27 -0700336 // non-encrypted source won't have a crypto
337 mIsEncrypted = (crypto != NULL);
338 // configure is called once; still using OR in case the behavior changes.
339 mIsEncryptedObservedEarlier = mIsEncryptedObservedEarlier || mIsEncrypted;
Hassan Shojaniacefac142017-02-06 21:02:02 -0800340 ALOGV("onConfigure mCrypto: %p (%d) mIsSecure: %d",
341 crypto.get(), (crypto != NULL ? crypto->getStrongCount() : 0), mIsSecure);
342
Lajos Molnar14986f62014-09-15 11:04:44 -0700343 err = mCodec->configure(
Hassan Shojaniacefac142017-02-06 21:02:02 -0800344 format, mSurface, crypto, 0 /* flags */);
345
Lajos Molnar1cd13982014-01-17 15:12:51 -0800346 if (err != OK) {
Wei Jiafcd87872017-07-28 15:50:04 -0700347 ALOGE("Failed to configure [%s] decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700348 mCodec->release();
349 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800350 handleError(err);
351 return;
352 }
Lajos Molnar87603c02014-08-20 19:25:30 -0700353 rememberCodecSpecificData(format);
354
Lajos Molnar1cd13982014-01-17 15:12:51 -0800355 // the following should work in configured state
356 CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
357 CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
358
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700359 mStats->setString("mime", mime.c_str());
360 mStats->setString("component-name", mComponentName.c_str());
361
362 if (!mIsAudio) {
363 int32_t width, height;
364 if (mOutputFormat->findInt32("width", &width)
365 && mOutputFormat->findInt32("height", &height)) {
366 mStats->setInt32("width", width);
367 mStats->setInt32("height", height);
368 }
369 }
370
Marco Nelissen421f47c2015-03-25 14:40:32 -0700371 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
372 mCodec->setCallback(reply);
373
Lajos Molnar1cd13982014-01-17 15:12:51 -0800374 err = mCodec->start();
375 if (err != OK) {
Wei Jiafcd87872017-07-28 15:50:04 -0700376 ALOGE("Failed to start [%s] decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700377 mCodec->release();
378 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800379 handleError(err);
380 return;
Andreas Huberf9334412010-12-15 15:17:42 -0800381 }
382
Lajos Molnar09524832014-07-17 14:29:51 -0700383 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700384
Wei Jia704e7262014-06-04 16:21:56 -0700385 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800386 mResumePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800387}
Andreas Huber078cfcf2011-09-15 12:25:04 -0700388
Ronghua Wu8db88132015-04-22 13:51:35 -0700389void NuPlayer::Decoder::onSetParameters(const sp<AMessage> &params) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700390 bool needAdjustLayers = false;
391 float frameRateTotal;
392 if (params->findFloat("frame-rate-total", &frameRateTotal)
393 && mFrameRateTotal != frameRateTotal) {
394 needAdjustLayers = true;
395 mFrameRateTotal = frameRateTotal;
Ronghua Wu8db88132015-04-22 13:51:35 -0700396 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700397
398 int32_t numVideoTemporalLayerTotal;
399 if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
Lajos Molnar9fb81522016-07-14 07:33:43 -0700400 && numVideoTemporalLayerTotal >= 0
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700401 && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
402 && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
403 needAdjustLayers = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700404 mNumVideoTemporalLayerTotal = std::max(numVideoTemporalLayerTotal, 1);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700405 }
406
Lajos Molnar9fb81522016-07-14 07:33:43 -0700407 if (needAdjustLayers && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700408 // TODO: For now, layer fps is calculated for some specific architectures.
409 // But it really should be extracted from the stream.
410 mVideoTemporalLayerAggregateFps[0] =
411 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - 1));
412 for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
413 mVideoTemporalLayerAggregateFps[i] =
414 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - i))
415 + mVideoTemporalLayerAggregateFps[i - 1];
416 }
417 }
418
419 float playbackSpeed;
420 if (params->findFloat("playback-speed", &playbackSpeed)
421 && mPlaybackSpeed != playbackSpeed) {
422 needAdjustLayers = true;
423 mPlaybackSpeed = playbackSpeed;
424 }
425
426 if (needAdjustLayers) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700427 float decodeFrameRate = mFrameRateTotal;
428 // enable temporal layering optimization only if we know the layering depth
429 if (mNumVideoTemporalLayerTotal > 1) {
430 int32_t layerId;
431 for (layerId = 0; layerId < mNumVideoTemporalLayerTotal - 1; ++layerId) {
432 if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
433 >= kDisplayRefreshingRate * 0.9) {
434 break;
435 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700436 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700437 mNumVideoTemporalLayerAllowed = layerId + 1;
438 decodeFrameRate = mVideoTemporalLayerAggregateFps[layerId];
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700439 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700440 ALOGV("onSetParameters: allowed layers=%d, decodeFps=%g",
441 mNumVideoTemporalLayerAllowed, decodeFrameRate);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700442
443 if (mCodec == NULL) {
444 ALOGW("onSetParameters called before codec is created.");
445 return;
446 }
447
448 sp<AMessage> codecParams = new AMessage();
Lajos Molnar9fb81522016-07-14 07:33:43 -0700449 codecParams->setFloat("operating-rate", decodeFrameRate * mPlaybackSpeed);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700450 mCodec->setParameters(codecParams);
451 }
Ronghua Wu8db88132015-04-22 13:51:35 -0700452}
453
Chong Zhang7137ec72014-11-12 16:41:05 -0800454void NuPlayer::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800455 mRenderer = renderer;
Chong Zhang7137ec72014-11-12 16:41:05 -0800456}
457
Chong Zhangf8d71772014-11-26 15:08:34 -0800458void NuPlayer::Decoder::onResume(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800459 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800460
461 if (notifyComplete) {
462 mResumePending = true;
463 }
Wei Jiafcd87872017-07-28 15:50:04 -0700464
465 if (mCodec == NULL) {
466 ALOGE("[%s] onResume without a valid codec", mComponentName.c_str());
467 handleError(NO_INIT);
468 return;
469 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700470 mCodec->start();
Chong Zhang7137ec72014-11-12 16:41:05 -0800471}
472
Chong Zhang66704af2015-03-03 19:32:35 -0800473void NuPlayer::Decoder::doFlush(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800474 if (mCCDecoder != NULL) {
475 mCCDecoder->flush();
476 }
477
478 if (mRenderer != NULL) {
479 mRenderer->flush(mIsAudio, notifyComplete);
480 mRenderer->signalTimeDiscontinuity();
481 }
482
483 status_t err = OK;
484 if (mCodec != NULL) {
485 err = mCodec->flush();
486 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
487 ++mBufferGeneration;
488 }
489
490 if (err != OK) {
Wei Jiafcd87872017-07-28 15:50:04 -0700491 ALOGE("failed to flush [%s] (err=%d)", mComponentName.c_str(), err);
Chong Zhang7137ec72014-11-12 16:41:05 -0800492 handleError(err);
493 // finish with posting kWhatFlushCompleted.
494 // we attempt to release the buffers even if flush fails.
495 }
496 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700497 mPaused = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800498}
Chong Zhang7137ec72014-11-12 16:41:05 -0800499
Marco Nelissen421f47c2015-03-25 14:40:32 -0700500
Chong Zhang66704af2015-03-03 19:32:35 -0800501void NuPlayer::Decoder::onFlush() {
502 doFlush(true);
503
504 if (isDiscontinuityPending()) {
505 // This could happen if the client starts seeking/shutdown
506 // after we queued an EOS for discontinuities.
507 // We can consider discontinuity handled.
508 finishHandleDiscontinuity(false /* flushOnTimeChange */);
Chong Zhang7137ec72014-11-12 16:41:05 -0800509 }
Chong Zhang66704af2015-03-03 19:32:35 -0800510
511 sp<AMessage> notify = mNotify->dup();
512 notify->setInt32("what", kWhatFlushCompleted);
513 notify->post();
Chong Zhang7137ec72014-11-12 16:41:05 -0800514}
515
516void NuPlayer::Decoder::onShutdown(bool notifyComplete) {
517 status_t err = OK;
Chong Zhangf8d71772014-11-26 15:08:34 -0800518
519 // if there is a pending resume request, notify complete now
520 notifyResumeCompleteIfNecessary();
521
Chong Zhang7137ec72014-11-12 16:41:05 -0800522 if (mCodec != NULL) {
523 err = mCodec->release();
524 mCodec = NULL;
525 ++mBufferGeneration;
526
Lajos Molnar1de1e252015-04-30 18:18:34 -0700527 if (mSurface != NULL) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800528 // reconnect to surface as MediaCodec disconnected from it
Chong Zhang181fd9b2017-02-16 15:53:03 -0800529 status_t error = nativeWindowConnect(mSurface.get(), "onShutdown");
Chong Zhang7137ec72014-11-12 16:41:05 -0800530 ALOGW_IF(error != NO_ERROR,
531 "[%s] failed to connect to native window, error=%d",
532 mComponentName.c_str(), error);
533 }
534 mComponentName = "decoder";
535 }
536
537 releaseAndResetMediaBuffers();
538
539 if (err != OK) {
Wei Jiafcd87872017-07-28 15:50:04 -0700540 ALOGE("failed to release [%s] (err=%d)", mComponentName.c_str(), err);
Chong Zhang7137ec72014-11-12 16:41:05 -0800541 handleError(err);
542 // finish with posting kWhatShutdownCompleted.
543 }
544
545 if (notifyComplete) {
546 sp<AMessage> notify = mNotify->dup();
547 notify->setInt32("what", kWhatShutdownCompleted);
548 notify->post();
549 mPaused = true;
550 }
551}
552
Chong Zhang3b032b32015-04-17 15:49:06 -0700553/*
554 * returns true if we should request more data
555 */
556bool NuPlayer::Decoder::doRequestBuffers() {
Jeff Tinker29b7dcf2016-10-24 10:28:30 -0700557 if (isDiscontinuityPending()) {
Chong Zhang3b032b32015-04-17 15:49:06 -0700558 return false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800559 }
560 status_t err = OK;
Chong Zhang66704af2015-03-03 19:32:35 -0800561 while (err == OK && !mDequeuedInputBuffers.empty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800562 size_t bufferIx = *mDequeuedInputBuffers.begin();
563 sp<AMessage> msg = new AMessage();
564 msg->setSize("buffer-ix", bufferIx);
565 err = fetchInputData(msg);
Chong Zhang66704af2015-03-03 19:32:35 -0800566 if (err != OK && err != ERROR_END_OF_STREAM) {
567 // if EOS, need to queue EOS buffer
Chong Zhang7137ec72014-11-12 16:41:05 -0800568 break;
569 }
570 mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
571
572 if (!mPendingInputMessages.empty()
573 || !onInputBufferFetched(msg)) {
574 mPendingInputMessages.push_back(msg);
Lajos Molnar09524832014-07-17 14:29:51 -0700575 }
576 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800577
Chong Zhang3b032b32015-04-17 15:49:06 -0700578 return err == -EWOULDBLOCK
579 && mSource->feedMoreTSData() == OK;
Lajos Molnar09524832014-07-17 14:29:51 -0700580}
581
Marco Nelissen421f47c2015-03-25 14:40:32 -0700582void NuPlayer::Decoder::handleError(int32_t err)
583{
584 // We cannot immediately release the codec due to buffers still outstanding
585 // in the renderer. We signal to the player the error so it can shutdown/release the
586 // decoder after flushing and increment the generation to discard unnecessary messages.
587
588 ++mBufferGeneration;
589
590 sp<AMessage> notify = mNotify->dup();
591 notify->setInt32("what", kWhatError);
592 notify->setInt32("err", err);
593 notify->post();
594}
595
Hassan Shojaniacefac142017-02-06 21:02:02 -0800596status_t NuPlayer::Decoder::releaseCrypto()
597{
598 ALOGV("releaseCrypto");
599
600 sp<AMessage> msg = new AMessage(kWhatDrmReleaseCrypto, this);
601
602 sp<AMessage> response;
603 status_t status = msg->postAndAwaitResponse(&response);
604 if (status == OK && response != NULL) {
605 CHECK(response->findInt32("status", &status));
606 ALOGV("releaseCrypto ret: %d ", status);
607 } else {
608 ALOGE("releaseCrypto err: %d", status);
609 }
610
611 return status;
612}
613
614void NuPlayer::Decoder::onReleaseCrypto(const sp<AMessage>& msg)
615{
616 status_t status = INVALID_OPERATION;
617 if (mCodec != NULL) {
618 status = mCodec->releaseCrypto();
619 } else {
620 // returning OK if the codec has been already released
621 status = OK;
622 ALOGE("onReleaseCrypto No mCodec. err: %d", status);
623 }
624
625 sp<AMessage> response = new AMessage;
626 response->setInt32("status", status);
Hassan Shojania62dec952017-05-18 10:45:27 -0700627 // Clearing the state as it's tied to crypto. mIsEncryptedObservedEarlier is sticky though
628 // and lasts for the lifetime of this codec. See its use in fetchInputData.
629 mIsEncrypted = false;
Hassan Shojaniacefac142017-02-06 21:02:02 -0800630
631 sp<AReplyToken> replyID;
632 CHECK(msg->senderAwaitsResponse(&replyID));
633 response->postReply(replyID);
634}
635
Marco Nelissen421f47c2015-03-25 14:40:32 -0700636bool NuPlayer::Decoder::handleAnInputBuffer(size_t index) {
Chong Zhang66704af2015-03-03 19:32:35 -0800637 if (isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800638 return false;
639 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700640
Wei Jiafcd87872017-07-28 15:50:04 -0700641 if (mCodec == NULL) {
642 ALOGE("[%s] handleAnInputBuffer without a valid codec", mComponentName.c_str());
643 handleError(NO_INIT);
644 return false;
645 }
646
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900647 sp<MediaCodecBuffer> buffer;
Marco Nelissen421f47c2015-03-25 14:40:32 -0700648 mCodec->getInputBuffer(index, &buffer);
649
Wei Jia6301a5e2015-05-13 13:15:18 -0700650 if (buffer == NULL) {
Wei Jiafcd87872017-07-28 15:50:04 -0700651 ALOGE("[%s] handleAnInputBuffer, failed to get input buffer", mComponentName.c_str());
Wei Jia6301a5e2015-05-13 13:15:18 -0700652 handleError(UNKNOWN_ERROR);
653 return false;
654 }
655
Marco Nelissen421f47c2015-03-25 14:40:32 -0700656 if (index >= mInputBuffers.size()) {
657 for (size_t i = mInputBuffers.size(); i <= index; ++i) {
658 mInputBuffers.add();
659 mMediaBuffers.add();
660 mInputBufferIsDequeued.add();
661 mMediaBuffers.editItemAt(i) = NULL;
662 mInputBufferIsDequeued.editItemAt(i) = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800663 }
Andreas Huber078cfcf2011-09-15 12:25:04 -0700664 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700665 mInputBuffers.editItemAt(index) = buffer;
Andreas Huber078cfcf2011-09-15 12:25:04 -0700666
Marco Nelissen421f47c2015-03-25 14:40:32 -0700667 //CHECK_LT(bufferIx, mInputBuffers.size());
Andreas Huberf9334412010-12-15 15:17:42 -0800668
Marco Nelissen421f47c2015-03-25 14:40:32 -0700669 if (mMediaBuffers[index] != NULL) {
670 mMediaBuffers[index]->release();
671 mMediaBuffers.editItemAt(index) = NULL;
Lajos Molnar09524832014-07-17 14:29:51 -0700672 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700673 mInputBufferIsDequeued.editItemAt(index) = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700674
Lajos Molnar87603c02014-08-20 19:25:30 -0700675 if (!mCSDsToSubmit.isEmpty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800676 sp<AMessage> msg = new AMessage();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700677 msg->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800678
Lajos Molnar87603c02014-08-20 19:25:30 -0700679 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
680 ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
Chong Zhang7137ec72014-11-12 16:41:05 -0800681 msg->setBuffer("buffer", buffer);
Lajos Molnar87603c02014-08-20 19:25:30 -0700682 mCSDsToSubmit.removeAt(0);
Wei Jia56097a82016-01-07 16:03:03 -0800683 if (!onInputBufferFetched(msg)) {
684 handleError(UNKNOWN_ERROR);
685 return false;
686 }
Wei Jia2245fc62014-10-02 15:12:25 -0700687 return true;
688 }
689
690 while (!mPendingInputMessages.empty()) {
691 sp<AMessage> msg = *mPendingInputMessages.begin();
Chong Zhang7137ec72014-11-12 16:41:05 -0800692 if (!onInputBufferFetched(msg)) {
Wei Jia2245fc62014-10-02 15:12:25 -0700693 break;
694 }
695 mPendingInputMessages.erase(mPendingInputMessages.begin());
696 }
697
Marco Nelissen421f47c2015-03-25 14:40:32 -0700698 if (!mInputBufferIsDequeued.editItemAt(index)) {
Lajos Molnar87603c02014-08-20 19:25:30 -0700699 return true;
700 }
701
Marco Nelissen421f47c2015-03-25 14:40:32 -0700702 mDequeuedInputBuffers.push_back(index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800703
704 onRequestInputBuffers();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800705 return true;
706}
707
Marco Nelissen421f47c2015-03-25 14:40:32 -0700708bool NuPlayer::Decoder::handleAnOutputBuffer(
709 size_t index,
710 size_t offset,
711 size_t size,
712 int64_t timeUs,
713 int32_t flags) {
Wei Jiafcd87872017-07-28 15:50:04 -0700714 if (mCodec == NULL) {
715 ALOGE("[%s] handleAnOutputBuffer without a valid codec", mComponentName.c_str());
716 handleError(NO_INIT);
717 return false;
718 }
719
Marco Nelissen421f47c2015-03-25 14:40:32 -0700720// CHECK_LT(bufferIx, mOutputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900721 sp<MediaCodecBuffer> buffer;
Marco Nelissen421f47c2015-03-25 14:40:32 -0700722 mCodec->getOutputBuffer(index, &buffer);
723
Santhosh Behara3539def2015-10-09 17:32:58 -0700724 if (buffer == NULL) {
Wei Jiafcd87872017-07-28 15:50:04 -0700725 ALOGE("[%s] handleAnOutputBuffer, failed to get output buffer", mComponentName.c_str());
Santhosh Behara3539def2015-10-09 17:32:58 -0700726 handleError(UNKNOWN_ERROR);
727 return false;
728 }
729
Marco Nelissen421f47c2015-03-25 14:40:32 -0700730 if (index >= mOutputBuffers.size()) {
731 for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
732 mOutputBuffers.add();
733 }
734 }
735
736 mOutputBuffers.editItemAt(index) = buffer;
737
Chong Zhang7137ec72014-11-12 16:41:05 -0800738 buffer->setRange(offset, size);
739 buffer->meta()->clear();
740 buffer->meta()->setInt64("timeUs", timeUs);
Chong Zhang66704af2015-03-03 19:32:35 -0800741
742 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
Chong Zhang7137ec72014-11-12 16:41:05 -0800743 // we do not expect CODECCONFIG or SYNCFRAME for decoder
744
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800745 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700746 reply->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800747 reply->setInt32("generation", mBufferGeneration);
Praveen Chavanbc5fe9a2018-04-27 16:18:11 -0700748 reply->setSize("size", size);
Chong Zhang7137ec72014-11-12 16:41:05 -0800749
Chong Zhang66704af2015-03-03 19:32:35 -0800750 if (eos) {
751 ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
752
753 buffer->meta()->setInt32("eos", true);
754 reply->setInt32("eos", true);
Wei Jiaaec8d822017-08-25 15:27:57 -0700755 }
756
Ray Essickc6e9f6e2017-12-07 16:57:36 -0800757 mNumFramesTotal += !mIsAudio;
758
Wei Jiaaec8d822017-08-25 15:27:57 -0700759 if (mSkipRenderingUntilMediaTimeUs >= 0) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800760 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
761 ALOGV("[%s] dropping buffer at time %lld as requested.",
762 mComponentName.c_str(), (long long)timeUs);
763
764 reply->post();
Wei Jiaaec8d822017-08-25 15:27:57 -0700765 if (eos) {
766 notifyResumeCompleteIfNecessary();
767 if (mRenderer != NULL && !isDiscontinuityPending()) {
768 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
769 }
770 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800771 return true;
772 }
773
774 mSkipRenderingUntilMediaTimeUs = -1;
775 }
776
Chong Zhangf8d71772014-11-26 15:08:34 -0800777 // wait until 1st frame comes out to signal resume complete
778 notifyResumeCompleteIfNecessary();
779
Chong Zhang7137ec72014-11-12 16:41:05 -0800780 if (mRenderer != NULL) {
781 // send the buffer to renderer.
782 mRenderer->queueBuffer(mIsAudio, buffer, reply);
Chong Zhang66704af2015-03-03 19:32:35 -0800783 if (eos && !isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800784 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
785 }
786 }
787
788 return true;
789}
790
Marco Nelissen421f47c2015-03-25 14:40:32 -0700791void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
792 if (!mIsAudio) {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700793 int32_t width, height;
794 if (format->findInt32("width", &width)
795 && format->findInt32("height", &height)) {
796 mStats->setInt32("width", width);
797 mStats->setInt32("height", height);
798 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700799 sp<AMessage> notify = mNotify->dup();
800 notify->setInt32("what", kWhatVideoSizeChanged);
801 notify->setMessage("format", format);
802 notify->post();
803 } else if (mRenderer != NULL) {
804 uint32_t flags;
805 int64_t durationUs;
806 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
Andy Hung288da022015-05-31 22:55:59 -0700807 if (getAudioDeepBufferSetting() // override regardless of source duration
Andy Hung71c8e5c2017-04-03 15:50:27 -0700808 || (mSource->getDuration(&durationUs) == OK
Andy Hung288da022015-05-31 22:55:59 -0700809 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700810 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
811 } else {
812 flags = AUDIO_OUTPUT_FLAG_NONE;
813 }
814
Wei Jia9a3101b2016-11-08 14:34:24 -0800815 sp<AMessage> reply = new AMessage(kWhatAudioOutputFormatChanged, this);
816 reply->setInt32("generation", mBufferGeneration);
817 mRenderer->changeAudioFormat(
Dhananjay Kumarc387f2b2015-08-06 10:43:16 +0530818 format, false /* offloadOnly */, hasVideo,
819 flags, mSource->isStreaming(), reply);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700820 }
821}
822
Chong Zhang7137ec72014-11-12 16:41:05 -0800823void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
824 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
825 if (mMediaBuffers[i] != NULL) {
826 mMediaBuffers[i]->release();
827 mMediaBuffers.editItemAt(i) = NULL;
828 }
829 }
830 mMediaBuffers.resize(mInputBuffers.size());
831 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
832 mMediaBuffers.editItemAt(i) = NULL;
833 }
834 mInputBufferIsDequeued.clear();
835 mInputBufferIsDequeued.resize(mInputBuffers.size());
836 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
837 mInputBufferIsDequeued.editItemAt(i) = false;
838 }
839
840 mPendingInputMessages.clear();
841 mDequeuedInputBuffers.clear();
842 mSkipRenderingUntilMediaTimeUs = -1;
843}
844
845void NuPlayer::Decoder::requestCodecNotification() {
Chong Zhang7137ec72014-11-12 16:41:05 -0800846 if (mCodec != NULL) {
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800847 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
Chong Zhang7137ec72014-11-12 16:41:05 -0800848 reply->setInt32("generation", mBufferGeneration);
849 mCodec->requestActivityNotification(reply);
850 }
851}
852
853bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
854 int32_t generation;
855 CHECK(msg->findInt32("generation", &generation));
856 return generation != mBufferGeneration;
857}
858
859status_t NuPlayer::Decoder::fetchInputData(sp<AMessage> &reply) {
860 sp<ABuffer> accessUnit;
Robert Shih59e9ca72016-10-20 13:51:42 -0700861 bool dropAccessUnit = true;
Chong Zhang7137ec72014-11-12 16:41:05 -0800862 do {
863 status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
864
865 if (err == -EWOULDBLOCK) {
866 return err;
867 } else if (err != OK) {
868 if (err == INFO_DISCONTINUITY) {
869 int32_t type;
870 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
871
872 bool formatChange =
873 (mIsAudio &&
874 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
875 || (!mIsAudio &&
876 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
877
878 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
879
880 ALOGI("%s discontinuity (format=%d, time=%d)",
881 mIsAudio ? "audio" : "video", formatChange, timeChange);
882
883 bool seamlessFormatChange = false;
884 sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
885 if (formatChange) {
886 seamlessFormatChange =
887 supportsSeamlessFormatChange(newFormat);
888 // treat seamless format change separately
889 formatChange = !seamlessFormatChange;
890 }
891
Chong Zhang66704af2015-03-03 19:32:35 -0800892 // For format or time change, return EOS to queue EOS input,
893 // then wait for EOS on output.
Chong Zhang7137ec72014-11-12 16:41:05 -0800894 if (formatChange /* not seamless */) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800895 mFormatChangePending = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800896 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800897 } else if (timeChange) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800898 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800899 mTimeChangePending = true;
900 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800901 } else if (seamlessFormatChange) {
902 // reuse existing decoder and don't flush
903 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800904 continue;
Chong Zhang7137ec72014-11-12 16:41:05 -0800905 } else {
906 // This stream is unaffected by the discontinuity
907 return -EWOULDBLOCK;
908 }
909 }
910
Chong Zhang66704af2015-03-03 19:32:35 -0800911 // reply should only be returned without a buffer set
912 // when there is an error (including EOS)
913 CHECK(err != OK);
914
Chong Zhang7137ec72014-11-12 16:41:05 -0800915 reply->setInt32("err", err);
Chong Zhang66704af2015-03-03 19:32:35 -0800916 return ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800917 }
918
Chong Zhang7137ec72014-11-12 16:41:05 -0800919 dropAccessUnit = false;
Hassan Shojania62dec952017-05-18 10:45:27 -0700920 if (!mIsAudio && !mIsEncrypted) {
921 // Extra safeguard if higher-level behavior changes. Otherwise, not required now.
922 // Preventing the buffer from being processed (and sent to codec) if this is a later
923 // round of playback but this time without prepareDrm. Or if there is a race between
924 // stop (which is not blocking) and releaseDrm allowing buffers being processed after
925 // Crypto has been released (GenericSource currently prevents this race though).
926 // Particularly doing this check before IsAVCReferenceFrame call to prevent parsing
927 // of encrypted data.
928 if (mIsEncryptedObservedEarlier) {
929 ALOGE("fetchInputData: mismatched mIsEncrypted/mIsEncryptedObservedEarlier (0/1)");
930
931 return INVALID_OPERATION;
932 }
933
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700934 int32_t layerId = 0;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700935 bool haveLayerId = accessUnit->meta()->findInt32("temporal-layer-id", &layerId);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700936 if (mRenderer->getVideoLateByUs() > 100000ll
937 && mIsVideoAVC
938 && !IsAVCReferenceFrame(accessUnit)) {
939 dropAccessUnit = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700940 } else if (haveLayerId && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700941 // Add only one layer each time.
942 if (layerId > mCurrentMaxVideoTemporalLayerId + 1
943 || layerId >= mNumVideoTemporalLayerAllowed) {
944 dropAccessUnit = true;
945 ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
946 layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
947 mCurrentMaxVideoTemporalLayerId);
948 } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
949 mCurrentMaxVideoTemporalLayerId = layerId;
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700950 } else if (layerId == 0 && mNumVideoTemporalLayerTotal > 1
951 && IsIDR(accessUnit->data(), accessUnit->size())) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700952 mCurrentMaxVideoTemporalLayerId = mNumVideoTemporalLayerTotal - 1;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700953 }
954 }
955 if (dropAccessUnit) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700956 if (layerId <= mCurrentMaxVideoTemporalLayerId && layerId > 0) {
957 mCurrentMaxVideoTemporalLayerId = layerId - 1;
958 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700959 ++mNumInputFramesDropped;
960 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800961 }
962 } while (dropAccessUnit);
963
964 // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
965#if 0
966 int64_t mediaTimeUs;
967 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
Chong Zhang5abbd3d2015-04-20 16:03:00 -0700968 ALOGV("[%s] feeding input buffer at media time %.3f",
Chong Zhang7137ec72014-11-12 16:41:05 -0800969 mIsAudio ? "audio" : "video",
970 mediaTimeUs / 1E6);
971#endif
972
973 if (mCCDecoder != NULL) {
974 mCCDecoder->decode(accessUnit);
975 }
976
977 reply->setBuffer("buffer", accessUnit);
978
979 return OK;
980}
981
982bool NuPlayer::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
Wei Jiafcd87872017-07-28 15:50:04 -0700983 if (mCodec == NULL) {
984 ALOGE("[%s] onInputBufferFetched without a valid codec", mComponentName.c_str());
985 handleError(NO_INIT);
986 return false;
987 }
988
Lajos Molnar1cd13982014-01-17 15:12:51 -0800989 size_t bufferIx;
990 CHECK(msg->findSize("buffer-ix", &bufferIx));
991 CHECK_LT(bufferIx, mInputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900992 sp<MediaCodecBuffer> codecBuffer = mInputBuffers[bufferIx];
Lajos Molnar1cd13982014-01-17 15:12:51 -0800993
994 sp<ABuffer> buffer;
995 bool hasBuffer = msg->findBuffer("buffer", &buffer);
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900996 bool needsCopy = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700997
Lajos Molnar1cd13982014-01-17 15:12:51 -0800998 if (buffer == NULL /* includes !hasBuffer */) {
999 int32_t streamErr = ERROR_END_OF_STREAM;
1000 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
1001
Chong Zhang66704af2015-03-03 19:32:35 -08001002 CHECK(streamErr != OK);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001003
1004 // attempt to queue EOS
1005 status_t err = mCodec->queueInputBuffer(
1006 bufferIx,
1007 0,
1008 0,
1009 0,
1010 MediaCodec::BUFFER_FLAG_EOS);
Andy Hungcf31f1e2014-09-23 14:59:01 -07001011 if (err == OK) {
1012 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
1013 } else if (streamErr == ERROR_END_OF_STREAM) {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001014 streamErr = err;
1015 // err will not be ERROR_END_OF_STREAM
1016 }
1017
1018 if (streamErr != ERROR_END_OF_STREAM) {
Wei Jiafcd87872017-07-28 15:50:04 -07001019 ALOGE("Stream error for [%s] (err=%d), EOS %s queued",
Andy Hungcf31f1e2014-09-23 14:59:01 -07001020 mComponentName.c_str(),
1021 streamErr,
1022 err == OK ? "successfully" : "unsuccessfully");
Lajos Molnar1cd13982014-01-17 15:12:51 -08001023 handleError(streamErr);
1024 }
1025 } else {
Wei Jiac6cfd702014-11-11 16:33:20 -08001026 sp<AMessage> extra;
1027 if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
1028 int64_t resumeAtMediaTimeUs;
1029 if (extra->findInt64(
1030 "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
1031 ALOGI("[%s] suppressing rendering until %lld us",
1032 mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
1033 mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
1034 }
1035 }
1036
Lajos Molnar1cd13982014-01-17 15:12:51 -08001037 int64_t timeUs = 0;
1038 uint32_t flags = 0;
1039 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1040
Lajos Molnar87603c02014-08-20 19:25:30 -07001041 int32_t eos, csd;
1042 // we do not expect SYNCFRAME for decoder
Lajos Molnar1cd13982014-01-17 15:12:51 -08001043 if (buffer->meta()->findInt32("eos", &eos) && eos) {
1044 flags |= MediaCodec::BUFFER_FLAG_EOS;
Lajos Molnar87603c02014-08-20 19:25:30 -07001045 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
1046 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001047 }
1048
Hassan Shojaniacefac142017-02-06 21:02:02 -08001049 // Modular DRM
Dongwon Kang1889c3e2018-02-01 13:44:57 -08001050 MediaBufferBase *mediaBuf = NULL;
Hassan Shojaniacefac142017-02-06 21:02:02 -08001051 NuPlayerDrm::CryptoInfo *cryptInfo = NULL;
1052
Lajos Molnar1cd13982014-01-17 15:12:51 -08001053 // copy into codec buffer
Wonsik Kim7e34bf52016-08-23 00:09:18 +09001054 if (needsCopy) {
Wei Jia56097a82016-01-07 16:03:03 -08001055 if (buffer->size() > codecBuffer->capacity()) {
1056 handleError(ERROR_BUFFER_TOO_SMALL);
1057 mDequeuedInputBuffers.push_back(bufferIx);
1058 return false;
1059 }
Lajos Molnar1cd13982014-01-17 15:12:51 -08001060
Hassan Shojaniacefac142017-02-06 21:02:02 -08001061 if (buffer->data() != NULL) {
1062 codecBuffer->setRange(0, buffer->size());
1063 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
1064 } else { // No buffer->data()
1065 //Modular DRM
Dongwon Kangbc8f53b2018-01-25 17:01:44 -08001066 sp<RefBase> holder;
1067 if (buffer->meta()->findObject("mediaBufferHolder", &holder)) {
1068 mediaBuf = (holder != nullptr) ?
1069 static_cast<MediaBufferHolder*>(holder.get())->mediaBuffer() : nullptr;
1070 }
Hassan Shojaniacefac142017-02-06 21:02:02 -08001071 if (mediaBuf != NULL) {
1072 codecBuffer->setRange(0, mediaBuf->size());
1073 memcpy(codecBuffer->data(), mediaBuf->data(), mediaBuf->size());
1074
Marco Nelissen3d21ae32018-02-16 08:24:08 -08001075 MetaDataBase &meta_data = mediaBuf->meta_data();
Hassan Shojaniacefac142017-02-06 21:02:02 -08001076 cryptInfo = NuPlayerDrm::getSampleCryptoInfo(meta_data);
Hassan Shojaniacefac142017-02-06 21:02:02 -08001077 } else { // No mediaBuf
1078 ALOGE("onInputBufferFetched: buffer->data()/mediaBuf are NULL for %p",
1079 buffer.get());
1080 handleError(UNKNOWN_ERROR);
1081 return false;
1082 }
1083 } // buffer->data()
1084 } // needsCopy
1085
1086 status_t err;
1087 AString errorDetailMsg;
1088 if (cryptInfo != NULL) {
1089 err = mCodec->queueSecureInputBuffer(
1090 bufferIx,
1091 codecBuffer->offset(),
1092 cryptInfo->subSamples,
1093 cryptInfo->numSubSamples,
1094 cryptInfo->key,
1095 cryptInfo->iv,
1096 cryptInfo->mode,
1097 cryptInfo->pattern,
1098 timeUs,
1099 flags,
1100 &errorDetailMsg);
1101 // synchronous call so done with cryptInfo here
1102 free(cryptInfo);
1103 } else {
1104 err = mCodec->queueInputBuffer(
1105 bufferIx,
1106 codecBuffer->offset(),
1107 codecBuffer->size(),
1108 timeUs,
1109 flags,
1110 &errorDetailMsg);
1111 } // no cryptInfo
1112
Lajos Molnar1cd13982014-01-17 15:12:51 -08001113 if (err != OK) {
Wei Jiafcd87872017-07-28 15:50:04 -07001114 ALOGE("onInputBufferFetched: queue%sInputBuffer failed for [%s] (err=%d, %s)",
Hassan Shojaniacefac142017-02-06 21:02:02 -08001115 (cryptInfo != NULL ? "Secure" : ""),
1116 mComponentName.c_str(), err, errorDetailMsg.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -08001117 handleError(err);
Andy Hungcf31f1e2014-09-23 14:59:01 -07001118 } else {
1119 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
Lajos Molnar09524832014-07-17 14:29:51 -07001120 }
Hassan Shojaniacefac142017-02-06 21:02:02 -08001121
1122 } // buffer != NULL
Wei Jia2245fc62014-10-02 15:12:25 -07001123 return true;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001124}
1125
Lajos Molnar1cd13982014-01-17 15:12:51 -08001126void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
1127 status_t err;
1128 int32_t render;
1129 size_t bufferIx;
Chong Zhang66704af2015-03-03 19:32:35 -08001130 int32_t eos;
Praveen Chavanbc5fe9a2018-04-27 16:18:11 -07001131 size_t size;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001132 CHECK(msg->findSize("buffer-ix", &bufferIx));
Wei Jiac6cfd702014-11-11 16:33:20 -08001133
Chong Zhang7137ec72014-11-12 16:41:05 -08001134 if (!mIsAudio) {
Wei Jiac6cfd702014-11-11 16:33:20 -08001135 int64_t timeUs;
Wonsik Kim7e34bf52016-08-23 00:09:18 +09001136 sp<MediaCodecBuffer> buffer = mOutputBuffers[bufferIx];
Wei Jiac6cfd702014-11-11 16:33:20 -08001137 buffer->meta()->findInt64("timeUs", &timeUs);
Chong Zhang7137ec72014-11-12 16:41:05 -08001138
1139 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1140 mCCDecoder->display(timeUs);
1141 }
Wei Jiac6cfd702014-11-11 16:33:20 -08001142 }
1143
Wei Jiafcd87872017-07-28 15:50:04 -07001144 if (mCodec == NULL) {
1145 err = NO_INIT;
1146 } else if (msg->findInt32("render", &render) && render) {
Lajos Molnardc43dfa2014-05-07 15:33:04 -07001147 int64_t timestampNs;
1148 CHECK(msg->findInt64("timestampNs", &timestampNs));
1149 err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001150 } else {
Praveen Chavanbc5fe9a2018-04-27 16:18:11 -07001151 if (!msg->findInt32("eos", &eos) || !eos ||
1152 !msg->findSize("size", &size) || size) {
1153 mNumOutputFramesDropped += !mIsAudio;
1154 }
Lajos Molnar1cd13982014-01-17 15:12:51 -08001155 err = mCodec->releaseOutputBuffer(bufferIx);
1156 }
1157 if (err != OK) {
Wei Jiafcd87872017-07-28 15:50:04 -07001158 ALOGE("failed to release output buffer for [%s] (err=%d)",
Lajos Molnar1cd13982014-01-17 15:12:51 -08001159 mComponentName.c_str(), err);
1160 handleError(err);
1161 }
Chong Zhang66704af2015-03-03 19:32:35 -08001162 if (msg->findInt32("eos", &eos) && eos
1163 && isDiscontinuityPending()) {
1164 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1165 }
1166}
1167
1168bool NuPlayer::Decoder::isDiscontinuityPending() const {
1169 return mFormatChangePending || mTimeChangePending;
1170}
1171
1172void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1173 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1174 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1175
1176 // If we have format change, pause and wait to be killed;
1177 // If we have time change only, flush and restart fetching.
1178
1179 if (mFormatChangePending) {
1180 mPaused = true;
1181 } else if (mTimeChangePending) {
1182 if (flushOnTimeChange) {
Marco Nelissen421f47c2015-03-25 14:40:32 -07001183 doFlush(false /* notifyComplete */);
1184 signalResume(false /* notifyComplete */);
Chong Zhang66704af2015-03-03 19:32:35 -08001185 }
Chong Zhang66704af2015-03-03 19:32:35 -08001186 }
1187
1188 // Notify NuPlayer to either shutdown decoder, or rescan sources
1189 sp<AMessage> msg = mNotify->dup();
1190 msg->setInt32("what", kWhatInputDiscontinuity);
1191 msg->setInt32("formatChange", mFormatChangePending);
1192 msg->post();
1193
1194 mFormatChangePending = false;
1195 mTimeChangePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001196}
1197
Chong Zhang7137ec72014-11-12 16:41:05 -08001198bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
1199 const sp<AMessage> &targetFormat) const {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001200 if (targetFormat == NULL) {
1201 return true;
1202 }
1203
1204 AString mime;
1205 if (!targetFormat->findString("mime", &mime)) {
1206 return false;
1207 }
1208
1209 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1210 // field-by-field comparison
1211 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1212 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1213 int32_t oldVal, newVal;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001214 if (!mInputFormat->findInt32(keys[i], &oldVal) ||
Lajos Molnar1cd13982014-01-17 15:12:51 -08001215 !targetFormat->findInt32(keys[i], &newVal) ||
1216 oldVal != newVal) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001217 return false;
1218 }
1219 }
1220
1221 sp<ABuffer> oldBuf, newBuf;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001222 if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
Lajos Molnar1cd13982014-01-17 15:12:51 -08001223 targetFormat->findBuffer("csd-0", &newBuf)) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001224 if (oldBuf->size() != newBuf->size()) {
1225 return false;
1226 }
1227 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
1228 }
1229 }
1230 return false;
1231}
1232
1233bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
joakim johansson7abbd4c2015-01-30 14:16:03 +01001234 if (mInputFormat == NULL) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001235 return false;
1236 }
1237
1238 if (targetFormat == NULL) {
1239 return true;
1240 }
1241
1242 AString oldMime, newMime;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001243 if (!mInputFormat->findString("mime", &oldMime)
Robert Shih6d0a94e2014-01-23 16:18:22 -08001244 || !targetFormat->findString("mime", &newMime)
1245 || !(oldMime == newMime)) {
1246 return false;
1247 }
1248
1249 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1250 bool seamless;
1251 if (audio) {
1252 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1253 } else {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001254 int32_t isAdaptive;
1255 seamless = (mCodec != NULL &&
1256 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
1257 isAdaptive);
Robert Shih6d0a94e2014-01-23 16:18:22 -08001258 }
1259
1260 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1261 return seamless;
1262}
1263
Chong Zhang7137ec72014-11-12 16:41:05 -08001264void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1265 if (format == NULL) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001266 return;
1267 }
Chong Zhang7137ec72014-11-12 16:41:05 -08001268 mCSDsForCurrentFormat.clear();
1269 for (int32_t i = 0; ; ++i) {
1270 AString tag = "csd-";
1271 tag.append(i);
1272 sp<ABuffer> buffer;
1273 if (!format->findBuffer(tag.c_str(), &buffer)) {
1274 break;
1275 }
1276 mCSDsForCurrentFormat.push(buffer);
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001277 }
Chong Zhangb86e68f2014-08-01 13:46:53 -07001278}
1279
Chong Zhangf8d71772014-11-26 15:08:34 -08001280void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
1281 if (mResumePending) {
1282 mResumePending = false;
1283
1284 sp<AMessage> notify = mNotify->dup();
1285 notify->setInt32("what", kWhatResumeCompleted);
1286 notify->post();
1287 }
1288}
1289
Andreas Huberf9334412010-12-15 15:17:42 -08001290} // namespace android
1291