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.ra.decoder")) {
93 } else if (!strcmp(name, "OMX.ffmpeg.ac3.decoder")) {
95 } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
97 } else if (!strcmp(name, "OMX.ffmpeg.dts.decoder")) {
99 } else if (!strcmp(name, "OMX.ffmpeg.flac.decoder")) {
105 LOGV("SoftFFmpegAudio component: %s", name);
106 LOGV("SoftFFmpegAudio mMode: %d", mMode);
109 CHECK_EQ(initDecoder(), (status_t)OK);
112 SoftFFmpegAudio::~SoftFFmpegAudio() {
114 LOGV("~SoftFFmpegAudio");
119 void SoftFFmpegAudio::initPorts() {
120 OMX_PARAM_PORTDEFINITIONTYPE def;
124 def.eDir = OMX_DirInput;
125 def.nBufferCountMin = kNumBuffers;
126 def.nBufferCountActual = def.nBufferCountMin;
127 if (mMode == MODE_APE) {
128 def.nBufferSize = 204800; // ape!
129 } else if (mMode == MODE_DTS) {
130 def.nBufferSize = 512000; // dts!
132 def.nBufferSize = 20480; // 8192 is too small
134 def.bEnabled = OMX_TRUE;
135 def.bPopulated = OMX_FALSE;
136 def.eDomain = OMX_PortDomainAudio;
137 def.bBuffersContiguous = OMX_FALSE;
138 def.nBufferAlignment = 1;
142 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
143 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
146 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
147 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
150 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
151 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
154 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AAC);
155 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
158 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AC3);
160 //def.format.audio.eEncoding = OMX_AUDIO_CodingAC3;
161 def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect; // right?? orz
164 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_WMA);
165 def.format.audio.eEncoding = OMX_AUDIO_CodingWMA;
168 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_RA);
169 def.format.audio.eEncoding = OMX_AUDIO_CodingRA;
172 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_APE);
173 def.format.audio.eEncoding = OMX_AUDIO_CodingAPE;
176 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_DTS);
177 def.format.audio.eEncoding = OMX_AUDIO_CodingDTS;
180 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_FLAC);
181 def.format.audio.eEncoding = OMX_AUDIO_CodingFLAC;
184 CHECK(!"Should not be here. Unsupported mime type and compression format");
188 def.format.audio.pNativeRender = NULL;
189 def.format.audio.bFlagErrorConcealment = OMX_FALSE;
194 def.eDir = OMX_DirOutput;
195 def.nBufferCountMin = kNumBuffers;
196 def.nBufferCountActual = def.nBufferCountMin;
197 def.nBufferSize = kOutputBufferSize;
198 def.bEnabled = OMX_TRUE;
199 def.bPopulated = OMX_FALSE;
200 def.eDomain = OMX_PortDomainAudio;
201 def.bBuffersContiguous = OMX_FALSE;
202 def.nBufferAlignment = 2;
204 def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
205 def.format.audio.pNativeRender = NULL;
206 def.format.audio.bFlagErrorConcealment = OMX_FALSE;
207 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
212 void SoftFFmpegAudio::setAVCtxToDefault(AVCodecContext *avctx, const AVCodec *codec) {
215 avctx->workaround_bugs = 1;
217 if(avctx->lowres > codec->max_lowres){
218 LOGW("The maximum value for lowres supported by the decoder is %d",
220 avctx->lowres= codec->max_lowres;
222 avctx->idct_algo = 0;
223 avctx->skip_frame = AVDISCARD_DEFAULT;
224 avctx->skip_idct = AVDISCARD_DEFAULT;
225 avctx->skip_loop_filter = AVDISCARD_DEFAULT;
226 avctx->error_concealment = 3;
228 if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
229 if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
230 if(codec->capabilities & CODEC_CAP_DR1)
231 avctx->flags |= CODEC_FLAG_EMU_EDGE;
234 status_t SoftFFmpegAudio::initDecoder() {
237 status = initFFmpeg();
241 mCtx = avcodec_alloc_context3(NULL);
244 LOGE("avcodec_alloc_context failed.");
248 mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
251 mCtx->codec_id = CODEC_ID_MP3;
254 mCtx->codec_id = CODEC_ID_MP1;
257 mCtx->codec_id = CODEC_ID_MP2;
260 mCtx->codec_id = CODEC_ID_AAC;
263 mCtx->codec_id = CODEC_ID_AC3;
266 mCtx->codec_id = CODEC_ID_WMAV2; // FIXME, CODEC_ID_WMAV1 or CODEC_ID_WMAV2?
269 mCtx->codec_id = CODEC_ID_COOK; // FIXME
272 mCtx->codec_id = CODEC_ID_APE;
274 mCtx->codec_id = CODEC_ID_DTS;
276 mCtx->codec_id = CODEC_ID_FLAC;
279 CHECK(!"Should not be here. Unsupported codec");
283 mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
286 LOGE("find codec failed");
290 setAVCtxToDefault(mCtx, mCtx->codec);
292 mCtx->channels = mNumChannels;
293 mCtx->sample_rate = mSamplingRate;
294 mCtx->bit_rate = mBitRate;
295 mCtx->sample_fmt = mSamplingFmt;
297 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
298 mAudioSrcFreq = mAudioTgtFreq = mSamplingRate;
299 mAudioSrcChannels = mAudioTgtChannels = mNumChannels;
300 mAudioSrcChannelLayout = mAudioTgtChannelLayout =
301 av_get_default_channel_layout(mNumChannels);
303 memset(mSilenceBuffer, 0, kOutputBufferSize);
308 void SoftFFmpegAudio::deInitDecoder() {
310 //avcodec_flush_buffers(mCtx); // is it necessary? crash sometimes if call it
311 if (!mCtx->extradata) {
312 av_free(mCtx->extradata);
313 mCtx->extradata = NULL;
314 mCtx->extradata_size = 0;
328 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
329 OMX_INDEXTYPE index, OMX_PTR params) {
330 int32_t channels = 0;
331 int32_t sampling_rate = 0;
334 case OMX_IndexParamAudioAac:
336 OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
337 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
339 if (aacParams->nPortIndex != 0) {
340 return OMX_ErrorUndefined;
343 aacParams->nBitRate = 0;
344 aacParams->nAudioBandWidth = 0;
345 aacParams->nAACtools = 0;
346 aacParams->nAACERtools = 0;
347 aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
348 aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
349 aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
351 aacParams->nChannels = mNumChannels;
352 aacParams->nSampleRate = mSamplingRate;
354 return OMX_ErrorNone;
356 case OMX_IndexParamAudioWma:
358 OMX_AUDIO_PARAM_WMATYPE *wmaParams =
359 (OMX_AUDIO_PARAM_WMATYPE *)params;
361 if (wmaParams->nPortIndex != 0) {
362 return OMX_ErrorUndefined;
365 wmaParams->nChannels = 0;
366 wmaParams->nSamplingRate = 0;
367 wmaParams->nBitRate = 0;
368 wmaParams->eFormat = OMX_AUDIO_WMAFormatUnused;
370 return OMX_ErrorNone;
372 case OMX_IndexParamAudioRa:
374 OMX_AUDIO_PARAM_RATYPE *raParams =
375 (OMX_AUDIO_PARAM_RATYPE *)params;
377 if (raParams->nPortIndex != 0) {
378 return OMX_ErrorUndefined;
381 raParams->nChannels = 0;
382 raParams->nSamplingRate = 0;
383 raParams->eFormat = OMX_AUDIO_RAFormatUnused;
385 return OMX_ErrorNone;
387 case OMX_IndexParamAudioApe:
389 OMX_AUDIO_PARAM_APETYPE *apeParams =
390 (OMX_AUDIO_PARAM_APETYPE *)params;
392 if (apeParams->nPortIndex != 0) {
393 return OMX_ErrorUndefined;
396 apeParams->nChannels = 0;
397 apeParams->nSamplingRate = 0;
399 return OMX_ErrorNone;
401 case OMX_IndexParamAudioDts:
403 OMX_AUDIO_PARAM_DTSTYPE *dtsParams =
404 (OMX_AUDIO_PARAM_DTSTYPE *)params;
406 if (dtsParams->nPortIndex != 0) {
407 return OMX_ErrorUndefined;
410 dtsParams->nChannels = 0;
411 dtsParams->nSamplingRate = 0;
413 return OMX_ErrorNone;
415 case OMX_IndexParamAudioFlac:
417 OMX_AUDIO_PARAM_FLACTYPE *flacParams =
418 (OMX_AUDIO_PARAM_FLACTYPE *)params;
420 if (flacParams->nPortIndex != 0) {
421 return OMX_ErrorUndefined;
424 flacParams->nChannels = 0;
425 flacParams->nSamplingRate = 0;
427 return OMX_ErrorNone;
429 case OMX_IndexParamAudioPcm:
431 OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
432 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
434 if (pcmParams->nPortIndex > 1) {
435 return OMX_ErrorUndefined;
438 pcmParams->eNumData = OMX_NumericalDataSigned;
439 pcmParams->eEndian = OMX_EndianBig;
440 pcmParams->bInterleaved = OMX_TRUE;
441 pcmParams->nBitPerSample = 16;
442 pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
443 pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
444 pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
446 LOGV("audio config change");
448 channels = mNumChannels >= 2 ? 2 : 1;
449 sampling_rate = mSamplingRate;
450 // 4000 <= nSamplingRate <= 48000
451 if (mSamplingRate < 4000) {
452 sampling_rate = 4000;
453 } else if (mSamplingRate > 48000) {
454 sampling_rate = 48000;
457 // update src and target(except aac), only once!
458 mAudioSrcChannels = mAudioTgtChannels = channels;
459 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
460 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
461 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
463 pcmParams->nChannels = channels;
464 pcmParams->nSamplingRate = sampling_rate;
466 return OMX_ErrorNone;
470 return SimpleSoftOMXComponent::internalGetParameter(index, params);
474 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
475 OMX_INDEXTYPE index, const OMX_PTR params) {
476 int32_t channels = 0;
477 int32_t sampling_rate = 0;
480 case OMX_IndexParamStandardComponentRole:
482 const OMX_PARAM_COMPONENTROLETYPE *roleParams =
483 (const OMX_PARAM_COMPONENTROLETYPE *)params;
485 bool supported = true;
488 if (strncmp((const char *)roleParams->cRole,
489 "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
493 if (strncmp((const char *)roleParams->cRole,
494 "audio_decoder.mp1", OMX_MAX_STRINGNAME_SIZE - 1))
498 if (strncmp((const char *)roleParams->cRole,
499 "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
503 if (strncmp((const char *)roleParams->cRole,
504 "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
508 if (strncmp((const char *)roleParams->cRole,
509 "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
513 if (strncmp((const char *)roleParams->cRole,
514 "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
518 if (strncmp((const char *)roleParams->cRole,
519 "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
523 if (strncmp((const char *)roleParams->cRole,
524 "audio_decoder.ape", OMX_MAX_STRINGNAME_SIZE - 1))
528 if (strncmp((const char *)roleParams->cRole,
529 "audio_decoder.dts", OMX_MAX_STRINGNAME_SIZE - 1))
533 if (strncmp((const char *)roleParams->cRole,
534 "audio_decoder.flac", OMX_MAX_STRINGNAME_SIZE - 1))
538 CHECK(!"Should not be here. Unsupported role.");
542 LOGE("unsupported role: %s", (const char *)roleParams->cRole);
543 return OMX_ErrorUndefined;
546 return OMX_ErrorNone;
548 case OMX_IndexParamAudioAac:
550 const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
551 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
553 if (aacParams->nPortIndex != 0) {
554 return OMX_ErrorUndefined;
557 mNumChannels = aacParams->nChannels;
558 mSamplingRate = aacParams->nSampleRate;
560 channels = mNumChannels >= 2 ? 2 : 1;
561 sampling_rate = mSamplingRate;
562 // 4000 <= nSamplingRate <= 48000
563 if (mSamplingRate < 4000) {
564 sampling_rate = 4000;
565 } else if (mSamplingRate > 48000) {
566 sampling_rate = 48000;
569 // update src and target(only aac), only once!
570 mAudioSrcChannels = mAudioTgtChannels = channels;
571 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
572 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
573 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
575 LOGV("got OMX_IndexParamAudioAac, mNumChannels: %d, mSamplingRate: %d",
576 mNumChannels, mSamplingRate);
578 return OMX_ErrorNone;
580 case OMX_IndexParamAudioWma:
582 OMX_AUDIO_PARAM_WMATYPE *wmaParams =
583 (OMX_AUDIO_PARAM_WMATYPE *)params;
585 if (wmaParams->nPortIndex != 0) {
586 return OMX_ErrorUndefined;
589 if (wmaParams->eFormat == OMX_AUDIO_WMAFormat7) {
590 mCtx->codec_id = CODEC_ID_WMAV2;
591 } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat8) {
592 mCtx->codec_id = CODEC_ID_WMAPRO;
593 } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat9) {
594 mCtx->codec_id = CODEC_ID_WMALOSSLESS;
596 LOGE("unsupported wma codec: 0x%x", wmaParams->eFormat);
597 return OMX_ErrorUndefined;
600 mNumChannels = wmaParams->nChannels;
601 mSamplingRate = wmaParams->nSamplingRate;
602 mBitRate = wmaParams->nBitRate;
605 mCtx->bit_rate = mBitRate;
607 channels = mNumChannels >= 2 ? 2 : 1;
608 sampling_rate = mSamplingRate;
609 // 4000 <= nSamplingRate <= 48000
610 if (mSamplingRate < 4000) {
611 sampling_rate = 4000;
612 } else if (mSamplingRate > 48000) {
613 sampling_rate = 48000;
616 // update src and target(only wma), only once!
617 mAudioSrcChannels = mAudioTgtChannels = channels;
618 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
619 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
620 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
622 LOGV("got OMX_IndexParamAudioWma, mNumChannels: %d, mSamplingRate: %d, mBitRate: %d",
623 mNumChannels, mSamplingRate, mBitRate);
625 return OMX_ErrorNone;
627 case OMX_IndexParamAudioRa:
629 OMX_AUDIO_PARAM_RATYPE *raParams =
630 (OMX_AUDIO_PARAM_RATYPE *)params;
632 if (raParams->nPortIndex != 0) {
633 return OMX_ErrorUndefined;
636 mCtx->codec_id = CODEC_ID_COOK;
638 mNumChannels = raParams->nChannels;
639 mSamplingRate = raParams->nSamplingRate;
640 // FIXME, HACK!!!, I use the nNumRegions parameter pass blockAlign!!!
641 // the cook audio codec need blockAlign!
642 mBlockAlign = raParams->nNumRegions;
644 // cook decoder need block_align
645 mCtx->block_align = mBlockAlign;
647 channels = mNumChannels >= 2 ? 2 : 1;
648 sampling_rate = mSamplingRate;
649 // 4000 <= nSamplingRate <= 48000
650 if (mSamplingRate < 4000) {
651 sampling_rate = 4000;
652 } else if (mSamplingRate > 48000) {
653 sampling_rate = 48000;
656 // update src and target(only wma), only once!
657 mAudioSrcChannels = mAudioTgtChannels = channels;
658 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
659 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
660 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
662 LOGV("got OMX_IndexParamAudioRa, mNumChannels: %d, mSamplingRate: %d, mBlockAlign: %d",
663 mNumChannels, mSamplingRate, mBlockAlign);
665 return OMX_ErrorNone;
667 case OMX_IndexParamAudioApe:
669 OMX_AUDIO_PARAM_APETYPE *apeParams =
670 (OMX_AUDIO_PARAM_APETYPE *)params;
672 if (apeParams->nPortIndex != 0) {
673 return OMX_ErrorUndefined;
676 mCtx->codec_id = CODEC_ID_APE;
678 mNumChannels = apeParams->nChannels;
679 mSamplingRate = apeParams->nSamplingRate;
681 // ape decoder need bits_per_coded_sample
682 mCtx->bits_per_coded_sample = apeParams->nBitsPerSample;
684 channels = mNumChannels >= 2 ? 2 : 1;
685 sampling_rate = mSamplingRate;
686 // 4000 <= nSamplingRate <= 48000
687 if (mSamplingRate < 4000) {
688 sampling_rate = 4000;
689 } else if (mSamplingRate > 48000) {
690 sampling_rate = 48000;
693 // update src and target, only once!
694 mAudioSrcChannels = mAudioTgtChannels = channels;
695 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
696 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
697 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
699 LOGV("got OMX_IndexParamAudioApe, mNumChannels: %d, mSamplingRate: %d, nBitsPerSample: %d",
700 mNumChannels, mSamplingRate, apeParams->nBitsPerSample);
702 return OMX_ErrorNone;
704 case OMX_IndexParamAudioDts:
706 OMX_AUDIO_PARAM_DTSTYPE *dtsParams =
707 (OMX_AUDIO_PARAM_DTSTYPE *)params;
709 if (dtsParams->nPortIndex != 0) {
710 return OMX_ErrorUndefined;
713 mCtx->codec_id = CODEC_ID_DTS;
715 mNumChannels = dtsParams->nChannels;
716 mSamplingRate = dtsParams->nSamplingRate;
718 channels = mNumChannels >= 2 ? 2 : 1;
719 sampling_rate = mSamplingRate;
720 // 4000 <= nSamplingRate <= 48000
721 if (mSamplingRate < 4000) {
722 sampling_rate = 4000;
723 } else if (mSamplingRate > 48000) {
724 sampling_rate = 48000;
727 // update src and target, only once!
728 mAudioSrcChannels = mAudioTgtChannels = channels;
729 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
730 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
731 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
733 LOGV("got OMX_IndexParamAudioDts, mNumChannels: %d, mSamplingRate: %d",
734 mNumChannels, mSamplingRate);
736 return OMX_ErrorNone;
738 case OMX_IndexParamAudioFlac:
740 OMX_AUDIO_PARAM_FLACTYPE *flacParams =
741 (OMX_AUDIO_PARAM_FLACTYPE *)params;
743 if (flacParams->nPortIndex != 0) {
744 return OMX_ErrorUndefined;
747 mCtx->codec_id = CODEC_ID_FLAC;
749 mNumChannels = flacParams->nChannels;
750 mSamplingRate = flacParams->nSamplingRate;
752 channels = mNumChannels >= 2 ? 2 : 1;
753 sampling_rate = mSamplingRate;
754 // 4000 <= nSamplingRate <= 48000
755 if (mSamplingRate < 4000) {
756 sampling_rate = 4000;
757 } else if (mSamplingRate > 48000) {
758 sampling_rate = 48000;
761 // update src and target, only once!
762 mAudioSrcChannels = mAudioTgtChannels = channels;
763 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
764 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
765 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
767 LOGV("got OMX_IndexParamAudioFlac, mNumChannels: %d, mSamplingRate: %d",
768 mNumChannels, mSamplingRate);
770 return OMX_ErrorNone;
773 LOGI("internalSetParameter, index: 0x%x", index);
774 return SimpleSoftOMXComponent::internalSetParameter(index, params);
778 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
782 int64_t decChannelLayout;
783 int32_t inputBufferUsedLength = 0;
784 BufferInfo *inInfo = NULL;
785 OMX_BUFFERHEADERTYPE *inHeader = NULL;
787 if (mSignalledError || mOutputPortSettingsChange != NONE) {
791 List<BufferInfo *> &inQueue = getPortQueue(0);
792 List<BufferInfo *> &outQueue = getPortQueue(1);
794 while ((!inQueue.empty() || mInputBufferSize > 0 ||
795 mAudioBufferSize > 0 || mFlushComplete) && !outQueue.empty()) {
796 if (!inQueue.empty() || mInputBufferSize > 0) {
797 inInfo = *inQueue.begin();
798 inHeader = inInfo->mHeader;
804 BufferInfo *outInfo = *outQueue.begin();
805 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
807 if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
808 inQueue.erase(inQueue.begin());
809 inInfo->mOwnedByUs = false;
810 notifyEmptyBufferDone(inHeader);
814 if (mReceivedEOS && (mFlushComplete || !(mCtx->codec->capabilities & CODEC_CAP_DELAY))) {
815 outHeader->nFilledLen = 0;
816 outHeader->nFlags = OMX_BUFFERFLAG_EOS;
818 outQueue.erase(outQueue.begin());
819 outInfo->mOwnedByUs = false;
820 notifyFillBufferDone(outHeader);
824 if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
825 LOGI("got extradata, ignore: %d, size: %lu", mIgnoreExtradata, inHeader->nFilledLen);
826 hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
827 if (!mExtradataReady && !mIgnoreExtradata) {
828 int orig_extradata_size = mCtx->extradata_size;
829 mCtx->extradata_size += inHeader->nFilledLen;
830 mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
831 mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
832 if (!mCtx->extradata) {
833 LOGE("ffmpeg audio decoder failed to alloc extradata memory.");
834 notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
835 mSignalledError = true;
839 memcpy(mCtx->extradata + orig_extradata_size,
840 inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
841 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
843 inInfo->mOwnedByUs = false;
844 inQueue.erase(inQueue.begin());
846 notifyEmptyBufferDone(inHeader);
851 if (mIgnoreExtradata) {
852 LOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
853 inInfo->mOwnedByUs = false;
854 inQueue.erase(inQueue.begin());
856 notifyEmptyBufferDone(inHeader);
864 if (!mExtradataReady && !mIgnoreExtradata) {
865 LOGI("extradata is ready");
866 hexdump(mCtx->extradata, mCtx->extradata_size);
867 mExtradataReady = true;
870 // find decoder again as codec_id may have changed
871 mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
873 LOGE("ffmpeg audio decoder failed to find codec");
874 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
875 mSignalledError = true;
879 setAVCtxToDefault(mCtx, mCtx->codec);
881 LOGI("open ffmpeg decoder now");
882 err = avcodec_open2(mCtx, mCtx->codec, NULL);
884 print_error("avcodec_open2", err);
885 LOGE("ffmpeg audio decoder failed to initialize. (%d)", err);
886 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
887 mSignalledError = true;
891 LOGI("open ffmpeg audio decoder, mCtx sample_rate: %d, channels: %d, channel_layout: %llu, sample_fmt: %s",
892 mCtx->sample_rate, mCtx->channels, mCtx->channel_layout, av_get_sample_fmt_name(mCtx->sample_fmt));
895 /* update the audio clock with the pts */
896 if (inHeader && inHeader->nOffset == 0) {
897 mAnchorTimeUs = inHeader->nTimeStamp;
898 mInputBufferSize = inHeader->nFilledLen;
901 if (inHeader && mAudioBufferSize == 0 && !mFlushComplete) {
903 memset(&pkt, 0, sizeof(pkt));
904 av_init_packet(&pkt);
905 if (!mFlushComplete) {
906 pkt.data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
907 pkt.size = inHeader->nFilledLen;
908 pkt.pts = inHeader->nTimeStamp; // ingore it, we will compute it
912 pkt.pts = AV_NOPTS_VALUE;
915 LOGV("pkt size: %d, pts: %lld", pkt.size, pkt.pts);
918 if (!(mFrame = avcodec_alloc_frame())) {
919 LOGE("ffmpeg audio decoder failed to alloc memory.");
920 notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
921 mSignalledError = true;
925 avcodec_get_frame_defaults(mFrame);
929 inputBufferUsedLength = 0;
930 len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
932 LOGE("ffmpeg audio decoder failed to decode frame. consume pkt len: %d", len);
934 /* if !mAudioConfigChanged, Don't fill the out buffer */
935 if (!mAudioConfigChanged) {
936 inInfo->mOwnedByUs = false;
937 inQueue.erase(inQueue.begin());
939 notifyEmptyBufferDone(inHeader);
942 mInputBufferSize = 0; // need?
946 //inputBufferUsedLength = inHeader->nFilledLen;
947 /* if error, we skip the frame and play silence instead */
948 mPAudioBuffer = mSilenceBuffer;
949 mAudioBufferSize = kOutputBufferSize;
953 LOGV("ffmpeg audio decoder, consume pkt len: %d", len);
957 inputBufferUsedLength = inHeader->nFilledLen;
959 inputBufferUsedLength = len;
961 CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
962 inHeader->nOffset += inputBufferUsedLength;
963 inHeader->nFilledLen -= inputBufferUsedLength;
964 mInputBufferSize -= inputBufferUsedLength;
965 if (inHeader->nFilledLen == 0) {
966 inInfo->mOwnedByUs = false;
967 inQueue.erase(inQueue.begin());
969 notifyEmptyBufferDone(inHeader);
972 mInputBufferSize = 0;
976 LOGI("ffmpeg audio decoder failed to get frame.");
977 /* stop sending empty packets if the decoder is finished */
978 if (!pkt.data && mCtx->codec->capabilities & CODEC_CAP_DELAY)
979 mFlushComplete = true;
984 * FIXME, check mAudioConfigChanged when the first time you call the audio4!
985 * mCtx->sample_rate and mCtx->channels may be changed by audio decoder later, why???
987 if (!mAudioConfigChanged) {
988 //if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate || mCtx->sample_fmt != mSamplingFmt) {
989 if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate) {
990 LOGI("audio OMX_EventPortSettingsChanged, mCtx->channels: %d, mNumChannels: %d, mCtx->sample_rate: %d, mSamplingRate: %d, mCtx->sample_fmt: %s, mSamplingFmt: %s",
991 mCtx->channels, mNumChannels, mCtx->sample_rate, mSamplingRate,
992 av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mSamplingFmt));
993 mNumChannels = mCtx->channels;
994 mSamplingRate = mCtx->sample_rate;
995 mSamplingFmt = mCtx->sample_fmt;
996 mAudioConfigChanged = true;
997 notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
998 mOutputPortSettingsChange = AWAITING_DISABLED;
1001 // match with the default, set mAudioConfigChanged true anyway!
1002 mAudioConfigChanged = true;
1003 mSamplingFmt = mCtx->sample_fmt;
1007 dataSize = av_samples_get_buffer_size(NULL, mNumChannels, mFrame->nb_samples, mSamplingFmt, 1);
1010 LOGV("audio decoder, nb_samples: %d, get buffer size: %d", mFrame->nb_samples, dataSize);
1011 LOGV("audio decoder: mCtx channel_layout: %llu, channels: %d, channels_from_layout: %d\n",
1012 mCtx->channel_layout, mCtx->channels, av_get_channel_layout_nb_channels(mCtx->channel_layout));
1015 decChannelLayout = av_get_default_channel_layout(mNumChannels);
1016 if (mSamplingFmt != mAudioSrcFmt ||
1017 decChannelLayout != mAudioSrcChannelLayout ||
1018 mSamplingRate != mAudioSrcFreq ) {
1021 mSwrCtx = swr_alloc_set_opts(NULL,
1022 mAudioTgtChannelLayout, mAudioTgtFmt, mAudioTgtFreq,
1023 decChannelLayout, mSamplingFmt, mSamplingRate,
1025 if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
1026 LOGE("Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!",
1028 av_get_sample_fmt_name(mSamplingFmt),
1031 av_get_sample_fmt_name(mAudioTgtFmt),
1033 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
1034 mSignalledError = true;
1038 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)!",
1040 av_get_sample_fmt_name(mSamplingFmt),
1042 mAudioTgtChannelLayout,
1044 av_get_sample_fmt_name(mAudioTgtFmt),
1048 mAudioSrcChannelLayout = decChannelLayout;
1049 mAudioSrcChannels = mNumChannels;
1050 mAudioSrcFreq = mSamplingRate;
1051 mAudioSrcFmt = mSamplingFmt;
1055 //const uint8_t *in[] = { mFrame->data[0] };
1056 const uint8_t **in = (const uint8_t **)mFrame->extended_data;
1057 uint8_t *out[] = {mAudioBuf2};
1058 int out_count = sizeof(mAudioBuf2) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt);
1060 LOGV("swr_convert 1, out_count: %d, mFrame->nb_samples: %d, src frm: %s, tgt frm: %s",
1061 out_count, mFrame->nb_samples, av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mAudioTgtFmt));
1063 int len2 = swr_convert(mSwrCtx, out, out_count, in, mFrame->nb_samples);
1065 LOGE("audio_resample() failed");
1068 if (len2 == out_count) {
1069 LOGE("warning: audio buffer is probably too small");
1072 mPAudioBuffer = mAudioBuf2;
1073 mAudioBufferSize = len2 * mAudioTgtChannels * av_get_bytes_per_sample(mAudioTgtFmt);
1075 mPAudioBuffer = mFrame->data[0];
1076 mAudioBufferSize = dataSize;
1080 LOGV("ffmpeg audio decoder get frame. consume pkt len: %d, nb_samples(before resample): %d, mAudioBufferSize: %d",
1081 len, mFrame->nb_samples, mAudioBufferSize);
1083 } // if (inHeader && mAudioBufferSize == 0 && !mFlushComplete)
1085 size_t copyToOutputBufferLen = mAudioBufferSize;
1086 if (mAudioBufferSize > kOutputBufferSize)
1087 copyToOutputBufferLen = kOutputBufferSize;
1089 outHeader->nOffset = 0;
1090 outHeader->nFilledLen = copyToOutputBufferLen;
1091 outHeader->nTimeStamp = mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
1092 memcpy(outHeader->pBuffer, mPAudioBuffer, copyToOutputBufferLen);
1093 outHeader->nFlags = 0;
1096 LOGV("ffmpeg audio decoder, fill out buffer, pts: %lld, mNumFramesOutput: %lld", outHeader->nTimeStamp, mNumFramesOutput);
1099 mPAudioBuffer += copyToOutputBufferLen;
1100 mAudioBufferSize -= copyToOutputBufferLen;
1101 mNumFramesOutput += copyToOutputBufferLen / (av_get_bytes_per_sample(mAudioTgtFmt) * mNumChannels);
1103 // reset mNumFramesOutput
1104 if (mAudioBufferSize == 0) {
1106 LOGV("~~~~ mAudioBufferSize, set mNumFramesOutput = 0");
1108 mNumFramesOutput = 0;
1111 outInfo->mOwnedByUs = false;
1112 outQueue.erase(outQueue.begin());
1114 notifyFillBufferDone(outHeader);
1119 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
1120 if (portIndex == 0 && mCtx) {
1121 // Make sure that the next buffer output does not still
1122 // depend on fragments from the last one decoded.
1123 avcodec_flush_buffers(mCtx);
1128 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
1129 if (portIndex != 1) {
1133 switch (mOutputPortSettingsChange) {
1137 case AWAITING_DISABLED:
1140 mOutputPortSettingsChange = AWAITING_ENABLED;
1146 CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
1148 mOutputPortSettingsChange = NONE;
1154 } // namespace android
1156 android::SoftOMXComponent *createSoftOMXComponent(
1157 const char *name, const OMX_CALLBACKTYPE *callbacks,
1158 OMX_PTR appData, OMX_COMPONENTTYPE **component) {
1159 return new android::SoftFFmpegAudio(name, callbacks, appData, component);