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