blob: 822f1549006715d37839717181563f5943cd0f09 [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 Jiac6cfd702014-11-11 16:33:20 -080061 const sp<Renderer> &renderer,
Lajos Molnar1de1e252015-04-30 18:18:34 -070062 const sp<Surface> &surface,
Chong Zhang7137ec72014-11-12 16:41:05 -080063 const sp<CCDecoder> &ccDecoder)
Andy Hung202bce12014-12-03 11:47:36 -080064 : DecoderBase(notify),
Lajos Molnar1de1e252015-04-30 18:18:34 -070065 mSurface(surface),
Wei Jiac6cfd702014-11-11 16:33:20 -080066 mSource(source),
67 mRenderer(renderer),
Chong Zhang7137ec72014-11-12 16:41:05 -080068 mCCDecoder(ccDecoder),
Ronghua Wu68845c12015-07-21 09:50:48 -070069 mPid(pid),
Wei Jiac6cfd702014-11-11 16:33:20 -080070 mSkipRenderingUntilMediaTimeUs(-1ll),
Chong Zhang7137ec72014-11-12 16:41:05 -080071 mNumFramesTotal(0ll),
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070072 mNumInputFramesDropped(0ll),
73 mNumOutputFramesDropped(0ll),
74 mVideoWidth(0),
75 mVideoHeight(0),
Chong Zhang7137ec72014-11-12 16:41:05 -080076 mIsAudio(true),
77 mIsVideoAVC(false),
78 mIsSecure(false),
79 mFormatChangePending(false),
Chong Zhang66704af2015-03-03 19:32:35 -080080 mTimeChangePending(false),
Praveen Chavanbbaa1442016-04-08 13:33:49 -070081 mFrameRateTotal(kDefaultVideoFrameRateTotal),
82 mPlaybackSpeed(1.0f),
Lajos Molnar9fb81522016-07-14 07:33:43 -070083 mNumVideoTemporalLayerTotal(1), // decode all layers
Praveen Chavanbbaa1442016-04-08 13:33:49 -070084 mNumVideoTemporalLayerAllowed(1),
85 mCurrentMaxVideoTemporalLayerId(0),
Chong Zhangf8d71772014-11-26 15:08:34 -080086 mResumePending(false),
Lajos Molnar1cd13982014-01-17 15:12:51 -080087 mComponentName("decoder") {
Lajos Molnar1cd13982014-01-17 15:12:51 -080088 mCodecLooper = new ALooper;
Marco Nelissen9e2b7912014-08-18 16:13:03 -070089 mCodecLooper->setName("NPDecoder-CL");
Lajos Molnar1cd13982014-01-17 15:12:51 -080090 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
Praveen Chavanbbaa1442016-04-08 13:33:49 -070091 mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
Andreas Huberf9334412010-12-15 15:17:42 -080092}
93
94NuPlayer::Decoder::~Decoder() {
Ronghua Wufaeb0f22015-05-21 12:20:21 -070095 mCodec->release();
Wei Jia4923cee2014-09-24 14:25:19 -070096 releaseAndResetMediaBuffers();
Andreas Huberf9334412010-12-15 15:17:42 -080097}
98
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070099sp<AMessage> NuPlayer::Decoder::getStats() const {
100 mStats->setInt64("frames-total", mNumFramesTotal);
101 mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
102 mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
103 return mStats;
Lajos Molnar09524832014-07-17 14:29:51 -0700104}
105
Lajos Molnara81c6222015-07-10 19:17:45 -0700106status_t NuPlayer::Decoder::setVideoSurface(const sp<Surface> &surface) {
107 if (surface == NULL || ADebug::isExperimentEnabled("legacy-setsurface")) {
108 return BAD_VALUE;
109 }
110
111 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
112
113 msg->setObject("surface", surface);
114 sp<AMessage> response;
115 status_t err = msg->postAndAwaitResponse(&response);
116 if (err == OK && response != NULL) {
117 CHECK(response->findInt32("err", &err));
118 }
119 return err;
120}
121
Chong Zhang7137ec72014-11-12 16:41:05 -0800122void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
123 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
124
125 switch (msg->what()) {
126 case kWhatCodecNotify:
127 {
Chong Zhang3b032b32015-04-17 15:49:06 -0700128 int32_t cbID;
129 CHECK(msg->findInt32("callbackID", &cbID));
130
131 ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
132 mIsAudio ? "audio" : "video", cbID, mPaused);
133
Marco Nelissen421f47c2015-03-25 14:40:32 -0700134 if (mPaused) {
135 break;
Chong Zhang7137ec72014-11-12 16:41:05 -0800136 }
137
Marco Nelissen421f47c2015-03-25 14:40:32 -0700138 switch (cbID) {
139 case MediaCodec::CB_INPUT_AVAILABLE:
140 {
141 int32_t index;
142 CHECK(msg->findInt32("index", &index));
143
144 handleAnInputBuffer(index);
145 break;
146 }
147
148 case MediaCodec::CB_OUTPUT_AVAILABLE:
149 {
150 int32_t index;
151 size_t offset;
152 size_t size;
153 int64_t timeUs;
154 int32_t flags;
155
156 CHECK(msg->findInt32("index", &index));
157 CHECK(msg->findSize("offset", &offset));
158 CHECK(msg->findSize("size", &size));
159 CHECK(msg->findInt64("timeUs", &timeUs));
160 CHECK(msg->findInt32("flags", &flags));
161
162 handleAnOutputBuffer(index, offset, size, timeUs, flags);
163 break;
164 }
165
166 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED:
167 {
168 sp<AMessage> format;
169 CHECK(msg->findMessage("format", &format));
170
171 handleOutputFormatChange(format);
172 break;
173 }
174
175 case MediaCodec::CB_ERROR:
176 {
177 status_t err;
178 CHECK(msg->findInt32("err", &err));
179 ALOGE("Decoder (%s) reported error : 0x%x",
180 mIsAudio ? "audio" : "video", err);
181
182 handleError(err);
183 break;
184 }
185
186 default:
187 {
188 TRESPASS();
189 break;
190 }
191 }
192
Lajos Molnar87603c02014-08-20 19:25:30 -0700193 break;
194 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800195
196 case kWhatRenderBuffer:
197 {
198 if (!isStaleReply(msg)) {
199 onRenderBuffer(msg);
200 }
201 break;
202 }
203
Lajos Molnara81c6222015-07-10 19:17:45 -0700204 case kWhatSetVideoSurface:
205 {
206 sp<AReplyToken> replyID;
207 CHECK(msg->senderAwaitsResponse(&replyID));
208
209 sp<RefBase> obj;
210 CHECK(msg->findObject("surface", &obj));
211 sp<Surface> surface = static_cast<Surface *>(obj.get()); // non-null
212 int32_t err = INVALID_OPERATION;
213 // NOTE: in practice mSurface is always non-null, but checking here for completeness
214 if (mCodec != NULL && mSurface != NULL) {
215 // TODO: once AwesomePlayer is removed, remove this automatic connecting
216 // to the surface by MediaPlayerService.
217 //
218 // at this point MediaPlayerService::client has already connected to the
219 // surface, which MediaCodec does not expect
220 err = native_window_api_disconnect(surface.get(), NATIVE_WINDOW_API_MEDIA);
221 if (err == OK) {
222 err = mCodec->setSurface(surface);
223 ALOGI_IF(err, "codec setSurface returned: %d", err);
224 if (err == OK) {
225 // reconnect to the old surface as MPS::Client will expect to
226 // be able to disconnect from it.
227 (void)native_window_api_connect(mSurface.get(), NATIVE_WINDOW_API_MEDIA);
228 mSurface = surface;
229 }
230 }
231 if (err != OK) {
232 // reconnect to the new surface on error as MPS::Client will expect to
233 // be able to disconnect from it.
234 (void)native_window_api_connect(surface.get(), NATIVE_WINDOW_API_MEDIA);
235 }
236 }
237
238 sp<AMessage> response = new AMessage;
239 response->setInt32("err", err);
240 response->postReply(replyID);
241 break;
242 }
243
Chong Zhang7137ec72014-11-12 16:41:05 -0800244 default:
245 DecoderBase::onMessageReceived(msg);
246 break;
Lajos Molnar87603c02014-08-20 19:25:30 -0700247 }
248}
249
Lajos Molnar1cd13982014-01-17 15:12:51 -0800250void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
Andreas Huberf9334412010-12-15 15:17:42 -0800251 CHECK(mCodec == NULL);
Andreas Huberf9334412010-12-15 15:17:42 -0800252
Chong Zhang7137ec72014-11-12 16:41:05 -0800253 mFormatChangePending = false;
Chong Zhang66704af2015-03-03 19:32:35 -0800254 mTimeChangePending = false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800255
Lajos Molnar1cd13982014-01-17 15:12:51 -0800256 ++mBufferGeneration;
257
Andreas Huber84066782011-08-16 09:34:26 -0700258 AString mime;
259 CHECK(format->findString("mime", &mime));
Andreas Huberf9334412010-12-15 15:17:42 -0800260
Chong Zhang7137ec72014-11-12 16:41:05 -0800261 mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
262 mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
263
Lajos Molnar1cd13982014-01-17 15:12:51 -0800264 mComponentName = mime;
265 mComponentName.append(" decoder");
Lajos Molnar1de1e252015-04-30 18:18:34 -0700266 ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), mSurface.get());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800267
Ronghua Wu68845c12015-07-21 09:50:48 -0700268 mCodec = MediaCodec::CreateByType(
269 mCodecLooper, mime.c_str(), false /* encoder */, NULL /* err */, mPid);
Lajos Molnar09524832014-07-17 14:29:51 -0700270 int32_t secure = 0;
271 if (format->findInt32("secure", &secure) && secure != 0) {
272 if (mCodec != NULL) {
273 mCodec->getName(&mComponentName);
274 mComponentName.append(".secure");
275 mCodec->release();
276 ALOGI("[%s] creating", mComponentName.c_str());
277 mCodec = MediaCodec::CreateByComponentName(
Ronghua Wu68845c12015-07-21 09:50:48 -0700278 mCodecLooper, mComponentName.c_str(), NULL /* err */, mPid);
Lajos Molnar09524832014-07-17 14:29:51 -0700279 }
280 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800281 if (mCodec == NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700282 ALOGE("Failed to create %s%s decoder",
283 (secure ? "secure " : ""), mime.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800284 handleError(UNKNOWN_ERROR);
285 return;
286 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800287 mIsSecure = secure;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800288
289 mCodec->getName(&mComponentName);
290
Lajos Molnar14986f62014-09-15 11:04:44 -0700291 status_t err;
Lajos Molnar1de1e252015-04-30 18:18:34 -0700292 if (mSurface != NULL) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800293 // disconnect from surface as MediaCodec will reconnect
Lajos Molnar14986f62014-09-15 11:04:44 -0700294 err = native_window_api_disconnect(
Lajos Molnar1de1e252015-04-30 18:18:34 -0700295 mSurface.get(), NATIVE_WINDOW_API_MEDIA);
Lajos Molnar14986f62014-09-15 11:04:44 -0700296 // We treat this as a warning, as this is a preparatory step.
297 // Codec will try to connect to the surface, which is where
298 // any error signaling will occur.
299 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800300 }
Lajos Molnar14986f62014-09-15 11:04:44 -0700301 err = mCodec->configure(
Lajos Molnar1de1e252015-04-30 18:18:34 -0700302 format, mSurface, NULL /* crypto */, 0 /* flags */);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800303 if (err != OK) {
304 ALOGE("Failed to configure %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700305 mCodec->release();
306 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800307 handleError(err);
308 return;
309 }
Lajos Molnar87603c02014-08-20 19:25:30 -0700310 rememberCodecSpecificData(format);
311
Lajos Molnar1cd13982014-01-17 15:12:51 -0800312 // the following should work in configured state
313 CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
314 CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
315
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700316 mStats->setString("mime", mime.c_str());
317 mStats->setString("component-name", mComponentName.c_str());
318
319 if (!mIsAudio) {
320 int32_t width, height;
321 if (mOutputFormat->findInt32("width", &width)
322 && mOutputFormat->findInt32("height", &height)) {
323 mStats->setInt32("width", width);
324 mStats->setInt32("height", height);
325 }
326 }
327
Marco Nelissen421f47c2015-03-25 14:40:32 -0700328 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
329 mCodec->setCallback(reply);
330
Lajos Molnar1cd13982014-01-17 15:12:51 -0800331 err = mCodec->start();
332 if (err != OK) {
333 ALOGE("Failed to start %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700334 mCodec->release();
335 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800336 handleError(err);
337 return;
Andreas Huberf9334412010-12-15 15:17:42 -0800338 }
339
Lajos Molnar09524832014-07-17 14:29:51 -0700340 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700341
Wei Jia704e7262014-06-04 16:21:56 -0700342 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800343 mResumePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800344}
Andreas Huber078cfcf2011-09-15 12:25:04 -0700345
Ronghua Wu8db88132015-04-22 13:51:35 -0700346void NuPlayer::Decoder::onSetParameters(const sp<AMessage> &params) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700347 bool needAdjustLayers = false;
348 float frameRateTotal;
349 if (params->findFloat("frame-rate-total", &frameRateTotal)
350 && mFrameRateTotal != frameRateTotal) {
351 needAdjustLayers = true;
352 mFrameRateTotal = frameRateTotal;
Ronghua Wu8db88132015-04-22 13:51:35 -0700353 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700354
355 int32_t numVideoTemporalLayerTotal;
356 if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
Lajos Molnar9fb81522016-07-14 07:33:43 -0700357 && numVideoTemporalLayerTotal >= 0
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700358 && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
359 && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
360 needAdjustLayers = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700361 mNumVideoTemporalLayerTotal = std::max(numVideoTemporalLayerTotal, 1);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700362 }
363
Lajos Molnar9fb81522016-07-14 07:33:43 -0700364 if (needAdjustLayers && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700365 // TODO: For now, layer fps is calculated for some specific architectures.
366 // But it really should be extracted from the stream.
367 mVideoTemporalLayerAggregateFps[0] =
368 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - 1));
369 for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
370 mVideoTemporalLayerAggregateFps[i] =
371 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - i))
372 + mVideoTemporalLayerAggregateFps[i - 1];
373 }
374 }
375
376 float playbackSpeed;
377 if (params->findFloat("playback-speed", &playbackSpeed)
378 && mPlaybackSpeed != playbackSpeed) {
379 needAdjustLayers = true;
380 mPlaybackSpeed = playbackSpeed;
381 }
382
383 if (needAdjustLayers) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700384 float decodeFrameRate = mFrameRateTotal;
385 // enable temporal layering optimization only if we know the layering depth
386 if (mNumVideoTemporalLayerTotal > 1) {
387 int32_t layerId;
388 for (layerId = 0; layerId < mNumVideoTemporalLayerTotal - 1; ++layerId) {
389 if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
390 >= kDisplayRefreshingRate * 0.9) {
391 break;
392 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700393 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700394 mNumVideoTemporalLayerAllowed = layerId + 1;
395 decodeFrameRate = mVideoTemporalLayerAggregateFps[layerId];
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700396 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700397 ALOGV("onSetParameters: allowed layers=%d, decodeFps=%g",
398 mNumVideoTemporalLayerAllowed, decodeFrameRate);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700399
400 if (mCodec == NULL) {
401 ALOGW("onSetParameters called before codec is created.");
402 return;
403 }
404
405 sp<AMessage> codecParams = new AMessage();
Lajos Molnar9fb81522016-07-14 07:33:43 -0700406 codecParams->setFloat("operating-rate", decodeFrameRate * mPlaybackSpeed);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700407 mCodec->setParameters(codecParams);
408 }
Ronghua Wu8db88132015-04-22 13:51:35 -0700409}
410
Chong Zhang7137ec72014-11-12 16:41:05 -0800411void NuPlayer::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
412 bool hadNoRenderer = (mRenderer == NULL);
413 mRenderer = renderer;
414 if (hadNoRenderer && mRenderer != NULL) {
Lajos Molnare6109e22015-04-10 17:18:22 -0700415 // this means that the widevine legacy source is ready
416 onRequestInputBuffers();
Chong Zhang7137ec72014-11-12 16:41:05 -0800417 }
418}
419
420void NuPlayer::Decoder::onGetInputBuffers(
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900421 Vector<sp<MediaCodecBuffer> > *dstBuffers) {
Lajos Molnare6109e22015-04-10 17:18:22 -0700422 CHECK_EQ((status_t)OK, mCodec->getWidevineLegacyBuffers(dstBuffers));
Chong Zhang7137ec72014-11-12 16:41:05 -0800423}
424
Chong Zhangf8d71772014-11-26 15:08:34 -0800425void NuPlayer::Decoder::onResume(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800426 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800427
428 if (notifyComplete) {
429 mResumePending = true;
430 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700431 mCodec->start();
Chong Zhang7137ec72014-11-12 16:41:05 -0800432}
433
Chong Zhang66704af2015-03-03 19:32:35 -0800434void NuPlayer::Decoder::doFlush(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800435 if (mCCDecoder != NULL) {
436 mCCDecoder->flush();
437 }
438
439 if (mRenderer != NULL) {
440 mRenderer->flush(mIsAudio, notifyComplete);
441 mRenderer->signalTimeDiscontinuity();
442 }
443
444 status_t err = OK;
445 if (mCodec != NULL) {
446 err = mCodec->flush();
447 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
448 ++mBufferGeneration;
449 }
450
451 if (err != OK) {
452 ALOGE("failed to flush %s (err=%d)", mComponentName.c_str(), err);
453 handleError(err);
454 // finish with posting kWhatFlushCompleted.
455 // we attempt to release the buffers even if flush fails.
456 }
457 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700458 mPaused = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800459}
Chong Zhang7137ec72014-11-12 16:41:05 -0800460
Marco Nelissen421f47c2015-03-25 14:40:32 -0700461
Chong Zhang66704af2015-03-03 19:32:35 -0800462void NuPlayer::Decoder::onFlush() {
463 doFlush(true);
464
465 if (isDiscontinuityPending()) {
466 // This could happen if the client starts seeking/shutdown
467 // after we queued an EOS for discontinuities.
468 // We can consider discontinuity handled.
469 finishHandleDiscontinuity(false /* flushOnTimeChange */);
Chong Zhang7137ec72014-11-12 16:41:05 -0800470 }
Chong Zhang66704af2015-03-03 19:32:35 -0800471
472 sp<AMessage> notify = mNotify->dup();
473 notify->setInt32("what", kWhatFlushCompleted);
474 notify->post();
Chong Zhang7137ec72014-11-12 16:41:05 -0800475}
476
477void NuPlayer::Decoder::onShutdown(bool notifyComplete) {
478 status_t err = OK;
Chong Zhangf8d71772014-11-26 15:08:34 -0800479
480 // if there is a pending resume request, notify complete now
481 notifyResumeCompleteIfNecessary();
482
Chong Zhang7137ec72014-11-12 16:41:05 -0800483 if (mCodec != NULL) {
484 err = mCodec->release();
485 mCodec = NULL;
486 ++mBufferGeneration;
487
Lajos Molnar1de1e252015-04-30 18:18:34 -0700488 if (mSurface != NULL) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800489 // reconnect to surface as MediaCodec disconnected from it
490 status_t error =
Lajos Molnar1de1e252015-04-30 18:18:34 -0700491 native_window_api_connect(mSurface.get(), NATIVE_WINDOW_API_MEDIA);
Chong Zhang7137ec72014-11-12 16:41:05 -0800492 ALOGW_IF(error != NO_ERROR,
493 "[%s] failed to connect to native window, error=%d",
494 mComponentName.c_str(), error);
495 }
496 mComponentName = "decoder";
497 }
498
499 releaseAndResetMediaBuffers();
500
501 if (err != OK) {
502 ALOGE("failed to release %s (err=%d)", mComponentName.c_str(), err);
503 handleError(err);
504 // finish with posting kWhatShutdownCompleted.
505 }
506
507 if (notifyComplete) {
508 sp<AMessage> notify = mNotify->dup();
509 notify->setInt32("what", kWhatShutdownCompleted);
510 notify->post();
511 mPaused = true;
512 }
513}
514
Chong Zhang3b032b32015-04-17 15:49:06 -0700515/*
516 * returns true if we should request more data
517 */
518bool NuPlayer::Decoder::doRequestBuffers() {
Lajos Molnare6109e22015-04-10 17:18:22 -0700519 // mRenderer is only NULL if we have a legacy widevine source that
520 // is not yet ready. In this case we must not fetch input.
521 if (isDiscontinuityPending() || mRenderer == NULL) {
Chong Zhang3b032b32015-04-17 15:49:06 -0700522 return false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800523 }
524 status_t err = OK;
Chong Zhang66704af2015-03-03 19:32:35 -0800525 while (err == OK && !mDequeuedInputBuffers.empty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800526 size_t bufferIx = *mDequeuedInputBuffers.begin();
527 sp<AMessage> msg = new AMessage();
528 msg->setSize("buffer-ix", bufferIx);
529 err = fetchInputData(msg);
Chong Zhang66704af2015-03-03 19:32:35 -0800530 if (err != OK && err != ERROR_END_OF_STREAM) {
531 // if EOS, need to queue EOS buffer
Chong Zhang7137ec72014-11-12 16:41:05 -0800532 break;
533 }
534 mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
535
536 if (!mPendingInputMessages.empty()
537 || !onInputBufferFetched(msg)) {
538 mPendingInputMessages.push_back(msg);
Lajos Molnar09524832014-07-17 14:29:51 -0700539 }
540 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800541
Chong Zhang3b032b32015-04-17 15:49:06 -0700542 return err == -EWOULDBLOCK
543 && mSource->feedMoreTSData() == OK;
Lajos Molnar09524832014-07-17 14:29:51 -0700544}
545
Marco Nelissen421f47c2015-03-25 14:40:32 -0700546void NuPlayer::Decoder::handleError(int32_t err)
547{
548 // We cannot immediately release the codec due to buffers still outstanding
549 // in the renderer. We signal to the player the error so it can shutdown/release the
550 // decoder after flushing and increment the generation to discard unnecessary messages.
551
552 ++mBufferGeneration;
553
554 sp<AMessage> notify = mNotify->dup();
555 notify->setInt32("what", kWhatError);
556 notify->setInt32("err", err);
557 notify->post();
558}
559
560bool NuPlayer::Decoder::handleAnInputBuffer(size_t index) {
Chong Zhang66704af2015-03-03 19:32:35 -0800561 if (isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800562 return false;
563 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700564
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900565 sp<MediaCodecBuffer> buffer;
Marco Nelissen421f47c2015-03-25 14:40:32 -0700566 mCodec->getInputBuffer(index, &buffer);
567
Wei Jia6301a5e2015-05-13 13:15:18 -0700568 if (buffer == NULL) {
569 handleError(UNKNOWN_ERROR);
570 return false;
571 }
572
Marco Nelissen421f47c2015-03-25 14:40:32 -0700573 if (index >= mInputBuffers.size()) {
574 for (size_t i = mInputBuffers.size(); i <= index; ++i) {
575 mInputBuffers.add();
576 mMediaBuffers.add();
577 mInputBufferIsDequeued.add();
578 mMediaBuffers.editItemAt(i) = NULL;
579 mInputBufferIsDequeued.editItemAt(i) = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800580 }
Andreas Huber078cfcf2011-09-15 12:25:04 -0700581 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700582 mInputBuffers.editItemAt(index) = buffer;
Andreas Huber078cfcf2011-09-15 12:25:04 -0700583
Marco Nelissen421f47c2015-03-25 14:40:32 -0700584 //CHECK_LT(bufferIx, mInputBuffers.size());
Andreas Huberf9334412010-12-15 15:17:42 -0800585
Marco Nelissen421f47c2015-03-25 14:40:32 -0700586 if (mMediaBuffers[index] != NULL) {
587 mMediaBuffers[index]->release();
588 mMediaBuffers.editItemAt(index) = NULL;
Lajos Molnar09524832014-07-17 14:29:51 -0700589 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700590 mInputBufferIsDequeued.editItemAt(index) = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700591
Lajos Molnar87603c02014-08-20 19:25:30 -0700592 if (!mCSDsToSubmit.isEmpty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800593 sp<AMessage> msg = new AMessage();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700594 msg->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800595
Lajos Molnar87603c02014-08-20 19:25:30 -0700596 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
597 ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
Chong Zhang7137ec72014-11-12 16:41:05 -0800598 msg->setBuffer("buffer", buffer);
Lajos Molnar87603c02014-08-20 19:25:30 -0700599 mCSDsToSubmit.removeAt(0);
Wei Jia56097a82016-01-07 16:03:03 -0800600 if (!onInputBufferFetched(msg)) {
601 handleError(UNKNOWN_ERROR);
602 return false;
603 }
Wei Jia2245fc62014-10-02 15:12:25 -0700604 return true;
605 }
606
607 while (!mPendingInputMessages.empty()) {
608 sp<AMessage> msg = *mPendingInputMessages.begin();
Chong Zhang7137ec72014-11-12 16:41:05 -0800609 if (!onInputBufferFetched(msg)) {
Wei Jia2245fc62014-10-02 15:12:25 -0700610 break;
611 }
612 mPendingInputMessages.erase(mPendingInputMessages.begin());
613 }
614
Marco Nelissen421f47c2015-03-25 14:40:32 -0700615 if (!mInputBufferIsDequeued.editItemAt(index)) {
Lajos Molnar87603c02014-08-20 19:25:30 -0700616 return true;
617 }
618
Marco Nelissen421f47c2015-03-25 14:40:32 -0700619 mDequeuedInputBuffers.push_back(index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800620
621 onRequestInputBuffers();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800622 return true;
623}
624
Marco Nelissen421f47c2015-03-25 14:40:32 -0700625bool NuPlayer::Decoder::handleAnOutputBuffer(
626 size_t index,
627 size_t offset,
628 size_t size,
629 int64_t timeUs,
630 int32_t flags) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700631// CHECK_LT(bufferIx, mOutputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900632 sp<MediaCodecBuffer> buffer;
Marco Nelissen421f47c2015-03-25 14:40:32 -0700633 mCodec->getOutputBuffer(index, &buffer);
634
635 if (index >= mOutputBuffers.size()) {
636 for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
637 mOutputBuffers.add();
638 }
639 }
640
641 mOutputBuffers.editItemAt(index) = buffer;
642
Chong Zhang7137ec72014-11-12 16:41:05 -0800643 buffer->setRange(offset, size);
644 buffer->meta()->clear();
645 buffer->meta()->setInt64("timeUs", timeUs);
Chong Zhang66704af2015-03-03 19:32:35 -0800646
647 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
Chong Zhang7137ec72014-11-12 16:41:05 -0800648 // we do not expect CODECCONFIG or SYNCFRAME for decoder
649
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800650 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700651 reply->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800652 reply->setInt32("generation", mBufferGeneration);
653
Chong Zhang66704af2015-03-03 19:32:35 -0800654 if (eos) {
655 ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
656
657 buffer->meta()->setInt32("eos", true);
658 reply->setInt32("eos", true);
659 } else if (mSkipRenderingUntilMediaTimeUs >= 0) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800660 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
661 ALOGV("[%s] dropping buffer at time %lld as requested.",
662 mComponentName.c_str(), (long long)timeUs);
663
664 reply->post();
665 return true;
666 }
667
668 mSkipRenderingUntilMediaTimeUs = -1;
669 }
670
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700671 mNumFramesTotal += !mIsAudio;
672
Chong Zhangf8d71772014-11-26 15:08:34 -0800673 // wait until 1st frame comes out to signal resume complete
674 notifyResumeCompleteIfNecessary();
675
Chong Zhang7137ec72014-11-12 16:41:05 -0800676 if (mRenderer != NULL) {
677 // send the buffer to renderer.
678 mRenderer->queueBuffer(mIsAudio, buffer, reply);
Chong Zhang66704af2015-03-03 19:32:35 -0800679 if (eos && !isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800680 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
681 }
682 }
683
684 return true;
685}
686
Marco Nelissen421f47c2015-03-25 14:40:32 -0700687void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
688 if (!mIsAudio) {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700689 int32_t width, height;
690 if (format->findInt32("width", &width)
691 && format->findInt32("height", &height)) {
692 mStats->setInt32("width", width);
693 mStats->setInt32("height", height);
694 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700695 sp<AMessage> notify = mNotify->dup();
696 notify->setInt32("what", kWhatVideoSizeChanged);
697 notify->setMessage("format", format);
698 notify->post();
699 } else if (mRenderer != NULL) {
700 uint32_t flags;
701 int64_t durationUs;
702 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
Andy Hung288da022015-05-31 22:55:59 -0700703 if (getAudioDeepBufferSetting() // override regardless of source duration
704 || (!hasVideo
705 && mSource->getDuration(&durationUs) == OK
706 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700707 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
708 } else {
709 flags = AUDIO_OUTPUT_FLAG_NONE;
710 }
711
Eric Laurent216f0172015-08-20 18:40:24 -0700712 status_t err = mRenderer->openAudioSink(
Marco Nelissen421f47c2015-03-25 14:40:32 -0700713 format, false /* offloadOnly */, hasVideo, flags, NULL /* isOffloaed */);
Eric Laurent216f0172015-08-20 18:40:24 -0700714 if (err != OK) {
715 handleError(err);
716 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700717 }
718}
719
Chong Zhang7137ec72014-11-12 16:41:05 -0800720void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
721 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
722 if (mMediaBuffers[i] != NULL) {
723 mMediaBuffers[i]->release();
724 mMediaBuffers.editItemAt(i) = NULL;
725 }
726 }
727 mMediaBuffers.resize(mInputBuffers.size());
728 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
729 mMediaBuffers.editItemAt(i) = NULL;
730 }
731 mInputBufferIsDequeued.clear();
732 mInputBufferIsDequeued.resize(mInputBuffers.size());
733 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
734 mInputBufferIsDequeued.editItemAt(i) = false;
735 }
736
737 mPendingInputMessages.clear();
738 mDequeuedInputBuffers.clear();
739 mSkipRenderingUntilMediaTimeUs = -1;
740}
741
742void NuPlayer::Decoder::requestCodecNotification() {
Chong Zhang7137ec72014-11-12 16:41:05 -0800743 if (mCodec != NULL) {
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800744 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
Chong Zhang7137ec72014-11-12 16:41:05 -0800745 reply->setInt32("generation", mBufferGeneration);
746 mCodec->requestActivityNotification(reply);
747 }
748}
749
750bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
751 int32_t generation;
752 CHECK(msg->findInt32("generation", &generation));
753 return generation != mBufferGeneration;
754}
755
756status_t NuPlayer::Decoder::fetchInputData(sp<AMessage> &reply) {
757 sp<ABuffer> accessUnit;
758 bool dropAccessUnit;
759 do {
760 status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
761
762 if (err == -EWOULDBLOCK) {
763 return err;
764 } else if (err != OK) {
765 if (err == INFO_DISCONTINUITY) {
766 int32_t type;
767 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
768
769 bool formatChange =
770 (mIsAudio &&
771 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
772 || (!mIsAudio &&
773 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
774
775 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
776
777 ALOGI("%s discontinuity (format=%d, time=%d)",
778 mIsAudio ? "audio" : "video", formatChange, timeChange);
779
780 bool seamlessFormatChange = false;
781 sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
782 if (formatChange) {
783 seamlessFormatChange =
784 supportsSeamlessFormatChange(newFormat);
785 // treat seamless format change separately
786 formatChange = !seamlessFormatChange;
787 }
788
Chong Zhang66704af2015-03-03 19:32:35 -0800789 // For format or time change, return EOS to queue EOS input,
790 // then wait for EOS on output.
Chong Zhang7137ec72014-11-12 16:41:05 -0800791 if (formatChange /* not seamless */) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800792 mFormatChangePending = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800793 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800794 } else if (timeChange) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800795 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800796 mTimeChangePending = true;
797 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800798 } else if (seamlessFormatChange) {
799 // reuse existing decoder and don't flush
800 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800801 continue;
Chong Zhang7137ec72014-11-12 16:41:05 -0800802 } else {
803 // This stream is unaffected by the discontinuity
804 return -EWOULDBLOCK;
805 }
806 }
807
Chong Zhang66704af2015-03-03 19:32:35 -0800808 // reply should only be returned without a buffer set
809 // when there is an error (including EOS)
810 CHECK(err != OK);
811
Chong Zhang7137ec72014-11-12 16:41:05 -0800812 reply->setInt32("err", err);
Chong Zhang66704af2015-03-03 19:32:35 -0800813 return ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800814 }
815
Chong Zhang7137ec72014-11-12 16:41:05 -0800816 dropAccessUnit = false;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700817 if (!mIsAudio && !mIsSecure) {
818 int32_t layerId = 0;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700819 bool haveLayerId = accessUnit->meta()->findInt32("temporal-layer-id", &layerId);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700820 if (mRenderer->getVideoLateByUs() > 100000ll
821 && mIsVideoAVC
822 && !IsAVCReferenceFrame(accessUnit)) {
823 dropAccessUnit = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700824 } else if (haveLayerId && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700825 // Add only one layer each time.
826 if (layerId > mCurrentMaxVideoTemporalLayerId + 1
827 || layerId >= mNumVideoTemporalLayerAllowed) {
828 dropAccessUnit = true;
829 ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
830 layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
831 mCurrentMaxVideoTemporalLayerId);
832 } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
833 mCurrentMaxVideoTemporalLayerId = layerId;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700834 } else if (layerId == 0 && mNumVideoTemporalLayerTotal > 1 && IsIDR(accessUnit)) {
835 mCurrentMaxVideoTemporalLayerId = mNumVideoTemporalLayerTotal - 1;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700836 }
837 }
838 if (dropAccessUnit) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700839 if (layerId <= mCurrentMaxVideoTemporalLayerId && layerId > 0) {
840 mCurrentMaxVideoTemporalLayerId = layerId - 1;
841 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700842 ++mNumInputFramesDropped;
843 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800844 }
845 } while (dropAccessUnit);
846
847 // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
848#if 0
849 int64_t mediaTimeUs;
850 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
Chong Zhang5abbd3d2015-04-20 16:03:00 -0700851 ALOGV("[%s] feeding input buffer at media time %.3f",
Chong Zhang7137ec72014-11-12 16:41:05 -0800852 mIsAudio ? "audio" : "video",
853 mediaTimeUs / 1E6);
854#endif
855
856 if (mCCDecoder != NULL) {
857 mCCDecoder->decode(accessUnit);
858 }
859
860 reply->setBuffer("buffer", accessUnit);
861
862 return OK;
863}
864
865bool NuPlayer::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800866 size_t bufferIx;
867 CHECK(msg->findSize("buffer-ix", &bufferIx));
868 CHECK_LT(bufferIx, mInputBuffers.size());
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900869 sp<MediaCodecBuffer> codecBuffer = mInputBuffers[bufferIx];
Lajos Molnar1cd13982014-01-17 15:12:51 -0800870
871 sp<ABuffer> buffer;
872 bool hasBuffer = msg->findBuffer("buffer", &buffer);
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900873 bool needsCopy = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700874
875 // handle widevine classic source - that fills an arbitrary input buffer
876 MediaBuffer *mediaBuffer = NULL;
Wei Jia96e92b52014-09-18 17:36:20 -0700877 if (hasBuffer) {
878 mediaBuffer = (MediaBuffer *)(buffer->getMediaBufferBase());
879 if (mediaBuffer != NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700880 // likely filled another buffer than we requested: adjust buffer index
881 size_t ix;
882 for (ix = 0; ix < mInputBuffers.size(); ix++) {
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900883 const sp<MediaCodecBuffer> &buf = mInputBuffers[ix];
Lajos Molnar09524832014-07-17 14:29:51 -0700884 if (buf->data() == mediaBuffer->data()) {
885 // all input buffers are dequeued on start, hence the check
Wei Jia2245fc62014-10-02 15:12:25 -0700886 if (!mInputBufferIsDequeued[ix]) {
887 ALOGV("[%s] received MediaBuffer for #%zu instead of #%zu",
888 mComponentName.c_str(), ix, bufferIx);
889 mediaBuffer->release();
890 return false;
891 }
Lajos Molnar09524832014-07-17 14:29:51 -0700892
893 // TRICKY: need buffer for the metadata, so instead, set
894 // codecBuffer to the same (though incorrect) buffer to
895 // avoid a memcpy into the codecBuffer
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900896 codecBuffer = new MediaCodecBuffer(codecBuffer->format(), buffer);
Lajos Molnar09524832014-07-17 14:29:51 -0700897 codecBuffer->setRange(
898 mediaBuffer->range_offset(),
899 mediaBuffer->range_length());
900 bufferIx = ix;
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900901 needsCopy = false;
Lajos Molnar09524832014-07-17 14:29:51 -0700902 break;
903 }
904 }
905 CHECK(ix < mInputBuffers.size());
906 }
907 }
908
Lajos Molnar1cd13982014-01-17 15:12:51 -0800909 if (buffer == NULL /* includes !hasBuffer */) {
910 int32_t streamErr = ERROR_END_OF_STREAM;
911 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
912
Chong Zhang66704af2015-03-03 19:32:35 -0800913 CHECK(streamErr != OK);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800914
915 // attempt to queue EOS
916 status_t err = mCodec->queueInputBuffer(
917 bufferIx,
918 0,
919 0,
920 0,
921 MediaCodec::BUFFER_FLAG_EOS);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700922 if (err == OK) {
923 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
924 } else if (streamErr == ERROR_END_OF_STREAM) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800925 streamErr = err;
926 // err will not be ERROR_END_OF_STREAM
927 }
928
929 if (streamErr != ERROR_END_OF_STREAM) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700930 ALOGE("Stream error for %s (err=%d), EOS %s queued",
931 mComponentName.c_str(),
932 streamErr,
933 err == OK ? "successfully" : "unsuccessfully");
Lajos Molnar1cd13982014-01-17 15:12:51 -0800934 handleError(streamErr);
935 }
936 } else {
Wei Jiac6cfd702014-11-11 16:33:20 -0800937 sp<AMessage> extra;
938 if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
939 int64_t resumeAtMediaTimeUs;
940 if (extra->findInt64(
941 "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
942 ALOGI("[%s] suppressing rendering until %lld us",
943 mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
944 mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
945 }
946 }
947
Lajos Molnar1cd13982014-01-17 15:12:51 -0800948 int64_t timeUs = 0;
949 uint32_t flags = 0;
950 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
951
Lajos Molnar87603c02014-08-20 19:25:30 -0700952 int32_t eos, csd;
953 // we do not expect SYNCFRAME for decoder
Lajos Molnar1cd13982014-01-17 15:12:51 -0800954 if (buffer->meta()->findInt32("eos", &eos) && eos) {
955 flags |= MediaCodec::BUFFER_FLAG_EOS;
Lajos Molnar87603c02014-08-20 19:25:30 -0700956 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
957 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800958 }
959
960 // copy into codec buffer
Wonsik Kim7e34bf52016-08-23 00:09:18 +0900961 if (needsCopy) {
Wei Jia56097a82016-01-07 16:03:03 -0800962 if (buffer->size() > codecBuffer->capacity()) {
963 handleError(ERROR_BUFFER_TOO_SMALL);
964 mDequeuedInputBuffers.push_back(bufferIx);
965 return false;
966 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800967 codecBuffer->setRange(0, buffer->size());
968 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
969 }
970
971 status_t err = mCodec->queueInputBuffer(
972 bufferIx,
973 codecBuffer->offset(),
974 codecBuffer->size(),
975 timeUs,
976 flags);
977 if (err != OK) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700978 if (mediaBuffer != NULL) {
979 mediaBuffer->release();
980 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800981 ALOGE("Failed to queue input buffer for %s (err=%d)",
982 mComponentName.c_str(), err);
983 handleError(err);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700984 } else {
985 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
986 if (mediaBuffer != NULL) {
987 CHECK(mMediaBuffers[bufferIx] == NULL);
988 mMediaBuffers.editItemAt(bufferIx) = mediaBuffer;
989 }
Lajos Molnar09524832014-07-17 14:29:51 -0700990 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800991 }
Wei Jia2245fc62014-10-02 15:12:25 -0700992 return true;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800993}
994
Lajos Molnar1cd13982014-01-17 15:12:51 -0800995void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
996 status_t err;
997 int32_t render;
998 size_t bufferIx;
Chong Zhang66704af2015-03-03 19:32:35 -0800999 int32_t eos;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001000 CHECK(msg->findSize("buffer-ix", &bufferIx));
Wei Jiac6cfd702014-11-11 16:33:20 -08001001
Chong Zhang7137ec72014-11-12 16:41:05 -08001002 if (!mIsAudio) {
Wei Jiac6cfd702014-11-11 16:33:20 -08001003 int64_t timeUs;
Wonsik Kim7e34bf52016-08-23 00:09:18 +09001004 sp<MediaCodecBuffer> buffer = mOutputBuffers[bufferIx];
Wei Jiac6cfd702014-11-11 16:33:20 -08001005 buffer->meta()->findInt64("timeUs", &timeUs);
Chong Zhang7137ec72014-11-12 16:41:05 -08001006
1007 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1008 mCCDecoder->display(timeUs);
1009 }
Wei Jiac6cfd702014-11-11 16:33:20 -08001010 }
1011
Lajos Molnar1cd13982014-01-17 15:12:51 -08001012 if (msg->findInt32("render", &render) && render) {
Lajos Molnardc43dfa2014-05-07 15:33:04 -07001013 int64_t timestampNs;
1014 CHECK(msg->findInt64("timestampNs", &timestampNs));
1015 err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001016 } else {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -07001017 mNumOutputFramesDropped += !mIsAudio;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001018 err = mCodec->releaseOutputBuffer(bufferIx);
1019 }
1020 if (err != OK) {
1021 ALOGE("failed to release output buffer for %s (err=%d)",
1022 mComponentName.c_str(), err);
1023 handleError(err);
1024 }
Chong Zhang66704af2015-03-03 19:32:35 -08001025 if (msg->findInt32("eos", &eos) && eos
1026 && isDiscontinuityPending()) {
1027 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1028 }
1029}
1030
1031bool NuPlayer::Decoder::isDiscontinuityPending() const {
1032 return mFormatChangePending || mTimeChangePending;
1033}
1034
1035void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1036 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1037 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1038
1039 // If we have format change, pause and wait to be killed;
1040 // If we have time change only, flush and restart fetching.
1041
1042 if (mFormatChangePending) {
1043 mPaused = true;
1044 } else if (mTimeChangePending) {
1045 if (flushOnTimeChange) {
Marco Nelissen421f47c2015-03-25 14:40:32 -07001046 doFlush(false /* notifyComplete */);
1047 signalResume(false /* notifyComplete */);
Chong Zhang66704af2015-03-03 19:32:35 -08001048 }
Chong Zhang66704af2015-03-03 19:32:35 -08001049 }
1050
1051 // Notify NuPlayer to either shutdown decoder, or rescan sources
1052 sp<AMessage> msg = mNotify->dup();
1053 msg->setInt32("what", kWhatInputDiscontinuity);
1054 msg->setInt32("formatChange", mFormatChangePending);
1055 msg->post();
1056
1057 mFormatChangePending = false;
1058 mTimeChangePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001059}
1060
Chong Zhang7137ec72014-11-12 16:41:05 -08001061bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
1062 const sp<AMessage> &targetFormat) const {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001063 if (targetFormat == NULL) {
1064 return true;
1065 }
1066
1067 AString mime;
1068 if (!targetFormat->findString("mime", &mime)) {
1069 return false;
1070 }
1071
1072 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1073 // field-by-field comparison
1074 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1075 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1076 int32_t oldVal, newVal;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001077 if (!mInputFormat->findInt32(keys[i], &oldVal) ||
Lajos Molnar1cd13982014-01-17 15:12:51 -08001078 !targetFormat->findInt32(keys[i], &newVal) ||
1079 oldVal != newVal) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001080 return false;
1081 }
1082 }
1083
1084 sp<ABuffer> oldBuf, newBuf;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001085 if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
Lajos Molnar1cd13982014-01-17 15:12:51 -08001086 targetFormat->findBuffer("csd-0", &newBuf)) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001087 if (oldBuf->size() != newBuf->size()) {
1088 return false;
1089 }
1090 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
1091 }
1092 }
1093 return false;
1094}
1095
1096bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
joakim johansson7abbd4c2015-01-30 14:16:03 +01001097 if (mInputFormat == NULL) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001098 return false;
1099 }
1100
1101 if (targetFormat == NULL) {
1102 return true;
1103 }
1104
1105 AString oldMime, newMime;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001106 if (!mInputFormat->findString("mime", &oldMime)
Robert Shih6d0a94e2014-01-23 16:18:22 -08001107 || !targetFormat->findString("mime", &newMime)
1108 || !(oldMime == newMime)) {
1109 return false;
1110 }
1111
1112 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1113 bool seamless;
1114 if (audio) {
1115 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1116 } else {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001117 int32_t isAdaptive;
1118 seamless = (mCodec != NULL &&
1119 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
1120 isAdaptive);
Robert Shih6d0a94e2014-01-23 16:18:22 -08001121 }
1122
1123 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1124 return seamless;
1125}
1126
Chong Zhang7137ec72014-11-12 16:41:05 -08001127void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1128 if (format == NULL) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001129 return;
1130 }
Chong Zhang7137ec72014-11-12 16:41:05 -08001131 mCSDsForCurrentFormat.clear();
1132 for (int32_t i = 0; ; ++i) {
1133 AString tag = "csd-";
1134 tag.append(i);
1135 sp<ABuffer> buffer;
1136 if (!format->findBuffer(tag.c_str(), &buffer)) {
1137 break;
1138 }
1139 mCSDsForCurrentFormat.push(buffer);
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001140 }
Chong Zhangb86e68f2014-08-01 13:46:53 -07001141}
1142
Chong Zhangf8d71772014-11-26 15:08:34 -08001143void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
1144 if (mResumePending) {
1145 mResumePending = false;
1146
1147 sp<AMessage> notify = mNotify->dup();
1148 notify->setInt32("what", kWhatResumeCompleted);
1149 notify->post();
1150 }
1151}
1152
Andreas Huberf9334412010-12-15 15:17:42 -08001153} // namespace android
1154