Golang 调整视频fps和分辨率 | Golang工具

Posted 剑客阿良_ALiang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang 调整视频fps和分辨率 | Golang工具相关的知识,希望对你有一定的参考价值。

目录

前言

环境依赖

代码

总结


前言

本文提供将视频修改fps和分辨率的工具方法,一如既往的实用主义。

主要也是学习一下golang使用ffmpeg工具的方式。

环境依赖

ffmpeg环境安装,可以参考我的另一篇文章:windows ffmpeg安装部署_阿良的博客-CSDN博客

本文主要使用到的不是ffmpeg,而是ffprobe也在上面这篇文章中的zip包中。

​​

golang主要依赖库

github.com/u2takey/ffmpeg-go

代码

不废话,上代码。下面为功能实现的主要代码。

package main

import (
	"fmt"
	"github.com/gofrs/uuid"
	"github.com/google/logger"
	ffmpeg "github.com/u2takey/ffmpeg-go"
	"path/filepath"
	"strings"
)

func InFormat(target string, str_array []string) bool 
	for _, element := range str_array 
		if target == element 
			return true
		
	
	return false


//转化fps视频
func ChangeFps(inputVideoPath, outputDir string, fps int) string 
	_formatArr := []string"mp4", "flv"
	_, _file := filepath.Split(inputVideoPath)
	_tmps := strings.Split(_file, ".")
	_ext := _tmps[len(_tmps)-1]
	if !InFormat(_ext, _formatArr) 
		logger.Fatal("格式不支持")
	
	_name, err := uuid.NewV4()
	if err != nil 
		logger.Fatal(err)
	
	_resultVideoPath := filepath.Join(outputDir, fmt.Sprintf("%s.%s", _name.String(), _ext))
	err = ffmpeg.Input(inputVideoPath).
		Output(_resultVideoPath, ffmpeg.KwArgs"qscale": 0, "r": fps).
		OverWriteOutput().ErrorToStdOut().Run()
	if err != nil 
		logger.Fatal(err)
	
	return _resultVideoPath


//转化视频分辨率
func ChangeResolution(inputVideoPath, outputDir string, width, height int) string 
	_formatArr := []string"mp4", "flv"
	_, _file := filepath.Split(inputVideoPath)
	_tmps := strings.Split(_file, ".")
	_ext := _tmps[len(_tmps)-1]
	if !InFormat(_ext, _formatArr) 
		logger.Fatal("格式不支持")
	
	_name, err := uuid.NewV4()
	if err != nil 
		logger.Fatal(err)
	
	_resultVideoPath := filepath.Join(outputDir, fmt.Sprintf("%s.%s", _name.String(), _ext))
	err = ffmpeg.Input(inputVideoPath).
		Output(_resultVideoPath, ffmpeg.KwArgs"s": fmt.Sprintf("%d*%d", width, height)).
		OverWriteOutput().ErrorToStdOut().Run()
	if err != nil 
		logger.Fatal(err)
	
	return _resultVideoPath


func main() 
	_changeFpsVideo := ChangeFps("E:\\\\360MoveData\\\\Users\\\\xxx\\\\Desktop\\\\3333333.mp4", "E:\\\\360MoveData\\\\Users\\\\xxx\\\\Desktop", 25)
	_changeResolution := ChangeResolution(_changeFpsVideo, "E:\\\\360MoveData\\\\Users\\\\huyi\\\\Desktop", 960, 540)
	fmt.Println(_changeFpsVideo, _changeResolution)

日志工具代码如下,非必要。

package logutil

import (
	"github.com/google/logger"
	"os"
)

var pLogger *logger.Logger

// Init init logger
func Init(verbose, systemLog bool, logPath string) 
	file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
	if err != nil 
		logger.Fatalf("logger Init: open log file(%v) error(%v)", logPath, err)
	
	pLogger = logger.Init("FFmpegDemoLogger", verbose, systemLog, file)


// Close close logger
func Close() 
	pLogger.Close()

代码说明

1、ChangeFps方法参数分别为,输入视频地址、输出目录地址、需要修改的fps值。

2、ChangeResolution方法参数分别为,输入视频地址、输出目录地址、需要修改分辨率的宽度、需要修改分辨率的高度。

3、做了简单的视频格式校验,如需添加,可以自己看着来。

4、最终视频名使用uuid避免重复。

5、主函数中先运行修改fps的方法,后运行修改分辨率的方法。

验证一下

准备的视频信息。

执行结果

2023/01/17 15:31:03 compiled command: ffmpeg -i E:\\360MoveData\\Users\\huyi\\Desktop\\3333333.mp4 -qscale 0 -r 25 E:\\360MoveData\\Users\\huyi\\Desktop\\5383a622-cd79-481d-9b26-4eb2eb2a2883.mp
4 -y
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enabl
e-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --dis
able-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-lib
bluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenj
peg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --ena
ble-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'E:\\360MoveData\\Users\\huyi\\Desktop\\3333333.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    creation_time   : 2022-09-08T12:04:43.000000Z
    Hw              : 1
                    :
    bitRate         : 16000000
                    :
    com.apple.quicktime.artwork: "data":"edittime":22,"infoStickerId":"","musicId":"","os":"windows","product":"lv","stickerId":"","videoEffectId":"","videoId":"245ba6f1-f2ab-4d70-b
c77-c70ea30c171a","videoParams":"be":0,"ef":0,"ft":0,"ma":0,"me":0,"mu":0,"re":0,"sp":0,"st":0,"te":0,"t
    maxrate         : 16000000
                    :
    te_is_reencode  : 1
                    :
    encoder         : Lavf58.76.100
  Duration: 00:00:26.91, start: 0.000000, bitrate: 11898 kb/s
    Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, bt709), 1920x1080 [SAR 1:1 DAR 16:9], 11741 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
    Metadata:
      creation_time   : 2022-09-08T12:04:43.000000Z
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 156 kb/s (default)
    Metadata:
      creation_time   : 2022-09-08T12:04:43.000000Z
      handler_name    : SoundHandler
Please use -q:a or -q:v, -qscale is ambiguous
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
  Stream #0:1 -> #0:1 (aac (native) -> aac (native))
Press [q] to stop, [?] for help
[libx264 @ 00000203e960dbc0] using SAR=1/1
[libx264 @ 00000203e960dbc0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 00000203e960dbc0] profile High, level 4.0, 4:2:0, 8-bit
[libx264 @ 00000203e960dbc0] 264 - core 161 - H.264/MPEG-4 AVC codec - Copyleft 2003-2020 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 
me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=9 lookahead_threads=1 sliced
_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 s
cenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to 'E:\\360MoveData\\Users\\huyi\\Desktop\\5383a622-cd79-481d-9b26-4eb2eb2a2883.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    te_is_reencode  : 1
                    :
    Hw              : 1
                    :
    bitRate         : 16000000
                    :
    com.apple.quicktime.artwork: "data":"edittime":22,"infoStickerId":"","musicId":"","os":"windows","product":"lv","stickerId":"","videoEffectId":"","videoId":"245ba6f1-f2ab-4d70-b
c77-c70ea30c171a","videoParams":"be":0,"ef":0,"ft":0,"ma":0,"me":0,"mu":0,"re":0,"sp":0,"st":0,"te":0,"t
    maxrate         : 16000000
                    :
    encoder         : Lavf58.45.100
    Stream #0:0(und): Video: h264 (libx264) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], q=-1--1, 25 fps, 12800 tbn, 25 tbc (default)
    Metadata:
      creation_time   : 2022-09-08T12:04:43.000000Z
      handler_name    : VideoHandler
      encoder         : Lavc58.91.100 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s (default)
    Metadata:
      creation_time   : 2022-09-08T12:04:43.000000Z
      handler_name    : SoundHandler
      encoder         : Lavc58.91.100 aac
frame=  674 fps= 36 q=-1.0 Lsize=   10724kB time=00:00:26.91 bitrate=3264.3kbits/s dup=0 drop=133 speed=1.43x    
video:10276kB audio:424kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.218878%
[libx264 @ 00000203e960dbc0] frame I:3     Avg QP:21.20  size:107179
[libx264 @ 00000203e960dbc0] frame P:170   Avg QP:22.81  size: 37100
[libx264 @ 00000203e960dbc0] frame B:501   Avg QP:26.27  size:  7772
[libx264 @ 00000203e960dbc0] consecutive B-frames:  0.7%  0.3%  0.4% 98.5%
[libx264 @ 00000203e960dbc0] mb I  I16..4: 21.0% 60.1% 18.9%
[libx264 @ 00000203e960dbc0] mb P  I16..4:  6.2%  7.1%  0.5%  P16..4: 44.4% 15.3%  7.4%  0.0%  0.0%    skip:19.0%
[libx264 @ 00000203e960dbc0] mb B  I16..4:  0.5%  0.5%  0.0%  B16..8: 37.2%  2.4%  0.3%  direct: 1.3%  skip:57.8%  L0:49.4% L1:47.8% BI: 2.7%
[libx264 @ 00000203e960dbc0] 8x8 transform intra:51.7% inter:77.1%
[libx264 @ 00000203e960dbc0] coded y,uvDC,uvAC intra: 31.6% 56.7% 5.4% inter: 11.5% 14.1% 0.0%
[libx264 @ 00000203e960dbc0] i16 v,h,dc,p: 19% 37% 13% 31%
[libx264 @ 00000203e960dbc0] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 21% 26% 25%  3%  5%  5%  6%  4%  4%
[libx264 @ 00000203e960dbc0] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 23% 36% 12%  3%  6%  5%  7%  4%  4%
[libx264 @ 00000203e960dbc0] i8c dc,h,v,p: 52% 26% 18%  4%
[libx264 @ 00000203e960dbc0] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 00000203e960dbc0] ref P L0: 51.3% 11.2% 28.0%  9.5%
[libx264 @ 00000203e960dbc0] ref B L0: 81.7% 13.6%  4.6%
[libx264 @ 00000203e960dbc0] ref B L1: 94.8%  5.2%
[libx264 @ 00000203e960dbc0] kb/s:3122.27
[aac @ 00000203eaf15440] Qavg: 481.300
2023/01/17 15:31:23 compiled command: ffmpeg -i E:\\360MoveData\\Users\\huyi\\Desktop\\5383a622-cd79-481d-9b26-4eb2eb2a2883.mp4 -s 960*540 E:\\360MoveData\\Users\\huyi\\Desktop\\8c0aecd8-7b7a-4
042-a939-1fe9a6e86da7.mp4 -y
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enabl
e-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --dis
able-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-lib
bluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenj
peg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --ena
ble-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'E:\\360MoveData\\Users\\huyi\\Desktop\\5383a622-cd79-481d-9b26-4eb2eb2a2883.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100
  Duration: 00:00:26.96, start: 0.000000, bitrate: 3258 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 3122 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 129 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
  Stream #0:1 -> #0:1 (aac (native) -> aac (native))
Press [q] to stop, [?] for help
[libx264 @ 0000020e6c032740] using SAR=1/1
[libx264 @ 0000020e6c032740] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 0000020e6c032740] profile High, level 3.1, 4:2:0, 8-bit
[libx264 @ 0000020e6c032740] 264 - core 161 - H.264/MPEG-4 AVC codec - Copyleft 2003-2020 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 
me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=9 lookahead_threads=1 sliced
_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 s
cenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to 'E:\\360MoveData\\Users\\huyi\\Desktop\\8c0aecd8-7b7a-4042-a939-1fe9a6e86da7.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.45.100
    Stream #0:0(und): Video: h264 (libx264) (avc1 / 0x31637661), yuv420p, 960x540 [SAR 1:1 DAR 16:9], q=-1--1, 25 fps, 12800 tbn, 25 tbc (default)
    Metadata:
      handler_name    : VideoHandler
      encoder         : Lavc58.91.100 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
      encoder         : Lavc58.91.100 aac
frame=  674 fps=134 q=-1.0 Lsize=    2478kB time=00:00:26.91 bitrate= 754.3kbits/s speed=5.35x    
video:2031kB audio:424kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.953781%
[libx264 @ 0000020e6c032740] frame I:3     Avg QP:20.81  size: 52181
[libx264 @ 0000020e6c032740] frame P:171   Avg QP:22.41  size:  8227
[libx264 @ 0000020e6c032740] frame B:500   Avg QP:26.34  size:  1031
[libx264 @ 0000020e6c032740] consecutive B-frames:  0.4%  1.5%  1.3% 96.7%
[libx264 @ 0000020e6c032740] mb I  I16..4:  9.7% 48.5% 41.8%
[libx264 @ 0000020e6c032740] mb P  I16..4:  1.0%  3.6%  0.5%  P16..4: 37.1% 15.4% 11.4%  0.0%  0.0%    skip:31.1%
[libx264 @ 0000020e6c032740] mb B  I16..4:  0.0%  0.1%  0.0%  B16..8: 22.8%  1.8%  0.3%  direct: 0.4%  skip:74.6%  L0:40.4% L1:55.3% BI: 4.2%
[libx264 @ 0000020e6c032740] 8x8 transform intra:65.3% inter:72.7%
[libx264 @ 0000020e6c032740] coded y,uvDC,uvAC intra: 64.0% 73.6% 20.3% inter: 7.6% 8.9% 0.1%
[libx264 @ 0000020e6c032740] i16 v,h,dc,p: 15% 35%  7% 43%
[libx264 @ 0000020e6c032740] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 17% 24% 16%  5%  8%  8%  9%  6%  7%
[libx264 @ 0000020e6c032740] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 22% 35%  8%  4%  7%  6%  8%  4%  6%
[libx264 @ 0000020e6c032740] i8c dc,h,v,p: 54% 23% 19%  4%
[libx264 @ 0000020e6c032740] Weighted P-Frames: Y:0.0% UV:0.0%
[libx264 @ 0000020e6c032740] ref P L0: 60.9% 12.9% 20.3%  5.9%
[libx264 @ 0000020e6c032740] ref B L0: 85.5%  9.9%  4.6%
[libx264 @ 0000020e6c032740] ref B L1: 96.9%  3.1%
[libx264 @ 0000020e6c032740] kb/s:616.91
[aac @ 0000020e6c2d3ec0] Qavg: 478.873
E:\\360MoveData\\Users\\huyi\\Desktop\\5383a622-cd79-481d-9b26-4eb2eb2a2883.mp4 E:\\360MoveData\\Users\\huyi\\Desktop\\8c0aecd8-7b7a-4042-a939-1fe9a6e86da7.mp4

结果视频信息

 

 

总结

没啥好总结的,正好用到了就分享下,大家用的时候看着改。

分享:

        敌人对我们的看法比我们自己的观点可能更接近事实。——《人性的弱点》

如果本文对你有帮助的话,点个赞吧,谢谢!

以上是关于Golang 调整视频fps和分辨率 | Golang工具的主要内容,如果未能解决你的问题,请参考以下文章

请帮忙计算,分辨率为640 x 480 ,帧数30fps, VGA 格式的视频,一个小时长度大概是多大呢?

在 OpenCV 上输入更高分辨率的视频文件时 fps 低

opencv获取fps为0

如何在低分辨率的 iPhone 6 上获得 240fps

是否可以使用 MPEG-DASH 流式传输多帧率视频?

视频基本概念