Created
June 11, 2019 05:49
-
-
Save 5S/982eb7ffd0d7894782206b0d07e360a2 to your computer and use it in GitHub Desktop.
Discord の 8 MB 制限に収まるよう動画をエンコードするやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import cv2 | |
import glob | |
import math | |
import os | |
import subprocess | |
import sys | |
# 環境変数 | |
ffmpeg_dir = 'ffmpeg' | |
limit_size = 8 # MB | |
audio_bitrate = 128 # kbps | |
video_width = 854 # px (480p) | |
output_name = 'output' # .mp4 | |
# 引数を取得 | |
try: | |
args = sys.argv | |
input_file = args[1] | |
input_dir = os.path.dirname(input_file) | |
except IndexError: | |
input('エラー: 第1引数に処理したい動画のパスを与えてください。\nEnterキーで終了します...') | |
# 動画を読み込み、長さを計算 | |
cap = cv2.VideoCapture(input_file) | |
video_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT) | |
video_fps = cap.get(cv2.CAP_PROP_FPS) | |
video_len = math.ceil(video_frame / video_fps) | |
# ビットレートを計算 | |
# 1 (MB) = 1024 (KB) | |
# 1 (Byte) = 8 (bit) | |
# 1024 (KB) * 8 (bit) = 8192 (bits) | |
total_bitrate = limit_size * 8192 / video_len # kbps | |
video_bitrate = math.floor(total_bitrate - audio_bitrate) # kbps | |
# 実行 | |
cmd = f'{ffmpeg_dir} -y -i {input_file} -vf scale={video_width}:-1 -c:v libx264 -b:v {video_bitrate}k -pass 1 -c:a libmp3lame -b:a {audio_bitrate}k -f mp4 {input_dir}\\ffmpeg2pass && {ffmpeg_dir} -i {input_file} -vf scale={video_width}:-1 -c:v libx264 -b:v {video_bitrate}k -pass 2 -c:a libmp3lame -b:a {audio_bitrate}k {input_dir}\\{output_name}.mp4' | |
subprocess.call(cmd, shell=True) | |
# ゴミ掃除 | |
for f in glob.glob(f'{input_dir}\\ffmpeg2pass*'): | |
os.remove(f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment