编码与格式 / 系统课时
音频帧编码
音频帧编码
本课实现一个可运行的音频编码流程:把大小不固定的 PCM 样本先写入音频 FIFO,再按编码器要求的固定帧长取出、编码,并对最后不足一帧的数据补静音。
学习目标
- 理解音频编码器的
frame_size与样本数量关系 - 使用
AVAudioFifo整理不规则输入块 - 正确补齐尾帧、维护音频
pts并冲刷编码器
为什么音频需要重新分帧
采集、解码或重采样模块每次交付的样本数,通常不等于编码器要求的帧长。例如 MP2 每帧需要 1152 个采样点,而上游可能每次只提供 500 个。直接发送这些小块会导致参数错误,或者让不同编码器表现不一致。
AVAudioFifo 负责在上游块大小与编码帧长之间缓冲样本:先持续写入,累计到 frame_size 后再读取完整一帧。FIFO 空间不足时可自动扩容,读取数量则不会超过当前已缓存的样本数。:contentReference[oaicite:1]{index=1}

音频时间戳按“每个声道的采样点数”累计,而不是按字节数累计。若时间基设置为 1/sample_rate,第一帧 pts=0,下一帧应增加 frame->nb_samples。
固定帧长与尾帧策略
编码器打开后,通过 context->frame_size 读取固定帧长。若编码器带有 AV_CODEC_CAP_VARIABLE_FRAME_SIZE 能力,输入帧可以使用不同的样本数;否则应始终提交完整帧。
文件结束时,FIFO 中可能只剩少量样本。本例先创建完整帧并填充静音,再把剩余样本覆盖到帧首部。这样既保留真实尾音,也满足固定帧长要求。补齐的静音会让编码结果略长于原始时长,封装到容器时可结合真实样本总数或跳过样本信息进一步修正。
完整示例:用 FIFO 编码 MP2
程序生成 1 秒、48 kHz、双声道的 440 Hz 正弦波。上游每次产生 500 个样本,FIFO 将其重新组织为 1152 样本的编码帧,输出文件为 output.mp2。
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <libavcodec/avcodec.h>
#include <libavutil/audio_fifo.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/error.h>
#include <libavutil/frame.h>
#include <libavutil/mem.h>
#include <libavutil/samplefmt.h>
static void fail(const char *message, int error_code) {
char error_text[AV_ERROR_MAX_STRING_SIZE] = {0};
av_strerror(error_code, error_text, sizeof(error_text));
fprintf(stderr, "%s: %s\n", message, error_text);
exit(EXIT_FAILURE);
}
static AVFrame *new_audio_frame(const AVCodecContext *context,
int sample_count) {
AVFrame *frame = av_frame_alloc();
if (!frame) {
return NULL;
}
frame->format = context->sample_fmt;
frame->sample_rate = context->sample_rate;
frame->nb_samples = sample_count;
int ret = av_channel_layout_copy(&frame->ch_layout,
&context->ch_layout);
if (ret < 0) {
av_frame_free(&frame);
return NULL;
}
ret = av_frame_get_buffer(frame, 0);
if (ret < 0) {
av_frame_free(&frame);
return NULL;
}
return frame;
}
static void encode_frame(AVCodecContext *context,
AVFrame *frame,
AVPacket *packet,
FILE *output) {
int ret = avcodec_send_frame(context, frame);
if (ret < 0) {
fail("无法发送音频帧", ret);
}
while (1) {
ret = avcodec_receive_packet(context, packet);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
return;
}
if (ret < 0) {
fail("无法接收压缩包", ret);
}
if (fwrite(packet->data, 1, packet->size, output) !=
(size_t) packet->size) {
fprintf(stderr, "写入输出文件失败\n");
exit(EXIT_FAILURE);
}
av_packet_unref(packet);
}
}
static void send_fifo_frame(AVAudioFifo *fifo,
AVCodecContext *context,
AVPacket *packet,
FILE *output,
int64_t *next_pts,
int samples_to_read) {
AVFrame *frame = new_audio_frame(context, context->frame_size);
if (!frame) {
fprintf(stderr, "无法创建音频帧\n");
exit(EXIT_FAILURE);
}
// 先填静音,最后不足一帧的区域会自然保持为零。
int ret = av_samples_set_silence(frame->data, 0,
frame->nb_samples,
context->ch_layout.nb_channels,
context->sample_fmt);
if (ret < 0) {
fail("无法填充静音", ret);
}
ret = av_audio_fifo_read(fifo, (void **) frame->data,
samples_to_read);
if (ret != samples_to_read) {
fail("FIFO 读取样本失败", ret < 0 ? ret : AVERROR_UNKNOWN);
}
frame->pts = *next_pts;
*next_pts += frame->nb_samples;
encode_frame(context, frame, packet, output);
av_frame_free(&frame);
}
int main(void) {
const AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_MP2);
if (!codec) {
fprintf(stderr, "未找到 MP2 编码器\n");
return EXIT_FAILURE;
}
AVCodecContext *context = avcodec_alloc_context3(codec);
AVPacket *packet = av_packet_alloc();
FILE *output = fopen("output.mp2", "wb");
if (!context || !packet || !output) {
fprintf(stderr, "资源分配失败\n");
return EXIT_FAILURE;
}
context->bit_rate = 192000;
context->sample_fmt = AV_SAMPLE_FMT_S16;
context->sample_rate = 48000;
context->time_base = (AVRational) {1, context->sample_rate};
av_channel_layout_default(&context->ch_layout, 2);
int ret = avcodec_open2(context, codec, NULL);
if (ret < 0) {
fail("无法打开编码器", ret);
}
if (context->frame_size <= 0) {
fprintf(stderr, "示例要求固定帧长编码器\n");
return EXIT_FAILURE;
}
AVAudioFifo *fifo = av_audio_fifo_alloc(
context->sample_fmt,
context->ch_layout.nb_channels,
1
);
if (!fifo) {
fprintf(stderr, "无法创建音频 FIFO\n");
return EXIT_FAILURE;
}
const int source_samples = 48000;
const int chunk_samples = 500;
const int channels = context->ch_layout.nb_channels;
int16_t *chunk = av_malloc_array(
chunk_samples * channels,
sizeof(*chunk)
);
if (!chunk) {
fprintf(stderr, "无法分配输入缓冲区\n");
return EXIT_FAILURE;
}
int generated = 0;
int64_t next_pts = 0;
const double pi = acos(-1.0);
while (generated < source_samples) {
int current = FFMIN(chunk_samples, source_samples - generated);
// 打包格式 S16:左右声道样本按 L、R、L、R 顺序交错。
for (int index = 0; index < current; ++index) {
double angle = 2.0 * pi * 440.0 *
(generated + index) / context->sample_rate;
int16_t value = (int16_t) (sin(angle) * 10000);
chunk[index * channels] = value;
chunk[index * channels + 1] = value;
}
void *input_planes[1] = {chunk};
ret = av_audio_fifo_write(fifo, input_planes, current);
if (ret != current) {
fail("FIFO 写入样本失败", ret < 0 ? ret : AVERROR_UNKNOWN);
}
generated += current;
while (av_audio_fifo_size(fifo) >= context->frame_size) {
send_fifo_frame(fifo, context, packet, output,
&next_pts, context->frame_size);
}
}
int remaining = av_audio_fifo_size(fifo);
int padded_samples = 0;
if (remaining > 0) {
padded_samples = context->frame_size - remaining;
send_fifo_frame(fifo, context, packet, output,
&next_pts, remaining);
}
// 排空编码器内部仍未输出的压缩包。
encode_frame(context, NULL, packet, output);
printf("frame_size=%d source_samples=%d padded_samples=%d\n",
context->frame_size, source_samples, padded_samples);
printf("written output.mp2\n");
av_free(chunk);
av_audio_fifo_free(fifo);
fclose(output);
av_packet_free(&packet);
avcodec_free_context(&context);
return EXIT_SUCCESS;
}编译并运行:
cc audio_encode.c -o audio_encode $(pkg-config --cflags --libs libavcodec libavutil) -lm
./audio_encode预期输出:
frame_size=1152 source_samples=48000 padded_samples=384
written output.mp2验证与常见错误
使用 ffprobe 验证编码格式和声道参数:
ffprobe -v error -show_entries stream=codec_name,sample_rate,channels -of default=noprint_wrappers=1 output.mp2预期输出:
codec_name=mp2
sample_rate=48000
channels=2常见错误是只按字节数计算 pts、忽略平面格式与打包格式的内存差异,或者把不足 frame_size 的尾帧直接发送给固定帧长编码器。接入重采样器时,还应确保 FIFO 的采样格式、采样率和声道布局与编码器上下文完全一致。