MediaCodec.cpp revision 197f84845ccea9319a1589b85edeb2dcf56b81b3
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 left, top, right, bottom, width, height; 1028 if (mOutputFormat->findRect("crop", &left, &top, &right, &bottom)) { 1029 mCrypto->notifyResolution(right - left + 1, bottom - top + 1); 1030 } else if (mOutputFormat->findInt32("width", &width) 1031 && mOutputFormat->findInt32("height", &height)) { 1032 mCrypto->notifyResolution(width, height); 1033 } 1034 } 1035 1036 break; 1037 } 1038 1039 case CodecBase::kWhatFillThisBuffer: 1040 { 1041 /* size_t index = */updateBuffers(kPortIndexInput, msg); 1042 1043 if (mState == FLUSHING 1044 || mState == STOPPING 1045 || mState == RELEASING) { 1046 returnBuffersToCodecOnPort(kPortIndexInput); 1047 break; 1048 } 1049 1050 if (!mCSD.empty()) { 1051 ssize_t index = dequeuePortBuffer(kPortIndexInput); 1052 CHECK_GE(index, 0); 1053 1054 // If codec specific data had been specified as 1055 // part of the format in the call to configure and 1056 // if there's more csd left, we submit it here 1057 // clients only get access to input buffers once 1058 // this data has been exhausted. 1059 1060 status_t err = queueCSDInputBuffer(index); 1061 1062 if (err != OK) { 1063 ALOGE("queueCSDInputBuffer failed w/ error %d", 1064 err); 1065 1066 setStickyError(err); 1067 postActivityNotificationIfPossible(); 1068 1069 cancelPendingDequeueOperations(); 1070 } 1071 break; 1072 } 1073 1074 if (mFlags & kFlagIsAsync) { 1075 if (!mHaveInputSurface) { 1076 onInputBufferAvailable(); 1077 } 1078 } else if (mFlags & kFlagDequeueInputPending) { 1079 CHECK(handleDequeueInputBuffer(mDequeueInputReplyID)); 1080 1081 ++mDequeueInputTimeoutGeneration; 1082 mFlags &= ~kFlagDequeueInputPending; 1083 mDequeueInputReplyID = 0; 1084 } else { 1085 postActivityNotificationIfPossible(); 1086 } 1087 break; 1088 } 1089 1090 case CodecBase::kWhatDrainThisBuffer: 1091 { 1092 /* size_t index = */updateBuffers(kPortIndexOutput, msg); 1093 1094 if (mState == FLUSHING 1095 || mState == STOPPING 1096 || mState == RELEASING) { 1097 returnBuffersToCodecOnPort(kPortIndexOutput); 1098 break; 1099 } 1100 1101 sp<ABuffer> buffer; 1102 CHECK(msg->findBuffer("buffer", &buffer)); 1103 1104 int32_t omxFlags; 1105 CHECK(msg->findInt32("flags", &omxFlags)); 1106 1107 buffer->meta()->setInt32("omxFlags", omxFlags); 1108 1109 if (mFlags & kFlagGatherCodecSpecificData) { 1110 // This is the very first output buffer after a 1111 // format change was signalled, it'll either contain 1112 // the one piece of codec specific data we can expect 1113 // or there won't be codec specific data. 1114 if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) { 1115 status_t err = 1116 amendOutputFormatWithCodecSpecificData(buffer); 1117 1118 if (err != OK) { 1119 ALOGE("Codec spit out malformed codec " 1120 "specific data!"); 1121 } 1122 } 1123 1124 mFlags &= ~kFlagGatherCodecSpecificData; 1125 if (mFlags & kFlagIsAsync) { 1126 onOutputFormatChanged(); 1127 } else { 1128 mFlags |= kFlagOutputFormatChanged; 1129 } 1130 } 1131 1132 if (mFlags & kFlagIsAsync) { 1133 onOutputBufferAvailable(); 1134 } else if (mFlags & kFlagDequeueOutputPending) { 1135 CHECK(handleDequeueOutputBuffer(mDequeueOutputReplyID)); 1136 1137 ++mDequeueOutputTimeoutGeneration; 1138 mFlags &= ~kFlagDequeueOutputPending; 1139 mDequeueOutputReplyID = 0; 1140 } else { 1141 postActivityNotificationIfPossible(); 1142 } 1143 1144 break; 1145 } 1146 1147 case CodecBase::kWhatEOS: 1148 { 1149 // We already notify the client of this by using the 1150 // corresponding flag in "onOutputBufferReady". 1151 break; 1152 } 1153 1154 case CodecBase::kWhatShutdownCompleted: 1155 { 1156 if (mState == STOPPING) { 1157 setState(INITIALIZED); 1158 } else { 1159 CHECK_EQ(mState, RELEASING); 1160 setState(UNINITIALIZED); 1161 mComponentName.clear(); 1162 } 1163 mFlags &= ~kFlagIsComponentAllocated; 1164 1165 (new AMessage)->postReply(mReplyID); 1166 break; 1167 } 1168 1169 case CodecBase::kWhatFlushCompleted: 1170 { 1171 if (mState != FLUSHING) { 1172 ALOGW("received FlushCompleted message in state %d", 1173 mState); 1174 break; 1175 } 1176 1177 if (mFlags & kFlagIsAsync) { 1178 setState(FLUSHED); 1179 } else { 1180 setState(STARTED); 1181 mCodec->signalResume(); 1182 } 1183 1184 (new AMessage)->postReply(mReplyID); 1185 break; 1186 } 1187 1188 default: 1189 TRESPASS(); 1190 } 1191 break; 1192 } 1193 1194 case kWhatInit: 1195 { 1196 uint32_t replyID; 1197 CHECK(msg->senderAwaitsResponse(&replyID)); 1198 1199 if (mState != UNINITIALIZED) { 1200 PostReplyWithError(replyID, INVALID_OPERATION); 1201 break; 1202 } 1203 1204 mReplyID = replyID; 1205 setState(INITIALIZING); 1206 1207 AString name; 1208 CHECK(msg->findString("name", &name)); 1209 1210 int32_t nameIsType; 1211 int32_t encoder = false; 1212 CHECK(msg->findInt32("nameIsType", &nameIsType)); 1213 if (nameIsType) { 1214 CHECK(msg->findInt32("encoder", &encoder)); 1215 } 1216 1217 sp<AMessage> format = new AMessage; 1218 1219 if (nameIsType) { 1220 format->setString("mime", name.c_str()); 1221 format->setInt32("encoder", encoder); 1222 } else { 1223 format->setString("componentName", name.c_str()); 1224 } 1225 1226 mCodec->initiateAllocateComponent(format); 1227 break; 1228 } 1229 1230 case kWhatSetCallback: 1231 { 1232 uint32_t replyID; 1233 CHECK(msg->senderAwaitsResponse(&replyID)); 1234 1235 if (mState == UNINITIALIZED 1236 || mState == INITIALIZING 1237 || isExecuting()) { 1238 // callback can't be set after codec is executing, 1239 // or before it's initialized (as the callback 1240 // will be cleared when it goes to INITIALIZED) 1241 PostReplyWithError(replyID, INVALID_OPERATION); 1242 break; 1243 } 1244 1245 sp<AMessage> callback; 1246 CHECK(msg->findMessage("callback", &callback)); 1247 1248 mCallback = callback; 1249 1250 if (mCallback != NULL) { 1251 ALOGI("MediaCodec will operate in async mode"); 1252 mFlags |= kFlagIsAsync; 1253 } else { 1254 mFlags &= ~kFlagIsAsync; 1255 } 1256 1257 sp<AMessage> response = new AMessage; 1258 response->postReply(replyID); 1259 break; 1260 } 1261 1262 case kWhatConfigure: 1263 { 1264 uint32_t replyID; 1265 CHECK(msg->senderAwaitsResponse(&replyID)); 1266 1267 if (mState != INITIALIZED) { 1268 PostReplyWithError(replyID, INVALID_OPERATION); 1269 break; 1270 } 1271 1272 sp<RefBase> obj; 1273 if (!msg->findObject("native-window", &obj)) { 1274 obj.clear(); 1275 } 1276 1277 sp<AMessage> format; 1278 CHECK(msg->findMessage("format", &format)); 1279 1280 if (obj != NULL) { 1281 format->setObject("native-window", obj); 1282 1283 status_t err = setNativeWindow( 1284 static_cast<NativeWindowWrapper *>(obj.get()) 1285 ->getSurfaceTextureClient()); 1286 1287 if (err != OK) { 1288 PostReplyWithError(replyID, err); 1289 break; 1290 } 1291 } else { 1292 setNativeWindow(NULL); 1293 } 1294 1295 mReplyID = replyID; 1296 setState(CONFIGURING); 1297 1298 void *crypto; 1299 if (!msg->findPointer("crypto", &crypto)) { 1300 crypto = NULL; 1301 } 1302 1303 mCrypto = static_cast<ICrypto *>(crypto); 1304 1305 uint32_t flags; 1306 CHECK(msg->findInt32("flags", (int32_t *)&flags)); 1307 1308 if (flags & CONFIGURE_FLAG_ENCODE) { 1309 format->setInt32("encoder", true); 1310 mFlags |= kFlagIsEncoder; 1311 } 1312 1313 extractCSD(format); 1314 1315 mCodec->initiateConfigureComponent(format); 1316 break; 1317 } 1318 1319 case kWhatCreateInputSurface: 1320 { 1321 uint32_t replyID; 1322 CHECK(msg->senderAwaitsResponse(&replyID)); 1323 1324 // Must be configured, but can't have been started yet. 1325 if (mState != CONFIGURED) { 1326 PostReplyWithError(replyID, INVALID_OPERATION); 1327 break; 1328 } 1329 1330 mReplyID = replyID; 1331 mCodec->initiateCreateInputSurface(); 1332 break; 1333 } 1334 1335 case kWhatStart: 1336 { 1337 uint32_t replyID; 1338 CHECK(msg->senderAwaitsResponse(&replyID)); 1339 1340 if (mState == FLUSHED) { 1341 setState(STARTED); 1342 mCodec->signalResume(); 1343 PostReplyWithError(replyID, OK); 1344 break; 1345 } else if (mState != CONFIGURED) { 1346 PostReplyWithError(replyID, INVALID_OPERATION); 1347 break; 1348 } 1349 1350 mReplyID = replyID; 1351 setState(STARTING); 1352 1353 mCodec->initiateStart(); 1354 break; 1355 } 1356 1357 case kWhatStop: 1358 case kWhatRelease: 1359 { 1360 State targetState = 1361 (msg->what() == kWhatStop) ? INITIALIZED : UNINITIALIZED; 1362 1363 uint32_t replyID; 1364 CHECK(msg->senderAwaitsResponse(&replyID)); 1365 1366 if (!((mFlags & kFlagIsComponentAllocated) && targetState == UNINITIALIZED) // See 1 1367 && mState != INITIALIZED 1368 && mState != CONFIGURED && !isExecuting()) { 1369 // 1) Permit release to shut down the component if allocated. 1370 // 1371 // 2) We may be in "UNINITIALIZED" state already and 1372 // also shutdown the encoder/decoder without the 1373 // client being aware of this if media server died while 1374 // we were being stopped. The client would assume that 1375 // after stop() returned, it would be safe to call release() 1376 // and it should be in this case, no harm to allow a release() 1377 // if we're already uninitialized. 1378 sp<AMessage> response = new AMessage; 1379 status_t err = mState == targetState ? OK : INVALID_OPERATION; 1380 response->setInt32("err", err); 1381 if (err == OK && targetState == UNINITIALIZED) { 1382 mComponentName.clear(); 1383 } 1384 response->postReply(replyID); 1385 break; 1386 } 1387 1388 if (mFlags & kFlagSawMediaServerDie) { 1389 // It's dead, Jim. Don't expect initiateShutdown to yield 1390 // any useful results now... 1391 setState(UNINITIALIZED); 1392 if (targetState == UNINITIALIZED) { 1393 mComponentName.clear(); 1394 } 1395 (new AMessage)->postReply(replyID); 1396 break; 1397 } 1398 1399 mReplyID = replyID; 1400 setState(msg->what() == kWhatStop ? STOPPING : RELEASING); 1401 1402 mCodec->initiateShutdown( 1403 msg->what() == kWhatStop /* keepComponentAllocated */); 1404 1405 returnBuffersToCodec(); 1406 break; 1407 } 1408 1409 case kWhatDequeueInputBuffer: 1410 { 1411 uint32_t replyID; 1412 CHECK(msg->senderAwaitsResponse(&replyID)); 1413 1414 if (mFlags & kFlagIsAsync) { 1415 ALOGE("dequeueOutputBuffer can't be used in async mode"); 1416 PostReplyWithError(replyID, INVALID_OPERATION); 1417 break; 1418 } 1419 1420 if (mHaveInputSurface) { 1421 ALOGE("dequeueInputBuffer can't be used with input surface"); 1422 PostReplyWithError(replyID, INVALID_OPERATION); 1423 break; 1424 } 1425 1426 if (handleDequeueInputBuffer(replyID, true /* new request */)) { 1427 break; 1428 } 1429 1430 int64_t timeoutUs; 1431 CHECK(msg->findInt64("timeoutUs", &timeoutUs)); 1432 1433 if (timeoutUs == 0ll) { 1434 PostReplyWithError(replyID, -EAGAIN); 1435 break; 1436 } 1437 1438 mFlags |= kFlagDequeueInputPending; 1439 mDequeueInputReplyID = replyID; 1440 1441 if (timeoutUs > 0ll) { 1442 sp<AMessage> timeoutMsg = 1443 new AMessage(kWhatDequeueInputTimedOut, id()); 1444 timeoutMsg->setInt32( 1445 "generation", ++mDequeueInputTimeoutGeneration); 1446 timeoutMsg->post(timeoutUs); 1447 } 1448 break; 1449 } 1450 1451 case kWhatDequeueInputTimedOut: 1452 { 1453 int32_t generation; 1454 CHECK(msg->findInt32("generation", &generation)); 1455 1456 if (generation != mDequeueInputTimeoutGeneration) { 1457 // Obsolete 1458 break; 1459 } 1460 1461 CHECK(mFlags & kFlagDequeueInputPending); 1462 1463 PostReplyWithError(mDequeueInputReplyID, -EAGAIN); 1464 1465 mFlags &= ~kFlagDequeueInputPending; 1466 mDequeueInputReplyID = 0; 1467 break; 1468 } 1469 1470 case kWhatQueueInputBuffer: 1471 { 1472 uint32_t replyID; 1473 CHECK(msg->senderAwaitsResponse(&replyID)); 1474 1475 if (!isExecuting()) { 1476 PostReplyWithError(replyID, INVALID_OPERATION); 1477 break; 1478 } else if (mFlags & kFlagStickyError) { 1479 PostReplyWithError(replyID, getStickyError()); 1480 break; 1481 } 1482 1483 status_t err = onQueueInputBuffer(msg); 1484 1485 PostReplyWithError(replyID, err); 1486 break; 1487 } 1488 1489 case kWhatDequeueOutputBuffer: 1490 { 1491 uint32_t replyID; 1492 CHECK(msg->senderAwaitsResponse(&replyID)); 1493 1494 if (mFlags & kFlagIsAsync) { 1495 ALOGE("dequeueOutputBuffer can't be used in async mode"); 1496 PostReplyWithError(replyID, INVALID_OPERATION); 1497 break; 1498 } 1499 1500 if (handleDequeueOutputBuffer(replyID, true /* new request */)) { 1501 break; 1502 } 1503 1504 int64_t timeoutUs; 1505 CHECK(msg->findInt64("timeoutUs", &timeoutUs)); 1506 1507 if (timeoutUs == 0ll) { 1508 PostReplyWithError(replyID, -EAGAIN); 1509 break; 1510 } 1511 1512 mFlags |= kFlagDequeueOutputPending; 1513 mDequeueOutputReplyID = replyID; 1514 1515 if (timeoutUs > 0ll) { 1516 sp<AMessage> timeoutMsg = 1517 new AMessage(kWhatDequeueOutputTimedOut, id()); 1518 timeoutMsg->setInt32( 1519 "generation", ++mDequeueOutputTimeoutGeneration); 1520 timeoutMsg->post(timeoutUs); 1521 } 1522 break; 1523 } 1524 1525 case kWhatDequeueOutputTimedOut: 1526 { 1527 int32_t generation; 1528 CHECK(msg->findInt32("generation", &generation)); 1529 1530 if (generation != mDequeueOutputTimeoutGeneration) { 1531 // Obsolete 1532 break; 1533 } 1534 1535 CHECK(mFlags & kFlagDequeueOutputPending); 1536 1537 PostReplyWithError(mDequeueOutputReplyID, -EAGAIN); 1538 1539 mFlags &= ~kFlagDequeueOutputPending; 1540 mDequeueOutputReplyID = 0; 1541 break; 1542 } 1543 1544 case kWhatReleaseOutputBuffer: 1545 { 1546 uint32_t replyID; 1547 CHECK(msg->senderAwaitsResponse(&replyID)); 1548 1549 if (!isExecuting()) { 1550 PostReplyWithError(replyID, INVALID_OPERATION); 1551 break; 1552 } else if (mFlags & kFlagStickyError) { 1553 PostReplyWithError(replyID, getStickyError()); 1554 break; 1555 } 1556 1557 status_t err = onReleaseOutputBuffer(msg); 1558 1559 PostReplyWithError(replyID, err); 1560 break; 1561 } 1562 1563 case kWhatSignalEndOfInputStream: 1564 { 1565 uint32_t replyID; 1566 CHECK(msg->senderAwaitsResponse(&replyID)); 1567 1568 if (!isExecuting()) { 1569 PostReplyWithError(replyID, INVALID_OPERATION); 1570 break; 1571 } else if (mFlags & kFlagStickyError) { 1572 PostReplyWithError(replyID, getStickyError()); 1573 break; 1574 } 1575 1576 mReplyID = replyID; 1577 mCodec->signalEndOfInputStream(); 1578 break; 1579 } 1580 1581 case kWhatGetBuffers: 1582 { 1583 uint32_t replyID; 1584 CHECK(msg->senderAwaitsResponse(&replyID)); 1585 1586 if (!isExecuting() || (mFlags & kFlagIsAsync)) { 1587 PostReplyWithError(replyID, INVALID_OPERATION); 1588 break; 1589 } else if (mFlags & kFlagStickyError) { 1590 PostReplyWithError(replyID, getStickyError()); 1591 break; 1592 } 1593 1594 int32_t portIndex; 1595 CHECK(msg->findInt32("portIndex", &portIndex)); 1596 1597 Vector<sp<ABuffer> > *dstBuffers; 1598 CHECK(msg->findPointer("buffers", (void **)&dstBuffers)); 1599 1600 dstBuffers->clear(); 1601 const Vector<BufferInfo> &srcBuffers = mPortBuffers[portIndex]; 1602 1603 for (size_t i = 0; i < srcBuffers.size(); ++i) { 1604 const BufferInfo &info = srcBuffers.itemAt(i); 1605 1606 dstBuffers->push_back( 1607 (portIndex == kPortIndexInput && mCrypto != NULL) 1608 ? info.mEncryptedData : info.mData); 1609 } 1610 1611 (new AMessage)->postReply(replyID); 1612 break; 1613 } 1614 1615 case kWhatFlush: 1616 { 1617 uint32_t replyID; 1618 CHECK(msg->senderAwaitsResponse(&replyID)); 1619 1620 if (!isExecuting()) { 1621 PostReplyWithError(replyID, INVALID_OPERATION); 1622 break; 1623 } else if (mFlags & kFlagStickyError) { 1624 PostReplyWithError(replyID, getStickyError()); 1625 break; 1626 } 1627 1628 mReplyID = replyID; 1629 // TODO: skip flushing if already FLUSHED 1630 setState(FLUSHING); 1631 1632 mCodec->signalFlush(); 1633 returnBuffersToCodec(); 1634 break; 1635 } 1636 1637 case kWhatGetInputFormat: 1638 case kWhatGetOutputFormat: 1639 { 1640 sp<AMessage> format = 1641 (msg->what() == kWhatGetOutputFormat ? mOutputFormat : mInputFormat); 1642 1643 uint32_t replyID; 1644 CHECK(msg->senderAwaitsResponse(&replyID)); 1645 1646 if ((mState != CONFIGURED && mState != STARTING && 1647 mState != STARTED && mState != FLUSHING && 1648 mState != FLUSHED) 1649 || format == NULL) { 1650 PostReplyWithError(replyID, INVALID_OPERATION); 1651 break; 1652 } else if (mFlags & kFlagStickyError) { 1653 PostReplyWithError(replyID, getStickyError()); 1654 break; 1655 } 1656 1657 sp<AMessage> response = new AMessage; 1658 response->setMessage("format", format); 1659 response->postReply(replyID); 1660 break; 1661 } 1662 1663 case kWhatRequestIDRFrame: 1664 { 1665 mCodec->signalRequestIDRFrame(); 1666 break; 1667 } 1668 1669 case kWhatRequestActivityNotification: 1670 { 1671 CHECK(mActivityNotify == NULL); 1672 CHECK(msg->findMessage("notify", &mActivityNotify)); 1673 1674 postActivityNotificationIfPossible(); 1675 break; 1676 } 1677 1678 case kWhatGetName: 1679 { 1680 uint32_t replyID; 1681 CHECK(msg->senderAwaitsResponse(&replyID)); 1682 1683 if (mComponentName.empty()) { 1684 PostReplyWithError(replyID, INVALID_OPERATION); 1685 break; 1686 } 1687 1688 sp<AMessage> response = new AMessage; 1689 response->setString("name", mComponentName.c_str()); 1690 response->postReply(replyID); 1691 break; 1692 } 1693 1694 case kWhatSetParameters: 1695 { 1696 uint32_t replyID; 1697 CHECK(msg->senderAwaitsResponse(&replyID)); 1698 1699 sp<AMessage> params; 1700 CHECK(msg->findMessage("params", ¶ms)); 1701 1702 status_t err = onSetParameters(params); 1703 1704 PostReplyWithError(replyID, err); 1705 break; 1706 } 1707 1708 default: 1709 TRESPASS(); 1710 } 1711} 1712 1713void MediaCodec::extractCSD(const sp<AMessage> &format) { 1714 mCSD.clear(); 1715 1716 size_t i = 0; 1717 for (;;) { 1718 sp<ABuffer> csd; 1719 if (!format->findBuffer(StringPrintf("csd-%u", i).c_str(), &csd)) { 1720 break; 1721 } 1722 1723 mCSD.push_back(csd); 1724 ++i; 1725 } 1726 1727 ALOGV("Found %zu pieces of codec specific data.", mCSD.size()); 1728} 1729 1730status_t MediaCodec::queueCSDInputBuffer(size_t bufferIndex) { 1731 CHECK(!mCSD.empty()); 1732 1733 const BufferInfo *info = 1734 &mPortBuffers[kPortIndexInput].itemAt(bufferIndex); 1735 1736 sp<ABuffer> csd = *mCSD.begin(); 1737 mCSD.erase(mCSD.begin()); 1738 1739 const sp<ABuffer> &codecInputData = 1740 (mCrypto != NULL) ? info->mEncryptedData : info->mData; 1741 1742 if (csd->size() > codecInputData->capacity()) { 1743 return -EINVAL; 1744 } 1745 1746 memcpy(codecInputData->data(), csd->data(), csd->size()); 1747 1748 AString errorDetailMsg; 1749 1750 sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, id()); 1751 msg->setSize("index", bufferIndex); 1752 msg->setSize("offset", 0); 1753 msg->setSize("size", csd->size()); 1754 msg->setInt64("timeUs", 0ll); 1755 msg->setInt32("flags", BUFFER_FLAG_CODECCONFIG); 1756 msg->setPointer("errorDetailMsg", &errorDetailMsg); 1757 1758 return onQueueInputBuffer(msg); 1759} 1760 1761void MediaCodec::setState(State newState) { 1762 if (newState == INITIALIZED || newState == UNINITIALIZED) { 1763 delete mSoftRenderer; 1764 mSoftRenderer = NULL; 1765 1766 mCrypto.clear(); 1767 setNativeWindow(NULL); 1768 1769 mInputFormat.clear(); 1770 mOutputFormat.clear(); 1771 mFlags &= ~kFlagOutputFormatChanged; 1772 mFlags &= ~kFlagOutputBuffersChanged; 1773 mFlags &= ~kFlagStickyError; 1774 mFlags &= ~kFlagIsEncoder; 1775 mFlags &= ~kFlagGatherCodecSpecificData; 1776 mFlags &= ~kFlagIsAsync; 1777 mStickyError = OK; 1778 1779 mActivityNotify.clear(); 1780 mCallback.clear(); 1781 } 1782 1783 if (newState == UNINITIALIZED) { 1784 // return any straggling buffers, e.g. if we got here on an error 1785 returnBuffersToCodec(); 1786 1787 // The component is gone, mediaserver's probably back up already 1788 // but should definitely be back up should we try to instantiate 1789 // another component.. and the cycle continues. 1790 mFlags &= ~kFlagSawMediaServerDie; 1791 } 1792 1793 mState = newState; 1794 1795 cancelPendingDequeueOperations(); 1796 1797 updateBatteryStat(); 1798} 1799 1800void MediaCodec::returnBuffersToCodec() { 1801 returnBuffersToCodecOnPort(kPortIndexInput); 1802 returnBuffersToCodecOnPort(kPortIndexOutput); 1803} 1804 1805void MediaCodec::returnBuffersToCodecOnPort(int32_t portIndex) { 1806 CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); 1807 Mutex::Autolock al(mBufferLock); 1808 1809 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 1810 1811 for (size_t i = 0; i < buffers->size(); ++i) { 1812 BufferInfo *info = &buffers->editItemAt(i); 1813 1814 if (info->mNotify != NULL) { 1815 sp<AMessage> msg = info->mNotify; 1816 info->mNotify = NULL; 1817 info->mOwnedByClient = false; 1818 1819 if (portIndex == kPortIndexInput) { 1820 /* no error, just returning buffers */ 1821 msg->setInt32("err", OK); 1822 } 1823 msg->post(); 1824 } 1825 } 1826 1827 mAvailPortBuffers[portIndex].clear(); 1828} 1829 1830size_t MediaCodec::updateBuffers( 1831 int32_t portIndex, const sp<AMessage> &msg) { 1832 CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); 1833 1834 uint32_t bufferID; 1835 CHECK(msg->findInt32("buffer-id", (int32_t*)&bufferID)); 1836 1837 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 1838 1839 for (size_t i = 0; i < buffers->size(); ++i) { 1840 BufferInfo *info = &buffers->editItemAt(i); 1841 1842 if (info->mBufferID == bufferID) { 1843 CHECK(info->mNotify == NULL); 1844 CHECK(msg->findMessage("reply", &info->mNotify)); 1845 1846 info->mFormat = 1847 (portIndex == kPortIndexInput) ? mInputFormat : mOutputFormat; 1848 mAvailPortBuffers[portIndex].push_back(i); 1849 1850 return i; 1851 } 1852 } 1853 1854 TRESPASS(); 1855 1856 return 0; 1857} 1858 1859status_t MediaCodec::onQueueInputBuffer(const sp<AMessage> &msg) { 1860 size_t index; 1861 size_t offset; 1862 size_t size; 1863 int64_t timeUs; 1864 uint32_t flags; 1865 CHECK(msg->findSize("index", &index)); 1866 CHECK(msg->findSize("offset", &offset)); 1867 CHECK(msg->findInt64("timeUs", &timeUs)); 1868 CHECK(msg->findInt32("flags", (int32_t *)&flags)); 1869 1870 const CryptoPlugin::SubSample *subSamples; 1871 size_t numSubSamples; 1872 const uint8_t *key; 1873 const uint8_t *iv; 1874 CryptoPlugin::Mode mode = CryptoPlugin::kMode_Unencrypted; 1875 1876 // We allow the simpler queueInputBuffer API to be used even in 1877 // secure mode, by fabricating a single unencrypted subSample. 1878 CryptoPlugin::SubSample ss; 1879 1880 if (msg->findSize("size", &size)) { 1881 if (mCrypto != NULL) { 1882 ss.mNumBytesOfClearData = size; 1883 ss.mNumBytesOfEncryptedData = 0; 1884 1885 subSamples = &ss; 1886 numSubSamples = 1; 1887 key = NULL; 1888 iv = NULL; 1889 } 1890 } else { 1891 if (mCrypto == NULL) { 1892 return -EINVAL; 1893 } 1894 1895 CHECK(msg->findPointer("subSamples", (void **)&subSamples)); 1896 CHECK(msg->findSize("numSubSamples", &numSubSamples)); 1897 CHECK(msg->findPointer("key", (void **)&key)); 1898 CHECK(msg->findPointer("iv", (void **)&iv)); 1899 1900 int32_t tmp; 1901 CHECK(msg->findInt32("mode", &tmp)); 1902 1903 mode = (CryptoPlugin::Mode)tmp; 1904 1905 size = 0; 1906 for (size_t i = 0; i < numSubSamples; ++i) { 1907 size += subSamples[i].mNumBytesOfClearData; 1908 size += subSamples[i].mNumBytesOfEncryptedData; 1909 } 1910 } 1911 1912 if (index >= mPortBuffers[kPortIndexInput].size()) { 1913 return -ERANGE; 1914 } 1915 1916 BufferInfo *info = &mPortBuffers[kPortIndexInput].editItemAt(index); 1917 1918 if (info->mNotify == NULL || !info->mOwnedByClient) { 1919 return -EACCES; 1920 } 1921 1922 if (offset + size > info->mData->capacity()) { 1923 return -EINVAL; 1924 } 1925 1926 sp<AMessage> reply = info->mNotify; 1927 info->mData->setRange(offset, size); 1928 info->mData->meta()->setInt64("timeUs", timeUs); 1929 1930 if (flags & BUFFER_FLAG_EOS) { 1931 info->mData->meta()->setInt32("eos", true); 1932 } 1933 1934 if (flags & BUFFER_FLAG_CODECCONFIG) { 1935 info->mData->meta()->setInt32("csd", true); 1936 } 1937 1938 if (mCrypto != NULL) { 1939 if (size > info->mEncryptedData->capacity()) { 1940 return -ERANGE; 1941 } 1942 1943 AString *errorDetailMsg; 1944 CHECK(msg->findPointer("errorDetailMsg", (void **)&errorDetailMsg)); 1945 1946 ssize_t result = mCrypto->decrypt( 1947 (mFlags & kFlagIsSecure) != 0, 1948 key, 1949 iv, 1950 mode, 1951 info->mEncryptedData->base() + offset, 1952 subSamples, 1953 numSubSamples, 1954 info->mData->base(), 1955 errorDetailMsg); 1956 1957 if (result < 0) { 1958 return result; 1959 } 1960 1961 info->mData->setRange(0, result); 1962 } 1963 1964 // synchronization boundary for getBufferAndFormat 1965 { 1966 Mutex::Autolock al(mBufferLock); 1967 info->mOwnedByClient = false; 1968 } 1969 reply->setBuffer("buffer", info->mData); 1970 reply->post(); 1971 1972 info->mNotify = NULL; 1973 1974 return OK; 1975} 1976 1977status_t MediaCodec::onReleaseOutputBuffer(const sp<AMessage> &msg) { 1978 size_t index; 1979 CHECK(msg->findSize("index", &index)); 1980 1981 int32_t render; 1982 if (!msg->findInt32("render", &render)) { 1983 render = 0; 1984 } 1985 1986 if (!isExecuting()) { 1987 return -EINVAL; 1988 } 1989 1990 if (index >= mPortBuffers[kPortIndexOutput].size()) { 1991 return -ERANGE; 1992 } 1993 1994 BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index); 1995 1996 if (info->mNotify == NULL || !info->mOwnedByClient) { 1997 return -EACCES; 1998 } 1999 2000 // synchronization boundary for getBufferAndFormat 2001 { 2002 Mutex::Autolock al(mBufferLock); 2003 info->mOwnedByClient = false; 2004 } 2005 2006 if (render && info->mData != NULL && info->mData->size() != 0) { 2007 info->mNotify->setInt32("render", true); 2008 2009 int64_t timestampNs = 0; 2010 if (msg->findInt64("timestampNs", ×tampNs)) { 2011 info->mNotify->setInt64("timestampNs", timestampNs); 2012 } else { 2013 // TODO: it seems like we should use the timestamp 2014 // in the (media)buffer as it potentially came from 2015 // an input surface, but we did not propagate it prior to 2016 // API 20. Perhaps check for target SDK version. 2017#if 0 2018 if (info->mData->meta()->findInt64("timeUs", ×tampNs)) { 2019 ALOGV("using buffer PTS of %" PRId64, timestampNs); 2020 timestampNs *= 1000; 2021 } 2022#endif 2023 } 2024 2025 if (mSoftRenderer != NULL) { 2026 mSoftRenderer->render( 2027 info->mData->data(), info->mData->size(), 2028 timestampNs, NULL, info->mFormat); 2029 } 2030 } 2031 2032 info->mNotify->post(); 2033 info->mNotify = NULL; 2034 2035 return OK; 2036} 2037 2038ssize_t MediaCodec::dequeuePortBuffer(int32_t portIndex) { 2039 CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput); 2040 2041 List<size_t> *availBuffers = &mAvailPortBuffers[portIndex]; 2042 2043 if (availBuffers->empty()) { 2044 return -EAGAIN; 2045 } 2046 2047 size_t index = *availBuffers->begin(); 2048 availBuffers->erase(availBuffers->begin()); 2049 2050 BufferInfo *info = &mPortBuffers[portIndex].editItemAt(index); 2051 CHECK(!info->mOwnedByClient); 2052 { 2053 Mutex::Autolock al(mBufferLock); 2054 info->mOwnedByClient = true; 2055 2056 // set image-data 2057 if (info->mFormat != NULL) { 2058 sp<ABuffer> imageData; 2059 if (info->mFormat->findBuffer("image-data", &imageData)) { 2060 info->mData->meta()->setBuffer("image-data", imageData); 2061 } 2062 int32_t left, top, right, bottom; 2063 if (info->mFormat->findRect("crop", &left, &top, &right, &bottom)) { 2064 info->mData->meta()->setRect("crop-rect", left, top, right, bottom); 2065 } 2066 } 2067 } 2068 2069 return index; 2070} 2071 2072status_t MediaCodec::setNativeWindow( 2073 const sp<Surface> &surfaceTextureClient) { 2074 status_t err; 2075 2076 if (mNativeWindow != NULL) { 2077 err = native_window_api_disconnect( 2078 mNativeWindow.get(), NATIVE_WINDOW_API_MEDIA); 2079 2080 if (err != OK) { 2081 ALOGW("native_window_api_disconnect returned an error: %s (%d)", 2082 strerror(-err), err); 2083 } 2084 2085 mNativeWindow.clear(); 2086 } 2087 2088 if (surfaceTextureClient != NULL) { 2089 err = native_window_api_connect( 2090 surfaceTextureClient.get(), NATIVE_WINDOW_API_MEDIA); 2091 2092 if (err != OK) { 2093 ALOGE("native_window_api_connect returned an error: %s (%d)", 2094 strerror(-err), err); 2095 2096 return err; 2097 } 2098 2099 mNativeWindow = surfaceTextureClient; 2100 } 2101 2102 return OK; 2103} 2104 2105void MediaCodec::onInputBufferAvailable() { 2106 int32_t index; 2107 while ((index = dequeuePortBuffer(kPortIndexInput)) >= 0) { 2108 sp<AMessage> msg = mCallback->dup(); 2109 msg->setInt32("callbackID", CB_INPUT_AVAILABLE); 2110 msg->setInt32("index", index); 2111 msg->post(); 2112 } 2113} 2114 2115void MediaCodec::onOutputBufferAvailable() { 2116 int32_t index; 2117 while ((index = dequeuePortBuffer(kPortIndexOutput)) >= 0) { 2118 const sp<ABuffer> &buffer = 2119 mPortBuffers[kPortIndexOutput].itemAt(index).mData; 2120 sp<AMessage> msg = mCallback->dup(); 2121 msg->setInt32("callbackID", CB_OUTPUT_AVAILABLE); 2122 msg->setInt32("index", index); 2123 msg->setSize("offset", buffer->offset()); 2124 msg->setSize("size", buffer->size()); 2125 2126 int64_t timeUs; 2127 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 2128 2129 msg->setInt64("timeUs", timeUs); 2130 2131 int32_t omxFlags; 2132 CHECK(buffer->meta()->findInt32("omxFlags", &omxFlags)); 2133 2134 uint32_t flags = 0; 2135 if (omxFlags & OMX_BUFFERFLAG_SYNCFRAME) { 2136 flags |= BUFFER_FLAG_SYNCFRAME; 2137 } 2138 if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) { 2139 flags |= BUFFER_FLAG_CODECCONFIG; 2140 } 2141 if (omxFlags & OMX_BUFFERFLAG_EOS) { 2142 flags |= BUFFER_FLAG_EOS; 2143 } 2144 2145 msg->setInt32("flags", flags); 2146 2147 msg->post(); 2148 } 2149} 2150 2151void MediaCodec::onError(status_t err, int32_t actionCode, const char *detail) { 2152 if (mCallback != NULL) { 2153 sp<AMessage> msg = mCallback->dup(); 2154 msg->setInt32("callbackID", CB_ERROR); 2155 msg->setInt32("err", err); 2156 msg->setInt32("actionCode", actionCode); 2157 2158 if (detail != NULL) { 2159 msg->setString("detail", detail); 2160 } 2161 2162 msg->post(); 2163 } 2164} 2165 2166void MediaCodec::onOutputFormatChanged() { 2167 if (mCallback != NULL) { 2168 sp<AMessage> msg = mCallback->dup(); 2169 msg->setInt32("callbackID", CB_OUTPUT_FORMAT_CHANGED); 2170 msg->setMessage("format", mOutputFormat); 2171 msg->post(); 2172 } 2173} 2174 2175 2176void MediaCodec::postActivityNotificationIfPossible() { 2177 if (mActivityNotify == NULL) { 2178 return; 2179 } 2180 2181 bool isErrorOrOutputChanged = 2182 (mFlags & (kFlagStickyError 2183 | kFlagOutputBuffersChanged 2184 | kFlagOutputFormatChanged)); 2185 2186 if (isErrorOrOutputChanged 2187 || !mAvailPortBuffers[kPortIndexInput].empty() 2188 || !mAvailPortBuffers[kPortIndexOutput].empty()) { 2189 mActivityNotify->setInt32("input-buffers", 2190 mAvailPortBuffers[kPortIndexInput].size()); 2191 2192 if (isErrorOrOutputChanged) { 2193 // we want consumer to dequeue as many times as it can 2194 mActivityNotify->setInt32("output-buffers", INT32_MAX); 2195 } else { 2196 mActivityNotify->setInt32("output-buffers", 2197 mAvailPortBuffers[kPortIndexOutput].size()); 2198 } 2199 mActivityNotify->post(); 2200 mActivityNotify.clear(); 2201 } 2202} 2203 2204status_t MediaCodec::setParameters(const sp<AMessage> ¶ms) { 2205 sp<AMessage> msg = new AMessage(kWhatSetParameters, id()); 2206 msg->setMessage("params", params); 2207 2208 sp<AMessage> response; 2209 return PostAndAwaitResponse(msg, &response); 2210} 2211 2212status_t MediaCodec::onSetParameters(const sp<AMessage> ¶ms) { 2213 mCodec->signalSetParameters(params); 2214 2215 return OK; 2216} 2217 2218status_t MediaCodec::amendOutputFormatWithCodecSpecificData( 2219 const sp<ABuffer> &buffer) { 2220 AString mime; 2221 CHECK(mOutputFormat->findString("mime", &mime)); 2222 2223 if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) { 2224 // Codec specific data should be SPS and PPS in a single buffer, 2225 // each prefixed by a startcode (0x00 0x00 0x00 0x01). 2226 // We separate the two and put them into the output format 2227 // under the keys "csd-0" and "csd-1". 2228 2229 unsigned csdIndex = 0; 2230 2231 const uint8_t *data = buffer->data(); 2232 size_t size = buffer->size(); 2233 2234 const uint8_t *nalStart; 2235 size_t nalSize; 2236 while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) { 2237 sp<ABuffer> csd = new ABuffer(nalSize + 4); 2238 memcpy(csd->data(), "\x00\x00\x00\x01", 4); 2239 memcpy(csd->data() + 4, nalStart, nalSize); 2240 2241 mOutputFormat->setBuffer( 2242 StringPrintf("csd-%u", csdIndex).c_str(), csd); 2243 2244 ++csdIndex; 2245 } 2246 2247 if (csdIndex != 2) { 2248 return ERROR_MALFORMED; 2249 } 2250 } else { 2251 // For everything else we just stash the codec specific data into 2252 // the output format as a single piece of csd under "csd-0". 2253 mOutputFormat->setBuffer("csd-0", buffer); 2254 } 2255 2256 return OK; 2257} 2258 2259void MediaCodec::updateBatteryStat() { 2260 if (mState == CONFIGURED && !mBatteryStatNotified) { 2261 AString mime; 2262 CHECK(mOutputFormat != NULL && 2263 mOutputFormat->findString("mime", &mime)); 2264 2265 mIsVideo = mime.startsWithIgnoreCase("video/"); 2266 2267 BatteryNotifier& notifier(BatteryNotifier::getInstance()); 2268 2269 if (mIsVideo) { 2270 notifier.noteStartVideo(); 2271 } else { 2272 notifier.noteStartAudio(); 2273 } 2274 2275 mBatteryStatNotified = true; 2276 } else if (mState == UNINITIALIZED && mBatteryStatNotified) { 2277 BatteryNotifier& notifier(BatteryNotifier::getInstance()); 2278 2279 if (mIsVideo) { 2280 notifier.noteStopVideo(); 2281 } else { 2282 notifier.noteStopAudio(); 2283 } 2284 2285 mBatteryStatNotified = false; 2286 } 2287} 2288 2289} // namespace android 2290