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

ffmpeg cv:Mat编码成H265数据流(ffmpeg编码mp4视频)

suiw9 2025-03-28 21:11 6 浏览 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 <opencv2/opencv.hpp>
#include 
 
extern "C"
{
#include <libavutil/opt.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}
 
 
 
//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 printffailed to open output file \n return -1 video_st='avformat_new_stream(pFormatCtx,' 0avstream 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(Pm, "preset", "slow", 0);
        av_dict_set(Pm, "tune", "zerolatency", 0);
        //av_dict_set(Pm, "profile", "main", 0);
    }
    //H.265
    if(pCodecCtx->codec_id == AV_CODEC_ID_H265){
        av_dict_set(Pm, "preset", "ultrafast", 0);
        av_dict_set(Pm, "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,Pm) < 0 printffailed 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<framenum; i++){
        //Read raw YUV data
//        if (fread(picture_buf, 1, y_size*3/2, in_file) <= 0 printffailed to read raw data \n return -1 else iffeofin_file break cv::mat srcimg cap>>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 printffailed to encode \n return -1 if got_picture='=1){' printfsucceed to encode frame: 5d\tsize:5d\nframecntpkt.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 printfflushing encoder failed\n return -1 write file trailer av_write_trailerpformatctx clean if video_st avcodec_closevideo_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)

相关推荐

看完这一篇数据仓库干货,终于搞懂什么是hive了

一、Hive定义Hive最早来源于FaceBook,因为FaceBook网站每天产生海量的结构化日志数据,为了对这些数据进行管理,并且因为机器学习的需求,产生了Hive这们技术,并继续发展成为一个成...

真正让你明白Hive参数调优系列1:控制map个数与性能调优参数

本系列几章系统地介绍了开发中Hive常见的用户配置属性(有时称为参数,变量或选项),并说明了哪些版本引入了哪些属性,常见有哪些属性的使用,哪些属性可以进行Hive调优,以及如何使用的问题。以及日常Hi...

HIVE SQL基础语法(hive sql是什么)

引言与关系型数据库的SQL略有不同,但支持了绝大多数的语句如DDL、DML以及常见的聚合函数、连接查询、条件查询。HIVE不适合用于联机事务处理,也不提供实时查询功能。它最适合应用在基于大量不可变数据...

[干货]Hive与Spark sql整合并测试效率

在目前的大数据架构中hive是用来做离线数据分析的,而在Spark1.4版本中spark加入了sparksql,我们知道spark的优势是速度快,那么到底sparksql会比hive...

Hive 常用的函数(hive 数学函数)

一、Hive函数概述及分类标准概述Hive内建了不少函数,用于满足用户不同使用需求,提高SQL编写效率:...

数仓/数开面试题真题总结(二)(数仓面试时应该讲些什么)

二.Hive...

Tomcat处理HTTP请求流程解析(tomcat 处理请求过程)

1、一个简单的HTTP服务器在Web应用中,浏览器请求一个URL,服务器就把生成的HTML网页发送给浏览器,而浏览器和服务器之间的传输协议是HTTP,那么接下来我们看下如何用Java来实现一个简单...

Python 高级编程之网络编程 Socket(六)

一、概述Python网络编程是指使用Python语言编写的网络应用程序。这种编程涉及到网络通信、套接字编程、协议解析等多种方面的知识。...

[904]ScalersTalk成长会Python小组第20周学习笔记

Scalers点评:在2015年,ScalersTalk成长会Python小组完成了《Python核心编程》第1轮的学习。到2016年,我们开始第二轮的学习,并且将重点放在章节的习题上。Python小...

「web开发」几款http请求测试工具

curl命令CURL(CommandLineUniformResourceLocator),是一个利用URL语法,在命令行终端下使用的网络请求工具,支持HTTP、HTTPS、FTP等协议...

x-cmd pkg | hurl - 强力的 HTTP 请求测试工具,让 API 测试更加简洁高效

简介...

Mac 基于HTTP方式访问下载共享文件,配置共享服务器

方法一:使用Python的SimpleHTTPServer进行局域网文件共享Mac自带Python,所以不需要安装其他软件,一条命令即可...

Python 基础教程十五之 Python 使用requests库发送http请求

前言...

使用curl进行http高并发访问(php curl 大量并发获得结果)

本文主要介绍curl异步接口的使用方式,以及获取高性能的一些思路和实践。同时假设读者已经熟悉并且使用过同步接口。1.curl接口基本介绍curl一共有三种接口:EasyInterface...

Django 中的 HttpResponse理解和用法-基础篇1

思路是方向,代码是时间,知识需积累,经验需摸索。希望对大家有用,有错误还望指出。...

取消回复欢迎 发表评论: