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