OMXCodec.cpp revision 965e4239ca1cf6c824c1f8ce23116f9ba8cf6ebd
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 CHECK(!mDecodingTimeList.empty()); 1987 List<int64_t>::iterator it = mDecodingTimeList.begin(); 1988 int64_t timeUs = *it; 1989 1990 // If the output buffer is codec specific configuration, 1991 // do not remove the decoding time from the list. 1992 if (!isCodecSpecific) { 1993 mDecodingTimeList.erase(it); 1994 } 1995 return timeUs; 1996} 1997 1998void OMXCodec::on_message(const omx_message &msg) { 1999 if (mState == ERROR) { 2000 LOGW("Dropping OMX message - we're in ERROR state."); 2001 return; 2002 } 2003 2004 switch (msg.type) { 2005 case omx_message::EVENT: 2006 { 2007 onEvent( 2008 msg.u.event_data.event, msg.u.event_data.data1, 2009 msg.u.event_data.data2); 2010 2011 break; 2012 } 2013 2014 case omx_message::EMPTY_BUFFER_DONE: 2015 { 2016 IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer; 2017 2018 CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer); 2019 2020 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 2021 size_t i = 0; 2022 while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) { 2023 ++i; 2024 } 2025 2026 CHECK(i < buffers->size()); 2027 if ((*buffers)[i].mStatus != OWNED_BY_COMPONENT) { 2028 LOGW("We already own input buffer %p, yet received " 2029 "an EMPTY_BUFFER_DONE.", buffer); 2030 } 2031 2032 BufferInfo* info = &buffers->editItemAt(i); 2033 info->mStatus = OWNED_BY_US; 2034 2035 // Buffer could not be released until empty buffer done is called. 2036 if (info->mMediaBuffer != NULL) { 2037 if (mIsEncoder && 2038 (mQuirks & kAvoidMemcopyInputRecordingFrames)) { 2039 // If zero-copy mode is enabled this will send the 2040 // input buffer back to the upstream source. 2041 restorePatchedDataPointer(info); 2042 } 2043 2044 info->mMediaBuffer->release(); 2045 info->mMediaBuffer = NULL; 2046 } 2047 2048 if (mPortStatus[kPortIndexInput] == DISABLING) { 2049 CODEC_LOGV("Port is disabled, freeing buffer %p", buffer); 2050 2051 status_t err = freeBuffer(kPortIndexInput, i); 2052 CHECK_EQ(err, (status_t)OK); 2053 } else if (mState != ERROR 2054 && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) { 2055 CHECK_EQ((int)mPortStatus[kPortIndexInput], (int)ENABLED); 2056 drainInputBuffer(&buffers->editItemAt(i)); 2057 } 2058 break; 2059 } 2060 2061 case omx_message::FILL_BUFFER_DONE: 2062 { 2063 IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer; 2064 OMX_U32 flags = msg.u.extended_buffer_data.flags; 2065 2066 CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))", 2067 buffer, 2068 msg.u.extended_buffer_data.range_length, 2069 flags, 2070 msg.u.extended_buffer_data.timestamp, 2071 msg.u.extended_buffer_data.timestamp / 1E6); 2072 2073 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 2074 size_t i = 0; 2075 while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) { 2076 ++i; 2077 } 2078 2079 CHECK(i < buffers->size()); 2080 BufferInfo *info = &buffers->editItemAt(i); 2081 2082 if (info->mStatus != OWNED_BY_COMPONENT) { 2083 LOGW("We already own output buffer %p, yet received " 2084 "a FILL_BUFFER_DONE.", buffer); 2085 } 2086 2087 info->mStatus = OWNED_BY_US; 2088 2089 if (mPortStatus[kPortIndexOutput] == DISABLING) { 2090 CODEC_LOGV("Port is disabled, freeing buffer %p", buffer); 2091 2092 status_t err = freeBuffer(kPortIndexOutput, i); 2093 CHECK_EQ(err, (status_t)OK); 2094 2095#if 0 2096 } else if (mPortStatus[kPortIndexOutput] == ENABLED 2097 && (flags & OMX_BUFFERFLAG_EOS)) { 2098 CODEC_LOGV("No more output data."); 2099 mNoMoreOutputData = true; 2100 mBufferFilled.signal(); 2101#endif 2102 } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) { 2103 CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED); 2104 2105 if (info->mMediaBuffer == NULL) { 2106 CHECK(mOMXLivesLocally); 2107 CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts); 2108 CHECK(mQuirks & kDefersOutputBufferAllocation); 2109 2110 // The qcom video decoders on Nexus don't actually allocate 2111 // output buffer memory on a call to OMX_AllocateBuffer 2112 // the "pBuffer" member of the OMX_BUFFERHEADERTYPE 2113 // structure is only filled in later. 2114 2115 info->mMediaBuffer = new MediaBuffer( 2116 msg.u.extended_buffer_data.data_ptr, 2117 info->mSize); 2118 info->mMediaBuffer->setObserver(this); 2119 } 2120 2121 MediaBuffer *buffer = info->mMediaBuffer; 2122 bool isGraphicBuffer = buffer->graphicBuffer() != NULL; 2123 2124 if (!isGraphicBuffer 2125 && msg.u.extended_buffer_data.range_offset 2126 + msg.u.extended_buffer_data.range_length 2127 > buffer->size()) { 2128 CODEC_LOGE( 2129 "Codec lied about its buffer size requirements, " 2130 "sending a buffer larger than the originally " 2131 "advertised size in FILL_BUFFER_DONE!"); 2132 } 2133 buffer->set_range( 2134 msg.u.extended_buffer_data.range_offset, 2135 msg.u.extended_buffer_data.range_length); 2136 2137 buffer->meta_data()->clear(); 2138 2139 buffer->meta_data()->setInt64( 2140 kKeyTime, msg.u.extended_buffer_data.timestamp); 2141 2142 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) { 2143 buffer->meta_data()->setInt32(kKeyIsSyncFrame, true); 2144 } 2145 bool isCodecSpecific = false; 2146 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) { 2147 buffer->meta_data()->setInt32(kKeyIsCodecConfig, true); 2148 isCodecSpecific = true; 2149 } 2150 2151 if (isGraphicBuffer || mQuirks & kOutputBuffersAreUnreadable) { 2152 buffer->meta_data()->setInt32(kKeyIsUnreadable, true); 2153 } 2154 2155 if (mIsEncoder) { 2156 int64_t decodingTimeUs = retrieveDecodingTimeUs(isCodecSpecific); 2157 buffer->meta_data()->setInt64(kKeyDecodingTime, decodingTimeUs); 2158 } 2159 2160 buffer->meta_data()->setPointer( 2161 kKeyPlatformPrivate, 2162 msg.u.extended_buffer_data.platform_private); 2163 2164 buffer->meta_data()->setPointer( 2165 kKeyBufferID, 2166 msg.u.extended_buffer_data.buffer); 2167 2168 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) { 2169 CODEC_LOGV("No more output data."); 2170 mNoMoreOutputData = true; 2171 } 2172 2173 if (mTargetTimeUs >= 0) { 2174 CHECK(msg.u.extended_buffer_data.timestamp <= mTargetTimeUs); 2175 2176 if (msg.u.extended_buffer_data.timestamp < mTargetTimeUs) { 2177 CODEC_LOGV( 2178 "skipping output buffer at timestamp %lld us", 2179 msg.u.extended_buffer_data.timestamp); 2180 2181 fillOutputBuffer(info); 2182 break; 2183 } 2184 2185 CODEC_LOGV( 2186 "returning output buffer at target timestamp " 2187 "%lld us", 2188 msg.u.extended_buffer_data.timestamp); 2189 2190 mTargetTimeUs = -1; 2191 } 2192 2193 mFilledBuffers.push_back(i); 2194 mBufferFilled.signal(); 2195 if (mIsEncoder) { 2196 sched_yield(); 2197 } 2198 } 2199 2200 break; 2201 } 2202 2203 default: 2204 { 2205 CHECK(!"should not be here."); 2206 break; 2207 } 2208 } 2209} 2210 2211// Has the format changed in any way that the client would have to be aware of? 2212static bool formatHasNotablyChanged( 2213 const sp<MetaData> &from, const sp<MetaData> &to) { 2214 if (from.get() == NULL && to.get() == NULL) { 2215 return false; 2216 } 2217 2218 if ((from.get() == NULL && to.get() != NULL) 2219 || (from.get() != NULL && to.get() == NULL)) { 2220 return true; 2221 } 2222 2223 const char *mime_from, *mime_to; 2224 CHECK(from->findCString(kKeyMIMEType, &mime_from)); 2225 CHECK(to->findCString(kKeyMIMEType, &mime_to)); 2226 2227 if (strcasecmp(mime_from, mime_to)) { 2228 return true; 2229 } 2230 2231 if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) { 2232 int32_t colorFormat_from, colorFormat_to; 2233 CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from)); 2234 CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to)); 2235 2236 if (colorFormat_from != colorFormat_to) { 2237 return true; 2238 } 2239 2240 int32_t width_from, width_to; 2241 CHECK(from->findInt32(kKeyWidth, &width_from)); 2242 CHECK(to->findInt32(kKeyWidth, &width_to)); 2243 2244 if (width_from != width_to) { 2245 return true; 2246 } 2247 2248 int32_t height_from, height_to; 2249 CHECK(from->findInt32(kKeyHeight, &height_from)); 2250 CHECK(to->findInt32(kKeyHeight, &height_to)); 2251 2252 if (height_from != height_to) { 2253 return true; 2254 } 2255 2256 int32_t left_from, top_from, right_from, bottom_from; 2257 CHECK(from->findRect( 2258 kKeyCropRect, 2259 &left_from, &top_from, &right_from, &bottom_from)); 2260 2261 int32_t left_to, top_to, right_to, bottom_to; 2262 CHECK(to->findRect( 2263 kKeyCropRect, 2264 &left_to, &top_to, &right_to, &bottom_to)); 2265 2266 if (left_to != left_from || top_to != top_from 2267 || right_to != right_from || bottom_to != bottom_from) { 2268 return true; 2269 } 2270 } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) { 2271 int32_t numChannels_from, numChannels_to; 2272 CHECK(from->findInt32(kKeyChannelCount, &numChannels_from)); 2273 CHECK(to->findInt32(kKeyChannelCount, &numChannels_to)); 2274 2275 if (numChannels_from != numChannels_to) { 2276 return true; 2277 } 2278 2279 int32_t sampleRate_from, sampleRate_to; 2280 CHECK(from->findInt32(kKeySampleRate, &sampleRate_from)); 2281 CHECK(to->findInt32(kKeySampleRate, &sampleRate_to)); 2282 2283 if (sampleRate_from != sampleRate_to) { 2284 return true; 2285 } 2286 } 2287 2288 return false; 2289} 2290 2291void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) { 2292 switch (event) { 2293 case OMX_EventCmdComplete: 2294 { 2295 onCmdComplete((OMX_COMMANDTYPE)data1, data2); 2296 break; 2297 } 2298 2299 case OMX_EventError: 2300 { 2301 CODEC_LOGE("ERROR(0x%08lx, %ld)", data1, data2); 2302 2303 setState(ERROR); 2304 break; 2305 } 2306 2307 case OMX_EventPortSettingsChanged: 2308 { 2309 CODEC_LOGV("OMX_EventPortSettingsChanged(port=%ld, data2=0x%08lx)", 2310 data1, data2); 2311 2312 if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) { 2313 onPortSettingsChanged(data1); 2314 } else if (data1 == kPortIndexOutput && 2315 (data2 == OMX_IndexConfigCommonOutputCrop || 2316 data2 == OMX_IndexConfigCommonScale)) { 2317 2318 sp<MetaData> oldOutputFormat = mOutputFormat; 2319 initOutputFormat(mSource->getFormat()); 2320 2321 if (data2 == OMX_IndexConfigCommonOutputCrop && 2322 formatHasNotablyChanged(oldOutputFormat, mOutputFormat)) { 2323 mOutputPortSettingsHaveChanged = true; 2324 2325 if (mNativeWindow != NULL) { 2326 int32_t left, top, right, bottom; 2327 CHECK(mOutputFormat->findRect( 2328 kKeyCropRect, 2329 &left, &top, &right, &bottom)); 2330 2331 android_native_rect_t crop; 2332 crop.left = left; 2333 crop.top = top; 2334 crop.right = right + 1; 2335 crop.bottom = bottom + 1; 2336 2337 // We'll ignore any errors here, if the surface is 2338 // already invalid, we'll know soon enough. 2339 native_window_set_crop(mNativeWindow.get(), &crop); 2340 } 2341 } else if (data2 == OMX_IndexConfigCommonScale) { 2342 OMX_CONFIG_SCALEFACTORTYPE scale; 2343 InitOMXParams(&scale); 2344 scale.nPortIndex = kPortIndexOutput; 2345 2346 // Change display dimension only when necessary. 2347 if (OK == mOMX->getConfig( 2348 mNode, 2349 OMX_IndexConfigCommonScale, 2350 &scale, sizeof(scale))) { 2351 int32_t left, top, right, bottom; 2352 CHECK(mOutputFormat->findRect(kKeyCropRect, 2353 &left, &top, 2354 &right, &bottom)); 2355 2356 // The scale is in 16.16 format. 2357 // scale 1.0 = 0x010000. When there is no 2358 // need to change the display, skip it. 2359 LOGV("Get OMX_IndexConfigScale: 0x%lx/0x%lx", 2360 scale.xWidth, scale.xHeight); 2361 2362 if (scale.xWidth != 0x010000) { 2363 mOutputFormat->setInt32(kKeyDisplayWidth, 2364 ((right - left + 1) * scale.xWidth) >> 16); 2365 mOutputPortSettingsHaveChanged = true; 2366 } 2367 2368 if (scale.xHeight != 0x010000) { 2369 mOutputFormat->setInt32(kKeyDisplayHeight, 2370 ((bottom - top + 1) * scale.xHeight) >> 16); 2371 mOutputPortSettingsHaveChanged = true; 2372 } 2373 } 2374 } 2375 } 2376 break; 2377 } 2378 2379#if 0 2380 case OMX_EventBufferFlag: 2381 { 2382 CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1); 2383 2384 if (data1 == kPortIndexOutput) { 2385 mNoMoreOutputData = true; 2386 } 2387 break; 2388 } 2389#endif 2390 2391 default: 2392 { 2393 CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2); 2394 break; 2395 } 2396 } 2397} 2398 2399void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) { 2400 switch (cmd) { 2401 case OMX_CommandStateSet: 2402 { 2403 onStateChange((OMX_STATETYPE)data); 2404 break; 2405 } 2406 2407 case OMX_CommandPortDisable: 2408 { 2409 OMX_U32 portIndex = data; 2410 CODEC_LOGV("PORT_DISABLED(%ld)", portIndex); 2411 2412 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2413 CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLING); 2414 CHECK_EQ(mPortBuffers[portIndex].size(), 0u); 2415 2416 mPortStatus[portIndex] = DISABLED; 2417 2418 if (mState == RECONFIGURING) { 2419 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2420 2421 sp<MetaData> oldOutputFormat = mOutputFormat; 2422 initOutputFormat(mSource->getFormat()); 2423 2424 // Don't notify clients if the output port settings change 2425 // wasn't of importance to them, i.e. it may be that just the 2426 // number of buffers has changed and nothing else. 2427 mOutputPortSettingsHaveChanged = 2428 formatHasNotablyChanged(oldOutputFormat, mOutputFormat); 2429 2430 enablePortAsync(portIndex); 2431 2432 status_t err = allocateBuffersOnPort(portIndex); 2433 2434 if (err != OK) { 2435 CODEC_LOGE("allocateBuffersOnPort failed (err = %d)", err); 2436 setState(ERROR); 2437 } 2438 } 2439 break; 2440 } 2441 2442 case OMX_CommandPortEnable: 2443 { 2444 OMX_U32 portIndex = data; 2445 CODEC_LOGV("PORT_ENABLED(%ld)", portIndex); 2446 2447 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2448 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLING); 2449 2450 mPortStatus[portIndex] = ENABLED; 2451 2452 if (mState == RECONFIGURING) { 2453 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2454 2455 setState(EXECUTING); 2456 2457 fillOutputBuffers(); 2458 } 2459 break; 2460 } 2461 2462 case OMX_CommandFlush: 2463 { 2464 OMX_U32 portIndex = data; 2465 2466 CODEC_LOGV("FLUSH_DONE(%ld)", portIndex); 2467 2468 CHECK_EQ((int)mPortStatus[portIndex], (int)SHUTTING_DOWN); 2469 mPortStatus[portIndex] = ENABLED; 2470 2471 CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]), 2472 mPortBuffers[portIndex].size()); 2473 2474 if (mState == RECONFIGURING) { 2475 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2476 2477 disablePortAsync(portIndex); 2478 } else if (mState == EXECUTING_TO_IDLE) { 2479 if (mPortStatus[kPortIndexInput] == ENABLED 2480 && mPortStatus[kPortIndexOutput] == ENABLED) { 2481 CODEC_LOGV("Finished flushing both ports, now completing " 2482 "transition from EXECUTING to IDLE."); 2483 2484 mPortStatus[kPortIndexInput] = SHUTTING_DOWN; 2485 mPortStatus[kPortIndexOutput] = SHUTTING_DOWN; 2486 2487 status_t err = 2488 mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 2489 CHECK_EQ(err, (status_t)OK); 2490 } 2491 } else { 2492 // We're flushing both ports in preparation for seeking. 2493 2494 if (mPortStatus[kPortIndexInput] == ENABLED 2495 && mPortStatus[kPortIndexOutput] == ENABLED) { 2496 CODEC_LOGV("Finished flushing both ports, now continuing from" 2497 " seek-time."); 2498 2499 // We implicitly resume pulling on our upstream source. 2500 mPaused = false; 2501 2502 drainInputBuffers(); 2503 fillOutputBuffers(); 2504 } 2505 2506 if (mOutputPortSettingsChangedPending) { 2507 CODEC_LOGV( 2508 "Honoring deferred output port settings change."); 2509 2510 mOutputPortSettingsChangedPending = false; 2511 onPortSettingsChanged(kPortIndexOutput); 2512 } 2513 } 2514 2515 break; 2516 } 2517 2518 default: 2519 { 2520 CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data); 2521 break; 2522 } 2523 } 2524} 2525 2526void OMXCodec::onStateChange(OMX_STATETYPE newState) { 2527 CODEC_LOGV("onStateChange %d", newState); 2528 2529 switch (newState) { 2530 case OMX_StateIdle: 2531 { 2532 CODEC_LOGV("Now Idle."); 2533 if (mState == LOADED_TO_IDLE) { 2534 status_t err = mOMX->sendCommand( 2535 mNode, OMX_CommandStateSet, OMX_StateExecuting); 2536 2537 CHECK_EQ(err, (status_t)OK); 2538 2539 setState(IDLE_TO_EXECUTING); 2540 } else { 2541 CHECK_EQ((int)mState, (int)EXECUTING_TO_IDLE); 2542 2543 CHECK_EQ( 2544 countBuffersWeOwn(mPortBuffers[kPortIndexInput]), 2545 mPortBuffers[kPortIndexInput].size()); 2546 2547 CHECK_EQ( 2548 countBuffersWeOwn(mPortBuffers[kPortIndexOutput]), 2549 mPortBuffers[kPortIndexOutput].size()); 2550 2551 status_t err = mOMX->sendCommand( 2552 mNode, OMX_CommandStateSet, OMX_StateLoaded); 2553 2554 CHECK_EQ(err, (status_t)OK); 2555 2556 err = freeBuffersOnPort(kPortIndexInput); 2557 CHECK_EQ(err, (status_t)OK); 2558 2559 err = freeBuffersOnPort(kPortIndexOutput); 2560 CHECK_EQ(err, (status_t)OK); 2561 2562 mPortStatus[kPortIndexInput] = ENABLED; 2563 mPortStatus[kPortIndexOutput] = ENABLED; 2564 2565 setState(IDLE_TO_LOADED); 2566 } 2567 break; 2568 } 2569 2570 case OMX_StateExecuting: 2571 { 2572 CHECK_EQ((int)mState, (int)IDLE_TO_EXECUTING); 2573 2574 CODEC_LOGV("Now Executing."); 2575 2576 mOutputPortSettingsChangedPending = false; 2577 2578 setState(EXECUTING); 2579 2580 // Buffers will be submitted to the component in the first 2581 // call to OMXCodec::read as mInitialBufferSubmit is true at 2582 // this point. This ensures that this on_message call returns, 2583 // releases the lock and ::init can notice the state change and 2584 // itself return. 2585 break; 2586 } 2587 2588 case OMX_StateLoaded: 2589 { 2590 CHECK_EQ((int)mState, (int)IDLE_TO_LOADED); 2591 2592 CODEC_LOGV("Now Loaded."); 2593 2594 setState(LOADED); 2595 break; 2596 } 2597 2598 case OMX_StateInvalid: 2599 { 2600 setState(ERROR); 2601 break; 2602 } 2603 2604 default: 2605 { 2606 CHECK(!"should not be here."); 2607 break; 2608 } 2609 } 2610} 2611 2612// static 2613size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) { 2614 size_t n = 0; 2615 for (size_t i = 0; i < buffers.size(); ++i) { 2616 if (buffers[i].mStatus != OWNED_BY_COMPONENT) { 2617 ++n; 2618 } 2619 } 2620 2621 return n; 2622} 2623 2624status_t OMXCodec::freeBuffersOnPort( 2625 OMX_U32 portIndex, bool onlyThoseWeOwn) { 2626 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 2627 2628 status_t stickyErr = OK; 2629 2630 for (size_t i = buffers->size(); i-- > 0;) { 2631 BufferInfo *info = &buffers->editItemAt(i); 2632 2633 if (onlyThoseWeOwn && info->mStatus == OWNED_BY_COMPONENT) { 2634 continue; 2635 } 2636 2637 CHECK(info->mStatus == OWNED_BY_US 2638 || info->mStatus == OWNED_BY_NATIVE_WINDOW); 2639 2640 CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex); 2641 2642 status_t err = freeBuffer(portIndex, i); 2643 2644 if (err != OK) { 2645 stickyErr = err; 2646 } 2647 2648 } 2649 2650 CHECK(onlyThoseWeOwn || buffers->isEmpty()); 2651 2652 return stickyErr; 2653} 2654 2655status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) { 2656 Vector<BufferInfo> *buffers = &mPortBuffers[portIndex]; 2657 2658 BufferInfo *info = &buffers->editItemAt(bufIndex); 2659 2660 status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer); 2661 2662 if (err == OK && info->mMediaBuffer != NULL) { 2663 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2664 info->mMediaBuffer->setObserver(NULL); 2665 2666 // Make sure nobody but us owns this buffer at this point. 2667 CHECK_EQ(info->mMediaBuffer->refcount(), 0); 2668 2669 // Cancel the buffer if it belongs to an ANativeWindow. 2670 sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer(); 2671 if (info->mStatus == OWNED_BY_US && graphicBuffer != 0) { 2672 err = cancelBufferToNativeWindow(info); 2673 } 2674 2675 info->mMediaBuffer->release(); 2676 info->mMediaBuffer = NULL; 2677 } 2678 2679 if (err == OK) { 2680 buffers->removeAt(bufIndex); 2681 } 2682 2683 return err; 2684} 2685 2686void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) { 2687 CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex); 2688 2689 CHECK_EQ((int)mState, (int)EXECUTING); 2690 CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput); 2691 CHECK(!mOutputPortSettingsChangedPending); 2692 2693 if (mPortStatus[kPortIndexOutput] != ENABLED) { 2694 CODEC_LOGV("Deferring output port settings change."); 2695 mOutputPortSettingsChangedPending = true; 2696 return; 2697 } 2698 2699 setState(RECONFIGURING); 2700 2701 if (mQuirks & kNeedsFlushBeforeDisable) { 2702 if (!flushPortAsync(portIndex)) { 2703 onCmdComplete(OMX_CommandFlush, portIndex); 2704 } 2705 } else { 2706 disablePortAsync(portIndex); 2707 } 2708} 2709 2710bool OMXCodec::flushPortAsync(OMX_U32 portIndex) { 2711 CHECK(mState == EXECUTING || mState == RECONFIGURING 2712 || mState == EXECUTING_TO_IDLE); 2713 2714 CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.", 2715 portIndex, countBuffersWeOwn(mPortBuffers[portIndex]), 2716 mPortBuffers[portIndex].size()); 2717 2718 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED); 2719 mPortStatus[portIndex] = SHUTTING_DOWN; 2720 2721 if ((mQuirks & kRequiresFlushCompleteEmulation) 2722 && countBuffersWeOwn(mPortBuffers[portIndex]) 2723 == mPortBuffers[portIndex].size()) { 2724 // No flush is necessary and this component fails to send a 2725 // flush-complete event in this case. 2726 2727 return false; 2728 } 2729 2730 status_t err = 2731 mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex); 2732 CHECK_EQ(err, (status_t)OK); 2733 2734 return true; 2735} 2736 2737void OMXCodec::disablePortAsync(OMX_U32 portIndex) { 2738 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2739 2740 CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED); 2741 mPortStatus[portIndex] = DISABLING; 2742 2743 CODEC_LOGV("sending OMX_CommandPortDisable(%ld)", portIndex); 2744 status_t err = 2745 mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex); 2746 CHECK_EQ(err, (status_t)OK); 2747 2748 freeBuffersOnPort(portIndex, true); 2749} 2750 2751void OMXCodec::enablePortAsync(OMX_U32 portIndex) { 2752 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2753 2754 CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLED); 2755 mPortStatus[portIndex] = ENABLING; 2756 2757 CODEC_LOGV("sending OMX_CommandPortEnable(%ld)", portIndex); 2758 status_t err = 2759 mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex); 2760 CHECK_EQ(err, (status_t)OK); 2761} 2762 2763void OMXCodec::fillOutputBuffers() { 2764 CHECK_EQ((int)mState, (int)EXECUTING); 2765 2766 // This is a workaround for some decoders not properly reporting 2767 // end-of-output-stream. If we own all input buffers and also own 2768 // all output buffers and we already signalled end-of-input-stream, 2769 // the end-of-output-stream is implied. 2770 if (mSignalledEOS 2771 && countBuffersWeOwn(mPortBuffers[kPortIndexInput]) 2772 == mPortBuffers[kPortIndexInput].size() 2773 && countBuffersWeOwn(mPortBuffers[kPortIndexOutput]) 2774 == mPortBuffers[kPortIndexOutput].size()) { 2775 mNoMoreOutputData = true; 2776 mBufferFilled.signal(); 2777 2778 return; 2779 } 2780 2781 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 2782 for (size_t i = 0; i < buffers->size(); ++i) { 2783 BufferInfo *info = &buffers->editItemAt(i); 2784 if (info->mStatus == OWNED_BY_US) { 2785 fillOutputBuffer(&buffers->editItemAt(i)); 2786 } 2787 } 2788} 2789 2790void OMXCodec::drainInputBuffers() { 2791 CHECK(mState == EXECUTING || mState == RECONFIGURING); 2792 2793 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 2794 for (size_t i = 0; i < buffers->size(); ++i) { 2795 BufferInfo *info = &buffers->editItemAt(i); 2796 2797 if (info->mStatus != OWNED_BY_US) { 2798 continue; 2799 } 2800 2801 if (!drainInputBuffer(info)) { 2802 break; 2803 } 2804 2805 if (mOnlySubmitOneBufferAtOneTime) { 2806 break; 2807 } 2808 } 2809} 2810 2811bool OMXCodec::drainInputBuffer(BufferInfo *info) { 2812 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 2813 2814 if (mSignalledEOS) { 2815 return false; 2816 } 2817 2818 if (mCodecSpecificDataIndex < mCodecSpecificData.size()) { 2819 const CodecSpecificData *specific = 2820 mCodecSpecificData[mCodecSpecificDataIndex]; 2821 2822 size_t size = specific->mSize; 2823 2824 if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME) 2825 && !(mQuirks & kWantsNALFragments)) { 2826 static const uint8_t kNALStartCode[4] = 2827 { 0x00, 0x00, 0x00, 0x01 }; 2828 2829 CHECK(info->mSize >= specific->mSize + 4); 2830 2831 size += 4; 2832 2833 memcpy(info->mData, kNALStartCode, 4); 2834 memcpy((uint8_t *)info->mData + 4, 2835 specific->mData, specific->mSize); 2836 } else { 2837 CHECK(info->mSize >= specific->mSize); 2838 memcpy(info->mData, specific->mData, specific->mSize); 2839 } 2840 2841 mNoMoreOutputData = false; 2842 2843 CODEC_LOGV("calling emptyBuffer with codec specific data"); 2844 2845 status_t err = mOMX->emptyBuffer( 2846 mNode, info->mBuffer, 0, size, 2847 OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG, 2848 0); 2849 CHECK_EQ(err, (status_t)OK); 2850 2851 info->mStatus = OWNED_BY_COMPONENT; 2852 2853 ++mCodecSpecificDataIndex; 2854 return true; 2855 } 2856 2857 if (mPaused) { 2858 return false; 2859 } 2860 2861 status_t err; 2862 2863 bool signalEOS = false; 2864 int64_t timestampUs = 0; 2865 2866 size_t offset = 0; 2867 int32_t n = 0; 2868 2869 for (;;) { 2870 MediaBuffer *srcBuffer; 2871 if (mSeekTimeUs >= 0) { 2872 if (mLeftOverBuffer) { 2873 mLeftOverBuffer->release(); 2874 mLeftOverBuffer = NULL; 2875 } 2876 2877 MediaSource::ReadOptions options; 2878 options.setSeekTo(mSeekTimeUs, mSeekMode); 2879 2880 mSeekTimeUs = -1; 2881 mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC; 2882 mBufferFilled.signal(); 2883 2884 err = mSource->read(&srcBuffer, &options); 2885 2886 if (err == OK) { 2887 int64_t targetTimeUs; 2888 if (srcBuffer->meta_data()->findInt64( 2889 kKeyTargetTime, &targetTimeUs) 2890 && targetTimeUs >= 0) { 2891 CODEC_LOGV("targetTimeUs = %lld us", targetTimeUs); 2892 mTargetTimeUs = targetTimeUs; 2893 } else { 2894 mTargetTimeUs = -1; 2895 } 2896 } 2897 } else if (mLeftOverBuffer) { 2898 srcBuffer = mLeftOverBuffer; 2899 mLeftOverBuffer = NULL; 2900 2901 err = OK; 2902 } else { 2903 err = mSource->read(&srcBuffer); 2904 } 2905 2906 if (err != OK) { 2907 signalEOS = true; 2908 mFinalStatus = err; 2909 mSignalledEOS = true; 2910 mBufferFilled.signal(); 2911 break; 2912 } 2913 2914 size_t remainingBytes = info->mSize - offset; 2915 2916 if (srcBuffer->range_length() > remainingBytes) { 2917 if (offset == 0) { 2918 CODEC_LOGE( 2919 "Codec's input buffers are too small to accomodate " 2920 "buffer read from source (info->mSize = %d, srcLength = %d)", 2921 info->mSize, srcBuffer->range_length()); 2922 2923 srcBuffer->release(); 2924 srcBuffer = NULL; 2925 2926 setState(ERROR); 2927 return false; 2928 } 2929 2930 mLeftOverBuffer = srcBuffer; 2931 break; 2932 } 2933 2934 bool releaseBuffer = true; 2935 if (mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)) { 2936 CHECK(mOMXLivesLocally && offset == 0); 2937 2938 OMX_BUFFERHEADERTYPE *header = 2939 (OMX_BUFFERHEADERTYPE *)info->mBuffer; 2940 2941 CHECK(header->pBuffer == info->mData); 2942 2943 header->pBuffer = 2944 (OMX_U8 *)srcBuffer->data() + srcBuffer->range_offset(); 2945 2946 releaseBuffer = false; 2947 info->mMediaBuffer = srcBuffer; 2948 } else { 2949 if (mIsMetaDataStoredInVideoBuffers) { 2950 releaseBuffer = false; 2951 info->mMediaBuffer = srcBuffer; 2952 } 2953 memcpy((uint8_t *)info->mData + offset, 2954 (const uint8_t *)srcBuffer->data() 2955 + srcBuffer->range_offset(), 2956 srcBuffer->range_length()); 2957 } 2958 2959 int64_t lastBufferTimeUs; 2960 CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs)); 2961 CHECK(lastBufferTimeUs >= 0); 2962 if (mIsEncoder) { 2963 mDecodingTimeList.push_back(lastBufferTimeUs); 2964 } 2965 2966 if (offset == 0) { 2967 timestampUs = lastBufferTimeUs; 2968 } 2969 2970 offset += srcBuffer->range_length(); 2971 2972 if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_VORBIS, mMIME)) { 2973 CHECK(!(mQuirks & kSupportsMultipleFramesPerInputBuffer)); 2974 CHECK_GE(info->mSize, offset + sizeof(int32_t)); 2975 2976 int32_t numPageSamples; 2977 if (!srcBuffer->meta_data()->findInt32( 2978 kKeyValidSamples, &numPageSamples)) { 2979 numPageSamples = -1; 2980 } 2981 2982 memcpy((uint8_t *)info->mData + offset, 2983 &numPageSamples, 2984 sizeof(numPageSamples)); 2985 2986 offset += sizeof(numPageSamples); 2987 } 2988 2989 if (releaseBuffer) { 2990 srcBuffer->release(); 2991 srcBuffer = NULL; 2992 } 2993 2994 ++n; 2995 2996 if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) { 2997 break; 2998 } 2999 3000 int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs; 3001 3002 if (coalescedDurationUs > 250000ll) { 3003 // Don't coalesce more than 250ms worth of encoded data at once. 3004 break; 3005 } 3006 } 3007 3008 if (n > 1) { 3009 LOGV("coalesced %d frames into one input buffer", n); 3010 } 3011 3012 OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME; 3013 3014 if (signalEOS) { 3015 flags |= OMX_BUFFERFLAG_EOS; 3016 } else { 3017 mNoMoreOutputData = false; 3018 } 3019 3020 CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), " 3021 "timestamp %lld us (%.2f secs)", 3022 info->mBuffer, offset, 3023 timestampUs, timestampUs / 1E6); 3024 3025 err = mOMX->emptyBuffer( 3026 mNode, info->mBuffer, 0, offset, 3027 flags, timestampUs); 3028 3029 if (err != OK) { 3030 setState(ERROR); 3031 return false; 3032 } 3033 3034 info->mStatus = OWNED_BY_COMPONENT; 3035 3036 // This component does not ever signal the EOS flag on output buffers, 3037 // Thanks for nothing. 3038 if (mSignalledEOS && !strcmp(mComponentName, "OMX.TI.Video.encoder")) { 3039 mNoMoreOutputData = true; 3040 mBufferFilled.signal(); 3041 } 3042 3043 return true; 3044} 3045 3046void OMXCodec::fillOutputBuffer(BufferInfo *info) { 3047 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 3048 3049 if (mNoMoreOutputData) { 3050 CODEC_LOGV("There is no more output data available, not " 3051 "calling fillOutputBuffer"); 3052 return; 3053 } 3054 3055 if (info->mMediaBuffer != NULL) { 3056 sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer(); 3057 if (graphicBuffer != 0) { 3058 // When using a native buffer we need to lock the buffer before 3059 // giving it to OMX. 3060 CODEC_LOGV("Calling lockBuffer on %p", info->mBuffer); 3061 int err = mNativeWindow->lockBuffer(mNativeWindow.get(), 3062 graphicBuffer.get()); 3063 if (err != 0) { 3064 CODEC_LOGE("lockBuffer failed w/ error 0x%08x", err); 3065 3066 setState(ERROR); 3067 return; 3068 } 3069 } 3070 } 3071 3072 CODEC_LOGV("Calling fillBuffer on buffer %p", info->mBuffer); 3073 status_t err = mOMX->fillBuffer(mNode, info->mBuffer); 3074 3075 if (err != OK) { 3076 CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err); 3077 3078 setState(ERROR); 3079 return; 3080 } 3081 3082 info->mStatus = OWNED_BY_COMPONENT; 3083} 3084 3085bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) { 3086 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; 3087 for (size_t i = 0; i < buffers->size(); ++i) { 3088 if ((*buffers)[i].mBuffer == buffer) { 3089 return drainInputBuffer(&buffers->editItemAt(i)); 3090 } 3091 } 3092 3093 CHECK(!"should not be here."); 3094 3095 return false; 3096} 3097 3098void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) { 3099 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 3100 for (size_t i = 0; i < buffers->size(); ++i) { 3101 if ((*buffers)[i].mBuffer == buffer) { 3102 fillOutputBuffer(&buffers->editItemAt(i)); 3103 return; 3104 } 3105 } 3106 3107 CHECK(!"should not be here."); 3108} 3109 3110void OMXCodec::setState(State newState) { 3111 mState = newState; 3112 mAsyncCompletion.signal(); 3113 3114 // This may cause some spurious wakeups but is necessary to 3115 // unblock the reader if we enter ERROR state. 3116 mBufferFilled.signal(); 3117} 3118 3119void OMXCodec::setRawAudioFormat( 3120 OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) { 3121 3122 // port definition 3123 OMX_PARAM_PORTDEFINITIONTYPE def; 3124 InitOMXParams(&def); 3125 def.nPortIndex = portIndex; 3126 status_t err = mOMX->getParameter( 3127 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3128 CHECK_EQ(err, (status_t)OK); 3129 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM; 3130 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition, 3131 &def, sizeof(def)), (status_t)OK); 3132 3133 // pcm param 3134 OMX_AUDIO_PARAM_PCMMODETYPE pcmParams; 3135 InitOMXParams(&pcmParams); 3136 pcmParams.nPortIndex = portIndex; 3137 3138 err = mOMX->getParameter( 3139 mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams)); 3140 3141 CHECK_EQ(err, (status_t)OK); 3142 3143 pcmParams.nChannels = numChannels; 3144 pcmParams.eNumData = OMX_NumericalDataSigned; 3145 pcmParams.bInterleaved = OMX_TRUE; 3146 pcmParams.nBitPerSample = 16; 3147 pcmParams.nSamplingRate = sampleRate; 3148 pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear; 3149 3150 if (numChannels == 1) { 3151 pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelCF; 3152 } else { 3153 CHECK_EQ(numChannels, 2); 3154 3155 pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelLF; 3156 pcmParams.eChannelMapping[1] = OMX_AUDIO_ChannelRF; 3157 } 3158 3159 err = mOMX->setParameter( 3160 mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams)); 3161 3162 CHECK_EQ(err, (status_t)OK); 3163} 3164 3165static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) { 3166 if (isAMRWB) { 3167 if (bps <= 6600) { 3168 return OMX_AUDIO_AMRBandModeWB0; 3169 } else if (bps <= 8850) { 3170 return OMX_AUDIO_AMRBandModeWB1; 3171 } else if (bps <= 12650) { 3172 return OMX_AUDIO_AMRBandModeWB2; 3173 } else if (bps <= 14250) { 3174 return OMX_AUDIO_AMRBandModeWB3; 3175 } else if (bps <= 15850) { 3176 return OMX_AUDIO_AMRBandModeWB4; 3177 } else if (bps <= 18250) { 3178 return OMX_AUDIO_AMRBandModeWB5; 3179 } else if (bps <= 19850) { 3180 return OMX_AUDIO_AMRBandModeWB6; 3181 } else if (bps <= 23050) { 3182 return OMX_AUDIO_AMRBandModeWB7; 3183 } 3184 3185 // 23850 bps 3186 return OMX_AUDIO_AMRBandModeWB8; 3187 } else { // AMRNB 3188 if (bps <= 4750) { 3189 return OMX_AUDIO_AMRBandModeNB0; 3190 } else if (bps <= 5150) { 3191 return OMX_AUDIO_AMRBandModeNB1; 3192 } else if (bps <= 5900) { 3193 return OMX_AUDIO_AMRBandModeNB2; 3194 } else if (bps <= 6700) { 3195 return OMX_AUDIO_AMRBandModeNB3; 3196 } else if (bps <= 7400) { 3197 return OMX_AUDIO_AMRBandModeNB4; 3198 } else if (bps <= 7950) { 3199 return OMX_AUDIO_AMRBandModeNB5; 3200 } else if (bps <= 10200) { 3201 return OMX_AUDIO_AMRBandModeNB6; 3202 } 3203 3204 // 12200 bps 3205 return OMX_AUDIO_AMRBandModeNB7; 3206 } 3207} 3208 3209void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) { 3210 OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput; 3211 3212 OMX_AUDIO_PARAM_AMRTYPE def; 3213 InitOMXParams(&def); 3214 def.nPortIndex = portIndex; 3215 3216 status_t err = 3217 mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def)); 3218 3219 CHECK_EQ(err, (status_t)OK); 3220 3221 def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; 3222 3223 def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate); 3224 err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def)); 3225 CHECK_EQ(err, (status_t)OK); 3226 3227 //////////////////////// 3228 3229 if (mIsEncoder) { 3230 sp<MetaData> format = mSource->getFormat(); 3231 int32_t sampleRate; 3232 int32_t numChannels; 3233 CHECK(format->findInt32(kKeySampleRate, &sampleRate)); 3234 CHECK(format->findInt32(kKeyChannelCount, &numChannels)); 3235 3236 setRawAudioFormat(kPortIndexInput, sampleRate, numChannels); 3237 } 3238} 3239 3240void OMXCodec::setAACFormat(int32_t numChannels, int32_t sampleRate, int32_t bitRate) { 3241 CHECK(numChannels == 1 || numChannels == 2); 3242 if (mIsEncoder) { 3243 //////////////// input port //////////////////// 3244 setRawAudioFormat(kPortIndexInput, sampleRate, numChannels); 3245 3246 //////////////// output port //////////////////// 3247 // format 3248 OMX_AUDIO_PARAM_PORTFORMATTYPE format; 3249 format.nPortIndex = kPortIndexOutput; 3250 format.nIndex = 0; 3251 status_t err = OMX_ErrorNone; 3252 while (OMX_ErrorNone == err) { 3253 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat, 3254 &format, sizeof(format)), (status_t)OK); 3255 if (format.eEncoding == OMX_AUDIO_CodingAAC) { 3256 break; 3257 } 3258 format.nIndex++; 3259 } 3260 CHECK_EQ((status_t)OK, err); 3261 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat, 3262 &format, sizeof(format)), (status_t)OK); 3263 3264 // port definition 3265 OMX_PARAM_PORTDEFINITIONTYPE def; 3266 InitOMXParams(&def); 3267 def.nPortIndex = kPortIndexOutput; 3268 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition, 3269 &def, sizeof(def)), (status_t)OK); 3270 def.format.audio.bFlagErrorConcealment = OMX_TRUE; 3271 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; 3272 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition, 3273 &def, sizeof(def)), (status_t)OK); 3274 3275 // profile 3276 OMX_AUDIO_PARAM_AACPROFILETYPE profile; 3277 InitOMXParams(&profile); 3278 profile.nPortIndex = kPortIndexOutput; 3279 CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac, 3280 &profile, sizeof(profile)), (status_t)OK); 3281 profile.nChannels = numChannels; 3282 profile.eChannelMode = (numChannels == 1? 3283 OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo); 3284 profile.nSampleRate = sampleRate; 3285 profile.nBitRate = bitRate; 3286 profile.nAudioBandWidth = 0; 3287 profile.nFrameLength = 0; 3288 profile.nAACtools = OMX_AUDIO_AACToolAll; 3289 profile.nAACERtools = OMX_AUDIO_AACERNone; 3290 profile.eAACProfile = OMX_AUDIO_AACObjectLC; 3291 profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; 3292 CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioAac, 3293 &profile, sizeof(profile)), (status_t)OK); 3294 3295 } else { 3296 OMX_AUDIO_PARAM_AACPROFILETYPE profile; 3297 InitOMXParams(&profile); 3298 profile.nPortIndex = kPortIndexInput; 3299 3300 status_t err = mOMX->getParameter( 3301 mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); 3302 CHECK_EQ(err, (status_t)OK); 3303 3304 profile.nChannels = numChannels; 3305 profile.nSampleRate = sampleRate; 3306 profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4ADTS; 3307 3308 err = mOMX->setParameter( 3309 mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); 3310 CHECK_EQ(err, (status_t)OK); 3311 } 3312} 3313 3314void OMXCodec::setG711Format(int32_t numChannels) { 3315 CHECK(!mIsEncoder); 3316 setRawAudioFormat(kPortIndexInput, 8000, numChannels); 3317} 3318 3319void OMXCodec::setImageOutputFormat( 3320 OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) { 3321 CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height); 3322 3323#if 0 3324 OMX_INDEXTYPE index; 3325 status_t err = mOMX->get_extension_index( 3326 mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index); 3327 CHECK_EQ(err, (status_t)OK); 3328 3329 err = mOMX->set_config(mNode, index, &format, sizeof(format)); 3330 CHECK_EQ(err, (status_t)OK); 3331#endif 3332 3333 OMX_PARAM_PORTDEFINITIONTYPE def; 3334 InitOMXParams(&def); 3335 def.nPortIndex = kPortIndexOutput; 3336 3337 status_t err = mOMX->getParameter( 3338 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3339 CHECK_EQ(err, (status_t)OK); 3340 3341 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage); 3342 3343 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 3344 3345 CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingUnused); 3346 imageDef->eColorFormat = format; 3347 imageDef->nFrameWidth = width; 3348 imageDef->nFrameHeight = height; 3349 3350 switch (format) { 3351 case OMX_COLOR_FormatYUV420PackedPlanar: 3352 case OMX_COLOR_FormatYUV411Planar: 3353 { 3354 def.nBufferSize = (width * height * 3) / 2; 3355 break; 3356 } 3357 3358 case OMX_COLOR_FormatCbYCrY: 3359 { 3360 def.nBufferSize = width * height * 2; 3361 break; 3362 } 3363 3364 case OMX_COLOR_Format32bitARGB8888: 3365 { 3366 def.nBufferSize = width * height * 4; 3367 break; 3368 } 3369 3370 case OMX_COLOR_Format16bitARGB4444: 3371 case OMX_COLOR_Format16bitARGB1555: 3372 case OMX_COLOR_Format16bitRGB565: 3373 case OMX_COLOR_Format16bitBGR565: 3374 { 3375 def.nBufferSize = width * height * 2; 3376 break; 3377 } 3378 3379 default: 3380 CHECK(!"Should not be here. Unknown color format."); 3381 break; 3382 } 3383 3384 def.nBufferCountActual = def.nBufferCountMin; 3385 3386 err = mOMX->setParameter( 3387 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3388 CHECK_EQ(err, (status_t)OK); 3389} 3390 3391void OMXCodec::setJPEGInputFormat( 3392 OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) { 3393 OMX_PARAM_PORTDEFINITIONTYPE def; 3394 InitOMXParams(&def); 3395 def.nPortIndex = kPortIndexInput; 3396 3397 status_t err = mOMX->getParameter( 3398 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3399 CHECK_EQ(err, (status_t)OK); 3400 3401 CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage); 3402 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 3403 3404 CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingJPEG); 3405 imageDef->nFrameWidth = width; 3406 imageDef->nFrameHeight = height; 3407 3408 def.nBufferSize = compressedSize; 3409 def.nBufferCountActual = def.nBufferCountMin; 3410 3411 err = mOMX->setParameter( 3412 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3413 CHECK_EQ(err, (status_t)OK); 3414} 3415 3416void OMXCodec::addCodecSpecificData(const void *data, size_t size) { 3417 CodecSpecificData *specific = 3418 (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1); 3419 3420 specific->mSize = size; 3421 memcpy(specific->mData, data, size); 3422 3423 mCodecSpecificData.push(specific); 3424} 3425 3426void OMXCodec::clearCodecSpecificData() { 3427 for (size_t i = 0; i < mCodecSpecificData.size(); ++i) { 3428 free(mCodecSpecificData.editItemAt(i)); 3429 } 3430 mCodecSpecificData.clear(); 3431 mCodecSpecificDataIndex = 0; 3432} 3433 3434status_t OMXCodec::start(MetaData *meta) { 3435 Mutex::Autolock autoLock(mLock); 3436 3437 if (mState != LOADED) { 3438 return UNKNOWN_ERROR; 3439 } 3440 3441 sp<MetaData> params = new MetaData; 3442 if (mQuirks & kWantsNALFragments) { 3443 params->setInt32(kKeyWantsNALFragments, true); 3444 } 3445 if (meta) { 3446 int64_t startTimeUs = 0; 3447 int64_t timeUs; 3448 if (meta->findInt64(kKeyTime, &timeUs)) { 3449 startTimeUs = timeUs; 3450 } 3451 params->setInt64(kKeyTime, startTimeUs); 3452 } 3453 status_t err = mSource->start(params.get()); 3454 3455 if (err != OK) { 3456 return err; 3457 } 3458 3459 mCodecSpecificDataIndex = 0; 3460 mInitialBufferSubmit = true; 3461 mSignalledEOS = false; 3462 mNoMoreOutputData = false; 3463 mOutputPortSettingsHaveChanged = false; 3464 mSeekTimeUs = -1; 3465 mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC; 3466 mTargetTimeUs = -1; 3467 mFilledBuffers.clear(); 3468 mPaused = false; 3469 3470 return init(); 3471} 3472 3473status_t OMXCodec::stop() { 3474 CODEC_LOGI("stop mState=%d", mState); 3475 3476 Mutex::Autolock autoLock(mLock); 3477 3478 while (isIntermediateState(mState)) { 3479 mAsyncCompletion.wait(mLock); 3480 } 3481 3482 switch (mState) { 3483 case LOADED: 3484 case ERROR: 3485 break; 3486 3487 case EXECUTING: 3488 { 3489 setState(EXECUTING_TO_IDLE); 3490 3491 if (mQuirks & kRequiresFlushBeforeShutdown) { 3492 CODEC_LOGV("This component requires a flush before transitioning " 3493 "from EXECUTING to IDLE..."); 3494 3495 bool emulateInputFlushCompletion = 3496 !flushPortAsync(kPortIndexInput); 3497 3498 bool emulateOutputFlushCompletion = 3499 !flushPortAsync(kPortIndexOutput); 3500 3501 if (emulateInputFlushCompletion) { 3502 onCmdComplete(OMX_CommandFlush, kPortIndexInput); 3503 } 3504 3505 if (emulateOutputFlushCompletion) { 3506 onCmdComplete(OMX_CommandFlush, kPortIndexOutput); 3507 } 3508 } else { 3509 mPortStatus[kPortIndexInput] = SHUTTING_DOWN; 3510 mPortStatus[kPortIndexOutput] = SHUTTING_DOWN; 3511 3512 status_t err = 3513 mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle); 3514 CHECK_EQ(err, (status_t)OK); 3515 } 3516 3517 while (mState != LOADED && mState != ERROR) { 3518 mAsyncCompletion.wait(mLock); 3519 } 3520 3521 break; 3522 } 3523 3524 default: 3525 { 3526 CHECK(!"should not be here."); 3527 break; 3528 } 3529 } 3530 3531 if (mLeftOverBuffer) { 3532 mLeftOverBuffer->release(); 3533 mLeftOverBuffer = NULL; 3534 } 3535 3536 CODEC_LOGI("stopping video source"); 3537 mSource->stop(); 3538 3539 CODEC_LOGI("stopped in state %d", mState); 3540 3541 return OK; 3542} 3543 3544sp<MetaData> OMXCodec::getFormat() { 3545 Mutex::Autolock autoLock(mLock); 3546 3547 return mOutputFormat; 3548} 3549 3550status_t OMXCodec::read( 3551 MediaBuffer **buffer, const ReadOptions *options) { 3552 *buffer = NULL; 3553 3554 Mutex::Autolock autoLock(mLock); 3555 3556 if (mState != EXECUTING && mState != RECONFIGURING) { 3557 return UNKNOWN_ERROR; 3558 } 3559 3560 bool seeking = false; 3561 int64_t seekTimeUs; 3562 ReadOptions::SeekMode seekMode; 3563 if (options && options->getSeekTo(&seekTimeUs, &seekMode)) { 3564 seeking = true; 3565 } 3566 3567 if (mInitialBufferSubmit) { 3568 mInitialBufferSubmit = false; 3569 3570 if (seeking) { 3571 CHECK(seekTimeUs >= 0); 3572 mSeekTimeUs = seekTimeUs; 3573 mSeekMode = seekMode; 3574 3575 // There's no reason to trigger the code below, there's 3576 // nothing to flush yet. 3577 seeking = false; 3578 mPaused = false; 3579 } 3580 3581 drainInputBuffers(); 3582 3583 if (mState == EXECUTING) { 3584 // Otherwise mState == RECONFIGURING and this code will trigger 3585 // after the output port is reenabled. 3586 fillOutputBuffers(); 3587 } 3588 } 3589 3590 if (seeking) { 3591 while (mState == RECONFIGURING) { 3592 mBufferFilled.wait(mLock); 3593 } 3594 3595 if (mState != EXECUTING) { 3596 return UNKNOWN_ERROR; 3597 } 3598 3599 CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6); 3600 3601 mSignalledEOS = false; 3602 3603 CHECK(seekTimeUs >= 0); 3604 mSeekTimeUs = seekTimeUs; 3605 mSeekMode = seekMode; 3606 3607 mFilledBuffers.clear(); 3608 3609 CHECK_EQ((int)mState, (int)EXECUTING); 3610 3611 bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput); 3612 bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput); 3613 3614 if (emulateInputFlushCompletion) { 3615 onCmdComplete(OMX_CommandFlush, kPortIndexInput); 3616 } 3617 3618 if (emulateOutputFlushCompletion) { 3619 onCmdComplete(OMX_CommandFlush, kPortIndexOutput); 3620 } 3621 3622 while (mSeekTimeUs >= 0) { 3623 mBufferFilled.wait(mLock); 3624 } 3625 } 3626 3627 while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) { 3628 if (mIsEncoder) { 3629 if (NO_ERROR != mBufferFilled.waitRelative(mLock, 3000000000LL)) { 3630 LOGW("Timed out waiting for buffers from video encoder: %d/%d", 3631 countBuffersWeOwn(mPortBuffers[kPortIndexInput]), 3632 countBuffersWeOwn(mPortBuffers[kPortIndexOutput])); 3633 } 3634 } else { 3635 mBufferFilled.wait(mLock); 3636 } 3637 } 3638 3639 if (mState == ERROR) { 3640 return UNKNOWN_ERROR; 3641 } 3642 3643 if (mFilledBuffers.empty()) { 3644 return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM; 3645 } 3646 3647 if (mOutputPortSettingsHaveChanged) { 3648 mOutputPortSettingsHaveChanged = false; 3649 3650 return INFO_FORMAT_CHANGED; 3651 } 3652 3653 size_t index = *mFilledBuffers.begin(); 3654 mFilledBuffers.erase(mFilledBuffers.begin()); 3655 3656 BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index); 3657 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US); 3658 info->mStatus = OWNED_BY_CLIENT; 3659 3660 info->mMediaBuffer->add_ref(); 3661 *buffer = info->mMediaBuffer; 3662 3663 return OK; 3664} 3665 3666void OMXCodec::signalBufferReturned(MediaBuffer *buffer) { 3667 Mutex::Autolock autoLock(mLock); 3668 3669 Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput]; 3670 for (size_t i = 0; i < buffers->size(); ++i) { 3671 BufferInfo *info = &buffers->editItemAt(i); 3672 3673 if (info->mMediaBuffer == buffer) { 3674 CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED); 3675 CHECK_EQ((int)info->mStatus, (int)OWNED_BY_CLIENT); 3676 3677 info->mStatus = OWNED_BY_US; 3678 3679 if (buffer->graphicBuffer() == 0) { 3680 fillOutputBuffer(info); 3681 } else { 3682 sp<MetaData> metaData = info->mMediaBuffer->meta_data(); 3683 int32_t rendered = 0; 3684 if (!metaData->findInt32(kKeyRendered, &rendered)) { 3685 rendered = 0; 3686 } 3687 if (!rendered) { 3688 status_t err = cancelBufferToNativeWindow(info); 3689 if (err < 0) { 3690 return; 3691 } 3692 } 3693 3694 info->mStatus = OWNED_BY_NATIVE_WINDOW; 3695 3696 // Dequeue the next buffer from the native window. 3697 BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow(); 3698 if (nextBufInfo == 0) { 3699 return; 3700 } 3701 3702 // Give the buffer to the OMX node to fill. 3703 fillOutputBuffer(nextBufInfo); 3704 } 3705 return; 3706 } 3707 } 3708 3709 CHECK(!"should not be here."); 3710} 3711 3712static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) { 3713 static const char *kNames[] = { 3714 "OMX_IMAGE_CodingUnused", 3715 "OMX_IMAGE_CodingAutoDetect", 3716 "OMX_IMAGE_CodingJPEG", 3717 "OMX_IMAGE_CodingJPEG2K", 3718 "OMX_IMAGE_CodingEXIF", 3719 "OMX_IMAGE_CodingTIFF", 3720 "OMX_IMAGE_CodingGIF", 3721 "OMX_IMAGE_CodingPNG", 3722 "OMX_IMAGE_CodingLZW", 3723 "OMX_IMAGE_CodingBMP", 3724 }; 3725 3726 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3727 3728 if (type < 0 || (size_t)type >= numNames) { 3729 return "UNKNOWN"; 3730 } else { 3731 return kNames[type]; 3732 } 3733} 3734 3735static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) { 3736 static const char *kNames[] = { 3737 "OMX_COLOR_FormatUnused", 3738 "OMX_COLOR_FormatMonochrome", 3739 "OMX_COLOR_Format8bitRGB332", 3740 "OMX_COLOR_Format12bitRGB444", 3741 "OMX_COLOR_Format16bitARGB4444", 3742 "OMX_COLOR_Format16bitARGB1555", 3743 "OMX_COLOR_Format16bitRGB565", 3744 "OMX_COLOR_Format16bitBGR565", 3745 "OMX_COLOR_Format18bitRGB666", 3746 "OMX_COLOR_Format18bitARGB1665", 3747 "OMX_COLOR_Format19bitARGB1666", 3748 "OMX_COLOR_Format24bitRGB888", 3749 "OMX_COLOR_Format24bitBGR888", 3750 "OMX_COLOR_Format24bitARGB1887", 3751 "OMX_COLOR_Format25bitARGB1888", 3752 "OMX_COLOR_Format32bitBGRA8888", 3753 "OMX_COLOR_Format32bitARGB8888", 3754 "OMX_COLOR_FormatYUV411Planar", 3755 "OMX_COLOR_FormatYUV411PackedPlanar", 3756 "OMX_COLOR_FormatYUV420Planar", 3757 "OMX_COLOR_FormatYUV420PackedPlanar", 3758 "OMX_COLOR_FormatYUV420SemiPlanar", 3759 "OMX_COLOR_FormatYUV422Planar", 3760 "OMX_COLOR_FormatYUV422PackedPlanar", 3761 "OMX_COLOR_FormatYUV422SemiPlanar", 3762 "OMX_COLOR_FormatYCbYCr", 3763 "OMX_COLOR_FormatYCrYCb", 3764 "OMX_COLOR_FormatCbYCrY", 3765 "OMX_COLOR_FormatCrYCbY", 3766 "OMX_COLOR_FormatYUV444Interleaved", 3767 "OMX_COLOR_FormatRawBayer8bit", 3768 "OMX_COLOR_FormatRawBayer10bit", 3769 "OMX_COLOR_FormatRawBayer8bitcompressed", 3770 "OMX_COLOR_FormatL2", 3771 "OMX_COLOR_FormatL4", 3772 "OMX_COLOR_FormatL8", 3773 "OMX_COLOR_FormatL16", 3774 "OMX_COLOR_FormatL24", 3775 "OMX_COLOR_FormatL32", 3776 "OMX_COLOR_FormatYUV420PackedSemiPlanar", 3777 "OMX_COLOR_FormatYUV422PackedSemiPlanar", 3778 "OMX_COLOR_Format18BitBGR666", 3779 "OMX_COLOR_Format24BitARGB6666", 3780 "OMX_COLOR_Format24BitABGR6666", 3781 }; 3782 3783 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3784 3785 if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) { 3786 return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar"; 3787 } else if (type < 0 || (size_t)type >= numNames) { 3788 return "UNKNOWN"; 3789 } else { 3790 return kNames[type]; 3791 } 3792} 3793 3794static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) { 3795 static const char *kNames[] = { 3796 "OMX_VIDEO_CodingUnused", 3797 "OMX_VIDEO_CodingAutoDetect", 3798 "OMX_VIDEO_CodingMPEG2", 3799 "OMX_VIDEO_CodingH263", 3800 "OMX_VIDEO_CodingMPEG4", 3801 "OMX_VIDEO_CodingWMV", 3802 "OMX_VIDEO_CodingRV", 3803 "OMX_VIDEO_CodingAVC", 3804 "OMX_VIDEO_CodingMJPEG", 3805 }; 3806 3807 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3808 3809 if (type < 0 || (size_t)type >= numNames) { 3810 return "UNKNOWN"; 3811 } else { 3812 return kNames[type]; 3813 } 3814} 3815 3816static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) { 3817 static const char *kNames[] = { 3818 "OMX_AUDIO_CodingUnused", 3819 "OMX_AUDIO_CodingAutoDetect", 3820 "OMX_AUDIO_CodingPCM", 3821 "OMX_AUDIO_CodingADPCM", 3822 "OMX_AUDIO_CodingAMR", 3823 "OMX_AUDIO_CodingGSMFR", 3824 "OMX_AUDIO_CodingGSMEFR", 3825 "OMX_AUDIO_CodingGSMHR", 3826 "OMX_AUDIO_CodingPDCFR", 3827 "OMX_AUDIO_CodingPDCEFR", 3828 "OMX_AUDIO_CodingPDCHR", 3829 "OMX_AUDIO_CodingTDMAFR", 3830 "OMX_AUDIO_CodingTDMAEFR", 3831 "OMX_AUDIO_CodingQCELP8", 3832 "OMX_AUDIO_CodingQCELP13", 3833 "OMX_AUDIO_CodingEVRC", 3834 "OMX_AUDIO_CodingSMV", 3835 "OMX_AUDIO_CodingG711", 3836 "OMX_AUDIO_CodingG723", 3837 "OMX_AUDIO_CodingG726", 3838 "OMX_AUDIO_CodingG729", 3839 "OMX_AUDIO_CodingAAC", 3840 "OMX_AUDIO_CodingMP3", 3841 "OMX_AUDIO_CodingSBC", 3842 "OMX_AUDIO_CodingVORBIS", 3843 "OMX_AUDIO_CodingWMA", 3844 "OMX_AUDIO_CodingRA", 3845 "OMX_AUDIO_CodingMIDI", 3846 }; 3847 3848 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3849 3850 if (type < 0 || (size_t)type >= numNames) { 3851 return "UNKNOWN"; 3852 } else { 3853 return kNames[type]; 3854 } 3855} 3856 3857static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) { 3858 static const char *kNames[] = { 3859 "OMX_AUDIO_PCMModeLinear", 3860 "OMX_AUDIO_PCMModeALaw", 3861 "OMX_AUDIO_PCMModeMULaw", 3862 }; 3863 3864 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3865 3866 if (type < 0 || (size_t)type >= numNames) { 3867 return "UNKNOWN"; 3868 } else { 3869 return kNames[type]; 3870 } 3871} 3872 3873static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) { 3874 static const char *kNames[] = { 3875 "OMX_AUDIO_AMRBandModeUnused", 3876 "OMX_AUDIO_AMRBandModeNB0", 3877 "OMX_AUDIO_AMRBandModeNB1", 3878 "OMX_AUDIO_AMRBandModeNB2", 3879 "OMX_AUDIO_AMRBandModeNB3", 3880 "OMX_AUDIO_AMRBandModeNB4", 3881 "OMX_AUDIO_AMRBandModeNB5", 3882 "OMX_AUDIO_AMRBandModeNB6", 3883 "OMX_AUDIO_AMRBandModeNB7", 3884 "OMX_AUDIO_AMRBandModeWB0", 3885 "OMX_AUDIO_AMRBandModeWB1", 3886 "OMX_AUDIO_AMRBandModeWB2", 3887 "OMX_AUDIO_AMRBandModeWB3", 3888 "OMX_AUDIO_AMRBandModeWB4", 3889 "OMX_AUDIO_AMRBandModeWB5", 3890 "OMX_AUDIO_AMRBandModeWB6", 3891 "OMX_AUDIO_AMRBandModeWB7", 3892 "OMX_AUDIO_AMRBandModeWB8", 3893 }; 3894 3895 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3896 3897 if (type < 0 || (size_t)type >= numNames) { 3898 return "UNKNOWN"; 3899 } else { 3900 return kNames[type]; 3901 } 3902} 3903 3904static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) { 3905 static const char *kNames[] = { 3906 "OMX_AUDIO_AMRFrameFormatConformance", 3907 "OMX_AUDIO_AMRFrameFormatIF1", 3908 "OMX_AUDIO_AMRFrameFormatIF2", 3909 "OMX_AUDIO_AMRFrameFormatFSF", 3910 "OMX_AUDIO_AMRFrameFormatRTPPayload", 3911 "OMX_AUDIO_AMRFrameFormatITU", 3912 }; 3913 3914 size_t numNames = sizeof(kNames) / sizeof(kNames[0]); 3915 3916 if (type < 0 || (size_t)type >= numNames) { 3917 return "UNKNOWN"; 3918 } else { 3919 return kNames[type]; 3920 } 3921} 3922 3923void OMXCodec::dumpPortStatus(OMX_U32 portIndex) { 3924 OMX_PARAM_PORTDEFINITIONTYPE def; 3925 InitOMXParams(&def); 3926 def.nPortIndex = portIndex; 3927 3928 status_t err = mOMX->getParameter( 3929 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 3930 CHECK_EQ(err, (status_t)OK); 3931 3932 printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output"); 3933 3934 CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput) 3935 || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput)); 3936 3937 printf(" nBufferCountActual = %ld\n", def.nBufferCountActual); 3938 printf(" nBufferCountMin = %ld\n", def.nBufferCountMin); 3939 printf(" nBufferSize = %ld\n", def.nBufferSize); 3940 3941 switch (def.eDomain) { 3942 case OMX_PortDomainImage: 3943 { 3944 const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 3945 3946 printf("\n"); 3947 printf(" // Image\n"); 3948 printf(" nFrameWidth = %ld\n", imageDef->nFrameWidth); 3949 printf(" nFrameHeight = %ld\n", imageDef->nFrameHeight); 3950 printf(" nStride = %ld\n", imageDef->nStride); 3951 3952 printf(" eCompressionFormat = %s\n", 3953 imageCompressionFormatString(imageDef->eCompressionFormat)); 3954 3955 printf(" eColorFormat = %s\n", 3956 colorFormatString(imageDef->eColorFormat)); 3957 3958 break; 3959 } 3960 3961 case OMX_PortDomainVideo: 3962 { 3963 OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video; 3964 3965 printf("\n"); 3966 printf(" // Video\n"); 3967 printf(" nFrameWidth = %ld\n", videoDef->nFrameWidth); 3968 printf(" nFrameHeight = %ld\n", videoDef->nFrameHeight); 3969 printf(" nStride = %ld\n", videoDef->nStride); 3970 3971 printf(" eCompressionFormat = %s\n", 3972 videoCompressionFormatString(videoDef->eCompressionFormat)); 3973 3974 printf(" eColorFormat = %s\n", 3975 colorFormatString(videoDef->eColorFormat)); 3976 3977 break; 3978 } 3979 3980 case OMX_PortDomainAudio: 3981 { 3982 OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio; 3983 3984 printf("\n"); 3985 printf(" // Audio\n"); 3986 printf(" eEncoding = %s\n", 3987 audioCodingTypeString(audioDef->eEncoding)); 3988 3989 if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) { 3990 OMX_AUDIO_PARAM_PCMMODETYPE params; 3991 InitOMXParams(¶ms); 3992 params.nPortIndex = portIndex; 3993 3994 err = mOMX->getParameter( 3995 mNode, OMX_IndexParamAudioPcm, ¶ms, sizeof(params)); 3996 CHECK_EQ(err, (status_t)OK); 3997 3998 printf(" nSamplingRate = %ld\n", params.nSamplingRate); 3999 printf(" nChannels = %ld\n", params.nChannels); 4000 printf(" bInterleaved = %d\n", params.bInterleaved); 4001 printf(" nBitPerSample = %ld\n", params.nBitPerSample); 4002 4003 printf(" eNumData = %s\n", 4004 params.eNumData == OMX_NumericalDataSigned 4005 ? "signed" : "unsigned"); 4006 4007 printf(" ePCMMode = %s\n", audioPCMModeString(params.ePCMMode)); 4008 } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) { 4009 OMX_AUDIO_PARAM_AMRTYPE amr; 4010 InitOMXParams(&amr); 4011 amr.nPortIndex = portIndex; 4012 4013 err = mOMX->getParameter( 4014 mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr)); 4015 CHECK_EQ(err, (status_t)OK); 4016 4017 printf(" nChannels = %ld\n", amr.nChannels); 4018 printf(" eAMRBandMode = %s\n", 4019 amrBandModeString(amr.eAMRBandMode)); 4020 printf(" eAMRFrameFormat = %s\n", 4021 amrFrameFormatString(amr.eAMRFrameFormat)); 4022 } 4023 4024 break; 4025 } 4026 4027 default: 4028 { 4029 printf(" // Unknown\n"); 4030 break; 4031 } 4032 } 4033 4034 printf("}\n"); 4035} 4036 4037status_t OMXCodec::initNativeWindow() { 4038 // Enable use of a GraphicBuffer as the output for this node. This must 4039 // happen before getting the IndexParamPortDefinition parameter because it 4040 // will affect the pixel format that the node reports. 4041 status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE); 4042 if (err != 0) { 4043 return err; 4044 } 4045 4046 return OK; 4047} 4048 4049void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) { 4050 mOutputFormat = new MetaData; 4051 mOutputFormat->setCString(kKeyDecoderComponent, mComponentName); 4052 if (mIsEncoder) { 4053 int32_t timeScale; 4054 if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) { 4055 mOutputFormat->setInt32(kKeyTimeScale, timeScale); 4056 } 4057 } 4058 4059 OMX_PARAM_PORTDEFINITIONTYPE def; 4060 InitOMXParams(&def); 4061 def.nPortIndex = kPortIndexOutput; 4062 4063 status_t err = mOMX->getParameter( 4064 mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); 4065 CHECK_EQ(err, (status_t)OK); 4066 4067 switch (def.eDomain) { 4068 case OMX_PortDomainImage: 4069 { 4070 OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image; 4071 CHECK_EQ((int)imageDef->eCompressionFormat, 4072 (int)OMX_IMAGE_CodingUnused); 4073 4074 mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW); 4075 mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat); 4076 mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth); 4077 mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight); 4078 break; 4079 } 4080 4081 case OMX_PortDomainAudio: 4082 { 4083 OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio; 4084 4085 if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) { 4086 OMX_AUDIO_PARAM_PCMMODETYPE params; 4087 InitOMXParams(¶ms); 4088 params.nPortIndex = kPortIndexOutput; 4089 4090 err = mOMX->getParameter( 4091 mNode, OMX_IndexParamAudioPcm, ¶ms, sizeof(params)); 4092 CHECK_EQ(err, (status_t)OK); 4093 4094 CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned); 4095 CHECK_EQ(params.nBitPerSample, 16u); 4096 CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear); 4097 4098 int32_t numChannels, sampleRate; 4099 inputFormat->findInt32(kKeyChannelCount, &numChannels); 4100 inputFormat->findInt32(kKeySampleRate, &sampleRate); 4101 4102 if ((OMX_U32)numChannels != params.nChannels) { 4103 LOGW("Codec outputs a different number of channels than " 4104 "the input stream contains (contains %d channels, " 4105 "codec outputs %ld channels).", 4106 numChannels, params.nChannels); 4107 } 4108 4109 if (sampleRate != (int32_t)params.nSamplingRate) { 4110 LOGW("Codec outputs at different sampling rate than " 4111 "what the input stream contains (contains data at " 4112 "%d Hz, codec outputs %lu Hz)", 4113 sampleRate, params.nSamplingRate); 4114 } 4115 4116 mOutputFormat->setCString( 4117 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW); 4118 4119 // Use the codec-advertised number of channels, as some 4120 // codecs appear to output stereo even if the input data is 4121 // mono. If we know the codec lies about this information, 4122 // use the actual number of channels instead. 4123 mOutputFormat->setInt32( 4124 kKeyChannelCount, 4125 (mQuirks & kDecoderLiesAboutNumberOfChannels) 4126 ? numChannels : params.nChannels); 4127 4128 mOutputFormat->setInt32(kKeySampleRate, params.nSamplingRate); 4129 } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) { 4130 OMX_AUDIO_PARAM_AMRTYPE amr; 4131 InitOMXParams(&amr); 4132 amr.nPortIndex = kPortIndexOutput; 4133 4134 err = mOMX->getParameter( 4135 mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr)); 4136 CHECK_EQ(err, (status_t)OK); 4137 4138 CHECK_EQ(amr.nChannels, 1u); 4139 mOutputFormat->setInt32(kKeyChannelCount, 1); 4140 4141 if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0 4142 && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) { 4143 mOutputFormat->setCString( 4144 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB); 4145 mOutputFormat->setInt32(kKeySampleRate, 8000); 4146 } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0 4147 && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) { 4148 mOutputFormat->setCString( 4149 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB); 4150 mOutputFormat->setInt32(kKeySampleRate, 16000); 4151 } else { 4152 CHECK(!"Unknown AMR band mode."); 4153 } 4154 } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) { 4155 mOutputFormat->setCString( 4156 kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC); 4157 int32_t numChannels, sampleRate, bitRate; 4158 inputFormat->findInt32(kKeyChannelCount, &numChannels); 4159 inputFormat->findInt32(kKeySampleRate, &sampleRate); 4160 inputFormat->findInt32(kKeyBitRate, &bitRate); 4161 mOutputFormat->setInt32(kKeyChannelCount, numChannels); 4162 mOutputFormat->setInt32(kKeySampleRate, sampleRate); 4163 mOutputFormat->setInt32(kKeyBitRate, bitRate); 4164 } else { 4165 CHECK(!"Should not be here. Unknown audio encoding."); 4166 } 4167 break; 4168 } 4169 4170 case OMX_PortDomainVideo: 4171 { 4172 OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video; 4173 4174 if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) { 4175 mOutputFormat->setCString( 4176 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW); 4177 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) { 4178 mOutputFormat->setCString( 4179 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4); 4180 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) { 4181 mOutputFormat->setCString( 4182 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263); 4183 } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) { 4184 mOutputFormat->setCString( 4185 kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC); 4186 } else { 4187 CHECK(!"Unknown compression format."); 4188 } 4189 4190 mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth); 4191 mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight); 4192 mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat); 4193 4194 if (!mIsEncoder) { 4195 OMX_CONFIG_RECTTYPE rect; 4196 InitOMXParams(&rect); 4197 rect.nPortIndex = kPortIndexOutput; 4198 status_t err = 4199 mOMX->getConfig( 4200 mNode, OMX_IndexConfigCommonOutputCrop, 4201 &rect, sizeof(rect)); 4202 4203 if (err == OK) { 4204 CHECK_GE(rect.nLeft, 0); 4205 CHECK_GE(rect.nTop, 0); 4206 CHECK_GE(rect.nWidth, 0u); 4207 CHECK_GE(rect.nHeight, 0u); 4208 CHECK_LE(rect.nLeft + rect.nWidth - 1, video_def->nFrameWidth); 4209 CHECK_LE(rect.nTop + rect.nHeight - 1, video_def->nFrameHeight); 4210 4211 mOutputFormat->setRect( 4212 kKeyCropRect, 4213 rect.nLeft, 4214 rect.nTop, 4215 rect.nLeft + rect.nWidth - 1, 4216 rect.nTop + rect.nHeight - 1); 4217 } else { 4218 mOutputFormat->setRect( 4219 kKeyCropRect, 4220 0, 0, 4221 video_def->nFrameWidth - 1, 4222 video_def->nFrameHeight - 1); 4223 } 4224 } 4225 4226 break; 4227 } 4228 4229 default: 4230 { 4231 CHECK(!"should not be here, neither audio nor video."); 4232 break; 4233 } 4234 } 4235 4236 // If the input format contains rotation information, flag the output 4237 // format accordingly. 4238 4239 int32_t rotationDegrees; 4240 if (mSource->getFormat()->findInt32(kKeyRotation, &rotationDegrees)) { 4241 mOutputFormat->setInt32(kKeyRotation, rotationDegrees); 4242 } 4243} 4244 4245status_t OMXCodec::pause() { 4246 Mutex::Autolock autoLock(mLock); 4247 4248 mPaused = true; 4249 4250 return OK; 4251} 4252 4253//////////////////////////////////////////////////////////////////////////////// 4254 4255status_t QueryCodecs( 4256 const sp<IOMX> &omx, 4257 const char *mime, bool queryDecoders, 4258 Vector<CodecCapabilities> *results) { 4259 results->clear(); 4260 4261 for (int index = 0;; ++index) { 4262 const char *componentName; 4263 4264 if (!queryDecoders) { 4265 componentName = GetCodec( 4266 kEncoderInfo, sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]), 4267 mime, index); 4268 } else { 4269 componentName = GetCodec( 4270 kDecoderInfo, sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]), 4271 mime, index); 4272 } 4273 4274 if (!componentName) { 4275 return OK; 4276 } 4277 4278 if (strncmp(componentName, "OMX.", 4)) { 4279 // Not an OpenMax component but a software codec. 4280 4281#if HAVE_SOFTWARE_DECODERS 4282 results->push(); 4283 CodecCapabilities *caps = &results->editItemAt(results->size() - 1); 4284 caps->mComponentName = componentName; 4285#endif 4286 4287 continue; 4288 } 4289 4290 sp<OMXCodecObserver> observer = new OMXCodecObserver; 4291 IOMX::node_id node; 4292 status_t err = omx->allocateNode(componentName, observer, &node); 4293 4294 if (err != OK) { 4295 continue; 4296 } 4297 4298 OMXCodec::setComponentRole(omx, node, !queryDecoders, mime); 4299 4300 results->push(); 4301 CodecCapabilities *caps = &results->editItemAt(results->size() - 1); 4302 caps->mComponentName = componentName; 4303 4304 OMX_VIDEO_PARAM_PROFILELEVELTYPE param; 4305 InitOMXParams(¶m); 4306 4307 param.nPortIndex = queryDecoders ? 0 : 1; 4308 4309 for (param.nProfileIndex = 0;; ++param.nProfileIndex) { 4310 err = omx->getParameter( 4311 node, OMX_IndexParamVideoProfileLevelQuerySupported, 4312 ¶m, sizeof(param)); 4313 4314 if (err != OK) { 4315 break; 4316 } 4317 4318 CodecProfileLevel profileLevel; 4319 profileLevel.mProfile = param.eProfile; 4320 profileLevel.mLevel = param.eLevel; 4321 4322 caps->mProfileLevels.push(profileLevel); 4323 } 4324 4325 // Color format query 4326 OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat; 4327 InitOMXParams(&portFormat); 4328 portFormat.nPortIndex = queryDecoders ? 1 : 0; 4329 for (portFormat.nIndex = 0;; ++portFormat.nIndex) { 4330 err = omx->getParameter( 4331 node, OMX_IndexParamVideoPortFormat, 4332 &portFormat, sizeof(portFormat)); 4333 if (err != OK) { 4334 break; 4335 } 4336 caps->mColorFormats.push(portFormat.eColorFormat); 4337 } 4338 4339 CHECK_EQ(omx->freeNode(node), (status_t)OK); 4340 } 4341} 4342 4343void OMXCodec::restorePatchedDataPointer(BufferInfo *info) { 4344 CHECK(mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)); 4345 CHECK(mOMXLivesLocally); 4346 4347 OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)info->mBuffer; 4348 header->pBuffer = (OMX_U8 *)info->mData; 4349} 4350 4351} // namespace android 4352