OSDN Git Service

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