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