blob: 87f85e7256b51acbd22e6e9f4800f6394997a2da [file] [log] [blame]
Andreas Huberf9334412010-12-15 15:17:42 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
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
22#include "NuPlayerDecoder.h"
23
Lajos Molnar1cd13982014-01-17 15:12:51 -080024#include <media/ICrypto.h>
Chong Zhanga7fa1d92014-06-11 14:49:23 -070025#include <media/stagefright/foundation/ABitReader.h>
Andreas Huberf9334412010-12-15 15:17:42 -080026#include <media/stagefright/foundation/ABuffer.h>
27#include <media/stagefright/foundation/ADebug.h>
Andreas Huber5bc087c2010-12-23 10:27:40 -080028#include <media/stagefright/foundation/AMessage.h>
Lajos Molnar09524832014-07-17 14:29:51 -070029#include <media/stagefright/MediaBuffer.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080030#include <media/stagefright/MediaCodec.h>
Andreas Huberf9334412010-12-15 15:17:42 -080031#include <media/stagefright/MediaDefs.h>
Lajos Molnar1cd13982014-01-17 15:12:51 -080032#include <media/stagefright/MediaErrors.h>
Andreas Huberf9334412010-12-15 15:17:42 -080033
34namespace android {
35
36NuPlayer::Decoder::Decoder(
Glenn Kasten11731182011-02-08 17:26:17 -080037 const sp<AMessage> &notify,
38 const sp<NativeWindowWrapper> &nativeWindow)
Andreas Huberf9334412010-12-15 15:17:42 -080039 : mNotify(notify),
Lajos Molnar1cd13982014-01-17 15:12:51 -080040 mNativeWindow(nativeWindow),
41 mBufferGeneration(0),
Wei Jia704e7262014-06-04 16:21:56 -070042 mPaused(true),
Lajos Molnar1cd13982014-01-17 15:12:51 -080043 mComponentName("decoder") {
44 // Every decoder has its own looper because MediaCodec operations
45 // are blocking, but NuPlayer needs asynchronous operations.
46 mDecoderLooper = new ALooper;
Marco Nelissen9e2b7912014-08-18 16:13:03 -070047 mDecoderLooper->setName("NPDecoder");
Lajos Molnar1cd13982014-01-17 15:12:51 -080048 mDecoderLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
49
50 mCodecLooper = new ALooper;
Marco Nelissen9e2b7912014-08-18 16:13:03 -070051 mCodecLooper->setName("NPDecoder-CL");
Lajos Molnar1cd13982014-01-17 15:12:51 -080052 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
Andreas Huberf9334412010-12-15 15:17:42 -080053}
54
55NuPlayer::Decoder::~Decoder() {
56}
57
Lajos Molnar09524832014-07-17 14:29:51 -070058static
59status_t PostAndAwaitResponse(
60 const sp<AMessage> &msg, sp<AMessage> *response) {
61 status_t err = msg->postAndAwaitResponse(response);
62
63 if (err != OK) {
64 return err;
65 }
66
67 if (!(*response)->findInt32("err", &err)) {
68 err = OK;
69 }
70
71 return err;
72}
73
Lajos Molnar87603c02014-08-20 19:25:30 -070074void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
75 mCSDsForCurrentFormat.clear();
76 for (int32_t i = 0; ; ++i) {
77 AString tag = "csd-";
78 tag.append(i);
79 sp<ABuffer> buffer;
80 if (!format->findBuffer(tag.c_str(), &buffer)) {
81 break;
82 }
83 mCSDsForCurrentFormat.push(buffer);
84 }
85}
86
Lajos Molnar1cd13982014-01-17 15:12:51 -080087void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
Andreas Huberf9334412010-12-15 15:17:42 -080088 CHECK(mCodec == NULL);
Andreas Huberf9334412010-12-15 15:17:42 -080089
Lajos Molnar1cd13982014-01-17 15:12:51 -080090 ++mBufferGeneration;
91
Andreas Huber84066782011-08-16 09:34:26 -070092 AString mime;
93 CHECK(format->findString("mime", &mime));
Andreas Huberf9334412010-12-15 15:17:42 -080094
Lajos Molnar1cd13982014-01-17 15:12:51 -080095 sp<Surface> surface = NULL;
96 if (mNativeWindow != NULL) {
97 surface = mNativeWindow->getSurfaceTextureClient();
Andreas Huber84066782011-08-16 09:34:26 -070098 }
Andreas Huberf9334412010-12-15 15:17:42 -080099
Lajos Molnar1cd13982014-01-17 15:12:51 -0800100 mComponentName = mime;
101 mComponentName.append(" decoder");
102 ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), surface.get());
103
104 mCodec = MediaCodec::CreateByType(mCodecLooper, mime.c_str(), false /* encoder */);
Lajos Molnar09524832014-07-17 14:29:51 -0700105 int32_t secure = 0;
106 if (format->findInt32("secure", &secure) && secure != 0) {
107 if (mCodec != NULL) {
108 mCodec->getName(&mComponentName);
109 mComponentName.append(".secure");
110 mCodec->release();
111 ALOGI("[%s] creating", mComponentName.c_str());
112 mCodec = MediaCodec::CreateByComponentName(
113 mCodecLooper, mComponentName.c_str());
114 }
115 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800116 if (mCodec == NULL) {
Lajos Molnar09524832014-07-17 14:29:51 -0700117 ALOGE("Failed to create %s%s decoder",
118 (secure ? "secure " : ""), mime.c_str());
Lajos Molnar1cd13982014-01-17 15:12:51 -0800119 handleError(UNKNOWN_ERROR);
120 return;
121 }
122
123 mCodec->getName(&mComponentName);
124
Lajos Molnar14986f62014-09-15 11:04:44 -0700125 status_t err;
Glenn Kasten11731182011-02-08 17:26:17 -0800126 if (mNativeWindow != NULL) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800127 // disconnect from surface as MediaCodec will reconnect
Lajos Molnar14986f62014-09-15 11:04:44 -0700128 err = native_window_api_disconnect(
129 surface.get(), NATIVE_WINDOW_API_MEDIA);
130 // We treat this as a warning, as this is a preparatory step.
131 // Codec will try to connect to the surface, which is where
132 // any error signaling will occur.
133 ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800134 }
Lajos Molnar14986f62014-09-15 11:04:44 -0700135 err = mCodec->configure(
Lajos Molnar1cd13982014-01-17 15:12:51 -0800136 format, surface, NULL /* crypto */, 0 /* flags */);
137 if (err != OK) {
138 ALOGE("Failed to configure %s decoder (err=%d)", mComponentName.c_str(), err);
139 handleError(err);
140 return;
141 }
Lajos Molnar87603c02014-08-20 19:25:30 -0700142 rememberCodecSpecificData(format);
143
Lajos Molnar1cd13982014-01-17 15:12:51 -0800144 // the following should work in configured state
145 CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
146 CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
147
148 err = mCodec->start();
149 if (err != OK) {
150 ALOGE("Failed to start %s decoder (err=%d)", mComponentName.c_str(), err);
151 handleError(err);
152 return;
Andreas Huberf9334412010-12-15 15:17:42 -0800153 }
154
Lajos Molnar1cd13982014-01-17 15:12:51 -0800155 // the following should work after start
156 CHECK_EQ((status_t)OK, mCodec->getInputBuffers(&mInputBuffers));
Lajos Molnar09524832014-07-17 14:29:51 -0700157 releaseAndResetMediaBuffers();
Lajos Molnar1cd13982014-01-17 15:12:51 -0800158 CHECK_EQ((status_t)OK, mCodec->getOutputBuffers(&mOutputBuffers));
159 ALOGV("[%s] got %zu input and %zu output buffers",
160 mComponentName.c_str(),
161 mInputBuffers.size(),
162 mOutputBuffers.size());
Andreas Huber078cfcf2011-09-15 12:25:04 -0700163
Lajos Molnar1cd13982014-01-17 15:12:51 -0800164 requestCodecNotification();
Wei Jia704e7262014-06-04 16:21:56 -0700165 mPaused = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800166}
Andreas Huber078cfcf2011-09-15 12:25:04 -0700167
Lajos Molnar09524832014-07-17 14:29:51 -0700168void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
169 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
170 if (mMediaBuffers[i] != NULL) {
171 mMediaBuffers[i]->release();
172 mMediaBuffers.editItemAt(i) = NULL;
173 }
174 }
175 mMediaBuffers.resize(mInputBuffers.size());
Wei Jia81e50d02014-07-24 10:28:47 -0700176 for (size_t i = 0; i < mMediaBuffers.size(); i++) {
177 mMediaBuffers.editItemAt(i) = NULL;
178 }
Lajos Molnar09524832014-07-17 14:29:51 -0700179 mInputBufferIsDequeued.clear();
180 mInputBufferIsDequeued.resize(mInputBuffers.size());
Wei Jia81e50d02014-07-24 10:28:47 -0700181 for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
182 mInputBufferIsDequeued.editItemAt(i) = false;
183 }
Lajos Molnar09524832014-07-17 14:29:51 -0700184}
185
Lajos Molnar1cd13982014-01-17 15:12:51 -0800186void NuPlayer::Decoder::requestCodecNotification() {
187 if (mCodec != NULL) {
188 sp<AMessage> reply = new AMessage(kWhatCodecNotify, id());
189 reply->setInt32("generation", mBufferGeneration);
190 mCodec->requestActivityNotification(reply);
191 }
192}
193
194bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
195 int32_t generation;
196 CHECK(msg->findInt32("generation", &generation));
197 return generation != mBufferGeneration;
198}
199
200void NuPlayer::Decoder::init() {
201 mDecoderLooper->registerHandler(this);
202}
203
204void NuPlayer::Decoder::configure(const sp<AMessage> &format) {
205 sp<AMessage> msg = new AMessage(kWhatConfigure, id());
206 msg->setMessage("format", format);
207 msg->post();
208}
209
Lajos Molnar87603c02014-08-20 19:25:30 -0700210void NuPlayer::Decoder::signalUpdateFormat(const sp<AMessage> &format) {
211 sp<AMessage> msg = new AMessage(kWhatUpdateFormat, id());
212 msg->setMessage("format", format);
213 msg->post();
214}
215
Lajos Molnar09524832014-07-17 14:29:51 -0700216status_t NuPlayer::Decoder::getInputBuffers(Vector<sp<ABuffer> > *buffers) const {
217 sp<AMessage> msg = new AMessage(kWhatGetInputBuffers, id());
218 msg->setPointer("buffers", buffers);
219
220 sp<AMessage> response;
221 return PostAndAwaitResponse(msg, &response);
222}
223
Lajos Molnar1cd13982014-01-17 15:12:51 -0800224void NuPlayer::Decoder::handleError(int32_t err)
225{
Wei Jiac22c6952014-08-29 14:47:50 -0700226 mCodec->release();
227
Lajos Molnar1cd13982014-01-17 15:12:51 -0800228 sp<AMessage> notify = mNotify->dup();
229 notify->setInt32("what", kWhatError);
230 notify->setInt32("err", err);
231 notify->post();
232}
233
234bool NuPlayer::Decoder::handleAnInputBuffer() {
235 size_t bufferIx = -1;
236 status_t res = mCodec->dequeueInputBuffer(&bufferIx);
237 ALOGV("[%s] dequeued input: %d",
238 mComponentName.c_str(), res == OK ? (int)bufferIx : res);
239 if (res != OK) {
240 if (res != -EAGAIN) {
241 handleError(res);
242 }
243 return false;
Andreas Huber078cfcf2011-09-15 12:25:04 -0700244 }
245
Lajos Molnar1cd13982014-01-17 15:12:51 -0800246 CHECK_LT(bufferIx, mInputBuffers.size());
Andreas Huberf9334412010-12-15 15:17:42 -0800247
Lajos Molnar09524832014-07-17 14:29:51 -0700248 if (mMediaBuffers[bufferIx] != NULL) {
249 mMediaBuffers[bufferIx]->release();
250 mMediaBuffers.editItemAt(bufferIx) = NULL;
251 }
252 mInputBufferIsDequeued.editItemAt(bufferIx) = true;
253
Lajos Molnar1cd13982014-01-17 15:12:51 -0800254 sp<AMessage> reply = new AMessage(kWhatInputBufferFilled, id());
255 reply->setSize("buffer-ix", bufferIx);
256 reply->setInt32("generation", mBufferGeneration);
257
Lajos Molnar87603c02014-08-20 19:25:30 -0700258 if (!mCSDsToSubmit.isEmpty()) {
259 sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
260 ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
261 reply->setBuffer("buffer", buffer);
262 mCSDsToSubmit.removeAt(0);
263 reply->post();
264 return true;
265 }
266
Lajos Molnar1cd13982014-01-17 15:12:51 -0800267 sp<AMessage> notify = mNotify->dup();
268 notify->setInt32("what", kWhatFillThisBuffer);
269 notify->setBuffer("buffer", mInputBuffers[bufferIx]);
270 notify->setMessage("reply", reply);
271 notify->post();
272 return true;
273}
274
275void android::NuPlayer::Decoder::onInputBufferFilled(const sp<AMessage> &msg) {
276 size_t bufferIx;
277 CHECK(msg->findSize("buffer-ix", &bufferIx));
278 CHECK_LT(bufferIx, mInputBuffers.size());
279 sp<ABuffer> codecBuffer = mInputBuffers[bufferIx];
280
281 sp<ABuffer> buffer;
282 bool hasBuffer = msg->findBuffer("buffer", &buffer);
Lajos Molnar09524832014-07-17 14:29:51 -0700283
284 // handle widevine classic source - that fills an arbitrary input buffer
285 MediaBuffer *mediaBuffer = NULL;
286 if (hasBuffer && buffer->meta()->findPointer(
287 "mediaBuffer", (void **)&mediaBuffer)) {
288 if (mediaBuffer == NULL) {
289 // received no actual buffer
290 ALOGW("[%s] received null MediaBuffer %s",
291 mComponentName.c_str(), msg->debugString().c_str());
292 buffer = NULL;
293 } else {
294 // likely filled another buffer than we requested: adjust buffer index
295 size_t ix;
296 for (ix = 0; ix < mInputBuffers.size(); ix++) {
297 const sp<ABuffer> &buf = mInputBuffers[ix];
298 if (buf->data() == mediaBuffer->data()) {
299 // all input buffers are dequeued on start, hence the check
300 CHECK(mInputBufferIsDequeued[ix]);
301 ALOGV("[%s] received MediaBuffer for #%zu instead of #%zu",
302 mComponentName.c_str(), ix, bufferIx);
303
304 // TRICKY: need buffer for the metadata, so instead, set
305 // codecBuffer to the same (though incorrect) buffer to
306 // avoid a memcpy into the codecBuffer
307 codecBuffer = buffer;
308 codecBuffer->setRange(
309 mediaBuffer->range_offset(),
310 mediaBuffer->range_length());
311 bufferIx = ix;
312 break;
313 }
314 }
315 CHECK(ix < mInputBuffers.size());
316 }
317 }
318
319 mInputBufferIsDequeued.editItemAt(bufferIx) = false;
320
Lajos Molnar1cd13982014-01-17 15:12:51 -0800321 if (buffer == NULL /* includes !hasBuffer */) {
322 int32_t streamErr = ERROR_END_OF_STREAM;
323 CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
324
325 if (streamErr == OK) {
326 /* buffers are returned to hold on to */
327 return;
328 }
329
330 // attempt to queue EOS
331 status_t err = mCodec->queueInputBuffer(
332 bufferIx,
333 0,
334 0,
335 0,
336 MediaCodec::BUFFER_FLAG_EOS);
337 if (streamErr == ERROR_END_OF_STREAM && err != OK) {
338 streamErr = err;
339 // err will not be ERROR_END_OF_STREAM
340 }
341
342 if (streamErr != ERROR_END_OF_STREAM) {
343 handleError(streamErr);
344 }
345 } else {
346 int64_t timeUs = 0;
347 uint32_t flags = 0;
348 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
349
Lajos Molnar87603c02014-08-20 19:25:30 -0700350 int32_t eos, csd;
351 // we do not expect SYNCFRAME for decoder
Lajos Molnar1cd13982014-01-17 15:12:51 -0800352 if (buffer->meta()->findInt32("eos", &eos) && eos) {
353 flags |= MediaCodec::BUFFER_FLAG_EOS;
Lajos Molnar87603c02014-08-20 19:25:30 -0700354 } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
355 flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800356 }
357
358 // copy into codec buffer
359 if (buffer != codecBuffer) {
360 CHECK_LE(buffer->size(), codecBuffer->capacity());
361 codecBuffer->setRange(0, buffer->size());
362 memcpy(codecBuffer->data(), buffer->data(), buffer->size());
363 }
364
365 status_t err = mCodec->queueInputBuffer(
366 bufferIx,
367 codecBuffer->offset(),
368 codecBuffer->size(),
369 timeUs,
370 flags);
371 if (err != OK) {
372 ALOGE("Failed to queue input buffer for %s (err=%d)",
373 mComponentName.c_str(), err);
374 handleError(err);
375 }
Lajos Molnar09524832014-07-17 14:29:51 -0700376
377 if (mediaBuffer != NULL) {
378 CHECK(mMediaBuffers[bufferIx] == NULL);
379 mMediaBuffers.editItemAt(bufferIx) = mediaBuffer;
380 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800381 }
382}
383
384bool NuPlayer::Decoder::handleAnOutputBuffer() {
385 size_t bufferIx = -1;
386 size_t offset;
387 size_t size;
388 int64_t timeUs;
389 uint32_t flags;
390 status_t res = mCodec->dequeueOutputBuffer(
391 &bufferIx, &offset, &size, &timeUs, &flags);
392
393 if (res != OK) {
394 ALOGV("[%s] dequeued output: %d", mComponentName.c_str(), res);
395 } else {
396 ALOGV("[%s] dequeued output: %d (time=%lld flags=%" PRIu32 ")",
397 mComponentName.c_str(), (int)bufferIx, timeUs, flags);
398 }
399
400 if (res == INFO_OUTPUT_BUFFERS_CHANGED) {
401 res = mCodec->getOutputBuffers(&mOutputBuffers);
402 if (res != OK) {
403 ALOGE("Failed to get output buffers for %s after INFO event (err=%d)",
404 mComponentName.c_str(), res);
405 handleError(res);
406 return false;
407 }
408 // NuPlayer ignores this
409 return true;
410 } else if (res == INFO_FORMAT_CHANGED) {
411 sp<AMessage> format = new AMessage();
412 res = mCodec->getOutputFormat(&format);
413 if (res != OK) {
414 ALOGE("Failed to get output format for %s after INFO event (err=%d)",
415 mComponentName.c_str(), res);
416 handleError(res);
417 return false;
418 }
419
420 sp<AMessage> notify = mNotify->dup();
421 notify->setInt32("what", kWhatOutputFormatChanged);
422 notify->setMessage("format", format);
423 notify->post();
424 return true;
425 } else if (res == INFO_DISCONTINUITY) {
426 // nothing to do
427 return true;
428 } else if (res != OK) {
429 if (res != -EAGAIN) {
430 handleError(res);
431 }
432 return false;
433 }
434
435 CHECK_LT(bufferIx, mOutputBuffers.size());
436 sp<ABuffer> buffer = mOutputBuffers[bufferIx];
437 buffer->setRange(offset, size);
438 buffer->meta()->clear();
439 buffer->meta()->setInt64("timeUs", timeUs);
440 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
441 buffer->meta()->setInt32("eos", true);
442 }
443 // we do not expect CODECCONFIG or SYNCFRAME for decoder
444
445 sp<AMessage> reply = new AMessage(kWhatRenderBuffer, id());
446 reply->setSize("buffer-ix", bufferIx);
447 reply->setInt32("generation", mBufferGeneration);
448
449 sp<AMessage> notify = mNotify->dup();
450 notify->setInt32("what", kWhatDrainThisBuffer);
451 notify->setBuffer("buffer", buffer);
452 notify->setMessage("reply", reply);
453 notify->post();
454
455 // FIXME: This should be handled after rendering is complete,
456 // but Renderer needs it now
457 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
458 ALOGV("queueing eos [%s]", mComponentName.c_str());
459 sp<AMessage> notify = mNotify->dup();
460 notify->setInt32("what", kWhatEOS);
461 notify->setInt32("err", ERROR_END_OF_STREAM);
462 notify->post();
463 }
464 return true;
465}
466
467void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
468 status_t err;
469 int32_t render;
470 size_t bufferIx;
471 CHECK(msg->findSize("buffer-ix", &bufferIx));
472 if (msg->findInt32("render", &render) && render) {
473 err = mCodec->renderOutputBufferAndRelease(bufferIx);
474 } else {
475 err = mCodec->releaseOutputBuffer(bufferIx);
476 }
477 if (err != OK) {
478 ALOGE("failed to release output buffer for %s (err=%d)",
479 mComponentName.c_str(), err);
480 handleError(err);
481 }
482}
483
484void NuPlayer::Decoder::onFlush() {
485 status_t err = OK;
486 if (mCodec != NULL) {
487 err = mCodec->flush();
Lajos Molnar87603c02014-08-20 19:25:30 -0700488 mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
Lajos Molnar1cd13982014-01-17 15:12:51 -0800489 ++mBufferGeneration;
490 }
491
492 if (err != OK) {
493 ALOGE("failed to flush %s (err=%d)", mComponentName.c_str(), err);
494 handleError(err);
495 return;
496 }
497
Lajos Molnar09524832014-07-17 14:29:51 -0700498 releaseAndResetMediaBuffers();
499
Lajos Molnar1cd13982014-01-17 15:12:51 -0800500 sp<AMessage> notify = mNotify->dup();
501 notify->setInt32("what", kWhatFlushCompleted);
502 notify->post();
Wei Jia704e7262014-06-04 16:21:56 -0700503 mPaused = true;
504}
505
506void NuPlayer::Decoder::onResume() {
507 mPaused = false;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800508}
509
510void NuPlayer::Decoder::onShutdown() {
511 status_t err = OK;
512 if (mCodec != NULL) {
513 err = mCodec->release();
514 mCodec = NULL;
515 ++mBufferGeneration;
516
517 if (mNativeWindow != NULL) {
518 // reconnect to surface as MediaCodec disconnected from it
Wei Jia3fb9f682014-08-20 14:30:09 -0700519 status_t error =
Lajos Molnar1cd13982014-01-17 15:12:51 -0800520 native_window_api_connect(
521 mNativeWindow->getNativeWindow().get(),
Wei Jia3fb9f682014-08-20 14:30:09 -0700522 NATIVE_WINDOW_API_MEDIA);
523 ALOGW_IF(error != NO_ERROR,
524 "[%s] failed to connect to native window, error=%d",
525 mComponentName.c_str(), error);
Lajos Molnar1cd13982014-01-17 15:12:51 -0800526 }
527 mComponentName = "decoder";
528 }
529
Lajos Molnar09524832014-07-17 14:29:51 -0700530 releaseAndResetMediaBuffers();
531
Lajos Molnar1cd13982014-01-17 15:12:51 -0800532 if (err != OK) {
533 ALOGE("failed to release %s (err=%d)", mComponentName.c_str(), err);
534 handleError(err);
535 return;
536 }
537
538 sp<AMessage> notify = mNotify->dup();
539 notify->setInt32("what", kWhatShutdownCompleted);
540 notify->post();
Wei Jia704e7262014-06-04 16:21:56 -0700541 mPaused = true;
Andreas Huberf9334412010-12-15 15:17:42 -0800542}
543
544void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800545 ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
546
Andreas Huberf9334412010-12-15 15:17:42 -0800547 switch (msg->what()) {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800548 case kWhatConfigure:
549 {
550 sp<AMessage> format;
551 CHECK(msg->findMessage("format", &format));
552 onConfigure(format);
553 break;
554 }
555
Lajos Molnar87603c02014-08-20 19:25:30 -0700556 case kWhatUpdateFormat:
557 {
558 sp<AMessage> format;
559 CHECK(msg->findMessage("format", &format));
560 rememberCodecSpecificData(format);
561 break;
562 }
563
Lajos Molnar09524832014-07-17 14:29:51 -0700564 case kWhatGetInputBuffers:
565 {
566 uint32_t replyID;
567 CHECK(msg->senderAwaitsResponse(&replyID));
568
569 Vector<sp<ABuffer> > *dstBuffers;
570 CHECK(msg->findPointer("buffers", (void **)&dstBuffers));
571
572 dstBuffers->clear();
573 for (size_t i = 0; i < mInputBuffers.size(); i++) {
574 dstBuffers->push(mInputBuffers[i]);
575 }
576
577 (new AMessage)->postReply(replyID);
578 break;
579 }
580
Andreas Huberf9334412010-12-15 15:17:42 -0800581 case kWhatCodecNotify:
582 {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800583 if (!isStaleReply(msg)) {
Wei Jia704e7262014-06-04 16:21:56 -0700584 if (!mPaused) {
585 while (handleAnInputBuffer()) {
586 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800587 }
Andreas Huberf9334412010-12-15 15:17:42 -0800588
Lajos Molnar1cd13982014-01-17 15:12:51 -0800589 while (handleAnOutputBuffer()) {
590 }
Andreas Huberf9334412010-12-15 15:17:42 -0800591 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800592
593 requestCodecNotification();
594 break;
595 }
596
597 case kWhatInputBufferFilled:
598 {
599 if (!isStaleReply(msg)) {
600 onInputBufferFilled(msg);
Lajos Molnarb9b87fe2014-09-10 13:53:21 -0700601 } else {
602 /* release any MediaBuffer passed in the stale buffer */
603 sp<ABuffer> buffer;
604 MediaBuffer *mediaBuffer = NULL;
605 if (msg->findBuffer("buffer", &buffer) &&
606 buffer->meta()->findPointer(
607 "mediaBuffer", (void **)&mediaBuffer) &&
608 mediaBuffer != NULL) {
609 mediaBuffer->release();
610 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800611 }
Lajos Molnarb9b87fe2014-09-10 13:53:21 -0700612
Lajos Molnar1cd13982014-01-17 15:12:51 -0800613 break;
614 }
615
616 case kWhatRenderBuffer:
617 {
618 if (!isStaleReply(msg)) {
619 onRenderBuffer(msg);
620 }
621 break;
622 }
623
624 case kWhatFlush:
625 {
Lajos Molnar87603c02014-08-20 19:25:30 -0700626 sp<AMessage> format;
627 if (msg->findMessage("new-format", &format)) {
628 rememberCodecSpecificData(format);
629 }
Lajos Molnar1cd13982014-01-17 15:12:51 -0800630 onFlush();
631 break;
632 }
633
Wei Jia704e7262014-06-04 16:21:56 -0700634 case kWhatResume:
635 {
636 onResume();
637 break;
638 }
639
Lajos Molnar1cd13982014-01-17 15:12:51 -0800640 case kWhatShutdown:
641 {
642 onShutdown();
Andreas Huberf9334412010-12-15 15:17:42 -0800643 break;
644 }
645
646 default:
647 TRESPASS();
648 break;
649 }
650}
651
Lajos Molnar87603c02014-08-20 19:25:30 -0700652void NuPlayer::Decoder::signalFlush(const sp<AMessage> &format) {
653 sp<AMessage> msg = new AMessage(kWhatFlush, id());
654 if (format != NULL) {
655 msg->setMessage("new-format", format);
656 }
657 msg->post();
Andreas Huberf9334412010-12-15 15:17:42 -0800658}
659
660void NuPlayer::Decoder::signalResume() {
Wei Jia704e7262014-06-04 16:21:56 -0700661 (new AMessage(kWhatResume, id()))->post();
Andreas Huberf9334412010-12-15 15:17:42 -0800662}
663
Andreas Huber3831a062010-12-21 10:22:33 -0800664void NuPlayer::Decoder::initiateShutdown() {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800665 (new AMessage(kWhatShutdown, id()))->post();
Andreas Huber3831a062010-12-21 10:22:33 -0800666}
667
Robert Shih6d0a94e2014-01-23 16:18:22 -0800668bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(const sp<AMessage> &targetFormat) const {
669 if (targetFormat == NULL) {
670 return true;
671 }
672
673 AString mime;
674 if (!targetFormat->findString("mime", &mime)) {
675 return false;
676 }
677
678 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
679 // field-by-field comparison
680 const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
681 for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
682 int32_t oldVal, newVal;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800683 if (!mOutputFormat->findInt32(keys[i], &oldVal) ||
684 !targetFormat->findInt32(keys[i], &newVal) ||
685 oldVal != newVal) {
Robert Shih6d0a94e2014-01-23 16:18:22 -0800686 return false;
687 }
688 }
689
690 sp<ABuffer> oldBuf, newBuf;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800691 if (mOutputFormat->findBuffer("csd-0", &oldBuf) &&
692 targetFormat->findBuffer("csd-0", &newBuf)) {
Robert Shih6d0a94e2014-01-23 16:18:22 -0800693 if (oldBuf->size() != newBuf->size()) {
694 return false;
695 }
696 return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
697 }
698 }
699 return false;
700}
701
702bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800703 if (mOutputFormat == NULL) {
Robert Shih6d0a94e2014-01-23 16:18:22 -0800704 return false;
705 }
706
707 if (targetFormat == NULL) {
708 return true;
709 }
710
711 AString oldMime, newMime;
Lajos Molnar1cd13982014-01-17 15:12:51 -0800712 if (!mOutputFormat->findString("mime", &oldMime)
Robert Shih6d0a94e2014-01-23 16:18:22 -0800713 || !targetFormat->findString("mime", &newMime)
714 || !(oldMime == newMime)) {
715 return false;
716 }
717
718 bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
719 bool seamless;
720 if (audio) {
721 seamless = supportsSeamlessAudioFormatChange(targetFormat);
722 } else {
Lajos Molnar1cd13982014-01-17 15:12:51 -0800723 int32_t isAdaptive;
724 seamless = (mCodec != NULL &&
725 mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
726 isAdaptive);
Robert Shih6d0a94e2014-01-23 16:18:22 -0800727 }
728
729 ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
730 return seamless;
731}
732
Chong Zhangb86e68f2014-08-01 13:46:53 -0700733struct CCData {
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700734 CCData(uint8_t type, uint8_t data1, uint8_t data2)
735 : mType(type), mData1(data1), mData2(data2) {
736 }
Chong Zhangb86e68f2014-08-01 13:46:53 -0700737 bool getChannel(size_t *channel) const {
738 if (mData1 >= 0x10 && mData1 <= 0x1f) {
739 *channel = (mData1 >= 0x18 ? 1 : 0) + (mType ? 2 : 0);
740 return true;
741 }
742 return false;
743 }
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700744
745 uint8_t mType;
746 uint8_t mData1;
747 uint8_t mData2;
748};
749
Chong Zhangb86e68f2014-08-01 13:46:53 -0700750static bool isNullPad(CCData *cc) {
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700751 return cc->mData1 < 0x10 && cc->mData2 < 0x10;
752}
753
Chong Zhangb86e68f2014-08-01 13:46:53 -0700754static void dumpBytePair(const sp<ABuffer> &ccBuf) {
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700755 size_t offset = 0;
756 AString out;
757
758 while (offset < ccBuf->size()) {
759 char tmp[128];
760
761 CCData *cc = (CCData *) (ccBuf->data() + offset);
762
763 if (isNullPad(cc)) {
764 // 1 null pad or XDS metadata, ignore
765 offset += sizeof(CCData);
766 continue;
767 }
768
769 if (cc->mData1 >= 0x20 && cc->mData1 <= 0x7f) {
770 // 2 basic chars
771 sprintf(tmp, "[%d]Basic: %c %c", cc->mType, cc->mData1, cc->mData2);
772 } else if ((cc->mData1 == 0x11 || cc->mData1 == 0x19)
773 && cc->mData2 >= 0x30 && cc->mData2 <= 0x3f) {
774 // 1 special char
775 sprintf(tmp, "[%d]Special: %02x %02x", cc->mType, cc->mData1, cc->mData2);
776 } else if ((cc->mData1 == 0x12 || cc->mData1 == 0x1A)
777 && cc->mData2 >= 0x20 && cc->mData2 <= 0x3f){
778 // 1 Spanish/French char
779 sprintf(tmp, "[%d]Spanish: %02x %02x", cc->mType, cc->mData1, cc->mData2);
780 } else if ((cc->mData1 == 0x13 || cc->mData1 == 0x1B)
781 && cc->mData2 >= 0x20 && cc->mData2 <= 0x3f){
782 // 1 Portuguese/German/Danish char
783 sprintf(tmp, "[%d]German: %02x %02x", cc->mType, cc->mData1, cc->mData2);
784 } else if ((cc->mData1 == 0x11 || cc->mData1 == 0x19)
785 && cc->mData2 >= 0x20 && cc->mData2 <= 0x2f){
786 // Mid-Row Codes (Table 69)
787 sprintf(tmp, "[%d]Mid-row: %02x %02x", cc->mType, cc->mData1, cc->mData2);
788 } else if (((cc->mData1 == 0x14 || cc->mData1 == 0x1c)
789 && cc->mData2 >= 0x20 && cc->mData2 <= 0x2f)
790 ||
791 ((cc->mData1 == 0x17 || cc->mData1 == 0x1f)
792 && cc->mData2 >= 0x21 && cc->mData2 <= 0x23)){
793 // Misc Control Codes (Table 70)
794 sprintf(tmp, "[%d]Ctrl: %02x %02x", cc->mType, cc->mData1, cc->mData2);
795 } else if ((cc->mData1 & 0x70) == 0x10
796 && (cc->mData2 & 0x40) == 0x40
797 && ((cc->mData1 & 0x07) || !(cc->mData2 & 0x20)) ) {
798 // Preamble Address Codes (Table 71)
799 sprintf(tmp, "[%d]PAC: %02x %02x", cc->mType, cc->mData1, cc->mData2);
800 } else {
801 sprintf(tmp, "[%d]Invalid: %02x %02x", cc->mType, cc->mData1, cc->mData2);
802 }
803
804 if (out.size() > 0) {
805 out.append(", ");
806 }
807
808 out.append(tmp);
809
810 offset += sizeof(CCData);
811 }
812
813 ALOGI("%s", out.c_str());
814}
815
Chong Zhangb86e68f2014-08-01 13:46:53 -0700816NuPlayer::CCDecoder::CCDecoder(const sp<AMessage> &notify)
817 : mNotify(notify),
818 mCurrentChannel(0),
819 mSelectedTrack(-1) {
820 for (size_t i = 0; i < sizeof(mTrackIndices)/sizeof(mTrackIndices[0]); ++i) {
821 mTrackIndices[i] = -1;
822 }
823}
824
825size_t NuPlayer::CCDecoder::getTrackCount() const {
826 return mFoundChannels.size();
827}
828
829sp<AMessage> NuPlayer::CCDecoder::getTrackInfo(size_t index) const {
830 if (!isTrackValid(index)) {
831 return NULL;
832 }
833
834 sp<AMessage> format = new AMessage();
835
836 format->setInt32("type", MEDIA_TRACK_TYPE_SUBTITLE);
837 format->setString("language", "und");
838 format->setString("mime", MEDIA_MIMETYPE_TEXT_CEA_608);
839 //CC1, field 0 channel 0
840 bool isDefaultAuto = (mFoundChannels[index] == 0);
841 format->setInt32("auto", isDefaultAuto);
842 format->setInt32("default", isDefaultAuto);
843 format->setInt32("forced", 0);
844
845 return format;
846}
847
848status_t NuPlayer::CCDecoder::selectTrack(size_t index, bool select) {
849 if (!isTrackValid(index)) {
850 return BAD_VALUE;
851 }
852
853 if (select) {
854 if (mSelectedTrack == (ssize_t)index) {
855 ALOGE("track %zu already selected", index);
856 return BAD_VALUE;
857 }
858 ALOGV("selected track %zu", index);
859 mSelectedTrack = index;
860 } else {
861 if (mSelectedTrack != (ssize_t)index) {
862 ALOGE("track %zu is not selected", index);
863 return BAD_VALUE;
864 }
865 ALOGV("unselected track %zu", index);
866 mSelectedTrack = -1;
867 }
868
869 return OK;
870}
871
872bool NuPlayer::CCDecoder::isSelected() const {
873 return mSelectedTrack >= 0 && mSelectedTrack < (int32_t) getTrackCount();
874}
875
876bool NuPlayer::CCDecoder::isTrackValid(size_t index) const {
877 return index < getTrackCount();
878}
879
880int32_t NuPlayer::CCDecoder::getTrackIndex(size_t channel) const {
881 if (channel < sizeof(mTrackIndices)/sizeof(mTrackIndices[0])) {
882 return mTrackIndices[channel];
883 }
884 return -1;
885}
886
887// returns true if a new CC track is found
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700888bool NuPlayer::CCDecoder::extractFromSEI(const sp<ABuffer> &accessUnit) {
889 int64_t timeUs;
890 CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
891
892 sp<ABuffer> sei;
893 if (!accessUnit->meta()->findBuffer("sei", &sei) || sei == NULL) {
894 return false;
895 }
896
Chong Zhangb86e68f2014-08-01 13:46:53 -0700897 bool trackAdded = false;
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700898
Chong Zhang862f8452014-06-26 19:55:23 -0700899 NALBitReader br(sei->data() + 1, sei->size() - 1);
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700900 // sei_message()
Chong Zhang862f8452014-06-26 19:55:23 -0700901 while (br.atLeastNumBitsLeft(16)) { // at least 16-bit for sei_message()
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700902 uint32_t payload_type = 0;
903 size_t payload_size = 0;
904 uint8_t last_byte;
905
906 do {
907 last_byte = br.getBits(8);
908 payload_type += last_byte;
909 } while (last_byte == 0xFF);
910
911 do {
912 last_byte = br.getBits(8);
913 payload_size += last_byte;
914 } while (last_byte == 0xFF);
915
916 // sei_payload()
917 if (payload_type == 4) {
918 // user_data_registered_itu_t_t35()
919
920 // ATSC A/72: 6.4.2
921 uint8_t itu_t_t35_country_code = br.getBits(8);
922 uint16_t itu_t_t35_provider_code = br.getBits(16);
923 uint32_t user_identifier = br.getBits(32);
924 uint8_t user_data_type_code = br.getBits(8);
925
926 payload_size -= 1 + 2 + 4 + 1;
927
928 if (itu_t_t35_country_code == 0xB5
929 && itu_t_t35_provider_code == 0x0031
930 && user_identifier == 'GA94'
931 && user_data_type_code == 0x3) {
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700932 // MPEG_cc_data()
933 // ATSC A/53 Part 4: 6.2.3.1
934 br.skipBits(1); //process_em_data_flag
935 bool process_cc_data_flag = br.getBits(1);
936 br.skipBits(1); //additional_data_flag
937 size_t cc_count = br.getBits(5);
938 br.skipBits(8); // em_data;
939 payload_size -= 2;
940
941 if (process_cc_data_flag) {
942 AString out;
943
944 sp<ABuffer> ccBuf = new ABuffer(cc_count * sizeof(CCData));
945 ccBuf->setRange(0, 0);
946
947 for (size_t i = 0; i < cc_count; i++) {
948 uint8_t marker = br.getBits(5);
949 CHECK_EQ(marker, 0x1f);
950
951 bool cc_valid = br.getBits(1);
952 uint8_t cc_type = br.getBits(2);
953 // remove odd parity bit
954 uint8_t cc_data_1 = br.getBits(8) & 0x7f;
955 uint8_t cc_data_2 = br.getBits(8) & 0x7f;
956
957 if (cc_valid
958 && (cc_type == 0 || cc_type == 1)) {
959 CCData cc(cc_type, cc_data_1, cc_data_2);
960 if (!isNullPad(&cc)) {
Chong Zhangb86e68f2014-08-01 13:46:53 -0700961 size_t channel;
962 if (cc.getChannel(&channel) && getTrackIndex(channel) < 0) {
963 mTrackIndices[channel] = mFoundChannels.size();
964 mFoundChannels.push_back(channel);
965 trackAdded = true;
966 }
Chong Zhanga7fa1d92014-06-11 14:49:23 -0700967 memcpy(ccBuf->data() + ccBuf->size(),
968 (void *)&cc, sizeof(cc));
969 ccBuf->setRange(0, ccBuf->size() + sizeof(CCData));
970 }
971 }
972 }
973 payload_size -= cc_count * 3;
974
975 mCCMap.add(timeUs, ccBuf);
976 break;
977 }
978 } else {
979 ALOGV("Malformed SEI payload type 4");
980 }
981 } else {
982 ALOGV("Unsupported SEI payload type %d", payload_type);
983 }
984
985 // skipping remaining bits of this payload
986 br.skipBits(payload_size * 8);
987 }
988
Chong Zhangb86e68f2014-08-01 13:46:53 -0700989 return trackAdded;
990}
991
992sp<ABuffer> NuPlayer::CCDecoder::filterCCBuf(
993 const sp<ABuffer> &ccBuf, size_t index) {
994 sp<ABuffer> filteredCCBuf = new ABuffer(ccBuf->size());
995 filteredCCBuf->setRange(0, 0);
996
997 size_t cc_count = ccBuf->size() / sizeof(CCData);
998 const CCData* cc_data = (const CCData*)ccBuf->data();
999 for (size_t i = 0; i < cc_count; ++i) {
1000 size_t channel;
1001 if (cc_data[i].getChannel(&channel)) {
1002 mCurrentChannel = channel;
1003 }
1004 if (mCurrentChannel == mFoundChannels[index]) {
1005 memcpy(filteredCCBuf->data() + filteredCCBuf->size(),
1006 (void *)&cc_data[i], sizeof(CCData));
1007 filteredCCBuf->setRange(0, filteredCCBuf->size() + sizeof(CCData));
1008 }
1009 }
1010
1011 return filteredCCBuf;
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001012}
1013
1014void NuPlayer::CCDecoder::decode(const sp<ABuffer> &accessUnit) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001015 if (extractFromSEI(accessUnit)) {
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001016 ALOGI("Found CEA-608 track");
1017 sp<AMessage> msg = mNotify->dup();
1018 msg->setInt32("what", kWhatTrackAdded);
1019 msg->post();
1020 }
1021 // TODO: extract CC from other sources
1022}
1023
1024void NuPlayer::CCDecoder::display(int64_t timeUs) {
Chong Zhangb86e68f2014-08-01 13:46:53 -07001025 if (!isTrackValid(mSelectedTrack)) {
1026 ALOGE("Could not find current track(index=%d)", mSelectedTrack);
1027 return;
1028 }
1029
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001030 ssize_t index = mCCMap.indexOfKey(timeUs);
1031 if (index < 0) {
1032 ALOGV("cc for timestamp %" PRId64 " not found", timeUs);
1033 return;
1034 }
1035
Chong Zhangb86e68f2014-08-01 13:46:53 -07001036 sp<ABuffer> ccBuf = filterCCBuf(mCCMap.valueAt(index), mSelectedTrack);
Chong Zhanga7fa1d92014-06-11 14:49:23 -07001037
1038 if (ccBuf->size() > 0) {
1039#if 0
1040 dumpBytePair(ccBuf);
1041#endif
1042
1043 ccBuf->meta()->setInt32("trackIndex", mSelectedTrack);
1044 ccBuf->meta()->setInt64("timeUs", timeUs);
1045 ccBuf->meta()->setInt64("durationUs", 0ll);
1046
1047 sp<AMessage> msg = mNotify->dup();
1048 msg->setInt32("what", kWhatClosedCaptionData);
1049 msg->setBuffer("buffer", ccBuf);
1050 msg->post();
1051 }
1052
1053 // remove all entries before timeUs
1054 mCCMap.removeItemsAt(0, index + 1);
1055}
1056
Chong Zhangb86e68f2014-08-01 13:46:53 -07001057void NuPlayer::CCDecoder::flush() {
1058 mCCMap.clear();
1059}
1060
Andreas Huberf9334412010-12-15 15:17:42 -08001061} // namespace android
1062