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