参考雷霄骅博士的文章,链接:最简单的基于FFMPEG的视频编码器(YUV编码为H.264)
本文介绍一个最简单的基于 FFmpeg 的视频编码器。
该编码器实现了 YUV420P 的像素数据编码为 H.264 的压缩编码数据。
下面附一张使用 FFmpeg 编码视频的流程图。使用该流程,不仅可以编码 H.264 的视频,而且可以编码 MPEG4/MPEG2/VP8 等等各种 FFmpeg 支持的视频。图中蓝色背景的函数是实际输出数据的函数。浅绿色的函数是视频编码的函数。
简单介绍一下流程中各个函数的意义:
源代码:
// Simplest FFmpeg Video Encoder H.264.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
// 解决报错:fopen() 函数不安全
#pragma warning(disable:4996)
// 解决报错:无法解析的外部符号 __imp__fprintf,该符号在函数 _ShowError 中被引用
#pragma comment(lib, "legacy_stdio_definitions.lib")
extern "C"
{
// 解决报错:无法解析的外部符号 __imp____iob_func,该符号在函数 _ShowError 中被引用
FILE __iob_func[3] = { *stdin, *stdout, *stderr };
}
#define __STDC_CONSTANT_MACROS
#ifdef _WIN32
// Windows
extern "C"
{
#include "libavutil/opt.h"
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
};
#else
// Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include
#include
#include
#ifdef __cplusplus
};
#endif
#endif
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;
}
}
return ret;
}
int main(int argc, char* argv[])
{
AVFormatContext* pFormatCtx;
AVOutputFormat* fmt;
AVStream* video_stream;
AVCodecContext* pCodecCtx;
AVCodec* pCodec;
AVPacket pkt;
uint8_t* picture_buf;
AVFrame* pFrame;
int ret;
int picture_size = 0;
int y_size = 0;
int framecnt = 0;
// Input raw YUV data
FILE *fp_in = fopen("ds_480x272.yuv", "rb");
// FILE *in_file = fopen("src01_480x272.yuv", "rb");
const int in_width = 480, in_height = 272; // Input data's width and height
int framenum = 100; // Frames to encode
// Output Filepath
const char* out_file = "ds.h264";
// const char* out_file = "src01.h264";
// const char* out_file = "src01.ts";
// const char* out_file = "src01.hevc";
av_register_all();
// Method1
// pFormatCtx = avformat_alloc_context();
// fmt = av_guess_format(NULL, out_file, NULL); // Guess Format
// pFormatCtx->oformat = fmt;
// Method 2
avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
fmt = pFormatCtx->oformat;
//Open output URL
ret = avio_open(&pFormatCtx->pb, out_file, AVIO_FLAG_READ_WRITE);
if (ret < 0)
{
printf("Can't open output file.\n");
return -1;
}
video_stream = avformat_new_stream(pFormatCtx, 0);
// video_st->time_base.num = 1;
// video_st->time_base.den = 25;
if (video_stream == NULL)
{
printf("Can't create video stream.\n");
return -1;
}
// Param that must set
pCodecCtx = video_stream->codec;
// pCodecCtx->codec_id = AV_CODEC_ID_HEVC;
pCodecCtx->codec_id = fmt->video_codec;
pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
pCodecCtx->width = in_width;
pCodecCtx->height = in_height;
pCodecCtx->bit_rate = 400000;
pCodecCtx->gop_size = 250;
pCodecCtx->time_base.num = 1;
pCodecCtx->time_base.den = 25;
// H.264
// 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;
// Set Option
AVDictionary *param = 0;
// 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't find encoder.\n");
return -1;
}
ret = avcodec_open2(pCodecCtx, pCodec, ¶m);
if (ret < 0)
{
printf("Failed to open encoder.\n");
return -1;
}
pFrame = av_frame_alloc();
picture_size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
picture_buf = (uint8_t *)av_malloc(picture_size);
avpicture_fill((AVPicture *)pFrame, picture_buf, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
// Write File Header
avformat_write_header(pFormatCtx, NULL);
av_new_packet(&pkt, picture_size);
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, fp_in) <= 0)
{
printf("Failed to read raw data.\n");
return -1;
}
else if (feof(fp_in))
{
break;
}
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_stream->time_base.den) / ((video_stream->time_base.num) * 25);
int got_picture = 0;
// Encode
ret = avcodec_encode_video2(pCodecCtx, &pkt, pFrame, &got_picture);
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_stream->index;
ret = av_write_frame(pFormatCtx, &pkt);
av_free_packet(&pkt);
}
}
// Flush Encoder
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_stream)
{
avcodec_close(video_stream->codec);
av_free(pFrame);
av_free(picture_buf);
}
avio_close(pFormatCtx->pb);
avformat_free_context(pFormatCtx);
fclose(fp_in);
system("pause");
return 0;
}
运行程序,将输入 YUV 文件编码为 H.264 文件,以下是其信息:
可以正常播放。
GitHub:UestcXiye / Simplest-FFmpeg-Video-Encoder-H.264
CSDN:Simplest FFmpeg Video Encoder H.264.zip