-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhevc-convert.py
More file actions
executable file
·279 lines (225 loc) · 7.09 KB
/
hevc-convert.py
File metadata and controls
executable file
·279 lines (225 loc) · 7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python3
"""
HEVC Convert
Recompress video files in place to HEVC using FFMPEG and libx265.
TODO:
- Change FFMPEG arguments based on command line options.
- Fill implementation of secure_copy()
2025-08-27
Experimented with AV1 encoding, using the `libsvtav1` encoder. Underwhelming,
but more experimentation/comparison needed:
ffmpeg -i input.mp4 \
-ss 00:01:00 -to 00:02:00 \
-map 0:v:0 -map 0:a:0 -map 0:s? \
-c:v libsvtav1 -crf 35 -preset 4 \
-c:a libopus -c:s copy output.mkv
"""
import argparse
import logging
from pathlib import Path
from pprint import pprint as pp
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
logger = logging.getLogger(__name__)
class FFmpegArgumentBuilder:
"""
Build list of FFmpeg command-line arguments.
$ ffmpeg [global_options] \
{[input_file_options] -i input_url} \
{[output_file_options] output_url}
"""
global_options: list[str]
input_options: list[str]
output_options: list[str]
def __init__(self, input_path: Path, output_path: Path):
self.input_options = []
self.input_path = input_path
self.output_options = []
self.output_path = output_path
self.global_options = ['-hide_banner', '-nostdin']
def args(self) -> list[str]:
args = ['ffmpeg'] + self.global_options
args += self.input_options
args += ['-i', str(self.input_path)]
args += ['-map', '0:v:0'] # Keep first video stream
args += ['-map', '0:a:0'] # Keep first audio stream
args += ['-map', '0:s?'] # Keep all subtitle streams
args += self.output_options
args += [str(self.output_path)]
return args
def build_ffmpeg_args(
input_path: Path,
output_path: Path,
options: argparse.Namespace,
) -> list[str]:
"""
Prepare list of command-line arguments ready for `subprocess.run()`
Opinionated choice of arguments to get decent x265/HEVC videos.
Args:
input_path:
Path to input file.
output_path:
Folder to save partially encoded file into.
options:
Command-line options
Returns:
List of arguments.
"""
# x265/HEVC
builder = FFmpegArgumentBuilder(input_path, output_path)
builder.output_options += [
'-c:v', 'libx265',
'-x265-params', 'log-level=warning',
]
# Quality
if options.better:
builder.output_options += ['-preset', 'slower', '-crf', '26']
else:
builder.output_options += ['-preset', 'slow', '-crf', '28']
# Video filters
if options.scale_480:
builder.output_options += [
'-vf', "scale=w=-2:h='min(480,ih)'",
]
if options.scale_720:
builder.output_options += [
'-vf', "scale=w=-2:h='min(720,ih)'",
]
if options.scale_1080:
builder.output_options += [
'-vf', "scale=w=-2:h='min(1080,ih)'",
]
if options.deinterlace:
builder.output_options += [
'-vf', 'bwdif=mode=send_field:parity=auto:deint=all',
]
# Audio
if options.stereo:
builder.output_options += [
'-ac', '2',
'-c:a', 'aac',
'-b:a', '128k',
]
else:
builder.output_options += ['-c:a', 'copy']
# Subtitles
builder.output_options += [
'-c:s', 'copy',
]
# Tune
if options.animation:
builder.output_options += ['-tune', 'animation']
return builder.args()
def hevc_convert(original: Path, temp_folder: Path, options: argparse.Namespace) -> None:
"""
Convert video in-place.
Args:
original:
Path to input file.
temp_folder:
Folder to save partially encoded file into.
options:
Command-line options
Returns:
None
"""
logger.info("START compressing HEVC MP4 video: %s", original.name)
# Recompress output original into temporary folder
output_name = original.with_suffix('.mp4').name
output_video = temp_folder / output_name
builder = FFmpegArgumentBuilder(original, output_video)
args = build_ffmpeg_args(original, output_video, options)
print()
print("="*80)
print(original.name)
print("="*80)
print(" ".join(args))
print()
logger.info("Execute FFMPEG, output to: %s", output_video)
if not options.dry_run:
subprocess.run(args, check=True)
# Copy new file into same folder (and maybe over top of) original file
shutil.copyfile(output_video, original.parent / output_name)
# Remove temp file
output_video.unlink()
def main(options: argparse.Namespace) -> int:
videos = [Path(name) for name in options.videos]
with TemporaryDirectory(prefix='hevc-convert-') as temp_folder:
for video in videos:
if video.is_dir():
logger.info("Skipping folder: %s", video)
continue
hevc_convert(video, Path(temp_folder), options)
return 0
def parse_arguments(args: list[str]) -> argparse.Namespace:
"""
Create and run `argparse`-based command parser.
"""
parser = argparse.ArgumentParser(
description="Recompress video files in place",
)
# --animation
parser.add_argument(
'--animation', action='store_true',
help='Hint to encoder that input is animation',
)
# --better, -b
parser.add_argument(
'-b', '--better', action='store_true',
help='improve video quality by changing x265 CRF value from 28 to 26',
)
# --deinterlace
parser.add_argument(
'--deinterlace',
action='store_true',
help="Deinterlace using the 'bwdif' filter",
)
# --dry-run, -n
parser.add_argument(
'-n', '--dry-run', action='store_true',
help='only show which files would be transfered',
)
# --stereo, -s
parser.add_argument(
'-s', '--stereo', action='store_true',
help='Force stereo audio, downmixing channels if necessary',
)
# --480, --720, --1080
resize_parser = parser.add_mutually_exclusive_group()
resize_parser.add_argument(
'--480',
action='store_true',
dest='scale_480',
help="downsize to 480p, keeping aspect ratio",
)
resize_parser.add_argument(
'--720',
action='store_true',
dest='scale_720',
help="downsize to 720p, keeping aspect ratio",
)
resize_parser.add_argument(
'--1080',
action='store_true',
dest='scale_1080',
help="downsize to 1080p, keeping aspect ratio",
)
# File arguments
parser.add_argument(
dest='videos',
metavar='VIDEO',
nargs='+',
help="One or more video files to recompress using x265",
)
options = parser.parse_args(args)
return options
if __name__ == '__main__':
options = parse_arguments(sys.argv[1:])
logging.basicConfig(
format='%(message)s',
level=logging.INFO,
)
status = main(options)
sys.exit(status)