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