解码AAC裸流为PCM写入文件

简介: 使用FFmpeg库将AAC裸流解码为PCM数据并写入文件的过程。

使用AAC裸流解析器将aac裸流文件解析为pcm数据,然后写入文件

#include "myLog.h"
#include <iostream>

extern "C"
{
#include <libavcodec\avcodec.h>
}

#define AUDIO_INBUF_SIZE 20480            // 读取 20KB数据
#define AUDIO_REFILL_THRESH 4096

/*
    从src复制size字符到dst(dstBuff 与 srcBuff内存块可重叠)
    memmove(dst, src, size);
*/

static char* av_get_err(int errnum)
{
    char err_buf[128] = { 0 };
    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);    // 格式需要注意,实际存储到本地文件时已经改成交错模式 FLT
}


static void decode(AVCodecContext* dec_ctx, AVPacket* pkt, AVFrame* frame, FILE* out_fp)
{
    int nRet = avcodec_send_packet(dec_ctx, pkt);
    if (nRet == AVERROR(EAGAIN))        // 需要更多pkt
    {
        LOG_WARNING("need more pkt\n");
        return;
    }
    else if (nRet < 0)
    {
        // 当为mp3文件时,因为前面的一部分字节解码器解不出来, 直接退出程序的话,会导致mp3文件解析失败,应该函数返回解析下一帧
        LOG_WARNING("Error submitting the packet to the decoder, err:%s, pkt_size:%d\n",
            av_get_err(nRet), pkt->size);
        return;
    }

    // 一个pkt可能对应多个frame
    while (nRet >= 0)
    {
        nRet = avcodec_receive_frame(dec_ctx, frame);
        if (nRet == AVERROR(EAGAIN) || nRet == AVERROR_EOF)
        {
            return;
        }
        else if (nRet < 0)
        {
            LOG_WARNING("Error during decoding\n");
            return;
        }

        // 一个采样点字节数
        int data_size = av_get_bytes_per_sample(dec_ctx->sample_fmt);
        if (data_size < 0)
        {
            LOG_WARNING("av_get_bytes_per_sample error\n");
            return;
        }

        // 打印一次信息
        static bool is_print = 0;
        if (!is_print)
        {
            is_print = !is_print;
            print_sample_format(frame);
        }

        // planar to packed
        for (int i = 0; i < frame->nb_samples; i++)
        {
            for (int ch = 0; ch < frame->channels; ch++)
            {
                fwrite(frame->data[ch] + i * data_size, 1, data_size, out_fp);
            }
        }
    }
}

int main_audio_decodec()
{
    // ffplay -ar 44100 -ac 2 -f f32le -i out_put_48000_2_f32le.pcm
    const char* in_file_name = "./out_put.aac";
    const char* out_file_name = "./out_put_48000_2_f32le.pcm";

    enum AVCodecID audio_codec_id = AV_CODEC_ID_AAC;    // 指定aac

    // 1. 查找解码器
    AVCodec* audio_decoder = avcodec_find_decoder(audio_codec_id);
    if (nullptr == audio_decoder)
    {
        LOG_WARNING("avcodec_find_decoder error\n");
        return -1;
    }

    // 2. 获取(aac)裸流解析器
    AVCodecParserContext* parser = av_parser_init(audio_decoder->id);
    if (nullptr == parser)
    {
        LOG_WARNING("av_parser_init error\n");
        return -2;
    }

    // 3. 根据解码器创建解码上下文
    auto audio_decoder_ctx = avcodec_alloc_context3(audio_decoder);
    if (audio_decoder_ctx == nullptr)
    {
        LOG_WARNING("avcodec_alloc_context3 error\n");
        return -3;
    }

    // 4. 打开解码器
    int nRet = avcodec_open2(audio_decoder_ctx, audio_decoder, NULL);
    if (nRet < 0)
    {
        LOG_WARNING("avcodec_open2 error\n");
        return -4;
    }

    // 5. 打开输入输出文件
    FILE* in_fp = fopen(in_file_name, "rb");
    if (NULL == in_fp)
    {
        LOG_WARNING("fopen in_file_name error\n");
        return -5;
    }

    FILE* out_fp = fopen(out_file_name, "wb");
    if (NULL == out_fp)
    {
        LOG_WARNING("out_fp out_file_name error\n");
        return -5;
    }

    // 6.从输入文件中读取数据
    // AV_INPUT_BUFFER_PADDING_SIZE   在用于解码的输入比特流末尾所需的额外分配的字节数
    uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
    uint8_t *data = NULL;
    size_t   data_size = 0;

    data = inbuf;
    data_size = fread(inbuf, 1, AUDIO_INBUF_SIZE, in_fp);

    AVPacket* pkt = av_packet_alloc();
    AVFrame* decoded_frame = av_frame_alloc();
    while (data_size > 0)
    {
        if (decoded_frame == nullptr)
        {
            LOG_WARNING("av_frame_alloc error\n");
            return -6;
        }

        // pkt->data 不会分配内存而是直接指向data的内存
        // av_read_frame():获取媒体的一帧压缩编码数据。其中调用了av_parser_parse2()
        // 返回值为 该函数返回读取的bytes
        nRet = av_parser_parse2(parser, audio_decoder_ctx,
            &pkt->data, &pkt->size,        // 输出 pkt
            data, data_size,            // 输入 buff裸流数据(h264, aac等)
            AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);

        if (nRet < 0)
        {
            LOG_WARNING("av_parser_parse2 error\n");
            return -7;
        }
        data += nRet;        // 将指针挪动到未解析的buff位置
        data_size -= nRet;

        if (pkt->size >= 0)
        {
            // 解码
            decode(audio_decoder_ctx, pkt, decoded_frame, out_fp);
        }

        // 数据不够了继续读取
        if (data_size < AUDIO_REFILL_THRESH)
        {
            memmove(inbuf, data, data_size);    // 将未读取完的拷贝到inbuf开始位置
            data = inbuf;
            int len = fread(data + data_size, 1, AUDIO_INBUF_SIZE - data_size, in_fp);
            if (len > 0)
            {
                data_size += len;
            }
        }
    }

    // 空包冲刷解码器
    pkt->data = NULL;
    pkt->size = 0;
    decode(audio_decoder_ctx, pkt, decoded_frame, out_fp);

    // 释放相关资源
    fclose(in_fp);
    fclose(out_fp);

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

    getchar();
    return 0;
}
相关文章
|
27天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
4天前
|
人工智能 Rust Java
10月更文挑战赛火热启动,坚持热爱坚持创作!
开发者社区10月更文挑战,寻找热爱技术内容创作的你,欢迎来创作!
438 17
|
7天前
|
JSON 自然语言处理 数据管理
阿里云百炼产品月刊【2024年9月】
阿里云百炼产品月刊【2024年9月】,涵盖本月产品和功能发布、活动,应用实践等内容,帮助您快速了解阿里云百炼产品的最新动态。
阿里云百炼产品月刊【2024年9月】
|
20天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
7天前
|
Linux 虚拟化 开发者
一键将CentOs的yum源更换为国内阿里yum源
一键将CentOs的yum源更换为国内阿里yum源
379 2
|
22天前
|
人工智能 IDE 程序员
期盼已久!通义灵码 AI 程序员开启邀测,全流程开发仅用几分钟
在云栖大会上,阿里云云原生应用平台负责人丁宇宣布,「通义灵码」完成全面升级,并正式发布 AI 程序员。
|
24天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2600 22
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
|
6天前
|
存储 人工智能 搜索推荐
数据治理,是时候打破刻板印象了
瓴羊智能数据建设与治理产品Datapin全面升级,可演进扩展的数据架构体系为企业数据治理预留发展空间,推出敏捷版用以解决企业数据量不大但需构建数据的场景问题,基于大模型打造的DataAgent更是为企业用好数据资产提供了便利。
286 2
|
4天前
|
编译器 C#
C#多态概述:通过继承实现的不同对象调用相同的方法,表现出不同的行为
C#多态概述:通过继承实现的不同对象调用相同的方法,表现出不同的行为
106 65
|
24天前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1582 17
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码