OSDN Git Service

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