OMXCodec.cpp revision 4f6eed0d1c7972a983c075bdcf03089569e13fe1
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 // FIXME: 1127 // Remove the workaround after the work in done. 1128 if (!strncmp(mComponentName, "OMX.TI.DUCATI1", 14)) { 1129 h264type.eProfile = OMX_VIDEO_AVCProfileBaseline; 1130 } 1131 1132 if (h264type.eProfile == OMX_VIDEO_AVCProfileBaseline) { 1133 h264type.nSliceHeaderSpacing = 0; 1134 h264type.bUseHadamard = OMX_TRUE; 1135 h264type.nRefFrames = 1; 1136 h264type.nBFrames = 0; 1137 h264type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate); 1138 if (h264type.nPFrames == 0) { 1139 h264type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI; 1140 } 1141 h264type.nRefIdx10ActiveMinus1 = 0; 1142 h264type.nRefIdx11ActiveMinus1 = 0; 1143 h264type.bEntropyCodingCABAC = OMX_FALSE; 1144 h264type.bWeightedPPrediction = OMX_FALSE; 1145 h264type.bconstIpred = OMX_FALSE; 1146 h264type.bDirect8x8Inference = OMX_FALSE; 1147 h264type.bDirectSpatialTemporal = OMX_FALSE; 1148 h264type.nCabacInitIdc = 0; 1149 } 1150 1151 if (h264type.nBFrames != 0) { 1152 h264type.nAllowedPictureTypes |= OMX_VIDEO_PictureTypeB; 1153 } 1154 1155 h264type.bEnableUEP = OMX_FALSE; 1156 h264type.bEnableFMO = OMX_FALSE; 1157 h264type.bEnableASO = OMX_FALSE; 1158 h264type.bEnableRS = OMX_FALSE; 1159 h264type.bFrameMBsOnly = OMX_TRUE; 1160 h264type.bMBAFF = OMX_FALSE; 1161 h264type.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable; 1162 1163 if (!strcasecmp("OMX.Nvidia.h264.encoder", mComponentName)) { 1164 h264type.eLevel = OMX_VIDEO_AVCLevelMax; 1165 } 1166 1167 err = mOMX->setParameter( 1168 mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type)); 1169 CHECK_EQ(err, (status_t)OK); 1170 1171 CHECK_EQ(setupBitRate(bitRate), (status_t)OK); 1172 1173 return OK; 1174} 1175 1176status_t OMXCodec::setVideoOutputFormat( 1177 const char *mime, OMX_U32 width, OMX_U32 height) { 1178 CODEC_LOGV("setVideoOutputFormat width=%ld, height=%ld", width, height); 1179 1180 OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused; 1181 if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) { 1182 compressionFormat = OMX_VIDEO_CodingAVC; 1183 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) { 1184 compressionFormat = OMX_VIDEO_CodingMPEG4; 1185 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) { 1186 compressionFormat = OMX_VIDEO_CodingH263; 1187 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_VPX, mime)) { 1188 compressionFormat = OMX_VIDEO_CodingVPX; 1189 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG2, mime)) { 1190 compressionFormat = OMX_VIDEO_CodingMPEG2; 1191 } else { 1192 ALOGE("Not a supported video mime type: %s", mime); 1193 CHECK(!"Should not be here. Not a supported video mime type."); 1194 } 1195 1196 status_t err = setVideoPortFormatType( 1197 kPortIndexInput, compressionFormat, OMX_COLOR_FormatUnused); 1198 1199 if (err != OK) { 1200 return err; 1201 } 1202 1203#if 1 1204 { 1205 OMX_VIDEO_PARAM_PORTFORMATTYPE format; 1206 InitOMXParams(&format); 1207 format.nPortIndex = kPortIndexOutput; 1208 format.nIndex = 0; 1209 1210 status_t err = mOMX->getParameter( 1211 mNode, OMX_IndexParamVideoPortFormat, 1212 &format, sizeof(format)); 1213 CHECK_EQ(err, (status_t)OK); 1214 CHECK_EQ((int)format.eCompressionFormat, (int)OMX_VIDEO_CodingUnused); 1215 1216 CHECK(format.eColorFormat == OMX_COLOR_FormatYUV420Planar 1217 || format.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar 1218 || format.eColorFormat == OMX_COLOR_FormatCbYCrY 1219 || format.eColorFormat == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar 1220 || format.eColorFormat == OMX_QCOM_COLOR_FormatYVU420SemiPlanar); 1221 1222 err = mOMX->setParameter( 1223 mNode, OMX_IndexParamVideoPortFormat, 1224 &format, sizeof(format)); 1225 1226 if (err != OK) { 1227 return err; 1228 } 1229 } 1230#endif 1231 1232 OMX_PARAM_PORTDEFINITIONTYPE def; 1233 InitOMXParams(&def); 1234 def.nPortIndex = kPortIndexInput; 1235 1236 OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video; 1237 1238 err = mOMX->getParameter( 1239 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1240 1241 CHECK_EQ(err, (status_t)OK); 1242 1243#if 1 1244 // XXX Need a (much) better heuristic to compute input buffer sizes. 1245 const size_t X = 64 * 1024; 1246 if (def.nBufferSize < X) { 1247 def.nBufferSize = X; 1248 } 1249#endif 1250 1251 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo); 1252 1253 video_def->nFrameWidth = width; 1254 video_def->nFrameHeight = height; 1255 1256 video_def->eCompressionFormat = compressionFormat; 1257 video_def->eColorFormat = OMX_COLOR_FormatUnused; 1258 1259 err = mOMX->setParameter( 1260 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1261 1262 if (err != OK) { 1263 return err; 1264 } 1265 1266 //////////////////////////////////////////////////////////////////////////// 1267 1268 InitOMXParams(&def); 1269 def.nPortIndex = kPortIndexOutput; 1270 1271 err = mOMX->getParameter( 1272 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1273 CHECK_EQ(err, (status_t)OK); 1274 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo); 1275 1276#if 0 1277 def.nBufferSize = 1278 (((width + 15) & -16) * ((height + 15) & -16) * 3) / 2; // YUV420 1279#endif 1280 1281 video_def->nFrameWidth = width; 1282 video_def->nFrameHeight = height; 1283 1284 err = mOMX->setParameter( 1285 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1286 1287 return err; 1288} 1289 1290OMXCodec::OMXCodec( 1291 const sp<IOMX> &omx, IOMX::node_id node, 1292 uint32_t quirks, uint32_t flags, 1293 bool isEncoder, 1294 const char *mime, 1295 const char *componentName, 1296 const sp<MediaSource> &source, 1297 const sp<ANativeWindow> &nativeWindow) 1298 : mOMX(omx), 1299 mOMXLivesLocally(omx->livesLocally(node, getpid())), 1300 mNode(node), 1301 mQuirks(quirks), 1302 mFlags(flags), 1303 mIsEncoder(isEncoder), 1304 mIsVideo(!strncasecmp("video/", mime, 6)), 1305 mMIME(strdup(mime)), 1306 mComponentName(strdup(componentName)), 1307 mSource(source), 1308 mCodecSpecificDataIndex(0), 1309 mState(LOADED), 1310 mInitialBufferSubmit(true), 1311 mSignalledEOS(false), 1312 mNoMoreOutputData(false), 1313 mOutputPortSettingsHaveChanged(false), 1314 mSeekTimeUs(-1), 1315 mSeekMode(ReadOptions::SEEK_CLOSEST_SYNC), 1316 mTargetTimeUs(-1), 1317 mOutputPortSettingsChangedPending(false), 1318 mSkipCutBuffer(NULL), 1319 mLeftOverBuffer(NULL), 1320 mPaused(false), 1321 mNativeWindow( 1322 (!strncmp(componentName, "OMX.google.", 11) 1323 || !strcmp(componentName, "OMX.Nvidia.mpeg2v.decode")) 1324 ? NULL : nativeWindow) { 1325 mPortStatus[kPortIndexInput] = ENABLED; 1326 mPortStatus[kPortIndexOutput] = ENABLED; 1327 1328 setComponentRole(); 1329} 1330 1331// static 1332void OMXCodec::setComponentRole( 1333 const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder, 1334 const char *mime) { 1335 struct MimeToRole { 1336 const char *mime; 1337 const char *decoderRole; 1338 const char *encoderRole; 1339 }; 1340 1341 static const MimeToRole kMimeToRole[] = { 1342 { MEDIA_MIMETYPE_AUDIO_MPEG, 1343 "audio_decoder.mp3", "audio_encoder.mp3" }, 1344 { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I, 1345 "audio_decoder.mp1", "audio_encoder.mp1" }, 1346 { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II, 1347 "audio_decoder.mp2", "audio_encoder.mp2" }, 1348 { MEDIA_MIMETYPE_AUDIO_AMR_NB, 1349 "audio_decoder.amrnb", "audio_encoder.amrnb" }, 1350 { MEDIA_MIMETYPE_AUDIO_AMR_WB, 1351 "audio_decoder.amrwb", "audio_encoder.amrwb" }, 1352 { MEDIA_MIMETYPE_AUDIO_AAC, 1353 "audio_decoder.aac", "audio_encoder.aac" }, 1354 { MEDIA_MIMETYPE_AUDIO_VORBIS, 1355 "audio_decoder.vorbis", "audio_encoder.vorbis" }, 1356 { MEDIA_MIMETYPE_AUDIO_G711_MLAW, 1357 "audio_decoder.g711mlaw", "audio_encoder.g711mlaw" }, 1358 { MEDIA_MIMETYPE_AUDIO_G711_ALAW, 1359 "audio_decoder.g711alaw", "audio_encoder.g711alaw" }, 1360 { MEDIA_MIMETYPE_VIDEO_AVC, 1361 "video_decoder.avc", "video_encoder.avc" }, 1362 { MEDIA_MIMETYPE_VIDEO_MPEG4, 1363 "video_decoder.mpeg4", "video_encoder.mpeg4" }, 1364 { MEDIA_MIMETYPE_VIDEO_H263, 1365 "video_decoder.h263", "video_encoder.h263" }, 1366 { MEDIA_MIMETYPE_VIDEO_VPX, 1367 "video_decoder.vpx", "video_encoder.vpx" }, 1368 { MEDIA_MIMETYPE_AUDIO_RAW, 1369 "audio_decoder.raw", "audio_encoder.raw" }, 1370 }; 1371 1372 static const size_t kNumMimeToRole = 1373 sizeof(kMimeToRole) / sizeof(kMimeToRole[0]); 1374 1375 size_t i; 1376 for (i = 0; i < kNumMimeToRole; ++i) { 1377 if (!strcasecmp(mime, kMimeToRole[i].mime)) { 1378 break; 1379 } 1380 } 1381 1382 if (i == kNumMimeToRole) { 1383 return; 1384 } 1385 1386 const char *role = 1387 isEncoder ? kMimeToRole[i].encoderRole 1388 : kMimeToRole[i].decoderRole; 1389 1390 if (role != NULL) { 1391 OMX_PARAM_COMPONENTROLETYPE roleParams; 1392 InitOMXParams(&roleParams); 1393 1394 strncpy((char *)roleParams.cRole, 1395 role, OMX_MAX_STRINGNAME_SIZE - 1); 1396 1397 roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0'; 1398 1399 status_t err = omx->setParameter( 1400 node, OMX_IndexParamStandardComponentRole, 1401 &roleParams, sizeof(roleParams)); 1402 1403 if (err != OK) { 1404 ALOGW("Failed to set standard component role '%s'.", role); 1405 } 1406 } 1407} 1408 1409void OMXCodec::setComponentRole() { 1410 setComponentRole(mOMX, mNode, mIsEncoder, mMIME); 1411} 1412 1413OMXCodec::~OMXCodec() { 1414 mSource.clear(); 1415 1416 CHECK(mState == LOADED || mState == ERROR || mState == LOADED_TO_IDLE); 1417 1418 status_t err = mOMX->freeNode(mNode); 1419 CHECK_EQ(err, (status_t)OK); 1420 1421 mNode = NULL; 1422 setState(DEAD); 1423 1424 clearCodecSpecificData(); 1425 1426 free(mComponentName); 1427 mComponentName = NULL; 1428 1429 free(mMIME); 1430 mMIME = NULL; 1431} 1432 1433status_t OMXCodec::init() { 1434 // mLock is held. 1435 1436 CHECK_EQ((int)mState, (int)LOADED); 1437 1438 status_t err; 1439 if (!(mQuirks & kRequiresLoadedToIdleAfterAllocation)) { 1440 err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 1441 CHECK_EQ(err, (status_t)OK); 1442 setState(LOADED_TO_IDLE); 1443 } 1444 1445 err = allocateBuffers(); 1446 if (err != (status_t)OK) { 1447 return err; 1448 } 1449 1450 if (mQuirks & kRequiresLoadedToIdleAfterAllocation) { 1451 err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 1452 CHECK_EQ(err, (status_t)OK); 1453 1454 setState(LOADED_TO_IDLE); 1455 } 1456 1457 while (mState != EXECUTING && mState != ERROR) { 1458 mAsyncCompletion.wait(mLock); 1459 } 1460 1461 return mState == ERROR ? UNKNOWN_ERROR : OK; 1462} 1463 1464// static 1465bool OMXCodec::isIntermediateState(State state) { 1466 return state == LOADED_TO_IDLE 1467 || state == IDLE_TO_EXECUTING 1468 || state == EXECUTING_TO_IDLE 1469 || state == IDLE_TO_LOADED 1470 || state == RECONFIGURING; 1471} 1472 1473status_t OMXCodec::allocateBuffers() { 1474 status_t err = allocateBuffersOnPort(kPortIndexInput); 1475 1476 if (err != OK) { 1477 return err; 1478 } 1479 1480 return allocateBuffersOnPort(kPortIndexOutput); 1481} 1482 1483status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) { 1484 if (mNativeWindow != NULL && portIndex == kPortIndexOutput) { 1485 return allocateOutputBuffersFromNativeWindow(); 1486 } 1487 1488 if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) { 1489 ALOGE("protected output buffers must be stent to an ANativeWindow"); 1490 return PERMISSION_DENIED; 1491 } 1492 1493 status_t err = OK; 1494 if ((mFlags & kStoreMetaDataInVideoBuffers) 1495 && portIndex == kPortIndexInput) { 1496 err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE); 1497 if (err != OK) { 1498 ALOGE("Storing meta data in video buffers is not supported"); 1499 return err; 1500 } 1501 } 1502 1503 OMX_PARAM_PORTDEFINITIONTYPE def; 1504 InitOMXParams(&def); 1505 def.nPortIndex = portIndex; 1506 1507 err = mOMX->getParameter( 1508 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1509 1510 if (err != OK) { 1511 return err; 1512 } 1513 1514 CODEC_LOGV("allocating %lu buffers of size %lu on %s port", 1515 def.nBufferCountActual, def.nBufferSize, 1516 portIndex == kPortIndexInput ? "input" : "output"); 1517 1518 size_t totalSize = def.nBufferCountActual * def.nBufferSize; 1519 mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec"); 1520 1521 for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) { 1522 sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize); 1523 CHECK(mem.get() != NULL); 1524 1525 BufferInfo info; 1526 info.mData = NULL; 1527 info.mSize = def.nBufferSize; 1528 1529 IOMX::buffer_id buffer; 1530 if (portIndex == kPortIndexInput 1531 && ((mQuirks & kRequiresAllocateBufferOnInputPorts) 1532 || (mFlags & kUseSecureInputBuffers))) { 1533 if (mOMXLivesLocally) { 1534 mem.clear(); 1535 1536 err = mOMX->allocateBuffer( 1537 mNode, portIndex, def.nBufferSize, &buffer, 1538 &info.mData); 1539 } else { 1540 err = mOMX->allocateBufferWithBackup( 1541 mNode, portIndex, mem, &buffer); 1542 } 1543 } else if (portIndex == kPortIndexOutput 1544 && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) { 1545 if (mOMXLivesLocally) { 1546 mem.clear(); 1547 1548 err = mOMX->allocateBuffer( 1549 mNode, portIndex, def.nBufferSize, &buffer, 1550 &info.mData); 1551 } else { 1552 err = mOMX->allocateBufferWithBackup( 1553 mNode, portIndex, mem, &buffer); 1554 } 1555 } else { 1556 err = mOMX->useBuffer(mNode, portIndex, mem, &buffer); 1557 } 1558 1559 if (err != OK) { 1560 ALOGE("allocate_buffer_with_backup failed"); 1561 return err; 1562 } 1563 1564 if (mem != NULL) { 1565 info.mData = mem->pointer(); 1566 } 1567 1568 info.mBuffer = buffer; 1569 info.mStatus = OWNED_BY_US; 1570 info.mMem = mem; 1571 info.mMediaBuffer = NULL; 1572 1573 if (portIndex == kPortIndexOutput) { 1574 if (!(mOMXLivesLocally 1575 && (mQuirks & kRequiresAllocateBufferOnOutputPorts) 1576 && (mQuirks & kDefersOutputBufferAllocation))) { 1577 // If the node does not fill in the buffer ptr at this time, 1578 // we will defer creating the MediaBuffer until receiving 1579 // the first FILL_BUFFER_DONE notification instead. 1580 info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize); 1581 info.mMediaBuffer->setObserver(this); 1582 } 1583 } 1584 1585 mPortBuffers[portIndex].push(info); 1586 1587 CODEC_LOGV("allocated buffer %p on %s port", buffer, 1588 portIndex == kPortIndexInput ? "input" : "output"); 1589 } 1590 1591 if (portIndex == kPortIndexOutput) { 1592 1593 sp<MetaData> meta = mSource->getFormat(); 1594 int32_t delay = 0; 1595 if (!meta->findInt32(kKeyEncoderDelay, &delay)) { 1596 delay = 0; 1597 } 1598 int32_t padding = 0; 1599 if (!meta->findInt32(kKeyEncoderPadding, &padding)) { 1600 padding = 0; 1601 } 1602 int32_t numchannels = 0; 1603 if (delay + padding) { 1604 if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) { 1605 size_t frameSize = numchannels * sizeof(int16_t); 1606 if (mSkipCutBuffer != NULL) { 1607 size_t prevbuffersize = mSkipCutBuffer->size(); 1608 if (prevbuffersize != 0) { 1609 ALOGW("Replacing SkipCutBuffer holding %d bytes", prevbuffersize); 1610 } 1611 } 1612 mSkipCutBuffer = new SkipCutBuffer(delay * frameSize, padding * frameSize); 1613 } 1614 } 1615 } 1616 1617 // dumpPortStatus(portIndex); 1618 1619 if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) { 1620 Vector<MediaBuffer *> buffers; 1621 for (size_t i = 0; i < def.nBufferCountActual; ++i) { 1622 const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i); 1623 1624 MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize); 1625 buffers.push(mbuf); 1626 } 1627 1628 status_t err = mSource->setBuffers(buffers); 1629 1630 if (err != OK) { 1631 for (size_t i = 0; i < def.nBufferCountActual; ++i) { 1632 buffers.editItemAt(i)->release(); 1633 } 1634 buffers.clear(); 1635 1636 CODEC_LOGE( 1637 "Codec requested to use secure input buffers but " 1638 "upstream source didn't support that."); 1639 1640 return err; 1641 } 1642 } 1643 1644 return OK; 1645} 1646 1647status_t OMXCodec::applyRotation() { 1648 sp<MetaData> meta = mSource->getFormat(); 1649 1650 int32_t rotationDegrees; 1651 if (!meta->findInt32(kKeyRotation, &rotationDegrees)) { 1652 rotationDegrees = 0; 1653 } 1654 1655 uint32_t transform; 1656 switch (rotationDegrees) { 1657 case 0: transform = 0; break; 1658 case 90: transform = HAL_TRANSFORM_ROT_90; break; 1659 case 180: transform = HAL_TRANSFORM_ROT_180; break; 1660 case 270: transform = HAL_TRANSFORM_ROT_270; break; 1661 default: transform = 0; break; 1662 } 1663 1664 status_t err = OK; 1665 1666 if (transform) { 1667 err = native_window_set_buffers_transform( 1668 mNativeWindow.get(), transform); 1669 } 1670 1671 return err; 1672} 1673 1674status_t OMXCodec::allocateOutputBuffersFromNativeWindow() { 1675 // Get the number of buffers needed. 1676 OMX_PARAM_PORTDEFINITIONTYPE def; 1677 InitOMXParams(&def); 1678 def.nPortIndex = kPortIndexOutput; 1679 1680 status_t err = mOMX->getParameter( 1681 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1682 if (err != OK) { 1683 return err; 1684 } 1685 1686 err = native_window_set_buffers_geometry( 1687 mNativeWindow.get(), 1688 def.format.video.nFrameWidth, 1689 def.format.video.nFrameHeight, 1690 def.format.video.eColorFormat); 1691 1692 if (err != 0) { 1693 ALOGE("native_window_set_buffers_geometry failed: %s (%d)", 1694 strerror(-err), -err); 1695 return err; 1696 } 1697 1698 err = applyRotation(); 1699 if (err != OK) { 1700 return err; 1701 } 1702 1703 // Set up the native window. 1704 OMX_U32 usage = 0; 1705 err = mOMX->getGraphicBufferUsage(mNode, kPortIndexOutput, &usage); 1706 if (err != 0) { 1707 ALOGW("querying usage flags from OMX IL component failed: %d", err); 1708 // XXX: Currently this error is logged, but not fatal. 1709 usage = 0; 1710 } 1711 if (mFlags & kEnableGrallocUsageProtected) { 1712 usage |= GRALLOC_USAGE_PROTECTED; 1713 } 1714 1715 // Make sure to check whether either Stagefright or the video decoder 1716 // requested protected buffers. 1717 if (usage & GRALLOC_USAGE_PROTECTED) { 1718 // Verify that the ANativeWindow sends images directly to 1719 // SurfaceFlinger. 1720 int queuesToNativeWindow = 0; 1721 err = mNativeWindow->query( 1722 mNativeWindow.get(), NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER, 1723 &queuesToNativeWindow); 1724 if (err != 0) { 1725 ALOGE("error authenticating native window: %d", err); 1726 return err; 1727 } 1728 if (queuesToNativeWindow != 1) { 1729 ALOGE("native window could not be authenticated"); 1730 return PERMISSION_DENIED; 1731 } 1732 } 1733 1734 ALOGV("native_window_set_usage usage=0x%lx", usage); 1735 err = native_window_set_usage( 1736 mNativeWindow.get(), usage | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP); 1737 if (err != 0) { 1738 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), -err); 1739 return err; 1740 } 1741 1742 int minUndequeuedBufs = 0; 1743 err = mNativeWindow->query(mNativeWindow.get(), 1744 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs); 1745 if (err != 0) { 1746 ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)", 1747 strerror(-err), -err); 1748 return err; 1749 } 1750 1751 // XXX: Is this the right logic to use? It's not clear to me what the OMX 1752 // buffer counts refer to - how do they account for the renderer holding on 1753 // to buffers? 1754 if (def.nBufferCountActual < def.nBufferCountMin + minUndequeuedBufs) { 1755 OMX_U32 newBufferCount = def.nBufferCountMin + minUndequeuedBufs; 1756 def.nBufferCountActual = newBufferCount; 1757 err = mOMX->setParameter( 1758 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 1759 if (err != OK) { 1760 CODEC_LOGE("setting nBufferCountActual to %lu failed: %d", 1761 newBufferCount, err); 1762 return err; 1763 } 1764 } 1765 1766 err = native_window_set_buffer_count( 1767 mNativeWindow.get(), def.nBufferCountActual); 1768 if (err != 0) { 1769 ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err), 1770 -err); 1771 return err; 1772 } 1773 1774 CODEC_LOGV("allocating %lu buffers from a native window of size %lu on " 1775 "output port", def.nBufferCountActual, def.nBufferSize); 1776 1777 // Dequeue buffers and send them to OMX 1778 for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) { 1779 ANativeWindowBuffer* buf; 1780 err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf); 1781 if (err != 0) { 1782 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), -err); 1783 break; 1784 } 1785 1786 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false)); 1787 BufferInfo info; 1788 info.mData = NULL; 1789 info.mSize = def.nBufferSize; 1790 info.mStatus = OWNED_BY_US; 1791 info.mMem = NULL; 1792 info.mMediaBuffer = new MediaBuffer(graphicBuffer); 1793 info.mMediaBuffer->setObserver(this); 1794 mPortBuffers[kPortIndexOutput].push(info); 1795 1796 IOMX::buffer_id bufferId; 1797 err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer, 1798 &bufferId); 1799 if (err != 0) { 1800 CODEC_LOGE("registering GraphicBuffer with OMX IL component " 1801 "failed: %d", err); 1802 break; 1803 } 1804 1805 mPortBuffers[kPortIndexOutput].editItemAt(i).mBuffer = bufferId; 1806 1807 CODEC_LOGV("registered graphic buffer with ID %p (pointer = %p)", 1808 bufferId, graphicBuffer.get()); 1809 } 1810 1811 OMX_U32 cancelStart; 1812 OMX_U32 cancelEnd; 1813 if (err != 0) { 1814 // If an error occurred while dequeuing we need to cancel any buffers 1815 // that were dequeued. 1816 cancelStart = 0; 1817 cancelEnd = mPortBuffers[kPortIndexOutput].size(); 1818 } else { 1819 // Return the last two buffers to the native window. 1820 cancelStart = def.nBufferCountActual - minUndequeuedBufs; 1821 cancelEnd = def.nBufferCountActual; 1822 } 1823 1824 for (OMX_U32 i = cancelStart; i < cancelEnd; i++) { 1825 BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(i); 1826 cancelBufferToNativeWindow(info); 1827 } 1828 1829 return err; 1830} 1831 1832status_t OMXCodec::cancelBufferToNativeWindow(BufferInfo *info) { 1833 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 1834 CODEC_LOGV("Calling cancelBuffer on buffer %p", info->mBuffer); 1835 int err = mNativeWindow->cancelBuffer( 1836 mNativeWindow.get(), info->mMediaBuffer->graphicBuffer().get()); 1837 if (err != 0) { 1838 CODEC_LOGE("cancelBuffer failed w/ error 0x%08x", err); 1839 1840 setState(ERROR); 1841 return err; 1842 } 1843 info->mStatus = OWNED_BY_NATIVE_WINDOW; 1844 return OK; 1845} 1846 1847OMXCodec::BufferInfo* OMXCodec::dequeueBufferFromNativeWindow() { 1848 // Dequeue the next buffer from the native window. 1849 ANativeWindowBuffer* buf; 1850 int err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf); 1851 if (err != 0) { 1852 CODEC_LOGE("dequeueBuffer failed w/ error 0x%08x", err); 1853 1854 setState(ERROR); 1855 return 0; 1856 } 1857 1858 // Determine which buffer we just dequeued. 1859 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 1860 BufferInfo *bufInfo = 0; 1861 for (size_t i = 0; i < buffers->size(); i++) { 1862 sp<GraphicBuffer> graphicBuffer = buffers->itemAt(i). 1863 mMediaBuffer->graphicBuffer(); 1864 if (graphicBuffer->handle == buf->handle) { 1865 bufInfo = &buffers->editItemAt(i); 1866 break; 1867 } 1868 } 1869 1870 if (bufInfo == 0) { 1871 CODEC_LOGE("dequeued unrecognized buffer: %p", buf); 1872 1873 setState(ERROR); 1874 return 0; 1875 } 1876 1877 // The native window no longer owns the buffer. 1878 CHECK_EQ((int)bufInfo->mStatus, (int)OWNED_BY_NATIVE_WINDOW); 1879 bufInfo->mStatus = OWNED_BY_US; 1880 1881 return bufInfo; 1882} 1883 1884status_t OMXCodec::pushBlankBuffersToNativeWindow() { 1885 status_t err = NO_ERROR; 1886 ANativeWindowBuffer* anb = NULL; 1887 int numBufs = 0; 1888 int minUndequeuedBufs = 0; 1889 1890 // We need to reconnect to the ANativeWindow as a CPU client to ensure that 1891 // no frames get dropped by SurfaceFlinger assuming that these are video 1892 // frames. 1893 err = native_window_api_disconnect(mNativeWindow.get(), 1894 NATIVE_WINDOW_API_MEDIA); 1895 if (err != NO_ERROR) { 1896 ALOGE("error pushing blank frames: api_disconnect failed: %s (%d)", 1897 strerror(-err), -err); 1898 return err; 1899 } 1900 1901 err = native_window_api_connect(mNativeWindow.get(), 1902 NATIVE_WINDOW_API_CPU); 1903 if (err != NO_ERROR) { 1904 ALOGE("error pushing blank frames: api_connect failed: %s (%d)", 1905 strerror(-err), -err); 1906 return err; 1907 } 1908 1909 err = native_window_set_buffers_geometry(mNativeWindow.get(), 1, 1, 1910 HAL_PIXEL_FORMAT_RGBX_8888); 1911 if (err != NO_ERROR) { 1912 ALOGE("error pushing blank frames: set_buffers_geometry failed: %s (%d)", 1913 strerror(-err), -err); 1914 goto error; 1915 } 1916 1917 err = native_window_set_usage(mNativeWindow.get(), 1918 GRALLOC_USAGE_SW_WRITE_OFTEN); 1919 if (err != NO_ERROR) { 1920 ALOGE("error pushing blank frames: set_usage failed: %s (%d)", 1921 strerror(-err), -err); 1922 goto error; 1923 } 1924 1925 err = mNativeWindow->query(mNativeWindow.get(), 1926 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs); 1927 if (err != NO_ERROR) { 1928 ALOGE("error pushing blank frames: MIN_UNDEQUEUED_BUFFERS query " 1929 "failed: %s (%d)", strerror(-err), -err); 1930 goto error; 1931 } 1932 1933 numBufs = minUndequeuedBufs + 1; 1934 err = native_window_set_buffer_count(mNativeWindow.get(), numBufs); 1935 if (err != NO_ERROR) { 1936 ALOGE("error pushing blank frames: set_buffer_count failed: %s (%d)", 1937 strerror(-err), -err); 1938 goto error; 1939 } 1940 1941 // We push numBufs + 1 buffers to ensure that we've drawn into the same 1942 // buffer twice. This should guarantee that the buffer has been displayed 1943 // on the screen and then been replaced, so an previous video frames are 1944 // guaranteed NOT to be currently displayed. 1945 for (int i = 0; i < numBufs + 1; i++) { 1946 err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &anb); 1947 if (err != NO_ERROR) { 1948 ALOGE("error pushing blank frames: dequeueBuffer failed: %s (%d)", 1949 strerror(-err), -err); 1950 goto error; 1951 } 1952 1953 sp<GraphicBuffer> buf(new GraphicBuffer(anb, false)); 1954 err = mNativeWindow->lockBuffer(mNativeWindow.get(), 1955 buf->getNativeBuffer()); 1956 if (err != NO_ERROR) { 1957 ALOGE("error pushing blank frames: lockBuffer failed: %s (%d)", 1958 strerror(-err), -err); 1959 goto error; 1960 } 1961 1962 // Fill the buffer with the a 1x1 checkerboard pattern ;) 1963 uint32_t* img = NULL; 1964 err = buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img)); 1965 if (err != NO_ERROR) { 1966 ALOGE("error pushing blank frames: lock failed: %s (%d)", 1967 strerror(-err), -err); 1968 goto error; 1969 } 1970 1971 *img = 0; 1972 1973 err = buf->unlock(); 1974 if (err != NO_ERROR) { 1975 ALOGE("error pushing blank frames: unlock failed: %s (%d)", 1976 strerror(-err), -err); 1977 goto error; 1978 } 1979 1980 err = mNativeWindow->queueBuffer(mNativeWindow.get(), 1981 buf->getNativeBuffer()); 1982 if (err != NO_ERROR) { 1983 ALOGE("error pushing blank frames: queueBuffer failed: %s (%d)", 1984 strerror(-err), -err); 1985 goto error; 1986 } 1987 1988 anb = NULL; 1989 } 1990 1991error: 1992 1993 if (err != NO_ERROR) { 1994 // Clean up after an error. 1995 if (anb != NULL) { 1996 mNativeWindow->cancelBuffer(mNativeWindow.get(), anb); 1997 } 1998 1999 native_window_api_disconnect(mNativeWindow.get(), 2000 NATIVE_WINDOW_API_CPU); 2001 native_window_api_connect(mNativeWindow.get(), 2002 NATIVE_WINDOW_API_MEDIA); 2003 2004 return err; 2005 } else { 2006 // Clean up after success. 2007 err = native_window_api_disconnect(mNativeWindow.get(), 2008 NATIVE_WINDOW_API_CPU); 2009 if (err != NO_ERROR) { 2010 ALOGE("error pushing blank frames: api_disconnect failed: %s (%d)", 2011 strerror(-err), -err); 2012 return err; 2013 } 2014 2015 err = native_window_api_connect(mNativeWindow.get(), 2016 NATIVE_WINDOW_API_MEDIA); 2017 if (err != NO_ERROR) { 2018 ALOGE("error pushing blank frames: api_connect failed: %s (%d)", 2019 strerror(-err), -err); 2020 return err; 2021 } 2022 2023 return NO_ERROR; 2024 } 2025} 2026 2027int64_t OMXCodec::getDecodingTimeUs() { 2028 CHECK(mIsEncoder && mIsVideo); 2029 2030 if (mDecodingTimeList.empty()) { 2031 CHECK(mSignalledEOS || mNoMoreOutputData); 2032 // No corresponding input frame available. 2033 // This could happen when EOS is reached. 2034 return 0; 2035 } 2036 2037 List<int64_t>::iterator it = mDecodingTimeList.begin(); 2038 int64_t timeUs = *it; 2039 mDecodingTimeList.erase(it); 2040 return timeUs; 2041} 2042 2043void OMXCodec::on_message(const omx_message &msg) { 2044 if (mState == ERROR) { 2045 ALOGW("Dropping OMX message - we're in ERROR state."); 2046 return; 2047 } 2048 2049 switch (msg.type) { 2050 case omx_message::EVENT: 2051 { 2052 onEvent( 2053 msg.u.event_data.event, msg.u.event_data.data1, 2054 msg.u.event_data.data2); 2055 2056 break; 2057 } 2058 2059 case omx_message::EMPTY_BUFFER_DONE: 2060 { 2061 IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer; 2062 2063 CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer); 2064 2065 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 2066 size_t i = 0; 2067 while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) { 2068 ++i; 2069 } 2070 2071 CHECK(i < buffers->size()); 2072 if ((*buffers)[i].mStatus != OWNED_BY_COMPONENT) { 2073 ALOGW("We already own input buffer %p, yet received " 2074 "an EMPTY_BUFFER_DONE.", buffer); 2075 } 2076 2077 BufferInfo* info = &buffers->editItemAt(i); 2078 info->mStatus = OWNED_BY_US; 2079 2080 // Buffer could not be released until empty buffer done is called. 2081 if (info->mMediaBuffer != NULL) { 2082 if (mIsEncoder && 2083 (mQuirks & kAvoidMemcopyInputRecordingFrames)) { 2084 // If zero-copy mode is enabled this will send the 2085 // input buffer back to the upstream source. 2086 restorePatchedDataPointer(info); 2087 } 2088 2089 info->mMediaBuffer->release(); 2090 info->mMediaBuffer = NULL; 2091 } 2092 2093 if (mPortStatus[kPortIndexInput] == DISABLING) { 2094 CODEC_LOGV("Port is disabled, freeing buffer %p", buffer); 2095 2096 status_t err = freeBuffer(kPortIndexInput, i); 2097 CHECK_EQ(err, (status_t)OK); 2098 } else if (mState != ERROR 2099 && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) { 2100 CHECK_EQ((int)mPortStatus[kPortIndexInput], (int)ENABLED); 2101 2102 if (mFlags & kUseSecureInputBuffers) { 2103 drainAnyInputBuffer(); 2104 } else { 2105 drainInputBuffer(&buffers->editItemAt(i)); 2106 } 2107 } 2108 break; 2109 } 2110 2111 case omx_message::FILL_BUFFER_DONE: 2112 { 2113 IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer; 2114 OMX_U32 flags = msg.u.extended_buffer_data.flags; 2115 2116 CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))", 2117 buffer, 2118 msg.u.extended_buffer_data.range_length, 2119 flags, 2120 msg.u.extended_buffer_data.timestamp, 2121 msg.u.extended_buffer_data.timestamp / 1E6); 2122 2123 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 2124 size_t i = 0; 2125 while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) { 2126 ++i; 2127 } 2128 2129 CHECK(i < buffers->size()); 2130 BufferInfo *info = &buffers->editItemAt(i); 2131 2132 if (info->mStatus != OWNED_BY_COMPONENT) { 2133 ALOGW("We already own output buffer %p, yet received " 2134 "a FILL_BUFFER_DONE.", buffer); 2135 } 2136 2137 info->mStatus = OWNED_BY_US; 2138 2139 if (mPortStatus[kPortIndexOutput] == DISABLING) { 2140 CODEC_LOGV("Port is disabled, freeing buffer %p", buffer); 2141 2142 status_t err = freeBuffer(kPortIndexOutput, i); 2143 CHECK_EQ(err, (status_t)OK); 2144 2145#if 0 2146 } else if (mPortStatus[kPortIndexOutput] == ENABLED 2147 && (flags & OMX_BUFFERFLAG_EOS)) { 2148 CODEC_LOGV("No more output data."); 2149 mNoMoreOutputData = true; 2150 mBufferFilled.signal(); 2151#endif 2152 } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) { 2153 CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED); 2154 2155 if (info->mMediaBuffer == NULL) { 2156 CHECK(mOMXLivesLocally); 2157 CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts); 2158 CHECK(mQuirks & kDefersOutputBufferAllocation); 2159 2160 // The qcom video decoders on Nexus don't actually allocate 2161 // output buffer memory on a call to OMX_AllocateBuffer 2162 // the "pBuffer" member of the OMX_BUFFERHEADERTYPE 2163 // structure is only filled in later. 2164 2165 info->mMediaBuffer = new MediaBuffer( 2166 msg.u.extended_buffer_data.data_ptr, 2167 info->mSize); 2168 info->mMediaBuffer->setObserver(this); 2169 } 2170 2171 MediaBuffer *buffer = info->mMediaBuffer; 2172 bool isGraphicBuffer = buffer->graphicBuffer() != NULL; 2173 2174 if (!isGraphicBuffer 2175 && msg.u.extended_buffer_data.range_offset 2176 + msg.u.extended_buffer_data.range_length 2177 > buffer->size()) { 2178 CODEC_LOGE( 2179 "Codec lied about its buffer size requirements, " 2180 "sending a buffer larger than the originally " 2181 "advertised size in FILL_BUFFER_DONE!"); 2182 } 2183 buffer->set_range( 2184 msg.u.extended_buffer_data.range_offset, 2185 msg.u.extended_buffer_data.range_length); 2186 2187 buffer->meta_data()->clear(); 2188 2189 buffer->meta_data()->setInt64( 2190 kKeyTime, msg.u.extended_buffer_data.timestamp); 2191 2192 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) { 2193 buffer->meta_data()->setInt32(kKeyIsSyncFrame, true); 2194 } 2195 bool isCodecSpecific = false; 2196 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) { 2197 buffer->meta_data()->setInt32(kKeyIsCodecConfig, true); 2198 isCodecSpecific = true; 2199 } 2200 2201 if (isGraphicBuffer || mQuirks & kOutputBuffersAreUnreadable) { 2202 buffer->meta_data()->setInt32(kKeyIsUnreadable, true); 2203 } 2204 2205 buffer->meta_data()->setPointer( 2206 kKeyPlatformPrivate, 2207 msg.u.extended_buffer_data.platform_private); 2208 2209 buffer->meta_data()->setPointer( 2210 kKeyBufferID, 2211 msg.u.extended_buffer_data.buffer); 2212 2213 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) { 2214 CODEC_LOGV("No more output data."); 2215 mNoMoreOutputData = true; 2216 } 2217 2218 if (mIsEncoder && mIsVideo) { 2219 int64_t decodingTimeUs = isCodecSpecific? 0: getDecodingTimeUs(); 2220 buffer->meta_data()->setInt64(kKeyDecodingTime, decodingTimeUs); 2221 } 2222 2223 if (mTargetTimeUs >= 0) { 2224 CHECK(msg.u.extended_buffer_data.timestamp <= mTargetTimeUs); 2225 2226 if (msg.u.extended_buffer_data.timestamp < mTargetTimeUs) { 2227 CODEC_LOGV( 2228 "skipping output buffer at timestamp %lld us", 2229 msg.u.extended_buffer_data.timestamp); 2230 2231 fillOutputBuffer(info); 2232 break; 2233 } 2234 2235 CODEC_LOGV( 2236 "returning output buffer at target timestamp " 2237 "%lld us", 2238 msg.u.extended_buffer_data.timestamp); 2239 2240 mTargetTimeUs = -1; 2241 } 2242 2243 mFilledBuffers.push_back(i); 2244 mBufferFilled.signal(); 2245 if (mIsEncoder) { 2246 sched_yield(); 2247 } 2248 } 2249 2250 break; 2251 } 2252 2253 default: 2254 { 2255 CHECK(!"should not be here."); 2256 break; 2257 } 2258 } 2259} 2260 2261// Has the format changed in any way that the client would have to be aware of? 2262static bool formatHasNotablyChanged( 2263 const sp<MetaData> &from, const sp<MetaData> &to) { 2264 if (from.get() == NULL && to.get() == NULL) { 2265 return false; 2266 } 2267 2268 if ((from.get() == NULL && to.get() != NULL) 2269 || (from.get() != NULL && to.get() == NULL)) { 2270 return true; 2271 } 2272 2273 const char *mime_from, *mime_to; 2274 CHECK(from->findCString(kKeyMIMEType, &mime_from)); 2275 CHECK(to->findCString(kKeyMIMEType, &mime_to)); 2276 2277 if (strcasecmp(mime_from, mime_to)) { 2278 return true; 2279 } 2280 2281 if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) { 2282 int32_t colorFormat_from, colorFormat_to; 2283 CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from)); 2284 CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to)); 2285 2286 if (colorFormat_from != colorFormat_to) { 2287 return true; 2288 } 2289 2290 int32_t width_from, width_to; 2291 CHECK(from->findInt32(kKeyWidth, &width_from)); 2292 CHECK(to->findInt32(kKeyWidth, &width_to)); 2293 2294 if (width_from != width_to) { 2295 return true; 2296 } 2297 2298 int32_t height_from, height_to; 2299 CHECK(from->findInt32(kKeyHeight, &height_from)); 2300 CHECK(to->findInt32(kKeyHeight, &height_to)); 2301 2302 if (height_from != height_to) { 2303 return true; 2304 } 2305 2306 int32_t left_from, top_from, right_from, bottom_from; 2307 CHECK(from->findRect( 2308 kKeyCropRect, 2309 &left_from, &top_from, &right_from, &bottom_from)); 2310 2311 int32_t left_to, top_to, right_to, bottom_to; 2312 CHECK(to->findRect( 2313 kKeyCropRect, 2314 &left_to, &top_to, &right_to, &bottom_to)); 2315 2316 if (left_to != left_from || top_to != top_from 2317 || right_to != right_from || bottom_to != bottom_from) { 2318 return true; 2319 } 2320 } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) { 2321 int32_t numChannels_from, numChannels_to; 2322 CHECK(from->findInt32(kKeyChannelCount, &numChannels_from)); 2323 CHECK(to->findInt32(kKeyChannelCount, &numChannels_to)); 2324 2325 if (numChannels_from != numChannels_to) { 2326 return true; 2327 } 2328 2329 int32_t sampleRate_from, sampleRate_to; 2330 CHECK(from->findInt32(kKeySampleRate, &sampleRate_from)); 2331 CHECK(to->findInt32(kKeySampleRate, &sampleRate_to)); 2332 2333 if (sampleRate_from != sampleRate_to) { 2334 return true; 2335 } 2336 } 2337 2338 return false; 2339} 2340 2341void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) { 2342 switch (event) { 2343 case OMX_EventCmdComplete: 2344 { 2345 onCmdComplete((OMX_COMMANDTYPE)data1, data2); 2346 break; 2347 } 2348 2349 case OMX_EventError: 2350 { 2351 CODEC_LOGE("ERROR(0x%08lx, %ld)", data1, data2); 2352 2353 setState(ERROR); 2354 break; 2355 } 2356 2357 case OMX_EventPortSettingsChanged: 2358 { 2359 CODEC_LOGV("OMX_EventPortSettingsChanged(port=%ld, data2=0x%08lx)", 2360 data1, data2); 2361 2362 if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) { 2363 // There is no need to check whether mFilledBuffers is empty or not 2364 // when the OMX_EventPortSettingsChanged is not meant for reallocating 2365 // the output buffers. 2366 if (data1 == kPortIndexOutput) { 2367 CHECK(mFilledBuffers.empty()); 2368 } 2369 onPortSettingsChanged(data1); 2370 } else if (data1 == kPortIndexOutput && 2371 (data2 == OMX_IndexConfigCommonOutputCrop || 2372 data2 == OMX_IndexConfigCommonScale)) { 2373 2374 sp<MetaData> oldOutputFormat = mOutputFormat; 2375 initOutputFormat(mSource->getFormat()); 2376 2377 if (data2 == OMX_IndexConfigCommonOutputCrop && 2378 formatHasNotablyChanged(oldOutputFormat, mOutputFormat)) { 2379 mOutputPortSettingsHaveChanged = true; 2380 2381 } else if (data2 == OMX_IndexConfigCommonScale) { 2382 OMX_CONFIG_SCALEFACTORTYPE scale; 2383 InitOMXParams(&scale); 2384 scale.nPortIndex = kPortIndexOutput; 2385 2386 // Change display dimension only when necessary. 2387 if (OK == mOMX->getConfig( 2388 mNode, 2389 OMX_IndexConfigCommonScale, 2390 &scale, sizeof(scale))) { 2391 int32_t left, top, right, bottom; 2392 CHECK(mOutputFormat->findRect(kKeyCropRect, 2393 &left, &top, 2394 &right, &bottom)); 2395 2396 // The scale is in 16.16 format. 2397 // scale 1.0 = 0x010000. When there is no 2398 // need to change the display, skip it. 2399 ALOGV("Get OMX_IndexConfigScale: 0x%lx/0x%lx", 2400 scale.xWidth, scale.xHeight); 2401 2402 if (scale.xWidth != 0x010000) { 2403 mOutputFormat->setInt32(kKeyDisplayWidth, 2404 ((right - left + 1) * scale.xWidth) >> 16); 2405 mOutputPortSettingsHaveChanged = true; 2406 } 2407 2408 if (scale.xHeight != 0x010000) { 2409 mOutputFormat->setInt32(kKeyDisplayHeight, 2410 ((bottom - top + 1) * scale.xHeight) >> 16); 2411 mOutputPortSettingsHaveChanged = true; 2412 } 2413 } 2414 } 2415 } 2416 break; 2417 } 2418 2419#if 0 2420 case OMX_EventBufferFlag: 2421 { 2422 CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1); 2423 2424 if (data1 == kPortIndexOutput) { 2425 mNoMoreOutputData = true; 2426 } 2427 break; 2428 } 2429#endif 2430 2431 default: 2432 { 2433 CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2); 2434 break; 2435 } 2436 } 2437} 2438 2439void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) { 2440 switch (cmd) { 2441 case OMX_CommandStateSet: 2442 { 2443 onStateChange((OMX_STATETYPE)data); 2444 break; 2445 } 2446 2447 case OMX_CommandPortDisable: 2448 { 2449 OMX_U32 portIndex = data; 2450 CODEC_LOGV("PORT_DISABLED(%ld)", portIndex); 2451 2452 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2453 CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLING); 2454 CHECK_EQ(mPortBuffers[portIndex].size(), 0u); 2455 2456 mPortStatus[portIndex] = DISABLED; 2457 2458 if (mState == RECONFIGURING) { 2459 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2460 2461 sp<MetaData> oldOutputFormat = mOutputFormat; 2462 initOutputFormat(mSource->getFormat()); 2463 2464 // Don't notify clients if the output port settings change 2465 // wasn't of importance to them, i.e. it may be that just the 2466 // number of buffers has changed and nothing else. 2467 bool formatChanged = formatHasNotablyChanged(oldOutputFormat, mOutputFormat); 2468 if (!mOutputPortSettingsHaveChanged) { 2469 mOutputPortSettingsHaveChanged = formatChanged; 2470 } 2471 2472 status_t err = enablePortAsync(portIndex); 2473 if (err != OK) { 2474 CODEC_LOGE("enablePortAsync(%ld) failed (err = %d)", portIndex, err); 2475 setState(ERROR); 2476 } else { 2477 err = allocateBuffersOnPort(portIndex); 2478 if (err != OK) { 2479 CODEC_LOGE("allocateBuffersOnPort failed (err = %d)", err); 2480 setState(ERROR); 2481 } 2482 } 2483 } 2484 break; 2485 } 2486 2487 case OMX_CommandPortEnable: 2488 { 2489 OMX_U32 portIndex = data; 2490 CODEC_LOGV("PORT_ENABLED(%ld)", portIndex); 2491 2492 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2493 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLING); 2494 2495 mPortStatus[portIndex] = ENABLED; 2496 2497 if (mState == RECONFIGURING) { 2498 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2499 2500 setState(EXECUTING); 2501 2502 fillOutputBuffers(); 2503 } 2504 break; 2505 } 2506 2507 case OMX_CommandFlush: 2508 { 2509 OMX_U32 portIndex = data; 2510 2511 CODEC_LOGV("FLUSH_DONE(%ld)", portIndex); 2512 2513 CHECK_EQ((int)mPortStatus[portIndex], (int)SHUTTING_DOWN); 2514 mPortStatus[portIndex] = ENABLED; 2515 2516 CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]), 2517 mPortBuffers[portIndex].size()); 2518 2519 if (mSkipCutBuffer != NULL && mPortStatus[kPortIndexOutput] == ENABLED) { 2520 mSkipCutBuffer->clear(); 2521 } 2522 2523 if (mState == RECONFIGURING) { 2524 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2525 2526 disablePortAsync(portIndex); 2527 } else if (mState == EXECUTING_TO_IDLE) { 2528 if (mPortStatus[kPortIndexInput] == ENABLED 2529 && mPortStatus[kPortIndexOutput] == ENABLED) { 2530 CODEC_LOGV("Finished flushing both ports, now completing " 2531 "transition from EXECUTING to IDLE."); 2532 2533 mPortStatus[kPortIndexInput] = SHUTTING_DOWN; 2534 mPortStatus[kPortIndexOutput] = SHUTTING_DOWN; 2535 2536 status_t err = 2537 mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 2538 CHECK_EQ(err, (status_t)OK); 2539 } 2540 } else { 2541 // We're flushing both ports in preparation for seeking. 2542 2543 if (mPortStatus[kPortIndexInput] == ENABLED 2544 && mPortStatus[kPortIndexOutput] == ENABLED) { 2545 CODEC_LOGV("Finished flushing both ports, now continuing from" 2546 " seek-time."); 2547 2548 // We implicitly resume pulling on our upstream source. 2549 mPaused = false; 2550 2551 drainInputBuffers(); 2552 fillOutputBuffers(); 2553 } 2554 2555 if (mOutputPortSettingsChangedPending) { 2556 CODEC_LOGV( 2557 "Honoring deferred output port settings change."); 2558 2559 mOutputPortSettingsChangedPending = false; 2560 onPortSettingsChanged(kPortIndexOutput); 2561 } 2562 } 2563 2564 break; 2565 } 2566 2567 default: 2568 { 2569 CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data); 2570 break; 2571 } 2572 } 2573} 2574 2575void OMXCodec::onStateChange(OMX_STATETYPE newState) { 2576 CODEC_LOGV("onStateChange %d", newState); 2577 2578 switch (newState) { 2579 case OMX_StateIdle: 2580 { 2581 CODEC_LOGV("Now Idle."); 2582 if (mState == LOADED_TO_IDLE) { 2583 status_t err = mOMX->sendCommand( 2584 mNode, OMX_CommandStateSet, OMX_StateExecuting); 2585 2586 CHECK_EQ(err, (status_t)OK); 2587 2588 setState(IDLE_TO_EXECUTING); 2589 } else { 2590 CHECK_EQ((int)mState, (int)EXECUTING_TO_IDLE); 2591 2592 CHECK_EQ( 2593 countBuffersWeOwn(mPortBuffers[kPortIndexInput]), 2594 mPortBuffers[kPortIndexInput].size()); 2595 2596 CHECK_EQ( 2597 countBuffersWeOwn(mPortBuffers[kPortIndexOutput]), 2598 mPortBuffers[kPortIndexOutput].size()); 2599 2600 status_t err = mOMX->sendCommand( 2601 mNode, OMX_CommandStateSet, OMX_StateLoaded); 2602 2603 CHECK_EQ(err, (status_t)OK); 2604 2605 err = freeBuffersOnPort(kPortIndexInput); 2606 CHECK_EQ(err, (status_t)OK); 2607 2608 err = freeBuffersOnPort(kPortIndexOutput); 2609 CHECK_EQ(err, (status_t)OK); 2610 2611 mPortStatus[kPortIndexInput] = ENABLED; 2612 mPortStatus[kPortIndexOutput] = ENABLED; 2613 2614 if ((mFlags & kEnableGrallocUsageProtected) && 2615 mNativeWindow != NULL) { 2616 // We push enough 1x1 blank buffers to ensure that one of 2617 // them has made it to the display. This allows the OMX 2618 // component teardown to zero out any protected buffers 2619 // without the risk of scanning out one of those buffers. 2620 pushBlankBuffersToNativeWindow(); 2621 } 2622 2623 setState(IDLE_TO_LOADED); 2624 } 2625 break; 2626 } 2627 2628 case OMX_StateExecuting: 2629 { 2630 CHECK_EQ((int)mState, (int)IDLE_TO_EXECUTING); 2631 2632 CODEC_LOGV("Now Executing."); 2633 2634 mOutputPortSettingsChangedPending = false; 2635 2636 setState(EXECUTING); 2637 2638 // Buffers will be submitted to the component in the first 2639 // call to OMXCodec::read as mInitialBufferSubmit is true at 2640 // this point. This ensures that this on_message call returns, 2641 // releases the lock and ::init can notice the state change and 2642 // itself return. 2643 break; 2644 } 2645 2646 case OMX_StateLoaded: 2647 { 2648 CHECK_EQ((int)mState, (int)IDLE_TO_LOADED); 2649 2650 CODEC_LOGV("Now Loaded."); 2651 2652 setState(LOADED); 2653 break; 2654 } 2655 2656 case OMX_StateInvalid: 2657 { 2658 setState(ERROR); 2659 break; 2660 } 2661 2662 default: 2663 { 2664 CHECK(!"should not be here."); 2665 break; 2666 } 2667 } 2668} 2669 2670// static 2671size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) { 2672 size_t n = 0; 2673 for (size_t i = 0; i < buffers.size(); ++i) { 2674 if (buffers[i].mStatus != OWNED_BY_COMPONENT) { 2675 ++n; 2676 } 2677 } 2678 2679 return n; 2680} 2681 2682status_t OMXCodec::freeBuffersOnPort( 2683 OMX_U32 portIndex, bool onlyThoseWeOwn) { 2684 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 2685 2686 status_t stickyErr = OK; 2687 2688 for (size_t i = buffers->size(); i-- > 0;) { 2689 BufferInfo *info = &buffers->editItemAt(i); 2690 2691 if (onlyThoseWeOwn && info->mStatus == OWNED_BY_COMPONENT) { 2692 continue; 2693 } 2694 2695 CHECK(info->mStatus == OWNED_BY_US 2696 || info->mStatus == OWNED_BY_NATIVE_WINDOW); 2697 2698 CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex); 2699 2700 status_t err = freeBuffer(portIndex, i); 2701 2702 if (err != OK) { 2703 stickyErr = err; 2704 } 2705 2706 } 2707 2708 CHECK(onlyThoseWeOwn || buffers->isEmpty()); 2709 2710 return stickyErr; 2711} 2712 2713status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) { 2714 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 2715 2716 BufferInfo *info = &buffers->editItemAt(bufIndex); 2717 2718 status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer); 2719 2720 if (err == OK && info->mMediaBuffer != NULL) { 2721 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2722 info->mMediaBuffer->setObserver(NULL); 2723 2724 // Make sure nobody but us owns this buffer at this point. 2725 CHECK_EQ(info->mMediaBuffer->refcount(), 0); 2726 2727 // Cancel the buffer if it belongs to an ANativeWindow. 2728 sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer(); 2729 if (info->mStatus == OWNED_BY_US && graphicBuffer != 0) { 2730 err = cancelBufferToNativeWindow(info); 2731 } 2732 2733 info->mMediaBuffer->release(); 2734 info->mMediaBuffer = NULL; 2735 } 2736 2737 if (err == OK) { 2738 buffers->removeAt(bufIndex); 2739 } 2740 2741 return err; 2742} 2743 2744void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) { 2745 CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex); 2746 2747 CHECK_EQ((int)mState, (int)EXECUTING); 2748 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2749 CHECK(!mOutputPortSettingsChangedPending); 2750 2751 if (mPortStatus[kPortIndexOutput] != ENABLED) { 2752 CODEC_LOGV("Deferring output port settings change."); 2753 mOutputPortSettingsChangedPending = true; 2754 return; 2755 } 2756 2757 setState(RECONFIGURING); 2758 2759 if (mQuirks & kNeedsFlushBeforeDisable) { 2760 if (!flushPortAsync(portIndex)) { 2761 onCmdComplete(OMX_CommandFlush, portIndex); 2762 } 2763 } else { 2764 disablePortAsync(portIndex); 2765 } 2766} 2767 2768bool OMXCodec::flushPortAsync(OMX_U32 portIndex) { 2769 CHECK(mState == EXECUTING || mState == RECONFIGURING 2770 || mState == EXECUTING_TO_IDLE); 2771 2772 CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.", 2773 portIndex, countBuffersWeOwn(mPortBuffers[portIndex]), 2774 mPortBuffers[portIndex].size()); 2775 2776 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED); 2777 mPortStatus[portIndex] = SHUTTING_DOWN; 2778 2779 if ((mQuirks & kRequiresFlushCompleteEmulation) 2780 && countBuffersWeOwn(mPortBuffers[portIndex]) 2781 == mPortBuffers[portIndex].size()) { 2782 // No flush is necessary and this component fails to send a 2783 // flush-complete event in this case. 2784 2785 return false; 2786 } 2787 2788 status_t err = 2789 mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex); 2790 CHECK_EQ(err, (status_t)OK); 2791 2792 return true; 2793} 2794 2795void OMXCodec::disablePortAsync(OMX_U32 portIndex) { 2796 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2797 2798 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED); 2799 mPortStatus[portIndex] = DISABLING; 2800 2801 CODEC_LOGV("sending OMX_CommandPortDisable(%ld)", portIndex); 2802 status_t err = 2803 mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex); 2804 CHECK_EQ(err, (status_t)OK); 2805 2806 freeBuffersOnPort(portIndex, true); 2807} 2808 2809status_t OMXCodec::enablePortAsync(OMX_U32 portIndex) { 2810 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2811 2812 CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLED); 2813 mPortStatus[portIndex] = ENABLING; 2814 2815 CODEC_LOGV("sending OMX_CommandPortEnable(%ld)", portIndex); 2816 return mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex); 2817} 2818 2819void OMXCodec::fillOutputBuffers() { 2820 CHECK_EQ((int)mState, (int)EXECUTING); 2821 2822 // This is a workaround for some decoders not properly reporting 2823 // end-of-output-stream. If we own all input buffers and also own 2824 // all output buffers and we already signalled end-of-input-stream, 2825 // the end-of-output-stream is implied. 2826 if (mSignalledEOS 2827 && countBuffersWeOwn(mPortBuffers[kPortIndexInput]) 2828 == mPortBuffers[kPortIndexInput].size() 2829 && countBuffersWeOwn(mPortBuffers[kPortIndexOutput]) 2830 == mPortBuffers[kPortIndexOutput].size()) { 2831 mNoMoreOutputData = true; 2832 mBufferFilled.signal(); 2833 2834 return; 2835 } 2836 2837 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 2838 for (size_t i = 0; i < buffers->size(); ++i) { 2839 BufferInfo *info = &buffers->editItemAt(i); 2840 if (info->mStatus == OWNED_BY_US) { 2841 fillOutputBuffer(&buffers->editItemAt(i)); 2842 } 2843 } 2844} 2845 2846void OMXCodec::drainInputBuffers() { 2847 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2848 2849 if (mFlags & kUseSecureInputBuffers) { 2850 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 2851 for (size_t i = 0; i < buffers->size(); ++i) { 2852 if (!drainAnyInputBuffer() 2853 || (mFlags & kOnlySubmitOneInputBufferAtOneTime)) { 2854 break; 2855 } 2856 } 2857 } else { 2858 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 2859 for (size_t i = 0; i < buffers->size(); ++i) { 2860 BufferInfo *info = &buffers->editItemAt(i); 2861 2862 if (info->mStatus != OWNED_BY_US) { 2863 continue; 2864 } 2865 2866 if (!drainInputBuffer(info)) { 2867 break; 2868 } 2869 2870 if (mFlags & kOnlySubmitOneInputBufferAtOneTime) { 2871 break; 2872 } 2873 } 2874 } 2875} 2876 2877bool OMXCodec::drainAnyInputBuffer() { 2878 return drainInputBuffer((BufferInfo *)NULL); 2879} 2880 2881OMXCodec::BufferInfo *OMXCodec::findInputBufferByDataPointer(void *ptr) { 2882 Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput]; 2883 for (size_t i = 0; i < infos->size(); ++i) { 2884 BufferInfo *info = &infos->editItemAt(i); 2885 2886 if (info->mData == ptr) { 2887 CODEC_LOGV( 2888 "input buffer data ptr = %p, buffer_id = %p", 2889 ptr, 2890 info->mBuffer); 2891 2892 return info; 2893 } 2894 } 2895 2896 TRESPASS(); 2897} 2898 2899OMXCodec::BufferInfo *OMXCodec::findEmptyInputBuffer() { 2900 Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput]; 2901 for (size_t i = 0; i < infos->size(); ++i) { 2902 BufferInfo *info = &infos->editItemAt(i); 2903 2904 if (info->mStatus == OWNED_BY_US) { 2905 return info; 2906 } 2907 } 2908 2909 TRESPASS(); 2910} 2911 2912bool OMXCodec::drainInputBuffer(BufferInfo *info) { 2913 if (info != NULL) { 2914 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 2915 } 2916 2917 if (mSignalledEOS) { 2918 return false; 2919 } 2920 2921 if (mCodecSpecificDataIndex < mCodecSpecificData.size()) { 2922 CHECK(!(mFlags & kUseSecureInputBuffers)); 2923 2924 const CodecSpecificData *specific = 2925 mCodecSpecificData[mCodecSpecificDataIndex]; 2926 2927 size_t size = specific->mSize; 2928 2929 if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME) 2930 && !(mQuirks & kWantsNALFragments)) { 2931 static const uint8_t kNALStartCode[4] = 2932 { 0x00, 0x00, 0x00, 0x01 }; 2933 2934 CHECK(info->mSize >= specific->mSize + 4); 2935 2936 size += 4; 2937 2938 memcpy(info->mData, kNALStartCode, 4); 2939 memcpy((uint8_t *)info->mData + 4, 2940 specific->mData, specific->mSize); 2941 } else { 2942 CHECK(info->mSize >= specific->mSize); 2943 memcpy(info->mData, specific->mData, specific->mSize); 2944 } 2945 2946 mNoMoreOutputData = false; 2947 2948 CODEC_LOGV("calling emptyBuffer with codec specific data"); 2949 2950 status_t err = mOMX->emptyBuffer( 2951 mNode, info->mBuffer, 0, size, 2952 OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG, 2953 0); 2954 CHECK_EQ(err, (status_t)OK); 2955 2956 info->mStatus = OWNED_BY_COMPONENT; 2957 2958 ++mCodecSpecificDataIndex; 2959 return true; 2960 } 2961 2962 if (mPaused) { 2963 return false; 2964 } 2965 2966 status_t err; 2967 2968 bool signalEOS = false; 2969 int64_t timestampUs = 0; 2970 2971 size_t offset = 0; 2972 int32_t n = 0; 2973 2974 2975 for (;;) { 2976 MediaBuffer *srcBuffer; 2977 if (mSeekTimeUs >= 0) { 2978 if (mLeftOverBuffer) { 2979 mLeftOverBuffer->release(); 2980 mLeftOverBuffer = NULL; 2981 } 2982 2983 MediaSource::ReadOptions options; 2984 options.setSeekTo(mSeekTimeUs, mSeekMode); 2985 2986 mSeekTimeUs = -1; 2987 mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC; 2988 mBufferFilled.signal(); 2989 2990 err = mSource->read(&srcBuffer, &options); 2991 2992 if (err == OK) { 2993 int64_t targetTimeUs; 2994 if (srcBuffer->meta_data()->findInt64( 2995 kKeyTargetTime, &targetTimeUs) 2996 && targetTimeUs >= 0) { 2997 CODEC_LOGV("targetTimeUs = %lld us", targetTimeUs); 2998 mTargetTimeUs = targetTimeUs; 2999 } else { 3000 mTargetTimeUs = -1; 3001 } 3002 } 3003 } else if (mLeftOverBuffer) { 3004 srcBuffer = mLeftOverBuffer; 3005 mLeftOverBuffer = NULL; 3006 3007 err = OK; 3008 } else { 3009 err = mSource->read(&srcBuffer); 3010 } 3011 3012 if (err != OK) { 3013 signalEOS = true; 3014 mFinalStatus = err; 3015 mSignalledEOS = true; 3016 mBufferFilled.signal(); 3017 break; 3018 } 3019 3020 if (mFlags & kUseSecureInputBuffers) { 3021 info = findInputBufferByDataPointer(srcBuffer->data()); 3022 CHECK(info != NULL); 3023 } 3024 3025 size_t remainingBytes = info->mSize - offset; 3026 3027 if (srcBuffer->range_length() > remainingBytes) { 3028 if (offset == 0) { 3029 CODEC_LOGE( 3030 "Codec's input buffers are too small to accomodate " 3031 "buffer read from source (info->mSize = %d, srcLength = %d)", 3032 info->mSize, srcBuffer->range_length()); 3033 3034 srcBuffer->release(); 3035 srcBuffer = NULL; 3036 3037 setState(ERROR); 3038 return false; 3039 } 3040 3041 mLeftOverBuffer = srcBuffer; 3042 break; 3043 } 3044 3045 bool releaseBuffer = true; 3046 if (mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)) { 3047 CHECK(mOMXLivesLocally && offset == 0); 3048 3049 OMX_BUFFERHEADERTYPE *header = 3050 (OMX_BUFFERHEADERTYPE *)info->mBuffer; 3051 3052 CHECK(header->pBuffer == info->mData); 3053 3054 header->pBuffer = 3055 (OMX_U8 *)srcBuffer->data() + srcBuffer->range_offset(); 3056 3057 releaseBuffer = false; 3058 info->mMediaBuffer = srcBuffer; 3059 } else { 3060 if (mFlags & kStoreMetaDataInVideoBuffers) { 3061 releaseBuffer = false; 3062 info->mMediaBuffer = srcBuffer; 3063 } 3064 3065 if (mFlags & kUseSecureInputBuffers) { 3066 // Data in "info" is already provided at this time. 3067 3068 releaseBuffer = false; 3069 3070 CHECK(info->mMediaBuffer == NULL); 3071 info->mMediaBuffer = srcBuffer; 3072 } else { 3073 CHECK(srcBuffer->data() != NULL) ; 3074 memcpy((uint8_t *)info->mData + offset, 3075 (const uint8_t *)srcBuffer->data() 3076 + srcBuffer->range_offset(), 3077 srcBuffer->range_length()); 3078 } 3079 } 3080 3081 int64_t lastBufferTimeUs; 3082 CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs)); 3083 CHECK(lastBufferTimeUs >= 0); 3084 if (mIsEncoder && mIsVideo) { 3085 mDecodingTimeList.push_back(lastBufferTimeUs); 3086 } 3087 3088 if (offset == 0) { 3089 timestampUs = lastBufferTimeUs; 3090 } 3091 3092 offset += srcBuffer->range_length(); 3093 3094 if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_VORBIS, mMIME)) { 3095 CHECK(!(mQuirks & kSupportsMultipleFramesPerInputBuffer)); 3096 CHECK_GE(info->mSize, offset + sizeof(int32_t)); 3097 3098 int32_t numPageSamples; 3099 if (!srcBuffer->meta_data()->findInt32( 3100 kKeyValidSamples, &numPageSamples)) { 3101 numPageSamples = -1; 3102 } 3103 3104 memcpy((uint8_t *)info->mData + offset, 3105 &numPageSamples, 3106 sizeof(numPageSamples)); 3107 3108 offset += sizeof(numPageSamples); 3109 } 3110 3111 if (releaseBuffer) { 3112 srcBuffer->release(); 3113 srcBuffer = NULL; 3114 } 3115 3116 ++n; 3117 3118 if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) { 3119 break; 3120 } 3121 3122 int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs; 3123 3124 if (coalescedDurationUs > 250000ll) { 3125 // Don't coalesce more than 250ms worth of encoded data at once. 3126 break; 3127 } 3128 } 3129 3130 if (n > 1) { 3131 ALOGV("coalesced %d frames into one input buffer", n); 3132 } 3133 3134 OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME; 3135 3136 if (signalEOS) { 3137 flags |= OMX_BUFFERFLAG_EOS; 3138 } else { 3139 mNoMoreOutputData = false; 3140 } 3141 3142 CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), " 3143 "timestamp %lld us (%.2f secs)", 3144 info->mBuffer, offset, 3145 timestampUs, timestampUs / 1E6); 3146 3147 if (info == NULL) { 3148 CHECK(mFlags & kUseSecureInputBuffers); 3149 CHECK(signalEOS); 3150 3151 // This is fishy, there's still a MediaBuffer corresponding to this 3152 // info available to the source at this point even though we're going 3153 // to use it to signal EOS to the codec. 3154 info = findEmptyInputBuffer(); 3155 } 3156 3157 err = mOMX->emptyBuffer( 3158 mNode, info->mBuffer, 0, offset, 3159 flags, timestampUs); 3160 3161 if (err != OK) { 3162 setState(ERROR); 3163 return false; 3164 } 3165 3166 info->mStatus = OWNED_BY_COMPONENT; 3167 3168 return true; 3169} 3170 3171void OMXCodec::fillOutputBuffer(BufferInfo *info) { 3172 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 3173 3174 if (mNoMoreOutputData) { 3175 CODEC_LOGV("There is no more output data available, not " 3176 "calling fillOutputBuffer"); 3177 return; 3178 } 3179 3180 if (info->mMediaBuffer != NULL) { 3181 sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer(); 3182 if (graphicBuffer != 0) { 3183 // When using a native buffer we need to lock the buffer before 3184 // giving it to OMX. 3185 CODEC_LOGV("Calling lockBuffer on %p", info->mBuffer); 3186 int err = mNativeWindow->lockBuffer(mNativeWindow.get(), 3187 graphicBuffer.get()); 3188 if (err != 0) { 3189 CODEC_LOGE("lockBuffer failed w/ error 0x%08x", err); 3190 3191 setState(ERROR); 3192 return; 3193 } 3194 } 3195 } 3196 3197 CODEC_LOGV("Calling fillBuffer on buffer %p", info->mBuffer); 3198 status_t err = mOMX->fillBuffer(mNode, info->mBuffer); 3199 3200 if (err != OK) { 3201 CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err); 3202 3203 setState(ERROR); 3204 return; 3205 } 3206 3207 info->mStatus = OWNED_BY_COMPONENT; 3208} 3209 3210bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) { 3211 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 3212 for (size_t i = 0; i < buffers->size(); ++i) { 3213 if ((*buffers)[i].mBuffer == buffer) { 3214 return drainInputBuffer(&buffers->editItemAt(i)); 3215 } 3216 } 3217 3218 CHECK(!"should not be here."); 3219 3220 return false; 3221} 3222 3223void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) { 3224 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 3225 for (size_t i = 0; i < buffers->size(); ++i) { 3226 if ((*buffers)[i].mBuffer == buffer) { 3227 fillOutputBuffer(&buffers->editItemAt(i)); 3228 return; 3229 } 3230 } 3231 3232 CHECK(!"should not be here."); 3233} 3234 3235void OMXCodec::setState(State newState) { 3236 mState = newState; 3237 mAsyncCompletion.signal(); 3238 3239 // This may cause some spurious wakeups but is necessary to 3240 // unblock the reader if we enter ERROR state. 3241 mBufferFilled.signal(); 3242} 3243 3244status_t OMXCodec::waitForBufferFilled_l() { 3245 3246 if (mIsEncoder) { 3247 // For timelapse video recording, the timelapse video recording may 3248 // not send an input frame for a _long_ time. Do not use timeout 3249 // for video encoding. 3250 return mBufferFilled.wait(mLock); 3251 } 3252 status_t err = mBufferFilled.waitRelative(mLock, kBufferFilledEventTimeOutNs); 3253 if (err != OK) { 3254 CODEC_LOGE("Timed out waiting for output buffers: %d/%d", 3255 countBuffersWeOwn(mPortBuffers[kPortIndexInput]), 3256 countBuffersWeOwn(mPortBuffers[kPortIndexOutput])); 3257 } 3258 return err; 3259} 3260 3261void OMXCodec::setRawAudioFormat( 3262 OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) { 3263 3264 // port definition 3265 OMX_PARAM_PORTDEFINITIONTYPE def; 3266 InitOMXParams(&def); 3267 def.nPortIndex = portIndex; 3268 status_t err = mOMX->getParameter( 3269 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3270 CHECK_EQ(err, (status_t)OK); 3271 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM; 3272 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition, 3273 &def, sizeof(def)), (status_t)OK); 3274 3275 // pcm param 3276 OMX_AUDIO_PARAM_PCMMODETYPE pcmParams; 3277 InitOMXParams(&pcmParams); 3278 pcmParams.nPortIndex = portIndex; 3279 3280 err = mOMX->getParameter( 3281 mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams)); 3282 3283 CHECK_EQ(err, (status_t)OK); 3284 3285 pcmParams.nChannels = numChannels; 3286 pcmParams.eNumData = OMX_NumericalDataSigned; 3287 pcmParams.bInterleaved = OMX_TRUE; 3288 pcmParams.nBitPerSample = 16; 3289 pcmParams.nSamplingRate = sampleRate; 3290 pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear; 3291 3292 CHECK_EQ(getOMXChannelMapping( 3293 numChannels, pcmParams.eChannelMapping), (status_t)OK); 3294 3295 err = mOMX->setParameter( 3296 mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams)); 3297 3298 CHECK_EQ(err, (status_t)OK); 3299} 3300 3301static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) { 3302 if (isAMRWB) { 3303 if (bps <= 6600) { 3304 return OMX_AUDIO_AMRBandModeWB0; 3305 } else if (bps <= 8850) { 3306 return OMX_AUDIO_AMRBandModeWB1; 3307 } else if (bps <= 12650) { 3308 return OMX_AUDIO_AMRBandModeWB2; 3309 } else if (bps <= 14250) { 3310 return OMX_AUDIO_AMRBandModeWB3; 3311 } else if (bps <= 15850) { 3312 return OMX_AUDIO_AMRBandModeWB4; 3313 } else if (bps <= 18250) { 3314 return OMX_AUDIO_AMRBandModeWB5; 3315 } else if (bps <= 19850) { 3316 return OMX_AUDIO_AMRBandModeWB6; 3317 } else if (bps <= 23050) { 3318 return OMX_AUDIO_AMRBandModeWB7; 3319 } 3320 3321 // 23850 bps 3322 return OMX_AUDIO_AMRBandModeWB8; 3323 } else { // AMRNB 3324 if (bps <= 4750) { 3325 return OMX_AUDIO_AMRBandModeNB0; 3326 } else if (bps <= 5150) { 3327 return OMX_AUDIO_AMRBandModeNB1; 3328 } else if (bps <= 5900) { 3329 return OMX_AUDIO_AMRBandModeNB2; 3330 } else if (bps <= 6700) { 3331 return OMX_AUDIO_AMRBandModeNB3; 3332 } else if (bps <= 7400) { 3333 return OMX_AUDIO_AMRBandModeNB4; 3334 } else if (bps <= 7950) { 3335 return OMX_AUDIO_AMRBandModeNB5; 3336 } else if (bps <= 10200) { 3337 return OMX_AUDIO_AMRBandModeNB6; 3338 } 3339 3340 // 12200 bps 3341 return OMX_AUDIO_AMRBandModeNB7; 3342 } 3343} 3344 3345void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) { 3346 OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput; 3347 3348 OMX_AUDIO_PARAM_AMRTYPE def; 3349 InitOMXParams(&def); 3350 def.nPortIndex = portIndex; 3351 3352 status_t err = 3353 mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def)); 3354 3355 CHECK_EQ(err, (status_t)OK); 3356 3357 def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; 3358 3359 def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate); 3360 err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def)); 3361 CHECK_EQ(err, (status_t)OK); 3362 3363 //////////////////////// 3364 3365 if (mIsEncoder) { 3366 sp<MetaData> format = mSource->getFormat(); 3367 int32_t sampleRate; 3368 int32_t numChannels; 3369 CHECK(format->findInt32(kKeySampleRate, &sampleRate)); 3370 CHECK(format->findInt32(kKeyChannelCount, &numChannels)); 3371 3372 setRawAudioFormat(kPortIndexInput, sampleRate, numChannels); 3373 } 3374} 3375 3376status_t OMXCodec::setAACFormat( 3377 int32_t numChannels, int32_t sampleRate, int32_t bitRate, int32_t aacProfile, bool isADTS) { 3378 if (numChannels > 2) { 3379 ALOGW("Number of channels: (%d) \n", numChannels); 3380 } 3381 3382 if (mIsEncoder) { 3383 if (isADTS) { 3384 return -EINVAL; 3385 } 3386 3387 //////////////// input port //////////////////// 3388 setRawAudioFormat(kPortIndexInput, sampleRate, numChannels); 3389 3390 //////////////// output port //////////////////// 3391 // format 3392 OMX_AUDIO_PARAM_PORTFORMATTYPE format; 3393 InitOMXParams(&format); 3394 format.nPortIndex = kPortIndexOutput; 3395 format.nIndex = 0; 3396 status_t err = OMX_ErrorNone; 3397 while (OMX_ErrorNone == err) { 3398 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat, 3399 &format, sizeof(format)), (status_t)OK); 3400 if (format.eEncoding == OMX_AUDIO_CodingAAC) { 3401 break; 3402 } 3403 format.nIndex++; 3404 } 3405 CHECK_EQ((status_t)OK, err); 3406 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat, 3407 &format, sizeof(format)), (status_t)OK); 3408 3409 // port definition 3410 OMX_PARAM_PORTDEFINITIONTYPE def; 3411 InitOMXParams(&def); 3412 def.nPortIndex = kPortIndexOutput; 3413 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition, 3414 &def, sizeof(def)), (status_t)OK); 3415 def.format.audio.bFlagErrorConcealment = OMX_TRUE; 3416 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; 3417 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition, 3418 &def, sizeof(def)), (status_t)OK); 3419 3420 // profile 3421 OMX_AUDIO_PARAM_AACPROFILETYPE profile; 3422 InitOMXParams(&profile); 3423 profile.nPortIndex = kPortIndexOutput; 3424 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac, 3425 &profile, sizeof(profile)), (status_t)OK); 3426 profile.nChannels = numChannels; 3427 profile.eChannelMode = (numChannels == 1? 3428 OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo); 3429 profile.nSampleRate = sampleRate; 3430 profile.nBitRate = bitRate; 3431 profile.nAudioBandWidth = 0; 3432 profile.nFrameLength = 0; 3433 profile.nAACtools = OMX_AUDIO_AACToolAll; 3434 profile.nAACERtools = OMX_AUDIO_AACERNone; 3435 profile.eAACProfile = (OMX_AUDIO_AACPROFILETYPE) aacProfile; 3436 profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; 3437 err = mOMX->setParameter(mNode, OMX_IndexParamAudioAac, 3438 &profile, sizeof(profile)); 3439 3440 if (err != OK) { 3441 CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed " 3442 "(err = %d)", 3443 err); 3444 return err; 3445 } 3446 } else { 3447 OMX_AUDIO_PARAM_AACPROFILETYPE profile; 3448 InitOMXParams(&profile); 3449 profile.nPortIndex = kPortIndexInput; 3450 3451 status_t err = mOMX->getParameter( 3452 mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); 3453 CHECK_EQ(err, (status_t)OK); 3454 3455 profile.nChannels = numChannels; 3456 profile.nSampleRate = sampleRate; 3457 3458 profile.eAACStreamFormat = 3459 isADTS 3460 ? OMX_AUDIO_AACStreamFormatMP4ADTS 3461 : OMX_AUDIO_AACStreamFormatMP4FF; 3462 3463 err = mOMX->setParameter( 3464 mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); 3465 3466 if (err != OK) { 3467 CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed " 3468 "(err = %d)", 3469 err); 3470 return err; 3471 } 3472 } 3473 3474 return OK; 3475} 3476 3477void OMXCodec::setG711Format(int32_t numChannels) { 3478 CHECK(!mIsEncoder); 3479 setRawAudioFormat(kPortIndexInput, 8000, numChannels); 3480} 3481 3482void OMXCodec::setImageOutputFormat( 3483 OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) { 3484 CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height); 3485 3486#if 0 3487 OMX_INDEXTYPE index; 3488 status_t err = mOMX->get_extension_index( 3489 mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index); 3490 CHECK_EQ(err, (status_t)OK); 3491 3492 err = mOMX->set_config(mNode, index, &format, sizeof(format)); 3493 CHECK_EQ(err, (status_t)OK); 3494#endif 3495 3496 OMX_PARAM_PORTDEFINITIONTYPE def; 3497 InitOMXParams(&def); 3498 def.nPortIndex = kPortIndexOutput; 3499 3500 status_t err = mOMX->getParameter( 3501 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3502 CHECK_EQ(err, (status_t)OK); 3503 3504 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage); 3505 3506 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 3507 3508 CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingUnused); 3509 imageDef->eColorFormat = format; 3510 imageDef->nFrameWidth = width; 3511 imageDef->nFrameHeight = height; 3512 3513 switch (format) { 3514 case OMX_COLOR_FormatYUV420PackedPlanar: 3515 case OMX_COLOR_FormatYUV411Planar: 3516 { 3517 def.nBufferSize = (width * height * 3) / 2; 3518 break; 3519 } 3520 3521 case OMX_COLOR_FormatCbYCrY: 3522 { 3523 def.nBufferSize = width * height * 2; 3524 break; 3525 } 3526 3527 case OMX_COLOR_Format32bitARGB8888: 3528 { 3529 def.nBufferSize = width * height * 4; 3530 break; 3531 } 3532 3533 case OMX_COLOR_Format16bitARGB4444: 3534 case OMX_COLOR_Format16bitARGB1555: 3535 case OMX_COLOR_Format16bitRGB565: 3536 case OMX_COLOR_Format16bitBGR565: 3537 { 3538 def.nBufferSize = width * height * 2; 3539 break; 3540 } 3541 3542 default: 3543 CHECK(!"Should not be here. Unknown color format."); 3544 break; 3545 } 3546 3547 def.nBufferCountActual = def.nBufferCountMin; 3548 3549 err = mOMX->setParameter( 3550 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3551 CHECK_EQ(err, (status_t)OK); 3552} 3553 3554void OMXCodec::setJPEGInputFormat( 3555 OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) { 3556 OMX_PARAM_PORTDEFINITIONTYPE def; 3557 InitOMXParams(&def); 3558 def.nPortIndex = kPortIndexInput; 3559 3560 status_t err = mOMX->getParameter( 3561 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3562 CHECK_EQ(err, (status_t)OK); 3563 3564 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage); 3565 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 3566 3567 CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingJPEG); 3568 imageDef->nFrameWidth = width; 3569 imageDef->nFrameHeight = height; 3570 3571 def.nBufferSize = compressedSize; 3572 def.nBufferCountActual = def.nBufferCountMin; 3573 3574 err = mOMX->setParameter( 3575 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3576 CHECK_EQ(err, (status_t)OK); 3577} 3578 3579void OMXCodec::addCodecSpecificData(const void *data, size_t size) { 3580 CodecSpecificData *specific = 3581 (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1); 3582 3583 specific->mSize = size; 3584 memcpy(specific->mData, data, size); 3585 3586 mCodecSpecificData.push(specific); 3587} 3588 3589void OMXCodec::clearCodecSpecificData() { 3590 for (size_t i = 0; i < mCodecSpecificData.size(); ++i) { 3591 free(mCodecSpecificData.editItemAt(i)); 3592 } 3593 mCodecSpecificData.clear(); 3594 mCodecSpecificDataIndex = 0; 3595} 3596 3597status_t OMXCodec::start(MetaData *meta) { 3598 Mutex::Autolock autoLock(mLock); 3599 3600 if (mState != LOADED) { 3601 return UNKNOWN_ERROR; 3602 } 3603 3604 sp<MetaData> params = new MetaData; 3605 if (mQuirks & kWantsNALFragments) { 3606 params->setInt32(kKeyWantsNALFragments, true); 3607 } 3608 if (meta) { 3609 int64_t startTimeUs = 0; 3610 int64_t timeUs; 3611 if (meta->findInt64(kKeyTime, &timeUs)) { 3612 startTimeUs = timeUs; 3613 } 3614 params->setInt64(kKeyTime, startTimeUs); 3615 } 3616 status_t err = mSource->start(params.get()); 3617 3618 if (err != OK) { 3619 return err; 3620 } 3621 3622 mCodecSpecificDataIndex = 0; 3623 mInitialBufferSubmit = true; 3624 mSignalledEOS = false; 3625 mNoMoreOutputData = false; 3626 mOutputPortSettingsHaveChanged = false; 3627 mSeekTimeUs = -1; 3628 mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC; 3629 mTargetTimeUs = -1; 3630 mFilledBuffers.clear(); 3631 mPaused = false; 3632 3633 return init(); 3634} 3635 3636status_t OMXCodec::stop() { 3637 CODEC_LOGV("stop mState=%d", mState); 3638 3639 Mutex::Autolock autoLock(mLock); 3640 3641 while (isIntermediateState(mState)) { 3642 mAsyncCompletion.wait(mLock); 3643 } 3644 3645 bool isError = false; 3646 switch (mState) { 3647 case LOADED: 3648 break; 3649 3650 case ERROR: 3651 { 3652 OMX_STATETYPE state = OMX_StateInvalid; 3653 status_t err = mOMX->getState(mNode, &state); 3654 CHECK_EQ(err, (status_t)OK); 3655 3656 if (state != OMX_StateExecuting) { 3657 break; 3658 } 3659 // else fall through to the idling code 3660 isError = true; 3661 } 3662 3663 case EXECUTING: 3664 { 3665 setState(EXECUTING_TO_IDLE); 3666 3667 if (mQuirks & kRequiresFlushBeforeShutdown) { 3668 CODEC_LOGV("This component requires a flush before transitioning " 3669 "from EXECUTING to IDLE..."); 3670 3671 bool emulateInputFlushCompletion = 3672 !flushPortAsync(kPortIndexInput); 3673 3674 bool emulateOutputFlushCompletion = 3675 !flushPortAsync(kPortIndexOutput); 3676 3677 if (emulateInputFlushCompletion) { 3678 onCmdComplete(OMX_CommandFlush, kPortIndexInput); 3679 } 3680 3681 if (emulateOutputFlushCompletion) { 3682 onCmdComplete(OMX_CommandFlush, kPortIndexOutput); 3683 } 3684 } else { 3685 mPortStatus[kPortIndexInput] = SHUTTING_DOWN; 3686 mPortStatus[kPortIndexOutput] = SHUTTING_DOWN; 3687 3688 status_t err = 3689 mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 3690 CHECK_EQ(err, (status_t)OK); 3691 } 3692 3693 while (mState != LOADED && mState != ERROR) { 3694 mAsyncCompletion.wait(mLock); 3695 } 3696 3697 if (isError) { 3698 // We were in the ERROR state coming in, so restore that now 3699 // that we've idled the OMX component. 3700 setState(ERROR); 3701 } 3702 3703 break; 3704 } 3705 3706 default: 3707 { 3708 CHECK(!"should not be here."); 3709 break; 3710 } 3711 } 3712 3713 if (mLeftOverBuffer) { 3714 mLeftOverBuffer->release(); 3715 mLeftOverBuffer = NULL; 3716 } 3717 3718 mSource->stop(); 3719 3720 CODEC_LOGV("stopped in state %d", mState); 3721 3722 return OK; 3723} 3724 3725sp<MetaData> OMXCodec::getFormat() { 3726 Mutex::Autolock autoLock(mLock); 3727 3728 return mOutputFormat; 3729} 3730 3731status_t OMXCodec::read( 3732 MediaBuffer **buffer, const ReadOptions *options) { 3733 status_t err = OK; 3734 *buffer = NULL; 3735 3736 Mutex::Autolock autoLock(mLock); 3737 3738 if (mState != EXECUTING && mState != RECONFIGURING) { 3739 return UNKNOWN_ERROR; 3740 } 3741 3742 bool seeking = false; 3743 int64_t seekTimeUs; 3744 ReadOptions::SeekMode seekMode; 3745 if (options && options->getSeekTo(&seekTimeUs, &seekMode)) { 3746 seeking = true; 3747 } 3748 3749 if (mInitialBufferSubmit) { 3750 mInitialBufferSubmit = false; 3751 3752 if (seeking) { 3753 CHECK(seekTimeUs >= 0); 3754 mSeekTimeUs = seekTimeUs; 3755 mSeekMode = seekMode; 3756 3757 // There's no reason to trigger the code below, there's 3758 // nothing to flush yet. 3759 seeking = false; 3760 mPaused = false; 3761 } 3762 3763 drainInputBuffers(); 3764 3765 if (mState == EXECUTING) { 3766 // Otherwise mState == RECONFIGURING and this code will trigger 3767 // after the output port is reenabled. 3768 fillOutputBuffers(); 3769 } 3770 } 3771 3772 if (seeking) { 3773 while (mState == RECONFIGURING) { 3774 if ((err = waitForBufferFilled_l()) != OK) { 3775 return err; 3776 } 3777 } 3778 3779 if (mState != EXECUTING) { 3780 return UNKNOWN_ERROR; 3781 } 3782 3783 CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6); 3784 3785 mSignalledEOS = false; 3786 3787 CHECK(seekTimeUs >= 0); 3788 mSeekTimeUs = seekTimeUs; 3789 mSeekMode = seekMode; 3790 3791 mFilledBuffers.clear(); 3792 3793 CHECK_EQ((int)mState, (int)EXECUTING); 3794 3795 bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput); 3796 bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput); 3797 3798 if (emulateInputFlushCompletion) { 3799 onCmdComplete(OMX_CommandFlush, kPortIndexInput); 3800 } 3801 3802 if (emulateOutputFlushCompletion) { 3803 onCmdComplete(OMX_CommandFlush, kPortIndexOutput); 3804 } 3805 3806 while (mSeekTimeUs >= 0) { 3807 if ((err = waitForBufferFilled_l()) != OK) { 3808 return err; 3809 } 3810 } 3811 } 3812 3813 while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) { 3814 if ((err = waitForBufferFilled_l()) != OK) { 3815 return err; 3816 } 3817 } 3818 3819 if (mState == ERROR) { 3820 return UNKNOWN_ERROR; 3821 } 3822 3823 if (mFilledBuffers.empty()) { 3824 return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM; 3825 } 3826 3827 if (mOutputPortSettingsHaveChanged) { 3828 mOutputPortSettingsHaveChanged = false; 3829 3830 return INFO_FORMAT_CHANGED; 3831 } 3832 3833 size_t index = *mFilledBuffers.begin(); 3834 mFilledBuffers.erase(mFilledBuffers.begin()); 3835 3836 BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index); 3837 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 3838 info->mStatus = OWNED_BY_CLIENT; 3839 3840 info->mMediaBuffer->add_ref(); 3841 if (mSkipCutBuffer != NULL) { 3842 mSkipCutBuffer->submit(info->mMediaBuffer); 3843 } 3844 *buffer = info->mMediaBuffer; 3845 3846 return OK; 3847} 3848 3849void OMXCodec::signalBufferReturned(MediaBuffer *buffer) { 3850 Mutex::Autolock autoLock(mLock); 3851 3852 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 3853 for (size_t i = 0; i < buffers->size(); ++i) { 3854 BufferInfo *info = &buffers->editItemAt(i); 3855 3856 if (info->mMediaBuffer == buffer) { 3857 CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED); 3858 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_CLIENT); 3859 3860 info->mStatus = OWNED_BY_US; 3861 3862 if (buffer->graphicBuffer() == 0) { 3863 fillOutputBuffer(info); 3864 } else { 3865 sp<MetaData> metaData = info->mMediaBuffer->meta_data(); 3866 int32_t rendered = 0; 3867 if (!metaData->findInt32(kKeyRendered, &rendered)) { 3868 rendered = 0; 3869 } 3870 if (!rendered) { 3871 status_t err = cancelBufferToNativeWindow(info); 3872 if (err < 0) { 3873 return; 3874 } 3875 } 3876 3877 info->mStatus = OWNED_BY_NATIVE_WINDOW; 3878 3879 // Dequeue the next buffer from the native window. 3880 BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow(); 3881 if (nextBufInfo == 0) { 3882 return; 3883 } 3884 3885 // Give the buffer to the OMX node to fill. 3886 fillOutputBuffer(nextBufInfo); 3887 } 3888 return; 3889 } 3890 } 3891 3892 CHECK(!"should not be here."); 3893} 3894 3895static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) { 3896 static const char *kNames[] = { 3897 "OMX_IMAGE_CodingUnused", 3898 "OMX_IMAGE_CodingAutoDetect", 3899 "OMX_IMAGE_CodingJPEG", 3900 "OMX_IMAGE_CodingJPEG2K", 3901 "OMX_IMAGE_CodingEXIF", 3902 "OMX_IMAGE_CodingTIFF", 3903 "OMX_IMAGE_CodingGIF", 3904 "OMX_IMAGE_CodingPNG", 3905 "OMX_IMAGE_CodingLZW", 3906 "OMX_IMAGE_CodingBMP", 3907 }; 3908 3909 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3910 3911 if (type < 0 || (size_t)type >= numNames) { 3912 return "UNKNOWN"; 3913 } else { 3914 return kNames[type]; 3915 } 3916} 3917 3918static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) { 3919 static const char *kNames[] = { 3920 "OMX_COLOR_FormatUnused", 3921 "OMX_COLOR_FormatMonochrome", 3922 "OMX_COLOR_Format8bitRGB332", 3923 "OMX_COLOR_Format12bitRGB444", 3924 "OMX_COLOR_Format16bitARGB4444", 3925 "OMX_COLOR_Format16bitARGB1555", 3926 "OMX_COLOR_Format16bitRGB565", 3927 "OMX_COLOR_Format16bitBGR565", 3928 "OMX_COLOR_Format18bitRGB666", 3929 "OMX_COLOR_Format18bitARGB1665", 3930 "OMX_COLOR_Format19bitARGB1666", 3931 "OMX_COLOR_Format24bitRGB888", 3932 "OMX_COLOR_Format24bitBGR888", 3933 "OMX_COLOR_Format24bitARGB1887", 3934 "OMX_COLOR_Format25bitARGB1888", 3935 "OMX_COLOR_Format32bitBGRA8888", 3936 "OMX_COLOR_Format32bitARGB8888", 3937 "OMX_COLOR_FormatYUV411Planar", 3938 "OMX_COLOR_FormatYUV411PackedPlanar", 3939 "OMX_COLOR_FormatYUV420Planar", 3940 "OMX_COLOR_FormatYUV420PackedPlanar", 3941 "OMX_COLOR_FormatYUV420SemiPlanar", 3942 "OMX_COLOR_FormatYUV422Planar", 3943 "OMX_COLOR_FormatYUV422PackedPlanar", 3944 "OMX_COLOR_FormatYUV422SemiPlanar", 3945 "OMX_COLOR_FormatYCbYCr", 3946 "OMX_COLOR_FormatYCrYCb", 3947 "OMX_COLOR_FormatCbYCrY", 3948 "OMX_COLOR_FormatCrYCbY", 3949 "OMX_COLOR_FormatYUV444Interleaved", 3950 "OMX_COLOR_FormatRawBayer8bit", 3951 "OMX_COLOR_FormatRawBayer10bit", 3952 "OMX_COLOR_FormatRawBayer8bitcompressed", 3953 "OMX_COLOR_FormatL2", 3954 "OMX_COLOR_FormatL4", 3955 "OMX_COLOR_FormatL8", 3956 "OMX_COLOR_FormatL16", 3957 "OMX_COLOR_FormatL24", 3958 "OMX_COLOR_FormatL32", 3959 "OMX_COLOR_FormatYUV420PackedSemiPlanar", 3960 "OMX_COLOR_FormatYUV422PackedSemiPlanar", 3961 "OMX_COLOR_Format18BitBGR666", 3962 "OMX_COLOR_Format24BitARGB6666", 3963 "OMX_COLOR_Format24BitABGR6666", 3964 }; 3965 3966 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3967 3968 if (type == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar) { 3969 return "OMX_TI_COLOR_FormatYUV420PackedSemiPlanar"; 3970 } else if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) { 3971 return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar"; 3972 } else if (type < 0 || (size_t)type >= numNames) { 3973 return "UNKNOWN"; 3974 } else { 3975 return kNames[type]; 3976 } 3977} 3978 3979static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) { 3980 static const char *kNames[] = { 3981 "OMX_VIDEO_CodingUnused", 3982 "OMX_VIDEO_CodingAutoDetect", 3983 "OMX_VIDEO_CodingMPEG2", 3984 "OMX_VIDEO_CodingH263", 3985 "OMX_VIDEO_CodingMPEG4", 3986 "OMX_VIDEO_CodingWMV", 3987 "OMX_VIDEO_CodingRV", 3988 "OMX_VIDEO_CodingAVC", 3989 "OMX_VIDEO_CodingMJPEG", 3990 }; 3991 3992 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3993 3994 if (type < 0 || (size_t)type >= numNames) { 3995 return "UNKNOWN"; 3996 } else { 3997 return kNames[type]; 3998 } 3999} 4000 4001static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) { 4002 static const char *kNames[] = { 4003 "OMX_AUDIO_CodingUnused", 4004 "OMX_AUDIO_CodingAutoDetect", 4005 "OMX_AUDIO_CodingPCM", 4006 "OMX_AUDIO_CodingADPCM", 4007 "OMX_AUDIO_CodingAMR", 4008 "OMX_AUDIO_CodingGSMFR", 4009 "OMX_AUDIO_CodingGSMEFR", 4010 "OMX_AUDIO_CodingGSMHR", 4011 "OMX_AUDIO_CodingPDCFR", 4012 "OMX_AUDIO_CodingPDCEFR", 4013 "OMX_AUDIO_CodingPDCHR", 4014 "OMX_AUDIO_CodingTDMAFR", 4015 "OMX_AUDIO_CodingTDMAEFR", 4016 "OMX_AUDIO_CodingQCELP8", 4017 "OMX_AUDIO_CodingQCELP13", 4018 "OMX_AUDIO_CodingEVRC", 4019 "OMX_AUDIO_CodingSMV", 4020 "OMX_AUDIO_CodingG711", 4021 "OMX_AUDIO_CodingG723", 4022 "OMX_AUDIO_CodingG726", 4023 "OMX_AUDIO_CodingG729", 4024 "OMX_AUDIO_CodingAAC", 4025 "OMX_AUDIO_CodingMP3", 4026 "OMX_AUDIO_CodingSBC", 4027 "OMX_AUDIO_CodingVORBIS", 4028 "OMX_AUDIO_CodingWMA", 4029 "OMX_AUDIO_CodingRA", 4030 "OMX_AUDIO_CodingMIDI", 4031 }; 4032 4033 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 4034 4035 if (type < 0 || (size_t)type >= numNames) { 4036 return "UNKNOWN"; 4037 } else { 4038 return kNames[type]; 4039 } 4040} 4041 4042static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) { 4043 static const char *kNames[] = { 4044 "OMX_AUDIO_PCMModeLinear", 4045 "OMX_AUDIO_PCMModeALaw", 4046 "OMX_AUDIO_PCMModeMULaw", 4047 }; 4048 4049 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 4050 4051 if (type < 0 || (size_t)type >= numNames) { 4052 return "UNKNOWN"; 4053 } else { 4054 return kNames[type]; 4055 } 4056} 4057 4058static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) { 4059 static const char *kNames[] = { 4060 "OMX_AUDIO_AMRBandModeUnused", 4061 "OMX_AUDIO_AMRBandModeNB0", 4062 "OMX_AUDIO_AMRBandModeNB1", 4063 "OMX_AUDIO_AMRBandModeNB2", 4064 "OMX_AUDIO_AMRBandModeNB3", 4065 "OMX_AUDIO_AMRBandModeNB4", 4066 "OMX_AUDIO_AMRBandModeNB5", 4067 "OMX_AUDIO_AMRBandModeNB6", 4068 "OMX_AUDIO_AMRBandModeNB7", 4069 "OMX_AUDIO_AMRBandModeWB0", 4070 "OMX_AUDIO_AMRBandModeWB1", 4071 "OMX_AUDIO_AMRBandModeWB2", 4072 "OMX_AUDIO_AMRBandModeWB3", 4073 "OMX_AUDIO_AMRBandModeWB4", 4074 "OMX_AUDIO_AMRBandModeWB5", 4075 "OMX_AUDIO_AMRBandModeWB6", 4076 "OMX_AUDIO_AMRBandModeWB7", 4077 "OMX_AUDIO_AMRBandModeWB8", 4078 }; 4079 4080 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 4081 4082 if (type < 0 || (size_t)type >= numNames) { 4083 return "UNKNOWN"; 4084 } else { 4085 return kNames[type]; 4086 } 4087} 4088 4089static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) { 4090 static const char *kNames[] = { 4091 "OMX_AUDIO_AMRFrameFormatConformance", 4092 "OMX_AUDIO_AMRFrameFormatIF1", 4093 "OMX_AUDIO_AMRFrameFormatIF2", 4094 "OMX_AUDIO_AMRFrameFormatFSF", 4095 "OMX_AUDIO_AMRFrameFormatRTPPayload", 4096 "OMX_AUDIO_AMRFrameFormatITU", 4097 }; 4098 4099 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 4100 4101 if (type < 0 || (size_t)type >= numNames) { 4102 return "UNKNOWN"; 4103 } else { 4104 return kNames[type]; 4105 } 4106} 4107 4108void OMXCodec::dumpPortStatus(OMX_U32 portIndex) { 4109 OMX_PARAM_PORTDEFINITIONTYPE def; 4110 InitOMXParams(&def); 4111 def.nPortIndex = portIndex; 4112 4113 status_t err = mOMX->getParameter( 4114 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 4115 CHECK_EQ(err, (status_t)OK); 4116 4117 printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output"); 4118 4119 CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput) 4120 || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput)); 4121 4122 printf(" nBufferCountActual = %ld\n", def.nBufferCountActual); 4123 printf(" nBufferCountMin = %ld\n", def.nBufferCountMin); 4124 printf(" nBufferSize = %ld\n", def.nBufferSize); 4125 4126 switch (def.eDomain) { 4127 case OMX_PortDomainImage: 4128 { 4129 const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 4130 4131 printf("\n"); 4132 printf(" // Image\n"); 4133 printf(" nFrameWidth = %ld\n", imageDef->nFrameWidth); 4134 printf(" nFrameHeight = %ld\n", imageDef->nFrameHeight); 4135 printf(" nStride = %ld\n", imageDef->nStride); 4136 4137 printf(" eCompressionFormat = %s\n", 4138 imageCompressionFormatString(imageDef->eCompressionFormat)); 4139 4140 printf(" eColorFormat = %s\n", 4141 colorFormatString(imageDef->eColorFormat)); 4142 4143 break; 4144 } 4145 4146 case OMX_PortDomainVideo: 4147 { 4148 OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video; 4149 4150 printf("\n"); 4151 printf(" // Video\n"); 4152 printf(" nFrameWidth = %ld\n", videoDef->nFrameWidth); 4153 printf(" nFrameHeight = %ld\n", videoDef->nFrameHeight); 4154 printf(" nStride = %ld\n", videoDef->nStride); 4155 4156 printf(" eCompressionFormat = %s\n", 4157 videoCompressionFormatString(videoDef->eCompressionFormat)); 4158 4159 printf(" eColorFormat = %s\n", 4160 colorFormatString(videoDef->eColorFormat)); 4161 4162 break; 4163 } 4164 4165 case OMX_PortDomainAudio: 4166 { 4167 OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio; 4168 4169 printf("\n"); 4170 printf(" // Audio\n"); 4171 printf(" eEncoding = %s\n", 4172 audioCodingTypeString(audioDef->eEncoding)); 4173 4174 if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) { 4175 OMX_AUDIO_PARAM_PCMMODETYPE params; 4176 InitOMXParams(¶ms); 4177 params.nPortIndex = portIndex; 4178 4179 err = mOMX->getParameter( 4180 mNode, OMX_IndexParamAudioPcm, ¶ms, sizeof(params)); 4181 CHECK_EQ(err, (status_t)OK); 4182 4183 printf(" nSamplingRate = %ld\n", params.nSamplingRate); 4184 printf(" nChannels = %ld\n", params.nChannels); 4185 printf(" bInterleaved = %d\n", params.bInterleaved); 4186 printf(" nBitPerSample = %ld\n", params.nBitPerSample); 4187 4188 printf(" eNumData = %s\n", 4189 params.eNumData == OMX_NumericalDataSigned 4190 ? "signed" : "unsigned"); 4191 4192 printf(" ePCMMode = %s\n", audioPCMModeString(params.ePCMMode)); 4193 } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) { 4194 OMX_AUDIO_PARAM_AMRTYPE amr; 4195 InitOMXParams(&amr); 4196 amr.nPortIndex = portIndex; 4197 4198 err = mOMX->getParameter( 4199 mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr)); 4200 CHECK_EQ(err, (status_t)OK); 4201 4202 printf(" nChannels = %ld\n", amr.nChannels); 4203 printf(" eAMRBandMode = %s\n", 4204 amrBandModeString(amr.eAMRBandMode)); 4205 printf(" eAMRFrameFormat = %s\n", 4206 amrFrameFormatString(amr.eAMRFrameFormat)); 4207 } 4208 4209 break; 4210 } 4211 4212 default: 4213 { 4214 printf(" // Unknown\n"); 4215 break; 4216 } 4217 } 4218 4219 printf("}\n"); 4220} 4221 4222status_t OMXCodec::initNativeWindow() { 4223 // Enable use of a GraphicBuffer as the output for this node. This must 4224 // happen before getting the IndexParamPortDefinition parameter because it 4225 // will affect the pixel format that the node reports. 4226 status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE); 4227 if (err != 0) { 4228 return err; 4229 } 4230 4231 return OK; 4232} 4233 4234void OMXCodec::initNativeWindowCrop() { 4235 int32_t left, top, right, bottom; 4236 4237 CHECK(mOutputFormat->findRect( 4238 kKeyCropRect, 4239 &left, &top, &right, &bottom)); 4240 4241 android_native_rect_t crop; 4242 crop.left = left; 4243 crop.top = top; 4244 crop.right = right + 1; 4245 crop.bottom = bottom + 1; 4246 4247 // We'll ignore any errors here, if the surface is 4248 // already invalid, we'll know soon enough. 4249 native_window_set_crop(mNativeWindow.get(), &crop); 4250} 4251 4252void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) { 4253 mOutputFormat = new MetaData; 4254 mOutputFormat->setCString(kKeyDecoderComponent, mComponentName); 4255 if (mIsEncoder) { 4256 int32_t timeScale; 4257 if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) { 4258 mOutputFormat->setInt32(kKeyTimeScale, timeScale); 4259 } 4260 } 4261 4262 OMX_PARAM_PORTDEFINITIONTYPE def; 4263 InitOMXParams(&def); 4264 def.nPortIndex = kPortIndexOutput; 4265 4266 status_t err = mOMX->getParameter( 4267 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 4268 CHECK_EQ(err, (status_t)OK); 4269 4270 switch (def.eDomain) { 4271 case OMX_PortDomainImage: 4272 { 4273 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 4274 CHECK_EQ((int)imageDef->eCompressionFormat, 4275 (int)OMX_IMAGE_CodingUnused); 4276 4277 mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW); 4278 mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat); 4279 mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth); 4280 mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight); 4281 break; 4282 } 4283 4284 case OMX_PortDomainAudio: 4285 { 4286 OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio; 4287 4288 if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) { 4289 OMX_AUDIO_PARAM_PCMMODETYPE params; 4290 InitOMXParams(¶ms); 4291 params.nPortIndex = kPortIndexOutput; 4292 4293 err = mOMX->getParameter( 4294 mNode, OMX_IndexParamAudioPcm, ¶ms, sizeof(params)); 4295 CHECK_EQ(err, (status_t)OK); 4296 4297 CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned); 4298 CHECK_EQ(params.nBitPerSample, 16u); 4299 CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear); 4300 4301 int32_t numChannels, sampleRate; 4302 inputFormat->findInt32(kKeyChannelCount, &numChannels); 4303 inputFormat->findInt32(kKeySampleRate, &sampleRate); 4304 4305 if ((OMX_U32)numChannels != params.nChannels) { 4306 ALOGV("Codec outputs a different number of channels than " 4307 "the input stream contains (contains %d channels, " 4308 "codec outputs %ld channels).", 4309 numChannels, params.nChannels); 4310 } 4311 4312 if (sampleRate != (int32_t)params.nSamplingRate) { 4313 ALOGV("Codec outputs at different sampling rate than " 4314 "what the input stream contains (contains data at " 4315 "%d Hz, codec outputs %lu Hz)", 4316 sampleRate, params.nSamplingRate); 4317 } 4318 4319 mOutputFormat->setCString( 4320 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW); 4321 4322 // Use the codec-advertised number of channels, as some 4323 // codecs appear to output stereo even if the input data is 4324 // mono. If we know the codec lies about this information, 4325 // use the actual number of channels instead. 4326 mOutputFormat->setInt32( 4327 kKeyChannelCount, 4328 (mQuirks & kDecoderLiesAboutNumberOfChannels) 4329 ? numChannels : params.nChannels); 4330 4331 mOutputFormat->setInt32(kKeySampleRate, params.nSamplingRate); 4332 } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) { 4333 OMX_AUDIO_PARAM_AMRTYPE amr; 4334 InitOMXParams(&amr); 4335 amr.nPortIndex = kPortIndexOutput; 4336 4337 err = mOMX->getParameter( 4338 mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr)); 4339 CHECK_EQ(err, (status_t)OK); 4340 4341 CHECK_EQ(amr.nChannels, 1u); 4342 mOutputFormat->setInt32(kKeyChannelCount, 1); 4343 4344 if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0 4345 && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) { 4346 mOutputFormat->setCString( 4347 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB); 4348 mOutputFormat->setInt32(kKeySampleRate, 8000); 4349 } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0 4350 && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) { 4351 mOutputFormat->setCString( 4352 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB); 4353 mOutputFormat->setInt32(kKeySampleRate, 16000); 4354 } else { 4355 CHECK(!"Unknown AMR band mode."); 4356 } 4357 } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) { 4358 mOutputFormat->setCString( 4359 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC); 4360 int32_t numChannels, sampleRate, bitRate; 4361 inputFormat->findInt32(kKeyChannelCount, &numChannels); 4362 inputFormat->findInt32(kKeySampleRate, &sampleRate); 4363 inputFormat->findInt32(kKeyBitRate, &bitRate); 4364 mOutputFormat->setInt32(kKeyChannelCount, numChannels); 4365 mOutputFormat->setInt32(kKeySampleRate, sampleRate); 4366 mOutputFormat->setInt32(kKeyBitRate, bitRate); 4367 } else { 4368 CHECK(!"Should not be here. Unknown audio encoding."); 4369 } 4370 break; 4371 } 4372 4373 case OMX_PortDomainVideo: 4374 { 4375 OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video; 4376 4377 if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) { 4378 mOutputFormat->setCString( 4379 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW); 4380 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) { 4381 mOutputFormat->setCString( 4382 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4); 4383 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) { 4384 mOutputFormat->setCString( 4385 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263); 4386 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) { 4387 mOutputFormat->setCString( 4388 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC); 4389 } else { 4390 CHECK(!"Unknown compression format."); 4391 } 4392 4393 mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth); 4394 mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight); 4395 mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat); 4396 4397 if (!mIsEncoder) { 4398 OMX_CONFIG_RECTTYPE rect; 4399 InitOMXParams(&rect); 4400 rect.nPortIndex = kPortIndexOutput; 4401 status_t err = 4402 mOMX->getConfig( 4403 mNode, OMX_IndexConfigCommonOutputCrop, 4404 &rect, sizeof(rect)); 4405 4406 CODEC_LOGI( 4407 "video dimensions are %ld x %ld", 4408 video_def->nFrameWidth, video_def->nFrameHeight); 4409 4410 if (err == OK) { 4411 CHECK_GE(rect.nLeft, 0); 4412 CHECK_GE(rect.nTop, 0); 4413 CHECK_GE(rect.nWidth, 0u); 4414 CHECK_GE(rect.nHeight, 0u); 4415 CHECK_LE(rect.nLeft + rect.nWidth - 1, video_def->nFrameWidth); 4416 CHECK_LE(rect.nTop + rect.nHeight - 1, video_def->nFrameHeight); 4417 4418 mOutputFormat->setRect( 4419 kKeyCropRect, 4420 rect.nLeft, 4421 rect.nTop, 4422 rect.nLeft + rect.nWidth - 1, 4423 rect.nTop + rect.nHeight - 1); 4424 4425 CODEC_LOGI( 4426 "Crop rect is %ld x %ld @ (%ld, %ld)", 4427 rect.nWidth, rect.nHeight, rect.nLeft, rect.nTop); 4428 } else { 4429 mOutputFormat->setRect( 4430 kKeyCropRect, 4431 0, 0, 4432 video_def->nFrameWidth - 1, 4433 video_def->nFrameHeight - 1); 4434 } 4435 4436 if (mNativeWindow != NULL) { 4437 initNativeWindowCrop(); 4438 } 4439 } 4440 break; 4441 } 4442 4443 default: 4444 { 4445 CHECK(!"should not be here, neither audio nor video."); 4446 break; 4447 } 4448 } 4449 4450 // If the input format contains rotation information, flag the output 4451 // format accordingly. 4452 4453 int32_t rotationDegrees; 4454 if (mSource->getFormat()->findInt32(kKeyRotation, &rotationDegrees)) { 4455 mOutputFormat->setInt32(kKeyRotation, rotationDegrees); 4456 } 4457} 4458 4459status_t OMXCodec::pause() { 4460 Mutex::Autolock autoLock(mLock); 4461 4462 mPaused = true; 4463 4464 return OK; 4465} 4466 4467//////////////////////////////////////////////////////////////////////////////// 4468 4469status_t QueryCodecs( 4470 const sp<IOMX> &omx, 4471 const char *mime, bool queryDecoders, bool hwCodecOnly, 4472 Vector<CodecCapabilities> *results) { 4473 Vector<String8> matchingCodecs; 4474 results->clear(); 4475 4476 OMXCodec::findMatchingCodecs(mime, 4477 !queryDecoders /*createEncoder*/, 4478 NULL /*matchComponentName*/, 4479 hwCodecOnly ? OMXCodec::kHardwareCodecsOnly : 0 /*flags*/, 4480 &matchingCodecs); 4481 4482 for (size_t c = 0; c < matchingCodecs.size(); c++) { 4483 const char *componentName = matchingCodecs.itemAt(c).string(); 4484 4485 results->push(); 4486 CodecCapabilities *caps = &results->editItemAt(results->size() - 1); 4487 4488 status_t err = 4489 QueryCodec(omx, componentName, mime, !queryDecoders, caps); 4490 4491 if (err != OK) { 4492 results->removeAt(results->size() - 1); 4493 } 4494 } 4495 4496 return OK; 4497} 4498 4499status_t QueryCodec( 4500 const sp<IOMX> &omx, 4501 const char *componentName, const char *mime, 4502 bool isEncoder, 4503 CodecCapabilities *caps) { 4504 if (strncmp(componentName, "OMX.", 4)) { 4505 // Not an OpenMax component but a software codec. 4506 4507 caps->mComponentName = componentName; 4508 return OK; 4509 } 4510 4511 sp<OMXCodecObserver> observer = new OMXCodecObserver; 4512 IOMX::node_id node; 4513 status_t err = omx->allocateNode(componentName, observer, &node); 4514 4515 if (err != OK) { 4516 return err; 4517 } 4518 4519 OMXCodec::setComponentRole(omx, node, isEncoder, mime); 4520 4521 caps->mComponentName = componentName; 4522 4523 OMX_VIDEO_PARAM_PROFILELEVELTYPE param; 4524 InitOMXParams(¶m); 4525 4526 param.nPortIndex = !isEncoder ? 0 : 1; 4527 4528 for (param.nProfileIndex = 0;; ++param.nProfileIndex) { 4529 err = omx->getParameter( 4530 node, OMX_IndexParamVideoProfileLevelQuerySupported, 4531 ¶m, sizeof(param)); 4532 4533 if (err != OK) { 4534 break; 4535 } 4536 4537 CodecProfileLevel profileLevel; 4538 profileLevel.mProfile = param.eProfile; 4539 profileLevel.mLevel = param.eLevel; 4540 4541 caps->mProfileLevels.push(profileLevel); 4542 } 4543 4544 // Color format query 4545 OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat; 4546 InitOMXParams(&portFormat); 4547 portFormat.nPortIndex = !isEncoder ? 1 : 0; 4548 for (portFormat.nIndex = 0;; ++portFormat.nIndex) { 4549 err = omx->getParameter( 4550 node, OMX_IndexParamVideoPortFormat, 4551 &portFormat, sizeof(portFormat)); 4552 if (err != OK) { 4553 break; 4554 } 4555 caps->mColorFormats.push(portFormat.eColorFormat); 4556 } 4557 4558 CHECK_EQ(omx->freeNode(node), (status_t)OK); 4559 4560 return OK; 4561} 4562 4563status_t QueryCodecs( 4564 const sp<IOMX> &omx, 4565 const char *mimeType, bool queryDecoders, 4566 Vector<CodecCapabilities> *results) { 4567 return QueryCodecs(omx, mimeType, queryDecoders, false /*hwCodecOnly*/, results); 4568} 4569 4570void OMXCodec::restorePatchedDataPointer(BufferInfo *info) { 4571 CHECK(mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)); 4572 CHECK(mOMXLivesLocally); 4573 4574 OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)info->mBuffer; 4575 header->pBuffer = (OMX_U8 *)info->mData; 4576} 4577 4578// These are supposed be equivalent to the logic in 4579// "audio_channel_out_mask_from_count". 4580status_t getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]) { 4581 switch (numChannels) { 4582 case 1: 4583 map[0] = OMX_AUDIO_ChannelCF; 4584 break; 4585 case 2: 4586 map[0] = OMX_AUDIO_ChannelLF; 4587 map[1] = OMX_AUDIO_ChannelRF; 4588 break; 4589 case 3: 4590 map[0] = OMX_AUDIO_ChannelLF; 4591 map[1] = OMX_AUDIO_ChannelRF; 4592 map[2] = OMX_AUDIO_ChannelCF; 4593 break; 4594 case 4: 4595 map[0] = OMX_AUDIO_ChannelLF; 4596 map[1] = OMX_AUDIO_ChannelRF; 4597 map[2] = OMX_AUDIO_ChannelLR; 4598 map[3] = OMX_AUDIO_ChannelRR; 4599 break; 4600 case 5: 4601 map[0] = OMX_AUDIO_ChannelLF; 4602 map[1] = OMX_AUDIO_ChannelRF; 4603 map[2] = OMX_AUDIO_ChannelCF; 4604 map[3] = OMX_AUDIO_ChannelLR; 4605 map[4] = OMX_AUDIO_ChannelRR; 4606 break; 4607 case 6: 4608 map[0] = OMX_AUDIO_ChannelLF; 4609 map[1] = OMX_AUDIO_ChannelRF; 4610 map[2] = OMX_AUDIO_ChannelCF; 4611 map[3] = OMX_AUDIO_ChannelLFE; 4612 map[4] = OMX_AUDIO_ChannelLR; 4613 map[5] = OMX_AUDIO_ChannelRR; 4614 break; 4615 case 7: 4616 map[0] = OMX_AUDIO_ChannelLF; 4617 map[1] = OMX_AUDIO_ChannelRF; 4618 map[2] = OMX_AUDIO_ChannelCF; 4619 map[3] = OMX_AUDIO_ChannelLFE; 4620 map[4] = OMX_AUDIO_ChannelLR; 4621 map[5] = OMX_AUDIO_ChannelRR; 4622 map[6] = OMX_AUDIO_ChannelCS; 4623 break; 4624 case 8: 4625 map[0] = OMX_AUDIO_ChannelLF; 4626 map[1] = OMX_AUDIO_ChannelRF; 4627 map[2] = OMX_AUDIO_ChannelCF; 4628 map[3] = OMX_AUDIO_ChannelLFE; 4629 map[4] = OMX_AUDIO_ChannelLR; 4630 map[5] = OMX_AUDIO_ChannelRR; 4631 map[6] = OMX_AUDIO_ChannelLS; 4632 map[7] = OMX_AUDIO_ChannelRS; 4633 break; 4634 default: 4635 return -EINVAL; 4636 } 4637 4638 return OK; 4639} 4640 4641} // namespace android 4642