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