#include #include"pch.h"#include
extern "C"{
#include"libavcodec/avcodec.h"#include"libavformat/avformat.h"#include"libavcodec/avcodec.h"#include"libswscale/swscale.h"#include};using namespacestd;int flush_encoder(AVFormatContext *fmt_ctx, unsigned intstream_index);intYUV2H264()
{
AVFormatContext*pFormatCtx =nullptr;
AVOutputFormat*fmt =nullptr;
AVStream*video_st =nullptr;
AVCodecContext*pCodecCtx =nullptr;
AVCodec*pCodec =nullptr;
uint8_t*picture_buf =nullptr;
AVFrame*picture =nullptr;intsize;//打开视频文件
FILE *in_file = fopen("111.yuv", "rb");if (!in_file) {
cout<< "can not open file!" <
}//352x288
int in_w = 352, in_h = 288;int framenum = 50;const char* out_file = "111.H264";//[1] --注册所有ffmpeg组件
avcodec_register_all();
av_register_all();//[2] --初始化AVFormatContext结构体,根据文件名获取到合适的封装格式
avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
fmt= pFormatCtx->oformat;//[3] --打开文件
if (avio_open(&pFormatCtx->pb, out_file, AVIO_FLAG_READ_WRITE)) {
cout<< "output file open fail!";return -1;
}//[3]//[4] --初始化视频码流
video_st = avformat_new_stream(pFormatCtx, 0);if (video_st ==NULL)
{
printf("failed allocating output stram\n");return -1;
}
video_st->time_base.num = 1;
video_st->time_base.den = 25;//[4]//[5] --编码器Context设置参数
pCodecCtx = video_st->codec;
pCodecCtx->codec_id = fmt->video_codec;
pCodecCtx->codec_type =AVMEDIA_TYPE_VIDEO;
pCodecCtx->pix_fmt =AV_PIX_FMT_YUV420P;
pCodecCtx->width =in_w;
pCodecCtx->height =in_h;
pCodecCtx->time_base.num = 1;
pCodecCtx->time_base.den = 25;
pCodecCtx->bit_rate = 400000;
pCodecCtx->gop_size = 12;if (pCodecCtx->codec_id ==AV_CODEC_ID_H264)
{
pCodecCtx->qmin = 10;
pCodecCtx->qmax = 51;
pCodecCtx->qcompress = 0.6;
}if (pCodecCtx->codec_id ==AV_CODEC_ID_MPEG2VIDEO)
pCodecCtx->max_b_frames = 2;if (pCodecCtx->codec_id ==AV_CODEC_ID_MPEG1VIDEO)
pCodecCtx->mb