1.查看幫助文檔
ffmpeg是一個開源的音視頻轉(zhuǎn)碼工具
本文是自己學(xué)習(xí)ffmpeg使用方式的一個筆記
將ffmpeg命令行工具加入環(huán)境變量之后,輸入ffmpeg -h打印幫助文檔
PS C:\Users\mudssky\Desktop> ffmpeg -h
ffmpeg version N-92752-g16ec62bbf4 Copyright (c) 2000-2018 the FFmpeg developers
built with gcc 8.2.1 (GCC) 20181201
configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
libavutil 56\. 24.101 / 56\. 24.101
libavcodec 58\. 42.104 / 58\. 42.104
libavformat 58\. 24.101 / 58\. 24.101
libavdevice 58. 6.101 / 58. 6.101
libavfilter 7\. 46.101 / 7\. 46.101
libswscale 5. 4.100 / 5. 4.100
libswresample 3. 4.100 / 3. 4.100
libpostproc 55. 4.100 / 55. 4.100
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/bsf
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
-muxers show available muxers
-demuxers show available demuxers
-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
-filter_threads number of non-complex filter threads
-filter_complex_threads number of threads for -filter_complex
-stats print progress report during encoding
-max_error_rate maximum error rate ratio of errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.
-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
可選視頻編碼方案
1. MP4封裝:H264視頻編碼+AAC音頻編碼(最通用)
2. WebM封裝: VP8視頻編碼+Vorbis音頻編碼(Google為了避開專利開發(fā),無明顯優(yōu)勢)
3. OGG封裝: Theora視頻編碼 +Vorvis音頻編碼(完全開源的編碼方式,無專利,HTML5可用)
2.音頻轉(zhuǎn)碼
例子 flac轉(zhuǎn)mp3
ffmpeg -i input.flac -acodec libmp3lame -ar 44100 -ab 320k -ac 2 out.mp3
-acodec 輸入編碼器,不輸入也可以,ffmpeg會自動根據(jù)后綴名選擇編碼器
-ar rate 指定采樣頻率,不指定采樣頻率會根據(jù)輸入音視頻的采樣頻率
-ab audio byte rates 指定比特率,如果不輸入默認是128K,這點就有點坑了。128K作為視頻的音軌比較合適,但是這個音質(zhì)作為單純的音頻來說還是基本上是最低音質(zhì),平時我們在手機里聽聽的水平。
-ac audio channel 指定聲道數(shù)
3.視頻壓制
ffmpeg -i in.webm -s 1920*1080 -pix_format yuv420p -vcodec libx264 -preset medium -profile:v high -level:v -crf 23
-s size 指定視頻尺寸進行縮放
-pix_format 指定視頻使用的顏色空間 ,輸入
ffmpeg -pix_fmts可以打印出所有支持的選項。我就知道兩個YUV和RGB,YUV表示明亮度,色度和濃度,因為人的色覺對亮度的敏感程度要高一些,所以網(wǎng)絡(luò)視頻通常會對色度層面進行壓縮。也就是所謂的yuv420p。Y保留全部UV進行壓縮-vcodex 指定視頻編碼器,建議使用libx264
-
-preset 對編碼器的預(yù)設(shè),精度越高編碼速度越慢,占用cpu性能越高,默認是medium
有以下幾個選項
1. ultrafast
2. superfast
3. veryfast
4. faster
5. fast
6. medium
7. slow
8. slower
9. veryslow
10. placebo
通常我們在網(wǎng)絡(luò)上發(fā)布視頻,會使用veryfast選項。較快,消耗性能少,對播放器的要求也低,缺點是生成的視頻會大一些
壓制視頻的時候,一般采用veryslow選項。
-profile:v 指定編碼器配置,主要和壓縮比有關(guān)。
如下圖所示,越往左支持的選項越少,質(zhì)量越低
實時通信領(lǐng)域采用baseline
流媒體領(lǐng)域 使用 main
超清視頻 使用high

- -level:v 對編碼器配置的限制,如下表
一般情況下1080P及以下視頻選用4.1即可

-crf Constant Rate Factor 恒定速率因子模式,每一幀的畫面都按照要求的視頻質(zhì)量計算需要的比特數(shù),畫質(zhì)均衡,但是無法控制碼率,也無法控制最終生成文件的大小。 適用于對于畫質(zhì)有要求,文件大小沒有要求的情況,范圍0-51,默認值就是23,數(shù)字越小質(zhì)量越高
-r 設(shè)置視頻幀率
-b:a 同 -ab 設(shè)置音頻比特率,大多數(shù)視頻網(wǎng)站的音頻比特率都是128K或者192K
4.碼率控制模式
fmmpeg支持3種碼率控制模式
1. -qp 恒定量化器模式,量化器就是用算法將每一幀的質(zhì)量轉(zhuǎn)化為數(shù)字,可以設(shè)置,建議讓軟件自動設(shè)置。
體積最大
一般不使用這種模式,除非你想無損壓制視頻
無損壓制視頻的例子(快速編碼)
ffmpeg -i input -vcodec libx264 -preset ultrafast -qp 0 output.mkv
無損壓制視頻的例子(高壓縮比)
ffmpeg -i input -vcodec libx264 -preset veryslow -qp 0 output.mkv
嘗試了用這種無損壓縮方式壓縮dvd鏡像中提取的vob文件,發(fā)現(xiàn)這種方式壓制出來的文件體積竟然是原來的兩倍。所以說還是使用crf 18,這樣就比較接近無損了。
2. -crf 恒定速率因子模式,相當(dāng)于浮動值的qp模式,會給每個畫面不同的量化值,比如說把人眼不敏感的部分碼率調(diào)低。一般壓制視頻使用這個選項。但是不懂不推薦亂設(shè)置,讓軟件自動配置即可
值的范圍是0-51,默認值是23,通常認為crf值18壓制出來的視頻視覺上是無損的。18-23之間的變化不明顯。
3. -b 固定目標(biāo)碼率模式,當(dāng)上傳視頻網(wǎng)站有碼率限制時,可以使用這個選項。但是不推薦。crf也可以獲得合適的體積和畫質(zhì)。沒必要
使用上面3個選項壓制,都是單遍編碼,最好加上-preset veryslow 選項,這樣軟件對參數(shù)的控制會更精準(zhǔn)
比特率模式
VBR 動態(tài)比特率,ffmpeg默認采用,簡單的內(nèi)容少給碼率,復(fù)雜內(nèi)容多給碼率。
ABR 平均比特率,網(wǎng)絡(luò)視頻會采用這一格式,因為VBR碼率變化太大,不適用網(wǎng)絡(luò)傳輸
CBR 恒定比特率, 通常沒有人使用
輸入 ffmpeg -h encoder=libx264 查看最常用的x264編碼器的使用方式
-nal-hrd 可以指定VBR和CBR兩種,但是CBR在.mp4不支持?
其余還有-maxrate -minrate 選項,設(shè)置這兩個選項就能達到ABR的效果
PS C:\Users\mudssky\Desktop> ffmpeg.exe -h encoder=libx264
ffmpeg version N-92752-g16ec62bbf4 Copyright (c) 2000-2018 the FFmpeg developers
built with gcc 8.2.1 (GCC) 20181201
configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt
libavutil 56. 24.101 / 56. 24.101
libavcodec 58. 42.104 / 58. 42.104
libavformat 58. 24.101 / 58. 24.101
libavdevice 58. 6.101 / 58. 6.101
libavfilter 7. 46.101 / 7. 46.101
libswscale 5. 4.100 / 5. 4.100
libswresample 3. 4.100 / 3. 4.100
libpostproc 55. 4.100 / 55. 4.100
Encoder libx264 [libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10]:
General capabilities: delay threads
Threading capabilities: auto
Supported pixel formats: yuv420p yuvj420p yuv422p yuvj422p yuv444p yuvj444p nv12 nv16 nv21 yuv420p10le yuv422p10le yuv444p10le nv20le gray gray10le
libx264 AVOptions:
-preset <string> E..V..... Set the encoding preset (cf. x264 --fullhelp) (default "medium")
-tune <string> E..V..... Tune the encoding params (cf. x264 --fullhelp)
-profile <string> E..V..... Set profile restrictions (cf. x264 --fullhelp)
-fastfirstpass <boolean> E..V..... Use fast settings when encoding first pass (default true)
-level <string> E..V..... Specify level (as defined by Annex A)
-passlogfile <string> E..V..... Filename for 2 pass stats
-wpredp <string> E..V..... Weighted prediction for P-frames
-a53cc <boolean> E..V..... Use A53 Closed Captions (if available) (default true)
-x264opts <string> E..V..... x264 options
-crf <float> E..V..... Select the quality for constant quality mode (from -1 to FLT_MAX) (default -1)
-crf_max <float> E..V..... In CRF mode, prevents VBV from lowering quality beyond this point. (from -1 to FLT_MAX) (default -1)
-qp <int> E..V..... Constant quantization parameter rate control method (from -1 to INT_MAX) (default -1)
-aq-mode <int> E..V..... AQ method (from -1 to INT_MAX) (default -1)
none E..V.....
variance E..V..... Variance AQ (complexity mask)
autovariance E..V..... Auto-variance AQ
autovariance-biased E..V..... Auto-variance AQ with bias to dark scenes
-aq-strength <float> E..V..... AQ strength. Reduces blocking and blurring in flat and textured areas. (from -1 to FLT_MAX) (default -1)
-psy <boolean> E..V..... Use psychovisual optimizations. (default auto)
-psy-rd <string> E..V..... Strength of psychovisual optimization, in <psy-rd>:<psy-trellis> format.
-rc-lookahead <int> E..V..... Number of frames to look ahead for frametype and ratecontrol (from -1 to INT_MAX) (default -1)
-weightb <boolean> E..V..... Weighted prediction for B-frames. (default auto)
-weightp <int> E..V..... Weighted prediction analysis method. (from -1 to INT_MAX) (default -1)
none E..V.....
simple E..V.....
smart E..V.....
-ssim <boolean> E..V..... Calculate and print SSIM stats. (default auto)
-intra-refresh <boolean> E..V..... Use Periodic Intra Refresh instead of IDR frames. (default auto)
-bluray-compat <boolean> E..V..... Bluray compatibility workarounds. (default auto)
-b-bias <int> E..V..... Influences how often B-frames are used (from INT_MIN to INT_MAX) (default INT_MIN)
-b-pyramid <int> E..V..... Keep some B-frames as references. (from -1 to INT_MAX) (default -1)
none E..V.....
strict E..V..... Strictly hierarchical pyramid
normal E..V..... Non-strict (not Blu-ray compatible)
-mixed-refs <boolean> E..V..... One reference per partition, as opposed to one reference per macroblock (default auto)
-8x8dct <boolean> E..V..... High profile 8x8 transform. (default auto)
-fast-pskip <boolean> E..V..... (default auto)
-aud <boolean> E..V..... Use access unit delimiters. (default auto)
-mbtree <boolean> E..V..... Use macroblock tree ratecontrol. (default auto)
-deblock <string> E..V..... Loop filter parameters, in <alpha:beta> form.
-cplxblur <float> E..V..... Reduce fluctuations in QP (before curve compression) (from -1 to FLT_MAX) (default -1)
-partitions <string> E..V..... A comma-separated list of partitions to consider. Possible values: p8x8, p4x4, b8x8, i8x8, i4x4, none, all
-direct-pred <int> E..V..... Direct MV prediction mode (from -1 to INT_MAX) (default -1)
none E..V.....
spatial E..V.....
temporal E..V.....
auto E..V.....
-slice-max-size <int> E..V..... Limit the size of each slice in bytes (from -1 to INT_MAX) (default -1)
-stats <string> E..V..... Filename for 2 pass stats
-nal-hrd <int> E..V..... Signal HRD information (requires vbv-bufsize; cbr not allowed in .mp4) (from -1 to INT_MAX) (default -1)
none E..V.....
vbr E..V.....
cbr E..V.....
-avcintra-class <int> E..V..... AVC-Intra class 50/100/200 (from -1 to 200) (default -1)
-me_method <int> E..V..... Set motion estimation method (from -1 to 4) (default -1)
dia E..V.....
hex E..V.....
umh E..V.....
esa E..V.....
tesa E..V.....
-motion-est <int> E..V..... Set motion estimation method (from -1 to 4) (default -1)
dia E..V.....
hex E..V.....
umh E..V.....
esa E..V.....
tesa E..V.....
-forced-idr <boolean> E..V..... If forcing keyframes, force them as IDR frames. (default false)
-coder <int> E..V..... Coder type (from -1 to 1) (default default)
default E..V.....
cavlc E..V.....
cabac E..V.....
vlc E..V.....
ac E..V.....
-b_strategy <int> E..V..... Strategy to choose between I/P/B-frames (from -1 to 2) (default -1)
-chromaoffset <int> E..V..... QP difference between chroma and luma (from INT_MIN to INT_MAX) (default -1)
-sc_threshold <int> E..V..... Scene change threshold (from INT_MIN to INT_MAX) (default -1)
-noise_reduction <int> E..V..... Noise reduction (from INT_MIN to INT_MAX) (default -1)
-x264-params <string> E..V..... Override the x264 configuration using a :-separated list of key=value parameters
5.合并,提取視頻
01.提取視頻流,
假設(shè)我們提取mp4視頻中的視頻流
ffmpeg -i in.mp4 -vcodec copy -an v.mp4
-an選項是 audio no 也就是忽略音頻
02.提取音頻
ffmpeg -i in.mp4 -acodec copy -vn a.m4a
同理 -vn 即忽略音頻
如果提取多個音軌的視頻:
比如我們用ffprobe看到如下

提取第二條 只需加上-map 0:3
03.合并音視頻
ffmpeg -i a.m4a -i v.mp4 -c copy out.mp4
瞬間就能完成合并,因為音頻和視頻都是現(xiàn)成的,不用重新編碼
-c 就是 -codec的簡寫
6.截取、連接音視頻
01.截取音視頻
ffmpeg -i in.mp3 -ss 00:01:00 -to 00:01:10 -acodec copy out.mp3
-ss 設(shè)置起始時間位移
-to 設(shè)置結(jié)束時間位移
也可以使用下面的方式
ffmpeg -i in.mp3 -ss 00:01:00 -t 10 -acodec copy out.mp3
-t 設(shè)置截取時長
還有-sseof 選項 是以媒體末尾作為起點,可以配合-t截取末尾多少秒
看下面2條命令
ffmpeg -i in.mp4 -ss 00:01:00 -to 00:01:10 -acodec copy out.mp4
ffmpeg -ss 00:01:00 -i in.mp4 -to 00:01:10 -acodec copy out.mp4
調(diào)換-ss和-i的位置對結(jié)果的影響?
-ss在前面會調(diào)用關(guān)鍵幀技術(shù),可能導(dǎo)致截取的時間并不準(zhǔn)確
ffmpeg -ss 00:01:00 -i in.mp4 -to 00:01:10 -acodec copy -copyts out.mp4
我們可以加上 -copyts選項,作用是保留時間戳,這樣就能正確截取了。
02.合并音視頻
方法一
ffmpeg -i "concat:01.mp4|02.mp4|03.mp4" -c copy out.mp4
當(dāng)合并的幾個視頻參數(shù)一致時,很快就合并完成了。
合并不同參數(shù)的視頻,操作會比較麻煩。
方法二
上面的方法其實相當(dāng)于把兩個文件直接拼在一起,適用于mp2之類的視頻,如果是flv連接處會有卡頓現(xiàn)象
下面的方法,先在一個txt文本中把要拼接的文件列出來。
這條命令只要是相同格式的視頻均可以拼接
ffmpeg -f concat -safe 0 -i files.txt -c copy output.mp4
-safe 命令是讓ffmpeg無視安全問題報錯
在txt文件中的格式需要是這樣子
file 'file1.mp4'
file 'file2.mp4'
可以使用開源軟件Avidemux,圖形化界面,操作方便
7.截圖、水印、動圖
01.截圖
ffmpeg -i in.mp4 -ss 5 -vframes 1 img.jpg
-vframe 指定截取的幀
02.加水印
ffmpeg -i in.mp4 -i logo.png -filter_complex "overlay=20:20"
-filter_complex 添加濾鏡 overlay20:20 指的是,離左邊20像素,離上邊20像素
03.制作GIF動圖
ffmpeg -i in.mp4 -ss 4.5 -to 8.5 -s 640*320 -r 15 out.gif
8.錄屏、直播
01.錄屏
ffmpeg -f gdigrab -i desktop rec.mp4
默認錄屏參數(shù)是下面這樣的
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '.\rec.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf58.24.101
Duration: 00:00:04.11, start: 0.000000, bitrate: 676 kb/s
Stream #0:0(und): Video: h264 (High 4:4:4 Predictive) (avc1 / 0x31637661), yuv444p, 2560x1440, 672 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 59.94 tbc (default)
Metadata:
handler_name : VideoHandler
清晰度相當(dāng)不錯,字符都很清楚,但是沒有聲音
-f 格式化 gdigrab 是ffmpeg的一個組件,用來捕獲視頻。 在windows系統(tǒng)中,ffmpeg自帶的就是和默認使用的gdigrab,只能錄制屏幕,不能錄制聲音
直播推薦使用OBS Studio,開源免費,功能強大
02.直播推流
ffmpeg -re -i rec.mp4 按網(wǎng)站要求輸入想要的編碼 -f flv rtmp地址