前提背景:3通道的Mat(CV_8UC3) --> AVFrame(yuv420p)
以下的编码过程是正确的,但写入文件的逻辑未验证
#include <opencv2/highgui.hpp>
#include <iostream>
extern "C"
{
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}
#pragma comment(lib, "swscale.lib")
#pragma comment(lib, "avcodec.lib")
#pragma comment(lib, "avutil.lib")
#pragma comment(lib, "avformat.lib")
#pragma comment(lib,"opencv_world320.lib")
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
//注册所有的编解码器
avcodec_register_all();
//像素格式转换上下文
SwsContext *vsc = NULL;
//输出的数据结构
AVFrame *p_frame= nullptr;
//编码器上下文
AVCodecContext *vc = NULL;
//初始化格式转换上下文
//推荐使用下列函数,另有sws_getCachedContext(),在循环里使用,但要在循环里释放相关资源,使用sws_freeContext()释放之
vsc = sws_getCachedContext(vsc,
inWidth, inHeight, AV_PIX_FMT_BGR24, //源宽、高、像素格式
inWidth, inHeight, AV_PIX_FMT_YUV420P,//目标宽、高、像素格式
SWS_BICUBIC, // 尺寸变化使用算法
0, 0, 0);
//初始化AVFrame
p_frame = av_frame_alloc();
p_frame->format = AV_PIX_FMT_YUV420P;
p_frame->width = inWidth;
p_frame->height = inHeight;
p_frame->pts = 0;
//分配yuv空间,32意为内存对齐方式
int ret = av_frame_get_buffer(p_frame, 32);
// 初始化编码上下文
//a 找到编码器
AVCodec *codec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (!codec)
{
throw exception("Can`t find h264 encoder!");
}
//b 创建编码器上下文
vc = avcodec_alloc_context3(codec);
if (!vc)
{
throw exception("avcodec_alloc_context3 failed!");
}
//c 配置编码器参数
//写入文件必须配置该参数
vc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; //全局参数
vc->codec_id = codec->id;
vc->thread_count = 8;
vc->bit_rate = 50 * 1024 * 8;//压缩后每秒视频的bit位大小 50kB
vc->width = inWidth;
vc->height = inHeight;
vc->time_base = { 1,fps };
vc->framerate = { fps,1 };
//画面组的大小,多少帧一个关键帧
vc->gop_size = 50;
vc->max_b_frames = 0;
vc->pix_fmt = AV_PIX_FMT_YUV420P;
//d 打开编码器上下文
ret = avcodec_open2(vc, 0, 0);
if (ret != 0)
{
char buf[1024] = { 0 };
av_strerror(ret, buf, sizeof(buf) - 1);
throw exception(buf);
}
cout << "avcodec_open2 success!" << endl;
//为写文件做准备
FILE* p_file = nullptr;
p_file = fopen("xx.h264", "wb");
//栈上分配AVPacket对象
AVPacket pack;
memset(&pack, 0, sizeof(pack));
int vpts = 0;
for (;;)
{
//bgr to yuv420p
//输入的数据结构
uint8_t *indata[AV_NUM_DATA_POINTERS] = { 0 };
//indata[0] bgrbgrbgr
//plane indata[0] bbbbb indata[1]ggggg indata[2]rrrrr
indata[0] = mat.data;
int insize[AV_NUM_DATA_POINTERS] = { 0 };
//一行(宽)数据的字节数
insize[0] = mat.cols * mat.elemSize();
int h = sws_scale(vsc, indata, insize, 0, mat.rows, //源数据
p_frame->data, p_frame->linesize);
if (h <= 0)
{
continue;
}
//cout << h << " " << flush;
//h264编码
p_frame->pts = vpts;
vpts++;
ret = avcodec_send_frame(vc, p_frame);
if (ret != 0)
continue;
ret = avcodec_receive_packet(vc, &pack);
if (ret != 0 || pack.size > 0)
{
//cout << "*" << pack.size << flush;
}
else
{
continue;
}
//写入文件
pack.pts = av_rescale_q(pack.pts, vc->time_base, vs->time_base);
pack.dts = av_rescale_q(pack.dts, vc->time_base, vs->time_base);
pack.duration = av_rescale_q(pack.duration, vc->time_base, vs->time_base);
fwrite(pack.data, 1, pack.size, p_file);
if (ret == 0)
{
cout << "#" << flush;
}
}
//flush the encoder
ret = avcodec_send_frame(vc, nullptr);
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)
break;
else if (ret < 0)
{
fprintf(stderr, "Error during encoding\n");
}
printf("Write packet %3"PRId64" (size=%5d)\n", pkt->pts, pkt->size);
fwrite(pack.data, 1, pack.size, p_file);
av_packet_unref(pkt);
}
//add sequence end code to have a real MPEG file
uint8_t endcode[] = { 0, 0, 1, 0xb7 };
fwrite(endcode, 1, sizeof(endcode), p_file);
fclose(p_file);
return 0;
}