-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
7508 lines (6601 loc) · 303 KB
/
Copy pathmain.py
File metadata and controls
7508 lines (6601 loc) · 303 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
# SPDX-License-Identifier: AGPL-3.0-only
"""Main FastAPI application for FXRoute."""
import json
import logging
import re
import shutil
import time
import asyncio
import hashlib
import random
import subprocess
import tempfile
import zipfile
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, List, Optional
from urllib.parse import unquote
from uuid import uuid4
import uvicorn
from fastapi import FastAPI, Request, HTTPException, WebSocket, WebSocketDisconnect, UploadFile, File, Form
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
from mutagen import File as MutagenFile
from starlette.background import BackgroundTask
from config import get_settings
BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"
COVER_CACHE_DIR = BASE_DIR / "media" / "cache" / "covers"
TOP40_COVER_IMAGE = STATIC_DIR / "Top40.png"
INSTALL_CONFIG_FILE = Path.home() / ".config" / "fxroute" / "install-config.env"
UPDATE_SCRIPT = BASE_DIR / "scripts" / "update_fxroute.sh"
# Cooldown to prevent rapid mpv IPC flooding (ms)
PLAY_COMMAND_COOLDOWN_MS = 400
LOCAL_TRACK_SWITCH_SETTLE_MS = 260
SOURCE_HANDOFF_SETTLE_MS = 260
PIPEWIRE_HANDOFF_RELEASE_TIMEOUT_MS = 1800
PIPEWIRE_HANDOFF_POLL_INTERVAL_MS = 50
PEAK_MONITOR_INACTIVE_GRACE_MS = 450
PEAK_MONITOR_RESTART_SETTLE_MS = 320
PEAK_MONITOR_RATE_MATCH_TIMEOUT_MS = 900
RADIO_SAMPLERATE_RENEGOTIATE_DELAY_MS = 1200
RADIO_SAMPLERATE_PRESET_BOUNCE_DELAY_MS = 350
SPOTIFY_PREARM_SAMPLE_RATE_HZ = 44100
RADIO_RECONNECT_DELAY_SECONDS = 2.0
RADIO_RECONNECT_MAX_ATTEMPTS = 5
SPOTIFY_STATE_POLL_INTERVAL_SECONDS = 2.0
SPOTIFY_STATE_IDLE_POLL_INTERVAL_SECONDS = 5.0
SPOTIFY_STATE_REFRESH_DEBOUNCE_SECONDS = 0.20
MEASUREMENT_WINDOW_TTL_SECONDS = 30.0
# Track last play command time to debounce rapid requests
_last_play_command_time = 0.0
def _path_within_root(path: Path, root: Path) -> bool:
try:
resolved_path = path.resolve()
resolved_root = root.resolve()
except Exception:
return False
return resolved_path == resolved_root or resolved_root in resolved_path.parents
def _can_send_play_command():
"""Debounce rapid play/pause/seek commands to prevent mpv IPC overload."""
global _last_play_command_time
now = time.monotonic()
if now - _last_play_command_time < PLAY_COMMAND_COOLDOWN_MS / 1000:
return False
_last_play_command_time = now
return True
def _cleanup_temp_file(path: Path):
path.unlink(missing_ok=True)
def _read_version_file() -> str:
try:
return (BASE_DIR / "VERSION").read_text(encoding="utf-8").strip()
except Exception:
return ""
def _read_build_id() -> str:
version = _read_version_file() or "unknown-version"
try:
deployed_build = (BASE_DIR / "BUILD_ID").read_text(encoding="utf-8").strip()
if deployed_build:
return f"{version} {deployed_build}"
except Exception:
pass
try:
completed = subprocess.run(
["git", "-C", str(BASE_DIR), "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
check=False,
timeout=1.5,
)
commit = completed.stdout.strip() if completed.returncode == 0 else ""
except Exception:
commit = ""
return f"{version} commit={commit or 'unknown'}"
def _read_install_config() -> dict:
data: dict[str, str] = {}
try:
for raw_line in INSTALL_CONFIG_FILE.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
data[key.strip()] = value.strip()
except Exception:
pass
return data
def _configured_service_name() -> str:
return _read_install_config().get("FXROUTE_SERVICE_NAME") or "fxroute"
async def _run_update_script(*args: str) -> dict:
if not UPDATE_SCRIPT.exists():
raise HTTPException(status_code=500, detail=f"Update script missing: {UPDATE_SCRIPT}")
proc = await asyncio.create_subprocess_exec(
str(UPDATE_SCRIPT),
*args,
cwd=str(BASE_DIR),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await proc.communicate()
return {
"returncode": proc.returncode,
"stdout": stdout.decode(errors="replace"),
"stderr": stderr.decode(errors="replace"),
}
async def _restart_fxroute_service_after_response(service_name: str) -> None:
await asyncio.sleep(0.8)
try:
proc = await asyncio.create_subprocess_exec(
"systemctl",
"--user",
"restart",
f"{service_name}.service",
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await proc.wait()
except Exception as exc:
logger.warning("Deferred FXRoute service restart failed: %s", exc)
def _list_sink_inputs() -> list[dict]:
try:
completed = subprocess.run(["pactl", "list", "sink-inputs"], capture_output=True, text=True, check=False, timeout=1.5)
except Exception:
return []
if completed.returncode != 0:
return []
entries: list[dict] = []
current: dict | None = None
in_properties = False
for raw_line in completed.stdout.splitlines():
if raw_line.startswith("Sink Input #"):
if current:
entries.append(current)
current = {"id": raw_line.split("#", 1)[1].strip(), "properties": {}}
in_properties = False
continue
if current is None:
continue
stripped = raw_line.strip()
if stripped.startswith("Sample Specification:"):
match = re.search(r"(\d+)\s*Hz\b", stripped)
if match:
try:
current["sample_rate"] = int(match.group(1))
except ValueError:
pass
continue
if stripped == "Properties:":
in_properties = True
continue
if not stripped:
in_properties = False
continue
if in_properties:
if " = " not in stripped:
continue
key, value = stripped.split(" = ", 1)
current["properties"][key.strip()] = value.strip().strip('"')
if current:
entries.append(current)
return entries
def _list_mpv_sink_inputs() -> list[dict]:
return [
entry
for entry in _list_sink_inputs()
if (entry.get("properties") or {}).get("application.name") == "mpv"
or (entry.get("properties") or {}).get("application.id") == "mpv"
or (entry.get("properties") or {}).get("node.name") == "mpv"
]
def _list_spotify_sink_inputs() -> list[dict]:
return [
entry
for entry in _list_sink_inputs()
if (entry.get("properties") or {}).get("application.name") == "spotify"
or (entry.get("properties") or {}).get("application.id") == "spotify"
or (entry.get("properties") or {}).get("node.name") == "spotify"
or (entry.get("properties") or {}).get("media.name") == "Spotify"
]
def _get_first_sink_input_samplerate(entries: list[dict]) -> Optional[int]:
for entry in entries:
rate = entry.get("sample_rate")
if isinstance(rate, int) and rate > 0:
return rate
return None
async def _wait_for_sink_input_release(list_fn, timeout_ms: int) -> bool:
deadline = time.monotonic() + max(timeout_ms, 0) / 1000
while time.monotonic() <= deadline:
if not list_fn():
return True
await asyncio.sleep(PIPEWIRE_HANDOFF_POLL_INTERVAL_MS / 1000)
return not list_fn()
async def _wait_for_pipewire_mpv_release(timeout_ms: int = PIPEWIRE_HANDOFF_RELEASE_TIMEOUT_MS) -> bool:
return await _wait_for_sink_input_release(_list_mpv_sink_inputs, timeout_ms)
async def _wait_for_pipewire_spotify_release(timeout_ms: int = PIPEWIRE_HANDOFF_RELEASE_TIMEOUT_MS) -> bool:
return await _wait_for_sink_input_release(_list_spotify_sink_inputs, timeout_ms)
async def _wait_for_pipewire_spotify_samplerate_alignment(
timeout_ms: int = PIPEWIRE_HANDOFF_RELEASE_TIMEOUT_MS,
) -> tuple[bool, Optional[int], Optional[int]]:
deadline = time.monotonic() + max(timeout_ms, 0) / 1000
last_stream_rate: Optional[int] = None
last_sink_rate: Optional[int] = None
while time.monotonic() <= deadline:
spotify_inputs = _list_spotify_sink_inputs()
last_stream_rate = _get_first_sink_input_samplerate(spotify_inputs)
if spotify_inputs and last_stream_rate:
try:
samplerate_status = get_samplerate_status()
except Exception:
samplerate_status = {}
sink_rate = samplerate_status.get("active_rate")
last_sink_rate = sink_rate if isinstance(sink_rate, int) and sink_rate > 0 else None
if last_sink_rate == last_stream_rate:
return True, last_stream_rate, last_sink_rate
await asyncio.sleep(PIPEWIRE_HANDOFF_POLL_INTERVAL_MS / 1000)
return False, last_stream_rate, last_sink_rate
async def _recover_spotify_samplerate_alignment() -> tuple[bool, Optional[int], Optional[int]]:
"""Retry a stuck Spotify start with one controlled pause/play release cycle."""
global source_transition_lock
if source_transition_lock is None:
source_transition_lock = asyncio.Lock()
async with source_transition_lock:
data = await spotify_pause()
released = await _wait_for_pipewire_spotify_release()
if not released:
await asyncio.sleep(SOURCE_HANDOFF_SETTLE_MS / 1000)
await _prearm_spotify_samplerate("spotify-recovery")
data = await spotify_play()
if data.get("status") != "Playing":
return False, None, None
return await _wait_for_pipewire_spotify_samplerate_alignment()
async def _complete_spotify_entry_handoff() -> dict:
global spotify_samplerate_recovery_active
await pause_local_playback_for_spotify_broadcast()
await _prearm_spotify_samplerate("spotify-entry-handoff")
await asyncio.sleep(SOURCE_HANDOFF_SETTLE_MS / 1000)
data = await spotify_play()
if data.get("status") == "Playing":
aligned, stream_rate, sink_rate = await _wait_for_pipewire_spotify_samplerate_alignment()
if not aligned and not spotify_samplerate_recovery_active:
logger.warning(
"Spotify samplerate did not align on entry handoff; leaving recovery to watcher: spotify_stream_rate=%s sink_rate=%s",
stream_rate,
sink_rate,
)
elif not aligned:
logger.info(
"Spotify samplerate still settling during active recovery: spotify_stream_rate=%s sink_rate=%s",
stream_rate,
sink_rate,
)
return data
async def _wait_for_samplerate_alignment(expected_rate: Optional[int], timeout_ms: int = PEAK_MONITOR_RATE_MATCH_TIMEOUT_MS) -> bool:
if not expected_rate or expected_rate <= 0:
return False
deadline = time.monotonic() + max(timeout_ms, 0) / 1000
while time.monotonic() <= deadline:
try:
samplerate_status = get_samplerate_status()
except Exception:
samplerate_status = {}
sink_rate = samplerate_status.get("active_rate")
if isinstance(sink_rate, int) and sink_rate == expected_rate:
return True
await asyncio.sleep(PIPEWIRE_HANDOFF_POLL_INTERVAL_MS / 1000)
return False
def _set_pipewire_force_rate(rate: int) -> None:
completed = subprocess.run(
["pw-metadata", "-n", "settings", "0", "clock.force-rate", str(rate)],
capture_output=True,
text=True,
check=False,
timeout=1.5,
)
if completed.returncode != 0:
stderr = (completed.stderr or "").strip()
raise RuntimeError(stderr or f"pw-metadata clock.force-rate {rate} failed")
async def _release_local_samplerate_prearm(expected_rate: int, generation: int, reason: str) -> None:
global local_samplerate_prearm_generation, radio_samplerate_force_rate
try:
aligned = await _wait_for_samplerate_alignment(expected_rate, timeout_ms=1200)
if generation != local_samplerate_prearm_generation:
return
if current_track_info and current_track_info.get("source") in {"local", "radio"}:
radio_samplerate_force_rate = expected_rate
logger.info(
"Local samplerate pre-arm retained for active playback: reason=%s expected_rate=%s aligned=%s source=%s",
reason,
expected_rate,
aligned,
current_track_info.get("source"),
)
return
_set_pipewire_force_rate(0)
logger.info(
"Local samplerate pre-arm released: reason=%s expected_rate=%s aligned=%s",
reason,
expected_rate,
aligned,
)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.warning(
"Local samplerate pre-arm release failed: reason=%s expected_rate=%s error=%s",
reason,
expected_rate,
exc,
)
async def _prearm_known_local_samplerate(track_info: dict | None, reason: str) -> tuple[Optional[int], Optional[int]]:
global local_samplerate_prearm_generation, radio_samplerate_force_rate
track_info = track_info or {}
if track_info.get("source") != "local":
return None, None
target_rate = track_info.get("sample_rate_hz")
if not isinstance(target_rate, int) or target_rate <= 0:
logger.info("Local samplerate pre-arm skipped: no known sample_rate_hz reason=%s", reason)
return None, None
try:
samplerate_status = get_samplerate_status()
except Exception as exc:
logger.info("Local samplerate pre-arm skipped: samplerate status unavailable reason=%s error=%s", reason, exc)
return None, None
active_rate = samplerate_status.get("active_rate")
force_rate = samplerate_status.get("force_rate")
allowed_rates = samplerate_status.get("allowed_rates") or []
if allowed_rates and target_rate not in allowed_rates:
logger.info(
"Local samplerate pre-arm skipped: target_rate=%s not in allowed_rates=%s reason=%s",
target_rate,
allowed_rates,
reason,
)
return None, None
if active_rate == target_rate and force_rate in {None, 0, target_rate}:
logger.info(
"Local samplerate pre-arm not needed: reason=%s target_rate=%s active_rate=%s force_rate=%s",
reason,
target_rate,
active_rate,
force_rate,
)
return None, None
_set_pipewire_force_rate(target_rate)
radio_samplerate_force_rate = None
local_samplerate_prearm_generation += 1
generation = local_samplerate_prearm_generation
logger.info(
"Local samplerate pre-arm applied: reason=%s target_rate=%s active_rate=%s force_rate=%s title=%s",
reason,
target_rate,
active_rate,
force_rate,
track_info.get("title") or track_info.get("id"),
)
return target_rate, generation
def _get_current_pipewire_force_rate() -> Optional[int]:
try:
status = get_samplerate_status()
except Exception:
return None
force_rate = status.get("force_rate") if isinstance(status, dict) else None
return force_rate if isinstance(force_rate, int) and force_rate > 0 else 0
async def _ensure_radio_samplerate_force(expected_rate: Optional[int], reason: str) -> bool:
global radio_samplerate_force_rate
if not isinstance(expected_rate, int) or expected_rate <= 0:
return False
try:
samplerate_status = get_samplerate_status()
except Exception:
samplerate_status = {}
active_rate = samplerate_status.get("active_rate") if isinstance(samplerate_status, dict) else None
force_rate = samplerate_status.get("force_rate") if isinstance(samplerate_status, dict) else None
if active_rate == expected_rate and force_rate == expected_rate:
radio_samplerate_force_rate = expected_rate
return True
if force_rate != expected_rate:
_set_pipewire_force_rate(expected_rate)
radio_samplerate_force_rate = expected_rate
logger.info(
"Radio samplerate force-rate applied: reason=%s expected_rate=%s active_rate=%s previous_force_rate=%s",
reason,
expected_rate,
active_rate,
force_rate,
)
return await _wait_for_samplerate_alignment(expected_rate, timeout_ms=1200)
def _clear_radio_samplerate_force_if_active(reason: str) -> None:
global radio_samplerate_force_rate
if not radio_samplerate_force_rate:
return
current_force_rate = _get_current_pipewire_force_rate()
if current_force_rate == radio_samplerate_force_rate:
try:
_set_pipewire_force_rate(0)
logger.info("Radio samplerate force-rate released: reason=%s previous_force_rate=%s", reason, radio_samplerate_force_rate)
except Exception as exc:
logger.warning("Radio samplerate force-rate release failed: reason=%s error=%s", reason, exc)
return
radio_samplerate_force_rate = None
async def _prearm_spotify_samplerate(reason: str) -> None:
global radio_samplerate_force_rate
expected_rate = SPOTIFY_PREARM_SAMPLE_RATE_HZ
try:
samplerate_status = get_samplerate_status()
except Exception:
samplerate_status = {}
active_rate = samplerate_status.get("active_rate") if isinstance(samplerate_status, dict) else None
force_rate = samplerate_status.get("force_rate") if isinstance(samplerate_status, dict) else None
if force_rate != expected_rate:
_set_pipewire_force_rate(expected_rate)
logger.info(
"Spotify samplerate pre-arm applied: reason=%s expected_rate=%s active_rate=%s previous_force_rate=%s",
reason,
expected_rate,
active_rate,
force_rate,
)
radio_samplerate_force_rate = expected_rate
await _wait_for_samplerate_alignment(expected_rate, timeout_ms=700)
def _is_local_playback_active(state: dict | None) -> bool:
state = state or {}
return bool(state.get("current_file") and not state.get("paused") and not state.get("ended"))
def _is_spotify_playback_active(state: dict | None) -> bool:
state = state or {}
return bool(state.get("available") and state.get("status") == "Playing")
def _is_measurement_window_open() -> bool:
if last_measurement_window_seen_at <= 0:
return False
return (time.monotonic() - last_measurement_window_seen_at) <= MEASUREMENT_WINDOW_TTL_SECONDS
def _build_power_state_payload() -> dict:
local_state = player_instance.state if player_instance else {}
spotify_state = latest_spotify_state or {}
playback_active = _is_local_playback_active(local_state) or _is_spotify_playback_active(spotify_state)
measurement_window_open = _is_measurement_window_open()
if measurement_window_open:
reason = "measurement_window"
elif playback_active:
reason = "playback"
else:
reason = "idle"
return {
"amp_should_be_on": bool(playback_active or measurement_window_open),
"reason": reason,
"playback_active": bool(playback_active),
"measurement_window_open": bool(measurement_window_open),
}
def _has_local_footer_context(state: dict | None) -> bool:
state = state or {}
track = current_track_info or state.get("current_track") or {}
source = (track or {}).get("source")
if source not in {"local", "radio"}:
return False
return bool(
state.get("current_file")
or state.get("playing")
or state.get("paused")
or state.get("ended")
)
def _get_authoritative_footer_owner(playback_state: dict | None = None, spotify_state: dict | None = None) -> str:
global current_footer_owner, latest_spotify_state, player_instance
playback_state = playback_state or (player_instance.state if player_instance else {})
spotify_state = spotify_state or latest_spotify_state or {}
if _has_local_footer_context(playback_state):
current_footer_owner = "local"
return current_footer_owner
if _is_spotify_playback_active(spotify_state):
current_footer_owner = "spotify"
return current_footer_owner
return current_footer_owner or "local"
async def _apply_hard_playback_handoff(previous_file: Optional[str], next_url: Optional[str], handoff_reason: Optional[str], transition_reason: str) -> None:
if not player_instance:
return
logger.info(
"Applying hard handoff before %s (%s): %s -> %s",
transition_reason,
handoff_reason,
previous_file,
next_url,
)
player_instance.stop_playback()
released = await _wait_for_pipewire_mpv_release()
if not released:
settle_ms = LOCAL_TRACK_SWITCH_SETTLE_MS if handoff_reason == "manual local track switch" else SOURCE_HANDOFF_SETTLE_MS
logger.warning(
"Timed out waiting for mpv PipeWire stream release before %s; falling back to %sms settle",
transition_reason,
settle_ms,
)
await asyncio.sleep(settle_ms / 1000)
def _dedupe_archive_name(name: str, used_names: set[str]) -> str:
candidate = Path(name or "track").name or "track"
stem = Path(candidate).stem or "track"
suffix = Path(candidate).suffix
index = 2
while candidate in used_names:
candidate = f"{stem}-{index}{suffix}"
index += 1
used_names.add(candidate)
return candidate
from models import (
DeleteFolderRequest,
DeleteTracksRequest,
DownloadTracksRequest,
PlaylistSaveRequest,
PlayRequest,
StationUpsertRequest,
)
from pydantic import BaseModel
from player import get_player, MPVNotInstalledError, MPVError
from stations import add_station, delete_station, get_stations, update_station
from playlists import delete_playlist, get_playlists, save_playlist
from library import AUDIO_EXTENSIONS, LibraryScanner
from downloader import Downloader
from easyeffects import EasyEffectsManager
try:
from hardware_controller import HardwareController
except ImportError:
HardwareController = None
from measurement import MeasurementStore, score_sub_alignment_candidates
from peak_monitor import EasyEffectsPeakMonitor
from subwoofer_runtime import Subwoofer21Runtime, SubwooferRuntimeConfig, DEFAULT_SAMPLE_RATE
REMOVABLE_ARTWORK_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp"}
REMOVABLE_ARTWORK_STEMS = {"cover", "folder", "front", "albumart"}
REMOVABLE_EMPTY_SIDECAR_SUFFIXES = {".m3u", ".m3u8", ".cue", ".log", ".nfo", ".txt"}
def _is_removable_artwork_file(path: Path) -> bool:
if not path.is_file() or path.suffix.lower() not in REMOVABLE_ARTWORK_SUFFIXES:
return False
name = path.name.lower()
stem = path.stem.lower()
folder_stem = path.parent.name.lower()
return stem in REMOVABLE_ARTWORK_STEMS or stem.startswith("albumart") or any(
token in name for token in ("cover", "folder", "front", "album", "artwork")
) or stem == folder_stem
def _is_removable_metadata_sidecar(path: Path) -> bool:
if not path.is_file() or path.suffix.lower() not in REMOVABLE_EMPTY_SIDECAR_SUFFIXES:
return False
return True
def _is_cleanup_only_file(path: Path) -> bool:
if not path.is_file():
return False
return path.suffix.lower() in REMOVABLE_ARTWORK_SUFFIXES or _is_removable_metadata_sidecar(path)
def _folder_has_audio_files(folder: Path) -> bool:
try:
for child in folder.iterdir():
if child.is_file() and child.suffix.lower() in AUDIO_EXTENSIONS:
return True
except OSError:
return False
return False
def _cleanup_track_parent_folder(folder: Path, music_root: Path, protected_folders: Optional[set[Path]] = None) -> dict:
cleaned = {"folder": str(folder), "removed_files": [], "removed_folder": False, "kept": []}
protected = {item.resolve() for item in (protected_folders or set())}
if (
not folder.is_dir()
or not _path_within_root(folder, music_root)
or folder.resolve() == music_root.resolve()
or folder.resolve() in protected
):
return cleaned
if _folder_has_audio_files(folder):
return cleaned
try:
children = list(folder.iterdir())
except OSError as exc:
cleaned["kept"].append({"path": str(folder), "reason": str(exc)})
return cleaned
files = [child for child in children if child.is_file()]
cleanup_only_folder = bool(files) and all(_is_cleanup_only_file(child) for child in files)
for child in children:
if cleanup_only_folder or _is_removable_artwork_file(child) or _is_removable_metadata_sidecar(child):
try:
child.unlink()
cleaned["removed_files"].append(str(child))
except OSError as exc:
cleaned["kept"].append({"path": str(child), "reason": str(exc)})
try:
if not any(folder.iterdir()):
folder.rmdir()
cleaned["removed_folder"] = True
except OSError as exc:
cleaned["kept"].append({"path": str(folder), "reason": str(exc)})
return cleaned
def _resolve_library_folder(folder: str, music_root: Path) -> Path:
requested = Path(str(folder or "").strip().lstrip("/"))
if not str(requested):
raise HTTPException(status_code=400, detail="folder is required")
if requested.is_absolute() or ".." in requested.parts:
raise HTTPException(status_code=400, detail="Invalid folder path")
folder_path = (music_root / requested).resolve()
if folder_path == music_root.resolve() or not _path_within_root(folder_path, music_root):
raise HTTPException(status_code=403, detail="Folder path outside music root")
if not folder_path.is_dir():
raise HTTPException(status_code=404, detail="Folder not found")
return folder_path
from samplerate import (
OUTPUT_MODE_STEREO,
OUTPUT_MODE_SUBWOOFER_21,
SOURCE_MODE_APP_PLAYBACK,
SOURCE_MODE_BLUETOOTH_INPUT,
SOURCE_MODE_EXTERNAL_INPUT,
apply_persisted_audio_output_selection,
disconnect_connected_bluetooth_audio_sources,
get_audio_output_overview,
get_audio_source_overview,
get_bluetooth_audio_overview,
get_samplerate_status,
set_audio_output_mode,
set_audio_output_selection,
set_audio_source_selection,
set_bluetooth_receiver_enabled,
)
from spotify import (
playerctl_available,
spotify_installed,
get_status as spotify_get_status,
play as spotify_play,
pause as spotify_pause,
toggle as spotify_toggle,
next_track as spotify_next,
previous as spotify_previous,
shuffle_toggle as spotify_shuffle_toggle,
loop_cycle as spotify_loop_cycle,
seek_to as spotify_seek_to,
set_volume as spotify_set_volume,
)
from system_volume import SystemVolumeError, get_output_volume, set_output_volume
logger = logging.getLogger(__name__)
UPLOAD_AUDIO_EXTENSIONS = {".mp3", ".flac", ".ogg", ".oga", ".opus", ".m4a", ".aac", ".wav", ".wma", ".webm", ".weba"}
PLAYLIST_FILE_EXTENSIONS = {".m3u", ".m3u8"}
ZIP_IGNORED_PARTS = {"__MACOSX"}
ZIP_IGNORED_FILENAMES = {".ds_store", "thumbs.db"}
# Global instances (initialized on startup)
settings = None
player_instance = None
library_scanner = None
downloader = None
easyeffects_manager = None
measurement_store = None
peak_monitor = None
subwoofer_runtime = None
subwoofer_runtime_link_watch_task = None
hardware_controller = None
peak_monitor_playback_armed = False
peak_monitor_transition_lock = None
peak_monitor_context_signature = None
easyeffects_preset_load_lock = None
source_transition_lock = None
external_input_loopback_module_id = None
external_input_loopback_source_name = None
bluetooth_input_source_name = None
bluetooth_monitor_task = None
bluetooth_agent_process = None
spotify_playerctl_watch_task = None
spotify_playerctl_detect_task = None
spotify_state_refresh_task = None
spotify_state_poll_task = None
spotify_playerctl_last_trigger_at = 0.0
spotify_samplerate_recovery_lock = None
spotify_samplerate_recovery_active = False
local_samplerate_prearm_generation = 0
radio_samplerate_force_rate = None
current_source_mode = SOURCE_MODE_APP_PLAYBACK
latest_spotify_state = None
current_footer_owner = "local"
last_measurement_window_seen_at = 0.0
last_spotify_samplerate_recovery_at = 0.0
last_app_samplerate_drift_repair_at = 0.0
latest_player_state_seq_seen = 0
current_track_info = None
last_track_info = None
radio_reconnect_task = None
radio_reconnect_attempts = 0
radio_reconnect_url = None
radio_reconnect_active_since = 0.0
playback_queue = []
playback_queue_original = []
playback_queue_index = -1
playback_queue_mode = "app_replace"
queue_advancing = False
queue_transition_target_url = None
playback_queue_loop = False
playback_queue_shuffle = False
single_track_loop = False
# WebSocket connection manager
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
logger.info(f"WebSocket connected: {len(self.active_connections)} active")
def disconnect(self, websocket: WebSocket) -> bool:
if websocket not in self.active_connections:
return False
self.active_connections.remove(websocket)
logger.info(f"WebSocket disconnected: {len(self.active_connections)} active")
return True
async def broadcast(self, message: dict):
data = json.dumps(message)
dead = []
for connection in list(self.active_connections):
try:
if connection.client_state.name != "CONNECTED":
dead.append(connection)
continue
await connection.send_text(data)
except Exception as e:
logger.debug(f"WebSocket send failed: {e}")
dead.append(connection)
for conn in set(dead):
self.disconnect(conn)
manager = ConnectionManager()
def _choose_unique_path(path: Path) -> Path:
if not path.exists():
return path
counter = 2
while True:
candidate = path.with_name(f"{path.stem}-{counter}{path.suffix}")
if not candidate.exists():
return candidate
counter += 1
def _choose_unique_dir(path: Path) -> Path:
if not path.exists():
return path
counter = 2
while True:
candidate = path.with_name(f"{path.name}-{counter}")
if not candidate.exists():
return candidate
counter += 1
def _is_safe_relative_zip_path(name: str) -> Optional[Path]:
normalized = name.replace("\\", "/").strip("/")
if not normalized:
return None
candidate = Path(normalized)
if candidate.is_absolute() or any(part in {"", ".", ".."} for part in candidate.parts):
return None
if any(part in ZIP_IGNORED_PARTS for part in candidate.parts):
return None
if candidate.name.lower() in ZIP_IGNORED_FILENAMES:
return None
return candidate
def _extract_zip_album(zip_path: Path, target_root: Path) -> dict:
extracted_files = []
skipped_entries = []
try:
with zipfile.ZipFile(zip_path) as archive:
if archive.testzip() is not None:
raise HTTPException(status_code=400, detail="Invalid ZIP archive")
for member in archive.infolist():
safe_relative = _is_safe_relative_zip_path(member.filename)
if safe_relative is None:
skipped_entries.append(member.filename)
continue
if member.is_dir():
(target_root / safe_relative).mkdir(parents=True, exist_ok=True)
continue
destination = target_root / safe_relative
destination.parent.mkdir(parents=True, exist_ok=True)
if destination.suffix.lower() in UPLOAD_AUDIO_EXTENSIONS:
destination = _choose_unique_path(destination)
with archive.open(member) as source, destination.open("wb") as target:
shutil.copyfileobj(source, target)
extracted_files.append(destination)
except zipfile.BadZipFile:
raise HTTPException(status_code=400, detail="Invalid ZIP archive")
audio_files = [path for path in extracted_files if path.suffix.lower() in UPLOAD_AUDIO_EXTENSIONS]
playlist_files = [path for path in extracted_files if path.suffix.lower() in PLAYLIST_FILE_EXTENSIONS]
return {
"audio_files": audio_files,
"playlist_files": playlist_files,
"extracted_files": extracted_files,
"skipped_entries": skipped_entries,
}
def _parse_m3u_entries(content: str) -> List[str]:
entries = []
for raw_line in (content or "").splitlines():
line = raw_line.strip().lstrip("\ufeff")
if not line or line.startswith("#"):
continue
entries.append(line)
return entries
def _playlist_download_filename(name: str) -> str:
slug = re.sub(r"[^A-Za-z0-9._-]+", "-", (name or "playlist").strip()).strip("-._")
return f"{slug or 'playlist'}.m3u8"
def _track_relative_m3u_path(track) -> str:
if track.path and settings:
try:
return track.path.resolve().relative_to(settings.MUSIC_ROOT.resolve()).as_posix()
except Exception:
pass
return Path(track.url or track.id).name
def _build_m3u_for_playlist(playlist) -> str:
tracks_by_id = {track.id: track for track in library_scanner.get_tracks(refresh=True)}
lines = ["#EXTM3U"]
for track_id in playlist.track_ids:
track = tracks_by_id.get(track_id)
if not track:
continue
duration = int(track.duration) if track.duration and track.duration > 0 else -1
label = track.title or Path(track.path or track_id).stem
if track.artist:
label = f"{track.artist} - {label}"
lines.append(f"#EXTINF:{duration},{label}")
lines.append(_track_relative_m3u_path(track))
return "\n".join(lines) + "\n"
def _build_track_match_index(tracks) -> dict[str, str]:
matches = {}
ambiguous = set()
def add(key: str, track_id: str) -> None:
key = (key or "").replace("\\", "/").strip().lstrip("./").lower()
if not key:
return
if key in matches and matches[key] != track_id:
ambiguous.add(key)
matches.pop(key, None)
return
if key not in ambiguous:
matches[key] = track_id
for track in tracks:
if not track.path:
continue
path = track.path.resolve()
try:
rel = path.relative_to(settings.MUSIC_ROOT.resolve()).as_posix()
add(rel, track.id)
except Exception:
pass
add(path.as_posix(), track.id)
add(path.name, track.id)
if track.url:
add(str(track.url), track.id)
return matches
def _resolve_m3u_track_ids(entries: List[str], base_dir: Optional[Path] = None, tracks=None) -> List[str]:
if tracks is None:
tracks = library_scanner.get_tracks(refresh=True)
match_index = _build_track_match_index(tracks)