MediaCodec.cpp revision 67d93552f0fca5a2ac6a451569cc1b1e15cd138a
1/* 2 * Copyright 2012, 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 "MediaCodec" 19#include <inttypes.h> 20 21#include "include/avc_utils.h" 22#include "include/SoftwareRenderer.h" 23 24#include <binder/IBatteryStats.h> 25#include <binder/IServiceManager.h> 26#include <gui/Surface.h> 27#include <media/ICrypto.h> 28#include <media/stagefright/foundation/ABuffer.h> 29#include <media/stagefright/foundation/ADebug.h> 30#include <media/stagefright/foundation/AMessage.h> 31#include <media/stagefright/foundation/AString.h> 32#include <media/stagefright/foundation/hexdump.h> 33#include <media/stagefright/ACodec.h> 34#include <media/stagefright/BufferProducerWrapper.h> 35#include <media/stagefright/MediaCodec.h> 36#include <media/stagefright/MediaCodecList.h> 37#include <media/stagefright/MediaDefs.h> 38#include <media/stagefright/MediaErrors.h> 39#include <media/stagefright/MediaFilter.h> 40#include <media/stagefright/MetaData.h> 41#include <media/stagefright/NativeWindowWrapper.h> 42#include <private/android_filesystem_config.h> 43#include <utils/Log.h> 44#include <utils/Singleton.h> 45 46namespace android { 47 48struct MediaCodec::BatteryNotifier : public Singleton<BatteryNotifier> { 49 BatteryNotifier(); 50 51 void noteStartVideo(); 52 void noteStopVideo(); 53 void noteStartAudio(); 54 void noteStopAudio(); 55 56private: 57 int32_t mVideoRefCount; 58 int32_t mAudioRefCount; 59 sp<IBatteryStats> mBatteryStatService; 60}; 61 62ANDROID_SINGLETON_STATIC_INSTANCE(MediaCodec::BatteryNotifier) 63 64MediaCodec::BatteryNotifier::BatteryNotifier() : 65 mVideoRefCount(0), 66 mAudioRefCount(0) { 67 // get battery service 68 const sp<IServiceManager> sm(defaultServiceManager()); 69 if (sm != NULL) { 70 const String16 name("batterystats"); 71 mBatteryStatService = interface_cast<IBatteryStats>(sm->getService(name)); 72 if (mBatteryStatService == NULL) { 73 ALOGE("batterystats service unavailable!"); 74 } 75 } 76} 77 78void MediaCodec::BatteryNotifier::noteStartVideo() { 79 if (mVideoRefCount == 0 && mBatteryStatService != NULL) { 80 mBatteryStatService->noteStartVideo(AID_MEDIA); 81 } 82 mVideoRefCount++; 83} 84 85void MediaCodec::BatteryNotifier::noteStopVideo() { 86 if (mVideoRefCount == 0) { 87 ALOGW("BatteryNotifier::noteStop(): video refcount is broken!"); 88 return; 89 } 90 91 mVideoRefCount--; 92 if (mVideoRefCount == 0 && mBatteryStatService != NULL) { 93 mBatteryStatService->noteStopVideo(AID_MEDIA); 94 } 95} 96 97void MediaCodec::BatteryNotifier::noteStartAudio() { 98 if (mAudioRefCount == 0 && mBatteryStatService != NULL) { 99 mBatteryStatService->noteStartAudio(AID_MEDIA); 100 } 101 mAudioRefCount++; 102} 103 104void MediaCodec::BatteryNotifier::noteStopAudio() { 105 if (mAudioRefCount == 0) { 106 ALOGW("BatteryNotifier::noteStop(): audio refcount is broken!"); 107 return; 108 } 109 110 mAudioRefCount--; 111 if (mAudioRefCount == 0 && mBatteryStatService != NULL) { 112 mBatteryStatService->noteStopAudio(AID_MEDIA); 113 } 114} 115// static 116sp<MediaCodec> MediaCodec::CreateByType( 117 const sp<ALooper> &looper, const char *mime, bool encoder, status_t *err) { 118 sp<MediaCodec> codec = new MediaCodec(looper); 119 120 const status_t ret = codec->init(mime, true /* nameIsType */, encoder); 121 if (err != NULL) { 122 *err = ret; 123 } 124 return ret == OK ? codec : NULL; // NULL deallocates codec. 125} 126 127// static 128sp<MediaCodec> MediaCodec::CreateByComponentName( 129 const sp<ALooper> &looper, const char *name, status_t *err) { 130 sp<MediaCodec> codec = new MediaCodec(looper); 131 132 const status_t ret = codec->init(name, false /* nameIsType */, false /* encoder */); 133 if (err != NULL) { 134 *err = ret; 135 } 136 return ret == OK ? codec : NULL; // NULL deallocates codec. 137} 138 139MediaCodec::MediaCodec(const sp<ALooper> &looper) 140 : mState(UNINITIALIZED), 141 mLooper(looper), 142 mCodec(NULL), 143 mReplyID(0), 144 mFlags(0), 145 mStickyError(OK), 146 mSoftRenderer(NULL), 147 mBatteryStatNotified(false), 148 mIsVideo(false), 149 mDequeueInputTimeoutGeneration(0), 150 mDequeueInputReplyID(0), 151 mDequeueOutputTimeoutGeneration(0), 152 mDequeueOutputReplyID(0), 153 mHaveInputSurface(false) { 154} 155 156MediaCodec::~MediaCodec() { 157 CHECK_EQ(mState, UNINITIALIZED); 158} 159 160// static 161status_t MediaCodec::PostAndAwaitResponse( 162 const sp<AMessage> &msg, sp<AMessage> *response) { 163 status_t err = msg->postAndAwaitResponse(response); 164 165 if (err != OK) { 166 return err; 167 } 168 169 if (!(*response)->findInt32("err", &err)) { 170 err = OK; 171 } 172 173 return err; 174} 175 176// static 177void MediaCodec::PostReplyWithError(int32_t replyID, int32_t err) { 178 sp<AMessage> response = new AMessage; 179 response->setInt32("err", err); 180 response->postReply(replyID); 181} 182 183status_t MediaCodec::init(const AString &name, bool nameIsType, bool encoder) { 184 // save init parameters for reset 185 mInitName = name; 186 mInitNameIsType = nameIsType; 187 mInitIsEncoder = encoder; 188 189 // Current video decoders do not return from OMX_FillThisBuffer 190 // quickly, violating the OpenMAX specs, until that is remedied 191 // we need to invest in an extra looper to free the main event 192 // queue. 193 194 if (nameIsType || !strncasecmp(name.c_str(), "omx.", 4)) { 195 mCodec = new ACodec; 196 } else if (!nameIsType 197 && !strncasecmp(name.c_str(), "android.filter.", 15)) { 198 mCodec = new MediaFilter; 199 } else { 200 return NAME_NOT_FOUND; 201 } 202 203 bool needDedicatedLooper = false; 204 if (nameIsType && !strncasecmp(name.c_str(), "video/", 6)) { 205 needDedicatedLooper = true; 206 } else { 207 AString tmp = name; 208 if (tmp.endsWith(".secure")) { 209 tmp.erase(tmp.size() - 7, 7); 210 } 211 const sp<IMediaCodecList> mcl = MediaCodecList::getInstance(); 212 ssize_t codecIdx = mcl->findCodecByName(tmp.c_str()); 213 if (codecIdx >= 0) { 214 const sp<MediaCodecInfo> info = mcl->getCodecInfo(codecIdx); 215 Vector<AString> mimes; 216 info->getSupportedMimes(&mimes); 217 for (size_t i = 0; i < mimes.size(); i++) { 218 if (mimes[i].startsWith("video/")) { 219 needDedicatedLooper = true; 220 break; 221 } 222 } 223 } 224 } 225 226 if (needDedicatedLooper) { 227 if (mCodecLooper == NULL) { 228 mCodecLooper = new ALooper; 229 mCodecLooper->setName("CodecLooper"); 230 mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO); 231 } 232 233 mCodecLooper->registerHandler(mCodec); 234 } else { 235 mLooper->registerHandler(mCodec); 236 } 237 238 mLooper->registerHandler(this); 239 240 mCodec->setNotificationMessage(new AMessage(kWhatCodecNotify, id())); 241 242 sp<AMessage> msg = new AMessage(kWhatInit, id()); 243 msg->setString("name", name); 244 msg->setInt32("nameIsType", nameIsType); 245 246 if (nameIsType) { 247 msg->setInt32("encoder", encoder); 248 } 249 250 sp<AMessage> response; 251 return PostAndAwaitResponse(msg, &response); 252} 253 254status_t MediaCodec::setCallback(const sp<AMessage> &callback) { 255 sp<AMessage> msg = new AMessage(kWhatSetCallback, id()); 256 msg->setMessage("callback", callback); 257 258 sp<AMessage> response; 259 return PostAndAwaitResponse(msg, &response); 260} 261 262status_t MediaCodec::configure( 263 const sp<AMessage> &format, 264 const sp<Surface> &nativeWindow, 265 const sp<ICrypto> &crypto, 266 uint32_t flags) { 267 sp<AMessage> msg = new AMessage(kWhatConfigure, id()); 268 269 msg->setMessage("format", format); 270 msg->setInt32("flags", flags); 271 272 if (nativeWindow != NULL) { 273 msg->setObject( 274 "native-window", 275 new NativeWindowWrapper(nativeWindow)); 276 } 277 278 if (crypto != NULL) { 279 msg->setPointer("crypto", crypto.get()); 280 } 281 282 sp<AMessage> response; 283 status_t err = PostAndAwaitResponse(msg, &response); 284 285 if (err != OK && err != INVALID_OPERATION) { 286 // MediaCodec now set state to UNINITIALIZED upon any fatal error. 287 // To maintain backward-compatibility, do a reset() to put codec 288 // back into INITIALIZED state. 289 // But don't reset if the err is INVALID_OPERATION, which means 290 // the configure failure is due to wrong state. 291 292 ALOGE("configure failed with err 0x%08x, resetting...", err); 293 reset(); 294 } 295 296 return err; 297} 298 299status_t MediaCodec::createInputSurface( 300 sp<IGraphicBufferProducer>* bufferProducer) { 301 sp<AMessage> msg = new AMessage(kWhatCreateInputSurface, id()); 302 303 sp<AMessage> response; 304 status_t err = PostAndAwaitResponse(msg, &response); 305 if (err == NO_ERROR) { 306 // unwrap the sp<IGraphicBufferProducer> 307 sp<RefBase> obj; 308 bool found = response->findObject("input-surface", &obj); 309 CHECK(found); 310 sp<BufferProducerWrapper> wrapper( 311 static_cast<BufferProducerWrapper*>(obj.get())); 312 *bufferProducer = wrapper->getBufferProducer(); 313 } else { 314 ALOGW("createInputSurface failed, err=%d", err); 315 } 316 return err; 317} 318 319status_t MediaCodec::start() { 320 sp<AMessage> msg = new AMessage(kWhatStart, id()); 321 322 sp<AMessage> response; 323 return PostAndAwaitResponse(msg, &response); 324} 325 326status_t MediaCodec::stop() { 327 sp<AMessage> msg = new AMessage(kWhatStop, id()); 328 329 sp<AMessage> response; 330 return PostAndAwaitResponse(msg, &response); 331} 332 333status_t MediaCodec::release() { 334 sp<AMessage> msg = new AMessage(kWhatRelease, id()); 335 336 sp<AMessage> response; 337 return PostAndAwaitResponse(msg, &response); 338} 339 340status_t MediaCodec::reset() { 341 /* When external-facing MediaCodec object is created, 342 it is already initialized. Thus, reset is essentially 343 release() followed by init(), plus clearing the state */ 344 345 status_t err = release(); 346 347 // unregister handlers 348 if (mCodec != NULL) { 349 if (mCodecLooper != NULL) { 350 mCodecLooper->unregisterHandler(mCodec->id()); 351 } else { 352 mLooper->unregisterHandler(mCodec->id()); 353 } 354 mCodec = NULL; 355 } 356 mLooper->unregisterHandler(id()); 357 358 mFlags = 0; // clear all flags 359 mStickyError = OK; 360 361 // reset state not reset by setState(UNINITIALIZED) 362 mReplyID = 0; 363 mDequeueInputReplyID = 0; 364 mDequeueOutputReplyID = 0; 365 mDequeueInputTimeoutGeneration = 0; 366 mDequeueOutputTimeoutGeneration = 0; 367 mHaveInputSurface = false; 368 369 if (err == OK) { 370 err = init(mInitName, mInitNameIsType, mInitIsEncoder); 371 } 372 return err; 373} 374 375status_t MediaCodec::queueInputBuffer( 376 size_t index, 377 size_t offset, 378 size_t size, 379 int64_t presentationTimeUs, 380 uint32_t flags, 381 AString *errorDetailMsg) { 382 if (errorDetailMsg != NULL) { 383 errorDetailMsg->clear(); 384 } 385 386 sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, id()); 387 msg->setSize("index", index); 388 msg->setSize("offset", offset); 389 msg->setSize("size", size); 390 msg->setInt64("timeUs", presentationTimeUs); 391 msg->setInt32("flags", flags); 392 msg->setPointer("errorDetailMsg", errorDetailMsg); 393 394 sp<AMessage> response; 395 return PostAndAwaitResponse(msg, &response); 396} 397 398status_t MediaCodec::queueSecureInputBuffer( 399 size_t index, 400 size_t offset, 401 const CryptoPlugin::SubSample *subSamples, 402 size_t numSubSamples, 403 const uint8_t key[16], 404 const uint8_t iv[16], 405 CryptoPlugin::Mode mode, 406 int64_t presentationTimeUs, 407 uint32_t flags, 408 AString *errorDetailMsg) { 409 if (errorDetailMsg != NULL) { 410 errorDetailMsg->clear(); 411 } 412 413 sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, id()); 414 msg->setSize("index", index); 415 msg->setSize("offset", offset); 416 msg->setPointer("subSamples", (void *)subSamples); 417 msg->setSize("numSubSamples", numSubSamples); 418 msg->setPointer("key", (void *)key); 419 msg->setPointer("iv", (void *)iv); 420 msg->setInt32("mode", mode); 421 msg->setInt64("timeUs", presentationTimeUs); 422 msg->setInt32("flags", flags); 423 msg->setPointer("errorDetailMsg", errorDetailMsg); 424 425 sp<AMessage> response; 426 status_t err = PostAndAwaitResponse(msg, &response); 427 428 return err; 429} 430 431status_t MediaCodec::dequeueInputBuffer(size_t *index, int64_t timeoutUs) { 432 sp<AMessage> msg = new AMessage(kWhatDequeueInputBuffer, id()); 433 msg->setInt64("timeoutUs", timeoutUs); 434 435 sp<AMessage> response; 436 status_t err; 437 if ((err = PostAndAwaitResponse(msg, &response)) != OK) { 438 return err; 439 } 440 441 CHECK(response->findSize("index", index)); 442 443 return OK; 444} 445 446status_t MediaCodec::dequeueOutputBuffer( 447 size_t *index, 448 size_t *offset, 449 size_t *size, 450 int64_t *presentationTimeUs, 451 uint32_t *flags, 452 int64_t timeoutUs) { 453 sp<AMessage> msg = new AMessage(kWhatDequeueOutputBuffer, id()); 454 msg->setInt64("timeoutUs", timeoutUs); 455 456 sp<AMessage> response; 457 status_t err; 458 if ((err = PostAndAwaitResponse(msg, &response)) != OK) { 459 return err; 460 } 461 462 CHECK(response->findSize("index", index)); 463 CHECK(response->findSize("offset", offset)); 464 CHECK(response->findSize("size", size)); 465 CHECK(response->findInt64("timeUs", presentationTimeUs)); 466 CHECK(response->findInt32("flags", (int32_t *)flags)); 467 468 return OK; 469} 470 471status_t MediaCodec::renderOutputBufferAndRelease(size_t index) { 472 sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, id()); 473 msg->setSize("index", index); 474 msg->setInt32("render", true); 475 476 sp<AMessage> response; 477 return PostAndAwaitResponse(msg, &response); 478} 479 480status_t MediaCodec::renderOutputBufferAndRelease(size_t index, int64_t timestampNs) { 481 sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, id()); 482 msg->setSize("index", index); 483 msg->setInt32("render", true); 484 msg->setInt64("timestampNs", timestampNs); 485 486 sp<AMessage> response; 487 return PostAndAwaitResponse(msg, &response); 488} 489 490status_t MediaCodec::releaseOutputBuffer(size_t index) { 491 sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, id()); 492 msg->setSize("index", index); 493 494 sp<AMessage> response; 495 return PostAndAwaitResponse(msg, &response); 496} 497 498status_t MediaCodec::signalEndOfInputStream() { 499 sp<AMessage> msg = new AMessage(kWhatSignalEndOfInputStream, id()); 500 501 sp<AMessage> response; 502 return PostAndAwaitResponse(msg, &response); 503} 504 505status_t MediaCodec::getOutputFormat(sp<AMessage> *format) const { 506 sp<AMessage> msg = new AMessage(kWhatGetOutputFormat, id()); 507 508 sp<AMessage> response; 509 status_t err; 510 if ((err = PostAndAwaitResponse(msg, &response)) != OK) { 511 return err; 512 } 513 514 CHECK(response->findMessage("format", format)); 515 516 return OK; 517} 518 519status_t MediaCodec::getInputFormat(sp<AMessage> *format) const { 520 sp<AMessage> msg = new AMessage(kWhatGetInputFormat, id()); 521 522 sp<AMessage> response; 523 status_t err; 524 if ((err = PostAndAwaitResponse(msg, &response)) != OK) { 525 return err; 526 } 527 528 CHECK(response->findMessage("format", format)); 529 530 return OK; 531} 532 533status_t MediaCodec::getName(AString *name) const { 534 sp<AMessage> msg = new AMessage(kWhatGetName, id()); 535 536 sp<AMessage> response; 537 status_t err; 538 if ((err = PostAndAwaitResponse(msg, &response)) != OK) { 539 return err; 540 } 541 542 CHECK(response->findString("name", name)); 543 544 return OK; 545} 546 547status_t MediaCodec::getInputBuffers(Vector<sp<ABuffer> > *buffers) const { 548 sp<AMessage> msg = new AMessage(kWhatGetBuffers, id()); 549 msg->setInt32("portIndex", kPortIndexInput); 550 msg->setPointer("buffers", buffers); 551 552 sp<AMessage> response; 553 return PostAndAwaitResponse(msg, &response); 554} 555 556status_t MediaCodec::getOutputBuffers(Vector<sp<ABuffer> > *buffers) const { 557 sp<AMessage> msg = new AMessage(kWhatGetBuffers, id()); 558 msg->setInt32("portIndex", kPortIndexOutput); 559 msg->setPointer("buffers", buffers); 560 561 sp<AMessage> response; 562 return PostAndAwaitResponse(msg, &response); 563} 564 565status_t MediaCodec::getOutputBuffer(size_t index, sp<ABuffer> *buffer) { 566 sp<AMessage> format; 567 return getBufferAndFormat(kPortIndexOutput, index, buffer, &format); 568} 569 570status_t MediaCodec::getOutputFormat(size_t index, sp<AMessage> *format) { 571 sp<ABuffer> buffer; 572 return getBufferAndFormat(kPortIndexOutput, index, &buffer, format); 573} 574 575status_t MediaCodec::getInputBuffer(size_t index, sp<ABuffer> *buffer) { 576 sp<AMessage> format; 577 return getBufferAndFormat(kPortIndexInput, index, buffer, &format); 578} 579 580bool MediaCodec::isExecuting() const { 581 return mState == STARTED || mState == FLUSHED; 582} 583 584status_t MediaCodec::getBufferAndFormat( 585 size_t portIndex, size_t index, 586 sp<ABuffer> *buffer, sp<AMessage> *format) { 587 // use mutex instead of a context switch 588 589 buffer->clear(); 590 format->clear(); 591 if (!isExecuting()) { 592 return INVALID_OPERATION; 593 } 594 595 // we do not want mPortBuffers to change during this section 596 // we also don't want mOwnedByClient to change during this 597 Mutex::Autolock al(mBufferLock); 598 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 599 if (index < buffers->size()) { 600 const BufferInfo &info = buffers->itemAt(index); 601 if (info.mOwnedByClient) { 602 // by the time buffers array is initialized, crypto is set 603 if (portIndex == kPortIndexInput && mCrypto != NULL) { 604 *buffer = info.mEncryptedData; 605 } else { 606 *buffer = info.mData; 607 } 608 *format = info.mFormat; 609 } 610 } 611 return OK; 612} 613 614status_t MediaCodec::flush() { 615 sp<AMessage> msg = new AMessage(kWhatFlush, id()); 616 617 sp<AMessage> response; 618 return PostAndAwaitResponse(msg, &response); 619} 620 621status_t MediaCodec::requestIDRFrame() { 622 (new AMessage(kWhatRequestIDRFrame, id()))->post(); 623 624 return OK; 625} 626 627void MediaCodec::requestActivityNotification(const sp<AMessage> ¬ify) { 628 sp<AMessage> msg = new AMessage(kWhatRequestActivityNotification, id()); 629 msg->setMessage("notify", notify); 630 msg->post(); 631} 632 633//////////////////////////////////////////////////////////////////////////////// 634 635void MediaCodec::cancelPendingDequeueOperations() { 636 if (mFlags & kFlagDequeueInputPending) { 637 PostReplyWithError(mDequeueInputReplyID, INVALID_OPERATION); 638 639 ++mDequeueInputTimeoutGeneration; 640 mDequeueInputReplyID = 0; 641 mFlags &= ~kFlagDequeueInputPending; 642 } 643 644 if (mFlags & kFlagDequeueOutputPending) { 645 PostReplyWithError(mDequeueOutputReplyID, INVALID_OPERATION); 646 647 ++mDequeueOutputTimeoutGeneration; 648 mDequeueOutputReplyID = 0; 649 mFlags &= ~kFlagDequeueOutputPending; 650 } 651} 652 653bool MediaCodec::handleDequeueInputBuffer(uint32_t replyID, bool newRequest) { 654 if (!isExecuting() || (mFlags & kFlagIsAsync) 655 || (newRequest && (mFlags & kFlagDequeueInputPending))) { 656 PostReplyWithError(replyID, INVALID_OPERATION); 657 return true; 658 } else if (mFlags & kFlagStickyError) { 659 PostReplyWithError(replyID, getStickyError()); 660 return true; 661 } 662 663 ssize_t index = dequeuePortBuffer(kPortIndexInput); 664 665 if (index < 0) { 666 CHECK_EQ(index, -EAGAIN); 667 return false; 668 } 669 670 sp<AMessage> response = new AMessage; 671 response->setSize("index", index); 672 response->postReply(replyID); 673 674 return true; 675} 676 677bool MediaCodec::handleDequeueOutputBuffer(uint32_t replyID, bool newRequest) { 678 sp<AMessage> response = new AMessage; 679 680 if (!isExecuting() || (mFlags & kFlagIsAsync) 681 || (newRequest && (mFlags & kFlagDequeueOutputPending))) { 682 response->setInt32("err", INVALID_OPERATION); 683 } else if (mFlags & kFlagStickyError) { 684 response->setInt32("err", getStickyError()); 685 } else if (mFlags & kFlagOutputBuffersChanged) { 686 response->setInt32("err", INFO_OUTPUT_BUFFERS_CHANGED); 687 mFlags &= ~kFlagOutputBuffersChanged; 688 } else if (mFlags & kFlagOutputFormatChanged) { 689 response->setInt32("err", INFO_FORMAT_CHANGED); 690 mFlags &= ~kFlagOutputFormatChanged; 691 } else { 692 ssize_t index = dequeuePortBuffer(kPortIndexOutput); 693 694 if (index < 0) { 695 CHECK_EQ(index, -EAGAIN); 696 return false; 697 } 698 699 const sp<ABuffer> &buffer = 700 mPortBuffers[kPortIndexOutput].itemAt(index).mData; 701 702 response->setSize("index", index); 703 response->setSize("offset", buffer->offset()); 704 response->setSize("size", buffer->size()); 705 706 int64_t timeUs; 707 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 708 709 response->setInt64("timeUs", timeUs); 710 711 int32_t omxFlags; 712 CHECK(buffer->meta()->findInt32("omxFlags", &omxFlags)); 713 714 uint32_t flags = 0; 715 if (omxFlags & OMX_BUFFERFLAG_SYNCFRAME) { 716 flags |= BUFFER_FLAG_SYNCFRAME; 717 } 718 if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) { 719 flags |= BUFFER_FLAG_CODECCONFIG; 720 } 721 if (omxFlags & OMX_BUFFERFLAG_EOS) { 722 flags |= BUFFER_FLAG_EOS; 723 } 724 725 response->setInt32("flags", flags); 726 } 727 728 response->postReply(replyID); 729 730 return true; 731} 732 733void MediaCodec::onMessageReceived(const sp<AMessage> &msg) { 734 switch (msg->what()) { 735 case kWhatCodecNotify: 736 { 737 int32_t what; 738 CHECK(msg->findInt32("what", &what)); 739 740 switch (what) { 741 case CodecBase::kWhatError: 742 { 743 int32_t err, actionCode; 744 CHECK(msg->findInt32("err", &err)); 745 CHECK(msg->findInt32("actionCode", &actionCode)); 746 747 ALOGE("Codec reported err %#x, actionCode %d, while in state %d", 748 err, actionCode, mState); 749 if (err == DEAD_OBJECT) { 750 mFlags |= kFlagSawMediaServerDie; 751 mFlags &= ~kFlagIsComponentAllocated; 752 } 753 754 bool sendErrorResponse = true; 755 756 switch (mState) { 757 case INITIALIZING: 758 { 759 setState(UNINITIALIZED); 760 break; 761 } 762 763 case CONFIGURING: 764 { 765 setState(actionCode == ACTION_CODE_FATAL ? 766 UNINITIALIZED : INITIALIZED); 767 break; 768 } 769 770 case STARTING: 771 { 772 setState(actionCode == ACTION_CODE_FATAL ? 773 UNINITIALIZED : CONFIGURED); 774 break; 775 } 776 777 case STOPPING: 778 case RELEASING: 779 { 780 // Ignore the error, assuming we'll still get 781 // the shutdown complete notification. 782 783 sendErrorResponse = false; 784 785 if (mFlags & kFlagSawMediaServerDie) { 786 // MediaServer died, there definitely won't 787 // be a shutdown complete notification after 788 // all. 789 790 // note that we're directly going from 791 // STOPPING->UNINITIALIZED, instead of the 792 // usual STOPPING->INITIALIZED state. 793 setState(UNINITIALIZED); 794 if (mState == RELEASING) { 795 mComponentName.clear(); 796 } 797 (new AMessage)->postReply(mReplyID); 798 } 799 break; 800 } 801 802 case FLUSHING: 803 { 804 if (actionCode == ACTION_CODE_FATAL) { 805 setState(UNINITIALIZED); 806 } else { 807 setState( 808 (mFlags & kFlagIsAsync) ? FLUSHED : STARTED); 809 } 810 break; 811 } 812 813 case FLUSHED: 814 case STARTED: 815 { 816 sendErrorResponse = false; 817 818 setStickyError(err); 819 postActivityNotificationIfPossible(); 820 821 cancelPendingDequeueOperations(); 822 823 if (mFlags & kFlagIsAsync) { 824 onError(err, actionCode); 825 } 826 switch (actionCode) { 827 case ACTION_CODE_TRANSIENT: 828 break; 829 case ACTION_CODE_RECOVERABLE: 830 setState(INITIALIZED); 831 break; 832 default: 833 setState(UNINITIALIZED); 834 break; 835 } 836 break; 837 } 838 839 default: 840 { 841 sendErrorResponse = false; 842 843 setStickyError(err); 844 postActivityNotificationIfPossible(); 845 846 // actionCode in an uninitialized state is always fatal. 847 if (mState == UNINITIALIZED) { 848 actionCode = ACTION_CODE_FATAL; 849 } 850 if (mFlags & kFlagIsAsync) { 851 onError(err, actionCode); 852 } 853 switch (actionCode) { 854 case ACTION_CODE_TRANSIENT: 855 break; 856 case ACTION_CODE_RECOVERABLE: 857 setState(INITIALIZED); 858 break; 859 default: 860 setState(UNINITIALIZED); 861 break; 862 } 863 break; 864 } 865 } 866 867 if (sendErrorResponse) { 868 PostReplyWithError(mReplyID, err); 869 } 870 break; 871 } 872 873 case CodecBase::kWhatComponentAllocated: 874 { 875 CHECK_EQ(mState, INITIALIZING); 876 setState(INITIALIZED); 877 mFlags |= kFlagIsComponentAllocated; 878 879 CHECK(msg->findString("componentName", &mComponentName)); 880 881 if (mComponentName.startsWith("OMX.google.")) { 882 mFlags |= kFlagIsSoftwareCodec; 883 } else { 884 mFlags &= ~kFlagIsSoftwareCodec; 885 } 886 887 if (mComponentName.endsWith(".secure")) { 888 mFlags |= kFlagIsSecure; 889 } else { 890 mFlags &= ~kFlagIsSecure; 891 } 892 893 (new AMessage)->postReply(mReplyID); 894 break; 895 } 896 897 case CodecBase::kWhatComponentConfigured: 898 { 899 CHECK_EQ(mState, CONFIGURING); 900 901 // reset input surface flag 902 mHaveInputSurface = false; 903 904 CHECK(msg->findMessage("input-format", &mInputFormat)); 905 CHECK(msg->findMessage("output-format", &mOutputFormat)); 906 907 setState(CONFIGURED); 908 (new AMessage)->postReply(mReplyID); 909 break; 910 } 911 912 case CodecBase::kWhatInputSurfaceCreated: 913 { 914 // response to initiateCreateInputSurface() 915 status_t err = NO_ERROR; 916 sp<AMessage> response = new AMessage(); 917 if (!msg->findInt32("err", &err)) { 918 sp<RefBase> obj; 919 msg->findObject("input-surface", &obj); 920 CHECK(obj != NULL); 921 response->setObject("input-surface", obj); 922 mHaveInputSurface = true; 923 } else { 924 response->setInt32("err", err); 925 } 926 response->postReply(mReplyID); 927 break; 928 } 929 930 case CodecBase::kWhatSignaledInputEOS: 931 { 932 // response to signalEndOfInputStream() 933 sp<AMessage> response = new AMessage(); 934 status_t err; 935 if (msg->findInt32("err", &err)) { 936 response->setInt32("err", err); 937 } 938 response->postReply(mReplyID); 939 break; 940 } 941 942 943 case CodecBase::kWhatBuffersAllocated: 944 { 945 Mutex::Autolock al(mBufferLock); 946 int32_t portIndex; 947 CHECK(msg->findInt32("portIndex", &portIndex)); 948 949 ALOGV("%s buffers allocated", 950 portIndex == kPortIndexInput ? "input" : "output"); 951 952 CHECK(portIndex == kPortIndexInput 953 || portIndex == kPortIndexOutput); 954 955 mPortBuffers[portIndex].clear(); 956 957 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 958 959 sp<RefBase> obj; 960 CHECK(msg->findObject("portDesc", &obj)); 961 962 sp<CodecBase::PortDescription> portDesc = 963 static_cast<CodecBase::PortDescription *>(obj.get()); 964 965 size_t numBuffers = portDesc->countBuffers(); 966 967 for (size_t i = 0; i < numBuffers; ++i) { 968 BufferInfo info; 969 info.mBufferID = portDesc->bufferIDAt(i); 970 info.mOwnedByClient = false; 971 info.mData = portDesc->bufferAt(i); 972 973 if (portIndex == kPortIndexInput && mCrypto != NULL) { 974 info.mEncryptedData = 975 new ABuffer(info.mData->capacity()); 976 } 977 978 buffers->push_back(info); 979 } 980 981 if (portIndex == kPortIndexOutput) { 982 if (mState == STARTING) { 983 // We're always allocating output buffers after 984 // allocating input buffers, so this is a good 985 // indication that now all buffers are allocated. 986 setState(STARTED); 987 (new AMessage)->postReply(mReplyID); 988 } else { 989 mFlags |= kFlagOutputBuffersChanged; 990 postActivityNotificationIfPossible(); 991 } 992 } 993 break; 994 } 995 996 case CodecBase::kWhatOutputFormatChanged: 997 { 998 ALOGV("codec output format changed"); 999 1000 if (mSoftRenderer == NULL && 1001 mNativeWindow != NULL && 1002 (mFlags & kFlagIsSoftwareCodec)) { 1003 AString mime; 1004 CHECK(msg->findString("mime", &mime)); 1005 1006 if (mime.startsWithIgnoreCase("video/")) { 1007 mSoftRenderer = new SoftwareRenderer(mNativeWindow); 1008 } 1009 } 1010 1011 mOutputFormat = msg; 1012 1013 if (mFlags & kFlagIsEncoder) { 1014 // Before we announce the format change we should 1015 // collect codec specific data and amend the output 1016 // format as necessary. 1017 mFlags |= kFlagGatherCodecSpecificData; 1018 } else if (mFlags & kFlagIsAsync) { 1019 onOutputFormatChanged(); 1020 } else { 1021 mFlags |= kFlagOutputFormatChanged; 1022 postActivityNotificationIfPossible(); 1023 } 1024 1025 // Notify mCrypto of video resolution changes 1026 if (mCrypto != NULL) { 1027 int32_t height, width; 1028 if (mOutputFormat->findInt32("height", &height) && 1029 mOutputFormat->findInt32("width", &width)) { 1030 mCrypto->notifyResolution(width, height); 1031 } 1032 } 1033 1034 break; 1035 } 1036 1037 case CodecBase::kWhatFillThisBuffer: 1038 { 1039 /* size_t index = */updateBuffers(kPortIndexInput, msg); 1040 1041 if (mState == FLUSHING 1042 || mState == STOPPING 1043 || mState == RELEASING) { 1044 returnBuffersToCodecOnPort(kPortIndexInput); 1045 break; 1046 } 1047 1048 if (!mCSD.empty()) { 1049 ssize_t index = dequeuePortBuffer(kPortIndexInput); 1050 CHECK_GE(index, 0); 1051 1052 // If codec specific data had been specified as 1053 // part of the format in the call to configure and 1054 // if there's more csd left, we submit it here 1055 // clients only get access to input buffers once 1056 // this data has been exhausted. 1057 1058 status_t err = queueCSDInputBuffer(index); 1059 1060 if (err != OK) { 1061 ALOGE("queueCSDInputBuffer failed w/ error %d", 1062 err); 1063 1064 setStickyError(err); 1065 postActivityNotificationIfPossible(); 1066 1067 cancelPendingDequeueOperations(); 1068 } 1069 break; 1070 } 1071 1072 if (mFlags & kFlagIsAsync) { 1073 if (!mHaveInputSurface) { 1074 onInputBufferAvailable(); 1075 } 1076 } else if (mFlags & kFlagDequeueInputPending) { 1077 CHECK(handleDequeueInputBuffer(mDequeueInputReplyID)); 1078 1079 ++mDequeueInputTimeoutGeneration; 1080 mFlags &= ~kFlagDequeueInputPending; 1081 mDequeueInputReplyID = 0; 1082 } else { 1083 postActivityNotificationIfPossible(); 1084 } 1085 break; 1086 } 1087 1088 case CodecBase::kWhatDrainThisBuffer: 1089 { 1090 /* size_t index = */updateBuffers(kPortIndexOutput, msg); 1091 1092 if (mState == FLUSHING 1093 || mState == STOPPING 1094 || mState == RELEASING) { 1095 returnBuffersToCodecOnPort(kPortIndexOutput); 1096 break; 1097 } 1098 1099 sp<ABuffer> buffer; 1100 CHECK(msg->findBuffer("buffer", &buffer)); 1101 1102 int32_t omxFlags; 1103 CHECK(msg->findInt32("flags", &omxFlags)); 1104 1105 buffer->meta()->setInt32("omxFlags", omxFlags); 1106 1107 if (mFlags & kFlagGatherCodecSpecificData) { 1108 // This is the very first output buffer after a 1109 // format change was signalled, it'll either contain 1110 // the one piece of codec specific data we can expect 1111 // or there won't be codec specific data. 1112 if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) { 1113 status_t err = 1114 amendOutputFormatWithCodecSpecificData(buffer); 1115 1116 if (err != OK) { 1117 ALOGE("Codec spit out malformed codec " 1118 "specific data!"); 1119 } 1120 } 1121 1122 mFlags &= ~kFlagGatherCodecSpecificData; 1123 if (mFlags & kFlagIsAsync) { 1124 onOutputFormatChanged(); 1125 } else { 1126 mFlags |= kFlagOutputFormatChanged; 1127 } 1128 } 1129 1130 if (mFlags & kFlagIsAsync) { 1131 onOutputBufferAvailable(); 1132 } else if (mFlags & kFlagDequeueOutputPending) { 1133 CHECK(handleDequeueOutputBuffer(mDequeueOutputReplyID)); 1134 1135 ++mDequeueOutputTimeoutGeneration; 1136 mFlags &= ~kFlagDequeueOutputPending; 1137 mDequeueOutputReplyID = 0; 1138 } else { 1139 postActivityNotificationIfPossible(); 1140 } 1141 1142 break; 1143 } 1144 1145 case CodecBase::kWhatEOS: 1146 { 1147 // We already notify the client of this by using the 1148 // corresponding flag in "onOutputBufferReady". 1149 break; 1150 } 1151 1152 case CodecBase::kWhatShutdownCompleted: 1153 { 1154 if (mState == STOPPING) { 1155 setState(INITIALIZED); 1156 } else { 1157 CHECK_EQ(mState, RELEASING); 1158 setState(UNINITIALIZED); 1159 mComponentName.clear(); 1160 } 1161 mFlags &= ~kFlagIsComponentAllocated; 1162 1163 (new AMessage)->postReply(mReplyID); 1164 break; 1165 } 1166 1167 case CodecBase::kWhatFlushCompleted: 1168 { 1169 if (mState != FLUSHING) { 1170 ALOGW("received FlushCompleted message in state %d", 1171 mState); 1172 break; 1173 } 1174 1175 if (mFlags & kFlagIsAsync) { 1176 setState(FLUSHED); 1177 } else { 1178 setState(STARTED); 1179 mCodec->signalResume(); 1180 } 1181 1182 (new AMessage)->postReply(mReplyID); 1183 break; 1184 } 1185 1186 default: 1187 TRESPASS(); 1188 } 1189 break; 1190 } 1191 1192 case kWhatInit: 1193 { 1194 uint32_t replyID; 1195 CHECK(msg->senderAwaitsResponse(&replyID)); 1196 1197 if (mState != UNINITIALIZED) { 1198 PostReplyWithError(replyID, INVALID_OPERATION); 1199 break; 1200 } 1201 1202 mReplyID = replyID; 1203 setState(INITIALIZING); 1204 1205 AString name; 1206 CHECK(msg->findString("name", &name)); 1207 1208 int32_t nameIsType; 1209 int32_t encoder = false; 1210 CHECK(msg->findInt32("nameIsType", &nameIsType)); 1211 if (nameIsType) { 1212 CHECK(msg->findInt32("encoder", &encoder)); 1213 } 1214 1215 sp<AMessage> format = new AMessage; 1216 1217 if (nameIsType) { 1218 format->setString("mime", name.c_str()); 1219 format->setInt32("encoder", encoder); 1220 } else { 1221 format->setString("componentName", name.c_str()); 1222 } 1223 1224 mCodec->initiateAllocateComponent(format); 1225 break; 1226 } 1227 1228 case kWhatSetCallback: 1229 { 1230 uint32_t replyID; 1231 CHECK(msg->senderAwaitsResponse(&replyID)); 1232 1233 if (mState == UNINITIALIZED 1234 || mState == INITIALIZING 1235 || isExecuting()) { 1236 // callback can't be set after codec is executing, 1237 // or before it's initialized (as the callback 1238 // will be cleared when it goes to INITIALIZED) 1239 PostReplyWithError(replyID, INVALID_OPERATION); 1240 break; 1241 } 1242 1243 sp<AMessage> callback; 1244 CHECK(msg->findMessage("callback", &callback)); 1245 1246 mCallback = callback; 1247 1248 if (mCallback != NULL) { 1249 ALOGI("MediaCodec will operate in async mode"); 1250 mFlags |= kFlagIsAsync; 1251 } else { 1252 mFlags &= ~kFlagIsAsync; 1253 } 1254 1255 sp<AMessage> response = new AMessage; 1256 response->postReply(replyID); 1257 break; 1258 } 1259 1260 case kWhatConfigure: 1261 { 1262 uint32_t replyID; 1263 CHECK(msg->senderAwaitsResponse(&replyID)); 1264 1265 if (mState != INITIALIZED) { 1266 PostReplyWithError(replyID, INVALID_OPERATION); 1267 break; 1268 } 1269 1270 sp<RefBase> obj; 1271 if (!msg->findObject("native-window", &obj)) { 1272 obj.clear(); 1273 } 1274 1275 sp<AMessage> format; 1276 CHECK(msg->findMessage("format", &format)); 1277 1278 if (obj != NULL) { 1279 format->setObject("native-window", obj); 1280 1281 status_t err = setNativeWindow( 1282 static_cast<NativeWindowWrapper *>(obj.get()) 1283 ->getSurfaceTextureClient()); 1284 1285 if (err != OK) { 1286 PostReplyWithError(replyID, err); 1287 break; 1288 } 1289 } else { 1290 setNativeWindow(NULL); 1291 } 1292 1293 mReplyID = replyID; 1294 setState(CONFIGURING); 1295 1296 void *crypto; 1297 if (!msg->findPointer("crypto", &crypto)) { 1298 crypto = NULL; 1299 } 1300 1301 mCrypto = static_cast<ICrypto *>(crypto); 1302 1303 uint32_t flags; 1304 CHECK(msg->findInt32("flags", (int32_t *)&flags)); 1305 1306 if (flags & CONFIGURE_FLAG_ENCODE) { 1307 format->setInt32("encoder", true); 1308 mFlags |= kFlagIsEncoder; 1309 } 1310 1311 extractCSD(format); 1312 1313 mCodec->initiateConfigureComponent(format); 1314 break; 1315 } 1316 1317 case kWhatCreateInputSurface: 1318 { 1319 uint32_t replyID; 1320 CHECK(msg->senderAwaitsResponse(&replyID)); 1321 1322 // Must be configured, but can't have been started yet. 1323 if (mState != CONFIGURED) { 1324 PostReplyWithError(replyID, INVALID_OPERATION); 1325 break; 1326 } 1327 1328 mReplyID = replyID; 1329 mCodec->initiateCreateInputSurface(); 1330 break; 1331 } 1332 1333 case kWhatStart: 1334 { 1335 uint32_t replyID; 1336 CHECK(msg->senderAwaitsResponse(&replyID)); 1337 1338 if (mState == FLUSHED) { 1339 setState(STARTED); 1340 mCodec->signalResume(); 1341 PostReplyWithError(replyID, OK); 1342 break; 1343 } else if (mState != CONFIGURED) { 1344 PostReplyWithError(replyID, INVALID_OPERATION); 1345 break; 1346 } 1347 1348 mReplyID = replyID; 1349 setState(STARTING); 1350 1351 mCodec->initiateStart(); 1352 break; 1353 } 1354 1355 case kWhatStop: 1356 case kWhatRelease: 1357 { 1358 State targetState = 1359 (msg->what() == kWhatStop) ? INITIALIZED : UNINITIALIZED; 1360 1361 uint32_t replyID; 1362 CHECK(msg->senderAwaitsResponse(&replyID)); 1363 1364 if (!((mFlags & kFlagIsComponentAllocated) && targetState == UNINITIALIZED) // See 1 1365 && mState != INITIALIZED 1366 && mState != CONFIGURED && !isExecuting()) { 1367 // 1) Permit release to shut down the component if allocated. 1368 // 1369 // 2) We may be in "UNINITIALIZED" state already and 1370 // also shutdown the encoder/decoder without the 1371 // client being aware of this if media server died while 1372 // we were being stopped. The client would assume that 1373 // after stop() returned, it would be safe to call release() 1374 // and it should be in this case, no harm to allow a release() 1375 // if we're already uninitialized. 1376 sp<AMessage> response = new AMessage; 1377 status_t err = mState == targetState ? OK : INVALID_OPERATION; 1378 response->setInt32("err", err); 1379 if (err == OK && targetState == UNINITIALIZED) { 1380 mComponentName.clear(); 1381 } 1382 response->postReply(replyID); 1383 break; 1384 } 1385 1386 if (mFlags & kFlagSawMediaServerDie) { 1387 // It's dead, Jim. Don't expect initiateShutdown to yield 1388 // any useful results now... 1389 setState(UNINITIALIZED); 1390 if (targetState == UNINITIALIZED) { 1391 mComponentName.clear(); 1392 } 1393 (new AMessage)->postReply(replyID); 1394 break; 1395 } 1396 1397 mReplyID = replyID; 1398 setState(msg->what() == kWhatStop ? STOPPING : RELEASING); 1399 1400 mCodec->initiateShutdown( 1401 msg->what() == kWhatStop /* keepComponentAllocated */); 1402 1403 returnBuffersToCodec(); 1404 break; 1405 } 1406 1407 case kWhatDequeueInputBuffer: 1408 { 1409 uint32_t replyID; 1410 CHECK(msg->senderAwaitsResponse(&replyID)); 1411 1412 if (mFlags & kFlagIsAsync) { 1413 ALOGE("dequeueOutputBuffer can't be used in async mode"); 1414 PostReplyWithError(replyID, INVALID_OPERATION); 1415 break; 1416 } 1417 1418 if (mHaveInputSurface) { 1419 ALOGE("dequeueInputBuffer can't be used with input surface"); 1420 PostReplyWithError(replyID, INVALID_OPERATION); 1421 break; 1422 } 1423 1424 if (handleDequeueInputBuffer(replyID, true /* new request */)) { 1425 break; 1426 } 1427 1428 int64_t timeoutUs; 1429 CHECK(msg->findInt64("timeoutUs", &timeoutUs)); 1430 1431 if (timeoutUs == 0ll) { 1432 PostReplyWithError(replyID, -EAGAIN); 1433 break; 1434 } 1435 1436 mFlags |= kFlagDequeueInputPending; 1437 mDequeueInputReplyID = replyID; 1438 1439 if (timeoutUs > 0ll) { 1440 sp<AMessage> timeoutMsg = 1441 new AMessage(kWhatDequeueInputTimedOut, id()); 1442 timeoutMsg->setInt32( 1443 "generation", ++mDequeueInputTimeoutGeneration); 1444 timeoutMsg->post(timeoutUs); 1445 } 1446 break; 1447 } 1448 1449 case kWhatDequeueInputTimedOut: 1450 { 1451 int32_t generation; 1452 CHECK(msg->findInt32("generation", &generation)); 1453 1454 if (generation != mDequeueInputTimeoutGeneration) { 1455 // Obsolete 1456 break; 1457 } 1458 1459 CHECK(mFlags & kFlagDequeueInputPending); 1460 1461 PostReplyWithError(mDequeueInputReplyID, -EAGAIN); 1462 1463 mFlags &= ~kFlagDequeueInputPending; 1464 mDequeueInputReplyID = 0; 1465 break; 1466 } 1467 1468 case kWhatQueueInputBuffer: 1469 { 1470 uint32_t replyID; 1471 CHECK(msg->senderAwaitsResponse(&replyID)); 1472 1473 if (!isExecuting()) { 1474 PostReplyWithError(replyID, INVALID_OPERATION); 1475 break; 1476 } else if (mFlags & kFlagStickyError) { 1477 PostReplyWithError(replyID, getStickyError()); 1478 break; 1479 } 1480 1481 status_t err = onQueueInputBuffer(msg); 1482 1483 PostReplyWithError(replyID, err); 1484 break; 1485 } 1486 1487 case kWhatDequeueOutputBuffer: 1488 { 1489 uint32_t replyID; 1490 CHECK(msg->senderAwaitsResponse(&replyID)); 1491 1492 if (mFlags & kFlagIsAsync) { 1493 ALOGE("dequeueOutputBuffer can't be used in async mode"); 1494 PostReplyWithError(replyID, INVALID_OPERATION); 1495 break; 1496 } 1497 1498 if (handleDequeueOutputBuffer(replyID, true /* new request */)) { 1499 break; 1500 } 1501 1502 int64_t timeoutUs; 1503 CHECK(msg->findInt64("timeoutUs", &timeoutUs)); 1504 1505 if (timeoutUs == 0ll) { 1506 PostReplyWithError(replyID, -EAGAIN); 1507 break; 1508 } 1509 1510 mFlags |= kFlagDequeueOutputPending; 1511 mDequeueOutputReplyID = replyID; 1512 1513 if (timeoutUs > 0ll) { 1514 sp<AMessage> timeoutMsg = 1515 new AMessage(kWhatDequeueOutputTimedOut, id()); 1516 timeoutMsg->setInt32( 1517 "generation", ++mDequeueOutputTimeoutGeneration); 1518 timeoutMsg->post(timeoutUs); 1519 } 1520 break; 1521 } 1522 1523 case kWhatDequeueOutputTimedOut: 1524 { 1525 int32_t generation; 1526 CHECK(msg->findInt32("generation", &generation)); 1527 1528 if (generation != mDequeueOutputTimeoutGeneration) { 1529 // Obsolete 1530 break; 1531 } 1532 1533 CHECK(mFlags & kFlagDequeueOutputPending); 1534 1535 PostReplyWithError(mDequeueOutputReplyID, -EAGAIN); 1536 1537 mFlags &= ~kFlagDequeueOutputPending; 1538 mDequeueOutputReplyID = 0; 1539 break; 1540 } 1541 1542 case kWhatReleaseOutputBuffer: 1543 { 1544 uint32_t replyID; 1545 CHECK(msg->senderAwaitsResponse(&replyID)); 1546 1547 if (!isExecuting()) { 1548 PostReplyWithError(replyID, INVALID_OPERATION); 1549 break; 1550 } else if (mFlags & kFlagStickyError) { 1551 PostReplyWithError(replyID, getStickyError()); 1552 break; 1553 } 1554 1555 status_t err = onReleaseOutputBuffer(msg); 1556 1557 PostReplyWithError(replyID, err); 1558 break; 1559 } 1560 1561 case kWhatSignalEndOfInputStream: 1562 { 1563 uint32_t replyID; 1564 CHECK(msg->senderAwaitsResponse(&replyID)); 1565 1566 if (!isExecuting()) { 1567 PostReplyWithError(replyID, INVALID_OPERATION); 1568 break; 1569 } else if (mFlags & kFlagStickyError) { 1570 PostReplyWithError(replyID, getStickyError()); 1571 break; 1572 } 1573 1574 mReplyID = replyID; 1575 mCodec->signalEndOfInputStream(); 1576 break; 1577 } 1578 1579 case kWhatGetBuffers: 1580 { 1581 uint32_t replyID; 1582 CHECK(msg->senderAwaitsResponse(&replyID)); 1583 1584 if (!isExecuting() || (mFlags & kFlagIsAsync)) { 1585 PostReplyWithError(replyID, INVALID_OPERATION); 1586 break; 1587 } else if (mFlags & kFlagStickyError) { 1588 PostReplyWithError(replyID, getStickyError()); 1589 break; 1590 } 1591 1592 int32_t portIndex; 1593 CHECK(msg->findInt32("portIndex", &portIndex)); 1594 1595 Vector<sp<ABuffer> > *dstBuffers; 1596 CHECK(msg->findPointer("buffers", (void **)&dstBuffers)); 1597 1598 dstBuffers->clear(); 1599 const Vector<BufferInfo> &srcBuffers = mPortBuffers[portIndex]; 1600 1601 for (size_t i = 0; i < srcBuffers.size(); ++i) { 1602 const BufferInfo &info = srcBuffers.itemAt(i); 1603 1604 dstBuffers->push_back( 1605 (portIndex == kPortIndexInput && mCrypto != NULL) 1606 ? info.mEncryptedData : info.mData); 1607 } 1608 1609 (new AMessage)->postReply(replyID); 1610 break; 1611 } 1612 1613 case kWhatFlush: 1614 { 1615 uint32_t replyID; 1616 CHECK(msg->senderAwaitsResponse(&replyID)); 1617 1618 if (!isExecuting()) { 1619 PostReplyWithError(replyID, INVALID_OPERATION); 1620 break; 1621 } else if (mFlags & kFlagStickyError) { 1622 PostReplyWithError(replyID, getStickyError()); 1623 break; 1624 } 1625 1626 mReplyID = replyID; 1627 // TODO: skip flushing if already FLUSHED 1628 setState(FLUSHING); 1629 1630 mCodec->signalFlush(); 1631 returnBuffersToCodec(); 1632 break; 1633 } 1634 1635 case kWhatGetInputFormat: 1636 case kWhatGetOutputFormat: 1637 { 1638 sp<AMessage> format = 1639 (msg->what() == kWhatGetOutputFormat ? mOutputFormat : mInputFormat); 1640 1641 uint32_t replyID; 1642 CHECK(msg->senderAwaitsResponse(&replyID)); 1643 1644 if ((mState != CONFIGURED && mState != STARTING && 1645 mState != STARTED && mState != FLUSHING && 1646 mState != FLUSHED) 1647 || format == NULL) { 1648 PostReplyWithError(replyID, INVALID_OPERATION); 1649 break; 1650 } else if (mFlags & kFlagStickyError) { 1651 PostReplyWithError(replyID, getStickyError()); 1652 break; 1653 } 1654 1655 sp<AMessage> response = new AMessage; 1656 response->setMessage("format", format); 1657 response->postReply(replyID); 1658 break; 1659 } 1660 1661 case kWhatRequestIDRFrame: 1662 { 1663 mCodec->signalRequestIDRFrame(); 1664 break; 1665 } 1666 1667 case kWhatRequestActivityNotification: 1668 { 1669 CHECK(mActivityNotify == NULL); 1670 CHECK(msg->findMessage("notify", &mActivityNotify)); 1671 1672 postActivityNotificationIfPossible(); 1673 break; 1674 } 1675 1676 case kWhatGetName: 1677 { 1678 uint32_t replyID; 1679 CHECK(msg->senderAwaitsResponse(&replyID)); 1680 1681 if (mComponentName.empty()) { 1682 PostReplyWithError(replyID, INVALID_OPERATION); 1683 break; 1684 } 1685 1686 sp<AMessage> response = new AMessage; 1687 response->setString("name", mComponentName.c_str()); 1688 response->postReply(replyID); 1689 break; 1690 } 1691 1692 case kWhatSetParameters: 1693 { 1694 uint32_t replyID; 1695 CHECK(msg->senderAwaitsResponse(&replyID)); 1696 1697 sp<AMessage> params; 1698 CHECK(msg->findMessage("params", ¶ms)); 1699 1700 status_t err = onSetParameters(params); 1701 1702 PostReplyWithError(replyID, err); 1703 break; 1704 } 1705 1706 default: 1707 TRESPASS(); 1708 } 1709} 1710 1711void MediaCodec::extractCSD(const sp<AMessage> &format) { 1712 mCSD.clear(); 1713 1714 size_t i = 0; 1715 for (;;) { 1716 sp<ABuffer> csd; 1717 if (!format->findBuffer(StringPrintf("csd-%u", i).c_str(), &csd)) { 1718 break; 1719 } 1720 1721 mCSD.push_back(csd); 1722 ++i; 1723 } 1724 1725 ALOGV("Found %zu pieces of codec specific data.", mCSD.size()); 1726} 1727 1728status_t MediaCodec::queueCSDInputBuffer(size_t bufferIndex) { 1729 CHECK(!mCSD.empty()); 1730 1731 const BufferInfo *info = 1732 &mPortBuffers[kPortIndexInput].itemAt(bufferIndex); 1733 1734 sp<ABuffer> csd = *mCSD.begin(); 1735 mCSD.erase(mCSD.begin()); 1736 1737 const sp<ABuffer> &codecInputData = 1738 (mCrypto != NULL) ? info->mEncryptedData : info->mData; 1739 1740 if (csd->size() > codecInputData->capacity()) { 1741 return -EINVAL; 1742 } 1743 1744 memcpy(codecInputData->data(), csd->data(), csd->size()); 1745 1746 AString errorDetailMsg; 1747 1748 sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, id()); 1749 msg->setSize("index", bufferIndex); 1750 msg->setSize("offset", 0); 1751 msg->setSize("size", csd->size()); 1752 msg->setInt64("timeUs", 0ll); 1753 msg->setInt32("flags", BUFFER_FLAG_CODECCONFIG); 1754 msg->setPointer("errorDetailMsg", &errorDetailMsg); 1755 1756 return onQueueInputBuffer(msg); 1757} 1758 1759void MediaCodec::setState(State newState) { 1760 if (newState == INITIALIZED || newState == UNINITIALIZED) { 1761 delete mSoftRenderer; 1762 mSoftRenderer = NULL; 1763 1764 mCrypto.clear(); 1765 setNativeWindow(NULL); 1766 1767 mInputFormat.clear(); 1768 mOutputFormat.clear(); 1769 mFlags &= ~kFlagOutputFormatChanged; 1770 mFlags &= ~kFlagOutputBuffersChanged; 1771 mFlags &= ~kFlagStickyError; 1772 mFlags &= ~kFlagIsEncoder; 1773 mFlags &= ~kFlagGatherCodecSpecificData; 1774 mFlags &= ~kFlagIsAsync; 1775 mStickyError = OK; 1776 1777 mActivityNotify.clear(); 1778 mCallback.clear(); 1779 } 1780 1781 if (newState == UNINITIALIZED) { 1782 // return any straggling buffers, e.g. if we got here on an error 1783 returnBuffersToCodec(); 1784 1785 // The component is gone, mediaserver's probably back up already 1786 // but should definitely be back up should we try to instantiate 1787 // another component.. and the cycle continues. 1788 mFlags &= ~kFlagSawMediaServerDie; 1789 } 1790 1791 mState = newState; 1792 1793 cancelPendingDequeueOperations(); 1794 1795 updateBatteryStat(); 1796} 1797 1798void MediaCodec::returnBuffersToCodec() { 1799 returnBuffersToCodecOnPort(kPortIndexInput); 1800 returnBuffersToCodecOnPort(kPortIndexOutput); 1801} 1802 1803void MediaCodec::returnBuffersToCodecOnPort(int32_t portIndex) { 1804 CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); 1805 Mutex::Autolock al(mBufferLock); 1806 1807 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 1808 1809 for (size_t i = 0; i < buffers->size(); ++i) { 1810 BufferInfo *info = &buffers->editItemAt(i); 1811 1812 if (info->mNotify != NULL) { 1813 sp<AMessage> msg = info->mNotify; 1814 info->mNotify = NULL; 1815 info->mOwnedByClient = false; 1816 1817 if (portIndex == kPortIndexInput) { 1818 /* no error, just returning buffers */ 1819 msg->setInt32("err", OK); 1820 } 1821 msg->post(); 1822 } 1823 } 1824 1825 mAvailPortBuffers[portIndex].clear(); 1826} 1827 1828size_t MediaCodec::updateBuffers( 1829 int32_t portIndex, const sp<AMessage> &msg) { 1830 CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); 1831 1832 uint32_t bufferID; 1833 CHECK(msg->findInt32("buffer-id", (int32_t*)&bufferID)); 1834 1835 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 1836 1837 for (size_t i = 0; i < buffers->size(); ++i) { 1838 BufferInfo *info = &buffers->editItemAt(i); 1839 1840 if (info->mBufferID == bufferID) { 1841 CHECK(info->mNotify == NULL); 1842 CHECK(msg->findMessage("reply", &info->mNotify)); 1843 1844 info->mFormat = 1845 (portIndex == kPortIndexInput) ? mInputFormat : mOutputFormat; 1846 mAvailPortBuffers[portIndex].push_back(i); 1847 1848 return i; 1849 } 1850 } 1851 1852 TRESPASS(); 1853 1854 return 0; 1855} 1856 1857status_t MediaCodec::onQueueInputBuffer(const sp<AMessage> &msg) { 1858 size_t index; 1859 size_t offset; 1860 size_t size; 1861 int64_t timeUs; 1862 uint32_t flags; 1863 CHECK(msg->findSize("index", &index)); 1864 CHECK(msg->findSize("offset", &offset)); 1865 CHECK(msg->findInt64("timeUs", &timeUs)); 1866 CHECK(msg->findInt32("flags", (int32_t *)&flags)); 1867 1868 const CryptoPlugin::SubSample *subSamples; 1869 size_t numSubSamples; 1870 const uint8_t *key; 1871 const uint8_t *iv; 1872 CryptoPlugin::Mode mode = CryptoPlugin::kMode_Unencrypted; 1873 1874 // We allow the simpler queueInputBuffer API to be used even in 1875 // secure mode, by fabricating a single unencrypted subSample. 1876 CryptoPlugin::SubSample ss; 1877 1878 if (msg->findSize("size", &size)) { 1879 if (mCrypto != NULL) { 1880 ss.mNumBytesOfClearData = size; 1881 ss.mNumBytesOfEncryptedData = 0; 1882 1883 subSamples = &ss; 1884 numSubSamples = 1; 1885 key = NULL; 1886 iv = NULL; 1887 } 1888 } else { 1889 if (mCrypto == NULL) { 1890 return -EINVAL; 1891 } 1892 1893 CHECK(msg->findPointer("subSamples", (void **)&subSamples)); 1894 CHECK(msg->findSize("numSubSamples", &numSubSamples)); 1895 CHECK(msg->findPointer("key", (void **)&key)); 1896 CHECK(msg->findPointer("iv", (void **)&iv)); 1897 1898 int32_t tmp; 1899 CHECK(msg->findInt32("mode", &tmp)); 1900 1901 mode = (CryptoPlugin::Mode)tmp; 1902 1903 size = 0; 1904 for (size_t i = 0; i < numSubSamples; ++i) { 1905 size += subSamples[i].mNumBytesOfClearData; 1906 size += subSamples[i].mNumBytesOfEncryptedData; 1907 } 1908 } 1909 1910 if (index >= mPortBuffers[kPortIndexInput].size()) { 1911 return -ERANGE; 1912 } 1913 1914 BufferInfo *info = &mPortBuffers[kPortIndexInput].editItemAt(index); 1915 1916 if (info->mNotify == NULL || !info->mOwnedByClient) { 1917 return -EACCES; 1918 } 1919 1920 if (offset + size > info->mData->capacity()) { 1921 return -EINVAL; 1922 } 1923 1924 sp<AMessage> reply = info->mNotify; 1925 info->mData->setRange(offset, size); 1926 info->mData->meta()->setInt64("timeUs", timeUs); 1927 1928 if (flags & BUFFER_FLAG_EOS) { 1929 info->mData->meta()->setInt32("eos", true); 1930 } 1931 1932 if (flags & BUFFER_FLAG_CODECCONFIG) { 1933 info->mData->meta()->setInt32("csd", true); 1934 } 1935 1936 if (mCrypto != NULL) { 1937 if (size > info->mEncryptedData->capacity()) { 1938 return -ERANGE; 1939 } 1940 1941 AString *errorDetailMsg; 1942 CHECK(msg->findPointer("errorDetailMsg", (void **)&errorDetailMsg)); 1943 1944 ssize_t result = mCrypto->decrypt( 1945 (mFlags & kFlagIsSecure) != 0, 1946 key, 1947 iv, 1948 mode, 1949 info->mEncryptedData->base() + offset, 1950 subSamples, 1951 numSubSamples, 1952 info->mData->base(), 1953 errorDetailMsg); 1954 1955 if (result < 0) { 1956 return result; 1957 } 1958 1959 info->mData->setRange(0, result); 1960 } 1961 1962 // synchronization boundary for getBufferAndFormat 1963 { 1964 Mutex::Autolock al(mBufferLock); 1965 info->mOwnedByClient = false; 1966 } 1967 reply->setBuffer("buffer", info->mData); 1968 reply->post(); 1969 1970 info->mNotify = NULL; 1971 1972 return OK; 1973} 1974 1975status_t MediaCodec::onReleaseOutputBuffer(const sp<AMessage> &msg) { 1976 size_t index; 1977 CHECK(msg->findSize("index", &index)); 1978 1979 int32_t render; 1980 if (!msg->findInt32("render", &render)) { 1981 render = 0; 1982 } 1983 1984 if (!isExecuting()) { 1985 return -EINVAL; 1986 } 1987 1988 if (index >= mPortBuffers[kPortIndexOutput].size()) { 1989 return -ERANGE; 1990 } 1991 1992 BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index); 1993 1994 if (info->mNotify == NULL || !info->mOwnedByClient) { 1995 return -EACCES; 1996 } 1997 1998 // synchronization boundary for getBufferAndFormat 1999 { 2000 Mutex::Autolock al(mBufferLock); 2001 info->mOwnedByClient = false; 2002 } 2003 2004 if (render && info->mData != NULL && info->mData->size() != 0) { 2005 info->mNotify->setInt32("render", true); 2006 2007 int64_t timestampNs = 0; 2008 if (msg->findInt64("timestampNs", ×tampNs)) { 2009 info->mNotify->setInt64("timestampNs", timestampNs); 2010 } else { 2011 // TODO: it seems like we should use the timestamp 2012 // in the (media)buffer as it potentially came from 2013 // an input surface, but we did not propagate it prior to 2014 // API 20. Perhaps check for target SDK version. 2015#if 0 2016 if (info->mData->meta()->findInt64("timeUs", ×tampNs)) { 2017 ALOGV("using buffer PTS of %" PRId64, timestampNs); 2018 timestampNs *= 1000; 2019 } 2020#endif 2021 } 2022 2023 if (mSoftRenderer != NULL) { 2024 mSoftRenderer->render( 2025 info->mData->data(), info->mData->size(), 2026 timestampNs, NULL, info->mFormat); 2027 } 2028 } 2029 2030 info->mNotify->post(); 2031 info->mNotify = NULL; 2032 2033 return OK; 2034} 2035 2036ssize_t MediaCodec::dequeuePortBuffer(int32_t portIndex) { 2037 CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); 2038 2039 List<size_t> *availBuffers = &mAvailPortBuffers[portIndex]; 2040 2041 if (availBuffers->empty()) { 2042 return -EAGAIN; 2043 } 2044 2045 size_t index = *availBuffers->begin(); 2046 availBuffers->erase(availBuffers->begin()); 2047 2048 BufferInfo *info = &mPortBuffers[portIndex].editItemAt(index); 2049 CHECK(!info->mOwnedByClient); 2050 { 2051 Mutex::Autolock al(mBufferLock); 2052 info->mOwnedByClient = true; 2053 2054 // set image-data 2055 if (info->mFormat != NULL) { 2056 sp<ABuffer> imageData; 2057 if (info->mFormat->findBuffer("image-data", &imageData)) { 2058 info->mData->meta()->setBuffer("image-data", imageData); 2059 } 2060 int32_t left, top, right, bottom; 2061 if (info->mFormat->findRect("crop", &left, &top, &right, &bottom)) { 2062 info->mData->meta()->setRect("crop-rect", left, top, right, bottom); 2063 } 2064 } 2065 } 2066 2067 return index; 2068} 2069 2070status_t MediaCodec::setNativeWindow( 2071 const sp<Surface> &surfaceTextureClient) { 2072 status_t err; 2073 2074 if (mNativeWindow != NULL) { 2075 err = native_window_api_disconnect( 2076 mNativeWindow.get(), NATIVE_WINDOW_API_MEDIA); 2077 2078 if (err != OK) { 2079 ALOGW("native_window_api_disconnect returned an error: %s (%d)", 2080 strerror(-err), err); 2081 } 2082 2083 mNativeWindow.clear(); 2084 } 2085 2086 if (surfaceTextureClient != NULL) { 2087 err = native_window_api_connect( 2088 surfaceTextureClient.get(), NATIVE_WINDOW_API_MEDIA); 2089 2090 if (err != OK) { 2091 ALOGE("native_window_api_connect returned an error: %s (%d)", 2092 strerror(-err), err); 2093 2094 return err; 2095 } 2096 2097 mNativeWindow = surfaceTextureClient; 2098 } 2099 2100 return OK; 2101} 2102 2103void MediaCodec::onInputBufferAvailable() { 2104 int32_t index; 2105 while ((index = dequeuePortBuffer(kPortIndexInput)) >= 0) { 2106 sp<AMessage> msg = mCallback->dup(); 2107 msg->setInt32("callbackID", CB_INPUT_AVAILABLE); 2108 msg->setInt32("index", index); 2109 msg->post(); 2110 } 2111} 2112 2113void MediaCodec::onOutputBufferAvailable() { 2114 int32_t index; 2115 while ((index = dequeuePortBuffer(kPortIndexOutput)) >= 0) { 2116 const sp<ABuffer> &buffer = 2117 mPortBuffers[kPortIndexOutput].itemAt(index).mData; 2118 sp<AMessage> msg = mCallback->dup(); 2119 msg->setInt32("callbackID", CB_OUTPUT_AVAILABLE); 2120 msg->setInt32("index", index); 2121 msg->setSize("offset", buffer->offset()); 2122 msg->setSize("size", buffer->size()); 2123 2124 int64_t timeUs; 2125 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 2126 2127 msg->setInt64("timeUs", timeUs); 2128 2129 int32_t omxFlags; 2130 CHECK(buffer->meta()->findInt32("omxFlags", &omxFlags)); 2131 2132 uint32_t flags = 0; 2133 if (omxFlags & OMX_BUFFERFLAG_SYNCFRAME) { 2134 flags |= BUFFER_FLAG_SYNCFRAME; 2135 } 2136 if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) { 2137 flags |= BUFFER_FLAG_CODECCONFIG; 2138 } 2139 if (omxFlags & OMX_BUFFERFLAG_EOS) { 2140 flags |= BUFFER_FLAG_EOS; 2141 } 2142 2143 msg->setInt32("flags", flags); 2144 2145 msg->post(); 2146 } 2147} 2148 2149void MediaCodec::onError(status_t err, int32_t actionCode, const char *detail) { 2150 if (mCallback != NULL) { 2151 sp<AMessage> msg = mCallback->dup(); 2152 msg->setInt32("callbackID", CB_ERROR); 2153 msg->setInt32("err", err); 2154 msg->setInt32("actionCode", actionCode); 2155 2156 if (detail != NULL) { 2157 msg->setString("detail", detail); 2158 } 2159 2160 msg->post(); 2161 } 2162} 2163 2164void MediaCodec::onOutputFormatChanged() { 2165 if (mCallback != NULL) { 2166 sp<AMessage> msg = mCallback->dup(); 2167 msg->setInt32("callbackID", CB_OUTPUT_FORMAT_CHANGED); 2168 msg->setMessage("format", mOutputFormat); 2169 msg->post(); 2170 } 2171} 2172 2173 2174void MediaCodec::postActivityNotificationIfPossible() { 2175 if (mActivityNotify == NULL) { 2176 return; 2177 } 2178 2179 bool isErrorOrOutputChanged = 2180 (mFlags & (kFlagStickyError 2181 | kFlagOutputBuffersChanged 2182 | kFlagOutputFormatChanged)); 2183 2184 if (isErrorOrOutputChanged 2185 || !mAvailPortBuffers[kPortIndexInput].empty() 2186 || !mAvailPortBuffers[kPortIndexOutput].empty()) { 2187 mActivityNotify->setInt32("input-buffers", 2188 mAvailPortBuffers[kPortIndexInput].size()); 2189 2190 if (isErrorOrOutputChanged) { 2191 // we want consumer to dequeue as many times as it can 2192 mActivityNotify->setInt32("output-buffers", INT32_MAX); 2193 } else { 2194 mActivityNotify->setInt32("output-buffers", 2195 mAvailPortBuffers[kPortIndexOutput].size()); 2196 } 2197 mActivityNotify->post(); 2198 mActivityNotify.clear(); 2199 } 2200} 2201 2202status_t MediaCodec::setParameters(const sp<AMessage> ¶ms) { 2203 sp<AMessage> msg = new AMessage(kWhatSetParameters, id()); 2204 msg->setMessage("params", params); 2205 2206 sp<AMessage> response; 2207 return PostAndAwaitResponse(msg, &response); 2208} 2209 2210status_t MediaCodec::onSetParameters(const sp<AMessage> ¶ms) { 2211 mCodec->signalSetParameters(params); 2212 2213 return OK; 2214} 2215 2216status_t MediaCodec::amendOutputFormatWithCodecSpecificData( 2217 const sp<ABuffer> &buffer) { 2218 AString mime; 2219 CHECK(mOutputFormat->findString("mime", &mime)); 2220 2221 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) { 2222 // Codec specific data should be SPS and PPS in a single buffer, 2223 // each prefixed by a startcode (0x00 0x00 0x00 0x01). 2224 // We separate the two and put them into the output format 2225 // under the keys "csd-0" and "csd-1". 2226 2227 unsigned csdIndex = 0; 2228 2229 const uint8_t *data = buffer->data(); 2230 size_t size = buffer->size(); 2231 2232 const uint8_t *nalStart; 2233 size_t nalSize; 2234 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) { 2235 sp<ABuffer> csd = new ABuffer(nalSize + 4); 2236 memcpy(csd->data(), "\x00\x00\x00\x01", 4); 2237 memcpy(csd->data() + 4, nalStart, nalSize); 2238 2239 mOutputFormat->setBuffer( 2240 StringPrintf("csd-%u", csdIndex).c_str(), csd); 2241 2242 ++csdIndex; 2243 } 2244 2245 if (csdIndex != 2) { 2246 return ERROR_MALFORMED; 2247 } 2248 } else { 2249 // For everything else we just stash the codec specific data into 2250 // the output format as a single piece of csd under "csd-0". 2251 mOutputFormat->setBuffer("csd-0", buffer); 2252 } 2253 2254 return OK; 2255} 2256 2257void MediaCodec::updateBatteryStat() { 2258 if (mState == CONFIGURED && !mBatteryStatNotified) { 2259 AString mime; 2260 CHECK(mOutputFormat != NULL && 2261 mOutputFormat->findString("mime", &mime)); 2262 2263 mIsVideo = mime.startsWithIgnoreCase("video/"); 2264 2265 BatteryNotifier& notifier(BatteryNotifier::getInstance()); 2266 2267 if (mIsVideo) { 2268 notifier.noteStartVideo(); 2269 } else { 2270 notifier.noteStartAudio(); 2271 } 2272 2273 mBatteryStatNotified = true; 2274 } else if (mState == UNINITIALIZED && mBatteryStatNotified) { 2275 BatteryNotifier& notifier(BatteryNotifier::getInstance()); 2276 2277 if (mIsVideo) { 2278 notifier.noteStopVideo(); 2279 } else { 2280 notifier.noteStopAudio(); 2281 } 2282 2283 mBatteryStatNotified = false; 2284 } 2285} 2286 2287} // namespace android 2288