-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideocompress.py
More file actions
958 lines (791 loc) · 37.9 KB
/
videocompress.py
File metadata and controls
958 lines (791 loc) · 37.9 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
import sys
import subprocess
import time
import os
import re
import math
import json
import threading
import tempfile
import shutil
from pathlib import Path
from typing import Tuple, Optional, List
# --- Constants ---
MB_TO_BYTES = 1024 * 1024
MB_TO_BITS = 8 * 1024 * 1024
BITRATE_SAFETY_FACTOR = 0.90
MIN_BPP = 0.04 # Target Bits Per Pixel threshold
LOG_FILES_TO_CLEAN = ["ffmpeg2pass.log", "ffmpeg2pass-0.log", "ffmpeg2pass-0.log.mbtree"]
ENCODER_PRIORITY = {
"hevc": {
"win32": ["hevc_nvenc", "hevc_amf", "hevc_qsv"],
"linux": ["hevc_nvenc", "hevc_vaapi"],
"darwin": ["hevc_videotoolbox"],
"fallback": "libx265"
},
"h264": {
"win32": ["h264_nvenc", "h264_amf", "h264_qsv"],
"linux": ["h264_nvenc", "h264_vaapi"],
"darwin": ["h264_videotoolbox"],
"fallback": "libx264"
}
}
# Create a generic chain for unknown OSes by combining all platform-specific encoders
for codec, config in ENCODER_PRIORITY.items():
# Use dict.fromkeys to preserve order and remove duplicates
win: List[str] = config.get('win32', []) # type: ignore
lin: List[str] = config.get('linux', []) # type: ignore
mac: List[str] = config.get('darwin', []) # type: ignore
all_encoders: List[str] = win + lin + mac
generic_chain: List[str] = list(dict.fromkeys(all_encoders))
config['other'] = generic_chain
# --- Helpers ---
def format_progress(prog: float, fps: float, bitrate_k: int, speed: float, eta_sec: float) -> str:
"""Standardize progress printing format across encoders.
Args:
prog: Percentage progress (0-100).
fps: Current frames per second processed.
bitrate_k: Target bitrate in kbps.
speed: Encoding speed multiplier (e.g., 1.5x).
eta_sec: Estimated time remaining in seconds.
Returns:
A formatted string suitable for carriage-return printing.
"""
eta_str = f"{int(eta_sec//60)}m{int(eta_sec%60)}s" if eta_sec < 3600 else f"{int(eta_sec//3600)}h{int((eta_sec%3600)//60)}m"
return f"Prog: {prog:5.1f}% | FPS: {fps:5.1f} | Bitrate: {bitrate_k:4d}k | Speed: {speed:4.2f}x | ETA: {eta_str:7s}"
def get_resource_path(filename: str) -> str:
"""Resolve the absolute path to bundled resources.
Args:
filename: Base executable or file name (e.g., "ffmpeg").
Returns:
Absolute path to the resource, respecting PyInstaller bundling.
"""
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
base_path = sys._MEIPASS # type: ignore
if sys.platform == 'win32' and not filename.lower().endswith('.exe'):
filename = f"{filename}.exe"
return os.path.join(base_path, filename)
return filename
def get_file_size(file_path: str) -> int:
"""Return the file size in bytes.
Args:
file_path: Path to the file.
Returns:
File size in bytes.
"""
return os.path.getsize(file_path)
def format_size(size_bytes: int) -> str:
"""Format a byte count as a human-readable string.
Args:
size_bytes: Size value in bytes.
Returns:
A concise human-readable string (B, KB, MB).
"""
if size_bytes < 1024: return f"{size_bytes} B"
elif size_bytes < MB_TO_BYTES: return f"{size_bytes/1024:.2f} KB"
else: return f"{size_bytes/MB_TO_BYTES:.2f} MB"
def clean_log_file(prefixes: Optional[List[str]] = None) -> None:
"""Remove temporary FFmpeg log files.
Args:
prefixes: Optional list of 2-pass log prefixes to clean as well.
"""
for log_file in LOG_FILES_TO_CLEAN:
try:
if os.path.exists(log_file): os.remove(log_file)
except OSError: pass
prefixes_list: List[str] = prefixes if prefixes else [] # type: ignore
for p in prefixes_list:
for ext in ["-0.log", "-0.log.mbtree"]:
try:
log_path = f"{p}{ext}"
if os.path.exists(log_path): os.remove(log_path)
except OSError: pass
def check_encoder_available(encoder_name: str) -> bool:
"""Check if a specific FFmpeg encoder can be used.
Args:
encoder_name: FFmpeg encoder name (e.g., "hevc_nvenc").
Returns:
True if a short test encode succeeds, else False.
"""
ffmpeg_exe = get_resource_path("ffmpeg")
try:
# VAAPI often requires hwupload for software sources
is_vaapi = "vaapi" in encoder_name
vf_args = ["-vf", "format=nv12,hwupload"] if is_vaapi else []
pre_args = ["-init_hw_device", "vaapi"] if is_vaapi else []
cmd = [ffmpeg_exe, "-hide_banner", "-v", "error"] + pre_args + [
"-f", "lavfi", "-i", "color=c=black:s=1280x720:r=1:d=0.1",
"-vframes", "1", "-c:v", encoder_name
] + vf_args + ["-f", "null", "-"]
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
return True
except (subprocess.CalledProcessError, FileNotFoundError, OSError):
return False
def select_best_encoder(codec_type: str = "hevc") -> str:
"""Detect the best available encoder based on OS and Hardware.
This function checks for hardware encoders in a preferred order based on
the operating system and configured codec type (H.264 or HEVC).
Args:
codec_type: "hevc" or "h264".
Returns:
The name of the best available FFmpeg encoder.
Raises:
ValueError: If the configured `codec_type` is invalid.
"""
codec_config = ENCODER_PRIORITY.get(codec_type)
if not codec_config:
raise ValueError(f"Invalid codec_type: {codec_type}")
if sys.platform.startswith("linux"):
platform_key = "linux"
elif sys.platform == "darwin":
platform_key = "darwin"
elif sys.platform == "win32":
platform_key = "win32"
else:
platform_key = "other"
if platform_key in codec_config:
priority_chain = codec_config[platform_key]
else:
priority_chain = codec_config["other"]
fallback = codec_config["fallback"]
print(f"OS: {sys.platform}. Codec: {codec_type}. Checking encoders: {', '.join(priority_chain)}...")
for enc in priority_chain:
is_available = check_encoder_available(enc)
print(f" {enc}: {'Available' if is_available else 'Unavailable'}")
if is_available:
return enc
print(f" No hardware encoder found. Fallback to CPU ({fallback}).")
if isinstance(fallback, list):
return str(fallback[0])
return str(fallback)
def get_video_info(input_path: str) -> Optional[Tuple[float, int, float, int, int, int]]:
"""Probe video metadata.
Args:
input_path: Path to the input media file.
Returns:
Tuple of (duration_seconds, file_size_bytes, fps, audio_kbps, width, height), or None on failure.
"""
ffprobe_exe = get_resource_path("ffprobe")
try:
# Get metadata as JSON
cmd = [ffprobe_exe, "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=width,height,avg_frame_rate",
"-show_entries", "format=duration", "-of", "json", input_path]
res = json.loads(subprocess.check_output(cmd, text=True))
v_stream = res['streams'][0]
width = int(v_stream.get('width', 0))
height = int(v_stream.get('height', 0))
dur_out = res['format'].get('duration', 0)
fps_val = v_stream.get('avg_frame_rate', '30/1')
if '/' in fps_val:
num, den = map(int, fps_val.split('/'))
fps = num / den if den > 0 else 30
else:
fps = float(fps_val)
# Audio probe
cmd_aud = [ffprobe_exe, "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=bit_rate", "-of", "default=noprint_wrappers=1:nokey=1", input_path]
try:
aud_out = subprocess.check_output(cmd_aud, text=True).strip()
audio_bps = int(aud_out) if aud_out.isdigit() else 128000
except subprocess.CalledProcessError:
audio_bps = 128000 # Default if no audio stream found or probe fails
return float(dur_out), get_file_size(input_path), fps, math.ceil(audio_bps / 1000), width, height
except (subprocess.CalledProcessError, ValueError, OSError, KeyError, IndexError):
return None
def get_smart_split_point(input_path: str, duration: float) -> float:
"""Find a keyframe-aligned split point near the middle.
Args:
input_path: Path to the input media file.
duration: Total duration in seconds.
Returns:
Timestamp in seconds to split the encode. Falls back to duration/2
if keyframe analysis fails or no suitable keyframe is found.
"""
print("Analyzing for Smart Split point...")
try:
cmd = [get_resource_path("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time,size,flags", "-of", "json", input_path]
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
packets = json.loads(res.stdout).get('packets', [])
target = sum(int(p.get('size', 0)) for p in packets) / 2
curr, last_k = 0, 0.0
for p in packets:
curr += int(p.get('size', 0))
if 'K' in p.get('flags', ''): last_k = float(p.get('pts_time', 0))
if curr >= target: return last_k if last_k > 0 else duration/2
except Exception as e:
sys.stderr.write(f"Warning: Smart split analysis failed ({e}). Falling back to midpoint.\n")
return duration / 2
def get_optimal_settings(target_mb: int, duration: float, width: int, height: int, fps: float) -> Tuple[int, float]:
"""Determine optimal resolution and frame rate based on bits-per-pixel threshold.
Prioritizes maintaining 60+ FPS for gaming content while ensuring visual
quality stays above MIN_BPP threshold.
Args:
target_mb: Target file size in megabytes.
duration: Video duration in seconds.
width: Source video width in pixels.
height: Source video height in pixels.
fps: Source video frame rate.
Returns:
Tuple of (target_height, target_fps). Values will never exceed source
dimensions. Returns source values if no scaling is needed.
"""
target_bits = target_mb * MB_TO_BITS
aspect_ratio = width / height
height_options = [2160, 1440, 1080, 720]
fps_options = [120.0, 90.0, 60.0]
# 1. Filter Options (Never Upscale)
valid_heights = [h for h in height_options if h <= height]
# Ensure if source is 1080p, 1440p is invalid.
if height not in valid_heights: valid_heights.insert(0, height)
valid_fps = [f for f in fps_options if f <= fps]
if fps not in valid_fps: valid_fps.insert(0, fps)
# 2. Generate All Valid Candidates (BPP >= Floor)
candidates = [] # List of tuples: (fps_priority, pixels_throughput, h, f)
for h in valid_heights:
# Calculate width maintaining aspect ratio (approx) for pixel math
w = int(h * aspect_ratio)
for f in valid_fps:
pixels_per_sec = w * h * f
if pixels_per_sec == 0: continue
bpp = target_bits / (duration * pixels_per_sec)
if bpp >= MIN_BPP:
# Priority Logic:
# 1. FPS Priority: True if FPS >= 60. (Gaming preference)
# 2. Throughput: Resolution * FPS (General quality metric)
fps_priority = (f >= 60)
candidates.append((fps_priority, pixels_per_sec, h, f))
# 3. Sort Logic
if candidates:
# Sort by:
# Primary: FPS >= 60 (True > False)
# Secondary: Throughput (Higher is better)
candidates.sort(key=lambda x: (x[0], x[1]), reverse=True)
best = candidates[0]
# If the best option is basically the source, return source values to avoid filter overhead
if best[2] == height and best[3] == fps:
return height, fps
return best[2], best[3]
# Fallback: Smallest possible valid config
return valid_heights[-1], valid_fps[-1]
# --- Progress Tracking ---
class ProgressTracker:
"""Track progress for two parallel encoding segments.
Attributes:
dur_a: Duration of first segment in seconds.
dur_b: Duration of second segment in seconds.
total_dur: Combined duration of both segments.
time_a: Current encoded time for first segment.
time_b: Current encoded time for second segment.
fps_a: Current FPS for first segment encoder.
fps_b: Current FPS for second segment encoder.
spd_a: Current speed multiplier for first segment.
spd_b: Current speed multiplier for second segment.
lock: Threading lock for thread-safe updates.
"""
dur_a: float
dur_b: float
total_dur: float
time_a: float
time_b: float
fps_a: float
fps_b: float
spd_a: float
spd_b: float
lock: threading.Lock
def __init__(self, duration_a: float, duration_b: float) -> None:
"""Initialize the progress tracker.
Args:
duration_a: Duration of first segment in seconds.
duration_b: Duration of second segment in seconds.
"""
self.dur_a, self.dur_b = duration_a, duration_b
self.total_dur = duration_a + duration_b
self.time_a = self.time_b = 0.0
self.fps_a = self.fps_b = 0.0
self.spd_a = self.spd_b = 0.001
self.lock = threading.Lock()
def update(self, is_a: bool, time_val: float, fps_val: float, speed_val: float) -> None:
"""Update stats for a segment.
Args:
is_a: True for first segment, False for second.
time_val: Last parsed encode time in seconds.
fps_val: Current frames per second.
speed_val: Current encode speed multiplier.
"""
with self.lock:
if is_a:
self.time_a = time_val
if fps_val: self.fps_a = fps_val
if speed_val: self.spd_a = speed_val
else:
self.time_b = time_val
if fps_val: self.fps_b = fps_val
if speed_val: self.spd_b = speed_val
def get_stats(self) -> Tuple[float, float, int]:
"""Compute aggregate progress, fps, and ETA.
Returns:
Tuple of (progress_percent, total_fps, eta_seconds).
"""
with self.lock:
t_a = self.time_a if self.time_a < self.dur_a else self.dur_a
t_b = self.time_b if self.time_b < self.dur_b else self.dur_b
prog_val = ((t_a + t_b) / self.total_dur) * 100.0
prog = prog_val if prog_val < 100.0 else 100.0
fps = self.fps_a + self.fps_b
rem_a = (self.dur_a - self.time_a) if self.dur_a > self.time_a else 0.0
rem_b = (self.dur_b - self.time_b) if self.dur_b > self.time_b else 0.0
eta_a = rem_a / self.spd_a if self.spd_a > 0 else 0.0
eta_b = rem_b / self.spd_b if self.spd_b > 0 else 0.0
eta = eta_a if eta_a > eta_b else eta_b
return float(prog), float(fps), int(eta)
def monitor_process(process: subprocess.Popen[str], tracker: ProgressTracker, is_a: bool) -> None:
"""Monitor an FFmpeg process and update progress.
Reads FFmpeg's stderr output character by character, parses progress
information (time, fps, speed), and updates the shared tracker.
Args:
process: Running FFmpeg process (stderr expected with progress lines).
tracker: Shared tracker to update.
is_a: True if this process represents the first segment.
"""
re_time = re.compile(r'time=\s*(\d+:\d+:\d+\.\d+)')
re_fps = re.compile(r'fps=\s*(\d+\.?\d*)')
re_speed = re.compile(r'speed=\s*(\d+\.?\d*)x')
buf = ""
while True:
char = process.stderr.read(1) # type: ignore
if not char: break
if char in ('\r', '\n'):
if buf.strip():
try:
t_match = re_time.search(buf)
f_match = re_fps.search(buf)
s_match = re_speed.search(buf)
if t_match:
h, m, s = map(float, t_match.group(1).split(':'))
secs = h*3600 + m*60 + s
fps = float(f_match.group(1)) if f_match else 0.0
spd = float(s_match.group(1)) if s_match else 0.001
tracker.update(is_a, secs, fps, spd)
except (ValueError, AttributeError, IndexError): pass
buf = ""
else:
buf += char
# --- Main Logic ---
def encode_single_pass_hw(
ffmpeg_exe: str,
input_path: str,
output_path: str,
encoder: str,
codec_type: str,
bitrate_k: int,
fps: float,
duration: float,
tgt_h: int,
tgt_fps: float
) -> bool:
"""Encode using a single pass for non-NVENC paths.
Args:
ffmpeg_exe: Path to the ffmpeg executable.
input_path: Source video path.
output_path: Destination video path.
encoder: FFmpeg video encoder name.
bitrate_k: Target video bitrate in kbps.
fps: Input frames per second.
duration: Total duration in seconds (for progress reporting).
tgt_h: Target height for scaling.
tgt_fps: Target frames per second.
Returns:
True on success, False on failure.
"""
cmd = build_single_pass_cmd(
ffmpeg_exe=ffmpeg_exe,
input_path=input_path,
encoder=encoder,
codec_type=codec_type,
bitrate_k=bitrate_k,
src_fps=fps,
start=None,
end=None,
output_path=output_path,
tgt_h=tgt_h,
tgt_fps=tgt_fps)
process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, encoding='utf-8', errors='ignore', bufsize=0)
# Simple single-process monitor
pat_str = r'frame=\s*(\d+).*?fps=\s*(\d+\.?\d*).*?time=(\d+:\d+:\d+\.\d+).*?speed=\s*(\d+\.?\d*)x'
buf = ""
last_speed = 0.001
try:
while True:
char = process.stderr.read(1) # type: ignore
if not char: break
if char == '\r' or char == '\n':
match = re.search(pat_str, buf)
if match:
cur_fps = float(match.group(2)) if match.group(2) else 0
h, m, s = map(float, match.group(3).split(':'))
cur_time = h * 3600 + m * 60 + s
speed = float(match.group(4)) if match.group(4) else last_speed
if speed > 0: last_speed = speed
prog = min(100, (cur_time / duration) * 100)
eta = max(0.0, duration - cur_time) / float(last_speed)
if speed != 0.001: # Only print if we have real speed data
print(f"\r{format_progress(prog, cur_fps, bitrate_k, speed, eta)} ", end="")
buf = ""
else:
buf += char
finally:
process.wait()
print()
return process.returncode == 0
def build_single_pass_cmd(
ffmpeg_exe: str,
input_path: str,
encoder: str,
codec_type: str,
bitrate_k: int,
src_fps: float,
start: Optional[float],
end: Optional[float],
output_path: str,
tgt_h: int,
tgt_fps: float
) -> List[str]:
"""Build a single-pass FFmpeg command for the requested encoder.
Args:
ffmpeg_exe: Path to the ffmpeg executable.
input_path: Source video path.
encoder: FFmpeg encoder name.
bitrate_k: Target bitrate in kbps.
src_fps: Source frames per second.
start: Optional start time for segmenting.
end: Optional end time for segmenting.
output_path: Destination video path.
tgt_h: Target height for scaling. Uses -2:height format to ensure
even width. Set to 0 or equal to source height to skip scaling.
tgt_fps: Target frames per second. Set equal to src_fps to skip
FPS conversion.
Returns:
A command list ready for subprocess execution.
"""
cmd: List[str] = [ffmpeg_exe, "-y"]
filters = []
if "vaapi" in encoder:
cmd.extend(["-init_hw_device", "vaapi"])
if start is not None:
cmd.extend(["-ss", str(start)])
if end is not None:
cmd.extend(["-to", str(end)])
cmd.extend(["-i", input_path])
# Build Filters
if tgt_fps < src_fps: filters.append(f"fps={tgt_fps}")
# Scale Filter: -2:height ensures width is even (divisible by 2) while keeping aspect ratio
# If using -1, encoders often fail with odd pixel counts (e.g. 853x480). -2 gives 854x480.
if tgt_h > 0: filters.append(f"scale=-2:{tgt_h}")
# Encoder Specific Filter Chains
if "vaapi" in encoder:
filters.append("format=nv12,hwupload")
cmd.extend(["-vf", ",".join(filters)] if filters else ["-vf", "format=nv12,hwupload"])
elif encoder == "libx265":
# x265 requires fps filter sometimes for retiming
if not any("fps" in f for f in filters): filters.append(f"fps={src_fps}")
cmd.extend(["-vf", ",".join(filters)])
elif encoder == "libx264":
if not any("fps" in f for f in filters): filters.append(f"fps={src_fps}")
cmd.extend(["-vf", ",".join(filters)])
else:
if filters: cmd.extend(["-vf", ",".join(filters)])
cmd.extend(["-c:v", encoder, "-b:v", f"{bitrate_k}k"])
if "amf" in encoder:
cmd.extend(["-usage", "transcoding", "-quality", "balanced", "-rc", "cbr"])
elif "qsv" in encoder:
if "hevc" in encoder: cmd.extend(["-load_plugin", "hevc_hw"])
cmd.extend(["-preset", "medium"])
elif "videotoolbox" in encoder:
cmd.extend(["-allow_sw", "1", "-realtime", "0"])
elif encoder == "libx265":
cmd.extend(["-preset", "medium"])
elif encoder == "libx264":
cmd.extend(["-preset", "medium"])
if codec_type == "hevc": cmd.extend(["-tag:v", "hvc1"])
elif codec_type == "h264": cmd.extend(["-tag:v", "avc1"])
cmd.extend(["-maxrate:v", f"{bitrate_k}k", "-bufsize:v", f"{bitrate_k*2}k"])
cmd.extend(["-c:a", "copy", "-loglevel", "error", "-stats", output_path])
return cmd
def encode_split_single_pass_hw(
ffmpeg_exe: str,
input_path: str,
output_path: str,
encoder: str,
codec_type: str,
bitrates_k: Tuple[int, int],
fps: float,
durations: Tuple[float, float],
split_time: float,
tgt_h: int,
tgt_fps: float
) -> Tuple[bool, str]:
"""Run split single-pass encoding for hardware encoders other than NVENC.
Args:
ffmpeg_exe: Path to the ffmpeg executable.
input_path: Source video path.
output_path: Destination file path.
encoder: Active hardware encoder name (e.g., 'hevc_vaapi').
bitrates_k: Tuple of (first_segment_kbps, second_segment_kbps).
fps: Source frames per second (used for progress calculation).
durations: Tuple of (first_segment_duration, second_segment_duration)
in seconds.
split_time: Timestamp in seconds marking the segment boundary.
tgt_h: Target height for scaling (0 to skip scaling).
tgt_fps: Target frames per second.
Returns:
Tuple of (success flag, error message when unsuccessful).
"""
with tempfile.TemporaryDirectory(prefix="vidcomp_hw_") as temp_dir:
p1_path = os.path.join(temp_dir, "p1.mp4")
p2_path = os.path.join(temp_dir, "p2.mp4")
list_path = os.path.join(temp_dir, "list.txt")
try:
cmd_a = build_single_pass_cmd(ffmpeg_exe, input_path, encoder, codec_type, bitrates_k[0], fps, 0.0, float(split_time), p1_path, tgt_h, tgt_fps)
cmd_b = build_single_pass_cmd(ffmpeg_exe, input_path, encoder, codec_type, bitrates_k[1], fps, float(split_time), None, p2_path, tgt_h, tgt_fps)
pa = subprocess.Popen(cmd_a, stderr=subprocess.PIPE, text=True, bufsize=0)
pb = subprocess.Popen(cmd_b, stderr=subprocess.PIPE, text=True, bufsize=0)
tracker = ProgressTracker(durations[0], durations[1])
t1 = threading.Thread(target=monitor_process, args=(pa, tracker, True))
t2 = threading.Thread(target=monitor_process, args=(pb, tracker, False))
t1.start(); t2.start()
while pa.poll() is None or pb.poll() is None:
prog, fps_total, eta = tracker.get_stats()
speed = fps_total / fps if fps > 0 else 0
print(f"\rProg: {prog:.1f}% | FPS: {fps_total:.1f} | Speed: {speed:.2f}x | ETA: {eta//3600:02}:{(eta%3600)//60:02}:{eta%60:02} ", end="")
time.sleep(0.5)
t1.join(); t2.join()
if pa.returncode != 0 or pb.returncode != 0:
return False, "Split encode failed"
print("\nStitching...")
with open(list_path, "w") as lf:
lf.write(f"file '{p1_path}'\nfile '{p2_path}'")
try:
subprocess.run([ffmpeg_exe, "-f", "concat", "-safe", "0", "-i", list_path, "-c", "copy", "-y", output_path], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception as e:
return False, f"Stitching failed: {e}"
return True, ""
except Exception as e:
return False, f"Split single-pass error: {e}"
def compress_video(input_path: str, output_path: Optional[str] = None, target_size_mb: int = 100, codec_type: str = "hevc") -> Tuple[bool, str]:
"""Compress a video to an approximate target size.
Chooses the best available encoder and uses either a parallel 2-pass split
(NVENC), a split single-pass for other hardware encoders, or a single
unsplit pass for CPU (libx265).
Args:
input_path: Path to the input video.
output_path: Optional output path.
target_size_mb: Desired approximate size in megabytes.
codec_type: "hevc" or "h264".
Returns:
Tuple of (success, output_path_or_error_message).
"""
start_t = time.time()
ffmpeg_exe = get_resource_path("ffmpeg")
clean_log_file()
if not os.path.exists(input_path): return False, f"Input not found: {input_path}"
info = get_video_info(input_path)
if not info: return False, f"Failed to extract video info from: {input_path}"
duration, orig_bytes, fps, audio_kbps, src_w, src_h = info
if (orig_bytes / MB_TO_BYTES) <= target_size_mb:
return False, f"Already smaller: {orig_bytes/MB_TO_BYTES:.2f} MB"
if output_path is None:
output_path = str(Path(input_path).with_name(f"{Path(input_path).stem}_{target_size_mb}MB{Path(input_path).suffix}"))
# Decision Algorithm: Optimize Res/FPS
opt_h, opt_fps = get_optimal_settings(target_size_mb, duration, src_w, src_h, fps)
# Calculate opt_w just for logging (approx)
opt_w_log = int(opt_h * (src_w/src_h))
if opt_h != src_h or opt_fps != fps:
print(f"Optimizing: {src_w}x{src_h}@{fps:.2f} -> ~{opt_w_log}x{opt_h}@{opt_fps:.2f}")
active_encoder = select_best_encoder(codec_type)
print(f"Active Encoder: {active_encoder}")
# --- NVENC / AMF (Windows) PARALLEL 2-PASS ---
if "nvenc" in active_encoder or ("amf" in active_encoder and sys.platform == "win32"):
split_time = get_smart_split_point(input_path, duration)
print(f"Splitting at {split_time:.2f}s")
durs = [split_time, duration - split_time]
brs = []
tgt_part_mb = target_size_mb / 2
for d in durs:
audio_mb = (audio_kbps * d * 1000) / 8 / MB_TO_BYTES
video_mb = max(0.5, tgt_part_mb - audio_mb)
br_k = math.floor(((video_mb * MB_TO_BITS) / d / 1000) * BITRATE_SAFETY_FACTOR)
brs.append(br_k)
print(f"Worker 1: {brs[0]}k | Worker 2: {brs[1]}k")
with tempfile.TemporaryDirectory(prefix="vidcomp_") as temp_dir:
p1_path = os.path.join(temp_dir, "p1.mp4")
p2_path = os.path.join(temp_dir, "p2.mp4")
list_path = os.path.join(temp_dir, "list.txt")
log_a = os.path.join(temp_dir, "log_part1")
log_b = os.path.join(temp_dir, "log_part2")
try:
# Build filters for NVENC
filters = []
if opt_fps < fps: filters.append(f"fps={opt_fps}")
if opt_h < src_h: filters.append(f"scale=-2:{opt_h}")
if "nvenc" in active_encoder:
hw_accel = ["-hwaccel", "cuda"]
enc_params = ["-preset", "p5"]
else:
hw_accel = ["-hwaccel", "auto"]
enc_params = ["-usage", "transcoding", "-quality", "quality"]
base = [ffmpeg_exe] + hw_accel + ["-y", "-hide_banner", "-loglevel", "error", "-stats"]
vf_args = ["-vf", ",".join(filters)] if filters else []
# PASS 1
print("Parallel Pass 1/2: Analysis...")
cmd_a1 = base + ["-ss", "0", "-to", str(split_time), "-i", input_path] + vf_args + ["-c:v", active_encoder] + enc_params + [
"-b:v", f"{brs[0]}k", "-maxrate:v", f"{brs[0]}k", "-bufsize:v", f"{brs[0]*2}k",
"-pass", "1", "-passlogfile", log_a, "-f", "null", "NUL" if os.name=='nt' else "/dev/null"]
cmd_b1 = base + ["-ss", str(split_time), "-i", input_path] + vf_args + ["-c:v", active_encoder] + enc_params + [
"-b:v", f"{brs[1]}k", "-maxrate:v", f"{brs[1]}k", "-bufsize:v", f"{brs[1]*2}k",
"-pass", "1", "-passlogfile", log_b, "-f", "null", "NUL" if os.name=='nt' else "/dev/null"]
pa = subprocess.Popen(cmd_a1, stderr=subprocess.PIPE, text=True, bufsize=0)
pb = subprocess.Popen(cmd_b1, stderr=subprocess.PIPE, text=True, bufsize=0)
trk = ProgressTracker(durs[0], durs[1])
t1 = threading.Thread(target=monitor_process, args=(pa, trk, True))
t2 = threading.Thread(target=monitor_process, args=(pb, trk, False))
t1.start(); t2.start()
while pa.poll() is None or pb.poll() is None:
p, f, e = trk.get_stats()
spd = f / fps if fps > 0 else 0
if spd > 0.001:
# For Pass 1 we do not know the exact bitrate target
print(f"\rPass 1 | {format_progress(p, f, brs[0] + brs[1], spd, e)} ", end="")
time.sleep(0.5)
t1.join(); t2.join()
if pa.returncode != 0 or pb.returncode != 0: return False, "Pass 1 Failed"
print("\nPass 1 Complete.")
# PASS 2
print("Parallel Pass 2/2: Encoding...")
trk = ProgressTracker(durs[0], durs[1])
cmd_a2 = base + ["-ss", "0", "-to", str(split_time), "-i", input_path] + vf_args + ["-c:v", active_encoder] + enc_params + [
"-b:v", f"{brs[0]}k", "-maxrate:v", f"{brs[0]}k", "-bufsize:v", f"{brs[0]*2}k",
"-pass", "2", "-passlogfile", log_a]
cmd_b2 = base + ["-ss", str(split_time), "-i", input_path] + vf_args + ["-c:v", active_encoder] + enc_params + [
"-b:v", f"{brs[1]}k", "-maxrate:v", f"{brs[1]}k", "-bufsize:v", f"{brs[1]*2}k",
"-pass", "2", "-passlogfile", log_b]
if codec_type == "hevc":
cmd_a2.extend(["-tag:v", "hvc1"])
cmd_b2.extend(["-tag:v", "hvc1"])
elif codec_type == "h264":
cmd_a2.extend(["-tag:v", "avc1"])
cmd_b2.extend(["-tag:v", "avc1"])
cmd_a2.extend(["-c:a", "copy", str(p1_path)])
cmd_b2.extend(["-c:a", "copy", str(p2_path)])
pa = subprocess.Popen(cmd_a2, stderr=subprocess.PIPE, text=True, bufsize=0)
pb = subprocess.Popen(cmd_b2, stderr=subprocess.PIPE, text=True, bufsize=0)
t1 = threading.Thread(target=monitor_process, args=(pa, trk, True))
t2 = threading.Thread(target=monitor_process, args=(pb, trk, False))
t1.start(); t2.start()
while pa.poll() is None or pb.poll() is None:
p, f, e = trk.get_stats()
spd = f / fps if fps > 0 else 0
if spd > 0.001:
print(f"\rPass 2 | {format_progress(p, f, brs[0] + brs[1], spd, e)} ", end="")
time.sleep(0.5)
t1.join(); t2.join()
if pa.returncode != 0 or pb.returncode != 0: return False, "Pass 2 Failed"
print("\nStitching...")
with open(list_path, "w") as lf: lf.write(f"file '{p1_path}'\nfile '{p2_path}'")
try:
subprocess.run([ffmpeg_exe, "-f", "concat", "-safe", "0", "-i", list_path, "-c", "copy", "-y", output_path], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception as e:
return False, f"Stitching Failed: {e}"
except KeyboardInterrupt:
print("\nCancelling...")
try: pa.kill()
except Exception: pass
try: pb.kill()
except Exception: pass
return False, "Cancelled"
except Exception as e:
return False, f"NVENC pass error: {e}"
finally:
clean_log_file()
# --- SPLIT SINGLE-PASS FOR OTHER HW ENCODERS ---
elif active_encoder not in ["libx265", "libx264"]:
split_time = get_smart_split_point(input_path, duration)
print(f"Splitting at {split_time:.2f}s")
durs = (split_time, duration - split_time)
brs: List[int] = []
tgt_part_mb = target_size_mb / 2
for seg_dur in durs:
audio_mb = (audio_kbps * seg_dur * 1000) / 8 / MB_TO_BYTES
video_mb = max(0.5, tgt_part_mb - audio_mb)
br_k = math.floor(((video_mb * MB_TO_BITS) / seg_dur / 1000) * BITRATE_SAFETY_FACTOR)
brs.append(br_k)
print(f"Worker 1: {brs[0]}k | Worker 2: {brs[1]}k")
ok, err = encode_split_single_pass_hw(ffmpeg_exe, input_path, output_path, active_encoder, codec_type, (brs[0], brs[1]), fps, durs, split_time, opt_h, opt_fps)
if not ok:
clean_log_file()
return False, err
# --- SERIAL SINGLE-PASS (CPU) ---
else:
tgt_bits = target_size_mb * MB_TO_BITS
vid_bits = max(0.0, tgt_bits - (audio_kbps * 1000 * duration))
vid_br = math.floor(((vid_bits / duration) / 1000) * BITRATE_SAFETY_FACTOR)
print(f"Encoding Single Pass. Target: {vid_br}k")
success = encode_single_pass_hw(ffmpeg_exe, input_path, output_path, active_encoder, codec_type, vid_br, fps, duration, opt_h, opt_fps)
if not success: return False, "Encode Failed"
clean_log_file()
if os.path.exists(output_path):
final_sz = get_file_size(output_path)
print(f"Finished. Final size: {format_size(final_sz)} ({(1-final_sz/orig_bytes)*100:.1f}% reduced)")
print(f"Time: {time.time()-start_t:.1f}s")
return True, output_path
return False, "Output missing"
def main() -> None:
if len(sys.argv) < 2:
print("Usage: <input.mp4> [output.mp4] [size_in_mb] [hevc/h264]")
sys.exit(1)
input_file: Optional[str] = None
output_file: Optional[str] = None
target_mb: int = 100
codec_type: str = "hevc"
# Strategy:
# 1. Extract flags and numbers first.
# 2. Assign the rest as paths: first path that exists is input.
# 3. First path that isn't the input is output.
raw_args = sys.argv # Pyre workaround: avoid slicing sys.argv directly
potential_paths: List[str] = []
for i in range(1, len(raw_args)):
arg_s = str(raw_args[i])
arg_lower = arg_s.lower()
if arg_lower in ["hevc", "h264"]:
codec_type = arg_lower
elif arg_s.isdigit():
target_mb = int(arg_s)
else:
potential_paths.append(arg_s)
# First pass: Identify input file (must exist)
for path in potential_paths:
if os.path.exists(path):
input_file = path
break
# Second pass: Identify output file (first non-input path)
for path in potential_paths:
if path != input_file:
output_file = path
break
if input_file is None:
# Fallback for when the input file path might not have been recognized as such
# strictly (e.g. if it doesn't exist yet, although it should for input).
print("Error: Valid input video file not provided or found.")
sys.exit(1)
# Final validation for Pyre: input_file is not None
inp_path = str(input_file)
success, result = compress_video(
inp_path,
output_file,
target_size_mb=target_mb,
codec_type=codec_type
)
if not success:
sys.stderr.write(f"Compression failed: {result}\n")
sys.exit(1)
if __name__ == "__main__":
main()