extern "C"
{
#include "libavformat\avformat.h"
};
int AudioPacketDecode(AVPacket pPacket,int got_frame_ptr,int AudioIndex,AVCodecContext* pCodecContext,AVFrame* pFrame,FILE* f_pcm)
{
int ReturnValue = pPacket.size;
got_frame_ptr = 0;
if(pPacket.stream_index == AudioIndex)
{
int Result = avcodec_decode_audio4(pCodecContext,pFrame,&got_frame_ptr,&pPacket);
if(Result< 0)
return Result;
ReturnValue = FFMIN(Result,pPacket.size);
if(got_frame_ptr)
{
size_t unpadded_linesize = pFrame->nb_samples * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
fwrite(pFrame->extended_data[0],1,unpadded_linesize,f_pcm);
}
}
return ReturnValue;
}
int AudioDecode(char* AudioName,int ProgramNumber,char* PcmName)
{
AVFormatContext* pFormatContext = NULL;
if(avformat_open_input(&pFormatContext,AudioName,NULL,NULL) < 0)
return -1;
if(avformat_find_stream_info(pFormatContext,NULL) < 0)
{
avformat_close_input(&pFormatContext);
return -2;
}
int AudioIndex = -1;
for(int i=0;i<pFormatContext->nb_programs;i++)
{
if(pFormatContext->programs[i]->id == ProgramNumber)
{
for(int j=0;j<pFormatContext->programs[i]->nb_stream_indexes;j++)
{
if(pFormatContext->streams[pFormatContext->programs[i]->stream_index[j]]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
AudioIndex = pFormatContext->programs[i]->stream_index[j];
}
}
}
if(AudioIndex == -1)
{
avformat_close_input(&pFormatContext);
return -3;
}
AVCodecContext* pCodecContext = NULL;
pCodecContext = pFormatContext->streams[AudioIndex]->codec;
AVCodec* pCodec = NULL;
pCodec = avcodec_find_decoder(pCodecContext->codec_id);
if(!pCodec)
{
avformat_close_input(&pFormatContext);
return -4;
}
if(avcodec_open2(pCodecContext,pCodec,NULL) < 0)
{
avformat_close_input(&pFormatContext);
return -5;
}
AVFrame* pFrame = NULL;
pFrame = av_frame_alloc();
if(!pFrame)
{
avcodec_close(pCodecContext);
avformat_close_input(&pFormatContext);
return -6;
}
AVPacket pPacket;
av_init_packet(&pPacket);
pPacket.data = NULL;
pPacket.size = 0;
FILE* f_pcm = fopen(PcmName,"wb");
if(f_pcm == NULL)
{
av_frame_free(&pFrame);
avcodec_close(pCodecContext);
avformat_close_input(&pFormatContext);
return -7;
}
int ReturnValue = 0;
int got_frame_ptr = 0;
while(av_read_frame(pFormatContext,&pPacket) >= 0)
{
AVPacket pPacketTemp = pPacket;
do
{
ReturnValue = AudioPacketDecode(pPacket,got_frame_ptr,AudioIndex,pCodecContext,pFrame,f_pcm);
if(ReturnValue < 0)
break;
pPacket.data += ReturnValue;
pPacket.size -= ReturnValue;
}while(pPacket.size > 0);
av_free_packet(&pPacketTemp);
}
pPacket.data = NULL;
pPacket.size = 0;
do
{
AudioPacketDecode(pPacket,got_frame_ptr,AudioIndex,pCodecContext,pFrame,f_pcm);
}while(got_frame_ptr);
fclose(f_pcm);
av_frame_free(&pFrame);
avcodec_close(pCodecContext);
avformat_close_input(&pFormatContext);
return 0;
}
int main()
{
av_register_all();
int ReturnValue = AudioDecode("test_1.ts",1,"decode_1.pcm");
printf("ReturnValue = %d\n",ReturnValue);
system("PAUSE");
return 0;
}