OSDN Git Service

ba1487ce319b8219486872cbae83d3d7e234f24e
[android-x86/external-stagefright-plugins.git] / libstagefright / codecs / ffmpegdec / adec / SoftFFmpegAudio.cpp
1 /*
2  * Copyright 2012 Michael Chen <omxcodec@gmail.com>
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #define LOG_NDEBUG 0
18 #define LOG_TAG "SoftFFmpegAudio"
19 #include <utils/Log.h>
20
21 #include "SoftFFmpegAudio.h"
22
23 #include <media/stagefright/foundation/ADebug.h>
24 #include <media/stagefright/foundation/hexdump.h>
25 #include <media/stagefright/MediaDefs.h>
26
27 #include "utils/ffmpeg_utils.h"
28
29 #define DEBUG_PKT 0
30 #define DEBUG_FRM 0
31
32 namespace android {
33
34 template<class T>
35 static void InitOMXParams(T *params) {
36     params->nSize = sizeof(T);
37     params->nVersion.s.nVersionMajor = 1;
38     params->nVersion.s.nVersionMinor = 0;
39     params->nVersion.s.nRevision = 0;
40     params->nVersion.s.nStep = 0;
41 }
42
43 void SoftFFmpegAudio::setMode(const char *name) {
44     if (!strcmp(name, "OMX.ffmpeg.aac.decoder")) {
45         mMode = MODE_AAC;
46         } else if (!strcmp(name, "OMX.ffmpeg.mp3.decoder")) {
47         mMode = MODE_MPEG;
48         mIgnoreExtradata = true;
49     } else if (!strcmp(name, "OMX.ffmpeg.vorbis.decoder")) {
50         mMode = MODE_VORBIS;
51     } else if (!strcmp(name, "OMX.ffmpeg.wma.decoder")) {
52         mMode = MODE_WMA;
53     } else if (!strcmp(name, "OMX.ffmpeg.ra.decoder")) {
54         mMode = MODE_RA;
55     } else if (!strcmp(name, "OMX.ffmpeg.flac.decoder")) {
56         mMode = MODE_FLAC;
57     } else if (!strcmp(name, "OMX.ffmpeg.mp2.decoder")) {
58         mMode = MODE_MPEGL2;
59     } else if (!strcmp(name, "OMX.ffmpeg.ac3.decoder")) {
60         mMode = MODE_AC3;
61     } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
62         mMode = MODE_APE;
63     } else if (!strcmp(name, "OMX.ffmpeg.dts.decoder")) {
64         mMode = MODE_DTS;
65     } else if (!strcmp(name, "OMX.ffmpeg.atrial.decoder")) {
66         mMode = MODE_TRIAL;
67     } else {
68         TRESPASS();
69     }
70 }
71
72 SoftFFmpegAudio::SoftFFmpegAudio(
73         const char *name,
74         const OMX_CALLBACKTYPE *callbacks,
75         OMX_PTR appData,
76         OMX_COMPONENTTYPE **component)
77     : SimpleSoftOMXComponent(name, callbacks, appData, component),
78       mMode(MODE_NONE),
79       mFFmpegAlreadyInited(false),
80       mCodecAlreadyOpened(false),
81       mExtradataReady(false),
82       mIgnoreExtradata(false),
83       mCtx(NULL),
84       mSwrCtx(NULL),
85       mFrame(NULL),
86       mEOSStatus(INPUT_DATA_AVAILABLE),
87       mSignalledError(false),
88       mAudioClock(0),
89       mInputBufferSize(0),
90       mResampledData(NULL),
91       mResampledDataSize(0),
92       mOutputPortSettingsChange(NONE) {
93
94     setMode(name);
95
96     ALOGD("SoftFFmpegAudio component: %s mMode: %d", name, mMode);
97
98     initPorts();
99     CHECK_EQ(initDecoder(), (status_t)OK);
100 }
101
102 SoftFFmpegAudio::~SoftFFmpegAudio() {
103     ALOGV("~SoftFFmpegAudio");
104     deInitDecoder();
105     if (mFFmpegAlreadyInited) {
106         deInitFFmpeg();
107     }
108 }
109
110 void SoftFFmpegAudio::initInputFormat(uint32_t mode,
111         OMX_PARAM_PORTDEFINITIONTYPE &def) {
112     switch (mode) {
113     case MODE_AAC:
114         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AAC);
115         def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
116         break;
117     case MODE_MPEG:
118         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
119         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
120         break;
121     case MODE_VORBIS:
122         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_VORBIS);
123         def.format.audio.eEncoding = OMX_AUDIO_CodingVORBIS;
124         break;
125     case MODE_WMA:
126         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_WMA);
127         def.format.audio.eEncoding = OMX_AUDIO_CodingWMA;
128         break;
129     case MODE_RA:
130         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_RA);
131         def.format.audio.eEncoding = OMX_AUDIO_CodingRA;
132         break;
133     case MODE_FLAC:
134         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_FLAC);
135         def.format.audio.eEncoding = OMX_AUDIO_CodingFLAC;
136         break;
137     case MODE_MPEGL2:
138         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
139         def.format.audio.eEncoding = OMX_AUDIO_CodingMP2;
140         break;
141     case MODE_AC3:
142         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AC3);
143         def.format.audio.eEncoding = OMX_AUDIO_CodingAC3;
144         break;
145     case MODE_APE:
146         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_APE);
147         def.format.audio.eEncoding = OMX_AUDIO_CodingAPE;
148         break;
149     case MODE_DTS:
150         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_DTS);
151         def.format.audio.eEncoding = OMX_AUDIO_CodingDTS;
152         break;
153     case MODE_TRIAL:
154         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_FFMPEG);
155         def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect;
156         break;
157     default:
158         CHECK(!"Should not be here. Unsupported mime type and compression format");
159         break;
160     }
161
162     def.format.audio.pNativeRender = NULL;
163     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
164 }
165
166 void SoftFFmpegAudio::initPorts() {
167     OMX_PARAM_PORTDEFINITIONTYPE def;
168     InitOMXParams(&def);
169
170     def.nPortIndex = 0;
171     def.eDir = OMX_DirInput;
172     def.nBufferCountMin = kNumInputBuffers;
173     def.nBufferCountActual = def.nBufferCountMin;
174     if (mMode == MODE_APE) {
175         def.nBufferSize = 1000000; // ape!
176     } else if (mMode == MODE_DTS) {
177         def.nBufferSize = 1000000; // dts!
178     } else {
179         def.nBufferSize = 20480; // 8192 is too small
180     }
181     def.bEnabled = OMX_TRUE;
182     def.bPopulated = OMX_FALSE;
183     def.eDomain = OMX_PortDomainAudio;
184     def.bBuffersContiguous = OMX_FALSE;
185     def.nBufferAlignment = 1;
186
187     initInputFormat(mMode, def);
188
189     addPort(def);
190
191     def.nPortIndex = 1;
192     def.eDir = OMX_DirOutput;
193     def.nBufferCountMin = kNumOutputBuffers;
194     def.nBufferCountActual = def.nBufferCountMin;
195     def.nBufferSize = kOutputBufferSize;
196     def.bEnabled = OMX_TRUE;
197     def.bPopulated = OMX_FALSE;
198     def.eDomain = OMX_PortDomainAudio;
199     def.bBuffersContiguous = OMX_FALSE;
200     def.nBufferAlignment = 2;
201
202     def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
203     def.format.audio.pNativeRender = NULL;
204     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
205     def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
206
207     addPort(def);
208 }
209
210 void SoftFFmpegAudio::setDefaultCtx(AVCodecContext *avctx, const AVCodec *codec) {
211     int fast = 0;
212
213     avctx->workaround_bugs   = 1;
214     avctx->lowres            = 0;
215     if(avctx->lowres > codec->max_lowres){
216         ALOGW("The maximum value for lowres supported by the decoder is %d",
217                 codec->max_lowres);
218         avctx->lowres= codec->max_lowres;
219     }
220     avctx->idct_algo         = 0;
221     avctx->skip_frame        = AVDISCARD_DEFAULT;
222     avctx->skip_idct         = AVDISCARD_DEFAULT;
223     avctx->skip_loop_filter  = AVDISCARD_DEFAULT;
224     avctx->error_concealment = 3;
225
226     if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
227     if (fast)   avctx->flags2 |= CODEC_FLAG2_FAST;
228     if(codec->capabilities & CODEC_CAP_DR1)
229         avctx->flags |= CODEC_FLAG_EMU_EDGE;
230 }
231
232 bool SoftFFmpegAudio::isConfigured() {
233         return mAudioSrcChannels != -1;
234 }
235
236 void SoftFFmpegAudio::resetCtx() {
237     mCtx->channels = -1;
238     mCtx->sample_rate = -1;
239     mCtx->bit_rate = -1;
240     mCtx->sample_fmt = AV_SAMPLE_FMT_NONE;
241
242     mAudioSrcChannels = mAudioTgtChannels = -1;
243     mAudioSrcFreq = mAudioTgtFreq = -1;
244     mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_NONE;
245     mAudioSrcChannelLayout = mAudioTgtChannelLayout = 0;
246 }
247
248 void SoftFFmpegAudio::initVorbisHdr() {
249     int32_t i = 0;
250     for (i = 0; i < 3; i++) {
251         mVorbisHeaderStart[i] = NULL;
252         mVorbisHeaderLen[i] = 0;
253     }
254 }
255
256 void SoftFFmpegAudio::deinitVorbisHdr() {
257     int32_t i = 0;
258     for (i = 0; i < 3; i++) {
259         if (mVorbisHeaderLen[i] > 0) {
260             av_free(mVorbisHeaderStart[i]);
261             mVorbisHeaderStart[i] = NULL;
262             mVorbisHeaderLen[i] = 0;
263         }
264     }
265 }
266
267 status_t SoftFFmpegAudio::initDecoder() {
268     status_t status;
269
270     status = initFFmpeg();
271     if (status != OK) {
272         return NO_INIT;
273     }
274     mFFmpegAlreadyInited = true;
275
276     mCtx = avcodec_alloc_context3(NULL);
277     if (!mCtx) {
278         ALOGE("avcodec_alloc_context failed.");
279         return NO_MEMORY;
280     }
281
282     mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
283     switch (mMode) {
284     case MODE_AAC:
285         mCtx->codec_id = AV_CODEC_ID_AAC;
286         break;
287     case MODE_MPEG:
288         mCtx->codec_id = AV_CODEC_ID_MP3;
289         break;
290     case MODE_VORBIS:
291         mCtx->codec_id = AV_CODEC_ID_VORBIS;
292         break;
293     case MODE_WMA:
294         mCtx->codec_id = AV_CODEC_ID_WMAV2; //should be adjusted later
295         break;
296     case MODE_RA:
297         mCtx->codec_id = AV_CODEC_ID_COOK;
298         break;
299     case MODE_FLAC:
300         mCtx->codec_id = AV_CODEC_ID_FLAC;
301         break;
302     case MODE_MPEGL2:
303         mCtx->codec_id = AV_CODEC_ID_MP2;
304         break;
305     case MODE_AC3:
306         mCtx->codec_id = AV_CODEC_ID_AC3;
307         break;
308     case MODE_APE:
309         mCtx->codec_id = AV_CODEC_ID_APE;
310         break;
311     case MODE_DTS:
312         mCtx->codec_id = AV_CODEC_ID_DTS;
313         break;
314     case MODE_TRIAL:
315         mCtx->codec_id = AV_CODEC_ID_NONE;
316         break;
317     default:
318         CHECK(!"Should not be here. Unsupported codec");
319         break;
320     }
321
322     //invalid ctx
323     resetCtx();
324
325     mCtx->extradata = NULL;
326     mCtx->extradata_size = 0;
327
328     initVorbisHdr();
329
330     memset(mSilenceBuffer, 0, kOutputBufferSize);
331
332     return OK;
333 }
334
335 void SoftFFmpegAudio::deInitDecoder() {
336     if (mCtx) {
337         if (!mCtx->extradata) {
338             av_free(mCtx->extradata);
339             mCtx->extradata = NULL;
340             mCtx->extradata_size = 0;
341         }
342
343         deinitVorbisHdr();
344
345         if (mCodecAlreadyOpened) {
346             avcodec_close(mCtx);
347             av_free(mCtx);
348             mCtx = NULL;
349         }
350     }
351     if (mFrame) {
352         av_freep(&mFrame);
353         mFrame = NULL;
354     }
355     if (mSwrCtx) {
356         swr_free(&mSwrCtx);
357         mSwrCtx = NULL;
358     }
359 }
360
361 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
362         OMX_INDEXTYPE index, OMX_PTR params) {
363     //ALOGV("internalGetParameter index:0x%x", index);
364     switch (index) {
365         case OMX_IndexParamAudioPcm:
366         {
367             OMX_AUDIO_PARAM_PCMMODETYPE *profile =
368                 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
369
370             if (profile->nPortIndex > kOutputPortIndex) {
371                 return OMX_ErrorUndefined;
372             }
373
374             profile->eNumData = OMX_NumericalDataSigned;
375             profile->eEndian = OMX_EndianBig;
376             profile->bInterleaved = OMX_TRUE;
377             profile->nBitPerSample = 16;
378             profile->ePCMMode = OMX_AUDIO_PCMModeLinear;
379             profile->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
380             profile->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
381
382             CHECK(isConfigured());
383
384             profile->nChannels = mAudioSrcChannels;
385             profile->nSamplingRate = mAudioSrcFreq;
386
387             //mCtx has been updated(adjustAudioParams)!
388             ALOGV("get pcm params, nChannels:%lu, nSamplingRate:%lu",
389                    profile->nChannels, profile->nSamplingRate);
390
391             return OMX_ErrorNone;
392         }
393
394         case OMX_IndexParamAudioAac:
395         {
396             OMX_AUDIO_PARAM_AACPROFILETYPE *profile =
397                 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
398
399             if (profile->nPortIndex != kInputPortIndex) {
400                 return OMX_ErrorUndefined;
401             }
402
403             CHECK(!isConfigured());
404
405             profile->nBitRate = 0;
406             profile->nAudioBandWidth = 0;
407             profile->nAACtools = 0;
408             profile->nAACERtools = 0;
409             profile->eAACProfile = OMX_AUDIO_AACObjectMain;
410             profile->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
411             profile->eChannelMode = OMX_AUDIO_ChannelModeStereo;
412
413             profile->nChannels = 0;
414             profile->nSampleRate = 0;
415
416             return OMX_ErrorNone;
417         }
418
419         case OMX_IndexParamAudioMp3:
420         {
421             OMX_AUDIO_PARAM_MP3TYPE *profile =
422                 (OMX_AUDIO_PARAM_MP3TYPE *)params;
423
424             if (profile->nPortIndex != kInputPortIndex) {
425                 return OMX_ErrorUndefined;
426             }
427
428             CHECK(!isConfigured());
429
430             profile->nChannels = 0;
431             profile->nSampleRate = 0;
432             profile->nBitRate = 0;
433             profile->nAudioBandWidth = 0;
434             profile->eChannelMode = OMX_AUDIO_ChannelModeStereo;
435             profile->eFormat = OMX_AUDIO_MP3StreamFormatMP1Layer3;
436
437             return OMX_ErrorNone;
438         }
439         case OMX_IndexParamAudioVorbis:
440         {
441             OMX_AUDIO_PARAM_VORBISTYPE *profile =
442                 (OMX_AUDIO_PARAM_VORBISTYPE *)params;
443
444             if (profile->nPortIndex != kInputPortIndex) {
445                 return OMX_ErrorUndefined;
446             }
447
448             CHECK(!isConfigured());
449
450             profile->nBitRate = 0;
451             profile->nMinBitRate = 0;
452             profile->nMaxBitRate = 0;
453             profile->nAudioBandWidth = 0;
454             profile->nQuality = 3;
455             profile->bManaged = OMX_FALSE;
456             profile->bDownmix = OMX_FALSE;
457
458             profile->nChannels = 0;
459             profile->nSampleRate = 0;
460
461             return OMX_ErrorNone;
462         }
463
464         case OMX_IndexParamAudioWma:
465         {
466             OMX_AUDIO_PARAM_WMATYPE *profile =
467                 (OMX_AUDIO_PARAM_WMATYPE *)params;
468
469             if (profile->nPortIndex != kInputPortIndex) {
470                 return OMX_ErrorUndefined;
471             }
472
473             CHECK(!isConfigured());
474
475             profile->nChannels = 0;
476             profile->nSamplingRate = 0;
477             profile->nBitRate = 0;
478             profile->eFormat = OMX_AUDIO_WMAFormatUnused;
479
480             return OMX_ErrorNone;
481         }
482
483         case OMX_IndexParamAudioRa:
484         {
485             OMX_AUDIO_PARAM_RATYPE *profile =
486                 (OMX_AUDIO_PARAM_RATYPE *)params;
487
488             if (profile->nPortIndex != kInputPortIndex) {
489                 return OMX_ErrorUndefined;
490             }
491
492             CHECK(!isConfigured());
493
494             profile->nChannels = 0;
495             profile->nSamplingRate = 0;
496             profile->eFormat = OMX_AUDIO_RAFormatUnused;
497
498             return OMX_ErrorNone;
499         }
500
501         case OMX_IndexParamAudioFlac:
502         {
503             OMX_AUDIO_PARAM_FLACTYPE *profile =
504                 (OMX_AUDIO_PARAM_FLACTYPE *)params;
505
506             if (profile->nPortIndex != kInputPortIndex) {
507                 return OMX_ErrorUndefined;
508             }
509
510             CHECK(!isConfigured());
511
512             profile->nChannels = 0;
513             profile->nSampleRate = 0;
514
515             return OMX_ErrorNone;
516         }
517
518         case OMX_IndexParamAudioMp2:
519         {
520             OMX_AUDIO_PARAM_MP2TYPE *profile =
521                 (OMX_AUDIO_PARAM_MP2TYPE *)params;
522
523             if (profile->nPortIndex != kInputPortIndex) {
524                 return OMX_ErrorUndefined;
525             }
526
527             CHECK(!isConfigured());
528
529             profile->nChannels = 0;
530             profile->nSampleRate = 0;
531
532             return OMX_ErrorNone;
533         }
534
535         case OMX_IndexParamAudioAc3:
536         {
537             OMX_AUDIO_PARAM_AC3TYPE *profile =
538                 (OMX_AUDIO_PARAM_AC3TYPE *)params;
539
540             if (profile->nPortIndex != kInputPortIndex) {
541                 return OMX_ErrorUndefined;
542             }
543
544             CHECK(!isConfigured());
545
546             profile->nChannels = 0;
547             profile->nSamplingRate = 0;
548
549             return OMX_ErrorNone;
550         }
551
552         case OMX_IndexParamAudioApe:
553         {
554             OMX_AUDIO_PARAM_APETYPE *profile =
555                 (OMX_AUDIO_PARAM_APETYPE *)params;
556
557             if (profile->nPortIndex != kInputPortIndex) {
558                 return OMX_ErrorUndefined;
559             }
560
561             CHECK(!isConfigured());
562
563             profile->nChannels = 0;
564             profile->nSamplingRate = 0;
565
566             return OMX_ErrorNone;
567         }
568
569         case OMX_IndexParamAudioDts:
570         {
571             OMX_AUDIO_PARAM_DTSTYPE *profile =
572                 (OMX_AUDIO_PARAM_DTSTYPE *)params;
573
574             if (profile->nPortIndex != kInputPortIndex) {
575                 return OMX_ErrorUndefined;
576             }
577
578             CHECK(!isConfigured());
579
580             profile->nChannels = 0;
581             profile->nSamplingRate = 0;
582
583             return OMX_ErrorNone;
584         }
585
586         case OMX_IndexParamAudioFFmpeg:
587         {
588             OMX_AUDIO_PARAM_FFMPEGTYPE *profile =
589                 (OMX_AUDIO_PARAM_FFMPEGTYPE *)params;
590
591             if (profile->nPortIndex != kInputPortIndex) {
592                 return OMX_ErrorUndefined;
593             }
594
595             CHECK(!isConfigured());
596
597             profile->eCodecId = 0;
598             profile->nChannels = 0;
599             profile->nBitRate = 0;
600             profile->nBitsPerSample = 0;
601             profile->nSampleRate = 0;
602             profile->nBlockAlign = 0;
603             profile->eSampleFormat = 0;
604
605             return OMX_ErrorNone;
606         }
607
608         default:
609
610             return SimpleSoftOMXComponent::internalGetParameter(index, params);
611     }
612 }
613
614 OMX_ERRORTYPE SoftFFmpegAudio::isRoleSupported(
615         const OMX_PARAM_COMPONENTROLETYPE *roleParams) {
616     bool supported = true;
617
618     switch (mMode) {
619     case MODE_AAC:
620         if (strncmp((const char *)roleParams->cRole,
621                 "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
622         supported = false;
623         break;
624     case MODE_MPEG:
625         if (strncmp((const char *)roleParams->cRole,
626                 "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
627             supported = false;
628         break;
629     case MODE_VORBIS:
630         if (strncmp((const char *)roleParams->cRole,
631                 "audio_decoder.vorbis", OMX_MAX_STRINGNAME_SIZE - 1))
632         supported = false;
633         break;
634     case MODE_WMA:
635         if (strncmp((const char *)roleParams->cRole,
636                 "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
637         supported = false;
638         break;
639     case MODE_RA:
640         if (strncmp((const char *)roleParams->cRole,
641                 "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
642         supported = false;
643         break;
644     case MODE_FLAC:
645         if (strncmp((const char *)roleParams->cRole,
646                 "audio_decoder.flac", OMX_MAX_STRINGNAME_SIZE - 1))
647         supported = false;
648         break;
649     case MODE_MPEGL2:
650         if (strncmp((const char *)roleParams->cRole,
651                 "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
652             supported = false;
653         break;
654     case MODE_AC3:
655         if (strncmp((const char *)roleParams->cRole,
656                 "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
657             supported = false;
658         break;
659     case MODE_APE:
660         if (strncmp((const char *)roleParams->cRole,
661                 "audio_decoder.ape", OMX_MAX_STRINGNAME_SIZE - 1))
662         supported = false;
663         break;
664     case MODE_DTS:
665         if (strncmp((const char *)roleParams->cRole,
666                 "audio_decoder.dts", OMX_MAX_STRINGNAME_SIZE - 1))
667         supported = false;
668         break;
669     case MODE_TRIAL:
670         if (strncmp((const char *)roleParams->cRole,
671                 "audio_decoder.trial", OMX_MAX_STRINGNAME_SIZE - 1))
672         supported = false;
673         break;
674     default:
675         CHECK(!"Should not be here. Unsupported role.");
676         break;
677     }
678
679     if (!supported) {
680         ALOGE("unsupported role: %s", (const char *)roleParams->cRole);
681         return OMX_ErrorUndefined;
682     }
683
684     return OMX_ErrorNone;
685 }
686
687 void SoftFFmpegAudio::adjustAudioParams() {
688     int32_t channels = 0;
689     int32_t sampling_rate = 0;
690
691     CHECK(!isConfigured());
692
693     sampling_rate = mCtx->sample_rate;
694
695     //channels support 1 or 2 only
696     channels = mCtx->channels >= 2 ? 2 : 1;
697
698     //4000 <= sampling rate <= 48000
699     if (sampling_rate < 4000) {
700         sampling_rate = 4000;
701     } else if (sampling_rate > 48000) {
702         sampling_rate = 48000;
703     }
704
705     mAudioSrcChannels = mAudioTgtChannels = channels;
706     mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
707     mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
708     mAudioSrcChannelLayout = mAudioTgtChannelLayout =
709         av_get_default_channel_layout(channels);
710 }
711
712 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
713         OMX_INDEXTYPE index, const OMX_PTR params) {
714     //ALOGV("internalSetParameter index:0x%x", index);
715     switch (index) {
716         case OMX_IndexParamStandardComponentRole:
717         {
718             const OMX_PARAM_COMPONENTROLETYPE *roleParams =
719                 (const OMX_PARAM_COMPONENTROLETYPE *)params;
720                         return isRoleSupported(roleParams);
721         }
722
723         case OMX_IndexParamAudioPcm:
724         {
725             const OMX_AUDIO_PARAM_PCMMODETYPE *profile =
726                 (const OMX_AUDIO_PARAM_PCMMODETYPE *)params;
727
728             if (profile->nPortIndex != kOutputPortIndex) {
729                 return OMX_ErrorUndefined;
730             }
731
732             CHECK(!isConfigured());
733
734             mCtx->channels = profile->nChannels;
735             mCtx->sample_rate = profile->nSamplingRate;
736             mCtx->bits_per_coded_sample = profile->nBitPerSample;
737
738             ALOGV("set OMX_IndexParamAudioPcm, nChannels:%lu, "
739                     "nSampleRate:%lu, nBitsPerSample:%lu",
740                 profile->nChannels, profile->nSamplingRate,
741                 profile->nBitPerSample);
742
743             return OMX_ErrorNone;
744         }
745
746         case OMX_IndexParamAudioAac:
747         {
748             const OMX_AUDIO_PARAM_AACPROFILETYPE *profile =
749                 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
750
751             if (profile->nPortIndex != kInputPortIndex) {
752                 return OMX_ErrorUndefined;
753             }
754
755             CHECK(!isConfigured());
756
757             mCtx->channels = profile->nChannels;
758             mCtx->sample_rate = profile->nSampleRate;
759
760             adjustAudioParams();
761
762             ALOGV("set OMX_IndexParamAudioAac, nChannels:%lu, nSampleRate:%lu",
763                 profile->nChannels, profile->nSampleRate);
764
765             return OMX_ErrorNone;
766         }
767
768         case OMX_IndexParamAudioMp3:
769         {
770             const OMX_AUDIO_PARAM_MP3TYPE *profile =
771                 (const OMX_AUDIO_PARAM_MP3TYPE *)params;
772
773             if (profile->nPortIndex != kInputPortIndex) {
774                 return OMX_ErrorUndefined;
775             }
776
777             CHECK(!isConfigured());
778
779             mCtx->channels = profile->nChannels;
780             mCtx->sample_rate = profile->nSampleRate;
781
782             adjustAudioParams();
783
784             ALOGV("set OMX_IndexParamAudioMp3, nChannels:%lu, nSampleRate:%lu",
785                 profile->nChannels, profile->nSampleRate);
786
787             return OMX_ErrorNone;
788         }
789
790         case OMX_IndexParamAudioVorbis:
791         {
792             const OMX_AUDIO_PARAM_VORBISTYPE *profile =
793                 (const OMX_AUDIO_PARAM_VORBISTYPE *)params;
794
795             if (profile->nPortIndex != kInputPortIndex) {
796                 return OMX_ErrorUndefined;
797             }
798
799             CHECK(!isConfigured());
800
801             mCtx->channels = profile->nChannels;
802             mCtx->sample_rate = profile->nSampleRate;
803
804             adjustAudioParams();
805
806             ALOGD("set OMX_IndexParamAudioVorbis, "
807                     "nChannels=%lu, nSampleRate=%lu, nBitRate=%lu, "
808                     "nMinBitRate=%lu, nMaxBitRate=%lu",
809                 profile->nChannels, profile->nSampleRate,
810                 profile->nBitRate, profile->nMinBitRate,
811                 profile->nMaxBitRate);
812
813             return OMX_ErrorNone;
814         }
815
816         case OMX_IndexParamAudioWma:
817         {
818             OMX_AUDIO_PARAM_WMATYPE *profile =
819                 (OMX_AUDIO_PARAM_WMATYPE *)params;
820
821             if (profile->nPortIndex != kInputPortIndex) {
822                 return OMX_ErrorUndefined;
823             }
824
825             CHECK(!isConfigured());
826
827             if (profile->eFormat == OMX_AUDIO_WMAFormat7) {
828                mCtx->codec_id = AV_CODEC_ID_WMAV2;
829             } else if (profile->eFormat == OMX_AUDIO_WMAFormat8) {
830                mCtx->codec_id = AV_CODEC_ID_WMAPRO;
831             } else if (profile->eFormat == OMX_AUDIO_WMAFormat9) {
832                mCtx->codec_id = AV_CODEC_ID_WMALOSSLESS;
833             } else {
834                 ALOGE("unsupported wma codec: 0x%x", profile->eFormat);
835                 return OMX_ErrorUndefined;
836             }
837
838             mCtx->channels = profile->nChannels;
839             mCtx->sample_rate = profile->nSamplingRate;
840
841             // wmadec needs bitrate, block_align
842             mCtx->bit_rate = profile->nBitRate;
843             mCtx->block_align = profile->nBlockAlign;
844
845             adjustAudioParams();
846
847             ALOGV("set OMX_IndexParamAudioWma, nChannels:%u, "
848                     "nSampleRate:%lu, nBitRate:%lu, nBlockAlign:%u",
849                 profile->nChannels, profile->nSamplingRate,
850                 profile->nBitRate, profile->nBlockAlign);
851
852             return OMX_ErrorNone;
853         }
854
855         case OMX_IndexParamAudioRa:
856         {
857             OMX_AUDIO_PARAM_RATYPE *profile =
858                 (OMX_AUDIO_PARAM_RATYPE *)params;
859
860             if (profile->nPortIndex != kInputPortIndex) {
861                 return OMX_ErrorUndefined;
862             }
863
864             CHECK(!isConfigured());
865
866             mCtx->channels = profile->nChannels;
867             mCtx->sample_rate = profile->nSamplingRate;
868
869             // FIXME, HACK!!!, I use the nNumRegions parameter pass blockAlign!!!
870             // the cook audio codec need blockAlign!
871             mCtx->block_align = profile->nNumRegions;
872
873             adjustAudioParams();
874
875             ALOGV("set OMX_IndexParamAudioRa, nChannels:%lu, "
876                     "nSampleRate:%lu, nBlockAlign:%d",
877                 profile->nChannels, profile->nSamplingRate, mCtx->block_align);
878
879             return OMX_ErrorNone;
880         }
881
882         case OMX_IndexParamAudioFlac:
883         {
884             OMX_AUDIO_PARAM_FLACTYPE *profile =
885                 (OMX_AUDIO_PARAM_FLACTYPE *)params;
886
887             if (profile->nPortIndex != kInputPortIndex) {
888                 return OMX_ErrorUndefined;
889             }
890
891             CHECK(!isConfigured());
892
893             mCtx->channels = profile->nChannels;
894             mCtx->sample_rate = profile->nSampleRate;
895
896             adjustAudioParams();
897
898             ALOGV("set OMX_IndexParamAudioFlac, nChannels:%lu, nSampleRate:%lu",
899                 profile->nChannels, profile->nSampleRate);
900
901             return OMX_ErrorNone;
902         }
903
904         case OMX_IndexParamAudioMp2:
905         {
906             OMX_AUDIO_PARAM_MP2TYPE *profile =
907                 (OMX_AUDIO_PARAM_MP2TYPE *)params;
908
909             if (profile->nPortIndex != kInputPortIndex) {
910                 return OMX_ErrorUndefined;
911             }
912
913             CHECK(!isConfigured());
914
915             mCtx->channels = profile->nChannels;
916             mCtx->sample_rate = profile->nSampleRate;
917
918             adjustAudioParams();
919
920             ALOGV("set OMX_IndexParamAudioMp2, nChannels:%lu, nSampleRate:%lu",
921                 profile->nChannels, profile->nSampleRate);
922
923             return OMX_ErrorNone;
924         }
925
926         case OMX_IndexParamAudioAc3:
927         {
928             OMX_AUDIO_PARAM_AC3TYPE *profile =
929                 (OMX_AUDIO_PARAM_AC3TYPE *)params;
930
931             if (profile->nPortIndex != kInputPortIndex) {
932                 return OMX_ErrorUndefined;
933             }
934
935             CHECK(!isConfigured());
936
937             mCtx->channels = profile->nChannels;
938             mCtx->sample_rate = profile->nSamplingRate;
939
940             adjustAudioParams();
941
942             ALOGV("set OMX_IndexParamAudioFlac, nChannels:%lu, nSampleRate:%lu",
943                 profile->nChannels, profile->nSamplingRate);
944
945             return OMX_ErrorNone;
946         }
947
948         case OMX_IndexParamAudioApe:
949         {
950             OMX_AUDIO_PARAM_APETYPE *profile =
951                 (OMX_AUDIO_PARAM_APETYPE *)params;
952
953             if (profile->nPortIndex != kInputPortIndex) {
954                 return OMX_ErrorUndefined;
955             }
956
957             CHECK(!isConfigured());
958
959             mCtx->channels = profile->nChannels;
960             mCtx->sample_rate = profile->nSamplingRate;
961
962             //ape decoder need bits_per_coded_sample
963             mCtx->bits_per_coded_sample = profile->nBitsPerSample;
964
965             adjustAudioParams();
966
967             ALOGV("set OMX_IndexParamAudioApe, nChannels:%lu, "
968                     "nSampleRate:%lu, nBitsPerSample:%lu",
969                 profile->nChannels, profile->nSamplingRate,
970                 profile->nBitsPerSample);
971
972             return OMX_ErrorNone;
973         }
974
975         case OMX_IndexParamAudioDts:
976         {
977             OMX_AUDIO_PARAM_DTSTYPE *profile =
978                 (OMX_AUDIO_PARAM_DTSTYPE *)params;
979
980             if (profile->nPortIndex != kInputPortIndex) {
981                 return OMX_ErrorUndefined;
982             }
983
984             CHECK(!isConfigured());
985
986             mCtx->channels = profile->nChannels;
987             mCtx->sample_rate = profile->nSamplingRate;
988
989             adjustAudioParams();
990
991             ALOGV("set OMX_IndexParamAudioDts, nChannels:%lu, nSampleRate:%lu",
992                 profile->nChannels, profile->nSamplingRate);
993
994             return OMX_ErrorNone;
995         }
996
997         case OMX_IndexParamAudioFFmpeg:
998         {
999             OMX_AUDIO_PARAM_FFMPEGTYPE *profile =
1000                 (OMX_AUDIO_PARAM_FFMPEGTYPE *)params;
1001
1002             if (profile->nPortIndex != kInputPortIndex) {
1003                 return OMX_ErrorUndefined;
1004             }
1005
1006             CHECK(!isConfigured());
1007
1008
1009             mCtx->codec_id = (enum AVCodecID)profile->eCodecId;
1010             mCtx->channels = profile->nChannels;
1011             mCtx->bit_rate = profile->nBitRate;
1012             mCtx->bits_per_coded_sample = profile->nBitsPerSample;
1013             mCtx->sample_rate = profile->nSampleRate;
1014             mCtx->block_align = profile->nBlockAlign;
1015             mCtx->sample_fmt = (AVSampleFormat)profile->eSampleFormat;
1016
1017             adjustAudioParams();
1018
1019             ALOGD("set OMX_IndexParamAudioFFmpeg, "
1020                 "eCodecId:%ld(%s), nChannels:%lu, nBitRate:%lu, "
1021                 "nBitsPerSample:%lu, nSampleRate:%lu, "
1022                 "nBlockAlign:%lu, eSampleFormat:%lu(%s)",
1023                 profile->eCodecId, avcodec_get_name(mCtx->codec_id),
1024                 profile->nChannels, profile->nBitRate,
1025                 profile->nBitsPerSample, profile->nSampleRate,
1026                 profile->nBlockAlign, profile->eSampleFormat,
1027                 av_get_sample_fmt_name(mCtx->sample_fmt));
1028             return OMX_ErrorNone;
1029         }
1030
1031         default:
1032
1033             return SimpleSoftOMXComponent::internalSetParameter(index, params);
1034     }
1035 }
1036
1037 int32_t SoftFFmpegAudio::handleVorbisExtradata(OMX_BUFFERHEADERTYPE *inHeader)
1038 {
1039     uint8_t *p = inHeader->pBuffer + inHeader->nOffset;
1040     int len = inHeader->nFilledLen;
1041     int index = 0;
1042
1043     if (p[0] == 1) {
1044         index = 0;
1045     } else if (p[0] == 3) {
1046         index = 1;
1047     } else if (p[0] == 5) {
1048         index = 2;
1049     } else {
1050         ALOGE("error vorbis codec config");
1051         return ERR_INVALID_PARAM;
1052     }
1053
1054     mVorbisHeaderStart[index] = (uint8_t *)av_mallocz(len);
1055     if (!mVorbisHeaderStart[index]) {
1056         ALOGE("oom for vorbis extradata");
1057         return ERR_OOM;
1058     }
1059     memcpy(mVorbisHeaderStart[index], p, len);
1060     mVorbisHeaderLen[index] = inHeader->nFilledLen;
1061
1062     return ERR_OK;
1063 }
1064
1065 int32_t SoftFFmpegAudio::handleExtradata() {
1066     List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
1067     BufferInfo *inInfo = *inQueue.begin();
1068     OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
1069
1070     ALOGI("got extradata, ignore: %d, size: %lu",
1071             mIgnoreExtradata, inHeader->nFilledLen);
1072     hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
1073
1074     if (mIgnoreExtradata) {
1075         ALOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
1076     } else {
1077         if (!mExtradataReady) {
1078             uint32_t ret = ERR_OK;
1079             if (mCtx->codec_id == AV_CODEC_ID_VORBIS) {
1080                 if ((ret = handleVorbisExtradata(inHeader)) != ERR_OK) {
1081                     ALOGE("ffmpeg audio decoder failed to alloc vorbis extradata memory.");
1082                     return ret;
1083                 }
1084             } else {
1085                 int orig_extradata_size = mCtx->extradata_size;
1086                 mCtx->extradata_size += inHeader->nFilledLen;
1087                 mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
1088                     mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1089                 if (!mCtx->extradata) {
1090                     ALOGE("ffmpeg audio decoder failed to alloc extradata memory.");
1091                     return ERR_OOM;
1092                 }
1093
1094                 memcpy(mCtx->extradata + orig_extradata_size,
1095                     inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
1096                 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1097             }
1098         }
1099     }
1100
1101     inInfo->mOwnedByUs = false;
1102     inQueue.erase(inQueue.begin());
1103     inInfo = NULL;
1104     notifyEmptyBufferDone(inHeader);
1105     inHeader = NULL;
1106
1107     return ERR_OK;
1108 }
1109
1110 int32_t SoftFFmpegAudio::openDecoder() {
1111     if (mCodecAlreadyOpened) {
1112         return ERR_OK;
1113     }
1114
1115     if (!mExtradataReady && !mIgnoreExtradata) {
1116         if (mCtx->codec_id == AV_CODEC_ID_VORBIS) {
1117                     if (!setup_vorbis_extradata(&mCtx->extradata,
1118                         &mCtx->extradata_size,
1119                         (const uint8_t **)mVorbisHeaderStart,
1120                         mVorbisHeaderLen)) {
1121                 return ERR_OOM;
1122             }
1123             deinitVorbisHdr();
1124             }
1125         ALOGI("extradata is ready, size: %d", mCtx->extradata_size);
1126         hexdump(mCtx->extradata, mCtx->extradata_size);
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 }