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