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