FFmepg--音频编码流程--pcm编码为aac

news/2024/7/10 22:04:06 标签: pcm, ffmpeg

文章目录

      • 基本概念
      • 流程
      • api
      • code(核心部分)

基本概念

从本地⽂件读取PCM数据进⾏AAC格式编码,然后将编码后的AAC数据存储到本地⽂件。

PCM样本格式:未经压缩的⾳频采样数据裸流
参数:

  • Sample Rate : 采样频率
  • Sample Size : 量化位数
  • Number of Channels : 通道个数
  • Sign : 表示样本数据是否是有符号位
  • Byte Ordering : 字节序
  • Integer Or Floating Point : 整形或浮点型

流程

请添加图片描述

api

  • avcodec_find_encoder:根据指定的AVCodecID查找注册的编码器
  • avcodec_alloc_context3:为AVCodecContext分配内存
  • avcodec_open2:打开编码器
  • avcodec_send_frame:将AVFrame⾮压缩数据给编码器
  • avcodec_receive_packet:获取到编码后的AVPacket数据
  • 设置AVFrame参数: format 、nb_samples、channel_layout、width/height
  • av_frame_get_buffer: 为⾳频或视频帧分配新的buffer
  • av_frame_make_writable:确保AVFrame是可写的
  • av_samples_fill_arrays 填充⾳频帧

code(核心部分)

static int encode(AVCodecContext *ctx, AVFrame *frame, AVPacket *pkt, FILE *output)
{
    int ret;

    /* send the frame for encoding */
    ret = avcodec_send_frame(ctx, frame);
    if (ret < 0) {
        fprintf(stderr, "Error sending the frame to the encoder\n");
        return -1;
    }
    while (ret >= 0) {
        ret = avcodec_receive_packet(ctx, pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
            return 0;
        } else if (ret < 0) {
            fprintf(stderr, "Error encoding audio frame\n");
            return -1;
        }

        size_t len = 0;
        if((ctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
            // 需要额外的adts header写入
            uint8_t aac_header[7];
            get_adts_header(ctx, aac_header, pkt->size);
            len = fwrite(aac_header, 1, 7, output);
            if(len != 7) {
                fprintf(stderr, "fwrite aac_header failed\n");
                return -1;
            }
        }
        len = fwrite(pkt->data, 1, pkt->size, output);
        if(len != pkt->size) {
            fprintf(stderr, "fwrite aac data failed\n");
            return -1;
        }
       
    }
    return -1;
}

int main(int argc, char **argv)
{
    char *in_pcm_file = NULL;
    char *out_aac_file = NULL;
    FILE *infile = NULL;
    FILE *outfile = NULL;
    const AVCodec *codec = NULL;
    AVCodecContext *codec_ctx= NULL;
    AVFrame *frame = NULL;
    AVPacket *pkt = NULL;
    int ret = 0;
    int force_codec = 0;     // 强制使用指定的编码
    char *codec_name = NULL;

    in_pcm_file = argv[1];      // 输入PCM文件
    out_aac_file = argv[2];     // 输出的AAC文件

    enum AVCodecID codec_id = AV_CODEC_ID_AAC;

    codec_ctx = avcodec_alloc_context3(codec);
    if (!codec_ctx) {
        fprintf(stderr, "Could not allocate audio codec context\n");
        exit(1);
    }
    codec_ctx->codec_id = codec_id;
    codec_ctx->codec_type = AVMEDIA_TYPE_AUDIO;
    codec_ctx->bit_rate = 128*1024;
    codec_ctx->channel_layout = AV_CH_LAYOUT_STEREO;
    codec_ctx->sample_rate    = 48000; //48000;
    codec_ctx->channels       = av_get_channel_layout_nb_channels(codec_ctx->channel_layout);
    codec_ctx->profile = FF_PROFILE_AAC_LOW;    //

    if(strcmp(codec->name, "aac") == 0) {
        codec_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
    } else if(strcmp(codec->name, "libfdk_aac") == 0) {
        codec_ctx->sample_fmt = AV_SAMPLE_FMT_S16;
    } else {
        codec_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
    }
    /* 检测支持采样格式支持情况 */
    check_sample_fmt(codec, codec_ctx->sample_fmt);
    check_sample_rate(codec, codec_ctx->sample_rate);
    check_channel_layout(codec, codec_ctx->channel_layout);
    
    codec_ctx->flags = AV_CODEC_FLAG_GLOBAL_HEADER;  //ffmpeg默认的aac是不带adts,而fdk_aac默认带adts,这里我们强制不带
    /* 将编码器上下文和编码器进行关联 */
    avcodec_open2(codec_ctx, codec, NULL);
    
    // 打开输入和输出文件
    infile = fopen(in_pcm_file, "rb");
    outfile = fopen(out_aac_file, "wb");

    /* packet for holding encoded output */
    pkt = av_packet_alloc();

    /* frame containing input raw audio */
    frame = av_frame_alloc();
  
    // 设置frame参数
    frame->nb_samples     = codec_ctx->frame_size;
    frame->format         = codec_ctx->sample_fmt;
    frame->channel_layout = codec_ctx->channel_layout;
    frame->channels = av_get_channel_layout_nb_channels(frame->channel_layout);
   
    
    /* 为frame分配buffer */
    av_frame_get_buffer(frame, 0);
   
    // 计算出每一帧的数据 单个采样点的字节 * 通道数目 * 每帧采样点数量
    int frame_bytes = av_get_bytes_per_sample(frame->format) \
            * frame->channels \
            * frame->nb_samples;
    
    uint8_t *pcm_buf = (uint8_t *)malloc(frame_bytes);
    uint8_t *pcm_temp_buf = (uint8_t *)malloc(frame_bytes);
    int64_t pts = 0;
    
    printf("start enode\n");
    for (;;) {
        memset(pcm_buf, 0, frame_bytes);
        size_t read_bytes = fread(pcm_buf, 1, frame_bytes, infile);
        if(read_bytes <= 0) {
            printf("read file finish\n");
            break;
        }

        /* 确保该frame可写, 如果编码器内部保持了内存参考计数,则需要重新拷贝一个备份
            目的是新写入的数据和编码器保存的数据不能产生冲突
        */
        av_frame_make_writable(frame);
      
        if(AV_SAMPLE_FMT_S16 == frame->format) {
            // 将读取到的PCM数据填充到frame去
            ret = av_samples_fill_arrays(frame->data, frame->linesize,
                                   pcm_buf, frame->channels,
                                   frame->nb_samples, frame->format, 0);
        } else {
            // 将读取到的PCM数据填充到frame去
            // 将本地的f32le packed模式的数据转为float palanar
            memset(pcm_temp_buf, 0, frame_bytes);
            f32le_convert_to_fltp((float *)pcm_buf, (float *)pcm_temp_buf, frame->nb_samples);
            ret = av_samples_fill_arrays(frame->data, frame->linesize,
                                   pcm_temp_buf, frame->channels,
                                   frame->nb_samples, frame->format, 0);
        }
        // 设置pts
        pts += frame->nb_samples;
        frame->pts = pts;       // 使用采样率作为pts的单位,具体换算成秒 pts*1/采样率
        ret = encode(codec_ctx, frame, pkt, outfile);
        if(ret < 0) {
            printf("encode failed\n");
            break;
        }
    }

    /* 冲刷编码器 */
    encode(codec_ctx, NULL, pkt, outfile);

    // 关闭文件
    fclose(infile);
    fclose(outfile);

    // 释放内存
    if(pcm_buf) {
        free(pcm_buf);
    }
    if (pcm_temp_buf) {
        free(pcm_temp_buf);
    }
    av_frame_free(&frame);
    av_packet_free(&pkt);
    avcodec_free_context(&codec_ctx);
    printf("main finish, please enter Enter and exit\n");
    getchar();
    return 0;
}


http://www.niftyadmin.cn/n/5429020.html

相关文章

目标检测——YOLOv3算法解读

论文&#xff1a;YOLOv3&#xff1a;An Incremental Improvement 作者&#xff1a;Joseph Redmon, Ali Farhadi 链接&#xff1a;https://arxiv.org/abs/1804.02767 代码&#xff1a;http://pjreddie.com/yolo/ YOLO系列其他文章&#xff1a; YOLOv1通俗易懂版解读SSD算法解读…

[数据集][目标检测]零售柜零食检测数据集VOC+YOLO格式5422张113类

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;5422 标注数量(xml文件个数)&#xff1a;5422 标注数量(txt文件个数)&#xff1a;5422 标注…

基于深度学习的人体姿态估计

论文标题&#xff1a;基于深度学习的人体姿态估计综述 基于深度学习的人体姿态估计 论文标题&#xff1a;基于深度学习的人体姿态估计综述目录1. 引言2. 2D人体姿态估计2.1 单人2D姿态估计2.2 多人2D姿态估计 3. 3D人体姿态估计3.1 基于单目RGB图像和视频的3D姿态估计3.2 基于其…

发布组件到npm

1.环境准备&#xff0c;需要装好node&#xff0c;注册号npm账号,这里不做详解 2.创建编写组件和方法的文件夹package 3.在文件夹中创建需要定义的组件&#xff0c;并且加上name属性 //组件 <template><div><button>按钮组件</button></div> &…

【Elasticsearch】windows安装es(elasticsearch)教程及遇到的坑

一、安装参考 1、安装参考&#xff1a;ES的安装使用(windows版) elasticsearch的下载地址&#xff1a;https://www.elastic.co/cn/downloads/elasticsearch ik分词器的下载地址&#xff1a;https://github.com/medcl/elasticsearch-analysis-ik/releases kibana可视化工具下载…

深入浅出:Objective-C中使用MWFeedParser下载豆瓣RSS

摘要 本文旨在介绍如何在Objective-C中使用MWFeedParser库下载豆瓣RSS内容&#xff0c;同时展示如何通过爬虫代理IP技术和多线程提高爬虫的效率和安全性。 背景 随着信息量的激增&#xff0c;爬虫技术成为了获取和处理大量网络数据的重要手段。Objective-C作为一种成熟的编程…

2024-03-14 Android app runOnUiThread 函数,它的作用是让一个Runnable对象在主线程(UI线程)上运行。

一、看到别人app有这么一个runOnUiThread 函数用法。 二、在Android中&#xff0c;runOnUiThread 是一个非常重要的方法&#xff0c;它的作用是让一个Runnable对象在主线程&#xff08;UI线程&#xff09;上运行。在Android中&#xff0c;主线程是负责更新UI的线程&#xff0c;…

[数据结构]二叉树(上)

目录 一、树 1.树的概念 2.树的相关概念 3.树的表示 4.树的应用 二、二叉树 1.二叉树的概念 2.二叉树的性质 3.特殊的二叉树 4.二叉树的顺序存储 一、树 1.树的概念 树是一种非线性的数据结构&#xff0c;它是由n&#xff08;n>0&#xff09;个有限结点组成一个具…