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