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