OSDN Git Service

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