OSDN Git Service

add setMode func
[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 <OMX_FFExt.h>
28
29 #include "utils/ffmpeg_utils.h"
30
31 //#undef realloc
32 //#include <stdlib.h>
33
34 #define DEBUG_PKT 0
35 #define DEBUG_FRM 0
36
37 namespace android {
38
39 template<class T>
40 static void InitOMXParams(T *params) {
41     params->nSize = sizeof(T);
42     params->nVersion.s.nVersionMajor = 1;
43     params->nVersion.s.nVersionMinor = 0;
44     params->nVersion.s.nRevision = 0;
45     params->nVersion.s.nStep = 0;
46 }
47
48 void SoftFFmpegAudio::setMode(const char *name) {
49     if (!strcmp(name, "OMX.ffmpeg.mp3.decoder")) {
50         mMode = MODE_MPEG;
51         mIgnoreExtradata = true;
52     } else if (!strcmp(name, "OMX.ffmpeg.mp1.decoder")) {
53         mMode = MODE_MPEGL1;
54     } else if (!strcmp(name, "OMX.ffmpeg.mp2.decoder")) {
55         mMode = MODE_MPEGL2;
56     } else if (!strcmp(name, "OMX.ffmpeg.aac.decoder")) {
57         mMode = MODE_AAC;
58     } else if (!strcmp(name, "OMX.ffmpeg.wma.decoder")) {
59         mMode = MODE_WMA;
60     } else if (!strcmp(name, "OMX.ffmpeg.ra.decoder")) {
61         mMode = MODE_RA;
62     } else if (!strcmp(name, "OMX.ffmpeg.ac3.decoder")) {
63         mMode = MODE_AC3;
64     } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
65         mMode = MODE_APE;
66     } else if (!strcmp(name, "OMX.ffmpeg.dts.decoder")) {
67         mMode = MODE_DTS;
68     } else if (!strcmp(name, "OMX.ffmpeg.flac.decoder")) {
69         mMode = MODE_FLAC;
70     } else if (!strcmp(name, "OMX.ffmpeg.vorbis.decoder")) {
71         mMode = MODE_VORBIS;
72     } else if (!strcmp(name, "OMX.ffmpeg.aheuristic.decoder")) {
73         mMode = MODE_HEURISTIC;
74     } else {
75         TRESPASS();
76     }
77 }
78
79 SoftFFmpegAudio::SoftFFmpegAudio(
80         const char *name,
81         const OMX_CALLBACKTYPE *callbacks,
82         OMX_PTR appData,
83         OMX_COMPONENTTYPE **component)
84     : SimpleSoftOMXComponent(name, callbacks, appData, component),
85       mMode(MODE_MPEG),
86       mFFmpegInited(false),
87       mCtx(NULL),
88       mSwrCtx(NULL),
89       mCodecOpened(false),
90       mExtradataReady(false),
91       mIgnoreExtradata(false),
92       mFlushComplete(false),
93       mSignalledError(false),
94       mReceivedEOS(false),
95       mFrame(NULL),
96       mAnchorTimeUs(0),
97       mNumFramesOutput(0),
98       mInputBufferSize(0),
99       mAudioBufferSize(0),
100       mNumChannels(2),
101       mSamplingRate(44100),
102       mBitRate(0),
103       mBlockAlign(0),
104       mSamplingFmt(AV_SAMPLE_FMT_S16),
105       mAudioConfigChanged(false),
106       mOutputPortSettingsChange(NONE) {
107
108     setMode(name);
109
110     ALOGD("SoftFFmpegAudio component: %s mMode: %d", name, mMode);
111
112     initPorts();
113     CHECK_EQ(initDecoder(), (status_t)OK);
114 }
115
116 SoftFFmpegAudio::~SoftFFmpegAudio() {
117     ALOGV("~SoftFFmpegAudio");
118     av_freep(&mFrame);
119     deInitDecoder();
120     if (mFFmpegInited) {
121         deInitFFmpeg();
122     }
123 }
124
125 void SoftFFmpegAudio::initPorts() {
126     OMX_PARAM_PORTDEFINITIONTYPE def;
127     InitOMXParams(&def);
128
129     def.nPortIndex = 0;
130     def.eDir = OMX_DirInput;
131     def.nBufferCountMin = kNumBuffers;
132     def.nBufferCountActual = def.nBufferCountMin;
133     if (mMode == MODE_APE) {
134         def.nBufferSize = 1000000; // ape!
135     } else if (mMode == MODE_DTS) {
136         def.nBufferSize = 1000000; // dts!
137     } else {
138         def.nBufferSize = 20480; // 8192 is too small
139     }
140     def.bEnabled = OMX_TRUE;
141     def.bPopulated = OMX_FALSE;
142     def.eDomain = OMX_PortDomainAudio;
143     def.bBuffersContiguous = OMX_FALSE;
144     def.nBufferAlignment = 1;
145
146     switch (mMode) {
147     case MODE_MPEG:
148         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
149         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
150         break;
151     case MODE_MPEGL1:
152         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
153         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
154         break;
155     case MODE_MPEGL2:
156         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
157         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
158         break;
159     case MODE_AAC:
160         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AAC);
161         def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
162         break;
163     case MODE_AC3:
164         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AC3);
165         // TODO
166         //def.format.audio.eEncoding = OMX_AUDIO_CodingAC3;
167         def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect; // right?? orz
168         break;
169     case MODE_WMA:
170         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_WMA);
171         def.format.audio.eEncoding = OMX_AUDIO_CodingWMA;
172         break;
173     case MODE_RA:
174         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_RA);
175         def.format.audio.eEncoding = OMX_AUDIO_CodingRA;
176         break;
177     case MODE_APE:
178         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_APE);
179         def.format.audio.eEncoding = OMX_AUDIO_CodingAPE;
180         break;
181     case MODE_DTS:
182         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_DTS);
183         def.format.audio.eEncoding = OMX_AUDIO_CodingDTS;
184         break;
185     case MODE_FLAC:
186         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_FLAC);
187         def.format.audio.eEncoding = OMX_AUDIO_CodingFLAC;
188         break;
189     case MODE_VORBIS:
190         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_VORBIS);
191         def.format.audio.eEncoding = OMX_AUDIO_CodingVORBIS;
192         break;
193     case MODE_HEURISTIC:
194         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_FFMPEG);
195         def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect;
196         break;
197     default:
198         CHECK(!"Should not be here. Unsupported mime type and compression format");
199         break;
200     }
201
202     def.format.audio.pNativeRender = NULL;
203     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
204
205     addPort(def);
206
207     def.nPortIndex = 1;
208     def.eDir = OMX_DirOutput;
209     def.nBufferCountMin = kNumBuffers;
210     def.nBufferCountActual = def.nBufferCountMin;
211     def.nBufferSize = kOutputBufferSize;
212     def.bEnabled = OMX_TRUE;
213     def.bPopulated = OMX_FALSE;
214     def.eDomain = OMX_PortDomainAudio;
215     def.bBuffersContiguous = OMX_FALSE;
216     def.nBufferAlignment = 2;
217
218     def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
219     def.format.audio.pNativeRender = NULL;
220     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
221     def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
222
223     addPort(def);
224 }
225
226 void SoftFFmpegAudio::setAVCtxToDefault(AVCodecContext *avctx, const AVCodec *codec) {
227     int fast = 0;
228
229     avctx->workaround_bugs   = 1;
230     avctx->lowres            = 0;
231     if(avctx->lowres > codec->max_lowres){
232         ALOGW("The maximum value for lowres supported by the decoder is %d",
233                 codec->max_lowres);
234         avctx->lowres= codec->max_lowres;
235     }
236     avctx->idct_algo         = 0;
237     avctx->skip_frame        = AVDISCARD_DEFAULT;
238     avctx->skip_idct         = AVDISCARD_DEFAULT;
239     avctx->skip_loop_filter  = AVDISCARD_DEFAULT;
240     avctx->error_concealment = 3;
241
242     if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
243     if (fast)   avctx->flags2 |= CODEC_FLAG2_FAST;
244     if(codec->capabilities & CODEC_CAP_DR1)
245         avctx->flags |= CODEC_FLAG_EMU_EDGE;
246 }
247
248
249 void SoftFFmpegAudio::configDefaultCtx() {
250     mCtx->channels = mNumChannels;
251     mCtx->sample_rate = mSamplingRate;
252     mCtx->bit_rate = mBitRate;
253     mCtx->sample_fmt = mSamplingFmt;
254
255     mAudioSrcChannels = mAudioTgtChannels = mNumChannels;
256     mAudioSrcFreq = mAudioTgtFreq = mSamplingRate;
257     mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
258     mAudioSrcChannelLayout = mAudioTgtChannelLayout =
259         av_get_default_channel_layout(mNumChannels);
260 }
261
262 status_t SoftFFmpegAudio::initDecoder() {
263     status_t status;
264
265     status = initFFmpeg();
266     if (status != OK)
267         return NO_INIT;
268
269     mFFmpegInited = true;
270
271     mCtx = avcodec_alloc_context3(NULL);
272     if (!mCtx)
273     {
274         ALOGE("avcodec_alloc_context failed.");
275         return NO_MEMORY;
276     }
277
278     mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
279     switch (mMode) {
280     case MODE_MPEG:
281         mCtx->codec_id = CODEC_ID_MP3;
282         break;
283     case MODE_MPEGL1:
284         mCtx->codec_id = CODEC_ID_MP1;
285         break;
286     case MODE_MPEGL2:
287         mCtx->codec_id = CODEC_ID_MP2;
288         break;
289     case MODE_AAC:
290         mCtx->codec_id = CODEC_ID_AAC;
291         break;
292     case MODE_AC3:
293         mCtx->codec_id = CODEC_ID_AC3;
294         break;
295     case MODE_WMA:
296         mCtx->codec_id = CODEC_ID_WMAV2; // FIXME, CODEC_ID_WMAV1 or CODEC_ID_WMAV2?
297         break;
298     case MODE_RA:
299         mCtx->codec_id = CODEC_ID_COOK; // FIXME
300         break;
301     case MODE_APE:
302         mCtx->codec_id = CODEC_ID_APE;
303         break;
304     case MODE_DTS:
305         mCtx->codec_id = CODEC_ID_DTS;
306         break;
307     case MODE_FLAC:
308         mCtx->codec_id = CODEC_ID_FLAC;
309         break;
310     case MODE_VORBIS:
311         mCtx->codec_id = CODEC_ID_VORBIS;
312         break;
313     case MODE_HEURISTIC:
314         mCtx->codec_id = CODEC_ID_NONE;
315         break;
316     default:
317         CHECK(!"Should not be here. Unsupported codec");
318         break;
319     }
320
321     //default config
322     configDefaultCtx();
323
324     mCtx->extradata = NULL;
325     mCtx->extradata_size = 0;
326
327     memset(mSilenceBuffer, 0, kOutputBufferSize);
328
329     return OK;
330 }
331
332 void SoftFFmpegAudio::deInitDecoder() {
333     if (mCtx) {
334         //avcodec_flush_buffers(mCtx); // is it necessary? crash sometimes if call it
335         if (!mCtx->extradata) {
336             av_free(mCtx->extradata);
337             mCtx->extradata = NULL;
338             mCtx->extradata_size = 0;
339         }
340         avcodec_close(mCtx);
341         av_free(mCtx);
342         mCtx = NULL;
343     }
344
345     if (mSwrCtx) {
346         swr_free(&mSwrCtx);
347         mSwrCtx = NULL;
348     }
349 }
350
351 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
352         OMX_INDEXTYPE index, OMX_PTR params) {
353     int32_t channels = 0;
354     int32_t sampling_rate = 0;
355
356     switch (index) {
357         case OMX_IndexParamAudioAac:
358         {
359             OMX_AUDIO_PARAM_AACPROFILETYPE *profile =
360                 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
361
362             if (profile->nPortIndex != 0) {
363                 return OMX_ErrorUndefined;
364             }
365
366             profile->nBitRate = 0;
367             profile->nAudioBandWidth = 0;
368             profile->nAACtools = 0;
369             profile->nAACERtools = 0;
370             profile->eAACProfile = OMX_AUDIO_AACObjectMain;
371             profile->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
372             profile->eChannelMode = OMX_AUDIO_ChannelModeStereo;
373
374             profile->nChannels = 0;
375             profile->nSampleRate = 0;
376
377             return OMX_ErrorNone;
378         }
379         case OMX_IndexParamAudioWma:
380         {
381             OMX_AUDIO_PARAM_WMATYPE *profile =
382                 (OMX_AUDIO_PARAM_WMATYPE *)params;
383
384             if (profile->nPortIndex != 0) {
385                 return OMX_ErrorUndefined;
386             }
387
388             profile->nChannels = 0;
389             profile->nSamplingRate = 0;
390             profile->nBitRate = 0;
391             profile->eFormat = OMX_AUDIO_WMAFormatUnused;
392
393             return OMX_ErrorNone;
394         }
395         case OMX_IndexParamAudioRa:
396         {
397             OMX_AUDIO_PARAM_RATYPE *profile =
398                 (OMX_AUDIO_PARAM_RATYPE *)params;
399
400             if (profile->nPortIndex != 0) {
401                 return OMX_ErrorUndefined;
402             }
403
404             profile->nChannels = 0;
405             profile->nSamplingRate = 0;
406             profile->eFormat = OMX_AUDIO_RAFormatUnused;
407
408             return OMX_ErrorNone;
409         }
410         case OMX_IndexParamAudioApe:
411         {
412             OMX_AUDIO_PARAM_APETYPE *profile =
413                 (OMX_AUDIO_PARAM_APETYPE *)params;
414
415             if (profile->nPortIndex != 0) {
416                 return OMX_ErrorUndefined;
417             }
418
419             profile->nChannels = 0;
420             profile->nSamplingRate = 0;
421
422             return OMX_ErrorNone;
423         }
424         case OMX_IndexParamAudioDts:
425         {
426             OMX_AUDIO_PARAM_DTSTYPE *profile =
427                 (OMX_AUDIO_PARAM_DTSTYPE *)params;
428
429             if (profile->nPortIndex != 0) {
430                 return OMX_ErrorUndefined;
431             }
432
433             profile->nChannels = 0;
434             profile->nSamplingRate = 0;
435
436             return OMX_ErrorNone;
437         }
438         case OMX_IndexParamAudioFlac:
439         {
440             OMX_AUDIO_PARAM_FLACTYPE *profile =
441                 (OMX_AUDIO_PARAM_FLACTYPE *)params;
442
443             if (profile->nPortIndex != 0) {
444                 return OMX_ErrorUndefined;
445             }
446
447             profile->nChannels = 0;
448             profile->nSampleRate = 0;
449
450             return OMX_ErrorNone;
451         }
452         case OMX_IndexParamAudioPcm:
453         {
454             OMX_AUDIO_PARAM_PCMMODETYPE *profile =
455                 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
456
457             if (profile->nPortIndex > 1) {
458                 return OMX_ErrorUndefined;
459             }
460
461             profile->eNumData = OMX_NumericalDataSigned;
462             profile->eEndian = OMX_EndianBig;
463             profile->bInterleaved = OMX_TRUE;
464             profile->nBitPerSample = 16;
465             profile->ePCMMode = OMX_AUDIO_PCMModeLinear;
466             profile->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
467             profile->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
468
469             // update src and target(except aac), only once!
470             adjustAudioParameter();
471
472             channels = mNumChannels >= 2 ? 2 : 1;
473
474             // 4000 <= sampling rate <= 48000
475             sampling_rate = mSamplingRate;
476             if (mSamplingRate < 4000) {
477                 sampling_rate = 4000;
478             } else if (mSamplingRate > 48000) {
479                 sampling_rate = 48000;
480             }
481
482             profile->nChannels = channels;
483             profile->nSamplingRate = sampling_rate;
484
485             return OMX_ErrorNone;
486         }
487         case OMX_IndexParamAudioVorbis:
488         {
489             OMX_AUDIO_PARAM_VORBISTYPE *profile =
490                 (OMX_AUDIO_PARAM_VORBISTYPE *)params;
491
492             if (profile->nPortIndex != 0) {
493                 return OMX_ErrorUndefined;
494             }
495
496             profile->nBitRate = 0;
497             profile->nMinBitRate = 0;
498             profile->nMaxBitRate = 0;
499             profile->nAudioBandWidth = 0;
500             profile->nQuality = 3;
501             profile->bManaged = OMX_FALSE;
502             profile->bDownmix = OMX_FALSE;
503
504             profile->nChannels = 1;
505             profile->nSampleRate = 44100;
506 /*
507             if (!isConfigured()) {
508                 profile->nChannels = 1;
509                 profile->nSampleRate = 44100;
510             } else {
511                 profile->nChannels = mVi->channels;
512                 profile->nSampleRate = mVi->rate;
513                 profile->nBitRate = mVi->bitrate_nominal;
514                 profile->nMinBitRate = mVi->bitrate_lower;
515                 profile->nMaxBitRate = mVi->bitrate_upper;
516             }
517 */
518             return OMX_ErrorNone;
519         }
520
521         default:
522             if ((OMX_FF_INDEXTYPE)index == OMX_IndexParamAudioFFmpeg)
523             {
524                 OMX_AUDIO_PARAM_FFMPEGTYPE *profile =
525                     (OMX_AUDIO_PARAM_FFMPEGTYPE *)params;
526
527                 if (profile->nPortIndex != 0) {
528                     return OMX_ErrorUndefined;
529                 }
530
531                 profile->eCodecId = 0; 
532                 profile->nChannels = 0;
533                 profile->nBitRate = 0;
534                 profile->nBitsPerSample = 0;
535                 profile->nSampleRate = 0;
536                 profile->nBlockAlign = 0;
537                 profile->eSampleFormat = 0;
538
539                 return OMX_ErrorNone;
540             }
541
542             return SimpleSoftOMXComponent::internalGetParameter(index, params);
543     }
544 }
545
546 OMX_ERRORTYPE SoftFFmpegAudio::isRoleSupported(
547         const OMX_PARAM_COMPONENTROLETYPE *roleParams) {
548     bool supported = true;
549
550     switch (mMode) {
551     case MODE_MPEG:
552         if (strncmp((const char *)roleParams->cRole,
553                 "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
554             supported =  false;
555         break;
556     case MODE_MPEGL1:
557         if (strncmp((const char *)roleParams->cRole,
558                 "audio_decoder.mp1", OMX_MAX_STRINGNAME_SIZE - 1))
559             supported =  false;
560         break;
561     case MODE_MPEGL2:
562         if (strncmp((const char *)roleParams->cRole,
563                 "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
564             supported =  false;
565         break;
566     case MODE_AAC:
567         if (strncmp((const char *)roleParams->cRole,
568                 "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
569         supported =  false;
570         break;
571     case MODE_AC3:
572         if (strncmp((const char *)roleParams->cRole,
573                 "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
574             supported =  false;
575         break;
576     case MODE_WMA:
577         if (strncmp((const char *)roleParams->cRole,
578                 "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
579         supported =  false;
580         break;
581     case MODE_RA:
582         if (strncmp((const char *)roleParams->cRole,
583                 "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
584         supported =  false;
585         break;
586     case MODE_APE:
587         if (strncmp((const char *)roleParams->cRole,
588                 "audio_decoder.ape", OMX_MAX_STRINGNAME_SIZE - 1))
589         supported =  false;
590         break;
591     case MODE_DTS:
592         if (strncmp((const char *)roleParams->cRole,
593                 "audio_decoder.dts", OMX_MAX_STRINGNAME_SIZE - 1))
594         supported =  false;
595         break;
596     case MODE_FLAC:
597         if (strncmp((const char *)roleParams->cRole,
598                 "audio_decoder.flac", OMX_MAX_STRINGNAME_SIZE - 1))
599         supported =  false;
600         break;
601     case MODE_VORBIS:
602         if (strncmp((const char *)roleParams->cRole,
603                 "audio_decoder.vorbis", OMX_MAX_STRINGNAME_SIZE - 1))
604         supported =  false;
605         break;
606     case MODE_HEURISTIC:
607         if (strncmp((const char *)roleParams->cRole,
608                 "audio_decoder.heuristic", OMX_MAX_STRINGNAME_SIZE - 1))
609         supported =  false;
610         break;
611     default:
612         CHECK(!"Should not be here. Unsupported role.");
613         break;
614     }
615
616     if (!supported) {
617         ALOGE("unsupported role: %s", (const char *)roleParams->cRole);
618         return OMX_ErrorUndefined;
619     }
620
621     return OMX_ErrorNone;
622 }
623
624 void SoftFFmpegAudio::adjustAudioParameter() {
625     int32_t channels = 0;
626     int32_t sampling_rate = 0;
627
628     mCtx->channels = mNumChannels;
629     mCtx->sample_rate = mSamplingRate;
630     mCtx->bit_rate = mBitRate;
631     mCtx->sample_fmt = mSamplingFmt;
632
633     // channels support 1 or 2 only
634     channels = mNumChannels >= 2 ? 2 : 1;
635
636     // 4000 <= sampling rate <= 48000
637     sampling_rate = mSamplingRate;
638     if (mSamplingRate < 4000) {
639         sampling_rate = 4000;
640     } else if (mSamplingRate > 48000) {
641         sampling_rate = 48000;
642     }
643
644     // update src and target(only wma), only once!
645     mAudioSrcChannels = mAudioTgtChannels = channels;
646     mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
647     mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
648     mAudioSrcChannelLayout = mAudioTgtChannelLayout =
649         av_get_default_channel_layout(channels);
650 }
651
652 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
653         OMX_INDEXTYPE index, const OMX_PTR params) {
654     switch (index) {
655         case OMX_IndexParamStandardComponentRole:
656         {
657             const OMX_PARAM_COMPONENTROLETYPE *roleParams =
658                 (const OMX_PARAM_COMPONENTROLETYPE *)params;
659                         return isRoleSupported(roleParams);
660         }
661         case OMX_IndexParamAudioPcm:
662         {
663             const OMX_AUDIO_PARAM_PCMMODETYPE *profile =
664                 (const OMX_AUDIO_PARAM_PCMMODETYPE *)params;
665
666             if (profile->nPortIndex != 1) {
667                 return OMX_ErrorUndefined;
668             }
669
670             mNumChannels = profile->nChannels;
671             mSamplingRate = profile->nSamplingRate;
672
673             return OMX_ErrorNone;
674         }
675         case OMX_IndexParamAudioAac:
676         {
677             const OMX_AUDIO_PARAM_AACPROFILETYPE *profile =
678                 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
679
680             if (profile->nPortIndex != 0) {
681                 return OMX_ErrorUndefined;
682             }
683
684             mNumChannels = profile->nChannels;
685             mSamplingRate = profile->nSampleRate;
686
687             // update src and target(only aac), only once!
688             adjustAudioParameter();
689
690             ALOGV("got OMX_IndexParamAudioAac, mNumChannels: %d, mSamplingRate: %d",
691                 mNumChannels, mSamplingRate);
692
693             return OMX_ErrorNone;
694         }
695         case OMX_IndexParamAudioWma:
696         {
697             OMX_AUDIO_PARAM_WMATYPE *profile =
698                 (OMX_AUDIO_PARAM_WMATYPE *)params;
699
700             if (profile->nPortIndex != 0) {
701                 return OMX_ErrorUndefined;
702             }
703
704             if (profile->eFormat == OMX_AUDIO_WMAFormat7) {
705                mCtx->codec_id = CODEC_ID_WMAV2;
706             } else if (profile->eFormat == OMX_AUDIO_WMAFormat8) {
707                mCtx->codec_id = CODEC_ID_WMAPRO;
708             } else if (profile->eFormat == OMX_AUDIO_WMAFormat9) {
709                mCtx->codec_id = CODEC_ID_WMALOSSLESS;
710             } else {
711                 ALOGE("unsupported wma codec: 0x%x", profile->eFormat);
712                 return OMX_ErrorUndefined;
713             }
714
715             mNumChannels = profile->nChannels;
716             mSamplingRate = profile->nSamplingRate;
717             mBitRate = profile->nBitRate;
718             mBlockAlign = profile->nBlockAlign;
719
720             // wmadec needs bitrate, block_align
721             mCtx->bit_rate = mBitRate;
722             mCtx->block_align = mBlockAlign;
723
724             // update src and target(only wma), only once!
725             adjustAudioParameter();
726
727             ALOGV("got OMX_IndexParamAudioWma, mNumChannels: %d, "
728                     "mSamplingRate: %d, mBitRate: %d, mBlockAlign: %d",
729                 mNumChannels, mSamplingRate, mBitRate, mBlockAlign);
730
731             return OMX_ErrorNone;
732         }
733         case OMX_IndexParamAudioRa:
734         {
735             OMX_AUDIO_PARAM_RATYPE *profile =
736                 (OMX_AUDIO_PARAM_RATYPE *)params;
737
738             if (profile->nPortIndex != 0) {
739                 return OMX_ErrorUndefined;
740             }
741
742             mCtx->codec_id = CODEC_ID_COOK;
743
744             mNumChannels = profile->nChannels;
745             mSamplingRate = profile->nSamplingRate;
746             // FIXME, HACK!!!, I use the nNumRegions parameter pass blockAlign!!!
747             // the cook audio codec need blockAlign!
748             mBlockAlign = profile->nNumRegions;
749
750             // cook decoder need block_align
751             mCtx->block_align = mBlockAlign;
752
753             // update src and target(only wma), only once!
754             adjustAudioParameter();
755
756             ALOGV("got OMX_IndexParamAudioRa, mNumChannels: %d, "
757                     "mSamplingRate: %d, mBlockAlign: %d",
758                 mNumChannels, mSamplingRate, mBlockAlign);
759
760             return OMX_ErrorNone;
761         }
762         case OMX_IndexParamAudioApe:
763         {
764             OMX_AUDIO_PARAM_APETYPE *profile =
765                 (OMX_AUDIO_PARAM_APETYPE *)params;
766
767             if (profile->nPortIndex != 0) {
768                 return OMX_ErrorUndefined;
769             }
770
771             mNumChannels = profile->nChannels;
772             mSamplingRate = profile->nSamplingRate;
773
774             // ape decoder need bits_per_coded_sample
775             mCtx->bits_per_coded_sample = profile->nBitsPerSample;
776
777             // update src and target, only once!
778             adjustAudioParameter();
779
780             ALOGV("got OMX_IndexParamAudioApe, mNumChannels: %d, "
781                     "mSamplingRate: %d, nBitsPerSample: %lu",
782                 mNumChannels, mSamplingRate, profile->nBitsPerSample);
783
784             return OMX_ErrorNone;
785         }
786         case OMX_IndexParamAudioDts:
787         {
788             OMX_AUDIO_PARAM_DTSTYPE *profile =
789                 (OMX_AUDIO_PARAM_DTSTYPE *)params;
790
791             if (profile->nPortIndex != 0) {
792                 return OMX_ErrorUndefined;
793             }
794
795             mNumChannels = profile->nChannels;
796             mSamplingRate = profile->nSamplingRate;
797
798             // update src and target, only once!
799             adjustAudioParameter();
800
801             ALOGV("got OMX_IndexParamAudioDts, mNumChannels: %d, mSamplingRate: %d",
802                 mNumChannels, mSamplingRate);
803
804             return OMX_ErrorNone;
805         }
806         case OMX_IndexParamAudioFlac:
807         {
808             OMX_AUDIO_PARAM_FLACTYPE *profile =
809                 (OMX_AUDIO_PARAM_FLACTYPE *)params;
810
811             if (profile->nPortIndex != 0) {
812                 return OMX_ErrorUndefined;
813             }
814
815             mNumChannels = profile->nChannels;
816             mSamplingRate = profile->nSampleRate;
817
818             // update src and target, only once!
819             adjustAudioParameter();
820
821             ALOGV("got OMX_IndexParamAudioFlac, mNumChannels: %d, mSamplingRate: %d",
822                 mNumChannels, mSamplingRate);
823
824             return OMX_ErrorNone;
825         }
826         case OMX_IndexParamAudioVorbis:
827         {
828             const OMX_AUDIO_PARAM_VORBISTYPE *profile =
829                 (const OMX_AUDIO_PARAM_VORBISTYPE *)params;
830
831             if (profile->nPortIndex != 0) {
832                 return OMX_ErrorUndefined;
833             }
834
835             ALOGD("got OMX_IndexParamAudioVorbis, "
836                     "mNumChannels=%lu, mSamplingRate=%lu, nBitRate=%lu, "
837                     "nMinBitRate=%lu, nMaxBitRate=%lu",
838                 profile->nChannels, profile->nSampleRate,
839                 profile->nBitRate, profile->nMinBitRate,
840                 profile->nMaxBitRate);
841
842             return OMX_ErrorNone;
843         }
844         default:
845             if ((OMX_FF_INDEXTYPE)index == OMX_IndexParamAudioFFmpeg)
846             {
847                 OMX_AUDIO_PARAM_FFMPEGTYPE *profile =
848                     (OMX_AUDIO_PARAM_FFMPEGTYPE *)params;
849
850                 if (profile->nPortIndex != 0) {
851                     return OMX_ErrorUndefined;
852                 }
853
854                 mNumChannels = profile->nChannels;
855                 mSamplingRate = profile->nSampleRate;
856                 mBitRate = profile->nBitRate;
857                 mSamplingFmt = (AVSampleFormat)profile->eSampleFormat;
858
859                 mCtx->codec_id = (enum AVCodecID)profile->eCodecId; 
860                 //mCtx->channels = profile->nChannels;
861                 //mCtx->bit_rate = profile->nBitRate;
862                 mCtx->bits_per_coded_sample = profile->nBitsPerSample;
863                 //mCtx->sample_rate = profile->nSampleRate;
864                 mCtx->block_align = mBlockAlign;
865                 //mCtx->sample_fmt = profile->eSampleFormat;
866
867                 // FIXME, need to cleanup
868                 adjustAudioParameter();
869
870                 ALOGD("got OMX_IndexParamAudioFFmpeg, "
871                     "eCodecId:%ld(%s), nChannels:%lu, nBitRate:%lu, "
872                     "nBitsPerSample:%lu, nSampleRate:%lu, "
873                     "nBlockAlign:%lu, eSampleFormat:%lu(%s)",
874                     profile->eCodecId, avcodec_get_name(mCtx->codec_id),
875                     profile->nChannels, profile->nBitRate,
876                     profile->nBitsPerSample, profile->nSampleRate,
877                     profile->nBlockAlign, profile->eSampleFormat,
878                     av_get_sample_fmt_name(mCtx->sample_fmt));
879
880                 return OMX_ErrorNone;
881             }
882
883             ALOGI("internalSetParameter, index: 0x%x", index);
884             return SimpleSoftOMXComponent::internalSetParameter(index, params);
885     }
886 }
887
888 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
889     int len = 0;
890     int err = 0;
891     size_t dataSize = 0;
892     int64_t decChannelLayout;
893     int32_t inputBufferUsedLength = 0;
894     BufferInfo *inInfo = NULL;
895     OMX_BUFFERHEADERTYPE *inHeader = NULL;
896
897     if (mSignalledError || mOutputPortSettingsChange != NONE) {
898         return;
899     }
900
901     List<BufferInfo *> &inQueue = getPortQueue(0);
902     List<BufferInfo *> &outQueue = getPortQueue(1);
903
904     while ((!inQueue.empty()  //there are input buffers to be emptied
905                 || mAudioBufferSize > 0 //there are left decoded frame
906                 || mReceivedEOS)  //need to fill eos outbuffer
907             && !outQueue.empty()) { //there are out buffers to be filled
908         if (!inQueue.empty()) {
909             inInfo = *inQueue.begin();
910             inHeader = inInfo->mHeader;
911         } else {
912             inInfo = NULL;
913             inHeader = NULL;
914         }
915
916         BufferInfo *outInfo = *outQueue.begin();
917         OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
918
919         if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
920                         CHECK(mInputBufferSize == 0);
921             ALOGD("ffmpeg audio decoder empty eos inbuf");
922             inQueue.erase(inQueue.begin());
923             inInfo->mOwnedByUs = false;
924             notifyEmptyBufferDone(inHeader);
925             mReceivedEOS = true;
926                         continue; //empty eos input buffer
927         }
928
929         // eos
930         if (mReceivedEOS && (mFlushComplete || !(mCtx->codec->capabilities & CODEC_CAP_DELAY))) {
931             ALOGD("ffmpeg audio decoder fill eos outbuf");
932             outHeader->nFilledLen = 0;
933             outHeader->nFlags = OMX_BUFFERFLAG_EOS;
934
935             outQueue.erase(outQueue.begin());
936             outInfo->mOwnedByUs = false;
937             notifyFillBufferDone(outHeader);
938             return;
939         }
940
941         // extradata
942         if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
943             ALOGI("got extradata, ignore: %d, size: %lu", mIgnoreExtradata, inHeader->nFilledLen);
944             hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
945
946             if (mIgnoreExtradata) {
947                 ALOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
948                 inInfo->mOwnedByUs = false;
949                 inQueue.erase(inQueue.begin());
950                 inInfo = NULL;
951                 notifyEmptyBufferDone(inHeader);
952                 inHeader = NULL;
953
954                 continue;
955             }
956
957             if (!mExtradataReady) {
958                 int orig_extradata_size = mCtx->extradata_size;
959                 mCtx->extradata_size += inHeader->nFilledLen;
960                 mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
961                         mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
962                 if (!mCtx->extradata) {
963                     ALOGE("ffmpeg audio decoder failed to alloc extradata memory.");
964                     notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
965                     mSignalledError = true;
966                     return;
967                 }
968
969                 memcpy(mCtx->extradata + orig_extradata_size,
970                         inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
971                 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
972
973                 inInfo->mOwnedByUs = false;
974                 inQueue.erase(inQueue.begin());
975                 inInfo = NULL;
976                 notifyEmptyBufferDone(inHeader);
977                 inHeader = NULL;
978
979                 continue;
980             }
981         }
982
983         // open codec
984         if (!mCodecOpened) {
985             if (!mExtradataReady && !mIgnoreExtradata) {
986                 ALOGI("extradata is ready, size: %d", mCtx->extradata_size);
987                 hexdump(mCtx->extradata, mCtx->extradata_size);
988                 mExtradataReady = true;
989             }
990
991             // find decoder
992             mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
993             if (!mCtx->codec) {
994                 ALOGE("ffmpeg audio decoder failed to find codec");
995                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
996                 mSignalledError = true;
997                 return;
998             }
999
1000             setAVCtxToDefault(mCtx, mCtx->codec);
1001
1002             ALOGI("begin to open ffmpeg audio decoder, mCtx sample_rate: %d, "
1003                     "channels: %d, channel_layout: %llu, sample_fmt: %s",
1004                 mCtx->sample_rate, mCtx->channels, mCtx->channel_layout,
1005                 av_get_sample_fmt_name(mCtx->sample_fmt));
1006
1007             ALOGI("open ffmpeg decoder now");
1008             err = avcodec_open2(mCtx, mCtx->codec, NULL);
1009             if (err < 0) {
1010                 ALOGE("ffmpeg audio decoder failed to initialize. (%d)", err);
1011                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
1012                 mSignalledError = true;
1013                 return;
1014             }
1015             mCodecOpened = true;
1016             ALOGI("open ffmpeg audio decoder success, mCtx sample_rate: %d, "
1017                     "channels: %d, channel_layout: %llu, sample_fmt: %s",
1018                 mCtx->sample_rate, mCtx->channels, mCtx->channel_layout,
1019                 av_get_sample_fmt_name(mCtx->sample_fmt));
1020         }
1021
1022         //update the audio clock with the pts
1023         if (inHeader && inHeader->nOffset == 0
1024                 && mInputBufferSize == 0  // the last input buffer have be emptied
1025                 && mAudioBufferSize == 0) { // the last decoded frame have be filled
1026             mAnchorTimeUs = inHeader->nTimeStamp;
1027             mInputBufferSize = inHeader->nFilledLen;
1028         }
1029
1030         if ((inHeader && mAudioBufferSize == 0) //hope to get more decoded frame while have not read eos pkt
1031                 || (mReceivedEOS && !mFlushComplete)) { //hope to get left decoded frame while have read eos pkt
1032             AVPacket pkt;
1033             memset(&pkt, 0, sizeof(pkt));
1034             av_init_packet(&pkt);
1035
1036             if (inHeader) {
1037                                 CHECK(mAudioBufferSize == 0);
1038                 pkt.data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
1039                 pkt.size = inHeader->nFilledLen;
1040                 pkt.pts = inHeader->nTimeStamp; // ingore it, we will compute it
1041             } else {
1042                                 CHECK(mReceivedEOS == true);
1043                                 CHECK(mFlushComplete == false);
1044                 pkt.data = NULL;
1045                 pkt.size = 0;
1046                 pkt.pts = AV_NOPTS_VALUE;
1047             }
1048 #if DEBUG_PKT
1049             ALOGV("pkt size: %d, pts: %lld", pkt.size, pkt.pts);
1050 #endif
1051             if (!mFrame) {
1052                 if (!(mFrame = avcodec_alloc_frame())) {
1053                     ALOGE("ffmpeg audio decoder failed to alloc memory.");
1054                     notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
1055                     mSignalledError = true;
1056                     return;
1057                 }
1058             } else {
1059                 avcodec_get_frame_defaults(mFrame);
1060             }
1061
1062             int gotFrm = false;
1063             inputBufferUsedLength = 0;
1064
1065             len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
1066
1067             // A negative error code is returned if an error occurred during decoding
1068             if (len < 0) {
1069                 ALOGE("ffmpeg audio decoder failed to decode frame. "
1070                         "consume pkt len: %d", len);
1071
1072                 /* if !mAudioConfigChanged, Don't fill the out buffer */
1073                 if (!mAudioConfigChanged) {
1074                     inInfo->mOwnedByUs = false;
1075                     inQueue.erase(inQueue.begin());
1076                     inInfo = NULL;
1077                     notifyEmptyBufferDone(inHeader);
1078                     inHeader = NULL;
1079
1080                     mInputBufferSize = 0; // need?
1081                     continue;
1082                 }
1083
1084                 //inputBufferUsedLength = inHeader->nFilledLen;
1085                 /* if error, we skip the frame and play silence instead */
1086                 mPAudioBuffer = mSilenceBuffer;
1087                 mAudioBufferSize = kOutputBufferSize; //FIXME, need to calculate the size
1088             }
1089
1090 #if DEBUG_PKT
1091             ALOGV("ffmpeg audio decoder, consume pkt len: %d", len);
1092 #endif
1093
1094                         if (inHeader) {
1095                                 CHECK(mFlushComplete == false);
1096
1097                 if (len < 0)
1098                     inputBufferUsedLength = mInputBufferSize;
1099                 else
1100                     inputBufferUsedLength = len;
1101
1102                 CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
1103                 inHeader->nOffset += inputBufferUsedLength;
1104                 inHeader->nFilledLen -= inputBufferUsedLength;
1105                 mInputBufferSize -= inputBufferUsedLength;
1106                 if (inHeader->nFilledLen == 0) {
1107                     inInfo->mOwnedByUs = false;
1108                     inQueue.erase(inQueue.begin());
1109                     inInfo = NULL;
1110                     notifyEmptyBufferDone(inHeader);
1111                     inHeader = NULL;
1112
1113                                         //reset mInputBufferSize
1114                     mInputBufferSize = 0;
1115                 }
1116                         }
1117
1118             if (!gotFrm) {
1119                 ALOGI("ffmpeg audio decoder failed to get more frame.");
1120                 /* stop sending empty packets if the decoder is finished */
1121                 if (!pkt.data && mCtx->codec->capabilities & CODEC_CAP_DELAY)
1122                     mFlushComplete = true;
1123                 continue;
1124             }
1125
1126             /**
1127              * FIXME, check mAudioConfigChanged when the first time you call the audio4!
1128              * mCtx->sample_rate and mCtx->channels may be changed by audio decoder later, why???
1129              */
1130             if (!mAudioConfigChanged) {
1131                 //if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate
1132                                 //    || mCtx->sample_fmt != mSamplingFmt) {
1133                 if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate) {
1134                     ALOGI("audio OMX_EventPortSettingsChanged, mCtx->channels: %d, "
1135                             "mNumChannels: %d, mCtx->sample_rate: %d, mSamplingRate: %d, "
1136                             "mCtx->sample_fmt: %s, mSamplingFmt: %s",
1137                              mCtx->channels, mNumChannels, mCtx->sample_rate, mSamplingRate,
1138                              av_get_sample_fmt_name(mCtx->sample_fmt),
1139                              av_get_sample_fmt_name(mSamplingFmt));
1140                     mNumChannels = mCtx->channels;
1141                     mSamplingRate = mCtx->sample_rate;
1142                     mSamplingFmt = mCtx->sample_fmt;
1143                     mAudioConfigChanged = true;
1144                     notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
1145                     mOutputPortSettingsChange = AWAITING_DISABLED;
1146                     return;
1147                 } else {
1148                     // match with the default, set mAudioConfigChanged true anyway!
1149                     mAudioConfigChanged = true;
1150                     mSamplingFmt = mCtx->sample_fmt;
1151                 }
1152             }
1153
1154             dataSize = av_samples_get_buffer_size(NULL, mNumChannels,
1155                            mFrame->nb_samples, mSamplingFmt, 1);
1156
1157 #if DEBUG_FRM
1158             ALOGV("audio decoder, nb_samples: %d, get buffer size: %d",
1159                     mFrame->nb_samples, dataSize);
1160             ALOGV("audio decoder: mCtx channel_layout: %llu, "
1161                     "channels: %d, channels_from_layout: %d",
1162                 mCtx->channel_layout,  mCtx->channels,
1163                 av_get_channel_layout_nb_channels(mCtx->channel_layout));
1164 #endif
1165
1166             decChannelLayout = av_get_default_channel_layout(mNumChannels);
1167             if (mSamplingFmt != mAudioSrcFmt
1168                     || decChannelLayout != mAudioSrcChannelLayout
1169                     || mSamplingRate != mAudioSrcFreq) {
1170                 if (mSwrCtx)
1171                     swr_free(&mSwrCtx);
1172                 mSwrCtx = swr_alloc_set_opts(NULL,
1173                         mAudioTgtChannelLayout, mAudioTgtFmt, mAudioTgtFreq,
1174                         decChannelLayout,       mSamplingFmt, mSamplingRate,
1175                         0, NULL);
1176                 if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
1177                     ALOGE("Cannot create sample rate converter for conversion "
1178                             "of %d Hz %s %d channels to %d Hz %s %d channels!",
1179                             mSamplingRate,
1180                             av_get_sample_fmt_name(mSamplingFmt),
1181                             mNumChannels,
1182                             mAudioTgtFreq,
1183                             av_get_sample_fmt_name(mAudioTgtFmt),
1184                             mAudioTgtChannels);
1185                     notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
1186                     mSignalledError = true;
1187                     return;
1188                 }
1189
1190                 ALOGI("Create sample rate converter for conversion "
1191                         "of %d Hz %s %d channels(%lld channel_layout) "
1192                         "to %d Hz %s %d channels(%lld channel_layout)!",
1193                         mSamplingRate,
1194                         av_get_sample_fmt_name(mSamplingFmt),
1195                         mNumChannels,
1196                         mAudioTgtChannelLayout,
1197                         mAudioTgtFreq,
1198                         av_get_sample_fmt_name(mAudioTgtFmt),
1199                         mAudioTgtChannels,
1200                         decChannelLayout);
1201
1202                 mAudioSrcChannelLayout = decChannelLayout;
1203                 mAudioSrcChannels = mNumChannels;
1204                 mAudioSrcFreq = mSamplingRate;
1205                 mAudioSrcFmt = mSamplingFmt;
1206             }
1207
1208             if (mSwrCtx) {
1209                 //const uint8_t *in[] = { mFrame->data[0] };
1210                 const uint8_t **in = (const uint8_t **)mFrame->extended_data;
1211                 uint8_t *out[] = {mAudioBuf2};
1212                 int out_count = sizeof(mAudioBuf2) / mAudioTgtChannels /
1213                     av_get_bytes_per_sample(mAudioTgtFmt);
1214 #if DEBUG_FRM
1215                 ALOGV("swr_convert 1, out_count: %d, mFrame->nb_samples: %d, "
1216                         "src frm: %s, tgt frm: %s",
1217                     out_count, mFrame->nb_samples,
1218                     av_get_sample_fmt_name(mCtx->sample_fmt),
1219                     av_get_sample_fmt_name(mAudioTgtFmt));
1220 #endif
1221                 int len2 = swr_convert(mSwrCtx, out, out_count, in, mFrame->nb_samples);
1222                 if (len2 < 0) {
1223                     ALOGE("audio_resample() failed");
1224                     break;
1225                 }
1226                 if (len2 == out_count) {
1227                     ALOGE("warning: audio buffer is probably too small");
1228                     swr_init(mSwrCtx);
1229                 }
1230                 mPAudioBuffer = mAudioBuf2;
1231                 mAudioBufferSize = len2 * mAudioTgtChannels *
1232                     av_get_bytes_per_sample(mAudioTgtFmt);
1233             } else {
1234                 mPAudioBuffer = mFrame->data[0];
1235                 mAudioBufferSize = dataSize;
1236             }
1237
1238 #if DEBUG_FRM
1239             ALOGV("ffmpeg audio decoder get frame. consume pkt len: %d, "
1240                     "nb_samples(before resample): %d, mAudioBufferSize: %d",
1241                     len, mFrame->nb_samples, mAudioBufferSize);
1242 #endif
1243         } //if ((inHeader && mAudioBufferSize == 0) || (mReceivedEOS && !mFlushComplete))
1244
1245         size_t copyToOutputBufferLen = mAudioBufferSize;
1246         if (mAudioBufferSize > kOutputBufferSize)
1247             copyToOutputBufferLen = kOutputBufferSize;
1248
1249         outHeader->nOffset = 0;
1250         outHeader->nFilledLen = copyToOutputBufferLen;
1251         outHeader->nTimeStamp = mAnchorTimeUs + 
1252             (mNumFramesOutput * 1000000ll) / mSamplingRate;
1253         memcpy(outHeader->pBuffer, mPAudioBuffer, copyToOutputBufferLen);
1254         outHeader->nFlags = 0;
1255
1256 #if DEBUG_FRM
1257         ALOGV("ffmpeg audio decoder, fill out buffer, "
1258                                 "pts: %lld, mNumFramesOutput: %lld",
1259                 outHeader->nTimeStamp, mNumFramesOutput);
1260 #endif
1261
1262         mPAudioBuffer += copyToOutputBufferLen;
1263         mAudioBufferSize -= copyToOutputBufferLen;
1264         mNumFramesOutput += copyToOutputBufferLen /
1265             (av_get_bytes_per_sample(mAudioTgtFmt) * mNumChannels);
1266
1267         // reset mNumFramesOutput
1268         if (mInputBufferSize == 0 && mAudioBufferSize == 0) {
1269 #if DEBUG_FRM
1270             ALOGV("~~~~ reset mNumFramesOutput to 0");
1271 #endif
1272             mNumFramesOutput = 0;
1273         }
1274
1275         outInfo->mOwnedByUs = false;
1276         outQueue.erase(outQueue.begin());
1277         outInfo = NULL;
1278         notifyFillBufferDone(outHeader);
1279         outHeader = NULL;
1280     }
1281 }
1282
1283 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
1284     ALOGV("ffmpeg audio decoder flush port(%lu)", portIndex);
1285     if (portIndex == 0 && mCtx) {
1286         // Make sure that the next buffer output does not still
1287         // depend on fragments from the last one decoded.
1288         avcodec_flush_buffers(mCtx);
1289     }
1290         mReceivedEOS = false;
1291         mFlushComplete = false;
1292         mAnchorTimeUs = 0;
1293         mInputBufferSize = 0;
1294         mNumFramesOutput = 0;
1295         mAudioBufferSize = 0;
1296         mPAudioBuffer = NULL;
1297         //don't free mFrame!
1298 }
1299
1300 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
1301     if (portIndex != 1) {
1302         return;
1303     }
1304
1305     switch (mOutputPortSettingsChange) {
1306         case NONE:
1307             break;
1308
1309         case AWAITING_DISABLED:
1310         {
1311             CHECK(!enabled);
1312             mOutputPortSettingsChange = AWAITING_ENABLED;
1313             break;
1314         }
1315
1316         default:
1317         {
1318             CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
1319             CHECK(enabled);
1320             mOutputPortSettingsChange = NONE;
1321             break;
1322         }
1323     }
1324 }
1325
1326 }  // namespace android
1327
1328 android::SoftOMXComponent *createSoftOMXComponent(
1329         const char *name, const OMX_CALLBACKTYPE *callbacks,
1330         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
1331     return new android::SoftFFmpegAudio(name, callbacks, appData, component);
1332 }