-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode265_cuda
More file actions
1000 lines (845 loc) · 34.6 KB
/
Copy pathencode265_cuda
File metadata and controls
1000 lines (845 loc) · 34.6 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
encode265: Batch re-encode video files to H.265/HEVC with hardware acceleration using both NVIDIA and Intel GPUs.
This script scans the current directory for video files (MKV, MP4, AVI, MOV) and allows you to select which files to encode.
It supports hardware acceleration on NVIDIA GPUs via NVENC and on Intel iGPUs via VAAPI, enabling parallel encodes when both are available.
You can choose to scale video to 720p, convert audio to AAC 2.0, and select the desired encoding mode or bitrate.
Text-based subtitles are converted to SRT, while image-based subtitles (like PGS) are copied as-is.
Only the first audio track is kept, and external subtitles are renamed to match the new output file.
The script shows a live progress bar, ETA, and encoding speed for each file.
Features:
- Interactive selection of files, GPU, encoding mode, and options.
- Hardware-accelerated H.265/HEVC encoding using:
• NVENC (for NVIDIA GPUs such as the RTX 2000 E Ada)
• VAAPI (for Intel iGPUs)
- Optional scaling to 720p and audio conversion to AAC 2.0.
- Converts text subtitles to SRT, copies non-text subtitles.
- Removes attachments from MKV files.
- Keeps only the first audio track.
- Renames external subtitles to match output.
- Parallel encoding if both NVIDIA and Intel GPUs are available.
- Live progress display with speed and ETA.
- Optionally deletes original files after encoding.
- Handles Ctrl+C gracefully, terminating all running encodes.
- Encoding settings optimized for small file size and good quality-to-speed balance.
Usage:
python3 encode265
# Follow the prompts to select files and options.
Requirements:
- ffmpeg and ffprobe (compiled with NVENC and VAAPI support)
- NVIDIA GPU (e.g. RTX 2000 E Ada) and/or Intel iGPU
- Python 3.7+
- Linux (tested on Debian/Ubuntu)
This script is ideal for efficiently batch-converting your media library to H.265/HEVC with hardware acceleration,
taking advantage of both NVIDIA and Intel GPUs for maximum performance and minimal file size.
"""
import os
import sys
import re
import json
import shutil
import signal
import subprocess
import threading
import time
import queue
from pathlib import Path
# Supported video file extensions
VIDEO_EXTENSIONS = [
".mkv", ".mp4", ".avi", ".mov", ".m4v", ".flv", ".wmv", ".webm", ".ts"
]
def human_readable_size(num, suffix='B'):
"""Return human readable file size (e.g. 1.2G)."""
try:
num = float(num)
except Exception:
return "N/A"
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Y{suffix}"
# Global state trackers
stop_requested = False # Flag for graceful shutdown
processes = {} # Active ffmpeg Popen objects
encode_info = {} # Start times / progress info for ETA
def handle_sigint(signum, frame):
"""
Handle Ctrl+C gracefully: stop all ongoing ffmpeg processes,
print user feedback, and exit cleanly.
"""
global stop_requested
if stop_requested:
# Double Ctrl+C → force quit
print("\n⚠️ Second Ctrl+C detected — forcing shutdown.")
sys.exit(1)
stop_requested = True
print("\n🛑 Ctrl+C received. Attempting to terminate all encoding processes...")
for file, proc in list(processes.items()):
if proc.poll() is None: # still running
print(f"🔻 Terminating process for: {file}")
try:
proc.terminate()
except Exception as e:
print(f" ⚠️ Could not terminate {file}: {e}")
# Give ffmpeg a moment to exit cleanly
time.sleep(1)
print("✅ All encoding processes stopped.")
sys.exit(1)
# Register the handler
signal.signal(signal.SIGINT, handle_sigint)
def should_convert_audio(input_file, target_channels):
"""
Checks if the file is already AAC with the specific target channel count.
Returns True if conversion is needed, False if we can just copy.
"""
try:
result = subprocess.run([
"ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries",
"stream=codec_name,channels", "-of", "json", input_file
], capture_output=True, text=True)
data = json.loads(result.stdout)
if not data.get("streams"):
return True # No audio stream found, let ffmpeg handle/fail it logic later
stream = data["streams"][0]
codec = stream.get("codec_name", "").lower()
channels = stream.get("channels", 0)
# If it's already aac and matches target channels, no need to convert
return not (codec == "aac" and channels == target_channels)
except Exception as e:
print(f"⚠️ Could not determine audio stream info for {input_file}: {e}")
return True
def list_media_files(directory):
files = [f for f in sorted(os.listdir(directory)) if Path(f).suffix.lower() in VIDEO_EXTENSIONS]
for idx, file in enumerate(files):
try:
size = (Path(directory) / file).stat().st_size
size_str = human_readable_size(size)
except Exception:
size_str = "N/A"
print(f"{idx + 1}. {file} ({size_str})")
return files
def get_user_selection(files):
selection = input("Select files to encode by number (comma-separated), or press Enter for all: ").strip()
if not selection or selection.lower() == "all":
return files
indices = [int(i) - 1 for i in selection.split(",") if i.strip().isdigit() and 0 < int(i) <= len(files)]
return [files[i] for i in indices]
def yes_no(prompt, default="no"):
default = default.lower()
options = "[Y/n]" if default == "yes" else "[y/N]"
choice = input(f"{prompt} {options}: ").strip().lower()
if not choice:
return default == "yes"
if choice in ["y", "yes"]:
return True
if choice in ["n", "no"]:
return False
print("Invalid choice. Using default.")
return default == "yes"
def choose_gpu(multi=False):
print("\nChoose GPU for encoding:")
print("1) NVIDIA RTX 2000E Ada (default)")
print("2) Intel iGPU")
if multi:
print("3) Both (parallel encodes)")
choice = input("Enter choice [1-3]: ").strip() if multi else input("Enter choice [1-2]: ").strip()
# Intel iGPU (VAAPI)
if choice == "2":
return [{"type": "intel", "device": "/dev/dri/renderD128"}]
# Both GPUs (parallel encodes)
elif multi and choice == "3":
return [
{"type": "nvidia", "device": "cuda"}, # RTX 2000E Ada
{"type": "intel", "device": "/dev/dri/renderD128"} # Intel iGPU
]
# NVIDIA GPU (default)
return [{"type": "nvidia", "device": "cuda"}]
def choose_encoding_mode():
print("\nChoose encoding mode:")
print("1) Auto-quality (QP 24) [default]")
print("2) Higher quality (QP 22)")
print("3) Fixed bitrate (1M, slow preset)")
print("4) Fixed bitrate (2M, slow preset)")
choice = input("Enter choice: ").strip()
if choice == "2":
return "qp22"
elif choice == "3":
return "bitrate_1M"
elif choice == "4":
return "bitrate_2M"
return "qp"
def choose_scale():
print("\nScale:")
print("1) Keep original (default)")
print("2) Scale to 720p")
print("3) Scale to 1080p")
c = input("Choice [1]: ").strip()
if c == "2":
return "720p"
if c == "3":
return "1080p"
return None
def choose_audio_mode():
print("\nAudio Mode:")
print("1) Keep original (Copy) [default]")
print("2) Convert to AAC 2.0 (Stereo)")
print("3) Convert to AAC 5.1 (Surround)")
choice = input("Enter choice [1-3]: ").strip()
if choice == "2":
return "aac_2.0"
elif choice == "3":
return "aac_5.1"
return "copy"
def choose_codec():
print("\nChoose video codec:")
print("1) x265 (HEVC) [default]")
print("2) x264 (AVC)")
choice = input("Enter choice [1-2]: ").strip()
if choice == "2":
return "x264"
return "x265"
def choose_audio_bitrate(mode):
print("\nChoose audio bitrate:")
# Context menu for 5.1 Surround
if mode == "aac_5.1":
print("1) 384 kbps (Default)")
print("2) 256 kbps (Small file size)")
print("3) 448 kbps (High quality)")
print("4) 640 kbps (Maximum quality)")
choice = input("Enter choice [1-4]: ").strip()
if choice == "2": return "256k"
if choice == "3": return "448k"
if choice == "4": return "640k"
return "384k" # Default
# Context menu for 2.0 Stereo (or others)
else:
print("1) 128 kbps (Default)")
print("2) 192 kbps (High Quality)")
print("3) 96 kbps (Small file size)")
choice = input("Enter choice [1-3]: ").strip()
if choice == "2": return "192k"
if choice == "3": return "96k"
return "128k" # Default
def sanitize_filename(original_name, scaled, audio_mode, video_codec):
name = original_name
# Video Codec handling
if video_codec == "copy":
pass # Audio-only re-encode: leave video codec tag untouched
elif video_codec == "x264":
name = re.sub(r'(h\.?264|x264)', 'x264', name, flags=re.IGNORECASE)
name = re.sub(r'(h\.?265|x265)', 'x264', name, flags=re.IGNORECASE)
else:
name = re.sub(r'(h\.?264|x264)', 'x265', name, flags=re.IGNORECASE)
# Resolution handling
if scaled == "720p":
name = re.sub(r'(4K|UHD|1080p|576p|480p|720p)', '720p', name, flags=re.IGNORECASE)
if not re.search(r'720p', name, re.IGNORECASE):
name += ".720p"
elif scaled == "1080p":
name = re.sub(r'(1080p|576p|480p|720p)', '1080p', name, flags=re.IGNORECASE)
if not re.search(r'1080p', name, re.IGNORECASE):
name += ".1080p"
# Audio handling
if audio_mode != "copy":
# Remove old audio tags
name = re.sub(r'\b(dts|ac3|eac3|ddp|ddplus|mp3|ogg|flac|opus)\b', 'AAC', name, flags=re.IGNORECASE)
name = re.sub(r'\b(atmos)\b', '', name, flags=re.IGNORECASE)
if audio_mode == "aac_2.0":
name = re.sub(r'\b(aac|ddp|dd\+|ddplus)[\s_.-]*5[\s_.-]*1\b', 'AAC2.0', name, flags=re.IGNORECASE)
name = re.sub(r'\b5[\s_.-]*1\b', '2.0', name, flags=re.IGNORECASE)
elif audio_mode == "aac_5.1":
name = re.sub(r'\b(aac|ddp|dd\+|ddplus)[\s_.-]*2[\s_.-]*0\b', 'AAC5.1', name, flags=re.IGNORECASE)
name = re.sub(r'\b2[\s_.-]*0\b', '5.1', name, flags=re.IGNORECASE)
return name
def rename_external_subtitles(original_file, new_file):
original_stem = Path(original_file).stem
new_stem = Path(new_file).stem
for sub in Path(original_file).parent.glob(f"{original_stem}.*.srt"):
lang = sub.suffixes[-2] if len(sub.suffixes) > 1 else ""
new_sub_name = f"{new_stem}{lang}.srt"
new_sub_path = sub.parent / new_sub_name
print(f"📄 Renaming subtitle: {sub.name} -> {new_sub_name}")
shutil.move(sub, new_sub_path)
def get_subtitle_codecs(input_file):
"""Return a list of subtitle codecs for all subtitle streams in the file."""
try:
result = subprocess.run([
"ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
"stream=index,codec_name", "-of", "json", input_file
], capture_output=True, text=True)
data = json.loads(result.stdout)
return [(s["index"], s.get("codec_name", "")) for s in data.get("streams", [])]
except Exception as e:
print(f"⚠️ Could not determine subtitle codecs for {input_file}: {e}")
return []
def detect_video_codec(input_file):
"""Detects the codec of the input video stream (e.g., h264, hevc, vp9, av1)."""
try:
result = subprocess.run([
"ffprobe", "-v", "error",
"-select_streams", "v:0",
"-show_entries", "stream=codec_name",
"-of", "default=noprint_wrappers=1:nokey=1",
input_file
], capture_output=True, text=True)
return result.stdout.strip().lower()
except Exception as e:
print(f"⚠️ Could not detect codec for {input_file}: {e}")
return ""
def build_ffmpeg_command(input_file, scale, audio_mode, audio_bitrate, gpu, encoding_mode, video_codec="x265"):
"""
Build the ffmpeg command dynamically for either NVIDIA (NVENC) or Intel (VAAPI).
Automatically detects input codec for correct hardware decode.
"""
path = Path(input_file)
new_stem = sanitize_filename(path.stem, scale, audio_mode, video_codec)
out_file = f"{new_stem}.mkv"
# Prevent accidental overwrite of input
if Path(input_file).resolve() == Path(out_file).resolve():
out_file = f"{new_stem}_x265.mkv"
print(f"⚠️ Output file would overwrite input! Renaming output to: {out_file}")
# Prevent overwriting existing output by auto-renaming
counter = 1
while Path(out_file).exists():
out_file = f"{new_stem}_{counter}.mkv"
counter += 1
# ----------------------------
# Audio & subtitle setup
# ----------------------------
try:
probe = subprocess.run([
"ffprobe", "-v", "error", "-select_streams", "a:0",
"-show_entries", "stream=channels", "-of", "csv=p=0", input_file
], capture_output=True, text=True)
input_channels = int(probe.stdout.strip())
except:
input_channels = 2 # Assume stereo if probe fails to be safe
audio_args = ["-c:a", "copy"] # Default to copy
if audio_mode == "aac_5.1":
if input_channels >= 6:
if should_convert_audio(input_file, 6):
audio_args = ["-c:a", "aac", "-b:a", audio_bitrate, "-ac", "6"]
else:
# Source is Stereo -> FALLBACK to Stereo (Don't upmix!)
print(f"⚠️ Notice: {Path(input_file).name} is Stereo. Creating Stereo output instead of 5.1.")
if should_convert_audio(input_file, 2):
# Use a standard stereo bitrate (128k) instead of the 5.1 bitrate
audio_args = ["-c:a", "aac", "-b:a", "128k", "-ac", "2"]
elif audio_mode == "aac_2.0":
# Downmixing (5.1 -> 2.0) is always okay
if should_convert_audio(input_file, 2):
audio_args = ["-c:a", "aac", "-b:a", audio_bitrate, "-ac", "2"]
subtitle_codecs = get_subtitle_codecs(input_file)
subtitle_args = ["-map", "0:V", "-map", "0:a:0", "-map", "0:s?"]
text_codecs = {"ass", "ssa", "subrip", "srt", "text", "mov_text"}
for out_idx, (in_idx, codec) in enumerate(subtitle_codecs):
if codec.lower() in text_codecs:
subtitle_args += [f"-c:s:{out_idx}", "srt"]
else:
subtitle_args += [f"-c:s:{out_idx}", "copy"]
# ----------------------------
# NVIDIA path (NVENC + CUVID)
# ----------------------------
if gpu["type"] == "nvidia":
# Detect source codec and use matching CUDA decoder if possible
input_codec = detect_video_codec(input_file)
cuda_decoders = {
"h264": "h264_cuvid",
"hevc": "hevc_cuvid",
"vp8": "vp8_cuvid",
"vp9": "vp9_cuvid",
"av1": "av1_cuvid"
}
decode_codec = cuda_decoders.get(input_codec)
if decode_codec:
# Full HW path: CUDA decode → scale_cuda → NVENC
hwaccel_args = ["-hwaccel", "cuda", "-hwaccel_output_format", "cuda"]
decode_args = ["-c:v", decode_codec]
if scale == "720p":
vf_filter = "scale_cuda=w=1280:h=-2"
elif scale == "1080p":
vf_filter = "scale_cuda=w=1920:h=-2"
else:
vf_filter = None
else:
# No CUDA decoder for this codec (e.g. mpeg4/xvid); software decode → NVENC
hwaccel_args = []
decode_args = []
if scale == "720p":
vf_filter = "scale=w=1280:h=-2"
elif scale == "1080p":
vf_filter = "scale=w=1920:h=-2"
else:
vf_filter = None
# Encoder selection
if video_codec == "x264":
video_args = ["-c:v", "h264_nvenc"]
else:
video_args = ["-c:v", "hevc_nvenc"]
# Quality / bitrate
if encoding_mode == "qp":
video_args += ["-rc", "constqp", "-qp", "24", "-preset", "medium"]
elif encoding_mode == "qp22":
video_args += ["-rc", "constqp", "-qp", "22", "-preset", "medium"]
elif encoding_mode == "bitrate_1M":
video_args += ["-b:v", "1M", "-maxrate", "2M", "-preset", "slow"]
elif encoding_mode == "bitrate_2M":
video_args += ["-b:v", "2M", "-maxrate", "4M", "-preset", "slow"]
else:
print(f"❌ Unknown encoding mode: {encoding_mode}. Defaulting to auto-quality (QP 24).")
video_args += ["-rc", "constqp", "-qp", "24", "-preset", "medium"]
# Final command for NVIDIA
cmd = [
"ffmpeg",
*hwaccel_args,
*decode_args,
"-i", input_file,
*(["-vf", vf_filter] if vf_filter else []),
*video_args,
*audio_args,
*subtitle_args,
out_file
]
return cmd
# ----------------------------
# Intel path (VAAPI)
# ----------------------------
elif gpu["type"] == "intel":
hwaccel_args = ["-hwaccel", "vaapi", "-vaapi_device", gpu["device"]]
if video_codec == "x264":
video_args = ["-c:v", "h264_vaapi"]
else:
video_args = ["-c:v", "hevc_vaapi"]
if encoding_mode == "qp":
video_args += ["-qp", "24"]
elif encoding_mode == "qp22":
video_args += ["-qp", "22"]
elif encoding_mode == "bitrate_1M":
video_args += ["-b:v", "1M", "-preset", "slow"]
elif encoding_mode == "bitrate_2M":
video_args += ["-b:v", "2M", "-preset", "slow"]
else:
print(f"❌ Unknown encoding mode: {encoding_mode}. Defaulting to auto-quality (QP 24).")
video_args += ["-qp", "24"]
if scale == "720p":
vf_filter = "scale=w=1280:-2,format=nv12,hwupload"
elif scale == "1080p":
vf_filter = "scale=w=1920:-2,format=nv12,hwupload"
else:
vf_filter = "format=nv12,hwupload"
cmd = [
"ffmpeg",
*hwaccel_args,
"-i", input_file,
"-vf", vf_filter,
*video_args,
*audio_args,
*subtitle_args,
out_file
]
return cmd
# ----------------------------
# Unknown GPU type
# ----------------------------
else:
raise ValueError(f"Unknown GPU type: {gpu['type']}")
# Global synchronization primitives for progress display
progress_display_lock = threading.Lock()
progress_lines = {}
def monitor_encoding_progress(file, process, gpu_label):
global progress_display_lock, progress_lines
start_time = time.time()
duration = None
last_progress = ""
stderr_lines = [] # Collect all stderr output
speed = 1.0 # Default speed
while process.poll() is None and not stop_requested:
try:
while True:
stderr_output = process.stderr.readline()
if not stderr_output:
break
stderr_output = stderr_output.strip()
if stderr_output:
stderr_lines.append(stderr_output) # Collect for later
progress_match = re.search(r"Duration: (\d{2}:\d{2}:\d{2}\.\d{2})", stderr_output)
if progress_match and not duration:
duration = sum(
float(x) * 60 ** i for i, x in enumerate(reversed(progress_match.group(1).split(':')))
)
time_match = re.search(r"time=(\d{2}:\d{2}:\d{2}\.\d{2})", stderr_output)
speed_match = re.search(r"speed=([\d\.]+)x", stderr_output)
if time_match and duration:
elapsed_time = time.time() - start_time
current_time_seconds = sum(
float(x) * 60 ** i for i, x in enumerate(reversed(time_match.group(1).split(':')))
)
progress = (current_time_seconds / duration) * 100 if duration > 0 else 0
speed = float(speed_match.group(1)) if speed_match else speed
eta = (duration - current_time_seconds) / speed if speed and speed > 0 else "N/A"
bar_length = 30
bar_fill = int(progress / 100 * bar_length)
bar = '█' * bar_fill + '-' * (bar_length - bar_fill)
progress_str = (
f"🎬 {Path(file).name} | {gpu_label} | [{bar}] "
f"{progress:.2f}% | ⏱ {time.strftime('%H:%M:%S', time.gmtime(elapsed_time))}"
)
if speed:
progress_str += f" | Speed: {speed:.2f}x"
if eta != "N/A":
progress_str += f" | ETA: {time.strftime('%H:%M:%S', time.gmtime(eta))}"
if progress_str != last_progress:
with progress_display_lock:
progress_lines[file] = progress_str
os.system("clear")
for line in progress_lines.values():
print(line)
last_progress = progress_str
time.sleep(0.1)
except ValueError:
pass
except Exception as e:
print(f"\n⚠️ Error monitoring progress for {file}: {e}")
break
# --- Final status output ---
with progress_display_lock:
if stop_requested:
progress_lines[file] = f"🛑 Encoding of {Path(file).name} interrupted."
elif process.returncode == 0:
progress_lines[file] = f"✅ Done: {Path(file).name} on {gpu_label} @ {speed:.2f}x"
else:
progress_lines[file] = (
f"❌ Encoding of {Path(file).name} failed (return code: {process.returncode})."
)
os.system("clear")
for line in progress_lines.values():
print(line)
if process.returncode != 0:
print(f"\n🔍 FFmpeg Error Output for {file}:\n" + "\n".join(stderr_lines))
time.sleep(1) # Give time to read the error
def process_encoding(file, scale, audio_mode, audio_bitrate, gpu, encoding_mode, delete_originals, video_codec="x265"):
"""
Handles a single encoding job:
- Builds the ffmpeg command
- Starts the encoding process and monitors progress
- Applies timestamp fix after encoding (copy pass)
- Cleans up when finished
"""
global processes, encode_info
if stop_requested:
print(f"⏭️ Skipping: {file} (interrupted)")
return
gpu_label = "NVIDIA RTX 2000E" if gpu["type"] == "nvidia" else "Intel iGPU"
print(f"\n▶️ Encoding: {file} using {gpu_label}")
# Build ffmpeg command
cmd = build_ffmpeg_command(file, scale, audio_mode, audio_bitrate, gpu, encoding_mode, video_codec)
out_file = cmd[-1]
time.sleep(3)
# ------------------------------
# Run encoding
# ------------------------------
try:
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, text=True)
processes[file] = process
encode_info[file] = {'start_time': time.time()}
monitor_thread = threading.Thread(
target=monitor_encoding_progress,
args=(file, process, gpu_label)
)
monitor_thread.daemon = True
monitor_thread.start()
process.wait()
monitor_thread.join(timeout=0.1)
del processes[file]
del encode_info[file]
except Exception as e:
print(f"\n⚠️ Encoding of {file} failed: {e}")
if process:
process.terminate()
return
# ------------------------------
# If encode failed → stop
# ------------------------------
if process.returncode != 0:
print(f"❌ ffmpeg exited with code {process.returncode}. Skipping timestamp fix.")
return
# ------------------------------
# External subtitle renaming
# ------------------------------
rename_external_subtitles(file, out_file)
# ------------------------------
# Timestamp fix (copy pass)
# ------------------------------
print(f"🔧 Fixing timestamps: {out_file}")
fixed_file = out_file.replace(".mkv", ".fixed.mkv")
fix_cmd = [
"ffmpeg", "-loglevel", "error",
"-i", out_file,
"-map", "0",
"-c", "copy",
"-fflags", "+genpts",
"-avoid_negative_ts", "make_zero",
fixed_file
]
fix_proc = subprocess.run(fix_cmd)
if fix_proc.returncode == 0 and Path(fixed_file).exists() and Path(fixed_file).stat().st_size > 5000:
os.replace(fixed_file, out_file)
print(f"✔ Timestamp repair complete: {out_file}")
else:
print(f"⚠️ Timestamp fix failed, original kept.")
if Path(fixed_file).exists():
Path(fixed_file).unlink()
# ------------------------------
# Delete original if requested
# ------------------------------
if delete_originals:
print(f"🗑️ Deleting original: {file}")
try:
os.remove(file)
except OSError as e:
print(f"⚠️ Error deleting {file}: {e}")
def choose_operation():
print("\nWhat would you like to do?")
print("1) Re-encode video (H.265/H.264) [default]")
print("2) Re-encode audio only")
print("3) Fix timestamps only (copy pass)")
choice = input("Enter choice [1-3]: ").strip()
if choice == "2":
return "audio_only"
if choice == "3":
return "timestamp_fix"
return "video"
def choose_audio_reencoding_mode():
print("\nTarget audio format:")
print("1) AAC 2.0 (Stereo) [default]")
print("2) AAC 5.1 (Surround)")
choice = input("Enter choice [1-2]: ").strip()
if choice == "2":
return "aac_5.1"
return "aac_2.0"
def build_audio_only_command(input_file, audio_mode, audio_bitrate):
path = Path(input_file)
new_stem = sanitize_filename(path.stem, None, audio_mode, "copy")
final_out_file = f"{new_stem}.mkv"
tmp_file = f"{new_stem}.tmp.mkv"
try:
probe = subprocess.run([
"ffprobe", "-v", "error", "-select_streams", "a:0",
"-show_entries", "stream=channels", "-of", "csv=p=0", input_file
], capture_output=True, text=True)
input_channels = int(probe.stdout.strip())
except Exception:
input_channels = 2
audio_args = ["-c:a", "copy"]
if audio_mode == "aac_5.1":
if input_channels >= 6:
if should_convert_audio(input_file, 6):
audio_args = ["-c:a", "aac", "-b:a", audio_bitrate, "-ac", "6"]
else:
print(f"⚠️ Notice: {path.name} is Stereo. Creating Stereo output instead of 5.1.")
if should_convert_audio(input_file, 2):
audio_args = ["-c:a", "aac", "-b:a", "128k", "-ac", "2"]
elif audio_mode == "aac_2.0":
if should_convert_audio(input_file, 2):
audio_args = ["-c:a", "aac", "-b:a", audio_bitrate, "-ac", "2"]
subtitle_codecs = get_subtitle_codecs(input_file)
subtitle_args = ["-map", "0:V", "-map", "0:a:0", "-map", "0:s?"]
text_codecs = {"ass", "ssa", "subrip", "srt", "text", "mov_text"}
for out_idx, (in_idx, codec) in enumerate(subtitle_codecs):
if codec.lower() in text_codecs:
subtitle_args += [f"-c:s:{out_idx}", "srt"]
else:
subtitle_args += [f"-c:s:{out_idx}", "copy"]
cmd = [
"ffmpeg",
"-i", input_file,
*subtitle_args,
"-c:v", "copy",
*audio_args,
tmp_file
]
return cmd, final_out_file
def process_audio_only_encoding(file, audio_mode, audio_bitrate, delete_originals):
global processes, encode_info
if stop_requested:
print(f"⏭️ Skipping: {file} (interrupted)")
return
print(f"\n▶️ Re-encoding audio: {file}")
cmd, final_out_file = build_audio_only_command(file, audio_mode, audio_bitrate)
tmp_file = cmd[-1]
time.sleep(1)
try:
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, text=True)
processes[file] = process
encode_info[file] = {'start_time': time.time()}
monitor_thread = threading.Thread(
target=monitor_encoding_progress,
args=(file, process, "CPU")
)
monitor_thread.daemon = True
monitor_thread.start()
process.wait()
monitor_thread.join(timeout=0.1)
del processes[file]
del encode_info[file]
except Exception as e:
print(f"\n⚠️ Encoding of {file} failed: {e}")
if process:
process.terminate()
return
if process.returncode != 0:
print(f"❌ ffmpeg exited with code {process.returncode}.")
if Path(tmp_file).exists():
Path(tmp_file).unlink()
return
rename_external_subtitles(file, final_out_file)
print(f"🔧 Fixing timestamps: {tmp_file}")
fix_cmd = [
"ffmpeg", "-loglevel", "error",
"-i", tmp_file,
"-map", "0",
"-c", "copy",
"-fflags", "+genpts",
"-avoid_negative_ts", "make_zero",
final_out_file
]
fix_proc = subprocess.run(fix_cmd)
if fix_proc.returncode == 0 and Path(final_out_file).exists() and Path(final_out_file).stat().st_size > 5000:
Path(tmp_file).unlink()
print(f"✔ Done: {final_out_file}")
else:
print(f"⚠️ Timestamp fix failed, keeping encode without fix.")
if Path(final_out_file).exists():
Path(final_out_file).unlink()
os.replace(tmp_file, final_out_file)
if delete_originals and Path(file).resolve() != Path(final_out_file).resolve():
print(f"🗑️ Deleting original: {file}")
try:
os.remove(file)
except OSError as e:
print(f"⚠️ Error deleting {file}: {e}")
def process_timestamp_fix(file, delete_originals):
if stop_requested:
print(f"⏭️ Skipping: {file} (interrupted)")
return
path = Path(file)
fixed_file = str(path.with_suffix(".fixed.mkv"))
print(f"\n🔧 Fixing timestamps: {file}")
fix_cmd = [
"ffmpeg", "-loglevel", "error",
"-i", file,
"-map", "0",
"-c", "copy",
"-fflags", "+genpts",
"-avoid_negative_ts", "make_zero",
fixed_file
]
fix_proc = subprocess.run(fix_cmd)
if fix_proc.returncode == 0 and Path(fixed_file).exists() and Path(fixed_file).stat().st_size > 5000:
out_file = str(path.with_suffix(".mkv"))
os.replace(fixed_file, out_file)
print(f"✔ Timestamp repair complete: {out_file}")
if delete_originals and Path(file).resolve() != Path(out_file).resolve():
print(f"🗑️ Deleting original: {file}")
try:
os.remove(file)
except OSError as e:
print(f"⚠️ Error deleting {file}: {e}")
else:
print(f"⚠️ Timestamp fix failed, original kept.")
if Path(fixed_file).exists():
Path(fixed_file).unlink()
def main():
"""
Main entry point.
Scans for video files, asks the user for encoding preferences, and
dispatches encoding jobs across available GPUs (NVIDIA + Intel iGPU).
"""
current_dir = os.getcwd()
files = list_media_files(current_dir)
if not files:
print("No media files found.")
return
# User configuration prompts
selected_files = get_user_selection(files)
operation = choose_operation()
# --- Timestamp-fix only path ---
if operation == "timestamp_fix":
delete_originals = yes_no("Delete original files after fixing?", default="no")
for file in selected_files:
if stop_requested:
print("🛑 Stopped by user.")
break
process_timestamp_fix(file, delete_originals)
return
# --- Audio-only re-encode path ---
if operation == "audio_only":
audio_mode = choose_audio_reencoding_mode()
audio_bitrate = choose_audio_bitrate(audio_mode)
delete_originals = yes_no("Delete original files after encoding?", default="no")
for file in selected_files:
if stop_requested:
print("🛑 Stopped by user.")
break
process_audio_only_encoding(file, audio_mode, audio_bitrate, delete_originals)
return
# --- Video re-encode path ---
scale = choose_scale()
audio_mode = choose_audio_mode()
audio_bitrate = "128k" # Default
if audio_mode != "copy":
audio_bitrate = choose_audio_bitrate(audio_mode)
video_codec = choose_codec()
encoding_mode = choose_encoding_mode()
# If more than one file, ask whether to use both GPUs (NVIDIA + Intel)
use_both = len(selected_files) > 1
gpu_devices = choose_gpu(multi=use_both)
delete_originals = yes_no("Delete original files after encoding?", default="no")
# Parallel mode: distribute jobs across NVIDIA and Intel GPUs
if len(gpu_devices) == 2:
file_queue = queue.Queue()
for f in selected_files:
file_queue.put(f)
def gpu_worker(gpu):
while not file_queue.empty() and not stop_requested:
try:
file = file_queue.get_nowait()
except queue.Empty:
break
process_encoding(
file,
scale,
audio_mode,
audio_bitrate,
gpu,
encoding_mode,
delete_originals,
video_codec,
)
file_queue.task_done()
threads = []
for gpu in gpu_devices:
t = threading.Thread(target=gpu_worker, args=(gpu,))
t.start()
threads.append(t)
for t in threads:
t.join()
# Single GPU (either NVIDIA or Intel)
else:
for file in selected_files:
if stop_requested:
print("🛑 Stopped by user.")
break
process_encoding(
file,
scale,
audio_mode,
audio_bitrate,
gpu_devices[0],
encoding_mode,
delete_originals,
video_codec,
)
if __name__ == "__main__":
main()