2 * Copyright 2012 Michael Chen <omxcodec@gmail.com>
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #define LOG_TAG "SoftFFmpegAudio"
19 #include <utils/Log.h>
21 #include "SoftFFmpegAudio.h"
23 #include <media/stagefright/foundation/ADebug.h>
24 #include <media/stagefright/foundation/hexdump.h>
25 #include <media/stagefright/MediaDefs.h>
27 #include "utils/common_utils.h"
28 #include "utils/ffmpeg_utils.h"
37 * Note: DECLARE_ALIGNED should move from "*.h" to here, otherwise
38 * "Fatal signal 7 (SIGBUS)"!!! SIGBUS is because of an alignment exception
40 DECLARE_ALIGNED(16, uint8_t, mAudioBuf2)[AVCODEC_MAX_AUDIO_FRAME_SIZE * 4];
45 static void InitOMXParams(T *params) {
46 params->nSize = sizeof(T);
47 params->nVersion.s.nVersionMajor = 1;
48 params->nVersion.s.nVersionMinor = 0;
49 params->nVersion.s.nRevision = 0;
50 params->nVersion.s.nStep = 0;
53 SoftFFmpegAudio::SoftFFmpegAudio(
55 const OMX_CALLBACKTYPE *callbacks,
57 OMX_COMPONENTTYPE **component)
58 : SimpleSoftOMXComponent(name, callbacks, appData, component),
63 mExtradataReady(false),
64 mIgnoreExtradata(false),
65 mFlushComplete(false),
66 mSignalledError(false),
77 mSamplingFmt(AV_SAMPLE_FMT_S16),
78 mAudioConfigChanged(false),
79 mOutputPortSettingsChange(NONE) {
80 if (!strcmp(name, "OMX.ffmpeg.mp3.decoder")) {
82 mIgnoreExtradata = true;
83 } else if (!strcmp(name, "OMX.ffmpeg.mp1.decoder")) {
85 } else if (!strcmp(name, "OMX.ffmpeg.mp2.decoder")) {
87 } else if (!strcmp(name, "OMX.ffmpeg.aac.decoder")) {
89 } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
91 } else if (!strcmp(name, "OMX.ffmpeg.wma.decoder")) {
93 } else if (!strcmp(name, "OMX.ffmpeg.dts.decoder")) {
95 } else if (!strcmp(name, "OMX.ffmpeg.ra.decoder")) {
97 } else if (strcmp(name, "OMX.ffmpeg.ac3.decoder")) {
99 } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
105 LOGV("SoftFFmpegAudio component: %s", name);
108 CHECK_EQ(initDecoder(), (status_t)OK);
111 SoftFFmpegAudio::~SoftFFmpegAudio() {
113 LOGV("~SoftFFmpegAudio");
118 void SoftFFmpegAudio::initPorts() {
119 OMX_PARAM_PORTDEFINITIONTYPE def;
123 def.eDir = OMX_DirInput;
124 def.nBufferCountMin = kNumBuffers;
125 def.nBufferCountActual = def.nBufferCountMin;
126 def.nBufferSize = 20480; // 8192 is too small
127 if (mMode == MODE_APE)
128 def.nBufferSize = 204800; // large!
129 def.bEnabled = OMX_TRUE;
130 def.bPopulated = OMX_FALSE;
131 def.eDomain = OMX_PortDomainAudio;
132 def.bBuffersContiguous = OMX_FALSE;
133 def.nBufferAlignment = 1;
137 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
138 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
141 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
142 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
145 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
146 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
149 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AAC);
150 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
153 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AC3);
155 //def.format.audio.eEncoding = OMX_AUDIO_CodingAC3;
156 def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect; // right?? orz
159 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_WMA);
160 def.format.audio.eEncoding = OMX_AUDIO_CodingWMA;
163 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_RA);
164 def.format.audio.eEncoding = OMX_AUDIO_CodingRA;
167 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_APE);
168 def.format.audio.eEncoding = OMX_AUDIO_CodingAPE;
171 CHECK(!"Should not be here. Unsupported mime type and compression format");
175 def.format.audio.pNativeRender = NULL;
176 def.format.audio.bFlagErrorConcealment = OMX_FALSE;
181 def.eDir = OMX_DirOutput;
182 def.nBufferCountMin = kNumBuffers;
183 def.nBufferCountActual = def.nBufferCountMin;
184 def.nBufferSize = kOutputBufferSize;
185 def.bEnabled = OMX_TRUE;
186 def.bPopulated = OMX_FALSE;
187 def.eDomain = OMX_PortDomainAudio;
188 def.bBuffersContiguous = OMX_FALSE;
189 def.nBufferAlignment = 2;
191 def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
192 def.format.audio.pNativeRender = NULL;
193 def.format.audio.bFlagErrorConcealment = OMX_FALSE;
194 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
199 void SoftFFmpegAudio::setAVCtxToDefault(AVCodecContext *avctx, const AVCodec *codec) {
202 avctx->workaround_bugs = 1;
204 if(avctx->lowres > codec->max_lowres){
205 LOGW("The maximum value for lowres supported by the decoder is %d",
207 avctx->lowres= codec->max_lowres;
209 avctx->idct_algo = 0;
210 avctx->skip_frame = AVDISCARD_DEFAULT;
211 avctx->skip_idct = AVDISCARD_DEFAULT;
212 avctx->skip_loop_filter = AVDISCARD_DEFAULT;
213 avctx->error_concealment = 3;
215 if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
216 if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
217 if(codec->capabilities & CODEC_CAP_DR1)
218 avctx->flags |= CODEC_FLAG_EMU_EDGE;
221 status_t SoftFFmpegAudio::initDecoder() {
224 status = initFFmpeg();
228 mCtx = avcodec_alloc_context3(NULL);
231 LOGE("avcodec_alloc_context failed.");
235 mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
238 mCtx->codec_id = CODEC_ID_MP3;
241 mCtx->codec_id = CODEC_ID_MP1;
244 mCtx->codec_id = CODEC_ID_MP2;
247 mCtx->codec_id = CODEC_ID_AAC;
250 mCtx->codec_id = CODEC_ID_AC3;
253 mCtx->codec_id = CODEC_ID_WMAV2; // FIXME, CODEC_ID_WMAV1 or CODEC_ID_WMAV2?
256 mCtx->codec_id = CODEC_ID_COOK; // FIXME
259 mCtx->codec_id = CODEC_ID_APE;
262 CHECK(!"Should not be here. Unsupported codec");
266 mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
269 LOGE("find codec failed");
273 setAVCtxToDefault(mCtx, mCtx->codec);
275 mCtx->channels = mNumChannels;
276 mCtx->sample_rate = mSamplingRate;
277 mCtx->bit_rate = mBitRate;
278 mCtx->sample_fmt = mSamplingFmt;
280 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
281 mAudioSrcFreq = mAudioTgtFreq = mSamplingRate;
282 mAudioSrcChannels = mAudioTgtChannels = mNumChannels;
283 mAudioSrcChannelLayout = mAudioTgtChannelLayout =
284 av_get_default_channel_layout(mNumChannels);
286 memset(mSilenceBuffer, 0, kOutputBufferSize);
291 void SoftFFmpegAudio::deInitDecoder() {
293 //avcodec_flush_buffers(mCtx); // is it necessary? crash sometimes if call it
294 if (!mCtx->extradata) {
295 av_free(mCtx->extradata);
296 mCtx->extradata = NULL;
297 mCtx->extradata_size = 0;
311 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
312 OMX_INDEXTYPE index, OMX_PTR params) {
313 int32_t channels = 0;
314 int32_t sampling_rate = 0;
317 case OMX_IndexParamAudioAac:
319 OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
320 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
322 if (aacParams->nPortIndex != 0) {
323 return OMX_ErrorUndefined;
326 aacParams->nBitRate = 0;
327 aacParams->nAudioBandWidth = 0;
328 aacParams->nAACtools = 0;
329 aacParams->nAACERtools = 0;
330 aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
331 aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
332 aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
334 aacParams->nChannels = mNumChannels;
335 aacParams->nSampleRate = mSamplingRate;
337 return OMX_ErrorNone;
339 case OMX_IndexParamAudioWma:
341 OMX_AUDIO_PARAM_WMATYPE *wmaParams =
342 (OMX_AUDIO_PARAM_WMATYPE *)params;
344 if (wmaParams->nPortIndex != 0) {
345 return OMX_ErrorUndefined;
348 wmaParams->nChannels = 0;
349 wmaParams->nSamplingRate = 0;
350 wmaParams->nBitRate = 0;
351 wmaParams->eFormat = OMX_AUDIO_WMAFormatUnused;
353 return OMX_ErrorNone;
355 case OMX_IndexParamAudioRa:
357 OMX_AUDIO_PARAM_RATYPE *raParams =
358 (OMX_AUDIO_PARAM_RATYPE *)params;
360 if (raParams->nPortIndex != 0) {
361 return OMX_ErrorUndefined;
364 raParams->nChannels = 0;
365 raParams->nSamplingRate = 0;
366 raParams->eFormat = OMX_AUDIO_RAFormatUnused;
368 return OMX_ErrorNone;
370 case OMX_IndexParamAudioApe:
372 OMX_AUDIO_PARAM_APETYPE *apeParams =
373 (OMX_AUDIO_PARAM_APETYPE *)params;
375 if (apeParams->nPortIndex != 0) {
376 return OMX_ErrorUndefined;
379 apeParams->nChannels = 0;
380 apeParams->nSamplingRate = 0;
382 return OMX_ErrorNone;
384 case OMX_IndexParamAudioPcm:
386 OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
387 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
389 if (pcmParams->nPortIndex > 1) {
390 return OMX_ErrorUndefined;
393 pcmParams->eNumData = OMX_NumericalDataSigned;
394 pcmParams->eEndian = OMX_EndianBig;
395 pcmParams->bInterleaved = OMX_TRUE;
396 pcmParams->nBitPerSample = 16;
397 pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
398 pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
399 pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
401 LOGV("audio config change");
403 channels = mNumChannels >= 2 ? 2 : 1;
404 sampling_rate = mSamplingRate;
405 // 4000 <= nSamplingRate <= 48000
406 if (mSamplingRate < 4000) {
407 sampling_rate = 4000;
408 } else if (mSamplingRate > 48000) {
409 sampling_rate = 48000;
412 // update src and target(except aac), only once!
413 mAudioSrcChannels = mAudioTgtChannels = channels;
414 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
415 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
416 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
418 pcmParams->nChannels = channels;
419 pcmParams->nSamplingRate = sampling_rate;
421 return OMX_ErrorNone;
425 return SimpleSoftOMXComponent::internalGetParameter(index, params);
429 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
430 OMX_INDEXTYPE index, const OMX_PTR params) {
431 int32_t channels = 0;
432 int32_t sampling_rate = 0;
435 case OMX_IndexParamStandardComponentRole:
437 const OMX_PARAM_COMPONENTROLETYPE *roleParams =
438 (const OMX_PARAM_COMPONENTROLETYPE *)params;
440 bool supported = true;
443 if (strncmp((const char *)roleParams->cRole,
444 "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
448 if (strncmp((const char *)roleParams->cRole,
449 "audio_decoder.mp1", OMX_MAX_STRINGNAME_SIZE - 1))
453 if (strncmp((const char *)roleParams->cRole,
454 "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
458 if (strncmp((const char *)roleParams->cRole,
459 "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
463 if (strncmp((const char *)roleParams->cRole,
464 "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
468 if (strncmp((const char *)roleParams->cRole,
469 "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
473 if (strncmp((const char *)roleParams->cRole,
474 "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
478 if (strncmp((const char *)roleParams->cRole,
479 "audio_decoder.ape", OMX_MAX_STRINGNAME_SIZE - 1))
483 CHECK(!"Should not be here. Unsupported role.");
487 LOGE("unsupported role: %s", (const char *)roleParams->cRole);
488 return OMX_ErrorUndefined;
491 return OMX_ErrorNone;
493 case OMX_IndexParamAudioAac:
495 const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
496 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
498 if (aacParams->nPortIndex != 0) {
499 return OMX_ErrorUndefined;
502 mNumChannels = aacParams->nChannels;
503 mSamplingRate = aacParams->nSampleRate;
505 channels = mNumChannels >= 2 ? 2 : 1;
506 sampling_rate = mSamplingRate;
507 // 4000 <= nSamplingRate <= 48000
508 if (mSamplingRate < 4000) {
509 sampling_rate = 4000;
510 } else if (mSamplingRate > 48000) {
511 sampling_rate = 48000;
514 // update src and target(only aac), only once!
515 mAudioSrcChannels = mAudioTgtChannels = channels;
516 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
517 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
518 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
520 LOGV("got OMX_IndexParamAudioAac, mNumChannels: %d, mSamplingRate: %d",
521 mNumChannels, mSamplingRate);
523 return OMX_ErrorNone;
525 case OMX_IndexParamAudioWma:
527 OMX_AUDIO_PARAM_WMATYPE *wmaParams =
528 (OMX_AUDIO_PARAM_WMATYPE *)params;
530 if (wmaParams->nPortIndex != 0) {
531 return OMX_ErrorUndefined;
534 if (wmaParams->eFormat == OMX_AUDIO_WMAFormat7) {
535 mCtx->codec_id = CODEC_ID_WMAV2;
536 } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat8) {
537 mCtx->codec_id = CODEC_ID_WMAPRO;
538 } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat9) {
539 mCtx->codec_id = CODEC_ID_WMALOSSLESS;
541 LOGE("unsupported wma codec: 0x%x", wmaParams->eFormat);
542 return OMX_ErrorUndefined;
545 mNumChannels = wmaParams->nChannels;
546 mSamplingRate = wmaParams->nSamplingRate;
547 mBitRate = wmaParams->nBitRate;
550 mCtx->bit_rate = mBitRate;
552 channels = mNumChannels >= 2 ? 2 : 1;
553 sampling_rate = mSamplingRate;
554 // 4000 <= nSamplingRate <= 48000
555 if (mSamplingRate < 4000) {
556 sampling_rate = 4000;
557 } else if (mSamplingRate > 48000) {
558 sampling_rate = 48000;
561 // update src and target(only wma), only once!
562 mAudioSrcChannels = mAudioTgtChannels = channels;
563 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
564 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
565 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
567 LOGV("got OMX_IndexParamAudioWma, mNumChannels: %d, mSamplingRate: %d, mBitRate: %d",
568 mNumChannels, mSamplingRate, mBitRate);
570 return OMX_ErrorNone;
572 case OMX_IndexParamAudioRa:
574 OMX_AUDIO_PARAM_RATYPE *raParams =
575 (OMX_AUDIO_PARAM_RATYPE *)params;
577 if (raParams->nPortIndex != 0) {
578 return OMX_ErrorUndefined;
581 mCtx->codec_id = CODEC_ID_COOK;
583 mNumChannels = raParams->nChannels;
584 mSamplingRate = raParams->nSamplingRate;
585 // FIXME, HACK!!!, I use the nNumRegions parameter pass blockAlign!!!
586 // the cook audio codec need blockAlign!
587 mBlockAlign = raParams->nNumRegions;
589 // cook decoder need block_align
590 mCtx->block_align = mBlockAlign;
592 channels = mNumChannels >= 2 ? 2 : 1;
593 sampling_rate = mSamplingRate;
594 // 4000 <= nSamplingRate <= 48000
595 if (mSamplingRate < 4000) {
596 sampling_rate = 4000;
597 } else if (mSamplingRate > 48000) {
598 sampling_rate = 48000;
601 // update src and target(only wma), only once!
602 mAudioSrcChannels = mAudioTgtChannels = channels;
603 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
604 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
605 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
607 LOGV("got OMX_IndexParamAudioRa, mNumChannels: %d, mSamplingRate: %d, mBlockAlign: %d",
608 mNumChannels, mSamplingRate, mBlockAlign);
610 return OMX_ErrorNone;
612 case OMX_IndexParamAudioApe:
614 OMX_AUDIO_PARAM_APETYPE *apeParams =
615 (OMX_AUDIO_PARAM_APETYPE *)params;
617 if (apeParams->nPortIndex != 0) {
618 return OMX_ErrorUndefined;
621 mCtx->codec_id = CODEC_ID_APE;
623 mNumChannels = apeParams->nChannels;
624 mSamplingRate = apeParams->nSamplingRate;
626 // ape decoder need bits_per_coded_sample
627 mCtx->bits_per_coded_sample = apeParams->nBitsPerSample;
629 channels = mNumChannels >= 2 ? 2 : 1;
630 sampling_rate = mSamplingRate;
631 // 4000 <= nSamplingRate <= 48000
632 if (mSamplingRate < 4000) {
633 sampling_rate = 4000;
634 } else if (mSamplingRate > 48000) {
635 sampling_rate = 48000;
638 // update src and target(only wma), only once!
639 mAudioSrcChannels = mAudioTgtChannels = channels;
640 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
641 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
642 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
644 LOGV("got OMX_IndexParamAudioApe, mNumChannels: %d, mSamplingRate: %d, nBitsPerSample: %d",
645 mNumChannels, mSamplingRate, apeParams->nBitsPerSample);
647 return OMX_ErrorNone;
650 LOGI("internalSetParameter, index: 0x%x", index);
651 return SimpleSoftOMXComponent::internalSetParameter(index, params);
655 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
659 int64_t decChannelLayout;
660 int32_t inputBufferUsedLength = 0;
661 BufferInfo *inInfo = NULL;
662 OMX_BUFFERHEADERTYPE *inHeader = NULL;
664 if (mSignalledError || mOutputPortSettingsChange != NONE) {
668 List<BufferInfo *> &inQueue = getPortQueue(0);
669 List<BufferInfo *> &outQueue = getPortQueue(1);
671 while ((!inQueue.empty() || mInputBufferSize > 0 ||
672 mAudioBufferSize > 0 || mFlushComplete) && !outQueue.empty()) {
673 if (!inQueue.empty() || mInputBufferSize > 0) {
674 inInfo = *inQueue.begin();
675 inHeader = inInfo->mHeader;
681 BufferInfo *outInfo = *outQueue.begin();
682 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
684 if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
685 inQueue.erase(inQueue.begin());
686 inInfo->mOwnedByUs = false;
687 notifyEmptyBufferDone(inHeader);
691 if (mReceivedEOS && (mFlushComplete || !(mCtx->codec->capabilities & CODEC_CAP_DELAY))) {
692 outHeader->nFilledLen = 0;
693 outHeader->nFlags = OMX_BUFFERFLAG_EOS;
695 outQueue.erase(outQueue.begin());
696 outInfo->mOwnedByUs = false;
697 notifyFillBufferDone(outHeader);
701 if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
702 LOGI("got extradata, ignore: %d, size: %lu", mIgnoreExtradata, inHeader->nFilledLen);
703 hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
704 if (!mExtradataReady && !mIgnoreExtradata) {
705 int orig_extradata_size = mCtx->extradata_size;
706 mCtx->extradata_size += inHeader->nFilledLen;
707 mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
708 mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
709 if (!mCtx->extradata) {
710 LOGE("ffmpeg audio decoder failed to alloc extradata memory.");
711 notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
712 mSignalledError = true;
716 memcpy(mCtx->extradata + orig_extradata_size,
717 inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
718 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
720 inInfo->mOwnedByUs = false;
721 inQueue.erase(inQueue.begin());
723 notifyEmptyBufferDone(inHeader);
728 if (mIgnoreExtradata) {
729 LOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
730 inInfo->mOwnedByUs = false;
731 inQueue.erase(inQueue.begin());
733 notifyEmptyBufferDone(inHeader);
741 if (!mExtradataReady && !mIgnoreExtradata) {
742 LOGI("extradata is ready");
743 hexdump(mCtx->extradata, mCtx->extradata_size);
744 mExtradataReady = true;
747 // find decoder again as codec_id may have changed
748 mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
750 LOGE("ffmpeg audio decoder failed to find codec");
751 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
752 mSignalledError = true;
756 setAVCtxToDefault(mCtx, mCtx->codec);
758 LOGI("open ffmpeg decoder now");
759 err = avcodec_open2(mCtx, mCtx->codec, NULL);
761 print_error("avcodec_open2", err);
762 LOGE("ffmpeg audio decoder failed to initialize. (%d)", err);
763 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
764 mSignalledError = true;
768 LOGI("open ffmpeg audio decoder, mCtx sample_rate: %d, channels: %d, channel_layout: %llu, sample_fmt: %s",
769 mCtx->sample_rate, mCtx->channels, mCtx->channel_layout, av_get_sample_fmt_name(mCtx->sample_fmt));
772 /* update the audio clock with the pts */
773 if (inHeader && inHeader->nOffset == 0) {
774 mAnchorTimeUs = inHeader->nTimeStamp;
775 mInputBufferSize = inHeader->nFilledLen;
778 if (inHeader && mAudioBufferSize == 0 && !mFlushComplete) {
780 memset(&pkt, 0, sizeof(pkt));
781 av_init_packet(&pkt);
782 if (!mFlushComplete) {
783 pkt.data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
784 pkt.size = inHeader->nFilledLen;
785 pkt.pts = inHeader->nTimeStamp; // ingore it, we will compute it
789 pkt.pts = AV_NOPTS_VALUE;
792 LOGV("pkt size: %d, pts: %lld", pkt.size, pkt.pts);
795 if (!(mFrame = avcodec_alloc_frame())) {
796 LOGE("ffmpeg audio decoder failed to alloc memory.");
797 notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
798 mSignalledError = true;
802 avcodec_get_frame_defaults(mFrame);
806 inputBufferUsedLength = 0;
807 len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
809 LOGE("ffmpeg audio decoder failed to decode frame. consume pkt len: %d", len);
811 /* if !mAudioConfigChanged, Don't fill the out buffer */
812 if (!mAudioConfigChanged) {
813 inInfo->mOwnedByUs = false;
814 inQueue.erase(inQueue.begin());
816 notifyEmptyBufferDone(inHeader);
819 mInputBufferSize = 0; // need?
823 //inputBufferUsedLength = inHeader->nFilledLen;
824 /* if error, we skip the frame and play silence instead */
825 mPAudioBuffer = mSilenceBuffer;
826 mAudioBufferSize = kOutputBufferSize;
830 LOGV("ffmpeg audio decoder, consume pkt len: %d", len);
834 inputBufferUsedLength = inHeader->nFilledLen;
836 inputBufferUsedLength = len;
838 CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
839 inHeader->nOffset += inputBufferUsedLength;
840 inHeader->nFilledLen -= inputBufferUsedLength;
841 mInputBufferSize -= inputBufferUsedLength;
842 if (inHeader->nFilledLen == 0) {
843 inInfo->mOwnedByUs = false;
844 inQueue.erase(inQueue.begin());
846 notifyEmptyBufferDone(inHeader);
849 mInputBufferSize = 0;
853 LOGI("ffmpeg audio decoder failed to get frame.");
854 /* stop sending empty packets if the decoder is finished */
855 if (!pkt.data && mCtx->codec->capabilities & CODEC_CAP_DELAY)
856 mFlushComplete = true;
861 * FIXME, check mAudioConfigChanged when the first time you call the audio4!
862 * mCtx->sample_rate and mCtx->channels may be changed by audio decoder later, why???
864 if (!mAudioConfigChanged) {
865 //if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate || mCtx->sample_fmt != mSamplingFmt) {
866 if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate) {
867 LOGI("audio OMX_EventPortSettingsChanged, mCtx->channels: %d, mNumChannels: %d, mCtx->sample_rate: %d, mSamplingRate: %d, mCtx->sample_fmt: %s, mSamplingFmt: %s",
868 mCtx->channels, mNumChannels, mCtx->sample_rate, mSamplingRate,
869 av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mSamplingFmt));
870 mNumChannels = mCtx->channels;
871 mSamplingRate = mCtx->sample_rate;
872 mSamplingFmt = mCtx->sample_fmt;
873 mAudioConfigChanged = true;
874 notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
875 mOutputPortSettingsChange = AWAITING_DISABLED;
878 // match with the default, set mAudioConfigChanged true anyway!
879 mAudioConfigChanged = true;
880 mSamplingFmt = mCtx->sample_fmt;
884 dataSize = av_samples_get_buffer_size(NULL, mNumChannels, mFrame->nb_samples, mSamplingFmt, 1);
887 LOGV("audio decoder, nb_samples: %d, get buffer size: %d", mFrame->nb_samples, dataSize);
888 LOGV("audio decoder: mCtx channel_layout: %llu, channels: %d, channels_from_layout: %d\n",
889 mCtx->channel_layout, mCtx->channels, av_get_channel_layout_nb_channels(mCtx->channel_layout));
892 decChannelLayout = av_get_default_channel_layout(mNumChannels);
893 if (mSamplingFmt != mAudioSrcFmt ||
894 decChannelLayout != mAudioSrcChannelLayout ||
895 mSamplingRate != mAudioSrcFreq ) {
898 mSwrCtx = swr_alloc_set_opts(NULL,
899 mAudioTgtChannelLayout, mAudioTgtFmt, mAudioTgtFreq,
900 decChannelLayout, mSamplingFmt, mSamplingRate,
902 if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
903 LOGE("Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!",
905 av_get_sample_fmt_name(mSamplingFmt),
908 av_get_sample_fmt_name(mAudioTgtFmt),
910 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
911 mSignalledError = true;
915 LOGI("Create sample rate converter for conversion of %d Hz %s %d channels(%lld channel_layout) to %d Hz %s %d channels(%lld channel_layout)!",
917 av_get_sample_fmt_name(mSamplingFmt),
919 mAudioTgtChannelLayout,
921 av_get_sample_fmt_name(mAudioTgtFmt),
925 mAudioSrcChannelLayout = decChannelLayout;
926 mAudioSrcChannels = mNumChannels;
927 mAudioSrcFreq = mSamplingRate;
928 mAudioSrcFmt = mSamplingFmt;
932 //const uint8_t *in[] = { mFrame->data[0] };
933 const uint8_t **in = (const uint8_t **)mFrame->extended_data;
934 uint8_t *out[] = {mAudioBuf2};
935 int out_count = sizeof(mAudioBuf2) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt);
937 LOGV("swr_convert 1, out_count: %d, mFrame->nb_samples: %d, src frm: %s, tgt frm: %s",
938 out_count, mFrame->nb_samples, av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mAudioTgtFmt));
940 int len2 = swr_convert(mSwrCtx, out, out_count, in, mFrame->nb_samples);
942 LOGE("audio_resample() failed");
945 if (len2 == out_count) {
946 LOGE("warning: audio buffer is probably too small");
949 mPAudioBuffer = mAudioBuf2;
950 mAudioBufferSize = len2 * mAudioTgtChannels * av_get_bytes_per_sample(mAudioTgtFmt);
952 mPAudioBuffer = mFrame->data[0];
953 mAudioBufferSize = dataSize;
957 LOGV("ffmpeg audio decoder get frame. consume pkt len: %d, nb_samples(before resample): %d, mAudioBufferSize: %d",
958 len, mFrame->nb_samples, mAudioBufferSize);
960 } // if (inHeader && mAudioBufferSize == 0 && !mFlushComplete)
962 size_t copyToOutputBufferLen = mAudioBufferSize;
963 if (mAudioBufferSize > kOutputBufferSize)
964 copyToOutputBufferLen = kOutputBufferSize;
966 outHeader->nOffset = 0;
967 outHeader->nFilledLen = copyToOutputBufferLen;
968 outHeader->nTimeStamp = mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
969 memcpy(outHeader->pBuffer, mPAudioBuffer, copyToOutputBufferLen);
970 outHeader->nFlags = 0;
973 LOGV("ffmpeg audio decoder, fill out buffer, pts: %lld, mNumFramesOutput: %lld", outHeader->nTimeStamp, mNumFramesOutput);
976 mPAudioBuffer += copyToOutputBufferLen;
977 mAudioBufferSize -= copyToOutputBufferLen;
978 mNumFramesOutput += copyToOutputBufferLen / (av_get_bytes_per_sample(mAudioTgtFmt) * mNumChannels);
980 // reset mNumFramesOutput
981 if (mAudioBufferSize == 0) {
983 LOGV("~~~~ mAudioBufferSize, set mNumFramesOutput = 0");
985 mNumFramesOutput = 0;
988 outInfo->mOwnedByUs = false;
989 outQueue.erase(outQueue.begin());
991 notifyFillBufferDone(outHeader);
996 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
997 if (portIndex == 0 && mCtx) {
998 // Make sure that the next buffer output does not still
999 // depend on fragments from the last one decoded.
1000 avcodec_flush_buffers(mCtx);
1005 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
1006 if (portIndex != 1) {
1010 switch (mOutputPortSettingsChange) {
1014 case AWAITING_DISABLED:
1017 mOutputPortSettingsChange = AWAITING_ENABLED;
1023 CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
1025 mOutputPortSettingsChange = NONE;
1031 } // namespace android
1033 android::SoftOMXComponent *createSoftOMXComponent(
1034 const char *name, const OMX_CALLBACKTYPE *callbacks,
1035 OMX_PTR appData, OMX_COMPONENTTYPE **component) {
1036 return new android::SoftFFmpegAudio(name, callbacks, appData, component);