[ffmpeg] aac 音频编码

aac 介绍

aac 简单说就是音频的一种压缩编码器,相同音质下压缩比 mp3好,目前比较常用。

aac 编码支持的格式

aac 支持的 sample_fmts: 8

aac 支持的 samplerates: 96000 88200 64000 48000 44100 32000 24000 22050 16000 12000 11025 8000 7350

通过 AVCodec 中的 supported_xx 字段来获取

具体代码

cpp 复制代码
static int check_sample_fmt(const AVCodec* codec, enum AVSampleFormat sample_fmt)
{
    const enum AVSampleFormat* p = codec->sample_fmts;
    cout << "sample_fmts: ";
    while (*p != AV_SAMPLE_FMT_NONE)
    {
        cout << *p << " ";
        p++;
    }
	cout << endl;
    p = codec->sample_fmts;
    while (*p != AV_SAMPLE_FMT_NONE) {
        if (*p == sample_fmt)
            return 1;
        p++;
    }
    return 0;
}

也可以用命令行获取支持格式,以及可设置的额外参数

具体实现

编码步骤

bash 复制代码
// 1. 通过名字或者 id 找到编码器(相当于找到了那个能力结构体指针);获取的结构体会有些编码器的简单介绍,以及编码器支持的能力
// 2. 通过编码器创建上下文,相当于创建上下文实例,并将 codec 指针保存在上下文中,并根据编码器能力初始化一些参数
 // 3. 根据用户需要,以及编码器支持的能力,将编码参数设置到编码器上下文中
 // 4. 根据编码器上下文初始化编码器
 // 5. 创建 avframe 并把编码器上下文中的参数赋值给他
 // 6. avframe 根据参数,算出每次编码需要的内部大小,并分配
 // 7. 将编码数据传给 avframe
 // 8. 将 avframe 传给 avcodec_send_frame
 // 9. 通过 avcodec_receive_packet 获取 avpacket 数据

具体代码

cpp 复制代码
#include <iostream>
using namespace std;
extern"C"
{
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/frame.h>
#include <libavutil/samplefmt.h>
}

const int sampling_frequencies[] = {
	96000,  // 0x0
	88200,  // 0x1
	64000,  // 0x2
	48000,  // 0x3
	44100,  // 0x4
	32000,  // 0x5
	24000,  // 0x6
	22050,  // 0x7
	16000,  // 0x8
	12000,  // 0x9
	11025,  // 0xa
	8000   // 0xb
	// 0xc d e f是保留的
};

int adts_header(char* const p_adts_header, const int data_length,
	const int profile, const int samplerate,
	const int channels)
{

	int sampling_frequency_index = 3; // 默认使用48000hz
	int adtsLen = data_length + 7;

	int frequencies_size = sizeof(sampling_frequencies) / sizeof(sampling_frequencies[0]);
	int i = 0;
	for (i = 0; i < frequencies_size; i++)
	{
		if (sampling_frequencies[i] == samplerate)
		{
			sampling_frequency_index = i;
			break;
		}
	}
	if (i >= frequencies_size)
	{
		printf("unsupport samplerate:%d\n", samplerate);
		return -1;
	}

	p_adts_header[0] = 0xff;         //syncword:0xfff                          高8bits
	p_adts_header[1] = 0xf0;         //syncword:0xfff                          低4bits
	p_adts_header[1] |= (0 << 3);    //MPEG Version:0 for MPEG-4,1 for MPEG-2  1bit
	p_adts_header[1] |= (0 << 1);    //Layer:0                                 2bits
	p_adts_header[1] |= 1;           //protection absent:1                     1bit

	p_adts_header[2] = (profile) << 6;            //profile:profile               2bits
	p_adts_header[2] |= (sampling_frequency_index & 0x0f) << 2; //sampling frequency index:sampling_frequency_index  4bits
	p_adts_header[2] |= (0 << 1);             //private bit:0                   1bit
	p_adts_header[2] |= (channels & 0x04) >> 2; //channel configuration:channels  高1bit

	p_adts_header[3] = (channels & 0x03) << 6; //channel configuration:channels 低2bits
	p_adts_header[3] |= (0 << 5);               //original:0                1bit
	p_adts_header[3] |= (0 << 4);               //home:0                    1bit
	p_adts_header[3] |= (0 << 3);               //copyright id bit:0        1bit
	p_adts_header[3] |= (0 << 2);               //copyright id start:0      1bit
	p_adts_header[3] |= ((adtsLen & 0x1800) >> 11);           //frame length:value   高2bits

	p_adts_header[4] = (uint8_t)((adtsLen & 0x7f8) >> 3);     //frame length:value    中间8bits
	p_adts_header[5] = (uint8_t)((adtsLen & 0x7) << 5);       //frame length:value    低3bits
	p_adts_header[5] |= 0x1f;                                 //buffer fullness:0x7ff 高5bits
	p_adts_header[6] = 0xfc;      //       //buffer fullness:0x7ff 低6bits
	// number_of_raw_data_blocks_in_frame:
	//    表示ADTS帧中有number_of_raw_data_blocks_in_frame + 1个AAC原始帧。

	return 0;
}

/* select layout with the highest channel count */
static int select_channel_layout(const AVCodec* codec, AVChannelLayout* dst)
{
    const AVChannelLayout* p, * best_ch_layout;
    int best_nb_channels = 0;

    if (!codec->ch_layouts)
    {
        AVChannelLayout layout = AV_CHANNEL_LAYOUT_STEREO;
        return av_channel_layout_copy(dst, &layout);

    }

    p = codec->ch_layouts;
    while (p->nb_channels) {
        int nb_channels = p->nb_channels;

        if (nb_channels > best_nb_channels) {
            best_ch_layout = p;
            best_nb_channels = nb_channels;
        }
        p++;
    }
    return av_channel_layout_copy(dst, best_ch_layout);
}

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

    // 把 frame 传给编码器,调用编码器 cb.encode 函数进行处理
    ret = avcodec_send_frame(ctx, frame);
    if (ret < 0) {
        fprintf(stderr, "Error sending the frame to the encoder\n");
        exit(1);
    }

    /* read all the available output packets (in general there may be any
     * number of them */
    while (ret >= 0) {
        ret = avcodec_receive_packet(ctx, pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            fprintf(stderr, "Error encoding audio frame\n");
            exit(1);
        }
        char adts_header_buf[7] = { 0 };
        adts_header(adts_header_buf, pkt->size, ctx->profile, ctx->sample_rate, ctx->ch_layout.nb_channels);
        fwrite(adts_header_buf, 1, 7, output);

        fwrite(pkt->data, 1, pkt->size, output);
        av_packet_unref(pkt);
    }
}

int main(int argc, char** argv)
{
	const char* filename;
	AVFrame* frame;
	AVPacket* pkt;
	int i, j, k, ret;
	FILE* f;
	float* samples;
	float t, tincr;

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

    // 1. 通过名字或者 id 找到编码器(相当于找到了那个能力结构体指针);获取的结构体会有些编码器的简单介绍,以及编码器支持的能力
    // AVCodec 和 FFCodec 可以相互转换
    const AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_AAC);
	if (!codec) {
		fprintf(stderr, "Codec not found\n");
		exit(1);
	}
    // 2. 通过编码器创建上下文,相当于创建上下文实例,并将 codec 指针保存在上下文中,并根据编码器能力初始化一些参数
    AVCodecContext* c = avcodec_alloc_context3(codec);
	if (!c) {
		fprintf(stderr, "Could not allocate audio codec context\n");
		exit(1);
	}
    // 3. 根据用户需要,以及编码器支持的能力,将编码参数设置到编码器上下文中
	c->bit_rate = 64000;
	c->sample_fmt = AV_SAMPLE_FMT_FLTP;
	c->sample_rate = 48000;
	ret = select_channel_layout(codec, &c->ch_layout);
	if (ret < 0)
		exit(1);

    // 4. 进一步初始化编码器和编码器上下文参数,将 options 传到编码器内部,最后调用编码器的 init 函数,初始化编码器
	if (avcodec_open2(c, codec, NULL) < 0) {
		fprintf(stderr, "Could not open codec\n");
		exit(1);
	}

    // 5. 创建 avframe 并把编码器上下文中的参数赋值给他
	frame = av_frame_alloc();
	if (!frame) {
		fprintf(stderr, "Could not allocate audio frame\n");
		exit(1);
	}

	frame->nb_samples = c->frame_size;
	frame->format = c->sample_fmt;
	ret = av_channel_layout_copy(&frame->ch_layout, &c->ch_layout);
	if (ret < 0)
		exit(1);
    // 6. avframe 根据参数,算出 linesize 和 当前格式需要的 data 大小并创建
	ret = av_frame_get_buffer(frame, 0);
	if (ret < 0) {
		fprintf(stderr, "Could not allocate audio data buffers\n");
		exit(1);
	}
	
    // 7. 将编码数据传给 avframe
        f = fopen(filename, "wb");
    if (!f) {
        fprintf(stderr, "Could not open %s\n", filename);
        exit(1);
    }

    pkt = av_packet_alloc();
    if (!pkt) {
        fprintf(stderr, "could not allocate the packet\n");
        exit(1);
    }

    t = 0;
    tincr = 2 * M_PI * 440.0 / c->sample_rate;
    for (i = 0; i < 200; i++) {
        ret = av_frame_make_writable(frame);
        if (ret < 0)
            exit(1);
        for (k = 0; k < c->ch_layout.nb_channels; k++)
        {
			samples = (float*)frame->data[k];
			for (j = 0; j < c->frame_size; j++) {
				samples[j] = sin(t) * 10000;
				t += tincr;
			}
        }
		// 8. 将 avframe 传给 avcodec_send_frame
		// 9. 通过 avcodec_receive_packet 获取 avpacket 数据
        encode(c, frame, pkt, f);
    }

    encode(c, NULL, pkt, f);
    fclose(f);
    av_frame_free(&frame);
    av_packet_free(&pkt);
    avcodec_free_context(&c);

    return 0;
}

现象

用 vlc 波形显示查看输出的曲线图

备注

ffmpeg demo 在 c++ 环境不能直接编译通过

  1. 添加头文件需要加上 extern "C"
cpp 复制代码
extern"C"
{
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/frame.h>
#include <libavutil/samplefmt.h>
}
  1. 另一个报错不清楚,ffmpeg是怎么编译通过的,c++这边会报错
c 复制代码
av_channel_layout_copy(dst, &(AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO);

需要改成
AVChannelLayout layout = AV_CHANNEL_LAYOUT_STEREO;
av_channel_layout_copy(dst, &layout);
相关推荐
FutureUniant3 小时前
GitHub每日最火火火项目(9.21)
人工智能·计算机视觉·ai·github·音视频
数据蛙苹果恢复专家5 小时前
无损转换:严选4个视频mkv转mp4格式的方法
音视频
EasyCVR5 小时前
视频存储EasyCVR视频监控汇聚管理平台设备录像下载报错404是什么原因?
音视频·视频监控·监控视频接入·视频质量诊断·视频诊断
shelutai7 小时前
FFMPEG: Overlay a video on a video after x seconds
ffmpeg
aqi0013 小时前
FFmpeg开发笔记(五十三)移动端的国产直播录制工具EasyPusher
android·ffmpeg·音视频·直播·流媒体
Q1860000000014 小时前
在HTML中添加视频
前端·html·音视频
学习前端的小z14 小时前
【AI视频】Runway:Gen-2 运镜详解
人工智能·aigc·音视频
学习前端的小z20 小时前
【AI视频】Runway:Gen-2 图文生视频与运动模式详解
人工智能·aigc·音视频
羌俊恩1 天前
视频服务器:GB28181网络视频协议
服务器·网络·音视频
cuijiecheng20181 天前
音视频入门基础:AAC专题(3)——AAC的ADTS格式简介
音视频·aac