-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVideo-Optimizer-GUI.py
More file actions
1623 lines (1394 loc) · 77.5 KB
/
Video-Optimizer-GUI.py
File metadata and controls
1623 lines (1394 loc) · 77.5 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
import os
import sys
# Version: 3.0.0
import json
import time
import uuid
import threading
import subprocess
import customtkinter as ctk
from tkinter import filedialog, ttk
from pathlib import Path
from datetime import datetime
def bootstrap():
"""Detect if running in venv, if not look for '.venv' and restart."""
if hasattr(sys, 'real_prefix') or (sys.base_prefix != sys.prefix):
return # Already in venv
# Check for .venv in the current directory
venv_dir = Path(".venv")
if os.name == 'nt':
python_exe = venv_dir / "Scripts" / "python.exe"
else:
python_exe = venv_dir / "bin" / "python"
if python_exe.exists():
# Restart the script using the python executable from the venv
os.execv(str(python_exe), [str(python_exe)] + sys.argv)
# Initialize bootstrap before anything else
bootstrap()
# --- THEME CONFIGURATION ---
ctk.set_appearance_mode("System") # Modes: "System" (standard), "Dark", "Light"
ctk.set_default_color_theme("green") # Themes: "blue" (standard), "green", "dark-blue"
class VideoOptimizerEngine:
def __init__(self, logger_callback=None, progress_callback=None, status_callback=None):
self.logger_callback = logger_callback
self.progress_callback = progress_callback
self.status_callback = status_callback
self.stop_requested = False
# Defaults (will be overridden by config.json)
self.known_extensions = [
'.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.ts', '.vob',
'.m2ts', '.mpeg', '.mpg', '.rm', '.rmvb', '.3gp', '.3g2', '.ogv', '.mp4v', '.f4v',
'.asf', '.divx', '.xvid', '.yuv', '.viv', '.mxf'
]
self.ignored_extensions = [
'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.lnk', '.exe', '.tif',
'.heic', '.ico', '.svg', '.psd', '.ai', '.txt', '.log', '.pdf', '.zip', '.rar',
'.7z', '.iso', '.ps1', '.md', '.json', '.csv', '.xml', '.ini', '.cfg', '.yaml',
'.yml', '.html', '.css', '.js', '.db', '.sqlite', '.bak', '.nef', '.dng', '.arw',
'.xmp', '.mp3', '.wav', '.m4a', '.aac', '.flac', '.cfa', '.pek', '.ffx', '.prfpset',
'.ds_store', '.setting', '.drp', '.cube', '.url', '.drfx', '.ttf', '.otf', '.eot',
'.woff', '.woff2', '.fon', '.ttc', '.compositefont', '.dat', '.htm', '.eps', '.jfif',
'.avif', '.sfk', '.mogrt', '.prproj', '.aep', '.aegraphic', '.aif', '.atn', '.abr',
'.grd', '.pat', '.asl', '.settings', '.zxp', '.rtf', '.plp', '.apk', '.docx', '.atom'
]
self.efficient_codecs = ['hevc', 'h265', 'av1']
def log(self, message):
if self.logger_callback:
self.logger_callback(message)
else:
print(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")
def update_status(self, status):
if self.status_callback:
self.status_callback(status)
def update_progress(self, progress_data):
if self.progress_callback:
self.progress_callback(progress_data)
def request_stop(self):
self.stop_requested = True
self.log("[STOP] Cancellation requested.")
def get_ffmpeg_encoders(self):
try:
result = subprocess.run(['ffmpeg', '-encoders'], capture_output=True, text=True, check=True)
return result.stdout
except Exception as e:
self.log(f"[FAIL] Failed to detect encoders: {e}")
return ""
def check_encoder_support(self, codec):
encoders = self.get_ffmpeg_encoders()
if codec in encoders:
# Try a dummy encode to confirm hardware init
dummy_args = [
'ffmpeg', '-y', '-loglevel', 'error',
'-f', 'lavfi', '-i', 'color=black:s=1280x720:r=24',
'-pix_fmt', 'yuv420p', '-vframes', '1',
'-c:v', codec, '-f', 'null', '-'
]
try:
subprocess.run(dummy_args, check=True, capture_output=True)
return True
except subprocess.CalledProcessError:
return False
return False
def get_video_duration(self, file_path):
try:
args = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', str(file_path)]
result = subprocess.run(args, capture_output=True, text=True, check=True)
return float(result.stdout.strip())
except:
return 60.0
def get_video_codec(self, file_path):
try:
args = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=codec_name', '-of', 'default=noprint_wrappers=1:nokey=1', str(file_path)]
result = subprocess.run(args, capture_output=True, text=True, check=True)
return result.stdout.strip().lower()
except:
return "unknown"
def get_audio_codec(self, file_path):
try:
args = ['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_name', '-of', 'default=noprint_wrappers=1:nokey=1', str(file_path)]
result = subprocess.run(args, capture_output=True, text=True, check=True)
return result.stdout.strip().lower()
except:
return "unknown"
def calculate_vmaf(self, reference, distorted):
threads = max(1, min(4, os.cpu_count() // 2))
args = ['ffmpeg', '-i', str(distorted), '-i', str(reference), '-filter_complex', f'libvmaf=n_threads={threads}', '-f', 'null', '-']
try:
result = subprocess.run(args, capture_output=True, text=True)
import re
match = re.search(r"VMAF score: (\d+\.\d+)", result.stderr)
if match:
return float(match.group(1))
except Exception as e:
self.log(f"[FAIL] VMAF calculation failed: {e}")
return None
def run_vmaf_search(self, file_path, config, target_vmaf=None, signature=None):
ref_samples = []
try:
best_cq = 26
best_score = 0.0
max_score = 0.0
max_score_cq = 26
if target_vmaf is None:
target_vmaf = config.get('VmafTarget', 93)
self.log(f"[PROBE] Starting VMAF search (Target: {target_vmaf}) for: {Path(file_path).name}")
duration = self.get_video_duration(file_path)
samples_count = config.get('VmafSamples', 3)
sample_dur = config.get('VmafDur', 5)
encoder = config.get('Encoder', 'libx264')
preset = config.get('Preset', 'medium')
mode_flag = config.get('Mode', 'crf')
# Hardware Decode Detection
hw_decode_args = []
if 'nvenc' in encoder: hw_decode_args = ['-hwaccel', 'cuda']
elif 'qsv' in encoder: hw_decode_args = ['-hwaccel', 'qsv']
elif 'amf' in encoder: hw_decode_args = ['-hwaccel', 'd3d11va']
# Probe Cache Setup
probe_key = f"codec={encoder}|preset={preset}|samples={samples_count}|dur={sample_dur}"
cache_key = str(file_path).lower()
probe_cache = None
if config.get('CacheEnabled') and signature:
if 'Cache' not in config: config['Cache'] = {}
if cache_key not in config['Cache']: config['Cache'][cache_key] = {}
file_cache = config['Cache'][cache_key]
if file_cache.get('Signature') != signature:
file_cache['VmafProbeCache'] = {}
file_cache['Signature'] = signature
if 'VmafProbeCache' not in file_cache: file_cache['VmafProbeCache'] = {}
if probe_key not in file_cache['VmafProbeCache']:
file_cache['VmafProbeCache'][probe_key] = {
'Probes': {},
'MaxAchievableVmaf': 0.0,
'MaxVmafCq': 26
}
probe_cache = file_cache['VmafProbeCache'][probe_key]
if probe_cache.get('Probes'):
closest_cq = None
closest_diff = 100
closest_score = 0
for c_cq, c_score in probe_cache['Probes'].items():
diff = abs(c_score - target_vmaf)
if diff < closest_diff:
closest_diff = diff
closest_cq = int(c_cq)
closest_score = c_score
if closest_diff <= 0.5:
self.log(f"[PROBE] Found ideal cached match: CQ {closest_cq} -> VMAF {closest_score:.2f} (Target: {target_vmaf})")
return closest_cq, closest_score, probe_cache.get('MaxAchievableVmaf', 0), probe_cache.get('MaxVmafCq', 26)
if samples_count == 1:
sample_points = [duration / 2]
else:
if duration is None:
duration = 0.0
sample_points = [(duration / (samples_count + 1)) * i for i in range(1, samples_count + 1)]
temp_dir = Path(os.environ.get('TEMP', '.'))
uid = str(uuid.uuid4())[:8]
self.log(f"[PROBE] Pre-extracting {len(sample_points)} reference sample segments...")
for idx, sp in enumerate(sample_points):
if self.stop_requested:
break
sample_src = temp_dir / f"v_s_ref_{idx}_{uid}.mkv"
extract_args = ['ffmpeg', '-y', '-loglevel', 'error'] + hw_decode_args + ['-ss', str(sp), '-t', str(sample_dur), '-i', str(file_path), '-c:v', 'copy', '-an', str(sample_src)]
subprocess.run(extract_args, check=True)
ref_samples.append(sample_src)
if self.stop_requested:
return 26, 0.0, 0.0, 26
local_probes = {}
if probe_cache is not None and 'Probes' in probe_cache:
for k, v in probe_cache['Probes'].items():
local_probes[int(k)] = v
# --- Local helper: probe a single CQ value ---
def probe_cq(cq_val, pass_label=""):
"""Probe VMAF at a given CQ. Returns avg score or None."""
if self.stop_requested:
return None
str_cq = str(cq_val)
# Check probe cache first
if probe_cache is not None and str_cq in probe_cache['Probes']:
cached_score = probe_cache['Probes'][str_cq]
self.log(f"[PROBE] {pass_label}Cached CQ {cq_val} -> VMAF: {cached_score:.2f}")
local_probes[cq_val] = cached_score
return cached_score
self.log(f"[PROBE] {pass_label}Probing Visual Fidelity at CQ {cq_val}")
scores = []
for idx, sample_src in enumerate(ref_samples):
if self.stop_requested:
break
sample_enc = temp_dir / f"v_e_{idx}_{uid}.mkv"
try:
encode_args = ['ffmpeg', '-y', '-loglevel', 'error'] + hw_decode_args + ['-i', str(sample_src), '-c:v', encoder, '-preset', preset, f"-{mode_flag}", str(cq_val), str(sample_enc)]
subprocess.run(encode_args, check=True)
if self.stop_requested: break
score = self.calculate_vmaf(sample_src, sample_enc)
if score is not None:
scores.append(score)
except Exception as e:
self.log(f"[FAIL] Sample processing failed: {e}")
finally:
if sample_enc.exists(): sample_enc.unlink()
if not scores or self.stop_requested:
return None
avg = sum(scores) / len(scores)
self.log(f"[PROBE] {pass_label}CQ {cq_val} -> VMAF: {avg:.2f}")
# Update probe cache
local_probes[cq_val] = avg
if probe_cache is not None:
probe_cache['Probes'][str_cq] = avg
if avg > probe_cache.get('MaxAchievableVmaf', 0):
probe_cache['MaxAchievableVmaf'] = avg
probe_cache['MaxVmafCq'] = cq_val
try:
with open(config['CacheFile'], 'w') as f:
json.dump(list(config['Cache'].values()), f, indent=4)
except:
pass
return avg
# --- Helper: update best tracking ---
def update_best(cq_val, score_val):
nonlocal best_cq, best_score, max_score, max_score_cq
if score_val > max_score:
max_score = score_val
max_score_cq = cq_val
if best_score == 0 or abs(score_val - target_vmaf) < abs(best_score - target_vmaf):
best_cq = cq_val
best_score = score_val
# --- Binary Search between bounds ---
cq_min = config.get('CqMin', 1)
cq_max = config.get('CqMax', 51)
best_cq = cq_min
best_score = 0.0
max_score = 0.0
max_score_cq = cq_min
# 1. Check CQ/CRF cq_max (floor) and record/remember output data
self.log(f"[PROBE] Boundary: Testing VMAF floor at CQ {cq_max}...")
floor_score = probe_cq(cq_max, "Boundary Floor: ")
if floor_score is not None:
update_best(cq_max, floor_score)
# If even floor exceeds target, we immediately use max compression
if floor_score >= target_vmaf:
self.log(f"[PROBE] Floor CQ {cq_max} already meets target ({floor_score:.2f} >= {target_vmaf}). Max compression achieved.")
return cq_max, floor_score, max_score, max_score_cq
if self.stop_requested:
return best_cq, best_score, max_score, max_score_cq
# 2. Check CQ/CRF cq_min (ceiling) and record/remember output data
self.log(f"[PROBE] Boundary: Testing VMAF ceiling at CQ {cq_min}...")
ceiling_score = probe_cq(cq_min, "Boundary Ceiling: ")
effective_target = target_vmaf
target_unreachable = False
if ceiling_score is not None:
update_best(cq_min, ceiling_score)
# If even the highest quality cannot reach target VMAF
if ceiling_score < target_vmaf:
target_unreachable = True
# Dynamically adjust the target to ceiling directly as per user request (no tolerance subtracted)
effective_target = ceiling_score
self.log(f"[PROBE] Ceiling CQ {cq_min} cannot reach target ({ceiling_score:.2f} < {target_vmaf}). Adjusting effective VMAF target to known ceiling {effective_target:.2f} and continuing search.")
if self.stop_requested:
return best_cq, best_score, max_score, max_score_cq
# 3. Stage 1 Binary Search
low_cq = cq_min
high_cq = cq_max
final_mid_cq = cq_min
final_vmaf = ceiling_score if ceiling_score is not None else 0.0
early_plateau_break = False
for attempt in range(1, 16):
if self.stop_requested:
break
# Plateau Detection: check if we have 3 probed CQs with VMAF within 0.05 tolerance
if len(local_probes) >= 3:
sorted_probes = sorted(local_probes.items(), key=lambda x: x[1], reverse=True)
plateau_detected = False
for i in range(len(sorted_probes) - 2):
p1, p2, p3 = sorted_probes[i], sorted_probes[i+1], sorted_probes[i+2]
if abs(p1[1] - p3[1]) <= 0.05:
plateau_cq = max(p1[0], p2[0], p3[0])
self.log(f"[PROBE] Plateau detected at CQ {p3[0]}, {p2[0]}, {p1[0]} (Scores: {p3[1]:.2f}, {p2[1]:.2f}, {p1[1]:.2f}). Stopping first search phase early.")
final_mid_cq = plateau_cq
final_vmaf = local_probes[plateau_cq]
plateau_detected = True
early_plateau_break = True
break
if plateau_detected:
break
# Stop if there are no more integer points between low and high
if high_cq - low_cq <= 1:
break
mid_cq = (low_cq + high_cq) // 2
score = probe_cq(mid_cq, f"Pass {attempt}: ")
if score is None:
break
update_best(mid_cq, score)
final_mid_cq = mid_cq
final_vmaf = score
if score >= effective_target:
# Quality is enough/high, try to compress more (higher CQ value)
low_cq = mid_cq
else:
# Quality is too low, we must use higher quality (lower CQ value)
high_cq = mid_cq
# 4. Stage 2 Refinement Binary Search (Directional Search)
self.log(f"[PROBE] Stage 1 finished. Final midpoint CQ {final_mid_cq} has VMAF {final_vmaf:.2f}.")
if final_vmaf >= effective_target:
# Case A: Quality is sufficient. Search to the right (higher CQs / more compression)
# Find tested similar_cq in local_probes that is > final_mid_cq and closest to effective_target
candidates = [k for k in local_probes.keys() if k > final_mid_cq]
if candidates:
similar_cq = min(candidates, key=lambda k: abs(local_probes[k] - effective_target))
else:
similar_cq = cq_max
self.log(f"[PROBE] VMAF >= target. Refining search to the right (higher CQs) between {final_mid_cq} and {similar_cq}...")
else:
# Case B: Quality is too low. Search to the left (lower CQs / higher quality)
# Find tested similar_cq in local_probes that is < final_mid_cq and closest to effective_target
candidates = [k for k in local_probes.keys() if k < final_mid_cq]
if candidates:
similar_cq = min(candidates, key=lambda k: abs(local_probes[k] - effective_target))
else:
similar_cq = cq_min
self.log(f"[PROBE] VMAF < target. Refining search to the left (lower CQs) between {similar_cq} and {final_mid_cq}...")
refine_low = min(final_mid_cq, similar_cq)
refine_high = max(final_mid_cq, similar_cq)
# Run second binary search
for attempt_ref in range(1, 10):
if self.stop_requested:
break
if refine_high - refine_low <= 1:
break
mid_cq = (refine_low + refine_high) // 2
score = probe_cq(mid_cq, f"Refinement Pass {attempt_ref}: ")
if score is None:
break
update_best(mid_cq, score)
if score >= effective_target:
refine_low = mid_cq
else:
refine_high = mid_cq
# 5. Final Selection: choose the highest CQ meeting quality, fallback to closest overall
if local_probes:
valid_cqs = []
for c_cq, c_score in local_probes.items():
if c_score >= effective_target - 0.05:
valid_cqs.append((c_cq, c_score))
if valid_cqs:
best_cq, best_score = max(valid_cqs, key=lambda x: x[0])
self.log(f"[PROBE] Final evaluation: optimal CQ is {best_cq} with VMAF {best_score:.2f}")
else:
closest_cq = min(local_probes.keys(), key=lambda x: abs(local_probes[x] - target_vmaf))
best_cq = closest_cq
best_score = local_probes[closest_cq]
self.log(f"[PROBE] Final evaluation: fallback to closest CQ {best_cq} with VMAF {best_score:.2f}")
if probe_cache is not None and target_unreachable:
probe_cache['MaxVmafCq'] = best_cq
probe_cache['MaxAchievableVmaf'] = best_score
try:
with open(config['CacheFile'], 'w') as f:
json.dump(list(config['Cache'].values()), f, indent=4)
except:
pass
return best_cq, best_score, max_score, max_score_cq
except Exception as e:
self.log(f"[CRITICAL] Unexpected error in VMAF search: {e}")
import traceback
self.log(traceback.format_exc())
return 26, 0.0, 0.0, 26
finally:
for sample_src in ref_samples:
try:
if sample_src.exists():
sample_src.unlink()
except:
pass
def run_ffmpeg_with_progress(self, args, file_index, total_files, file_duration):
cmd = ['ffmpeg', '-progress', 'pipe:1'] + args
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, universal_newlines=True)
while True:
if self.stop_requested:
process.terminate()
return False
line = process.stdout.readline()
if not line and process.poll() is not None:
break
if line:
if "out_time_us=" in line:
try:
val = int(line.split('=')[1].strip())
current_sec = val / 1000000.0
if file_duration > 0:
pct = current_sec / file_duration
pct = max(0.0, min(1.0, pct))
overall_pct = (file_index + pct) / total_files
self.update_progress(overall_pct)
self.update_status(f"Processing: File {file_index + 1}/{total_files} - {pct * 100:.1f}% ({current_sec:.1f}s / {file_duration:.1f}s)")
except:
pass
elif "Error" in line or "failed" in line:
self.log(f"[FFMPEG] {line.strip()}")
return process.returncode == 0
def optimize_file(self, file_info, config, file_index, total_files):
file_path = Path(file_info['FullName'])
self.log(f"--- [INFO] Processing: {file_path.name} ---")
# 1. Cache Skip
key = str(file_path).lower()
signature = f"{file_info['OldSizeBytes']}|{int(file_path.stat().st_mtime)}"
if config.get('ResumeEnabled') and config.get('Cache'):
cached = config['Cache'].get(key)
if cached and cached.get('Signature') == signature and cached.get('SettingsKey') == config.get('SettingsKey'):
if cached.get('Status') == 'Optimized':
self.log("[SKIP] Found in cache with matching settings (Optimized).")
return {'Success': True, 'Msg': 'Cached Skip', 'NewSize': cached.get('NewSize', file_info['OldSizeBytes']), 'FinalVmaf': cached.get('FinalVmaf', '---')}
else:
reason = cached.get('Reason', 'Failed Previously')
self.log(f"[SKIP] Found in cache with matching settings ({reason}).")
return {'Success': False, 'Msg': f"Cached Fail: {reason}", 'FinalVmaf': '---'}
# 2. Codec-Aware Skip
source_codec = self.get_video_codec(file_path)
target_codec = config['Encoder'].lower()
if config.get('SkipEfficient', True):
if any(c in source_codec for c in self.efficient_codecs):
self.log(f"[SKIP] Source is already efficient ({source_codec}).")
return {'Success': True, 'Msg': 'Already Efficient', 'NewSize': file_info['OldSizeBytes'], 'FinalVmaf': '---'}
res = {'Success': False, 'NewSize': 0, 'Msg': 'Failed', 'FinalVmaf': '---'}
container = config.get('Container', '.mp4')
if container == 'Original': container = file_path.suffix
temp_dir_opt = config.get('TempDir')
if temp_dir_opt:
uid = str(uuid.uuid4())[:8]
temp_out = Path(temp_dir_opt) / f"{file_path.stem}_{uid}.tmp{container}"
else:
temp_out = file_path.with_suffix(f"{file_path.suffix}.tmp{container}")
if config.get('OnSuccess') == 'Replace Original':
final_out = file_path.with_suffix(container)
else:
final_out = file_path.parent / f"{file_path.stem}_opt{container}"
# 3. Hardware Decode Detection
hw_decode_args = []
if 'nvenc' in target_codec: hw_decode_args = ['-hwaccel', 'cuda']
elif 'qsv' in target_codec: hw_decode_args = ['-hwaccel', 'qsv']
elif 'amf' in target_codec: hw_decode_args = ['-hwaccel', 'd3d11va']
# 4. Audio Compatibility Fallback
source_audio = self.get_audio_codec(file_path)
target_audio_opt = config.get('Audio', 'copy')
target_audio_args = []
if target_audio_opt == 'copy':
incompatible = False
if container == '.mp4' and not any(a in source_audio for a in ['aac', 'mp3', 'opus', 'ac3', 'eac3', 'mp2', 'mp1']): incompatible = True
elif container == '.mov' and not any(a in source_audio for a in ['aac', 'mp3', 'ac3', 'eac3', 'alac', 'pcm']): incompatible = True
if incompatible:
self.log(f"[WARN] Audio ({source_audio}) incompatible with {container}. Encoding to AAC.")
target_audio_args = ['-c:a', 'aac', '-b:a', '128k']
else:
target_audio_args = ['-c:a', 'copy']
else:
parts = target_audio_opt.split(' ')
target_audio_args = ['-c:a', parts[0], '-b:a', parts[1]]
# 5. Get duration for progress tracking during encode
duration = self.get_video_duration(file_path)
# 5. Core Processing Loop
if config.get('VmafEnabled'):
vmaf_ladder = config.get('VmafLadder', [config.get('VmafTarget', 93)])
max_achievable_vmaf = 100.0
max_vmaf_cq = None
min_ceiling = config.get('VmafMinCeiling', 85.0)
# Load cached ceiling if available
probe_key = f"codec={config.get('Encoder', 'libx264')}|preset={config.get('Preset', 'medium')}|samples={config.get('VmafSamples', 3)}|dur={config.get('VmafDur', 5)}"
if config.get('CacheEnabled'):
file_cache = config.get('Cache', {}).get(key, {})
if file_cache.get('Signature') == signature:
cached_probe = file_cache.get('VmafProbeCache', {}).get(probe_key, {})
if cached_probe and cached_probe.get('MaxAchievableVmaf', 0.0) > 0:
max_achievable_vmaf = cached_probe.get('MaxAchievableVmaf')
max_vmaf_cq = cached_probe.get('MaxVmafCq')
if max_achievable_vmaf < min_ceiling:
self.log(f"[WARN] Cached absolute Quality ceiling hit. Max achievable VMAF ({max_achievable_vmaf:.1f}) is below minimum floor ({min_ceiling}). Skipping file entirely.")
res['Msg'] = 'Max VMAF < Min VMAF'
else:
for target in vmaf_ladder:
if self.stop_requested: break
if target > max_achievable_vmaf + 0.5:
self.log(f"[SKIP] Skipping VMAF Target {target} (Ceiling is {max_achievable_vmaf:.1f})")
continue
if max_vmaf_cq is not None and abs(target - max_achievable_vmaf) <= 0.5:
self.log(f"[PROBE] Target {target} is close to known ceiling {max_achievable_vmaf:.1f}. Using CQ {max_vmaf_cq}.")
best_cq = max_vmaf_cq
res['FinalVmaf'] = f"{max_achievable_vmaf:.1f}"
else:
best_cq, best_score_val, max_score_val, max_score_cq = self.run_vmaf_search(file_path, config, target, signature)
res['FinalVmaf'] = f"{best_score_val:.1f}"
if max_score_val < min_ceiling:
self.log(f"[WARN] Absolute Quality ceiling hit. Max achievable VMAF ({max_score_val:.1f}) is below minimum floor ({min_ceiling}). Skipping file entirely.")
res['Msg'] = 'Max VMAF < Min VMAF'
break
if max_score_val < target - 0.5:
max_achievable_vmaf = max_score_val
max_vmaf_cq = best_cq
if config.get('VmafFallbackEnabled', False):
self.log(f"[WARN] Quality ceiling hit. Max achievable VMAF: {max_score_val:.1f} (Target: {target}). Fallback Enabled: using CQ {best_cq}.")
res['FinalVmaf'] = f"{max_score_val:.1f}"
else:
self.log(f"[WARN] Quality ceiling hit. Max achievable VMAF: {max_score_val:.1f} (Target: {target}). Skipping target encode.")
continue
self.log(f"[ENCODE] Running final encode (VMAF Target: {target}, CQ: {best_cq})...")
success = self.execute_encode(file_path, temp_out, hw_decode_args, target_audio_args, config, best_cq, file_index, total_files, duration)
if success and temp_out.exists():
val_res = self.validate_output(file_path, temp_out, final_out, file_info, config)
if val_res['Success']:
res.update(val_res)
break
else:
if temp_out.exists(): temp_out.unlink()
self.log(f"[FAIL] VMAF Target {target} yielded larger file or failed validation.")
else:
if temp_out.exists(): temp_out.unlink()
self.log(f"[FAIL] Encoding failed for VMAF Target {target}.")
else:
active_qualities = config.get('QualityLadder', [23, 26, 29])
for q in active_qualities:
if self.stop_requested: break
self.log(f"[ENCODE] Running final encode (CQ: {q})...")
success = self.execute_encode(file_path, temp_out, hw_decode_args, target_audio_args, config, q, file_index, total_files, duration)
if success and temp_out.exists():
val_res = self.validate_output(file_path, temp_out, final_out, file_info, config)
if val_res['Success']:
res.update(val_res)
break
else:
if temp_out.exists(): temp_out.unlink()
else:
if temp_out.exists(): temp_out.unlink()
# 6. Failed Action Handling
if not res['Success']:
try:
on_fail = config.get('OnFail', 'Ignore (Keep Original)')
if "Unoptimizable" in on_fail:
unopt_dir = file_path.parent / "Unoptimizable"
unopt_dir.mkdir(exist_ok=True)
dest = unopt_dir / file_path.name
if file_path.exists():
import shutil
shutil.move(str(file_path), str(dest))
self.log(f"[WARN] Moved failed file to 'Unoptimizable'.")
elif "Delete" in on_fail:
if file_path.exists():
file_path.unlink()
self.log(f"[WARN] Deleted failed file.")
except Exception as e:
self.log(f"[FAIL] Failed to execute OnFail action: {e}")
# 7. Cache Update
if config.get('CacheEnabled') and not self.stop_requested:
cache_entry = config['Cache'].get(key, {})
cache_entry.update({
'Path': str(file_path),
'Signature': signature,
'SettingsKey': config.get('SettingsKey')
})
if not res['Success'] and "Ignore" in config.get('OnFail', 'Ignore'):
cache_entry.update({
'Reason': res.get('Msg', 'Unknown'),
'LastTried': datetime.now().isoformat()
})
config['Cache'][key] = cache_entry
elif res['Success']:
cache_entry.update({
'Status': 'Optimized',
'NewSize': res['NewSize'],
'FinalVmaf': res['FinalVmaf']
})
cache_entry.pop('Reason', None)
cache_entry.pop('LastTried', None)
config['Cache'][key] = cache_entry
try:
with open(config['CacheFile'], 'w') as f:
json.dump(list(config['Cache'].values()), f, indent=4)
except:
pass
return res
def execute_encode(self, file_path, temp_out, hw_decode_args, target_audio_args, config, q, file_index, total_files, file_duration):
target_codec = config['Encoder'].lower()
ff_args = ['-y', '-loglevel', 'info'] + hw_decode_args + ['-i', str(file_path), '-c:v', config['Encoder'], f"-{config['Mode']}", str(q)]
if config.get('Preset') and config.get('Preset') != 'none':
ff_args += ['-preset', config['Preset']]
# NVENC Visual Tuning
if 'nvenc' in target_codec:
ff_args += ['-spatial_aq', '1', '-aq-strength', '8']
ff_args += target_audio_args
ff_args.append(str(temp_out))
return self.run_ffmpeg_with_progress(ff_args, file_index, total_files, file_duration)
def validate_output(self, file_path, temp_out, final_out, file_info, config):
self.log("[VALIDATE] Verifying output integrity...")
new_size = temp_out.stat().st_size
if new_size < file_info['OldSizeBytes']:
in_dur = self.get_video_duration(file_path)
out_dur = self.get_video_duration(temp_out)
if abs(in_dur - out_dur) <= 2.0:
if config.get('OnSuccess') == 'Replace Original':
backup = file_path.with_suffix(f"{file_path.suffix}.bak")
try:
if backup.exists(): backup.unlink()
file_path.rename(backup)
if final_out.exists() and final_out != backup:
final_out.unlink()
temp_out.replace(final_out)
if backup.exists(): backup.unlink()
except Exception as e:
self.log(f"[FAIL] Replacement failed: {e}")
if backup.exists() and not file_path.exists():
backup.rename(file_path)
return {'Success': False, 'Msg': 'Replacement Failed'}
else:
temp_out.replace(final_out)
self.log(f"[SUCCESS] Optimization complete. Saved {(file_info['OldSizeBytes'] - new_size) / 1024 / 1024:.2f} MB")
return {'Success': True, 'NewSize': new_size, 'Msg': 'Optimized'}
else:
self.log("[FAIL] Duration mismatch detected.")
return {'Success': False, 'Msg': 'Duration Mismatch'}
else:
self.log("[FAIL] Output larger than source.")
return {'Success': False, 'Msg': 'Larger than Source'}
def scan_files(self, path, recursive=True):
path = Path(path)
if not path.exists():
return []
files = []
pattern = "**/*" if recursive else "*"
for f in path.glob(pattern):
if f.is_file():
ext = f.suffix.lower()
if ext in self.ignored_extensions:
continue
if ext in self.known_extensions:
files.append({
'Name': f.name,
'FullName': str(f),
'Directory': str(f.parent),
'Extension': f.suffix,
'OldSize': self.format_bytes(f.stat().st_size),
'OldSizeBytes': f.stat().st_size,
'NewSize': '---',
'Saving': '---',
'Status': 'Queued'
})
return files
def format_bytes(self, size):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return f"{size:.2f} {unit}"
size /= 1024.0
return f"{size:.2f} PB"
class VideoOptimizerGUI(ctk.CTk):
def __init__(self):
super().__init__()
self.title("Ultimate Video Optimizer Pro v3.0.0")
self.geometry("1200x900")
self.engine = VideoOptimizerEngine(
logger_callback=self.add_log,
status_callback=self.update_status_label,
progress_callback=self.update_progress
)
self.video_files = []
self.is_processing = False
self.total_saved_bytes = 0
self.total_original_bytes = 0
self.processed_count = 0
# Internal App Data
appdata = os.environ.get('APPDATA')
if appdata:
self.app_dir = Path(appdata) / "Video Optimizer"
else:
self.app_dir = Path.home() / ".Video_Optimizer"
self.config_file = self.app_dir / "config.json"
if not self.app_dir.exists(): self.app_dir.mkdir(parents=True)
self.setup_ui()
self.update_treeview_style()
self.detect_encoders()
self.load_config() # Load after UI setup to populate fields
self.cleanup_orphans()
self.scan_files()
self.protocol("WM_DELETE_WINDOW", self.on_closing)
def on_closing(self):
self.save_config()
if self.is_processing:
self.stop_optimization()
self.add_log("[WARN] Gracefully stopping before exit... Please wait.")
# Wait for thread to finish
for _ in range(30):
if not self.is_processing:
break
self.update()
time.sleep(0.1)
self.destroy()
sys.exit(0)
def setup_ui(self):
# Configure grid layout (1x2)
self.grid_columnconfigure(0, weight=0) # Sidebar
self.grid_columnconfigure(1, weight=1) # Main Content
self.grid_rowconfigure(0, weight=1)
# --- SIDEBAR (SETTINGS) ---
self.sidebar = ctk.CTkScrollableFrame(self, width=400, corner_radius=0)
self.sidebar.grid(row=0, column=0, sticky="nsew", padx=0, pady=0)
self.logo_label = ctk.CTkLabel(self.sidebar, text="VIDEO OPTIMIZER PRO", font=ctk.CTkFont(size=20, weight="bold"))
self.logo_label.pack(pady=(20, 10), padx=20)
self.sub_logo_label = ctk.CTkLabel(self.sidebar, text="Expert FFmpeg Workflow", font=ctk.CTkFont(size=12))
self.sub_logo_label.pack(pady=(0, 20), padx=20)
# 1. SOURCE & ENGINE
self.setup_section_label("1. SOURCE & ENGINE")
self.path_frame = ctk.CTkFrame(self.sidebar, fg_color="transparent")
self.path_frame.pack(fill="x", padx=20, pady=5)
self.entry_path = ctk.CTkEntry(self.path_frame, placeholder_text="Select folder...")
self.entry_path.pack(side="left", fill="x", expand=True, padx=(0, 5))
self.entry_path.insert(0, os.getcwd())
self.btn_browse = ctk.CTkButton(self.path_frame, text="Browse", width=70, command=self.browse_folder)
self.btn_browse.pack(side="right")
self.engine_frame = ctk.CTkFrame(self.sidebar, fg_color="transparent")
self.engine_frame.pack(fill="x", padx=20, pady=5)
self.lbl_encoder = ctk.CTkLabel(self.engine_frame, text="Encoder", font=ctk.CTkFont(size=10))
self.lbl_encoder.grid(row=0, column=0, sticky="w")
self.combo_encoder = ctk.CTkComboBox(self.engine_frame, values=["Detecting..."], command=self.on_encoder_change)
self.combo_encoder.grid(row=1, column=0, sticky="ew", padx=(0, 5))
self.lbl_container = ctk.CTkLabel(self.engine_frame, text="Container", font=ctk.CTkFont(size=10))
self.lbl_container.grid(row=0, column=1, sticky="w")
self.combo_container = ctk.CTkComboBox(self.engine_frame, values=["MP4", "MKV", "MOV", "Original"])
self.combo_container.grid(row=1, column=1, sticky="ew", padx=(5, 0))
self.combo_container.set("MP4")
self.engine_frame.grid_columnconfigure(0, weight=1)
self.engine_frame.grid_columnconfigure(1, weight=1)
self.chk_recursive = ctk.CTkCheckBox(self.sidebar, text="Recursive Scan")
self.chk_recursive.pack(padx=20, pady=(15, 5), anchor="w")
self.chk_recursive.select()
self.chk_skip_efficient = ctk.CTkCheckBox(self.sidebar, text="Skip Efficient Codecs (HEVC/AV1)")
self.chk_skip_efficient.pack(padx=20, pady=5, anchor="w")
self.chk_skip_efficient.select()
self.chk_vmaf = ctk.CTkCheckBox(self.sidebar, text="Enable Advanced VMAF", text_color="#2DA44E", font=ctk.CTkFont(weight="bold"), command=self.toggle_vmaf_card)
self.chk_vmaf.pack(padx=20, pady=5, anchor="w")
self.chk_vmaf.select()
# 2. VMAF TUNING / MANUAL
self.vmaf_card = ctk.CTkFrame(self.sidebar)
self.vmaf_card.pack(fill="x", padx=20, pady=10)
self.setup_card_label(self.vmaf_card, "2. ADVANCED VMAF TUNING")
self.vmaf_chk_frame = ctk.CTkFrame(self.vmaf_card, fg_color="transparent")
self.vmaf_chk_frame.pack(fill="x", padx=10, pady=0)
self.chk_vmaf_fallback = ctk.CTkCheckBox(self.vmaf_chk_frame, text="Encode with Max VMAF as Fallback")
self.chk_vmaf_fallback.pack(anchor="w", pady=5)
self.chk_vmaf_fallback.select()
self.chk_vmaf_ladder = ctk.CTkCheckBox(self.vmaf_chk_frame, text="Enable Stepping Target", command=self.toggle_vmaf_ladder)
self.chk_vmaf_ladder.pack(anchor="w", pady=5)
self.vmaf_ceil_frame = ctk.CTkFrame(self.vmaf_card, fg_color="transparent")
self.vmaf_ceil_frame.pack(fill="x", padx=10, pady=(5, 2))
ctk.CTkLabel(self.vmaf_ceil_frame, text="Minimum VMAF Ceiling", font=ctk.CTkFont(size=10)).pack(side="left")
self.lbl_vmaf_ceiling_val = ctk.CTkLabel(self.vmaf_ceil_frame, text="85", font=ctk.CTkFont(weight="bold"))
self.lbl_vmaf_ceiling_val.pack(side="right")
self.slider_vmaf_ceiling = ctk.CTkSlider(self.vmaf_card, from_=0, to=100, number_of_steps=100, command=self.update_vmaf_ceiling_label)
self.slider_vmaf_ceiling.pack(fill="x", padx=10, pady=(0, 5))
self.slider_vmaf_ceiling.set(85)
self.vmaf_target_frame = ctk.CTkFrame(self.vmaf_card, fg_color="transparent")
self.vmaf_target_frame.pack(fill="x", padx=10, pady=2)
ctk.CTkLabel(self.vmaf_target_frame, text="Target Quality (VMAF)", font=ctk.CTkFont(size=10)).pack(side="left")
self.lbl_vmaf_val = ctk.CTkLabel(self.vmaf_target_frame, text="93", font=ctk.CTkFont(weight="bold"), text_color="#2DA44E")
self.lbl_vmaf_val.pack(side="right")
self.slider_vmaf = ctk.CTkSlider(self.vmaf_card, from_=70, to=100, number_of_steps=30, command=self.update_vmaf_label)
self.slider_vmaf.pack(fill="x", padx=10, pady=5)
self.slider_vmaf.set(93)
self.lbl_vmaf_ladder_text = ctk.CTkLabel(self.vmaf_card, text="VMAF Target Ladder (Space/Comma Separated)", font=ctk.CTkFont(size=10))
self.entry_vmaf_ladder = ctk.CTkEntry(self.vmaf_card, placeholder_text="95 93 91")
self.entry_vmaf_ladder.insert(0, "93")
self.vmaf_opt_frame = ctk.CTkFrame(self.vmaf_card, fg_color="transparent")
self.vmaf_opt_frame.pack(fill="x", padx=10, pady=5)
self.combo_samples = ctk.CTkComboBox(self.vmaf_opt_frame, values=["1 Sample", "3 Samples (Balanced)", "5 Samples"])
self.combo_samples.set("3 Samples (Balanced)")
self.combo_samples.pack(side="left", fill="x", expand=True, padx=(0, 2))
self.combo_probe = ctk.CTkComboBox(self.vmaf_opt_frame, values=["3 Seconds", "5 Seconds", "10 Seconds"])
self.combo_probe.set("5 Seconds")
self.combo_probe.pack(side="right", fill="x", expand=True, padx=(2, 0))
self.manual_card = ctk.CTkFrame(self.sidebar)
# Hidden initially
self.setup_card_label(self.manual_card, "2. MANUAL QUALITY LADDER")
self.entry_ladder = ctk.CTkEntry(self.manual_card, placeholder_text="23,26,29")
self.entry_ladder.insert(0, "23,26,29")
self.entry_ladder.pack(fill="x", padx=10, pady=5)
ctk.CTkLabel(self.manual_card, text="Speed Preset", font=ctk.CTkFont(size=10)).pack(padx=10, anchor="w")
self.combo_preset = ctk.CTkComboBox(self.manual_card, values=["medium"])
self.combo_preset.pack(fill="x", padx=10, pady=5)
# 3. AUDIO & SKIP LOGIC
self.setup_section_label("3. AUDIO & SKIP LOGIC")
self.combo_audio = ctk.CTkComboBox(self.sidebar, values=["Copy (Original)", "AAC (128k)", "AAC (192k)"])
self.combo_audio.set("Copy (Original)")
self.combo_audio.pack(fill="x", padx=20, pady=5)
# 4. SESSION OPTIONS
self.setup_section_label("4. SESSION OPTIONS")
self.lbl_on_success = ctk.CTkLabel(self.sidebar, text="On Success", font=ctk.CTkFont(size=10))
self.lbl_on_success.pack(padx=20, anchor="w")
self.combo_on_success = ctk.CTkComboBox(self.sidebar, values=["Replace Original", "Keep Original (Add _opt)"])
self.combo_on_success.set("Replace Original")
self.combo_on_success.pack(fill="x", padx=20, pady=5)
self.lbl_on_fail = ctk.CTkLabel(self.sidebar, text="On Failure", font=ctk.CTkFont(size=10))
self.lbl_on_fail.pack(padx=20, anchor="w")
self.combo_on_fail = ctk.CTkComboBox(self.sidebar, values=["Move to 'Unoptimizable'", "Delete File", "Ignore (Keep Original)"])
self.combo_on_fail.set("Move to 'Unoptimizable'")
self.combo_on_fail.pack(fill="x", padx=20, pady=5)
self.chk_resume = ctk.CTkCheckBox(self.sidebar, text="Enable Resume Functionality")
self.chk_resume.pack(padx=20, pady=(15, 5), anchor="w")
self.chk_resume.select()
self.chk_cache = ctk.CTkCheckBox(self.sidebar, text="Enable Cache")
self.chk_cache.pack(padx=20, pady=5, anchor="w")
self.chk_cache.select()
self.chk_log = ctk.CTkCheckBox(self.sidebar, text="Enable Log")
self.chk_log.pack(padx=20, pady=5, anchor="w")
self.chk_log.select()
# --- MAIN CONTENT ---
self.main_frame = ctk.CTkFrame(self, corner_radius=0, fg_color="transparent")
self.main_frame.grid(row=0, column=1, sticky="nsew", padx=30, pady=30)
self.main_frame.grid_rowconfigure(1, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
# Stats Dashboard
self.stats_frame = ctk.CTkFrame(self.main_frame, fg_color="transparent")
self.stats_frame.grid(row=0, column=0, sticky="ew", pady=(0, 20))
for i in range(4): self.stats_frame.grid_columnconfigure(i, weight=1)
self.stat_files = self.create_stat_card(self.stats_frame, 0, "FILES", "0")
self.stat_saved = self.create_stat_card(self.stats_frame, 1, "SAVED", "0 MB", color="#2DA44E")
self.stat_eff = self.create_stat_card(self.stats_frame, 2, "EFFICIENCY", "0%", color="#0969DA")
self.stat_vmaf = self.create_stat_card(self.stats_frame, 3, "VMAF", "---")
# File List
self.table_frame = ctk.CTkFrame(self.main_frame)
self.table_frame.grid(row=1, column=0, sticky="nsew")