blob: caaa7356b98d85f02be53366dd7f8393f6a264b7 [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>
Andreas Huberf9334412010-12-15 15:17:42 -080031#include <media/stagefright/foundation/ABuffer.h>
32#include <media/stagefright/foundation/ADebug.h>
Andreas Huber5bc087c2010-12-23 10:27:40 -080033#include <media/stagefright/foundation/AMessage.h>
Lajos Molnar09524832014-07-17 14:29:51 -070034#include <media/stagefright/MediaBuffer.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080035#include <media/stagefright/MediaCodec.h>
Andreas Huberf9334412010-12-15 15:17:42 -080036#include <media/stagefright/MediaDefs.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080037#include <media/stagefright/MediaErrors.h>
Andreas Huberf9334412010-12-15 15:17:42 -080038
Lajos Molnar1de1e252015-04-30 18:18:34 -070039#include <gui/Surface.h>
40
Chong Zhang7137ec72014-11-12 16:41:05 -080041#include "avc_utils.h"
42#include "ATSParser.h"
43
Andreas Huberf9334412010-12-15 15:17:42 -080044namespace android {
45
Lajos Molnar9fb81522016-07-14 07:33:43 -070046static float kDisplayRefreshingRate = 60.f; // TODO: get this from the display
Praveen Chavanbbaa1442016-04-08 13:33:49 -070047
48// The default total video frame rate of a stream when that info is not available from
49// the source.
50static float kDefaultVideoFrameRateTotal = 30.f;
51
Andy Hung288da022015-05-31 22:55:59 -070052static inline bool getAudioDeepBufferSetting() {
53 return property_get_bool("media.stagefright.audio.deep", false /* default_value */);
54}
55
Andreas Huberf9334412010-12-15 15:17:42 -080056NuPlayer::Decoder::Decoder(
Glenn Kasten11731182011-02-08 17:26:17 -080057 const sp<AMessage> &notify,
Wei Jiac6cfd702014-11-11 16:33:20 -080058 const sp<Source> &source,
Ronghua Wu68845c12015-07-21 09:50:48 -070059 pid_t pid,
Wei Jiac6cfd702014-11-11 16:33:20 -080060 const sp<Renderer> &renderer,
Lajos Molnar1de1e252015-04-30 18:18:34 -070061 const sp<Surface> &surface,
Chong Zhang7137ec72014-11-12 16:41:05 -080062 const sp<CCDecoder> &ccDecoder)
Andy Hung202bce12014-12-03 11:47:36 -080063 : DecoderBase(notify),
Lajos Molnar1de1e252015-04-30 18:18:34 -070064 mSurface(surface),
Wei Jiac6cfd702014-11-11 16:33:20 -080065 mSource(source),
66 mRenderer(renderer),
Chong Zhang7137ec72014-11-12 16:41:05 -080067 mCCDecoder(ccDecoder),
Ronghua Wu68845c12015-07-21 09:50:48 -070068 mPid(pid),
Wei Jiac6cfd702014-11-11 16:33:20 -080069 mSkipRenderingUntilMediaTimeUs(-1ll),
Chong Zhang7137ec72014-11-12 16:41:05 -080070 mNumFramesTotal(0ll),
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070071 mNumInputFramesDropped(0ll),
72 mNumOutputFramesDropped(0ll),
73 mVideoWidth(0),
74 mVideoHeight(0),
Chong Zhang7137ec72014-11-12 16:41:05 -080075 mIsAudio(true),
76 mIsVideoAVC(false),
77 mIsSecure(false),
78 mFormatChangePending(false),
Chong Zhang66704af2015-03-03 19:32:35 -080079 mTimeChangePending(false),
Praveen Chavanbbaa1442016-04-08 13:33:49 -070080 mFrameRateTotal(kDefaultVideoFrameRateTotal),
81 mPlaybackSpeed(1.0f),
Lajos Molnar9fb81522016-07-14 07:33:43 -070082 mNumVideoTemporalLayerTotal(1), // decode all layers
Praveen Chavanbbaa1442016-04-08 13:33:49 -070083 mNumVideoTemporalLayerAllowed(1),
84 mCurrentMaxVideoTemporalLayerId(0),
Chong Zhangf8d71772014-11-26 15:08:34 -080085 mResumePending(false),
Lajos Molnar1cd13982014-01-17 15:12:51 -080086 mComponentName("decoder") {
Lajos Molnar1cd13982014-01-17 15:12:51 -080087 mCodecLooper = new ALooper;
Marco Nelissen9e2b7912014-08-18 16:13:03 -070088 mCodecLooper->setName("NPDecoder-CL");
Lajos Molnar1cd13982014-01-17 15:12:51 -080089 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
Praveen Chavanbbaa1442016-04-08 13:33:49 -070090 mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
Andreas Huberf9334412010-12-15 15:17:42 -080091}
92
93NuPlayer::Decoder::~Decoder() {
Ronghua Wufaeb0f22015-05-21 12:20:21 -070094 mCodec->release();
Wei Jia4923cee2014-09-24 14:25:19 -070095 releaseAndResetMediaBuffers();
Andreas Huberf9334412010-12-15 15:17:42 -080096}
97
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070098sp<AMessage> NuPlayer::Decoder::getStats() const {
99 mStats->setInt64("frames-total", mNumFramesTotal);
100 mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
101 mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
102 return mStats;
Lajos Molnar09524832014-07-17 14:29:51 -0700103}
104
Lajos Molnara81c6222015-07-10 19:17:45 -0700105status_t NuPlayer::Decoder::setVideoSurface(const sp<Surface> &surface) {
106 if (surface == NULL || ADebug::isExperimentEnabled("legacy-setsurface")) {
107 return BAD_VALUE;
108 }
109
110 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
111
112 msg->setObject("surface", surface);
113 sp<AMessage> response;
114 status_t err = msg->postAndAwaitResponse(&response);
115 if (err == OK && response != NULL) {
116 CHECK(response->findInt32("err", &err));
117 }
118 return err;
119}
120
Chong Zhang7137ec72014-11-12 16:41:05 -0800121void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
122 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
123
124 switch (msg->what()) {
125 case kWhatCodecNotify:
126 {
Chong Zhang3b032b32015-04-17 15:49:06 -0700127 int32_t cbID;
128 CHECK(msg->findInt32("callbackID", &cbID));
129
130 ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
131 mIsAudio ? "audio" : "video", cbID, mPaused);
132
Marco Nelissen421f47c2015-03-25 14:40:32 -0700133 if (mPaused) {
134 break;
Chong Zhang7137ec72014-11-12 16:41:05 -0800135 }
136
Marco Nelissen421f47c2015-03-25 14:40:32 -0700137 switch (cbID) {
138 case MediaCodec::CB_INPUT_AVAILABLE:
139 {
140 int32_t index;
141 CHECK(msg->findInt32("index", &index));
142
143 handleAnInputBuffer(index);
144 break;
145 }
146
147 case MediaCodec::CB_OUTPUT_AVAILABLE:
148 {
149 int32_t index;
150 size_t offset;
151 size_t size;
152 int64_t timeUs;
153 int32_t flags;
154
155 CHECK(msg->findInt32("index", &index));
156 CHECK(msg->findSize("offset", &offset));
157 CHECK(msg->findSize("size", &size));
158 CHECK(msg->findInt64("timeUs", &timeUs));
159 CHECK(msg->findInt32("flags", &flags));
160
161 handleAnOutputBuffer(index, offset, size, timeUs, flags);
162 break;
163 }
164
165 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED:
166 {
167 sp<AMessage> format;
168 CHECK(msg->findMessage("format", &format));
169
170 handleOutputFormatChange(format);
171 break;
172 }
173
174 case MediaCodec::CB_ERROR:
175 {
176 status_t err;
177 CHECK(msg->findInt32("err", &err));
178 ALOGE("Decoder (%s) reported error : 0x%x",
179 mIsAudio ? "audio" : "video", err);
180
181 handleError(err);
182 break;
183 }
184
185 default:
186 {
187 TRESPASS();
188 break;
189 }
190 }
191
Lajos Molnar87603c02014-08-20 19:25:30 -0700192 break;
193 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800194
195 case kWhatRenderBuffer:
196 {
197 if (!isStaleReply(msg)) {
198 onRenderBuffer(msg);
199 }
200 break;
201 }
202
Lajos Molnara81c6222015-07-10 19:17:45 -0700203 case kWhatSetVideoSurface:
204 {
205 sp<AReplyToken> replyID;
206 CHECK(msg->senderAwaitsResponse(&replyID));
207
208 sp<RefBase> obj;
209 CHECK(msg->findObject("surface", &obj));
210 sp<Surface> surface = static_cast<Surface *>(obj.get()); // non-null
211 int32_t err = INVALID_OPERATION;
212 // NOTE: in practice mSurface is always non-null, but checking here for completeness
213 if (mCodec != NULL && mSurface != NULL) {
214 // TODO: once AwesomePlayer is removed, remove this automatic connecting
215 // to the surface by MediaPlayerService.
216 //
217 // at this point MediaPlayerService::client has already connected to the
218 // surface, which MediaCodec does not expect
219 err = native_window_api_disconnect(surface.get(), NATIVE_WINDOW_API_MEDIA);
220 if (err == OK) {
221 err = mCodec->setSurface(surface);
222 ALOGI_IF(err, "codec setSurface returned: %d", err);
223 if (err == OK) {
224 // reconnect to the old surface as MPS::Client will expect to
225 // be able to disconnect from it.
226 (void)native_window_api_connect(mSurface.get(), NATIVE_WINDOW_API_MEDIA);
227 mSurface = surface;
228 }
229 }
230 if (err != OK) {
231 // reconnect to the new surface on error as MPS::Client will expect to
232 // be able to disconnect from it.
233 (void)native_window_api_connect(surface.get(), NATIVE_WINDOW_API_MEDIA);
234 }
235 }
236
237 sp<AMessage> response = new AMessage;
238 response->setInt32("err", err);
239 response->postReply(replyID);
240 break;
241 }
242
Chong Zhang7137ec72014-11-12 16:41:05 -0800243 default:
244 DecoderBase::onMessageReceived(msg);
245 break;
Lajos Molnar87603c02014-08-20 19:25:30 -0700246 }
247}
248
Lajos Molnar1cd13982014-01-17 15:12:51 -0800249void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
Andreas Huberf9334412010-12-15 15:17:42 -0800250 CHECK(mCodec == NULL);
Andreas Huberf9334412010-12-15 15:17:42 -0800251
Chong Zhang7137ec72014-11-12 16:41:05 -0800252 mFormatChangePending = false;
Chong Zhang66704af2015-03-03 19:32:35 -0800253 mTimeChangePending = false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800254
Lajos Molnar1cd13982014-01-17 15:12:51 -0800255 ++mBufferGeneration;
256
Andreas Huber84066782011-08-16 09:34:26 -0700257 AString mime;
258 CHECK(format->findString("mime", &mime));
Andreas Huberf9334412010-12-15 15:17:42 -0800259
Chong Zhang7137ec72014-11-12 16:41:05 -0800260 mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
261 mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
262
Lajos Molnar1cd13982014-01-17 15:12:51 -0800263 mComponentName = mime;
264 mComponentName.append(" decoder");
Lajos Molnar1de1e252015-04-30 18:18:34 -0700265 ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), mSurface.get());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800266
Ronghua Wu68845c12015-07-21 09:50:48 -0700267 mCodec = MediaCodec::CreateByType(
268 mCodecLooper, mime.c_str(), false /* encoder */, NULL /* err */, mPid);
Lajos Molnar09524832014-07-17 14:29:51 -0700269 int32_t secure = 0;
270 if (format->findInt32("secure", &secure) && secure != 0) {
271 if (mCodec != NULL) {
272 mCodec->getName(&mComponentName);
273 mComponentName.append(".secure");
274 mCodec->release();
275 ALOGI("[%s] creating", mComponentName.c_str());
276 mCodec = MediaCodec::CreateByComponentName(
Ronghua Wu68845c12015-07-21 09:50:48 -0700277 mCodecLooper, mComponentName.c_str(), NULL /* err */, mPid);
Lajos Molnar09524832014-07-17 14:29:51 -0700278 }
279 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800280 if (mCodec == NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700281 ALOGE("Failed to create %s%s decoder",
282 (secure ? "secure " : ""), mime.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800283 handleError(UNKNOWN_ERROR);
284 return;
285 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800286 mIsSecure = secure;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800287
288 mCodec->getName(&mComponentName);
289
Lajos Molnar14986f62014-09-15 11:04:44 -0700290 status_t err;
Lajos Molnar1de1e252015-04-30 18:18:34 -0700291 if (mSurface != NULL) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800292 // disconnect from surface as MediaCodec will reconnect
Lajos Molnar14986f62014-09-15 11:04:44 -0700293 err = native_window_api_disconnect(
Lajos Molnar1de1e252015-04-30 18:18:34 -0700294 mSurface.get(), NATIVE_WINDOW_API_MEDIA);
Lajos Molnar14986f62014-09-15 11:04:44 -0700295 // We treat this as a warning, as this is a preparatory step.
296 // Codec will try to connect to the surface, which is where
297 // any error signaling will occur.
298 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800299 }
Lajos Molnar14986f62014-09-15 11:04:44 -0700300 err = mCodec->configure(
Lajos Molnar1de1e252015-04-30 18:18:34 -0700301 format, mSurface, NULL /* crypto */, 0 /* flags */);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800302 if (err != OK) {
303 ALOGE("Failed to configure %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700304 mCodec->release();
305 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800306 handleError(err);
307 return;
308 }
Lajos Molnar87603c02014-08-20 19:25:30 -0700309 rememberCodecSpecificData(format);
310
Lajos Molnar1cd13982014-01-17 15:12:51 -0800311 // the following should work in configured state
312 CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
313 CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
314
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700315 mStats->setString("mime", mime.c_str());
316 mStats->setString("component-name", mComponentName.c_str());
317
318 if (!mIsAudio) {
319 int32_t width, height;
320 if (mOutputFormat->findInt32("width", &width)
321 && mOutputFormat->findInt32("height", &height)) {
322 mStats->setInt32("width", width);
323 mStats->setInt32("height", height);
324 }
325 }
326
Marco Nelissen421f47c2015-03-25 14:40:32 -0700327 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
328 mCodec->setCallback(reply);
329
Lajos Molnar1cd13982014-01-17 15:12:51 -0800330 err = mCodec->start();
331 if (err != OK) {
332 ALOGE("Failed to start %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700333 mCodec->release();
334 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800335 handleError(err);
336 return;
Andreas Huberf9334412010-12-15 15:17:42 -0800337 }
338
Lajos Molnar09524832014-07-17 14:29:51 -0700339 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700340
Wei Jia704e7262014-06-04 16:21:56 -0700341 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800342 mResumePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800343}
Andreas Huber078cfcf2011-09-15 12:25:04 -0700344
Ronghua Wu8db88132015-04-22 13:51:35 -0700345void NuPlayer::Decoder::onSetParameters(const sp<AMessage> &params) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700346 bool needAdjustLayers = false;
347 float frameRateTotal;
348 if (params->findFloat("frame-rate-total", &frameRateTotal)
349 && mFrameRateTotal != frameRateTotal) {
350 needAdjustLayers = true;
351 mFrameRateTotal = frameRateTotal;
Ronghua Wu8db88132015-04-22 13:51:35 -0700352 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700353
354 int32_t numVideoTemporalLayerTotal;
355 if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
Lajos Molnar9fb81522016-07-14 07:33:43 -0700356 && numVideoTemporalLayerTotal >= 0
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700357 && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
358 && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
359 needAdjustLayers = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700360 mNumVideoTemporalLayerTotal = std::max(numVideoTemporalLayerTotal, 1);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700361 }
362
Lajos Molnar9fb81522016-07-14 07:33:43 -0700363 if (needAdjustLayers && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700364 // TODO: For now, layer fps is calculated for some specific architectures.
365 // But it really should be extracted from the stream.
366 mVideoTemporalLayerAggregateFps[0] =
367 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - 1));
368 for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
369 mVideoTemporalLayerAggregateFps[i] =
370 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - i))
371 + mVideoTemporalLayerAggregateFps[i - 1];
372 }
373 }
374
375 float playbackSpeed;
376 if (params->findFloat("playback-speed", &playbackSpeed)
377 && mPlaybackSpeed != playbackSpeed) {
378 needAdjustLayers = true;
379 mPlaybackSpeed = playbackSpeed;
380 }
381
382 if (needAdjustLayers) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700383 float decodeFrameRate = mFrameRateTotal;
384 // enable temporal layering optimization only if we know the layering depth
385 if (mNumVideoTemporalLayerTotal > 1) {
386 int32_t layerId;
387 for (layerId = 0; layerId < mNumVideoTemporalLayerTotal - 1; ++layerId) {
388 if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
389 >= kDisplayRefreshingRate * 0.9) {
390 break;
391 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700392 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700393 mNumVideoTemporalLayerAllowed = layerId + 1;
394 decodeFrameRate = mVideoTemporalLayerAggregateFps[layerId];
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700395 }
Lajos Molnar9fb81522016-07-14 07:33:43 -0700396 ALOGV("onSetParameters: allowed layers=%d, decodeFps=%g",
397 mNumVideoTemporalLayerAllowed, decodeFrameRate);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700398
399 if (mCodec == NULL) {
400 ALOGW("onSetParameters called before codec is created.");
401 return;
402 }
403
404 sp<AMessage> codecParams = new AMessage();
Lajos Molnar9fb81522016-07-14 07:33:43 -0700405 codecParams->setFloat("operating-rate", decodeFrameRate * mPlaybackSpeed);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700406 mCodec->setParameters(codecParams);
407 }
Ronghua Wu8db88132015-04-22 13:51:35 -0700408}
409
Chong Zhang7137ec72014-11-12 16:41:05 -0800410void NuPlayer::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
411 bool hadNoRenderer = (mRenderer == NULL);
412 mRenderer = renderer;
413 if (hadNoRenderer && mRenderer != NULL) {
Lajos Molnare6109e22015-04-10 17:18:22 -0700414 // this means that the widevine legacy source is ready
415 onRequestInputBuffers();
Chong Zhang7137ec72014-11-12 16:41:05 -0800416 }
417}
418
419void NuPlayer::Decoder::onGetInputBuffers(
420 Vector<sp<ABuffer> > *dstBuffers) {
Lajos Molnare6109e22015-04-10 17:18:22 -0700421 CHECK_EQ((status_t)OK, mCodec->getWidevineLegacyBuffers(dstBuffers));
Chong Zhang7137ec72014-11-12 16:41:05 -0800422}
423
Chong Zhangf8d71772014-11-26 15:08:34 -0800424void NuPlayer::Decoder::onResume(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800425 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800426
427 if (notifyComplete) {
428 mResumePending = true;
429 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700430 mCodec->start();
Chong Zhang7137ec72014-11-12 16:41:05 -0800431}
432
Chong Zhang66704af2015-03-03 19:32:35 -0800433void NuPlayer::Decoder::doFlush(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800434 if (mCCDecoder != NULL) {
435 mCCDecoder->flush();
436 }
437
438 if (mRenderer != NULL) {
439 mRenderer->flush(mIsAudio, notifyComplete);
440 mRenderer->signalTimeDiscontinuity();
441 }
442
443 status_t err = OK;
444 if (mCodec != NULL) {
445 err = mCodec->flush();
446 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
447 ++mBufferGeneration;
448 }
449
450 if (err != OK) {
451 ALOGE("failed to flush %s (err=%d)", mComponentName.c_str(), err);
452 handleError(err);
453 // finish with posting kWhatFlushCompleted.
454 // we attempt to release the buffers even if flush fails.
455 }
456 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700457 mPaused = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800458}
Chong Zhang7137ec72014-11-12 16:41:05 -0800459
Marco Nelissen421f47c2015-03-25 14:40:32 -0700460
Chong Zhang66704af2015-03-03 19:32:35 -0800461void NuPlayer::Decoder::onFlush() {
462 doFlush(true);
463
464 if (isDiscontinuityPending()) {
465 // This could happen if the client starts seeking/shutdown
466 // after we queued an EOS for discontinuities.
467 // We can consider discontinuity handled.
468 finishHandleDiscontinuity(false /* flushOnTimeChange */);
Chong Zhang7137ec72014-11-12 16:41:05 -0800469 }
Chong Zhang66704af2015-03-03 19:32:35 -0800470
471 sp<AMessage> notify = mNotify->dup();
472 notify->setInt32("what", kWhatFlushCompleted);
473 notify->post();
Chong Zhang7137ec72014-11-12 16:41:05 -0800474}
475
476void NuPlayer::Decoder::onShutdown(bool notifyComplete) {
477 status_t err = OK;
Chong Zhangf8d71772014-11-26 15:08:34 -0800478
479 // if there is a pending resume request, notify complete now
480 notifyResumeCompleteIfNecessary();
481
Chong Zhang7137ec72014-11-12 16:41:05 -0800482 if (mCodec != NULL) {
483 err = mCodec->release();
484 mCodec = NULL;
485 ++mBufferGeneration;
486
Lajos Molnar1de1e252015-04-30 18:18:34 -0700487 if (mSurface != NULL) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800488 // reconnect to surface as MediaCodec disconnected from it
489 status_t error =
Lajos Molnar1de1e252015-04-30 18:18:34 -0700490 native_window_api_connect(mSurface.get(), NATIVE_WINDOW_API_MEDIA);
Chong Zhang7137ec72014-11-12 16:41:05 -0800491 ALOGW_IF(error != NO_ERROR,
492 "[%s] failed to connect to native window, error=%d",
493 mComponentName.c_str(), error);
494 }
495 mComponentName = "decoder";
496 }
497
498 releaseAndResetMediaBuffers();
499
500 if (err != OK) {
501 ALOGE("failed to release %s (err=%d)", mComponentName.c_str(), err);
502 handleError(err);
503 // finish with posting kWhatShutdownCompleted.
504 }
505
506 if (notifyComplete) {
507 sp<AMessage> notify = mNotify->dup();
508 notify->setInt32("what", kWhatShutdownCompleted);
509 notify->post();
510 mPaused = true;
511 }
512}
513
Chong Zhang3b032b32015-04-17 15:49:06 -0700514/*
515 * returns true if we should request more data
516 */
517bool NuPlayer::Decoder::doRequestBuffers() {
Lajos Molnare6109e22015-04-10 17:18:22 -0700518 // mRenderer is only NULL if we have a legacy widevine source that
519 // is not yet ready. In this case we must not fetch input.
520 if (isDiscontinuityPending() || mRenderer == NULL) {
Chong Zhang3b032b32015-04-17 15:49:06 -0700521 return false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800522 }
523 status_t err = OK;
Chong Zhang66704af2015-03-03 19:32:35 -0800524 while (err == OK && !mDequeuedInputBuffers.empty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800525 size_t bufferIx = *mDequeuedInputBuffers.begin();
526 sp<AMessage> msg = new AMessage();
527 msg->setSize("buffer-ix", bufferIx);
528 err = fetchInputData(msg);
Chong Zhang66704af2015-03-03 19:32:35 -0800529 if (err != OK && err != ERROR_END_OF_STREAM) {
530 // if EOS, need to queue EOS buffer
Chong Zhang7137ec72014-11-12 16:41:05 -0800531 break;
532 }
533 mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
534
535 if (!mPendingInputMessages.empty()
536 || !onInputBufferFetched(msg)) {
537 mPendingInputMessages.push_back(msg);
Lajos Molnar09524832014-07-17 14:29:51 -0700538 }
539 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800540
Chong Zhang3b032b32015-04-17 15:49:06 -0700541 return err == -EWOULDBLOCK
542 && mSource->feedMoreTSData() == OK;
Lajos Molnar09524832014-07-17 14:29:51 -0700543}
544
Marco Nelissen421f47c2015-03-25 14:40:32 -0700545void NuPlayer::Decoder::handleError(int32_t err)
546{
547 // We cannot immediately release the codec due to buffers still outstanding
548 // in the renderer. We signal to the player the error so it can shutdown/release the
549 // decoder after flushing and increment the generation to discard unnecessary messages.
550
551 ++mBufferGeneration;
552
553 sp<AMessage> notify = mNotify->dup();
554 notify->setInt32("what", kWhatError);
555 notify->setInt32("err", err);
556 notify->post();
557}
558
559bool NuPlayer::Decoder::handleAnInputBuffer(size_t index) {
Chong Zhang66704af2015-03-03 19:32:35 -0800560 if (isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800561 return false;
562 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700563
564 sp<ABuffer> buffer;
565 mCodec->getInputBuffer(index, &buffer);
566
Wei Jia6301a5e2015-05-13 13:15:18 -0700567 if (buffer == NULL) {
568 handleError(UNKNOWN_ERROR);
569 return false;
570 }
571
Marco Nelissen421f47c2015-03-25 14:40:32 -0700572 if (index >= mInputBuffers.size()) {
573 for (size_t i = mInputBuffers.size(); i <= index; ++i) {
574 mInputBuffers.add();
575 mMediaBuffers.add();
576 mInputBufferIsDequeued.add();
577 mMediaBuffers.editItemAt(i) = NULL;
578 mInputBufferIsDequeued.editItemAt(i) = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800579 }
Andreas Huber078cfcf2011-09-15 12:25:04 -0700580 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700581 mInputBuffers.editItemAt(index) = buffer;
Andreas Huber078cfcf2011-09-15 12:25:04 -0700582
Marco Nelissen421f47c2015-03-25 14:40:32 -0700583 //CHECK_LT(bufferIx, mInputBuffers.size());
Andreas Huberf9334412010-12-15 15:17:42 -0800584
Marco Nelissen421f47c2015-03-25 14:40:32 -0700585 if (mMediaBuffers[index] != NULL) {
586 mMediaBuffers[index]->release();
587 mMediaBuffers.editItemAt(index) = NULL;
Lajos Molnar09524832014-07-17 14:29:51 -0700588 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700589 mInputBufferIsDequeued.editItemAt(index) = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700590
Lajos Molnar87603c02014-08-20 19:25:30 -0700591 if (!mCSDsToSubmit.isEmpty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800592 sp<AMessage> msg = new AMessage();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700593 msg->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800594
Lajos Molnar87603c02014-08-20 19:25:30 -0700595 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
596 ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
Chong Zhang7137ec72014-11-12 16:41:05 -0800597 msg->setBuffer("buffer", buffer);
Lajos Molnar87603c02014-08-20 19:25:30 -0700598 mCSDsToSubmit.removeAt(0);
Wei Jia56097a82016-01-07 16:03:03 -0800599 if (!onInputBufferFetched(msg)) {
600 handleError(UNKNOWN_ERROR);
601 return false;
602 }
Wei Jia2245fc62014-10-02 15:12:25 -0700603 return true;
604 }
605
606 while (!mPendingInputMessages.empty()) {
607 sp<AMessage> msg = *mPendingInputMessages.begin();
Chong Zhang7137ec72014-11-12 16:41:05 -0800608 if (!onInputBufferFetched(msg)) {
Wei Jia2245fc62014-10-02 15:12:25 -0700609 break;
610 }
611 mPendingInputMessages.erase(mPendingInputMessages.begin());
612 }
613
Marco Nelissen421f47c2015-03-25 14:40:32 -0700614 if (!mInputBufferIsDequeued.editItemAt(index)) {
Lajos Molnar87603c02014-08-20 19:25:30 -0700615 return true;
616 }
617
Marco Nelissen421f47c2015-03-25 14:40:32 -0700618 mDequeuedInputBuffers.push_back(index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800619
620 onRequestInputBuffers();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800621 return true;
622}
623
Marco Nelissen421f47c2015-03-25 14:40:32 -0700624bool NuPlayer::Decoder::handleAnOutputBuffer(
625 size_t index,
626 size_t offset,
627 size_t size,
628 int64_t timeUs,
629 int32_t flags) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700630// CHECK_LT(bufferIx, mOutputBuffers.size());
631 sp<ABuffer> buffer;
632 mCodec->getOutputBuffer(index, &buffer);
633
Santhosh Behara065e2292015-10-09 17:32:58 -0700634 if (buffer == NULL) {
635 handleError(UNKNOWN_ERROR);
636 return false;
637 }
638
Marco Nelissen421f47c2015-03-25 14:40:32 -0700639 if (index >= mOutputBuffers.size()) {
640 for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
641 mOutputBuffers.add();
642 }
643 }
644
645 mOutputBuffers.editItemAt(index) = buffer;
646
Chong Zhang7137ec72014-11-12 16:41:05 -0800647 buffer->setRange(offset, size);
648 buffer->meta()->clear();
649 buffer->meta()->setInt64("timeUs", timeUs);
Chong Zhang66704af2015-03-03 19:32:35 -0800650
651 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
Chong Zhang7137ec72014-11-12 16:41:05 -0800652 // we do not expect CODECCONFIG or SYNCFRAME for decoder
653
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800654 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700655 reply->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800656 reply->setInt32("generation", mBufferGeneration);
657
Chong Zhang66704af2015-03-03 19:32:35 -0800658 if (eos) {
659 ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
660
661 buffer->meta()->setInt32("eos", true);
662 reply->setInt32("eos", true);
663 } else if (mSkipRenderingUntilMediaTimeUs >= 0) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800664 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
665 ALOGV("[%s] dropping buffer at time %lld as requested.",
666 mComponentName.c_str(), (long long)timeUs);
667
668 reply->post();
669 return true;
670 }
671
672 mSkipRenderingUntilMediaTimeUs = -1;
673 }
674
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700675 mNumFramesTotal += !mIsAudio;
676
Chong Zhangf8d71772014-11-26 15:08:34 -0800677 // wait until 1st frame comes out to signal resume complete
678 notifyResumeCompleteIfNecessary();
679
Chong Zhang7137ec72014-11-12 16:41:05 -0800680 if (mRenderer != NULL) {
681 // send the buffer to renderer.
682 mRenderer->queueBuffer(mIsAudio, buffer, reply);
Chong Zhang66704af2015-03-03 19:32:35 -0800683 if (eos && !isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800684 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
685 }
686 }
687
688 return true;
689}
690
Marco Nelissen421f47c2015-03-25 14:40:32 -0700691void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
692 if (!mIsAudio) {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700693 int32_t width, height;
694 if (format->findInt32("width", &width)
695 && format->findInt32("height", &height)) {
696 mStats->setInt32("width", width);
697 mStats->setInt32("height", height);
698 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700699 sp<AMessage> notify = mNotify->dup();
700 notify->setInt32("what", kWhatVideoSizeChanged);
701 notify->setMessage("format", format);
702 notify->post();
703 } else if (mRenderer != NULL) {
704 uint32_t flags;
705 int64_t durationUs;
706 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
Andy Hung288da022015-05-31 22:55:59 -0700707 if (getAudioDeepBufferSetting() // override regardless of source duration
708 || (!hasVideo
709 && mSource->getDuration(&durationUs) == OK
710 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700711 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
712 } else {
713 flags = AUDIO_OUTPUT_FLAG_NONE;
714 }
715
Eric Laurent216f0172015-08-20 18:40:24 -0700716 status_t err = mRenderer->openAudioSink(
Marco Nelissen421f47c2015-03-25 14:40:32 -0700717 format, false /* offloadOnly */, hasVideo, flags, NULL /* isOffloaed */);
Eric Laurent216f0172015-08-20 18:40:24 -0700718 if (err != OK) {
719 handleError(err);
720 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700721 }
722}
723
Chong Zhang7137ec72014-11-12 16:41:05 -0800724void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
725 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
726 if (mMediaBuffers[i] != NULL) {
727 mMediaBuffers[i]->release();
728 mMediaBuffers.editItemAt(i) = NULL;
729 }
730 }
731 mMediaBuffers.resize(mInputBuffers.size());
732 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
733 mMediaBuffers.editItemAt(i) = NULL;
734 }
735 mInputBufferIsDequeued.clear();
736 mInputBufferIsDequeued.resize(mInputBuffers.size());
737 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
738 mInputBufferIsDequeued.editItemAt(i) = false;
739 }
740
741 mPendingInputMessages.clear();
742 mDequeuedInputBuffers.clear();
743 mSkipRenderingUntilMediaTimeUs = -1;
744}
745
746void NuPlayer::Decoder::requestCodecNotification() {
Chong Zhang7137ec72014-11-12 16:41:05 -0800747 if (mCodec != NULL) {
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800748 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
Chong Zhang7137ec72014-11-12 16:41:05 -0800749 reply->setInt32("generation", mBufferGeneration);
750 mCodec->requestActivityNotification(reply);
751 }
752}
753
754bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
755 int32_t generation;
756 CHECK(msg->findInt32("generation", &generation));
757 return generation != mBufferGeneration;
758}
759
760status_t NuPlayer::Decoder::fetchInputData(sp<AMessage> &reply) {
761 sp<ABuffer> accessUnit;
Robert Shih59e9ca72016-10-20 13:51:42 -0700762 bool dropAccessUnit = true;
Chong Zhang7137ec72014-11-12 16:41:05 -0800763 do {
764 status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
765
766 if (err == -EWOULDBLOCK) {
767 return err;
768 } else if (err != OK) {
769 if (err == INFO_DISCONTINUITY) {
770 int32_t type;
771 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
772
773 bool formatChange =
774 (mIsAudio &&
775 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
776 || (!mIsAudio &&
777 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
778
779 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
780
781 ALOGI("%s discontinuity (format=%d, time=%d)",
782 mIsAudio ? "audio" : "video", formatChange, timeChange);
783
784 bool seamlessFormatChange = false;
785 sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
786 if (formatChange) {
787 seamlessFormatChange =
788 supportsSeamlessFormatChange(newFormat);
789 // treat seamless format change separately
790 formatChange = !seamlessFormatChange;
791 }
792
Chong Zhang66704af2015-03-03 19:32:35 -0800793 // For format or time change, return EOS to queue EOS input,
794 // then wait for EOS on output.
Chong Zhang7137ec72014-11-12 16:41:05 -0800795 if (formatChange /* not seamless */) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800796 mFormatChangePending = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800797 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800798 } else if (timeChange) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800799 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800800 mTimeChangePending = true;
801 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800802 } else if (seamlessFormatChange) {
803 // reuse existing decoder and don't flush
804 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800805 continue;
Chong Zhang7137ec72014-11-12 16:41:05 -0800806 } else {
807 // This stream is unaffected by the discontinuity
808 return -EWOULDBLOCK;
809 }
810 }
811
Chong Zhang66704af2015-03-03 19:32:35 -0800812 // reply should only be returned without a buffer set
813 // when there is an error (including EOS)
814 CHECK(err != OK);
815
Chong Zhang7137ec72014-11-12 16:41:05 -0800816 reply->setInt32("err", err);
Chong Zhang66704af2015-03-03 19:32:35 -0800817 return ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800818 }
819
Chong Zhang7137ec72014-11-12 16:41:05 -0800820 dropAccessUnit = false;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700821 if (!mIsAudio && !mIsSecure) {
822 int32_t layerId = 0;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700823 bool haveLayerId = accessUnit->meta()->findInt32("temporal-layer-id", &layerId);
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700824 if (mRenderer->getVideoLateByUs() > 100000ll
825 && mIsVideoAVC
826 && !IsAVCReferenceFrame(accessUnit)) {
827 dropAccessUnit = true;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700828 } else if (haveLayerId && mNumVideoTemporalLayerTotal > 1) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700829 // Add only one layer each time.
830 if (layerId > mCurrentMaxVideoTemporalLayerId + 1
831 || layerId >= mNumVideoTemporalLayerAllowed) {
832 dropAccessUnit = true;
833 ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
834 layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
835 mCurrentMaxVideoTemporalLayerId);
836 } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
837 mCurrentMaxVideoTemporalLayerId = layerId;
Lajos Molnar9fb81522016-07-14 07:33:43 -0700838 } else if (layerId == 0 && mNumVideoTemporalLayerTotal > 1 && IsIDR(accessUnit)) {
839 mCurrentMaxVideoTemporalLayerId = mNumVideoTemporalLayerTotal - 1;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700840 }
841 }
842 if (dropAccessUnit) {
Lajos Molnar9fb81522016-07-14 07:33:43 -0700843 if (layerId <= mCurrentMaxVideoTemporalLayerId && layerId > 0) {
844 mCurrentMaxVideoTemporalLayerId = layerId - 1;
845 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700846 ++mNumInputFramesDropped;
847 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800848 }
849 } while (dropAccessUnit);
850
851 // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
852#if 0
853 int64_t mediaTimeUs;
854 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
Chong Zhang5abbd3d2015-04-20 16:03:00 -0700855 ALOGV("[%s] feeding input buffer at media time %.3f",
Chong Zhang7137ec72014-11-12 16:41:05 -0800856 mIsAudio ? "audio" : "video",
857 mediaTimeUs / 1E6);
858#endif
859
860 if (mCCDecoder != NULL) {
861 mCCDecoder->decode(accessUnit);
862 }
863
864 reply->setBuffer("buffer", accessUnit);
865
866 return OK;
867}
868
869bool NuPlayer::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800870 size_t bufferIx;
871 CHECK(msg->findSize("buffer-ix", &bufferIx));
872 CHECK_LT(bufferIx, mInputBuffers.size());
873 sp<ABuffer> codecBuffer = mInputBuffers[bufferIx];
874
875 sp<ABuffer> buffer;
876 bool hasBuffer = msg->findBuffer("buffer", &buffer);
Lajos Molnar09524832014-07-17 14:29:51 -0700877
878 // handle widevine classic source - that fills an arbitrary input buffer
879 MediaBuffer *mediaBuffer = NULL;
Wei Jia96e92b52014-09-18 17:36:20 -0700880 if (hasBuffer) {
881 mediaBuffer = (MediaBuffer *)(buffer->getMediaBufferBase());
882 if (mediaBuffer != NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700883 // likely filled another buffer than we requested: adjust buffer index
884 size_t ix;
885 for (ix = 0; ix < mInputBuffers.size(); ix++) {
886 const sp<ABuffer> &buf = mInputBuffers[ix];
887 if (buf->data() == mediaBuffer->data()) {
888 // all input buffers are dequeued on start, hence the check
Wei Jia2245fc62014-10-02 15:12:25 -0700889 if (!mInputBufferIsDequeued[ix]) {
890 ALOGV("[%s] received MediaBuffer for #%zu instead of #%zu",
891 mComponentName.c_str(), ix, bufferIx);
892 mediaBuffer->release();
893 return false;
894 }
Lajos Molnar09524832014-07-17 14:29:51 -0700895
896 // TRICKY: need buffer for the metadata, so instead, set
897 // codecBuffer to the same (though incorrect) buffer to
898 // avoid a memcpy into the codecBuffer
899 codecBuffer = buffer;
900 codecBuffer->setRange(
901 mediaBuffer->range_offset(),
902 mediaBuffer->range_length());
903 bufferIx = ix;
904 break;
905 }
906 }
907 CHECK(ix < mInputBuffers.size());
908 }
909 }
910
Lajos Molnar1cd13982014-01-17 15:12:51 -0800911 if (buffer == NULL /* includes !hasBuffer */) {
912 int32_t streamErr = ERROR_END_OF_STREAM;
913 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
914
Chong Zhang66704af2015-03-03 19:32:35 -0800915 CHECK(streamErr != OK);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800916
917 // attempt to queue EOS
918 status_t err = mCodec->queueInputBuffer(
919 bufferIx,
920 0,
921 0,
922 0,
923 MediaCodec::BUFFER_FLAG_EOS);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700924 if (err == OK) {
925 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
926 } else if (streamErr == ERROR_END_OF_STREAM) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800927 streamErr = err;
928 // err will not be ERROR_END_OF_STREAM
929 }
930
931 if (streamErr != ERROR_END_OF_STREAM) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700932 ALOGE("Stream error for %s (err=%d), EOS %s queued",
933 mComponentName.c_str(),
934 streamErr,
935 err == OK ? "successfully" : "unsuccessfully");
Lajos Molnar1cd13982014-01-17 15:12:51 -0800936 handleError(streamErr);
937 }
938 } else {
Wei Jiac6cfd702014-11-11 16:33:20 -0800939 sp<AMessage> extra;
940 if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
941 int64_t resumeAtMediaTimeUs;
942 if (extra->findInt64(
943 "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
944 ALOGI("[%s] suppressing rendering until %lld us",
945 mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
946 mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
947 }
948 }
949
Lajos Molnar1cd13982014-01-17 15:12:51 -0800950 int64_t timeUs = 0;
951 uint32_t flags = 0;
952 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
953
Lajos Molnar87603c02014-08-20 19:25:30 -0700954 int32_t eos, csd;
955 // we do not expect SYNCFRAME for decoder
Lajos Molnar1cd13982014-01-17 15:12:51 -0800956 if (buffer->meta()->findInt32("eos", &eos) && eos) {
957 flags |= MediaCodec::BUFFER_FLAG_EOS;
Lajos Molnar87603c02014-08-20 19:25:30 -0700958 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
959 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800960 }
961
962 // copy into codec buffer
963 if (buffer != codecBuffer) {
Wei Jia56097a82016-01-07 16:03:03 -0800964 if (buffer->size() > codecBuffer->capacity()) {
965 handleError(ERROR_BUFFER_TOO_SMALL);
966 mDequeuedInputBuffers.push_back(bufferIx);
967 return false;
968 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800969 codecBuffer->setRange(0, buffer->size());
970 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
971 }
972
973 status_t err = mCodec->queueInputBuffer(
974 bufferIx,
975 codecBuffer->offset(),
976 codecBuffer->size(),
977 timeUs,
978 flags);
979 if (err != OK) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700980 if (mediaBuffer != NULL) {
981 mediaBuffer->release();
982 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800983 ALOGE("Failed to queue input buffer for %s (err=%d)",
984 mComponentName.c_str(), err);
985 handleError(err);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700986 } else {
987 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
988 if (mediaBuffer != NULL) {
989 CHECK(mMediaBuffers[bufferIx] == NULL);
990 mMediaBuffers.editItemAt(bufferIx) = mediaBuffer;
991 }
Lajos Molnar09524832014-07-17 14:29:51 -0700992 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800993 }
Wei Jia2245fc62014-10-02 15:12:25 -0700994 return true;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800995}
996
Lajos Molnar1cd13982014-01-17 15:12:51 -0800997void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
998 status_t err;
999 int32_t render;
1000 size_t bufferIx;
Chong Zhang66704af2015-03-03 19:32:35 -08001001 int32_t eos;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001002 CHECK(msg->findSize("buffer-ix", &bufferIx));
Wei Jiac6cfd702014-11-11 16:33:20 -08001003
Chong Zhang7137ec72014-11-12 16:41:05 -08001004 if (!mIsAudio) {
Wei Jiac6cfd702014-11-11 16:33:20 -08001005 int64_t timeUs;
1006 sp<ABuffer> buffer = mOutputBuffers[bufferIx];
1007 buffer->meta()->findInt64("timeUs", &timeUs);
Chong Zhang7137ec72014-11-12 16:41:05 -08001008
1009 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1010 mCCDecoder->display(timeUs);
1011 }
Wei Jiac6cfd702014-11-11 16:33:20 -08001012 }
1013
Lajos Molnar1cd13982014-01-17 15:12:51 -08001014 if (msg->findInt32("render", &render) && render) {
Lajos Molnardc43dfa2014-05-07 15:33:04 -07001015 int64_t timestampNs;
1016 CHECK(msg->findInt64("timestampNs", &timestampNs));
1017 err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001018 } else {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -07001019 mNumOutputFramesDropped += !mIsAudio;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001020 err = mCodec->releaseOutputBuffer(bufferIx);
1021 }
1022 if (err != OK) {
1023 ALOGE("failed to release output buffer for %s (err=%d)",
1024 mComponentName.c_str(), err);
1025 handleError(err);
1026 }
Chong Zhang66704af2015-03-03 19:32:35 -08001027 if (msg->findInt32("eos", &eos) && eos
1028 && isDiscontinuityPending()) {
1029 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1030 }
1031}
1032
1033bool NuPlayer::Decoder::isDiscontinuityPending() const {
1034 return mFormatChangePending || mTimeChangePending;
1035}
1036
1037void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1038 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1039 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1040
1041 // If we have format change, pause and wait to be killed;
1042 // If we have time change only, flush and restart fetching.
1043
1044 if (mFormatChangePending) {
1045 mPaused = true;
1046 } else if (mTimeChangePending) {
1047 if (flushOnTimeChange) {
Marco Nelissen421f47c2015-03-25 14:40:32 -07001048 doFlush(false /* notifyComplete */);
1049 signalResume(false /* notifyComplete */);
Chong Zhang66704af2015-03-03 19:32:35 -08001050 }
Chong Zhang66704af2015-03-03 19:32:35 -08001051 }
1052
1053 // Notify NuPlayer to either shutdown decoder, or rescan sources
1054 sp<AMessage> msg = mNotify->dup();
1055 msg->setInt32("what", kWhatInputDiscontinuity);
1056 msg->setInt32("formatChange", mFormatChangePending);
1057 msg->post();
1058
1059 mFormatChangePending = false;
1060 mTimeChangePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001061}
1062
Chong Zhang7137ec72014-11-12 16:41:05 -08001063bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
1064 const sp<AMessage> &targetFormat) const {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001065 if (targetFormat == NULL) {
1066 return true;
1067 }
1068
1069 AString mime;
1070 if (!targetFormat->findString("mime", &mime)) {
1071 return false;
1072 }
1073
1074 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1075 // field-by-field comparison
1076 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1077 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1078 int32_t oldVal, newVal;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001079 if (!mInputFormat->findInt32(keys[i], &oldVal) ||
Lajos Molnar1cd13982014-01-17 15:12:51 -08001080 !targetFormat->findInt32(keys[i], &newVal) ||
1081 oldVal != newVal) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001082 return false;
1083 }
1084 }
1085
1086 sp<ABuffer> oldBuf, newBuf;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001087 if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
Lajos Molnar1cd13982014-01-17 15:12:51 -08001088 targetFormat->findBuffer("csd-0", &newBuf)) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001089 if (oldBuf->size() != newBuf->size()) {
1090 return false;
1091 }
1092 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
1093 }
1094 }
1095 return false;
1096}
1097
1098bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
joakim johansson7abbd4c2015-01-30 14:16:03 +01001099 if (mInputFormat == NULL) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001100 return false;
1101 }
1102
1103 if (targetFormat == NULL) {
1104 return true;
1105 }
1106
1107 AString oldMime, newMime;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001108 if (!mInputFormat->findString("mime", &oldMime)
Robert Shih6d0a94e2014-01-23 16:18:22 -08001109 || !targetFormat->findString("mime", &newMime)
1110 || !(oldMime == newMime)) {
1111 return false;
1112 }
1113
1114 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1115 bool seamless;
1116 if (audio) {
1117 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1118 } else {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001119 int32_t isAdaptive;
1120 seamless = (mCodec != NULL &&
1121 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
1122 isAdaptive);
Robert Shih6d0a94e2014-01-23 16:18:22 -08001123 }
1124
1125 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1126 return seamless;
1127}
1128
Chong Zhang7137ec72014-11-12 16:41:05 -08001129void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1130 if (format == NULL) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001131 return;
1132 }
Chong Zhang7137ec72014-11-12 16:41:05 -08001133 mCSDsForCurrentFormat.clear();
1134 for (int32_t i = 0; ; ++i) {
1135 AString tag = "csd-";
1136 tag.append(i);
1137 sp<ABuffer> buffer;
1138 if (!format->findBuffer(tag.c_str(), &buffer)) {
1139 break;
1140 }
1141 mCSDsForCurrentFormat.push(buffer);
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001142 }
Chong Zhangb86e68f2014-08-01 13:46:53 -07001143}
1144
Chong Zhangf8d71772014-11-26 15:08:34 -08001145void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
1146 if (mResumePending) {
1147 mResumePending = false;
1148
1149 sp<AMessage> notify = mNotify->dup();
1150 notify->setInt32("what", kWhatResumeCompleted);
1151 notify->post();
1152 }
1153}
1154
Andreas Huberf9334412010-12-15 15:17:42 -08001155} // namespace android
1156