Skip to content

Instantly share code, notes, and snippets.

@vitalyisaev2
Last active September 7, 2020 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitalyisaev2/e6869586deab71294219601e6a174858 to your computer and use it in GitHub Desktop.
Save vitalyisaev2/e6869586deab71294219601e6a174858 to your computer and use it in GitHub Desktop.
Encode video files with ffmpeg NVIDIA hardware acceleration
#!/usr/bin/env python
from pathlib import Path, PurePath
import subprocess
import os
root = "."
def main():
src_files = list(Path('uncompressed').rglob('*.mp4'))
counter = 0
for src_file in src_files:
counter+=1
dst_file = PurePath(root, 'compressed', src_file.name)
# either try using GPU
try:
print("============ PROGRESS ===========: {:10.4f}".format(counter/len(src_files)))
cmd = f"ffmpeg -hwaccel_device 0 -hwaccel cuvid -c:v h264_cuvid -i {src_file} -c:v h264_nvenc -rc:v vbr_hq -cq:v 19 -b:v 2500k -maxrate:v 5000k -preset slow {dst_file}"
subprocess.check_call(cmd, shell=True)
# or fallback to CPU
except Exception as e:
print(e)
os.remove(dst_file)
cmd = f"ffmpeg -i {src_file} -c:v libx264 -crf 24 -preset slow {dst_file}"
subprocess.check_call(cmd, shell=True)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment