-
Notifications
You must be signed in to change notification settings - Fork 0
/
hevc-convert.py
executable file
·278 lines (222 loc) · 6.99 KB
/
hevc-convert.py
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
#!/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()
"""
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
TODO:
Right now only the first audio and subtitle stream are copied across
from the input stream. That's usually what I want, and doing anything
else involves breaking out the 'map' option. Doing so might be taking
my little automatation script too far.
https://ffmpeg.org/ffmpeg.html#Advanced-options
Using `-map 0` specifies all streams, while `-map 0:s:1` would copy
only the second subtitle stream. To get all subtitle streams you
would use `-map 0:s:?`.
All of the map options need to come before the other input 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
builder.output_options += ['-preset', 'slow']
if options.better:
builder.output_options += ['-crf', '26']
else:
builder.output_options += ['-crf', '28']
# Video filters
if options.scale_720:
builder.output_options += [
'-vf', 'scale=w=-2:h=720:force_original_aspect_ratio=decrease',
]
if options.scale_1080:
builder.output_options += [
'-vf', 'scale=w=-2:h=1080:force_original_aspect_ratio=decrease',
]
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(video: Path, temp_folder: Path, options: argparse.Namespace) -> None:
"""
Convert video in-place.
Args:
video:
Path to input file.
temp_folder:
Folder to save partially encoded file into.
options:
Command-line options
Returns:
None
"""
# Recompress into new file
output_video = temp_folder / video.name
builder = FFmpegArgumentBuilder(video, output_video)
args = build_ffmpeg_args(video, output_video, options)
print()
print("="*80)
print(video.name)
print("="*80)
print(" ".join(args))
print()
subprocess.run(args, check=True)
# Replace original file
shutil.copyfile(output_video, video)
# Remove new file
output_video.unlink()
def secure_copy(old: Path, new: Path, exist_ok: bool = False) -> None:
"""
Copy file into new location avoiding partial copy errors.
Even if interupted, file should not be left in a partially copied state.
It is first copied to the destination folder using a temporary name,
then renamed to the final name only when copy is completed.
Args:
old:
Current
new:
Location to copy file to.
exist_ok:
Will silently overwrite any existing file if true.
Returns:
None
"""
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:
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",
)
# Files
parser.add_argument(
dest='videos',
metavar='VIDEO',
nargs='+',
help="One or more video files to recompress using x265",
)
# Quality
parser.add_argument(
'-b',
'--better',
action='store_true',
help='improve video quality by changing x265 CRF value from 28 to 26',
)
# Audio
parser.add_argument(
'--stereo',
action='store_true',
help='Force stereo audio, downmixing channels if necessary',
)
# Resize
resize_parser = parser.add_mutually_exclusive_group()
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",
)
# Deinterlace
parser.add_argument(
'--deinterlace',
action='store_true',
help="Deinterlace video using the 'bwdif' filter",
)
# Animation
parser.add_argument(
'--animation',
action='store_true',
help='Hint to encoder that input is animation',
)
options = parser.parse_args(args)
return options
if __name__ == '__main__':
options = parse_arguments(sys.argv[1:])
status = main(options)
sys.exit(status)