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