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