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