最简单的基于FFmpeg的视频编码器-更新版(YUV编码为HEVC(H.265))

=====================================================

最简单的基于FFmpeg的视频编码器文章列表:

最简单的基于FFMPEG的视频编码器(YUV编码为H.264)

最简单的基于FFmpeg的视频编码器-更新版(YUV编码为HEVC(H.265))

最简单的基于FFmpeg的编码器-纯净版(不包含libavformat)

=====================================================


前一阵子做过一个基于FFmpeg的视频编码器的例子:

最简单的基于FFMPEG的视频编码器(YUV编码为H.264)
在该例子中,可以将YUV像素数据(YUV420P)编码为H.264码流。因为如今FFmpeg已经实现了对libx265的支持,因此对上述编码H.264的例子进行了升级,使之变成编码H.265(HEVC)的例子。

比较早的FFmpeg的类库(大约几个月以前的版本,我这里编译时间是2014.05.06)对H.265的编码支持有问题。开始调试的时候,以为是自己的代码有问题,几经修改也没有找到解决方法。最终发现是类库本身的问题,更换新版本的类库(我这里编译时间是2014.09.16)后问题解决。


流程

下面附上一张FFmpeg编码视频的流程图。通过该流程,不仅可以编码H.264/H.265的码流,而且可以编码MPEG4/MPEG2/VP9/VP8等多种码流。实际上使用FFmpeg编码视频的方式都是一样的。图中蓝色背景的函数是实际输出数据的函数。浅绿色的函数是视频编码的函数。


 


简单介绍一下流程中各个函数的意义(上一篇YUV编码为H.264的文章中已经写过一遍,这里复制粘贴一下):
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)。


代码

下面直接贴上代码
  1. /**
  2. * 最简单的基于FFmpeg的视频编码器
  3. * Simplest FFmpeg Video Encoder
  4. *
  5. * 雷霄骅 Lei Xiaohua
  6. * leixiaohua1020@126.com
  7. * 中国传媒大学/数字电视技术
  8. * Communication University of China / Digital TV Technology
  9. * http://blog.csdn.net/leixiaohua1020
  10. *
  11. * 本程序实现了YUV像素数据编码为视频码流(HEVC(H.265),H264,MPEG2,VP8等等)。
  12. * 是最简单的FFmpeg视频编码方面的教程。
  13. * 通过学习本例子可以了解FFmpeg的编码流程。
  14. * This software encode YUV420P data to HEVC(H.265) bitstream (or
  15. * H.264, MPEG2, VP8 etc.).
  16. * It's the simplest video encoding software based on FFmpeg.
  17. * Suitable for beginner of FFmpeg
  18. */
  19. #include <stdio.h>
  20. extern "C"
  21. {
  22. #include "libavutil\opt.h"
  23. #include "libavcodec\avcodec.h"
  24. #include "libavformat\avformat.h"
  25. #include "libswscale\swscale.h"
  26. };
  27. int flush_encoder(AVFormatContext *fmt_ctx,unsigned int stream_index)
  28. {
  29. int ret;
  30. int got_frame;
  31. AVPacket enc_pkt;
  32. if (!(fmt_ctx->streams[stream_index]->codec->codec->capabilities &
  33. CODEC_CAP_DELAY))
  34. return 0;
  35. while ( 1) {
  36. printf( "Flushing stream #%u encoder\n", stream_index);
  37. //ret = encode_write_frame(NULL, stream_index, &got_frame);
  38. enc_pkt.data = NULL;
  39. enc_pkt.size = 0;
  40. av_init_packet(&enc_pkt);
  41. ret = avcodec_encode_video2 (fmt_ctx->streams[stream_index]->codec, &enc_pkt,
  42. NULL, &got_frame);
  43. av_frame_free( NULL);
  44. if (ret < 0)
  45. break;
  46. if (!got_frame){
  47. ret= 0;
  48. break;
  49. }
  50. printf( "Succeed to encode 1 frame! 编码成功1帧!\n");
  51. /* mux encoded frame */
  52. ret = av_write_frame(fmt_ctx, &enc_pkt);
  53. if (ret < 0)
  54. break;
  55. }
  56. return ret;
  57. }
  58. int main(int argc, char* argv[])
  59. {
  60. AVFormatContext* pFormatCtx;
  61. AVOutputFormat* fmt;
  62. AVStream* video_st;
  63. AVCodecContext* pCodecCtx;
  64. AVCodec* pCodec;
  65. uint8_t* picture_buf;
  66. AVFrame* picture;
  67. int size;
  68. //FILE *in_file = fopen("src01_480x272.yuv", "rb"); //Input YUV data 视频YUV源文件
  69. FILE *in_file = fopen( "ds_480x272.yuv", "rb"); //Input YUV data 视频YUV源文件
  70. int in_w= 480,in_h= 272; //宽高
  71. //Frames to encode
  72. int framenum= 100;
  73. //const char* out_file = "src01.h264"; //Output Filepath 输出文件路径
  74. //const char* out_file = "src01.ts";
  75. //const char* out_file = "src01.hevc";
  76. const char* out_file = "ds.hevc";
  77. av_register_all();
  78. //Method1 方法1.组合使用几个函数
  79. pFormatCtx = avformat_alloc_context();
  80. //Guess Format 猜格式
  81. fmt = av_guess_format( NULL, out_file, NULL);
  82. pFormatCtx->oformat = fmt;
  83. //Method 2 方法2.更加自动化一些
  84. //avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
  85. //fmt = pFormatCtx->oformat;
  86. //Output Format 注意输出路径
  87. if (avio_open(&pFormatCtx->pb,out_file, AVIO_FLAG_READ_WRITE) < 0)
  88. {
  89. printf( "Failed to open output file! 输出文件打开失败");
  90. return -1;
  91. }
  92. video_st = avformat_new_stream(pFormatCtx, 0);
  93. video_st->time_base.num = 1;
  94. video_st->time_base.den = 25;
  95. if (video_st== NULL)
  96. {
  97. return -1;
  98. }
  99. //Param that must set
  100. pCodecCtx = video_st->codec;
  101. //pCodecCtx->codec_id =AV_CODEC_ID_HEVC;
  102. pCodecCtx->codec_id = fmt->video_codec;
  103. pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  104. pCodecCtx->pix_fmt = PIX_FMT_YUV420P;
  105. pCodecCtx->width = in_w;
  106. pCodecCtx->height = in_h;
  107. pCodecCtx->time_base.num = 1;
  108. pCodecCtx->time_base.den = 25;
  109. pCodecCtx->bit_rate = 400000;
  110. pCodecCtx->gop_size= 250;
  111. //H264
  112. //pCodecCtx->me_range = 16;
  113. //pCodecCtx->max_qdiff = 4;
  114. //pCodecCtx->qcompress = 0.6;
  115. pCodecCtx->qmin = 10;
  116. pCodecCtx->qmax = 51;
  117. //Optional Param
  118. pCodecCtx->max_b_frames= 3;
  119. // Set Option
  120. AVDictionary *param = 0;
  121. //H.264
  122. if(pCodecCtx->codec_id == AV_CODEC_ID_H264) {
  123. av_dict_set(?m, "preset", "slow", 0);
  124. av_dict_set(?m, "tune", "zerolatency", 0);
  125. }
  126. //H.265
  127. if(pCodecCtx->codec_id == AV_CODEC_ID_H265){
  128. av_dict_set(?m, "x265-params", "qp=20", 0);
  129. av_dict_set(?m, "preset", "ultrafast", 0);
  130. av_dict_set(?m, "tune", "zero-latency", 0);
  131. }
  132. //Dump Information 输出格式信息
  133. av_dump_format(pFormatCtx, 0, out_file, 1);
  134. pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
  135. if (!pCodec){
  136. printf( "Can not find encoder! 没有找到合适的编码器!\n");
  137. return -1;
  138. }
  139. if (avcodec_open2(pCodecCtx, pCodec,?m) < 0){
  140. printf( "Failed to open encoder! 编码器打开失败!\n");
  141. return -1;
  142. }
  143. picture = avcodec_alloc_frame();
  144. size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
  145. picture_buf = ( uint8_t *)av_malloc(size);
  146. avpicture_fill((AVPicture *)picture, picture_buf, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
  147. //Write File Header 写文件头
  148. avformat_write_header(pFormatCtx, NULL);
  149. AVPacket pkt;
  150. int y_size = pCodecCtx->width * pCodecCtx->height;
  151. av_new_packet(&pkt,y_size* 3);
  152. for ( int i= 0; i<framenum; i++){
  153. //Read YUV 读入YUV
  154. if (fread(picture_buf, 1, y_size* 3/ 2, in_file) < 0){
  155. printf( "Failed to read YUV data! 文件读取错误\n");
  156. return -1;
  157. } else if(feof(in_file)){
  158. break;
  159. }
  160. picture->data[ 0] = picture_buf; // 亮度Y
  161. picture->data[ 1] = picture_buf+ y_size; // U
  162. picture->data[ 2] = picture_buf+ y_size* 5/ 4; // V
  163. //PTS
  164. picture->pts=i;
  165. int got_picture= 0;
  166. //Encode 编码
  167. int ret = avcodec_encode_video2(pCodecCtx, &pkt,picture, &got_picture);
  168. if(ret < 0){
  169. printf( "Failed to encode! 编码错误!\n");
  170. return -1;
  171. }
  172. if (got_picture== 1){
  173. printf( "Succeed to encode 1 frame! 编码成功1帧!\n");
  174. pkt.stream_index = video_st->index;
  175. ret = av_write_frame(pFormatCtx, &pkt);
  176. av_free_packet(&pkt);
  177. }
  178. }
  179. //Flush Encoder
  180. int ret = flush_encoder(pFormatCtx, 0);
  181. if (ret < 0) {
  182. printf( "Flushing encoder failed\n");
  183. return -1;
  184. }
  185. //Write file trailer 写文件尾
  186. av_write_trailer(pFormatCtx);
  187. //Clean 清理
  188. if (video_st){
  189. avcodec_close(video_st->codec);
  190. av_free(picture);
  191. av_free(picture_buf);
  192. }
  193. avio_close(pFormatCtx->pb);
  194. avformat_free_context(pFormatCtx);
  195. fclose(in_file);
  196. return 0;
  197. }


结果

软件运行截图(受限于文件体积,原始YUV帧数只有100帧):


这次换了个有趣点的YUV序列。之前总是看YUV标准测试序列都已经看烦了,这次换个电视剧里的序列相对更加生动一些。YUV序列如下图所示。

 
编码后的HEVC(H.265)码流:
 

下载


Simplest ffmpeg video encoder


项目主页

SourceForge:https://sourceforge.net/projects/simplestffmpegvideoencoder/

Github:https://github.com/leixiaohua1020/simplest_ffmpeg_video_encoder

开源中国:http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_video_encoder


CSDN下载地址:http://download.csdn.net/detail/leixiaohua1020/8001515


本程序实现了YUV像素数据编码为视频码流(H.265,H264,MPEG2,VP8等等)。是最简单的FFmpeg视频编码方面的教程。

它包含以下两个子项目:

simplest_ffmpeg_video_encoder:最简单的基于FFmpeg的视频编码器。使用libavcodec和libavformat编码并且封装视频。
simplest_ffmpeg_video_encoder_pure:最简单的基于FFmpeg的视频编码器-纯净版。仅使用libavcodec编码视频,不使用libavformat。


更新-1.1 (2015.1.03)=========================================

增加了《最简单的基于FFmpeg的编码器-纯净版(不包含libavformat)》中的simplest_ffmpeg_video_encoder_pure工程。

CSDN下载地址:http://download.csdn.net/detail/leixiaohua1020/8322003


更新-1.2 (2015.2.13)=========================================

这次考虑到了跨平台的要求,调整了源代码。经过这次调整之后,源代码可以在以下平台编译通过:

VC++:打开sln文件即可编译,无需配置。

cl.exe:打开compile_cl.bat即可命令行下使用cl.exe进行编译,注意可能需要按照VC的安装路径调整脚本里面的参数。编译命令如下。

::VS2010 Environment
call "D:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"
::include
@set INCLUDE=include;%INCLUDE%
::lib
@set LIB=lib;%LIB%
::compile and link
cl simplest_ffmpeg_video_encoder.cpp /link avcodec.lib avformat.lib avutil.lib ^
avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib /OPT:NOREF

MinGW:MinGW命令行下运行compile_mingw.sh即可使用MinGW的g++进行编译。编译命令如下。

g++ simplest_ffmpeg_video_encoder.cpp -g -o simplest_ffmpeg_video_encoder.exe \
-I /usr/local/include -L /usr/local/lib \
-lavformat -lavcodec -lavutil

GCC:Linux或者MacOS命令行下运行compile_gcc.sh即可使用GCC进行编译。编译命令如下。

gcc simplest_ffmpeg_video_encoder.cpp -g -o simplest_ffmpeg_video_encoder.out \
-I /usr/local/include -L /usr/local/lib -lavformat -lavcodec -lavutil

PS:相关的编译命令已经保存到了工程文件夹中


CSDN下载地址:http://download.csdn.net/detail/leixiaohua1020/8444967

SourceForge上已经更新。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值