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