-
Notifications
You must be signed in to change notification settings - Fork 1
/
__main__.py
2234 lines (2026 loc) · 83.4 KB
/
__main__.py
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
from collections import deque
from importlib import resources as impresources
from io import BytesIO
import itertools as it
import operator
from pathlib import Path
import re
import tomllib
from typing import NamedTuple, Self, TYPE_CHECKING, cast
from zipfile import ZipFile
if TYPE_CHECKING:
from _typeshed import FileDescriptorOrPath, StrOrBytesPath
from attrs import define
from cattrs import Converter
from PIL import Image, ImageFont
from pydub import AudioSegment
from . import fonts, images, transitions
from .cdg import *
from .config import *
from .pack import *
from .render import *
from .utils import *
import logging
logger = logging.getLogger(__name__)
ASS_REQUIREMENTS = True
try:
import ass
from fontTools import ttLib
from datetime import timedelta
except ImportError:
ASS_REQUIREMENTS = False
MP4_REQUIREMENTS = True
try:
import ffmpeg
except ImportError:
MP4_REQUIREMENTS = False
def file_relative_to(
filepath: "StrOrBytesPath | Path",
*relative_to: "StrOrBytesPath | Path",
) -> Path:
"""
Convert possibly relative filepath to absolute path, relative to any
of the paths in `relative_to`, or to the parent directory of this
very Python file itself.
If the filepath is already absolute, it is returned unchanged.
Otherwise, the first absolute filepath found to exist as a file will
be returned.
Parameters
----------
filepath : path-like
Filepath.
*relative_to
The filepath will be given as relative to these paths.
Returns
-------
`pathlib.Path`
Absolute path relative to given directories, if any exist as
files.
"""
filepath = Path(filepath)
if filepath.is_absolute():
return filepath
# If all else fails, check filepath relative to this file
relative_to += (Path(__file__).parent,)
for rel in relative_to:
outpath = Path(rel) / filepath
if outpath.is_file():
return outpath
raise RuntimeError("File not found")
def sync_to_cdg(cs: int) -> int:
"""
Convert sync time to CDG frame time to the nearest frame.
Parameters
----------
cs : int
Time in centiseconds (100ths of a second).
Returns
-------
int
Equivalent time in CDG frames.
"""
return cs * CDG_FPS // 100
def cdg_to_sync(fs: int) -> int:
"""
Convert CDG frame time to sync time to the nearest centisecond.
Parameters
----------
fs : int
Time in CDG frames.
Returns
-------
int
Equivalent time in centiseconds (100ths of a second).
"""
return fs * 100 // CDG_FPS
@define
class SyllableInfo:
mask: Image.Image
text: str
start_offset: int
end_offset: int
left_edge: int
right_edge: int
lyric_index: int
line_index: int
syllable_index: int
@define
class LineInfo:
image: Image.Image
text: str
syllables: list[SyllableInfo]
x: int
y: int
singer: int
lyric_index: int
line_index: int
class LyricInfo(NamedTuple):
lines: list[LineInfo]
line_tile_height: int
lines_per_page: int
lyric_index: int
@define
class LyricTimes:
line_draw: list[int]
line_erase: list[int]
@define
class LyricState:
line_draw: int
line_erase: int
syllable_line: int
syllable_index: int
draw_queue: deque[CDGPacket]
highlight_queue: deque[list[CDGPacket]]
@define
class ComposerState:
instrumental: int
this_page: int
last_page: int
just_cleared: bool
class KaraokeComposer:
BACKGROUND = 0
BORDER = 1
UNUSED_COLOR = (0, 0, 0)
#region Constructors
# SECTION Constructors
def __init__(
self,
config: Settings,
relative_dir: "StrOrBytesPath | Path" = "",
):
self.config = config
self.relative_dir = Path(relative_dir)
logger.debug("loading config settings")
font_path = self.config.font
try:
font_path = file_relative_to(font_path, self.relative_dir)
except:
pass
self.font = ImageFont.truetype(font_path, self.config.font_size)
# Set color table for lyrics sections
# NOTE At the moment, this only allows for up to 3 singers, with
# distinct color indices for active/inactive fills/strokes.
# REVIEW Could this be smarter? Perhaps if some colors are
# reused/omitted, color indices could be organized in a
# different way that allows for more singers at a time.
self.color_table = [
self.config.background,
self.config.border or self.UNUSED_COLOR,
self.UNUSED_COLOR,
self.UNUSED_COLOR,
]
for singer in self.config.singers:
self.color_table.extend([
singer.inactive_fill,
singer.inactive_stroke,
singer.active_fill,
singer.active_stroke,
])
self.color_table = list(pad(
self.color_table, 16, padvalue=self.UNUSED_COLOR,
))
self.max_tile_height = 0
self.lyrics: list[LyricInfo] = []
# Process lyric sets
for ci, lyric in enumerate(self.config.lyrics):
logger.debug(f"processing config lyric {ci}")
lines: list[list[str]] = []
line_singers: list[int] = []
for textline in re.split(r"\n+", lyric.text):
textline: str
# Assign singer
if "|" in textline:
singer, textline = textline.split("|")
singer = int(singer)
else:
singer = lyric.singer
textline = textline.strip()
# Tildes signify empty lines
if textline == "~":
syllables = []
else:
syllables = [
# Replace underscores in syllables with spaces
syllable.replace("_", " ")
for syllable in it.chain.from_iterable(
# Split syllables at slashes
cast(str, word).split("/")
# Split words after one space and possibly
# before other spaces
for word in re.split(r"(?<= )(?<! ) *", textline)
)
]
logger.debug(f"singer {singer}: {syllables}")
lines.append(syllables)
line_singers.append(singer)
logger.debug(f"rendering line images and masks for lyric {ci}")
line_images, line_masks = render_lines_and_masks(
lines,
font=self.font,
stroke_width=self.config.stroke_width,
stroke_type=self.config.stroke_type,
)
max_height = 0
for li, image in enumerate(line_images):
if image.width > CDG_VISIBLE_WIDTH:
logger.warning(
f"line {li} too wide\n"
f"max width is {CDG_VISIBLE_WIDTH} pixel(s); "
f"actual width is {image.width} pixel(s)\n"
f"\t{''.join(lines[li])}"
)
max_height = max(max_height, image.height)
tile_height = ceildiv(max_height, CDG_TILE_HEIGHT)
self.max_tile_height = max(self.max_tile_height, tile_height)
lyric_lines: list[LineInfo] = []
sync_i = 0
logger.debug(f"setting sync points for lyric {ci}")
for li, (line, singer, line_image, line_mask) in enumerate(zip(
lines, line_singers, line_images, line_masks,
)):
# Center line horizontally
x = (CDG_SCREEN_WIDTH - line_image.width) // 2
# Place line on correct row
y = lyric.row * CDG_TILE_HEIGHT + (
(li % lyric.lines_per_page)
* lyric.line_tile_height * CDG_TILE_HEIGHT
)
# Get enough sync points for this line's syllables
line_sync = lyric.sync[sync_i:sync_i + len(line)]
sync_i += len(line)
if line_sync:
# The last syllable ends 0.45 seconds after it
# starts...
next_sync_point = line_sync[-1] + 45
if sync_i < len(lyric.sync):
# ...or when the first syllable of the next line
# starts, whichever comes first
next_sync_point = min(
next_sync_point,
lyric.sync[sync_i],
)
line_sync.append(next_sync_point)
# Collect this line's syllables
syllables: list[SyllableInfo] = []
for si, (mask, syllable, (start, end)) in enumerate(zip(
line_mask,
line,
it.pairwise(line_sync),
)):
# NOTE Left and right edges here are relative to the
# mask. They will be stored relative to the screen.
left_edge, right_edge = 0, 0
bbox = mask.getbbox()
if bbox is not None:
left_edge, _, right_edge, _ = bbox
syllables.append(SyllableInfo(
mask=mask,
text=syllable,
start_offset=sync_to_cdg(start),
end_offset=sync_to_cdg(end),
left_edge=left_edge + x,
right_edge=right_edge + x,
lyric_index=ci,
line_index=li,
syllable_index=si,
))
lyric_lines.append(LineInfo(
image=line_image,
text="".join(line),
syllables=syllables,
x=x,
y=y,
singer=singer,
lyric_index=ci,
line_index=li,
))
self.lyrics.append(LyricInfo(
lines=lyric_lines,
line_tile_height=tile_height,
lines_per_page=lyric.lines_per_page,
lyric_index=ci,
))
# Add vertical offset to lines to vertically center them
max_height = max(
line.image.height
for lyric in self.lyrics
for line in lyric.lines
)
line_offset = (
self.max_tile_height * CDG_TILE_HEIGHT - max_height
) // 2
logger.debug(
f"lines will be vertically offset by {line_offset} pixel(s)"
)
if line_offset:
for lyric in self.lyrics:
for line in lyric.lines:
line.y += line_offset
self.sync_offset = sync_to_cdg(self.config.sync_offset)
self.writer = CDGWriter()
logger.info("config settings loaded")
self._set_draw_times()
@classmethod
def from_file(
cls,
file: "FileDescriptorOrPath",
) -> Self:
converter = Converter(prefer_attrib_converters=True)
relative_dir = Path(file).parent
with open(file, "rb") as stream:
return cls(
converter.structure(tomllib.load(stream), Settings),
relative_dir=relative_dir,
)
@classmethod
def from_string(
cls,
config: str,
relative_dir: "StrOrBytesPath | Path" = "",
) -> Self:
converter = Converter(prefer_attrib_converters=True)
return cls(
converter.structure(tomllib.loads(config), Settings),
relative_dir=relative_dir,
)
# !SECTION
#endregion
#region Set draw times
# SECTION Set draw times
# Gap between line draw/erase events = 1/6 second
LINE_DRAW_ERASE_GAP = CDG_FPS // 6
# TODO Make more values in these set-draw-times functions into named
# constants
def _set_draw_times(self):
self.lyric_times: list[LyricTimes] = []
for lyric in self.lyrics:
logger.debug(f"setting draw times for lyric {lyric.lyric_index}")
line_count = len(lyric.lines)
line_draw: list[int] = [0] * line_count
line_erase: list[int] = [0] * line_count
# The first page is drawn 3 seconds before the first
# syllable
first_syllable = next(iter(
syllable_info
for line_info in lyric.lines
for syllable_info in line_info.syllables
))
draw_time = first_syllable.start_offset - 900
for i in range(lyric.lines_per_page):
if i < line_count:
line_draw[i] = draw_time
draw_time += self.LINE_DRAW_ERASE_GAP
# For each pair of syllables
for last_wipe, wipe in it.pairwise(
syllable_info
for line_info in lyric.lines
for syllable_info in line_info.syllables
):
# Skip if not on a line boundary
if wipe.line_index <= last_wipe.line_index:
continue
# Set draw times for lines
match self.config.clear_mode:
case LyricClearMode.PAGE:
self._set_draw_times_page(
last_wipe, wipe,
lyric=lyric,
line_draw=line_draw,
line_erase=line_erase,
)
case LyricClearMode.LINE_EAGER:
self._set_draw_times_line_eager(
last_wipe, wipe,
lyric=lyric,
line_draw=line_draw,
line_erase=line_erase,
)
case LyricClearMode.LINE_DELAYED | _:
self._set_draw_times_line_delayed(
last_wipe, wipe,
lyric=lyric,
line_draw=line_draw,
line_erase=line_erase,
)
# If clearing page by page
if self.config.clear_mode == LyricClearMode.PAGE:
# Don't actually erase any lines
line_erase = []
# If we're not clearing page by page
else:
end_line = wipe.line_index
# Calculate the erase time of the last highlighted line
erase_time = wipe.end_offset + 600
line_erase[end_line] = erase_time
erase_time += self.LINE_DRAW_ERASE_GAP
logger.debug(
f"lyric {lyric.lyric_index} draw times: {line_draw!r}"
)
logger.debug(
f"lyric {lyric.lyric_index} erase times: {line_erase!r}"
)
self.lyric_times.append(LyricTimes(
line_draw=line_draw,
line_erase=line_erase,
))
logger.info("draw times set")
def _set_draw_times_page(
self,
last_wipe: SyllableInfo,
wipe: SyllableInfo,
lyric: LyricInfo,
line_draw: list[int],
line_erase: list[int],
):
line_count = len(lyric.lines)
last_page = last_wipe.line_index // lyric.lines_per_page
this_page = wipe.line_index // lyric.lines_per_page
# Skip if not on a page boundary
if this_page <= last_page:
return
# This page starts at the later of:
# - a few frames after the end of the last line
# - 3 seconds before this line
page_draw_time = max(
last_wipe.end_offset + 12,
wipe.start_offset - 900,
)
# Calculate the available time between the start of this line
# and the desired page draw time
available_time = wipe.start_offset - page_draw_time
# Calculate the absolute minimum time from the last line to this
# line
# NOTE This is a sensible minimum, but not guaranteed.
minimum_time = wipe.start_offset - last_wipe.start_offset - 24
# Warn the user if there's not likely to be enough time
if minimum_time < 32:
logger.warning(
"not enough bandwidth to clear screen on lyric "
f"{wipe.lyric_index} line {wipe.line_index}"
)
# If there's not enough time between the end of the last line
# and the start of this line, but there is enough time between
# the start of the last line and the start of this page
if available_time < 32:
# Shorten the last wipe's duration to make room
new_duration = wipe.start_offset - last_wipe.start_offset - 150
if new_duration > 0:
last_wipe.end_offset = last_wipe.start_offset + new_duration
page_draw_time = last_wipe.end_offset + 12
else:
last_wipe.end_offset = last_wipe.start_offset
page_draw_time = last_wipe.end_offset + 32
# Set the draw times for lines on this page
start_line = this_page * lyric.lines_per_page
for i in range(start_line, start_line + lyric.lines_per_page):
if i < line_count:
line_draw[i] = page_draw_time
page_draw_time += self.LINE_DRAW_ERASE_GAP
def _set_draw_times_line_eager(
self,
last_wipe: SyllableInfo,
wipe: SyllableInfo,
lyric: LyricInfo,
line_draw: list[int],
line_erase: list[int],
):
line_count = len(lyric.lines)
last_page = last_wipe.line_index // lyric.lines_per_page
this_page = wipe.line_index // lyric.lines_per_page
# The last line should be erased near the start of this line
erase_time = wipe.start_offset
# If we're not on the next page
if last_page >= this_page:
# The last line is erased 1/3 seconds after the start of
# this line
erase_time += 100
# Set draw and erase times for the last line
for i in range(last_wipe.line_index, wipe.line_index):
if i < line_count:
line_erase[i] = erase_time
erase_time += self.LINE_DRAW_ERASE_GAP
j = i + lyric.lines_per_page
if j < line_count:
line_draw[j] = erase_time
erase_time += self.LINE_DRAW_ERASE_GAP
return
# If we're here, we're on the next page
last_wipe_end = last_wipe.end_offset
inter_wipe_time = wipe.start_offset - last_wipe_end
# The last line is erased at the earlier of:
# - halfway between the pages
# - 1.5 seconds after the last line
erase_time = min(
last_wipe_end + inter_wipe_time // 2,
last_wipe_end + 450,
)
# If time between pages is less than 8 seconds
if inter_wipe_time < 2400:
# Set draw and erase times for the last line
for i in range(last_wipe.line_index, wipe.line_index):
if i < line_count:
line_erase[i] = erase_time
erase_time += self.LINE_DRAW_ERASE_GAP
j = i + lyric.lines_per_page
if j < line_count:
line_draw[j] = erase_time
erase_time += self.LINE_DRAW_ERASE_GAP
# If time between pages is 8 seconds or longer
else:
# Set erase time for the last line
for i in range(last_wipe.line_index, wipe.line_index):
if i < line_count:
line_erase[i] = erase_time
erase_time += self.LINE_DRAW_ERASE_GAP
# The new page will be drawn 3 seconds before the start of
# this line
draw_time = wipe.start_offset - 900
start_line = wipe.line_index
for i in range(start_line, start_line + lyric.lines_per_page):
if i < line_count:
line_draw[i] = draw_time
draw_time += self.LINE_DRAW_ERASE_GAP
def _set_draw_times_line_delayed(
self,
last_wipe: SyllableInfo,
wipe: SyllableInfo,
lyric: LyricInfo,
line_draw: list[int],
line_erase: list[int],
):
line_count = len(lyric.lines)
last_page = last_wipe.line_index // lyric.lines_per_page
this_page = wipe.line_index // lyric.lines_per_page
# If we're on the same page
if last_page == this_page:
# The last line will be erased at the earlier of:
# - 1/3 seconds after the start of this line
# - 1.5 seconds after the end of the last line
erase_time = min(
wipe.start_offset + 100,
last_wipe.end_offset + 450,
)
# Set erase time for the last line
for i in range(last_wipe.line_index, wipe.line_index):
if i < line_count:
line_erase[i] = erase_time
erase_time += self.LINE_DRAW_ERASE_GAP
return
# If we're here, we're on the next page
last_wipe_end = max(
last_wipe.end_offset,
last_wipe.start_offset + 100,
)
inter_wipe_time = wipe.start_offset - last_wipe_end
last_line_start_offset = lyric.lines[
last_wipe.line_index
].syllables[0].start_offset
# The last line will be erased at the earlier of:
# - 1/3 seconds after the start of this line
# - 1.5 seconds after the end of the last line
# - 1/3 of the way between the pages
erase_time = min(
wipe.start_offset + 100,
last_wipe_end + 450,
last_wipe_end + inter_wipe_time // 3,
)
# This line will be drawn at the latest of:
# - 1/3 seconds after the start of the last line
# - 3 seconds before the start of this line
# - 1/3 of the way between the pages
draw_time = max(
last_line_start_offset + 100,
wipe.start_offset - 900,
last_wipe_end + inter_wipe_time // 3,
)
# If time between pages is 4 seconds or more, clear current page
# lines before drawing new page lines
if inter_wipe_time >= 1200:
# Set erase times for lines on previous page
for i in range(last_wipe.line_index, wipe.line_index):
if i < line_count:
line_erase[i] = erase_time
erase_time += self.LINE_DRAW_ERASE_GAP
draw_time = max(draw_time, erase_time)
start_line = last_page * lyric.lines_per_page
# Set draw times for lines on this page
for i in range(start_line, start_line + lyric.lines_per_page):
j = i + lyric.lines_per_page
if j < line_count:
line_draw[j] = draw_time
draw_time += self.LINE_DRAW_ERASE_GAP
return
# If time between pages is less than 4 seconds, draw new page
# lines before clearing current page lines
# The first lines on the next page should be drawn 1/2 seconds
# after the start of the last line
draw_time = last_line_start_offset + 150
# Set draw time for all lines on the next page before this line
start_line = last_page * lyric.lines_per_page
for i in range(start_line, last_wipe.line_index):
j = i + lyric.lines_per_page
if j < line_count:
line_draw[j] = draw_time
draw_time += self.LINE_DRAW_ERASE_GAP
# The last lines on the next page should be drawn at least 1/3
# of the way between the pages
draw_time = max(
draw_time,
last_wipe_end + inter_wipe_time // 3,
)
# Set erase times for the rest of the lines on the previous page
for i in range(last_wipe.line_index, wipe.line_index):
if i < line_count:
line_erase[i] = draw_time
draw_time += self.LINE_DRAW_ERASE_GAP
# Set draw times for the rest of the lines on this page
for i in range(last_wipe.line_index, wipe.line_index):
j = i + lyric.lines_per_page
if j < line_count:
line_draw[j] = draw_time
draw_time += self.LINE_DRAW_ERASE_GAP
# !SECTION
#endregion
#region Compose words
# SECTION Compose words
def compose(self):
# NOTE Logistically, multiple simultaneous lyric sets doesn't
# make sense if the lyrics are being cleared by page.
if (
self.config.clear_mode == LyricClearMode.PAGE
and len(self.lyrics) > 1
):
raise RuntimeError(
"page mode doesn't support more than one lyric set"
)
logger.debug("loading song file")
song: AudioSegment = AudioSegment.from_file(
file_relative_to(self.config.file, self.relative_dir)
)
logger.info("song file loaded")
self.lyric_packet_indices: set[int] = set()
self.instrumental_times: list[int] = []
self.intro_delay = 0
# Compose the intro
# NOTE This also sets the intro delay for later.
self._compose_intro()
lyric_states: list[LyricState] = []
for lyric in self.lyrics:
lyric_states.append(LyricState(
line_draw=0,
line_erase=0,
syllable_line=0,
syllable_index=0,
draw_queue=deque(),
highlight_queue=deque(),
))
composer_state = ComposerState(
instrumental=0,
this_page=0,
last_page=0,
just_cleared=False,
)
# XXX If there is an instrumental section immediately after the
# intro, the screen should not be cleared. The way I'm detecting
# this, however, is by (mostly) copy-pasting the code that
# checks for instrumental sections. I shouldn't do it this way.
current_time = (
self.writer.packets_queued - self.sync_offset
- self.intro_delay
)
should_instrumental = False
instrumental = None
if composer_state.instrumental < len(self.config.instrumentals):
instrumental = self.config.instrumentals[
composer_state.instrumental
]
instrumental_time = sync_to_cdg(instrumental.sync)
# NOTE Normally, this part has code to handle waiting for a
# lyric to finish. If there's an instrumental this early,
# however, there shouldn't be any lyrics to finish.
should_instrumental = current_time >= instrumental_time
# If there should not be an instrumental section now
if not should_instrumental:
logger.debug("instrumental intro is not present; clearing")
# Clear the screen
self.writer.queue_packets([
*memory_preset_repeat(self.BACKGROUND),
*load_color_table(self.color_table),
])
if self.config.border is not None:
self.writer.queue_packet(border_preset(self.BORDER))
else:
logger.debug("instrumental intro is present; not clearing")
# While there are lines to draw/erase, or syllables to
# highlight, or events in the highlight/draw queues, or
# instrumental sections to process
while any(
state.line_draw < len(times.line_draw)
or state.line_erase < len(times.line_erase)
or state.syllable_line < len(lyric.lines)
or state.draw_queue
or state.highlight_queue
for lyric, times, state in zip(
self.lyrics,
self.lyric_times,
lyric_states,
)
) or (
composer_state.instrumental < len(self.config.instrumentals)
):
for lyric, times, state in zip(
self.lyrics,
self.lyric_times,
lyric_states,
):
self._compose_lyric(
lyric=lyric,
times=times,
state=state,
lyric_states=lyric_states,
composer_state=composer_state,
)
# Add audio padding to intro
logger.debug("padding intro of audio file")
intro_silence: AudioSegment = AudioSegment.silent(
self.intro_delay * 1000 // CDG_FPS,
frame_rate=song.frame_rate,
)
self.audio = intro_silence + song
# NOTE If video padding is not added to the end of the song, the
# outro (or next instrumental section) begins immediately after
# the end of the last syllable, which would be abrupt.
if self.config.clear_mode == LyricClearMode.PAGE:
logger.debug(
"clear mode is page; adding padding before outro"
)
self.writer.queue_packets([no_instruction()] * 3 * CDG_FPS)
# Calculate video padding before outro
OUTRO_DURATION = 2400
# This karaoke file ends at the later of:
# - The end of the audio (with the padded intro)
# - 8 seconds after the current video time
end = max(
int(self.audio.duration_seconds * CDG_FPS),
self.writer.packets_queued + OUTRO_DURATION,
)
logger.debug(f"song should be {end} frame(s) long")
padding_before_outro = (
(end - OUTRO_DURATION) - self.writer.packets_queued
)
logger.debug(
f"queueing {padding_before_outro} packets before outro"
)
self.writer.queue_packets([no_instruction()] * padding_before_outro)
# Compose the outro (and thus, finish the video)
self._compose_outro(end)
logger.info("karaoke file composed")
# Add audio padding to outro (and thus, finish the audio)
logger.debug("padding outro of audio file")
outro_silence: AudioSegment = AudioSegment.silent(
(
(self.writer.packets_queued * 1000 // CDG_FPS)
- int(self.audio.duration_seconds * 1000)
),
frame_rate=song.frame_rate,
)
self.audio += outro_silence
# Write CDG and MP3 data to ZIP file
outname = self.config.outname
zipfile_name = self.relative_dir / Path(f"{outname}.zip")
logger.debug(f"creating {zipfile_name}")
with ZipFile(zipfile_name, "w") as zipfile:
cdg_bytes = BytesIO()
logger.debug("writing cdg packets to stream")
self.writer.write_packets(cdg_bytes)
logger.debug(
f"writing stream to zipfile as {outname}.cdg"
)
cdg_bytes.seek(0)
zipfile.writestr(f"{outname}.cdg", cdg_bytes.read())
mp3_bytes = BytesIO()
logger.debug("writing mp3 data to stream")
self.audio.export(mp3_bytes, format="mp3")
logger.debug(
f"writing stream to zipfile as {outname}.mp3"
)
mp3_bytes.seek(0)
zipfile.writestr(f"{outname}.mp3", mp3_bytes.read())
logger.info(f"karaoke files written to {zipfile_name}")
def _compose_lyric(
self,
lyric: LyricInfo,
times: LyricTimes,
state: LyricState,
lyric_states: list[LyricState],
composer_state: ComposerState,
):
current_time = (
self.writer.packets_queued - self.sync_offset
- self.intro_delay
)
should_draw_this_line = False
line_draw_info, line_draw_time = None, None
if state.line_draw < len(times.line_draw):
line_draw_info = lyric.lines[state.line_draw]
line_draw_time = times.line_draw[state.line_draw]
should_draw_this_line = current_time >= line_draw_time
should_erase_this_line = False
line_erase_info, line_erase_time = None, None
if state.line_erase < len(times.line_erase):
line_erase_info = lyric.lines[state.line_erase]
line_erase_time = times.line_erase[state.line_erase]
should_erase_this_line = current_time >= line_erase_time
# If we're clearing lyrics by page and drawing a new line
if (
self.config.clear_mode == LyricClearMode.PAGE
and should_draw_this_line
):
composer_state.last_page = composer_state.this_page
composer_state.this_page = (
line_draw_info.line_index // lyric.lines_per_page
)
# If this line is the start of a new page
if composer_state.this_page > composer_state.last_page:
logger.debug(
f"going from page {composer_state.last_page} to "
f"page {composer_state.this_page} in page mode"
)
# If we have not just cleared the screen
if not composer_state.just_cleared:
logger.debug("clearing screen on page transition")
# Clear the last page
page_clear_packets = [
*memory_preset_repeat(self.BACKGROUND),
]
if self.config.border is not None:
page_clear_packets.append(border_preset(self.BORDER))
self.lyric_packet_indices.update(range(
self.writer.packets_queued,
self.writer.packets_queued + len(page_clear_packets),
))
self.writer.queue_packets(page_clear_packets)
composer_state.just_cleared = True
# Update the current frame time
current_time += len(page_clear_packets)
else:
logger.debug("not clearing screen on page transition")
# Queue the erasing of this line if necessary
if should_erase_this_line:
assert line_erase_info is not None
logger.debug(
f"t={self.writer.packets_queued}: erasing lyric "
f"{line_erase_info.lyric_index} line "
f"{line_erase_info.line_index}"
)
if line_erase_info.text.strip():
state.draw_queue.extend(line_image_to_packets(
line_erase_info.image,
xy=(line_erase_info.x, line_erase_info.y),
background=self.BACKGROUND,
erase=True,
))
else:
logger.debug("line is blank; not erased")
state.line_erase += 1
# Queue the drawing of this line if necessary
if should_draw_this_line:
assert line_draw_info is not None
logger.debug(