OSDN Git Service

17ec1f24ffa56f54a90649c0b884aa1e5eb5d5a2
[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       mInputBufferSize(0),
98       mResampledDataSize(0),
99       mAudioConfigChanged(false),
100       mOutputPortSettingsChange(NONE) {
101
102     setMode(name);
103
104     ALOGD("SoftFFmpegAudio component: %s mMode: %d", name, mMode);
105
106     initPorts();
107     CHECK_EQ(initDecoder(), (status_t)OK);
108 }
109
110 SoftFFmpegAudio::~SoftFFmpegAudio() {
111     ALOGV("~SoftFFmpegAudio");
112     av_freep(&mFrame);
113     mFrame = NULL;
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 = mCtx->channels;
462             profile->nSamplingRate = mCtx->sample_rate;
463
464             //NOTE: mCtx is the default(configDefaultCtx), or has
465             //been updated(adjustAudioParameter)!!!
466             ALOGV("get pcm params, nChannels:%lu, nSamplingRate:%lu",
467                    profile->nChannels, profile->nSamplingRate);
468
469             return OMX_ErrorNone;
470         }
471         case OMX_IndexParamAudioVorbis:
472         {
473             OMX_AUDIO_PARAM_VORBISTYPE *profile =
474                 (OMX_AUDIO_PARAM_VORBISTYPE *)params;
475
476             if (profile->nPortIndex != 0) {
477                 return OMX_ErrorUndefined;
478             }
479
480             profile->nBitRate = 0;
481             profile->nMinBitRate = 0;
482             profile->nMaxBitRate = 0;
483             profile->nAudioBandWidth = 0;
484             profile->nQuality = 3;
485             profile->bManaged = OMX_FALSE;
486             profile->bDownmix = OMX_FALSE;
487
488             profile->nChannels = 1;
489             profile->nSampleRate = 44100;
490 /*
491             if (!isConfigured()) {
492                 profile->nChannels = 1;
493                 profile->nSampleRate = 44100;
494             } else {
495                 profile->nChannels = mVi->channels;
496                 profile->nSampleRate = mVi->rate;
497                 profile->nBitRate = mVi->bitrate_nominal;
498                 profile->nMinBitRate = mVi->bitrate_lower;
499                 profile->nMaxBitRate = mVi->bitrate_upper;
500             }
501 */
502             return OMX_ErrorNone;
503         }
504
505         default:
506             if ((OMX_FF_INDEXTYPE)index == OMX_IndexParamAudioFFmpeg)
507             {
508                 OMX_AUDIO_PARAM_FFMPEGTYPE *profile =
509                     (OMX_AUDIO_PARAM_FFMPEGTYPE *)params;
510
511                 if (profile->nPortIndex != 0) {
512                     return OMX_ErrorUndefined;
513                 }
514
515                 profile->eCodecId = 0; 
516                 profile->nChannels = 0;
517                 profile->nBitRate = 0;
518                 profile->nBitsPerSample = 0;
519                 profile->nSampleRate = 0;
520                 profile->nBlockAlign = 0;
521                 profile->eSampleFormat = 0;
522
523                 return OMX_ErrorNone;
524             }
525
526             return SimpleSoftOMXComponent::internalGetParameter(index, params);
527     }
528 }
529
530 OMX_ERRORTYPE SoftFFmpegAudio::isRoleSupported(
531         const OMX_PARAM_COMPONENTROLETYPE *roleParams) {
532     bool supported = true;
533
534     switch (mMode) {
535     case MODE_MPEG:
536         if (strncmp((const char *)roleParams->cRole,
537                 "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
538             supported =  false;
539         break;
540     case MODE_MPEGL1:
541         if (strncmp((const char *)roleParams->cRole,
542                 "audio_decoder.mp1", OMX_MAX_STRINGNAME_SIZE - 1))
543             supported =  false;
544         break;
545     case MODE_MPEGL2:
546         if (strncmp((const char *)roleParams->cRole,
547                 "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
548             supported =  false;
549         break;
550     case MODE_AAC:
551         if (strncmp((const char *)roleParams->cRole,
552                 "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
553         supported =  false;
554         break;
555     case MODE_AC3:
556         if (strncmp((const char *)roleParams->cRole,
557                 "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
558             supported =  false;
559         break;
560     case MODE_WMA:
561         if (strncmp((const char *)roleParams->cRole,
562                 "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
563         supported =  false;
564         break;
565     case MODE_RA:
566         if (strncmp((const char *)roleParams->cRole,
567                 "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
568         supported =  false;
569         break;
570     case MODE_APE:
571         if (strncmp((const char *)roleParams->cRole,
572                 "audio_decoder.ape", OMX_MAX_STRINGNAME_SIZE - 1))
573         supported =  false;
574         break;
575     case MODE_DTS:
576         if (strncmp((const char *)roleParams->cRole,
577                 "audio_decoder.dts", OMX_MAX_STRINGNAME_SIZE - 1))
578         supported =  false;
579         break;
580     case MODE_FLAC:
581         if (strncmp((const char *)roleParams->cRole,
582                 "audio_decoder.flac", OMX_MAX_STRINGNAME_SIZE - 1))
583         supported =  false;
584         break;
585     case MODE_VORBIS:
586         if (strncmp((const char *)roleParams->cRole,
587                 "audio_decoder.vorbis", OMX_MAX_STRINGNAME_SIZE - 1))
588         supported =  false;
589         break;
590     case MODE_HEURISTIC:
591         if (strncmp((const char *)roleParams->cRole,
592                 "audio_decoder.heuristic", OMX_MAX_STRINGNAME_SIZE - 1))
593         supported =  false;
594         break;
595     default:
596         CHECK(!"Should not be here. Unsupported role.");
597         break;
598     }
599
600     if (!supported) {
601         ALOGE("unsupported role: %s", (const char *)roleParams->cRole);
602         return OMX_ErrorUndefined;
603     }
604
605     return OMX_ErrorNone;
606 }
607
608 void SoftFFmpegAudio::adjustAudioParameter() {
609     int32_t channels = 0;
610     int32_t sampling_rate = 0;
611
612     sampling_rate = mCtx->sample_rate;
613
614     //channels support 1 or 2 only
615     channels = mCtx->channels >= 2 ? 2 : 1;
616
617     //4000 <= sampling rate <= 48000
618     if (sampling_rate < 4000) {
619         sampling_rate = 4000;
620     } else if (sampling_rate > 48000) {
621         sampling_rate = 48000;
622     }
623
624     mAudioSrcChannels = mAudioTgtChannels = channels;
625     mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
626     mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
627     mAudioSrcChannelLayout = mAudioTgtChannelLayout =
628         av_get_default_channel_layout(channels);
629 }
630
631 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
632         OMX_INDEXTYPE index, const OMX_PTR params) {
633     switch (index) {
634         case OMX_IndexParamStandardComponentRole:
635         {
636             const OMX_PARAM_COMPONENTROLETYPE *roleParams =
637                 (const OMX_PARAM_COMPONENTROLETYPE *)params;
638                         return isRoleSupported(roleParams);
639         }
640         case OMX_IndexParamAudioPcm:
641         {
642             const OMX_AUDIO_PARAM_PCMMODETYPE *profile =
643                 (const OMX_AUDIO_PARAM_PCMMODETYPE *)params;
644
645             if (profile->nPortIndex != 1) {
646                 return OMX_ErrorUndefined;
647             }
648
649             mCtx->channels = profile->nChannels;
650             mCtx->sample_rate = profile->nSamplingRate;
651             mCtx->bits_per_coded_sample = profile->nBitPerSample;
652
653             ALOGV("set OMX_IndexParamAudioPcm, nChannels:%lu, "
654                     "nSampleRate:%lu, nBitsPerSample:%lu",
655                 profile->nChannels, profile->nSamplingRate,
656                 profile->nBitPerSample);
657
658             return OMX_ErrorNone;
659         }
660         case OMX_IndexParamAudioAac:
661         {
662             const OMX_AUDIO_PARAM_AACPROFILETYPE *profile =
663                 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
664
665             if (profile->nPortIndex != 0) {
666                 return OMX_ErrorUndefined;
667             }
668
669             mCtx->channels = profile->nChannels;
670             mCtx->sample_rate = profile->nSampleRate;
671
672             adjustAudioParameter();
673
674             ALOGV("set OMX_IndexParamAudioAac, nChannels:%lu, nSamplingRate:%lu",
675                 profile->nChannels, profile->nSampleRate);
676
677             return OMX_ErrorNone;
678         }
679         case OMX_IndexParamAudioWma:
680         {
681             OMX_AUDIO_PARAM_WMATYPE *profile =
682                 (OMX_AUDIO_PARAM_WMATYPE *)params;
683
684             if (profile->nPortIndex != 0) {
685                 return OMX_ErrorUndefined;
686             }
687
688             if (profile->eFormat == OMX_AUDIO_WMAFormat7) {
689                mCtx->codec_id = CODEC_ID_WMAV2;
690             } else if (profile->eFormat == OMX_AUDIO_WMAFormat8) {
691                mCtx->codec_id = CODEC_ID_WMAPRO;
692             } else if (profile->eFormat == OMX_AUDIO_WMAFormat9) {
693                mCtx->codec_id = CODEC_ID_WMALOSSLESS;
694             } else {
695                 ALOGE("unsupported wma codec: 0x%x", profile->eFormat);
696                 return OMX_ErrorUndefined;
697             }
698
699             mCtx->channels = profile->nChannels;
700             mCtx->sample_rate = profile->nSamplingRate;
701
702             // wmadec needs bitrate, block_align
703             mCtx->bit_rate = profile->nBitRate;
704             mCtx->block_align = profile->nBlockAlign;
705
706             adjustAudioParameter();
707
708             ALOGV("set OMX_IndexParamAudioWma, nChannels:%u, "
709                     "nSampleRate:%lu, nBitRate:%lu, nBlockAlign:%u",
710                 profile->nChannels, profile->nSamplingRate,
711                 profile->nBitRate, profile->nBlockAlign);
712
713             return OMX_ErrorNone;
714         }
715         case OMX_IndexParamAudioRa:
716         {
717             OMX_AUDIO_PARAM_RATYPE *profile =
718                 (OMX_AUDIO_PARAM_RATYPE *)params;
719
720             if (profile->nPortIndex != 0) {
721                 return OMX_ErrorUndefined;
722             }
723
724             mCtx->channels = profile->nChannels;
725             mCtx->sample_rate = profile->nSamplingRate;
726
727             // FIXME, HACK!!!, I use the nNumRegions parameter pass blockAlign!!!
728             // the cook audio codec need blockAlign!
729             mCtx->block_align = profile->nNumRegions;
730
731             adjustAudioParameter();
732
733             ALOGV("set OMX_IndexParamAudioRa, nChannels:%lu, "
734                     "nSampleRate:%lu, nBlockAlign:%d",
735                 profile->nChannels, profile->nSamplingRate, mCtx->block_align);
736
737             return OMX_ErrorNone;
738         }
739         case OMX_IndexParamAudioApe:
740         {
741             OMX_AUDIO_PARAM_APETYPE *profile =
742                 (OMX_AUDIO_PARAM_APETYPE *)params;
743
744             if (profile->nPortIndex != 0) {
745                 return OMX_ErrorUndefined;
746             }
747
748             mCtx->channels = profile->nChannels;
749             mCtx->sample_rate = profile->nSamplingRate;
750
751             // ape decoder need bits_per_coded_sample
752             mCtx->bits_per_coded_sample = profile->nBitsPerSample;
753
754             adjustAudioParameter();
755
756             ALOGV("set OMX_IndexParamAudioApe, nChannels:%lu, "
757                     "nSampleRate:%lu, nBitsPerSample:%lu",
758                 profile->nChannels, profile->nSamplingRate,
759                 profile->nBitsPerSample);
760
761             return OMX_ErrorNone;
762         }
763         case OMX_IndexParamAudioDts:
764         {
765             OMX_AUDIO_PARAM_DTSTYPE *profile =
766                 (OMX_AUDIO_PARAM_DTSTYPE *)params;
767
768             if (profile->nPortIndex != 0) {
769                 return OMX_ErrorUndefined;
770             }
771
772             mCtx->channels = profile->nChannels;
773             mCtx->sample_rate = profile->nSamplingRate;
774
775             adjustAudioParameter();
776
777             ALOGV("set OMX_IndexParamAudioDts, nChannels:%lu, nSamplingRate:%lu",
778                 profile->nChannels, profile->nSamplingRate);
779
780             return OMX_ErrorNone;
781         }
782         case OMX_IndexParamAudioFlac:
783         {
784             OMX_AUDIO_PARAM_FLACTYPE *profile =
785                 (OMX_AUDIO_PARAM_FLACTYPE *)params;
786
787             if (profile->nPortIndex != 0) {
788                 return OMX_ErrorUndefined;
789             }
790
791             mCtx->channels = profile->nChannels;
792             mCtx->sample_rate = profile->nSampleRate;
793
794             adjustAudioParameter();
795
796             ALOGV("set OMX_IndexParamAudioFlac, nChannels:%lu, nSamplingRate:%lu",
797                 profile->nChannels, profile->nSampleRate);
798
799             return OMX_ErrorNone;
800         }
801         case OMX_IndexParamAudioVorbis:
802         {
803             const OMX_AUDIO_PARAM_VORBISTYPE *profile =
804                 (const OMX_AUDIO_PARAM_VORBISTYPE *)params;
805
806             if (profile->nPortIndex != 0) {
807                 return OMX_ErrorUndefined;
808             }
809
810             mCtx->channels = profile->nChannels;
811             mCtx->sample_rate = profile->nSampleRate;
812
813             ALOGD("set OMX_IndexParamAudioVorbis, "
814                     "nChannels=%lu, nSampleRate=%lu, nBitRate=%lu, "
815                     "nMinBitRate=%lu, nMaxBitRate=%lu",
816                 profile->nChannels, profile->nSampleRate,
817                 profile->nBitRate, profile->nMinBitRate,
818                 profile->nMaxBitRate);
819
820             return OMX_ErrorNone;
821         }
822         default:
823             if ((OMX_FF_INDEXTYPE)index == OMX_IndexParamAudioFFmpeg)
824             {
825                 OMX_AUDIO_PARAM_FFMPEGTYPE *profile =
826                     (OMX_AUDIO_PARAM_FFMPEGTYPE *)params;
827
828                 if (profile->nPortIndex != 0) {
829                     return OMX_ErrorUndefined;
830                 }
831
832                 mCtx->codec_id = (enum AVCodecID)profile->eCodecId; 
833                 mCtx->channels = profile->nChannels;
834                 mCtx->bit_rate = profile->nBitRate;
835                 mCtx->bits_per_coded_sample = profile->nBitsPerSample;
836                 mCtx->sample_rate = profile->nSampleRate;
837                 mCtx->block_align = profile->nBlockAlign;
838                 mCtx->sample_fmt = (AVSampleFormat)profile->eSampleFormat;
839
840                 adjustAudioParameter();
841
842                 ALOGD("set OMX_IndexParamAudioFFmpeg, "
843                     "eCodecId:%ld(%s), nChannels:%lu, nBitRate:%lu, "
844                     "nBitsPerSample:%lu, nSampleRate:%lu, "
845                     "nBlockAlign:%lu, eSampleFormat:%lu(%s)",
846                     profile->eCodecId, avcodec_get_name(mCtx->codec_id),
847                     profile->nChannels, profile->nBitRate,
848                     profile->nBitsPerSample, profile->nSampleRate,
849                     profile->nBlockAlign, profile->eSampleFormat,
850                     av_get_sample_fmt_name(mCtx->sample_fmt));
851
852                 return OMX_ErrorNone;
853             }
854
855             ALOGI("internalSetParameter, index: 0x%x", index);
856             return SimpleSoftOMXComponent::internalSetParameter(index, params);
857     }
858 }
859
860 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
861     int len = 0;
862     int err = 0;
863     size_t dataSize = 0;
864     int64_t decChannelLayout = 0;
865     int32_t inputBufferUsedLength = 0;
866     BufferInfo *inInfo = NULL;
867     OMX_BUFFERHEADERTYPE *inHeader = NULL;
868
869     if (mSignalledError || mOutputPortSettingsChange != NONE) {
870         return;
871     }
872
873     List<BufferInfo *> &inQueue = getPortQueue(0);
874     List<BufferInfo *> &outQueue = getPortQueue(1);
875
876     while ((!inQueue.empty()  //there are input buffers to be emptied
877                 || mResampledDataSize > 0 //there are left decoded frame
878                 || mReceivedEOS)  //need to fill eos outbuffer
879             && !outQueue.empty()) { //there are out buffers to be filled
880         if (!inQueue.empty()) {
881             inInfo = *inQueue.begin();
882             inHeader = inInfo->mHeader;
883         } else {
884             inInfo = NULL;
885             inHeader = NULL;
886         }
887
888         BufferInfo *outInfo = *outQueue.begin();
889         OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
890
891         //empty eos
892         if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
893                         CHECK(mInputBufferSize == 0);
894             ALOGD("ffmpeg audio decoder empty eos inbuf");
895             inQueue.erase(inQueue.begin());
896             inInfo->mOwnedByUs = false;
897             notifyEmptyBufferDone(inHeader);
898             mReceivedEOS = true;
899                         continue; //empty eos input buffer
900         }
901
902         //fill eos
903         if (mReceivedEOS && (mFlushComplete || !(mCtx->codec->capabilities & CODEC_CAP_DELAY))) {
904             ALOGD("ffmpeg audio decoder fill eos outbuf");
905             outHeader->nFilledLen = 0;
906             outHeader->nFlags = OMX_BUFFERFLAG_EOS;
907
908             outQueue.erase(outQueue.begin());
909             outInfo->mOwnedByUs = false;
910             notifyFillBufferDone(outHeader);
911             return;
912         }
913
914         //prepare extradata
915         if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
916             ALOGI("got extradata, ignore: %d, size: %lu", mIgnoreExtradata, inHeader->nFilledLen);
917             hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
918
919             if (mIgnoreExtradata) {
920                 ALOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
921                 inInfo->mOwnedByUs = false;
922                 inQueue.erase(inQueue.begin());
923                 inInfo = NULL;
924                 notifyEmptyBufferDone(inHeader);
925                 inHeader = NULL;
926
927                 continue;
928             }
929
930             if (!mExtradataReady) {
931                 int orig_extradata_size = mCtx->extradata_size;
932                 mCtx->extradata_size += inHeader->nFilledLen;
933                 mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
934                         mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
935                 if (!mCtx->extradata) {
936                     ALOGE("ffmpeg audio decoder failed to alloc extradata memory.");
937                     notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
938                     mSignalledError = true;
939                     return;
940                 }
941
942                 memcpy(mCtx->extradata + orig_extradata_size,
943                         inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
944                 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
945
946                 inInfo->mOwnedByUs = false;
947                 inQueue.erase(inQueue.begin());
948                 inInfo = NULL;
949                 notifyEmptyBufferDone(inHeader);
950                 inHeader = NULL;
951
952                 continue;
953             }
954         }
955
956         //open codec
957         if (!mCodecAlreadyOpened) {
958             if (!mExtradataReady && !mIgnoreExtradata) {
959                 ALOGI("extradata is ready, size: %d", mCtx->extradata_size);
960                 hexdump(mCtx->extradata, mCtx->extradata_size);
961                 mExtradataReady = true;
962             }
963
964             // find decoder
965             mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
966             if (!mCtx->codec) {
967                 ALOGE("ffmpeg audio decoder failed to find codec");
968                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
969                 mSignalledError = true;
970                 return;
971             }
972
973             setAVCtxToDefault(mCtx, mCtx->codec);
974
975             ALOGD("begin to open ffmpeg audio decoder, mCtx sample_rate: %d, "
976                     "channels: %d, , sample_fmt: %s",
977                 mCtx->sample_rate, mCtx->channels,
978                 av_get_sample_fmt_name(mCtx->sample_fmt));
979
980             err = avcodec_open2(mCtx, mCtx->codec, NULL);
981             if (err < 0) {
982                 ALOGE("ffmpeg audio decoder failed to initialize. (%d)", err);
983                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
984                 mSignalledError = true;
985                 return;
986             }
987
988             mCodecAlreadyOpened = true;
989
990             ALOGD("open ffmpeg audio decoder success, mCtx sample_rate: %d, "
991                     "channels: %d, sample_fmt: %s",
992                 mCtx->sample_rate, mCtx->channels,
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                 && mResampledDataSize == 0) { // the last decoded frame have be filled
1000             if (inHeader->nTimeStamp != SF_NOPTS_VALUE) {
1001                 mAudioClock = inHeader->nTimeStamp; //if no pts in input buffer
1002                         } else {
1003                 //reset to AV_NOPTS_VALUE
1004                 inHeader->nTimeStamp = AV_NOPTS_VALUE;
1005             }
1006             mInputBufferSize = inHeader->nFilledLen;
1007         }
1008
1009         if ((inHeader && mResampledDataSize == 0) //hope to get more decoded frame while have not read eos pkt
1010                 || (mReceivedEOS && !mFlushComplete)) { //hope to get left decoded frame while have read eos pkt
1011             AVPacket pkt;
1012             memset(&pkt, 0, sizeof(pkt));
1013             av_init_packet(&pkt);
1014
1015             if (inHeader) {
1016                                 CHECK(mResampledDataSize == 0);
1017                 pkt.data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
1018                 pkt.size = inHeader->nFilledLen;
1019                 pkt.pts = inHeader->nTimeStamp; // ingore it, we will compute it
1020             } else {
1021                                 CHECK(mReceivedEOS == true);
1022                                 CHECK(mFlushComplete == false);
1023                 pkt.data = NULL;
1024                 pkt.size = 0;
1025                 pkt.pts = AV_NOPTS_VALUE;
1026             }
1027 #if DEBUG_PKT
1028             if (pkt.pts != AV_NOPTS_VALUE)
1029             {
1030                 ALOGV("pkt size:%d, pts:%lld", pkt.size, pkt.pts);
1031             } else {
1032                 ALOGV("pkt size:%d, pts:N/A", pkt.size);
1033             }
1034 #endif
1035             if (!mFrame) {
1036                 if (!(mFrame = avcodec_alloc_frame())) {
1037                     ALOGE("ffmpeg audio decoder failed to alloc memory.");
1038                     notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
1039                     mSignalledError = true;
1040                     return;
1041                 }
1042             } else {
1043                 avcodec_get_frame_defaults(mFrame);
1044             }
1045
1046             int gotFrm = false;
1047             inputBufferUsedLength = 0;
1048
1049             //decode audio packet
1050             len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
1051
1052             // A negative error code is returned if an error occurred during decoding
1053             if (len < 0) {
1054                 ALOGE("ffmpeg audio decoder failed to decode frame. "
1055                         "consume pkt len: %d", len);
1056
1057                 /* if !mAudioConfigChanged, Don't fill the out buffer */
1058                 if (!mAudioConfigChanged) {
1059                     inInfo->mOwnedByUs = false;
1060                     inQueue.erase(inQueue.begin());
1061                     inInfo = NULL;
1062                     notifyEmptyBufferDone(inHeader);
1063                     inHeader = NULL;
1064
1065                     mInputBufferSize = 0; // need?
1066                     continue;
1067                 }
1068
1069                 //inputBufferUsedLength = inHeader->nFilledLen;
1070                 /* if error, we skip the frame and play silence instead */
1071                 mResampledData = mSilenceBuffer;
1072                 mResampledDataSize = kOutputBufferSize; //FIXME, need to calculate the size
1073             }
1074
1075 #if DEBUG_PKT
1076             ALOGV("ffmpeg audio decoder, consume pkt len: %d", len);
1077 #endif
1078
1079                         if (inHeader) {
1080                                 CHECK(mFlushComplete == false);
1081
1082                 if (len < 0) {
1083                     inputBufferUsedLength = mInputBufferSize;
1084                  } else {
1085                     inputBufferUsedLength = len;
1086                  }
1087
1088                 CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
1089                 inHeader->nOffset += inputBufferUsedLength;
1090                 inHeader->nFilledLen -= inputBufferUsedLength;
1091                 mInputBufferSize -= inputBufferUsedLength;
1092                 if (inHeader->nFilledLen == 0) {
1093                     inInfo->mOwnedByUs = false;
1094                     inQueue.erase(inQueue.begin());
1095                     inInfo = NULL;
1096                     notifyEmptyBufferDone(inHeader);
1097                     inHeader = NULL;
1098
1099                                         //reset mInputBufferSize
1100                     mInputBufferSize = 0;
1101                 }
1102                         }
1103
1104             if (!gotFrm) {
1105                 ALOGI("ffmpeg audio decoder failed to get more frame.");
1106                 /* stop sending empty packets if the decoder is finished */
1107                 if (!pkt.data && mCtx->codec->capabilities & CODEC_CAP_DELAY)
1108                     mFlushComplete = true;
1109                 continue;
1110             }
1111
1112 #if 0 //TODO
1113             /**
1114              * FIXME, check mAudioConfigChanged when the first time you call the audio4!
1115              * mCtx->sample_rate and mCtx->channels may be changed by audio decoder later, why???
1116              */
1117             if (!mAudioConfigChanged) {
1118                 //if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate
1119                                 //    || mCtx->sample_fmt != mSamplingFmt) {
1120                 if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate) {
1121                     ALOGI("audio OMX_EventPortSettingsChanged, mCtx->channels: %d, "
1122                             "mNumChannels: %d, mCtx->sample_rate: %d, mSamplingRate: %d, "
1123                             "mCtx->sample_fmt: %s, mSamplingFmt: %s",
1124                              mCtx->channels, mNumChannels, mCtx->sample_rate, mSamplingRate,
1125                              av_get_sample_fmt_name(mCtx->sample_fmt),
1126                              av_get_sample_fmt_name(mSamplingFmt));
1127                     mNumChannels = mCtx->channels;
1128                     mSamplingRate = mCtx->sample_rate;
1129                     mSamplingFmt = mCtx->sample_fmt;
1130                     mAudioConfigChanged = true;
1131                     notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
1132                     mOutputPortSettingsChange = AWAITING_DISABLED;
1133                     return;
1134                 } else {
1135                     // match with the default, set mAudioConfigChanged true anyway!
1136                     mAudioConfigChanged = true;
1137                     mSamplingFmt = mCtx->sample_fmt;
1138                 }
1139                         }
1140 #endif
1141
1142             dataSize = av_samples_get_buffer_size(NULL, av_frame_get_channels(mFrame),
1143                            mFrame->nb_samples, (enum AVSampleFormat)mFrame->format, 1);
1144
1145 #if DEBUG_FRM
1146             ALOGV("ffmpeg audio decoder, nb_samples:%d, get buffer size:%d",
1147                     mFrame->nb_samples, dataSize);
1148 #endif
1149
1150             decChannelLayout =
1151                 (mFrame->channel_layout && av_frame_get_channels(mFrame) == av_get_channel_layout_nb_channels(mFrame->channel_layout)) ?
1152                 mFrame->channel_layout : av_get_default_channel_layout(av_frame_get_channels(mFrame));
1153
1154             if (mFrame->format != mAudioSrcFmt
1155                     || decChannelLayout != mAudioSrcChannelLayout
1156                     || mFrame->sample_rate != mAudioSrcFreq) {
1157                 if (mSwrCtx)
1158                     swr_free(&mSwrCtx);
1159                 mSwrCtx = swr_alloc_set_opts(NULL,
1160                         mAudioTgtChannelLayout, mAudioTgtFmt,                        mAudioTgtFreq,
1161                         decChannelLayout,       (enum AVSampleFormat)mFrame->format, mFrame->sample_rate,
1162                         0, NULL);
1163                 if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
1164                     ALOGE("Cannot create sample rate converter for conversion "
1165                             "of %d Hz %s %d channels to %d Hz %s %d channels!",
1166                             mFrame->sample_rate,
1167                             av_get_sample_fmt_name((enum AVSampleFormat)mFrame->format),
1168                             av_frame_get_channels(mFrame),
1169                             mAudioTgtFreq,
1170                             av_get_sample_fmt_name(mAudioTgtFmt),
1171                             mAudioTgtChannels);
1172                     notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
1173                     mSignalledError = true;
1174                     return;
1175                 }
1176
1177                                 char src_layout_name[1024] = {0};
1178                                 char tgt_layout_name[1024] = {0};
1179                 av_get_channel_layout_string(src_layout_name, sizeof(src_layout_name),
1180                         mCtx->channels, decChannelLayout);
1181                 av_get_channel_layout_string(tgt_layout_name, sizeof(tgt_layout_name),
1182                         mAudioTgtChannels, mAudioTgtChannelLayout);
1183                 ALOGI("Create sample rate converter for conversion "
1184                         "of %d Hz %s %d channels(%s) "
1185                         "to %d Hz %s %d channels(%s)!",
1186                         mFrame->sample_rate,
1187                         av_get_sample_fmt_name((enum AVSampleFormat)mFrame->format),
1188                         av_frame_get_channels(mFrame),
1189                         src_layout_name,
1190                         mAudioTgtFreq,
1191                         av_get_sample_fmt_name(mAudioTgtFmt),
1192                         mAudioTgtChannels,
1193                         tgt_layout_name);
1194
1195                 mAudioSrcChannelLayout = decChannelLayout;
1196                 mAudioSrcChannels = av_frame_get_channels(mFrame);
1197                 mAudioSrcFreq = mFrame->sample_rate;
1198                 mAudioSrcFmt = (enum AVSampleFormat)mFrame->format;
1199             }
1200
1201             if (mSwrCtx) {
1202                 const uint8_t **in = (const uint8_t **)mFrame->extended_data;
1203                 uint8_t *out[] = {mAudioBuffer};
1204                 int out_count = sizeof(mAudioBuffer) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt);
1205                 int out_size  = av_samples_get_buffer_size(NULL, mAudioTgtChannels, out_count, mAudioTgtFmt, 0);
1206                 int len2 = 0;
1207                 if (out_size < 0) {
1208                     ALOGE("av_samples_get_buffer_size() failed");
1209                     break; //TODO
1210                 }
1211 #if DEBUG_FRM
1212                 ALOGV("swr_convert 1, out_count:%d, mFrame->nb_samples:%d, "
1213                         "src channel:%u, src fmt:%s, tgt channel:%u, tgt fmt:%s",
1214                     out_count, mFrame->nb_samples,
1215                     av_frame_get_channels(mFrame),
1216                     av_get_sample_fmt_name((enum AVSampleFormat)mFrame->format),
1217                     mAudioTgtChannels,
1218                     av_get_sample_fmt_name(mAudioTgtFmt));
1219 #endif
1220
1221                 len2 = swr_convert(mSwrCtx, out, out_count, in, mFrame->nb_samples);
1222                 if (len2 < 0) {
1223                     ALOGE("audio_resample() failed");
1224                     break;
1225                 }
1226                 if (len2 == out_count) {
1227                     ALOGE("warning: audio buffer is probably too small");
1228                     swr_init(mSwrCtx);
1229                 }
1230                 mResampledData = mAudioBuffer;
1231                 mResampledDataSize = len2 * mAudioTgtChannels *
1232                     av_get_bytes_per_sample(mAudioTgtFmt);
1233 #if DEBUG_FRM
1234                 ALOGV("swr_convert 2, len2:%d, mResampledDataSize:%d",
1235                     len2, mResampledDataSize);
1236 #endif
1237             } else {
1238                 mResampledData = mFrame->data[0];
1239                 mResampledDataSize = dataSize;
1240             }
1241
1242 #if DEBUG_FRM
1243             ALOGV("ffmpeg audio decoder get frame. consume pkt len:%d, "
1244                     "nb_samples(before resample):%d, mResampledDataSize:%d",
1245                     len, mFrame->nb_samples, mResampledDataSize);
1246 #endif
1247         } //if ((inHeader && mResampledDataSize == 0) || (mReceivedEOS && !mFlushComplete))
1248
1249         size_t copyToOutputBufferLen = mResampledDataSize;
1250         if (mResampledDataSize > kOutputBufferSize)
1251             copyToOutputBufferLen = kOutputBufferSize;
1252
1253         outHeader->nOffset = 0;
1254         outHeader->nFilledLen = copyToOutputBufferLen;
1255         outHeader->nTimeStamp = mAudioClock; 
1256         memcpy(outHeader->pBuffer, mResampledData, copyToOutputBufferLen);
1257         outHeader->nFlags = 0;
1258
1259 #if DEBUG_FRM
1260         ALOGV("ffmpeg audio decoder, fill out buffer, "
1261                                 "pts: %lld", outHeader->nTimeStamp);
1262 #endif
1263
1264         mResampledData += copyToOutputBufferLen;
1265         mResampledDataSize -= copyToOutputBufferLen;
1266         size_t numFramesOutput = copyToOutputBufferLen /
1267             (av_get_bytes_per_sample(mAudioTgtFmt) * mAudioTgtChannels);
1268
1269
1270 #if DEBUG_FRM
1271         ALOGV("ffmpeg audio decoder, copyToOutputBufferLen:%d, "
1272                 "mAudioTgtChannels:%d, mAudioTgtFreq:%d, bytes_per_sample:%d",
1273                 copyToOutputBufferLen, mAudioTgtChannels,
1274                 mAudioTgtFreq, av_get_bytes_per_sample(mAudioTgtFmt));
1275 #endif
1276
1277         //update audio pts
1278         mAudioClock += (numFramesOutput * 1000000ll) / mAudioTgtFreq;
1279
1280         outInfo->mOwnedByUs = false;
1281         outQueue.erase(outQueue.begin());
1282         outInfo = NULL;
1283         notifyFillBufferDone(outHeader);
1284         outHeader = NULL;
1285     }
1286 }
1287
1288 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
1289     ALOGV("ffmpeg audio decoder flush port(%lu)", portIndex);
1290     if (portIndex == 0 && mCtx) {
1291         // Make sure that the next buffer output does not still
1292         // depend on fragments from the last one decoded.
1293         avcodec_flush_buffers(mCtx);
1294     }
1295         mReceivedEOS = false;
1296         mFlushComplete = false;
1297         mAudioClock = 0;
1298         mInputBufferSize = 0;
1299         mResampledDataSize = 0;
1300         mResampledData = NULL;
1301         //don't free mFrame!
1302 }
1303
1304 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
1305     if (portIndex != 1) {
1306         return;
1307     }
1308
1309     switch (mOutputPortSettingsChange) {
1310         case NONE:
1311             break;
1312
1313         case AWAITING_DISABLED:
1314         {
1315             CHECK(!enabled);
1316             mOutputPortSettingsChange = AWAITING_ENABLED;
1317             break;
1318         }
1319
1320         default:
1321         {
1322             CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
1323             CHECK(enabled);
1324             mOutputPortSettingsChange = NONE;
1325             break;
1326         }
1327     }
1328 }
1329
1330 }  // namespace android
1331
1332 android::SoftOMXComponent *createSoftOMXComponent(
1333         const char *name, const OMX_CALLBACKTYPE *callbacks,
1334         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
1335     return new android::SoftFFmpegAudio(name, callbacks, appData, component);
1336 }