-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·2954 lines (2607 loc) · 115 KB
/
server.py
File metadata and controls
executable file
·2954 lines (2607 loc) · 115 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
from flask import Flask, render_template, request, jsonify, session, send_file, send_from_directory
from flask import Response, stream_with_context
import os
from markupsafe import escape
import random
import time
import logging
import signal
from webrtc_microphone import WebRTCMicrophone, WebRTCMicrophoneManager
import subprocess
import json
import threading
import queue
import configparser
import argparse
import logging
import sys
import socket
import time
import re
DECODER_REGEX = re.compile(r'Using decoder FFmpeg_Decoder for "(?P<path>[^"]+)"')
# Automation phase identifiers
PHASE_IDLE = 'idle'
PHASE_PRE_OPEN_COUNTDOWN = 'pre_open_countdown'
PHASE_PLAYER_SELECTION_COUNTDOWN = 'player_selection_countdown'
PHASE_AWAITING_SONG_START = 'awaiting_song_start'
PHASE_SINGING = 'singing'
PHASE_SCORES_COUNTDOWN = 'scores_countdown'
PHASE_HIGHSCORE_COUNTDOWN = 'highscore_countdown'
PHASE_AWAITING_SONG_LIST = 'awaiting_song_list'
PHASE_NEXT_SONG_COUNTDOWN = 'next_song_countdown'
PHASE_STATUS_MAP = {
PHASE_IDLE: 'idle',
PHASE_PRE_OPEN_COUNTDOWN: 'pre_open_countdown',
PHASE_PLAYER_SELECTION_COUNTDOWN: 'player_selection_countdown',
PHASE_AWAITING_SONG_START: 'awaiting_song_start',
PHASE_SINGING: 'singing',
PHASE_SCORES_COUNTDOWN: 'scores_countdown',
PHASE_HIGHSCORE_COUNTDOWN: 'highscore_countdown',
PHASE_AWAITING_SONG_LIST: 'awaiting_song_list',
PHASE_NEXT_SONG_COUNTDOWN: 'next_song_countdown',
}
VIDEO_PLAYING_REGEX = re.compile(r'(Playing\s+video|Video\s*:|Start\s+video)', re.IGNORECASE)
STATUS_END_ONSHOW_REGEX = re.compile(r'STATUS:\s*End\s*\[OnShow\]', re.IGNORECASE)
log = logging.getLogger('werkzeug')
log.setLevel(logging.WARNING)
class NoSpaceConfigParser(configparser.ConfigParser):
def _write_section(self, fp, section_name, section_items, delimiter):
fp.write(f"[{section_name}]\n")
for key, value in section_items:
if value is not None or not self.allow_no_value:
value = str(value).replace('\n', '\n\t')
fp.write(f"{key}={value}\n")
else:
fp.write(f"{key}\n")
fp.write("\n")
logger = logging.getLogger(__name__)
sessions = {}
microphone_assignments = [None] * 6 # 6 microphones: Blue, Red, Green, Orange, Yellow, Pink
remote_control_user = "" # empty string means free
remote_control_text = ""
# Track last-seen timestamp for each session id (heartbeat from clients)
LAST_SEEN = {}
STALE_SESSION_TIMEOUT = 6.0
# Global rooms mapping: room name -> list of usernames
ROOMS = {
'lobby': [],
'mic1': [],
'mic2': [],
'mic3': [],
'mic4': [],
'mic5': [],
'mic6': []
}
BASE_DIR = os.path.dirname(__file__)
DATA_DIR = os.path.join(BASE_DIR, 'data')
os.makedirs(DATA_DIR, exist_ok=True)
ROOM_CAPACITY_FILE = os.path.join(DATA_DIR, 'room_capacity.json')
def _countdown_overlay_script():
return os.path.join(BASE_DIR, 'countdown_overlay.py')
def _launch_countdown_overlay(seconds):
global OVERLAY_PROCESS
script_path = _countdown_overlay_script()
if not os.path.isfile(script_path):
logger.warning('Countdown overlay script missing at %s; skipping overlay', script_path)
return
if sys.platform.startswith('linux') and not os.environ.get('DISPLAY'):
logger.warning('DISPLAY not set; skipping countdown overlay launch')
return
try:
seconds_int = max(1, int(seconds))
except Exception:
seconds_int = 15
with OVERLAY_LOCK:
if OVERLAY_PROCESS and OVERLAY_PROCESS.poll() is None:
try:
OVERLAY_PROCESS.terminate()
except Exception:
pass
try:
OVERLAY_PROCESS = subprocess.Popen([sys.executable, script_path, str(seconds_int)])
logger.info('Started server-side countdown overlay for %ss', seconds_int)
except Exception:
OVERLAY_PROCESS = None
logger.exception('Failed to launch countdown overlay via %s', script_path)
def _stop_countdown_overlay():
global OVERLAY_PROCESS
with OVERLAY_LOCK:
if OVERLAY_PROCESS and OVERLAY_PROCESS.poll() is None:
try:
OVERLAY_PROCESS.terminate()
logger.debug('Stopped server-side countdown overlay process')
except Exception:
logger.exception('Failed to terminate countdown overlay process')
finally:
OVERLAY_PROCESS = None
else:
OVERLAY_PROCESS = None
# Default per-channel capacity (can be updated at runtime via API)
DEFAULT_ROOM_CAPACITY = {
'mic1': 6,
'mic2': 6,
'mic3': 6,
'mic4': 6,
'mic5': 6,
'mic6': 6
}
ROOM_CAPACITY = {}
# When True, the server runs in control-only mode (no microphone/WebRTC features)
CONTROL_ONLY_MODE = False
# Maximum characters allowed for display names (can be overridden via CLI)
MAX_NAME_LENGTH = 16
PLAYLIST_FILE_LOCK = threading.Lock()
PLAYLIST_STATE_LOCK = threading.Lock()
SONGS_BY_AUDIO = {}
PLAYLIST_THREAD = None
PLAYLIST_THREAD_STOP = threading.Event()
PLAYLIST_LOG_POSITION = 0
PLAYLIST_COUNTDOWN_DEFAULT = 15
USDX_LOG_FILE = None
USDX_LOG_CANDIDATES = []
OVERLAY_PROCESS = None
OVERLAY_LOCK = threading.Lock()
def _default_playlist_state():
return {
'enabled': False,
'status': 'disabled',
'countdown_seconds': PLAYLIST_COUNTDOWN_DEFAULT,
'countdown_deadline': None,
'countdown_token': 0,
'phase_token': 0,
'automation_phase': PHASE_IDLE,
'current_index': 0,
'current_song': None,
'next_song': None,
'pending_index': None,
'pending_song': None,
'last_decoder_path': None,
'auto_added': 0,
'last_error': None,
'last_status_change': time.time(),
'song_started_at': None,
'phase_timeout': None,
'playlist_initialized': False,
'decoder_event_count': 0,
'decoder_last_timestamp': None,
'decoder_last_label': None,
'decoder_score_triggered': False,
}
PLAYLIST_STATE = _default_playlist_state()
def _playlist_audio_key():
if 'args' in globals():
try:
key = getattr(args, 'audio_format', 'm4a')
if key:
return key
except Exception:
pass
return 'm4a'
def _normalize_audio_path(path):
if not path:
return None
candidate = path
if not os.path.isabs(candidate):
candidate = os.path.join(BASE_DIR, candidate)
try:
return os.path.realpath(candidate)
except Exception:
return None
def _normalize_log_candidate(path):
if not path:
return None
expanded = os.path.expanduser(path)
try:
resolved = os.path.realpath(expanded)
except Exception:
resolved = expanded
return resolved
def _build_usdx_log_candidates(custom_path=None):
candidates = []
def _add(path):
normalized = _normalize_log_candidate(path)
if normalized and normalized not in candidates:
candidates.append(normalized)
if custom_path:
_add(custom_path)
usdx_dir = None
if 'args' in globals():
try:
usdx_dir = getattr(args, 'usdx_dir', None)
except Exception:
usdx_dir = None
if usdx_dir:
if not os.path.isabs(usdx_dir):
usdx_dir = os.path.realpath(os.path.join(BASE_DIR, usdx_dir))
_add(os.path.join(usdx_dir, 'Error.log'))
_add(os.path.join(BASE_DIR, '..', 'usdx', 'Error.log'))
_add('~/usdx/Error.log')
_add(os.path.join(BASE_DIR, 'Error.log'))
return candidates
def _set_usdx_log_file(path, seek_end=True):
global USDX_LOG_FILE, PLAYLIST_LOG_POSITION
if not path:
return
USDX_LOG_FILE = path
if not os.path.exists(path):
PLAYLIST_LOG_POSITION = 0
return
try:
with open(path, 'rb') as fh:
fh.seek(0, os.SEEK_END if seek_end else os.SEEK_SET)
if seek_end:
PLAYLIST_LOG_POSITION = fh.tell()
else:
PLAYLIST_LOG_POSITION = 0
except Exception:
PLAYLIST_LOG_POSITION = 0
def _initialize_usdx_log_monitor(custom_path=None):
global USDX_LOG_CANDIDATES
USDX_LOG_CANDIDATES = _build_usdx_log_candidates(custom_path)
selected = None
for candidate in USDX_LOG_CANDIDATES:
if os.path.exists(candidate):
selected = candidate
break
if selected:
_set_usdx_log_file(selected, seek_end=True)
logger.info('Monitoring USDX log file: %s', selected)
else:
if USDX_LOG_CANDIDATES:
logger.warning('USDX log file not found yet; will monitor once available. Candidates: %s', ', '.join(USDX_LOG_CANDIDATES))
_set_usdx_log_file(USDX_LOG_CANDIDATES[0], seek_end=True)
else:
logger.warning('No USDX log file candidates could be determined')
def _ensure_usdx_log_file():
global USDX_LOG_FILE
if USDX_LOG_FILE and os.path.exists(USDX_LOG_FILE):
return True
for candidate in USDX_LOG_CANDIDATES:
if os.path.exists(candidate):
if candidate != USDX_LOG_FILE:
logger.info('Switching USDX log monitor to %s', candidate)
_set_usdx_log_file(candidate, seek_end=True)
return True
return False
def _register_song_entry(entry):
if not entry:
return
audio_key = _playlist_audio_key()
candidates = []
try:
if entry.get(audio_key):
candidates.append(entry.get(audio_key))
except Exception:
pass
for fallback in ('m4a', 'mp3', 'ogg', 'wav'):
if fallback == audio_key:
continue
candidate = entry.get(fallback)
if candidate:
candidates.append(candidate)
seen = set()
for candidate in candidates:
normalized = _normalize_audio_path(candidate)
if normalized and normalized not in seen:
SONGS_BY_AUDIO[normalized] = entry
seen.add(normalized)
def playlist_file_path():
playlist_name = 'SmartMicSession.upl'
usdx_dir = '../usdx'
if 'args' in globals():
try:
playlist_name = args.playlist_name
usdx_dir = args.usdx_dir
except Exception:
pass
base_dir = os.path.dirname(__file__)
return os.path.realpath(os.path.join(base_dir, usdx_dir, 'playlists', playlist_name))
def _read_playlist_lines_unlocked():
try:
with open(playlist_file_path(), 'r', encoding='utf-8') as fh:
return [l.strip() for l in fh if l.strip()]
except FileNotFoundError:
return []
except Exception:
logger.exception('Failed to read playlist file')
return []
def _write_playlist_lines_unlocked(lines):
path = playlist_file_path()
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8') as fh:
for line in lines:
if line:
fh.write(line + '\n')
def get_playlist_lines():
with PLAYLIST_FILE_LOCK:
return list(_read_playlist_lines_unlocked())
def write_playlist_lines(lines):
with PLAYLIST_FILE_LOCK:
_write_playlist_lines_unlocked(lines)
def normalize_playlist_label(raw):
if not raw:
return None
label = str(raw).strip()
if not label:
return None
if ' : ' in label:
artist, title = label.split(':', 1)
return f"{artist.strip()} : {title.strip()}"
if ' - ' in label:
artist, title = label.split('-', 1)
artist = artist.strip()
title = title.strip()
if artist and title:
return f"{artist} : {title}"
return label
def _parse_artist_title_from_txt(entry):
txt_rel = entry.get('txt') if entry else None
if not txt_rel:
return None
try:
candidate_txt = txt_rel
if not os.path.isabs(candidate_txt):
candidate_txt = os.path.realpath(os.path.join(BASE_DIR, candidate_txt))
allowed_root = os.path.realpath(os.path.join(BASE_DIR, args.usdx_dir)) if 'args' in globals() else None
if allowed_root and not candidate_txt.startswith(allowed_root):
return None
if not os.path.exists(candidate_txt):
return None
artist = None
title = None
with open(candidate_txt, 'r', encoding='utf-8', errors='ignore') as fh:
for ln in fh:
s = ln.strip()
if not s:
continue
up = s.upper()
if up.startswith('#ARTIST'):
parts = s.split(':', 1)
artist = parts[1].strip() if len(parts) > 1 else s[len('#ARTIST'):].strip()
elif up.startswith('#TITLE'):
parts = s.split(':', 1)
title = parts[1].strip() if len(parts) > 1 else s[len('#TITLE'):].strip()
if artist and title:
break
if artist and title:
return f"{artist} : {title}"
if artist:
return artist
if title:
return title
except Exception:
logger.exception('Failed to parse artist/title from txt: %s', txt_rel)
return None
def derive_playlist_label(entry):
if not entry:
return None
cached = entry.get('_playlist_label')
if cached:
return cached
label = _parse_artist_title_from_txt(entry)
if not label:
display = entry.get('display')
if display:
label = display
else:
txt_path = entry.get('txt')
if txt_path:
label = os.path.splitext(os.path.basename(txt_path))[0].replace('_', ' ')
label = normalize_playlist_label(label or '')
if label:
entry['_playlist_label'] = label
return label
def _current_countdown_duration(custom_seconds=None):
if custom_seconds is not None:
try:
return max(1, int(custom_seconds))
except Exception:
pass
with PLAYLIST_STATE_LOCK:
base = PLAYLIST_STATE.get('countdown_seconds', PLAYLIST_COUNTDOWN_DEFAULT)
try:
return max(1, int(base))
except Exception:
return PLAYLIST_COUNTDOWN_DEFAULT
def _activate_countdown_phase(phase, duration=None, overlay=True, timeout=None):
duration_val = _current_countdown_duration(duration)
now = time.time()
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
state['automation_phase'] = phase
state['status'] = PHASE_STATUS_MAP.get(phase, phase)
state['countdown_deadline'] = now + duration_val
state['countdown_token'] += 1
state['phase_token'] = state['countdown_token']
state['phase_timeout'] = now + timeout if timeout else None
state['last_status_change'] = now
token = state['countdown_token']
if overlay:
_launch_countdown_overlay(duration_val)
return token, duration_val
def _activate_phase(phase, timeout=None):
now = time.time()
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
state['automation_phase'] = phase
state['status'] = PHASE_STATUS_MAP.get(phase, phase)
state['countdown_deadline'] = None
state['phase_token'] = state.get('countdown_token', 0)
state['phase_timeout'] = now + timeout if timeout else None
state['last_status_change'] = now
if phase == PHASE_AWAITING_SONG_START:
state['decoder_event_count'] = 0
state['decoder_last_timestamp'] = None
state['decoder_last_label'] = None
state['decoder_score_triggered'] = False
def _set_playlist_error(message):
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
state['status'] = 'error'
state['automation_phase'] = PHASE_IDLE
state['countdown_deadline'] = None
state['phase_timeout'] = None
state['decoder_event_count'] = 0
state['decoder_last_timestamp'] = None
state['decoder_last_label'] = None
state['decoder_score_triggered'] = False
state['last_error'] = message
state['last_status_change'] = time.time()
logger.error('Playlist automation error: %s', message)
def _append_random_song_locked(lines):
pool = SONGS_LIST or load_songs_index()
if not pool:
return None
attempts = min(64, len(pool))
seen = set()
while attempts > 0:
entry = random.choice(pool)
if not entry or entry.get('id') in seen:
attempts -= 1
continue
seen.add(entry.get('id'))
label = derive_playlist_label(entry)
if not label or label in lines:
attempts -= 1
continue
lines.append(label)
_write_playlist_lines_unlocked(lines)
entry['upl'] = True
try:
SONGS_BY_ID[str(entry.get('id'))] = entry
except Exception:
pass
_register_song_entry(entry)
return label
attempts -= 1
return None
def append_random_song_to_playlist():
with PLAYLIST_FILE_LOCK:
lines = _read_playlist_lines_unlocked()
added = _append_random_song_locked(lines)
return added
def ensure_playlist_has_entries(min_entries=1):
"""Ensure playlist file has at least `min_entries` entries; return (lines, added_labels)."""
try:
min_required = max(1, int(min_entries))
except Exception:
min_required = 1
added_labels = []
with PLAYLIST_FILE_LOCK:
lines = _read_playlist_lines_unlocked()
while len(lines) < min_required:
added = _append_random_song_locked(lines)
if not added:
break
added_labels.append(added)
lines = _read_playlist_lines_unlocked()
result_lines = list(lines)
return result_lines, added_labels
def refresh_playlist_state_cache(lines=None):
if lines is None:
lines = get_playlist_lines()
with PLAYLIST_STATE_LOCK:
idx = PLAYLIST_STATE.get('current_index', 0)
PLAYLIST_STATE['next_song'] = lines[idx] if idx < len(lines) else None
return PLAYLIST_STATE['next_song']
def _prepare_pending_playlist_entry():
auto_added = False
appended_next_label = None
with PLAYLIST_STATE_LOCK:
target_index = max(0, int(PLAYLIST_STATE.get('current_index', 0) or 0))
with PLAYLIST_FILE_LOCK:
lines = _read_playlist_lines_unlocked()
if target_index >= len(lines):
added_label = _append_random_song_locked(lines)
if added_label:
auto_added = True
lines = _read_playlist_lines_unlocked()
if not lines:
return False, 'Playlist is empty'
if target_index >= len(lines):
target_index = len(lines) - 1
line_to_start = lines[target_index]
if target_index + 1 >= len(lines):
appended_next_label = _append_random_song_locked(lines)
if appended_next_label:
lines = _read_playlist_lines_unlocked()
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
state['pending_index'] = target_index
state['pending_song'] = line_to_start
state['next_song'] = line_to_start
state['phase_timeout'] = None
if auto_added:
state['auto_added'] = state.get('auto_added', 0) + 1
elif appended_next_label:
state['auto_added'] = state.get('auto_added', 0) + 1
logger.info('Prepared pending playlist entry index=%s label=%s (auto_added=%s appended=%s)', target_index, line_to_start, auto_added, bool(appended_next_label))
return True, {'lines': lines, 'target_index': target_index, 'label': line_to_start}
def _handle_song_started(label=None, index=None, lines=None):
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
if state.get('automation_phase') != PHASE_AWAITING_SONG_START:
return
if label is None:
label = state.get('pending_song') or state.get('current_song')
if index is None:
index = state.get('pending_index')
if lines is None:
lines = get_playlist_lines()
state['automation_phase'] = PHASE_SINGING
state['status'] = PHASE_STATUS_MAP.get(PHASE_SINGING, 'singing')
state['countdown_deadline'] = None
state['phase_timeout'] = None
state['song_started_at'] = time.time()
state['decoder_event_count'] = 0
state['decoder_last_timestamp'] = None
state['decoder_last_label'] = label
state['decoder_score_triggered'] = False
state['current_song'] = label
if index is None:
index = state.get('current_index', 0)
state['current_index'] = int(index) + 1 if index is not None else state.get('current_index', 0)
next_idx = state['current_index']
if next_idx is not None and next_idx < len(lines):
state['next_song'] = lines[next_idx]
else:
state['next_song'] = None
state['pending_song'] = None
state['pending_index'] = None
state['last_error'] = None
state['last_status_change'] = time.time()
logger.info('Song playback detected; automation phase set to SINGING for "%s"', label or 'unknown')
def _find_playlist_index_for_label(label, lines, start_at=0):
if not label or not lines:
return None
start_idx = max(0, int(start_at or 0))
for idx in range(start_idx, len(lines)):
if lines[idx] == label:
return idx
for idx in range(0, start_idx):
if lines[idx] == label:
return idx
return None
def _process_decoder_path(audio_path):
normalized = _normalize_audio_path(audio_path)
if not normalized:
return
entry = SONGS_BY_AUDIO.get(normalized)
if not entry:
load_songs_index()
entry = SONGS_BY_AUDIO.get(normalized)
label = derive_playlist_label(entry) if entry else None
lines = get_playlist_lines()
with PLAYLIST_STATE_LOCK:
start_hint = max(0, PLAYLIST_STATE.get('current_index', 0) - 3)
PLAYLIST_STATE['last_decoder_path'] = normalized
automation_phase = PLAYLIST_STATE.get('automation_phase')
current_song = PLAYLIST_STATE.get('current_song')
pending_song = PLAYLIST_STATE.get('pending_song')
pending_index = PLAYLIST_STATE.get('pending_index')
active_label = label or (pending_song if automation_phase == PHASE_AWAITING_SONG_START else current_song)
idx = _find_playlist_index_for_label(active_label, lines, start_hint) if active_label else None
if idx is None:
idx = pending_index if automation_phase == PHASE_AWAITING_SONG_START else start_hint
now = time.time()
if automation_phase == PHASE_AWAITING_SONG_START:
_handle_song_started(active_label, idx, lines)
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
state['decoder_event_count'] = 1
state['decoder_last_timestamp'] = now
state['decoder_last_label'] = active_label
logger.info('Song started: %s (decoder=%s)', active_label or 'unknown', normalized)
return
if automation_phase == PHASE_SINGING:
should_update_label = False
score_count = None
score_delta = None
score_should_trigger = False
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
prev_song = state.get('current_song')
prev_ts = state.get('decoder_last_timestamp')
prev_count = state.get('decoder_event_count', 0) or 0
score_already_triggered = state.get('decoder_score_triggered', False)
label_matches_current = active_label == prev_song if active_label else True
if not label_matches_current and active_label:
state['current_song'] = active_label
if state.get('current_index', 0) < len(lines):
state['next_song'] = lines[state['current_index']]
state['decoder_event_count'] = 1
state['decoder_last_timestamp'] = now
state['decoder_last_label'] = active_label
state['last_status_change'] = time.time()
should_update_label = True
else:
score_count = prev_count + 1
state['decoder_event_count'] = score_count
state['decoder_last_timestamp'] = now
state['decoder_last_label'] = active_label or prev_song
if prev_ts:
score_delta = now - prev_ts
if not score_already_triggered and (score_count >= 3 or (score_delta is not None and score_delta >= 5.0)):
score_should_trigger = True
if should_update_label:
logger.info('Updated current song to %s based on decoder log', label)
return
if score_should_trigger and score_count:
if _trigger_scores_countdown():
if score_delta is not None:
logger.info('Detected decoder replay after song completion; starting score confirmation countdown (count=%d, Δt=%.2fs)', score_count, score_delta)
else:
logger.info('Detected decoder replay after song completion; starting score confirmation countdown (count=%d)', score_count)
else:
logger.debug('Decoder replay detected but scores countdown already active (count=%d)', score_count)
return
def playlist_status_payload(lines=None):
if lines is None:
lines = get_playlist_lines()
with PLAYLIST_STATE_LOCK:
state = dict(PLAYLIST_STATE)
now = time.time()
countdown_remaining = 0
if state.get('countdown_deadline'):
countdown_remaining = max(0, int(state['countdown_deadline'] - now))
countdown_active = state.get('countdown_deadline') is not None and countdown_remaining > 0
status_text = {
'disabled': 'Playlist mode disabled',
'idle': 'Idle — ready for next song',
'countdown': 'Countdown in progress',
'pre_open_countdown': 'Preparing playlist…',
'next_song_countdown': 'Next song countdown',
'player_selection_countdown': 'Player selection countdown',
'arming': 'Arming next song',
'awaiting_decoder': 'Starting song…',
'awaiting_song_start': 'Waiting for song to start…',
'singing': 'Song in progress',
'scores_countdown': 'Review scores in…',
'awaiting_scores_confirmation': 'Waiting to confirm scores…',
'highscore_countdown': 'Highscore countdown',
'awaiting_song_list': 'Waiting for song list…',
'error': 'Error'
}.get(state.get('status'), state.get('status', 'idle'))
return {
'enabled': state.get('enabled', False),
'status': state.get('status'),
'automation_phase': state.get('automation_phase'),
'status_text': status_text,
'current_index': state.get('current_index', 0),
'current_song': state.get('current_song'),
'next_song': state.get('next_song'),
'playlist_length': len(lines),
'countdown_seconds': state.get('countdown_seconds', PLAYLIST_COUNTDOWN_DEFAULT),
'countdown_remaining': countdown_remaining,
'countdown_active': countdown_active,
'last_decoder_path': state.get('last_decoder_path'),
'auto_added': state.get('auto_added', 0),
'lock_controls': state.get('enabled', False),
'last_error': state.get('last_error')
}
def set_playlist_enabled(enabled, countdown_seconds=None):
logger.info(f'set_playlist_enabled: enabled={enabled}, countdown_seconds={countdown_seconds}')
if enabled:
min_required = 2
lines, added_labels = ensure_playlist_has_entries(min_required)
auto_seed_count = len(added_labels)
if auto_seed_count:
logger.info('Playlist auto-seeded with %s before enabling mode', ', '.join(added_labels))
else:
lines = get_playlist_lines()
auto_seed_count = 0
if enabled and len(lines) < 2:
raise RuntimeError('Playlist is empty and no songs could be auto-added')
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
state['enabled'] = bool(enabled)
if countdown_seconds is not None:
try:
state['countdown_seconds'] = max(1, int(countdown_seconds))
except Exception:
state['countdown_seconds'] = PLAYLIST_COUNTDOWN_DEFAULT
state['countdown_deadline'] = None
state['countdown_token'] += 1
state['phase_token'] = state['countdown_token']
state['last_error'] = None
state['automation_phase'] = PHASE_IDLE
state['phase_timeout'] = None
state['playlist_initialized'] = False
state['pending_song'] = None
state['pending_index'] = None
if not state['enabled']:
state['auto_added'] = 0
state['decoder_event_count'] = 0
state['decoder_last_timestamp'] = None
state['decoder_last_label'] = None
state['decoder_score_triggered'] = False
if state['enabled']:
state['status'] = 'idle'
state['current_index'] = 0
state['current_song'] = None
state['next_song'] = lines[0] if lines else None
state['auto_added'] = auto_seed_count
else:
state['status'] = 'disabled'
state['current_song'] = None
state['next_song'] = None
if not enabled:
_stop_countdown_overlay()
return playlist_status_payload(lines)
def request_playlist_countdown(custom_seconds=None):
duration = _current_countdown_duration(custom_seconds)
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
if not state.get('enabled'):
return False, 'Playlist mode is not enabled'
phase = state.get('automation_phase', PHASE_IDLE)
if phase not in (PHASE_IDLE, PHASE_AWAITING_SONG_LIST):
return False, 'Playlist automation is busy'
state['countdown_seconds'] = duration
# Ensure playlist has entries before starting automation
try:
ensure_playlist_has_entries(2)
except Exception as exc:
logger.exception('Failed to ensure playlist entries: %s', exc)
return False, str(exc)
if not _is_playlist_initialized():
ok, error = _begin_initial_playlist_sequence(duration)
else:
ok, error = _select_next_song_with_countdown(duration)
if not ok:
return False, error
with PLAYLIST_STATE_LOCK:
token = PLAYLIST_STATE.get('countdown_token')
logger.info('Playlist countdown started for %ss (token=%s)', duration, token)
return True, token
def trigger_playlist_sequence_immediately(custom_seconds=None):
"""Start automation immediately by opening playlist and beginning countdown."""
logger.info(f'trigger_playlist_sequence_immediately: custom_seconds={custom_seconds}')
duration = _current_countdown_duration(custom_seconds)
with PLAYLIST_STATE_LOCK:
PLAYLIST_STATE['countdown_seconds'] = duration
ok, error = _begin_initial_playlist_sequence(duration)
if not ok:
return False, error
return True, None
def _is_playlist_initialized():
with PLAYLIST_STATE_LOCK:
return bool(PLAYLIST_STATE.get('playlist_initialized'))
def _begin_initial_playlist_sequence(duration):
ok, info = _prepare_pending_playlist_entry()
if not ok:
return False, info
ok, error = _send_playlist_open_sequence()
if not ok:
return False, error
with PLAYLIST_STATE_LOCK:
state = PLAYLIST_STATE
state['playlist_initialized'] = True
state['automation_phase'] = PHASE_NEXT_SONG_COUNTDOWN
_activate_countdown_phase(PHASE_NEXT_SONG_COUNTDOWN, duration)
logger.info('Initial playlist sequence started; countdown to confirm song initiated')
return True, None
def _select_next_song_with_countdown(duration):
ok, error = _send_playlist_select_next_song_sequence()
if not ok:
return False, error
_activate_countdown_phase(PHASE_NEXT_SONG_COUNTDOWN, duration)
logger.info('Advanced to next playlist entry; countdown before confirming song initiated')
return True, None
def _run_playlist_command_sequence(commands):
for cmd in commands:
if cmd[0] == 'delay':
try:
delay_sec = max(0.05, float(cmd[1]))
except Exception:
delay_sec = 0.1
# Show countdown overlay for delays >= 2s (player selection phase)
if delay_sec >= 2:
try:
_launch_countdown_overlay(int(delay_sec))
except Exception as e:
logger.warning(f'Failed to launch overlay during playlist delay: {e}')
time.sleep(delay_sec)
continue
ok, out = run_xdotool_command(cmd)
if not ok:
return False, out or 'xdotool failure'
time.sleep(0.05)
return True, None
def _send_playlist_open_sequence():
commands = [
['key', 'Escape'],
['key', 'Escape'],
['key', 'Escape'],
['key', 'Escape'],
['key', 'Escape'],
['key', 'Escape'],
['key', 'Escape'],
['key', 'Escape'],
['key', 'Escape'],
['key', 'Escape'],
['key', 'Return'], # confirm default singer
['key', 'p'], # open playlist mode selector
['key', 'Return'], # start playlist mode / queue next entry
['key', 'p'], # retry open playlist mode selector
['key', 'Return'], # retry start playlist mode / queue next entry
['key', 'Down'], # move to select playlist entry
['key', 'Down'], # move to select playlist entry
['key', 'Return'], # confirm selection
]
return _run_playlist_command_sequence(commands)
def _send_playlist_confirm_song_sequence():
commands = [
['key', 'Return']
]
return _run_playlist_command_sequence(commands)
def _send_playlist_confirm_players_sequence():
commands = [
['key', 'Return']
]
return _run_playlist_command_sequence(commands)
def _send_playlist_confirm_scores_sequence():
commands = [
['key', 'Return']
]
return _run_playlist_command_sequence(commands)
def _send_playlist_confirm_highscore_sequence():
commands = [
['key', 'Return']
]
return _run_playlist_command_sequence(commands)
def _send_playlist_select_next_song_sequence():
commands = [
['key', 'Down']
]
return _run_playlist_command_sequence(commands)
def _on_next_song_countdown_expired(expected_token):
with PLAYLIST_STATE_LOCK: