OSDN Git Service

add support for real-audio(RMVB), only cook audio codec
[android-x86/external-stagefright-plugins.git] / libstagefright / codecs / ffmpegdec / adec / SoftFFmpegAudio.cpp
1 /*
2  * Copyright 2012 Michael Chen <omxcodec@gmail.com>
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #define LOG_NDEBUG 0
18 #define LOG_TAG "SoftFFmpegAudio"
19 #include <utils/Log.h>
20
21 #include "SoftFFmpegAudio.h"
22
23 #include <media/stagefright/foundation/ADebug.h>
24 #include <media/stagefright/foundation/hexdump.h>
25 #include <media/stagefright/MediaDefs.h>
26
27 #include "utils/common_utils.h"
28 #include "utils/ffmpeg_utils.h"
29
30 //#undef realloc
31 //#include <stdlib.h>
32
33 #define DEBUG_PKT 0
34 #define DEBUG_FRM 0
35
36 namespace android {
37
38 template<class T>
39 static void InitOMXParams(T *params) {
40     params->nSize = sizeof(T);
41     params->nVersion.s.nVersionMajor = 1;
42     params->nVersion.s.nVersionMinor = 0;
43     params->nVersion.s.nRevision = 0;
44     params->nVersion.s.nStep = 0;
45 }
46
47 SoftFFmpegAudio::SoftFFmpegAudio(
48         const char *name,
49         const OMX_CALLBACKTYPE *callbacks,
50         OMX_PTR appData,
51         OMX_COMPONENTTYPE **component)
52     : SimpleSoftOMXComponent(name, callbacks, appData, component),
53       mMode(MODE_MPEG),
54       mCtx(NULL),
55       mSwrCtx(NULL),
56       mCodecOpened(false),
57       mExtradataReady(false),
58       mIgnoreExtradata(false),
59       mFlushComplete(false),
60       mSignalledError(false),
61       mReceivedEOS(false),
62       mFrame(NULL),
63       mAnchorTimeUs(0),
64       mNumFramesOutput(0),
65       mInputBufferSize(0),
66       mAudioBufferSize(0),
67       mNumChannels(2),
68       mSamplingRate(44100),
69       mBitRate(0),
70       mSamplingFmt(AV_SAMPLE_FMT_S16),
71       mAudioConfigChanged(false),
72       mOutputPortSettingsChange(NONE) {
73     if (!strcmp(name, "OMX.ffmpeg.mp3.decoder")) {
74         mMode = MODE_MPEG;
75         mIgnoreExtradata = true;
76     } else if (!strcmp(name, "OMX.ffmpeg.mp1.decoder")) {
77         mMode = MODE_MPEGL1;
78     } else if (!strcmp(name, "OMX.ffmpeg.mp2.decoder")) {
79         mMode = MODE_MPEGL2;
80     } else if (!strcmp(name, "OMX.ffmpeg.aac.decoder")) {
81         mMode = MODE_AAC;
82     } else if (!strcmp(name, "OMX.ffmpeg.ape.decoder")) {
83         mMode = MODE_APE;
84     } else if (!strcmp(name, "OMX.ffmpeg.wma.decoder")) {
85         mMode = MODE_WMA;
86     } else if (!strcmp(name, "OMX.ffmpeg.dts.decoder")) {
87         mMode = MODE_DTS;
88     } else if (!strcmp(name, "OMX.ffmpeg.ra.decoder")) {
89         mMode = MODE_RA;
90     } else {
91         CHECK(!strcmp(name, "OMX.ffmpeg.ac3.decoder"));
92         mMode = MODE_AC3;
93     }
94
95     LOGV("SoftFFmpegAudio component: %s", name);
96
97     initPorts();
98     CHECK_EQ(initDecoder(), (status_t)OK);
99 }
100
101 SoftFFmpegAudio::~SoftFFmpegAudio() {
102     av_freep(&mFrame);
103     LOGV("~SoftFFmpegAudio");
104     deInitDecoder();
105     deInitFFmpeg();
106 }
107
108 void SoftFFmpegAudio::initPorts() {
109     OMX_PARAM_PORTDEFINITIONTYPE def;
110     InitOMXParams(&def);
111
112     def.nPortIndex = 0;
113     def.eDir = OMX_DirInput;
114     def.nBufferCountMin = kNumBuffers;
115     def.nBufferCountActual = def.nBufferCountMin;
116     def.nBufferSize = 8192;
117     def.bEnabled = OMX_TRUE;
118     def.bPopulated = OMX_FALSE;
119     def.eDomain = OMX_PortDomainAudio;
120     def.bBuffersContiguous = OMX_FALSE;
121     def.nBufferAlignment = 1;
122
123     switch (mMode) {
124     case MODE_MPEG:
125         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG);
126         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
127         break;
128     case MODE_MPEGL1:
129         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
130         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
131         break;
132     case MODE_MPEGL2:
133         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
134         def.format.audio.eEncoding = OMX_AUDIO_CodingMP3;
135         break;
136     case MODE_AAC:
137         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AAC);
138         def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
139         break;
140     case MODE_AC3:
141         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_AC3);
142         // TODO
143         //def.format.audio.eEncoding = OMX_AUDIO_CodingAC3;
144         def.format.audio.eEncoding = OMX_AUDIO_CodingAutoDetect; // right?? orz
145         break;
146     case MODE_WMA:
147         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_WMA);
148         def.format.audio.eEncoding = OMX_AUDIO_CodingWMA;
149         break;
150     case MODE_RA:
151         def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_RA);
152         def.format.audio.eEncoding = OMX_AUDIO_CodingRA;
153         break;
154     default:
155         CHECK(!"Should not be here. Unsupported mime type and compression format");
156         break;
157     }
158
159     def.format.audio.pNativeRender = NULL;
160     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
161
162     addPort(def);
163
164     def.nPortIndex = 1;
165     def.eDir = OMX_DirOutput;
166     def.nBufferCountMin = kNumBuffers;
167     def.nBufferCountActual = def.nBufferCountMin;
168     def.nBufferSize = kOutputBufferSize;
169     def.bEnabled = OMX_TRUE;
170     def.bPopulated = OMX_FALSE;
171     def.eDomain = OMX_PortDomainAudio;
172     def.bBuffersContiguous = OMX_FALSE;
173     def.nBufferAlignment = 2;
174
175     def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
176     def.format.audio.pNativeRender = NULL;
177     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
178     def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
179
180     addPort(def);
181 }
182
183 void SoftFFmpegAudio::setAVCtxToDefault(AVCodecContext *avctx, const AVCodec *codec) {
184     int fast = 0;
185
186     avctx->workaround_bugs   = 1;
187     avctx->lowres            = 0;
188     if(avctx->lowres > codec->max_lowres){
189         LOGW("The maximum value for lowres supported by the decoder is %d",
190                 codec->max_lowres);
191         avctx->lowres= codec->max_lowres;
192     }
193     avctx->idct_algo         = 0;
194     avctx->skip_frame        = AVDISCARD_DEFAULT;
195     avctx->skip_idct         = AVDISCARD_DEFAULT;
196     avctx->skip_loop_filter  = AVDISCARD_DEFAULT;
197     avctx->error_concealment = 3;
198
199     if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
200     if (fast)   avctx->flags2 |= CODEC_FLAG2_FAST;
201     if(codec->capabilities & CODEC_CAP_DR1)
202         avctx->flags |= CODEC_FLAG_EMU_EDGE;
203 }
204
205 status_t SoftFFmpegAudio::initDecoder() {
206     status_t status;
207
208     status = initFFmpeg();
209     if (status != OK)
210         return NO_INIT;
211
212     mCtx = avcodec_alloc_context3(NULL);
213     if (!mCtx)
214     {
215         LOGE("avcodec_alloc_context failed.");
216         return NO_MEMORY;
217     }
218
219     mCtx->codec_type = AVMEDIA_TYPE_AUDIO;
220     switch (mMode) {
221     case MODE_MPEG:
222         mCtx->codec_id = CODEC_ID_MP3;
223         break;
224     case MODE_MPEGL1:
225         mCtx->codec_id = CODEC_ID_MP1;
226         break;
227     case MODE_MPEGL2:
228         mCtx->codec_id = CODEC_ID_MP2;
229         break;
230     case MODE_AAC:
231         mCtx->codec_id = CODEC_ID_AAC;
232         break;
233     case MODE_AC3:
234         mCtx->codec_id = CODEC_ID_AC3;
235         break;
236     case MODE_WMA:
237         mCtx->codec_id = CODEC_ID_WMAV2; // FIXME, CODEC_ID_WMAV1 or CODEC_ID_WMAV2?
238         break;
239     case MODE_RA:
240         mCtx->codec_id = CODEC_ID_COOK; // FIXME
241         mCtx->block_align = 186;
242         mBitRate = 64082;
243         break;
244     default:
245         CHECK(!"Should not be here. Unsupported codec");
246         break;
247     }
248
249     mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
250     if (!mCtx->codec)
251     {
252         LOGE("find codec failed");
253         return BAD_TYPE;
254     }
255
256     setAVCtxToDefault(mCtx, mCtx->codec);
257
258     mCtx->channels = mNumChannels;
259     mCtx->sample_rate = mSamplingRate;
260     mCtx->bit_rate = mBitRate;
261     mCtx->sample_fmt = mSamplingFmt;
262
263     mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
264     mAudioSrcFreq = mAudioTgtFreq = mSamplingRate;
265     mAudioSrcChannels = mAudioTgtChannels = mNumChannels;
266     mAudioSrcChannelLayout = mAudioTgtChannelLayout = 
267         av_get_default_channel_layout(mNumChannels);
268
269     memset(mSilenceBuffer, 0, kOutputBufferSize);
270
271     return OK;
272 }
273
274 void SoftFFmpegAudio::deInitDecoder() {
275     if (mCtx) {
276         //avcodec_flush_buffers(mCtx); // is it necessary? crash sometimes if call it
277         if (!mCtx->extradata) {
278             av_free(mCtx->extradata);
279             mCtx->extradata = NULL;
280             mCtx->extradata_size = 0;
281         }
282         avcodec_close(mCtx);
283         av_free(mCtx);
284         mCtx = NULL;
285     }
286
287     if (mSwrCtx) {
288         swr_free(&mSwrCtx);
289         mSwrCtx = NULL;
290     }
291
292 }
293
294 OMX_ERRORTYPE SoftFFmpegAudio::internalGetParameter(
295         OMX_INDEXTYPE index, OMX_PTR params) {
296     int32_t channels = 0;
297     int32_t sampling_rate = 0;
298
299     switch (index) {
300         case OMX_IndexParamAudioAac:
301         {
302             OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
303                 (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
304
305             if (aacParams->nPortIndex != 0) {
306                 return OMX_ErrorUndefined;
307             }
308
309             aacParams->nBitRate = 0;
310             aacParams->nAudioBandWidth = 0;
311             aacParams->nAACtools = 0;
312             aacParams->nAACERtools = 0;
313             aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
314             aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
315             aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
316
317             aacParams->nChannels = mNumChannels;
318             aacParams->nSampleRate = mSamplingRate;
319
320             return OMX_ErrorNone;
321         }
322         case OMX_IndexParamAudioWma:
323         {
324             OMX_AUDIO_PARAM_WMATYPE *wmaParams =
325                 (OMX_AUDIO_PARAM_WMATYPE *)params;
326
327             if (wmaParams->nPortIndex != 0) {
328                 return OMX_ErrorUndefined;
329             }
330
331             wmaParams->nChannels = 0;
332             wmaParams->nSamplingRate = 0;
333             wmaParams->nBitRate = 0;
334             wmaParams->eFormat = OMX_AUDIO_WMAFormatUnused;
335
336             return OMX_ErrorNone;
337         }
338         case OMX_IndexParamAudioPcm:
339         {
340             OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
341                 (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
342
343             if (pcmParams->nPortIndex > 1) {
344                 return OMX_ErrorUndefined;
345             }
346
347             pcmParams->eNumData = OMX_NumericalDataSigned;
348             pcmParams->eEndian = OMX_EndianBig;
349             pcmParams->bInterleaved = OMX_TRUE;
350             pcmParams->nBitPerSample = 16;
351             pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
352             pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
353             pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
354
355             LOGI("~~~~~~~~~~~~~ audio config change");
356
357             channels = mNumChannels >= 2 ? 2 : 1;
358             sampling_rate = mSamplingRate;
359             // 4000 <= nSamplingRate <= 48000
360             if (mSamplingRate < 4000) {
361                 sampling_rate = 4000;
362             } else if (mSamplingRate > 48000) {
363                 sampling_rate = 48000;
364             }
365
366             // update src and target(except aac), only once!
367             mAudioSrcChannels = mAudioTgtChannels =  channels;
368             mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
369             mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
370             mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
371
372             pcmParams->nChannels = channels;
373             pcmParams->nSamplingRate = sampling_rate;
374
375             return OMX_ErrorNone;
376         }
377
378         default:
379             return SimpleSoftOMXComponent::internalGetParameter(index, params);
380     }
381 }
382
383 OMX_ERRORTYPE SoftFFmpegAudio::internalSetParameter(
384         OMX_INDEXTYPE index, const OMX_PTR params) {
385     int32_t channels = 0;
386     int32_t sampling_rate = 0;
387
388     switch (index) {
389         case OMX_IndexParamStandardComponentRole:
390         {
391             const OMX_PARAM_COMPONENTROLETYPE *roleParams =
392                 (const OMX_PARAM_COMPONENTROLETYPE *)params;
393
394             bool supported = true;
395             switch (mMode) {
396             case MODE_MPEG:
397                 if (strncmp((const char *)roleParams->cRole,
398                         "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1))
399                     supported =  false;
400                 break;
401             case MODE_MPEGL1:
402                 if (strncmp((const char *)roleParams->cRole,
403                         "audio_decoder.mp1", OMX_MAX_STRINGNAME_SIZE - 1))
404                     supported =  false;
405                 break;
406             case MODE_MPEGL2:
407                 if (strncmp((const char *)roleParams->cRole,
408                         "audio_decoder.mp2", OMX_MAX_STRINGNAME_SIZE - 1))
409                     supported =  false;
410                 break;
411             case MODE_AAC:
412                 if (strncmp((const char *)roleParams->cRole,
413                         "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1))
414                     supported =  false;
415                 break;
416             case MODE_AC3:
417                 if (strncmp((const char *)roleParams->cRole,
418                         "audio_decoder.ac3", OMX_MAX_STRINGNAME_SIZE - 1))
419                     supported =  false;
420                 break;
421             case MODE_WMA:
422                 if (strncmp((const char *)roleParams->cRole,
423                         "audio_decoder.wma", OMX_MAX_STRINGNAME_SIZE - 1))
424                     supported =  false;
425                 break;
426             case MODE_RA:
427                 if (strncmp((const char *)roleParams->cRole,
428                         "audio_decoder.ra", OMX_MAX_STRINGNAME_SIZE - 1))
429                     supported =  false;
430                 break;
431             default:
432                 CHECK(!"Should not be here. Unsupported role.");
433                 break;
434             }
435             if (!supported) {
436                 LOGE("unsupported role: %s", (const char *)roleParams->cRole);
437                 return OMX_ErrorUndefined;
438             }
439
440             return OMX_ErrorNone;
441         }
442         case OMX_IndexParamAudioAac:
443         {
444             const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
445                 (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
446
447             if (aacParams->nPortIndex != 0) {
448                 return OMX_ErrorUndefined;
449             }
450
451             mNumChannels = aacParams->nChannels;
452             mSamplingRate = aacParams->nSampleRate;
453
454             channels = mNumChannels >= 2 ? 2 : 1;
455             sampling_rate = mSamplingRate;
456             // 4000 <= nSamplingRate <= 48000
457             if (mSamplingRate < 4000) {
458                 sampling_rate = 4000;
459             } else if (mSamplingRate > 48000) {
460                 sampling_rate = 48000;
461             }
462
463             // update src and target(only aac), only once!
464             mAudioSrcChannels = mAudioTgtChannels = channels;
465             mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
466             mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
467             mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
468
469             LOGV("got OMX_IndexParamAudioAac, mNumChannels: %d, mSamplingRate: %d",
470                 mNumChannels, mSamplingRate);
471
472             return OMX_ErrorNone;
473         }
474         case OMX_IndexParamAudioWma:
475         {
476             OMX_AUDIO_PARAM_WMATYPE *wmaParams =
477                 (OMX_AUDIO_PARAM_WMATYPE *)params;
478
479             if (wmaParams->nPortIndex != 0) {
480                 return OMX_ErrorUndefined;
481             }
482
483             if (wmaParams->eFormat == OMX_AUDIO_WMAFormat7) {
484                mCtx->codec_id = CODEC_ID_WMAV2;
485             } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat8) {
486                mCtx->codec_id = CODEC_ID_WMAPRO;
487             } else if (wmaParams->eFormat == OMX_AUDIO_WMAFormat9) {
488                mCtx->codec_id = CODEC_ID_WMALOSSLESS;
489             } else {
490                 LOGE("unsupported wma codec: 0x%x", wmaParams->eFormat);
491                 return OMX_ErrorUndefined;
492             }
493
494             mNumChannels = wmaParams->nChannels;
495             mSamplingRate = wmaParams->nSamplingRate;
496             mBitRate = wmaParams->nBitRate;
497
498             // wma need bitrate
499             mCtx->bit_rate = mBitRate;
500
501             channels = mNumChannels >= 2 ? 2 : 1;
502             sampling_rate = mSamplingRate;
503             // 4000 <= nSamplingRate <= 48000
504             if (mSamplingRate < 4000) {
505                 sampling_rate = 4000;
506             } else if (mSamplingRate > 48000) {
507                 sampling_rate = 48000;
508             }
509
510             // update src and target(only wma), only once!
511             mAudioSrcChannels = mAudioTgtChannels = channels;
512             mAudioSrcFreq = mAudioTgtFreq = sampling_rate;
513             mAudioSrcFmt = mAudioTgtFmt = AV_SAMPLE_FMT_S16;
514             mAudioSrcChannelLayout = mAudioTgtChannelLayout = av_get_default_channel_layout(channels);
515
516             LOGV("got OMX_IndexParamAudioWma, mNumChannels: %d, mSamplingRate: %d, mBitRate: %d",
517                 mNumChannels, mSamplingRate, mBitRate);
518
519             return OMX_ErrorNone;
520         }
521         default:
522             LOGI("internalSetParameter, index: 0x%x", index);
523             return SimpleSoftOMXComponent::internalSetParameter(index, params);
524     }
525 }
526
527 void SoftFFmpegAudio::onQueueFilled(OMX_U32 portIndex) {
528     int len = 0;
529     int err = 0;
530     size_t dataSize = 0;
531     int64_t decChannelLayout;
532     int32_t inputBufferUsedLength = 0;
533     BufferInfo *inInfo = NULL;
534     OMX_BUFFERHEADERTYPE *inHeader = NULL;
535
536     if (mSignalledError || mOutputPortSettingsChange != NONE) {
537         return;
538     }
539
540     List<BufferInfo *> &inQueue = getPortQueue(0);
541     List<BufferInfo *> &outQueue = getPortQueue(1);
542
543     while ((!inQueue.empty() || mInputBufferSize > 0 ||
544             mAudioBufferSize > 0 || mFlushComplete) && !outQueue.empty()) {
545         if (!inQueue.empty() || mInputBufferSize > 0) {
546             inInfo = *inQueue.begin();
547             inHeader = inInfo->mHeader;
548         } else {
549             inInfo = NULL;
550             inHeader = NULL;
551         }
552
553         BufferInfo *outInfo = *outQueue.begin();
554         OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
555
556         if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
557             inQueue.erase(inQueue.begin());
558             inInfo->mOwnedByUs = false;
559             notifyEmptyBufferDone(inHeader);
560             mReceivedEOS = true;
561         }
562
563         if (mReceivedEOS && (mFlushComplete || !(mCtx->codec->capabilities & CODEC_CAP_DELAY))) {
564             outHeader->nFilledLen = 0;
565             outHeader->nFlags = OMX_BUFFERFLAG_EOS;
566
567             outQueue.erase(outQueue.begin());
568             outInfo->mOwnedByUs = false;
569             notifyFillBufferDone(outHeader);
570             return;
571         }
572
573         if (inHeader && inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
574             LOGI("got extradata, ignore: %d, size: %lu", mIgnoreExtradata, inHeader->nFilledLen);
575             hexdump(inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
576             if (!mExtradataReady && !mIgnoreExtradata) {
577                 int orig_extradata_size = mCtx->extradata_size;
578                 mCtx->extradata_size += inHeader->nFilledLen;
579                 mCtx->extradata = (uint8_t *)av_realloc(mCtx->extradata,
580                         mCtx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
581                 if (!mCtx->extradata) {
582                     LOGE("ffmpeg audio decoder failed to alloc extradata memory.");
583                     notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
584                     mSignalledError = true;
585                     return;
586                 }
587
588                 memcpy(mCtx->extradata + orig_extradata_size,
589                         inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen);
590                 memset(mCtx->extradata + mCtx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
591
592                 inInfo->mOwnedByUs = false;
593                 inQueue.erase(inQueue.begin());
594                 inInfo = NULL;
595                 notifyEmptyBufferDone(inHeader);
596                 inHeader = NULL;
597
598                 continue;
599             }
600             if (mIgnoreExtradata) {
601                 LOGI("got extradata, size: %lu, but ignore it", inHeader->nFilledLen);
602                 inInfo->mOwnedByUs = false;
603                 inQueue.erase(inQueue.begin());
604                 inInfo = NULL;
605                 notifyEmptyBufferDone(inHeader);
606                 inHeader = NULL;
607
608                 continue;
609             }
610         }
611
612         if (!mCodecOpened) {
613             if (!mExtradataReady && !mIgnoreExtradata) {
614                 LOGI("extradata is ready");
615                 hexdump(mCtx->extradata, mCtx->extradata_size);
616                 mExtradataReady = true;
617             }
618
619             // find decoder again as codec_id may have changed
620             mCtx->codec = avcodec_find_decoder(mCtx->codec_id);
621             if (!mCtx->codec) {
622                 LOGE("ffmpeg audio decoder failed to find codec");
623                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
624                 mSignalledError = true;
625                 return;
626             }
627
628             setAVCtxToDefault(mCtx, mCtx->codec);
629
630             LOGI("open ffmpeg decoder now");
631             err = avcodec_open2(mCtx, mCtx->codec, NULL);
632             if (err < 0) {
633                 LOGE("ffmpeg audio decoder failed to initialize. (%d)", err);
634                 notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
635                 mSignalledError = true;
636                 return;
637             }
638             mCodecOpened = true;
639             LOGI("open ffmpeg audio decoder, mCtx sample_rate: %d, channels: %d, channel_layout: %llu, sample_fmt: %s",
640                 mCtx->sample_rate, mCtx->channels, mCtx->channel_layout, av_get_sample_fmt_name(mCtx->sample_fmt));
641         }
642
643         /* update the audio clock with the pts */
644         if (inHeader && inHeader->nOffset == 0) {
645             mAnchorTimeUs = inHeader->nTimeStamp;
646             mInputBufferSize = inHeader->nFilledLen;
647         }
648
649         if (inHeader && mAudioBufferSize == 0 && !mFlushComplete) {
650             AVPacket pkt;
651             memset(&pkt, 0, sizeof(pkt));
652             av_init_packet(&pkt);
653             if (!mFlushComplete) {
654                 pkt.data = (uint8_t *)inHeader->pBuffer + inHeader->nOffset;
655                 pkt.size = inHeader->nFilledLen;
656                 pkt.pts = inHeader->nTimeStamp; // ingore it, we will compute it
657             } else {
658                 pkt.data = NULL;
659                 pkt.size = 0;
660                 pkt.pts = AV_NOPTS_VALUE;
661             }
662 #if DEBUG_PKT
663             LOGV("pkt size: %d, pts: %lld", pkt.size, pkt.pts);
664 #endif
665             if (!mFrame) {
666                 if (!(mFrame = avcodec_alloc_frame())) {
667                     LOGE("ffmpeg audio decoder failed to alloc memory.");
668                     notify(OMX_EventError, OMX_ErrorInsufficientResources, 0, NULL);
669                     mSignalledError = true;
670                     return;
671                 }
672             } else {
673                 avcodec_get_frame_defaults(mFrame);
674             }
675
676             int gotFrm = false;
677             inputBufferUsedLength = 0;
678             len = avcodec_decode_audio4(mCtx, mFrame, &gotFrm, &pkt);
679             if (len < 0) {
680                 LOGE("ffmpeg audio decoder failed to decode frame. consume pkt len: %d", len);
681
682                 /* if !mAudioConfigChanged, Don't fill the out buffer */
683                 if (!mAudioConfigChanged) {
684                     inInfo->mOwnedByUs = false;
685                     inQueue.erase(inQueue.begin());
686                     inInfo = NULL;
687                     notifyEmptyBufferDone(inHeader);
688                     inHeader = NULL;
689
690                     mInputBufferSize = 0; // need?
691                     continue;
692                 }
693
694                 //inputBufferUsedLength = inHeader->nFilledLen;
695                 /* if error, we skip the frame and play silence instead */
696                 mPAudioBuffer = mSilenceBuffer;
697                 mAudioBufferSize = kOutputBufferSize;
698             }
699
700 #if DEBUG_PKT
701             LOGV("ffmpeg audio decoder, consume pkt len: %d", len);
702 #endif
703
704             if (len < 0)
705                 inputBufferUsedLength = inHeader->nFilledLen;
706             else
707                 inputBufferUsedLength = len;
708
709             CHECK_GE(inHeader->nFilledLen, inputBufferUsedLength);
710             inHeader->nOffset += inputBufferUsedLength;
711             inHeader->nFilledLen -= inputBufferUsedLength;
712             mInputBufferSize -= inputBufferUsedLength;
713             if (inHeader->nFilledLen == 0) {
714                 inInfo->mOwnedByUs = false;
715                 inQueue.erase(inQueue.begin());
716                 inInfo = NULL;
717                 notifyEmptyBufferDone(inHeader);
718                 inHeader = NULL;
719
720                 mInputBufferSize = 0;
721             }
722
723             if (!gotFrm) {
724                 LOGI("ffmpeg audio decoder failed to get frame.");
725                 /* stop sending empty packets if the decoder is finished */
726                 if (!pkt.data && mCtx->codec->capabilities & CODEC_CAP_DELAY)
727                     mFlushComplete = true;
728                 continue;
729             }
730
731             /**
732              * FIXME, check mAudioConfigChanged when the first time you call the audio4!
733              * mCtx->sample_rate and mCtx->channels may be changed by audio decoder later, why???
734              */
735             if (!mAudioConfigChanged) {
736                 //if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate || mCtx->sample_fmt != mSamplingFmt) {
737                 if (mCtx->channels != mNumChannels || mCtx->sample_rate != mSamplingRate) {
738                     LOGI("audio OMX_EventPortSettingsChanged, mCtx->channels: %d, mNumChannels: %d, mCtx->sample_rate: %d, mSamplingRate: %d, mCtx->sample_fmt: %s, mSamplingFmt: %s",
739                             mCtx->channels, mNumChannels, mCtx->sample_rate, mSamplingRate,
740                             av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mSamplingFmt));
741                     mNumChannels = mCtx->channels;
742                     mSamplingRate = mCtx->sample_rate;
743                     mSamplingFmt = mCtx->sample_fmt;
744                     mAudioConfigChanged = true;
745                     notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
746                     mOutputPortSettingsChange = AWAITING_DISABLED;
747                     return;
748                 } else {
749                     // match with the default, set mAudioConfigChanged true anyway!
750                     mAudioConfigChanged = true;
751                     mSamplingFmt = mCtx->sample_fmt;
752                 }
753             }
754
755             dataSize = av_samples_get_buffer_size(NULL, mNumChannels, mFrame->nb_samples, mSamplingFmt, 1);
756
757 #if DEBUG_FRM
758             LOGV("audio decoder, nb_samples: %d, get buffer size: %d", mFrame->nb_samples, dataSize);
759             LOGV("audio decoder: mCtx channel_layout: %llu, channels: %d, channels_from_layout: %d\n",
760                 mCtx->channel_layout,  mCtx->channels, av_get_channel_layout_nb_channels(mCtx->channel_layout));
761 #endif
762
763             decChannelLayout = av_get_default_channel_layout(mNumChannels);
764             if (mSamplingFmt != mAudioSrcFmt ||
765                     decChannelLayout != mAudioSrcChannelLayout ||
766                     mSamplingRate != mAudioSrcFreq ) {
767                 if (mSwrCtx)
768                     swr_free(&mSwrCtx);
769                 mSwrCtx = swr_alloc_set_opts(NULL,
770                                              mAudioTgtChannelLayout, mAudioTgtFmt, mAudioTgtFreq,
771                                              decChannelLayout,       mSamplingFmt, mSamplingRate,
772                                              0, NULL);
773                 if (!mSwrCtx || swr_init(mSwrCtx) < 0) {
774                     LOGE("Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!",
775                             mSamplingRate,
776                             av_get_sample_fmt_name(mSamplingFmt),
777                             mNumChannels,
778                             mAudioTgtFreq,
779                             av_get_sample_fmt_name(mAudioTgtFmt),
780                             mAudioTgtChannels);
781                     notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
782                     mSignalledError = true;
783                     return;
784                 }
785
786                 LOGI("Create sample rate converter for conversion of %d Hz %s %d channels(%lld channel_layout) to %d Hz %s %d channels(%lld channel_layout)!",
787                         mSamplingRate,
788                         av_get_sample_fmt_name(mSamplingFmt),
789                         mNumChannels,
790                         mAudioTgtChannelLayout,
791                         mAudioTgtFreq,
792                         av_get_sample_fmt_name(mAudioTgtFmt),
793                         mAudioTgtChannels,
794                         decChannelLayout);
795
796                 mAudioSrcChannelLayout = decChannelLayout;
797                 mAudioSrcChannels = mNumChannels;
798                 mAudioSrcFreq = mSamplingRate;
799                 mAudioSrcFmt = mSamplingFmt;
800             }
801
802             if (mSwrCtx) {
803                 //const uint8_t *in[] = { mFrame->data[0] };
804                 const uint8_t **in = (const uint8_t **)mFrame->extended_data;
805                 uint8_t *out[] = {mAudioBuf2};
806                 int out_count = sizeof(mAudioBuf2) / mAudioTgtChannels / av_get_bytes_per_sample(mAudioTgtFmt);
807
808 #if DEBUG_FRM
809                 LOGV("swr_convert 1, out_count: %d, mFrame->nb_samples: %d, src frm: %s, tgt frm: %s",
810                     out_count, mFrame->nb_samples, av_get_sample_fmt_name(mCtx->sample_fmt), av_get_sample_fmt_name(mAudioTgtFmt));
811 #endif
812                 int len2 = swr_convert(mSwrCtx, out, out_count, in, mFrame->nb_samples);
813                 if (len2 < 0) {
814                     LOGE("audio_resample() failed");
815                     break;
816                 }
817                 if (len2 == out_count) {
818                     LOGE("warning: audio buffer is probably too small");
819                     swr_init(mSwrCtx);
820                 }
821                 mPAudioBuffer = mAudioBuf2;
822                 mAudioBufferSize = len2 * mAudioTgtChannels * av_get_bytes_per_sample(mAudioTgtFmt);
823             } else {
824                 mPAudioBuffer = mFrame->data[0];
825                 mAudioBufferSize = dataSize;
826             }
827
828 #if DEBUG_FRM
829             LOGV("ffmpeg audio decoder get frame. consume pkt len: %d, nb_samples(before resample): %d, mAudioBufferSize: %d",
830                     len, mFrame->nb_samples, mAudioBufferSize);
831 #endif
832         } // if (inHeader && mAudioBufferSize == 0 && !mFlushComplete)
833
834         size_t copyToOutputBufferLen = mAudioBufferSize;
835         if (mAudioBufferSize > kOutputBufferSize)
836             copyToOutputBufferLen = kOutputBufferSize;
837
838         outHeader->nOffset = 0;
839         outHeader->nFilledLen = copyToOutputBufferLen;
840         outHeader->nTimeStamp = mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
841         memcpy(outHeader->pBuffer, mPAudioBuffer, copyToOutputBufferLen);
842         outHeader->nFlags = 0;
843
844 #if DEBUG_FRM
845         LOGV("ffmpeg audio decoder, fill out buffer, pts: %lld, mNumFramesOutput: %lld", outHeader->nTimeStamp, mNumFramesOutput);
846 #endif
847
848         mPAudioBuffer += copyToOutputBufferLen;
849         mAudioBufferSize -= copyToOutputBufferLen;
850         mNumFramesOutput += copyToOutputBufferLen / (av_get_bytes_per_sample(mAudioTgtFmt) * mNumChannels);
851
852         // reset mNumFramesOutput
853         if (mAudioBufferSize == 0) {
854 #if DEBUG_FRM
855             LOGV("~~~~ mAudioBufferSize, set mNumFramesOutput = 0");
856 #endif
857             mNumFramesOutput = 0;
858         }
859
860         outInfo->mOwnedByUs = false;
861         outQueue.erase(outQueue.begin());
862         outInfo = NULL;
863         notifyFillBufferDone(outHeader);
864         outHeader = NULL;
865     }
866 }
867
868 void SoftFFmpegAudio::onPortFlushCompleted(OMX_U32 portIndex) {
869     if (portIndex == 0 && mCtx) {
870         // Make sure that the next buffer output does not still
871         // depend on fragments from the last one decoded.
872         avcodec_flush_buffers(mCtx);
873     }
874
875 }
876
877 void SoftFFmpegAudio::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
878     if (portIndex != 1) {
879         return;
880     }
881
882     switch (mOutputPortSettingsChange) {
883         case NONE:
884             break;
885
886         case AWAITING_DISABLED:
887         {
888             CHECK(!enabled);
889             mOutputPortSettingsChange = AWAITING_ENABLED;
890             break;
891         }
892
893         default:
894         {
895             CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
896             CHECK(enabled);
897             mOutputPortSettingsChange = NONE;
898             break;
899         }
900     }
901 }
902
903 }  // namespace android
904
905 android::SoftOMXComponent *createSoftOMXComponent(
906         const char *name, const OMX_CALLBACKTYPE *callbacks,
907         OMX_PTR appData, OMX_COMPONENTTYPE **component) {
908     return new android::SoftFFmpegAudio(name, callbacks, appData, component);
909 }