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