ffmpeg 视频处理


2022-02-13 0

跟有意思的人一起做自己喜欢的事,顺道赚点钱,没有比这个更惬意的日子了。

前段时间给客户做 Lotus 技术培训的时候,需要对录制的视频进行一些简单处理。如添加水印,裁剪,拼接视频等。试了一下网友推荐的爱剪辑等傻瓜视频处理软件,结果发现我还是觉着用起来太麻烦, 而且还有各种商业水印,果断放弃了。偶然想起年轻的时候曾经用 ffmpeg 这个工具下载过一些教学视频,当时看 API 的时候貌似发现它还有很强大的视频处理功能,于是再去看了一下文档, 好家伙,视频剪辑,水印,滤镜,视频压缩,转码应有尽有。今天分享几个我这次用到的命令给大家。

首选你需要安装 ffmpeg 工具:

sudo apt-get install ffmpeg

# 1. 剪切视频

ffmpeg -ss 00:00:30 -t 00:30:40 -i input.mp4  -vcodec copy -acodec copy cut.mp4
  • -ss 指定从什么时间开始,00:00:30 表示从 30 秒后开始
  • -t 指定需要截取多长时间,00:30:40 表示截取长度为 30min40s
  • -i 指定输入文件

这里需要注意一下 通常输入的参数在 -i 参数之前,而输出的参数在 -i 参数之后,这是官方推荐的用法。

-ss position (input/output) When used as an input option (before -i), seeks in this input file to position.

如果你想要指定截取从 xx 开始到 xx 结束的中间的视频,那么你可以使用 -to 参数:

ffmpeg -ss 00:00:30 -i input.mp4 -to 00:31:10  -vcodec copy -acodec copy cut.mp4

注意如果你的 -ss 指定的位置不是关键帧,此时 ffmpeg 会在你输入的时间点附近圆整到最接近的关键帧处,然后做接下来的事情。

-ss position (input/output) Note that in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

要解决这个问题,我们可以将输入的视频先转换成所有的帧都为关键帧的视频,其实就是将所有的帧的编码方式转为帧内编码。使用下面的命令就可以解决:

ffmpeg -i input.mp4 -strict -2  -qscale 0 -intra output.mp4
  • -strict
  • -qscale 表示保持同样的视频质量
  • -intra 帧内编码

处理完之后,在使用上面的命令对视频进行裁剪。

# 2. 合并视频

假设你有 2 个待合并的视频,一个 vedio1.mp4, vedio2.mp4, 首先你需要创建一个视频列表文件,假设为 vedios.list, 文件内容如下:

file ./vedio1.mp4
file ./vedio2.mp4

然后执行下面命令对视频进行合并:

ffmpeg -f concat -i vedies.list -c copy concat.mp4

# 3. 视频水印

  1. 给视频添加图片水印

    ffmpeg -hide_banner -i input.mp4 -i logo.png -filter_complex "overlay=x=50:y=5" output.mp4 -y
    

    参数解析:

    • -filter_complex: 复杂滤镜参数,不同的参数之间用 ',' 分隔
    • logo.png: 水印文件
    • overlay:水印参数,这里指定水印在 X 轴和 Y 轴的位置,它可以使用一些内置变量计算得到结果。
      • overlay_w 水印的宽度
      • overlay_h 水印的高度
      • main_w 视频的宽度
      • main_h 视频的高度
  2. 给视频添加文字水印

    ffmpeg -i input.mp4 -vf "drawtext=fontfile=YaHei.ttf: text='原语云':x=10:y=10:fontsize=24:fontcolor=white:shadowy=2" output.mp4
    

    参数解析:

    • -vf: 滤镜相关,视频裁剪,水印等等操作都需要它完成
    • fontfile: 字体类型
    • text: 要添加的文字内容
    • fontsize: 字体大小
    • fontcolor: 字体颜色

    上述命令在视频左上角添加一条白色字体的文字水印。

最后,贴上一个年轻时候用来下载 m3u8 视频的命令,有需要的自取 O(∩_∩)O~

ffmpeg -i "https://xxxx.com/file.m3u8" -bsf:a aac_adtstoasc -vcodec copy -c copy -crf 50 file.mp4

# 参考链接