编码与格式 / 系统课时

解码资源管理

解码资源管理

本课解决解码程序“正常能跑、异常会泄漏、结尾少帧”的问题。你将建立统一的资源所有权与退出路径,正确处理数据包、帧、解码器刷新和文件结束标记,并能验证所有对象在成功或失败时都被释放。

学习目标

  • 区分 AVPacket、AVFrame、AVCodecContext 与 AVFormatContext 的释放职责
  • 正确处理 EAGAIN、AVERROR_EOF、异常退出和解码器尾帧
  • 掌握结束排空与跳转后刷新之间的区别

资源生命周期与释放顺序

解码过程中,容器层由 AVFormatContext 管理,解码器状态由 AVCodecContext 管理,压缩数据放在 AVPacket,解码结果放在 AVFrame。谁创建对象,谁负责在统一退出路径中释放;循环内反复复用的对象则通过 av_packet_unref() 和 av_frame_unref() 清空引用。

释放通常按“先临时对象、后长期对象”的逆序进行:先释放帧和数据包,再释放解码器上下文,最后关闭输入文件。这样即使初始化只完成一半,goto cleanup 也能安全处理空指针,避免为每个错误分支重复编写清理代码。

FFmpeg 解码资源生命周期与异常退出路径

av_packet_free() 和 av_frame_free() 会释放对象并把指针置空,适合最终销毁;av_packet_unref() 和 av_frame_unref() 只释放当前引用的数据,适合循环复用。两组 API 不能互相替代,否则容易出现重复分配或对象提前失效。

主示例:统一处理解码、排空与清理

下面的完整程序读取一个媒体文件,选择最佳视频流,统计解码帧数,并在所有错误路径上进入同一个清理区。示例使用 FFmpeg 当前的 send/receive 解码接口。

c
#include <stdio.h>
#include <stdlib.h>

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/error.h>

static void print_error(const char *action, int errnum) {
    char message[AV_ERROR_MAX_STRING_SIZE];
    av_strerror(errnum, message, sizeof(message));
    fprintf(stderr, "%s: %s\n", action, message);
}

int main(int argc, char **argv) {
    AVFormatContext *format_ctx = NULL;
    AVCodecContext *decoder_ctx = NULL;
    AVPacket *packet = NULL;
    AVFrame *frame = NULL;
    const AVCodec *decoder = NULL;
    int video_stream = -1;
    int frame_count = 0;
    int ret = 0;
    int exit_code = EXIT_FAILURE;

    // 所有资源先置空,任意失败都可以安全跳到统一清理区。
    if (argc != 2) {
        fprintf(stderr, "用法: %s <input-media>\n", argv[0]);
        return EXIT_FAILURE;
    }

    if ((ret = avformat_open_input(&format_ctx, argv[1], NULL, NULL)) < 0) {
        print_error("打开输入失败", ret);
        goto cleanup;
    }
    if ((ret = avformat_find_stream_info(format_ctx, NULL)) < 0) {
        print_error("读取流信息失败", ret);
        goto cleanup;
    }

    // 从容器参数创建并打开对应的视频解码器。
    ret = av_find_best_stream(
        format_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &decoder, 0
    );
    if (ret < 0) {
        print_error("未找到可解码的视频流", ret);
        goto cleanup;
    }
    video_stream = ret;

    decoder_ctx = avcodec_alloc_context3(decoder);
    if (!decoder_ctx) {
        ret = AVERROR(ENOMEM);
        print_error("创建解码器上下文失败", ret);
        goto cleanup;
    }

    ret = avcodec_parameters_to_context(
        decoder_ctx, format_ctx->streams[video_stream]->codecpar
    );
    if (ret < 0) {
        print_error("复制流参数失败", ret);
        goto cleanup;
    }
    if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0) {
        print_error("打开解码器失败", ret);
        goto cleanup;
    }

    packet = av_packet_alloc();
    frame = av_frame_alloc();
    if (!packet || !frame) {
        ret = AVERROR(ENOMEM);
        print_error("创建 packet 或 frame 失败", ret);
        goto cleanup;
    }

    // packet 与 frame 在循环中复用,每轮及时解除旧数据引用。
    while ((ret = av_read_frame(format_ctx, packet)) >= 0) {
        if (packet->stream_index == video_stream) {
            ret = avcodec_send_packet(decoder_ctx, packet);
            if (ret < 0) {
                print_error("发送压缩数据失败", ret);
                av_packet_unref(packet);
                goto cleanup;
            }

            while ((ret = avcodec_receive_frame(decoder_ctx, frame)) >= 0) {
                frame_count++;
                av_frame_unref(frame);
            }
            if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
                print_error("接收解码帧失败", ret);
                av_packet_unref(packet);
                goto cleanup;
            }
        }
        av_packet_unref(packet);
    }

    if (ret != AVERROR_EOF) {
        print_error("读取输入失败", ret);
        goto cleanup;
    }

    // 发送 NULL 表示输入结束,继续接收解码器内部缓存的尾帧。
    ret = avcodec_send_packet(decoder_ctx, NULL);
    if (ret < 0 && ret != AVERROR_EOF) {
        print_error("启动解码器排空失败", ret);
        goto cleanup;
    }

    while ((ret = avcodec_receive_frame(decoder_ctx, frame)) >= 0) {
        frame_count++;
        av_frame_unref(frame);
    }
    if (ret != AVERROR_EOF && ret != AVERROR(EAGAIN)) {
        print_error("排空解码器失败", ret);
        goto cleanup;
    }

    printf("decoded video frames: %d\n", frame_count);
    exit_code = EXIT_SUCCESS;

cleanup:
    // 按临时对象到长期对象的逆序释放,free 函数会把指针置空。
    av_frame_free(&frame);
    av_packet_free(&packet);
    avcodec_free_context(&decoder_ctx);
    avformat_close_input(&format_ctx);
    puts("resources released");
    return exit_code;
}

预期结果

text
程序可在链接 libavformat、libavcodec 和 libavutil 后编译;成功路径与任意 goto cleanup 路径都会执行资源释放。

在安装 FFmpeg 开发库并准备测试文件后编译运行:

bash
cc decode_resources.c -o decode_resources $(pkg-config --cflags --libs libavformat libavcodec libavutil)
./decode_resources <PATH>

预期输出

text
decoded video frames: <N>
resources released

<PATH> 是实际媒体文件路径,<N> 取决于视频内容。若打开或解码失败,程序会先输出具体错误,再输出 resources released,因此可以确认异常路径也进入了统一清理区。

异常、结束标记与刷新不能混用

AVERROR(EAGAIN) 不是致命错误。对 avcodec_receive_frame() 来说,它通常表示当前没有更多输出,需要继续发送输入;对发送函数来说,则表示应先取走已有输出。正确做法是保持“发送一次,持续接收直到 EAGAIN”的节奏。

容器读取返回 AVERROR_EOF 只表示输入端没有更多数据,解码器内部仍可能保存延迟帧。此时应向 avcodec_send_packet() 发送 NULL,随后持续接收,直到解码器返回 AVERROR_EOF。跳过这一步,含 B 帧或内部缓冲的流可能在结尾丢帧。

avcodec_flush_buffers() 用于跳转、切换时间点或重新使用同一解码器时清除旧状态,不是文件结束时的排空操作。执行 seek 后,应先完成容器跳转,再刷新对应解码器,防止跳转前缓存帧混入新时间点。

清理函数应允许指针为 NULL,但循环中的 unref 仍要在每次使用后及时执行。统一退出路径解决“最终释放”,不能替代“循环及时释放引用”。

验收资源管理是否正确

先用正常媒体验证帧数和退出码,再分别测试不存在的文件、损坏文件和只含音频的文件。每种失败都应输出可定位的错误,并进入 cleanup。在 Linux 上还可以使用 AddressSanitizer 或 Valgrind 检查泄漏,但不能只凭“进程退出后内存归还系统”判断代码正确。

重点检查三件事:循环每轮是否 unref、输入结束是否发送 NULL 排空、所有初始化失败是否都能安全释放已创建对象。做到这三点,解码模块才适合被播放器、转码器或服务端任务长期复用。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

解码资源管理

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通