OSDN Git Service

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