百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

ffmpeg cv:Mat编码成H265数据流

cac55 2025-03-04 10:56 17 浏览 0 评论

流程

下面附一张使用FFmpeg编码视频的流程图。使用该流程,不仅可以编码H.264的视频,而且可以编码MPEG4/MPEG2/VP8等等各种

简单介绍一下流程中各个函数的意义:

av_register_all():注册FFmpeg所有编解码器。


avformat_alloc_output_context2():初始化输出码流的AVFormatContext。

avio_open():打开输出文件。

av_new_stream():创建输出码流的AVStream。

avcodec_find_encoder():查找编码器。

avcodec_open2():打开编码器。

avformat_write_header():写文件头(对于某些没有文件头的封装格式,不需要此函数。比如说MPEG2TS)。

avcodec_encode_video2():编码一帧视频。即将AVFrame(存储YUV像素数据)编码为AVPacket(存储H.264等格式的码流数据)。

av_write_frame():将编码后的视频码流写入文件。

flush_encoder():输入的像素数据读取完成后调用此函数。用于输出编码器中剩余的AVPacket。

av_write_trailer():写文件尾(对于某些没有文件头的封装格式,不需要此函数。比如说MPEG2TS)。

代码

#include 
#include 
#include 
 
extern "C"
{
#include 
#include 
#include 
}
 
 
 
//H.265码流与YUV输入的帧数不同。经过观察对比其他程序后发现需要调用flush_encoder()将编码器中剩余的视频帧输出。当av_read_frame()循环退出的时候,实际上解码器中可能还包含剩余的几帧数据。
//因此需要通过“flush_decoder”将这几帧数据输出。“flush_decoder”功能简而言之即直接调用avcodec_decode_video2()获得AVFrame,而不再向解码器传递AVPacket
int flush_encoder(AVFormatContext *fmt_ctx,unsigned int stream_index){
    int ret;
    int got_frame;
    AVPacket enc_pkt;
//    if (!(fmt_ctx->streams[stream_index]->codec->codec->capabilities & CODEC_CAP_DELAY))
//        return 0;
    while (1) {
        enc_pkt.data = NULL;
        enc_pkt.size = 0;
        av_init_packet(&enc_pkt);
        ret = avcodec_encode_video2 (fmt_ctx->streams[stream_index]->codec, &enc_pkt, NULL, &got_frame);
        av_frame_free(NULL);
        if (ret < 0)
            break;
        if (!got_frame){
            ret=0;
            break;
        }
        printf("Flush Encoder: Succeed to encode 1 frame!\tsize:%5d\n",enc_pkt.size);
        /* mux encoded frame */
        ret = av_write_frame(fmt_ctx, &enc_pkt);
        if (ret < 0)
            break;
      //ret = avcodec_send_frame (fmt_ctx->streams[stream_index]->codec, &enc_pkt, NULL, &got_frame);
    }
    return ret;
}
 
int main(int argc, char* argv[])
{
    AVFormatContext* pFormatCtx;
    AVOutputFormat* fmt;
    AVStream* video_st;
    AVCodecContext* pCodecCtx;
    AVCodec* pCodec;
    AVPacket pkt;
    uint8_t* picture_buf;
    AVFrame* pFrame;
    int picture_size;
    int y_size;
    int framecnt=0;
    cv::VideoCapture cap(cv::String("/home/zhy/Documents/remote_driving/encoder_YUV_H264-h265/test.mp4"));
 
    if (!cap.isOpened())
         return -1;
 
       int frmCount = cap.get(CV_CAP_PROP_FRAME_COUNT);
       
       printf("frmCount: %d ", frmCount);
 
       int w =  cap.get(CV_CAP_PROP_FRAME_WIDTH);
       int h =  cap.get(CV_CAP_PROP_FRAME_HEIGHT);
       int bufLen = w*h*3/2;
                          
       int framenum=frmCount;                                   //Frames to encode
 
    //const char* out_file = "src01.h264";              //Output Filepath
    //const char* out_file = "src01.ts";
    const char* out_file = "/home/zhy/Documents/remote_driving/encoder_YUV_H264-h265/untitled2/src01.hevc";
    //const char* out_file = "ds.h264";
    //const char* out_file = "ds.h264";
 
    av_register_all();//注册FFmpeg所有编解码器。
    //Method1.
    pFormatCtx = avformat_alloc_context(); //初始化输出码流的AVFormatContext,释放avformat_free_context
    //Guess Format
    fmt = av_guess_format(NULL, out_file, NULL);   //决定视频输出时封装方式的函数
    pFormatCtx->oformat = fmt;
 
    //Method 2.
    //avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
    //fmt = pFormatCtx->oformat;
 
 
    //Open output URL
    //打开文件的缓冲区输入输出,flags 标识为  AVIO_FLAG_READ_WRITE ,可读写;将输出文件中的数据读入到程序的 buffer 当中,方便之后的数据写入fwrite
    if (avio_open(&pFormatCtx->pb,out_file, AVIO_FLAG_READ_WRITE) < 0){  //打开输出文件
        printf("Failed to open output file! \n");
        return -1;
    }
 
    video_st = avformat_new_stream(pFormatCtx, 0);//创建输出码流的AVStream。
        // 设置 码率25 帧每秒(fps=25)
    //video_st->time_base.num = 1;
    //video_st->time_base.den = 25;
 
    if (video_st==NULL){
        return -1;
    }
        //为输出文件设置编码的参数和格式
    //Param that must set
    pCodecCtx = video_st->codec; // 从媒体流中获取到编码结构体,一个 AVStream 对应一个  AVCodecContext
    pCodecCtx->codec_id =AV_CODEC_ID_HEVC;// 设置编码器的 id,例如 h265 的编码 id 就是 AV_CODEC_ID_H265
    //pCodecCtx->codec_id = fmt->video_codec;
    pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;//编码器视频编码的类型
    pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;//设置像素格式为 yuv 格式
    pCodecCtx->width = w;  //设置视频的宽高
    pCodecCtx->height = h;
    pCodecCtx->bit_rate = 400000;   //采样的码率;采样码率越大,视频大小越大
    pCodecCtx->gop_size=250;  //每250帧插入1个I帧,I帧越少,视频越小
 
    pCodecCtx->time_base.num = 1;
    pCodecCtx->time_base.den = 25;
 
    //H264
    //pCodecCtx->me_range = 16;
    //pCodecCtx->max_qdiff = 4;
    //pCodecCtx->qcompress = 0.6;
    pCodecCtx->qmin = 10; //最大和最小量化系数
    pCodecCtx->qmax = 51;
 
    //Optional Param
    pCodecCtx->max_b_frames=3; // 设置 B 帧最大的数量,B帧为视频图片空间的前后预测帧, B 帧相对于 I、P 帧来说,压缩率比较大,采用多编码 B 帧提高清晰度
 
    // Set Option //设置编码速度
    AVDictionary *param = 0;
        //preset的参数调节编码速度和质量的平衡。
    //tune的参数值指定片子的类型,是和视觉优化的参数,
    //zerolatency: 零延迟,用在需要非常低的延迟的情况下,比如电视电话会议的编码
    //H.264
    if(pCodecCtx->codec_id == AV_CODEC_ID_H264) {
        av_dict_set(?m, "preset", "slow", 0);
        av_dict_set(?m, "tune", "zerolatency", 0);
        //av_dict_set(?m, "profile", "main", 0);
    }
    //H.265
    if(pCodecCtx->codec_id == AV_CODEC_ID_H265){
        av_dict_set(?m, "preset", "ultrafast", 0);
        av_dict_set(?m, "tune", "zero-latency", 0);
    }   
    //Show some Information //输出格式的信息,例如时间,比特率,数据流,容器,元数据,辅助数据,编码,时间戳
    //av_dump_format(pFormatCtx, 0, out_file, 1);
 
    pCodec = avcodec_find_encoder(pCodecCtx->codec_id);//查找编码器
    if (!pCodec){
        printf("Can not find encoder! \n");
        return -1;
    }
       // 打开编码器,并设置参数 param
    if (avcodec_open2(pCodecCtx, pCodec,?m) < 0){
        printf("Failed to open encoder! \n");
        return -1;
    }
 
 
    pFrame = av_frame_alloc();//设置原始数据 AVFrame 非压缩数据
    picture_size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);  // 获取YUV像素格式图片的大小
    picture_buf = (uint8_t *)av_malloc(picture_size);// 将 picture_size 转换成字节数据
    avpicture_fill((AVPicture *)pFrame, picture_buf, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height); // 设置原始数据 AVFrame 的每一个frame 的图片大小,AVFrame 这里存储着 YUV 非压缩数据
 
 
    avformat_write_header(pFormatCtx,NULL); //Write File Header 写封装格式文件头
    av_new_packet(&pkt,picture_size);   //创建编码后的数据 AVPacket 结构体来存储 AVFrame 编码后生成的数据  //编码前:AVFrame  //编码后:AVPacket
 
        // 设置 yuv 数据中Y亮度图片的宽高,写入数据到 AVFrame 结构体中
    y_size = pCodecCtx->width * pCodecCtx->height;
 
    for (int i=0; i>srcImg;
 
       cv::Mat yuvImg;
       cv::cvtColor(srcImg, yuvImg, cv::COLOR_BGR2YUV_I420);
       memcpy(picture_buf, yuvImg.data, bufLen*sizeof(unsigned char));
 
        pFrame->data[0] = picture_buf;              // Y
        pFrame->data[1] = picture_buf+ y_size;      // U
        pFrame->data[2] = picture_buf+ y_size*5/4;  // V
        //PTS //顺序显示解码后的视频帧
        //pFrame->pts=i;
        //设置这一帧的显示时间
        pFrame->pts=i*(video_st->time_base.den)/((video_st->time_base.num)*25);
        int got_picture=0;
        //Encode //编码一帧视频。即将AVFrame(存储YUV像素数据)编码为AVPacket(存储H.264等格式的码流数据)
        int ret = avcodec_encode_video2(pCodecCtx, &pkt,pFrame, &got_picture); //成功时返回0,失败时返回负错误代码
        if(ret < 0){
            printf("Failed to encode! \n");
            return -1;
        }
        if (got_picture==1){
            printf("Succeed to encode frame: %5d\tsize:%5d\n",framecnt,pkt.size);
            framecnt++;
            pkt.stream_index = video_st->index;
            ret = av_write_frame(pFormatCtx, &pkt);//将编码后的视频码流写入文件(fwrite)
            av_free_packet(&pkt);//释放内存
        }
    }
    //Flush Encoder //输出编码器中剩余的AVPacket
    int ret = flush_encoder(pFormatCtx,0);
    if (ret < 0) {
        printf("Flushing encoder failed\n");
        return -1;
    }
 
    //Write file trailer // 写入数据流尾部到输出文件当中,表示结束并释放文件的私有数据
    av_write_trailer(pFormatCtx);
 
    //Clean
    if (video_st){
                // 关闭编码器
        avcodec_close(video_st->codec);
                // 释放 AVFrame
        av_free(pFrame);
                // 释放图片 buf
        av_free(picture_buf);
    }
    avio_close(pFormatCtx->pb);
    avformat_free_context(pFormatCtx);
 
    //fclose(in_file);
 
    return 0;
}

编译 Makefile

CC = g++
LD = g++
 
SRCS = $(wildcard *.cpp)
OBJS = $(patsubst %c, %o, $(SRCS))
 
TARGET = main
 
.PHONY:all clean
 
all: $(TARGET)
 
$(TARGET): $(OBJS)
	$(LD) $^ -g -o $@ `pkg-config --cflags --libs opencv` -std=c++11 -I/usr/local/include -L/usr/local/lib  -lavformat -lavcodec -lavutil
  
 
%o:%c
	$(CC) -cpp $^
 
clean:
	rm -f $(OBJS) $(TARGET)

相关推荐

如何屏蔽色情网站?_怎么能屏蔽网站

一、基础防御:全网DNS劫持阻断1.修改全网DNS服务器推荐DNS:安全DNS:CleanBrowsing(成人内容过滤):185.228.168.168/185.228.169.168Open...

容器、Pod、虚拟机与宿主机网络通信全解:看这一篇就够了

在日常开发与部署过程中,很多人一开始都会有这样的疑惑:容器之间是怎么通信的?容器怎么访问宿主机?宿主机又如何访问容器?Kubernetes中Pod的网络和Docker容器一样吗?容器跨机器是...

Win11专业版找不到共享打印机的问题

有很多深度官网的用户,都是在办公室上班的。而上班就需要使用打印机,但更新win11系统后,却出现同一个办公室里面的打印机都找不到的问题,这该如何处理呢?其实,可能是由于我们并没有打开共享打印机而造成的...

常用电脑快捷键大全,摆脱鼠标依赖,建议收藏

Ctrl+C复制Ctrl+X剪切Ctrl+V粘贴Ctrl+Z撤销Ctrl+Y重做Ctrl+B加粗Ctrl+A全选所有文件Ctrl+S保存Ctrl+N新建Ctrl+O打开Ctrl+E...

Win11实现自动追剧Jellyfin硬解,免NAS复杂操作

大家好,欢迎来到思赞数码。本期将详细介绍如何通过安装和配置Sonarr、Radarr、Prowlarr、qBittorrent和Jellyfin,打造一套自动化的影视管理系统。很多人认为,要实现自动追...

微软Win11安卓子系统WSA 2308.40000.3.0更新推送下载

IT之家9月21日消息,微软官方博客今日宣布,已面向所有WindowsInsider用户推送了Windows11安卓子系统的2308.40000.3.0版本更新。本次更新和之前...

路由器总掉线 一个命令就能猜出八九分

明明网络强度满格或有线图标正常,但视频卡成PPT、网页刷不开、游戏动不了,闲心这些问题很多小伙伴都碰到过。每次都要开关路由、宽带/光猫、插拔网线……一通忙。有没有啥办法能快速确定故障到底在哪儿,方便处...

windows电脑如何修改hosts文件?_windows怎么修改hosts

先来简单说下电脑host的作用hosts文件的作用:hosts文件是一个用于储存计算机网络中各节点信息的计算机文件;作用是将一些常用的网址域名与其对应的IP地址建立一个关联“数据库”,当用户在浏览器中...

win10广告弹窗ShellExperienceHost.exe

win10右下角老是弹出广告弹窗,排查为以下程序引起,但是这个是系统菜单的程序不能动:C:\Windows\SystemApps\ShellExperienceHost_cw5n1h2txyewy\S...

Win10 Mobile预览版10512/10166越狱解锁部署已被黑客攻破

看起来统一的WindowsPhone和Windows越加吸引人们的关注,特别是黑客们的好奇心。XDA论坛宣称,在Win10Mobile预览版10512/10166上,已取得越狱/解锁部署突破,比如可...

6款冷门小众软件,都是宝藏,建议收藏

真的很不错(。-ω-)zzzBearhttps://bear.app/cn/Bear是一个漂亮,灵活的Markdown的写作工具。它一样只支持苹果家的全平台。它一出现就惊艳四方,就被AppSto...

如何让不符合条件的设备升级Windows 11

如果你是最近(6月24日之后)加入WindowsInsider项目并且你的设备并不符合升级条件,那么当你在尝试升级Windows11的时候可能会看到以下错误:你的PC不符合Wi...

windows host文件怎么恢复?局域网访问全靠这些!

windowshost文件怎么恢复?windowshost文件是常用网址域名及其相应IP地址建立一个关联文件,通过这个host文件配置域名和IP的映射关系,以提高域名解析的速度,方便局域网用户使用...

Mac Hosts管理工具---SwitchHosts

switchhosts!formac是一款帮助用户快速切换hosts文件的工具,switchhosts!formac能够帮助你快速方便的打造个人专用的网络环境,支持本地和在线两种方式,并且支持...

「浅谈趣说网络知识」 第十二弹 老而不死的Hosts,它还很有用

【浅谈趣说网络知识】第十二弹老而不死的Hosts,它还很有用什么时候才觉得自己真的老了,不是35岁以上的数字,不是头上的点点白发,而是不知觉中的怀旧。风口上的IT界讲的就是"长江后浪推前浪...

取消回复欢迎 发表评论: