You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.5 KiB
41 lines
1.5 KiB
import os
|
|
import ffmpeg
|
|
|
|
|
|
def compress_video(video_full_path):
|
|
# Reference: https://en.wikipedia.org/wiki/Bit_rate#Encoding_bit_rate
|
|
min_audio_bitrate = 32000
|
|
max_audio_bitrate = 256000
|
|
|
|
output_file_name = video_full_path[:-4] + '_compressed.mp4'
|
|
|
|
probe = ffmpeg.probe(video_full_path)
|
|
# Video duration, in s.
|
|
duration = float(probe['format']['duration'])
|
|
# Video output size
|
|
target_size = os.path.getsize(video_full_path) / 5000
|
|
# Audio bitrate, in bps.
|
|
audio_bitrate = float(next((s for s in probe['streams'] if s['codec_type'] == 'audio'), None)['bit_rate'])
|
|
# Target total bitrate, in bps.
|
|
target_total_bitrate = (target_size * 1024 * 8) / (1.073741824 * duration)
|
|
|
|
# Target audio bitrate, in bps
|
|
if 10 * audio_bitrate > target_total_bitrate:
|
|
audio_bitrate = target_total_bitrate / 10
|
|
if audio_bitrate < min_audio_bitrate < target_total_bitrate:
|
|
audio_bitrate = min_audio_bitrate
|
|
elif audio_bitrate > max_audio_bitrate:
|
|
audio_bitrate = max_audio_bitrate
|
|
# Target video bitrate, in bps.
|
|
video_bitrate = target_total_bitrate - audio_bitrate
|
|
|
|
i = ffmpeg.input(video_full_path)
|
|
ffmpeg.output(i, os.devnull,
|
|
**{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 1, 'f': 'mp4'}
|
|
).overwrite_output().run()
|
|
ffmpeg.output(i, output_file_name,
|
|
**{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 2, 'c:a': 'aac', 'b:a': audio_bitrate}
|
|
).overwrite_output().run()
|
|
|
|
return output_file_name
|