ffmpeg笔记

安装

Debian/Ubuntu/Linux Mint 下安装ffmpeg很简单:

apt-get install ffmpeg

其他操作系统安装方法,参考官网

如果想要手工编译 ffmpeg 可以参考官方 wiki。 Ubuntu/Debian/Mint 系手工编译 ffmpeg 参考 wiki

用法举例

显示文件信息

显示视频信息

ffmpeg -i input.avi

批量截图

将视频拆分多张图片,每一帧图片,保存到 frames 文件夹下,命名 frame001.png 这种。可以加上-r 参数以用来限制每秒的帧数,-r 10 就表示每秒10帧。

ffmpeg -i input.mp4 frames/frame%03d.png

图片合成视频

将多张图片合成视频

ffmpeg -i frames/frame%3d.png output.mp4

从视频中提取音频

从视频文件中提取音频并保存为 mp3

ffmpeg -i input.mp4 -f mp3 output.mp3

如果需要可以在中间加上 -ar 44100 -ac 2 -ab 192 系数,表示采样率 44100 ,通道2立体声,码率192 kb/s.

将声音合成到视频

将声音合成到视频中

ffmpeg -i input_music.mp3 -i input_video.mp4 output.mp4

转化格式

格式之间转换 大部分的情况下直接运行一下即可

ffmpeg -i input.mp4 output.avi

将 flv 转码 MP4

ffmpeg -i input.flv -vcodec copy -acodec copy out.mp4

-vcodec copy 和 -acodec copy 表示所使用的视频和音频编码格式,为原样拷贝。

转换文件格式

ffmpeg -y -i input_video.mp4 -bitexact -vcodec h263 -b 128 -r 15 -s 176x144 -acodec aac -ac 2 -ar 22500 -ab 24 -f 3gp test.3gp

ffmpeg -y -i test.wmv -ac 1 -acodec libamr_nb -ar 8000 -ab 12200 -s 176x144 -b 128 -r 15 test.3gp

视频切片操作

对视频切片操作

比如需要从视频第1分45秒地方,剪10秒画面,-ss 表示开始位置,-t 表示延长时间

ffmpeg -i input.mp4 -ss 00:01:45 -t 10 output.mp4

加速减速视频

加速视频

ffmpeg -i input.mp4 -vf setpts=0.5*PTS output.mp4

同理减速视频

ffmpeg -i input.mp4 -vf setpts=2.0*PTS output.mp4

此操作对音频无影响

视频截图

视频10秒的地方(-ss 参数)截取一张1920×1080尺寸大小的,格式为jpg的图片 -ss后跟的时间单位为秒

ffmpeg -i input_video.mp4 -y -f image2 -t 0.001 -ss 10 -s 1920x1080 output.jpg

或者

ffmpeg -i input_video.mp4 -ss 00:00:06.000 -vframes 1 output.png 

合成 gif

把视频的前30帧转换成一个Gif

ffmpeg -i input_video.mp4 -vframes 30 -y -f gif output.gif

将视频转成 gif

ffmpeg -ss 00:00:00.000 -i input.mp4 -pix_fmt rgb24 -r 10 -s 320x240 -t 00:00:10.000 output.gif

将输入的文件从(-ss)设定的时间开始以10帧频率,输出到320×240大小的 gif 中,时间长度为-t 设定的参数。通过这样转换出来的 gif 一般都比较大,可以使用 ImageMagick 来优化图片的大小。

 convert -layers Optimize output.gif output_optimized.gif

把frame.[001-100].jpg序列帧和bg.mp3音频文件利用mpeg4编码方式合成分辨率720p的视频文件output.avi:

ffmpeg -i bg.mp3 -i frame.%3d.jpg -s hd720 -vcodec mpeg4 output.avi

查看ffmpeg支持格式

要查看你的ffmpeg支持哪些格式,可以用如下命令:

ffmpeg -formats | less

设置输出文件编码率 64 kbit/s, To set the video bitrate of the output file to 64 kbit/s:

 ffmpeg -i input.avi -b:v 64k -bufsize 64k output.avi

设置输出文件帧率为24 fps,To force the frame rate of the output file to 24 fps:

 ffmpeg -i input.avi -r 24 output.avi

强制输入文件以1帧,输出文件24帧 , To force the frame rate of the input file (valid for raw formats only) to 1 fps and the frame rate of the output file to 24 fps:

 ffmpeg -r 1 -i input.mp4 -r 24 output.avi

下面几步分别是,创建frames文件夹,利用 ffmpeg 将视频文件以每秒10帧输出成图像保存到 frames 文件夹中,再利用 ImageMagick 将图片组成 gif。其中 convert 命令来自 ImageMagick。

mkdir frames
ffmpeg -i input.mp4 -r 10 frames/frame%03d.png
convert -delay 5 -loop 0 frames/frame*.png output.gif

Source: http://superuser.com/a/556031

利用ffmpeg屏幕录制

参考:https://trac.ffmpeg.org/wiki/Capture/Desktop

添加水印

ffmpeg -i input.mp4 -i picture.png -filter_complex overlay="(main_w/2)-(overlay_w/2):(main_h/2)-(overlay_h)/2" output.mp4

picture.png 为水印图片, overlay 为水印位置

ffmpeg使用语法

ffmpeg使用语法:

ffmpeg [global_options] {[input_file_options] -i input_file} ... {[output_file_options] output_file} ...

如果没有输入文件,那么视音频捕捉就会起作用。

作为通用的规则,选项一般用于下一个特定的文件。如果你给 –b 64选项,改选会设置下一个视频速率。对于原始输入文件,格式选项可能是需要的。

缺省情况下,ffmpeg试图尽可能的无损转换,采用与输入同样的音频视频参数来输出。

通用选项

-L license 显示协议  
-h 帮助  
-formats 显示可用的格式,编解码的,协议的  
-decoders 可用解码器  
-encoders 可用编码器  

主要选项

-i 	filename 输入文件  
-y 	覆盖输出文件  
-n 	不覆盖输出文件,如果输出文件存在则退出  
-t 	duration (input/output)  
    设置纪录时间 hh:mm:ss[.xxx]格式的记录时间也支持,在 `-i` 之前使用,则对输入文件限制记录时间;如果对输出文件使用,则是限制输出文件的时长。  
    
-ss position  
    搜索到指定的时间 [-]hh:mm:ss[.xxx]的格式也支持 ,更多[参考](https://ffmpeg.org/ffmpeg-utils.html#time-duration-syntax)  
    
-title string 设置标题  
-author string 设置作者  
-copyright string 设置版权  
-comment string 设置评论  
-f fmt 强迫采用格式fmt 输出  

-c[:stream_specifier] codec (input/output, per-stream)  
-codec[:stream_specifier] codec (input/output, per-stream)  
    给输入文件指定解码器,给输出文件指定编码器, codec 为编码器名字,如果 codec 值为 `copy` 则默认为和原视频一致。  
    
-vcodec codec  
    vcodec  -codec:v 的一个别称,强制使用codec编解码方式,未设定时使用与输入流相同的编码器。如果用copy表示原始编解码数据必须被拷贝。

-target type 设置目标文件类型(vcd,svcd,dvd) 所有的格式选项(比特率,编解码以及缓冲区大小)自动设置,只需要输入如下的就可以了:

    ffmpeg -i input.avi -target vcd /tmp/vcd.mpg

-hq 激活高质量设置  
-itsoffset offset 设置以秒为基准的时间偏移,该选项影响所有后面的输入文件。该偏移被加到输入文件的时戳,定义一个正偏移意味着相应的流被延迟了 offset秒。 [-]hh:mm:ss[.xxx]的格式也支持  

### 视频选项 {#video-options}

-vframes number (output)  
    设置视频输出帧数,是`-frames:v`的别称。
    
-b bitrate 设置比特率,缺省200kb/s  
-r fps 设置帧率 缺省25  
-s size 设置画面的宽高

    设置帧大小,分辨率, 格式为wxh 缺省为原视频大小。下面的简写也可以直接使用:
    ntsc 720x480
    snits 640x480
    hd720 1280x720
    hd1080 1920x1080
    更多[参考](https://ffmpeg.org/ffmpeg-utils.html#toc-Video-size)

-aspect aspect 设置画面比例 4:3 16:9  1.3333 1.7777  
-croptop size 设置顶部切除带大小 像素单位  
-cropbottom size cropleft size cropright size  
-padtop size 设置顶部补齐的大小 像素单位  

-padbottom size padleft size padright size padcolor color 设置补齐条颜色(hex,616进制的数,红:绿:兰排列,比如 000000代表黑色)

-vn 不做视频记录,输出无视频内容  
-bt tolerance 设置视频码率容忍度kbit/s  
-maxrate bitrate设置最大视频码率容忍度  
-minrate bitreate 设置最小视频码率容忍度

-bufsize size 设置码率控制缓冲区大小

-sameq 使用同样视频质量作为源(VBR

-pass n 选择处理遍数(1或者2)。两遍编码非常有用。第一遍生成统计信息,第二遍生成精确的请求的码率

-passlogfile file 选择两遍的纪录文件名为file

高级视频选项

-g gop_size 设置图像组大小

-intra 仅适用帧内编码

-qscale q 使用固定的视频量化标度(VBR)

-qmin q 最小视频量化标度(VBR)

-qmax q 最大视频量化标度(VBR)

-qdiff q 量化标度间最大偏差 (VBR)

-qblur blur 视频量化标度柔化(VBR)

-qcomp compression 视频量化标度压缩(VBR)

-rc_init_cplx complexity 一遍编码的初始复杂度

-b_qfactor factor pb帧间的qp因子

-i_qfactor factor pi帧间的qp因子

-b_qoffset offset pb帧间的qp偏差

-i_qoffset offset pi帧间的qp偏差

-rc_eq equation 设置码率控制方程 默认tex^qComp

-rc_override override 特定间隔下的速率控制重载

-me method 设置运动估计的方法 可用方法有 zero phods log x1 epzs(缺省) full

-dct_algo algo 设置dct的算法 可用的有 0 FF_DCT_AUTO 缺省的DCT 1 FF_DCT_FASTINT 2 FF_DCT_INT 3 FF_DCT_MMX 4 FF_DCT_MLIB 5 FF_DCT_ALTIVEC

-idct_algo algo 设置idct算法。可用的有 0 FF_IDCT_AUTO 缺省的IDCT 1 FF_IDCT_INT 2 FF_IDCT_SIMPLE 3 FF_IDCT_SIMPLEMMX 4 FF_IDCT_LIBMPEG2MMX 5 FF_IDCT_PS2 6 FF_IDCT_MLIB 7 FF_IDCT_ARM 8 FF_IDCT_ALTIVEC 9 FF_IDCT_SH4 10 FF_IDCT_SIMPLEARM

-er n 设置错误残留为n 1 FF_ER_CAREFULL 缺省 2 FF_ER_COMPLIANT 3 FF_ER_AGGRESSIVE 4 FF_ER_VERY_AGGRESSIVE

-ec bit_mask 设置错误掩蔽为bit_mask,该值为如下值的位掩码 1 FF_EC_GUESS_MVS (default=enabled) 2 FF_EC_DEBLOCK (default=enabled)

-bf frames 使用frames B 帧,支持mpeg1,mpeg2,mpeg4

-mbd mode 宏块决策 0 FF_MB_DECISION_SIMPLE 使用mb_cmp 1 FF_MB_DECISION_BITS 2 FF_MB_DECISION_RD

-4mv 使用4个运动矢量 仅用于mpeg4

-part 使用数据划分 仅用于mpeg4

-bug param 绕过没有被自动监测到编码器的问题

-strict strictness 跟标准的严格性

-aic 使能高级帧内编码 h263+

-umv 使能无限运动矢量 h263+

-deinterlace 不采用交织方法

-interlace 强迫交织法编码仅对mpeg2mpeg4有效。当你的输入是交织的并且你想要保持交织以最小图像损失的时候采用该选项。可选的方法是不交织,但是损失更大

-psnr 计算压缩帧的psnr

-vstats 输出视频编码统计到vstats_hhmmss.log

-vhook module 插入视频处理模块 module 包括了模块名和参数,用空格分开

### 音频选项 {#audio-options}

-aframes number (output)  
    设置输出文件音频帧数,是`-frames:a` 的别名

-ab bitrate  
    设置音频码率,声音比特率,-ac 设为立体声时要以一半比特率来设置,比如192kbps 的就设置成96,高品质音乐建议160kbps(80) 一上

-ar freq  
    设置音频采样率,一般设置44100

-ac channels  
    设置通道,声道数, 缺省为1, 1为单声道,2为立体声

-an 不使用音频纪录

-acodec codec
    使用codec编解码,是`-codec:a`的别名

音频/视频捕获选项

-vd device 设置视频捕获设备。比如/dev/video0

-vc channel 设置视频捕获通道 DV1394专用

-tvstd standard 设置电视标准 NTSC PAL(SECAM)

-dv1394 设置DV1394捕获

-av device 设置音频设备 比如/dev/dsp

### 高级选项 {#advance-option}

-map file:stream 设置输入流映射

-debug 打印特定调试信息

-benchmark 为基准测试加入时间

-hex 倾倒每一个输入包

-bitexact 仅使用位精确算法 用于编解码测试

-ps size 设置包大小,以bits为单位

-re 以本地帧频读数据,主要用于模拟捕获设备

-loop 循环输入流。只工作于图像流,用于ffserver测试

附录1:ffmpeg 简略帮助

Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...

Getting help:
    -h      -- print basic options
    -h long -- print more options
    -h full -- print all options (including all format and codec specific options, very long)
    -h type=name -- print all options for the named decoder/encoder/demuxer/muxer/filter
    See man ffmpeg for detailed description of the options.

Print help / information / capabilities:
-L                  show license
-h topic            show help
-? topic            show help
-help topic         show help
--help topic        show help
-version            show version
-buildconf          show build configuration
-formats            show available formats
-devices            show available devices
-codecs             show available codecs
-decoders           show available decoders
-encoders           show available encoders
-bsfs               show available bit stream filters
-protocols          show available protocols
-filters            show available filters
-pix_fmts           show available pixel formats
-layouts            show standard channel layouts
-sample_fmts        show available audio sample formats
-colors             show available color names
-sources device     list sources of the input device
-sinks device       list sinks of the output device
-hwaccels           show available HW acceleration methods

Global options (affect whole program instead of just one file:
-loglevel loglevel  set logging level
-v loglevel         set logging level
-report             generate a report
-max_alloc bytes    set maximum size of a single allocated block
-y                  overwrite output files
-n                  never overwrite output files
-ignore_unknown     Ignore unknown stream types
-stats              print progress report during encoding
-max_error_rate ratio of errors (0.0: no errors, 1.0: 100% error  maximum error rate
-bits_per_raw_sample number  set the number of bits per raw sample
-vol volume         change audio volume (256=normal)

Per-file main options:
-f fmt              force format
-c codec            codec name
-codec codec        codec name
-pre preset         preset name
-map_metadata outfile[,metadata]:infile[,metadata]  set metadata information of outfile from infile
-t duration         record or transcode "duration" seconds of audio/video
-to time_stop       record or transcode stop time
-fs limit_size      set the limit file size in bytes
-ss time_off        set the start time offset
-sseof time_off     set the start time offset relative to EOF
-seek_timestamp     enable/disable seeking by timestamp with -ss
-timestamp time     set the recording timestamp ('now' to set the current time)
-metadata string=string  add metadata
-program title=string:st=number...  add program with specified streams
-target type        specify target file type ("vcd", "svcd", "dvd", "dv" or "dv50" with optional prefixes "pal-", "ntsc-" or "film-")
-apad               audio pad
-frames number      set the number of frames to output
-filter filter_graph  set stream filtergraph
-filter_script filename  read stream filtergraph description from a file
-reinit_filter      reinit filtergraph on input parameter changes
-discard            discard
-disposition        disposition

Video options:
-vframes number     set the number of video frames to output
-r rate             set frame rate (Hz value, fraction or abbreviation)
-s size             set frame size (WxH or abbreviation)
-aspect aspect      set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)
-bits_per_raw_sample number  set the number of bits per raw sample
-vn                 disable video
-vcodec codec       force video codec ('copy' to copy stream)
-timecode hh:mm:ss[:;.]ff  set initial TimeCode value.
-pass n             select the pass number (1 to 3)
-vf filter_graph    set video filters
-ab bitrate         audio bitrate (please use -b:a)
-b bitrate          video bitrate (please use -b:v)
-dn                 disable data

Audio options:
-aframes number     set the number of audio frames to output
-aq quality         set audio quality (codec-specific)
-ar rate            set audio sampling rate (in Hz)
-ac channels        set number of audio channels
-an                 disable audio
-acodec codec       force audio codec ('copy' to copy stream)
-vol volume         change audio volume (256=normal)
-af filter_graph    set audio filters

Subtitle options:
-s size             set frame size (WxH or abbreviation)
-sn                 disable subtitle
-scodec codec       force subtitle codec ('copy' to copy stream)
-stag fourcc/tag    force subtitle tag/fourcc
-fix_sub_duration   fix subtitles duration
-canvas_size size   set canvas size (WxH or abbreviation)
-spre preset        set the subtitle options to the indicated preset


安装ffmpeg
CentOS 6和7安装方法是不一样的,下面分别说明:

安装前都需要先安装epel扩展源

yum -y install epel-release
CentOS 6比较简单,安装yum源之后直接安装即可:

su -c ‘yum localinstall –nogpgcheck https://download1.rpmfusion.org/free/el/rpmfusion-free-release-6.noarch.rpm https://download1.rpmfusion.org/nonfree/el/rpmfusion-nonfree-release-6.noarch.rpm’

yum -y install ffmpeg ffmpeg-devel
而CentOS 7需额外安装扩展源:

su -c ‘yum localinstall –nogpgcheck https://download1.rpmfusion.org/free/el/rpmfusion-free-release-7.noarch.rpm https://download1.rpmfusion.org/nonfree/el/rpmfusion-nonfree-release-7.noarch.rpm’

rpm –import http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro
rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-1.el7.nux.noarch.rpm

yum -y install ffmpeg ffmpeg-devel
安装youtube-dl
youtube-dl需要Python 2.6以上的版本。因此需要先确认安装的Python版本。默认CentOS6或者7都没有问题。以防万一通过以下命令可以查看版本:

python –version
youtube-dl直接下载最新版到/usr/local/bin/目录下并赋予权限即可使用。命令:

wget http://youtube-dl.org/latest/youtube-dl -O /usr/local/bin/youtube-dl
chmod a+x /usr/local/bin/youtube-dl