blob: 3da5030997f9c1ab8c6b5477e37fb783d01f66d3 [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"
Wei Jiac6cfd702014-11-11 16:33:20 -080026#include "NuPlayerRenderer.h"
27#include "NuPlayerSource.h"
28
Andy Hung288da022015-05-31 22:55:59 -070029#include <cutils/properties.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080030#include <media/ICrypto.h>
Wonsik Kim7e34bf52016-08-23 00:09:18 +090031#include <media/MediaCodecBuffer.h>
Andreas Huberf9334412010-12-15 15:17:42 -080032#include <media/stagefright/foundation/ABuffer.h>
33#include <media/stagefright/foundation/ADebug.h>
Andreas Huber5bc087c2010-12-23 10:27:40 -080034#include <media/stagefright/foundation/AMessage.h>
Lajos Molnar09524832014-07-17 14:29:51 -070035#include <media/stagefright/MediaBuffer.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080036#include <media/stagefright/MediaCodec.h>
Andreas Huberf9334412010-12-15 15:17:42 -080037#include <media/stagefright/MediaDefs.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080038#include <media/stagefright/MediaErrors.h>
Andreas Huberf9334412010-12-15 15:17:42 -080039
Lajos Molnar1de1e252015-04-30 18:18:34 -070040#include <gui/Surface.h>
41
Chong Zhang7137ec72014-11-12 16:41:05 -080042#include "avc_utils.h"
43#include "ATSParser.h"
44
Andreas Huberf9334412010-12-15 15:17:42 -080045namespace android {
46
Lajos Molnar9fb81522016-07-14 07:33:43 -070047static float kDisplayRefreshingRate = 60.f; // TODO: get this from the display
Praveen Chavanbbaa1442016-04-08 13:33:49 -070048
49// The default total video frame rate of a stream when that info is not available from
50// the source.
51static float kDefaultVideoFrameRateTotal = 30.f;
52
Andy Hung288da022015-05-31 22:55:59 -070053static inline bool getAudioDeepBufferSetting() {
54 return property_get_bool("media.stagefright.audio.deep", false /* default_value */);
55}
56
Andreas Huberf9334412010-12-15 15:17:42 -080057NuPlayer::Decoder::Decoder(
Glenn Kasten11731182011-02-08 17:26:17 -080058 const sp<AMessage> &notify,
Wei Jiac6cfd702014-11-11 16:33:20 -080059 const sp<Source> &source,
Ronghua Wu68845c12015-07-21 09:50:48 -070060 pid_t pid,
Wei Jiaf2ae3e12016-10-27 17:10:59 -070061 uid_t uid,
Wei Jiac6cfd702014-11-11 16:33:20 -080062 const sp<Renderer> &renderer,
Lajos Molnar1de1e252015-04-30 18:18:34 -070063 const sp<Surface> &surface,
Chong Zhang7137ec72014-11-12 16:41:05 -080064 const sp<CCDecoder> &ccDecoder)
Andy Hung202bce12014-12-03 11:47:36 -080065 : DecoderBase(notify),
Lajos Molnar1de1e252015-04-30 18:18:34 -070066 mSurface(surface),
Wei Jiac6cfd702014-11-11 16:33:20 -080067 mSource(source),
68 mRenderer(renderer),
Chong Zhang7137ec72014-11-12 16:41:05 -080069 mCCDecoder(ccDecoder),
Ronghua Wu68845c12015-07-21 09:50:48 -070070 mPid(pid),
Wei Jiaf2ae3e12016-10-27 17:10:59 -070071 mUid(uid),
Wei Jiac6cfd702014-11-11 16:33:20 -080072 mSkipRenderingUntilMediaTimeUs(-1ll),
Chong Zhang7137ec72014-11-12 16:41:05 -080073 mNumFramesTotal(0ll),
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070074 mNumInputFramesDropped(0ll),
75 mNumOutputFramesDropped(0ll),
76 mVideoWidth(0),
77 mVideoHeight(0),
Chong Zhang7137ec72014-11-12 16:41:05 -080078 mIsAudio(true),
79 mIsVideoAVC(false),
80 mIsSecure(false),
81 mFormatChangePending(false),
Chong Zhang66704af2015-03-03 19:32:35 -080082 mTimeChangePending(false),
Praveen Chavanbbaa1442016-04-08 13:33:49 -070083 mFrameRateTotal(kDefaultVideoFrameRateTotal),
84 mPlaybackSpeed(1.0f),
Lajos Molnar9fb81522016-07-14 07:33:43 -070085 mNumVideoTemporalLayerTotal(1), // decode all layers
Praveen Chavanbbaa1442016-04-08 13:33:49 -070086 mNumVideoTemporalLayerAllowed(1),
87 mCurrentMaxVideoTemporalLayerId(0),
Chong Zhangf8d71772014-11-26 15:08:34 -080088 mResumePending(false),
Lajos Molnar1cd13982014-01-17 15:12:51 -080089 mComponentName("decoder") {
Lajos Molnar1cd13982014-01-17 15:12:51 -080090 mCodecLooper = new ALooper;
Marco Nelissen9e2b7912014-08-18 16:13:03 -070091 mCodecLooper->setName("NPDecoder-CL");
Lajos Molnar1cd13982014-01-17 15:12:51 -080092 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
Praveen Chavanbbaa1442016-04-08 13:33:49 -070093 mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
Andreas Huberf9334412010-12-15 15:17:42 -080094}
95
96NuPlayer::Decoder::~Decoder() {
Ronghua Wufaeb0f22015-05-21 12:20:21 -070097 mCodec->release();
Wei Jia4923cee2014-09-24 14:25:19 -070098 releaseAndResetMediaBuffers();
Andreas Huberf9334412010-12-15 15:17:42 -080099}
100
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700101sp<AMessage> NuPlayer::Decoder::getStats() const {
102 mStats->setInt64("frames-total", mNumFramesTotal);
103 mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
104 mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
105 return mStats;
Lajos Molnar09524832014-07-17 14:29:51 -0700106}
107
Lajos Molnara81c6222015-07-10 19:17:45 -0700108status_t NuPlayer::Decoder::setVideoSurface(const sp<Surface> &surface) {
109 if (surface == NULL || ADebug::isExperimentEnabled("legacy-setsurface")) {
110 return BAD_VALUE;
111 }
112
113 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
114
115 msg->setObject("surface", surface);
116 sp<AMessage> response;
117 status_t err = msg->postAndAwaitResponse(&response);
118 if (err == OK && response != NULL) {
119 CHECK(response->findInt32("err", &err));
120 }
121 return err;
122}
123
Chong Zhang7137ec72014-11-12 16:41:05 -0800124void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
125 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
126
127 switch (msg->what()) {
128 case kWhatCodecNotify:
129 {
Chong Zhang3b032b32015-04-17 15:49:06 -0700130 int32_t cbID;
131 CHECK(msg->findInt32("callbackID", &cbID));
132
133 ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
134 mIsAudio ? "audio" : "video", cbID, mPaused);
135
Marco Nelissen421f47c2015-03-25 14:40:32 -0700136 if (mPaused) {
137 break;
Chong Zhang7137ec72014-11-12 16:41:05 -0800138 }
139
Marco Nelissen421f47c2015-03-25 14:40:32 -0700140 switch (cbID) {
141 case MediaCodec::CB_INPUT_AVAILABLE:
142 {
143 int32_t index;
144 CHECK(msg->findInt32("index", &index));
145
146 handleAnInputBuffer(index);
147 break;
148 }
149
150 case MediaCodec::CB_OUTPUT_AVAILABLE:
151 {
152 int32_t index;
153 size_t offset;
154 size_t size;
155 int64_t timeUs;
156 int32_t flags;
157
158 CHECK(msg->findInt32("index", &index));
159 CHECK(msg->findSize("offset", &offset));
160 CHECK(msg->findSize("size", &size));
161 CHECK(msg->findInt64("timeUs", &timeUs));
162 CHECK(msg->findInt32("flags", &flags));
163
164 handleAnOutputBuffer(index, offset, size, timeUs, flags);
165 break;
166 }
167
168 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED:
169 {
170 sp<AMessage> format;
171 CHECK(msg->findMessage("format", &format));
172
173 handleOutputFormatChange(format);
174 break;
175 }
176
177 case MediaCodec::CB_ERROR:
178 {
179 status_t err;
180 CHECK(msg->findInt32("err", &err));
181 ALOGE("Decoder (%s) reported error : 0x%x",
182 mIsAudio ? "audio" : "video", err);
183
184 handleError(err);
185 break;
186 }
187
188 default:
189 {
190 TRESPASS();
191 break;
192 }
193 }
194
Lajos Molnar87603c02014-08-20 19:25:30 -0700195 break;
196 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800197
198 case kWhatRenderBuffer:
199 {
200 if (!isStaleReply(msg)) {
201 onRenderBuffer(msg);
202 }
203 break;
204 }
205
Wei Jia9a3101b2016-11-08 14:34:24 -0800206 case kWhatAudioOutputFormatChanged:
207 {
208 if (!isStaleReply(msg)) {
209 status_t err;
210 if (msg->findInt32("err", &err) && err != OK) {
211 ALOGE("Renderer reported 0x%x when changing audio output format", err);
212 handleError(err);
213 }
214 }
215 break;
216 }
217
Lajos Molnara81c6222015-07-10 19:17:45 -0700218 case kWhatSetVideoSurface:
219 {
220 sp<AReplyToken> replyID;
221 CHECK(msg->senderAwaitsResponse(&replyID));
222
223 sp<RefBase> obj;
224 CHECK(msg->findObject("surface", &obj));
225 sp<Surface> surface = static_cast<Surface *>(obj.get()); // non-null
226 int32_t err = INVALID_OPERATION;
227 // NOTE: in practice mSurface is always non-null, but checking here for completeness
228 if (mCodec != NULL && mSurface != NULL) {
229 // TODO: once AwesomePlayer is removed, remove this automatic connecting
230 // to the surface by MediaPlayerService.
231 //
232 // at this point MediaPlayerService::client has already connected to the
233 // surface, which MediaCodec does not expect
234 err = native_window_api_disconnect(surface.get(), NATIVE_WINDOW_API_MEDIA);
235 if (err == OK) {
236 err = mCodec->setSurface(surface);
237 ALOGI_IF(err, "codec setSurface returned: %d", err);
238 if (err == OK) {
239 // reconnect to the old surface as MPS::Client will expect to
240 // be able to disconnect from it.
241 (void)native_window_api_connect(mSurface.get(), NATIVE_WINDOW_API_MEDIA);
242 mSurface = surface;
243 }
244 }
245 if (err != OK) {
246 // reconnect to the new surface on error as MPS::Client will expect to
247 // be able to disconnect from it.
248 (void)native_window_api_connect(surface.get(), NATIVE_WINDOW_API_MEDIA);
249 }
250 }
251
252 sp<AMessage> response = new AMessage;
253 response->setInt32("err", err);
254 response->postReply(replyID);
255 break;
256 }
257
Chong Zhang7137ec72014-11-12 16:41:05 -0800258 default:
259 DecoderBase::onMessageReceived(msg);
260 break;
Lajos Molnar87603c02014-08-20 19:25:30 -0700261 }
262}
263
Lajos Molnar1cd13982014-01-17 15:12:51 -0800264void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
Andreas Huberf9334412010-12-15 15:17:42 -0800265 CHECK(mCodec == NULL);
Andreas Huberf9334412010-12-15 15:17:42 -0800266
Chong Zhang7137ec72014-11-12 16:41:05 -0800267 mFormatChangePending = false;
Chong Zhang66704af2015-03-03 19:32:35 -0800268 mTimeChangePending = false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800269
Lajos Molnar1cd13982014-01-17 15:12:51 -0800270 ++mBufferGeneration;
271
Andreas Huber84066782011-08-16 09:34:26 -0700272 AString mime;
273 CHECK(format->findString("mime", &mime));
Andreas Huberf9334412010-12-15 15:17:42 -0800274
Chong Zhang7137ec72014-11-12 16:41:05 -0800275 mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
276 mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
277
Lajos Molnar1cd13982014-01-17 15:12:51 -0800278 mComponentName = mime;
279 mComponentName.append(" decoder");
Lajos Molnar1de1e252015-04-30 18:18:34 -0700280 ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), mSurface.get());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800281
Ronghua Wu68845c12015-07-21 09:50:48 -0700282 mCodec = MediaCodec::CreateByType(
Wei Jiaf2ae3e12016-10-27 17:10:59 -0700283 mCodecLooper, mime.c_str(), false /* encoder */, NULL /* err */, mPid, mUid);
Lajos Molnar09524832014-07-17 14:29:51 -0700284 int32_t secure = 0;
285 if (format->findInt32("secure", &secure) && secure != 0) {
286 if (mCodec != NULL) {
287 mCodec->getName(&mComponentName);
288 mComponentName.append(".secure");
289 mCodec->release();
290 ALOGI("[%s] creating", mComponentName.c_str());
291 mCodec = MediaCodec::CreateByComponentName(
Wei Jiaf2ae3e12016-10-27 17:10:59 -0700292 mCodecLooper, mComponentName.c_str(), NULL /* err */, mPid, mUid);
Lajos Molnar09524832014-07-17 14:29:51 -0700293 }
294 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800295 if (mCodec == NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700296 ALOGE("Failed to create %s%s decoder",
297 (secure ? "secure " : ""), mime.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800298 handleError(UNKNOWN_ERROR);
299 return;
300 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800301 mIsSecure = secure;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800302
303 mCodec->getName(&mComponentName);
304
Lajos Molnar14986f62014-09-15 11:04:44 -0700305 status_t err;
Lajos Molnar1de1e252015-04-30 18:18:34 -0700306 if (mSurface != NULL) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800307 // disconnect from surface as MediaCodec will reconnect
Lajos Molnar14986f62014-09-15 11:04:44 -0700308 err = native_window_api_disconnect(
Lajos Molnar1de1e252015-04-30 18:18:34 -0700309 mSurface.get(), NATIVE_WINDOW_API_MEDIA);
Lajos Molnar14986f62014-09-15 11:04:44 -0700310 // We treat this as a warning, as this is a preparatory step.
311 // Codec will try to connect to the surface, which is where
312 // any error signaling will occur.
313 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800314 }
Lajos Molnar14986f62014-09-15 11:04:44 -0700315 err = mCodec->configure(
Lajos Molnar1de1e252015-04-30 18:18:34 -0700316 format, mSurface, NULL /* crypto */, 0 /* flags */);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800317 if (err != OK) {
318 ALOGE("Failed to configure %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700319 mCodec->release();
320 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800321 handleError(err);
322 return;
323 }
Lajos Molnar87603c02014-08-20 19:25:30 -0700324 rememberCodecSpecificData(format);
325
Lajos Molnar1cd13982014-01-17 15:12:51 -0800326 // the following should work in configured state
327 CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
328 CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
329
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700330 mStats->setString("mime", mime.c_str());
331 mStats->setString("component-name", mComponentName.c_str());
332
333 if (!mIsAudio) {
334 int32_t width, height;
335 if (mOutputFormat->findInt32("width", &width)
336 && mOutputFormat->findInt32("height", &height)) {
337 mStats->setInt32("width", width);
338 mStats->setInt32("height", height);
339 }
340 }
341
Marco Nelissen421f47c2015-03-25 14:40:32 -0700342 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
343 mCodec->setCallback(reply);
344
Lajos Molnar1cd13982014-01-17 15:12:51 -0800345 err = mCodec->start();
346 if (err != OK) {
347 ALOGE("Failed to start %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;
Andreas Huberf9334412010-12-15 15:17:42 -0800352 }
353
Lajos Molnar09524832014-07-17 14:29:51 -0700354 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700355
Wei Jia704e7262014-06-04 16:21:56 -0700356 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800357 mResumePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800358}
Andreas Huber078cfcf2011-09-15 12:25:04 -0700359
Ronghua Wu8db88132015-04-22 13:51:35 -0700360void NuPlayer::Decoder::onSetParameters(const sp<AMessage> &params) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700361 bool needAdjustLayers = false;
362 float frameRateTotal;
363 if (params->findFloat("frame-rate-total", &frameRateTotal)
364 && mFrameRateTotal != frameRateTotal) {
365 needAdjustLayers = true;
366 mFrameRateTotal = frameRateTotal;
Ronghua Wu8db88132015-04-22 13:51:35 -0700367 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700368
369 int32_t numVideoTemporalLayerTotal;
370 if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
Lajos Molnar9fb81522016-07-14 07:33:43 -0700371 && numVideoTemporalLayerTotal >= 0
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700372 && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
373 && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
374 needAdjustLayers = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700375 mNumVideoTemporalLayerTotal = std::max(numVideoTemporalLayerTotal, 1);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700376 }
377
Lajos Molnar9fb81522016-07-14 07:33:43 -0700378 if (needAdjustLayers && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700379 // TODO: For now, layer fps is calculated for some specific architectures.
380 // But it really should be extracted from the stream.
381 mVideoTemporalLayerAggregateFps[0] =
382 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - 1));
383 for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
384 mVideoTemporalLayerAggregateFps[i] =
385 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - i))
386 + mVideoTemporalLayerAggregateFps[i - 1];
387 }
388 }
389
390 float playbackSpeed;
391 if (params->findFloat("playback-speed", &playbackSpeed)
392 && mPlaybackSpeed != playbackSpeed) {
393 needAdjustLayers = true;
394 mPlaybackSpeed = playbackSpeed;
395 }
396
397 if (needAdjustLayers) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700398 float decodeFrameRate = mFrameRateTotal;
399 // enable temporal layering optimization only if we know the layering depth
400 if (mNumVideoTemporalLayerTotal > 1) {
401 int32_t layerId;
402 for (layerId = 0; layerId < mNumVideoTemporalLayerTotal - 1; ++layerId) {
403 if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
404 >= kDisplayRefreshingRate * 0.9) {
405 break;
406 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700407 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700408 mNumVideoTemporalLayerAllowed = layerId + 1;
409 decodeFrameRate = mVideoTemporalLayerAggregateFps[layerId];
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700410 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700411 ALOGV("onSetParameters: allowed layers=%d, decodeFps=%g",
412 mNumVideoTemporalLayerAllowed, decodeFrameRate);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700413
414 if (mCodec == NULL) {
415 ALOGW("onSetParameters called before codec is created.");
416 return;
417 }
418
419 sp<AMessage> codecParams = new AMessage();
Lajos Molnar9fb81522016-07-14 07:33:43 -0700420 codecParams->setFloat("operating-rate", decodeFrameRate * mPlaybackSpeed);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700421 mCodec->setParameters(codecParams);
422 }
Ronghua Wu8db88132015-04-22 13:51:35 -0700423}
424
Chong Zhang7137ec72014-11-12 16:41:05 -0800425void NuPlayer::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
426 bool hadNoRenderer = (mRenderer == NULL);
427 mRenderer = renderer;
428 if (hadNoRenderer && mRenderer != NULL) {
Lajos Molnare6109e22015-04-10 17:18:22 -0700429 // this means that the widevine legacy source is ready
430 onRequestInputBuffers();
Chong Zhang7137ec72014-11-12 16:41:05 -0800431 }
432}
433
434void NuPlayer::Decoder::onGetInputBuffers(
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900435 Vector<sp<MediaCodecBuffer> > *dstBuffers) {
Lajos Molnare6109e22015-04-10 17:18:22 -0700436 CHECK_EQ((status_t)OK, mCodec->getWidevineLegacyBuffers(dstBuffers));
Chong Zhang7137ec72014-11-12 16:41:05 -0800437}
438
Chong Zhangf8d71772014-11-26 15:08:34 -0800439void NuPlayer::Decoder::onResume(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800440 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800441
442 if (notifyComplete) {
443 mResumePending = true;
444 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700445 mCodec->start();
Chong Zhang7137ec72014-11-12 16:41:05 -0800446}
447
Chong Zhang66704af2015-03-03 19:32:35 -0800448void NuPlayer::Decoder::doFlush(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800449 if (mCCDecoder != NULL) {
450 mCCDecoder->flush();
451 }
452
453 if (mRenderer != NULL) {
454 mRenderer->flush(mIsAudio, notifyComplete);
455 mRenderer->signalTimeDiscontinuity();
456 }
457
458 status_t err = OK;
459 if (mCodec != NULL) {
460 err = mCodec->flush();
461 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
462 ++mBufferGeneration;
463 }
464
465 if (err != OK) {
466 ALOGE("failed to flush %s (err=%d)", mComponentName.c_str(), err);
467 handleError(err);
468 // finish with posting kWhatFlushCompleted.
469 // we attempt to release the buffers even if flush fails.
470 }
471 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700472 mPaused = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800473}
Chong Zhang7137ec72014-11-12 16:41:05 -0800474
Marco Nelissen421f47c2015-03-25 14:40:32 -0700475
Chong Zhang66704af2015-03-03 19:32:35 -0800476void NuPlayer::Decoder::onFlush() {
477 doFlush(true);
478
479 if (isDiscontinuityPending()) {
480 // This could happen if the client starts seeking/shutdown
481 // after we queued an EOS for discontinuities.
482 // We can consider discontinuity handled.
483 finishHandleDiscontinuity(false /* flushOnTimeChange */);
Chong Zhang7137ec72014-11-12 16:41:05 -0800484 }
Chong Zhang66704af2015-03-03 19:32:35 -0800485
486 sp<AMessage> notify = mNotify->dup();
487 notify->setInt32("what", kWhatFlushCompleted);
488 notify->post();
Chong Zhang7137ec72014-11-12 16:41:05 -0800489}
490
491void NuPlayer::Decoder::onShutdown(bool notifyComplete) {
492 status_t err = OK;
Chong Zhangf8d71772014-11-26 15:08:34 -0800493
494 // if there is a pending resume request, notify complete now
495 notifyResumeCompleteIfNecessary();
496
Chong Zhang7137ec72014-11-12 16:41:05 -0800497 if (mCodec != NULL) {
498 err = mCodec->release();
499 mCodec = NULL;
500 ++mBufferGeneration;
501
Lajos Molnar1de1e252015-04-30 18:18:34 -0700502 if (mSurface != NULL) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800503 // reconnect to surface as MediaCodec disconnected from it
504 status_t error =
Lajos Molnar1de1e252015-04-30 18:18:34 -0700505 native_window_api_connect(mSurface.get(), NATIVE_WINDOW_API_MEDIA);
Chong Zhang7137ec72014-11-12 16:41:05 -0800506 ALOGW_IF(error != NO_ERROR,
507 "[%s] failed to connect to native window, error=%d",
508 mComponentName.c_str(), error);
509 }
510 mComponentName = "decoder";
511 }
512
513 releaseAndResetMediaBuffers();
514
515 if (err != OK) {
516 ALOGE("failed to release %s (err=%d)", mComponentName.c_str(), err);
517 handleError(err);
518 // finish with posting kWhatShutdownCompleted.
519 }
520
521 if (notifyComplete) {
522 sp<AMessage> notify = mNotify->dup();
523 notify->setInt32("what", kWhatShutdownCompleted);
524 notify->post();
525 mPaused = true;
526 }
527}
528
Chong Zhang3b032b32015-04-17 15:49:06 -0700529/*
530 * returns true if we should request more data
531 */
532bool NuPlayer::Decoder::doRequestBuffers() {
Lajos Molnare6109e22015-04-10 17:18:22 -0700533 // mRenderer is only NULL if we have a legacy widevine source that
534 // is not yet ready. In this case we must not fetch input.
535 if (isDiscontinuityPending() || mRenderer == NULL) {
Chong Zhang3b032b32015-04-17 15:49:06 -0700536 return false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800537 }
538 status_t err = OK;
Chong Zhang66704af2015-03-03 19:32:35 -0800539 while (err == OK && !mDequeuedInputBuffers.empty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800540 size_t bufferIx = *mDequeuedInputBuffers.begin();
541 sp<AMessage> msg = new AMessage();
542 msg->setSize("buffer-ix", bufferIx);
543 err = fetchInputData(msg);
Chong Zhang66704af2015-03-03 19:32:35 -0800544 if (err != OK && err != ERROR_END_OF_STREAM) {
545 // if EOS, need to queue EOS buffer
Chong Zhang7137ec72014-11-12 16:41:05 -0800546 break;
547 }
548 mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
549
550 if (!mPendingInputMessages.empty()
551 || !onInputBufferFetched(msg)) {
552 mPendingInputMessages.push_back(msg);
Lajos Molnar09524832014-07-17 14:29:51 -0700553 }
554 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800555
Chong Zhang3b032b32015-04-17 15:49:06 -0700556 return err == -EWOULDBLOCK
557 && mSource->feedMoreTSData() == OK;
Lajos Molnar09524832014-07-17 14:29:51 -0700558}
559
Marco Nelissen421f47c2015-03-25 14:40:32 -0700560void NuPlayer::Decoder::handleError(int32_t err)
561{
562 // We cannot immediately release the codec due to buffers still outstanding
563 // in the renderer. We signal to the player the error so it can shutdown/release the
564 // decoder after flushing and increment the generation to discard unnecessary messages.
565
566 ++mBufferGeneration;
567
568 sp<AMessage> notify = mNotify->dup();
569 notify->setInt32("what", kWhatError);
570 notify->setInt32("err", err);
571 notify->post();
572}
573
574bool NuPlayer::Decoder::handleAnInputBuffer(size_t index) {
Chong Zhang66704af2015-03-03 19:32:35 -0800575 if (isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800576 return false;
577 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700578
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900579 sp<MediaCodecBuffer> buffer;
Marco Nelissen421f47c2015-03-25 14:40:32 -0700580 mCodec->getInputBuffer(index, &buffer);
581
Wei Jia6301a5e2015-05-13 13:15:18 -0700582 if (buffer == NULL) {
583 handleError(UNKNOWN_ERROR);
584 return false;
585 }
586
Marco Nelissen421f47c2015-03-25 14:40:32 -0700587 if (index >= mInputBuffers.size()) {
588 for (size_t i = mInputBuffers.size(); i <= index; ++i) {
589 mInputBuffers.add();
590 mMediaBuffers.add();
591 mInputBufferIsDequeued.add();
592 mMediaBuffers.editItemAt(i) = NULL;
593 mInputBufferIsDequeued.editItemAt(i) = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800594 }
Andreas Huber078cfcf2011-09-15 12:25:04 -0700595 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700596 mInputBuffers.editItemAt(index) = buffer;
Andreas Huber078cfcf2011-09-15 12:25:04 -0700597
Marco Nelissen421f47c2015-03-25 14:40:32 -0700598 //CHECK_LT(bufferIx, mInputBuffers.size());
Andreas Huberf9334412010-12-15 15:17:42 -0800599
Marco Nelissen421f47c2015-03-25 14:40:32 -0700600 if (mMediaBuffers[index] != NULL) {
601 mMediaBuffers[index]->release();
602 mMediaBuffers.editItemAt(index) = NULL;
Lajos Molnar09524832014-07-17 14:29:51 -0700603 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700604 mInputBufferIsDequeued.editItemAt(index) = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700605
Lajos Molnar87603c02014-08-20 19:25:30 -0700606 if (!mCSDsToSubmit.isEmpty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800607 sp<AMessage> msg = new AMessage();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700608 msg->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800609
Lajos Molnar87603c02014-08-20 19:25:30 -0700610 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
611 ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
Chong Zhang7137ec72014-11-12 16:41:05 -0800612 msg->setBuffer("buffer", buffer);
Lajos Molnar87603c02014-08-20 19:25:30 -0700613 mCSDsToSubmit.removeAt(0);
Wei Jia56097a82016-01-07 16:03:03 -0800614 if (!onInputBufferFetched(msg)) {
615 handleError(UNKNOWN_ERROR);
616 return false;
617 }
Wei Jia2245fc62014-10-02 15:12:25 -0700618 return true;
619 }
620
621 while (!mPendingInputMessages.empty()) {
622 sp<AMessage> msg = *mPendingInputMessages.begin();
Chong Zhang7137ec72014-11-12 16:41:05 -0800623 if (!onInputBufferFetched(msg)) {
Wei Jia2245fc62014-10-02 15:12:25 -0700624 break;
625 }
626 mPendingInputMessages.erase(mPendingInputMessages.begin());
627 }
628
Marco Nelissen421f47c2015-03-25 14:40:32 -0700629 if (!mInputBufferIsDequeued.editItemAt(index)) {
Lajos Molnar87603c02014-08-20 19:25:30 -0700630 return true;
631 }
632
Marco Nelissen421f47c2015-03-25 14:40:32 -0700633 mDequeuedInputBuffers.push_back(index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800634
635 onRequestInputBuffers();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800636 return true;
637}
638
Marco Nelissen421f47c2015-03-25 14:40:32 -0700639bool NuPlayer::Decoder::handleAnOutputBuffer(
640 size_t index,
641 size_t offset,
642 size_t size,
643 int64_t timeUs,
644 int32_t flags) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700645// CHECK_LT(bufferIx, mOutputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900646 sp<MediaCodecBuffer> buffer;
Marco Nelissen421f47c2015-03-25 14:40:32 -0700647 mCodec->getOutputBuffer(index, &buffer);
648
649 if (index >= mOutputBuffers.size()) {
650 for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
651 mOutputBuffers.add();
652 }
653 }
654
655 mOutputBuffers.editItemAt(index) = buffer;
656
Chong Zhang7137ec72014-11-12 16:41:05 -0800657 buffer->setRange(offset, size);
658 buffer->meta()->clear();
659 buffer->meta()->setInt64("timeUs", timeUs);
Chong Zhang66704af2015-03-03 19:32:35 -0800660
661 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
Chong Zhang7137ec72014-11-12 16:41:05 -0800662 // we do not expect CODECCONFIG or SYNCFRAME for decoder
663
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800664 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700665 reply->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800666 reply->setInt32("generation", mBufferGeneration);
667
Chong Zhang66704af2015-03-03 19:32:35 -0800668 if (eos) {
669 ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
670
671 buffer->meta()->setInt32("eos", true);
672 reply->setInt32("eos", true);
673 } else if (mSkipRenderingUntilMediaTimeUs >= 0) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800674 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
675 ALOGV("[%s] dropping buffer at time %lld as requested.",
676 mComponentName.c_str(), (long long)timeUs);
677
678 reply->post();
679 return true;
680 }
681
682 mSkipRenderingUntilMediaTimeUs = -1;
683 }
684
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700685 mNumFramesTotal += !mIsAudio;
686
Chong Zhangf8d71772014-11-26 15:08:34 -0800687 // wait until 1st frame comes out to signal resume complete
688 notifyResumeCompleteIfNecessary();
689
Chong Zhang7137ec72014-11-12 16:41:05 -0800690 if (mRenderer != NULL) {
691 // send the buffer to renderer.
692 mRenderer->queueBuffer(mIsAudio, buffer, reply);
Chong Zhang66704af2015-03-03 19:32:35 -0800693 if (eos && !isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800694 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
695 }
696 }
697
698 return true;
699}
700
Marco Nelissen421f47c2015-03-25 14:40:32 -0700701void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
702 if (!mIsAudio) {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700703 int32_t width, height;
704 if (format->findInt32("width", &width)
705 && format->findInt32("height", &height)) {
706 mStats->setInt32("width", width);
707 mStats->setInt32("height", height);
708 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700709 sp<AMessage> notify = mNotify->dup();
710 notify->setInt32("what", kWhatVideoSizeChanged);
711 notify->setMessage("format", format);
712 notify->post();
713 } else if (mRenderer != NULL) {
714 uint32_t flags;
715 int64_t durationUs;
716 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
Andy Hung288da022015-05-31 22:55:59 -0700717 if (getAudioDeepBufferSetting() // override regardless of source duration
718 || (!hasVideo
719 && mSource->getDuration(&durationUs) == OK
720 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700721 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
722 } else {
723 flags = AUDIO_OUTPUT_FLAG_NONE;
724 }
725
Wei Jia9a3101b2016-11-08 14:34:24 -0800726 sp<AMessage> reply = new AMessage(kWhatAudioOutputFormatChanged, this);
727 reply->setInt32("generation", mBufferGeneration);
728 mRenderer->changeAudioFormat(
729 format, false /* offloadOnly */, hasVideo, flags, reply);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700730 }
731}
732
Chong Zhang7137ec72014-11-12 16:41:05 -0800733void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
734 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
735 if (mMediaBuffers[i] != NULL) {
736 mMediaBuffers[i]->release();
737 mMediaBuffers.editItemAt(i) = NULL;
738 }
739 }
740 mMediaBuffers.resize(mInputBuffers.size());
741 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
742 mMediaBuffers.editItemAt(i) = NULL;
743 }
744 mInputBufferIsDequeued.clear();
745 mInputBufferIsDequeued.resize(mInputBuffers.size());
746 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
747 mInputBufferIsDequeued.editItemAt(i) = false;
748 }
749
750 mPendingInputMessages.clear();
751 mDequeuedInputBuffers.clear();
752 mSkipRenderingUntilMediaTimeUs = -1;
753}
754
755void NuPlayer::Decoder::requestCodecNotification() {
Chong Zhang7137ec72014-11-12 16:41:05 -0800756 if (mCodec != NULL) {
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800757 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
Chong Zhang7137ec72014-11-12 16:41:05 -0800758 reply->setInt32("generation", mBufferGeneration);
759 mCodec->requestActivityNotification(reply);
760 }
761}
762
763bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
764 int32_t generation;
765 CHECK(msg->findInt32("generation", &generation));
766 return generation != mBufferGeneration;
767}
768
769status_t NuPlayer::Decoder::fetchInputData(sp<AMessage> &reply) {
770 sp<ABuffer> accessUnit;
Robert Shih59e9ca72016-10-20 13:51:42 -0700771 bool dropAccessUnit = true;
Chong Zhang7137ec72014-11-12 16:41:05 -0800772 do {
773 status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
774
775 if (err == -EWOULDBLOCK) {
776 return err;
777 } else if (err != OK) {
778 if (err == INFO_DISCONTINUITY) {
779 int32_t type;
780 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
781
782 bool formatChange =
783 (mIsAudio &&
784 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
785 || (!mIsAudio &&
786 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
787
788 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
789
790 ALOGI("%s discontinuity (format=%d, time=%d)",
791 mIsAudio ? "audio" : "video", formatChange, timeChange);
792
793 bool seamlessFormatChange = false;
794 sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
795 if (formatChange) {
796 seamlessFormatChange =
797 supportsSeamlessFormatChange(newFormat);
798 // treat seamless format change separately
799 formatChange = !seamlessFormatChange;
800 }
801
Chong Zhang66704af2015-03-03 19:32:35 -0800802 // For format or time change, return EOS to queue EOS input,
803 // then wait for EOS on output.
Chong Zhang7137ec72014-11-12 16:41:05 -0800804 if (formatChange /* not seamless */) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800805 mFormatChangePending = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800806 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800807 } else if (timeChange) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800808 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800809 mTimeChangePending = true;
810 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800811 } else if (seamlessFormatChange) {
812 // reuse existing decoder and don't flush
813 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800814 continue;
Chong Zhang7137ec72014-11-12 16:41:05 -0800815 } else {
816 // This stream is unaffected by the discontinuity
817 return -EWOULDBLOCK;
818 }
819 }
820
Chong Zhang66704af2015-03-03 19:32:35 -0800821 // reply should only be returned without a buffer set
822 // when there is an error (including EOS)
823 CHECK(err != OK);
824
Chong Zhang7137ec72014-11-12 16:41:05 -0800825 reply->setInt32("err", err);
Chong Zhang66704af2015-03-03 19:32:35 -0800826 return ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800827 }
828
Chong Zhang7137ec72014-11-12 16:41:05 -0800829 dropAccessUnit = false;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700830 if (!mIsAudio && !mIsSecure) {
831 int32_t layerId = 0;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700832 bool haveLayerId = accessUnit->meta()->findInt32("temporal-layer-id", &layerId);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700833 if (mRenderer->getVideoLateByUs() > 100000ll
834 && mIsVideoAVC
835 && !IsAVCReferenceFrame(accessUnit)) {
836 dropAccessUnit = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700837 } else if (haveLayerId && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700838 // Add only one layer each time.
839 if (layerId > mCurrentMaxVideoTemporalLayerId + 1
840 || layerId >= mNumVideoTemporalLayerAllowed) {
841 dropAccessUnit = true;
842 ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
843 layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
844 mCurrentMaxVideoTemporalLayerId);
845 } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
846 mCurrentMaxVideoTemporalLayerId = layerId;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700847 } else if (layerId == 0 && mNumVideoTemporalLayerTotal > 1 && IsIDR(accessUnit)) {
848 mCurrentMaxVideoTemporalLayerId = mNumVideoTemporalLayerTotal - 1;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700849 }
850 }
851 if (dropAccessUnit) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700852 if (layerId <= mCurrentMaxVideoTemporalLayerId && layerId > 0) {
853 mCurrentMaxVideoTemporalLayerId = layerId - 1;
854 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700855 ++mNumInputFramesDropped;
856 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800857 }
858 } while (dropAccessUnit);
859
860 // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
861#if 0
862 int64_t mediaTimeUs;
863 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
Chong Zhang5abbd3d2015-04-20 16:03:00 -0700864 ALOGV("[%s] feeding input buffer at media time %.3f",
Chong Zhang7137ec72014-11-12 16:41:05 -0800865 mIsAudio ? "audio" : "video",
866 mediaTimeUs / 1E6);
867#endif
868
869 if (mCCDecoder != NULL) {
870 mCCDecoder->decode(accessUnit);
871 }
872
873 reply->setBuffer("buffer", accessUnit);
874
875 return OK;
876}
877
878bool NuPlayer::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800879 size_t bufferIx;
880 CHECK(msg->findSize("buffer-ix", &bufferIx));
881 CHECK_LT(bufferIx, mInputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900882 sp<MediaCodecBuffer> codecBuffer = mInputBuffers[bufferIx];
Lajos Molnar1cd13982014-01-17 15:12:51 -0800883
884 sp<ABuffer> buffer;
885 bool hasBuffer = msg->findBuffer("buffer", &buffer);
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900886 bool needsCopy = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700887
888 // handle widevine classic source - that fills an arbitrary input buffer
889 MediaBuffer *mediaBuffer = NULL;
Wei Jia96e92b52014-09-18 17:36:20 -0700890 if (hasBuffer) {
891 mediaBuffer = (MediaBuffer *)(buffer->getMediaBufferBase());
892 if (mediaBuffer != NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700893 // likely filled another buffer than we requested: adjust buffer index
894 size_t ix;
895 for (ix = 0; ix < mInputBuffers.size(); ix++) {
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900896 const sp<MediaCodecBuffer> &buf = mInputBuffers[ix];
Lajos Molnar09524832014-07-17 14:29:51 -0700897 if (buf->data() == mediaBuffer->data()) {
898 // all input buffers are dequeued on start, hence the check
Wei Jia2245fc62014-10-02 15:12:25 -0700899 if (!mInputBufferIsDequeued[ix]) {
900 ALOGV("[%s] received MediaBuffer for #%zu instead of #%zu",
901 mComponentName.c_str(), ix, bufferIx);
902 mediaBuffer->release();
903 return false;
904 }
Lajos Molnar09524832014-07-17 14:29:51 -0700905
906 // TRICKY: need buffer for the metadata, so instead, set
907 // codecBuffer to the same (though incorrect) buffer to
908 // avoid a memcpy into the codecBuffer
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900909 codecBuffer = new MediaCodecBuffer(codecBuffer->format(), buffer);
Lajos Molnar09524832014-07-17 14:29:51 -0700910 codecBuffer->setRange(
911 mediaBuffer->range_offset(),
912 mediaBuffer->range_length());
913 bufferIx = ix;
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900914 needsCopy = false;
Lajos Molnar09524832014-07-17 14:29:51 -0700915 break;
916 }
917 }
918 CHECK(ix < mInputBuffers.size());
919 }
920 }
921
Lajos Molnar1cd13982014-01-17 15:12:51 -0800922 if (buffer == NULL /* includes !hasBuffer */) {
923 int32_t streamErr = ERROR_END_OF_STREAM;
924 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
925
Chong Zhang66704af2015-03-03 19:32:35 -0800926 CHECK(streamErr != OK);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800927
928 // attempt to queue EOS
929 status_t err = mCodec->queueInputBuffer(
930 bufferIx,
931 0,
932 0,
933 0,
934 MediaCodec::BUFFER_FLAG_EOS);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700935 if (err == OK) {
936 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
937 } else if (streamErr == ERROR_END_OF_STREAM) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800938 streamErr = err;
939 // err will not be ERROR_END_OF_STREAM
940 }
941
942 if (streamErr != ERROR_END_OF_STREAM) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700943 ALOGE("Stream error for %s (err=%d), EOS %s queued",
944 mComponentName.c_str(),
945 streamErr,
946 err == OK ? "successfully" : "unsuccessfully");
Lajos Molnar1cd13982014-01-17 15:12:51 -0800947 handleError(streamErr);
948 }
949 } else {
Wei Jiac6cfd702014-11-11 16:33:20 -0800950 sp<AMessage> extra;
951 if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
952 int64_t resumeAtMediaTimeUs;
953 if (extra->findInt64(
954 "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
955 ALOGI("[%s] suppressing rendering until %lld us",
956 mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
957 mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
958 }
959 }
960
Lajos Molnar1cd13982014-01-17 15:12:51 -0800961 int64_t timeUs = 0;
962 uint32_t flags = 0;
963 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
964
Lajos Molnar87603c02014-08-20 19:25:30 -0700965 int32_t eos, csd;
966 // we do not expect SYNCFRAME for decoder
Lajos Molnar1cd13982014-01-17 15:12:51 -0800967 if (buffer->meta()->findInt32("eos", &eos) && eos) {
968 flags |= MediaCodec::BUFFER_FLAG_EOS;
Lajos Molnar87603c02014-08-20 19:25:30 -0700969 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
970 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800971 }
972
973 // copy into codec buffer
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900974 if (needsCopy) {
Wei Jia56097a82016-01-07 16:03:03 -0800975 if (buffer->size() > codecBuffer->capacity()) {
976 handleError(ERROR_BUFFER_TOO_SMALL);
977 mDequeuedInputBuffers.push_back(bufferIx);
978 return false;
979 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800980 codecBuffer->setRange(0, buffer->size());
981 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
982 }
983
984 status_t err = mCodec->queueInputBuffer(
985 bufferIx,
986 codecBuffer->offset(),
987 codecBuffer->size(),
988 timeUs,
989 flags);
990 if (err != OK) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700991 if (mediaBuffer != NULL) {
992 mediaBuffer->release();
993 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800994 ALOGE("Failed to queue input buffer for %s (err=%d)",
995 mComponentName.c_str(), err);
996 handleError(err);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700997 } else {
998 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
999 if (mediaBuffer != NULL) {
1000 CHECK(mMediaBuffers[bufferIx] == NULL);
1001 mMediaBuffers.editItemAt(bufferIx) = mediaBuffer;
1002 }
Lajos Molnar09524832014-07-17 14:29:51 -07001003 }
Lajos Molnar1cd13982014-01-17 15:12:51 -08001004 }
Wei Jia2245fc62014-10-02 15:12:25 -07001005 return true;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001006}
1007
Lajos Molnar1cd13982014-01-17 15:12:51 -08001008void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
1009 status_t err;
1010 int32_t render;
1011 size_t bufferIx;
Chong Zhang66704af2015-03-03 19:32:35 -08001012 int32_t eos;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001013 CHECK(msg->findSize("buffer-ix", &bufferIx));
Wei Jiac6cfd702014-11-11 16:33:20 -08001014
Chong Zhang7137ec72014-11-12 16:41:05 -08001015 if (!mIsAudio) {
Wei Jiac6cfd702014-11-11 16:33:20 -08001016 int64_t timeUs;
Wonsik Kim7e34bf52016-08-23 00:09:18 +09001017 sp<MediaCodecBuffer> buffer = mOutputBuffers[bufferIx];
Wei Jiac6cfd702014-11-11 16:33:20 -08001018 buffer->meta()->findInt64("timeUs", &timeUs);
Chong Zhang7137ec72014-11-12 16:41:05 -08001019
1020 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1021 mCCDecoder->display(timeUs);
1022 }
Wei Jiac6cfd702014-11-11 16:33:20 -08001023 }
1024
Lajos Molnar1cd13982014-01-17 15:12:51 -08001025 if (msg->findInt32("render", &render) && render) {
Lajos Molnardc43dfa2014-05-07 15:33:04 -07001026 int64_t timestampNs;
1027 CHECK(msg->findInt64("timestampNs", &timestampNs));
1028 err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001029 } else {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -07001030 mNumOutputFramesDropped += !mIsAudio;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001031 err = mCodec->releaseOutputBuffer(bufferIx);
1032 }
1033 if (err != OK) {
1034 ALOGE("failed to release output buffer for %s (err=%d)",
1035 mComponentName.c_str(), err);
1036 handleError(err);
1037 }
Chong Zhang66704af2015-03-03 19:32:35 -08001038 if (msg->findInt32("eos", &eos) && eos
1039 && isDiscontinuityPending()) {
1040 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1041 }
1042}
1043
1044bool NuPlayer::Decoder::isDiscontinuityPending() const {
1045 return mFormatChangePending || mTimeChangePending;
1046}
1047
1048void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1049 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1050 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1051
1052 // If we have format change, pause and wait to be killed;
1053 // If we have time change only, flush and restart fetching.
1054
1055 if (mFormatChangePending) {
1056 mPaused = true;
1057 } else if (mTimeChangePending) {
1058 if (flushOnTimeChange) {
Marco Nelissen421f47c2015-03-25 14:40:32 -07001059 doFlush(false /* notifyComplete */);
1060 signalResume(false /* notifyComplete */);
Chong Zhang66704af2015-03-03 19:32:35 -08001061 }
Chong Zhang66704af2015-03-03 19:32:35 -08001062 }
1063
1064 // Notify NuPlayer to either shutdown decoder, or rescan sources
1065 sp<AMessage> msg = mNotify->dup();
1066 msg->setInt32("what", kWhatInputDiscontinuity);
1067 msg->setInt32("formatChange", mFormatChangePending);
1068 msg->post();
1069
1070 mFormatChangePending = false;
1071 mTimeChangePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001072}
1073
Chong Zhang7137ec72014-11-12 16:41:05 -08001074bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
1075 const sp<AMessage> &targetFormat) const {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001076 if (targetFormat == NULL) {
1077 return true;
1078 }
1079
1080 AString mime;
1081 if (!targetFormat->findString("mime", &mime)) {
1082 return false;
1083 }
1084
1085 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1086 // field-by-field comparison
1087 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1088 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1089 int32_t oldVal, newVal;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001090 if (!mInputFormat->findInt32(keys[i], &oldVal) ||
Lajos Molnar1cd13982014-01-17 15:12:51 -08001091 !targetFormat->findInt32(keys[i], &newVal) ||
1092 oldVal != newVal) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001093 return false;
1094 }
1095 }
1096
1097 sp<ABuffer> oldBuf, newBuf;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001098 if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
Lajos Molnar1cd13982014-01-17 15:12:51 -08001099 targetFormat->findBuffer("csd-0", &newBuf)) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001100 if (oldBuf->size() != newBuf->size()) {
1101 return false;
1102 }
1103 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
1104 }
1105 }
1106 return false;
1107}
1108
1109bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
joakim johansson7abbd4c2015-01-30 14:16:03 +01001110 if (mInputFormat == NULL) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001111 return false;
1112 }
1113
1114 if (targetFormat == NULL) {
1115 return true;
1116 }
1117
1118 AString oldMime, newMime;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001119 if (!mInputFormat->findString("mime", &oldMime)
Robert Shih6d0a94e2014-01-23 16:18:22 -08001120 || !targetFormat->findString("mime", &newMime)
1121 || !(oldMime == newMime)) {
1122 return false;
1123 }
1124
1125 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1126 bool seamless;
1127 if (audio) {
1128 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1129 } else {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001130 int32_t isAdaptive;
1131 seamless = (mCodec != NULL &&
1132 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
1133 isAdaptive);
Robert Shih6d0a94e2014-01-23 16:18:22 -08001134 }
1135
1136 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1137 return seamless;
1138}
1139
Chong Zhang7137ec72014-11-12 16:41:05 -08001140void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1141 if (format == NULL) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001142 return;
1143 }
Chong Zhang7137ec72014-11-12 16:41:05 -08001144 mCSDsForCurrentFormat.clear();
1145 for (int32_t i = 0; ; ++i) {
1146 AString tag = "csd-";
1147 tag.append(i);
1148 sp<ABuffer> buffer;
1149 if (!format->findBuffer(tag.c_str(), &buffer)) {
1150 break;
1151 }
1152 mCSDsForCurrentFormat.push(buffer);
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001153 }
Chong Zhangb86e68f2014-08-01 13:46:53 -07001154}
1155
Chong Zhangf8d71772014-11-26 15:08:34 -08001156void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
1157 if (mResumePending) {
1158 mResumePending = false;
1159
1160 sp<AMessage> notify = mNotify->dup();
1161 notify->setInt32("what", kWhatResumeCompleted);
1162 notify->post();
1163 }
1164}
1165
Andreas Huberf9334412010-12-15 15:17:42 -08001166} // namespace android
1167