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