Repository navigation
Expand file tree
/
Copy pathaom_opus_encoder.py
More file actions
executable file
·1928 lines (1714 loc) · 70.8 KB
/
Copy pathaom_opus_encoder.py
File metadata and controls
executable file
·1928 lines (1714 loc) · 70.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Note: This script is configured to use a custom version of aom
# called "aom-psy101" from https://gitlab.com/damian101/aom-psy101
#
# Batch encode: av1an is VIDEO ONLY. Audio, subs, attachments, mux: this script.
# Auto-detects SDR vs HDR and 1080p vs 4K (same intermediate/automation as svt_opus_encoder.py).
# 1080p SDR: HandBrake x264 all-intra intermediate, then VapourSynth BT.709.
# 4K or HDR CFR: mkvmerge video-only remux (no re-encode; keeps HDR/DoVi track metadata).
# VFR 4K/HDR (rare): HandBrake x265_10bit CFR fallback.
# ffmpeg is only a fallback if HandBrake produces an empty 1080p SDR file.
# --cq-level 25 always (overridable with --crf). Two-pass av1an.
# Av1an workers: (cpu_count // 2) - 1, not a fixed count.
# Audio: AAC/Opus remuxed. Else: Nightmode Dialogue pan (`<` so the mix cannot clip)
# → ffmpeg loudnorm 2-pass linear (I=-18, TP=-1.5, LRA=20) → opusenc.
# Final mkvmerge: av1an video + processed/remuxed audio + source subs/chapters.
# Font attachments: only those referenced by remaining ASS/SSA (skip with --nofontsclean / -nfc).
# Encode log lines FONT_CLEAN kept/dropped/missing use the font's full name, not the attachment filename.
# Non-font attachments are always kept.
import argparse
import json
import math
import multiprocessing as _multiprocessing_cropdetect
import os
import re
import shutil
import subprocess
import sys
import tempfile
from collections import Counter as _Counter_cropdetect
from datetime import datetime
from pathlib import Path
REQUIRED_TOOLS = [
"ffmpeg", "ffprobe", "mkvmerge", "mkvextract", "mkvpropedit",
"opusenc", "mediainfo", "av1an", "HandBrakeCLI", "ffmsindex",
]
DIR_COMPLETED = Path("completed")
DIR_ORIGINAL = Path("original")
DIR_CONV_LOGS = Path("conv_logs")
DIR_FAILED = Path("failed")
REMUX_CODECS = {"aac", "opus"}
PREP_SUFFIX = ".prep.mkv"
CFR_SUFFIX = ".cfr.mkv"
CFR_FULL_SUFFIX = ".cfr_full.mkv"
HEIGHT_4K = 1080
DEFAULT_CQ = 25
LOUDNESS_I = -18.0
LOUDNESS_TP = -1.5
LOUDNESS_LRA = 20.0
AOM_AV1_BASE = {
"bit-depth": 10,
"cpu-used": 2,
"good": "",
"end-usage": "q",
"cq-level": DEFAULT_CQ,
"min-q": 8,
"threads": 2,
"tune-content": "psy",
"tune": "psnr",
"sharpness": 2,
"arnr-maxframes": 7,
"arnr-strength": 2,
"quant-b-adapt": 1,
"frame-parallel": 1,
"tile-columns": 1,
"gf-max-pyr-height": 5,
"deltaq-mode": 2,
"enable-keyframe-filtering": 0,
"disable-kf": "",
"enable-fwd-kf": 1,
"kf-max-dist": 9999,
"sb-size": "64",
"enable-chroma-deltaq": 1,
"enable-qm": 1,
"lag-in-frames": 64,
"color-primaries": "bt709",
"transfer-characteristics": "bt709",
"matrix-coefficients": "bt709",
}
HDR_TRANSFER_MARKERS = (
"smpte2084", "smpte st 2084", "pq", "bt.2100", "bt2100",
"arib-std-b67", "arib std-b67", "hlg", "hybrid log-gamma",
)
HDR_FORMAT_MARKERS = ("hdr10", "hdr10+", "dolby vision", "dolbyvision", "hlg")
HLG_MARKERS = ("arib-std-b67", "arib std-b67", "hlg", "hybrid log-gamma")
HDR_TRACK_KEYS = (
"HDR_Format", "HDR_Format_String", "HDR_Format_Compatibility",
"transfer_characteristics", "TransferCharacteristics",
"Transfer_characteristics", "colour_transfer", "color_transfer",
)
class Tee:
"""Write to the log file and the real console at the same time."""
def __init__(self, *files):
self.files = files
def write(self, data):
for f in self.files:
try:
f.write(data)
except Exception:
pass
def flush(self):
for f in self.files:
try:
f.flush()
except Exception:
pass
def isatty(self):
return any(getattr(f, "isatty", lambda: False)() for f in self.files)
def fonttools_available():
try:
import fontTools.ttLib # noqa: F401
return True
except ImportError:
return False
def check_tools():
for tool in REQUIRED_TOOLS:
if shutil.which(tool) is None:
print(f"Required tool '{tool}' not found in PATH.")
sys.exit(1)
def run_cmd(cmd, capture_output=False, check=True):
if capture_output:
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=check, text=True)
return result.stdout
subprocess.run(cmd, check=check)
def run_ffmpeg_logged(args):
"""Run ffmpeg so -stats is teed to console and log as it happens."""
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
try:
while True:
chunk = proc.stdout.read(256)
if not chunk:
break
sys.stdout.write(chunk.decode("utf-8", errors="replace"))
sys.stdout.flush()
finally:
ret = proc.wait()
if ret != 0:
raise subprocess.CalledProcessError(ret, args)
def file_is_usable(path):
try:
return path.exists() and path.is_file() and path.stat().st_size > 0
except OSError:
return False
def mediainfo_json(path):
raw = run_cmd(["mediainfo", "--Output=JSON", "-f", str(path)], capture_output=True)
return json.loads(raw)
def video_track(media_info):
if not (media_info.get("media") and media_info["media"].get("track")):
return None
for track in media_info["media"]["track"]:
if track.get("@type") == "Video":
return track
return None
def video_height(track):
if not track:
return 0
try:
return int(float(str(track.get("Height", "0")).split()[0]))
except (TypeError, ValueError):
return 0
def video_bit_depth(track):
if not track:
return 8
raw = track.get("BitDepth") or track.get("Bit_depth") or "8"
try:
return int(float(str(raw).split()[0]))
except (TypeError, ValueError):
return 8
def video_fps(track, source_file=None):
"""MediaInfo original rate first. ffprobe r_frame_rate is often a fake 29.97 on MKV."""
if track:
orig_str = track.get("FrameRate_Original_String") or ""
match = re.search(r"\((\d+/\d+)\)", str(orig_str))
if match:
return match.group(1)
orig_num = track.get("FrameRate_Original_Num")
orig_den = track.get("FrameRate_Original_Den")
if orig_num and orig_den:
return f"{orig_num}/{orig_den}"
orig = track.get("FrameRate_Original")
if orig:
return str(orig).split()[0]
num, den = track.get("FrameRate_Num"), track.get("FrameRate_Den")
if num and den:
return f"{num}/{den}"
fr = track.get("FrameRate")
if fr:
return str(fr).split()[0]
if source_file:
try:
raw = run_cmd([
"ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=avg_frame_rate,r_frame_rate",
"-of", "json", str(source_file),
], capture_output=True)
streams = (json.loads(raw).get("streams") or [])
if streams:
for key in ("avg_frame_rate", "r_frame_rate"):
val = streams[0].get(key)
if val and val not in ("0/0", "0"):
return val
except (subprocess.CalledProcessError, json.JSONDecodeError, TypeError, ValueError):
pass
return None
def is_4k_path(track):
return video_height(track) > HEIGHT_4K
def _hdr_text(track):
if not track:
return ""
parts = []
for key in HDR_TRACK_KEYS:
val = track.get(key)
if val:
parts.append(str(val).lower())
return " ".join(parts)
def is_hdr(track):
"""True HDR (PQ/HLG/DoVi). 10-bit BT.709 Hi10p is SDR, not HDR."""
text = _hdr_text(track)
if any(m in text for m in HDR_FORMAT_MARKERS):
return True
return any(m in text for m in HDR_TRANSFER_MARKERS)
def is_hlg(track):
return any(m in _hdr_text(track) for m in HLG_MARKERS)
def is_4k_or_hdr(track):
return is_4k_path(track) or is_hdr(track)
def path_label(track):
height = video_height(track)
if is_hdr(track):
kind = "HLG" if is_hlg(track) else "PQ/HDR10"
return f"HDR {kind} (height={height})"
if is_4k_path(track):
return f"4K+ SDR (height={height})"
return f"1080p or lower SDR (height={height})"
def aom_params_for_track(track, cq_override=None):
params = dict(AOM_AV1_BASE)
params["cq-level"] = int(cq_override) if cq_override is not None else DEFAULT_CQ
if is_hdr(track):
params["color-primaries"] = "bt2020"
params["matrix-coefficients"] = "bt2020ncl"
params["transfer-characteristics"] = "arib-std-b67" if is_hlg(track) else "smpte2084"
return params
def vs_matrix_in(track):
return "2020ncl" if is_hdr(track) else "709"
def av1an_aom_param_string(params):
return " ".join(
f"--{key}={value}" if value != "" else f"--{key}"
for key, value in params.items()
)
def av1an_worker_count():
total_cores = os.cpu_count() or 4
workers = max(1, (total_cores // 2) - 1)
return workers, total_cores
def intermediate_encoder(track):
"""Return (ffmpeg codec args, handbrake encoder, label, handbrake --encopts or None)."""
ten = video_bit_depth(track) >= 10 or is_4k_or_hdr(track)
if is_4k_or_hdr(track):
ffmpeg_args = [
"-c:v", "libx265",
"-crf", "0",
"-preset", "superfast",
"-tune", "fastdecode",
"-pix_fmt", "yuv420p10le",
"-x265-params", "info=0",
]
return ffmpeg_args, "x265_10bit", "libx265 10-bit CRF 0, normal GOP (VFR 4K/HDR fallback)", None
if ten:
ffmpeg_args = [
"-c:v", "libx264",
"-crf", "0",
"-preset", "superfast",
"-tune", "fastdecode",
"-pix_fmt", "yuv420p10le",
"-g", "1",
"-bf", "0",
]
return ffmpeg_args, "x264_10bit", "libx264 10-bit CRF 0 all-intra (1080p SDR Hi10p)", "keyint=1:bframes=0"
ffmpeg_args = [
"-c:v", "libx264",
"-crf", "0",
"-preset", "superfast",
"-tune", "fastdecode",
"-g", "1",
"-bf", "0",
]
return ffmpeg_args, "x264", "libx264 8-bit CRF 0 all-intra (1080p SDR)", "keyint=1:bframes=0"
def detect_vfr(media_info):
is_vfr = False
target_cfr_fps = None
track = video_track(media_info)
if not track:
return is_vfr, target_cfr_fps
frame_rate_mode = track.get("FrameRate_Mode")
if not (frame_rate_mode and frame_rate_mode.upper() in ["VFR", "VARIABLE"]):
print(" - Video appears to be CFR or FrameRate_Mode not specified as VFR/Variable by MediaInfo.")
return is_vfr, target_cfr_fps
is_vfr = True
print(f" - Detected VFR based on MediaInfo FrameRate_Mode: {frame_rate_mode}")
original_fps_str = track.get("FrameRate_Original_String")
if original_fps_str:
match = re.search(r"\((\d+/\d+)\)", original_fps_str)
if match:
target_cfr_fps = match.group(1)
else:
target_cfr_fps = track.get("FrameRate_Original")
if not target_cfr_fps:
target_cfr_fps = track.get("FrameRate_Original")
if not target_cfr_fps:
target_cfr_fps = track.get("FrameRate")
if target_cfr_fps:
print(f" - Using MediaInfo FrameRate ({target_cfr_fps}) as fallback for HandBrake target FPS.")
if target_cfr_fps:
print(f" - Target CFR for HandBrake: {target_cfr_fps}")
if isinstance(target_cfr_fps, str) and "/" in target_cfr_fps:
try:
num, den = map(float, target_cfr_fps.split("/"))
target_cfr_fps = f"{num / den:.3f}"
print(f" - Converted fractional FPS to decimal for HandBrake: {target_cfr_fps}")
except ValueError:
print(f" - Warning: Could not parse fractional FPS '{target_cfr_fps}'. Sending source as-is.")
is_vfr = False
else:
print(" - Warning: VFR detected, but could not determine target CFR. Sending source as-is.")
is_vfr = False
return is_vfr, target_cfr_fps
def handbrake_rate(track, source_file, vfr_target=None):
"""Always pass --rate. Prefer MediaInfo original FPS (never HandBrake's fake 29.97)."""
raw = vfr_target or video_fps(track, source_file)
if not raw:
return None
raw = str(raw).split()[0]
if "/" in raw:
try:
num, den = map(float, raw.split("/", 1))
if den:
return f"{num / den:.3f}"
except ValueError:
return raw
try:
return f"{float(raw):.3f}"
except ValueError:
return raw
def strip_prep_tags(path):
"""HandBrake/ffmpeg can copy a video title; av1an would copy it again."""
try:
run_cmd([
"mkvpropedit", str(path),
"--delete", "title",
"--edit", "track:v1",
"--delete", "name",
])
except subprocess.CalledProcessError as e:
print(f" - Warning: could not strip intermediate titles ({e}).")
def prep_is_vfr(path):
try:
mode = (video_track(mediainfo_json(path)) or {}).get("FrameRate_Mode") or ""
except Exception:
return False
return str(mode).upper() in ("VFR", "VARIABLE")
def first_video_track_id(source_file):
"""mkvmerge track id of the first video track (BL if dual-layer DoVi)."""
try:
for t in mkvmerge_identify(source_file).get("tracks") or []:
if t.get("type") == "video":
return t.get("id", 0)
except (subprocess.CalledProcessError, json.JSONDecodeError, TypeError):
pass
return 0
def run_mkvmerge_video_only(source_file, output_file):
"""Copy the video track only. No re-encode. Keeps HDR10/DoVi track properties."""
vid = first_video_track_id(source_file)
print(
f" - mkvmerge video-only remux (no re-encode, keep HDR/DoVi metadata), "
f"video TID {vid}"
)
args = [
"mkvmerge", "-o", str(output_file),
"--title", "",
"--no-audio",
"--no-subtitles",
"--no-buttons",
"--no-attachments",
"--no-chapters",
"--no-global-tags",
"--video-tracks", str(vid),
"--track-name", f"{vid}:",
str(source_file),
]
print(f" - Running mkvmerge: {' '.join(args)}")
run_cmd(args)
return file_is_usable(output_file)
def prep_is_handbrake_reencode(path):
"""Old 4K/HDR preps were HandBrake HEVC CRF 0. Remux path should not reuse those."""
try:
media = mediainfo_json(path)
general = {}
for t in media.get("media", {}).get("track", []):
if t.get("@type") == "General":
general = t
break
writing = " ".join(
str(general.get(k) or "")
for k in ("WritingApplication", "Encoded_Application", "Writing_library")
)
return "handbrake" in writing.lower()
except Exception:
return False
def run_handbrake_intermediate(source_file, output_file, track, target_fps):
"""Video-only CFR intermediate. All-intra for 1080p SDR; VFR 4K/HDR uses HEVC."""
_ffmpeg_args, encoder, label, encopts = intermediate_encoder(track)
print(f" - HandBrakeCLI intermediate: encoder={encoder} ({label}), CFR {target_fps}")
handbrake_args = [
"HandBrakeCLI",
"--input", str(source_file),
"--output", str(output_file),
"--cfr",
"--rate", str(target_fps),
"--encoder", encoder,
"--quality", "0",
"--encoder-preset", "superfast",
"--encoder-tune", "fastdecode",
]
if encopts:
handbrake_args += ["--encopts", encopts]
handbrake_args += [
"--audio", "none",
"--subtitle", "none",
"--crop-mode", "none",
"--no-markers",
]
print(f" - Running HandBrakeCLI: {' '.join(handbrake_args)}")
run_cmd(handbrake_args)
return file_is_usable(output_file)
def create_ffmpeg_intermediate(source_file, output_file, track):
"""Video-only all-intra CFR fallback. Strip metadata/chapters/titles."""
video_args, _hb, label, _encopts = intermediate_encoder(track)
fps = video_fps(track, source_file)
print(f" - Creating ffmpeg intermediate: {label} (forced CFR)")
ffmpeg_args = [
"ffmpeg", "-hide_banner", "-v", "error", "-stats", "-y",
"-fflags", "+genpts",
"-i", str(source_file),
"-map", "0:v:0",
*video_args,
"-fps_mode", "cfr",
]
if fps:
ffmpeg_args += ["-r", str(fps)]
print(f" - Forcing CFR at {fps}")
ffmpeg_args += [
"-an", "-sn", "-dn",
"-map_metadata", "-1",
"-map_chapters", "-1",
"-metadata", "title=",
"-metadata:s:v:0", "title=",
str(output_file),
]
print(f" - Running ffmpeg: {' '.join(ffmpeg_args)}")
run_ffmpeg_logged(ffmpeg_args)
return file_is_usable(output_file)
def prepare_av1an_input(file_path, is_vfr, target_cfr_fps, track):
"""1080p SDR: HandBrake x264 all-intra. 4K/HDR CFR: mkvmerge video-only remux."""
prep_file = Path(f"{file_path.stem}{PREP_SUFFIX}")
temps = [prep_file]
uhd_or_hdr = is_4k_or_hdr(track)
if file_is_usable(prep_file):
if prep_is_vfr(prep_file):
print(f" - Existing intermediate is VFR; deleting and remaking: {prep_file}")
prep_file.unlink(missing_ok=True)
elif uhd_or_hdr and not is_vfr and prep_is_handbrake_reencode(prep_file):
print(
f" - Existing intermediate is a HandBrake re-encode; "
f"deleting and remuxing video-only: {prep_file}"
)
prep_file.unlink(missing_ok=True)
else:
print(f" - Reusing existing intermediate (resume): {prep_file}")
return prep_file, temps
if uhd_or_hdr and not is_vfr:
if run_mkvmerge_video_only(file_path, prep_file):
strip_prep_tags(prep_file)
return prep_file, temps
print(" - Warning: mkvmerge video-only remux failed. Falling back to HandBrake.")
fps = handbrake_rate(track, file_path, target_cfr_fps if is_vfr else None)
if fps:
if run_handbrake_intermediate(file_path, prep_file, track, fps):
strip_prep_tags(prep_file)
return prep_file, temps
print(" - Warning: HandBrakeCLI produced an empty file. Falling back to ffmpeg.")
else:
print(" - Warning: could not determine FPS for HandBrake. Falling back to ffmpeg.")
if create_ffmpeg_intermediate(file_path, prep_file, track):
strip_prep_tags(prep_file)
return prep_file, temps
print(" - Warning: ffmpeg intermediate failed. Sending source to av1an as-is.")
return file_path, temps
def strip_titles(mkv_path):
print(" - Clearing container and video-track titles...")
try:
run_cmd([
"mkvpropedit", str(mkv_path),
"--delete", "title",
"--edit", "track:v1",
"--delete", "name",
])
except subprocess.CalledProcessError as e:
print(f" - Warning: mkvpropedit could not clear titles ({e}). Continuing.")
TRACK_FLAG_MAP = (
("default_track", "flag-default", 0),
("forced_track", "flag-forced", 0),
("enabled_track", "flag-enabled", 1),
("flag_hearing_impaired", "flag-hearing-impaired", 0),
("flag_visual_impaired", "flag-visual-impaired", 0),
("flag_text_descriptions", "flag-text-descriptions", 0),
("flag_original", "flag-original", 0),
("flag_commentary", "flag-commentary", 0),
)
def collect_track_meta(path):
"""Audio/subtitle names and Matroska flags from the prepared source."""
mkv = mkvmerge_identify(path)
audio, subs = [], []
for t in mkv.get("tracks", []):
kind = t.get("type")
if kind not in ("audio", "subtitles"):
continue
props = t.get("properties") or {}
flags = {}
for json_key, prop_name, default in TRACK_FLAG_MAP:
if json_key in props:
flags[prop_name] = 1 if props[json_key] else 0
else:
flags[prop_name] = default
meta = {
"name": props.get("track_name") or "",
"language": props.get("language") or "und",
"language_ietf": props.get("language_ietf") or "",
"flags": flags,
}
if kind == "audio":
audio.append(meta)
else:
subs.append(meta)
return audio, subs
def _append_track_restore(args, selector, meta, label):
name = meta.get("name") or ""
flags = meta.get("flags") or {}
language = meta.get("language") or "und"
language_ietf = meta.get("language_ietf") or ""
args += ["--edit", selector]
if name:
args += ["--set", f"name={name}"]
shown = name
else:
args += ["--delete", "name"]
shown = "(no title)"
args += ["--set", f"language={language}"]
if language_ietf:
args += ["--set", f"language-ietf={language_ietf}"]
bits = []
for _json_key, prop_name, _default in TRACK_FLAG_MAP:
value = flags.get(prop_name, 0)
args += ["--set", f"{prop_name}={value}"]
if value:
bits.append(prop_name.replace("flag-", ""))
extra = f" [{', '.join(bits)}]" if bits else ""
ietf = f"/{language_ietf}" if language_ietf else ""
print(f" - {label}: {language}{ietf} {shown}{extra}")
def restore_track_meta(mkv_path, audio_meta, sub_meta):
"""Re-apply source audio/subtitle titles and flags."""
if not audio_meta and not sub_meta:
return
print(" - Restoring audio and subtitle language, titles, and flags from source...")
args = ["mkvpropedit", str(mkv_path)]
out = mkvmerge_identify(mkv_path)
out_audio = [t for t in out.get("tracks", []) if t.get("type") == "audio"]
out_subs = [t for t in out.get("tracks", []) if t.get("type") == "subtitles"]
for i, meta in enumerate(audio_meta[: len(out_audio)], start=1):
_append_track_restore(args, f"track:a{i}", meta, f"audio a{i}")
for i, meta in enumerate(sub_meta[: len(out_subs)], start=1):
_append_track_restore(args, f"track:s{i}", meta, f"subtitle s{i}")
if args == ["mkvpropedit", str(mkv_path)]:
return
try:
run_cmd(args)
except subprocess.CalledProcessError as e:
print(f" - Warning: mkvpropedit could not restore track titles/flags ({e}). Continuing.")
def ffprobe_json(path):
raw = run_cmd(
["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", str(path)],
capture_output=True,
)
return json.loads(raw)
def mkvmerge_identify(path):
return json.loads(run_cmd(["mkvmerge", "-J", str(path)], capture_output=True))
def _parse_loudnorm_json(stderr_output):
json_start_index = stderr_output.find("{")
if json_start_index == -1:
raise ValueError("Could not find start of JSON block in ffmpeg output for loudness analysis.")
brace_level = 0
json_end_index = -1
for i, char in enumerate(stderr_output[json_start_index:]):
if char == "{":
brace_level += 1
elif char == "}":
brace_level -= 1
if brace_level == 0:
json_end_index = json_start_index + i + 1
break
if json_end_index == -1:
raise ValueError("Could not find end of JSON block in ffmpeg output for loudness analysis.")
return json.loads(stderr_output[json_start_index:json_end_index])
def _finite_float(value, fallback):
try:
number = float(value)
except (TypeError, ValueError):
return fallback
return number if math.isfinite(number) else fallback
def stream_sample_rate(source_file, stream_index):
"""Source track sample rate in Hz. loudnorm leaks 192 kHz; we restore this for opusenc's header."""
try:
for stream in ffprobe_json(source_file).get("streams", []):
if int(stream.get("index", -1)) != int(stream_index):
continue
rate = int(str(stream.get("sample_rate") or "0").split()[0])
if rate > 0:
return rate
except (TypeError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError):
pass
return 48000
def apply_constant_gain_loudness(input_path, output_path, track_index, sample_rate=48000):
"""Two-pass ffmpeg loudnorm, linear (constant gain + true-peak). No asoftclip.
loudnorm true-peak uses 4× oversampling (48 kHz → 192 kHz). Pin the FLAC back
to the source rate so opusenc tags Input Sample Rate correctly (still encodes at 48 kHz).
"""
print(f" - Normalizing Audio Track #{track_index} (loudnorm 2-pass linear)...")
print(
f" - Targets: I={LOUDNESS_I} LUFS, TP={LOUDNESS_TP} dBTP, "
f"LRA={LOUDNESS_LRA} LU (linear; not a compressor)"
)
print(f" - Restore sample rate after loudnorm: {sample_rate} Hz (source; Opus encode stays 48 kHz)")
print(" - Pass 1: Measuring integrated loudness and true peak...")
result = subprocess.run(
[
"ffmpeg", "-hide_banner", "-v", "info", "-i", str(input_path),
"-af", (
f"loudnorm=I={LOUDNESS_I}:LRA={LOUDNESS_LRA}:tp={LOUDNESS_TP}"
f":print_format=json"
),
"-f", "null", "-",
],
capture_output=True, text=True, check=True,
)
stats = _parse_loudnorm_json(result.stderr)
measured_i = _finite_float(stats.get("input_i"), None)
if measured_i is None:
print(" - Could not measure integrated loudness; copying without gain.")
run_cmd(["ffmpeg", "-v", "quiet", "-y", "-i", str(input_path), "-c:a", "flac", str(output_path)])
return
measured_tp = _finite_float(stats.get("input_tp"), -99.0)
measured_lra = _finite_float(stats.get("input_lra"), 0.0)
measured_thresh = _finite_float(stats.get("input_thresh"), -70.0)
offset = _finite_float(stats.get("target_offset"), 0.0)
gain_db = LOUDNESS_I - measured_i
print(
f" - Measured I={measured_i:.2f} LUFS, TP={measured_tp:.2f} dBTP, "
f"LRA={measured_lra:.2f} LU → {gain_db:+.2f} dB (offset {offset:+.2f})"
)
if measured_lra > LOUDNESS_LRA:
print(
f" - Warning: source LRA {measured_lra:.2f} > {LOUDNESS_LRA}; "
"loudnorm may use dynamic mode. Prefer LRA<=20 for constant gain."
)
print(" - Pass 2: loudnorm linear=true (true-peak aware, not hard clip)...")
loudnorm_apply = (
f"loudnorm=I={LOUDNESS_I}:LRA={LOUDNESS_LRA}:tp={LOUDNESS_TP}"
f":measured_I={measured_i:.2f}"
f":measured_LRA={measured_lra:.2f}"
f":measured_TP={measured_tp:.2f}"
f":measured_thresh={measured_thresh:.2f}"
f":offset={offset:.2f}"
f":linear=true"
f":print_format=summary"
)
run_ffmpeg_logged([
"ffmpeg", "-hide_banner", "-v", "error", "-stats", "-y",
"-i", str(input_path),
"-af", f"{loudnorm_apply},aformat=sample_fmts=s32:sample_rates={sample_rate}",
"-ar", str(sample_rate),
"-c:a", "flac", "-sample_fmt", "s32",
str(output_path),
])
def downmix_filters(ch):
"""Nightmode Dialogue (Collier / Harrelson). pan '<' renormalizes so the mix cannot clip."""
if ch == 6:
return [
"pan=stereo|FL<FC+0.30*FL+0.30*SL|FR<FC+0.30*FR+0.30*SR",
"pan=stereo|FL<FC+0.30*FL+0.30*BL|FR<FC+0.30*FR+0.30*BR",
"aformat=ch_layouts=5.1,pan=stereo|FL<FC+0.30*FL+0.30*BL|FR<FC+0.30*FR+0.30*BR",
"pan=stereo|c0<c2+0.30*c0+0.30*c4|c1<c2+0.30*c1+0.30*c5",
]
if ch == 8:
return [
"pan=stereo|FL<FC+0.30*FL+0.30*SL+0.30*BL|FR<FC+0.30*FR+0.30*SR+0.30*BR",
"pan=stereo|c0<c2+0.30*c0+0.30*c4+0.30*c6|c1<c2+0.30*c1+0.30*c5+0.30*c7",
]
return []
def convert_audio_track(index, ch, audio_temp_dir, source_file, should_downmix):
audio_temp_path = Path(audio_temp_dir)
temp_extracted = audio_temp_path / f"track_{index}_extracted.flac"
temp_normalized = audio_temp_path / f"track_{index}_normalized.flac"
final_opus = audio_temp_path / f"track_{index}_final.opus"
print(f" - Extracting Audio Track #{index} to FLAC...")
base_args = [
"ffmpeg", "-hide_banner", "-v", "error", "-stats", "-y",
"-drc_scale", "0",
"-i", str(source_file),
"-map", f"0:{index}",
"-map_metadata", "-1",
]
downmix_attempts = []
if should_downmix and ch >= 6:
downmix_attempts.extend(downmix_filters(ch))
downmix_attempts.append(None)
else:
downmix_attempts.append("keep")
last_error = None
extracted = False
for attempt, filt in enumerate(downmix_attempts, start=1):
ffmpeg_args = list(base_args)
if filt == "keep":
pass
elif filt is None:
ffmpeg_args += ["-ac", "2"]
print(" - Downmix fallback: -ac 2")
else:
ffmpeg_args += ["-af", filt]
print(f" - Downmix filter (try {attempt}): {filt}")
ffmpeg_args += ["-c:a", "flac", str(temp_extracted)]
try:
run_ffmpeg_logged(ffmpeg_args)
extracted = True
break
except subprocess.CalledProcessError as e:
last_error = e
print(f" - Downmix try {attempt} failed, trying next option...")
if not extracted:
raise last_error
apply_constant_gain_loudness(
temp_extracted,
temp_normalized,
index,
sample_rate=stream_sample_rate(source_file, index),
)
is_being_downmixed = should_downmix and ch >= 6
if is_being_downmixed:
bitrate = "128k"
elif ch == 1:
bitrate = "64k"
elif ch == 2:
bitrate = "128k"
elif ch == 6:
bitrate = "256k"
elif ch == 8:
bitrate = "384k"
else:
bitrate = "192k"
print(f" - Encoding Audio Track #{index} to Opus at {bitrate}...")
run_cmd(["opusenc", "--vbr", "--bitrate", bitrate, str(temp_normalized), str(final_opus)])
return final_opus
def process_audio_tracks(source_file, audio_temp_dir, no_downmix):
"""AAC/Opus remux. Other codecs: pan (optional) → LUFS → opusenc. Original order."""
probe = ffprobe_json(source_file)
mkv = mkvmerge_identify(source_file)
media = mediainfo_json(source_file)
mkv_audio = [t for t in mkv.get("tracks", []) if t.get("type") == "audio"]
media_audio = {
int(t.get("StreamOrder", -1)): t
for t in media.get("media", {}).get("track", [])
if t.get("@type") == "Audio"
}
plan = []
audio_i = 0
print("--- Starting Audio Processing ---")
for stream in probe.get("streams", []):
if stream.get("codec_type") != "audio":
continue
idx = int(stream["index"])
codec = (stream.get("codec_name") or "").lower()
channels = stream.get("channels", 2)
mkv_track = None
for t in mkv_audio:
if t.get("properties", {}).get("stream_id") == idx:
mkv_track = t
break
if mkv_track is None and audio_i < len(mkv_audio):
mkv_track = mkv_audio[audio_i]
audio_i += 1
props = (mkv_track or {}).get("properties") or {}
mkv_id = (mkv_track or {}).get("id")
language = props.get("language") or stream.get("tags", {}).get("language") or "und"
title = props.get("track_name") or ""
delay = 0
delay_raw = (media_audio.get(idx) or {}).get("Video_Delay")
if delay_raw is not None:
try:
delay_val = float(delay_raw)
delay = int(round(delay_val * 1000 if delay_val < 1 else delay_val))
except Exception:
delay = 0
print(f"Processing Audio Stream #{idx} (TID: {mkv_id}, Codec: {codec}, Channels: {channels}, Lang: {language})")
if codec in REMUX_CODECS and mkv_id is not None:
print(" - Remux (AAC/Opus), skip re-encode")
plan.append({"kind": "remux", "mkv_id": str(mkv_id)})
else:
opus_path = convert_audio_track(idx, channels, audio_temp_dir, source_file, not no_downmix)
plan.append({
"kind": "encode",
"path": opus_path,
"language": language,
"title": title,
"delay": delay,
})
print("--- Finished Audio Processing ---")
return plan
def mux_final(dest, encoded_video, source_file, audio_plan, clean_fonts=True, work_dir=None):
"""av1an video only + audio in source order + source subs/chapters.
Default: drop font attachments not referenced by remaining ASS/SSA.
Non-font attachments stay. --nofontsclean copies every attachment.
"""
extra = [
"--no-video", "--no-subtitles", "--no-attachments",
"--no-chapters", "--no-global-tags",
]
source_tail = ["--no-video", "--no-audio"]
attach_args = []
if clean_fonts:
kept = fonts_to_keep(source_file, work_dir)
if kept is not None:
source_tail.append("--no-attachments")
attach_args = attachment_merge_args(kept)
args = [
"mkvmerge", "-o", str(dest),
"--title", "",
"--track-name", "0:",
"--no-audio", "--no-subtitles", "--no-attachments", "--no-chapters",
str(encoded_video),
]
for item in audio_plan:
if item["kind"] == "remux":
args += extra + ["--audio-tracks", item["mkv_id"], str(source_file)]
else:
sync = ["--sync", f"0:{item['delay']}"] if item.get("delay") else []
args += [
"--language", f"0:{item['language']}",
"--track-name", f"0:{item.get('title') or ''}",
] + sync + [str(item["path"])]
args += source_tail + [str(source_file)] + attach_args
print("Assembling final file with mkvmerge...")
print(f" - mkvmerge: {' '.join(args)}")
run_cmd(args)
if not file_is_usable(dest):
raise RuntimeError(f"mkvmerge produced an empty file: {dest}")
FONT_MIME_MARKERS = ("font", "truetype", "opentype", "sfnt", "application/x-truetype-font")
def is_font_attachment(att):
mime = str(att.get("content_type") or "").lower()
name = str(att.get("file_name") or "").lower()
if any(marker in mime for marker in FONT_MIME_MARKERS):
return True
return name.endswith((".ttf", ".otf", ".ttc", ".otc"))
def safe_font_filename(name):
return "".join(c for c in name if c.isalpha() or c.isdigit() or c in " .-_").rstrip() or "font"
def _remember_font_name(bucket, name):
if name:
bucket.setdefault(name.casefold(), name)