1. 概述
本文将介绍如何利用FFMPEG对桌面进行截屏,并保存成MP4的格式。
2. 基本工作流程
初始化:利用函数avformat_network_init();
和avdevice_register_all();
完成FFMPEG的初始化,其中avformat_network_init()
完成网络库的全局初始化,avdevice_register_all()
用于注册输入/输出设备;
截屏设置:
AVInputFormat *pInputFormat = av_find_input_format("gdigrab");
用于寻找的gdigrab输入设备。gdigrab是FFmpeg专门用于抓取Windows桌面图像的设备。
avformat_open_input(&pInputFormatContext, "desktop", pInputFormat, &options);
用于打开指定的视频流。
pInputFormatContext
:用户提供的指针,类型为AVFormatContext
,可以事先通过avformat_alloc_context()
进行分配。
"desktop"
: 提供一个可打开的流。可以是本地文件,rtmp协议、rtp协议指定的流地址,这里为“desktop”,表示对整个桌面进行截屏。
pInputFormat
:如果该值不为NULL,则会强制使用该值作为输入流格式,否则将会进行自动检测。在前面,程序前面已经分配AVInputFormat *pInputFormat = av_find_input_format("gdigrab");
option
包含AVFormatContext
和demuxer
私有选项的字典。
获取编码器信息:该步骤主要为了打开相应的解码器,用于对截屏的数据进行解码;
该步骤从开始到结束主要涉及的函数如下
avformat_find_stream_info(pInputFormatContext, 0);
获取码流信息。例如帧率、视频宽高等;
videoStreamIndex = av_find_best_stream(pInputFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, &pInputCodec, 0);获取对应的数据流索引;
pInputCodec = avcodec_find_decoder(videoStream->codecpar->codec_id);
获取对应的编码器;
ffret = avcodec_parameters_to_context(pInputCodecContex, videoStream->codecpar);
从videoStream
中拷贝编码器信息到pInputCodecContex
中;
fret = avcodec_open2(pInputCodecContex, pInputCodec, nullptr);
打开相应的编码器;
设置输出的编码器:
avformat_alloc_output_context2(&pOutputFormatContext, NULL, NULL, filename_out);
在编码前需要通过这个函数申请到一个AVFormatContext
p_outstream = avformat_new_stream(pOutputFormatContext, NULL);
为这个新申请到的AVFormatContext
分配一个新的stream