|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Source https://coderunner.io/shrink-videos-with-ffmpeg-and-preserve-metadata/ |
| 4 | + |
| 5 | +import traceback |
| 6 | +import os |
| 7 | +import subprocess |
| 8 | +import platform |
| 9 | +# shutil is consisting of high-level Python specific functions. shutil is on top of Python `os module`. |
| 10 | +# Thus, we can use the shutil module for high-level operations on files. |
| 11 | +# For example: Use it to copy files and metadata |
| 12 | +import shutil |
| 13 | +import argparse |
| 14 | + |
| 15 | +import pprint |
| 16 | +import json |
| 17 | + |
| 18 | + |
| 19 | +def preserve_file_dates(source_file, destination_file): |
| 20 | + """ |
| 21 | + Preserve original FILE dates. |
| 22 | + """ |
| 23 | + |
| 24 | + stat = os.stat(source_file) |
| 25 | + # Preserve access and modification date FILE attributes (EXIF are other dates) |
| 26 | + os.utime(destination_file, (stat.st_atime, stat.st_mtime)) |
| 27 | + |
| 28 | + |
| 29 | +def get_video_metadata(video_path): |
| 30 | + |
| 31 | + # run the ffprobe process, decode stdout into utf-8 & convert to JSON |
| 32 | + ffprobe_output = subprocess.check_output([FFPROBE_BIN, '-v', 'quiet', |
| 33 | + '-print_format', 'json', |
| 34 | + '-show_streams', |
| 35 | + video_path]).decode('utf-8') |
| 36 | + video_metadata = json.loads(ffprobe_output) |
| 37 | + |
| 38 | + # DEBUG - Prints all the metadata available: |
| 39 | + # pp = pprint.PrettyPrinter(indent=2) |
| 40 | + # pp.pprint(video_metadata) |
| 41 | + |
| 42 | + video_stream = next( |
| 43 | + (stream for stream in video_metadata['streams'] if stream['codec_type'] == 'video'), None) |
| 44 | + audio_stream = next( |
| 45 | + (stream for stream in video_metadata['streams'] if stream['codec_type'] == 'video'), None) |
| 46 | + |
| 47 | + return {'video': video_stream, |
| 48 | + 'audio': audio_stream} |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == '__main__': |
| 52 | + """ |
| 53 | + Main operation of this script: |
| 54 | + 1. NON-H.264 videos are copied to the other_codecs folder without being modified |
| 55 | + 2. H.264 videos: |
| 56 | + 2.1 Reduce video quality |
| 57 | + 2.1.1 Use a fixed quality that the human eye can not detect |
| 58 | + 2.2 Preserve FILE metadata (dates...) |
| 59 | + 3. Invalid video files are copied to failures folder |
| 60 | + """ |
| 61 | + |
| 62 | + # INPUT arguments |
| 63 | + ### |
| 64 | + parser = argparse.ArgumentParser(description='Compress Video files size') |
| 65 | + # Source folder is mandatory |
| 66 | + parser.add_argument('source_folder', |
| 67 | + help='videos source folder') |
| 68 | + parser.add_argument('--destination_folder', |
| 69 | + help='videos destination folder. Default is `source_folder/results`') |
| 70 | + parser.add_argument('--failures_folder', |
| 71 | + help='videos destination folder. Default is `destination_folder/failures`') |
| 72 | + parser.add_argument('--crf', |
| 73 | + type=int, |
| 74 | + choices=range(0, 51), |
| 75 | + default=23, |
| 76 | + help='video crf between 1-51`. Default is 23') |
| 77 | + |
| 78 | + args = parser.parse_args() |
| 79 | + |
| 80 | + source_folder = args.source_folder |
| 81 | + destination_folder = args.destination_folder or f'{source_folder}/results' |
| 82 | + failures_folder = args.failures_folder or f'{destination_folder}/failures' |
| 83 | + other_codecs_folder = f'{destination_folder}/other_codecs' |
| 84 | + # Because ffmpeg needs a str for CRF |
| 85 | + crf = str(args.crf) |
| 86 | + # |
| 87 | + ### |
| 88 | + |
| 89 | + # Check that it is an allowed platform |
| 90 | + assert (platform.system().upper() in ['LINUX', 'WINDOWS']), 'OS not allowed' |
| 91 | + |
| 92 | + if platform.system().upper() == 'LINUX': |
| 93 | + FFMPEG_BIN = 'ffmpeg' |
| 94 | + FFPROBE_BIN = 'ffprobe' |
| 95 | + elif platform.system().upper() == 'WINDOWS': |
| 96 | + FFMPEG_BIN = 'ffmpeg.exe' |
| 97 | + FFPROBE_BIN = 'ffprobe.exe' |
| 98 | + |
| 99 | + # Destination folder. Create if does not exist |
| 100 | + if not os.path.exists(destination_folder): |
| 101 | + os.makedirs(destination_folder) |
| 102 | + |
| 103 | + # Process videos |
| 104 | + with os.scandir(source_folder) as entries: |
| 105 | + for entry in entries: |
| 106 | + if entry.is_file(): |
| 107 | + try: |
| 108 | + |
| 109 | + print(entry.name) |
| 110 | + |
| 111 | + video_source_path = f'{source_folder}/{entry.name}' |
| 112 | + video_destination_path = f'{destination_folder}/{entry.name}' |
| 113 | + |
| 114 | + video_metadata = get_video_metadata(video_source_path) |
| 115 | + |
| 116 | + # Only process videos with this codec (at this moment) |
| 117 | + if video_metadata['video']['codec_name'] == 'h264': |
| 118 | + print(f"Video format detected: {video_metadata['video']['codec_name']}") |
| 119 | + |
| 120 | + # "copy_unknown" -> "", //if there are streams ffmpeg doesn't know about, still copy them (e.g some GoPro data stuff) |
| 121 | + # "map_metadata" -> "0", //copy over the global metadata from the first (only) input |
| 122 | + # "map" -> "0", //copy *all* streams found in the file, not just the best audio and video as is the default (e.g. including data) |
| 123 | + # "codec" -> "copy", //for all streams, default to just copying as it with no transcoding |
| 124 | + # "preset" -> "medium" //fmpeg speed preset to use |
| 125 | + # |
| 126 | + # "codec:v" -> "libx264", //specifically for the video stream, reencode to x264 |
| 127 | + # "pix_fmt" -> "yuv420p", //default pix_fmt |
| 128 | + # "crf" -> "23" //default constant rate factor for quality. 0-52 where 18 is near visually lossless |
| 129 | + # |
| 130 | + # "codec:a" -> "libfdk_aac", //specifically for the audio stream, reencode to aac |
| 131 | + # "vbr" -> "4" //variable bit rate quality setting |
| 132 | + |
| 133 | + # Use the same pix_fmt than the source video |
| 134 | + pix_fmt = video_metadata['video']['pix_fmt'] |
| 135 | + |
| 136 | + subprocess.call([FFMPEG_BIN, '-i', video_source_path, |
| 137 | + '-copy_unknown', |
| 138 | + '-map_metadata', '0', |
| 139 | + '-map', '0', |
| 140 | + '-codec', 'copy', |
| 141 | + '-codec:v', 'libx264', |
| 142 | + '-pix_fmt', pix_fmt, |
| 143 | + '-preset', 'slow', |
| 144 | + '-crf', crf, video_destination_path]) |
| 145 | + |
| 146 | + # Preserve file dates that are not in the video metadata. Example: modification_time |
| 147 | + preserve_file_dates(source_file=video_source_path, |
| 148 | + destination_file=video_destination_path) |
| 149 | + else: |
| 150 | + print(f"Non supported video format detected: {video_metadata['video']['codec_name']}") |
| 151 | + |
| 152 | + # Create folder if it does not exist |
| 153 | + if not os.path.exists(other_codecs_folder): |
| 154 | + os.makedirs(other_codecs_folder) |
| 155 | + |
| 156 | + video_other_codecs_path = f'{other_codecs_folder}/{entry.name}' |
| 157 | + # Copy files with other video formats |
| 158 | + shutil.copy2(video_source_path, video_other_codecs_path) |
| 159 | + except Exception as exception: |
| 160 | + # Create failures folder if it does not exist |
| 161 | + if not os.path.exists(failures_folder): |
| 162 | + os.makedirs(failures_folder) |
| 163 | + |
| 164 | + video_failure_path = f'{failures_folder}/{entry.name}' |
| 165 | + # Copy files that have raised an exception to the failure folder |
| 166 | + shutil.copy2(video_source_path, video_failure_path) |
| 167 | + |
| 168 | + # Show exception stack trace |
| 169 | + traceback.print_exc() |
0 commit comments