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