-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakemp4.py
More file actions
1598 lines (1444 loc) · 46.7 KB
/
makemp4.py
File metadata and controls
1598 lines (1444 loc) · 46.7 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
#!python3
# -*- coding: utf-8 -*-
prog = "MakeMP4"
version = "8.0"
author = "Carl Edman (CarlEdman@gmail.com)"
desc = """Extract all tracks from .mkv files;
convert video tracks to h264 or 265, audio tracks to aac;
then recombine all tracks into properly tagged .mp4 or .mkv
"""
import argparse
import json
import logging
import math
import mimetypes
import os
import pathlib
import re
import shutil
import subprocess
import sys
import time
import xml.etree.ElementTree as ET
import yaml
try:
from yaml import CDumper as Dumper
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader, Dumper
from cetools import * # pylint: disable=unused-wildcard-import
from tagmp4 import * # pylint: disable=unused-wildcard-import
parser = None
args = None
log = logging.getLogger()
progmodtime = None
iso6392BtoT = {
"alb": "sqi",
"arm": "hye",
"baq": "eus",
"bur": "mya",
"chi": "zho",
"cze": "ces",
"dut": "nld",
"fre": "fra",
"geo": "kat",
"ger": "deu",
"gre": "ell",
"ice": "isl",
"mac": "mkd",
"mao": "mri",
"may": "msa",
"per": "fas",
"rum": "ron",
"slo": "slk",
"tib": "bod",
"wel": "cym",
"English": "eng",
"Français": "fra",
"Japanese": "jpn",
"Español": "esp",
"German": "deu",
"Deutsch": "deu",
"Svenska": "swe",
"Latin": "lat",
"Dutch": "nld",
"Chinese": "zho",
}
json_exts = set(["json", "cfg"])
yaml_exts = set(["yaml", "yml"])
def cfgload(fn):
with open(fn, "r", encoding="utf-8") as f:
if fn.suffix[1:] in yaml_exts:
return yaml.load(f)
elif fn.suffix[1:] in json_exts:
return json.load(f, object_hook=defdict)
else:
log.error(f"{fn} is not a config file, skipping.")
def cfgdump(cfg, fn):
with open(fn, "w", encoding="utf-8") as f:
if fn.suffix[1:] in yaml_exts:
yaml.dump(cfg, f, indent=2, allow_unicode=True, encoding="utf-8")
elif fn.suffix[1:] in json_exts:
json.dump(
cfg, f, ensure_ascii=False, indent=2, sort_keys=True, cls=DefDictEncoder
)
else:
log.error(f"{fn} is not a config file, skipping.")
def syncconfig(cfg):
if cfg.modclear():
cfgdump(cfg, cfg["cfgname"])
def serveconfig(fn):
try:
j = cfgload(fn)
yield j
syncconfig(j)
except yaml.YAMLError:
log.error(f"{fn} is not a YAML config file, skipping.")
except json.JSONDecodeError:
log.error(f"{fn} is not a JSON config file, skipping.")
except TypeError:
log.error(f"Type Error in {fn}, skipping.")
def configs(path=None):
if path is None:
path = args.outdir
for e in json_exts | yaml_exts:
for fn in path.glob(f"*.{e}"):
yield from serveconfig(fn)
def maketrack(cfg, tid=None):
track = defdict()
if not isinstance(tid, int):
for tid in range(sys.maxsize):
n = f"track{tid:02d}"
if n not in cfg:
track["id"] = tid
cfg[n] = track
return track
def tracks(cfg, typ=None):
if not isinstance(cfg, dict):
return
for k in list(cfg):
if not re.fullmatch(r"track\d+", k):
continue
track = cfg[k]
if track["disable"]:
continue
if typ and track["type"] != typ:
continue
if (
"language" in track
and "languages" in cfg
and track["language"] not in cfg("languages")
):
continue
yield track
def readytomake(file, *comps):
for f in comps:
if not f.exists():
return False
if not f.is_file():
return False
if f.stat().st_size == 0:
return False
fd = os.open(f, os.O_RDONLY | os.O_EXCL)
if fd < 0:
return False
os.close(fd)
if file is None:
return True
if not file.exists():
return True
if file.stat().st_size == 0:
return False
# fd=os.open(file,os.O_WRONLY|os.O_EXCL)
# if fd<0: return False
# os.close(fd)
for f in comps:
if f.stat().st_mtime > file.stat().st_mtime:
file.unlink()
return True
return False
def work_lock_delete():
for l in args.outdir.glob("*.working"):
log.debug(f"Deleting worklock {l} and associated file.")
l.unlink()
try:
l.with_suffix("").unlink()
except FileNotFoundError:
pass
def do_call(cargs, outfile=None, infile=None):
def cookout(s):
s = re.sub(r"\s*\n\s*", r"\n", s)
s = re.sub(r"[^\n]*", r"", s)
s = re.sub(r"\n+", r"\n", s)
s = re.sub(r"\n \*(.*?) \*", r"\n\1", s)
return s.strip()
cs = [[]]
for a in cargs:
if a == "|":
cs.append([])
else:
cs[-1].append(str(a))
cstr = " | ".join([subprocess.list2cmdline(c) for c in cs])
log.debug("Executing: " + cstr)
lockfile = None
if outfile:
lockfile = outfile.with_suffix(f"{outfile.suffix}.working")
if lockfile.exists():
log.warning(f"Lockfile {lockfile} already exists.")
with open(lockfile, "w") as f:
f.truncate(0)
ps = []
for c in cs:
ps.append(
subprocess.Popen(
c,
stdin=ps[-1].stdout if ps else infile,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
)
outstr, errstr = ps[-1].communicate()
# encname='cp1252'/ encname='utf-8'
outstr = outstr.decode(errors="replace")
errstr = errstr.decode(errors="replace")
errstr += "".join(
[p.stderr.read().decode(errors="replace") for p in ps if not p.stderr.closed]
)
outstr = cookout(outstr)
errstr = cookout(errstr)
if outstr:
log.debug("Output: " + repr(outstr))
if errstr:
log.debug("Error: " + repr(errstr))
errcode = ps[-1].poll()
if errcode != 0:
if args.ignore_error:
log.warning("Error code (ignored) for " + repr(cstr) + ": " + str(errcode))
else:
log.error("Error code for " + repr(cstr) + ": " + str(errcode))
if outfile:
open(outfile, "w").truncate(0)
if lockfile is not None:
try:
lockfile.unlink()
except FileNotFoundError:
pass
return outstr + errstr
def make_srt(cfg, track):
base = cfg["base"]
srt = maketrack(cfg)
f = pathlib.Path(f'{base} T{srt["id"]:02d}.srt')
if not f.exists():
do_call(["ccextractorwin", track["file"], "-o", srt["file"]], srt["file"])
if f.exists() and f.stat().st_size == 0:
try:
f.unlink()
except FileNotFoundError:
pass
if not f.exists():
return False
srt["file"] = f
srt["type"] = "subtitles"
srt["delay"] = 0.0
srt["elongation"] = 1.0
srt["extension"] = "srt"
srt["language"] = "eng"
return True
def config_from_base(cfg, base):
cfg["base"] = base
cfg["show"] = base
# cfg['languages'] = ['eng'] # Set if we want to keep only some languages
if m := re.fullmatch(
r"(?P<show>.*?)\s+(pt\.? *(?P<episode>\d+) *)?\((?P<year>\d*)\) *(?P<song>.*?)",
base,
):
cfg["type"] = "movie"
cfg["show"] = m["show"]
if m["episode"]:
cfg["episode"] = int(m["episode"])
if m["year"]:
cfg["year"] = int(m["year"])
cfg["song"] = m["song"]
elif (
m := re.fullmatch(r"(?P<show>.*?)\s+S(?P<season>\d+)E(?P<episode>\d+)$", base)
) or (
m := re.fullmatch(
r"(.*?) (Se\.\s*(?P<season>\d+)\s*)?Ep\.\s*(?P<episode>\d+)$", base
)
):
cfg["type"] = "tvshow"
cfg["show"] = m["show"]
if m["season"] and m["season"] != "0":
cfg["season"] = int(m["season"])
cfg["episode"] = int(m["episode"])
elif (
m := re.fullmatch(r"(?P<show>.*?)\s+S(?P<season>\d+) +(?P<song>.*?)", base)
) or (m := re.fullmatch(r"(.*) Se\. *(?P<season>\d+) *(?P<song>.*?)", base)):
cfg["type"] = "tvshow"
cfg["show"] = m["show"]
cfg["season"] = int(m["season"])
cfg["song"] = m["song"]
elif m := re.fullmatch(
r"(?P<show>.*?)\s+(S(?P<season>\d+))?(V|Vol\. )(?P<episode>\d+)", base
):
cfg["type"] = "tvshow"
cfg["show"] = m["show"]
cfg["season"] = int(m["season"])
cfg["episode"] = int(m["episode"])
elif m := re.fullmatch(r"(?P<show>.*?)\s+S(?P<season>\d+)D\d+", base):
cfg["type"] = "tvshow"
cfg["show"] = m["show"]
cfg["season"] = int(m["season"])
def prepare_avi(cfg, avifile):
try:
xmlroot = ET.fromstring(
subprocess.check_output(["mediainfo", "--output=XML", avifile]).decode(
errors="replace"
)
)
for avitrack in xmlroot.iter("track"):
avittype = avitrack.get("type")
if avittype == "General":
for k in avitrack.iter():
cfg["avi" + "".join(l for l in k.tag.casefold() if l.isalnum())] = k.text
pass
elif avittype == "Video" or avittype == "Audio":
track = maketrack(cfg)
track["type"] = avittype.casefold()
for k in avitrack.iter():
track["avi" + "".join(l for l in k.tag.casefold() if l.isalnum())] = k.text
else:
log.warning(f"Unrecognized avi track type {avittype} in {avifile}")
except ET.ParseError:
return
def prepare_mkv(cfg, mkvfile):
try:
cs = cfg["chapters"] = defdict(
{
"uid": [],
"time": [],
"hidden": [],
"enabled": [],
"name": [],
"lang": [],
"delay": 0.0,
"elongation": 1.0,
}
)
xmlroot = ET.fromstring(
subprocess.check_output(["mkvextract", "chapters", mkvfile]).decode(
errors="replace"
)
)
for chap in xmlroot.iter("ChapterAtom"):
cs["uid"].append(chap.find("ChapterUID").text)
cs["time"].append(to_float(chap.find("ChapterTimeStart").text))
cs["hidden"].append(chap.find("ChapterFlagHidden").text)
cs["enabled"].append(chap.find("ChapterFlagEnabled").text)
cs["name"].append(chap.find("ChapterDisplay").find("ChapterString").text)
v = chap.find("ChapterDisplay").find("ChapterLanguage").text
cs["lang"].append(iso6392BtoT.get(v, v))
except ET.ParseError:
del cfg["chapters"]
j = json.loads(
subprocess.check_output(["mkvmerge", "-J", mkvfile]).decode(errors="replace")
)
jc = j["container"]
contain = cfg["mkvcontainer"] = defdict()
contain["type"] = jc["type"]
for k, v in jc["properties"].items():
if k == "duration":
cfg["duration"] = int(v) / 1000000000.0
else:
contain[k] = v
skip_a_dts = False
base = cfg["base"]
for t in j["tracks"]:
track = maketrack(cfg)
tid = track["id"]
track["mkvtrack"] = t["id"]
track["type"] = t["type"]
track["format"] = t["codec"]
if track["format"] in {
"V_MPEG2",
"MPEG-1/2",
}:
track["extension"] = "mpg"
track["file"] = f"{base} T{tid:02d}.mpg"
track["dgifile"] = f"{base} T{tid:02d}.dgi"
elif track["format"] in {
"V_MPEG4/ISO/AVC",
"MPEG-4p10/AVC/h.264",
"AVC/H.264/MPEG-4p10",
}:
track["extension"] = "264"
track["file"] = f"{base} T{tid:02d}.264"
# track['t2cfile'] = f'{base} T{tid:02d}.t2c'
track["dgifile"] = f"{base} T{tid:02d}.dgi"
elif track["format"] in {
"V_MS/VFW/FOURCC, WVC1",
"VC-1",
}:
track["extension"] = "wvc"
track["file"] = f"{base} T{tid:02d}.wvc"
# track['t2cfile'] = f'{base} T{tid:02d}.t2c'
track["dgifile"] = f"{base} T{tid:02d}.dgi"
elif track["format"] in {
"A_AC3",
"A_EAC3",
"AC3/EAC3",
"AC-3/E-AC-3",
"AC-3",
"E-AC-3",
"AC-3 Dolby Surround EX",
}:
track["extension"] = "ac3"
track["file"] = f"{base} T{tid:02d}.ac3"
track["quality"] = 60
elif track["format"] in {"E-AC-3"}:
log.warning(
f'{cfg["base"]}: Track type {track["format"]} in {mkvfile} not supported, disabling.'
)
track["disable"] = True
track["extension"] = "ac3"
track["file"] = f"{base} T{tid:02d}.ac3"
track["quality"] = 60
elif track["format"] in {
"TrueHD",
"A_TRUEHD",
"TrueHD Atmos",
}:
track["extension"] = "thd"
track["file"] = f"{base} T{tid:02d}.thd"
track["quality"] = 60
skip_a_dts = True
elif track["format"] in {
"DTS-HD Master Audio",
}:
track["extension"] = "dts"
track["file"] = f"{base} T{tid:02d}.dts"
track["quality"] = 60
skip_a_dts = True
elif track["format"] in {
"A_DTS",
"DTS",
"DTS-ES",
"DTS-HD High Resolution",
"DTS-HD High Resolution Audio",
}:
track["extension"] = "dts"
track["file"] = f"{base} T{tid:02d}.dts"
track["quality"] = 60
if skip_a_dts:
track["disable"] = True
skip_a_dts = False
elif track["format"] in {
"A_PCM/INT/LIT",
"PCM",
}:
track["extension"] = "pcm"
track["file"] = f"{base} T{tid:02d}.pcm"
track["quality"] = 60
elif track["format"] in {
"S_VOBSUB",
"VobSub",
}:
track["extension"] = "idx"
track["file"] = f"{base} T{tid:02d}.idx"
elif track["format"] in {
"S_HDMV/PGS",
"HDMV PGS",
"PGS",
}:
track["extension"] = "sup"
track["file"] = f"{base} T{tid:02d}.sup"
elif track["format"] in {
"SubRip/SRT",
}:
track["extension"] = "srt"
track["file"] = f"{base} T{tid:02d}.srt"
elif track["format"] in {
"A_MS/ACM",
}:
track["disable"] = True
else:
log.warning(
f'{cfg["base"]}: Unrecognized track type {track["format"]} in {mkvfile}'
)
track["disable"] = True
for k, v in t["properties"].items():
if k == "language":
track["language"] = iso6392BtoT.get(v, v)
elif k == "display_dimensions":
(w, h) = v.split("x")
track["display_width"] = int(w)
track["display_height"] = int(h)
elif k == "pixel_dimensions":
(w, h) = v.split("x")
track["pixel_width"] = int(w)
track["pixel_height"] = int(h)
# elif k == 'default_track':
# track['defaulttrack'] = int(v)!=0
elif k == "forced_track":
track["forcedtrack"] = int(v) != 0
elif k == "default_duration":
track["frameduration"] = int(v) / 1000000000.0
elif k == "track_name":
track["trackname"] = v
# elif k == 'minimum_timestamp':
# track['delay'] = int(v)/1000000000.0
elif k == "audio_sampling_frequency":
track["samplerate"] = v
elif k == "audio_channels":
track["channels"] = v
# if int(v)>2: track['downmix'] =
else:
track[k] = v
extract = []
for track in tracks(cfg):
file = track["file"]
print(type(file), repr(file))
mkvtrack = track["mkvtrack"]
if (args.keep_video_in_mkv and track["type"] == "video") or (
args.keep_audio_in_mkv and track["type"] == "audio"
):
track["extension"] = "mkv"
track["file"] = mkvfile
elif file and not file.exists() and mkvtrack:
extract.append(f"{mkvtrack:d}:{file}")
if extract:
do_call(["mkvextract", "tracks", mkvfile] + extract)
# for track in tracks(cfg, 'video'):
# make_srt(cfg, track)
tcs = []
for track in tracks(cfg):
if "t2cfile" not in track or "mkvtrack" not in track:
continue
tc = track["t2cfile"]
if not tc.exists() and track["mkvtrack"]:
tcs.append(f'{track["mkvtrack"]}:{track["t2cfile"]}')
if tcs:
do_call(["mkvextract", "timecodes_v2", mkvfile] + tcs)
for track in tracks(cfg):
if track["extension"] != ".sub":
continue
try:
with open(track["t2cfile"], "rt", encoding="utf-8") as fp:
t2cl = [to_float(l) for l in fp]
except ValueError:
log.warning(f'Unrecognized line in {track["t2cfile"]}, skipping.')
if len(t2cl) == 0:
continue
# oframes = track['frames']
# frames = len(t2cl)-1
# if oframes>0 and frames != oframes:
# log.warning(f'Timecodes changed frames in "{file}" from {oframes:d} to {frames:d}')
# cfg.set('frames',frames)
odur = track["duration"]
track["duration"] = dur = t2cl[-1] / 1000.0
if odur and odur > 0 and odur != dur:
log.warning(f'Encoding changed duration in "{file}" from {odur:f} to {dur:f}')
for track in tracks(cfg, "subtitle"):
if track["extension"] != ".sub":
continue
idxfile = track["file"].with_suffix(".idx")
track["timestamp"] = []
with open(idxfile, "rt", encoding="utf-8", errors="replace").read() as fp:
for l in fp:
if re.fullmatch(r"\s*#.*", l):
continue
elif re.fullmatch(r"\s*", l):
continue
elif (
m := re.fullmatch(
r"\s*timestamp:\s*(?P<time>.*),\s*filepos:\s*(?P<pos>[0-9a-fA-F]+)\s*",
l,
)
) and (t := to_float(m["time"])):
track["timestamp"].append(t)
track["filepos"].append(m["pos"])
elif m := re.fullmatch(r"\s*id\s*:\s*(\w+?)\s*, index:\s*(\d+)\s*", l):
track["language"] = m[1] # Convert to 3 character codes
track["langindex"] = m[2]
elif m := re.fullmatch(r"\s*(\w+)\s*:\s*(.*?)\s*", l):
track[m[1]] = m[2]
else:
log.warning(
f'{cfg["base"]}: Ignorning in {idxfile} uninterpretable line: {l}'
)
# remove idx file
if args.delete_source:
try:
mkvfile.unlink()
except FileNotFoundError:
pass
def build_indices(cfg, track):
file = track["file"]
dgifile = track["dgifile"]
logfile = file.with_suffix(".log")
if not dgifile or dgifile.exists():
return False
if dgifile.suffix == ".dgi":
do_call(["DGIndexNV", "-i", file, "-o", dgifile.resolve(), "-h", "-e"], dgifile)
elif dgifile.suffix == ".d2v":
do_call(
[
"dgindex",
"-i",
file.resolve(),
"-o",
dgifile.with_suffix("").resolve(),
"-fo",
"0",
"-ia",
"3",
"-om",
"2",
"-hide",
"-exit",
],
dgifile,
)
else:
return False
dg = track["dg"] = defdict()
while True:
time.sleep(1)
if not logfile.exists():
continue
with open(logfile, "rt", encoding="utf-8", errors="replace") as fp:
for l in fp:
l = l.strip()
if m := re.fullmatch("([^:]*):(.*)", l):
k = "".join(i for i in m[1].casefold() if i.isalnum())
v = m[2].strip()
if not v:
continue
if dg[k] == v:
continue
elif dg[k]:
dg[k] += f";{v}"
else:
dg[k] = v
else:
log.warning(f"Unrecognized DGIndex log line: {repr(l)}")
if dg["info"] == "Finished!":
break
try:
logfile.unlink()
except FileNotFoundError:
pass
track["type"] = "video"
# track['outformat'] = 'h264'
track["outformat"] = "h265"
track["avc_profile"] = "high"
track["x265_preset"] = "slow"
# track['x265_tune'] = 'animation'
# track['x265_output_depth'] = '8'
track["crop"] = "auto"
# = str(arf)
with open(dgifile, "rt", encoding="utf-8", errors="replace") as fp:
dgip = fp.read().split("\n\n")
if len(dgip) != 4:
log.error(f'Malformed index file {track["dgifile"]}')
return False
if re.match("DG(AVC|MPG|VC1)IndexFileNV(14|15|16)", dgip[0]):
if m := re.search(r"\bSIZ *(?P<sizex>\d+) *x *(?P<sizey>\d+)", dgip[3]):
track["picture_width"] = int(m["sizex"])
track["picture_height"] = int(m["sizey"])
else:
log.error(f'No SIZ in {track["dgifile"]}')
return False
if m := re.search(
r"\bCLIP\ *(?P<left>\d+) *(?P<right>\d+) *(?P<top>\d+) *(?P<bottom>\d+)",
dgip[2],
):
w = track["picture_width"] - int(m["left"]) - int(m["right"])
h = track["picture_height"] - int(m["top"]) - int(m["bottom"])
track["macroblocks"] = int(math.ceil(w / 16.0)) * int(math.ceil(h / 16.0))
else:
log.error(f'No CLIP in {track["dgifile"]}')
if "sar" in dg:
track["sample_aspect_ratio"] = to_float(dg["sar"])
elif (
"display_width" in track
and "display_height" in track
and "pixel_width" in track
and "pixel_height" in track
):
dratio = track["display_width"] / track["display_height"]
pratio = track["pixel_width"] / track["pixel_height"]
track["sample_aspect_ratio"] = dratio / pratio
else:
log.warning(f'Guessing 1:1 SAR for {track["dgifile"]}')
track["sample_aspect_ratio"] = 1.0
if m := re.search(r"\bORDER *(?P<order>\d+)", dgip[3]):
track["field_operation"] = int(m["order"])
else:
log.error(f'No ORDER in {track["dgifile"]}')
return False
if m := re.search(r"\bFPS *(?P<num>\d+) */ *(?P<denom>\d+) *", dgip[3]):
track["frame_rate_ratio"] = int(m["num"]) / int(m["denom"])
else:
log.error(f'No FPS in {track["dgifile"]}')
return False
if m := re.search(r"\b(?P<ipercent>\d*(\.\d*)?%) *FILM", dgip[3]):
track["interlace_fraction"] = to_float(m["ipercent"])
else:
log.error(f'No FILM in {track["dgifile"]}')
return False
if track["field_operation"] == 0:
track["interlace_type"] = "PROGRESSIVE"
elif track["interlace_fraction"] > 0.5:
track["interlace_type"] = "FILM"
else:
track["interlace_type"] = "INTERLACE"
# ALSO 'CODED' FRAMES
if m := re.search(r"\bPLAYBACK *(?P<playback>\d+)", dgip[3]):
track["frames"] = int(m["playback"])
else:
log.error(f'No PLAYBACK in {track["dgifile"]}')
return False
else:
log.error(f'Unrecognize index file {track["dgifile"]}')
return False
if track["macroblocks"] <= 1620: # 480p@30fps; 576p@25fps
track["avc_level"] = 3.0
track["x264_rate_factor"] = 16.0
track["x265_rate_factor"] = 17.0
elif track["macroblocks"] <= 3600: # 720p@30fps
track["avc_level"] = 3.1
track["x264_rate_factor"] = 18.0
track["x265_rate_factor"] = 19.0
elif track["macroblocks"] <= 8192: # 1080p@30fps
track["avc_level"] = 4.0
track["x264_rate_factor"] = 19.0
track["x265_rate_factor"] = 20.0
cfg["hdvideo"] = True
elif track["macroblocks"] <= 22080: # 1080p@72fps; 1920p@30fps
track["avc_level"] = 5.0
track["x264_rate_factor"] = 20.0
track["x265_rate_factor"] = 21.0
cfg["hdvideo"] = True
else: # 1080p@120fps; 2048@30fps
track["avc_level"] = 5.1
track["x264_rate_factor"] = 21.0
track["x265_rate_factor"] = 22.0
cfg["hdvideo"] = True
return True
def build_subtitle(cfg, track):
infile = track["file"]
inext = track["extension"]
delay = track["delay"] or 0.0
elong = track["elongation"] or 1.0
if inext == "sup" and args.keep_sup:
track["outfile"] = outfile = infile
elif inext == "sup" and not args.keep_sup:
track["outfile"] = outfile = infile.with_suffix(".idx")
if outfile.exists():
return # Should be not readytomake(outfile,)
call = ["bdsup2sub++", "--resolution", "keep"]
if delay != 0.0:
call += ["--delay", delay]
fps = track["frame_rate_ratio_out"] or cfg["track00"]["frame_rate_ratio_out"]
fps2target = {
24.0: "24p",
24000 / 1001: "24p",
25.0: "25p",
25000 / 1001: "25p",
30.0: "30p",
30000 / 1001: "30p",
}
if fps in fps2target:
call += ["--fps-target", fps2target[fps]]
call += ["--output", outfile, infile]
do_call(call, outfile) # '--fix-invisible',
if not outfile.exists() or not outfile.is_file() or outfile.stat().st_size == 0:
log.error(f"Subtitle {outfile} empty and disabled.")
track["disable"] = True
elif inext == "srt":
track["outfile"] = outfile = infile.with_suffix(".ttxt")
if outfile.exists():
return False # Should be not readytomake(outfile,)
with open(infile, "rt", encoding="utf-8", errors="replace") as i, open(
"temp.srt", "wt", encoding="utf-8", errors="replace"
) as o:
for l in i.read().split("\n\n"):
if l.startswith("\ufeff"):
l = l[1:]
if not l.strip():
continue
elif (
(
m := re.fullmatch(
r"(?s)(?P<beg>\s*\d*\s*)(?P<time1>[0-9,.:]*)(?P<mid> --> )(?P<time2>[0-9,.:]*)(?P<end>.*)",
l,
)
)
and (t1 := to_float(m["time1"]))
and (t2 := to_float(m["time2"]))
and (s1 := t1 * elong + delay) >= 0
and (s2 := t2 * elong + delay) >= 0
):
o.write(
f'{m["beg"]}{unparse_time(s1)}{m["mid"]}{unparse_time(s2)}{m["end"]}\n\n'
)
else:
log.warning(f"Unrecognized line in {infile}: {repr(l)}")
do_call(["mp4box", "-ttxt", "temp.srt"], outfile)
try:
pathlib.Path("temp.ttxt").rename(outfile)
except FileNotFoundError:
pass
try:
pathlib.Path("temp.srt").unlink()
except FileNotFoundError:
pass
elif False: # inext=='idx':
track["outfile"] = outfile = infile.with_suffix(".adj.idx")
subfile = infile.with_suffix(".adj.sub")
if not subfile.exits():
shutil.copy(infile.with_suffix(".sub"), subfile)
if outfile.exists():
return # Should be not readytomake(outfile,)
with open(infile, "rt", encoding="utf-8", errors="replace") as i, open(
outfile, "wt", encoding="utf-8", errors="replace"
) as o:
for l in i:
print(l)
if (
(
m := re.fullmatch(
r"(?s)(?P<beg>\s*timestamp:\s*)\b(?P<time>.*\d)\b(?P<end>.*)",
l,
)
)
and (t := to_float(m["time"]))
and ((s := t * elong + delay) >= 0)
):
l = f'{m["beg"]}{unparse_time(s)}{m["end"]}'
o.write(l)
else:
if elong != 1.0 or delay != 0.0:
log.warning(f'Delay and elongation not implemented for subtitles type "{infile}"')
track["outfile"] = outfile = infile
if not outfile.exists():
track["disable"] = True
return False
return True
def build_audio(cfg, track):
# pylint: disable=used-before-assignment
track["outfile"] = outfile = track["outfile"] or pathlib.Path(
f'{cfg["base"]} T{track["id"]:02d}.m4a'
)
if not readytomake(outfile, track["file"]):
return False
if track["extension"] in (): # ('dts', 'thd'):
call = ["dcadec", "-6", track["file"], "-"]
else:
if track["elongation"] and track["elongation"] != 1.0:
log.warning(f"Audio elongation not implemented")
if track["downmix"] not in (2, 6, None):
log.warning(f'Invalid downmix "{track["downmix"]}"')
call = [
"eac3to",
track["file"],
f'{track["mkvtrack"]+1}:' if track["extension"] == "mkv" else None,
"stdout.wav",
# , '-no2ndpass'
"-log=nul",
f'{track["delay"]*1000.0:+.0f}ms' if track["delay"] else None,
# , '-0,1,2,3,5,6,4' if track['channels']==7 else None
"-down6" if track["downmix"] == 6 else None,
"-downDpl" if track["downmix"] == 2 else None,
"-normalize" if track["normalize"] else None,
"|",
"qaac64",
"--threading",
"--ignorelength",
"--no-optimize",
"--tvbr",
track["quality"] or 60,
"--quality",
"2",
"-",
"-o",
outfile,
]
res = do_call((c for c in call if c), outfile)
if res and (m := re.match(r"\bwrote (\d+\.?\d*) seconds\b", res)):
track["duration"] = to_float(m[1])
if (dur := track["duration"]) and (mdur := cfg["duration"]) and abs(dur - mdur) > 0.5:
log.warning(
f'Audio track "{track["file"]}" duration differs (elongation={mdur/dur})'
)
return True
def build_video(cfg, track):
infile = track["file"]
dgifile = pathlib.Path(track["dgifile"])
fmt2ext = {"h264": ".264", "h265": ".265"}
avsfile = track["avsfile"]
if avsfile is None:
avsfile = track["avsfile"] = args.outdir / infile.with_suffix(".avs").name
else:
avsfile = track["avsfile"] = pathlib.Path(avsfile)
outfile = track["outfile"]
if outfile is None:
if track["outformat"] not in fmt2ext:
log.error(f'{infile}: Unrecognized output format: {track["outformat"]}')
return False
track["outfile"] = outfile = pathlib.Path(
f'{cfg["base"]} T{track["id"]:02d}{fmt2ext[track["outformat"]]}'
)
else:
track["outfile"] = outfile = pathlib.Path(outfile)
if not readytomake(outfile, infile, dgifile):
return False
procs = track["processors"] or 8
avs = [
f"SetMTMode(5,{procs:d})" if procs != 1 else None,
"SetMemoryMax(1024)",
f'DGDecode_mpeg2source("{dgifile}", info=3, idct=4, cpu=3)'
if dgifile.suffix == ".d2v"
else None,
f'DGSource("{dgifile}", deinterlace={1 if track["interlace_type"] in ["VIDEO", "INTERLACE"] else 0:d})\n'
if dgifile.suffix == ".dgi"
else None,
# , 'ColorMatrix(hints = true, interlaced=false)'
"unblock(cartoon=true)"
if track["unblock"] == "cartoon"
or (track["unblock"] == True and track["x264_tune"] == "animation")
else None,
"unblock(photo=true)"
if track["unblock"] == "photo" or (track["unblock"] == True and track["x264_tune"])
else None,
"unblock()" if track["unblock"] == "normal" or track["unblock"] == True else None,