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