FFmpeg———encode_video(学习)

本文详细描述了如何使用C++实现一个针对图片的encode_video函数,通过AVCodecContext和AVFrame等结构,进行H.264编码,同时记录了在编译和编码过程中遇到的问题及解决方法。

前言

encode_video:实现了对图片使用指定编码进行编码,生成可播放的视频流,编译时出现了一些错误,做了一些调整。
基本流程:
1、获取指定的编码器
2、编码器内存申请
3、编码器上下文内容参数设置
4、打开编码器
5、申请数据帧内存
6、模拟图片
7、编码

源码

测试代码,做了部分修改

#include <iostream>

using namespace std;


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

extern"C"
{
#include "libavcodec/avcodec.h"
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "libavutil/error.h"
}

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

    /* send the frame to the encoder */
    if (frame)
        printf("Send frame %lld\n", frame->pts);  //修改 lld 替换 PRId64

    /*avcodec_send_frame 与 avcodec_receive_packet 配合使用*/
    ret = avcodec_send_frame(enc_ctx, frame);
    if (ret < 0) {
        fprintf(stderr, "Error sending a frame for encoding\n");
        exit(1);
    }

    while (ret >= 0) {
        ret = avcodec_receive_packet(enc_ctx, pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            fprintf(stderr, "Error during encoding\n");
            exit(1);
        }

        printf("Write packet %lld (size=%d)\n", pkt->pts, pkt->size); //修改 lld 替换 PRId64
        fwrite(pkt->data, 1, pkt->size, outfile);
        av_packet_unref(pkt); //清空数据压缩包
    }
}

int main()
{
    const char* filename;
    const AVCodec* codec;
    AVCodecContext* c = NULL;  // 编码器上下文
    int i, ret, x, y;
    FILE* f;
    AVFrame* frame;  // 音视频数据帧结构体
    AVPacket* pkt;
    uint8_t endcode[] = { 0, 0, 1, 0xb7 };

    filename = "text_264";

    /* find the mpeg1video encoder */
    codec = avcodec_find_encoder(AV_CODEC_ID_H264);
    if (!codec) {
        fprintf(stderr, "Codec not found\n");
        exit(1);
    }

   // 为编码器申请空间并设置初始值
    c = avcodec_alloc_context3(codec);
    if (!c) {
        fprintf(stderr, "Could not allocate video codec context\n");
        exit(1);
    }

    pkt = av_packet_alloc();
    if (!pkt)
        exit(1);

    /* put sample parameters */
    c->bit_rate = 400000;
    /* 分辨率 为2的倍数 */
    c->width = 352;
    c->height = 288;
    /* frames per second */
    c->time_base.num = 1;
    c->time_base.den = 25;

    //帧率
    c->framerate.num = 25;
    c->framerate.den = 1;


    /* emit one intra frame every ten frames
     * check frame pict_type before passing frame
     * to encoder, if frame->pict_type is AV_PICTURE_TYPE_I
     * then gop_size is ignored and the output of encoder
     * will always be I frame irrespective to gop_size
     */
    c->gop_size = 10;
    c->max_b_frames = 1;  //非B帧之间的最大的B帧数
    c->pix_fmt = AV_PIX_FMT_YUV420P;   //像素格式

    if (codec->id == AV_CODEC_ID_H264)
        av_opt_set(c->priv_data, "preset", "slow", 0);   //设置属性

    /* open it */
    ret = avcodec_open2(c, codec, NULL);
    if (ret < 0) {

        fprintf(stderr, "Could not open codec: %s\n", av_err2str(ret));
        exit(1);
    }

    f = fopen(filename, "wb");
    if (!f) {
        fprintf(stderr, "Could not open %s\n", filename);
        exit(1);
    }

    frame = av_frame_alloc();
    if (!frame) {
        fprintf(stderr, "Could not allocate video frame\n");
        exit(1);
    }
    frame->format = c->pix_fmt;
    frame->width = c->width;
    frame->height = c->height;

    ret = av_frame_get_buffer(frame, 0);  //申请数据帧缓冲区
    if (ret < 0) {
        fprintf(stderr, "Could not allocate the video frame data\n");
        exit(1);
    }

    /* encode 1 second of video */
    for (i = 0; i < 25; i++) {
        fflush(stdout);

        /* Make sure the frame data is writable.
           On the first round, the frame is fresh from av_frame_get_buffer()
           and therefore we know it is writable.
           But on the next rounds, encode() will have called
           avcodec_send_frame(), and the codec may have kept a reference to
           the frame in its internal structures, that makes the frame
           unwritable.
           av_frame_make_writable() checks that and allocates a new buffer
           for the frame only if necessary.
         */
        ret = av_frame_make_writable(frame);    //确保数据帧是可写
        if (ret < 0)
            exit(1);

        /* 
        模拟图片数据
         */
         /* Y */
        for (y = 0; y < c->height; y++) {
            for (x = 0; x < c->width; x++) {
                frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
            }
        }

        /* Cb and Cr */
        for (y = 0; y < c->height / 2; y++) {
            for (x = 0; x < c->width / 2; x++) {
                frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
                frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
            }
        }

        frame->pts = i;

        /* encode the image */
        encode(c, frame, pkt, f);
    }

    /* flush the encoder */
    encode(c, NULL, pkt, f);

    /* Add sequence end code to have a real MPEG file.
       It makes only sense because this tiny examples writes packets
       directly. This is called "elementary stream" and only works for some
       codecs. To create a valid file, you usually need to write packets
       into a proper file format or protocol; see mux.c.
     */
    if (codec->id == AV_CODEC_ID_MPEG1VIDEO || codec->id == AV_CODEC_ID_MPEG2VIDEO)
        fwrite(endcode, 1, sizeof(endcode), f);
    fclose(f);

    avcodec_free_context(&c);
    av_frame_free(&frame);
    av_packet_free(&pkt);

    return 0;
}

函数

1、int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame);
向编码器发送音频或视频的数据包与
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt);配合使用
成功返回0
2、av_err2str(errnum)
编译会报错
修改:

char av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 };
#define av_err2str(errnum) \
    av_make_error_string(av_error, AV_ERROR_MAX_STRING_SIZE, errnum)

最终效果

在这里插入图片描述

你提出的问题非常关键,属于**嵌入式音视频系统开发中的“数据块抽象与占位流合成”问题**。 我们来一步步分析你的结构体和需求: --- ### ✅ 你的目标 > **能否用一张静态图片(或预定义图像)手动填充 `avdm_block_t` 结构,使其在摄像头失效时作为“替代视频块”使用?** 换句话说: 👉 原本 `avdm_block_t` 是从摄像头实时采集的 GOP 数据块; 现在你想在没有摄像头输入时,**人工构造一个合法的 `avdm_block_t`,内容是 H.264 编码的一张图片 + 若干 P 帧(小体积),并填入对应的时间戳、编码信息等元数据。** ✅ **答案是:完全可以!但需要正确编码和封装。** --- ## 🔍 一、理解 `avdm_block_t` 的用途 ```c typedef struct __avdm_block { time_t start_time; // 开始时间(系统时间) time_t end_time; // 结束时间 U32 unitCnt; // 帧数量(如 GOP 内帧数) U8* addr; // 指向编码后的视频流 buffer U32 len; // 流总长度 U64 pts; // 首帧 PTS(单位?us/ms?需确认) union { video_info_t video; audio_info_t audio; } unique_info; } avdm_block_t; ``` 这个结构本质上是一个 **AV 数据块容器(类似 AVPacket 的集合)**,用于传输一个 GOP 或一段音频。 其中: - `addr` 和 `len` 是核心 —— 存放实际编码后的 **H.264/H.265 码流** - `unique_info.video` 描述该 block 的视频属性(I帧类型、GOP 时长等) --- ## ✅ 二、可以用图片构造这样的 block 吗? ### ✔️ 可以,只要满足以下条件: | 条件 | 说明 | |------|------| | ✅ 1. 图片被编码为 H.264/H.265 码流 | 必须是标准编码格式,不能是原始 YUV 或 JPEG | | ✅ 2. 第一帧必须是 I 帧(IDR/Virtual I) | 符合 `iframe_type` 要求 | | ✅ 3. `addr` 指向编码后码流内存 | 动态分配并拷贝进去 | | ✅ 4. `pts`, `duration_us`, `iframe_timestamp` 正确设置 | 时间戳对齐播放/录制逻辑 | | ✅ 5. `unitCnt` 设置合理 | 如:1 个 I 帧 + 24 个 P 帧 → `unitCnt = 25` | --- ## ✅ 三、如何实现?步骤详解(C语言 + FFmpeg库) 我们将: 1. 将一张图片(PNG/JPEG)加载成 RGB; 2. 使用 FFmpeg 的 `libavcodec` 编码为 H.264 码流(首帧为 I 帧,后续为 P 帧); 3. 把编码后的字节流写入 `avdm_block_t.addr`; 4. 填充 `video_info_t` 中的各项字段; 5. 返回一个合法的 `avdm_block_t` 替代摄像头输出。 --- ### 🛠 示例代码(基于 libavcodec 实现) ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // 假设这些类型已定义(根据你的平台) typedef enum { TP_ENCODE_H264, TP_ENCODE_H265 } TP_ENCODE_TYPE_E; typedef enum { TP_I_FRAME_IDR, TP_I_FRAME_VIRTUAL } TP_VIDEO_FRAME_TYPE_E; typedef unsigned int U32; typedef unsigned long long U64; typedef unsigned char U8; // 结构体定义(同你提供) typedef struct __video_info { TP_ENCODE_TYPE_E encode_type; TP_VIDEO_FRAME_TYPE_E iframe_type; U32 iframe_size; U64 iframe_timestamp; U64 duration_us; } video_info_t; typedef struct __avdm_block { time_t start_time; time_t end_time; U32 unitCnt; U8* addr; U32 len; U64 pts; union { video_info_t video; // audio_info_t audio; } unique_info; } avdm_block_t; // ------------------------ 外部 FFmpeg 头文件 ------------------------ extern "C" { #include <libavcodec/avcodec.h> #include <libavutil/imgutils.h> #include <libswscale/swscale.h> } // ------------------------ 参数配置 ------------------------ #define WIDTH 1280 #define HEIGHT 720 #define FPS 25 #define GOP_SIZE 30 // 每30帧一个I帧(但我们只发一次) #define DURATION_S 2 // 占位 GOP 持续2秒 → 50帧 // ------------------------ 全局编码器上下文 ------------------------ static AVCodec *codec; static AVCodecContext *enc_ctx = NULL; static struct SwsContext *sws_ctx = NULL; static AVFrame *frame = NULL; static uint8_t *rgb_buffer = NULL; static uint8_t *yuv_buffer = NULL; // ------------------------ 初始化编码器 ------------------------ int init_encoder() { av_register_all(); codec = avcodec_find_encoder(AV_CODEC_ID_H264); if (!codec) { printf("H.264 encoder not found.\n"); return -1; } enc_ctx = avcodec_alloc_context3(codec); if (!enc_ctx) return -1; enc_ctx->bit_rate = 4000000; enc_ctx->width = WIDTH; enc_ctx->height = HEIGHT; enc_ctx->framerate = (AVRational){FPS, 1}; enc_ctx->time_base = (AVRational){1, FPS}; // PTS 单位:tick = 1/FPS 秒 enc_ctx->gop_size = GOP_SIZE; enc_ctx->max_b_frames = 0; enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P; // 快速编码设置 av_opt_set(enc_ctx->priv_data, "preset", "ultrafast", 0); av_opt_set(enc_ctx->priv_data, "tune", "stillimage", 0); if (avcodec_open2(enc_ctx, codec, NULL) < 0) { printf("Could not open codec.\n"); return -1; } // 分配 YUV frame frame = av_frame_alloc(); frame->format = AV_PIX_FMT_YUV420P; frame->width = WIDTH; frame->height = HEIGHT; av_frame_get_buffer(frame, 32); // 分配 RGB/YUV 临时缓冲区 rgb_buffer = av_malloc(av_image_get_buffer_size(AV_PIX_FMT_RGB24, WIDTH, HEIGHT, 1)); yuv_buffer = (uint8_t *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P, WIDTH, HEIGHT, 1)); sws_ctx = sws_getContext(WIDTH, HEIGHT, AV_PIX_FMT_RGB24, WIDTH, HEIGHT, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL); return 0; } // ------------------------ 构造占位图像(绿色)------------------------ void fill_placeholder_image() { for (int i = 0; i < WIDTH * HEIGHT; i++) { rgb_buffer[3*i + 0] = 0; // Blue rgb_buffer[3*i + 1] = 255; // Green rgb_buffer[3*i + 2] = 0; // Red } } // ------------------------ RGB -> YUV 转换 ------------------------ int rgb_to_yuv() { uint8_t *src_slice[] = { rgb_buffer }; int src_stride[] = { 3 * WIDTH }; sws_scale(sws_ctx, src_slice, src_stride, 0, HEIGHT, frame->data, frame->linesize); return 0; } // ------------------------ 编码生成完整 GOP 码流 ------------------------ avdm_block_t* create_placeholder_block(U64 base_pts) { AVPacket pkt; av_packet_init(&pkt); // 动态构建 buffer U8 *buffer = NULL; U32 buf_size = 0; U32 buf_capacity = 1024 * 1024; // 初始1MB buffer = malloc(buf_capacity); if (!buffer) return NULL; // 加载图片 → YUV fill_placeholder_image(); rgb_to_yuv(); // 设置 PTS U64 pts = base_pts; int frame_count = 0; // 编码多帧(第一个是 I 帧,后面是 P 帧) for (int i = 0; i < FPS * DURATION_S; i++) { frame->pts = pts + i; int ret = avcodec_send_frame(enc_ctx, i == 0 ? frame : frame); // 重复发送相同帧 while (ret >= 0) { ret = avcodec_receive_packet(enc_ctx, &pkt); if (ret == AVERROR(EAGAIN)) break; if (ret == AVERROR_EOF) break; if (ret < 0) goto fail; // 扩容检查 if (buf_size + pkt.size > buf_capacity) { buf_capacity *= 2; U8 *new_buf = realloc(buffer, buf_capacity); if (!new_buf) goto fail; buffer = new_buf; } memcpy(buffer + buf_size, pkt.data, pkt.size); buf_size += pkt.size; av_packet_unref(&pkt); frame_count++; } } // Flush 编码器 avcodec_send_frame(enc_ctx, NULL); while (avcodec_receive_packet(enc_ctx, &pkt) == 0) { if (buf_size + pkt.size > buf_capacity) { buf_capacity *= 2; U8 *new_buf = realloc(buffer, buf_capacity); if (!new_buf) goto fail; buffer = new_buf; } memcpy(buffer + buf_size, pkt.data, pkt.size); buf_size += pkt.size; av_packet_unref(&pkt); frame_count++; } // ✅ 成功生成码流,填充 avdm_block_t avdm_block_t *block = (avdm_block_t*)calloc(1, sizeof(avdm_block_t)); if (!block) goto fail; block->start_time = time(NULL); block->end_time = block->start_time + DURATION_S; block->unitCnt = frame_count; block->addr = buffer; block->len = buf_size; block->pts = base_pts; // 填充 video info block->unique_info.video.encode_type = TP_ENCODE_H264; block->unique_info.video.iframe_type = TP_I_FRAME_IDR; // 或 Virtual I 根据需求 block->unique_info.video.iframe_size = 0; // 可在编码后记录第一个 NALU 大小 block->unique_info.video.iframe_timestamp = base_pts; block->unique_info.video.duration_us = (U64)DURATION_S * 1000000; // us return block; fail: free(buffer); av_packet_unref(&pkt); return NULL; } // ------------------------ 清理资源 ------------------------ void destroy_encoder() { if (enc_ctx) { avcodec_free_context(&enc_ctx); } if (frame) av_frame_free(&frame); if (sws_ctx) sws_freeContext(sws_ctx); if (rgb_buffer) av_freep(&rgb_buffer); if (yuv_buffer) av_freep(&yuv_buffer); } ``` --- ### ✅ 使用方式(示例) ```c int main() { if (init_encoder() != 0) { printf("Failed to initialize encoder.\n"); return -1; } // 创建占位 block(假设当前 PTS 为 1000000 微秒) avdm_block_t *placeholder = create_placeholder_block(1000000); if (placeholder) { printf("Created placeholder block:\n"); printf(" Frame count: %u\n", placeholder->unitCnt); printf(" Data size: %u bytes\n", placeholder->len); printf(" PTS: %llu\n", placeholder->pts); // 这个 block 可以传给下游模块(如存储、推流) // 下游会认为这是一个正常的 GOP 数据块 } // 最后释放 free(placeholder->addr); free(placeholder); destroy_encoder(); return 0; } ``` --- ## ✅ 四、注意事项 | 项目 | 建议 | |------|------| | **PTS 单位一致性** | 确保 `pts` 单位与主系统一致(通常是微秒 or 视频 tick) | | **iframe_size** | 可通过解析第一个 NALU 获取 I 帧大小 | | **内存管理** | `addr` 必须动态分配,由接收方负责释放(或加引用计数) | | **线程安全** | 编码器上下文不要跨线程共享 | | **硬件加速** | 若支持 V4L2/VAAPI/NVENC,替换编码器名称即可提升性能 | --- ## ✅ 总结 > ✔️ 你可以完全用一张图片构造出符合 `avdm_block_t` 格式的视频块! 只需: 1. 用 FFmpeg 编码图片为 H.264 GOP; 2. 把编码后的字节流放入 `addr`; 3. 正确填写 `video_info_t` 和时间戳; 4. 返回 `avdm_block_t*` 给上层处理。 这样就能实现“摄像头失效 → 自动切换到静态提示画面”的功能,且对上层透明。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liu Zz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值