-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode265_cuda
More file actions
668 lines (567 loc) · 23.6 KB
/
encode265_cuda
File metadata and controls
668 lines (567 loc) · 23.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
#!/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"
]
# 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):
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)
stream = data.get("streams", [{}])[0]
codec = stream.get("codec_name", "").lower()
channels = stream.get("channels", 0)
return not (codec == "aac" and channels == 2)
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):
print(f"{idx + 1}. {file}")
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) Fixed bitrate (1M, slow preset)")
print("3) Fixed bitrate (2M, slow preset)")
choice = input("Enter choice: ").strip()
if choice == "2":
return "bitrate_1M"
elif choice == "3":
return "bitrate_2M"
return "qp"
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():
print("\nChoose audio bitrate:")
print("1) 128 kbps (default)")
print("2) 160 kbps")
print("3) 256 kbps")
choice = input("Enter choice [1-3]: ").strip()
if choice == "2":
return "160k"
elif choice == "3":
return "256k"
else:
return "128k"
def sanitize_filename(original_name, scaled, audio_converted, video_codec):
name = original_name
if 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)
if scaled:
name = re.sub(r'(1080p|576p|480p)', '720p', name, flags=re.IGNORECASE)
if not re.search(r'720p', name, re.IGNORECASE):
name += ".720p"
if audio_converted:
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(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)
name = re.sub(r'\b(atmos)\b', 'AAC', 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, convert_audio, 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, convert_audio, 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
# ----------------------------
if convert_audio and should_convert_audio(input_file):
audio_args = ["-c:a", "aac", "-b:a", audio_bitrate, "-ac", "2"]
else:
audio_args = ["-c:a", "copy"]
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":
hwaccel_args = ["-hwaccel", "cuda", "-hwaccel_output_format", "cuda"]
# 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)
decode_args = ["-c:v", decode_codec] if decode_codec else []
# 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 == "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"]
# Filter chain (CUDA)
if scale:
vf_filter = "scale_cuda=w=1280:h=-2"
else:
vf_filter = "scale_cuda=w=iw:h=ih"
# 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 == "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"]
vf_filter = "scale=w=1280:-2,format=nv12,hwupload" if scale else "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, convert_audio, audio_bitrate, gpu, encoding_mode, delete_originals, video_codec="x265"):
"""
Handles a single encoding job:
- Builds the ffmpeg command for the selected GPU (NVENC or VAAPI)
- Starts the encoding process and monitors progress
- Cleans up when finished
"""
global processes, encode_info
def process_encoding(file, scale, convert_audio, 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, convert_audio, 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 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)
scale = yes_no("Scale video to 720p?", default="no")
convert_audio = yes_no("Convert audio to AAC 2.0?", default="no")
audio_bitrate = None
if convert_audio:
audio_bitrate = choose_audio_bitrate()
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,
convert_audio,
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,
convert_audio,
audio_bitrate,
gpu_devices[0],
encoding_mode,
delete_originals,
video_codec,
)
if __name__ == "__main__":
main()