blob: 88594d202472522adb03ecdc21f2725b7fd534a7 [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);
748
Chong Zhang66704af2015-03-03 19:32:35 -0800749 if (eos) {
750 ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
751
752 buffer->meta()->setInt32("eos", true);
753 reply->setInt32("eos", true);
Wei Jiaaec8d822017-08-25 15:27:57 -0700754 }
755
Ray Essickc6e9f6e2017-12-07 16:57:36 -0800756 mNumFramesTotal += !mIsAudio;
757
Wei Jiaaec8d822017-08-25 15:27:57 -0700758 if (mSkipRenderingUntilMediaTimeUs >= 0) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800759 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
760 ALOGV("[%s] dropping buffer at time %lld as requested.",
761 mComponentName.c_str(), (long long)timeUs);
762
763 reply->post();
Wei Jiaaec8d822017-08-25 15:27:57 -0700764 if (eos) {
765 notifyResumeCompleteIfNecessary();
766 if (mRenderer != NULL && !isDiscontinuityPending()) {
767 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
768 }
769 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800770 return true;
771 }
772
773 mSkipRenderingUntilMediaTimeUs = -1;
774 }
775
Chong Zhangf8d71772014-11-26 15:08:34 -0800776 // wait until 1st frame comes out to signal resume complete
777 notifyResumeCompleteIfNecessary();
778
Chong Zhang7137ec72014-11-12 16:41:05 -0800779 if (mRenderer != NULL) {
780 // send the buffer to renderer.
781 mRenderer->queueBuffer(mIsAudio, buffer, reply);
Chong Zhang66704af2015-03-03 19:32:35 -0800782 if (eos && !isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800783 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
784 }
785 }
786
787 return true;
788}
789
Marco Nelissen421f47c2015-03-25 14:40:32 -0700790void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
791 if (!mIsAudio) {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700792 int32_t width, height;
793 if (format->findInt32("width", &width)
794 && format->findInt32("height", &height)) {
795 mStats->setInt32("width", width);
796 mStats->setInt32("height", height);
797 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700798 sp<AMessage> notify = mNotify->dup();
799 notify->setInt32("what", kWhatVideoSizeChanged);
800 notify->setMessage("format", format);
801 notify->post();
802 } else if (mRenderer != NULL) {
803 uint32_t flags;
804 int64_t durationUs;
805 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
Andy Hung288da022015-05-31 22:55:59 -0700806 if (getAudioDeepBufferSetting() // override regardless of source duration
Andy Hung71c8e5c2017-04-03 15:50:27 -0700807 || (mSource->getDuration(&durationUs) == OK
Andy Hung288da022015-05-31 22:55:59 -0700808 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700809 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
810 } else {
811 flags = AUDIO_OUTPUT_FLAG_NONE;
812 }
813
Wei Jia9a3101b2016-11-08 14:34:24 -0800814 sp<AMessage> reply = new AMessage(kWhatAudioOutputFormatChanged, this);
815 reply->setInt32("generation", mBufferGeneration);
816 mRenderer->changeAudioFormat(
Dhananjay Kumarc387f2b2015-08-06 10:43:16 +0530817 format, false /* offloadOnly */, hasVideo,
818 flags, mSource->isStreaming(), reply);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700819 }
820}
821
Chong Zhang7137ec72014-11-12 16:41:05 -0800822void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
823 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
824 if (mMediaBuffers[i] != NULL) {
825 mMediaBuffers[i]->release();
826 mMediaBuffers.editItemAt(i) = NULL;
827 }
828 }
829 mMediaBuffers.resize(mInputBuffers.size());
830 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
831 mMediaBuffers.editItemAt(i) = NULL;
832 }
833 mInputBufferIsDequeued.clear();
834 mInputBufferIsDequeued.resize(mInputBuffers.size());
835 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
836 mInputBufferIsDequeued.editItemAt(i) = false;
837 }
838
839 mPendingInputMessages.clear();
840 mDequeuedInputBuffers.clear();
841 mSkipRenderingUntilMediaTimeUs = -1;
842}
843
844void NuPlayer::Decoder::requestCodecNotification() {
Chong Zhang7137ec72014-11-12 16:41:05 -0800845 if (mCodec != NULL) {
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800846 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
Chong Zhang7137ec72014-11-12 16:41:05 -0800847 reply->setInt32("generation", mBufferGeneration);
848 mCodec->requestActivityNotification(reply);
849 }
850}
851
852bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
853 int32_t generation;
854 CHECK(msg->findInt32("generation", &generation));
855 return generation != mBufferGeneration;
856}
857
858status_t NuPlayer::Decoder::fetchInputData(sp<AMessage> &reply) {
859 sp<ABuffer> accessUnit;
Robert Shih59e9ca72016-10-20 13:51:42 -0700860 bool dropAccessUnit = true;
Chong Zhang7137ec72014-11-12 16:41:05 -0800861 do {
862 status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
863
864 if (err == -EWOULDBLOCK) {
865 return err;
866 } else if (err != OK) {
867 if (err == INFO_DISCONTINUITY) {
868 int32_t type;
869 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
870
871 bool formatChange =
872 (mIsAudio &&
873 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
874 || (!mIsAudio &&
875 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
876
877 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
878
879 ALOGI("%s discontinuity (format=%d, time=%d)",
880 mIsAudio ? "audio" : "video", formatChange, timeChange);
881
882 bool seamlessFormatChange = false;
883 sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
884 if (formatChange) {
885 seamlessFormatChange =
886 supportsSeamlessFormatChange(newFormat);
887 // treat seamless format change separately
888 formatChange = !seamlessFormatChange;
889 }
890
Chong Zhang66704af2015-03-03 19:32:35 -0800891 // For format or time change, return EOS to queue EOS input,
892 // then wait for EOS on output.
Chong Zhang7137ec72014-11-12 16:41:05 -0800893 if (formatChange /* not seamless */) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800894 mFormatChangePending = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800895 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800896 } else if (timeChange) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800897 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800898 mTimeChangePending = true;
899 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800900 } else if (seamlessFormatChange) {
901 // reuse existing decoder and don't flush
902 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800903 continue;
Chong Zhang7137ec72014-11-12 16:41:05 -0800904 } else {
905 // This stream is unaffected by the discontinuity
906 return -EWOULDBLOCK;
907 }
908 }
909
Chong Zhang66704af2015-03-03 19:32:35 -0800910 // reply should only be returned without a buffer set
911 // when there is an error (including EOS)
912 CHECK(err != OK);
913
Chong Zhang7137ec72014-11-12 16:41:05 -0800914 reply->setInt32("err", err);
Chong Zhang66704af2015-03-03 19:32:35 -0800915 return ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800916 }
917
Chong Zhang7137ec72014-11-12 16:41:05 -0800918 dropAccessUnit = false;
Hassan Shojania62dec952017-05-18 10:45:27 -0700919 if (!mIsAudio && !mIsEncrypted) {
920 // Extra safeguard if higher-level behavior changes. Otherwise, not required now.
921 // Preventing the buffer from being processed (and sent to codec) if this is a later
922 // round of playback but this time without prepareDrm. Or if there is a race between
923 // stop (which is not blocking) and releaseDrm allowing buffers being processed after
924 // Crypto has been released (GenericSource currently prevents this race though).
925 // Particularly doing this check before IsAVCReferenceFrame call to prevent parsing
926 // of encrypted data.
927 if (mIsEncryptedObservedEarlier) {
928 ALOGE("fetchInputData: mismatched mIsEncrypted/mIsEncryptedObservedEarlier (0/1)");
929
930 return INVALID_OPERATION;
931 }
932
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700933 int32_t layerId = 0;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700934 bool haveLayerId = accessUnit->meta()->findInt32("temporal-layer-id", &layerId);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700935 if (mRenderer->getVideoLateByUs() > 100000ll
936 && mIsVideoAVC
937 && !IsAVCReferenceFrame(accessUnit)) {
938 dropAccessUnit = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700939 } else if (haveLayerId && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700940 // Add only one layer each time.
941 if (layerId > mCurrentMaxVideoTemporalLayerId + 1
942 || layerId >= mNumVideoTemporalLayerAllowed) {
943 dropAccessUnit = true;
944 ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
945 layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
946 mCurrentMaxVideoTemporalLayerId);
947 } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
948 mCurrentMaxVideoTemporalLayerId = layerId;
Dongwon Kangd91dc5a2017-10-10 00:07:09 -0700949 } else if (layerId == 0 && mNumVideoTemporalLayerTotal > 1
950 && IsIDR(accessUnit->data(), accessUnit->size())) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700951 mCurrentMaxVideoTemporalLayerId = mNumVideoTemporalLayerTotal - 1;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700952 }
953 }
954 if (dropAccessUnit) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700955 if (layerId <= mCurrentMaxVideoTemporalLayerId && layerId > 0) {
956 mCurrentMaxVideoTemporalLayerId = layerId - 1;
957 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700958 ++mNumInputFramesDropped;
959 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800960 }
961 } while (dropAccessUnit);
962
963 // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
964#if 0
965 int64_t mediaTimeUs;
966 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
Chong Zhang5abbd3d2015-04-20 16:03:00 -0700967 ALOGV("[%s] feeding input buffer at media time %.3f",
Chong Zhang7137ec72014-11-12 16:41:05 -0800968 mIsAudio ? "audio" : "video",
969 mediaTimeUs / 1E6);
970#endif
971
972 if (mCCDecoder != NULL) {
973 mCCDecoder->decode(accessUnit);
974 }
975
976 reply->setBuffer("buffer", accessUnit);
977
978 return OK;
979}
980
981bool NuPlayer::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
Wei Jiafcd87872017-07-28 15:50:04 -0700982 if (mCodec == NULL) {
983 ALOGE("[%s] onInputBufferFetched without a valid codec", mComponentName.c_str());
984 handleError(NO_INIT);
985 return false;
986 }
987
Lajos Molnar1cd13982014-01-17 15:12:51 -0800988 size_t bufferIx;
989 CHECK(msg->findSize("buffer-ix", &bufferIx));
990 CHECK_LT(bufferIx, mInputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900991 sp<MediaCodecBuffer> codecBuffer = mInputBuffers[bufferIx];
Lajos Molnar1cd13982014-01-17 15:12:51 -0800992
993 sp<ABuffer> buffer;
994 bool hasBuffer = msg->findBuffer("buffer", &buffer);
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900995 bool needsCopy = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700996
Lajos Molnar1cd13982014-01-17 15:12:51 -0800997 if (buffer == NULL /* includes !hasBuffer */) {
998 int32_t streamErr = ERROR_END_OF_STREAM;
999 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
1000
Chong Zhang66704af2015-03-03 19:32:35 -08001001 CHECK(streamErr != OK);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001002
1003 // attempt to queue EOS
1004 status_t err = mCodec->queueInputBuffer(
1005 bufferIx,
1006 0,
1007 0,
1008 0,
1009 MediaCodec::BUFFER_FLAG_EOS);
Andy Hungcf31f1e2014-09-23 14:59:01 -07001010 if (err == OK) {
1011 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
1012 } else if (streamErr == ERROR_END_OF_STREAM) {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001013 streamErr = err;
1014 // err will not be ERROR_END_OF_STREAM
1015 }
1016
1017 if (streamErr != ERROR_END_OF_STREAM) {
Wei Jiafcd87872017-07-28 15:50:04 -07001018 ALOGE("Stream error for [%s] (err=%d), EOS %s queued",
Andy Hungcf31f1e2014-09-23 14:59:01 -07001019 mComponentName.c_str(),
1020 streamErr,
1021 err == OK ? "successfully" : "unsuccessfully");
Lajos Molnar1cd13982014-01-17 15:12:51 -08001022 handleError(streamErr);
1023 }
1024 } else {
Wei Jiac6cfd702014-11-11 16:33:20 -08001025 sp<AMessage> extra;
1026 if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
1027 int64_t resumeAtMediaTimeUs;
1028 if (extra->findInt64(
1029 "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
1030 ALOGI("[%s] suppressing rendering until %lld us",
1031 mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
1032 mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
1033 }
1034 }
1035
Lajos Molnar1cd13982014-01-17 15:12:51 -08001036 int64_t timeUs = 0;
1037 uint32_t flags = 0;
1038 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1039
Lajos Molnar87603c02014-08-20 19:25:30 -07001040 int32_t eos, csd;
1041 // we do not expect SYNCFRAME for decoder
Lajos Molnar1cd13982014-01-17 15:12:51 -08001042 if (buffer->meta()->findInt32("eos", &eos) && eos) {
1043 flags |= MediaCodec::BUFFER_FLAG_EOS;
Lajos Molnar87603c02014-08-20 19:25:30 -07001044 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
1045 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001046 }
1047
Hassan Shojaniacefac142017-02-06 21:02:02 -08001048 // Modular DRM
Dongwon Kang1889c3e2018-02-01 13:44:57 -08001049 MediaBufferBase *mediaBuf = NULL;
Hassan Shojaniacefac142017-02-06 21:02:02 -08001050 NuPlayerDrm::CryptoInfo *cryptInfo = NULL;
1051
Lajos Molnar1cd13982014-01-17 15:12:51 -08001052 // copy into codec buffer
Wonsik Kim7e34bf52016-08-23 00:09:18 +09001053 if (needsCopy) {
Wei Jia56097a82016-01-07 16:03:03 -08001054 if (buffer->size() > codecBuffer->capacity()) {
1055 handleError(ERROR_BUFFER_TOO_SMALL);
1056 mDequeuedInputBuffers.push_back(bufferIx);
1057 return false;
1058 }
Lajos Molnar1cd13982014-01-17 15:12:51 -08001059
Hassan Shojaniacefac142017-02-06 21:02:02 -08001060 if (buffer->data() != NULL) {
1061 codecBuffer->setRange(0, buffer->size());
1062 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
1063 } else { // No buffer->data()
1064 //Modular DRM
Dongwon Kangbc8f53b2018-01-25 17:01:44 -08001065 sp<RefBase> holder;
1066 if (buffer->meta()->findObject("mediaBufferHolder", &holder)) {
1067 mediaBuf = (holder != nullptr) ?
1068 static_cast<MediaBufferHolder*>(holder.get())->mediaBuffer() : nullptr;
1069 }
Hassan Shojaniacefac142017-02-06 21:02:02 -08001070 if (mediaBuf != NULL) {
1071 codecBuffer->setRange(0, mediaBuf->size());
1072 memcpy(codecBuffer->data(), mediaBuf->data(), mediaBuf->size());
1073
1074 sp<MetaData> meta_data = mediaBuf->meta_data();
1075 cryptInfo = NuPlayerDrm::getSampleCryptoInfo(meta_data);
Hassan Shojaniacefac142017-02-06 21:02:02 -08001076 } else { // No mediaBuf
1077 ALOGE("onInputBufferFetched: buffer->data()/mediaBuf are NULL for %p",
1078 buffer.get());
1079 handleError(UNKNOWN_ERROR);
1080 return false;
1081 }
1082 } // buffer->data()
1083 } // needsCopy
1084
1085 status_t err;
1086 AString errorDetailMsg;
1087 if (cryptInfo != NULL) {
1088 err = mCodec->queueSecureInputBuffer(
1089 bufferIx,
1090 codecBuffer->offset(),
1091 cryptInfo->subSamples,
1092 cryptInfo->numSubSamples,
1093 cryptInfo->key,
1094 cryptInfo->iv,
1095 cryptInfo->mode,
1096 cryptInfo->pattern,
1097 timeUs,
1098 flags,
1099 &errorDetailMsg);
1100 // synchronous call so done with cryptInfo here
1101 free(cryptInfo);
1102 } else {
1103 err = mCodec->queueInputBuffer(
1104 bufferIx,
1105 codecBuffer->offset(),
1106 codecBuffer->size(),
1107 timeUs,
1108 flags,
1109 &errorDetailMsg);
1110 } // no cryptInfo
1111
Lajos Molnar1cd13982014-01-17 15:12:51 -08001112 if (err != OK) {
Wei Jiafcd87872017-07-28 15:50:04 -07001113 ALOGE("onInputBufferFetched: queue%sInputBuffer failed for [%s] (err=%d, %s)",
Hassan Shojaniacefac142017-02-06 21:02:02 -08001114 (cryptInfo != NULL ? "Secure" : ""),
1115 mComponentName.c_str(), err, errorDetailMsg.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -08001116 handleError(err);
Andy Hungcf31f1e2014-09-23 14:59:01 -07001117 } else {
1118 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
Lajos Molnar09524832014-07-17 14:29:51 -07001119 }
Hassan Shojaniacefac142017-02-06 21:02:02 -08001120
1121 } // buffer != NULL
Wei Jia2245fc62014-10-02 15:12:25 -07001122 return true;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001123}
1124
Lajos Molnar1cd13982014-01-17 15:12:51 -08001125void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
1126 status_t err;
1127 int32_t render;
1128 size_t bufferIx;
Chong Zhang66704af2015-03-03 19:32:35 -08001129 int32_t eos;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001130 CHECK(msg->findSize("buffer-ix", &bufferIx));
Wei Jiac6cfd702014-11-11 16:33:20 -08001131
Chong Zhang7137ec72014-11-12 16:41:05 -08001132 if (!mIsAudio) {
Wei Jiac6cfd702014-11-11 16:33:20 -08001133 int64_t timeUs;
Wonsik Kim7e34bf52016-08-23 00:09:18 +09001134 sp<MediaCodecBuffer> buffer = mOutputBuffers[bufferIx];
Wei Jiac6cfd702014-11-11 16:33:20 -08001135 buffer->meta()->findInt64("timeUs", &timeUs);
Chong Zhang7137ec72014-11-12 16:41:05 -08001136
1137 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1138 mCCDecoder->display(timeUs);
1139 }
Wei Jiac6cfd702014-11-11 16:33:20 -08001140 }
1141
Wei Jiafcd87872017-07-28 15:50:04 -07001142 if (mCodec == NULL) {
1143 err = NO_INIT;
1144 } else if (msg->findInt32("render", &render) && render) {
Lajos Molnardc43dfa2014-05-07 15:33:04 -07001145 int64_t timestampNs;
1146 CHECK(msg->findInt64("timestampNs", &timestampNs));
1147 err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001148 } else {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -07001149 mNumOutputFramesDropped += !mIsAudio;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001150 err = mCodec->releaseOutputBuffer(bufferIx);
1151 }
1152 if (err != OK) {
Wei Jiafcd87872017-07-28 15:50:04 -07001153 ALOGE("failed to release output buffer for [%s] (err=%d)",
Lajos Molnar1cd13982014-01-17 15:12:51 -08001154 mComponentName.c_str(), err);
1155 handleError(err);
1156 }
Chong Zhang66704af2015-03-03 19:32:35 -08001157 if (msg->findInt32("eos", &eos) && eos
1158 && isDiscontinuityPending()) {
1159 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1160 }
1161}
1162
1163bool NuPlayer::Decoder::isDiscontinuityPending() const {
1164 return mFormatChangePending || mTimeChangePending;
1165}
1166
1167void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1168 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1169 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1170
1171 // If we have format change, pause and wait to be killed;
1172 // If we have time change only, flush and restart fetching.
1173
1174 if (mFormatChangePending) {
1175 mPaused = true;
1176 } else if (mTimeChangePending) {
1177 if (flushOnTimeChange) {
Marco Nelissen421f47c2015-03-25 14:40:32 -07001178 doFlush(false /* notifyComplete */);
1179 signalResume(false /* notifyComplete */);
Chong Zhang66704af2015-03-03 19:32:35 -08001180 }
Chong Zhang66704af2015-03-03 19:32:35 -08001181 }
1182
1183 // Notify NuPlayer to either shutdown decoder, or rescan sources
1184 sp<AMessage> msg = mNotify->dup();
1185 msg->setInt32("what", kWhatInputDiscontinuity);
1186 msg->setInt32("formatChange", mFormatChangePending);
1187 msg->post();
1188
1189 mFormatChangePending = false;
1190 mTimeChangePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001191}
1192
Chong Zhang7137ec72014-11-12 16:41:05 -08001193bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
1194 const sp<AMessage> &targetFormat) const {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001195 if (targetFormat == NULL) {
1196 return true;
1197 }
1198
1199 AString mime;
1200 if (!targetFormat->findString("mime", &mime)) {
1201 return false;
1202 }
1203
1204 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1205 // field-by-field comparison
1206 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1207 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1208 int32_t oldVal, newVal;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001209 if (!mInputFormat->findInt32(keys[i], &oldVal) ||
Lajos Molnar1cd13982014-01-17 15:12:51 -08001210 !targetFormat->findInt32(keys[i], &newVal) ||
1211 oldVal != newVal) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001212 return false;
1213 }
1214 }
1215
1216 sp<ABuffer> oldBuf, newBuf;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001217 if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
Lajos Molnar1cd13982014-01-17 15:12:51 -08001218 targetFormat->findBuffer("csd-0", &newBuf)) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001219 if (oldBuf->size() != newBuf->size()) {
1220 return false;
1221 }
1222 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
1223 }
1224 }
1225 return false;
1226}
1227
1228bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
joakim johansson7abbd4c2015-01-30 14:16:03 +01001229 if (mInputFormat == NULL) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001230 return false;
1231 }
1232
1233 if (targetFormat == NULL) {
1234 return true;
1235 }
1236
1237 AString oldMime, newMime;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001238 if (!mInputFormat->findString("mime", &oldMime)
Robert Shih6d0a94e2014-01-23 16:18:22 -08001239 || !targetFormat->findString("mime", &newMime)
1240 || !(oldMime == newMime)) {
1241 return false;
1242 }
1243
1244 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1245 bool seamless;
1246 if (audio) {
1247 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1248 } else {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001249 int32_t isAdaptive;
1250 seamless = (mCodec != NULL &&
1251 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
1252 isAdaptive);
Robert Shih6d0a94e2014-01-23 16:18:22 -08001253 }
1254
1255 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1256 return seamless;
1257}
1258
Chong Zhang7137ec72014-11-12 16:41:05 -08001259void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1260 if (format == NULL) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001261 return;
1262 }
Chong Zhang7137ec72014-11-12 16:41:05 -08001263 mCSDsForCurrentFormat.clear();
1264 for (int32_t i = 0; ; ++i) {
1265 AString tag = "csd-";
1266 tag.append(i);
1267 sp<ABuffer> buffer;
1268 if (!format->findBuffer(tag.c_str(), &buffer)) {
1269 break;
1270 }
1271 mCSDsForCurrentFormat.push(buffer);
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001272 }
Chong Zhangb86e68f2014-08-01 13:46:53 -07001273}
1274
Chong Zhangf8d71772014-11-26 15:08:34 -08001275void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
1276 if (mResumePending) {
1277 mResumePending = false;
1278
1279 sp<AMessage> notify = mNotify->dup();
1280 notify->setInt32("what", kWhatResumeCompleted);
1281 notify->post();
1282 }
1283}
1284
Andreas Huberf9334412010-12-15 15:17:42 -08001285} // namespace android
1286