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