OMXCodec.cpp revision 2f74ef3cdc192f817ee1121f41765f0852c1d81e
1/* 2 * Copyright (C) 2009 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 "OMXCodec" 19#include <utils/Log.h> 20 21#include "include/AACEncoder.h" 22 23#include "include/ESDS.h" 24 25#include <binder/IServiceManager.h> 26#include <binder/MemoryDealer.h> 27#include <binder/ProcessState.h> 28#include <HardwareAPI.h> 29#include <media/stagefright/foundation/ADebug.h> 30#include <media/IMediaPlayerService.h> 31#include <media/stagefright/MediaBuffer.h> 32#include <media/stagefright/MediaBufferGroup.h> 33#include <media/stagefright/MediaDefs.h> 34#include <media/stagefright/MediaCodecList.h> 35#include <media/stagefright/MediaExtractor.h> 36#include <media/stagefright/MetaData.h> 37#include <media/stagefright/OMXCodec.h> 38#include <media/stagefright/Utils.h> 39#include <media/stagefright/SkipCutBuffer.h> 40#include <utils/Vector.h> 41 42#include <OMX_Audio.h> 43#include <OMX_Component.h> 44 45#include "include/avc_utils.h" 46 47namespace android { 48 49// Treat time out as an error if we have not received any output 50// buffers after 3 seconds. 51const static int64_t kBufferFilledEventTimeOutNs = 3000000000LL; 52 53// OMX Spec defines less than 50 color formats. If the query for 54// color format is executed for more than kMaxColorFormatSupported, 55// the query will fail to avoid looping forever. 56// 1000 is more than enough for us to tell whether the omx 57// component in question is buggy or not. 58const static uint32_t kMaxColorFormatSupported = 1000; 59 60#define FACTORY_CREATE_ENCODER(name) \ 61static sp<MediaSource> Make##name(const sp<MediaSource> &source, const sp<MetaData> &meta) { \ 62 return new name(source, meta); \ 63} 64 65#define FACTORY_REF(name) { #name, Make##name }, 66 67FACTORY_CREATE_ENCODER(AACEncoder) 68 69static sp<MediaSource> InstantiateSoftwareEncoder( 70 const char *name, const sp<MediaSource> &source, 71 const sp<MetaData> &meta) { 72 struct FactoryInfo { 73 const char *name; 74 sp<MediaSource> (*CreateFunc)(const sp<MediaSource> &, const sp<MetaData> &); 75 }; 76 77 static const FactoryInfo kFactoryInfo[] = { 78 FACTORY_REF(AACEncoder) 79 }; 80 for (size_t i = 0; 81 i < sizeof(kFactoryInfo) / sizeof(kFactoryInfo[0]); ++i) { 82 if (!strcmp(name, kFactoryInfo[i].name)) { 83 return (*kFactoryInfo[i].CreateFunc)(source, meta); 84 } 85 } 86 87 return NULL; 88} 89 90#undef FACTORY_CREATE_ENCODER 91#undef FACTORY_REF 92 93#define CODEC_LOGI(x, ...) ALOGI("[%s] "x, mComponentName, ##__VA_ARGS__) 94#define CODEC_LOGV(x, ...) ALOGV("[%s] "x, mComponentName, ##__VA_ARGS__) 95#define CODEC_LOGE(x, ...) ALOGE("[%s] "x, mComponentName, ##__VA_ARGS__) 96 97struct OMXCodecObserver : public BnOMXObserver { 98 OMXCodecObserver() { 99 } 100 101 void setCodec(const sp<OMXCodec> &target) { 102 mTarget = target; 103 } 104 105 // from IOMXObserver 106 virtual void onMessage(const omx_message &msg) { 107 sp<OMXCodec> codec = mTarget.promote(); 108 109 if (codec.get() != NULL) { 110 Mutex::Autolock autoLock(codec->mLock); 111 codec->on_message(msg); 112 codec.clear(); 113 } 114 } 115 116protected: 117 virtual ~OMXCodecObserver() {} 118 119private: 120 wp<OMXCodec> mTarget; 121 122 OMXCodecObserver(const OMXCodecObserver &); 123 OMXCodecObserver &operator=(const OMXCodecObserver &); 124}; 125 126template<class T> 127static void InitOMXParams(T *params) { 128 params->nSize = sizeof(T); 129 params->nVersion.s.nVersionMajor = 1; 130 params->nVersion.s.nVersionMinor = 0; 131 params->nVersion.s.nRevision = 0; 132 params->nVersion.s.nStep = 0; 133} 134 135static bool IsSoftwareCodec(const char *componentName) { 136 if (!strncmp("OMX.google.", componentName, 11)) { 137 return true; 138 } 139 140 if (!strncmp("OMX.", componentName, 4)) { 141 return false; 142 } 143 144 return true; 145} 146 147// A sort order in which OMX software codecs are first, followed 148// by other (non-OMX) software codecs, followed by everything else. 149static int CompareSoftwareCodecsFirst( 150 const String8 *elem1, const String8 *elem2) { 151 bool isOMX1 = !strncmp(elem1->string(), "OMX.", 4); 152 bool isOMX2 = !strncmp(elem2->string(), "OMX.", 4); 153 154 bool isSoftwareCodec1 = IsSoftwareCodec(elem1->string()); 155 bool isSoftwareCodec2 = IsSoftwareCodec(elem2->string()); 156 157 if (isSoftwareCodec1) { 158 if (!isSoftwareCodec2) { return -1; } 159 160 if (isOMX1) { 161 if (isOMX2) { return 0; } 162 163 return -1; 164 } else { 165 if (isOMX2) { return 0; } 166 167 return 1; 168 } 169 170 return -1; 171 } 172 173 if (isSoftwareCodec2) { 174 return 1; 175 } 176 177 return 0; 178} 179 180// static 181void OMXCodec::findMatchingCodecs( 182 const char *mime, 183 bool createEncoder, const char *matchComponentName, 184 uint32_t flags, 185 Vector<String8> *matchingCodecs, 186 Vector<uint32_t> *matchingCodecQuirks) { 187 matchingCodecs->clear(); 188 189 if (matchingCodecQuirks) { 190 matchingCodecQuirks->clear(); 191 } 192 193 const MediaCodecList *list = MediaCodecList::getInstance(); 194 if (list == NULL) { 195 return; 196 } 197 198 size_t index = 0; 199 for (;;) { 200 ssize_t matchIndex = 201 list->findCodecByType(mime, createEncoder, index); 202 203 if (matchIndex < 0) { 204 break; 205 } 206 207 index = matchIndex + 1; 208 209 const char *componentName = list->getCodecName(matchIndex); 210 211 // If a specific codec is requested, skip the non-matching ones. 212 if (matchComponentName && strcmp(componentName, matchComponentName)) { 213 continue; 214 } 215 216 // When requesting software-only codecs, only push software codecs 217 // When requesting hardware-only codecs, only push hardware codecs 218 // When there is request neither for software-only nor for 219 // hardware-only codecs, push all codecs 220 if (((flags & kSoftwareCodecsOnly) && IsSoftwareCodec(componentName)) || 221 ((flags & kHardwareCodecsOnly) && !IsSoftwareCodec(componentName)) || 222 (!(flags & (kSoftwareCodecsOnly | kHardwareCodecsOnly)))) { 223 224 matchingCodecs->push(String8(componentName)); 225 226 if (matchingCodecQuirks) { 227 matchingCodecQuirks->push(getComponentQuirks(list, matchIndex)); 228 } 229 } 230 } 231 232 if (flags & kPreferSoftwareCodecs) { 233 matchingCodecs->sort(CompareSoftwareCodecsFirst); 234 } 235} 236 237// static 238uint32_t OMXCodec::getComponentQuirks( 239 const MediaCodecList *list, size_t index) { 240 uint32_t quirks = 0; 241 if (list->codecHasQuirk( 242 index, "requires-allocate-on-input-ports")) { 243 quirks |= kRequiresAllocateBufferOnInputPorts; 244 } 245 if (list->codecHasQuirk( 246 index, "requires-allocate-on-output-ports")) { 247 quirks |= kRequiresAllocateBufferOnOutputPorts; 248 } 249 if (list->codecHasQuirk( 250 index, "output-buffers-are-unreadable")) { 251 quirks |= kOutputBuffersAreUnreadable; 252 } 253 254 return quirks; 255} 256 257// static 258bool OMXCodec::findCodecQuirks(const char *componentName, uint32_t *quirks) { 259 const MediaCodecList *list = MediaCodecList::getInstance(); 260 261 if (list == NULL) { 262 return false; 263 } 264 265 ssize_t index = list->findCodecByName(componentName); 266 267 if (index < 0) { 268 return false; 269 } 270 271 *quirks = getComponentQuirks(list, index); 272 273 return true; 274} 275 276// static 277sp<MediaSource> OMXCodec::Create( 278 const sp<IOMX> &omx, 279 const sp<MetaData> &meta, bool createEncoder, 280 const sp<MediaSource> &source, 281 const char *matchComponentName, 282 uint32_t flags, 283 const sp<ANativeWindow> &nativeWindow) { 284 int32_t requiresSecureBuffers; 285 if (source->getFormat()->findInt32( 286 kKeyRequiresSecureBuffers, 287 &requiresSecureBuffers) 288 && requiresSecureBuffers) { 289 flags |= kIgnoreCodecSpecificData; 290 flags |= kUseSecureInputBuffers; 291 } 292 293 const char *mime; 294 bool success = meta->findCString(kKeyMIMEType, &mime); 295 CHECK(success); 296 297 Vector<String8> matchingCodecs; 298 Vector<uint32_t> matchingCodecQuirks; 299 findMatchingCodecs( 300 mime, createEncoder, matchComponentName, flags, 301 &matchingCodecs, &matchingCodecQuirks); 302 303 if (matchingCodecs.isEmpty()) { 304 return NULL; 305 } 306 307 sp<OMXCodecObserver> observer = new OMXCodecObserver; 308 IOMX::node_id node = 0; 309 310 for (size_t i = 0; i < matchingCodecs.size(); ++i) { 311 const char *componentNameBase = matchingCodecs[i].string(); 312 uint32_t quirks = matchingCodecQuirks[i]; 313 const char *componentName = componentNameBase; 314 315 AString tmp; 316 if (flags & kUseSecureInputBuffers) { 317 tmp = componentNameBase; 318 tmp.append(".secure"); 319 320 componentName = tmp.c_str(); 321 } 322 323 if (createEncoder) { 324 sp<MediaSource> softwareCodec = 325 InstantiateSoftwareEncoder(componentName, source, meta); 326 327 if (softwareCodec != NULL) { 328 ALOGV("Successfully allocated software codec '%s'", componentName); 329 330 return softwareCodec; 331 } 332 } 333 334 ALOGV("Attempting to allocate OMX node '%s'", componentName); 335 336 if (!createEncoder 337 && (quirks & kOutputBuffersAreUnreadable) 338 && (flags & kClientNeedsFramebuffer)) { 339 if (strncmp(componentName, "OMX.SEC.", 8)) { 340 // For OMX.SEC.* decoders we can enable a special mode that 341 // gives the client access to the framebuffer contents. 342 343 ALOGW("Component '%s' does not give the client access to " 344 "the framebuffer contents. Skipping.", 345 componentName); 346 347 continue; 348 } 349 } 350 351 status_t err = omx->allocateNode(componentName, observer, &node); 352 if (err == OK) { 353 ALOGV("Successfully allocated OMX node '%s'", componentName); 354 355 sp<OMXCodec> codec = new OMXCodec( 356 omx, node, quirks, flags, 357 createEncoder, mime, componentName, 358 source, nativeWindow); 359 360 observer->setCodec(codec); 361 362 err = codec->configureCodec(meta); 363 364 if (err == OK) { 365 if (!strcmp("OMX.Nvidia.mpeg2v.decode", componentName)) { 366 codec->mFlags |= kOnlySubmitOneInputBufferAtOneTime; 367 } 368 369 return codec; 370 } 371 372 ALOGV("Failed to configure codec '%s'", componentName); 373 } 374 } 375 376 return NULL; 377} 378 379status_t OMXCodec::parseAVCCodecSpecificData( 380 const void *data, size_t size, 381 unsigned *profile, unsigned *level) { 382 const uint8_t *ptr = (const uint8_t *)data; 383 384 // verify minimum size and configurationVersion == 1. 385 if (size < 7 || ptr[0] != 1) { 386 return ERROR_MALFORMED; 387 } 388 389 *profile = ptr[1]; 390 *level = ptr[3]; 391 392 // There is decodable content out there that fails the following 393 // assertion, let's be lenient for now... 394 // CHECK((ptr[4] >> 2) == 0x3f); // reserved 395 396 size_t lengthSize = 1 + (ptr[4] & 3); 397 398 // commented out check below as H264_QVGA_500_NO_AUDIO.3gp 399 // violates it... 400 // CHECK((ptr[5] >> 5) == 7); // reserved 401 402 size_t numSeqParameterSets = ptr[5] & 31; 403 404 ptr += 6; 405 size -= 6; 406 407 for (size_t i = 0; i < numSeqParameterSets; ++i) { 408 if (size < 2) { 409 return ERROR_MALFORMED; 410 } 411 412 size_t length = U16_AT(ptr); 413 414 ptr += 2; 415 size -= 2; 416 417 if (size < length) { 418 return ERROR_MALFORMED; 419 } 420 421 addCodecSpecificData(ptr, length); 422 423 ptr += length; 424 size -= length; 425 } 426 427 if (size < 1) { 428 return ERROR_MALFORMED; 429 } 430 431 size_t numPictureParameterSets = *ptr; 432 ++ptr; 433 --size; 434 435 for (size_t i = 0; i < numPictureParameterSets; ++i) { 436 if (size < 2) { 437 return ERROR_MALFORMED; 438 } 439 440 size_t length = U16_AT(ptr); 441 442 ptr += 2; 443 size -= 2; 444 445 if (size < length) { 446 return ERROR_MALFORMED; 447 } 448 449 addCodecSpecificData(ptr, length); 450 451 ptr += length; 452 size -= length; 453 } 454 455 return OK; 456} 457 458status_t OMXCodec::configureCodec(const sp<MetaData> &meta) { 459 ALOGV("configureCodec protected=%d", 460 (mFlags & kEnableGrallocUsageProtected) ? 1 : 0); 461 462 if (!(mFlags & kIgnoreCodecSpecificData)) { 463 uint32_t type; 464 const void *data; 465 size_t size; 466 if (meta->findData(kKeyESDS, &type, &data, &size)) { 467 ESDS esds((const char *)data, size); 468 CHECK_EQ(esds.InitCheck(), (status_t)OK); 469 470 const void *codec_specific_data; 471 size_t codec_specific_data_size; 472 esds.getCodecSpecificInfo( 473 &codec_specific_data, &codec_specific_data_size); 474 475 addCodecSpecificData( 476 codec_specific_data, codec_specific_data_size); 477 } else if (meta->findData(kKeyAVCC, &type, &data, &size)) { 478 // Parse the AVCDecoderConfigurationRecord 479 480 unsigned profile, level; 481 status_t err; 482 if ((err = parseAVCCodecSpecificData( 483 data, size, &profile, &level)) != OK) { 484 ALOGE("Malformed AVC codec specific data."); 485 return err; 486 } 487 488 CODEC_LOGI( 489 "AVC profile = %u (%s), level = %u", 490 profile, AVCProfileToString(profile), level); 491 } else if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) { 492 addCodecSpecificData(data, size); 493 494 CHECK(meta->findData(kKeyVorbisBooks, &type, &data, &size)); 495 addCodecSpecificData(data, size); 496 } 497 } 498 499 int32_t bitRate = 0; 500 if (mIsEncoder) { 501 CHECK(meta->findInt32(kKeyBitRate, &bitRate)); 502 } 503 if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) { 504 setAMRFormat(false /* isWAMR */, bitRate); 505 } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) { 506 setAMRFormat(true /* isWAMR */, bitRate); 507 } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) { 508 int32_t numChannels, sampleRate, aacProfile; 509 CHECK(meta->findInt32(kKeyChannelCount, &numChannels)); 510 CHECK(meta->findInt32(kKeySampleRate, &sampleRate)); 511 512 if (!meta->findInt32(kKeyAACProfile, &aacProfile)) { 513 aacProfile = OMX_AUDIO_AACObjectNull; 514 } 515 516 int32_t isADTS; 517 if (!meta->findInt32(kKeyIsADTS, &isADTS)) { 518 isADTS = false; 519 } 520 521 status_t err = setAACFormat(numChannels, sampleRate, bitRate, aacProfile, isADTS); 522 if (err != OK) { 523 CODEC_LOGE("setAACFormat() failed (err = %d)", err); 524 return err; 525 } 526 } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_ALAW, mMIME) 527 || !strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_MLAW, mMIME)) { 528 // These are PCM-like formats with a fixed sample rate but 529 // a variable number of channels. 530 531 int32_t numChannels; 532 CHECK(meta->findInt32(kKeyChannelCount, &numChannels)); 533 534 setG711Format(numChannels); 535 } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mMIME)) { 536 CHECK(!mIsEncoder); 537 538 int32_t numChannels, sampleRate; 539 CHECK(meta->findInt32(kKeyChannelCount, &numChannels)); 540 CHECK(meta->findInt32(kKeySampleRate, &sampleRate)); 541 542 setRawAudioFormat(kPortIndexInput, sampleRate, numChannels); 543 } 544 545 if (!strncasecmp(mMIME, "video/", 6)) { 546 547 if (mIsEncoder) { 548 setVideoInputFormat(mMIME, meta); 549 } else { 550 int32_t width, height; 551 bool success = meta->findInt32(kKeyWidth, &width); 552 success = success && meta->findInt32(kKeyHeight, &height); 553 CHECK(success); 554 status_t err = setVideoOutputFormat( 555 mMIME, width, height); 556 557 if (err != OK) { 558 return err; 559 } 560 } 561 } 562 563 int32_t maxInputSize; 564 if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) { 565 setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize); 566 } 567 568 initOutputFormat(meta); 569 570 if ((mFlags & kClientNeedsFramebuffer) 571 && !strncmp(mComponentName, "OMX.SEC.", 8)) { 572 OMX_INDEXTYPE index; 573 574 status_t err = 575 mOMX->getExtensionIndex( 576 mNode, 577 "OMX.SEC.index.ThumbnailMode", 578 &index); 579 580 if (err != OK) { 581 return err; 582 } 583 584 OMX_BOOL enable = OMX_TRUE; 585 err = mOMX->setConfig(mNode, index, &enable, sizeof(enable)); 586 587 if (err != OK) { 588 CODEC_LOGE("setConfig('OMX.SEC.index.ThumbnailMode') " 589 "returned error 0x%08x", err); 590 591 return err; 592 } 593 594 mQuirks &= ~kOutputBuffersAreUnreadable; 595 } 596 597 if (mNativeWindow != NULL 598 && !mIsEncoder 599 && !strncasecmp(mMIME, "video/", 6) 600 && !strncmp(mComponentName, "OMX.", 4)) { 601 status_t err = initNativeWindow(); 602 if (err != OK) { 603 return err; 604 } 605 } 606 607 return OK; 608} 609 610void OMXCodec::setMinBufferSize(OMX_U32 portIndex, OMX_U32 size) { 611 OMX_PARAM_PORTDEFINITIONTYPE def; 612 InitOMXParams(&def); 613 def.nPortIndex = portIndex; 614 615 status_t err = mOMX->getParameter( 616 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 617 CHECK_EQ(err, (status_t)OK); 618 619 if ((portIndex == kPortIndexInput && (mQuirks & kInputBufferSizesAreBogus)) 620 || (def.nBufferSize < size)) { 621 def.nBufferSize = size; 622 } 623 624 err = mOMX->setParameter( 625 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 626 CHECK_EQ(err, (status_t)OK); 627 628 err = mOMX->getParameter( 629 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 630 CHECK_EQ(err, (status_t)OK); 631 632 // Make sure the setting actually stuck. 633 if (portIndex == kPortIndexInput 634 && (mQuirks & kInputBufferSizesAreBogus)) { 635 CHECK_EQ(def.nBufferSize, size); 636 } else { 637 CHECK(def.nBufferSize >= size); 638 } 639} 640 641status_t OMXCodec::setVideoPortFormatType( 642 OMX_U32 portIndex, 643 OMX_VIDEO_CODINGTYPE compressionFormat, 644 OMX_COLOR_FORMATTYPE colorFormat) { 645 OMX_VIDEO_PARAM_PORTFORMATTYPE format; 646 InitOMXParams(&format); 647 format.nPortIndex = portIndex; 648 format.nIndex = 0; 649 bool found = false; 650 651 OMX_U32 index = 0; 652 for (;;) { 653 format.nIndex = index; 654 status_t err = mOMX->getParameter( 655 mNode, OMX_IndexParamVideoPortFormat, 656 &format, sizeof(format)); 657 658 if (err != OK) { 659 return err; 660 } 661 662 // The following assertion is violated by TI's video decoder. 663 // CHECK_EQ(format.nIndex, index); 664 665#if 1 666 CODEC_LOGV("portIndex: %ld, index: %ld, eCompressionFormat=%d eColorFormat=%d", 667 portIndex, 668 index, format.eCompressionFormat, format.eColorFormat); 669#endif 670 671 if (format.eCompressionFormat == compressionFormat 672 && format.eColorFormat == colorFormat) { 673 found = true; 674 break; 675 } 676 677 ++index; 678 if (index >= kMaxColorFormatSupported) { 679 CODEC_LOGE("color format %d or compression format %d is not supported", 680 colorFormat, compressionFormat); 681 return UNKNOWN_ERROR; 682 } 683 } 684 685 if (!found) { 686 return UNKNOWN_ERROR; 687 } 688 689 CODEC_LOGV("found a match."); 690 status_t err = mOMX->setParameter( 691 mNode, OMX_IndexParamVideoPortFormat, 692 &format, sizeof(format)); 693 694 return err; 695} 696 697static size_t getFrameSize( 698 OMX_COLOR_FORMATTYPE colorFormat, int32_t width, int32_t height) { 699 switch (colorFormat) { 700 case OMX_COLOR_FormatYCbYCr: 701 case OMX_COLOR_FormatCbYCrY: 702 return width * height * 2; 703 704 case OMX_COLOR_FormatYUV420Planar: 705 case OMX_COLOR_FormatYUV420SemiPlanar: 706 case OMX_TI_COLOR_FormatYUV420PackedSemiPlanar: 707 /* 708 * FIXME: For the Opaque color format, the frame size does not 709 * need to be (w*h*3)/2. It just needs to 710 * be larger than certain minimum buffer size. However, 711 * currently, this opaque foramt has been tested only on 712 * YUV420 formats. If that is changed, then we need to revisit 713 * this part in the future 714 */ 715 case OMX_COLOR_FormatAndroidOpaque: 716 return (width * height * 3) / 2; 717 718 default: 719 CHECK(!"Should not be here. Unsupported color format."); 720 break; 721 } 722} 723 724status_t OMXCodec::findTargetColorFormat( 725 const sp<MetaData>& meta, OMX_COLOR_FORMATTYPE *colorFormat) { 726 ALOGV("findTargetColorFormat"); 727 CHECK(mIsEncoder); 728 729 *colorFormat = OMX_COLOR_FormatYUV420SemiPlanar; 730 int32_t targetColorFormat; 731 if (meta->findInt32(kKeyColorFormat, &targetColorFormat)) { 732 *colorFormat = (OMX_COLOR_FORMATTYPE) targetColorFormat; 733 } 734 735 // Check whether the target color format is supported. 736 return isColorFormatSupported(*colorFormat, kPortIndexInput); 737} 738 739status_t OMXCodec::isColorFormatSupported( 740 OMX_COLOR_FORMATTYPE colorFormat, int portIndex) { 741 ALOGV("isColorFormatSupported: %d", static_cast<int>(colorFormat)); 742 743 // Enumerate all the color formats supported by 744 // the omx component to see whether the given 745 // color format is supported. 746 OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat; 747 InitOMXParams(&portFormat); 748 portFormat.nPortIndex = portIndex; 749 OMX_U32 index = 0; 750 portFormat.nIndex = index; 751 while (true) { 752 if (OMX_ErrorNone != mOMX->getParameter( 753 mNode, OMX_IndexParamVideoPortFormat, 754 &portFormat, sizeof(portFormat))) { 755 break; 756 } 757 // Make sure that omx component does not overwrite 758 // the incremented index (bug 2897413). 759 CHECK_EQ(index, portFormat.nIndex); 760 if (portFormat.eColorFormat == colorFormat) { 761 CODEC_LOGV("Found supported color format: %d", portFormat.eColorFormat); 762 return OK; // colorFormat is supported! 763 } 764 ++index; 765 portFormat.nIndex = index; 766 767 if (index >= kMaxColorFormatSupported) { 768 CODEC_LOGE("More than %ld color formats are supported???", index); 769 break; 770 } 771 } 772 773 CODEC_LOGE("color format %d is not supported", colorFormat); 774 return UNKNOWN_ERROR; 775} 776 777void OMXCodec::setVideoInputFormat( 778 const char *mime, const sp<MetaData>& meta) { 779 780 int32_t width, height, frameRate, bitRate, stride, sliceHeight; 781 bool success = meta->findInt32(kKeyWidth, &width); 782 success = success && meta->findInt32(kKeyHeight, &height); 783 success = success && meta->findInt32(kKeyFrameRate, &frameRate); 784 success = success && meta->findInt32(kKeyBitRate, &bitRate); 785 success = success && meta->findInt32(kKeyStride, &stride); 786 success = success && meta->findInt32(kKeySliceHeight, &sliceHeight); 787 CHECK(success); 788 CHECK(stride != 0); 789 790 OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused; 791 if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) { 792 compressionFormat = OMX_VIDEO_CodingAVC; 793 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) { 794 compressionFormat = OMX_VIDEO_CodingMPEG4; 795 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) { 796 compressionFormat = OMX_VIDEO_CodingH263; 797 } else { 798 ALOGE("Not a supported video mime type: %s", mime); 799 CHECK(!"Should not be here. Not a supported video mime type."); 800 } 801 802 OMX_COLOR_FORMATTYPE colorFormat; 803 CHECK_EQ((status_t)OK, findTargetColorFormat(meta, &colorFormat)); 804 805 status_t err; 806 OMX_PARAM_PORTDEFINITIONTYPE def; 807 OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video; 808 809 //////////////////////// Input port ///////////////////////// 810 CHECK_EQ(setVideoPortFormatType( 811 kPortIndexInput, OMX_VIDEO_CodingUnused, 812 colorFormat), (status_t)OK); 813 814 InitOMXParams(&def); 815 def.nPortIndex = kPortIndexInput; 816 817 err = mOMX->getParameter( 818 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 819 CHECK_EQ(err, (status_t)OK); 820 821 def.nBufferSize = getFrameSize(colorFormat, 822 stride > 0? stride: -stride, sliceHeight); 823 824 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo); 825 826 video_def->nFrameWidth = width; 827 video_def->nFrameHeight = height; 828 video_def->nStride = stride; 829 video_def->nSliceHeight = sliceHeight; 830 video_def->xFramerate = (frameRate << 16); // Q16 format 831 video_def->eCompressionFormat = OMX_VIDEO_CodingUnused; 832 video_def->eColorFormat = colorFormat; 833 834 err = mOMX->setParameter( 835 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 836 CHECK_EQ(err, (status_t)OK); 837 838 //////////////////////// Output port ///////////////////////// 839 CHECK_EQ(setVideoPortFormatType( 840 kPortIndexOutput, compressionFormat, OMX_COLOR_FormatUnused), 841 (status_t)OK); 842 InitOMXParams(&def); 843 def.nPortIndex = kPortIndexOutput; 844 845 err = mOMX->getParameter( 846 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 847 848 CHECK_EQ(err, (status_t)OK); 849 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo); 850 851 video_def->nFrameWidth = width; 852 video_def->nFrameHeight = height; 853 video_def->xFramerate = 0; // No need for output port 854 video_def->nBitrate = bitRate; // Q16 format 855 video_def->eCompressionFormat = compressionFormat; 856 video_def->eColorFormat = OMX_COLOR_FormatUnused; 857 if (mQuirks & kRequiresLargerEncoderOutputBuffer) { 858 // Increases the output buffer size 859 def.nBufferSize = ((def.nBufferSize * 3) >> 1); 860 } 861 862 err = mOMX->setParameter( 863 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 864 CHECK_EQ(err, (status_t)OK); 865 866 /////////////////// Codec-specific //////////////////////// 867 switch (compressionFormat) { 868 case OMX_VIDEO_CodingMPEG4: 869 { 870 CHECK_EQ(setupMPEG4EncoderParameters(meta), (status_t)OK); 871 break; 872 } 873 874 case OMX_VIDEO_CodingH263: 875 CHECK_EQ(setupH263EncoderParameters(meta), (status_t)OK); 876 break; 877 878 case OMX_VIDEO_CodingAVC: 879 { 880 CHECK_EQ(setupAVCEncoderParameters(meta), (status_t)OK); 881 break; 882 } 883 884 default: 885 CHECK(!"Support for this compressionFormat to be implemented."); 886 break; 887 } 888} 889 890static OMX_U32 setPFramesSpacing(int32_t iFramesInterval, int32_t frameRate) { 891 if (iFramesInterval < 0) { 892 return 0xFFFFFFFF; 893 } else if (iFramesInterval == 0) { 894 return 0; 895 } 896 OMX_U32 ret = frameRate * iFramesInterval; 897 CHECK(ret > 1); 898 return ret; 899} 900 901status_t OMXCodec::setupErrorCorrectionParameters() { 902 OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE errorCorrectionType; 903 InitOMXParams(&errorCorrectionType); 904 errorCorrectionType.nPortIndex = kPortIndexOutput; 905 906 status_t err = mOMX->getParameter( 907 mNode, OMX_IndexParamVideoErrorCorrection, 908 &errorCorrectionType, sizeof(errorCorrectionType)); 909 if (err != OK) { 910 ALOGW("Error correction param query is not supported"); 911 return OK; // Optional feature. Ignore this failure 912 } 913 914 errorCorrectionType.bEnableHEC = OMX_FALSE; 915 errorCorrectionType.bEnableResync = OMX_TRUE; 916 errorCorrectionType.nResynchMarkerSpacing = 256; 917 errorCorrectionType.bEnableDataPartitioning = OMX_FALSE; 918 errorCorrectionType.bEnableRVLC = OMX_FALSE; 919 920 err = mOMX->setParameter( 921 mNode, OMX_IndexParamVideoErrorCorrection, 922 &errorCorrectionType, sizeof(errorCorrectionType)); 923 if (err != OK) { 924 ALOGW("Error correction param configuration is not supported"); 925 } 926 927 // Optional feature. Ignore the failure. 928 return OK; 929} 930 931status_t OMXCodec::setupBitRate(int32_t bitRate) { 932 OMX_VIDEO_PARAM_BITRATETYPE bitrateType; 933 InitOMXParams(&bitrateType); 934 bitrateType.nPortIndex = kPortIndexOutput; 935 936 status_t err = mOMX->getParameter( 937 mNode, OMX_IndexParamVideoBitrate, 938 &bitrateType, sizeof(bitrateType)); 939 CHECK_EQ(err, (status_t)OK); 940 941 bitrateType.eControlRate = OMX_Video_ControlRateVariable; 942 bitrateType.nTargetBitrate = bitRate; 943 944 err = mOMX->setParameter( 945 mNode, OMX_IndexParamVideoBitrate, 946 &bitrateType, sizeof(bitrateType)); 947 CHECK_EQ(err, (status_t)OK); 948 return OK; 949} 950 951status_t OMXCodec::getVideoProfileLevel( 952 const sp<MetaData>& meta, 953 const CodecProfileLevel& defaultProfileLevel, 954 CodecProfileLevel &profileLevel) { 955 CODEC_LOGV("Default profile: %ld, level %ld", 956 defaultProfileLevel.mProfile, defaultProfileLevel.mLevel); 957 958 // Are the default profile and level overwriten? 959 int32_t profile, level; 960 if (!meta->findInt32(kKeyVideoProfile, &profile)) { 961 profile = defaultProfileLevel.mProfile; 962 } 963 if (!meta->findInt32(kKeyVideoLevel, &level)) { 964 level = defaultProfileLevel.mLevel; 965 } 966 CODEC_LOGV("Target profile: %d, level: %d", profile, level); 967 968 // Are the target profile and level supported by the encoder? 969 OMX_VIDEO_PARAM_PROFILELEVELTYPE param; 970 InitOMXParams(¶m); 971 param.nPortIndex = kPortIndexOutput; 972 for (param.nProfileIndex = 0;; ++param.nProfileIndex) { 973 status_t err = mOMX->getParameter( 974 mNode, OMX_IndexParamVideoProfileLevelQuerySupported, 975 ¶m, sizeof(param)); 976 977 if (err != OK) break; 978 979 int32_t supportedProfile = static_cast<int32_t>(param.eProfile); 980 int32_t supportedLevel = static_cast<int32_t>(param.eLevel); 981 CODEC_LOGV("Supported profile: %d, level %d", 982 supportedProfile, supportedLevel); 983 984 if (profile == supportedProfile && 985 level <= supportedLevel) { 986 // We can further check whether the level is a valid 987 // value; but we will leave that to the omx encoder component 988 // via OMX_SetParameter call. 989 profileLevel.mProfile = profile; 990 profileLevel.mLevel = level; 991 return OK; 992 } 993 } 994 995 CODEC_LOGE("Target profile (%d) and level (%d) is not supported", 996 profile, level); 997 return BAD_VALUE; 998} 999 1000status_t OMXCodec::setupH263EncoderParameters(const sp<MetaData>& meta) { 1001 int32_t iFramesInterval, frameRate, bitRate; 1002 bool success = meta->findInt32(kKeyBitRate, &bitRate); 1003 success = success && meta->findInt32(kKeyFrameRate, &frameRate); 1004 success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval); 1005 CHECK(success); 1006 OMX_VIDEO_PARAM_H263TYPE h263type; 1007 InitOMXParams(&h263type); 1008 h263type.nPortIndex = kPortIndexOutput; 1009 1010 status_t err = mOMX->getParameter( 1011 mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type)); 1012 CHECK_EQ(err, (status_t)OK); 1013 1014 h263type.nAllowedPictureTypes = 1015 OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP; 1016 1017 h263type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate); 1018 if (h263type.nPFrames == 0) { 1019 h263type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI; 1020 } 1021 h263type.nBFrames = 0; 1022 1023 // Check profile and level parameters 1024 CodecProfileLevel defaultProfileLevel, profileLevel; 1025 defaultProfileLevel.mProfile = h263type.eProfile; 1026 defaultProfileLevel.mLevel = h263type.eLevel; 1027 err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel); 1028 if (err != OK) return err; 1029 h263type.eProfile = static_cast<OMX_VIDEO_H263PROFILETYPE>(profileLevel.mProfile); 1030 h263type.eLevel = static_cast<OMX_VIDEO_H263LEVELTYPE>(profileLevel.mLevel); 1031 1032 h263type.bPLUSPTYPEAllowed = OMX_FALSE; 1033 h263type.bForceRoundingTypeToZero = OMX_FALSE; 1034 h263type.nPictureHeaderRepetition = 0; 1035 h263type.nGOBHeaderInterval = 0; 1036 1037 err = mOMX->setParameter( 1038 mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type)); 1039 CHECK_EQ(err, (status_t)OK); 1040 1041 CHECK_EQ(setupBitRate(bitRate), (status_t)OK); 1042 CHECK_EQ(setupErrorCorrectionParameters(), (status_t)OK); 1043 1044 return OK; 1045} 1046 1047status_t OMXCodec::setupMPEG4EncoderParameters(const sp<MetaData>& meta) { 1048 int32_t iFramesInterval, frameRate, bitRate; 1049 bool success = meta->findInt32(kKeyBitRate, &bitRate); 1050 success = success && meta->findInt32(kKeyFrameRate, &frameRate); 1051 success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval); 1052 CHECK(success); 1053 OMX_VIDEO_PARAM_MPEG4TYPE mpeg4type; 1054 InitOMXParams(&mpeg4type); 1055 mpeg4type.nPortIndex = kPortIndexOutput; 1056 1057 status_t err = mOMX->getParameter( 1058 mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type)); 1059 CHECK_EQ(err, (status_t)OK); 1060 1061 mpeg4type.nSliceHeaderSpacing = 0; 1062 mpeg4type.bSVH = OMX_FALSE; 1063 mpeg4type.bGov = OMX_FALSE; 1064 1065 mpeg4type.nAllowedPictureTypes = 1066 OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP; 1067 1068 mpeg4type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate); 1069 if (mpeg4type.nPFrames == 0) { 1070 mpeg4type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI; 1071 } 1072 mpeg4type.nBFrames = 0; 1073 mpeg4type.nIDCVLCThreshold = 0; 1074 mpeg4type.bACPred = OMX_TRUE; 1075 mpeg4type.nMaxPacketSize = 256; 1076 mpeg4type.nTimeIncRes = 1000; 1077 mpeg4type.nHeaderExtension = 0; 1078 mpeg4type.bReversibleVLC = OMX_FALSE; 1079 1080 // Check profile and level parameters 1081 CodecProfileLevel defaultProfileLevel, profileLevel; 1082 defaultProfileLevel.mProfile = mpeg4type.eProfile; 1083 defaultProfileLevel.mLevel = mpeg4type.eLevel; 1084 err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel); 1085 if (err != OK) return err; 1086 mpeg4type.eProfile = static_cast<OMX_VIDEO_MPEG4PROFILETYPE>(profileLevel.mProfile); 1087 mpeg4type.eLevel = static_cast<OMX_VIDEO_MPEG4LEVELTYPE>(profileLevel.mLevel); 1088 1089 err = mOMX->setParameter( 1090 mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type)); 1091 CHECK_EQ(err, (status_t)OK); 1092 1093 CHECK_EQ(setupBitRate(bitRate), (status_t)OK); 1094 CHECK_EQ(setupErrorCorrectionParameters(), (status_t)OK); 1095 1096 return OK; 1097} 1098 1099status_t OMXCodec::setupAVCEncoderParameters(const sp<MetaData>& meta) { 1100 int32_t iFramesInterval, frameRate, bitRate; 1101 bool success = meta->findInt32(kKeyBitRate, &bitRate); 1102 success = success && meta->findInt32(kKeyFrameRate, &frameRate); 1103 success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval); 1104 CHECK(success); 1105 1106 OMX_VIDEO_PARAM_AVCTYPE h264type; 1107 InitOMXParams(&h264type); 1108 h264type.nPortIndex = kPortIndexOutput; 1109 1110 status_t err = mOMX->getParameter( 1111 mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type)); 1112 CHECK_EQ(err, (status_t)OK); 1113 1114 h264type.nAllowedPictureTypes = 1115 OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP; 1116 1117 // Check profile and level parameters 1118 CodecProfileLevel defaultProfileLevel, profileLevel; 1119 defaultProfileLevel.mProfile = h264type.eProfile; 1120 defaultProfileLevel.mLevel = h264type.eLevel; 1121 err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel); 1122 if (err != OK) return err; 1123 h264type.eProfile = static_cast<OMX_VIDEO_AVCPROFILETYPE>(profileLevel.mProfile); 1124 h264type.eLevel = static_cast<OMX_VIDEO_AVCLEVELTYPE>(profileLevel.mLevel); 1125 1126 // XXX 1127 if (h264type.eProfile != OMX_VIDEO_AVCProfileBaseline) { 1128 ALOGW("Use baseline profile instead of %d for AVC recording", 1129 h264type.eProfile); 1130 h264type.eProfile = OMX_VIDEO_AVCProfileBaseline; 1131 } 1132 1133 if (h264type.eProfile == OMX_VIDEO_AVCProfileBaseline) { 1134 h264type.nSliceHeaderSpacing = 0; 1135 h264type.bUseHadamard = OMX_TRUE; 1136 h264type.nRefFrames = 1; 1137 h264type.nBFrames = 0; 1138 h264type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate); 1139 if (h264type.nPFrames == 0) { 1140 h264type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI; 1141 } 1142 h264type.nRefIdx10ActiveMinus1 = 0; 1143 h264type.nRefIdx11ActiveMinus1 = 0; 1144 h264type.bEntropyCodingCABAC = OMX_FALSE; 1145 h264type.bWeightedPPrediction = OMX_FALSE; 1146 h264type.bconstIpred = OMX_FALSE; 1147 h264type.bDirect8x8Inference = OMX_FALSE; 1148 h264type.bDirectSpatialTemporal = OMX_FALSE; 1149 h264type.nCabacInitIdc = 0; 1150 } 1151 1152 if (h264type.nBFrames != 0) { 1153 h264type.nAllowedPictureTypes |= OMX_VIDEO_PictureTypeB; 1154 } 1155 1156 h264type.bEnableUEP = OMX_FALSE; 1157 h264type.bEnableFMO = OMX_FALSE; 1158 h264type.bEnableASO = OMX_FALSE; 1159 h264type.bEnableRS = OMX_FALSE; 1160 h264type.bFrameMBsOnly = OMX_TRUE; 1161 h264type.bMBAFF = OMX_FALSE; 1162 h264type.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable; 1163 1164 err = mOMX->setParameter( 1165 mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type)); 1166 CHECK_EQ(err, (status_t)OK); 1167 1168 CHECK_EQ(setupBitRate(bitRate), (status_t)OK); 1169 1170 return OK; 1171} 1172 1173status_t OMXCodec::setVideoOutputFormat( 1174 const char *mime, OMX_U32 width, OMX_U32 height) { 1175 CODEC_LOGV("setVideoOutputFormat width=%ld, height=%ld", width, height); 1176 1177 OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused; 1178 if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) { 1179 compressionFormat = OMX_VIDEO_CodingAVC; 1180 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) { 1181 compressionFormat = OMX_VIDEO_CodingMPEG4; 1182 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) { 1183 compressionFormat = OMX_VIDEO_CodingH263; 1184 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_VPX, mime)) { 1185 compressionFormat = OMX_VIDEO_CodingVPX; 1186 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG2, mime)) { 1187 compressionFormat = OMX_VIDEO_CodingMPEG2; 1188 } else { 1189 ALOGE("Not a supported video mime type: %s", mime); 1190 CHECK(!"Should not be here. Not a supported video mime type."); 1191 } 1192 1193 status_t err = setVideoPortFormatType( 1194 kPortIndexInput, compressionFormat, OMX_COLOR_FormatUnused); 1195 1196 if (err != OK) { 1197 return err; 1198 } 1199 1200#if 1 1201 { 1202 OMX_VIDEO_PARAM_PORTFORMATTYPE format; 1203 InitOMXParams(&format); 1204 format.nPortIndex = kPortIndexOutput; 1205 format.nIndex = 0; 1206 1207 status_t err = mOMX->getParameter( 1208 mNode, OMX_IndexParamVideoPortFormat, 1209 &format, sizeof(format)); 1210 CHECK_EQ(err, (status_t)OK); 1211 CHECK_EQ((int)format.eCompressionFormat, (int)OMX_VIDEO_CodingUnused); 1212 1213 CHECK(format.eColorFormat == OMX_COLOR_FormatYUV420Planar 1214 || format.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar 1215 || format.eColorFormat == OMX_COLOR_FormatCbYCrY 1216 || format.eColorFormat == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar 1217 || format.eColorFormat == OMX_QCOM_COLOR_FormatYVU420SemiPlanar); 1218 1219 err = mOMX->setParameter( 1220 mNode, OMX_IndexParamVideoPortFormat, 1221 &format, sizeof(format)); 1222 1223 if (err != OK) { 1224 return err; 1225 } 1226 } 1227#endif 1228 1229 OMX_PARAM_PORTDEFINITIONTYPE def; 1230 InitOMXParams(&def); 1231 def.nPortIndex = kPortIndexInput; 1232 1233 OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video; 1234 1235 err = mOMX->getParameter( 1236 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1237 1238 CHECK_EQ(err, (status_t)OK); 1239 1240#if 1 1241 // XXX Need a (much) better heuristic to compute input buffer sizes. 1242 const size_t X = 64 * 1024; 1243 if (def.nBufferSize < X) { 1244 def.nBufferSize = X; 1245 } 1246#endif 1247 1248 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo); 1249 1250 video_def->nFrameWidth = width; 1251 video_def->nFrameHeight = height; 1252 1253 video_def->eCompressionFormat = compressionFormat; 1254 video_def->eColorFormat = OMX_COLOR_FormatUnused; 1255 1256 err = mOMX->setParameter( 1257 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1258 1259 if (err != OK) { 1260 return err; 1261 } 1262 1263 //////////////////////////////////////////////////////////////////////////// 1264 1265 InitOMXParams(&def); 1266 def.nPortIndex = kPortIndexOutput; 1267 1268 err = mOMX->getParameter( 1269 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1270 CHECK_EQ(err, (status_t)OK); 1271 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo); 1272 1273#if 0 1274 def.nBufferSize = 1275 (((width + 15) & -16) * ((height + 15) & -16) * 3) / 2; // YUV420 1276#endif 1277 1278 video_def->nFrameWidth = width; 1279 video_def->nFrameHeight = height; 1280 1281 err = mOMX->setParameter( 1282 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1283 1284 return err; 1285} 1286 1287OMXCodec::OMXCodec( 1288 const sp<IOMX> &omx, IOMX::node_id node, 1289 uint32_t quirks, uint32_t flags, 1290 bool isEncoder, 1291 const char *mime, 1292 const char *componentName, 1293 const sp<MediaSource> &source, 1294 const sp<ANativeWindow> &nativeWindow) 1295 : mOMX(omx), 1296 mOMXLivesLocally(omx->livesLocally(node, getpid())), 1297 mNode(node), 1298 mQuirks(quirks), 1299 mFlags(flags), 1300 mIsEncoder(isEncoder), 1301 mIsVideo(!strncasecmp("video/", mime, 6)), 1302 mMIME(strdup(mime)), 1303 mComponentName(strdup(componentName)), 1304 mSource(source), 1305 mCodecSpecificDataIndex(0), 1306 mState(LOADED), 1307 mInitialBufferSubmit(true), 1308 mSignalledEOS(false), 1309 mNoMoreOutputData(false), 1310 mOutputPortSettingsHaveChanged(false), 1311 mSeekTimeUs(-1), 1312 mSeekMode(ReadOptions::SEEK_CLOSEST_SYNC), 1313 mTargetTimeUs(-1), 1314 mOutputPortSettingsChangedPending(false), 1315 mSkipCutBuffer(NULL), 1316 mLeftOverBuffer(NULL), 1317 mPaused(false), 1318 mNativeWindow( 1319 (!strncmp(componentName, "OMX.google.", 11) 1320 || !strcmp(componentName, "OMX.Nvidia.mpeg2v.decode")) 1321 ? NULL : nativeWindow) { 1322 mPortStatus[kPortIndexInput] = ENABLED; 1323 mPortStatus[kPortIndexOutput] = ENABLED; 1324 1325 setComponentRole(); 1326} 1327 1328// static 1329void OMXCodec::setComponentRole( 1330 const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder, 1331 const char *mime) { 1332 struct MimeToRole { 1333 const char *mime; 1334 const char *decoderRole; 1335 const char *encoderRole; 1336 }; 1337 1338 static const MimeToRole kMimeToRole[] = { 1339 { MEDIA_MIMETYPE_AUDIO_MPEG, 1340 "audio_decoder.mp3", "audio_encoder.mp3" }, 1341 { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I, 1342 "audio_decoder.mp1", "audio_encoder.mp1" }, 1343 { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II, 1344 "audio_decoder.mp2", "audio_encoder.mp2" }, 1345 { MEDIA_MIMETYPE_AUDIO_AMR_NB, 1346 "audio_decoder.amrnb", "audio_encoder.amrnb" }, 1347 { MEDIA_MIMETYPE_AUDIO_AMR_WB, 1348 "audio_decoder.amrwb", "audio_encoder.amrwb" }, 1349 { MEDIA_MIMETYPE_AUDIO_AAC, 1350 "audio_decoder.aac", "audio_encoder.aac" }, 1351 { MEDIA_MIMETYPE_AUDIO_VORBIS, 1352 "audio_decoder.vorbis", "audio_encoder.vorbis" }, 1353 { MEDIA_MIMETYPE_AUDIO_G711_MLAW, 1354 "audio_decoder.g711mlaw", "audio_encoder.g711mlaw" }, 1355 { MEDIA_MIMETYPE_AUDIO_G711_ALAW, 1356 "audio_decoder.g711alaw", "audio_encoder.g711alaw" }, 1357 { MEDIA_MIMETYPE_VIDEO_AVC, 1358 "video_decoder.avc", "video_encoder.avc" }, 1359 { MEDIA_MIMETYPE_VIDEO_MPEG4, 1360 "video_decoder.mpeg4", "video_encoder.mpeg4" }, 1361 { MEDIA_MIMETYPE_VIDEO_H263, 1362 "video_decoder.h263", "video_encoder.h263" }, 1363 { MEDIA_MIMETYPE_VIDEO_VPX, 1364 "video_decoder.vpx", "video_encoder.vpx" }, 1365 { MEDIA_MIMETYPE_AUDIO_RAW, 1366 "audio_decoder.raw", "audio_encoder.raw" }, 1367 { MEDIA_MIMETYPE_AUDIO_FLAC, 1368 "audio_decoder.flac", "audio_encoder.flac" }, 1369 }; 1370 1371 static const size_t kNumMimeToRole = 1372 sizeof(kMimeToRole) / sizeof(kMimeToRole[0]); 1373 1374 size_t i; 1375 for (i = 0; i < kNumMimeToRole; ++i) { 1376 if (!strcasecmp(mime, kMimeToRole[i].mime)) { 1377 break; 1378 } 1379 } 1380 1381 if (i == kNumMimeToRole) { 1382 return; 1383 } 1384 1385 const char *role = 1386 isEncoder ? kMimeToRole[i].encoderRole 1387 : kMimeToRole[i].decoderRole; 1388 1389 if (role != NULL) { 1390 OMX_PARAM_COMPONENTROLETYPE roleParams; 1391 InitOMXParams(&roleParams); 1392 1393 strncpy((char *)roleParams.cRole, 1394 role, OMX_MAX_STRINGNAME_SIZE - 1); 1395 1396 roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0'; 1397 1398 status_t err = omx->setParameter( 1399 node, OMX_IndexParamStandardComponentRole, 1400 &roleParams, sizeof(roleParams)); 1401 1402 if (err != OK) { 1403 ALOGW("Failed to set standard component role '%s'.", role); 1404 } 1405 } 1406} 1407 1408void OMXCodec::setComponentRole() { 1409 setComponentRole(mOMX, mNode, mIsEncoder, mMIME); 1410} 1411 1412OMXCodec::~OMXCodec() { 1413 mSource.clear(); 1414 1415 CHECK(mState == LOADED || mState == ERROR || mState == LOADED_TO_IDLE); 1416 1417 status_t err = mOMX->freeNode(mNode); 1418 CHECK_EQ(err, (status_t)OK); 1419 1420 mNode = NULL; 1421 setState(DEAD); 1422 1423 clearCodecSpecificData(); 1424 1425 free(mComponentName); 1426 mComponentName = NULL; 1427 1428 free(mMIME); 1429 mMIME = NULL; 1430} 1431 1432status_t OMXCodec::init() { 1433 // mLock is held. 1434 1435 CHECK_EQ((int)mState, (int)LOADED); 1436 1437 status_t err; 1438 if (!(mQuirks & kRequiresLoadedToIdleAfterAllocation)) { 1439 err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 1440 CHECK_EQ(err, (status_t)OK); 1441 setState(LOADED_TO_IDLE); 1442 } 1443 1444 err = allocateBuffers(); 1445 if (err != (status_t)OK) { 1446 return err; 1447 } 1448 1449 if (mQuirks & kRequiresLoadedToIdleAfterAllocation) { 1450 err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 1451 CHECK_EQ(err, (status_t)OK); 1452 1453 setState(LOADED_TO_IDLE); 1454 } 1455 1456 while (mState != EXECUTING && mState != ERROR) { 1457 mAsyncCompletion.wait(mLock); 1458 } 1459 1460 return mState == ERROR ? UNKNOWN_ERROR : OK; 1461} 1462 1463// static 1464bool OMXCodec::isIntermediateState(State state) { 1465 return state == LOADED_TO_IDLE 1466 || state == IDLE_TO_EXECUTING 1467 || state == EXECUTING_TO_IDLE 1468 || state == IDLE_TO_LOADED 1469 || state == RECONFIGURING; 1470} 1471 1472status_t OMXCodec::allocateBuffers() { 1473 status_t err = allocateBuffersOnPort(kPortIndexInput); 1474 1475 if (err != OK) { 1476 return err; 1477 } 1478 1479 return allocateBuffersOnPort(kPortIndexOutput); 1480} 1481 1482status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) { 1483 if (mNativeWindow != NULL && portIndex == kPortIndexOutput) { 1484 return allocateOutputBuffersFromNativeWindow(); 1485 } 1486 1487 if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) { 1488 ALOGE("protected output buffers must be stent to an ANativeWindow"); 1489 return PERMISSION_DENIED; 1490 } 1491 1492 status_t err = OK; 1493 if ((mFlags & kStoreMetaDataInVideoBuffers) 1494 && portIndex == kPortIndexInput) { 1495 err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE); 1496 if (err != OK) { 1497 ALOGE("Storing meta data in video buffers is not supported"); 1498 return err; 1499 } 1500 } 1501 1502 OMX_PARAM_PORTDEFINITIONTYPE def; 1503 InitOMXParams(&def); 1504 def.nPortIndex = portIndex; 1505 1506 err = mOMX->getParameter( 1507 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1508 1509 if (err != OK) { 1510 return err; 1511 } 1512 1513 CODEC_LOGV("allocating %lu buffers of size %lu on %s port", 1514 def.nBufferCountActual, def.nBufferSize, 1515 portIndex == kPortIndexInput ? "input" : "output"); 1516 1517 size_t totalSize = def.nBufferCountActual * def.nBufferSize; 1518 mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec"); 1519 1520 for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) { 1521 sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize); 1522 CHECK(mem.get() != NULL); 1523 1524 BufferInfo info; 1525 info.mData = NULL; 1526 info.mSize = def.nBufferSize; 1527 1528 IOMX::buffer_id buffer; 1529 if (portIndex == kPortIndexInput 1530 && ((mQuirks & kRequiresAllocateBufferOnInputPorts) 1531 || (mFlags & kUseSecureInputBuffers))) { 1532 if (mOMXLivesLocally) { 1533 mem.clear(); 1534 1535 err = mOMX->allocateBuffer( 1536 mNode, portIndex, def.nBufferSize, &buffer, 1537 &info.mData); 1538 } else { 1539 err = mOMX->allocateBufferWithBackup( 1540 mNode, portIndex, mem, &buffer); 1541 } 1542 } else if (portIndex == kPortIndexOutput 1543 && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) { 1544 if (mOMXLivesLocally) { 1545 mem.clear(); 1546 1547 err = mOMX->allocateBuffer( 1548 mNode, portIndex, def.nBufferSize, &buffer, 1549 &info.mData); 1550 } else { 1551 err = mOMX->allocateBufferWithBackup( 1552 mNode, portIndex, mem, &buffer); 1553 } 1554 } else { 1555 err = mOMX->useBuffer(mNode, portIndex, mem, &buffer); 1556 } 1557 1558 if (err != OK) { 1559 ALOGE("allocate_buffer_with_backup failed"); 1560 return err; 1561 } 1562 1563 if (mem != NULL) { 1564 info.mData = mem->pointer(); 1565 } 1566 1567 info.mBuffer = buffer; 1568 info.mStatus = OWNED_BY_US; 1569 info.mMem = mem; 1570 info.mMediaBuffer = NULL; 1571 1572 if (portIndex == kPortIndexOutput) { 1573 if (!(mOMXLivesLocally 1574 && (mQuirks & kRequiresAllocateBufferOnOutputPorts) 1575 && (mQuirks & kDefersOutputBufferAllocation))) { 1576 // If the node does not fill in the buffer ptr at this time, 1577 // we will defer creating the MediaBuffer until receiving 1578 // the first FILL_BUFFER_DONE notification instead. 1579 info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize); 1580 info.mMediaBuffer->setObserver(this); 1581 } 1582 } 1583 1584 mPortBuffers[portIndex].push(info); 1585 1586 CODEC_LOGV("allocated buffer %p on %s port", buffer, 1587 portIndex == kPortIndexInput ? "input" : "output"); 1588 } 1589 1590 if (portIndex == kPortIndexOutput) { 1591 1592 sp<MetaData> meta = mSource->getFormat(); 1593 int32_t delay = 0; 1594 if (!meta->findInt32(kKeyEncoderDelay, &delay)) { 1595 delay = 0; 1596 } 1597 int32_t padding = 0; 1598 if (!meta->findInt32(kKeyEncoderPadding, &padding)) { 1599 padding = 0; 1600 } 1601 int32_t numchannels = 0; 1602 if (delay + padding) { 1603 if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) { 1604 size_t frameSize = numchannels * sizeof(int16_t); 1605 if (mSkipCutBuffer != NULL) { 1606 size_t prevbuffersize = mSkipCutBuffer->size(); 1607 if (prevbuffersize != 0) { 1608 ALOGW("Replacing SkipCutBuffer holding %d bytes", prevbuffersize); 1609 } 1610 } 1611 mSkipCutBuffer = new SkipCutBuffer(delay * frameSize, padding * frameSize); 1612 } 1613 } 1614 } 1615 1616 // dumpPortStatus(portIndex); 1617 1618 if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) { 1619 Vector<MediaBuffer *> buffers; 1620 for (size_t i = 0; i < def.nBufferCountActual; ++i) { 1621 const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i); 1622 1623 MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize); 1624 buffers.push(mbuf); 1625 } 1626 1627 status_t err = mSource->setBuffers(buffers); 1628 1629 if (err != OK) { 1630 for (size_t i = 0; i < def.nBufferCountActual; ++i) { 1631 buffers.editItemAt(i)->release(); 1632 } 1633 buffers.clear(); 1634 1635 CODEC_LOGE( 1636 "Codec requested to use secure input buffers but " 1637 "upstream source didn't support that."); 1638 1639 return err; 1640 } 1641 } 1642 1643 return OK; 1644} 1645 1646status_t OMXCodec::applyRotation() { 1647 sp<MetaData> meta = mSource->getFormat(); 1648 1649 int32_t rotationDegrees; 1650 if (!meta->findInt32(kKeyRotation, &rotationDegrees)) { 1651 rotationDegrees = 0; 1652 } 1653 1654 uint32_t transform; 1655 switch (rotationDegrees) { 1656 case 0: transform = 0; break; 1657 case 90: transform = HAL_TRANSFORM_ROT_90; break; 1658 case 180: transform = HAL_TRANSFORM_ROT_180; break; 1659 case 270: transform = HAL_TRANSFORM_ROT_270; break; 1660 default: transform = 0; break; 1661 } 1662 1663 status_t err = OK; 1664 1665 if (transform) { 1666 err = native_window_set_buffers_transform( 1667 mNativeWindow.get(), transform); 1668 } 1669 1670 return err; 1671} 1672 1673status_t OMXCodec::allocateOutputBuffersFromNativeWindow() { 1674 // Get the number of buffers needed. 1675 OMX_PARAM_PORTDEFINITIONTYPE def; 1676 InitOMXParams(&def); 1677 def.nPortIndex = kPortIndexOutput; 1678 1679 status_t err = mOMX->getParameter( 1680 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1681 if (err != OK) { 1682 return err; 1683 } 1684 1685 err = native_window_set_buffers_geometry( 1686 mNativeWindow.get(), 1687 def.format.video.nFrameWidth, 1688 def.format.video.nFrameHeight, 1689 def.format.video.eColorFormat); 1690 1691 if (err != 0) { 1692 ALOGE("native_window_set_buffers_geometry failed: %s (%d)", 1693 strerror(-err), -err); 1694 return err; 1695 } 1696 1697 err = applyRotation(); 1698 if (err != OK) { 1699 return err; 1700 } 1701 1702 // Set up the native window. 1703 OMX_U32 usage = 0; 1704 err = mOMX->getGraphicBufferUsage(mNode, kPortIndexOutput, &usage); 1705 if (err != 0) { 1706 ALOGW("querying usage flags from OMX IL component failed: %d", err); 1707 // XXX: Currently this error is logged, but not fatal. 1708 usage = 0; 1709 } 1710 if (mFlags & kEnableGrallocUsageProtected) { 1711 usage |= GRALLOC_USAGE_PROTECTED; 1712 } 1713 1714 // Make sure to check whether either Stagefright or the video decoder 1715 // requested protected buffers. 1716 if (usage & GRALLOC_USAGE_PROTECTED) { 1717 // Verify that the ANativeWindow sends images directly to 1718 // SurfaceFlinger. 1719 int queuesToNativeWindow = 0; 1720 err = mNativeWindow->query( 1721 mNativeWindow.get(), NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, 1722 &queuesToNativeWindow); 1723 if (err != 0) { 1724 ALOGE("error authenticating native window: %d", err); 1725 return err; 1726 } 1727 if (queuesToNativeWindow != 1) { 1728 ALOGE("native window could not be authenticated"); 1729 return PERMISSION_DENIED; 1730 } 1731 } 1732 1733 ALOGV("native_window_set_usage usage=0x%lx", usage); 1734 err = native_window_set_usage( 1735 mNativeWindow.get(), usage | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP); 1736 if (err != 0) { 1737 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), -err); 1738 return err; 1739 } 1740 1741 int minUndequeuedBufs = 0; 1742 err = mNativeWindow->query(mNativeWindow.get(), 1743 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs); 1744 if (err != 0) { 1745 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)", 1746 strerror(-err), -err); 1747 return err; 1748 } 1749 1750 // XXX: Is this the right logic to use? It's not clear to me what the OMX 1751 // buffer counts refer to - how do they account for the renderer holding on 1752 // to buffers? 1753 if (def.nBufferCountActual < def.nBufferCountMin + minUndequeuedBufs) { 1754 OMX_U32 newBufferCount = def.nBufferCountMin + minUndequeuedBufs; 1755 def.nBufferCountActual = newBufferCount; 1756 err = mOMX->setParameter( 1757 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1758 if (err != OK) { 1759 CODEC_LOGE("setting nBufferCountActual to %lu failed: %d", 1760 newBufferCount, err); 1761 return err; 1762 } 1763 } 1764 1765 err = native_window_set_buffer_count( 1766 mNativeWindow.get(), def.nBufferCountActual); 1767 if (err != 0) { 1768 ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err), 1769 -err); 1770 return err; 1771 } 1772 1773 CODEC_LOGV("allocating %lu buffers from a native window of size %lu on " 1774 "output port", def.nBufferCountActual, def.nBufferSize); 1775 1776 // Dequeue buffers and send them to OMX 1777 for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) { 1778 ANativeWindowBuffer* buf; 1779 err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf); 1780 if (err != 0) { 1781 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), -err); 1782 break; 1783 } 1784 1785 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false)); 1786 BufferInfo info; 1787 info.mData = NULL; 1788 info.mSize = def.nBufferSize; 1789 info.mStatus = OWNED_BY_US; 1790 info.mMem = NULL; 1791 info.mMediaBuffer = new MediaBuffer(graphicBuffer); 1792 info.mMediaBuffer->setObserver(this); 1793 mPortBuffers[kPortIndexOutput].push(info); 1794 1795 IOMX::buffer_id bufferId; 1796 err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer, 1797 &bufferId); 1798 if (err != 0) { 1799 CODEC_LOGE("registering GraphicBuffer with OMX IL component " 1800 "failed: %d", err); 1801 break; 1802 } 1803 1804 mPortBuffers[kPortIndexOutput].editItemAt(i).mBuffer = bufferId; 1805 1806 CODEC_LOGV("registered graphic buffer with ID %p (pointer = %p)", 1807 bufferId, graphicBuffer.get()); 1808 } 1809 1810 OMX_U32 cancelStart; 1811 OMX_U32 cancelEnd; 1812 if (err != 0) { 1813 // If an error occurred while dequeuing we need to cancel any buffers 1814 // that were dequeued. 1815 cancelStart = 0; 1816 cancelEnd = mPortBuffers[kPortIndexOutput].size(); 1817 } else { 1818 // Return the last two buffers to the native window. 1819 cancelStart = def.nBufferCountActual - minUndequeuedBufs; 1820 cancelEnd = def.nBufferCountActual; 1821 } 1822 1823 for (OMX_U32 i = cancelStart; i < cancelEnd; i++) { 1824 BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(i); 1825 cancelBufferToNativeWindow(info); 1826 } 1827 1828 return err; 1829} 1830 1831status_t OMXCodec::cancelBufferToNativeWindow(BufferInfo *info) { 1832 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 1833 CODEC_LOGV("Calling cancelBuffer on buffer %p", info->mBuffer); 1834 int err = mNativeWindow->cancelBuffer( 1835 mNativeWindow.get(), info->mMediaBuffer->graphicBuffer().get()); 1836 if (err != 0) { 1837 CODEC_LOGE("cancelBuffer failed w/ error 0x%08x", err); 1838 1839 setState(ERROR); 1840 return err; 1841 } 1842 info->mStatus = OWNED_BY_NATIVE_WINDOW; 1843 return OK; 1844} 1845 1846OMXCodec::BufferInfo* OMXCodec::dequeueBufferFromNativeWindow() { 1847 // Dequeue the next buffer from the native window. 1848 ANativeWindowBuffer* buf; 1849 int err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf); 1850 if (err != 0) { 1851 CODEC_LOGE("dequeueBuffer failed w/ error 0x%08x", err); 1852 1853 setState(ERROR); 1854 return 0; 1855 } 1856 1857 // Determine which buffer we just dequeued. 1858 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 1859 BufferInfo *bufInfo = 0; 1860 for (size_t i = 0; i < buffers->size(); i++) { 1861 sp<GraphicBuffer> graphicBuffer = buffers->itemAt(i). 1862 mMediaBuffer->graphicBuffer(); 1863 if (graphicBuffer->handle == buf->handle) { 1864 bufInfo = &buffers->editItemAt(i); 1865 break; 1866 } 1867 } 1868 1869 if (bufInfo == 0) { 1870 CODEC_LOGE("dequeued unrecognized buffer: %p", buf); 1871 1872 setState(ERROR); 1873 return 0; 1874 } 1875 1876 // The native window no longer owns the buffer. 1877 CHECK_EQ((int)bufInfo->mStatus, (int)OWNED_BY_NATIVE_WINDOW); 1878 bufInfo->mStatus = OWNED_BY_US; 1879 1880 return bufInfo; 1881} 1882 1883status_t OMXCodec::pushBlankBuffersToNativeWindow() { 1884 status_t err = NO_ERROR; 1885 ANativeWindowBuffer* anb = NULL; 1886 int numBufs = 0; 1887 int minUndequeuedBufs = 0; 1888 1889 // We need to reconnect to the ANativeWindow as a CPU client to ensure that 1890 // no frames get dropped by SurfaceFlinger assuming that these are video 1891 // frames. 1892 err = native_window_api_disconnect(mNativeWindow.get(), 1893 NATIVE_WINDOW_API_MEDIA); 1894 if (err != NO_ERROR) { 1895 ALOGE("error pushing blank frames: api_disconnect failed: %s (%d)", 1896 strerror(-err), -err); 1897 return err; 1898 } 1899 1900 err = native_window_api_connect(mNativeWindow.get(), 1901 NATIVE_WINDOW_API_CPU); 1902 if (err != NO_ERROR) { 1903 ALOGE("error pushing blank frames: api_connect failed: %s (%d)", 1904 strerror(-err), -err); 1905 return err; 1906 } 1907 1908 err = native_window_set_buffers_geometry(mNativeWindow.get(), 1, 1, 1909 HAL_PIXEL_FORMAT_RGBX_8888); 1910 if (err != NO_ERROR) { 1911 ALOGE("error pushing blank frames: set_buffers_geometry failed: %s (%d)", 1912 strerror(-err), -err); 1913 goto error; 1914 } 1915 1916 err = native_window_set_usage(mNativeWindow.get(), 1917 GRALLOC_USAGE_SW_WRITE_OFTEN); 1918 if (err != NO_ERROR) { 1919 ALOGE("error pushing blank frames: set_usage failed: %s (%d)", 1920 strerror(-err), -err); 1921 goto error; 1922 } 1923 1924 err = mNativeWindow->query(mNativeWindow.get(), 1925 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs); 1926 if (err != NO_ERROR) { 1927 ALOGE("error pushing blank frames: MIN_UNDEQUEUED_BUFFERS query " 1928 "failed: %s (%d)", strerror(-err), -err); 1929 goto error; 1930 } 1931 1932 numBufs = minUndequeuedBufs + 1; 1933 err = native_window_set_buffer_count(mNativeWindow.get(), numBufs); 1934 if (err != NO_ERROR) { 1935 ALOGE("error pushing blank frames: set_buffer_count failed: %s (%d)", 1936 strerror(-err), -err); 1937 goto error; 1938 } 1939 1940 // We push numBufs + 1 buffers to ensure that we've drawn into the same 1941 // buffer twice. This should guarantee that the buffer has been displayed 1942 // on the screen and then been replaced, so an previous video frames are 1943 // guaranteed NOT to be currently displayed. 1944 for (int i = 0; i < numBufs + 1; i++) { 1945 err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &anb); 1946 if (err != NO_ERROR) { 1947 ALOGE("error pushing blank frames: dequeueBuffer failed: %s (%d)", 1948 strerror(-err), -err); 1949 goto error; 1950 } 1951 1952 sp<GraphicBuffer> buf(new GraphicBuffer(anb, false)); 1953 err = mNativeWindow->lockBuffer(mNativeWindow.get(), 1954 buf->getNativeBuffer()); 1955 if (err != NO_ERROR) { 1956 ALOGE("error pushing blank frames: lockBuffer failed: %s (%d)", 1957 strerror(-err), -err); 1958 goto error; 1959 } 1960 1961 // Fill the buffer with the a 1x1 checkerboard pattern ;) 1962 uint32_t* img = NULL; 1963 err = buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img)); 1964 if (err != NO_ERROR) { 1965 ALOGE("error pushing blank frames: lock failed: %s (%d)", 1966 strerror(-err), -err); 1967 goto error; 1968 } 1969 1970 *img = 0; 1971 1972 err = buf->unlock(); 1973 if (err != NO_ERROR) { 1974 ALOGE("error pushing blank frames: unlock failed: %s (%d)", 1975 strerror(-err), -err); 1976 goto error; 1977 } 1978 1979 err = mNativeWindow->queueBuffer(mNativeWindow.get(), 1980 buf->getNativeBuffer()); 1981 if (err != NO_ERROR) { 1982 ALOGE("error pushing blank frames: queueBuffer failed: %s (%d)", 1983 strerror(-err), -err); 1984 goto error; 1985 } 1986 1987 anb = NULL; 1988 } 1989 1990error: 1991 1992 if (err != NO_ERROR) { 1993 // Clean up after an error. 1994 if (anb != NULL) { 1995 mNativeWindow->cancelBuffer(mNativeWindow.get(), anb); 1996 } 1997 1998 native_window_api_disconnect(mNativeWindow.get(), 1999 NATIVE_WINDOW_API_CPU); 2000 native_window_api_connect(mNativeWindow.get(), 2001 NATIVE_WINDOW_API_MEDIA); 2002 2003 return err; 2004 } else { 2005 // Clean up after success. 2006 err = native_window_api_disconnect(mNativeWindow.get(), 2007 NATIVE_WINDOW_API_CPU); 2008 if (err != NO_ERROR) { 2009 ALOGE("error pushing blank frames: api_disconnect failed: %s (%d)", 2010 strerror(-err), -err); 2011 return err; 2012 } 2013 2014 err = native_window_api_connect(mNativeWindow.get(), 2015 NATIVE_WINDOW_API_MEDIA); 2016 if (err != NO_ERROR) { 2017 ALOGE("error pushing blank frames: api_connect failed: %s (%d)", 2018 strerror(-err), -err); 2019 return err; 2020 } 2021 2022 return NO_ERROR; 2023 } 2024} 2025 2026int64_t OMXCodec::getDecodingTimeUs() { 2027 CHECK(mIsEncoder && mIsVideo); 2028 2029 if (mDecodingTimeList.empty()) { 2030 CHECK(mSignalledEOS || mNoMoreOutputData); 2031 // No corresponding input frame available. 2032 // This could happen when EOS is reached. 2033 return 0; 2034 } 2035 2036 List<int64_t>::iterator it = mDecodingTimeList.begin(); 2037 int64_t timeUs = *it; 2038 mDecodingTimeList.erase(it); 2039 return timeUs; 2040} 2041 2042void OMXCodec::on_message(const omx_message &msg) { 2043 if (mState == ERROR) { 2044 ALOGW("Dropping OMX message - we're in ERROR state."); 2045 return; 2046 } 2047 2048 switch (msg.type) { 2049 case omx_message::EVENT: 2050 { 2051 onEvent( 2052 msg.u.event_data.event, msg.u.event_data.data1, 2053 msg.u.event_data.data2); 2054 2055 break; 2056 } 2057 2058 case omx_message::EMPTY_BUFFER_DONE: 2059 { 2060 IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer; 2061 2062 CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer); 2063 2064 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 2065 size_t i = 0; 2066 while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) { 2067 ++i; 2068 } 2069 2070 CHECK(i < buffers->size()); 2071 if ((*buffers)[i].mStatus != OWNED_BY_COMPONENT) { 2072 ALOGW("We already own input buffer %p, yet received " 2073 "an EMPTY_BUFFER_DONE.", buffer); 2074 } 2075 2076 BufferInfo* info = &buffers->editItemAt(i); 2077 info->mStatus = OWNED_BY_US; 2078 2079 // Buffer could not be released until empty buffer done is called. 2080 if (info->mMediaBuffer != NULL) { 2081 if (mIsEncoder && 2082 (mQuirks & kAvoidMemcopyInputRecordingFrames)) { 2083 // If zero-copy mode is enabled this will send the 2084 // input buffer back to the upstream source. 2085 restorePatchedDataPointer(info); 2086 } 2087 2088 info->mMediaBuffer->release(); 2089 info->mMediaBuffer = NULL; 2090 } 2091 2092 if (mPortStatus[kPortIndexInput] == DISABLING) { 2093 CODEC_LOGV("Port is disabled, freeing buffer %p", buffer); 2094 2095 status_t err = freeBuffer(kPortIndexInput, i); 2096 CHECK_EQ(err, (status_t)OK); 2097 } else if (mState != ERROR 2098 && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) { 2099 CHECK_EQ((int)mPortStatus[kPortIndexInput], (int)ENABLED); 2100 2101 if (mFlags & kUseSecureInputBuffers) { 2102 drainAnyInputBuffer(); 2103 } else { 2104 drainInputBuffer(&buffers->editItemAt(i)); 2105 } 2106 } 2107 break; 2108 } 2109 2110 case omx_message::FILL_BUFFER_DONE: 2111 { 2112 IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer; 2113 OMX_U32 flags = msg.u.extended_buffer_data.flags; 2114 2115 CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))", 2116 buffer, 2117 msg.u.extended_buffer_data.range_length, 2118 flags, 2119 msg.u.extended_buffer_data.timestamp, 2120 msg.u.extended_buffer_data.timestamp / 1E6); 2121 2122 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 2123 size_t i = 0; 2124 while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) { 2125 ++i; 2126 } 2127 2128 CHECK(i < buffers->size()); 2129 BufferInfo *info = &buffers->editItemAt(i); 2130 2131 if (info->mStatus != OWNED_BY_COMPONENT) { 2132 ALOGW("We already own output buffer %p, yet received " 2133 "a FILL_BUFFER_DONE.", buffer); 2134 } 2135 2136 info->mStatus = OWNED_BY_US; 2137 2138 if (mPortStatus[kPortIndexOutput] == DISABLING) { 2139 CODEC_LOGV("Port is disabled, freeing buffer %p", buffer); 2140 2141 status_t err = freeBuffer(kPortIndexOutput, i); 2142 CHECK_EQ(err, (status_t)OK); 2143 2144#if 0 2145 } else if (mPortStatus[kPortIndexOutput] == ENABLED 2146 && (flags & OMX_BUFFERFLAG_EOS)) { 2147 CODEC_LOGV("No more output data."); 2148 mNoMoreOutputData = true; 2149 mBufferFilled.signal(); 2150#endif 2151 } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) { 2152 CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED); 2153 2154 if (info->mMediaBuffer == NULL) { 2155 CHECK(mOMXLivesLocally); 2156 CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts); 2157 CHECK(mQuirks & kDefersOutputBufferAllocation); 2158 2159 // The qcom video decoders on Nexus don't actually allocate 2160 // output buffer memory on a call to OMX_AllocateBuffer 2161 // the "pBuffer" member of the OMX_BUFFERHEADERTYPE 2162 // structure is only filled in later. 2163 2164 info->mMediaBuffer = new MediaBuffer( 2165 msg.u.extended_buffer_data.data_ptr, 2166 info->mSize); 2167 info->mMediaBuffer->setObserver(this); 2168 } 2169 2170 MediaBuffer *buffer = info->mMediaBuffer; 2171 bool isGraphicBuffer = buffer->graphicBuffer() != NULL; 2172 2173 if (!isGraphicBuffer 2174 && msg.u.extended_buffer_data.range_offset 2175 + msg.u.extended_buffer_data.range_length 2176 > buffer->size()) { 2177 CODEC_LOGE( 2178 "Codec lied about its buffer size requirements, " 2179 "sending a buffer larger than the originally " 2180 "advertised size in FILL_BUFFER_DONE!"); 2181 } 2182 buffer->set_range( 2183 msg.u.extended_buffer_data.range_offset, 2184 msg.u.extended_buffer_data.range_length); 2185 2186 buffer->meta_data()->clear(); 2187 2188 buffer->meta_data()->setInt64( 2189 kKeyTime, msg.u.extended_buffer_data.timestamp); 2190 2191 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) { 2192 buffer->meta_data()->setInt32(kKeyIsSyncFrame, true); 2193 } 2194 bool isCodecSpecific = false; 2195 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) { 2196 buffer->meta_data()->setInt32(kKeyIsCodecConfig, true); 2197 isCodecSpecific = true; 2198 } 2199 2200 if (isGraphicBuffer || mQuirks & kOutputBuffersAreUnreadable) { 2201 buffer->meta_data()->setInt32(kKeyIsUnreadable, true); 2202 } 2203 2204 buffer->meta_data()->setPointer( 2205 kKeyPlatformPrivate, 2206 msg.u.extended_buffer_data.platform_private); 2207 2208 buffer->meta_data()->setPointer( 2209 kKeyBufferID, 2210 msg.u.extended_buffer_data.buffer); 2211 2212 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) { 2213 CODEC_LOGV("No more output data."); 2214 mNoMoreOutputData = true; 2215 } 2216 2217 if (mIsEncoder && mIsVideo) { 2218 int64_t decodingTimeUs = isCodecSpecific? 0: getDecodingTimeUs(); 2219 buffer->meta_data()->setInt64(kKeyDecodingTime, decodingTimeUs); 2220 } 2221 2222 if (mTargetTimeUs >= 0) { 2223 CHECK(msg.u.extended_buffer_data.timestamp <= mTargetTimeUs); 2224 2225 if (msg.u.extended_buffer_data.timestamp < mTargetTimeUs) { 2226 CODEC_LOGV( 2227 "skipping output buffer at timestamp %lld us", 2228 msg.u.extended_buffer_data.timestamp); 2229 2230 fillOutputBuffer(info); 2231 break; 2232 } 2233 2234 CODEC_LOGV( 2235 "returning output buffer at target timestamp " 2236 "%lld us", 2237 msg.u.extended_buffer_data.timestamp); 2238 2239 mTargetTimeUs = -1; 2240 } 2241 2242 mFilledBuffers.push_back(i); 2243 mBufferFilled.signal(); 2244 if (mIsEncoder) { 2245 sched_yield(); 2246 } 2247 } 2248 2249 break; 2250 } 2251 2252 default: 2253 { 2254 CHECK(!"should not be here."); 2255 break; 2256 } 2257 } 2258} 2259 2260// Has the format changed in any way that the client would have to be aware of? 2261static bool formatHasNotablyChanged( 2262 const sp<MetaData> &from, const sp<MetaData> &to) { 2263 if (from.get() == NULL && to.get() == NULL) { 2264 return false; 2265 } 2266 2267 if ((from.get() == NULL && to.get() != NULL) 2268 || (from.get() != NULL && to.get() == NULL)) { 2269 return true; 2270 } 2271 2272 const char *mime_from, *mime_to; 2273 CHECK(from->findCString(kKeyMIMEType, &mime_from)); 2274 CHECK(to->findCString(kKeyMIMEType, &mime_to)); 2275 2276 if (strcasecmp(mime_from, mime_to)) { 2277 return true; 2278 } 2279 2280 if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) { 2281 int32_t colorFormat_from, colorFormat_to; 2282 CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from)); 2283 CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to)); 2284 2285 if (colorFormat_from != colorFormat_to) { 2286 return true; 2287 } 2288 2289 int32_t width_from, width_to; 2290 CHECK(from->findInt32(kKeyWidth, &width_from)); 2291 CHECK(to->findInt32(kKeyWidth, &width_to)); 2292 2293 if (width_from != width_to) { 2294 return true; 2295 } 2296 2297 int32_t height_from, height_to; 2298 CHECK(from->findInt32(kKeyHeight, &height_from)); 2299 CHECK(to->findInt32(kKeyHeight, &height_to)); 2300 2301 if (height_from != height_to) { 2302 return true; 2303 } 2304 2305 int32_t left_from, top_from, right_from, bottom_from; 2306 CHECK(from->findRect( 2307 kKeyCropRect, 2308 &left_from, &top_from, &right_from, &bottom_from)); 2309 2310 int32_t left_to, top_to, right_to, bottom_to; 2311 CHECK(to->findRect( 2312 kKeyCropRect, 2313 &left_to, &top_to, &right_to, &bottom_to)); 2314 2315 if (left_to != left_from || top_to != top_from 2316 || right_to != right_from || bottom_to != bottom_from) { 2317 return true; 2318 } 2319 } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) { 2320 int32_t numChannels_from, numChannels_to; 2321 CHECK(from->findInt32(kKeyChannelCount, &numChannels_from)); 2322 CHECK(to->findInt32(kKeyChannelCount, &numChannels_to)); 2323 2324 if (numChannels_from != numChannels_to) { 2325 return true; 2326 } 2327 2328 int32_t sampleRate_from, sampleRate_to; 2329 CHECK(from->findInt32(kKeySampleRate, &sampleRate_from)); 2330 CHECK(to->findInt32(kKeySampleRate, &sampleRate_to)); 2331 2332 if (sampleRate_from != sampleRate_to) { 2333 return true; 2334 } 2335 } 2336 2337 return false; 2338} 2339 2340void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) { 2341 switch (event) { 2342 case OMX_EventCmdComplete: 2343 { 2344 onCmdComplete((OMX_COMMANDTYPE)data1, data2); 2345 break; 2346 } 2347 2348 case OMX_EventError: 2349 { 2350 CODEC_LOGE("ERROR(0x%08lx, %ld)", data1, data2); 2351 2352 setState(ERROR); 2353 break; 2354 } 2355 2356 case OMX_EventPortSettingsChanged: 2357 { 2358 CODEC_LOGV("OMX_EventPortSettingsChanged(port=%ld, data2=0x%08lx)", 2359 data1, data2); 2360 2361 if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) { 2362 // There is no need to check whether mFilledBuffers is empty or not 2363 // when the OMX_EventPortSettingsChanged is not meant for reallocating 2364 // the output buffers. 2365 if (data1 == kPortIndexOutput) { 2366 CHECK(mFilledBuffers.empty()); 2367 } 2368 onPortSettingsChanged(data1); 2369 } else if (data1 == kPortIndexOutput && 2370 (data2 == OMX_IndexConfigCommonOutputCrop || 2371 data2 == OMX_IndexConfigCommonScale)) { 2372 2373 sp<MetaData> oldOutputFormat = mOutputFormat; 2374 initOutputFormat(mSource->getFormat()); 2375 2376 if (data2 == OMX_IndexConfigCommonOutputCrop && 2377 formatHasNotablyChanged(oldOutputFormat, mOutputFormat)) { 2378 mOutputPortSettingsHaveChanged = true; 2379 2380 } else if (data2 == OMX_IndexConfigCommonScale) { 2381 OMX_CONFIG_SCALEFACTORTYPE scale; 2382 InitOMXParams(&scale); 2383 scale.nPortIndex = kPortIndexOutput; 2384 2385 // Change display dimension only when necessary. 2386 if (OK == mOMX->getConfig( 2387 mNode, 2388 OMX_IndexConfigCommonScale, 2389 &scale, sizeof(scale))) { 2390 int32_t left, top, right, bottom; 2391 CHECK(mOutputFormat->findRect(kKeyCropRect, 2392 &left, &top, 2393 &right, &bottom)); 2394 2395 // The scale is in 16.16 format. 2396 // scale 1.0 = 0x010000. When there is no 2397 // need to change the display, skip it. 2398 ALOGV("Get OMX_IndexConfigScale: 0x%lx/0x%lx", 2399 scale.xWidth, scale.xHeight); 2400 2401 if (scale.xWidth != 0x010000) { 2402 mOutputFormat->setInt32(kKeyDisplayWidth, 2403 ((right - left + 1) * scale.xWidth) >> 16); 2404 mOutputPortSettingsHaveChanged = true; 2405 } 2406 2407 if (scale.xHeight != 0x010000) { 2408 mOutputFormat->setInt32(kKeyDisplayHeight, 2409 ((bottom - top + 1) * scale.xHeight) >> 16); 2410 mOutputPortSettingsHaveChanged = true; 2411 } 2412 } 2413 } 2414 } 2415 break; 2416 } 2417 2418#if 0 2419 case OMX_EventBufferFlag: 2420 { 2421 CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1); 2422 2423 if (data1 == kPortIndexOutput) { 2424 mNoMoreOutputData = true; 2425 } 2426 break; 2427 } 2428#endif 2429 2430 default: 2431 { 2432 CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2); 2433 break; 2434 } 2435 } 2436} 2437 2438void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) { 2439 switch (cmd) { 2440 case OMX_CommandStateSet: 2441 { 2442 onStateChange((OMX_STATETYPE)data); 2443 break; 2444 } 2445 2446 case OMX_CommandPortDisable: 2447 { 2448 OMX_U32 portIndex = data; 2449 CODEC_LOGV("PORT_DISABLED(%ld)", portIndex); 2450 2451 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2452 CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLING); 2453 CHECK_EQ(mPortBuffers[portIndex].size(), 0u); 2454 2455 mPortStatus[portIndex] = DISABLED; 2456 2457 if (mState == RECONFIGURING) { 2458 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2459 2460 sp<MetaData> oldOutputFormat = mOutputFormat; 2461 initOutputFormat(mSource->getFormat()); 2462 2463 // Don't notify clients if the output port settings change 2464 // wasn't of importance to them, i.e. it may be that just the 2465 // number of buffers has changed and nothing else. 2466 bool formatChanged = formatHasNotablyChanged(oldOutputFormat, mOutputFormat); 2467 if (!mOutputPortSettingsHaveChanged) { 2468 mOutputPortSettingsHaveChanged = formatChanged; 2469 } 2470 2471 status_t err = enablePortAsync(portIndex); 2472 if (err != OK) { 2473 CODEC_LOGE("enablePortAsync(%ld) failed (err = %d)", portIndex, err); 2474 setState(ERROR); 2475 } else { 2476 err = allocateBuffersOnPort(portIndex); 2477 if (err != OK) { 2478 CODEC_LOGE("allocateBuffersOnPort failed (err = %d)", err); 2479 setState(ERROR); 2480 } 2481 } 2482 } 2483 break; 2484 } 2485 2486 case OMX_CommandPortEnable: 2487 { 2488 OMX_U32 portIndex = data; 2489 CODEC_LOGV("PORT_ENABLED(%ld)", portIndex); 2490 2491 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2492 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLING); 2493 2494 mPortStatus[portIndex] = ENABLED; 2495 2496 if (mState == RECONFIGURING) { 2497 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2498 2499 setState(EXECUTING); 2500 2501 fillOutputBuffers(); 2502 } 2503 break; 2504 } 2505 2506 case OMX_CommandFlush: 2507 { 2508 OMX_U32 portIndex = data; 2509 2510 CODEC_LOGV("FLUSH_DONE(%ld)", portIndex); 2511 2512 CHECK_EQ((int)mPortStatus[portIndex], (int)SHUTTING_DOWN); 2513 mPortStatus[portIndex] = ENABLED; 2514 2515 CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]), 2516 mPortBuffers[portIndex].size()); 2517 2518 if (mSkipCutBuffer != NULL && mPortStatus[kPortIndexOutput] == ENABLED) { 2519 mSkipCutBuffer->clear(); 2520 } 2521 2522 if (mState == RECONFIGURING) { 2523 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2524 2525 disablePortAsync(portIndex); 2526 } else if (mState == EXECUTING_TO_IDLE) { 2527 if (mPortStatus[kPortIndexInput] == ENABLED 2528 && mPortStatus[kPortIndexOutput] == ENABLED) { 2529 CODEC_LOGV("Finished flushing both ports, now completing " 2530 "transition from EXECUTING to IDLE."); 2531 2532 mPortStatus[kPortIndexInput] = SHUTTING_DOWN; 2533 mPortStatus[kPortIndexOutput] = SHUTTING_DOWN; 2534 2535 status_t err = 2536 mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 2537 CHECK_EQ(err, (status_t)OK); 2538 } 2539 } else { 2540 // We're flushing both ports in preparation for seeking. 2541 2542 if (mPortStatus[kPortIndexInput] == ENABLED 2543 && mPortStatus[kPortIndexOutput] == ENABLED) { 2544 CODEC_LOGV("Finished flushing both ports, now continuing from" 2545 " seek-time."); 2546 2547 // We implicitly resume pulling on our upstream source. 2548 mPaused = false; 2549 2550 drainInputBuffers(); 2551 fillOutputBuffers(); 2552 } 2553 2554 if (mOutputPortSettingsChangedPending) { 2555 CODEC_LOGV( 2556 "Honoring deferred output port settings change."); 2557 2558 mOutputPortSettingsChangedPending = false; 2559 onPortSettingsChanged(kPortIndexOutput); 2560 } 2561 } 2562 2563 break; 2564 } 2565 2566 default: 2567 { 2568 CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data); 2569 break; 2570 } 2571 } 2572} 2573 2574void OMXCodec::onStateChange(OMX_STATETYPE newState) { 2575 CODEC_LOGV("onStateChange %d", newState); 2576 2577 switch (newState) { 2578 case OMX_StateIdle: 2579 { 2580 CODEC_LOGV("Now Idle."); 2581 if (mState == LOADED_TO_IDLE) { 2582 status_t err = mOMX->sendCommand( 2583 mNode, OMX_CommandStateSet, OMX_StateExecuting); 2584 2585 CHECK_EQ(err, (status_t)OK); 2586 2587 setState(IDLE_TO_EXECUTING); 2588 } else { 2589 CHECK_EQ((int)mState, (int)EXECUTING_TO_IDLE); 2590 2591 CHECK_EQ( 2592 countBuffersWeOwn(mPortBuffers[kPortIndexInput]), 2593 mPortBuffers[kPortIndexInput].size()); 2594 2595 CHECK_EQ( 2596 countBuffersWeOwn(mPortBuffers[kPortIndexOutput]), 2597 mPortBuffers[kPortIndexOutput].size()); 2598 2599 status_t err = mOMX->sendCommand( 2600 mNode, OMX_CommandStateSet, OMX_StateLoaded); 2601 2602 CHECK_EQ(err, (status_t)OK); 2603 2604 err = freeBuffersOnPort(kPortIndexInput); 2605 CHECK_EQ(err, (status_t)OK); 2606 2607 err = freeBuffersOnPort(kPortIndexOutput); 2608 CHECK_EQ(err, (status_t)OK); 2609 2610 mPortStatus[kPortIndexInput] = ENABLED; 2611 mPortStatus[kPortIndexOutput] = ENABLED; 2612 2613 if ((mFlags & kEnableGrallocUsageProtected) && 2614 mNativeWindow != NULL) { 2615 // We push enough 1x1 blank buffers to ensure that one of 2616 // them has made it to the display. This allows the OMX 2617 // component teardown to zero out any protected buffers 2618 // without the risk of scanning out one of those buffers. 2619 pushBlankBuffersToNativeWindow(); 2620 } 2621 2622 setState(IDLE_TO_LOADED); 2623 } 2624 break; 2625 } 2626 2627 case OMX_StateExecuting: 2628 { 2629 CHECK_EQ((int)mState, (int)IDLE_TO_EXECUTING); 2630 2631 CODEC_LOGV("Now Executing."); 2632 2633 mOutputPortSettingsChangedPending = false; 2634 2635 setState(EXECUTING); 2636 2637 // Buffers will be submitted to the component in the first 2638 // call to OMXCodec::read as mInitialBufferSubmit is true at 2639 // this point. This ensures that this on_message call returns, 2640 // releases the lock and ::init can notice the state change and 2641 // itself return. 2642 break; 2643 } 2644 2645 case OMX_StateLoaded: 2646 { 2647 CHECK_EQ((int)mState, (int)IDLE_TO_LOADED); 2648 2649 CODEC_LOGV("Now Loaded."); 2650 2651 setState(LOADED); 2652 break; 2653 } 2654 2655 case OMX_StateInvalid: 2656 { 2657 setState(ERROR); 2658 break; 2659 } 2660 2661 default: 2662 { 2663 CHECK(!"should not be here."); 2664 break; 2665 } 2666 } 2667} 2668 2669// static 2670size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) { 2671 size_t n = 0; 2672 for (size_t i = 0; i < buffers.size(); ++i) { 2673 if (buffers[i].mStatus != OWNED_BY_COMPONENT) { 2674 ++n; 2675 } 2676 } 2677 2678 return n; 2679} 2680 2681status_t OMXCodec::freeBuffersOnPort( 2682 OMX_U32 portIndex, bool onlyThoseWeOwn) { 2683 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 2684 2685 status_t stickyErr = OK; 2686 2687 for (size_t i = buffers->size(); i-- > 0;) { 2688 BufferInfo *info = &buffers->editItemAt(i); 2689 2690 if (onlyThoseWeOwn && info->mStatus == OWNED_BY_COMPONENT) { 2691 continue; 2692 } 2693 2694 CHECK(info->mStatus == OWNED_BY_US 2695 || info->mStatus == OWNED_BY_NATIVE_WINDOW); 2696 2697 CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex); 2698 2699 status_t err = freeBuffer(portIndex, i); 2700 2701 if (err != OK) { 2702 stickyErr = err; 2703 } 2704 2705 } 2706 2707 CHECK(onlyThoseWeOwn || buffers->isEmpty()); 2708 2709 return stickyErr; 2710} 2711 2712status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) { 2713 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 2714 2715 BufferInfo *info = &buffers->editItemAt(bufIndex); 2716 2717 status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer); 2718 2719 if (err == OK && info->mMediaBuffer != NULL) { 2720 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2721 info->mMediaBuffer->setObserver(NULL); 2722 2723 // Make sure nobody but us owns this buffer at this point. 2724 CHECK_EQ(info->mMediaBuffer->refcount(), 0); 2725 2726 // Cancel the buffer if it belongs to an ANativeWindow. 2727 sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer(); 2728 if (info->mStatus == OWNED_BY_US && graphicBuffer != 0) { 2729 err = cancelBufferToNativeWindow(info); 2730 } 2731 2732 info->mMediaBuffer->release(); 2733 info->mMediaBuffer = NULL; 2734 } 2735 2736 if (err == OK) { 2737 buffers->removeAt(bufIndex); 2738 } 2739 2740 return err; 2741} 2742 2743void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) { 2744 CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex); 2745 2746 CHECK_EQ((int)mState, (int)EXECUTING); 2747 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2748 CHECK(!mOutputPortSettingsChangedPending); 2749 2750 if (mPortStatus[kPortIndexOutput] != ENABLED) { 2751 CODEC_LOGV("Deferring output port settings change."); 2752 mOutputPortSettingsChangedPending = true; 2753 return; 2754 } 2755 2756 setState(RECONFIGURING); 2757 2758 if (mQuirks & kNeedsFlushBeforeDisable) { 2759 if (!flushPortAsync(portIndex)) { 2760 onCmdComplete(OMX_CommandFlush, portIndex); 2761 } 2762 } else { 2763 disablePortAsync(portIndex); 2764 } 2765} 2766 2767bool OMXCodec::flushPortAsync(OMX_U32 portIndex) { 2768 CHECK(mState == EXECUTING || mState == RECONFIGURING 2769 || mState == EXECUTING_TO_IDLE); 2770 2771 CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.", 2772 portIndex, countBuffersWeOwn(mPortBuffers[portIndex]), 2773 mPortBuffers[portIndex].size()); 2774 2775 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED); 2776 mPortStatus[portIndex] = SHUTTING_DOWN; 2777 2778 if ((mQuirks & kRequiresFlushCompleteEmulation) 2779 && countBuffersWeOwn(mPortBuffers[portIndex]) 2780 == mPortBuffers[portIndex].size()) { 2781 // No flush is necessary and this component fails to send a 2782 // flush-complete event in this case. 2783 2784 return false; 2785 } 2786 2787 status_t err = 2788 mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex); 2789 CHECK_EQ(err, (status_t)OK); 2790 2791 return true; 2792} 2793 2794void OMXCodec::disablePortAsync(OMX_U32 portIndex) { 2795 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2796 2797 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED); 2798 mPortStatus[portIndex] = DISABLING; 2799 2800 CODEC_LOGV("sending OMX_CommandPortDisable(%ld)", portIndex); 2801 status_t err = 2802 mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex); 2803 CHECK_EQ(err, (status_t)OK); 2804 2805 freeBuffersOnPort(portIndex, true); 2806} 2807 2808status_t OMXCodec::enablePortAsync(OMX_U32 portIndex) { 2809 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2810 2811 CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLED); 2812 mPortStatus[portIndex] = ENABLING; 2813 2814 CODEC_LOGV("sending OMX_CommandPortEnable(%ld)", portIndex); 2815 return mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex); 2816} 2817 2818void OMXCodec::fillOutputBuffers() { 2819 CHECK_EQ((int)mState, (int)EXECUTING); 2820 2821 // This is a workaround for some decoders not properly reporting 2822 // end-of-output-stream. If we own all input buffers and also own 2823 // all output buffers and we already signalled end-of-input-stream, 2824 // the end-of-output-stream is implied. 2825 if (mSignalledEOS 2826 && countBuffersWeOwn(mPortBuffers[kPortIndexInput]) 2827 == mPortBuffers[kPortIndexInput].size() 2828 && countBuffersWeOwn(mPortBuffers[kPortIndexOutput]) 2829 == mPortBuffers[kPortIndexOutput].size()) { 2830 mNoMoreOutputData = true; 2831 mBufferFilled.signal(); 2832 2833 return; 2834 } 2835 2836 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 2837 for (size_t i = 0; i < buffers->size(); ++i) { 2838 BufferInfo *info = &buffers->editItemAt(i); 2839 if (info->mStatus == OWNED_BY_US) { 2840 fillOutputBuffer(&buffers->editItemAt(i)); 2841 } 2842 } 2843} 2844 2845void OMXCodec::drainInputBuffers() { 2846 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2847 2848 if (mFlags & kUseSecureInputBuffers) { 2849 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 2850 for (size_t i = 0; i < buffers->size(); ++i) { 2851 if (!drainAnyInputBuffer() 2852 || (mFlags & kOnlySubmitOneInputBufferAtOneTime)) { 2853 break; 2854 } 2855 } 2856 } else { 2857 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 2858 for (size_t i = 0; i < buffers->size(); ++i) { 2859 BufferInfo *info = &buffers->editItemAt(i); 2860 2861 if (info->mStatus != OWNED_BY_US) { 2862 continue; 2863 } 2864 2865 if (!drainInputBuffer(info)) { 2866 break; 2867 } 2868 2869 if (mFlags & kOnlySubmitOneInputBufferAtOneTime) { 2870 break; 2871 } 2872 } 2873 } 2874} 2875 2876bool OMXCodec::drainAnyInputBuffer() { 2877 return drainInputBuffer((BufferInfo *)NULL); 2878} 2879 2880OMXCodec::BufferInfo *OMXCodec::findInputBufferByDataPointer(void *ptr) { 2881 Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput]; 2882 for (size_t i = 0; i < infos->size(); ++i) { 2883 BufferInfo *info = &infos->editItemAt(i); 2884 2885 if (info->mData == ptr) { 2886 CODEC_LOGV( 2887 "input buffer data ptr = %p, buffer_id = %p", 2888 ptr, 2889 info->mBuffer); 2890 2891 return info; 2892 } 2893 } 2894 2895 TRESPASS(); 2896} 2897 2898OMXCodec::BufferInfo *OMXCodec::findEmptyInputBuffer() { 2899 Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput]; 2900 for (size_t i = 0; i < infos->size(); ++i) { 2901 BufferInfo *info = &infos->editItemAt(i); 2902 2903 if (info->mStatus == OWNED_BY_US) { 2904 return info; 2905 } 2906 } 2907 2908 TRESPASS(); 2909} 2910 2911bool OMXCodec::drainInputBuffer(BufferInfo *info) { 2912 if (info != NULL) { 2913 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 2914 } 2915 2916 if (mSignalledEOS) { 2917 return false; 2918 } 2919 2920 if (mCodecSpecificDataIndex < mCodecSpecificData.size()) { 2921 CHECK(!(mFlags & kUseSecureInputBuffers)); 2922 2923 const CodecSpecificData *specific = 2924 mCodecSpecificData[mCodecSpecificDataIndex]; 2925 2926 size_t size = specific->mSize; 2927 2928 if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME) 2929 && !(mQuirks & kWantsNALFragments)) { 2930 static const uint8_t kNALStartCode[4] = 2931 { 0x00, 0x00, 0x00, 0x01 }; 2932 2933 CHECK(info->mSize >= specific->mSize + 4); 2934 2935 size += 4; 2936 2937 memcpy(info->mData, kNALStartCode, 4); 2938 memcpy((uint8_t *)info->mData + 4, 2939 specific->mData, specific->mSize); 2940 } else { 2941 CHECK(info->mSize >= specific->mSize); 2942 memcpy(info->mData, specific->mData, specific->mSize); 2943 } 2944 2945 mNoMoreOutputData = false; 2946 2947 CODEC_LOGV("calling emptyBuffer with codec specific data"); 2948 2949 status_t err = mOMX->emptyBuffer( 2950 mNode, info->mBuffer, 0, size, 2951 OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG, 2952 0); 2953 CHECK_EQ(err, (status_t)OK); 2954 2955 info->mStatus = OWNED_BY_COMPONENT; 2956 2957 ++mCodecSpecificDataIndex; 2958 return true; 2959 } 2960 2961 if (mPaused) { 2962 return false; 2963 } 2964 2965 status_t err; 2966 2967 bool signalEOS = false; 2968 int64_t timestampUs = 0; 2969 2970 size_t offset = 0; 2971 int32_t n = 0; 2972 2973 2974 for (;;) { 2975 MediaBuffer *srcBuffer; 2976 if (mSeekTimeUs >= 0) { 2977 if (mLeftOverBuffer) { 2978 mLeftOverBuffer->release(); 2979 mLeftOverBuffer = NULL; 2980 } 2981 2982 MediaSource::ReadOptions options; 2983 options.setSeekTo(mSeekTimeUs, mSeekMode); 2984 2985 mSeekTimeUs = -1; 2986 mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC; 2987 mBufferFilled.signal(); 2988 2989 err = mSource->read(&srcBuffer, &options); 2990 2991 if (err == OK) { 2992 int64_t targetTimeUs; 2993 if (srcBuffer->meta_data()->findInt64( 2994 kKeyTargetTime, &targetTimeUs) 2995 && targetTimeUs >= 0) { 2996 CODEC_LOGV("targetTimeUs = %lld us", targetTimeUs); 2997 mTargetTimeUs = targetTimeUs; 2998 } else { 2999 mTargetTimeUs = -1; 3000 } 3001 } 3002 } else if (mLeftOverBuffer) { 3003 srcBuffer = mLeftOverBuffer; 3004 mLeftOverBuffer = NULL; 3005 3006 err = OK; 3007 } else { 3008 err = mSource->read(&srcBuffer); 3009 } 3010 3011 if (err != OK) { 3012 signalEOS = true; 3013 mFinalStatus = err; 3014 mSignalledEOS = true; 3015 mBufferFilled.signal(); 3016 break; 3017 } 3018 3019 if (mFlags & kUseSecureInputBuffers) { 3020 info = findInputBufferByDataPointer(srcBuffer->data()); 3021 CHECK(info != NULL); 3022 } 3023 3024 size_t remainingBytes = info->mSize - offset; 3025 3026 if (srcBuffer->range_length() > remainingBytes) { 3027 if (offset == 0) { 3028 CODEC_LOGE( 3029 "Codec's input buffers are too small to accomodate " 3030 "buffer read from source (info->mSize = %d, srcLength = %d)", 3031 info->mSize, srcBuffer->range_length()); 3032 3033 srcBuffer->release(); 3034 srcBuffer = NULL; 3035 3036 setState(ERROR); 3037 return false; 3038 } 3039 3040 mLeftOverBuffer = srcBuffer; 3041 break; 3042 } 3043 3044 bool releaseBuffer = true; 3045 if (mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)) { 3046 CHECK(mOMXLivesLocally && offset == 0); 3047 3048 OMX_BUFFERHEADERTYPE *header = 3049 (OMX_BUFFERHEADERTYPE *)info->mBuffer; 3050 3051 CHECK(header->pBuffer == info->mData); 3052 3053 header->pBuffer = 3054 (OMX_U8 *)srcBuffer->data() + srcBuffer->range_offset(); 3055 3056 releaseBuffer = false; 3057 info->mMediaBuffer = srcBuffer; 3058 } else { 3059 if (mFlags & kStoreMetaDataInVideoBuffers) { 3060 releaseBuffer = false; 3061 info->mMediaBuffer = srcBuffer; 3062 } 3063 3064 if (mFlags & kUseSecureInputBuffers) { 3065 // Data in "info" is already provided at this time. 3066 3067 releaseBuffer = false; 3068 3069 CHECK(info->mMediaBuffer == NULL); 3070 info->mMediaBuffer = srcBuffer; 3071 } else { 3072 CHECK(srcBuffer->data() != NULL) ; 3073 memcpy((uint8_t *)info->mData + offset, 3074 (const uint8_t *)srcBuffer->data() 3075 + srcBuffer->range_offset(), 3076 srcBuffer->range_length()); 3077 } 3078 } 3079 3080 int64_t lastBufferTimeUs; 3081 CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs)); 3082 CHECK(lastBufferTimeUs >= 0); 3083 if (mIsEncoder && mIsVideo) { 3084 mDecodingTimeList.push_back(lastBufferTimeUs); 3085 } 3086 3087 if (offset == 0) { 3088 timestampUs = lastBufferTimeUs; 3089 } 3090 3091 offset += srcBuffer->range_length(); 3092 3093 if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_VORBIS, mMIME)) { 3094 CHECK(!(mQuirks & kSupportsMultipleFramesPerInputBuffer)); 3095 CHECK_GE(info->mSize, offset + sizeof(int32_t)); 3096 3097 int32_t numPageSamples; 3098 if (!srcBuffer->meta_data()->findInt32( 3099 kKeyValidSamples, &numPageSamples)) { 3100 numPageSamples = -1; 3101 } 3102 3103 memcpy((uint8_t *)info->mData + offset, 3104 &numPageSamples, 3105 sizeof(numPageSamples)); 3106 3107 offset += sizeof(numPageSamples); 3108 } 3109 3110 if (releaseBuffer) { 3111 srcBuffer->release(); 3112 srcBuffer = NULL; 3113 } 3114 3115 ++n; 3116 3117 if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) { 3118 break; 3119 } 3120 3121 int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs; 3122 3123 if (coalescedDurationUs > 250000ll) { 3124 // Don't coalesce more than 250ms worth of encoded data at once. 3125 break; 3126 } 3127 } 3128 3129 if (n > 1) { 3130 ALOGV("coalesced %d frames into one input buffer", n); 3131 } 3132 3133 OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME; 3134 3135 if (signalEOS) { 3136 flags |= OMX_BUFFERFLAG_EOS; 3137 } else { 3138 mNoMoreOutputData = false; 3139 } 3140 3141 CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), " 3142 "timestamp %lld us (%.2f secs)", 3143 info->mBuffer, offset, 3144 timestampUs, timestampUs / 1E6); 3145 3146 if (info == NULL) { 3147 CHECK(mFlags & kUseSecureInputBuffers); 3148 CHECK(signalEOS); 3149 3150 // This is fishy, there's still a MediaBuffer corresponding to this 3151 // info available to the source at this point even though we're going 3152 // to use it to signal EOS to the codec. 3153 info = findEmptyInputBuffer(); 3154 } 3155 3156 err = mOMX->emptyBuffer( 3157 mNode, info->mBuffer, 0, offset, 3158 flags, timestampUs); 3159 3160 if (err != OK) { 3161 setState(ERROR); 3162 return false; 3163 } 3164 3165 info->mStatus = OWNED_BY_COMPONENT; 3166 3167 return true; 3168} 3169 3170void OMXCodec::fillOutputBuffer(BufferInfo *info) { 3171 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 3172 3173 if (mNoMoreOutputData) { 3174 CODEC_LOGV("There is no more output data available, not " 3175 "calling fillOutputBuffer"); 3176 return; 3177 } 3178 3179 if (info->mMediaBuffer != NULL) { 3180 sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer(); 3181 if (graphicBuffer != 0) { 3182 // When using a native buffer we need to lock the buffer before 3183 // giving it to OMX. 3184 CODEC_LOGV("Calling lockBuffer on %p", info->mBuffer); 3185 int err = mNativeWindow->lockBuffer(mNativeWindow.get(), 3186 graphicBuffer.get()); 3187 if (err != 0) { 3188 CODEC_LOGE("lockBuffer failed w/ error 0x%08x", err); 3189 3190 setState(ERROR); 3191 return; 3192 } 3193 } 3194 } 3195 3196 CODEC_LOGV("Calling fillBuffer on buffer %p", info->mBuffer); 3197 status_t err = mOMX->fillBuffer(mNode, info->mBuffer); 3198 3199 if (err != OK) { 3200 CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err); 3201 3202 setState(ERROR); 3203 return; 3204 } 3205 3206 info->mStatus = OWNED_BY_COMPONENT; 3207} 3208 3209bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) { 3210 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 3211 for (size_t i = 0; i < buffers->size(); ++i) { 3212 if ((*buffers)[i].mBuffer == buffer) { 3213 return drainInputBuffer(&buffers->editItemAt(i)); 3214 } 3215 } 3216 3217 CHECK(!"should not be here."); 3218 3219 return false; 3220} 3221 3222void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) { 3223 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 3224 for (size_t i = 0; i < buffers->size(); ++i) { 3225 if ((*buffers)[i].mBuffer == buffer) { 3226 fillOutputBuffer(&buffers->editItemAt(i)); 3227 return; 3228 } 3229 } 3230 3231 CHECK(!"should not be here."); 3232} 3233 3234void OMXCodec::setState(State newState) { 3235 mState = newState; 3236 mAsyncCompletion.signal(); 3237 3238 // This may cause some spurious wakeups but is necessary to 3239 // unblock the reader if we enter ERROR state. 3240 mBufferFilled.signal(); 3241} 3242 3243status_t OMXCodec::waitForBufferFilled_l() { 3244 3245 if (mIsEncoder) { 3246 // For timelapse video recording, the timelapse video recording may 3247 // not send an input frame for a _long_ time. Do not use timeout 3248 // for video encoding. 3249 return mBufferFilled.wait(mLock); 3250 } 3251 status_t err = mBufferFilled.waitRelative(mLock, kBufferFilledEventTimeOutNs); 3252 if (err != OK) { 3253 CODEC_LOGE("Timed out waiting for output buffers: %d/%d", 3254 countBuffersWeOwn(mPortBuffers[kPortIndexInput]), 3255 countBuffersWeOwn(mPortBuffers[kPortIndexOutput])); 3256 } 3257 return err; 3258} 3259 3260void OMXCodec::setRawAudioFormat( 3261 OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) { 3262 3263 // port definition 3264 OMX_PARAM_PORTDEFINITIONTYPE def; 3265 InitOMXParams(&def); 3266 def.nPortIndex = portIndex; 3267 status_t err = mOMX->getParameter( 3268 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3269 CHECK_EQ(err, (status_t)OK); 3270 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM; 3271 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition, 3272 &def, sizeof(def)), (status_t)OK); 3273 3274 // pcm param 3275 OMX_AUDIO_PARAM_PCMMODETYPE pcmParams; 3276 InitOMXParams(&pcmParams); 3277 pcmParams.nPortIndex = portIndex; 3278 3279 err = mOMX->getParameter( 3280 mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams)); 3281 3282 CHECK_EQ(err, (status_t)OK); 3283 3284 pcmParams.nChannels = numChannels; 3285 pcmParams.eNumData = OMX_NumericalDataSigned; 3286 pcmParams.bInterleaved = OMX_TRUE; 3287 pcmParams.nBitPerSample = 16; 3288 pcmParams.nSamplingRate = sampleRate; 3289 pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear; 3290 3291 CHECK_EQ(getOMXChannelMapping( 3292 numChannels, pcmParams.eChannelMapping), (status_t)OK); 3293 3294 err = mOMX->setParameter( 3295 mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams)); 3296 3297 CHECK_EQ(err, (status_t)OK); 3298} 3299 3300static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) { 3301 if (isAMRWB) { 3302 if (bps <= 6600) { 3303 return OMX_AUDIO_AMRBandModeWB0; 3304 } else if (bps <= 8850) { 3305 return OMX_AUDIO_AMRBandModeWB1; 3306 } else if (bps <= 12650) { 3307 return OMX_AUDIO_AMRBandModeWB2; 3308 } else if (bps <= 14250) { 3309 return OMX_AUDIO_AMRBandModeWB3; 3310 } else if (bps <= 15850) { 3311 return OMX_AUDIO_AMRBandModeWB4; 3312 } else if (bps <= 18250) { 3313 return OMX_AUDIO_AMRBandModeWB5; 3314 } else if (bps <= 19850) { 3315 return OMX_AUDIO_AMRBandModeWB6; 3316 } else if (bps <= 23050) { 3317 return OMX_AUDIO_AMRBandModeWB7; 3318 } 3319 3320 // 23850 bps 3321 return OMX_AUDIO_AMRBandModeWB8; 3322 } else { // AMRNB 3323 if (bps <= 4750) { 3324 return OMX_AUDIO_AMRBandModeNB0; 3325 } else if (bps <= 5150) { 3326 return OMX_AUDIO_AMRBandModeNB1; 3327 } else if (bps <= 5900) { 3328 return OMX_AUDIO_AMRBandModeNB2; 3329 } else if (bps <= 6700) { 3330 return OMX_AUDIO_AMRBandModeNB3; 3331 } else if (bps <= 7400) { 3332 return OMX_AUDIO_AMRBandModeNB4; 3333 } else if (bps <= 7950) { 3334 return OMX_AUDIO_AMRBandModeNB5; 3335 } else if (bps <= 10200) { 3336 return OMX_AUDIO_AMRBandModeNB6; 3337 } 3338 3339 // 12200 bps 3340 return OMX_AUDIO_AMRBandModeNB7; 3341 } 3342} 3343 3344void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) { 3345 OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput; 3346 3347 OMX_AUDIO_PARAM_AMRTYPE def; 3348 InitOMXParams(&def); 3349 def.nPortIndex = portIndex; 3350 3351 status_t err = 3352 mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def)); 3353 3354 CHECK_EQ(err, (status_t)OK); 3355 3356 def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; 3357 3358 def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate); 3359 err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def)); 3360 CHECK_EQ(err, (status_t)OK); 3361 3362 //////////////////////// 3363 3364 if (mIsEncoder) { 3365 sp<MetaData> format = mSource->getFormat(); 3366 int32_t sampleRate; 3367 int32_t numChannels; 3368 CHECK(format->findInt32(kKeySampleRate, &sampleRate)); 3369 CHECK(format->findInt32(kKeyChannelCount, &numChannels)); 3370 3371 setRawAudioFormat(kPortIndexInput, sampleRate, numChannels); 3372 } 3373} 3374 3375status_t OMXCodec::setAACFormat( 3376 int32_t numChannels, int32_t sampleRate, int32_t bitRate, int32_t aacProfile, bool isADTS) { 3377 if (numChannels > 2) { 3378 ALOGW("Number of channels: (%d) \n", numChannels); 3379 } 3380 3381 if (mIsEncoder) { 3382 if (isADTS) { 3383 return -EINVAL; 3384 } 3385 3386 //////////////// input port //////////////////// 3387 setRawAudioFormat(kPortIndexInput, sampleRate, numChannels); 3388 3389 //////////////// output port //////////////////// 3390 // format 3391 OMX_AUDIO_PARAM_PORTFORMATTYPE format; 3392 InitOMXParams(&format); 3393 format.nPortIndex = kPortIndexOutput; 3394 format.nIndex = 0; 3395 status_t err = OMX_ErrorNone; 3396 while (OMX_ErrorNone == err) { 3397 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat, 3398 &format, sizeof(format)), (status_t)OK); 3399 if (format.eEncoding == OMX_AUDIO_CodingAAC) { 3400 break; 3401 } 3402 format.nIndex++; 3403 } 3404 CHECK_EQ((status_t)OK, err); 3405 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat, 3406 &format, sizeof(format)), (status_t)OK); 3407 3408 // port definition 3409 OMX_PARAM_PORTDEFINITIONTYPE def; 3410 InitOMXParams(&def); 3411 def.nPortIndex = kPortIndexOutput; 3412 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition, 3413 &def, sizeof(def)), (status_t)OK); 3414 def.format.audio.bFlagErrorConcealment = OMX_TRUE; 3415 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; 3416 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition, 3417 &def, sizeof(def)), (status_t)OK); 3418 3419 // profile 3420 OMX_AUDIO_PARAM_AACPROFILETYPE profile; 3421 InitOMXParams(&profile); 3422 profile.nPortIndex = kPortIndexOutput; 3423 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac, 3424 &profile, sizeof(profile)), (status_t)OK); 3425 profile.nChannels = numChannels; 3426 profile.eChannelMode = (numChannels == 1? 3427 OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo); 3428 profile.nSampleRate = sampleRate; 3429 profile.nBitRate = bitRate; 3430 profile.nAudioBandWidth = 0; 3431 profile.nFrameLength = 0; 3432 profile.nAACtools = OMX_AUDIO_AACToolAll; 3433 profile.nAACERtools = OMX_AUDIO_AACERNone; 3434 profile.eAACProfile = (OMX_AUDIO_AACPROFILETYPE) aacProfile; 3435 profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; 3436 err = mOMX->setParameter(mNode, OMX_IndexParamAudioAac, 3437 &profile, sizeof(profile)); 3438 3439 if (err != OK) { 3440 CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed " 3441 "(err = %d)", 3442 err); 3443 return err; 3444 } 3445 } else { 3446 OMX_AUDIO_PARAM_AACPROFILETYPE profile; 3447 InitOMXParams(&profile); 3448 profile.nPortIndex = kPortIndexInput; 3449 3450 status_t err = mOMX->getParameter( 3451 mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); 3452 CHECK_EQ(err, (status_t)OK); 3453 3454 profile.nChannels = numChannels; 3455 profile.nSampleRate = sampleRate; 3456 3457 profile.eAACStreamFormat = 3458 isADTS 3459 ? OMX_AUDIO_AACStreamFormatMP4ADTS 3460 : OMX_AUDIO_AACStreamFormatMP4FF; 3461 3462 err = mOMX->setParameter( 3463 mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); 3464 3465 if (err != OK) { 3466 CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed " 3467 "(err = %d)", 3468 err); 3469 return err; 3470 } 3471 } 3472 3473 return OK; 3474} 3475 3476void OMXCodec::setG711Format(int32_t numChannels) { 3477 CHECK(!mIsEncoder); 3478 setRawAudioFormat(kPortIndexInput, 8000, numChannels); 3479} 3480 3481void OMXCodec::setImageOutputFormat( 3482 OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) { 3483 CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height); 3484 3485#if 0 3486 OMX_INDEXTYPE index; 3487 status_t err = mOMX->get_extension_index( 3488 mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index); 3489 CHECK_EQ(err, (status_t)OK); 3490 3491 err = mOMX->set_config(mNode, index, &format, sizeof(format)); 3492 CHECK_EQ(err, (status_t)OK); 3493#endif 3494 3495 OMX_PARAM_PORTDEFINITIONTYPE def; 3496 InitOMXParams(&def); 3497 def.nPortIndex = kPortIndexOutput; 3498 3499 status_t err = mOMX->getParameter( 3500 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3501 CHECK_EQ(err, (status_t)OK); 3502 3503 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage); 3504 3505 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 3506 3507 CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingUnused); 3508 imageDef->eColorFormat = format; 3509 imageDef->nFrameWidth = width; 3510 imageDef->nFrameHeight = height; 3511 3512 switch (format) { 3513 case OMX_COLOR_FormatYUV420PackedPlanar: 3514 case OMX_COLOR_FormatYUV411Planar: 3515 { 3516 def.nBufferSize = (width * height * 3) / 2; 3517 break; 3518 } 3519 3520 case OMX_COLOR_FormatCbYCrY: 3521 { 3522 def.nBufferSize = width * height * 2; 3523 break; 3524 } 3525 3526 case OMX_COLOR_Format32bitARGB8888: 3527 { 3528 def.nBufferSize = width * height * 4; 3529 break; 3530 } 3531 3532 case OMX_COLOR_Format16bitARGB4444: 3533 case OMX_COLOR_Format16bitARGB1555: 3534 case OMX_COLOR_Format16bitRGB565: 3535 case OMX_COLOR_Format16bitBGR565: 3536 { 3537 def.nBufferSize = width * height * 2; 3538 break; 3539 } 3540 3541 default: 3542 CHECK(!"Should not be here. Unknown color format."); 3543 break; 3544 } 3545 3546 def.nBufferCountActual = def.nBufferCountMin; 3547 3548 err = mOMX->setParameter( 3549 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3550 CHECK_EQ(err, (status_t)OK); 3551} 3552 3553void OMXCodec::setJPEGInputFormat( 3554 OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) { 3555 OMX_PARAM_PORTDEFINITIONTYPE def; 3556 InitOMXParams(&def); 3557 def.nPortIndex = kPortIndexInput; 3558 3559 status_t err = mOMX->getParameter( 3560 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3561 CHECK_EQ(err, (status_t)OK); 3562 3563 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage); 3564 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 3565 3566 CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingJPEG); 3567 imageDef->nFrameWidth = width; 3568 imageDef->nFrameHeight = height; 3569 3570 def.nBufferSize = compressedSize; 3571 def.nBufferCountActual = def.nBufferCountMin; 3572 3573 err = mOMX->setParameter( 3574 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3575 CHECK_EQ(err, (status_t)OK); 3576} 3577 3578void OMXCodec::addCodecSpecificData(const void *data, size_t size) { 3579 CodecSpecificData *specific = 3580 (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1); 3581 3582 specific->mSize = size; 3583 memcpy(specific->mData, data, size); 3584 3585 mCodecSpecificData.push(specific); 3586} 3587 3588void OMXCodec::clearCodecSpecificData() { 3589 for (size_t i = 0; i < mCodecSpecificData.size(); ++i) { 3590 free(mCodecSpecificData.editItemAt(i)); 3591 } 3592 mCodecSpecificData.clear(); 3593 mCodecSpecificDataIndex = 0; 3594} 3595 3596status_t OMXCodec::start(MetaData *meta) { 3597 Mutex::Autolock autoLock(mLock); 3598 3599 if (mState != LOADED) { 3600 return UNKNOWN_ERROR; 3601 } 3602 3603 sp<MetaData> params = new MetaData; 3604 if (mQuirks & kWantsNALFragments) { 3605 params->setInt32(kKeyWantsNALFragments, true); 3606 } 3607 if (meta) { 3608 int64_t startTimeUs = 0; 3609 int64_t timeUs; 3610 if (meta->findInt64(kKeyTime, &timeUs)) { 3611 startTimeUs = timeUs; 3612 } 3613 params->setInt64(kKeyTime, startTimeUs); 3614 } 3615 status_t err = mSource->start(params.get()); 3616 3617 if (err != OK) { 3618 return err; 3619 } 3620 3621 mCodecSpecificDataIndex = 0; 3622 mInitialBufferSubmit = true; 3623 mSignalledEOS = false; 3624 mNoMoreOutputData = false; 3625 mOutputPortSettingsHaveChanged = false; 3626 mSeekTimeUs = -1; 3627 mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC; 3628 mTargetTimeUs = -1; 3629 mFilledBuffers.clear(); 3630 mPaused = false; 3631 3632 return init(); 3633} 3634 3635status_t OMXCodec::stop() { 3636 CODEC_LOGV("stop mState=%d", mState); 3637 3638 Mutex::Autolock autoLock(mLock); 3639 3640 while (isIntermediateState(mState)) { 3641 mAsyncCompletion.wait(mLock); 3642 } 3643 3644 bool isError = false; 3645 switch (mState) { 3646 case LOADED: 3647 break; 3648 3649 case ERROR: 3650 { 3651 OMX_STATETYPE state = OMX_StateInvalid; 3652 status_t err = mOMX->getState(mNode, &state); 3653 CHECK_EQ(err, (status_t)OK); 3654 3655 if (state != OMX_StateExecuting) { 3656 break; 3657 } 3658 // else fall through to the idling code 3659 isError = true; 3660 } 3661 3662 case EXECUTING: 3663 { 3664 setState(EXECUTING_TO_IDLE); 3665 3666 if (mQuirks & kRequiresFlushBeforeShutdown) { 3667 CODEC_LOGV("This component requires a flush before transitioning " 3668 "from EXECUTING to IDLE..."); 3669 3670 bool emulateInputFlushCompletion = 3671 !flushPortAsync(kPortIndexInput); 3672 3673 bool emulateOutputFlushCompletion = 3674 !flushPortAsync(kPortIndexOutput); 3675 3676 if (emulateInputFlushCompletion) { 3677 onCmdComplete(OMX_CommandFlush, kPortIndexInput); 3678 } 3679 3680 if (emulateOutputFlushCompletion) { 3681 onCmdComplete(OMX_CommandFlush, kPortIndexOutput); 3682 } 3683 } else { 3684 mPortStatus[kPortIndexInput] = SHUTTING_DOWN; 3685 mPortStatus[kPortIndexOutput] = SHUTTING_DOWN; 3686 3687 status_t err = 3688 mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 3689 CHECK_EQ(err, (status_t)OK); 3690 } 3691 3692 while (mState != LOADED && mState != ERROR) { 3693 mAsyncCompletion.wait(mLock); 3694 } 3695 3696 if (isError) { 3697 // We were in the ERROR state coming in, so restore that now 3698 // that we've idled the OMX component. 3699 setState(ERROR); 3700 } 3701 3702 break; 3703 } 3704 3705 default: 3706 { 3707 CHECK(!"should not be here."); 3708 break; 3709 } 3710 } 3711 3712 if (mLeftOverBuffer) { 3713 mLeftOverBuffer->release(); 3714 mLeftOverBuffer = NULL; 3715 } 3716 3717 mSource->stop(); 3718 3719 CODEC_LOGV("stopped in state %d", mState); 3720 3721 return OK; 3722} 3723 3724sp<MetaData> OMXCodec::getFormat() { 3725 Mutex::Autolock autoLock(mLock); 3726 3727 return mOutputFormat; 3728} 3729 3730status_t OMXCodec::read( 3731 MediaBuffer **buffer, const ReadOptions *options) { 3732 status_t err = OK; 3733 *buffer = NULL; 3734 3735 Mutex::Autolock autoLock(mLock); 3736 3737 if (mState != EXECUTING && mState != RECONFIGURING) { 3738 return UNKNOWN_ERROR; 3739 } 3740 3741 bool seeking = false; 3742 int64_t seekTimeUs; 3743 ReadOptions::SeekMode seekMode; 3744 if (options && options->getSeekTo(&seekTimeUs, &seekMode)) { 3745 seeking = true; 3746 } 3747 3748 if (mInitialBufferSubmit) { 3749 mInitialBufferSubmit = false; 3750 3751 if (seeking) { 3752 CHECK(seekTimeUs >= 0); 3753 mSeekTimeUs = seekTimeUs; 3754 mSeekMode = seekMode; 3755 3756 // There's no reason to trigger the code below, there's 3757 // nothing to flush yet. 3758 seeking = false; 3759 mPaused = false; 3760 } 3761 3762 drainInputBuffers(); 3763 3764 if (mState == EXECUTING) { 3765 // Otherwise mState == RECONFIGURING and this code will trigger 3766 // after the output port is reenabled. 3767 fillOutputBuffers(); 3768 } 3769 } 3770 3771 if (seeking) { 3772 while (mState == RECONFIGURING) { 3773 if ((err = waitForBufferFilled_l()) != OK) { 3774 return err; 3775 } 3776 } 3777 3778 if (mState != EXECUTING) { 3779 return UNKNOWN_ERROR; 3780 } 3781 3782 CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6); 3783 3784 mSignalledEOS = false; 3785 3786 CHECK(seekTimeUs >= 0); 3787 mSeekTimeUs = seekTimeUs; 3788 mSeekMode = seekMode; 3789 3790 mFilledBuffers.clear(); 3791 3792 CHECK_EQ((int)mState, (int)EXECUTING); 3793 3794 bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput); 3795 bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput); 3796 3797 if (emulateInputFlushCompletion) { 3798 onCmdComplete(OMX_CommandFlush, kPortIndexInput); 3799 } 3800 3801 if (emulateOutputFlushCompletion) { 3802 onCmdComplete(OMX_CommandFlush, kPortIndexOutput); 3803 } 3804 3805 while (mSeekTimeUs >= 0) { 3806 if ((err = waitForBufferFilled_l()) != OK) { 3807 return err; 3808 } 3809 } 3810 } 3811 3812 while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) { 3813 if ((err = waitForBufferFilled_l()) != OK) { 3814 return err; 3815 } 3816 } 3817 3818 if (mState == ERROR) { 3819 return UNKNOWN_ERROR; 3820 } 3821 3822 if (mFilledBuffers.empty()) { 3823 return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM; 3824 } 3825 3826 if (mOutputPortSettingsHaveChanged) { 3827 mOutputPortSettingsHaveChanged = false; 3828 3829 return INFO_FORMAT_CHANGED; 3830 } 3831 3832 size_t index = *mFilledBuffers.begin(); 3833 mFilledBuffers.erase(mFilledBuffers.begin()); 3834 3835 BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index); 3836 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 3837 info->mStatus = OWNED_BY_CLIENT; 3838 3839 info->mMediaBuffer->add_ref(); 3840 if (mSkipCutBuffer != NULL) { 3841 mSkipCutBuffer->submit(info->mMediaBuffer); 3842 } 3843 *buffer = info->mMediaBuffer; 3844 3845 return OK; 3846} 3847 3848void OMXCodec::signalBufferReturned(MediaBuffer *buffer) { 3849 Mutex::Autolock autoLock(mLock); 3850 3851 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 3852 for (size_t i = 0; i < buffers->size(); ++i) { 3853 BufferInfo *info = &buffers->editItemAt(i); 3854 3855 if (info->mMediaBuffer == buffer) { 3856 CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED); 3857 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_CLIENT); 3858 3859 info->mStatus = OWNED_BY_US; 3860 3861 if (buffer->graphicBuffer() == 0) { 3862 fillOutputBuffer(info); 3863 } else { 3864 sp<MetaData> metaData = info->mMediaBuffer->meta_data(); 3865 int32_t rendered = 0; 3866 if (!metaData->findInt32(kKeyRendered, &rendered)) { 3867 rendered = 0; 3868 } 3869 if (!rendered) { 3870 status_t err = cancelBufferToNativeWindow(info); 3871 if (err < 0) { 3872 return; 3873 } 3874 } 3875 3876 info->mStatus = OWNED_BY_NATIVE_WINDOW; 3877 3878 // Dequeue the next buffer from the native window. 3879 BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow(); 3880 if (nextBufInfo == 0) { 3881 return; 3882 } 3883 3884 // Give the buffer to the OMX node to fill. 3885 fillOutputBuffer(nextBufInfo); 3886 } 3887 return; 3888 } 3889 } 3890 3891 CHECK(!"should not be here."); 3892} 3893 3894static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) { 3895 static const char *kNames[] = { 3896 "OMX_IMAGE_CodingUnused", 3897 "OMX_IMAGE_CodingAutoDetect", 3898 "OMX_IMAGE_CodingJPEG", 3899 "OMX_IMAGE_CodingJPEG2K", 3900 "OMX_IMAGE_CodingEXIF", 3901 "OMX_IMAGE_CodingTIFF", 3902 "OMX_IMAGE_CodingGIF", 3903 "OMX_IMAGE_CodingPNG", 3904 "OMX_IMAGE_CodingLZW", 3905 "OMX_IMAGE_CodingBMP", 3906 }; 3907 3908 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3909 3910 if (type < 0 || (size_t)type >= numNames) { 3911 return "UNKNOWN"; 3912 } else { 3913 return kNames[type]; 3914 } 3915} 3916 3917static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) { 3918 static const char *kNames[] = { 3919 "OMX_COLOR_FormatUnused", 3920 "OMX_COLOR_FormatMonochrome", 3921 "OMX_COLOR_Format8bitRGB332", 3922 "OMX_COLOR_Format12bitRGB444", 3923 "OMX_COLOR_Format16bitARGB4444", 3924 "OMX_COLOR_Format16bitARGB1555", 3925 "OMX_COLOR_Format16bitRGB565", 3926 "OMX_COLOR_Format16bitBGR565", 3927 "OMX_COLOR_Format18bitRGB666", 3928 "OMX_COLOR_Format18bitARGB1665", 3929 "OMX_COLOR_Format19bitARGB1666", 3930 "OMX_COLOR_Format24bitRGB888", 3931 "OMX_COLOR_Format24bitBGR888", 3932 "OMX_COLOR_Format24bitARGB1887", 3933 "OMX_COLOR_Format25bitARGB1888", 3934 "OMX_COLOR_Format32bitBGRA8888", 3935 "OMX_COLOR_Format32bitARGB8888", 3936 "OMX_COLOR_FormatYUV411Planar", 3937 "OMX_COLOR_FormatYUV411PackedPlanar", 3938 "OMX_COLOR_FormatYUV420Planar", 3939 "OMX_COLOR_FormatYUV420PackedPlanar", 3940 "OMX_COLOR_FormatYUV420SemiPlanar", 3941 "OMX_COLOR_FormatYUV422Planar", 3942 "OMX_COLOR_FormatYUV422PackedPlanar", 3943 "OMX_COLOR_FormatYUV422SemiPlanar", 3944 "OMX_COLOR_FormatYCbYCr", 3945 "OMX_COLOR_FormatYCrYCb", 3946 "OMX_COLOR_FormatCbYCrY", 3947 "OMX_COLOR_FormatCrYCbY", 3948 "OMX_COLOR_FormatYUV444Interleaved", 3949 "OMX_COLOR_FormatRawBayer8bit", 3950 "OMX_COLOR_FormatRawBayer10bit", 3951 "OMX_COLOR_FormatRawBayer8bitcompressed", 3952 "OMX_COLOR_FormatL2", 3953 "OMX_COLOR_FormatL4", 3954 "OMX_COLOR_FormatL8", 3955 "OMX_COLOR_FormatL16", 3956 "OMX_COLOR_FormatL24", 3957 "OMX_COLOR_FormatL32", 3958 "OMX_COLOR_FormatYUV420PackedSemiPlanar", 3959 "OMX_COLOR_FormatYUV422PackedSemiPlanar", 3960 "OMX_COLOR_Format18BitBGR666", 3961 "OMX_COLOR_Format24BitARGB6666", 3962 "OMX_COLOR_Format24BitABGR6666", 3963 }; 3964 3965 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3966 3967 if (type == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar) { 3968 return "OMX_TI_COLOR_FormatYUV420PackedSemiPlanar"; 3969 } else if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) { 3970 return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar"; 3971 } else if (type < 0 || (size_t)type >= numNames) { 3972 return "UNKNOWN"; 3973 } else { 3974 return kNames[type]; 3975 } 3976} 3977 3978static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) { 3979 static const char *kNames[] = { 3980 "OMX_VIDEO_CodingUnused", 3981 "OMX_VIDEO_CodingAutoDetect", 3982 "OMX_VIDEO_CodingMPEG2", 3983 "OMX_VIDEO_CodingH263", 3984 "OMX_VIDEO_CodingMPEG4", 3985 "OMX_VIDEO_CodingWMV", 3986 "OMX_VIDEO_CodingRV", 3987 "OMX_VIDEO_CodingAVC", 3988 "OMX_VIDEO_CodingMJPEG", 3989 }; 3990 3991 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3992 3993 if (type < 0 || (size_t)type >= numNames) { 3994 return "UNKNOWN"; 3995 } else { 3996 return kNames[type]; 3997 } 3998} 3999 4000static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) { 4001 static const char *kNames[] = { 4002 "OMX_AUDIO_CodingUnused", 4003 "OMX_AUDIO_CodingAutoDetect", 4004 "OMX_AUDIO_CodingPCM", 4005 "OMX_AUDIO_CodingADPCM", 4006 "OMX_AUDIO_CodingAMR", 4007 "OMX_AUDIO_CodingGSMFR", 4008 "OMX_AUDIO_CodingGSMEFR", 4009 "OMX_AUDIO_CodingGSMHR", 4010 "OMX_AUDIO_CodingPDCFR", 4011 "OMX_AUDIO_CodingPDCEFR", 4012 "OMX_AUDIO_CodingPDCHR", 4013 "OMX_AUDIO_CodingTDMAFR", 4014 "OMX_AUDIO_CodingTDMAEFR", 4015 "OMX_AUDIO_CodingQCELP8", 4016 "OMX_AUDIO_CodingQCELP13", 4017 "OMX_AUDIO_CodingEVRC", 4018 "OMX_AUDIO_CodingSMV", 4019 "OMX_AUDIO_CodingG711", 4020 "OMX_AUDIO_CodingG723", 4021 "OMX_AUDIO_CodingG726", 4022 "OMX_AUDIO_CodingG729", 4023 "OMX_AUDIO_CodingAAC", 4024 "OMX_AUDIO_CodingMP3", 4025 "OMX_AUDIO_CodingSBC", 4026 "OMX_AUDIO_CodingVORBIS", 4027 "OMX_AUDIO_CodingWMA", 4028 "OMX_AUDIO_CodingRA", 4029 "OMX_AUDIO_CodingMIDI", 4030 }; 4031 4032 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 4033 4034 if (type < 0 || (size_t)type >= numNames) { 4035 return "UNKNOWN"; 4036 } else { 4037 return kNames[type]; 4038 } 4039} 4040 4041static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) { 4042 static const char *kNames[] = { 4043 "OMX_AUDIO_PCMModeLinear", 4044 "OMX_AUDIO_PCMModeALaw", 4045 "OMX_AUDIO_PCMModeMULaw", 4046 }; 4047 4048 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 4049 4050 if (type < 0 || (size_t)type >= numNames) { 4051 return "UNKNOWN"; 4052 } else { 4053 return kNames[type]; 4054 } 4055} 4056 4057static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) { 4058 static const char *kNames[] = { 4059 "OMX_AUDIO_AMRBandModeUnused", 4060 "OMX_AUDIO_AMRBandModeNB0", 4061 "OMX_AUDIO_AMRBandModeNB1", 4062 "OMX_AUDIO_AMRBandModeNB2", 4063 "OMX_AUDIO_AMRBandModeNB3", 4064 "OMX_AUDIO_AMRBandModeNB4", 4065 "OMX_AUDIO_AMRBandModeNB5", 4066 "OMX_AUDIO_AMRBandModeNB6", 4067 "OMX_AUDIO_AMRBandModeNB7", 4068 "OMX_AUDIO_AMRBandModeWB0", 4069 "OMX_AUDIO_AMRBandModeWB1", 4070 "OMX_AUDIO_AMRBandModeWB2", 4071 "OMX_AUDIO_AMRBandModeWB3", 4072 "OMX_AUDIO_AMRBandModeWB4", 4073 "OMX_AUDIO_AMRBandModeWB5", 4074 "OMX_AUDIO_AMRBandModeWB6", 4075 "OMX_AUDIO_AMRBandModeWB7", 4076 "OMX_AUDIO_AMRBandModeWB8", 4077 }; 4078 4079 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 4080 4081 if (type < 0 || (size_t)type >= numNames) { 4082 return "UNKNOWN"; 4083 } else { 4084 return kNames[type]; 4085 } 4086} 4087 4088static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) { 4089 static const char *kNames[] = { 4090 "OMX_AUDIO_AMRFrameFormatConformance", 4091 "OMX_AUDIO_AMRFrameFormatIF1", 4092 "OMX_AUDIO_AMRFrameFormatIF2", 4093 "OMX_AUDIO_AMRFrameFormatFSF", 4094 "OMX_AUDIO_AMRFrameFormatRTPPayload", 4095 "OMX_AUDIO_AMRFrameFormatITU", 4096 }; 4097 4098 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 4099 4100 if (type < 0 || (size_t)type >= numNames) { 4101 return "UNKNOWN"; 4102 } else { 4103 return kNames[type]; 4104 } 4105} 4106 4107void OMXCodec::dumpPortStatus(OMX_U32 portIndex) { 4108 OMX_PARAM_PORTDEFINITIONTYPE def; 4109 InitOMXParams(&def); 4110 def.nPortIndex = portIndex; 4111 4112 status_t err = mOMX->getParameter( 4113 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 4114 CHECK_EQ(err, (status_t)OK); 4115 4116 printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output"); 4117 4118 CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput) 4119 || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput)); 4120 4121 printf(" nBufferCountActual = %ld\n", def.nBufferCountActual); 4122 printf(" nBufferCountMin = %ld\n", def.nBufferCountMin); 4123 printf(" nBufferSize = %ld\n", def.nBufferSize); 4124 4125 switch (def.eDomain) { 4126 case OMX_PortDomainImage: 4127 { 4128 const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 4129 4130 printf("\n"); 4131 printf(" // Image\n"); 4132 printf(" nFrameWidth = %ld\n", imageDef->nFrameWidth); 4133 printf(" nFrameHeight = %ld\n", imageDef->nFrameHeight); 4134 printf(" nStride = %ld\n", imageDef->nStride); 4135 4136 printf(" eCompressionFormat = %s\n", 4137 imageCompressionFormatString(imageDef->eCompressionFormat)); 4138 4139 printf(" eColorFormat = %s\n", 4140 colorFormatString(imageDef->eColorFormat)); 4141 4142 break; 4143 } 4144 4145 case OMX_PortDomainVideo: 4146 { 4147 OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video; 4148 4149 printf("\n"); 4150 printf(" // Video\n"); 4151 printf(" nFrameWidth = %ld\n", videoDef->nFrameWidth); 4152 printf(" nFrameHeight = %ld\n", videoDef->nFrameHeight); 4153 printf(" nStride = %ld\n", videoDef->nStride); 4154 4155 printf(" eCompressionFormat = %s\n", 4156 videoCompressionFormatString(videoDef->eCompressionFormat)); 4157 4158 printf(" eColorFormat = %s\n", 4159 colorFormatString(videoDef->eColorFormat)); 4160 4161 break; 4162 } 4163 4164 case OMX_PortDomainAudio: 4165 { 4166 OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio; 4167 4168 printf("\n"); 4169 printf(" // Audio\n"); 4170 printf(" eEncoding = %s\n", 4171 audioCodingTypeString(audioDef->eEncoding)); 4172 4173 if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) { 4174 OMX_AUDIO_PARAM_PCMMODETYPE params; 4175 InitOMXParams(¶ms); 4176 params.nPortIndex = portIndex; 4177 4178 err = mOMX->getParameter( 4179 mNode, OMX_IndexParamAudioPcm, ¶ms, sizeof(params)); 4180 CHECK_EQ(err, (status_t)OK); 4181 4182 printf(" nSamplingRate = %ld\n", params.nSamplingRate); 4183 printf(" nChannels = %ld\n", params.nChannels); 4184 printf(" bInterleaved = %d\n", params.bInterleaved); 4185 printf(" nBitPerSample = %ld\n", params.nBitPerSample); 4186 4187 printf(" eNumData = %s\n", 4188 params.eNumData == OMX_NumericalDataSigned 4189 ? "signed" : "unsigned"); 4190 4191 printf(" ePCMMode = %s\n", audioPCMModeString(params.ePCMMode)); 4192 } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) { 4193 OMX_AUDIO_PARAM_AMRTYPE amr; 4194 InitOMXParams(&amr); 4195 amr.nPortIndex = portIndex; 4196 4197 err = mOMX->getParameter( 4198 mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr)); 4199 CHECK_EQ(err, (status_t)OK); 4200 4201 printf(" nChannels = %ld\n", amr.nChannels); 4202 printf(" eAMRBandMode = %s\n", 4203 amrBandModeString(amr.eAMRBandMode)); 4204 printf(" eAMRFrameFormat = %s\n", 4205 amrFrameFormatString(amr.eAMRFrameFormat)); 4206 } 4207 4208 break; 4209 } 4210 4211 default: 4212 { 4213 printf(" // Unknown\n"); 4214 break; 4215 } 4216 } 4217 4218 printf("}\n"); 4219} 4220 4221status_t OMXCodec::initNativeWindow() { 4222 // Enable use of a GraphicBuffer as the output for this node. This must 4223 // happen before getting the IndexParamPortDefinition parameter because it 4224 // will affect the pixel format that the node reports. 4225 status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE); 4226 if (err != 0) { 4227 return err; 4228 } 4229 4230 return OK; 4231} 4232 4233void OMXCodec::initNativeWindowCrop() { 4234 int32_t left, top, right, bottom; 4235 4236 CHECK(mOutputFormat->findRect( 4237 kKeyCropRect, 4238 &left, &top, &right, &bottom)); 4239 4240 android_native_rect_t crop; 4241 crop.left = left; 4242 crop.top = top; 4243 crop.right = right + 1; 4244 crop.bottom = bottom + 1; 4245 4246 // We'll ignore any errors here, if the surface is 4247 // already invalid, we'll know soon enough. 4248 native_window_set_crop(mNativeWindow.get(), &crop); 4249} 4250 4251void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) { 4252 mOutputFormat = new MetaData; 4253 mOutputFormat->setCString(kKeyDecoderComponent, mComponentName); 4254 if (mIsEncoder) { 4255 int32_t timeScale; 4256 if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) { 4257 mOutputFormat->setInt32(kKeyTimeScale, timeScale); 4258 } 4259 } 4260 4261 OMX_PARAM_PORTDEFINITIONTYPE def; 4262 InitOMXParams(&def); 4263 def.nPortIndex = kPortIndexOutput; 4264 4265 status_t err = mOMX->getParameter( 4266 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 4267 CHECK_EQ(err, (status_t)OK); 4268 4269 switch (def.eDomain) { 4270 case OMX_PortDomainImage: 4271 { 4272 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 4273 CHECK_EQ((int)imageDef->eCompressionFormat, 4274 (int)OMX_IMAGE_CodingUnused); 4275 4276 mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW); 4277 mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat); 4278 mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth); 4279 mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight); 4280 break; 4281 } 4282 4283 case OMX_PortDomainAudio: 4284 { 4285 OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio; 4286 4287 if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) { 4288 OMX_AUDIO_PARAM_PCMMODETYPE params; 4289 InitOMXParams(¶ms); 4290 params.nPortIndex = kPortIndexOutput; 4291 4292 err = mOMX->getParameter( 4293 mNode, OMX_IndexParamAudioPcm, ¶ms, sizeof(params)); 4294 CHECK_EQ(err, (status_t)OK); 4295 4296 CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned); 4297 CHECK_EQ(params.nBitPerSample, 16u); 4298 CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear); 4299 4300 int32_t numChannels, sampleRate; 4301 inputFormat->findInt32(kKeyChannelCount, &numChannels); 4302 inputFormat->findInt32(kKeySampleRate, &sampleRate); 4303 4304 if ((OMX_U32)numChannels != params.nChannels) { 4305 ALOGV("Codec outputs a different number of channels than " 4306 "the input stream contains (contains %d channels, " 4307 "codec outputs %ld channels).", 4308 numChannels, params.nChannels); 4309 } 4310 4311 if (sampleRate != (int32_t)params.nSamplingRate) { 4312 ALOGV("Codec outputs at different sampling rate than " 4313 "what the input stream contains (contains data at " 4314 "%d Hz, codec outputs %lu Hz)", 4315 sampleRate, params.nSamplingRate); 4316 } 4317 4318 mOutputFormat->setCString( 4319 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW); 4320 4321 // Use the codec-advertised number of channels, as some 4322 // codecs appear to output stereo even if the input data is 4323 // mono. If we know the codec lies about this information, 4324 // use the actual number of channels instead. 4325 mOutputFormat->setInt32( 4326 kKeyChannelCount, 4327 (mQuirks & kDecoderLiesAboutNumberOfChannels) 4328 ? numChannels : params.nChannels); 4329 4330 mOutputFormat->setInt32(kKeySampleRate, params.nSamplingRate); 4331 } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) { 4332 OMX_AUDIO_PARAM_AMRTYPE amr; 4333 InitOMXParams(&amr); 4334 amr.nPortIndex = kPortIndexOutput; 4335 4336 err = mOMX->getParameter( 4337 mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr)); 4338 CHECK_EQ(err, (status_t)OK); 4339 4340 CHECK_EQ(amr.nChannels, 1u); 4341 mOutputFormat->setInt32(kKeyChannelCount, 1); 4342 4343 if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0 4344 && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) { 4345 mOutputFormat->setCString( 4346 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB); 4347 mOutputFormat->setInt32(kKeySampleRate, 8000); 4348 } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0 4349 && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) { 4350 mOutputFormat->setCString( 4351 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB); 4352 mOutputFormat->setInt32(kKeySampleRate, 16000); 4353 } else { 4354 CHECK(!"Unknown AMR band mode."); 4355 } 4356 } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) { 4357 mOutputFormat->setCString( 4358 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC); 4359 int32_t numChannels, sampleRate, bitRate; 4360 inputFormat->findInt32(kKeyChannelCount, &numChannels); 4361 inputFormat->findInt32(kKeySampleRate, &sampleRate); 4362 inputFormat->findInt32(kKeyBitRate, &bitRate); 4363 mOutputFormat->setInt32(kKeyChannelCount, numChannels); 4364 mOutputFormat->setInt32(kKeySampleRate, sampleRate); 4365 mOutputFormat->setInt32(kKeyBitRate, bitRate); 4366 } else { 4367 CHECK(!"Should not be here. Unknown audio encoding."); 4368 } 4369 break; 4370 } 4371 4372 case OMX_PortDomainVideo: 4373 { 4374 OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video; 4375 4376 if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) { 4377 mOutputFormat->setCString( 4378 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW); 4379 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) { 4380 mOutputFormat->setCString( 4381 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4); 4382 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) { 4383 mOutputFormat->setCString( 4384 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263); 4385 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) { 4386 mOutputFormat->setCString( 4387 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC); 4388 } else { 4389 CHECK(!"Unknown compression format."); 4390 } 4391 4392 mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth); 4393 mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight); 4394 mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat); 4395 4396 if (!mIsEncoder) { 4397 OMX_CONFIG_RECTTYPE rect; 4398 InitOMXParams(&rect); 4399 rect.nPortIndex = kPortIndexOutput; 4400 status_t err = 4401 mOMX->getConfig( 4402 mNode, OMX_IndexConfigCommonOutputCrop, 4403 &rect, sizeof(rect)); 4404 4405 CODEC_LOGI( 4406 "video dimensions are %ld x %ld", 4407 video_def->nFrameWidth, video_def->nFrameHeight); 4408 4409 if (err == OK) { 4410 CHECK_GE(rect.nLeft, 0); 4411 CHECK_GE(rect.nTop, 0); 4412 CHECK_GE(rect.nWidth, 0u); 4413 CHECK_GE(rect.nHeight, 0u); 4414 CHECK_LE(rect.nLeft + rect.nWidth - 1, video_def->nFrameWidth); 4415 CHECK_LE(rect.nTop + rect.nHeight - 1, video_def->nFrameHeight); 4416 4417 mOutputFormat->setRect( 4418 kKeyCropRect, 4419 rect.nLeft, 4420 rect.nTop, 4421 rect.nLeft + rect.nWidth - 1, 4422 rect.nTop + rect.nHeight - 1); 4423 4424 CODEC_LOGI( 4425 "Crop rect is %ld x %ld @ (%ld, %ld)", 4426 rect.nWidth, rect.nHeight, rect.nLeft, rect.nTop); 4427 } else { 4428 mOutputFormat->setRect( 4429 kKeyCropRect, 4430 0, 0, 4431 video_def->nFrameWidth - 1, 4432 video_def->nFrameHeight - 1); 4433 } 4434 4435 if (mNativeWindow != NULL) { 4436 initNativeWindowCrop(); 4437 } 4438 } 4439 break; 4440 } 4441 4442 default: 4443 { 4444 CHECK(!"should not be here, neither audio nor video."); 4445 break; 4446 } 4447 } 4448 4449 // If the input format contains rotation information, flag the output 4450 // format accordingly. 4451 4452 int32_t rotationDegrees; 4453 if (mSource->getFormat()->findInt32(kKeyRotation, &rotationDegrees)) { 4454 mOutputFormat->setInt32(kKeyRotation, rotationDegrees); 4455 } 4456} 4457 4458status_t OMXCodec::pause() { 4459 Mutex::Autolock autoLock(mLock); 4460 4461 mPaused = true; 4462 4463 return OK; 4464} 4465 4466//////////////////////////////////////////////////////////////////////////////// 4467 4468status_t QueryCodecs( 4469 const sp<IOMX> &omx, 4470 const char *mime, bool queryDecoders, bool hwCodecOnly, 4471 Vector<CodecCapabilities> *results) { 4472 Vector<String8> matchingCodecs; 4473 results->clear(); 4474 4475 OMXCodec::findMatchingCodecs(mime, 4476 !queryDecoders /*createEncoder*/, 4477 NULL /*matchComponentName*/, 4478 hwCodecOnly ? OMXCodec::kHardwareCodecsOnly : 0 /*flags*/, 4479 &matchingCodecs); 4480 4481 for (size_t c = 0; c < matchingCodecs.size(); c++) { 4482 const char *componentName = matchingCodecs.itemAt(c).string(); 4483 4484 results->push(); 4485 CodecCapabilities *caps = &results->editItemAt(results->size() - 1); 4486 4487 status_t err = 4488 QueryCodec(omx, componentName, mime, !queryDecoders, caps); 4489 4490 if (err != OK) { 4491 results->removeAt(results->size() - 1); 4492 } 4493 } 4494 4495 return OK; 4496} 4497 4498status_t QueryCodec( 4499 const sp<IOMX> &omx, 4500 const char *componentName, const char *mime, 4501 bool isEncoder, 4502 CodecCapabilities *caps) { 4503 if (strncmp(componentName, "OMX.", 4)) { 4504 // Not an OpenMax component but a software codec. 4505 4506 caps->mComponentName = componentName; 4507 return OK; 4508 } 4509 4510 sp<OMXCodecObserver> observer = new OMXCodecObserver; 4511 IOMX::node_id node; 4512 status_t err = omx->allocateNode(componentName, observer, &node); 4513 4514 if (err != OK) { 4515 return err; 4516 } 4517 4518 OMXCodec::setComponentRole(omx, node, isEncoder, mime); 4519 4520 caps->mComponentName = componentName; 4521 4522 OMX_VIDEO_PARAM_PROFILELEVELTYPE param; 4523 InitOMXParams(¶m); 4524 4525 param.nPortIndex = !isEncoder ? 0 : 1; 4526 4527 for (param.nProfileIndex = 0;; ++param.nProfileIndex) { 4528 err = omx->getParameter( 4529 node, OMX_IndexParamVideoProfileLevelQuerySupported, 4530 ¶m, sizeof(param)); 4531 4532 if (err != OK) { 4533 break; 4534 } 4535 4536 CodecProfileLevel profileLevel; 4537 profileLevel.mProfile = param.eProfile; 4538 profileLevel.mLevel = param.eLevel; 4539 4540 caps->mProfileLevels.push(profileLevel); 4541 } 4542 4543 // Color format query 4544 OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat; 4545 InitOMXParams(&portFormat); 4546 portFormat.nPortIndex = !isEncoder ? 1 : 0; 4547 for (portFormat.nIndex = 0;; ++portFormat.nIndex) { 4548 err = omx->getParameter( 4549 node, OMX_IndexParamVideoPortFormat, 4550 &portFormat, sizeof(portFormat)); 4551 if (err != OK) { 4552 break; 4553 } 4554 caps->mColorFormats.push(portFormat.eColorFormat); 4555 } 4556 4557 CHECK_EQ(omx->freeNode(node), (status_t)OK); 4558 4559 return OK; 4560} 4561 4562status_t QueryCodecs( 4563 const sp<IOMX> &omx, 4564 const char *mimeType, bool queryDecoders, 4565 Vector<CodecCapabilities> *results) { 4566 return QueryCodecs(omx, mimeType, queryDecoders, false /*hwCodecOnly*/, results); 4567} 4568 4569void OMXCodec::restorePatchedDataPointer(BufferInfo *info) { 4570 CHECK(mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)); 4571 CHECK(mOMXLivesLocally); 4572 4573 OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)info->mBuffer; 4574 header->pBuffer = (OMX_U8 *)info->mData; 4575} 4576 4577// These are supposed be equivalent to the logic in 4578// "audio_channel_out_mask_from_count". 4579status_t getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]) { 4580 switch (numChannels) { 4581 case 1: 4582 map[0] = OMX_AUDIO_ChannelCF; 4583 break; 4584 case 2: 4585 map[0] = OMX_AUDIO_ChannelLF; 4586 map[1] = OMX_AUDIO_ChannelRF; 4587 break; 4588 case 3: 4589 map[0] = OMX_AUDIO_ChannelLF; 4590 map[1] = OMX_AUDIO_ChannelRF; 4591 map[2] = OMX_AUDIO_ChannelCF; 4592 break; 4593 case 4: 4594 map[0] = OMX_AUDIO_ChannelLF; 4595 map[1] = OMX_AUDIO_ChannelRF; 4596 map[2] = OMX_AUDIO_ChannelLR; 4597 map[3] = OMX_AUDIO_ChannelRR; 4598 break; 4599 case 5: 4600 map[0] = OMX_AUDIO_ChannelLF; 4601 map[1] = OMX_AUDIO_ChannelRF; 4602 map[2] = OMX_AUDIO_ChannelCF; 4603 map[3] = OMX_AUDIO_ChannelLR; 4604 map[4] = OMX_AUDIO_ChannelRR; 4605 break; 4606 case 6: 4607 map[0] = OMX_AUDIO_ChannelLF; 4608 map[1] = OMX_AUDIO_ChannelRF; 4609 map[2] = OMX_AUDIO_ChannelCF; 4610 map[3] = OMX_AUDIO_ChannelLFE; 4611 map[4] = OMX_AUDIO_ChannelLR; 4612 map[5] = OMX_AUDIO_ChannelRR; 4613 break; 4614 case 7: 4615 map[0] = OMX_AUDIO_ChannelLF; 4616 map[1] = OMX_AUDIO_ChannelRF; 4617 map[2] = OMX_AUDIO_ChannelCF; 4618 map[3] = OMX_AUDIO_ChannelLFE; 4619 map[4] = OMX_AUDIO_ChannelLR; 4620 map[5] = OMX_AUDIO_ChannelRR; 4621 map[6] = OMX_AUDIO_ChannelCS; 4622 break; 4623 case 8: 4624 map[0] = OMX_AUDIO_ChannelLF; 4625 map[1] = OMX_AUDIO_ChannelRF; 4626 map[2] = OMX_AUDIO_ChannelCF; 4627 map[3] = OMX_AUDIO_ChannelLFE; 4628 map[4] = OMX_AUDIO_ChannelLR; 4629 map[5] = OMX_AUDIO_ChannelRR; 4630 map[6] = OMX_AUDIO_ChannelLS; 4631 map[7] = OMX_AUDIO_ChannelRS; 4632 break; 4633 default: 4634 return -EINVAL; 4635 } 4636 4637 return OK; 4638} 4639 4640} // namespace android 4641