解码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;
}
相关文章
|
Ubuntu Linux 内存技术
Linux下使用alsamixer配置系统默认的声卡设备(默认音频输出设备、输入设备、系统音量)
Linux下使用alsamixer配置系统默认的声卡设备(默认音频输出设备、输入设备、系统音量)
5370 0
Linux下使用alsamixer配置系统默认的声卡设备(默认音频输出设备、输入设备、系统音量)
|
Ubuntu Linux Windows
Linux下音频开发: 读取声卡PCM数据保存到文件(alsa-lib库)
Linux下音频开发: 读取声卡PCM数据保存到文件(alsa-lib库)
2081 0
Linux下音频开发: 读取声卡PCM数据保存到文件(alsa-lib库)
|
11月前
|
Windows
SDL基础使用07(YUV数据显示)
使用SDL库在Windows上处理和显示YUV数据,包括生成随机YUV数据、播放YUV文件以及实现带缩放的实时渲染。
167 1
|
9月前
|
机器学习/深度学习 网络架构 计算机视觉
深度学习在图像识别中的应用与挑战
【10月更文挑战第21天】 本文探讨了深度学习技术在图像识别领域的应用,并分析了当前面临的主要挑战。通过研究卷积神经网络(CNN)的结构和原理,本文展示了深度学习如何提高图像识别的准确性和效率。同时,本文也讨论了数据不平衡、过拟合、计算资源限制等问题,并提出了相应的解决策略。
260 19
|
机器学习/深度学习 人工智能 算法
技术开源|FunASR升级第三代热词方案
技术开源|FunASR升级第三代热词方案
2964 62
|
编解码 移动开发 C++
RTMP协议深度解析:从原理到实践,掌握实时流媒体传输技术
RTMP协议深度解析:从原理到实践,掌握实时流媒体传输技术
2061 0
RTMP协议深度解析:从原理到实践,掌握实时流媒体传输技术
|
11月前
|
机器学习/深度学习 传感器 数据采集
深度学习之设备异常检测与预测性维护
基于深度学习的设备异常检测与预测性维护是一项利用深度学习技术分析设备运行数据,实时检测设备运行过程中的异常情况,并预测未来可能的故障,以便提前进行维护,防止意外停机和生产中断。
635 1
|
人工智能 监控 数据可视化
如何利用 DataV 的 AI 功能进行数据可视化?
如何利用 DataV 的 AI 功能进行数据可视化?
624 1
|
API 开发工具 Android开发
Android源码下载
Android源码下载
1499 0
|
流计算 计算机视觉 索引
使用ffmpeg将视频转成HLS(m3u8)格式
HLS (HTTP Live Streaming)是苹果推出的视频流协议,HLS格式的视频包含一个m3u8文本文件,以及众多的.ts的视频片段,而m3u8文本文件的作用就是将这些ts片段索引起来。 因为HLS协议是将视频切分成很多小的ts片段,这些小片段很适合放到cdn上,有很多视频文章都使用了hls格式传输视频。今天我在这里教大家如何用ffmpeg将mp4格式的视频转为HLS(m3u8)格式。
1054 0