ffmpeg调用libx264编码高级选项

在命令行中输入:

ffmpeg -h encoder=libx264

会输出一下信息:

Encoder libx264 [libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10]:
    Threading capabilities: no
    Supported pixel formats: yuv420p yuvj420p yuv422p yuvj422p yuv444p yuvj444pnv12 nv16
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     <int>        E..V.... Use fast settings when encoding first pass (from 0 to 1) (default 1)
  -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
  -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 ratecontrol 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
  -aq-strength       <float>      E..V.... AQ strength. Reduces blocking and blurring in flat and textured areas. (from -1 to FLT_MAX) (default -1)
  -psy               <int>        E..V.... Use psychovisual optimizations. (from -1 to 1) (default -1)
  -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           <int>        E..V.... Weighted prediction for B-frames. (from -1 to 1) (default -1)
  -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              <int>        E..V.... Calculate and print SSIM stats. (from -1 to 1) (default -1)
  -intra-refresh     <int>        E..V.... Use Periodic Intra Refresh instead of IDR frames. (from -1 to 1) (default -1)
  -bluray-compat     <int>        E..V.... Bluray compatibility workarounds. (from -1 to 1) (default -1)
  -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        <int>        E..V.... One reference per partition, as opposed to one reference per macroblock (from -1 to 1) (default -1)
  -8x8dct            <int>        E..V.... High profile 8x8 transform. (from -1to 1) (default -1)
  -fast-pskip        <int>        E..V.... (from -1 to 1) (default -1)
  -aud               <int>        E..V.... Use access unit delimiters. (from -1to 1) (default -1)
  -mbtree            <int>        E..V.... Use macroblock tree ratecontrol. (from -1 to 1) (default -1)
  -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 partitionsto 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)
  -x264-params       <string>     E..V.... Override the x264 configuration using a :-separated list of key=value parameters
参数介绍:

-preset <string>       Use a preset to select encoding settings [medium]
                            Overridden by user settings.
                            - ultrafast,superfast,veryfast,faster,fast
                            - medium,slow,slower,veryslow,placebo

按编码速度的内置参数,内置的编码设置有:ultrafast,superfast,veryfast,faster,fast,medium,slow,slower,veryslow,placebo,按快到慢排列,默认为medium级,当然越慢效果越好,但是体积会增大,一般最求高质量用veryslow就够了。

-tune <string>         Tune the settings for a particular type of source or situation
                            Overridden by user settings.
                            Multiple tunings are separated by commas.
                            Only one psy tuning can be used at a time.
                            - psy tunings: film,animation,grain,
                                           stillimage,psnr,ssim
                            - other tunings: fastdecode,zerolatency
按不同的源或者不用的应用场景的内置参数,主要有:film,animation,grain,stillimage,psnr,ssim,fastdecode,zerolatency。

film:电影、真人类型;
animation:动画;
grain:需要保留大量的grain时用;
stillimage:静态图像编码时使用;
psnr:为提高psnr做了优化的参数;
ssim:为提高ssim做了优化的参数;
fastdecode:可以快速解码的参数;
zerolatency:零延迟,用在需要非常低的延迟的情况下,比如电视电话会议的编码。


-profile <string>      Force the limits of an H.264 profile
                            Overrides all settings.
                            - baseline,main,high,high10,high422,high444
默认值:未设置
限定编码输出流的等级。如果你指定了等级,它将取代全部其它选项,所以使用等级选项可以得到良好的兼容性。但使用等级选项,就无法使用无损压缩(--qp 0 or --crf 0)。
如果你的播放器仅能支持特定等级的话,就需要指定等级选项。大多数播放器支持高等级,就不需要指定等级选项了。
可选项:baseline,main,high,high10,high422,high444

不同的设备支持不同的等级,在此不详细说明,需要一个个的去查。

-fastfirstpass     <int>        E..V.... Use fast settings when encoding first pass (from 0 to 1) (default 1)
在第一遍编码的时候用fast参数。默认为1。

<pre name="code" class="cpp">-level <string>        Specify level (as defined by Annex A)



默认: -1 (自动)在输出流中设定等级标志(H.264 标准附录A。http://en.wikipedia.org/wiki/H.264#Levels)。

允许的等级有: 1 1.1 1.2 1.3 2 2.1 2.2 3 3.1 3.2 4 4.1 4.2 5 5.1 (等级 1b 不被支持)如果没有设定等级,x264 将试图自动判断。自动判断并不完美且在不使用 VBV 的情况下可能低估等级。x264 将自动限制 DPB 尺寸(看 --ref)与你设定的等级相匹配(除非你手工指定 --ref)。注意:--vbv_maxrate 或 --vbv_bufsize 不会根据设定的等级自动设置,但是如果它们的参数超越设定的等级会告警。选择什么等级?Level 4.1 常常是桌面型硬件能支持的最高等级。蓝光碟仅支持 Level 4.1,许多非手机类设备,像 Xbox 360,指定 Level 4.1 为官方支持的最高等级。手机设备,像 iPhone/Android 则是完全不同的处理方式。详细的等级限制图表,参见:http://en.wikipedia.org/wiki/H.264/MPEG-4_AVC#Levels建议: Default,除非是为一个特定设备编码。

-passlogfile       <string>     E..V.... Filename for 2 pass stats

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

  -wpredp            <string>     E..V.... Weighted prediction for P-frames
P帧的预测权重。

  -x264opts          <string>     E..V.... x264 options
修改参数值,用法:-x264opts keyint=123:min-keyint=20。

  -crf               <float>      E..V.... Select the quality for constant quality mode (from -1 to FLT_MAX) (default -1)
质量标准,默认为-1(自动),一般18就比较好了。

  -crf_max           <float>      E..V.... In CRF mode, prevents VBV from lowering quality beyond this point. (from -1 to FLT_MAX) (default -1)
crf最大值。

  -qp                <int>        E..V.... Constant quantization parameter ratecontrol method (from -1 to INT_MAX) (default -1)

默认:无
说明:三种可选的码率控制方法之一。设置x264使用固定量化参数模式。给定的数量将被作为P帧的量化参数,I帧和B帧的量化参数由–ipratio and –pbratio参数进一步算出。QP模式适用固定的量化参数,这意味着最终的文件大小是不可知的(可以通过一些其他方法预测)。设置为0将产出无损的输出。相同视觉质量时,QP模式产出的文件比crf模式大。QP模式将关闭自适应量化器,因为它是固定QP的。
这个选项和 –bitrate和–crf是互斥的,三者只能选一个,它们背后的原理可以看这篇文章http://blog.yikuyiku.com/index.php/archives/1901。
一般而言crf都能代替QP模式,不过QP因为完全不需要预测所以它会运行地更快些。
参见:–bitrate, –crf, –ipratio, –pbratio

-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

默认:1
说明:自适应量化器模式。不使用自适应量化的话,x264趋向于使用较少的bit在缺乏细节的场景里。自适应量化可以在整个视频的宏块里更好地分配比特。它有以下选项:
none —— 完全关闭自适应量化器 
variance —— 允许自适应量化器在所有视频帧内部分配比特。
autovariance—— 根据前一帧强度决策的自变量化器(实验性的)。
参见: –aq-strength

  -aq-strength       <float>      E..V.... AQ strength. Reduces blocking and blurring in flat and textured areas. (from -1 to FLT_MAX) (default -1)
默认:1.0
说明:自适应量化强度。设置自适应量化对于缺乏细节(平坦)的宏块的剥削程度。不允许负值。0.0 – 2.0之外的值不推荐。
参见:–aq-mode

<pre name="code" class="cpp">-psy               <int>        E..V.... Use psychovisual optimizations. (from -1 to 1) (default -1)


视觉优化参数,从-1到1,默认为-1。

  -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)
默认:-1
说明:为mb-tree ratecontrol(Macroblock Tree Ratecontrol)和vbv-lookahead设置可用的帧的数量。最大可设置为250。
对于mb-tree而言,调大这个值会得到更准确地结果,但也会更慢。mb-tree能使用的最大值是–rc-lookahead和–keyint中较小的那一个。
对于vbv-lookahead而言,调大这个值会得更稳定和精确的码率控制。vbv-lookahead能使用的最大值是如下公式算出来的:

MIN(rc-lookahead, MAX(–keyint, MAX(–vbv-maxrate, –bitrate) / –vbv-bufsize * –fps))
参见:–no-mbtree, –vbv-bufsize, –vbv-maxrate

  -weightb           <int>        E..V.... Weighted prediction for B-frames. (from -1 to 1) (default -1)
b帧的预测权重,默认-1,从-1到1。

  -weightp           <int>        E..V.... Weighted prediction analysis method.(from -1 to INT_MAX) (default -1)
     none                         E..V....
     simple                       E..V....
     smart                        E..V....
预测分析方法的权重。从-1到INT_MAX,默认-1。

  -ssim              <int>        E..V.... Calculate and print SSIM stats. (from -1 to 1) (default -1)
计算ssim并打印,从-1到1,默认1,ssim是一种视频质量参考模型,用于衡量目标视频与原视频之间的差距。最大值为1,越大质量越好。

  -intra-refresh     <int>        E..V.... Use Periodic Intra Refresh instead of IDR frames. (from -1 to 1) (default -1)
默认:-1-off
说明:让x264为每keyint数量的帧使用宏块内部编码取代IDR帧。块以水平移动列的方式更新,也叫刷新波。对于低延迟的流,这样可以让帧的尺寸比使用标准的IDR帧更加保持恒定。而且这样可以增强视频流对丢包的容错能力。这个选项会降低压缩率,所以在确实需要的时候才选择它。
还有一些有意思的事情:1、第一帧依然是IDR帧。2、内部宏块只在P帧中存在,刷新波在一个或多个B帧后的P帧中广泛存在。3、主要的压缩率下降原因是在宏块中新(左边)的波并不能参考旧(右边)的波。
建议:使用默认值
  -bluray-compat     <int>        E..V.... Bluray compatibility workarounds. (from -1 to 1) (default -1)
兼容蓝光,默认-1,范围-1到1。

  -b-bias            <int>        E..V.... Influences how often B-frames are used (from INT_MIN to INT_MAX) (default INT_MIN)
默认:0
说明:调节使用B帧的力度。越大的值越偏向B帧,可以在-100和100之间选择。100或-100不能保证完全或是全是B帧(使用 –b-adapt 0)。
请只在你认为你能做出比x264更好的码率控制时才使用这个选项。慎用!
参见: –b-frames, –ipratio
  -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)
默认:-1-none
说明:允许B帧作为参照帧。如果关闭,那么只有I帧和P帧才能作为参照帧。可以作为参照帧的B帧的量化参数会介于P帧和普通B帧之间。只在–b-frames设置大于等于2时此选项才生效。如果是在为蓝光光盘编码,请使用none或者strict。
none —— 不允许B帧作为参照帧;
strict —— 一个图像组内只允许一个B帧参照帧,这是蓝光编码强制要求的标准;
normal —— 任意使用B帧参照帧;
参见:–bframes, –refs, -mixed-refs
  -mixed-refs        <int>        E..V.... One reference per partition, as opposed to one reference per macroblock (from -1 to 1) (default -1)
默认:-1-无
说明:Mixed refs(混合参照)会以8×8的切块为参照取代以整个宏块为参照。会增进多帧参照的帧的质量,会有一些时间耗用。
建议:保持默认
参见:–ref
  -8x8dct            <int>        E..V.... High profile 8x8 transform. (from -1to 1) (default -1)
默认:-1-无
说明:自适应的8×8 DCT会在I帧中开启更智能的自适应8×8的时域变换。(开启此选项会将H.264的等级提升为Profile)。
建议:保持默认
  -fast-pskip        <int>        E..V.... (from -1 to 1) (default -1)
默认:-1-无
说明:P帧的早期跳过决策。大量的时耗换回非常小的质量提升。
建议:保持默认
  -aud               <int>        E..V.... Use access unit delimiters. (from -1to 1) (default -1)
没试用过,以后加上
  -mbtree            <int>        E..V.... Use macroblock tree ratecontrol. (from -1 to 1) (default -1)
默认:-1-无
说明:基于宏块树的比特控制(macroblock tree ratecontrol)。基于宏块树的比特控制通过持续监控宏块在帧间的运动和相对权重来提升视频质量。它会单独生成一个很大的stats文件。
建议值:保持默认
参见:–rc-lookahead
  -deblock           <string>     E..V.... Loop filter parameters, in <alpha:beta> form.
调节H.264标准中的内置去块滤镜。这是个性价比很高的选则。 默认:0:0
详细的参数运作原理可以看这篇文章http://forum.doom9.org/showthread.php?t=109747(看楼主和akupenguin的回复)。
  -cplxblur          <float>      E..V.... Reduce fluctuations in QP (before curve compression) (from -1 to FLT_MAX) (default -1)
默认:-1
说明:把给定值作为高斯模糊的半径应用到量化曲线上。这意味着分配给每个帧的量化器会被它附近的帧的量化器平均掉,这样会达到限制量化器波动的效果。
参见:–qcomp, –qblur
  -partitions        <string>     E..V.... A comma-separated list of partitionsto consider. Possible values: p8x8, p4x4, b8x8, i8x8, i4x4, none, all
说明:H.264在压缩前会被切分为16×16大小的宏块。这些块可被进一步切分成更小的块,利用此参数,可以控制不同的帧类型(I、P、B)开启更细的帧切分(8×8、4×4),具体参数如下:
I帧:i8x8、i4x4;
P帧:p8x8(会同时开启p16x8和p8x16)、p4x4(会同时开启p8x4和p4x8);
B帧:b8x8(会同时开启b18x8和b8x16);
另外,也可以设置为’none’和’all’。一般而言,开启p4x4不会带来多少的质量提升,而且它极其耗时,是个性价比比较低的选项。
参见:-8x8dct

  -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....

默认:-1 none

说明:为’direct’类型的运动矢量设定预测模式。有两种可选的模式:spatial(空间预测)和temporal(时间预测)。可以设置为’none’关闭预测,也可以设置为’auto’让x264去选择它认为更好的模式,x264会在编码结束时告诉你它的选择。’auto’最好在2趟编码中使用,但也可以在1趟编码时使用。如果用于2趟编码,x264会在第1趟编吗时同时尝试2种预测模式,然后在第2趟编码时使用它认为较好的那一个。注意,如果第1趟编码时选择了’auto’,那么第2趟编码时也必须设置为’auto’。不然,第2趟编码会使用’temporal’。本选项从不会浪费比特,强烈推荐使用。
  -slice-max-size    <int>        E..V.... Limit the size of each slice in bytes (from -1 to INT_MAX) (default -1)
默认:-1
说明:设置每个分块包括NAL头的最大大小(bytes)。 (目前与 –interlaced选项不兼容)

  -stats             <string>     E..V.... Filename for 2 pass stats
为pass 2指定stat文件。

  -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....
默认:none -1
说明:设置HRD信息。用于蓝光流、电视广播和其他一些特殊场合。可用选项如下:
none —— 不设置HRD信息
vbr —— 设置HRD信息
cbr —— 设置HRD信息,而且把流限制在bitrate参数定义的码率内。需要bitrate码率控制方式。
建议:none,除非你需要设置HRD。
参见:–vbv-bufsize,和 –aud
  -avcintra-class    <int>        E..V.... AVC-Intra class 50/100/200 (from -1 to 200) (default -1)
未用过,以后补上
  -x264-params       <string>     E..V.... Override the x264 configuration using a :-separated list of key=value parameters

x264opts一样,具体参照x264opts。




参考资料:http://trac.ffmpeg.org/wiki/Encode/H.264

http://blog.yikuyiku.com/?p=2029



























### 配置 FFmpeg 使用 libx264 编码器 #### 安装依赖项 为了使 FFmpeg 能够使用 libx264 编码器,在 Windows 平台上需安装必要的依赖项。通常情况下,推荐通过预构建二进制文件的方式获取已集成 libx264FFmpeg 版本。 如果选择自行编译,则需要先下载并编译 libx264 库[^3]。此过程较为复杂,涉及到 MinGW 或 MSYS2 环境搭建以及 CMake 工具链配置等问题。 #### 获取带有 libx264 支持的 FFmpeg 构建版本 对于大多数开发者而言,最简便的方法是从第三方网站下载已经包含了 libx264 支持的静态链接 FFmpeg 可执行程序包。这些可执行文件可以直接运行于 Windows 操作系统之上而无需额外设置环境变量或路径。 可以从 BtbN/FFmpeg-Builds 提供的 GitHub Releases 页面找到适用于 Windows 的最新稳定版 FFmpeg 发布包,并确保选择了包含 `--enable-libx264` 参数选项在内的定制化版本[^1]。 #### 测试 FFmpeglibx264 的支持情况 完成上述操作之后,可以通过命令行工具验证当前使用的 FFmpeg 是否成功集成了 libx264 功能: ```bash ffmpeg -encoders | findstr /C:"libx264" ``` 当屏幕上显示出有关 "libx264" 的信息时,说明该版本确实具备所需的编码能力。 #### 实现简单的视频转码脚本 下面给出一段 Python 代码片段作为例子展示如何借助 subprocess 模块调用 FFmpeg 命令实现基本的 MP4 文件转换任务: ```python import os from pathlib import Path import subprocess def convert_video(input_file, output_dir=None): """Convert video to h264 using ffmpeg and libx264.""" input_path = Path(input_file).resolve() if not input_path.exists(): raise FileNotFoundError(f"{input_file} does not exist.") output_filename = f"{input_path.stem}_converted.mp4" if output_dir is None: output_path = input_path.parent.joinpath(output_filename) else: output_path = Path(output_dir).joinpath(output_filename) command = [ 'ffmpeg', '-i', str(input_path), '-c:v', 'libx264', '-preset', 'medium', '-crf', '23', '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', str(output_path) ] try: result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print(result.stdout.decode()) except subprocess.CalledProcessError as e: error_message = e.output.decode().strip() print(error_message) if __name__ == '__main__': test_input = r"C:\example\test.avi" convert_video(test_input) ``` 这段代码定义了一个名为 `convert_video()` 函数用于接收输入媒体文件路径参数并将之转化为采用 H.264 编码格式保存的新文件;同时允许指定目标存储位置。此外还展示了异常处理机制以便更好地捕捉潜在错误消息输出给用户查看。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dancing_night

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值