OSDN Git Service

add HEVC(H.265) decoder. plz sync:
[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_CodingMP3;
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 status_t SoftFFmpegAudio::initDecoder() {
249     status_t status;
250
251     status = initFFmpeg();
252     if (status != OK) {
253         return NO_INIT;
254     }
255     mFFmpegAlreadyInited = true;
256
257     mCtx = avcodec_alloc_context3(NULL);
258     if (!mCtx) {
259         ALOGE("avcodec_alloc_context failed.");
260         return NO_MEMORY;
261     }
262
263     mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
264     switch (mMode) {
265     case MODE_AAC:
266         mCtx->codec_id = AV_CODEC_ID_AAC;
267         break;
268     case MODE_MPEG:
269         mCtx->codec_id = AV_CODEC_ID_MP3;
270         break;
271     case MODE_VORBIS:
272         mCtx->codec_id = AV_CODEC_ID_VORBIS;
273         break;
274     case MODE_WMA:
275         mCtx->codec_id = AV_CODEC_ID_WMAV2; //should be adjusted later
276         break;
277     case MODE_RA:
278         mCtx->codec_id = AV_CODEC_ID_COOK;
279         break;
280     case MODE_FLAC:
281         mCtx->codec_id = AV_CODEC_ID_FLAC;
282         break;
283     case MODE_MPEGL2:
284         mCtx->codec_id = AV_CODEC_ID_MP2;
285         break;
286     case MODE_AC3:
287         mCtx->codec_id = AV_CODEC_ID_AC3;
288         break;
289     case MODE_APE:
290         mCtx->codec_id = AV_CODEC_ID_APE;
291         break;
292     case MODE_DTS:
293         mCtx->codec_id = AV_CODEC_ID_DTS;
294         break;
295     case MODE_TRIAL:
296         mCtx->codec_id = AV_CODEC_ID_NONE;
297         break;
298     default:
299         CHECK(!"Should not be here. Unsupported codec");
300         break;
301     }
302
303     //invalid ctx
304     resetCtx();
305
306     mCtx->extradata = NULL;
307     mCtx->extradata_size = 0;
308
309     memset(mSilenceBuffer, 0, kOutputBufferSize);
310
311     return OK;
312 }
313
314 void SoftFFmpegAudio::deInitDecoder() {
315     if (mCtx) {
316         if (!mCtx->extradata) {
317             av_free(mCtx->extradata);
318             mCtx->extradata = NULL;
319             mCtx->extradata_size = 0;
320         }
321         if (mCodecAlreadyOpened) {
322             avcodec_close(mCtx);
323             av_free(mCtx);
324             mCtx = NULL;
325         }
326     }
327     if (mFrame) {
328         av_freep(&mFrame);
329         mFrame = NULL;
330     }
331     if (mSwrCtx) {
332         swr_free(&mSwrCtx);
333         mSwrCtx = NULL;
334     }
335 }
336
337 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
338         OMX_INDEXTYPE index, OMX_PTR params) {
339     //ALOGV("internalGetParameter index:0x%x", index);
340     switch (index) {
341         case OMX_IndexParamAudioPcm:
342         {
343             OMX_AUDIO_PARAM_PCMMODETYPE *profile =
344                 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
345
346             if (profile->nPortIndex > kOutputPortIndex) {
347                 return OMX_ErrorUndefined;
348             }
349
350             profile->eNumData = OMX_NumericalDataSigned;
351             profile->eEndian = OMX_EndianBig;
352             profile->bInterleaved = OMX_TRUE;
353             profile->nBitPerSample = 16;
354             profile->ePCMMode = OMX_AUDIO_PCMModeLinear;
355             profile->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
356             profile->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
357
358             CHECK(isConfigured());
359
360             profile->nChannels = mAudioSrcChannels;
361             profile->nSamplingRate = mAudioSrcFreq;
362
363             //mCtx has been updated(adjustAudioParams)!
364             ALOGV("get pcm params, nChannels:%lu, nSamplingRate:%lu",
365                    profile->nChannels, profile->nSamplingRate);
366
367             return OMX_ErrorNone;
368         }
369
370         case OMX_IndexParamAudioAac:
371         {
372             OMX_AUDIO_PARAM_AACPROFILETYPE *profile =
373                 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
374
375             if (profile->nPortIndex != kInputPortIndex) {
376                 return OMX_ErrorUndefined;
377             }
378
379             CHECK(!isConfigured());
380
381             profile->nBitRate = 0;
382             profile->nAudioBandWidth = 0;
383             profile->nAACtools = 0;
384             profile->nAACERtools = 0;
385             profile->eAACProfile = OMX_AUDIO_AACObjectMain;
386             profile->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
387             profile->eChannelMode = OMX_AUDIO_ChannelModeStereo;
388
389             profile->nChannels = 0;
390             profile->nSampleRate = 0;
391
392             return OMX_ErrorNone;
393         }
394
395         case OMX_IndexParamAudioMp3:
396         {
397             OMX_AUDIO_PARAM_MP3TYPE *profile =
398                 (OMX_AUDIO_PARAM_MP3TYPE *)params;
399
400             if (profile->nPortIndex != kInputPortIndex) {
401                 return OMX_ErrorUndefined;
402             }
403
404             CHECK(!isConfigured());
405
406             profile->nChannels = 0;
407             profile->nSampleRate = 0;
408             profile->nBitRate = 0;
409             profile->nAudioBandWidth = 0;
410             profile->eChannelMode = OMX_AUDIO_ChannelModeStereo;
411             profile->eFormat = OMX_AUDIO_MP3StreamFormatMP1Layer3;
412
413             return OMX_ErrorNone;
414         }
415         case OMX_IndexParamAudioVorbis:
416         {
417             OMX_AUDIO_PARAM_VORBISTYPE *profile =
418                 (OMX_AUDIO_PARAM_VORBISTYPE *)params;
419
420             if (profile->nPortIndex != kInputPortIndex) {
421                 return OMX_ErrorUndefined;
422             }
423
424             CHECK(!isConfigured());
425
426             profile->nBitRate = 0;
427             profile->nMinBitRate = 0;
428             profile->nMaxBitRate = 0;
429             profile->nAudioBandWidth = 0;
430             profile->nQuality = 3;
431             profile->bManaged = OMX_FALSE;
432             profile->bDownmix = OMX_FALSE;
433
434             profile->nChannels = 0;
435             profile->nSampleRate = 0;
436
437             return OMX_ErrorNone;
438         }
439
440         case OMX_IndexParamAudioWma:
441         {
442             OMX_AUDIO_PARAM_WMATYPE *profile =
443                 (OMX_AUDIO_PARAM_WMATYPE *)params;
444
445             if (profile->nPortIndex != kInputPortIndex) {
446                 return OMX_ErrorUndefined;
447             }
448
449             CHECK(!isConfigured());
450
451             profile->nChannels = 0;
452             profile->nSamplingRate = 0;
453             profile->nBitRate = 0;
454             profile->eFormat = OMX_AUDIO_WMAFormatUnused;
455
456             return OMX_ErrorNone;
457         }
458
459         case OMX_IndexParamAudioRa:
460         {
461             OMX_AUDIO_PARAM_RATYPE *profile =
462                 (OMX_AUDIO_PARAM_RATYPE *)params;
463
464             if (profile->nPortIndex != kInputPortIndex) {
465                 return OMX_ErrorUndefined;
466             }
467
468             CHECK(!isConfigured());
469
470             profile->nChannels = 0;
471             profile->nSamplingRate = 0;
472             profile->eFormat = OMX_AUDIO_RAFormatUnused;
473
474             return OMX_ErrorNone;
475         }
476
477         case OMX_IndexParamAudioFlac:
478         {
479             OMX_AUDIO_PARAM_FLACTYPE *profile =
480                 (OMX_AUDIO_PARAM_FLACTYPE *)params;
481
482             if (profile->nPortIndex != kInputPortIndex) {
483                 return OMX_ErrorUndefined;
484             }
485
486             CHECK(!isConfigured());
487
488             profile->nChannels = 0;
489             profile->nSampleRate = 0;
490
491             return OMX_ErrorNone;
492         }
493
494         case OMX_IndexParamAudioMp2:
495         {
496             OMX_AUDIO_PARAM_MP2TYPE *profile =
497                 (OMX_AUDIO_PARAM_MP2TYPE *)params;
498
499             if (profile->nPortIndex != kInputPortIndex) {
500                 return OMX_ErrorUndefined;
501             }
502
503             CHECK(!isConfigured());
504
505             profile->nChannels = 0;
506             profile->nSampleRate = 0;
507
508             return OMX_ErrorNone;
509         }
510
511         case OMX_IndexParamAudioAc3:
512         {
513             OMX_AUDIO_PARAM_AC3TYPE *profile =
514                 (OMX_AUDIO_PARAM_AC3TYPE *)params;
515
516             if (profile->nPortIndex != kInputPortIndex) {
517                 return OMX_ErrorUndefined;
518             }
519
520             CHECK(!isConfigured());
521
522             profile->nChannels = 0;
523             profile->nSamplingRate = 0;
524
525             return OMX_ErrorNone;
526         }
527
528         case OMX_IndexParamAudioApe:
529         {
530             OMX_AUDIO_PARAM_APETYPE *profile =
531                 (OMX_AUDIO_PARAM_APETYPE *)params;
532
533             if (profile->nPortIndex != kInputPortIndex) {
534                 return OMX_ErrorUndefined;
535             }
536
537             CHECK(!isConfigured());
538
539             profile->nChannels = 0;
540             profile->nSamplingRate = 0;
541
542             return OMX_ErrorNone;
543         }
544
545         case OMX_IndexParamAudioDts:
546         {
547             OMX_AUDIO_PARAM_DTSTYPE *profile =
548                 (OMX_AUDIO_PARAM_DTSTYPE *)params;
549
550             if (profile->nPortIndex != kInputPortIndex) {
551                 return OMX_ErrorUndefined;
552             }
553
554             CHECK(!isConfigured());
555
556             profile->nChannels = 0;
557             profile->nSamplingRate = 0;
558
559             return OMX_ErrorNone;
560         }
561
562         case OMX_IndexParamAudioFFmpeg:
563         {
564             OMX_AUDIO_PARAM_FFMPEGTYPE *profile =
565                 (OMX_AUDIO_PARAM_FFMPEGTYPE *)params;
566
567             if (profile->nPortIndex != kInputPortIndex) {
568                 return OMX_ErrorUndefined;
569             }
570
571             CHECK(!isConfigured());
572
573             profile->eCodecId = 0;
574             profile->nChannels = 0;
575             profile->nBitRate = 0;
576             profile->nBitsPerSample = 0;
577             profile->nSampleRate = 0;
578             profile->nBlockAlign = 0;
579             profile->eSampleFormat = 0;
580
581             return OMX_ErrorNone;
582         }
583
584         default:
585
586             return SimpleSoftOMXComponent::internalGetParameter(index, params);
587     }
588 }
589
590 OMX_ERRORTYPE SoftFFmpegAudio::isRoleSupported(
591         const OMX_PARAM_COMPONENTROLETYPE *roleParams) {
592     bool supported = true;
593
594     switch (mMode) {
595     case MODE_AAC:
596         if (strncmp((const char *)roleParams->cRole,
597                 "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
598         supported = false;
599         break;
600     case MODE_MPEG:
601         if (strncmp((const char *)roleParams->cRole,
602                 "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
603             supported = false;
604         break;
605     case MODE_VORBIS:
606         if (strncmp((const char *)roleParams->cRole,
607                 "audio_decoder.vorbis", OMX_MAX_STRINGNAME_SIZE - 1))
608         supported = false;
609         break;
610     case MODE_WMA:
611         if (strncmp((const char *)roleParams->cRole,
612                 "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
613         supported = false;
614         break;
615     case MODE_RA:
616         if (strncmp((const char *)roleParams->cRole,
617                 "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
618         supported = false;
619         break;
620     case MODE_FLAC:
621         if (strncmp((const char *)roleParams->cRole,
622                 "audio_decoder.flac", OMX_MAX_STRINGNAME_SIZE - 1))
623         supported = false;
624         break;
625     case MODE_MPEGL2:
626         if (strncmp((const char *)roleParams->cRole,
627                 "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
628             supported = false;
629         break;
630     case MODE_AC3:
631         if (strncmp((const char *)roleParams->cRole,
632                 "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
633             supported = false;
634         break;
635     case MODE_APE:
636         if (strncmp((const char *)roleParams->cRole,
637                 "audio_decoder.ape", OMX_MAX_STRINGNAME_SIZE - 1))
638         supported = false;
639         break;
640     case MODE_DTS:
641         if (strncmp((const char *)roleParams->cRole,
642                 "audio_decoder.dts", OMX_MAX_STRINGNAME_SIZE - 1))
643         supported = false;
644         break;
645     case MODE_TRIAL:
646         if (strncmp((const char *)roleParams->cRole,
647                 "audio_decoder.trial", OMX_MAX_STRINGNAME_SIZE - 1))
648         supported = false;
649         break;
650     default:
651         CHECK(!"Should not be here. Unsupported role.");
652         break;
653     }
654
655     if (!supported) {
656         ALOGE("unsupported role: %s", (const char *)roleParams->cRole);
657         return OMX_ErrorUndefined;
658     }
659
660     return OMX_ErrorNone;
661 }
662
663 void SoftFFmpegAudio::adjustAudioParams() {
664     int32_t channels = 0;
665     int32_t sampling_rate = 0;
666
667     CHECK(!isConfigured());
668
669     sampling_rate = mCtx->sample_rate;
670
671     //channels support 1 or 2 only
672     channels = mCtx->channels >= 2 ? 2 : 1;
673
674     //4000 <= sampling rate <= 48000
675     if (sampling_rate < 4000) {
676         sampling_rate = 4000;
677     } else if (sampling_rate > 48000) {
678         sampling_rate = 48000;
679     }
680
681     mAudioSrcChannels = mAudioTgtChannels = channels;
682     mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
683     mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
684     mAudioSrcChannelLayout = mAudioTgtChannelLayout =
685         av_get_default_channel_layout(channels);
686 }
687
688 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
689         OMX_INDEXTYPE index, const OMX_PTR params) {
690     //ALOGV("internalSetParameter index:0x%x", index);
691     switch (index) {
692         case OMX_IndexParamStandardComponentRole:
693         {
694             const OMX_PARAM_COMPONENTROLETYPE *roleParams =
695                 (const OMX_PARAM_COMPONENTROLETYPE *)params;
696                         return isRoleSupported(roleParams);
697         }
698
699         case OMX_IndexParamAudioPcm:
700         {
701             const OMX_AUDIO_PARAM_PCMMODETYPE *profile =
702                 (const OMX_AUDIO_PARAM_PCMMODETYPE *)params;
703
704             if (profile->nPortIndex != kOutputPortIndex) {
705                 return OMX_ErrorUndefined;
706             }
707
708             CHECK(!isConfigured());
709
710             mCtx->channels = profile->nChannels;
711             mCtx->sample_rate = profile->nSamplingRate;
712             mCtx->bits_per_coded_sample = profile->nBitPerSample;
713
714             ALOGV("set OMX_IndexParamAudioPcm, nChannels:%lu, "
715                     "nSampleRate:%lu, nBitsPerSample:%lu",
716                 profile->nChannels, profile->nSamplingRate,
717                 profile->nBitPerSample);
718
719             return OMX_ErrorNone;
720         }
721
722         case OMX_IndexParamAudioAac:
723         {
724             const OMX_AUDIO_PARAM_AACPROFILETYPE *profile =
725                 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
726
727             if (profile->nPortIndex != kInputPortIndex) {
728                 return OMX_ErrorUndefined;
729             }
730
731             CHECK(!isConfigured());
732
733             mCtx->channels = profile->nChannels;
734             mCtx->sample_rate = profile->nSampleRate;
735
736             adjustAudioParams();
737
738             ALOGV("set OMX_IndexParamAudioAac, nChannels:%lu, nSampleRate:%lu",
739                 profile->nChannels, profile->nSampleRate);
740
741             return OMX_ErrorNone;
742         }
743
744         case OMX_IndexParamAudioMp3:
745         {
746             const OMX_AUDIO_PARAM_MP3TYPE *profile =
747                 (const OMX_AUDIO_PARAM_MP3TYPE *)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_IndexParamAudioMp3, nChannels:%lu, nSampleRate:%lu",
761                 profile->nChannels, profile->nSampleRate);
762
763             return OMX_ErrorNone;
764         }
765
766         case OMX_IndexParamAudioVorbis:
767         {
768             const OMX_AUDIO_PARAM_VORBISTYPE *profile =
769                 (const OMX_AUDIO_PARAM_VORBISTYPE *)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             ALOGD("set OMX_IndexParamAudioVorbis, "
783                     "nChannels=%lu, nSampleRate=%lu, nBitRate=%lu, "
784                     "nMinBitRate=%lu, nMaxBitRate=%lu",
785                 profile->nChannels, profile->nSampleRate,
786                 profile->nBitRate, profile->nMinBitRate,
787                 profile->nMaxBitRate);
788
789             return OMX_ErrorNone;
790         }
791
792         case OMX_IndexParamAudioWma:
793         {
794             OMX_AUDIO_PARAM_WMATYPE *profile =
795                 (OMX_AUDIO_PARAM_WMATYPE *)params;
796
797             if (profile->nPortIndex != kInputPortIndex) {
798                 return OMX_ErrorUndefined;
799             }
800
801             CHECK(!isConfigured());
802
803             if (profile->eFormat == OMX_AUDIO_WMAFormat7) {
804                mCtx->codec_id = AV_CODEC_ID_WMAV2;
805             } else if (profile->eFormat == OMX_AUDIO_WMAFormat8) {
806                mCtx->codec_id = AV_CODEC_ID_WMAPRO;
807             } else if (profile->eFormat == OMX_AUDIO_WMAFormat9) {
808                mCtx->codec_id = AV_CODEC_ID_WMALOSSLESS;
809             } else {
810                 ALOGE("unsupported wma codec: 0x%x", profile->eFormat);
811                 return OMX_ErrorUndefined;
812             }
813
814             mCtx->channels = profile->nChannels;
815             mCtx->sample_rate = profile->nSamplingRate;
816
817             // wmadec needs bitrate, block_align
818             mCtx->bit_rate = profile->nBitRate;
819             mCtx->block_align = profile->nBlockAlign;
820
821             adjustAudioParams();
822
823             ALOGV("set OMX_IndexParamAudioWma, nChannels:%u, "
824                     "nSampleRate:%lu, nBitRate:%lu, nBlockAlign:%u",
825                 profile->nChannels, profile->nSamplingRate,
826                 profile->nBitRate, profile->nBlockAlign);
827
828             return OMX_ErrorNone;
829         }
830
831         case OMX_IndexParamAudioRa:
832         {
833             OMX_AUDIO_PARAM_RATYPE *profile =
834                 (OMX_AUDIO_PARAM_RATYPE *)params;
835
836             if (profile->nPortIndex != kInputPortIndex) {
837                 return OMX_ErrorUndefined;
838             }
839
840             CHECK(!isConfigured());
841
842             mCtx->channels = profile->nChannels;
843             mCtx->sample_rate = profile->nSamplingRate;
844
845             // FIXME, HACK!!!, I use the nNumRegions parameter pass blockAlign!!!
846             // the cook audio codec need blockAlign!
847             mCtx->block_align = profile->nNumRegions;
848
849             adjustAudioParams();
850
851             ALOGV("set OMX_IndexParamAudioRa, nChannels:%lu, "
852                     "nSampleRate:%lu, nBlockAlign:%d",
853                 profile->nChannels, profile->nSamplingRate, mCtx->block_align);
854
855             return OMX_ErrorNone;
856         }
857
858         case OMX_IndexParamAudioFlac:
859         {
860             OMX_AUDIO_PARAM_FLACTYPE *profile =
861                 (OMX_AUDIO_PARAM_FLACTYPE *)params;
862
863             if (profile->nPortIndex != kInputPortIndex) {
864                 return OMX_ErrorUndefined;
865             }
866
867             CHECK(!isConfigured());
868
869             mCtx->channels = profile->nChannels;
870             mCtx->sample_rate = profile->nSampleRate;
871
872             adjustAudioParams();
873
874             ALOGV("set OMX_IndexParamAudioFlac, nChannels:%lu, nSampleRate:%lu",
875                 profile->nChannels, profile->nSampleRate);
876
877             return OMX_ErrorNone;
878         }
879
880         case OMX_IndexParamAudioMp2:
881         {
882             OMX_AUDIO_PARAM_MP2TYPE *profile =
883                 (OMX_AUDIO_PARAM_MP2TYPE *)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_IndexParamAudioMp2, nChannels:%lu, nSampleRate:%lu",
897                 profile->nChannels, profile->nSampleRate);
898
899             return OMX_ErrorNone;
900         }
901
902         case OMX_IndexParamAudioAc3:
903         {
904             OMX_AUDIO_PARAM_AC3TYPE *profile =
905                 (OMX_AUDIO_PARAM_AC3TYPE *)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->nSamplingRate;
915
916             adjustAudioParams();
917
918             ALOGV("set OMX_IndexParamAudioFlac, nChannels:%lu, nSampleRate:%lu",
919                 profile->nChannels, profile->nSamplingRate);
920
921             return OMX_ErrorNone;
922         }
923
924         case OMX_IndexParamAudioApe:
925         {
926             OMX_AUDIO_PARAM_APETYPE *profile =
927                 (OMX_AUDIO_PARAM_APETYPE *)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             //ape decoder need bits_per_coded_sample
939             mCtx->bits_per_coded_sample = profile->nBitsPerSample;
940
941             adjustAudioParams();
942
943             ALOGV("set OMX_IndexParamAudioApe, nChannels:%lu, "
944                     "nSampleRate:%lu, nBitsPerSample:%lu",
945                 profile->nChannels, profile->nSamplingRate,
946                 profile->nBitsPerSample);
947
948             return OMX_ErrorNone;
949         }
950
951         case OMX_IndexParamAudioDts:
952         {
953             OMX_AUDIO_PARAM_DTSTYPE *profile =
954                 (OMX_AUDIO_PARAM_DTSTYPE *)params;
955
956             if (profile->nPortIndex != kInputPortIndex) {
957                 return OMX_ErrorUndefined;
958             }
959
960             CHECK(!isConfigured());
961
962             mCtx->channels = profile->nChannels;
963             mCtx->sample_rate = profile->nSamplingRate;
964
965             adjustAudioParams();
966
967             ALOGV("set OMX_IndexParamAudioDts, nChannels:%lu, nSampleRate:%lu",
968                 profile->nChannels, profile->nSamplingRate);
969
970             return OMX_ErrorNone;
971         }
972
973         case OMX_IndexParamAudioFFmpeg:
974         {
975             OMX_AUDIO_PARAM_FFMPEGTYPE *profile =
976                 (OMX_AUDIO_PARAM_FFMPEGTYPE *)params;
977
978             if (profile->nPortIndex != kInputPortIndex) {
979                 return OMX_ErrorUndefined;
980             }
981
982             CHECK(!isConfigured());
983
984
985             mCtx->codec_id = (enum AVCodecID)profile->eCodecId;
986             mCtx->channels = profile->nChannels;
987             mCtx->bit_rate = profile->nBitRate;
988             mCtx->bits_per_coded_sample = profile->nBitsPerSample;
989             mCtx->sample_rate = profile->nSampleRate;
990             mCtx->block_align = profile->nBlockAlign;
991             mCtx->sample_fmt = (AVSampleFormat)profile->eSampleFormat;
992
993             adjustAudioParams();
994
995             ALOGD("set OMX_IndexParamAudioFFmpeg, "
996                 "eCodecId:%ld(%s), nChannels:%lu, nBitRate:%lu, "
997                 "nBitsPerSample:%lu, nSampleRate:%lu, "
998                 "nBlockAlign:%lu, eSampleFormat:%lu(%s)",
999                 profile->eCodecId, avcodec_get_name(mCtx->codec_id),
1000                 profile->nChannels, profile->nBitRate,
1001                 profile->nBitsPerSample, profile->nSampleRate,
1002                 profile->nBlockAlign, profile->eSampleFormat,
1003                 av_get_sample_fmt_name(mCtx->sample_fmt));
1004             return OMX_ErrorNone;
1005         }
1006
1007         default:
1008
1009             return SimpleSoftOMXComponent::internalSetParameter(index, params);
1010     }
1011 }
1012
1013 int32_t SoftFFmpegAudio::handleExtradata() {
1014     List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
1015     BufferInfo *inInfo = *inQueue.begin();
1016     OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
1017
1018     ALOGI("got extradata, ignore: %d, size: %lu",
1019             mIgnoreExtradata, inHeader->nFilledLen);
1020     hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
1021
1022     if (mIgnoreExtradata) {
1023         ALOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
1024     } else {
1025         if (!mExtradataReady) {
1026             int orig_extradata_size = mCtx->extradata_size;
1027             mCtx->extradata_size += inHeader->nFilledLen;
1028             mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
1029                     mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
1030             if (!mCtx->extradata) {
1031                 ALOGE("ffmpeg audio decoder failed to alloc extradata memory.");
1032                 return ERR_OOM;
1033             }
1034
1035             memcpy(mCtx->extradata + orig_extradata_size,
1036                     inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
1037             memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1038         }
1039     }
1040
1041     inInfo->mOwnedByUs = false;
1042     inQueue.erase(inQueue.begin());
1043     inInfo = NULL;
1044     notifyEmptyBufferDone(inHeader);
1045     inHeader = NULL;
1046
1047     return ERR_OK;
1048 }
1049
1050 int32_t SoftFFmpegAudio::openDecoder() {
1051     if (mCodecAlreadyOpened) {
1052         return ERR_OK;
1053     }
1054
1055     if (!mExtradataReady && !mIgnoreExtradata) {
1056         ALOGI("extradata is ready, size: %d", mCtx->extradata_size);
1057         hexdump(mCtx->extradata, mCtx->extradata_size);
1058         mExtradataReady = true;
1059     }
1060
1061     //find decoder
1062     mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
1063     if (!mCtx->codec) {
1064         ALOGE("ffmpeg audio decoder failed to find codec");
1065         return ERR_CODEC_NOT_FOUND;
1066     }
1067
1068     CHECK(isConfigured());
1069
1070     setDefaultCtx(mCtx, mCtx->codec);
1071
1072     ALOGD("begin to open ffmpeg audio decoder(%s), mCtx sample_rate: %d, "
1073            "channels: %d, , sample_fmt: %s",
1074            avcodec_get_name(mCtx->codec_id),
1075            mCtx->sample_rate, mCtx->channels,
1076            av_get_sample_fmt_name(mCtx->sample_fmt));
1077
1078     int err = avcodec_open2(mCtx, mCtx->codec, NULL);
1079     if (err < 0) {
1080         ALOGE("ffmpeg audio decoder failed to initialize.(%s)", av_err2str(err));
1081         return ERR_DECODER_OPEN_FAILED;
1082     }
1083     mCodecAlreadyOpened = true;
1084
1085     ALOGD("open ffmpeg audio decoder(%s) success, mCtx sample_rate: %d, "
1086             "channels: %d, sample_fmt: %s",
1087             avcodec_get_name(mCtx->codec_id),
1088             mCtx->sample_rate, mCtx->channels,
1089             av_get_sample_fmt_name(mCtx->sample_fmt));
1090
1091     mFrame = avcodec_alloc_frame();
1092     if (!mFrame) {
1093         ALOGE("oom for video frame");
1094         return ERR_OOM;
1095     }
1096
1097         return ERR_OK;
1098 }
1099
1100 void SoftFFmpegAudio::updateTimeStamp(OMX_BUFFERHEADERTYPE *inHeader) {
1101     CHECK_EQ(mInputBufferSize, 0);
1102
1103     //XXX reset to AV_NOPTS_VALUE if the pts is invalid
1104     if (inHeader->nTimeStamp == SF_NOPTS_VALUE) {
1105         inHeader->nTimeStamp = AV_NOPTS_VALUE;
1106     }
1107
1108     //update the audio clock if the pts is valid
1109     if (inHeader->nTimeStamp != AV_NOPTS_VALUE) {
1110         mAudioClock = inHeader->nTimeStamp;
1111     }
1112 }
1113
1114 void SoftFFmpegAudio::initPacket(AVPacket *pkt,
1115         OMX_BUFFERHEADERTYPE *inHeader) {
1116     memset(pkt, 0, sizeof(AVPacket));
1117     av_init_packet(pkt);
1118
1119     if (inHeader) {
1120         pkt->data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
1121         pkt->size = inHeader->nFilledLen;
1122         pkt->pts = inHeader->nTimeStamp; //ingore it, we will compute it
1123     } else {
1124         pkt->data = NULL;
1125         pkt->size = 0;
1126         pkt->pts = AV_NOPTS_VALUE;
1127     }
1128
1129 #if DEBUG_PKT
1130     if (pkt->pts != AV_NOPTS_VALUE)
1131     {
1132         ALOGV("pkt size:%d, pts:%lld", pkt->size, pkt->pts);
1133     } else {
1134         ALOGV("pkt size:%d, pts:N/A", pkt->size);
1135     }
1136 #endif
1137 }
1138
1139 int32_t SoftFFmpegAudio::decodeAudio() {
1140     int len = 0;
1141     int gotFrm = false;
1142         int32_t ret = ERR_OK;
1143     int32_t inputBufferUsedLength = 0;
1144         bool is_flush = (mEOSStatus != INPUT_DATA_AVAILABLE);
1145     List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
1146     BufferInfo *inInfo = NULL;
1147     OMX_BUFFERHEADERTYPE *inHeader = NULL;
1148
1149     CHECK_EQ(mResampledDataSize, 0);
1150
1151     if (!is_flush) {
1152         inInfo = *inQueue.begin();
1153         CHECK(inInfo != NULL);
1154         inHeader = inInfo->mHeader;
1155
1156                 if (mInputBufferSize == 0) {
1157                     updateTimeStamp(inHeader);
1158             mInputBufferSize = inHeader->nFilledLen;
1159         }
1160     }
1161
1162     AVPacket pkt;
1163     initPacket(&pkt, inHeader);
1164     av_frame_unref(mFrame);
1165     avcodec_get_frame_defaults(mFrame);
1166
1167     len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
1168     //a negative error code is returned if an error occurred during decoding
1169     if (len < 0) {
1170         ALOGW("ffmpeg audio decoder err, we skip the frame and play silence instead");
1171         mResampledData = mSilenceBuffer;
1172         mResampledDataSize = kOutputBufferSize;
1173         ret = ERR_OK;
1174     } else {
1175 #if DEBUG_PKT
1176         ALOGV("ffmpeg audio decoder, consume pkt len: %d", len);
1177 #endif
1178         if (!gotFrm) {
1179             ALOGI("ffmpeg audio decoder failed to get frame.");
1180             //stop sending empty packets if the decoder is finished
1181             if (is_flush && mCtx->codec->capabilities & CODEC_CAP_DELAY) {
1182                             ret = ERR_FLUSHED;
1183                     } else {
1184                         ret = ERR_NO_FRM;
1185                     }
1186         } else {
1187             ret = resampleAudio();
1188                 }
1189     }
1190
1191         if (!is_flush) {
1192         if (len < 0) {
1193             //if error, we skip the frame 
1194             inputBufferUsedLength = mInputBufferSize;
1195         } else {
1196             inputBufferUsedLength = len;
1197         }
1198
1199         CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
1200         inHeader->nOffset += inputBufferUsedLength;
1201         inHeader->nFilledLen -= inputBufferUsedLength;
1202         mInputBufferSize -= inputBufferUsedLength;
1203
1204         if (inHeader->nFilledLen == 0) {
1205             CHECK_EQ(mInputBufferSize, 0);
1206             inQueue.erase(inQueue.begin());
1207             inInfo->mOwnedByUs = false;
1208             notifyEmptyBufferDone(inHeader);
1209         }
1210         }
1211
1212     return ret;
1213 }
1214
1215 int32_t SoftFFmpegAudio::resampleAudio() {
1216         int channels = 0;
1217     int64_t channelLayout = 0;
1218     size_t dataSize = 0;
1219
1220     dataSize = av_samples_get_buffer_size(NULL, av_frame_get_channels(mFrame),
1221             mFrame->nb_samples, (enum AVSampleFormat)mFrame->format, 1);
1222
1223 #if DEBUG_FRM
1224     ALOGV("ffmpeg audio decoder, nb_samples:%d, get buffer size:%d",
1225             mFrame->nb_samples, dataSize);
1226 #endif
1227
1228         channels = av_get_channel_layout_nb_channels(mFrame->channel_layout);
1229     channelLayout =
1230         (mFrame->channel_layout && av_frame_get_channels(mFrame) == channels) ?
1231         mFrame->channel_layout : av_get_default_channel_layout(av_frame_get_channels(mFrame));
1232
1233     if (mFrame->format != mAudioSrcFmt
1234             || channelLayout != mAudioSrcChannelLayout
1235             || mFrame->sample_rate != mAudioSrcFreq) {
1236         if (mSwrCtx) {
1237             swr_free(&mSwrCtx);
1238         }
1239         mSwrCtx = swr_alloc_set_opts(NULL,
1240                 mAudioTgtChannelLayout, mAudioTgtFmt,                     mAudioTgtFreq,
1241                 channelLayout,       (enum AVSampleFormat)mFrame->format, mFrame->sample_rate,
1242                 0, NULL);
1243         if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
1244             ALOGE("Cannot create sample rate converter for conversion "
1245                     "of %d Hz %s %d channels to %d Hz %s %d channels!",
1246                     mFrame->sample_rate,
1247                     av_get_sample_fmt_name((enum AVSampleFormat)mFrame->format),
1248                     av_frame_get_channels(mFrame),
1249                     mAudioTgtFreq,
1250                     av_get_sample_fmt_name(mAudioTgtFmt),
1251                     mAudioTgtChannels);
1252             return ERR_SWR_INIT_FAILED;
1253         }
1254
1255         char src_layout_name[1024] = {0};
1256         char tgt_layout_name[1024] = {0};
1257         av_get_channel_layout_string(src_layout_name, sizeof(src_layout_name),
1258                 mCtx->channels, channelLayout);
1259         av_get_channel_layout_string(tgt_layout_name, sizeof(tgt_layout_name),
1260                 mAudioTgtChannels, mAudioTgtChannelLayout);
1261         ALOGI("Create sample rate converter for conversion "
1262                 "of %d Hz %s %d channels(%s) "
1263                 "to %d Hz %s %d channels(%s)!",
1264                 mFrame->sample_rate,
1265                 av_get_sample_fmt_name((enum AVSampleFormat)mFrame->format),
1266                 av_frame_get_channels(mFrame),
1267                 src_layout_name,
1268                 mAudioTgtFreq,
1269                 av_get_sample_fmt_name(mAudioTgtFmt),
1270                 mAudioTgtChannels,
1271                 tgt_layout_name);
1272
1273         mAudioSrcChannelLayout = channelLayout;
1274         mAudioSrcChannels = av_frame_get_channels(mFrame);
1275         mAudioSrcFreq = mFrame->sample_rate;
1276         mAudioSrcFmt = (enum AVSampleFormat)mFrame->format;
1277     }
1278
1279     if (mSwrCtx) {
1280         const uint8_t **in = (const uint8_t **)mFrame->extended_data;
1281         uint8_t *out[] = {mAudioBuffer};
1282         int out_count = sizeof(mAudioBuffer) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt);
1283         int out_size  = av_samples_get_buffer_size(NULL, mAudioTgtChannels, out_count, mAudioTgtFmt, 0);
1284         int len2 = 0;
1285         if (out_size < 0) {
1286             ALOGE("av_samples_get_buffer_size() failed");
1287             return ERR_INVALID_PARAM;
1288         }
1289
1290         len2 = swr_convert(mSwrCtx, out, out_count, in, mFrame->nb_samples);
1291         if (len2 < 0) {
1292             ALOGE("audio_resample() failed");
1293             return ERR_RESAMPLE_FAILED;
1294         }
1295         if (len2 == out_count) {
1296             ALOGE("warning: audio buffer is probably too small");
1297             swr_init(mSwrCtx);
1298         }
1299         mResampledData = mAudioBuffer;
1300         mResampledDataSize = len2 * mAudioTgtChannels * av_get_bytes_per_sample(mAudioTgtFmt);
1301
1302 #if DEBUG_FRM
1303         ALOGV("ffmpeg audio decoder(resample), mFrame->nb_samples:%d, len2:%d, mResampledDataSize:%d, "
1304                 "src channel:%u, src fmt:%s, tgt channel:%u, tgt fmt:%s",
1305                 mFrame->nb_samples, len2, mResampledDataSize,
1306                 av_frame_get_channels(mFrame),
1307                 av_get_sample_fmt_name((enum AVSampleFormat)mFrame->format),
1308                 mAudioTgtChannels,
1309                 av_get_sample_fmt_name(mAudioTgtFmt));
1310 #endif
1311     } else {
1312         mResampledData = mFrame->data[0];
1313         mResampledDataSize = dataSize;
1314
1315 #if DEBUG_FRM
1316     ALOGV("ffmpeg audio decoder(no resample),"
1317             "nb_samples(before resample):%d, mResampledDataSize:%d",
1318             mFrame->nb_samples, mResampledDataSize);
1319 #endif
1320     }
1321
1322         return ERR_OK;
1323 }
1324
1325 void SoftFFmpegAudio::drainOneOutputBuffer() {
1326     List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
1327         BufferInfo *outInfo = *outQueue.begin();
1328         CHECK(outInfo != NULL);
1329         OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
1330
1331         CHECK_GT(mResampledDataSize, 0);
1332
1333     size_t copy = mResampledDataSize;
1334     if (mResampledDataSize > kOutputBufferSize) {
1335         copy = kOutputBufferSize;
1336         }
1337
1338     outHeader->nOffset = 0;
1339     outHeader->nFilledLen = copy;
1340     outHeader->nTimeStamp = mAudioClock; 
1341     memcpy(outHeader->pBuffer, mResampledData, copy);
1342     outHeader->nFlags = 0;
1343
1344     //update mResampledSize
1345     mResampledData += copy;
1346     mResampledDataSize -= copy;
1347
1348     //update audio pts
1349     size_t frames = copy / (av_get_bytes_per_sample(mAudioTgtFmt) * mAudioTgtChannels);
1350     mAudioClock += (frames * 1000000ll) / mAudioTgtFreq;
1351
1352 #if DEBUG_FRM
1353     ALOGV("ffmpeg audio decoder, fill out buffer, copy:%u, pts: %lld",
1354             copy, outHeader->nTimeStamp);
1355 #endif
1356
1357     outQueue.erase(outQueue.begin());
1358     outInfo->mOwnedByUs = false;
1359     notifyFillBufferDone(outHeader);
1360 }
1361
1362 void SoftFFmpegAudio::drainEOSOutputBuffer() {
1363     List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
1364         BufferInfo *outInfo = *outQueue.begin();
1365         CHECK(outInfo != NULL);
1366         OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
1367
1368         CHECK_EQ(mResampledDataSize, 0);
1369
1370     ALOGD("ffmpeg audio decoder fill eos outbuf");
1371
1372     outHeader->nTimeStamp = 0;
1373     outHeader->nFilledLen = 0;
1374     outHeader->nFlags = OMX_BUFFERFLAG_EOS;
1375
1376     outQueue.erase(outQueue.begin());
1377     outInfo->mOwnedByUs = false;
1378     notifyFillBufferDone(outHeader);
1379
1380     mEOSStatus = OUTPUT_FRAMES_FLUSHED;
1381 }
1382
1383 void SoftFFmpegAudio::drainAllOutputBuffers() {
1384     List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
1385
1386     if (!mCodecAlreadyOpened) {
1387         drainEOSOutputBuffer();
1388         mEOSStatus = OUTPUT_FRAMES_FLUSHED;
1389         return;
1390     }
1391
1392     if(!(mCtx->codec->capabilities & CODEC_CAP_DELAY)) {
1393         drainEOSOutputBuffer();
1394         mEOSStatus = OUTPUT_FRAMES_FLUSHED;
1395         return;
1396     }
1397
1398     while (!outQueue.empty()) {
1399         if (mResampledDataSize == 0) {
1400             int32_t err = decodeAudio();
1401             if (err < ERR_OK) {
1402                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
1403                 mSignalledError = true;
1404                             return;
1405             } else if (err == ERR_FLUSHED) {
1406                 drainEOSOutputBuffer();
1407                 return;
1408                         } else {
1409                 CHECK_EQ(err, ERR_OK);
1410                         }
1411         }
1412
1413                 if (mResampledDataSize > 0) {
1414             drainOneOutputBuffer();
1415         }
1416     }
1417 }
1418
1419 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
1420     BufferInfo *inInfo = NULL;
1421     OMX_BUFFERHEADERTYPE *inHeader = NULL;
1422
1423     if (mSignalledError || mOutputPortSettingsChange != NONE) {
1424         return;
1425     }
1426
1427     if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) {
1428         return;
1429     }
1430
1431     List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
1432     List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
1433
1434     while (((mEOSStatus != INPUT_DATA_AVAILABLE) || !inQueue.empty())
1435             && !outQueue.empty()) {
1436
1437         if (mEOSStatus == INPUT_EOS_SEEN) {
1438             drainAllOutputBuffers();
1439             return;
1440         }
1441
1442         inInfo   = *inQueue.begin();
1443         inHeader = inInfo->mHeader;
1444
1445         if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
1446             ALOGD("ffmpeg audio decoder empty eos inbuf");
1447             inQueue.erase(inQueue.begin());
1448             inInfo->mOwnedByUs = false;
1449             notifyEmptyBufferDone(inHeader);
1450             mEOSStatus = INPUT_EOS_SEEN;
1451             continue;
1452         }
1453
1454         if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
1455                     if (handleExtradata() != ERR_OK) {
1456                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
1457                 mSignalledError = true;
1458                 return;
1459             }
1460             continue;
1461         }
1462
1463         if (!mCodecAlreadyOpened) {
1464             if (openDecoder() != ERR_OK) {
1465                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
1466                 mSignalledError = true;
1467                     return;
1468             }
1469         }
1470
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_NO_FRM) {
1478                 CHECK_EQ(mResampledDataSize, 0);
1479                 continue;
1480                         } else {
1481                 CHECK_EQ(err, ERR_OK);
1482                         }
1483                 }
1484
1485                 if (mResampledDataSize > 0) {
1486                         drainOneOutputBuffer();
1487                 }
1488     }
1489 }
1490
1491 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
1492     ALOGV("ffmpeg audio decoder flush port(%lu)", portIndex);
1493     if (portIndex == kInputPortIndex) {
1494         if (mCtx) {
1495             //Make sure that the next buffer output does not still
1496             //depend on fragments from the last one decoded.
1497             avcodec_flush_buffers(mCtx);
1498         }
1499
1500             mAudioClock = 0;
1501             mInputBufferSize = 0;
1502             mResampledDataSize = 0;
1503             mResampledData = NULL;
1504         mEOSStatus = INPUT_DATA_AVAILABLE;
1505     }
1506 }
1507
1508 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
1509     if (portIndex != kOutputPortIndex) {
1510         return;
1511     }
1512
1513     switch (mOutputPortSettingsChange) {
1514         case NONE:
1515             break;
1516
1517         case AWAITING_DISABLED:
1518         {
1519             CHECK(!enabled);
1520             mOutputPortSettingsChange = AWAITING_ENABLED;
1521             break;
1522         }
1523
1524         default:
1525         {
1526             CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
1527             CHECK(enabled);
1528             mOutputPortSettingsChange = NONE;
1529             break;
1530         }
1531     }
1532 }
1533
1534 }  // namespace android
1535
1536 android::SoftOMXComponent *createSoftOMXComponent(
1537         const char *name, const OMX_CALLBACKTYPE *callbacks,
1538         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
1539     return new android::SoftFFmpegAudio(name, callbacks, appData, component);
1540 }