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