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.wma.decoder")) {
91 } else if (!strcmp(name, "OMX.ffmpeg.dts.decoder")) {
93 } else if (!strcmp(name, "OMX.ffmpeg.ra.decoder")) {
95 } else if (strcmp(name, "OMX.ffmpeg.ac3.decoder")) {
97 } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
103 LOGV("SoftFFmpegAudio component: %s", name);
106 CHECK_EQ(initDecoder(), (status_t)OK);
109 SoftFFmpegAudio::~SoftFFmpegAudio() {
111 LOGV("~SoftFFmpegAudio");
116 void SoftFFmpegAudio::initPorts() {
117 OMX_PARAM_PORTDEFINITIONTYPE def;
121 def.eDir = OMX_DirInput;
122 def.nBufferCountMin = kNumBuffers;
123 def.nBufferCountActual = def.nBufferCountMin;
124 if (mMode == MODE_APE) {
125 def.nBufferSize = 204800; // ape!
126 } else if (mMode == MODE_DTS) {
127 def.nBufferSize = 512000; // dts!
129 def.nBufferSize = 20480; // 8192 is too small
131 def.bEnabled = OMX_TRUE;
132 def.bPopulated = OMX_FALSE;
133 def.eDomain = OMX_PortDomainAudio;
134 def.bBuffersContiguous = OMX_FALSE;
135 def.nBufferAlignment = 1;
139 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
140 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
143 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
144 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
147 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
148 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
151 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AAC);
152 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
155 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AC3);
157 //def.format.audio.eEncoding = OMX_AUDIO_CodingAC3;
158 def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect; // right?? orz
161 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_WMA);
162 def.format.audio.eEncoding = OMX_AUDIO_CodingWMA;
165 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_RA);
166 def.format.audio.eEncoding = OMX_AUDIO_CodingRA;
169 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_APE);
170 def.format.audio.eEncoding = OMX_AUDIO_CodingAPE;
173 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_DTS);
174 def.format.audio.eEncoding = OMX_AUDIO_CodingDTS;
177 CHECK(!"Should not be here. Unsupported mime type and compression format");
181 def.format.audio.pNativeRender = NULL;
182 def.format.audio.bFlagErrorConcealment = OMX_FALSE;
187 def.eDir = OMX_DirOutput;
188 def.nBufferCountMin = kNumBuffers;
189 def.nBufferCountActual = def.nBufferCountMin;
190 def.nBufferSize = kOutputBufferSize;
191 def.bEnabled = OMX_TRUE;
192 def.bPopulated = OMX_FALSE;
193 def.eDomain = OMX_PortDomainAudio;
194 def.bBuffersContiguous = OMX_FALSE;
195 def.nBufferAlignment = 2;
197 def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
198 def.format.audio.pNativeRender = NULL;
199 def.format.audio.bFlagErrorConcealment = OMX_FALSE;
200 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
205 void SoftFFmpegAudio::setAVCtxToDefault(AVCodecContext *avctx, const AVCodec *codec) {
208 avctx->workaround_bugs = 1;
210 if(avctx->lowres > codec->max_lowres){
211 LOGW("The maximum value for lowres supported by the decoder is %d",
213 avctx->lowres= codec->max_lowres;
215 avctx->idct_algo = 0;
216 avctx->skip_frame = AVDISCARD_DEFAULT;
217 avctx->skip_idct = AVDISCARD_DEFAULT;
218 avctx->skip_loop_filter = AVDISCARD_DEFAULT;
219 avctx->error_concealment = 3;
221 if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
222 if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
223 if(codec->capabilities & CODEC_CAP_DR1)
224 avctx->flags |= CODEC_FLAG_EMU_EDGE;
227 status_t SoftFFmpegAudio::initDecoder() {
230 status = initFFmpeg();
234 mCtx = avcodec_alloc_context3(NULL);
237 LOGE("avcodec_alloc_context failed.");
241 mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
244 mCtx->codec_id = CODEC_ID_MP3;
247 mCtx->codec_id = CODEC_ID_MP1;
250 mCtx->codec_id = CODEC_ID_MP2;
253 mCtx->codec_id = CODEC_ID_AAC;
256 mCtx->codec_id = CODEC_ID_AC3;
259 mCtx->codec_id = CODEC_ID_WMAV2; // FIXME, CODEC_ID_WMAV1 or CODEC_ID_WMAV2?
262 mCtx->codec_id = CODEC_ID_COOK; // FIXME
265 mCtx->codec_id = CODEC_ID_APE;
267 mCtx->codec_id = CODEC_ID_DTS;
270 CHECK(!"Should not be here. Unsupported codec");
274 mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
277 LOGE("find codec failed");
281 setAVCtxToDefault(mCtx, mCtx->codec);
283 mCtx->channels = mNumChannels;
284 mCtx->sample_rate = mSamplingRate;
285 mCtx->bit_rate = mBitRate;
286 mCtx->sample_fmt = mSamplingFmt;
288 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
289 mAudioSrcFreq = mAudioTgtFreq = mSamplingRate;
290 mAudioSrcChannels = mAudioTgtChannels = mNumChannels;
291 mAudioSrcChannelLayout = mAudioTgtChannelLayout =
292 av_get_default_channel_layout(mNumChannels);
294 memset(mSilenceBuffer, 0, kOutputBufferSize);
299 void SoftFFmpegAudio::deInitDecoder() {
301 //avcodec_flush_buffers(mCtx); // is it necessary? crash sometimes if call it
302 if (!mCtx->extradata) {
303 av_free(mCtx->extradata);
304 mCtx->extradata = NULL;
305 mCtx->extradata_size = 0;
319 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
320 OMX_INDEXTYPE index, OMX_PTR params) {
321 int32_t channels = 0;
322 int32_t sampling_rate = 0;
325 case OMX_IndexParamAudioAac:
327 OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
328 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
330 if (aacParams->nPortIndex != 0) {
331 return OMX_ErrorUndefined;
334 aacParams->nBitRate = 0;
335 aacParams->nAudioBandWidth = 0;
336 aacParams->nAACtools = 0;
337 aacParams->nAACERtools = 0;
338 aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
339 aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
340 aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
342 aacParams->nChannels = mNumChannels;
343 aacParams->nSampleRate = mSamplingRate;
345 return OMX_ErrorNone;
347 case OMX_IndexParamAudioWma:
349 OMX_AUDIO_PARAM_WMATYPE *wmaParams =
350 (OMX_AUDIO_PARAM_WMATYPE *)params;
352 if (wmaParams->nPortIndex != 0) {
353 return OMX_ErrorUndefined;
356 wmaParams->nChannels = 0;
357 wmaParams->nSamplingRate = 0;
358 wmaParams->nBitRate = 0;
359 wmaParams->eFormat = OMX_AUDIO_WMAFormatUnused;
361 return OMX_ErrorNone;
363 case OMX_IndexParamAudioRa:
365 OMX_AUDIO_PARAM_RATYPE *raParams =
366 (OMX_AUDIO_PARAM_RATYPE *)params;
368 if (raParams->nPortIndex != 0) {
369 return OMX_ErrorUndefined;
372 raParams->nChannels = 0;
373 raParams->nSamplingRate = 0;
374 raParams->eFormat = OMX_AUDIO_RAFormatUnused;
376 return OMX_ErrorNone;
378 case OMX_IndexParamAudioApe:
380 OMX_AUDIO_PARAM_APETYPE *apeParams =
381 (OMX_AUDIO_PARAM_APETYPE *)params;
383 if (apeParams->nPortIndex != 0) {
384 return OMX_ErrorUndefined;
387 apeParams->nChannels = 0;
388 apeParams->nSamplingRate = 0;
390 return OMX_ErrorNone;
392 case OMX_IndexParamAudioDts:
394 OMX_AUDIO_PARAM_DTSTYPE *dtsParams =
395 (OMX_AUDIO_PARAM_DTSTYPE *)params;
397 if (dtsParams->nPortIndex != 0) {
398 return OMX_ErrorUndefined;
401 dtsParams->nChannels = 0;
402 dtsParams->nSamplingRate = 0;
404 return OMX_ErrorNone;
406 case OMX_IndexParamAudioPcm:
408 OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
409 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
411 if (pcmParams->nPortIndex > 1) {
412 return OMX_ErrorUndefined;
415 pcmParams->eNumData = OMX_NumericalDataSigned;
416 pcmParams->eEndian = OMX_EndianBig;
417 pcmParams->bInterleaved = OMX_TRUE;
418 pcmParams->nBitPerSample = 16;
419 pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
420 pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
421 pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
423 LOGV("audio config change");
425 channels = mNumChannels >= 2 ? 2 : 1;
426 sampling_rate = mSamplingRate;
427 // 4000 <= nSamplingRate <= 48000
428 if (mSamplingRate < 4000) {
429 sampling_rate = 4000;
430 } else if (mSamplingRate > 48000) {
431 sampling_rate = 48000;
434 // update src and target(except aac), only once!
435 mAudioSrcChannels = mAudioTgtChannels = channels;
436 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
437 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
438 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
440 pcmParams->nChannels = channels;
441 pcmParams->nSamplingRate = sampling_rate;
443 return OMX_ErrorNone;
447 return SimpleSoftOMXComponent::internalGetParameter(index, params);
451 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
452 OMX_INDEXTYPE index, const OMX_PTR params) {
453 int32_t channels = 0;
454 int32_t sampling_rate = 0;
457 case OMX_IndexParamStandardComponentRole:
459 const OMX_PARAM_COMPONENTROLETYPE *roleParams =
460 (const OMX_PARAM_COMPONENTROLETYPE *)params;
462 bool supported = true;
465 if (strncmp((const char *)roleParams->cRole,
466 "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
470 if (strncmp((const char *)roleParams->cRole,
471 "audio_decoder.mp1", OMX_MAX_STRINGNAME_SIZE - 1))
475 if (strncmp((const char *)roleParams->cRole,
476 "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
480 if (strncmp((const char *)roleParams->cRole,
481 "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
485 if (strncmp((const char *)roleParams->cRole,
486 "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
490 if (strncmp((const char *)roleParams->cRole,
491 "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
495 if (strncmp((const char *)roleParams->cRole,
496 "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
500 if (strncmp((const char *)roleParams->cRole,
501 "audio_decoder.ape", OMX_MAX_STRINGNAME_SIZE - 1))
505 if (strncmp((const char *)roleParams->cRole,
506 "audio_decoder.dts", OMX_MAX_STRINGNAME_SIZE - 1))
510 CHECK(!"Should not be here. Unsupported role.");
514 LOGE("unsupported role: %s", (const char *)roleParams->cRole);
515 return OMX_ErrorUndefined;
518 return OMX_ErrorNone;
520 case OMX_IndexParamAudioAac:
522 const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
523 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
525 if (aacParams->nPortIndex != 0) {
526 return OMX_ErrorUndefined;
529 mNumChannels = aacParams->nChannels;
530 mSamplingRate = aacParams->nSampleRate;
532 channels = mNumChannels >= 2 ? 2 : 1;
533 sampling_rate = mSamplingRate;
534 // 4000 <= nSamplingRate <= 48000
535 if (mSamplingRate < 4000) {
536 sampling_rate = 4000;
537 } else if (mSamplingRate > 48000) {
538 sampling_rate = 48000;
541 // update src and target(only aac), only once!
542 mAudioSrcChannels = mAudioTgtChannels = channels;
543 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
544 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
545 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
547 LOGV("got OMX_IndexParamAudioAac, mNumChannels: %d, mSamplingRate: %d",
548 mNumChannels, mSamplingRate);
550 return OMX_ErrorNone;
552 case OMX_IndexParamAudioWma:
554 OMX_AUDIO_PARAM_WMATYPE *wmaParams =
555 (OMX_AUDIO_PARAM_WMATYPE *)params;
557 if (wmaParams->nPortIndex != 0) {
558 return OMX_ErrorUndefined;
561 if (wmaParams->eFormat == OMX_AUDIO_WMAFormat7) {
562 mCtx->codec_id = CODEC_ID_WMAV2;
563 } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat8) {
564 mCtx->codec_id = CODEC_ID_WMAPRO;
565 } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat9) {
566 mCtx->codec_id = CODEC_ID_WMALOSSLESS;
568 LOGE("unsupported wma codec: 0x%x", wmaParams->eFormat);
569 return OMX_ErrorUndefined;
572 mNumChannels = wmaParams->nChannels;
573 mSamplingRate = wmaParams->nSamplingRate;
574 mBitRate = wmaParams->nBitRate;
577 mCtx->bit_rate = mBitRate;
579 channels = mNumChannels >= 2 ? 2 : 1;
580 sampling_rate = mSamplingRate;
581 // 4000 <= nSamplingRate <= 48000
582 if (mSamplingRate < 4000) {
583 sampling_rate = 4000;
584 } else if (mSamplingRate > 48000) {
585 sampling_rate = 48000;
588 // update src and target(only wma), only once!
589 mAudioSrcChannels = mAudioTgtChannels = channels;
590 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
591 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
592 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
594 LOGV("got OMX_IndexParamAudioWma, mNumChannels: %d, mSamplingRate: %d, mBitRate: %d",
595 mNumChannels, mSamplingRate, mBitRate);
597 return OMX_ErrorNone;
599 case OMX_IndexParamAudioRa:
601 OMX_AUDIO_PARAM_RATYPE *raParams =
602 (OMX_AUDIO_PARAM_RATYPE *)params;
604 if (raParams->nPortIndex != 0) {
605 return OMX_ErrorUndefined;
608 mCtx->codec_id = CODEC_ID_COOK;
610 mNumChannels = raParams->nChannels;
611 mSamplingRate = raParams->nSamplingRate;
612 // FIXME, HACK!!!, I use the nNumRegions parameter pass blockAlign!!!
613 // the cook audio codec need blockAlign!
614 mBlockAlign = raParams->nNumRegions;
616 // cook decoder need block_align
617 mCtx->block_align = mBlockAlign;
619 channels = mNumChannels >= 2 ? 2 : 1;
620 sampling_rate = mSamplingRate;
621 // 4000 <= nSamplingRate <= 48000
622 if (mSamplingRate < 4000) {
623 sampling_rate = 4000;
624 } else if (mSamplingRate > 48000) {
625 sampling_rate = 48000;
628 // update src and target(only wma), only once!
629 mAudioSrcChannels = mAudioTgtChannels = channels;
630 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
631 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
632 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
634 LOGV("got OMX_IndexParamAudioRa, mNumChannels: %d, mSamplingRate: %d, mBlockAlign: %d",
635 mNumChannels, mSamplingRate, mBlockAlign);
637 return OMX_ErrorNone;
639 case OMX_IndexParamAudioApe:
641 OMX_AUDIO_PARAM_APETYPE *apeParams =
642 (OMX_AUDIO_PARAM_APETYPE *)params;
644 if (apeParams->nPortIndex != 0) {
645 return OMX_ErrorUndefined;
648 mCtx->codec_id = CODEC_ID_APE;
650 mNumChannels = apeParams->nChannels;
651 mSamplingRate = apeParams->nSamplingRate;
653 // ape decoder need bits_per_coded_sample
654 mCtx->bits_per_coded_sample = apeParams->nBitsPerSample;
656 channels = mNumChannels >= 2 ? 2 : 1;
657 sampling_rate = mSamplingRate;
658 // 4000 <= nSamplingRate <= 48000
659 if (mSamplingRate < 4000) {
660 sampling_rate = 4000;
661 } else if (mSamplingRate > 48000) {
662 sampling_rate = 48000;
665 // update src and target, only once!
666 mAudioSrcChannels = mAudioTgtChannels = channels;
667 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
668 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
669 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
671 LOGV("got OMX_IndexParamAudioApe, mNumChannels: %d, mSamplingRate: %d, nBitsPerSample: %d",
672 mNumChannels, mSamplingRate, apeParams->nBitsPerSample);
674 return OMX_ErrorNone;
676 case OMX_IndexParamAudioDts:
678 OMX_AUDIO_PARAM_DTSTYPE *dtsParams =
679 (OMX_AUDIO_PARAM_DTSTYPE *)params;
681 if (dtsParams->nPortIndex != 0) {
682 return OMX_ErrorUndefined;
685 mCtx->codec_id = CODEC_ID_DTS;
687 mNumChannels = dtsParams->nChannels;
688 mSamplingRate = dtsParams->nSamplingRate;
690 channels = mNumChannels >= 2 ? 2 : 1;
691 sampling_rate = mSamplingRate;
692 // 4000 <= nSamplingRate <= 48000
693 if (mSamplingRate < 4000) {
694 sampling_rate = 4000;
695 } else if (mSamplingRate > 48000) {
696 sampling_rate = 48000;
699 // update src and target, only once!
700 mAudioSrcChannels = mAudioTgtChannels = channels;
701 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
702 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
703 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
705 LOGV("got OMX_IndexParamAudioDts, mNumChannels: %d, mSamplingRate: %d",
706 mNumChannels, mSamplingRate);
708 return OMX_ErrorNone;
711 LOGI("internalSetParameter, index: 0x%x", index);
712 return SimpleSoftOMXComponent::internalSetParameter(index, params);
716 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
720 int64_t decChannelLayout;
721 int32_t inputBufferUsedLength = 0;
722 BufferInfo *inInfo = NULL;
723 OMX_BUFFERHEADERTYPE *inHeader = NULL;
725 if (mSignalledError || mOutputPortSettingsChange != NONE) {
729 List<BufferInfo *> &inQueue = getPortQueue(0);
730 List<BufferInfo *> &outQueue = getPortQueue(1);
732 while ((!inQueue.empty() || mInputBufferSize > 0 ||
733 mAudioBufferSize > 0 || mFlushComplete) && !outQueue.empty()) {
734 if (!inQueue.empty() || mInputBufferSize > 0) {
735 inInfo = *inQueue.begin();
736 inHeader = inInfo->mHeader;
742 BufferInfo *outInfo = *outQueue.begin();
743 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
745 if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
746 inQueue.erase(inQueue.begin());
747 inInfo->mOwnedByUs = false;
748 notifyEmptyBufferDone(inHeader);
752 if (mReceivedEOS && (mFlushComplete || !(mCtx->codec->capabilities & CODEC_CAP_DELAY))) {
753 outHeader->nFilledLen = 0;
754 outHeader->nFlags = OMX_BUFFERFLAG_EOS;
756 outQueue.erase(outQueue.begin());
757 outInfo->mOwnedByUs = false;
758 notifyFillBufferDone(outHeader);
762 if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
763 LOGI("got extradata, ignore: %d, size: %lu", mIgnoreExtradata, inHeader->nFilledLen);
764 hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
765 if (!mExtradataReady && !mIgnoreExtradata) {
766 int orig_extradata_size = mCtx->extradata_size;
767 mCtx->extradata_size += inHeader->nFilledLen;
768 mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
769 mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
770 if (!mCtx->extradata) {
771 LOGE("ffmpeg audio decoder failed to alloc extradata memory.");
772 notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
773 mSignalledError = true;
777 memcpy(mCtx->extradata + orig_extradata_size,
778 inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
779 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
781 inInfo->mOwnedByUs = false;
782 inQueue.erase(inQueue.begin());
784 notifyEmptyBufferDone(inHeader);
789 if (mIgnoreExtradata) {
790 LOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
791 inInfo->mOwnedByUs = false;
792 inQueue.erase(inQueue.begin());
794 notifyEmptyBufferDone(inHeader);
802 if (!mExtradataReady && !mIgnoreExtradata) {
803 LOGI("extradata is ready");
804 hexdump(mCtx->extradata, mCtx->extradata_size);
805 mExtradataReady = true;
808 // find decoder again as codec_id may have changed
809 mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
811 LOGE("ffmpeg audio decoder failed to find codec");
812 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
813 mSignalledError = true;
817 setAVCtxToDefault(mCtx, mCtx->codec);
819 LOGI("open ffmpeg decoder now");
820 err = avcodec_open2(mCtx, mCtx->codec, NULL);
822 print_error("avcodec_open2", err);
823 LOGE("ffmpeg audio decoder failed to initialize. (%d)", err);
824 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
825 mSignalledError = true;
829 LOGI("open ffmpeg audio decoder, mCtx sample_rate: %d, channels: %d, channel_layout: %llu, sample_fmt: %s",
830 mCtx->sample_rate, mCtx->channels, mCtx->channel_layout, av_get_sample_fmt_name(mCtx->sample_fmt));
833 /* update the audio clock with the pts */
834 if (inHeader && inHeader->nOffset == 0) {
835 mAnchorTimeUs = inHeader->nTimeStamp;
836 mInputBufferSize = inHeader->nFilledLen;
839 if (inHeader && mAudioBufferSize == 0 && !mFlushComplete) {
841 memset(&pkt, 0, sizeof(pkt));
842 av_init_packet(&pkt);
843 if (!mFlushComplete) {
844 pkt.data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
845 pkt.size = inHeader->nFilledLen;
846 pkt.pts = inHeader->nTimeStamp; // ingore it, we will compute it
850 pkt.pts = AV_NOPTS_VALUE;
853 LOGV("pkt size: %d, pts: %lld", pkt.size, pkt.pts);
856 if (!(mFrame = avcodec_alloc_frame())) {
857 LOGE("ffmpeg audio decoder failed to alloc memory.");
858 notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
859 mSignalledError = true;
863 avcodec_get_frame_defaults(mFrame);
867 inputBufferUsedLength = 0;
868 len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
870 LOGE("ffmpeg audio decoder failed to decode frame. consume pkt len: %d", len);
872 /* if !mAudioConfigChanged, Don't fill the out buffer */
873 if (!mAudioConfigChanged) {
874 inInfo->mOwnedByUs = false;
875 inQueue.erase(inQueue.begin());
877 notifyEmptyBufferDone(inHeader);
880 mInputBufferSize = 0; // need?
884 //inputBufferUsedLength = inHeader->nFilledLen;
885 /* if error, we skip the frame and play silence instead */
886 mPAudioBuffer = mSilenceBuffer;
887 mAudioBufferSize = kOutputBufferSize;
891 LOGV("ffmpeg audio decoder, consume pkt len: %d", len);
895 inputBufferUsedLength = inHeader->nFilledLen;
897 inputBufferUsedLength = len;
899 CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
900 inHeader->nOffset += inputBufferUsedLength;
901 inHeader->nFilledLen -= inputBufferUsedLength;
902 mInputBufferSize -= inputBufferUsedLength;
903 if (inHeader->nFilledLen == 0) {
904 inInfo->mOwnedByUs = false;
905 inQueue.erase(inQueue.begin());
907 notifyEmptyBufferDone(inHeader);
910 mInputBufferSize = 0;
914 LOGI("ffmpeg audio decoder failed to get frame.");
915 /* stop sending empty packets if the decoder is finished */
916 if (!pkt.data && mCtx->codec->capabilities & CODEC_CAP_DELAY)
917 mFlushComplete = true;
922 * FIXME, check mAudioConfigChanged when the first time you call the audio4!
923 * mCtx->sample_rate and mCtx->channels may be changed by audio decoder later, why???
925 if (!mAudioConfigChanged) {
926 //if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate || mCtx->sample_fmt != mSamplingFmt) {
927 if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate) {
928 LOGI("audio OMX_EventPortSettingsChanged, mCtx->channels: %d, mNumChannels: %d, mCtx->sample_rate: %d, mSamplingRate: %d, mCtx->sample_fmt: %s, mSamplingFmt: %s",
929 mCtx->channels, mNumChannels, mCtx->sample_rate, mSamplingRate,
930 av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mSamplingFmt));
931 mNumChannels = mCtx->channels;
932 mSamplingRate = mCtx->sample_rate;
933 mSamplingFmt = mCtx->sample_fmt;
934 mAudioConfigChanged = true;
935 notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
936 mOutputPortSettingsChange = AWAITING_DISABLED;
939 // match with the default, set mAudioConfigChanged true anyway!
940 mAudioConfigChanged = true;
941 mSamplingFmt = mCtx->sample_fmt;
945 dataSize = av_samples_get_buffer_size(NULL, mNumChannels, mFrame->nb_samples, mSamplingFmt, 1);
948 LOGV("audio decoder, nb_samples: %d, get buffer size: %d", mFrame->nb_samples, dataSize);
949 LOGV("audio decoder: mCtx channel_layout: %llu, channels: %d, channels_from_layout: %d\n",
950 mCtx->channel_layout, mCtx->channels, av_get_channel_layout_nb_channels(mCtx->channel_layout));
953 decChannelLayout = av_get_default_channel_layout(mNumChannels);
954 if (mSamplingFmt != mAudioSrcFmt ||
955 decChannelLayout != mAudioSrcChannelLayout ||
956 mSamplingRate != mAudioSrcFreq ) {
959 mSwrCtx = swr_alloc_set_opts(NULL,
960 mAudioTgtChannelLayout, mAudioTgtFmt, mAudioTgtFreq,
961 decChannelLayout, mSamplingFmt, mSamplingRate,
963 if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
964 LOGE("Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!",
966 av_get_sample_fmt_name(mSamplingFmt),
969 av_get_sample_fmt_name(mAudioTgtFmt),
971 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
972 mSignalledError = true;
976 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)!",
978 av_get_sample_fmt_name(mSamplingFmt),
980 mAudioTgtChannelLayout,
982 av_get_sample_fmt_name(mAudioTgtFmt),
986 mAudioSrcChannelLayout = decChannelLayout;
987 mAudioSrcChannels = mNumChannels;
988 mAudioSrcFreq = mSamplingRate;
989 mAudioSrcFmt = mSamplingFmt;
993 //const uint8_t *in[] = { mFrame->data[0] };
994 const uint8_t **in = (const uint8_t **)mFrame->extended_data;
995 uint8_t *out[] = {mAudioBuf2};
996 int out_count = sizeof(mAudioBuf2) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt);
998 LOGV("swr_convert 1, out_count: %d, mFrame->nb_samples: %d, src frm: %s, tgt frm: %s",
999 out_count, mFrame->nb_samples, av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mAudioTgtFmt));
1001 int len2 = swr_convert(mSwrCtx, out, out_count, in, mFrame->nb_samples);
1003 LOGE("audio_resample() failed");
1006 if (len2 == out_count) {
1007 LOGE("warning: audio buffer is probably too small");
1010 mPAudioBuffer = mAudioBuf2;
1011 mAudioBufferSize = len2 * mAudioTgtChannels * av_get_bytes_per_sample(mAudioTgtFmt);
1013 mPAudioBuffer = mFrame->data[0];
1014 mAudioBufferSize = dataSize;
1018 LOGV("ffmpeg audio decoder get frame. consume pkt len: %d, nb_samples(before resample): %d, mAudioBufferSize: %d",
1019 len, mFrame->nb_samples, mAudioBufferSize);
1021 } // if (inHeader && mAudioBufferSize == 0 && !mFlushComplete)
1023 size_t copyToOutputBufferLen = mAudioBufferSize;
1024 if (mAudioBufferSize > kOutputBufferSize)
1025 copyToOutputBufferLen = kOutputBufferSize;
1027 outHeader->nOffset = 0;
1028 outHeader->nFilledLen = copyToOutputBufferLen;
1029 outHeader->nTimeStamp = mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
1030 memcpy(outHeader->pBuffer, mPAudioBuffer, copyToOutputBufferLen);
1031 outHeader->nFlags = 0;
1034 LOGV("ffmpeg audio decoder, fill out buffer, pts: %lld, mNumFramesOutput: %lld", outHeader->nTimeStamp, mNumFramesOutput);
1037 mPAudioBuffer += copyToOutputBufferLen;
1038 mAudioBufferSize -= copyToOutputBufferLen;
1039 mNumFramesOutput += copyToOutputBufferLen / (av_get_bytes_per_sample(mAudioTgtFmt) * mNumChannels);
1041 // reset mNumFramesOutput
1042 if (mAudioBufferSize == 0) {
1044 LOGV("~~~~ mAudioBufferSize, set mNumFramesOutput = 0");
1046 mNumFramesOutput = 0;
1049 outInfo->mOwnedByUs = false;
1050 outQueue.erase(outQueue.begin());
1052 notifyFillBufferDone(outHeader);
1057 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
1058 if (portIndex == 0 && mCtx) {
1059 // Make sure that the next buffer output does not still
1060 // depend on fragments from the last one decoded.
1061 avcodec_flush_buffers(mCtx);
1066 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
1067 if (portIndex != 1) {
1071 switch (mOutputPortSettingsChange) {
1075 case AWAITING_DISABLED:
1078 mOutputPortSettingsChange = AWAITING_ENABLED;
1084 CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
1086 mOutputPortSettingsChange = NONE;
1092 } // namespace android
1094 android::SoftOMXComponent *createSoftOMXComponent(
1095 const char *name, const OMX_CALLBACKTYPE *callbacks,
1096 OMX_PTR appData, OMX_COMPONENTTYPE **component) {
1097 return new android::SoftFFmpegAudio(name, callbacks, appData, component);