OSDN Git Service

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