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