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