blob: fa19410cc738c933026211ab48fbe22695b5b077 [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
Chong Zhang7137ec72014-11-12 16:41:05 -080022#include "NuPlayerCCDecoder.h"
Andreas Huberf9334412010-12-15 15:17:42 -080023#include "NuPlayerDecoder.h"
Wei Jiac6cfd702014-11-11 16:33:20 -080024#include "NuPlayerRenderer.h"
25#include "NuPlayerSource.h"
26
Andy Hung288da022015-05-31 22:55:59 -070027#include <cutils/properties.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080028#include <media/ICrypto.h>
Andreas Huberf9334412010-12-15 15:17:42 -080029#include <media/stagefright/foundation/ABuffer.h>
30#include <media/stagefright/foundation/ADebug.h>
Andreas Huber5bc087c2010-12-23 10:27:40 -080031#include <media/stagefright/foundation/AMessage.h>
Lajos Molnar09524832014-07-17 14:29:51 -070032#include <media/stagefright/MediaBuffer.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080033#include <media/stagefright/MediaCodec.h>
Andreas Huberf9334412010-12-15 15:17:42 -080034#include <media/stagefright/MediaDefs.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080035#include <media/stagefright/MediaErrors.h>
Andreas Huberf9334412010-12-15 15:17:42 -080036
Lajos Molnar1de1e252015-04-30 18:18:34 -070037#include <gui/Surface.h>
38
Chong Zhang7137ec72014-11-12 16:41:05 -080039#include "avc_utils.h"
40#include "ATSParser.h"
41
Andreas Huberf9334412010-12-15 15:17:42 -080042namespace android {
43
Praveen Chavanbbaa1442016-04-08 13:33:49 -070044static float kDisplayRefreshingRate = 60.f;
45
46// The default total video frame rate of a stream when that info is not available from
47// the source.
48static float kDefaultVideoFrameRateTotal = 30.f;
49
Andy Hung288da022015-05-31 22:55:59 -070050static inline bool getAudioDeepBufferSetting() {
51 return property_get_bool("media.stagefright.audio.deep", false /* default_value */);
52}
53
Andreas Huberf9334412010-12-15 15:17:42 -080054NuPlayer::Decoder::Decoder(
Glenn Kasten11731182011-02-08 17:26:17 -080055 const sp<AMessage> &notify,
Wei Jiac6cfd702014-11-11 16:33:20 -080056 const sp<Source> &source,
Ronghua Wu68845c12015-07-21 09:50:48 -070057 pid_t pid,
Wei Jiac6cfd702014-11-11 16:33:20 -080058 const sp<Renderer> &renderer,
Lajos Molnar1de1e252015-04-30 18:18:34 -070059 const sp<Surface> &surface,
Chong Zhang7137ec72014-11-12 16:41:05 -080060 const sp<CCDecoder> &ccDecoder)
Andy Hung202bce12014-12-03 11:47:36 -080061 : DecoderBase(notify),
Lajos Molnar1de1e252015-04-30 18:18:34 -070062 mSurface(surface),
Wei Jiac6cfd702014-11-11 16:33:20 -080063 mSource(source),
64 mRenderer(renderer),
Chong Zhang7137ec72014-11-12 16:41:05 -080065 mCCDecoder(ccDecoder),
Ronghua Wu68845c12015-07-21 09:50:48 -070066 mPid(pid),
Wei Jiac6cfd702014-11-11 16:33:20 -080067 mSkipRenderingUntilMediaTimeUs(-1ll),
Chong Zhang7137ec72014-11-12 16:41:05 -080068 mNumFramesTotal(0ll),
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070069 mNumInputFramesDropped(0ll),
70 mNumOutputFramesDropped(0ll),
71 mVideoWidth(0),
72 mVideoHeight(0),
Chong Zhang7137ec72014-11-12 16:41:05 -080073 mIsAudio(true),
74 mIsVideoAVC(false),
75 mIsSecure(false),
76 mFormatChangePending(false),
Chong Zhang66704af2015-03-03 19:32:35 -080077 mTimeChangePending(false),
Praveen Chavanbbaa1442016-04-08 13:33:49 -070078 mFrameRateTotal(kDefaultVideoFrameRateTotal),
79 mPlaybackSpeed(1.0f),
80 mNumVideoTemporalLayerTotal(1),
81 mNumVideoTemporalLayerAllowed(1),
82 mCurrentMaxVideoTemporalLayerId(0),
Chong Zhangf8d71772014-11-26 15:08:34 -080083 mResumePending(false),
Lajos Molnar1cd13982014-01-17 15:12:51 -080084 mComponentName("decoder") {
Lajos Molnar1cd13982014-01-17 15:12:51 -080085 mCodecLooper = new ALooper;
Marco Nelissen9e2b7912014-08-18 16:13:03 -070086 mCodecLooper->setName("NPDecoder-CL");
Lajos Molnar1cd13982014-01-17 15:12:51 -080087 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
Praveen Chavanbbaa1442016-04-08 13:33:49 -070088 mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
Andreas Huberf9334412010-12-15 15:17:42 -080089}
90
91NuPlayer::Decoder::~Decoder() {
Ronghua Wufaeb0f22015-05-21 12:20:21 -070092 mCodec->release();
Wei Jia4923cee2014-09-24 14:25:19 -070093 releaseAndResetMediaBuffers();
Andreas Huberf9334412010-12-15 15:17:42 -080094}
95
Praveen Chavane1e5d7a2015-05-19 19:09:48 -070096sp<AMessage> NuPlayer::Decoder::getStats() const {
97 mStats->setInt64("frames-total", mNumFramesTotal);
98 mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
99 mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
100 return mStats;
Lajos Molnar09524832014-07-17 14:29:51 -0700101}
102
Lajos Molnara81c6222015-07-10 19:17:45 -0700103status_t NuPlayer::Decoder::setVideoSurface(const sp<Surface> &surface) {
104 if (surface == NULL || ADebug::isExperimentEnabled("legacy-setsurface")) {
105 return BAD_VALUE;
106 }
107
108 sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
109
110 msg->setObject("surface", surface);
111 sp<AMessage> response;
112 status_t err = msg->postAndAwaitResponse(&response);
113 if (err == OK && response != NULL) {
114 CHECK(response->findInt32("err", &err));
115 }
116 return err;
117}
118
Chong Zhang7137ec72014-11-12 16:41:05 -0800119void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
120 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
121
122 switch (msg->what()) {
123 case kWhatCodecNotify:
124 {
Chong Zhang3b032b32015-04-17 15:49:06 -0700125 int32_t cbID;
126 CHECK(msg->findInt32("callbackID", &cbID));
127
128 ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
129 mIsAudio ? "audio" : "video", cbID, mPaused);
130
Marco Nelissen421f47c2015-03-25 14:40:32 -0700131 if (mPaused) {
132 break;
Chong Zhang7137ec72014-11-12 16:41:05 -0800133 }
134
Marco Nelissen421f47c2015-03-25 14:40:32 -0700135 switch (cbID) {
136 case MediaCodec::CB_INPUT_AVAILABLE:
137 {
138 int32_t index;
139 CHECK(msg->findInt32("index", &index));
140
141 handleAnInputBuffer(index);
142 break;
143 }
144
145 case MediaCodec::CB_OUTPUT_AVAILABLE:
146 {
147 int32_t index;
148 size_t offset;
149 size_t size;
150 int64_t timeUs;
151 int32_t flags;
152
153 CHECK(msg->findInt32("index", &index));
154 CHECK(msg->findSize("offset", &offset));
155 CHECK(msg->findSize("size", &size));
156 CHECK(msg->findInt64("timeUs", &timeUs));
157 CHECK(msg->findInt32("flags", &flags));
158
159 handleAnOutputBuffer(index, offset, size, timeUs, flags);
160 break;
161 }
162
163 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED:
164 {
165 sp<AMessage> format;
166 CHECK(msg->findMessage("format", &format));
167
168 handleOutputFormatChange(format);
169 break;
170 }
171
172 case MediaCodec::CB_ERROR:
173 {
174 status_t err;
175 CHECK(msg->findInt32("err", &err));
176 ALOGE("Decoder (%s) reported error : 0x%x",
177 mIsAudio ? "audio" : "video", err);
178
179 handleError(err);
180 break;
181 }
182
183 default:
184 {
185 TRESPASS();
186 break;
187 }
188 }
189
Lajos Molnar87603c02014-08-20 19:25:30 -0700190 break;
191 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800192
193 case kWhatRenderBuffer:
194 {
195 if (!isStaleReply(msg)) {
196 onRenderBuffer(msg);
197 }
198 break;
199 }
200
Lajos Molnara81c6222015-07-10 19:17:45 -0700201 case kWhatSetVideoSurface:
202 {
203 sp<AReplyToken> replyID;
204 CHECK(msg->senderAwaitsResponse(&replyID));
205
206 sp<RefBase> obj;
207 CHECK(msg->findObject("surface", &obj));
208 sp<Surface> surface = static_cast<Surface *>(obj.get()); // non-null
209 int32_t err = INVALID_OPERATION;
210 // NOTE: in practice mSurface is always non-null, but checking here for completeness
211 if (mCodec != NULL && mSurface != NULL) {
212 // TODO: once AwesomePlayer is removed, remove this automatic connecting
213 // to the surface by MediaPlayerService.
214 //
215 // at this point MediaPlayerService::client has already connected to the
216 // surface, which MediaCodec does not expect
217 err = native_window_api_disconnect(surface.get(), NATIVE_WINDOW_API_MEDIA);
218 if (err == OK) {
219 err = mCodec->setSurface(surface);
220 ALOGI_IF(err, "codec setSurface returned: %d", err);
221 if (err == OK) {
222 // reconnect to the old surface as MPS::Client will expect to
223 // be able to disconnect from it.
224 (void)native_window_api_connect(mSurface.get(), NATIVE_WINDOW_API_MEDIA);
225 mSurface = surface;
226 }
227 }
228 if (err != OK) {
229 // reconnect to the new surface on error as MPS::Client will expect to
230 // be able to disconnect from it.
231 (void)native_window_api_connect(surface.get(), NATIVE_WINDOW_API_MEDIA);
232 }
233 }
234
235 sp<AMessage> response = new AMessage;
236 response->setInt32("err", err);
237 response->postReply(replyID);
238 break;
239 }
240
Chong Zhang7137ec72014-11-12 16:41:05 -0800241 default:
242 DecoderBase::onMessageReceived(msg);
243 break;
Lajos Molnar87603c02014-08-20 19:25:30 -0700244 }
245}
246
Lajos Molnar1cd13982014-01-17 15:12:51 -0800247void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
Andreas Huberf9334412010-12-15 15:17:42 -0800248 CHECK(mCodec == NULL);
Andreas Huberf9334412010-12-15 15:17:42 -0800249
Chong Zhang7137ec72014-11-12 16:41:05 -0800250 mFormatChangePending = false;
Chong Zhang66704af2015-03-03 19:32:35 -0800251 mTimeChangePending = false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800252
Lajos Molnar1cd13982014-01-17 15:12:51 -0800253 ++mBufferGeneration;
254
Andreas Huber84066782011-08-16 09:34:26 -0700255 AString mime;
256 CHECK(format->findString("mime", &mime));
Andreas Huberf9334412010-12-15 15:17:42 -0800257
Chong Zhang7137ec72014-11-12 16:41:05 -0800258 mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
259 mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
260
Lajos Molnar1cd13982014-01-17 15:12:51 -0800261 mComponentName = mime;
262 mComponentName.append(" decoder");
Lajos Molnar1de1e252015-04-30 18:18:34 -0700263 ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), mSurface.get());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800264
Ronghua Wu68845c12015-07-21 09:50:48 -0700265 mCodec = MediaCodec::CreateByType(
266 mCodecLooper, mime.c_str(), false /* encoder */, NULL /* err */, mPid);
Lajos Molnar09524832014-07-17 14:29:51 -0700267 int32_t secure = 0;
268 if (format->findInt32("secure", &secure) && secure != 0) {
269 if (mCodec != NULL) {
270 mCodec->getName(&mComponentName);
271 mComponentName.append(".secure");
272 mCodec->release();
273 ALOGI("[%s] creating", mComponentName.c_str());
274 mCodec = MediaCodec::CreateByComponentName(
Ronghua Wu68845c12015-07-21 09:50:48 -0700275 mCodecLooper, mComponentName.c_str(), NULL /* err */, mPid);
Lajos Molnar09524832014-07-17 14:29:51 -0700276 }
277 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800278 if (mCodec == NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700279 ALOGE("Failed to create %s%s decoder",
280 (secure ? "secure " : ""), mime.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800281 handleError(UNKNOWN_ERROR);
282 return;
283 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800284 mIsSecure = secure;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800285
286 mCodec->getName(&mComponentName);
287
Lajos Molnar14986f62014-09-15 11:04:44 -0700288 status_t err;
Lajos Molnar1de1e252015-04-30 18:18:34 -0700289 if (mSurface != NULL) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800290 // disconnect from surface as MediaCodec will reconnect
Lajos Molnar14986f62014-09-15 11:04:44 -0700291 err = native_window_api_disconnect(
Lajos Molnar1de1e252015-04-30 18:18:34 -0700292 mSurface.get(), NATIVE_WINDOW_API_MEDIA);
Lajos Molnar14986f62014-09-15 11:04:44 -0700293 // We treat this as a warning, as this is a preparatory step.
294 // Codec will try to connect to the surface, which is where
295 // any error signaling will occur.
296 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800297 }
Lajos Molnar14986f62014-09-15 11:04:44 -0700298 err = mCodec->configure(
Lajos Molnar1de1e252015-04-30 18:18:34 -0700299 format, mSurface, NULL /* crypto */, 0 /* flags */);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800300 if (err != OK) {
301 ALOGE("Failed to configure %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700302 mCodec->release();
303 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800304 handleError(err);
305 return;
306 }
Lajos Molnar87603c02014-08-20 19:25:30 -0700307 rememberCodecSpecificData(format);
308
Lajos Molnar1cd13982014-01-17 15:12:51 -0800309 // the following should work in configured state
310 CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
311 CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
312
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700313 mStats->setString("mime", mime.c_str());
314 mStats->setString("component-name", mComponentName.c_str());
315
316 if (!mIsAudio) {
317 int32_t width, height;
318 if (mOutputFormat->findInt32("width", &width)
319 && mOutputFormat->findInt32("height", &height)) {
320 mStats->setInt32("width", width);
321 mStats->setInt32("height", height);
322 }
323 }
324
Marco Nelissen421f47c2015-03-25 14:40:32 -0700325 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
326 mCodec->setCallback(reply);
327
Lajos Molnar1cd13982014-01-17 15:12:51 -0800328 err = mCodec->start();
329 if (err != OK) {
330 ALOGE("Failed to start %s decoder (err=%d)", mComponentName.c_str(), err);
Andy Hung2abde2c2014-09-30 14:40:32 -0700331 mCodec->release();
332 mCodec.clear();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800333 handleError(err);
334 return;
Andreas Huberf9334412010-12-15 15:17:42 -0800335 }
336
Lajos Molnar09524832014-07-17 14:29:51 -0700337 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700338
Wei Jia704e7262014-06-04 16:21:56 -0700339 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800340 mResumePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800341}
Andreas Huber078cfcf2011-09-15 12:25:04 -0700342
Ronghua Wu8db88132015-04-22 13:51:35 -0700343void NuPlayer::Decoder::onSetParameters(const sp<AMessage> &params) {
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700344 bool needAdjustLayers = false;
345 float frameRateTotal;
346 if (params->findFloat("frame-rate-total", &frameRateTotal)
347 && mFrameRateTotal != frameRateTotal) {
348 needAdjustLayers = true;
349 mFrameRateTotal = frameRateTotal;
Ronghua Wu8db88132015-04-22 13:51:35 -0700350 }
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700351
352 int32_t numVideoTemporalLayerTotal;
353 if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
354 && numVideoTemporalLayerTotal > 0
355 && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
356 && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
357 needAdjustLayers = true;
358 mNumVideoTemporalLayerTotal = numVideoTemporalLayerTotal;
359 }
360
361 if (needAdjustLayers) {
362 // TODO: For now, layer fps is calculated for some specific architectures.
363 // But it really should be extracted from the stream.
364 mVideoTemporalLayerAggregateFps[0] =
365 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - 1));
366 for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
367 mVideoTemporalLayerAggregateFps[i] =
368 mFrameRateTotal / (float)(1ll << (mNumVideoTemporalLayerTotal - i))
369 + mVideoTemporalLayerAggregateFps[i - 1];
370 }
371 }
372
373 float playbackSpeed;
374 if (params->findFloat("playback-speed", &playbackSpeed)
375 && mPlaybackSpeed != playbackSpeed) {
376 needAdjustLayers = true;
377 mPlaybackSpeed = playbackSpeed;
378 }
379
380 if (needAdjustLayers) {
381 int32_t layerId;
382 for (layerId = 0; layerId < mNumVideoTemporalLayerTotal; ++layerId) {
383 if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
384 > kDisplayRefreshingRate) {
385 --layerId;
386 break;
387 }
388 }
389 if (layerId < 0) {
390 layerId = 0;
391 } else if (layerId >= mNumVideoTemporalLayerTotal) {
392 layerId = mNumVideoTemporalLayerTotal - 1;
393 }
394 mNumVideoTemporalLayerAllowed = layerId + 1;
395 if (mCurrentMaxVideoTemporalLayerId > layerId) {
396 mCurrentMaxVideoTemporalLayerId = layerId;
397 }
398 ALOGV("onSetParameters: allowed layers=%d, current max layerId=%d",
399 mNumVideoTemporalLayerAllowed, mCurrentMaxVideoTemporalLayerId);
400
401 if (mCodec == NULL) {
402 ALOGW("onSetParameters called before codec is created.");
403 return;
404 }
405
406 sp<AMessage> codecParams = new AMessage();
407 codecParams->setFloat("operating-rate",
408 mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed);
409 mCodec->setParameters(codecParams);
410 }
Ronghua Wu8db88132015-04-22 13:51:35 -0700411}
412
Chong Zhang7137ec72014-11-12 16:41:05 -0800413void NuPlayer::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
414 bool hadNoRenderer = (mRenderer == NULL);
415 mRenderer = renderer;
416 if (hadNoRenderer && mRenderer != NULL) {
Lajos Molnare6109e22015-04-10 17:18:22 -0700417 // this means that the widevine legacy source is ready
418 onRequestInputBuffers();
Chong Zhang7137ec72014-11-12 16:41:05 -0800419 }
420}
421
422void NuPlayer::Decoder::onGetInputBuffers(
423 Vector<sp<ABuffer> > *dstBuffers) {
Lajos Molnare6109e22015-04-10 17:18:22 -0700424 CHECK_EQ((status_t)OK, mCodec->getWidevineLegacyBuffers(dstBuffers));
Chong Zhang7137ec72014-11-12 16:41:05 -0800425}
426
Chong Zhangf8d71772014-11-26 15:08:34 -0800427void NuPlayer::Decoder::onResume(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800428 mPaused = false;
Chong Zhangf8d71772014-11-26 15:08:34 -0800429
430 if (notifyComplete) {
431 mResumePending = true;
432 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700433 mCodec->start();
Chong Zhang7137ec72014-11-12 16:41:05 -0800434}
435
Chong Zhang66704af2015-03-03 19:32:35 -0800436void NuPlayer::Decoder::doFlush(bool notifyComplete) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800437 if (mCCDecoder != NULL) {
438 mCCDecoder->flush();
439 }
440
441 if (mRenderer != NULL) {
442 mRenderer->flush(mIsAudio, notifyComplete);
443 mRenderer->signalTimeDiscontinuity();
444 }
445
446 status_t err = OK;
447 if (mCodec != NULL) {
448 err = mCodec->flush();
449 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
450 ++mBufferGeneration;
451 }
452
453 if (err != OK) {
454 ALOGE("failed to flush %s (err=%d)", mComponentName.c_str(), err);
455 handleError(err);
456 // finish with posting kWhatFlushCompleted.
457 // we attempt to release the buffers even if flush fails.
458 }
459 releaseAndResetMediaBuffers();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700460 mPaused = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800461}
Chong Zhang7137ec72014-11-12 16:41:05 -0800462
Marco Nelissen421f47c2015-03-25 14:40:32 -0700463
Chong Zhang66704af2015-03-03 19:32:35 -0800464void NuPlayer::Decoder::onFlush() {
465 doFlush(true);
466
467 if (isDiscontinuityPending()) {
468 // This could happen if the client starts seeking/shutdown
469 // after we queued an EOS for discontinuities.
470 // We can consider discontinuity handled.
471 finishHandleDiscontinuity(false /* flushOnTimeChange */);
Chong Zhang7137ec72014-11-12 16:41:05 -0800472 }
Chong Zhang66704af2015-03-03 19:32:35 -0800473
474 sp<AMessage> notify = mNotify->dup();
475 notify->setInt32("what", kWhatFlushCompleted);
476 notify->post();
Chong Zhang7137ec72014-11-12 16:41:05 -0800477}
478
479void NuPlayer::Decoder::onShutdown(bool notifyComplete) {
480 status_t err = OK;
Chong Zhangf8d71772014-11-26 15:08:34 -0800481
482 // if there is a pending resume request, notify complete now
483 notifyResumeCompleteIfNecessary();
484
Chong Zhang7137ec72014-11-12 16:41:05 -0800485 if (mCodec != NULL) {
486 err = mCodec->release();
487 mCodec = NULL;
488 ++mBufferGeneration;
489
Lajos Molnar1de1e252015-04-30 18:18:34 -0700490 if (mSurface != NULL) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800491 // reconnect to surface as MediaCodec disconnected from it
492 status_t error =
Lajos Molnar1de1e252015-04-30 18:18:34 -0700493 native_window_api_connect(mSurface.get(), NATIVE_WINDOW_API_MEDIA);
Chong Zhang7137ec72014-11-12 16:41:05 -0800494 ALOGW_IF(error != NO_ERROR,
495 "[%s] failed to connect to native window, error=%d",
496 mComponentName.c_str(), error);
497 }
498 mComponentName = "decoder";
499 }
500
501 releaseAndResetMediaBuffers();
502
503 if (err != OK) {
504 ALOGE("failed to release %s (err=%d)", mComponentName.c_str(), err);
505 handleError(err);
506 // finish with posting kWhatShutdownCompleted.
507 }
508
509 if (notifyComplete) {
510 sp<AMessage> notify = mNotify->dup();
511 notify->setInt32("what", kWhatShutdownCompleted);
512 notify->post();
513 mPaused = true;
514 }
515}
516
Chong Zhang3b032b32015-04-17 15:49:06 -0700517/*
518 * returns true if we should request more data
519 */
520bool NuPlayer::Decoder::doRequestBuffers() {
Lajos Molnare6109e22015-04-10 17:18:22 -0700521 // mRenderer is only NULL if we have a legacy widevine source that
522 // is not yet ready. In this case we must not fetch input.
523 if (isDiscontinuityPending() || mRenderer == NULL) {
Chong Zhang3b032b32015-04-17 15:49:06 -0700524 return false;
Chong Zhang7137ec72014-11-12 16:41:05 -0800525 }
526 status_t err = OK;
Chong Zhang66704af2015-03-03 19:32:35 -0800527 while (err == OK && !mDequeuedInputBuffers.empty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800528 size_t bufferIx = *mDequeuedInputBuffers.begin();
529 sp<AMessage> msg = new AMessage();
530 msg->setSize("buffer-ix", bufferIx);
531 err = fetchInputData(msg);
Chong Zhang66704af2015-03-03 19:32:35 -0800532 if (err != OK && err != ERROR_END_OF_STREAM) {
533 // if EOS, need to queue EOS buffer
Chong Zhang7137ec72014-11-12 16:41:05 -0800534 break;
535 }
536 mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
537
538 if (!mPendingInputMessages.empty()
539 || !onInputBufferFetched(msg)) {
540 mPendingInputMessages.push_back(msg);
Lajos Molnar09524832014-07-17 14:29:51 -0700541 }
542 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800543
Chong Zhang3b032b32015-04-17 15:49:06 -0700544 return err == -EWOULDBLOCK
545 && mSource->feedMoreTSData() == OK;
Lajos Molnar09524832014-07-17 14:29:51 -0700546}
547
Marco Nelissen421f47c2015-03-25 14:40:32 -0700548void NuPlayer::Decoder::handleError(int32_t err)
549{
550 // We cannot immediately release the codec due to buffers still outstanding
551 // in the renderer. We signal to the player the error so it can shutdown/release the
552 // decoder after flushing and increment the generation to discard unnecessary messages.
553
554 ++mBufferGeneration;
555
556 sp<AMessage> notify = mNotify->dup();
557 notify->setInt32("what", kWhatError);
558 notify->setInt32("err", err);
559 notify->post();
560}
561
562bool NuPlayer::Decoder::handleAnInputBuffer(size_t index) {
Chong Zhang66704af2015-03-03 19:32:35 -0800563 if (isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800564 return false;
565 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700566
567 sp<ABuffer> buffer;
568 mCodec->getInputBuffer(index, &buffer);
569
Wei Jia6301a5e2015-05-13 13:15:18 -0700570 if (buffer == NULL) {
571 handleError(UNKNOWN_ERROR);
572 return false;
573 }
574
Marco Nelissen421f47c2015-03-25 14:40:32 -0700575 if (index >= mInputBuffers.size()) {
576 for (size_t i = mInputBuffers.size(); i <= index; ++i) {
577 mInputBuffers.add();
578 mMediaBuffers.add();
579 mInputBufferIsDequeued.add();
580 mMediaBuffers.editItemAt(i) = NULL;
581 mInputBufferIsDequeued.editItemAt(i) = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800582 }
Andreas Huber078cfcf2011-09-15 12:25:04 -0700583 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700584 mInputBuffers.editItemAt(index) = buffer;
Andreas Huber078cfcf2011-09-15 12:25:04 -0700585
Marco Nelissen421f47c2015-03-25 14:40:32 -0700586 //CHECK_LT(bufferIx, mInputBuffers.size());
Andreas Huberf9334412010-12-15 15:17:42 -0800587
Marco Nelissen421f47c2015-03-25 14:40:32 -0700588 if (mMediaBuffers[index] != NULL) {
589 mMediaBuffers[index]->release();
590 mMediaBuffers.editItemAt(index) = NULL;
Lajos Molnar09524832014-07-17 14:29:51 -0700591 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700592 mInputBufferIsDequeued.editItemAt(index) = true;
Lajos Molnar09524832014-07-17 14:29:51 -0700593
Lajos Molnar87603c02014-08-20 19:25:30 -0700594 if (!mCSDsToSubmit.isEmpty()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800595 sp<AMessage> msg = new AMessage();
Marco Nelissen421f47c2015-03-25 14:40:32 -0700596 msg->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800597
Lajos Molnar87603c02014-08-20 19:25:30 -0700598 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
599 ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
Chong Zhang7137ec72014-11-12 16:41:05 -0800600 msg->setBuffer("buffer", buffer);
Lajos Molnar87603c02014-08-20 19:25:30 -0700601 mCSDsToSubmit.removeAt(0);
Wei Jia56097a82016-01-07 16:03:03 -0800602 if (!onInputBufferFetched(msg)) {
603 handleError(UNKNOWN_ERROR);
604 return false;
605 }
Wei Jia2245fc62014-10-02 15:12:25 -0700606 return true;
607 }
608
609 while (!mPendingInputMessages.empty()) {
610 sp<AMessage> msg = *mPendingInputMessages.begin();
Chong Zhang7137ec72014-11-12 16:41:05 -0800611 if (!onInputBufferFetched(msg)) {
Wei Jia2245fc62014-10-02 15:12:25 -0700612 break;
613 }
614 mPendingInputMessages.erase(mPendingInputMessages.begin());
615 }
616
Marco Nelissen421f47c2015-03-25 14:40:32 -0700617 if (!mInputBufferIsDequeued.editItemAt(index)) {
Lajos Molnar87603c02014-08-20 19:25:30 -0700618 return true;
619 }
620
Marco Nelissen421f47c2015-03-25 14:40:32 -0700621 mDequeuedInputBuffers.push_back(index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800622
623 onRequestInputBuffers();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800624 return true;
625}
626
Marco Nelissen421f47c2015-03-25 14:40:32 -0700627bool NuPlayer::Decoder::handleAnOutputBuffer(
628 size_t index,
629 size_t offset,
630 size_t size,
631 int64_t timeUs,
632 int32_t flags) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700633// CHECK_LT(bufferIx, mOutputBuffers.size());
634 sp<ABuffer> buffer;
635 mCodec->getOutputBuffer(index, &buffer);
636
637 if (index >= mOutputBuffers.size()) {
638 for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
639 mOutputBuffers.add();
640 }
641 }
642
643 mOutputBuffers.editItemAt(index) = buffer;
644
Chong Zhang7137ec72014-11-12 16:41:05 -0800645 buffer->setRange(offset, size);
646 buffer->meta()->clear();
647 buffer->meta()->setInt64("timeUs", timeUs);
Chong Zhang66704af2015-03-03 19:32:35 -0800648
649 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
Chong Zhang7137ec72014-11-12 16:41:05 -0800650 // we do not expect CODECCONFIG or SYNCFRAME for decoder
651
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800652 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
Marco Nelissen421f47c2015-03-25 14:40:32 -0700653 reply->setSize("buffer-ix", index);
Chong Zhang7137ec72014-11-12 16:41:05 -0800654 reply->setInt32("generation", mBufferGeneration);
655
Chong Zhang66704af2015-03-03 19:32:35 -0800656 if (eos) {
657 ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
658
659 buffer->meta()->setInt32("eos", true);
660 reply->setInt32("eos", true);
661 } else if (mSkipRenderingUntilMediaTimeUs >= 0) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800662 if (timeUs < mSkipRenderingUntilMediaTimeUs) {
663 ALOGV("[%s] dropping buffer at time %lld as requested.",
664 mComponentName.c_str(), (long long)timeUs);
665
666 reply->post();
667 return true;
668 }
669
670 mSkipRenderingUntilMediaTimeUs = -1;
671 }
672
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700673 mNumFramesTotal += !mIsAudio;
674
Chong Zhangf8d71772014-11-26 15:08:34 -0800675 // wait until 1st frame comes out to signal resume complete
676 notifyResumeCompleteIfNecessary();
677
Chong Zhang7137ec72014-11-12 16:41:05 -0800678 if (mRenderer != NULL) {
679 // send the buffer to renderer.
680 mRenderer->queueBuffer(mIsAudio, buffer, reply);
Chong Zhang66704af2015-03-03 19:32:35 -0800681 if (eos && !isDiscontinuityPending()) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800682 mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
683 }
684 }
685
686 return true;
687}
688
Marco Nelissen421f47c2015-03-25 14:40:32 -0700689void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
690 if (!mIsAudio) {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -0700691 int32_t width, height;
692 if (format->findInt32("width", &width)
693 && format->findInt32("height", &height)) {
694 mStats->setInt32("width", width);
695 mStats->setInt32("height", height);
696 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700697 sp<AMessage> notify = mNotify->dup();
698 notify->setInt32("what", kWhatVideoSizeChanged);
699 notify->setMessage("format", format);
700 notify->post();
701 } else if (mRenderer != NULL) {
702 uint32_t flags;
703 int64_t durationUs;
704 bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
Andy Hung288da022015-05-31 22:55:59 -0700705 if (getAudioDeepBufferSetting() // override regardless of source duration
706 || (!hasVideo
707 && mSource->getDuration(&durationUs) == OK
708 && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
Marco Nelissen421f47c2015-03-25 14:40:32 -0700709 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
710 } else {
711 flags = AUDIO_OUTPUT_FLAG_NONE;
712 }
713
Eric Laurent216f0172015-08-20 18:40:24 -0700714 status_t err = mRenderer->openAudioSink(
Marco Nelissen421f47c2015-03-25 14:40:32 -0700715 format, false /* offloadOnly */, hasVideo, flags, NULL /* isOffloaed */);
Eric Laurent216f0172015-08-20 18:40:24 -0700716 if (err != OK) {
717 handleError(err);
718 }
Marco Nelissen421f47c2015-03-25 14:40:32 -0700719 }
720}
721
Chong Zhang7137ec72014-11-12 16:41:05 -0800722void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
723 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
724 if (mMediaBuffers[i] != NULL) {
725 mMediaBuffers[i]->release();
726 mMediaBuffers.editItemAt(i) = NULL;
727 }
728 }
729 mMediaBuffers.resize(mInputBuffers.size());
730 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
731 mMediaBuffers.editItemAt(i) = NULL;
732 }
733 mInputBufferIsDequeued.clear();
734 mInputBufferIsDequeued.resize(mInputBuffers.size());
735 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
736 mInputBufferIsDequeued.editItemAt(i) = false;
737 }
738
739 mPendingInputMessages.clear();
740 mDequeuedInputBuffers.clear();
741 mSkipRenderingUntilMediaTimeUs = -1;
742}
743
744void NuPlayer::Decoder::requestCodecNotification() {
Chong Zhang7137ec72014-11-12 16:41:05 -0800745 if (mCodec != NULL) {
Lajos Molnar1d15ab52015-03-04 16:46:34 -0800746 sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
Chong Zhang7137ec72014-11-12 16:41:05 -0800747 reply->setInt32("generation", mBufferGeneration);
748 mCodec->requestActivityNotification(reply);
749 }
750}
751
752bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
753 int32_t generation;
754 CHECK(msg->findInt32("generation", &generation));
755 return generation != mBufferGeneration;
756}
757
758status_t NuPlayer::Decoder::fetchInputData(sp<AMessage> &reply) {
759 sp<ABuffer> accessUnit;
760 bool dropAccessUnit;
761 do {
762 status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
763
764 if (err == -EWOULDBLOCK) {
765 return err;
766 } else if (err != OK) {
767 if (err == INFO_DISCONTINUITY) {
768 int32_t type;
769 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
770
771 bool formatChange =
772 (mIsAudio &&
773 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
774 || (!mIsAudio &&
775 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
776
777 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
778
779 ALOGI("%s discontinuity (format=%d, time=%d)",
780 mIsAudio ? "audio" : "video", formatChange, timeChange);
781
782 bool seamlessFormatChange = false;
783 sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
784 if (formatChange) {
785 seamlessFormatChange =
786 supportsSeamlessFormatChange(newFormat);
787 // treat seamless format change separately
788 formatChange = !seamlessFormatChange;
789 }
790
Chong Zhang66704af2015-03-03 19:32:35 -0800791 // For format or time change, return EOS to queue EOS input,
792 // then wait for EOS on output.
Chong Zhang7137ec72014-11-12 16:41:05 -0800793 if (formatChange /* not seamless */) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800794 mFormatChangePending = true;
Chong Zhang66704af2015-03-03 19:32:35 -0800795 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800796 } else if (timeChange) {
Chong Zhang7137ec72014-11-12 16:41:05 -0800797 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800798 mTimeChangePending = true;
799 err = ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800800 } else if (seamlessFormatChange) {
801 // reuse existing decoder and don't flush
802 rememberCodecSpecificData(newFormat);
Chong Zhang66704af2015-03-03 19:32:35 -0800803 continue;
Chong Zhang7137ec72014-11-12 16:41:05 -0800804 } else {
805 // This stream is unaffected by the discontinuity
806 return -EWOULDBLOCK;
807 }
808 }
809
Chong Zhang66704af2015-03-03 19:32:35 -0800810 // reply should only be returned without a buffer set
811 // when there is an error (including EOS)
812 CHECK(err != OK);
813
Chong Zhang7137ec72014-11-12 16:41:05 -0800814 reply->setInt32("err", err);
Chong Zhang66704af2015-03-03 19:32:35 -0800815 return ERROR_END_OF_STREAM;
Chong Zhang7137ec72014-11-12 16:41:05 -0800816 }
817
Chong Zhang7137ec72014-11-12 16:41:05 -0800818 dropAccessUnit = false;
Praveen Chavanbbaa1442016-04-08 13:33:49 -0700819 if (!mIsAudio && !mIsSecure) {
820 int32_t layerId = 0;
821 if (mRenderer->getVideoLateByUs() > 100000ll
822 && mIsVideoAVC
823 && !IsAVCReferenceFrame(accessUnit)) {
824 dropAccessUnit = true;
825 } else if (accessUnit->meta()->findInt32("temporal-layer-id", &layerId)) {
826 // Add only one layer each time.
827 if (layerId > mCurrentMaxVideoTemporalLayerId + 1
828 || layerId >= mNumVideoTemporalLayerAllowed) {
829 dropAccessUnit = true;
830 ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
831 layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
832 mCurrentMaxVideoTemporalLayerId);
833 } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
834 mCurrentMaxVideoTemporalLayerId = layerId;
835 }
836 }
837 if (dropAccessUnit) {
838 ++mNumInputFramesDropped;
839 }
Chong Zhang7137ec72014-11-12 16:41:05 -0800840 }
841 } while (dropAccessUnit);
842
843 // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
844#if 0
845 int64_t mediaTimeUs;
846 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
Chong Zhang5abbd3d2015-04-20 16:03:00 -0700847 ALOGV("[%s] feeding input buffer at media time %.3f",
Chong Zhang7137ec72014-11-12 16:41:05 -0800848 mIsAudio ? "audio" : "video",
849 mediaTimeUs / 1E6);
850#endif
851
852 if (mCCDecoder != NULL) {
853 mCCDecoder->decode(accessUnit);
854 }
855
856 reply->setBuffer("buffer", accessUnit);
857
858 return OK;
859}
860
861bool NuPlayer::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800862 size_t bufferIx;
863 CHECK(msg->findSize("buffer-ix", &bufferIx));
864 CHECK_LT(bufferIx, mInputBuffers.size());
865 sp<ABuffer> codecBuffer = mInputBuffers[bufferIx];
866
867 sp<ABuffer> buffer;
868 bool hasBuffer = msg->findBuffer("buffer", &buffer);
Lajos Molnar09524832014-07-17 14:29:51 -0700869
870 // handle widevine classic source - that fills an arbitrary input buffer
871 MediaBuffer *mediaBuffer = NULL;
Wei Jia96e92b52014-09-18 17:36:20 -0700872 if (hasBuffer) {
873 mediaBuffer = (MediaBuffer *)(buffer->getMediaBufferBase());
874 if (mediaBuffer != NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700875 // likely filled another buffer than we requested: adjust buffer index
876 size_t ix;
877 for (ix = 0; ix < mInputBuffers.size(); ix++) {
878 const sp<ABuffer> &buf = mInputBuffers[ix];
879 if (buf->data() == mediaBuffer->data()) {
880 // all input buffers are dequeued on start, hence the check
Wei Jia2245fc62014-10-02 15:12:25 -0700881 if (!mInputBufferIsDequeued[ix]) {
882 ALOGV("[%s] received MediaBuffer for #%zu instead of #%zu",
883 mComponentName.c_str(), ix, bufferIx);
884 mediaBuffer->release();
885 return false;
886 }
Lajos Molnar09524832014-07-17 14:29:51 -0700887
888 // TRICKY: need buffer for the metadata, so instead, set
889 // codecBuffer to the same (though incorrect) buffer to
890 // avoid a memcpy into the codecBuffer
891 codecBuffer = buffer;
892 codecBuffer->setRange(
893 mediaBuffer->range_offset(),
894 mediaBuffer->range_length());
895 bufferIx = ix;
896 break;
897 }
898 }
899 CHECK(ix < mInputBuffers.size());
900 }
901 }
902
Lajos Molnar1cd13982014-01-17 15:12:51 -0800903 if (buffer == NULL /* includes !hasBuffer */) {
904 int32_t streamErr = ERROR_END_OF_STREAM;
905 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
906
Chong Zhang66704af2015-03-03 19:32:35 -0800907 CHECK(streamErr != OK);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800908
909 // attempt to queue EOS
910 status_t err = mCodec->queueInputBuffer(
911 bufferIx,
912 0,
913 0,
914 0,
915 MediaCodec::BUFFER_FLAG_EOS);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700916 if (err == OK) {
917 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
918 } else if (streamErr == ERROR_END_OF_STREAM) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800919 streamErr = err;
920 // err will not be ERROR_END_OF_STREAM
921 }
922
923 if (streamErr != ERROR_END_OF_STREAM) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700924 ALOGE("Stream error for %s (err=%d), EOS %s queued",
925 mComponentName.c_str(),
926 streamErr,
927 err == OK ? "successfully" : "unsuccessfully");
Lajos Molnar1cd13982014-01-17 15:12:51 -0800928 handleError(streamErr);
929 }
930 } else {
Wei Jiac6cfd702014-11-11 16:33:20 -0800931 sp<AMessage> extra;
932 if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
933 int64_t resumeAtMediaTimeUs;
934 if (extra->findInt64(
935 "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
936 ALOGI("[%s] suppressing rendering until %lld us",
937 mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
938 mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
939 }
940 }
941
Lajos Molnar1cd13982014-01-17 15:12:51 -0800942 int64_t timeUs = 0;
943 uint32_t flags = 0;
944 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
945
Lajos Molnar87603c02014-08-20 19:25:30 -0700946 int32_t eos, csd;
947 // we do not expect SYNCFRAME for decoder
Lajos Molnar1cd13982014-01-17 15:12:51 -0800948 if (buffer->meta()->findInt32("eos", &eos) && eos) {
949 flags |= MediaCodec::BUFFER_FLAG_EOS;
Lajos Molnar87603c02014-08-20 19:25:30 -0700950 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
951 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800952 }
953
954 // copy into codec buffer
955 if (buffer != codecBuffer) {
Wei Jia56097a82016-01-07 16:03:03 -0800956 if (buffer->size() > codecBuffer->capacity()) {
957 handleError(ERROR_BUFFER_TOO_SMALL);
958 mDequeuedInputBuffers.push_back(bufferIx);
959 return false;
960 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800961 codecBuffer->setRange(0, buffer->size());
962 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
963 }
964
965 status_t err = mCodec->queueInputBuffer(
966 bufferIx,
967 codecBuffer->offset(),
968 codecBuffer->size(),
969 timeUs,
970 flags);
971 if (err != OK) {
Andy Hungcf31f1e2014-09-23 14:59:01 -0700972 if (mediaBuffer != NULL) {
973 mediaBuffer->release();
974 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800975 ALOGE("Failed to queue input buffer for %s (err=%d)",
976 mComponentName.c_str(), err);
977 handleError(err);
Andy Hungcf31f1e2014-09-23 14:59:01 -0700978 } else {
979 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
980 if (mediaBuffer != NULL) {
981 CHECK(mMediaBuffers[bufferIx] == NULL);
982 mMediaBuffers.editItemAt(bufferIx) = mediaBuffer;
983 }
Lajos Molnar09524832014-07-17 14:29:51 -0700984 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800985 }
Wei Jia2245fc62014-10-02 15:12:25 -0700986 return true;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800987}
988
Lajos Molnar1cd13982014-01-17 15:12:51 -0800989void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
990 status_t err;
991 int32_t render;
992 size_t bufferIx;
Chong Zhang66704af2015-03-03 19:32:35 -0800993 int32_t eos;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800994 CHECK(msg->findSize("buffer-ix", &bufferIx));
Wei Jiac6cfd702014-11-11 16:33:20 -0800995
Chong Zhang7137ec72014-11-12 16:41:05 -0800996 if (!mIsAudio) {
Wei Jiac6cfd702014-11-11 16:33:20 -0800997 int64_t timeUs;
998 sp<ABuffer> buffer = mOutputBuffers[bufferIx];
999 buffer->meta()->findInt64("timeUs", &timeUs);
Chong Zhang7137ec72014-11-12 16:41:05 -08001000
1001 if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
1002 mCCDecoder->display(timeUs);
1003 }
Wei Jiac6cfd702014-11-11 16:33:20 -08001004 }
1005
Lajos Molnar1cd13982014-01-17 15:12:51 -08001006 if (msg->findInt32("render", &render) && render) {
Lajos Molnardc43dfa2014-05-07 15:33:04 -07001007 int64_t timestampNs;
1008 CHECK(msg->findInt64("timestampNs", &timestampNs));
1009 err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
Lajos Molnar1cd13982014-01-17 15:12:51 -08001010 } else {
Praveen Chavane1e5d7a2015-05-19 19:09:48 -07001011 mNumOutputFramesDropped += !mIsAudio;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001012 err = mCodec->releaseOutputBuffer(bufferIx);
1013 }
1014 if (err != OK) {
1015 ALOGE("failed to release output buffer for %s (err=%d)",
1016 mComponentName.c_str(), err);
1017 handleError(err);
1018 }
Chong Zhang66704af2015-03-03 19:32:35 -08001019 if (msg->findInt32("eos", &eos) && eos
1020 && isDiscontinuityPending()) {
1021 finishHandleDiscontinuity(true /* flushOnTimeChange */);
1022 }
1023}
1024
1025bool NuPlayer::Decoder::isDiscontinuityPending() const {
1026 return mFormatChangePending || mTimeChangePending;
1027}
1028
1029void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
1030 ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
1031 mFormatChangePending, mTimeChangePending, flushOnTimeChange);
1032
1033 // If we have format change, pause and wait to be killed;
1034 // If we have time change only, flush and restart fetching.
1035
1036 if (mFormatChangePending) {
1037 mPaused = true;
1038 } else if (mTimeChangePending) {
1039 if (flushOnTimeChange) {
Marco Nelissen421f47c2015-03-25 14:40:32 -07001040 doFlush(false /* notifyComplete */);
1041 signalResume(false /* notifyComplete */);
Chong Zhang66704af2015-03-03 19:32:35 -08001042 }
Chong Zhang66704af2015-03-03 19:32:35 -08001043 }
1044
1045 // Notify NuPlayer to either shutdown decoder, or rescan sources
1046 sp<AMessage> msg = mNotify->dup();
1047 msg->setInt32("what", kWhatInputDiscontinuity);
1048 msg->setInt32("formatChange", mFormatChangePending);
1049 msg->post();
1050
1051 mFormatChangePending = false;
1052 mTimeChangePending = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -08001053}
1054
Chong Zhang7137ec72014-11-12 16:41:05 -08001055bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
1056 const sp<AMessage> &targetFormat) const {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001057 if (targetFormat == NULL) {
1058 return true;
1059 }
1060
1061 AString mime;
1062 if (!targetFormat->findString("mime", &mime)) {
1063 return false;
1064 }
1065
1066 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
1067 // field-by-field comparison
1068 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
1069 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1070 int32_t oldVal, newVal;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001071 if (!mInputFormat->findInt32(keys[i], &oldVal) ||
Lajos Molnar1cd13982014-01-17 15:12:51 -08001072 !targetFormat->findInt32(keys[i], &newVal) ||
1073 oldVal != newVal) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001074 return false;
1075 }
1076 }
1077
1078 sp<ABuffer> oldBuf, newBuf;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001079 if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
Lajos Molnar1cd13982014-01-17 15:12:51 -08001080 targetFormat->findBuffer("csd-0", &newBuf)) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001081 if (oldBuf->size() != newBuf->size()) {
1082 return false;
1083 }
1084 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
1085 }
1086 }
1087 return false;
1088}
1089
1090bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
joakim johansson7abbd4c2015-01-30 14:16:03 +01001091 if (mInputFormat == NULL) {
Robert Shih6d0a94e2014-01-23 16:18:22 -08001092 return false;
1093 }
1094
1095 if (targetFormat == NULL) {
1096 return true;
1097 }
1098
1099 AString oldMime, newMime;
joakim johansson7abbd4c2015-01-30 14:16:03 +01001100 if (!mInputFormat->findString("mime", &oldMime)
Robert Shih6d0a94e2014-01-23 16:18:22 -08001101 || !targetFormat->findString("mime", &newMime)
1102 || !(oldMime == newMime)) {
1103 return false;
1104 }
1105
1106 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
1107 bool seamless;
1108 if (audio) {
1109 seamless = supportsSeamlessAudioFormatChange(targetFormat);
1110 } else {
Lajos Molnar1cd13982014-01-17 15:12:51 -08001111 int32_t isAdaptive;
1112 seamless = (mCodec != NULL &&
1113 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
1114 isAdaptive);
Robert Shih6d0a94e2014-01-23 16:18:22 -08001115 }
1116
1117 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
1118 return seamless;
1119}
1120
Chong Zhang7137ec72014-11-12 16:41:05 -08001121void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
1122 if (format == NULL) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001123 return;
1124 }
Chong Zhang7137ec72014-11-12 16:41:05 -08001125 mCSDsForCurrentFormat.clear();
1126 for (int32_t i = 0; ; ++i) {
1127 AString tag = "csd-";
1128 tag.append(i);
1129 sp<ABuffer> buffer;
1130 if (!format->findBuffer(tag.c_str(), &buffer)) {
1131 break;
1132 }
1133 mCSDsForCurrentFormat.push(buffer);
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001134 }
Chong Zhangb86e68f2014-08-01 13:46:53 -07001135}
1136
Chong Zhangf8d71772014-11-26 15:08:34 -08001137void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
1138 if (mResumePending) {
1139 mResumePending = false;
1140
1141 sp<AMessage> notify = mNotify->dup();
1142 notify->setInt32("what", kWhatResumeCompleted);
1143 notify->post();
1144 }
1145}
1146
Andreas Huberf9334412010-12-15 15:17:42 -08001147} // namespace android
1148