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