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