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