ffmpeg 创建编码器和封装视频

ffmpeg 创建编码器和封装视频

基于ffmpeg 6.1

1.创建编码器AVCodecContext和封装视频的AVFormatContext

//编码参数
struct EncodeParam
{
    AVCodecContext *codeCtx = nullptr;
    AVFrame* frame = nullptr;
    std::string encoderName = "libx265";//编码器 libx264等
    uint32_t width = 0;
    uint32_t height = 0;
    AVPixelFormat pixFmt = AV_PIX_FMT_YUV420P;
    AVRational frameRate = {0, 1};
    AVRational timeBase = {0, 1};
    uint32_t gopSize = 30;//I帧最大间隔。最多每 30 帧会有一个 I 帧
    uint32_t maxBFrame = 0;//在两个参考帧(I 或 P 帧)之间最多插入多少个 B 帧。B 帧利用前后帧进行双向预测,能显著提高压缩率,但会增加编码和解码的延迟
    uint32_t bitRate = 10 * 1024 * 1024 * 5;//5Mb 平均码率,编码器会尽量保证码率靠近它
    int32_t crf = -1;//码率使用crf模式。-1不启动。0-100,越小越清晰
};

//封装视频参数
struct VideoParam
{    
    AVFormatContext *fmtCtx = nullptr;
    AVPacket *packet = nullptr;
    uint64_t startPts = 0;
    std::string fileName;
};

bool CreateEncoder(EncodeParam &param)
{
    auto &encodeCtx = param.codeCtx;
    if (encodeCtx)
    {
        LOG("encoder is exsits. ");
        return false;
    }

    const AVCodec *encoder = nullptr;
     //查找编码器 libx265
    encoder = avcodec_find_encoder_by_name(param.encoderName.c_str());
    if (!encoder)
    {
        LOG("necessary encoder not found");
        return false;
    }

    //创建编码器Context
    encodeCtx = avcodec_alloc_context3(encoder);
    if (!encodeCtx)
    {
        LOG("failed to allocate the encoder context");
        return false;
    }
    
    //编码器要求 `AV_PIX_FMT_YUV420P` 且宽高为偶数
    encodeCtx->width = param.width;
    encodeCtx->height = param.height;
    encodeCtx->framerate = param.frameRate;
    encodeCtx->pix_fmt = param.pixFmt;
    encodeCtx->time_base = param.timeBase;
    encodeCtx->gop_size = param.gopSize;
    encodeCtx->max_b_frames = param.maxBFrame;
    //encodeCtx->width * encodeCtx->height * 1.5
    encodeCtx->bit_rate = param.bitRate;
    //码率使用CRF模式,保证清晰度稳定,crf越小越清晰,最小为0
    AVDictionary *options = NULL;
    if (param.crf >= 0)
    {
        param.crf = param.crf > 100 ? 100 : param.crf;
        std::string tmp = "crf=";
        tmp.append(std::to_string(param.crf));
        av_dict_set(&options, "preset", "medium", 0);
        av_dict_set(&options, "x265-params", tmp.c_str(), 0);
    }
    int ret = avcodec_open2(encodeCtx, encoder, &options);
    if (options)
    {
        av_dict_free(&options);
    }
    if (ret < 0)
    {
        avcodec_free_context(&encodeCtx);
        encodeCtx = nullptr;
        LOG("cannot open video encoder for stream.");
        return false;
    }

    //在这里,把AVFrame和AVPacket一起创建了
    if (param.frame)
    {
        av_frame_free(&param.frame);
        param.frame = nullptr;
    }

    param.frame = av_frame_alloc();
    if (nullptr == param.frame)
    {
        avcodec_free_context(&encodeCtx);
        encodeCtx = nullptr;
        LOG("av_frame_alloc failed.");
        return false;
    }

    param.frame->format = param.pixFmt;
    param.frame->width = encodeCtx->width;
    param.frame->height = encodeCtx->height;
    if (av_frame_get_buffer(param.frame, 0) < 0)
    {
        avcodec_free_context(&encodeCtx);
        encodeCtx = nullptr;
        av_frame_free(&param.frame);
        param.frame = nullptr;
        LOG("av_frame_get_buffer failed.");
        return false;
    }

    return true;
}

void ReleaseEncoder(EncodeParam &param)
{
    auto &encodeCtx = param.codeCtx;
    if (nullptr == encodeCtx)
    {
        return;
    }

    avcodec_free_context(&encodeCtx);
    encodeCtx = nullptr;

    if (param.frame)
    {
        av_frame_free(&param.frame);
        param.frame = nullptr;
    }        
}
    
bool CreateVideo(VideoParam &param, AVCodecContext *&encodeCtx)
{        
    AVFormatContext* &fmtCtx = param.fmtCtx;
    std::string &name = param.fileName;
    if (nullptr == encodeCtx)
    {
        LOG("encoder is null.");
        return false;
    }

    if (fmtCtx)
    {
        LOG("fmtCtx is exists.");
        return false;
    }

    if (param.packet)
    {
        av_packet_free(&param.packet);
        param.packet = nullptr;
    }

    param.packet = av_packet_alloc();
    if (nullptr == param.packet)
    {
        LOG("av_packet_alloc failed.");
        return false;
    }

    int ret = avformat_alloc_output_context2(&fmtCtx, NULL, NULL, name.c_str());
    if (ret < 0 || !fmtCtx)
    {
        LOG("could not create output context. ret:%d", ret);
        return false;
    }

    AVStream *outStream = nullptr;
    outStream = avformat_new_stream(fmtCtx, NULL);
    if (!outStream)
    {
        avformat_free_context(fmtCtx);
        fmtCtx = nullptr;
        LOG("failed allocating output stream.");
        return false;
    }

    ret = avcodec_parameters_from_context(outStream->codecpar, encodeCtx);
    if (ret < 0)
    {
        avformat_free_context(fmtCtx);
        fmtCtx = nullptr;
        LOG("failed to copy encoder parameters to output stream. ret:%d", ret);
        return false;
    }

    LOG("outStream codec_id: %d, format: %d", outStream->codecpar->codec_id, outStream->codecpar->format);
    av_dump_format(fmtCtx, 0, name.c_str(), 1);        
    if (!(fmtCtx->oformat->flags & AVFMT_NOFILE))
    {
        //打开AVIOContext
        //AVIOContext是ffmpeg中管理输入输出数据的结构体
        ret = avio_open(&fmtCtx->pb, name.c_str(), AVIO_FLAG_WRITE);
        if (ret < 0)
        {
            avformat_free_context(fmtCtx);
            fmtCtx = nullptr;
            LOG("could not open output file '%s'. ret:%d", name.c_str(), ret);
            return false;
        }
    }

    //写入文件头
    ret = avformat_write_header(fmtCtx, NULL);
    if (ret < 0)
    {
        avio_closep(&fmtCtx->pb);
        avformat_free_context(fmtCtx);
        fmtCtx = nullptr;
        LOG("error occurred when opening output file. ret:%d", ret);
        return false;
    }
    return true;
}

void ReleaseVideo(VideoParam &param)
{
    auto &fmtCtx = param.fmtCtx;
    if (nullptr == fmtCtx)
    {
        return;
    }

    av_write_trailer(fmtCtx);
    avio_closep(&fmtCtx->pb);
    avformat_free_context(fmtCtx);

    LOG("video writer stopped");
    if (param.packet)
    {
        av_packet_free(&param.packet);
        param.packet = nullptr;
    }
    param.startPts = 0;

    fmtCtx = nullptr;
}

2. 编码YUV420P的数据为mp4的示例

encode.h

/**
 * 使用ffmpeg6.1
 * 1.创建265编码器
 * 2.输入YUV420P原始图像数据,生成MP4
 */
#ifndef _ENCODE_H_
#define _ENCODE_H_

extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}

#include <string>

#ifdef _MSC_VER
    #define LOG_FUNC __FUNCSIG__
#else
    #define LOG_FUNC __FUNCTION__
#endif

namespace codec
{
void SimpleLog(const char *fmt, ...);
#define LOG(msg, ...) SimpleLog("%s:%s(%d): " msg, __FILE__, LOG_FUNC, __LINE__, ##__VA_ARGS__)

struct EncodeParam
{
    AVCodecContext *codeCtx = nullptr;
    AVFrame* frame = nullptr;
    std::string encoderName = "libx265";//编码器 libx264等
    uint32_t width = 0;
    uint32_t height = 0;
    AVPixelFormat pixFmt = AV_PIX_FMT_YUV420P;
    AVRational frameRate = {0, 1};
    AVRational timeBase = {0, 1};
    uint32_t gopSize = 30;//I帧最大间隔。最多每 30 帧会有一个 I 帧
    uint32_t maxBFrame = 0;//在两个参考帧(I 或 P 帧)之间最多插入多少个 B 帧。B 帧利用前后帧进行双向预测,能显著提高压缩率,但会增加编码和解码的延迟
    uint32_t bitRate = 10 * 1024 * 1024 * 5;//5Mb 平均码率,编码器会尽量保证码率靠近它
    int32_t crf = -1;//码率使用crf模式。-1不启动。0-100,越小越清晰
};

struct VideoParam
{    
    AVFormatContext *fmtCtx = nullptr;
    AVPacket *packet = nullptr;
    uint64_t startPts = 0;
    std::string fileName;
};

class Encoder
{
public:
    Encoder();
    ~Encoder();

    bool OpenVideoWriter();
    void CloseVideoWriter();

    //yuvData:Y 平面 + U 平面 + V 平面
    bool WriteFrame(uint8_t* yuvData, uint32_t width, uint32_t height, uint64_t timeStampMs);    
private:
    bool EncodeAndWrite(EncodeParam &encodeParam, VideoParam &videoParam, bool flush = false);

    void FlushEncoder();

private:
    bool mIsRecording = false;
    EncodeParam mEncodeParam;
    VideoParam mVideoParam;
};

}//namespace codec

#endif //_ENCODE_H_

encode.cpp

#include "encode/happy.h"

#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <fstream>

#include <opencv2/imgproc.hpp>

static AVRational DEFAULT_TIME_BASE{1, 1000}; //ms

namespace codec
{
void SimpleLog(const char *format, ...)
{
    std::string str;
    do
    {
        va_list args;
        va_start(args, format);
        const auto len = vsnprintf(nullptr, 0, (format), args);
        if (len <= 0)
        {
            va_end(args);
            break;
        }

        (str).resize(len);
        va_start(args, format);
        vsnprintf(&(str).front(), len + 1, (format), args);
        va_end(args);
    } while (0);

    if (str.empty())
    {
        return;
    }
    printf("%s\n", str.c_str());
}

bool CreateEncoder(EncodeParam &param)
{
    auto &encodeCtx = param.codeCtx;
    if (encodeCtx)
    {
        LOG("encoder is exsits. ");
        return false;
    }

    const AVCodec *encoder = nullptr;
     //查找编码器 libx265
    encoder = avcodec_find_encoder_by_name(param.encoderName.c_str());
    if (!encoder)
    {
        LOG("necessary encoder not found");
        return false;
    }

    //创建编码器Context
    encodeCtx = avcodec_alloc_context3(encoder);
    if (!encodeCtx)
    {
        LOG("failed to allocate the encoder context");
        return false;
    }
    
    //编码器要求 `AV_PIX_FMT_YUV420P` 且宽高为偶数
    encodeCtx->width = param.width;
    encodeCtx->height = param.height;
    encodeCtx->framerate = param.frameRate;
    encodeCtx->pix_fmt = param.pixFmt;
    encodeCtx->time_base = param.timeBase;
    encodeCtx->gop_size = param.gopSize;
    encodeCtx->max_b_frames = param.maxBFrame;
    //encodeCtx->width * encodeCtx->height * 1.5
    encodeCtx->bit_rate = param.bitRate;
    //码率使用CRF模式,保证清晰度稳定,crf越小越清晰,最小为0
    AVDictionary *options = NULL;
    if (param.crf >= 0)
    {
        param.crf = param.crf > 100 ? 100 : param.crf;
        std::string tmp = "crf=";
        tmp.append(std::to_string(param.crf));
        av_dict_set(&options, "preset", "medium", 0);
        av_dict_set(&options, "x265-params", tmp.c_str(), 0);
    }
    int ret = avcodec_open2(encodeCtx, encoder, &options);
    if (options)
    {
        av_dict_free(&options);
    }
    if (ret < 0)
    {
        avcodec_free_context(&encodeCtx);
        encodeCtx = nullptr;
        LOG("cannot open video encoder for stream.");
        return false;
    }

    //在这里,把AVFrame和AVPacket一起创建了
    if (param.frame)
    {
        av_frame_free(&param.frame);
        param.frame = nullptr;
    }

    param.frame = av_frame_alloc();
    if (nullptr == param.frame)
    {
        avcodec_free_context(&encodeCtx);
        encodeCtx = nullptr;
        LOG("av_frame_alloc failed.");
        return false;
    }

    param.frame->format = param.pixFmt;
    param.frame->width = encodeCtx->width;
    param.frame->height = encodeCtx->height;
    if (av_frame_get_buffer(param.frame, 0) < 0)
    {
        avcodec_free_context(&encodeCtx);
        encodeCtx = nullptr;
        av_frame_free(&param.frame);
        param.frame = nullptr;
        LOG("av_frame_get_buffer failed.");
        return false;
    }

    return true;
}

void ReleaseEncoder(EncodeParam &param)
{
    auto &encodeCtx = param.codeCtx;
    if (nullptr == encodeCtx)
    {
        return;
    }

    avcodec_free_context(&encodeCtx);
    encodeCtx = nullptr;

    if (param.frame)
    {
        av_frame_free(&param.frame);
        param.frame = nullptr;
    }        
}
    
bool CreateVideo(VideoParam &param, AVCodecContext *&encodeCtx)
{        
    AVFormatContext* &fmtCtx = param.fmtCtx;
    std::string &name = param.fileName;
    if (nullptr == encodeCtx)
    {
        LOG("encoder is null.");
        return false;
    }

    if (fmtCtx)
    {
        LOG("fmtCtx is exists.");
        return false;
    }

    if (param.packet)
    {
        av_packet_free(&param.packet);
        param.packet = nullptr;
    }

    param.packet = av_packet_alloc();
    if (nullptr == param.packet)
    {
        LOG("av_packet_alloc failed.");
        return false;
    }

    int ret = avformat_alloc_output_context2(&fmtCtx, NULL, NULL, name.c_str());
    if (ret < 0 || !fmtCtx)
    {
        LOG("could not create output context. ret:%d", ret);
        return false;
    }

    AVStream *outStream = nullptr;
    outStream = avformat_new_stream(fmtCtx, NULL);
    if (!outStream)
    {
        avformat_free_context(fmtCtx);
        fmtCtx = nullptr;
        LOG("failed allocating output stream.");
        return false;
    }

    ret = avcodec_parameters_from_context(outStream->codecpar, encodeCtx);
    if (ret < 0)
    {
        avformat_free_context(fmtCtx);
        fmtCtx = nullptr;
        LOG("failed to copy encoder parameters to output stream. ret:%d", ret);
        return false;
    }

    LOG("outStream codec_id: %d, format: %d", outStream->codecpar->codec_id, outStream->codecpar->format);
    av_dump_format(fmtCtx, 0, name.c_str(), 1);        
    if (!(fmtCtx->oformat->flags & AVFMT_NOFILE))
    {
        //打开AVIOContext
        //AVIOContext是ffmpeg中管理输入输出数据的结构体
        ret = avio_open(&fmtCtx->pb, name.c_str(), AVIO_FLAG_WRITE);
        if (ret < 0)
        {
            avformat_free_context(fmtCtx);
            fmtCtx = nullptr;
            LOG("could not open output file '%s'. ret:%d", name.c_str(), ret);
            return false;
        }
    }

    //写入文件头
    ret = avformat_write_header(fmtCtx, NULL);
    if (ret < 0)
    {
        avio_closep(&fmtCtx->pb);
        avformat_free_context(fmtCtx);
        fmtCtx = nullptr;
        LOG("error occurred when opening output file. ret:%d", ret);
        return false;
    }
    return true;
}

void ReleaseVideo(VideoParam &param)
{
    auto &fmtCtx = param.fmtCtx;
    if (nullptr == fmtCtx)
    {
        return;
    }

    av_write_trailer(fmtCtx);
    avio_closep(&fmtCtx->pb);
    avformat_free_context(fmtCtx);

    LOG("video writer stopped");
    if (param.packet)
    {
        av_packet_free(&param.packet);
        param.packet = nullptr;
    }
    param.startPts = 0;

    fmtCtx = nullptr;
}


Encoder::Encoder()
{
}
    
Encoder::~Encoder()
{
    CloseVideoWriter();
}

bool Encoder::OpenVideoWriter()
{
    if (mIsRecording)
    {
        LOG("recording... close first.");
        return false;
    }

    if (false == CreateEncoder(mEncodeParam))
    {
        return false;
        LOG("CreateEncoder failed.");
    }

    if (false == CreateVideo(mVideoParam, mEncodeParam.codeCtx))
    {
        return false;
        LOG("CreateVideo failed");
    }

    mIsRecording = true;
    
    return true;
}

void Encoder::CloseVideoWriter()
{
    FlushEncoder();

    mIsRecording = false;
    ReleaseEncoder(mEncodeParam);
    ReleaseVideo(mVideoParam);
}

void Encoder::FlushEncoder()
{
    if (mIsRecording)
    {
        LOG("start flus raw video.");
        EncodeAndWrite(mEncodeParam, mVideoParam, true);
        LOG("flus raw video done.");
    }
}

bool Encoder::EncodeAndWrite(EncodeParam &encodeParam, VideoParam &videoParam, bool flush)
{
    AVFrame* frame = encodeParam.frame;
    if (flush)
    {
        frame = nullptr;
    }

    auto &encodeCtx = encodeParam.codeCtx;
    auto &fmtCtx = videoParam.fmtCtx;
    auto &pkt = videoParam.packet;

    int ret = avcodec_send_frame(encodeCtx, frame);
    if (ret < 0)
    {
        LOG("avcodec_send_frame failed. ret:%d", ret);
        return false;
    }
    
    while (ret >= 0)
    {        
        ret = avcodec_receive_packet(encodeCtx, pkt);
        if (ret < 0)
        {
            if (ret == AVERROR(EAGAIN))
            {
                return true;
            }

            if (ret == AVERROR_EOF)
            {
                LOG("avcodec_receive_packet EOF.");
                return true;
            }

            LOG("avcodec_receive_packet failed. ret:%d", ret);
            return false;
        }        

        // //可以确定首帧时间戳必大于0
        // if (0 == startTimeStampPts)
        // {
        //     startTimeStampPts = pkt->pts;
        //     startTimeStampDts = pkt->dts;
        // }

        //统一减startTimeStampDts,pts 和 dts 在同一条时间轴上,"归零"是对时间轴原点做平移,平移必须对整条轴用同一个偏移量;分别减不同的基准就不再是平移
        //同一帧必定 pts>=dts
        pkt->stream_index = 0;
        if (pkt->pts != AV_NOPTS_VALUE)
        {
            // pkt->pts = pkt->pts - startTimeStampDts;
            pkt->pts = av_rescale_q(pkt->pts, encodeCtx->time_base, fmtCtx->streams[0]->time_base);
        }
        if (pkt->dts != AV_NOPTS_VALUE)
        {
            // pkt->dts = pkt->dts - startTimeStampDts;
            pkt->dts = av_rescale_q(pkt->dts, encodeCtx->time_base, fmtCtx->streams[0]->time_base);
        }

        // LOG("pkt size:%d, pts:%lld, dts:%lld", pkt->size, pkt->pts, pkt->dts);

        // pkt->duration = frame.duration;
        
        ret = av_write_frame(fmtCtx, pkt);
        if (ret < 0)
        {
            av_packet_unref(pkt);
            LOG("av_write_frame failed. ret:%d", ret);
            return false;
        }
    }//while

    return true;
}

bool Encoder::WriteFrame(uint8_t* yuvData, uint32_t width, uint32_t height, uint64_t timeStampMs)
{
    if (false == mIsRecording)
    {
        LOG("not initial.");
        return false;
    }

    //YUV420P 要求宽高为偶数
    if (0 != (width % 2) || 0 != (height % 2))
    {
        LOG("mat size must be even, got %d x %d.", width, height);
        return false;
    }

    auto &encodeCtx = mEncodeParam.codeCtx;
    if (encodeCtx->width != width || encodeCtx->height != height)
    {
        LOG("encoder width:%d, height:%d, mat width:%d, height:%d not match.", encodeCtx->width, encodeCtx->height, width, height);
        return false;
    }    

    auto &frame = mEncodeParam.frame;
    if (av_frame_make_writable(frame) < 0)
    {
        LOG("frame not writable.");
        return false;
    }
    frame->pts = timeStampMs;

    const int width = frame->width;
    const int height = frame->height;
    const int halfWidth = width / 2;
    const int halfHeight = height / 2;

    const uint8_t *srcY = yuvData;
    const uint8_t *srcU = srcY + width * height;
    const uint8_t *srcV = srcU + halfWidth * halfHeight;

    for (int i = 0; i < height; ++i)
    {
        memcpy(frame->data[0] + i * frame->linesize[0], srcY + i * width, width);
    }

    for (int i = 0; i < halfHeight; ++i)
    {
        memcpy(frame->data[1] + i * frame->linesize[1], srcU + i * halfWidth, halfWidth);
        memcpy(frame->data[2] + i * frame->linesize[2], srcV + i * halfWidth, halfWidth);
    }

    if (0 == mVideoParam.startPts)
    {
        mVideoParam.startPts = timeStampMs;        
    }
    frame->pts = frame->pts - mVideoParam.startPts;

    // LOG("pts:%lld. width:%d, height:%d, format:%d", frame.pts, frame.width, frame.height, frame.format);
    // static bool once = false;
    // if (false == once)
    // {
    //     once = true;
    //     std::ofstream out;
    //     out.open("happy.yuv", std::ios::binary);
    //     if (out.is_open())
    //     {
    //         const int width  = frame.width;
    //         const int height = frame.height;

    //         // Y 平面:完整分辨率
    //         for (int i = 0; i < height; i++) {
    //             out.write((char*)frame.data[0] + i * frame.linesize[0], width);
    //         }
        
    //         // U 平面:宽高各一半
    //         const int halfWidth  = width / 2;
    //         const int halfHeight = height / 2;
    //         for (int i = 0; i < halfHeight; i++) {                
    //             out.write((char*)frame.data[1] + i * frame.linesize[1], width);
    //         }
        
    //         // V 平面:宽高各一半
    //         for (int i = 0; i < halfHeight; i++) {                
    //             out.write((char*)frame.data[2] + i * frame.linesize[2], width);
    //         }

    //         out.close();
    //     }
    // }
            
    if (false == EncodeAndWrite(mEncodeParam, mVideoParam))
    {
        LOG("encode failed.");
        return false;
    }        

    return true;
}

}//namespace codec
posted on 2026-10-22 17:19  林西索  阅读(7)  评论(0)    收藏  举报