FFmpeg--音频解码:aac解码为pcm实战

音频解码流程

aac—音频解码器–pcm数据

API

avcodec_find_decoder:根据指定的AVCodecID查找注册的解码器
av_parser_init:初始化AVCodecParserContext
avcodec_alloc_context3:为AVCodecContext分配内存
avcodec_open2:打开解码器
av_parser_parse2:解析获得⼀个Packet

int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt); // 将AVPacket压缩数据给解码器

int avcodec_receive_frame ( AVCodecContext * avctx, AVFrame * frame ) // 获取到解码后的AVFrame数据


分析:

首先读文件(原始码流),将原始码流解析为Packet, 通过解码器获得AVFrame ,最后写文件 ,循环获取Packet,写文件

伪代码
// 读文件
data_size = fread(inbuf, 1, AUDIO_INBUF_SIZE, infile); // data_size 20480 

while(data_size) {
	av_parser_parse2()  //解析获得⼀个Packet
	decode(); // (压缩AVPacket,解码AVFrame数据,之后写数据)
	// data_size 减少
}


void decode() {
	ret = avcodec_send_packet; //将AVPacket压缩数据给解码器	
	while (ret ) {
	ret = avcodec_receive_frame; // 获取到解码后的AVFrame数据
	if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;  //  fwrite 结束后 ret == AVERROR(EAGAIN,需要新的输⼊, 返回
	av_get_bytes_per_sample //获取每个sample中的字节数
	fwrite();
	}
}
code:
#define AUDIO_INBUF_SIZE 20480
#define AUDIO_REFILL_THRESH 4096

static char err_buf[128] = {0};
static char* av_get_err(int errnum)
{
    av_strerror(errnum, err_buf, 128);
    return err_buf;
}

static void print_sample_format(const AVFrame *frame)
{
    printf("ar-samplerate: %uHz\n", frame->sample_rate);
    printf("ac-channel: %u\n", frame->channels);
    printf("f-format: %u\n", frame->format);// 格式需要注意,实际存储到本地文件时已经改成交错模式
}

static void decode(AVCodecContext *dec_ctx, AVPacket *pkt, AVFrame *frame,
                   FILE *outfile)
{
    int i, ch;
    int ret, data_size;
    /* send the packet with the compressed data to the decoder */
    ret = avcodec_send_packet(dec_ctx, pkt);
    if(ret == AVERROR(EAGAIN))
    {
        fprintf(stderr, "Receive_frame and send_packet both returned EAGAIN, which is an API violation.\n");
    }
    else if (ret < 0)
    {
        fprintf(stderr, "Error submitting the packet to the decoder, err:%s, pkt_size:%d\n",
                av_get_err(ret), pkt->size)return;
    }

    /* read all the output frames (infile general there may be any number of them */
    while (ret >= 0)
    {
        // 对于frame, avcodec_receive_frame内部每次都先调用
        ret = avcodec_receive_frame(dec_ctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0)
        {
            fprintf(stderr, "Error during decoding\n");
            exit(1);
        }
        data_size = av_get_bytes_per_sample(dec_ctx->sample_fmt);
        if (data_size < 0)
        {
            fprintf(stderr, "Failed to calculate data size\n");
            exit(1);
        }
        static int s_print_format = 0;
        if(s_print_format == 0)
        {
            s_print_format = 1;
            print_sample_format(frame);
        }
        for (i = 0; i < frame->nb_samples; i++)
        {
            for (ch = 0; ch < dec_ctx->channels; ch++)  // 交错的方式写入, 大部分float的格式输出
                fwrite(frame->data[ch] + data_size*i, 1, data_size, outfile);
        }
    }
}
   
int main(int argc, char **argv)
{
    const char *outfilename;
    const char *filename;
    const AVCodec *codec;
    AVCodecContext *codec_ctx= NULL;
    AVCodecParserContext *parser = NULL;
    int len = 0;
    int ret = 0;
    FILE *infile = NULL;
    FILE *outfile = NULL;
    uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
    uint8_t *data = NULL;
    size_t   data_size = 0;
    AVPacket *pkt = NULL;
    AVFrame *decoded_frame = NULL;

    if (argc <= 2)
    {
        fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
        exit(0);
    }
    filename    = argv[1];
    outfilename = argv[2];

    pkt = av_packet_alloc();
    enum AVCodecID audio_codec_id = AV_CODEC_ID_AAC;
    if(strstr(filename, "aac") != NULL)
    {
        audio_codec_id = AV_CODEC_ID_AAC;
    }
    else if(strstr(filename, "mp3") != NULL)
    {
        audio_codec_id = AV_CODEC_ID_MP3;
    }
    else
    {
        printf("default codec id:%d\n", audio_codec_id);
    }

    // 查找解码器
    codec = avcodec_find_decoder(audio_codec_id);  // AV_CODEC_ID_AAC
    if (!codec) {
        fprintf(stderr, "Codec not found\n");
        exit(1);
    }
    // 获取裸流的解析器 AVCodecParserContext(数据)  +  AVCodecParser(方法)
    parser = av_parser_init(codec->id);
    if (!parser) {
        fprintf(stderr, "Parser not found\n");
        exit(1);
    }
    // 分配codec上下文
    codec_ctx = avcodec_alloc_context3(codec);
    if (!codec_ctx) {
        fprintf(stderr, "Could not allocate audio codec context\n");
        exit(1);
    }

    // 将解码器和解码器上下文进行关联
    if (avcodec_open2(codec_ctx, codec, NULL) < 0) {
        fprintf(stderr, "Could not open codec\n");
        exit(1);
    }

    // 打开输入文件
    infile = fopen(filename, "rb");
    if (!infile) {
        fprintf(stderr, "Could not open %s\n", filename);
        exit(1);
    }
    // 打开输出文件
    outfile = fopen(outfilename, "wb");
    if (!outfile) {
        av_free(codec_ctx);
        exit(1);
    }

    // 读取文件进行解码
    data      = inbuf;
    data_size = fread(inbuf, 1, AUDIO_INBUF_SIZE, infile);

    while (data_size > 0)
    {
        if (!decoded_frame)
        {
            if (!(decoded_frame = av_frame_alloc()))
            {
                fprintf(stderr, "Could not allocate audio frame\n");
                exit(1);
            }
        }

        ret = av_parser_parse2(parser, codec_ctx, &pkt->data, &pkt->size,
                               data, data_size,
                               AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
        if (ret < 0)
        {
            fprintf(stderr, "Error while parsing\n");
            exit(1);
        }
        data      += ret;   // 跳过已经解析的数据
        data_size -= ret;   // 对应的缓存大小也做相应减小

        if (pkt->size)
            decode(codec_ctx, pkt, decoded_frame, outfile);

        if (data_size < AUDIO_REFILL_THRESH)    // 如果数据少了则再次读取
        {
            memmove(inbuf, data, data_size);    // 把之前剩的数据拷贝到buffer的起始位置
            data = inbuf;
            // 读取数据 长度: AUDIO_INBUF_SIZE - data_size
            len = fread(data + data_size, 1, AUDIO_INBUF_SIZE - data_size, infile);
            if (len > 0)
                data_size += len;
        }
    }

    /* 冲刷解码器 */
    pkt->data = NULL;   // 让其进入drain mode
    pkt->size = 0;
    decode(codec_ctx, pkt, decoded_frame, outfile);

    fclose(outfile);
    fclose(infile);

    avcodec_free_context(&codec_ctx);
    av_parser_close(parser);
    av_frame_free(&decoded_frame);
    av_packet_free(&pkt);

    printf("main finish, please enter Enter and exit\n");
    return 0;
}                     
Fixed-point HE-AAC decoder Developed by RealNetworks, 2005===============================Overview--------This module contains a high-performance HE-AAC decoder for 32-bit fixed-point processors. The following is a summary of what is and is not supported:Supported: - MPEG2, MPEG4 low complexity decoding (intensity stereo, M-S, TNS, PNS) - spectral band replication (SBR), high-quality mode - mono, stereo, and multichannel modes - ADTS, ADIF, and raw data block file formatsNot currently supported: - main or SSR profile, LTP - coupling channel elements (CCE) - 960/1920-sample frame size - low-power mode SBR - downsampled (single-rate) SBR - parametric stereoHighlights - highly optimized for ARM processors (details in docs/ subdirectory) - reference x86 implementation - C and assembly code only (C++ not required for codec library) - reentrant, statically linkable - low memory (details in docs/ subdirectory) - option to use Intel Integrated Performance Primitives (details below)Supported platforms and toolchainsThis codec should run on any 32-bit fixed-point processor which can perform a full 32x32-bit multiply (providing a 64-bit result). The following processors and toolchains are supported: - x86, Microsoft Visual C++ - x86, GNU toolchain (gcc) - ARM, ARM Developer Suite (ADS) - ARM, Microsoft Embedded Visual C++ - ARM, GNU toolchain (gcc)ARM refers to any processor supporting ARM architecture v.4 or above. Thumb is not required.Generally ADS produces the fastest code. EVC 3 does not support inline assembly code for ARM targets, so calls to MULSHIFT32 (smull on ARM) are left as function calls. This incurs a significant performance penalty. For the fastest code on targets which do not normally use ADS consider compiling with ADS, using the -S option to output assembly code, and feeding this assembly code to the assem
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

八月的雨季997

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值