OSDN Git Service

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