OSDN Git Service

add support for wmv1
[android-x86/external-stagefright-plugins.git] / libstagefright / codecs / ffmpegdec / adec / SoftFFmpegAudio.cpp
1 /*
2  * Copyright 2012 Michael Chen <omxcodec@gmail.com>
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #define LOG_NDEBUG 0
18 #define LOG_TAG "SoftFFmpegAudio"
19 #include <utils/Log.h>
20
21 #include "SoftFFmpegAudio.h"
22
23 #include <media/stagefright/foundation/ADebug.h>
24 #include <media/stagefright/foundation/hexdump.h>
25 #include <media/stagefright/MediaDefs.h>
26
27 #include "ffmpeg_utils/ffmpeg_utils.h"
28
29 #undef realloc
30 #include <stdlib.h>
31
32 #define DEBUG_PKT 0
33 #define DEBUG_FRM 0
34
35 namespace android {
36
37 template<class T>
38 static void InitOMXParams(T *params) {
39     params->nSize = sizeof(T);
40     params->nVersion.s.nVersionMajor = 1;
41     params->nVersion.s.nVersionMinor = 0;
42     params->nVersion.s.nRevision = 0;
43     params->nVersion.s.nStep = 0;
44 }
45
46 SoftFFmpegAudio::SoftFFmpegAudio(
47         const char *name,
48         const OMX_CALLBACKTYPE *callbacks,
49         OMX_PTR appData,
50         OMX_COMPONENTTYPE **component)
51     : SimpleSoftOMXComponent(name, callbacks, appData, component),
52       mMode(MODE_MPEG),
53       mCtx(NULL),
54       mSwrCtx(NULL),
55       mCodecOpened(false),
56       mExtradataReady(false),
57       mIgnoreExtradata(false),
58       mFlushComplete(false),
59       mSignalledError(false),
60       mReceivedEOS(false),
61       mFrame(NULL),
62       mAnchorTimeUs(0),
63       mNumFramesOutput(0),
64       mInputBufferSize(0),
65       mAudioBufferSize(0),
66       mNumChannels(2),
67       mSamplingRate(44100),
68       mSamplingFmt(AV_SAMPLE_FMT_S16),
69       mAudioConfigChanged(false),
70       mOutputPortSettingsChange(NONE) {
71     if (!strcmp(name, "OMX.ffmpeg.mp3.decoder")) {
72         mMode = MODE_MPEG;
73         mIgnoreExtradata = true;
74     } else if (!strcmp(name, "OMX.ffmpeg.mp1.decoder")) {
75         mMode = MODE_MPEGL1;
76     } else if (!strcmp(name, "OMX.ffmpeg.mp2.decoder")) {
77         mMode = MODE_MPEGL2;
78     } else if (!strcmp(name, "OMX.ffmpeg.aac.decoder")) {
79         mMode = MODE_AAC;
80     } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
81         mMode = MODE_APE;
82     } else if (!strcmp(name, "OMX.ffmpeg.wma.decoder")) {
83         mMode = MODE_WMA;
84     } else if (!strcmp(name, "OMX.ffmpeg.dts.decoder")) {
85         mMode = MODE_DTS;
86     } else if (!strcmp(name, "OMX.ffmpeg.ra.decoder")) {
87         mMode = MODE_RA;
88     } else {
89         CHECK(!strcmp(name, "OMX.ffmpeg.ac3.decoder"));
90         mMode = MODE_AC3;
91     }
92
93     LOGV("SoftFFmpegAudio component: %s", name);
94
95     initPorts();
96     CHECK_EQ(initDecoder(), (status_t)OK);
97 }
98
99 SoftFFmpegAudio::~SoftFFmpegAudio() {
100     av_freep(&mFrame);
101     LOGV("~SoftFFmpegAudio");
102     deInitDecoder();
103     deInitFFmpeg();
104 }
105
106 void SoftFFmpegAudio::initPorts() {
107     OMX_PARAM_PORTDEFINITIONTYPE def;
108     InitOMXParams(&def);
109
110     def.nPortIndex = 0;
111     def.eDir = OMX_DirInput;
112     def.nBufferCountMin = kNumBuffers;
113     def.nBufferCountActual = def.nBufferCountMin;
114     def.nBufferSize = 8192;
115     def.bEnabled = OMX_TRUE;
116     def.bPopulated = OMX_FALSE;
117     def.eDomain = OMX_PortDomainAudio;
118     def.bBuffersContiguous = OMX_FALSE;
119     def.nBufferAlignment = 1;
120
121     switch (mMode) {
122     case MODE_MPEG:
123         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
124         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
125         break;
126     case MODE_MPEGL1:
127         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
128         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
129         break;
130     case MODE_MPEGL2:
131         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
132         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
133         break;
134     case MODE_AAC:
135         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AAC);
136         def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
137         break;
138     case MODE_AC3:
139         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AC3);
140         // TODO
141         //def.format.audio.eEncoding = OMX_AUDIO_CodingAC3;
142         def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect; // right?? orz
143         break;
144     default:
145         CHECK(!"Should not be here. Unsupported mime type and compression format");
146         break;
147     }
148
149     def.format.audio.pNativeRender = NULL;
150     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
151
152     addPort(def);
153
154     def.nPortIndex = 1;
155     def.eDir = OMX_DirOutput;
156     def.nBufferCountMin = kNumBuffers;
157     def.nBufferCountActual = def.nBufferCountMin;
158     def.nBufferSize = kOutputBufferSize;
159     def.bEnabled = OMX_TRUE;
160     def.bPopulated = OMX_FALSE;
161     def.eDomain = OMX_PortDomainAudio;
162     def.bBuffersContiguous = OMX_FALSE;
163     def.nBufferAlignment = 2;
164
165     def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
166     def.format.audio.pNativeRender = NULL;
167     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
168     def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
169
170     addPort(def);
171 }
172
173 static int lockmgr(void **mtx, enum AVLockOp op) {
174    switch(op) {
175       case AV_LOCK_CREATE:
176           *mtx = (void *)SDL_CreateMutex();
177           if(!*mtx)
178               return 1;
179           return 0;
180       case AV_LOCK_OBTAIN:
181           return !!SDL_LockMutex((SDL_mutex *)*mtx);
182       case AV_LOCK_RELEASE:
183           return !!SDL_UnlockMutex((SDL_mutex *)*mtx);
184       case AV_LOCK_DESTROY:
185           SDL_DestroyMutex((SDL_mutex *)*mtx);
186           return 0;
187    }
188    return 1;
189 }
190
191 void SoftFFmpegAudio::setAVCtxToDefault(AVCodecContext *avctx, const AVCodec *codec) {
192     int fast = 0;
193
194     avctx->workaround_bugs   = 1;
195     avctx->lowres            = 0;
196     if(avctx->lowres > codec->max_lowres){
197         LOGW("The maximum value for lowres supported by the decoder is %d",
198                 codec->max_lowres);
199         avctx->lowres= codec->max_lowres;
200     }
201     avctx->idct_algo         = 0;
202     avctx->skip_frame        = AVDISCARD_DEFAULT;
203     avctx->skip_idct         = AVDISCARD_DEFAULT;
204     avctx->skip_loop_filter  = AVDISCARD_DEFAULT;
205     avctx->error_concealment = 3;
206
207     if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
208     if (fast)   avctx->flags2 |= CODEC_FLAG2_FAST;
209     if(codec->capabilities & CODEC_CAP_DR1)
210         avctx->flags |= CODEC_FLAG_EMU_EDGE;
211 }
212
213 status_t SoftFFmpegAudio::initDecoder() {
214     status_t status;
215
216     status = initFFmpeg();
217     if (status != OK)
218         return NO_INIT;
219
220     mCtx = avcodec_alloc_context3(NULL);
221     if (!mCtx)
222     {
223         LOGE("avcodec_alloc_context failed.");
224         return NO_MEMORY;
225     }
226
227     mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
228     switch (mMode) {
229     case MODE_MPEG:
230         mCtx->codec_id = CODEC_ID_MP3;
231         break;
232     case MODE_MPEGL1:
233         mCtx->codec_id = CODEC_ID_MP1;
234         break;
235     case MODE_MPEGL2:
236         mCtx->codec_id = CODEC_ID_MP2;
237         break;
238     case MODE_AAC:
239         mCtx->codec_id = CODEC_ID_AAC;
240         break;
241     case MODE_AC3:
242         mCtx->codec_id = CODEC_ID_AC3;
243         break;
244     default:
245         CHECK(!"Should not be here. Unsupported codec");
246         break;
247     }
248
249     mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
250     if (!mCtx->codec)
251     {
252         LOGE("find codec failed");
253         return BAD_TYPE;
254     }
255
256     setAVCtxToDefault(mCtx, mCtx->codec);
257
258     mCtx->sample_fmt = AV_SAMPLE_FMT_S16;
259
260     mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
261     mAudioSrcFreq = mAudioTgtFreq = mSamplingRate;
262     mAudioSrcChannels = mAudioTgtChannels = mNumChannels;
263     mAudioSrcChannelLayout = mAudioTgtChannelLayout = 
264         av_get_default_channel_layout(mNumChannels);
265
266     memset(mSilenceBuffer, 0, kOutputBufferSize);
267
268     return OK;
269 }
270
271 void SoftFFmpegAudio::deInitDecoder() {
272     if (mCtx) {
273         //avcodec_flush_buffers(mCtx); // is it necessary? crash sometimes if call it
274         if (!mCtx->extradata) {
275             av_free(mCtx->extradata);
276             mCtx->extradata = NULL;
277             mCtx->extradata_size = 0;
278         }
279         avcodec_close(mCtx);
280         av_free(mCtx);
281         mCtx = NULL;
282     }
283
284     if (mSwrCtx) {
285         swr_free(&mSwrCtx);
286         mSwrCtx = NULL;
287     }
288
289 }
290
291 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
292         OMX_INDEXTYPE index, OMX_PTR params) {
293     int32_t channels = 0;
294     int32_t sampling_rate = 0;
295
296     switch (index) {
297         case OMX_IndexParamAudioAac:
298         {
299             OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
300                 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
301
302             if (aacParams->nPortIndex != 0) {
303                 return OMX_ErrorUndefined;
304             }
305
306             aacParams->nBitRate = 0;
307             aacParams->nAudioBandWidth = 0;
308             aacParams->nAACtools = 0;
309             aacParams->nAACERtools = 0;
310             aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
311             aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
312             aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
313
314             aacParams->nChannels = mNumChannels;
315             aacParams->nSampleRate = mSamplingRate;
316
317             return OMX_ErrorNone;
318         }
319         case OMX_IndexParamAudioPcm:
320         {
321             OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
322                 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
323
324             if (pcmParams->nPortIndex > 1) {
325                 return OMX_ErrorUndefined;
326             }
327
328             pcmParams->eNumData = OMX_NumericalDataSigned;
329             pcmParams->eEndian = OMX_EndianBig;
330             pcmParams->bInterleaved = OMX_TRUE;
331             pcmParams->nBitPerSample = 16;
332             pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
333             pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
334             pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
335
336             channels = mNumChannels >= 2 ? 2 : 1;
337             sampling_rate = mSamplingRate;
338             // 4000 <= nSamplingRate <= 48000
339             if (mSamplingRate < 4000) {
340                 sampling_rate = 4000;
341             } else if (mSamplingRate > 48000) {
342                 sampling_rate = 48000;
343             }
344
345             // update src and target(except aac), only once!
346             mAudioSrcChannels = mAudioTgtChannels =  channels;
347             mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
348             mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
349             mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
350
351             pcmParams->nChannels = channels;
352             pcmParams->nSamplingRate = sampling_rate;
353
354             return OMX_ErrorNone;
355         }
356
357         default:
358             return SimpleSoftOMXComponent::internalGetParameter(index, params);
359     }
360 }
361
362 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
363         OMX_INDEXTYPE index, const OMX_PTR params) {
364     int32_t channels = 0;
365     int32_t sampling_rate = 0;
366
367     switch (index) {
368         case OMX_IndexParamStandardComponentRole:
369         {
370             const OMX_PARAM_COMPONENTROLETYPE *roleParams =
371                 (const OMX_PARAM_COMPONENTROLETYPE *)params;
372
373             bool supported = true;
374             switch (mMode) {
375             case MODE_MPEG:
376                 if (strncmp((const char *)roleParams->cRole,
377                         "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
378                     supported =  false;
379                 break;
380             case MODE_MPEGL1:
381                 if (strncmp((const char *)roleParams->cRole,
382                         "audio_decoder.mp1", OMX_MAX_STRINGNAME_SIZE - 1))
383                     supported =  false;
384                 break;
385             case MODE_MPEGL2:
386                 if (strncmp((const char *)roleParams->cRole,
387                         "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
388                     supported =  false;
389                 break;
390             case MODE_AAC:
391                 if (strncmp((const char *)roleParams->cRole,
392                         "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
393                     supported =  false;
394                 break;
395             case MODE_AC3:
396                 if (strncmp((const char *)roleParams->cRole,
397                         "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
398                     supported =  false;
399                 break;
400             default:
401                 CHECK(!"Should not be here. Unsupported role.");
402                 break;
403             }
404             if (!supported) {
405                 LOGE("unsupported role: %s", (const char *)roleParams->cRole);
406                 return OMX_ErrorUndefined;
407             }
408
409             return OMX_ErrorNone;
410         }
411         case OMX_IndexParamAudioAac:
412         {
413             const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
414                 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
415
416             if (aacParams->nPortIndex != 0) {
417                 return OMX_ErrorUndefined;
418             }
419
420             mNumChannels = aacParams->nChannels;
421             mSamplingRate = aacParams->nSampleRate;
422
423             channels = mNumChannels >= 2 ? 2 : 1;
424             sampling_rate = mSamplingRate;
425             // 4000 <= nSamplingRate <= 48000
426             if (mSamplingRate < 4000) {
427                 sampling_rate = 4000;
428             } else if (mSamplingRate > 48000) {
429                 sampling_rate = 48000;
430             }
431
432             // update src and target(only aac), only once!
433             mAudioSrcChannels = mAudioTgtChannels = channels;
434             mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
435             mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
436             mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
437
438             LOGV("got OMX_IndexParamAudioAac, mNumChannels: %d, mSamplingRate: %d",
439                 mNumChannels, mSamplingRate);
440
441             return OMX_ErrorNone;
442         }
443         default:
444             LOGI("internalSetParameter, index: 0x%x", index);
445             return SimpleSoftOMXComponent::internalSetParameter(index, params);
446     }
447 }
448
449 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
450     int len = 0;
451     int err = 0;
452     size_t dataSize = 0;
453     int64_t decChannelLayout;
454     int32_t inputBufferUsedLength = 0;
455     BufferInfo *inInfo = NULL;
456     OMX_BUFFERHEADERTYPE *inHeader = NULL;
457
458     if (mSignalledError || mOutputPortSettingsChange != NONE) {
459         return;
460     }
461
462     List<BufferInfo *> &inQueue = getPortQueue(0);
463     List<BufferInfo *> &outQueue = getPortQueue(1);
464
465     while ((!inQueue.empty() || mInputBufferSize > 0 ||
466             mAudioBufferSize > 0 || mFlushComplete) && !outQueue.empty()) {
467         if (!inQueue.empty() || mInputBufferSize > 0) {
468             inInfo = *inQueue.begin();
469             inHeader = inInfo->mHeader;
470         } else {
471             inInfo = NULL;
472             inHeader = NULL;
473         }
474
475         BufferInfo *outInfo = *outQueue.begin();
476         OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
477
478         if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
479             inQueue.erase(inQueue.begin());
480             inInfo->mOwnedByUs = false;
481             notifyEmptyBufferDone(inHeader);
482             mReceivedEOS = true;
483         }
484
485         if (mReceivedEOS && (mFlushComplete || !(mCtx->codec->capabilities & CODEC_CAP_DELAY))) {
486             outHeader->nFilledLen = 0;
487             outHeader->nFlags = OMX_BUFFERFLAG_EOS;
488
489             outQueue.erase(outQueue.begin());
490             outInfo->mOwnedByUs = false;
491             notifyFillBufferDone(outHeader);
492             return;
493         }
494
495         if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
496             LOGI("got extradata, ignore: %d, size: %lu", mIgnoreExtradata, inHeader->nFilledLen);
497             hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
498             if (!mExtradataReady && !mIgnoreExtradata) {
499                 int orig_extradata_size = mCtx->extradata_size;
500                 mCtx->extradata_size += inHeader->nFilledLen;
501                 mCtx->extradata = (uint8_t *)realloc(mCtx->extradata,
502                         mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
503                 if (!mCtx->extradata) {
504                     LOGE("ffmpeg audio decoder failed to alloc extradata memory.");
505                     notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
506                     mSignalledError = true;
507                     return;
508                 }
509
510                 memcpy(mCtx->extradata + orig_extradata_size,
511                         inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
512                 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
513
514                 inInfo->mOwnedByUs = false;
515                 inQueue.erase(inQueue.begin());
516                 inInfo = NULL;
517                 notifyEmptyBufferDone(inHeader);
518                 inHeader = NULL;
519
520                 continue;
521             }
522             if (mIgnoreExtradata) {
523                 LOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
524                 inInfo->mOwnedByUs = false;
525                 inQueue.erase(inQueue.begin());
526                 inInfo = NULL;
527                 notifyEmptyBufferDone(inHeader);
528                 inHeader = NULL;
529
530                 continue;
531             }
532         }
533
534         if (!mCodecOpened) {
535             if (!mExtradataReady && !mIgnoreExtradata) {
536                 LOGI("extradata is ready");
537                 hexdump(mCtx->extradata, mCtx->extradata_size);
538                 mExtradataReady = true;
539             }
540             LOGI("open ffmpeg decoder now");
541
542             err = avcodec_open2(mCtx, mCtx->codec, NULL);
543             if (err < 0) {
544                 LOGE("ffmpeg audio decoder failed to initialize. (%d)", err);
545                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
546                 mSignalledError = true;
547                 return;
548             }
549             mCodecOpened = true;
550         }
551
552         /* update the audio clock with the pts */
553         if (inHeader && inHeader->nOffset == 0) {
554             mAnchorTimeUs = inHeader->nTimeStamp;
555             mNumFramesOutput = 0;
556             mInputBufferSize = inHeader->nFilledLen;
557         }
558
559         if (inHeader && mAudioBufferSize == 0 && !mFlushComplete) {
560             AVPacket pkt;
561             av_init_packet(&pkt);
562             if (!mFlushComplete) {
563                 pkt.data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
564                 pkt.size = inHeader->nFilledLen;
565                 pkt.pts = inHeader->nTimeStamp; // ingore it, we will compute it
566             } else {
567                 pkt.data = NULL;
568                 pkt.size = 0;
569                 pkt.pts = AV_NOPTS_VALUE;
570             }
571 #if DEBUG_PKT
572             LOGV("pkt size: %d, pts: %lld", pkt.size, pkt.pts);
573 #endif
574             if (!mFrame) {
575                 if (!(mFrame = avcodec_alloc_frame())) {
576                     LOGE("ffmpeg audio decoder failed to alloc memory.");
577                     notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
578                     mSignalledError = true;
579                     return;
580                 }
581             } else {
582                 avcodec_get_frame_defaults(mFrame);
583             }
584
585             int gotFrm = false;
586             inputBufferUsedLength = 0;
587             len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
588             if (len < 0) {
589                 LOGE("ffmpeg audio decoder failed to decode frame. (0x%x)", len);
590
591                 /* if !mAudioConfigChanged, Don't fill the out buffer */
592                 if (!mAudioConfigChanged) {
593                     inInfo->mOwnedByUs = false;
594                     inQueue.erase(inQueue.begin());
595                     inInfo = NULL;
596                     notifyEmptyBufferDone(inHeader);
597                     inHeader = NULL;
598                     continue;
599                 }
600
601                 inputBufferUsedLength = inHeader->nFilledLen;
602                 /* if error, we skip the frame and play silence instead */
603                 mPAudioBuffer = mSilenceBuffer;
604                 mAudioBufferSize = kOutputBufferSize;
605             } else if (!gotFrm) {
606                 LOGI("ffmpeg audio decoder failed to get frame.");
607                 /* stop sending empty packets if the decoder is finished */
608                 if (!pkt.data && mCtx->codec->capabilities & CODEC_CAP_DELAY)
609                     mFlushComplete = true;
610                 continue;
611             } else {
612                 /**
613                  * FIXME, check mAudioConfigChanged when the first time you call the audio4!
614                  * mCtx->sample_rate and mCtx->channels may be changed by audio decoder later, why???
615                  */
616                 if (!mAudioConfigChanged) {
617                     if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate || mCtx->sample_fmt != mSamplingFmt) {
618                         LOGI("audio OMX_EventPortSettingsChanged, mCtx->channels: %d, mNumChannels: %d, mCtx->sample_rate: %d, mSamplingRate: %d",
619                                 mCtx->channels, mNumChannels, mCtx->sample_rate, mSamplingRate);
620                         mNumChannels = mCtx->channels;
621                         mSamplingRate = mCtx->sample_rate;
622                         mSamplingFmt = mCtx->sample_fmt;
623                         mAudioConfigChanged = true;
624                         notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
625                         mOutputPortSettingsChange = AWAITING_DISABLED;
626                         return;
627                     } else {
628                         // match with the default, set mAudioConfigChanged true anyway!
629                         mAudioConfigChanged = true;
630                     }
631                 }
632
633                 dataSize = av_samples_get_buffer_size(NULL, mNumChannels, mFrame->nb_samples, mSamplingFmt, 1);
634
635                 decChannelLayout = av_get_default_channel_layout(mNumChannels);
636                 if (mSamplingFmt != mAudioSrcFmt ||
637                         decChannelLayout != mAudioSrcChannelLayout ||
638                         mSamplingRate != mAudioSrcFreq ) {
639                     if (mSwrCtx)
640                         swr_free(&mSwrCtx);
641                     mSwrCtx = swr_alloc_set_opts(NULL,
642                                                  mAudioTgtChannelLayout, mAudioTgtFmt, mAudioTgtFreq,
643                                                  decChannelLayout,       mSamplingFmt, mSamplingRate,
644                                                  0, NULL);
645                     if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
646                         LOGE("Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!",
647                                 mSamplingRate,
648                                 av_get_sample_fmt_name(mSamplingFmt),
649                                 mNumChannels,
650                                 mAudioTgtFreq,
651                                 av_get_sample_fmt_name(mAudioTgtFmt),
652                                 mAudioTgtChannels);
653                         notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
654                         mSignalledError = true;
655                         return;
656                     }
657
658                     LOGI("Create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!",
659                         mSamplingRate,
660                         av_get_sample_fmt_name(mSamplingFmt),
661                         mNumChannels,
662                         mAudioTgtFreq,
663                         av_get_sample_fmt_name(mAudioTgtFmt),
664                         mAudioTgtChannels);
665
666                     mAudioSrcChannelLayout = decChannelLayout;
667                     mAudioSrcChannels = mNumChannels;
668                     mAudioSrcFreq = mSamplingRate;
669                     mAudioSrcFmt = mSamplingFmt;
670                 }
671
672                 if (mSwrCtx) {
673                     const uint8_t *in[] = { mFrame->data[0] };
674                     uint8_t *out[] = {mAudioBuf2};
675                     int len2 = swr_convert(mSwrCtx, out, sizeof(mAudioBuf2) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt),
676                                        in, mFrame->nb_samples);
677                     if (len2 < 0) {
678                         LOGE("audio_resample() failed");
679                         break;
680                     }
681                     if (len2 == sizeof(mAudioBuf2) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt)) {
682                         LOGE("warning: audio buffer is probably too small");
683                         swr_init(mSwrCtx);
684                     }
685                     mPAudioBuffer = mAudioBuf2;
686                     mAudioBufferSize = len2 * mAudioTgtChannels * av_get_bytes_per_sample(mAudioTgtFmt);
687                 } else {
688                     mPAudioBuffer = mFrame->data[0];
689                     mAudioBufferSize = dataSize;
690                 }
691
692                 inputBufferUsedLength = len;
693 #if DEBUG_FRM
694                 LOGV("ffmpeg audio decoder get frame. (%d), mAudioBufferSize: %d", len, mAudioBufferSize);
695 #endif
696             }
697         }
698
699         size_t copyToOutputBufferLen = mAudioBufferSize;
700         if (mAudioBufferSize > kOutputBufferSize)
701             copyToOutputBufferLen = kOutputBufferSize;
702
703         outHeader->nOffset = 0;
704         outHeader->nFilledLen = copyToOutputBufferLen;
705         outHeader->nTimeStamp = mAnchorTimeUs
706                 + (mNumFramesOutput * 1000000ll) / mSamplingRate;
707         memcpy(outHeader->pBuffer, mPAudioBuffer, copyToOutputBufferLen);
708         outHeader->nFlags = 0;
709
710         mPAudioBuffer += copyToOutputBufferLen;
711         mAudioBufferSize -= copyToOutputBufferLen;
712         mNumFramesOutput += copyToOutputBufferLen / av_get_bytes_per_sample(mCtx->sample_fmt) / mNumChannels;
713
714         if (inHeader) {
715             CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
716             inHeader->nOffset += inputBufferUsedLength;
717             inHeader->nFilledLen -= inputBufferUsedLength;
718             mInputBufferSize -= inputBufferUsedLength;
719             if (inHeader->nFilledLen == 0) {
720                 inInfo->mOwnedByUs = false;
721                 inQueue.erase(inQueue.begin());
722                 inInfo = NULL;
723                 notifyEmptyBufferDone(inHeader);
724                 inHeader = NULL;
725
726                 mInputBufferSize = 0;
727             }
728         }
729
730         outInfo->mOwnedByUs = false;
731         outQueue.erase(outQueue.begin());
732         outInfo = NULL;
733         notifyFillBufferDone(outHeader);
734         outHeader = NULL;
735     }
736 }
737
738 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
739     if (portIndex == 0 && mCtx) {
740         // Make sure that the next buffer output does not still
741         // depend on fragments from the last one decoded.
742         avcodec_flush_buffers(mCtx);
743     }
744
745 }
746
747 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
748     if (portIndex != 1) {
749         return;
750     }
751
752     switch (mOutputPortSettingsChange) {
753         case NONE:
754             break;
755
756         case AWAITING_DISABLED:
757         {
758             CHECK(!enabled);
759             mOutputPortSettingsChange = AWAITING_ENABLED;
760             break;
761         }
762
763         default:
764         {
765             CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
766             CHECK(enabled);
767             mOutputPortSettingsChange = NONE;
768             break;
769         }
770     }
771 }
772
773 }  // namespace android
774
775 android::SoftOMXComponent *createSoftOMXComponent(
776         const char *name, const OMX_CALLBACKTYPE *callbacks,
777         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
778     return new android::SoftFFmpegAudio(name, callbacks, appData, component);
779 }