-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtranscode2H265.py
More file actions
executable file
·395 lines (308 loc) · 13.8 KB
/
transcode2H265.py
File metadata and controls
executable file
·395 lines (308 loc) · 13.8 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
## A wrapper script to transcode video files to H265 in MKV format, using
## ffmpeg. Audio may be transcoded to aac or copied (passthrough).
##
## Amaury Pupo Merino
##
## This script is released under GPL v3.
##
## Importing modules
import sys
import os
import time
import random
import subprocess
import string
import argparse
## Classes
class Video:
"""Contains actual and proposed video information, and can transform itself.
"""
def __init__(self,filename):
self.__in_filename=filename
self.__in_ok=False
self.__check_input_file()
def __check_input_file(self):
"""Check if input is a proper video file
"""
self.__in_ok = False
try:
result = subprocess.run(
[
"ffprobe",
"-analyzeduration",
"100M",
"-probesize",
"100M",
"-v",
"error",
"-select_streams",
"v",
"-show_entries",
"stream=codec_type",
"-of",
"default=noprint_wrappers=1:nokey=1",
self.__in_filename
],
capture_output=True,
text=True,
check=True # Raise a CalledProcessError if the command returns a non-zero exit code
)
if "video" in result.stdout:
self.__in_ok = True
except subprocess.CalledProcessError as e:
print(f"Command failed with error: {e}")
print(f"Standard Error: {e.stderr}")
except FileNotFoundError:
print("Error: The command was not found. Please check the command name and path.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
def __get_max_audio_channels(self):
"""Get the maximum number of channels in any of the audio streams.
"""
n_channels = 2
if os.path.isfile(self.__in_filename):
try:
result = subprocess.run(
[
"ffprobe",
"-analyzeduration",
"100M",
"-probesize",
"100M",
"-v",
"error",
"-select_streams",
"a",
"-show_entries",
"stream=channels",
"-of",
"default=noprint_wrappers=1:nokey=1",
self.__in_filename
],
capture_output=True,
text=True,
check=True # Raise a CalledProcessError if the command returns a non-zero exit code
)
for line in result.stdout.split('\n'):
line=line.strip()
try:
stream_n_channels = int(line)
if stream_n_channels > n_channels:
n_channels = stream_n_channels
except:
pass
except subprocess.CalledProcessError as e:
print(f"Command failed with error: {e}")
print(f"Standard Error: {e.stderr}")
except FileNotFoundError:
print("Error: The command was not found. Please check the command name and path.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
return n_channels
def is_ok(self):
"""Returns true is video file exist and it is actually a video.
"""
return self.__in_ok
def set_transcoding_options(self,preset,crf,audio_codec, aac_audio_bitrate_per_channel,postfix,threads):
if self.__in_ok:
self.__preset = preset
self.__CRF = str(crf)
self.__audio_codec = audio_codec
self.__max_audio_channels = self.__get_max_audio_channels()
self.__aac_audio_bitrate = str(self.__max_audio_channels * aac_audio_bitrate_per_channel) + 'k'
self.__ffmpeg_output_ext='.mkv'
self.__output_postfix = postfix
self.__ffmpeg_output=os.path.splitext(self.__in_filename)[0] + self.__output_postfix + self.__ffmpeg_output_ext
self.__threads = threads
self.__transcoding_options_set = True
def transcode(self):
if self.__transcoding_options_set:
#cmd_line='ffmpeg -i \"{}\" -vcodec libx265 -crf {:d}'.format(self.__in_filename, self.__CRF)
cmd_line_list = [
"ffmpeg",
"-analyzeduration",
"100M",
"-probesize",
"100M",
"-i",
self.__in_filename,
"-c:v",
"libx265",
"-preset",
self.__preset,
"-crf",
self.__CRF,
"-pix_fmt",
"yuv420p10le"
]
if self.__audio_codec == "copy":
cmd_line_list += ["-c:a", "copy"]
elif self.__audio_codec == "aac":
cmd_line_list += ["-c:a", "aac", "-b:a", "{}".format(self.__aac_audio_bitrate)]
cmd_line_list += ["-c:s", "copy", "-map", "0"]
if self.__threads > 0:
cmd_line_list += [
"-threads",
str(self.__threads)
]
cmd_line_list += ["-y", self.__ffmpeg_output]
print(*cmd_line_list)
try:
with subprocess.Popen(cmd_line_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1) as process:
for line in process.stdout:
if 'frame=' in line:
print(line.strip(), end='\r')
else:
print(line.strip())
process.wait()
return True
except subprocess.CalledProcessError as e:
print(f"Command failed with error: {e}")
print(f"Standard Error: {e.stderr}")
except FileNotFoundError:
print("Error: The command was not found. Please check the command name and path.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
return False
class Reporter:
"""Holds information about the transcoding process and elaborate a final report.
"""
def __init__(self):
self.__files_ok_counter=0
self.__files_with_error=[]
self.__ignored_files=[]
def count_file_ok(self):
self.__files_ok_counter+=1
def add_file_with_errors(self,filename):
self.__files_with_error.append(filename)
def add_ignored_file(self,filename):
self.__ignored_files.append(filename)
def print_final_report(self):
"""Print report after all transcoding is made.
"""
print('\n==== Transcoding finished ====')
if self.__ignored_files:
print ('== There following files were ignored: ==')
for filename in self.__ignored_files:
print('\t* {}'.format(filename))
print(75*'=')
print('\n')
if self.__files_with_error:
print('== There were errors transcoding the files: ==')
for filename in self.__files_with_error:
print('\t* {}'.format(filename))
print(75*'=')
print('\n')
print('==== Final report ====')
output = '\t {}'.format(self.__files_ok_counter)
if self.__files_ok_counter == 1:
output += ' file'
else:
output += ' files'
output += ' transcoded OK.\n'
output += '\t {:d}'.format(len(self.__files_with_error))
if len(self.__files_with_error) == 1:
output += ' file'
else:
output += ' files'
output+=' with errors.\n'
sys.stdout.write(output)
print(75*'=')
print('\n')
def check_the_required_programs():
if os.system("ffmpeg -h > /dev/null 2>&1"):
sys.stderr.write("ERROR: ffmpeg is not installed in your system.\nThis script can not work properly without it.\n\n")
exit()
def print_duration(seconds):
output=''
seconds_per_minute=60
seconds_per_hour=60*seconds_per_minute
seconds_per_day=24*seconds_per_hour
days=int(seconds/seconds_per_day)
hours=int((seconds % seconds_per_day)/seconds_per_hour)
minutes=int((seconds % seconds_per_hour)/seconds_per_minute)
seconds=seconds%60
if days:
#output+=('%d' % (days))
output+=('{:d}'.format(days))
if days==1:
output+=' day '
else:
output+=' days '
if hours:
#output+=('%2d' % (hours))
output+=('{:2d}'.format(hours))
if hours==1:
output+=' hour '
else:
output+=' hours '
if minutes:
#output+=('%2d' % (minutes))
output+=('{:2d}'.format(minutes))
if minutes==1:
output+=' minute '
else:
output+=' minutes '
if seconds:
#output+=('%4.2f' % (seconds))
output+='{:4.2f}'.format(seconds)
if seconds==1:
output+=' second '
else:
output+=' seconds '
return output.strip()
def dstring2dint(duration_string):
hours,minutes,seconds=duration_string.split(':')
hours,minutes,seconds=int(hours),int(minutes),int(round(float(seconds)))
duration_seconds=3600*hours+60*minutes+seconds
return duration_seconds
def random_string(length = 10):
rand_string = ''
for letter in random.sample(string.ascii_lowercase + string.ascii_uppercase + string.digits, length):
rand_string += letter
return rand_string
def run_script():
"""Function to be called to actually run the script.
"""
check_the_required_programs()
initial_time=time.time()
parser=argparse.ArgumentParser(description="A wrapper script to transcode video files to H265 in MKV format, using ffmpeg. Audio may be transcoded to aac or copied (passthrough). All internal subtitles are copied. Metadata is preserved.")
parser.add_argument('video', nargs='+', help='Input video file(s).')
parser.add_argument('-p', '--preset', default='slow', choices=["ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"], help='X265 preset [default: %(default)s].')
parser.add_argument('-q', '--crf', type=int, default=26, help='CRF value [default: %(default)s]. Determines the output video quality. Smaller values gives better qualities and bigger file sizes, bigger values result in less quality and smaller file sizes. Default value results in a nice quality/size ratio. CRF values should be in the range of 0 to 51.')
parser.add_argument('-a', '--audio-codec', choices=["aac", "copy"], default='aac', help='Output audio codec. You may transcode all input audio streams into aac (preserving their channels), or copy the input streams as they are [default: %(default)s].')
parser.add_argument('-b', '--aac_audio_bitrate_per_channel', type=int, default=96, help='AAC audio bitrate per channel (in kb/s) [default: %(default)s]. Ignored if audio codec not aac. Maximum audio bitrate is determined by the audio stream with more channels.')
parser.add_argument('-x', '--filename-postfix', default='_h265', help='Postfix to be added to newly created H.265 video files [default: %(default)s].')
parser.add_argument('-t', '--threads', type=int, default=0, help='Indicates the number of processor cores the script will use. 0 indicates to use as many as possible, or current libx265 library defaults [default: %(default)s]. ffmpeg may or may not respect this.')
parser.add_argument('-v', '--version', action='version', version='4.0.1', help="Show program's version number and exit.")
args=parser.parse_args()
if args.crf < 0 or args.crf > 51:
parser.error('CRF values should be in the range of 1 to 50.')
if args.threads < 0:
parser.error('The number of threads must be 0 or positive.')
reporter=Reporter()
file_counter=0
for filename in args.video:
file_counter+=1
print('\n==== Transcoding file {:d}/{:d} ===='.format(file_counter,len(args.video)))
video=Video(filename)
if not video.is_ok():
sys.stderr.write("File {} is not a proper video file.\n".format(filename))
reporter.add_ignored_file(filename)
continue
video.set_transcoding_options(args.preset, str(args.crf), args.audio_codec, args.aac_audio_bitrate_per_channel, args.filename_postfix, args.threads)
if video.transcode():
reporter.count_file_ok()
else:
reporter.add_file_with_errors(filename)
print(75*'=')
reporter.print_final_report()
final_time=time.time()
print('Work finished in {}.'.format(print_duration(final_time-initial_time)))
print('Exiting OK.')
## Running the script
if __name__ == "__main__":
run_script()