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