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