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

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

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

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

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

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

本文介绍一个最简单的基于FFMPEG的视频编码器。该编码器实现了YUV420P的像素数据编码为H.264的压缩编码数据。编码器代码十分简单,但是每一行代码都很重要,适合好好研究一下。弄清楚了本代码也就基本弄清楚了FFMPEG的编码流程。目前我虽然已经调通了程序,但是还是有些地方没有完全搞明白,需要下一步继续探究然后补充内容。

本程序使用最新版的类库(编译时间为2014.5.6),开发平台为VC2010。所有的配置都已经做好,只需要运行就可以了。

流程

下面附一张使用FFmpeg编码视频的流程图。使用该流程,不仅可以编码H.264的视频,而且可以编码MPEG4/MPEG2/VP8等等各种FFmpeg支持的视频。图中蓝色背景的函数是实际输出数据的函数。浅绿色的函数是视频编码的函数。

简单介绍一下流程中各个函数的意义:

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像素数据编码为视频码流(H264,MPEG2,VP8等等)。
  12. * 是最简单的FFmpeg视频编码方面的教程。
  13. * 通过学习本例子可以了解FFmpeg的编码流程。
  14. * This software encode YUV420P data to H.264 bitstream.
  15. * It's the simplest video encoding software based on FFmpeg.
  16. * Suitable for beginner of FFmpeg
  17. */
  18. #include <stdio.h>
  19. #define __STDC_CONSTANT_MACROS
  20. #ifdef _WIN32
  21. //Windows
  22. extern "C"
  23. {
  24. #include "libavutil/opt.h"
  25. #include "libavcodec/avcodec.h"
  26. #include "libavformat/avformat.h"
  27. };
  28. #else
  29. //Linux...
  30. #ifdef __cplusplus
  31. extern "C"
  32. {
  33. #endif
  34. #include <libavutil/opt.h>
  35. #include <libavcodec/avcodec.h>
  36. #include <libavformat/avformat.h>
  37. #ifdef __cplusplus
  38. };
  39. #endif
  40. #endif
  41. int flush_encoder(AVFormatContext *fmt_ctx,unsigned int stream_index){
  42. int ret;
  43. int got_frame;
  44. AVPacket enc_pkt;
  45. if (!(fmt_ctx->streams[stream_index]->codec->codec->capabilities &
  46. CODEC_CAP_DELAY))
  47. return 0;
  48. while (1) {
  49. enc_pkt.data = NULL;
  50. enc_pkt.size = 0;
  51. av_init_packet(&enc_pkt);
  52. ret = avcodec_encode_video2 (fmt_ctx->streams[stream_index]->codec, &enc_pkt,
  53. NULL, &got_frame);
  54. av_frame_free(NULL);
  55. if (ret < 0)
  56. break;
  57. if (!got_frame){
  58. ret=0;
  59. break;
  60. }
  61. printf("Flush Encoder: Succeed to encode 1 frame!\tsize:%5d\n",enc_pkt.size);
  62. /* mux encoded frame */
  63. ret = av_write_frame(fmt_ctx, &enc_pkt);
  64. if (ret < 0)
  65. break;
  66. }
  67. return ret;
  68. }
  69. int main(int argc, char* argv[])
  70. {
  71. AVFormatContext* pFormatCtx;
  72. AVOutputFormat* fmt;
  73. AVStream* video_st;
  74. AVCodecContext* pCodecCtx;
  75. AVCodec* pCodec;
  76. AVPacket pkt;
  77. uint8_t* picture_buf;
  78. AVFrame* pFrame;
  79. int picture_size;
  80. int y_size;
  81. int framecnt=0;
  82. //FILE *in_file = fopen("src01_480x272.yuv", "rb"); //Input raw YUV data
  83. FILE *in_file = fopen("../ds_480x272.yuv", "rb"); //Input raw YUV data
  84. int in_w=480,in_h=272; //Input data's width and height
  85. int framenum=100; //Frames to encode
  86. //const char* out_file = "src01.h264"; //Output Filepath
  87. //const char* out_file = "src01.ts";
  88. //const char* out_file = "src01.hevc";
  89. const char* out_file = "ds.h264";
  90. av_register_all();
  91. //Method1.
  92. pFormatCtx = avformat_alloc_context();
  93. //Guess Format
  94. fmt = av_guess_format(NULL, out_file, NULL);
  95. pFormatCtx->oformat = fmt;
  96. //Method 2.
  97. //avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
  98. //fmt = pFormatCtx->oformat;
  99. //Open output URL
  100. if (avio_open(&pFormatCtx->pb,out_file, AVIO_FLAG_READ_WRITE) < 0){
  101. printf("Failed to open output file! \n");
  102. return -1;
  103. }
  104. video_st = avformat_new_stream(pFormatCtx, 0);
  105. //video_st->time_base.num = 1;
  106. //video_st->time_base.den = 25;
  107. if (video_st==NULL){
  108. return -1;
  109. }
  110. //Param that must set
  111. pCodecCtx = video_st->codec;
  112. //pCodecCtx->codec_id =AV_CODEC_ID_HEVC;
  113. pCodecCtx->codec_id = fmt->video_codec;
  114. pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  115. pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
  116. pCodecCtx->width = in_w;
  117. pCodecCtx->height = in_h;
  118. pCodecCtx->bit_rate = 400000;
  119. pCodecCtx->gop_size=250;
  120. pCodecCtx->time_base.num = 1;
  121. pCodecCtx->time_base.den = 25;
  122. //H264
  123. //pCodecCtx->me_range = 16;
  124. //pCodecCtx->max_qdiff = 4;
  125. //pCodecCtx->qcompress = 0.6;
  126. pCodecCtx->qmin = 10;
  127. pCodecCtx->qmax = 51;
  128. //Optional Param
  129. pCodecCtx->max_b_frames=3;
  130. // Set Option
  131. AVDictionary *param = 0;
  132. //H.264
  133. if(pCodecCtx->codec_id == AV_CODEC_ID_H264) {
  134. av_dict_set(¶m, "preset", "slow", 0);
  135. av_dict_set(¶m, "tune", "zerolatency", 0);
  136. //av_dict_set(¶m, "profile", "main", 0);
  137. }
  138. //H.265
  139. if(pCodecCtx->codec_id == AV_CODEC_ID_H265){
  140. av_dict_set(¶m, "preset", "ultrafast", 0);
  141. av_dict_set(¶m, "tune", "zero-latency", 0);
  142. }
  143. //Show some Information
  144. av_dump_format(pFormatCtx, 0, out_file, 1);
  145. pCodec = avcodec_find_encoder(pCodecCtx->codec_id);
  146. if (!pCodec){
  147. printf("Can not find encoder! \n");
  148. return -1;
  149. }
  150. if (avcodec_open2(pCodecCtx, pCodec,¶m) < 0){
  151. printf("Failed to open encoder! \n");
  152. return -1;
  153. }
  154. pFrame = av_frame_alloc();
  155. picture_size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
  156. picture_buf = (uint8_t *)av_malloc(picture_size);
  157. avpicture_fill((AVPicture *)pFrame, picture_buf, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);
  158. //Write File Header
  159. avformat_write_header(pFormatCtx,NULL);
  160. av_new_packet(&pkt,picture_size);
  161. y_size = pCodecCtx->width * pCodecCtx->height;
  162. for (int i=0; i<framenum; i++){
  163. //Read raw YUV data
  164. if (fread(picture_buf, 1, y_size*3/2, in_file) <= 0){
  165. printf("Failed to read raw data! \n");
  166. return -1;
  167. }else if(feof(in_file)){
  168. break;
  169. }
  170. pFrame->data[0] = picture_buf; // Y
  171. pFrame->data[1] = picture_buf+ y_size; // U
  172. pFrame->data[2] = picture_buf+ y_size*5/4; // V
  173. //PTS
  174. //pFrame->pts=i;
  175. pFrame->pts=i*(video_st->time_base.den)/((video_st->time_base.num)*25);
  176. int got_picture=0;
  177. //Encode
  178. int ret = avcodec_encode_video2(pCodecCtx, &pkt,pFrame, &got_picture);
  179. if(ret < 0){
  180. printf("Failed to encode! \n");
  181. return -1;
  182. }
  183. if (got_picture==1){
  184. printf("Succeed to encode frame: %5d\tsize:%5d\n",framecnt,pkt.size);
  185. framecnt++;
  186. pkt.stream_index = video_st->index;
  187. ret = av_write_frame(pFormatCtx, &pkt);
  188. av_free_packet(&pkt);
  189. }
  190. }
  191. //Flush Encoder
  192. int ret = flush_encoder(pFormatCtx,0);
  193. if (ret < 0) {
  194. printf("Flushing encoder failed\n");
  195. return -1;
  196. }
  197. //Write file trailer
  198. av_write_trailer(pFormatCtx);
  199. //Clean
  200. if (video_st){
  201. avcodec_close(video_st->codec);
  202. av_free(pFrame);
  203. av_free(picture_buf);
  204. }
  205. avio_close(pFormatCtx->pb);
  206. avformat_free_context(pFormatCtx);
  207. fclose(in_file);
  208. return 0;
  209. }

结果

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

编码前的YUV序列:

编码后的H.264码流:

下载

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

下载地址:

http://download.csdn.net/detail/leixiaohua1020/7324115

【修正】之前发现编码后的H.264码流与YUV输入的帧数不同。经过观察对比其他程序后发现需要调用flush_encoder()将编码器中剩余的视频帧输出。已经将该问题修正。

CSDN下载地址(修正后):

http://download.csdn.net/detail/leixiaohua1020/7466649

PUDN下载地址(修正后):

http://www.pudn.com/downloads644/sourcecode/multimedia/detail2605258.html

SourceForge上已经更新。

更新-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上已经更新。

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

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

    ===================================================== 最简单的基于FFmpeg的视频编码器文章列表: 最简单的基于FFMPEG的视频编码器(YUV ...

  2. 最简单的基于FFmpeg的内存读写的例子:内存转码器

    ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章列表: 最简单的基于FFmpeg的内存读写的 ...

  3. 最简单的基于FFmpeg的内存读写的例子:内存播放器

    ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章列表: 最简单的基于FFmpeg的内存读写的 ...

  4. 最简单的基于FFMPEG的转码程序

    本文介绍一个简单的基于FFmpeg的转码器.它可以将一种视频格式(包括封转格式和编码格式)转换为另一种视频格式.转码器在视音频编解码处理的程序中,属于一个比较复杂的东西.因为它结合了视频的解码和编码. ...

  5. 最简单的基于FFmpeg的libswscale的示例(YUV转RGB)

    ===================================================== 最简单的基于FFmpeg的libswscale的示例系列文章列表: 最简单的基于FFmpeg ...

  6. 最简单的基于FFMPEG的图像编码器(YUV编码为JPEG)

    伴随着毕业论文的完成,这两天终于腾出了空闲,又有时间搞搞FFMPEG的研究了.想着之前一直搞的都是FFMPEG解码方面的工作,很少涉及到FFMPEG编码方面的东西,于是打算研究一下FFMPEG的编码. ...

  7. 最简单的基于FFmpeg的AVfilter的例子-修正版

    代码是参考雷神的博客的代码,不过由于ffmpeg版本不同,记录使用中遇到的问题. 1.调用avfilter_get_by_name("ffbuffersink")时在新版本的ffm ...

  8. 最简单的基于FFMPEG+SDL的视频播放器 ver2 (采用SDL2.0)

    ===================================================== 最简单的基于FFmpeg的视频播放器系列文章列表: 100行代码实现最简单的基于FFMPEG ...

  9. 最简单的基于FFmpeg的AVDevice例子(屏幕录制)

    ===================================================== 最简单的基于FFmpeg的AVDevice例子文章列表: 最简单的基于FFmpeg的AVDe ...

最新文章

  1. python中where函数_如何在python中基于Where函数获取两列值
  2. spark提交到yarn_详细总结spark基于standalone、yarn集群提交作业流程
  3. /etc/rc.d 与 /etc/profile或者./.bash_profile的区别
  4. centos安装禅道的步骤
  5. java查看日志命令_[Java教程]【Linux】linux查看日志文件内容命令tail、cat、tac、head、echo...
  6. Nginx+MySQL+PHP+Memcache+Vsftpd一键安装包
  7. python中的栈及其实现
  8. ComBox 绑定数据库
  9. 软件开发过程模型——喷泉模型
  10. 360加固签名验证_360加固需要签名和密码
  11. Yate for Mac音乐标签管理工具
  12. 跳出固化语境,固化思维,坚持反洗脑
  13. php处理苹果支付接口回调
  14. Google Play Academy 组队 PK 赛,正式开赛!
  15. 饥荒中的聊天表情(Emoticons In Don‘t Starve Together)
  16. 《Presto(Trino)——The Definitive Guide》CHAPTER 6 Connectors Advanced CHAPTER 7 Connector Examples
  17. 这家为AI for Science而生的新研究院,要让科研进入“安卓模式”
  18. 鸿蒙系统(HarmonyOS)-- 第2章:鸿蒙Ul框架
  19. java 锁降级 知乎_锁降级
  20. iOS - 蓝牙开门智能门锁

热门文章

  1. SpringMVC拦截器-用户登录权限控制代码实现1
  2. 类加载器-线程上下文
  3. OAuth2.0授权流程分析
  4. 微服务发现组件Eureka:简介以及Eureka服务端开发
  5. Linux的shell脚本
  6. 模块-from import导入所有工具
  7. oracle11g同步,Oracle11g三种数据同步方式-Oracle
  8. smartupload 路径不存在_洞悉复杂金融场景,覆盖完备测试路径
  9. 斐波那契数列python递归 0、1、1、2、3_python实现斐波那契数列的多种方式
  10. 高版本JDK13新特性以及与JDK8对比