Advertisement
FanaticExplorer

ffmpeg_compress_error

Oct 21st, 2022 (edited)
760
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. import os, ffmpeg
  2. def compress_video(video_full_path, output_file_name, target_size):
  3.     # Reference: https://en.wikipedia.org/wiki/Bit_rate#Encoding_bit_rate
  4.     min_audio_bitrate = 32000
  5.     max_audio_bitrate = 256000
  6.  
  7.     probe = ffmpeg.probe(video_full_path)
  8.     # Video duration, in s.
  9.     duration = float(probe['format']['duration'])
  10.     # Audio bitrate, in bps.
  11.     audio_bitrate = float(next((s for s in probe['streams'] if s['codec_type'] == 'audio'), None)['bit_rate'])
  12.     # Target total bitrate, in bps.
  13.     target_total_bitrate = (target_size * 1024 * 8) / (1.073741824 * duration)
  14.  
  15.     # Target audio bitrate, in bps
  16.     if 10 * audio_bitrate > target_total_bitrate:
  17.         audio_bitrate = target_total_bitrate / 10
  18.         if audio_bitrate < min_audio_bitrate < target_total_bitrate:
  19.             audio_bitrate = min_audio_bitrate
  20.         elif audio_bitrate > max_audio_bitrate:
  21.             audio_bitrate = max_audio_bitrate
  22.     # Target video bitrate, in bps.
  23.     video_bitrate = target_total_bitrate - audio_bitrate
  24.  
  25.     i = ffmpeg.input(video_full_path)
  26.     ffmpeg.output(i, os.devnull,
  27.                   **{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 1, 'f': 'mp4'}
  28.                 ).overwrite_output().run()
  29.     ffmpeg.output(i, output_file_name,
  30.                   **{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 2, 'c:a': 'aac', 'b:a': audio_bitrate}
  31.                 ).overwrite_output().run()
  32.  
  33. # Compress input.mp4 to 50MB and save as output.mp4
  34. compress_video(r"D:\Python\VideosReplacer\test.mp4", r"D:\Python\VideosReplacer\test_out.mp4", 8 * 1000)
Tags: ffmpeg
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement