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