OSDN Git Service

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