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"
39 static void InitOMXParams(T *params) {
40 params->nSize = sizeof(T);
41 params->nVersion.s.nVersionMajor = 1;
42 params->nVersion.s.nVersionMinor = 0;
43 params->nVersion.s.nRevision = 0;
44 params->nVersion.s.nStep = 0;
47 SoftFFmpegAudio::SoftFFmpegAudio(
49 const OMX_CALLBACKTYPE *callbacks,
51 OMX_COMPONENTTYPE **component)
52 : SimpleSoftOMXComponent(name, callbacks, appData, component),
57 mExtradataReady(false),
58 mIgnoreExtradata(false),
59 mFlushComplete(false),
60 mSignalledError(false),
70 mSamplingFmt(AV_SAMPLE_FMT_S16),
71 mAudioConfigChanged(false),
72 mOutputPortSettingsChange(NONE) {
73 if (!strcmp(name, "OMX.ffmpeg.mp3.decoder")) {
75 mIgnoreExtradata = true;
76 } else if (!strcmp(name, "OMX.ffmpeg.mp1.decoder")) {
78 } else if (!strcmp(name, "OMX.ffmpeg.mp2.decoder")) {
80 } else if (!strcmp(name, "OMX.ffmpeg.aac.decoder")) {
82 } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
84 } else if (!strcmp(name, "OMX.ffmpeg.wma.decoder")) {
86 } else if (!strcmp(name, "OMX.ffmpeg.dts.decoder")) {
88 } else if (!strcmp(name, "OMX.ffmpeg.ra.decoder")) {
91 CHECK(!strcmp(name, "OMX.ffmpeg.ac3.decoder"));
95 LOGV("SoftFFmpegAudio component: %s", name);
98 CHECK_EQ(initDecoder(), (status_t)OK);
101 SoftFFmpegAudio::~SoftFFmpegAudio() {
103 LOGV("~SoftFFmpegAudio");
108 void SoftFFmpegAudio::initPorts() {
109 OMX_PARAM_PORTDEFINITIONTYPE def;
113 def.eDir = OMX_DirInput;
114 def.nBufferCountMin = kNumBuffers;
115 def.nBufferCountActual = def.nBufferCountMin;
116 def.nBufferSize = 8192;
117 def.bEnabled = OMX_TRUE;
118 def.bPopulated = OMX_FALSE;
119 def.eDomain = OMX_PortDomainAudio;
120 def.bBuffersContiguous = OMX_FALSE;
121 def.nBufferAlignment = 1;
125 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
126 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
129 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
130 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
133 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
134 def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
137 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AAC);
138 def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
141 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AC3);
143 //def.format.audio.eEncoding = OMX_AUDIO_CodingAC3;
144 def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect; // right?? orz
147 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_WMA);
148 def.format.audio.eEncoding = OMX_AUDIO_CodingWMA;
151 def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_RA);
152 def.format.audio.eEncoding = OMX_AUDIO_CodingRA;
155 CHECK(!"Should not be here. Unsupported mime type and compression format");
159 def.format.audio.pNativeRender = NULL;
160 def.format.audio.bFlagErrorConcealment = OMX_FALSE;
165 def.eDir = OMX_DirOutput;
166 def.nBufferCountMin = kNumBuffers;
167 def.nBufferCountActual = def.nBufferCountMin;
168 def.nBufferSize = kOutputBufferSize;
169 def.bEnabled = OMX_TRUE;
170 def.bPopulated = OMX_FALSE;
171 def.eDomain = OMX_PortDomainAudio;
172 def.bBuffersContiguous = OMX_FALSE;
173 def.nBufferAlignment = 2;
175 def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
176 def.format.audio.pNativeRender = NULL;
177 def.format.audio.bFlagErrorConcealment = OMX_FALSE;
178 def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
183 void SoftFFmpegAudio::setAVCtxToDefault(AVCodecContext *avctx, const AVCodec *codec) {
186 avctx->workaround_bugs = 1;
188 if(avctx->lowres > codec->max_lowres){
189 LOGW("The maximum value for lowres supported by the decoder is %d",
191 avctx->lowres= codec->max_lowres;
193 avctx->idct_algo = 0;
194 avctx->skip_frame = AVDISCARD_DEFAULT;
195 avctx->skip_idct = AVDISCARD_DEFAULT;
196 avctx->skip_loop_filter = AVDISCARD_DEFAULT;
197 avctx->error_concealment = 3;
199 if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
200 if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
201 if(codec->capabilities & CODEC_CAP_DR1)
202 avctx->flags |= CODEC_FLAG_EMU_EDGE;
205 status_t SoftFFmpegAudio::initDecoder() {
208 status = initFFmpeg();
212 mCtx = avcodec_alloc_context3(NULL);
215 LOGE("avcodec_alloc_context failed.");
219 mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
222 mCtx->codec_id = CODEC_ID_MP3;
225 mCtx->codec_id = CODEC_ID_MP1;
228 mCtx->codec_id = CODEC_ID_MP2;
231 mCtx->codec_id = CODEC_ID_AAC;
234 mCtx->codec_id = CODEC_ID_AC3;
237 mCtx->codec_id = CODEC_ID_WMAV2; // FIXME, CODEC_ID_WMAV1 or CODEC_ID_WMAV2?
240 mCtx->codec_id = CODEC_ID_COOK; // FIXME
241 mCtx->block_align = 186;
245 CHECK(!"Should not be here. Unsupported codec");
249 mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
252 LOGE("find codec failed");
256 setAVCtxToDefault(mCtx, mCtx->codec);
258 mCtx->channels = mNumChannels;
259 mCtx->sample_rate = mSamplingRate;
260 mCtx->bit_rate = mBitRate;
261 mCtx->sample_fmt = mSamplingFmt;
263 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
264 mAudioSrcFreq = mAudioTgtFreq = mSamplingRate;
265 mAudioSrcChannels = mAudioTgtChannels = mNumChannels;
266 mAudioSrcChannelLayout = mAudioTgtChannelLayout =
267 av_get_default_channel_layout(mNumChannels);
269 memset(mSilenceBuffer, 0, kOutputBufferSize);
274 void SoftFFmpegAudio::deInitDecoder() {
276 //avcodec_flush_buffers(mCtx); // is it necessary? crash sometimes if call it
277 if (!mCtx->extradata) {
278 av_free(mCtx->extradata);
279 mCtx->extradata = NULL;
280 mCtx->extradata_size = 0;
294 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
295 OMX_INDEXTYPE index, OMX_PTR params) {
296 int32_t channels = 0;
297 int32_t sampling_rate = 0;
300 case OMX_IndexParamAudioAac:
302 OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
303 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
305 if (aacParams->nPortIndex != 0) {
306 return OMX_ErrorUndefined;
309 aacParams->nBitRate = 0;
310 aacParams->nAudioBandWidth = 0;
311 aacParams->nAACtools = 0;
312 aacParams->nAACERtools = 0;
313 aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
314 aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
315 aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
317 aacParams->nChannels = mNumChannels;
318 aacParams->nSampleRate = mSamplingRate;
320 return OMX_ErrorNone;
322 case OMX_IndexParamAudioWma:
324 OMX_AUDIO_PARAM_WMATYPE *wmaParams =
325 (OMX_AUDIO_PARAM_WMATYPE *)params;
327 if (wmaParams->nPortIndex != 0) {
328 return OMX_ErrorUndefined;
331 wmaParams->nChannels = 0;
332 wmaParams->nSamplingRate = 0;
333 wmaParams->nBitRate = 0;
334 wmaParams->eFormat = OMX_AUDIO_WMAFormatUnused;
336 return OMX_ErrorNone;
338 case OMX_IndexParamAudioPcm:
340 OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
341 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
343 if (pcmParams->nPortIndex > 1) {
344 return OMX_ErrorUndefined;
347 pcmParams->eNumData = OMX_NumericalDataSigned;
348 pcmParams->eEndian = OMX_EndianBig;
349 pcmParams->bInterleaved = OMX_TRUE;
350 pcmParams->nBitPerSample = 16;
351 pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
352 pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
353 pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
355 LOGI("~~~~~~~~~~~~~ audio config change");
357 channels = mNumChannels >= 2 ? 2 : 1;
358 sampling_rate = mSamplingRate;
359 // 4000 <= nSamplingRate <= 48000
360 if (mSamplingRate < 4000) {
361 sampling_rate = 4000;
362 } else if (mSamplingRate > 48000) {
363 sampling_rate = 48000;
366 // update src and target(except aac), only once!
367 mAudioSrcChannels = mAudioTgtChannels = channels;
368 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
369 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
370 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
372 pcmParams->nChannels = channels;
373 pcmParams->nSamplingRate = sampling_rate;
375 return OMX_ErrorNone;
379 return SimpleSoftOMXComponent::internalGetParameter(index, params);
383 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
384 OMX_INDEXTYPE index, const OMX_PTR params) {
385 int32_t channels = 0;
386 int32_t sampling_rate = 0;
389 case OMX_IndexParamStandardComponentRole:
391 const OMX_PARAM_COMPONENTROLETYPE *roleParams =
392 (const OMX_PARAM_COMPONENTROLETYPE *)params;
394 bool supported = true;
397 if (strncmp((const char *)roleParams->cRole,
398 "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
402 if (strncmp((const char *)roleParams->cRole,
403 "audio_decoder.mp1", OMX_MAX_STRINGNAME_SIZE - 1))
407 if (strncmp((const char *)roleParams->cRole,
408 "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
412 if (strncmp((const char *)roleParams->cRole,
413 "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
417 if (strncmp((const char *)roleParams->cRole,
418 "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
422 if (strncmp((const char *)roleParams->cRole,
423 "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
427 if (strncmp((const char *)roleParams->cRole,
428 "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
432 CHECK(!"Should not be here. Unsupported role.");
436 LOGE("unsupported role: %s", (const char *)roleParams->cRole);
437 return OMX_ErrorUndefined;
440 return OMX_ErrorNone;
442 case OMX_IndexParamAudioAac:
444 const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
445 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
447 if (aacParams->nPortIndex != 0) {
448 return OMX_ErrorUndefined;
451 mNumChannels = aacParams->nChannels;
452 mSamplingRate = aacParams->nSampleRate;
454 channels = mNumChannels >= 2 ? 2 : 1;
455 sampling_rate = mSamplingRate;
456 // 4000 <= nSamplingRate <= 48000
457 if (mSamplingRate < 4000) {
458 sampling_rate = 4000;
459 } else if (mSamplingRate > 48000) {
460 sampling_rate = 48000;
463 // update src and target(only aac), only once!
464 mAudioSrcChannels = mAudioTgtChannels = channels;
465 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
466 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
467 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
469 LOGV("got OMX_IndexParamAudioAac, mNumChannels: %d, mSamplingRate: %d",
470 mNumChannels, mSamplingRate);
472 return OMX_ErrorNone;
474 case OMX_IndexParamAudioWma:
476 OMX_AUDIO_PARAM_WMATYPE *wmaParams =
477 (OMX_AUDIO_PARAM_WMATYPE *)params;
479 if (wmaParams->nPortIndex != 0) {
480 return OMX_ErrorUndefined;
483 if (wmaParams->eFormat == OMX_AUDIO_WMAFormat7) {
484 mCtx->codec_id = CODEC_ID_WMAV2;
485 } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat8) {
486 mCtx->codec_id = CODEC_ID_WMAPRO;
487 } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat9) {
488 mCtx->codec_id = CODEC_ID_WMALOSSLESS;
490 LOGE("unsupported wma codec: 0x%x", wmaParams->eFormat);
491 return OMX_ErrorUndefined;
494 mNumChannels = wmaParams->nChannels;
495 mSamplingRate = wmaParams->nSamplingRate;
496 mBitRate = wmaParams->nBitRate;
499 mCtx->bit_rate = mBitRate;
501 channels = mNumChannels >= 2 ? 2 : 1;
502 sampling_rate = mSamplingRate;
503 // 4000 <= nSamplingRate <= 48000
504 if (mSamplingRate < 4000) {
505 sampling_rate = 4000;
506 } else if (mSamplingRate > 48000) {
507 sampling_rate = 48000;
510 // update src and target(only wma), only once!
511 mAudioSrcChannels = mAudioTgtChannels = channels;
512 mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
513 mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
514 mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
516 LOGV("got OMX_IndexParamAudioWma, mNumChannels: %d, mSamplingRate: %d, mBitRate: %d",
517 mNumChannels, mSamplingRate, mBitRate);
519 return OMX_ErrorNone;
522 LOGI("internalSetParameter, index: 0x%x", index);
523 return SimpleSoftOMXComponent::internalSetParameter(index, params);
527 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
531 int64_t decChannelLayout;
532 int32_t inputBufferUsedLength = 0;
533 BufferInfo *inInfo = NULL;
534 OMX_BUFFERHEADERTYPE *inHeader = NULL;
536 if (mSignalledError || mOutputPortSettingsChange != NONE) {
540 List<BufferInfo *> &inQueue = getPortQueue(0);
541 List<BufferInfo *> &outQueue = getPortQueue(1);
543 while ((!inQueue.empty() || mInputBufferSize > 0 ||
544 mAudioBufferSize > 0 || mFlushComplete) && !outQueue.empty()) {
545 if (!inQueue.empty() || mInputBufferSize > 0) {
546 inInfo = *inQueue.begin();
547 inHeader = inInfo->mHeader;
553 BufferInfo *outInfo = *outQueue.begin();
554 OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
556 if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
557 inQueue.erase(inQueue.begin());
558 inInfo->mOwnedByUs = false;
559 notifyEmptyBufferDone(inHeader);
563 if (mReceivedEOS && (mFlushComplete || !(mCtx->codec->capabilities & CODEC_CAP_DELAY))) {
564 outHeader->nFilledLen = 0;
565 outHeader->nFlags = OMX_BUFFERFLAG_EOS;
567 outQueue.erase(outQueue.begin());
568 outInfo->mOwnedByUs = false;
569 notifyFillBufferDone(outHeader);
573 if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
574 LOGI("got extradata, ignore: %d, size: %lu", mIgnoreExtradata, inHeader->nFilledLen);
575 hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
576 if (!mExtradataReady && !mIgnoreExtradata) {
577 int orig_extradata_size = mCtx->extradata_size;
578 mCtx->extradata_size += inHeader->nFilledLen;
579 mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
580 mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
581 if (!mCtx->extradata) {
582 LOGE("ffmpeg audio decoder failed to alloc extradata memory.");
583 notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
584 mSignalledError = true;
588 memcpy(mCtx->extradata + orig_extradata_size,
589 inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
590 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
592 inInfo->mOwnedByUs = false;
593 inQueue.erase(inQueue.begin());
595 notifyEmptyBufferDone(inHeader);
600 if (mIgnoreExtradata) {
601 LOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
602 inInfo->mOwnedByUs = false;
603 inQueue.erase(inQueue.begin());
605 notifyEmptyBufferDone(inHeader);
613 if (!mExtradataReady && !mIgnoreExtradata) {
614 LOGI("extradata is ready");
615 hexdump(mCtx->extradata, mCtx->extradata_size);
616 mExtradataReady = true;
619 // find decoder again as codec_id may have changed
620 mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
622 LOGE("ffmpeg audio decoder failed to find codec");
623 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
624 mSignalledError = true;
628 setAVCtxToDefault(mCtx, mCtx->codec);
630 LOGI("open ffmpeg decoder now");
631 err = avcodec_open2(mCtx, mCtx->codec, NULL);
633 LOGE("ffmpeg audio decoder failed to initialize. (%d)", err);
634 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
635 mSignalledError = true;
639 LOGI("open ffmpeg audio decoder, mCtx sample_rate: %d, channels: %d, channel_layout: %llu, sample_fmt: %s",
640 mCtx->sample_rate, mCtx->channels, mCtx->channel_layout, av_get_sample_fmt_name(mCtx->sample_fmt));
643 /* update the audio clock with the pts */
644 if (inHeader && inHeader->nOffset == 0) {
645 mAnchorTimeUs = inHeader->nTimeStamp;
646 mInputBufferSize = inHeader->nFilledLen;
649 if (inHeader && mAudioBufferSize == 0 && !mFlushComplete) {
651 memset(&pkt, 0, sizeof(pkt));
652 av_init_packet(&pkt);
653 if (!mFlushComplete) {
654 pkt.data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
655 pkt.size = inHeader->nFilledLen;
656 pkt.pts = inHeader->nTimeStamp; // ingore it, we will compute it
660 pkt.pts = AV_NOPTS_VALUE;
663 LOGV("pkt size: %d, pts: %lld", pkt.size, pkt.pts);
666 if (!(mFrame = avcodec_alloc_frame())) {
667 LOGE("ffmpeg audio decoder failed to alloc memory.");
668 notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
669 mSignalledError = true;
673 avcodec_get_frame_defaults(mFrame);
677 inputBufferUsedLength = 0;
678 len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
680 LOGE("ffmpeg audio decoder failed to decode frame. consume pkt len: %d", len);
682 /* if !mAudioConfigChanged, Don't fill the out buffer */
683 if (!mAudioConfigChanged) {
684 inInfo->mOwnedByUs = false;
685 inQueue.erase(inQueue.begin());
687 notifyEmptyBufferDone(inHeader);
690 mInputBufferSize = 0; // need?
694 //inputBufferUsedLength = inHeader->nFilledLen;
695 /* if error, we skip the frame and play silence instead */
696 mPAudioBuffer = mSilenceBuffer;
697 mAudioBufferSize = kOutputBufferSize;
701 LOGV("ffmpeg audio decoder, consume pkt len: %d", len);
705 inputBufferUsedLength = inHeader->nFilledLen;
707 inputBufferUsedLength = len;
709 CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
710 inHeader->nOffset += inputBufferUsedLength;
711 inHeader->nFilledLen -= inputBufferUsedLength;
712 mInputBufferSize -= inputBufferUsedLength;
713 if (inHeader->nFilledLen == 0) {
714 inInfo->mOwnedByUs = false;
715 inQueue.erase(inQueue.begin());
717 notifyEmptyBufferDone(inHeader);
720 mInputBufferSize = 0;
724 LOGI("ffmpeg audio decoder failed to get frame.");
725 /* stop sending empty packets if the decoder is finished */
726 if (!pkt.data && mCtx->codec->capabilities & CODEC_CAP_DELAY)
727 mFlushComplete = true;
732 * FIXME, check mAudioConfigChanged when the first time you call the audio4!
733 * mCtx->sample_rate and mCtx->channels may be changed by audio decoder later, why???
735 if (!mAudioConfigChanged) {
736 //if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate || mCtx->sample_fmt != mSamplingFmt) {
737 if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate) {
738 LOGI("audio OMX_EventPortSettingsChanged, mCtx->channels: %d, mNumChannels: %d, mCtx->sample_rate: %d, mSamplingRate: %d, mCtx->sample_fmt: %s, mSamplingFmt: %s",
739 mCtx->channels, mNumChannels, mCtx->sample_rate, mSamplingRate,
740 av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mSamplingFmt));
741 mNumChannels = mCtx->channels;
742 mSamplingRate = mCtx->sample_rate;
743 mSamplingFmt = mCtx->sample_fmt;
744 mAudioConfigChanged = true;
745 notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
746 mOutputPortSettingsChange = AWAITING_DISABLED;
749 // match with the default, set mAudioConfigChanged true anyway!
750 mAudioConfigChanged = true;
751 mSamplingFmt = mCtx->sample_fmt;
755 dataSize = av_samples_get_buffer_size(NULL, mNumChannels, mFrame->nb_samples, mSamplingFmt, 1);
758 LOGV("audio decoder, nb_samples: %d, get buffer size: %d", mFrame->nb_samples, dataSize);
759 LOGV("audio decoder: mCtx channel_layout: %llu, channels: %d, channels_from_layout: %d\n",
760 mCtx->channel_layout, mCtx->channels, av_get_channel_layout_nb_channels(mCtx->channel_layout));
763 decChannelLayout = av_get_default_channel_layout(mNumChannels);
764 if (mSamplingFmt != mAudioSrcFmt ||
765 decChannelLayout != mAudioSrcChannelLayout ||
766 mSamplingRate != mAudioSrcFreq ) {
769 mSwrCtx = swr_alloc_set_opts(NULL,
770 mAudioTgtChannelLayout, mAudioTgtFmt, mAudioTgtFreq,
771 decChannelLayout, mSamplingFmt, mSamplingRate,
773 if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
774 LOGE("Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!",
776 av_get_sample_fmt_name(mSamplingFmt),
779 av_get_sample_fmt_name(mAudioTgtFmt),
781 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
782 mSignalledError = true;
786 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)!",
788 av_get_sample_fmt_name(mSamplingFmt),
790 mAudioTgtChannelLayout,
792 av_get_sample_fmt_name(mAudioTgtFmt),
796 mAudioSrcChannelLayout = decChannelLayout;
797 mAudioSrcChannels = mNumChannels;
798 mAudioSrcFreq = mSamplingRate;
799 mAudioSrcFmt = mSamplingFmt;
803 //const uint8_t *in[] = { mFrame->data[0] };
804 const uint8_t **in = (const uint8_t **)mFrame->extended_data;
805 uint8_t *out[] = {mAudioBuf2};
806 int out_count = sizeof(mAudioBuf2) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt);
809 LOGV("swr_convert 1, out_count: %d, mFrame->nb_samples: %d, src frm: %s, tgt frm: %s",
810 out_count, mFrame->nb_samples, av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mAudioTgtFmt));
812 int len2 = swr_convert(mSwrCtx, out, out_count, in, mFrame->nb_samples);
814 LOGE("audio_resample() failed");
817 if (len2 == out_count) {
818 LOGE("warning: audio buffer is probably too small");
821 mPAudioBuffer = mAudioBuf2;
822 mAudioBufferSize = len2 * mAudioTgtChannels * av_get_bytes_per_sample(mAudioTgtFmt);
824 mPAudioBuffer = mFrame->data[0];
825 mAudioBufferSize = dataSize;
829 LOGV("ffmpeg audio decoder get frame. consume pkt len: %d, nb_samples(before resample): %d, mAudioBufferSize: %d",
830 len, mFrame->nb_samples, mAudioBufferSize);
832 } // if (inHeader && mAudioBufferSize == 0 && !mFlushComplete)
834 size_t copyToOutputBufferLen = mAudioBufferSize;
835 if (mAudioBufferSize > kOutputBufferSize)
836 copyToOutputBufferLen = kOutputBufferSize;
838 outHeader->nOffset = 0;
839 outHeader->nFilledLen = copyToOutputBufferLen;
840 outHeader->nTimeStamp = mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
841 memcpy(outHeader->pBuffer, mPAudioBuffer, copyToOutputBufferLen);
842 outHeader->nFlags = 0;
845 LOGV("ffmpeg audio decoder, fill out buffer, pts: %lld, mNumFramesOutput: %lld", outHeader->nTimeStamp, mNumFramesOutput);
848 mPAudioBuffer += copyToOutputBufferLen;
849 mAudioBufferSize -= copyToOutputBufferLen;
850 mNumFramesOutput += copyToOutputBufferLen / (av_get_bytes_per_sample(mAudioTgtFmt) * mNumChannels);
852 // reset mNumFramesOutput
853 if (mAudioBufferSize == 0) {
855 LOGV("~~~~ mAudioBufferSize, set mNumFramesOutput = 0");
857 mNumFramesOutput = 0;
860 outInfo->mOwnedByUs = false;
861 outQueue.erase(outQueue.begin());
863 notifyFillBufferDone(outHeader);
868 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
869 if (portIndex == 0 && mCtx) {
870 // Make sure that the next buffer output does not still
871 // depend on fragments from the last one decoded.
872 avcodec_flush_buffers(mCtx);
877 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
878 if (portIndex != 1) {
882 switch (mOutputPortSettingsChange) {
886 case AWAITING_DISABLED:
889 mOutputPortSettingsChange = AWAITING_ENABLED;
895 CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
897 mOutputPortSettingsChange = NONE;
903 } // namespace android
905 android::SoftOMXComponent *createSoftOMXComponent(
906 const char *name, const OMX_CALLBACKTYPE *callbacks,
907 OMX_PTR appData, OMX_COMPONENTTYPE **component) {
908 return new android::SoftFFmpegAudio(name, callbacks, appData, component);