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