-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplayer.py
More file actions
808 lines (701 loc) · 33.8 KB
/
Copy pathplayer.py
File metadata and controls
808 lines (701 loc) · 33.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
#!/usr/bin/env python3
"""
Vinyl AirPlay: Catalog Playback Engine
Decodes recorded album FLAC files and feeds PCM at real-time rate
into AirPlay streams (or any list of AsyncAudioStream-like objects).
Flow:
1. Build playlist from album_audio records + track timestamps
2. Decode FLAC → raw PCM via ffmpeg subprocess pipe
3. Feed PCM chunks through EQ → AsyncAudioStreams at real-time rate
4. Track position and fire Now Playing callbacks at track boundaries
5. Support pause/resume/stop/seek/next/prev
"""
import subprocess
import threading
import time
from collections.abc import Callable
from pathlib import Path
import numpy as np
# ── Audio Constants (must match main.py) ─────────────────────────────────────
SAMPLE_RATE = 44100
CHANNELS = 2
BITS = 16
BYTES_PER_SAMPLE = CHANNELS * (BITS // 8) # 4 bytes per frame
BYTES_PER_SEC = SAMPLE_RATE * BYTES_PER_SAMPLE # 176,400 bytes/sec
# Feed chunks of this many frames at a time (~93ms per chunk)
CHUNK_FRAMES = 4096
CHUNK_BYTES = CHUNK_FRAMES * BYTES_PER_SAMPLE # 16,384 bytes
CHUNK_SECS = CHUNK_FRAMES / SAMPLE_RATE # ~0.0929s
# Anti-pop fade: 500ms covers the needle-drop transient that gets captured
# at the start of each side's recording (typically 70-350ms, up to 75% peak).
# The lead-in groove before music starts is usually 1-2s, so 500ms is safe.
FADE_IN_MS = 500
FADE_IN_FRAMES = int(SAMPLE_RATE * FADE_IN_MS / 1000) # ~22050 samples
# Short silence pre-fill for ALSA device settling (used in LocalOutputStream)
SILENCE_MS = 30
SILENCE_FRAMES = int(SAMPLE_RATE * SILENCE_MS / 1000)
# ── Playlist Entry ───────────────────────────────────────────────────────────
class PlaylistEntry:
"""One playable segment.
By default an entry represents one whole side of an album (one FLAC
file played from start to end). For track-level shuffle and similar,
pass source_offset_secs and source_duration_secs to make an entry
represent a single track range within a side's FLAC; ffmpeg will be
started with -ss source_offset_secs -t source_duration_secs so the
decoded PCM is exactly that track and nothing else.
Position semantics inside the player are entry-local: self._position
counts from 0 at the start of the entry, regardless of where the
entry sits within its source file.
"""
def __init__(self, audio_path: str, side: str, duration_secs: float,
tracks: list[dict], album_id: int | None = None,
album_title: str | None = None, album_artist: str | None = None,
artwork_path: str | None = None,
source_offset_secs: float = 0.0,
source_duration_secs: float | None = None):
self.audio_path = audio_path
self.side = side
self.duration_secs = duration_secs
# tracks: list of {id, title, artist, start_secs, end_secs, track_number}
# sorted by start_secs
self.tracks = sorted(tracks, key=lambda t: t.get("start_secs") or 0)
# Optional per-entry album info (used for multi-album queues)
self.album_id = album_id
self.album_title = album_title
self.album_artist = album_artist
self.artwork_path = artwork_path
# Where in audio_path this entry begins, and how much of it to
# consume. None means "play to natural EOF" (full-side behavior).
self.source_offset_secs = float(source_offset_secs or 0.0)
self.source_duration_secs = source_duration_secs
# ── Player ───────────────────────────────────────────────────────────────────
class Player:
"""
Decodes album FLAC files and feeds PCM to AirPlay streams.
Callbacks:
on_track_change(track_info: dict) : fired when current track changes
on_status_change(status: dict) : fired on play/pause/stop/position updates
on_finished() : fired when playlist ends
"""
def __init__(self, eq, streams: list,
on_track_change: Callable | None = None,
on_status_change: Callable | None = None,
on_finished: Callable | None = None):
self.eq = eq
self.streams = streams # list of AsyncAudioStream objects
self._on_track_change = on_track_change or (lambda t: None)
self._on_status_change = on_status_change or (lambda s: None)
self._on_finished = on_finished or (lambda: None)
self.playlist: list[PlaylistEntry] = []
self.album_id: int | None = None
self.album_info: dict | None = None # {title, artist, year, artwork_path, ...}
self._side_idx = 0 # current index into playlist
self._position = 0.0 # seconds into current side
self._current_track_idx = -1 # index into current side's tracks list
self._repeat_mode = "off" # off | album | track
self._state = "stopped" # stopped | playing | paused
self._lock = threading.Lock()
self._pause_event = threading.Event()
self._stop_event = threading.Event()
self._feed_thread: threading.Thread | None = None
self._ffmpeg: subprocess.Popen | None = None
self._next_ffmpeg: subprocess.Popen | None = None # pre-started for gapless
self._crossfade_secs = 0.0 # 0 = disabled
self._crossfade_bytes_consumed = 0 # bytes read from next side during crossfade
self._pause_event.set() # start unpaused
# ── Properties ───────────────────────────────────────────────────────────
@property
def state(self) -> str:
return self._state
@property
def position_secs(self) -> float:
return self._position
@property
def current_side(self) -> str | None:
if 0 <= self._side_idx < len(self.playlist):
return self.playlist[self._side_idx].side
return None
@property
def current_track(self) -> dict | None:
if 0 <= self._side_idx < len(self.playlist):
entry = self.playlist[self._side_idx]
if 0 <= self._current_track_idx < len(entry.tracks):
return entry.tracks[self._current_track_idx]
return None
@property
def duration_secs(self) -> float:
"""Duration of current side."""
if 0 <= self._side_idx < len(self.playlist):
return self.playlist[self._side_idx].duration_secs
return 0.0
def get_status(self) -> dict:
track = self.current_track
return {
"state": self._state,
"album_id": self.album_id,
"side": self.current_side,
"position_secs": round(self._position, 1),
"duration_secs": round(self.duration_secs, 1),
"track_id": track["id"] if track else None,
"track_title": track["title"] if track else None,
"side_index": self._side_idx,
"side_count": len(self.playlist),
"repeat_mode": self._repeat_mode,
}
def set_crossfade(self, secs: float):
"""Set crossfade duration (0 to disable, max 2 seconds)."""
self._crossfade_secs = max(0.0, min(2.0, float(secs)))
print(f"[player] Crossfade: {self._crossfade_secs}s")
def cycle_repeat(self) -> str:
"""Cycle repeat mode: off → album → track → off."""
modes = ["off", "album", "track"]
idx = modes.index(self._repeat_mode) if self._repeat_mode in modes else 0
self._repeat_mode = modes[(idx + 1) % 3]
print(f"[player] Repeat mode: {self._repeat_mode}")
self._on_status_change(self.get_status())
return self._repeat_mode
# ── Playback Control ─────────────────────────────────────────────────────
def play(self, album_id: int, album_info: dict,
playlist: list[PlaylistEntry], start_track_id: int | None = None):
"""Start playing an album. Stops any current playback first."""
self.stop()
self.album_id = album_id
self.album_info = album_info
self._crossfade_bytes_consumed = 0
self.playlist = playlist
if not playlist:
print("[player] Empty playlist: nothing to play")
return
# Find starting position
self._side_idx = 0
start_pos = 0.0
if start_track_id:
found = False
for si, entry in enumerate(playlist):
for t in entry.tracks:
if t["id"] == start_track_id:
self._side_idx = si
start_pos = t.get("start_secs") or 0.0
print(f"[player] Starting from track '{t.get('title')}' "
f"(id={start_track_id}, side_idx={si}, pos={start_pos:.1f}s)")
found = True
break
if found:
break
if not found:
print(f"[player] WARNING: start_track_id={start_track_id} not found in playlist")
self._position = start_pos
self._current_track_idx = -1
self._stop_event.clear()
self._pause_event.set()
self._state = "playing"
self._feed_thread = threading.Thread(
target=self._feed_loop,
name="player-feed",
daemon=True,
)
self._feed_thread.start()
self._on_status_change(self.get_status())
def pause(self):
if self._state == "playing":
self._state = "paused"
self._pause_event.clear()
self._on_status_change(self.get_status())
def resume(self):
if self._state == "paused":
self._state = "playing"
self._pause_event.set()
self._on_status_change(self.get_status())
def toggle_pause(self):
if self._state == "playing":
self.pause()
elif self._state == "paused":
self.resume()
def stop(self):
if self._state == "stopped":
return
self._state = "stopped"
self._stop_event.set()
self._pause_event.set() # unblock pause so thread can exit
self._kill_ffmpeg()
if self._feed_thread and self._feed_thread.is_alive():
self._feed_thread.join(timeout=3)
self._feed_thread = None
self._position = 0
self._current_track_idx = -1
self._on_status_change(self.get_status())
def seek_to(self, position_secs: float):
"""Seek to an absolute position within the current side."""
if not self.playlist:
return
with self._lock:
self._seek_target = max(0.0, position_secs)
self._seek_requested = True
def seek_to_track(self, track_id: int):
"""Jump to a specific track by ID."""
print(
f"[player] seek_to_track: looking for track_id={track_id} "
f"in {len(self.playlist)} entries, current side_idx={self._side_idx}"
)
for si, entry in enumerate(self.playlist):
for t in entry.tracks:
if t["id"] == track_id:
pos = t.get("start_secs") or 0.0
if si != self._side_idx:
print(
f"[player] seek_to_track: found '{t.get('title')}' "
f"on side {entry.side} (idx={si}), pos={pos:.1f}s: changing side"
)
self._change_side(si, pos)
else:
print(
f"[player] seek_to_track: found '{t.get('title')}' "
f"on current side (idx={si}), seeking to {pos:.1f}s"
)
self.seek_to(pos)
return
print(f"[player] seek_to_track: track_id={track_id} NOT FOUND in playlist")
def next_track(self):
"""Skip to next track."""
if not self.playlist:
return
entry = self.playlist[self._side_idx]
next_idx = self._current_track_idx + 1
if next_idx < len(entry.tracks):
pos = entry.tracks[next_idx].get("start_secs") or 0.0
self.seek_to(pos)
elif self._side_idx + 1 < len(self.playlist):
# Next side
self._change_side(self._side_idx + 1, 0.0)
elif self._repeat_mode == "album" and self.playlist:
# Repeat album: wrap around to first side
self._change_side(0, 0.0)
else:
# End of album
self.stop()
self._on_finished()
def prev_track(self):
"""Go to previous track (or start of current if >3s in)."""
if not self.playlist:
return
entry = self.playlist[self._side_idx]
current = self.current_track
if current:
track_start = current.get("start_secs") or 0.0
# If more than 3 seconds into the track, restart it
if self._position - track_start > 3.0:
self.seek_to(track_start)
return
prev_idx = self._current_track_idx - 1
if prev_idx >= 0:
pos = entry.tracks[prev_idx].get("start_secs") or 0.0
self.seek_to(pos)
elif self._side_idx > 0:
# Previous side, last track
prev_entry = self.playlist[self._side_idx - 1]
if prev_entry.tracks:
pos = prev_entry.tracks[-1].get("start_secs") or 0.0
self._change_side(self._side_idx - 1, pos)
else:
self._change_side(self._side_idx - 1, 0.0)
else:
# Already at start: restart first track
self.seek_to(0.0)
# ── Internal: Side Management ────────────────────────────────────────────
def _change_side(self, new_side_idx: int, start_pos: float = 0.0):
"""Switch to a different side (kills ffmpeg, restarts feed loop)."""
with self._lock:
self._side_change_target = (new_side_idx, start_pos)
self._side_change_requested = True
# Signal the feed loop to check
self._kill_ffmpeg()
# ── Internal: ffmpeg Decode ──────────────────────────────────────────────
def _start_ffmpeg(self, audio_path: str, start_secs: float = 0.0,
duration_secs: float | None = None) -> bool:
"""Start ffmpeg decoding FLAC → raw s16le PCM pipe.
start_secs and duration_secs are absolute to the source file:
ffmpeg will seek to start_secs and emit at most duration_secs of
audio. duration_secs=None plays to natural EOF.
"""
self._kill_ffmpeg()
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error"]
if start_secs > 0:
cmd += ["-ss", f"{start_secs:.3f}"]
cmd += ["-i", audio_path]
if duration_secs is not None and duration_secs > 0:
cmd += ["-t", f"{duration_secs:.3f}"]
cmd += [
"-f", "s16le",
"-acodec", "pcm_s16le",
"-ar", str(SAMPLE_RATE),
"-ac", str(CHANNELS),
"pipe:1",
]
try:
self._ffmpeg = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
)
return True
except Exception as e:
print(f"[player] ffmpeg start failed: {e}")
self._ffmpeg = None
return False
def _kill_ffmpeg(self):
if self._ffmpeg:
try:
self._ffmpeg.kill()
self._ffmpeg.wait(timeout=2)
except Exception:
pass
self._ffmpeg = None
self._kill_next_ffmpeg()
def _kill_next_ffmpeg(self):
if self._next_ffmpeg:
try:
self._next_ffmpeg.kill()
self._next_ffmpeg.wait(timeout=2)
except Exception:
pass
self._next_ffmpeg = None
def _prestart_next_side(self):
"""Pre-start ffmpeg for the next side so transitions are gapless.
The process blocks on its stdout pipe until we read from it."""
self._kill_next_ffmpeg()
next_idx = self._side_idx + 1
if next_idx >= len(self.playlist):
return
next_entry = self.playlist[next_idx]
if not Path(next_entry.audio_path).exists():
return
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error"]
if next_entry.source_offset_secs > 0:
cmd += ["-ss", f"{next_entry.source_offset_secs:.3f}"]
cmd += ["-i", next_entry.audio_path]
if next_entry.source_duration_secs is not None and next_entry.source_duration_secs > 0:
cmd += ["-t", f"{next_entry.source_duration_secs:.3f}"]
cmd += [
"-f", "s16le", "-acodec", "pcm_s16le",
"-ar", str(SAMPLE_RATE), "-ac", str(CHANNELS),
"pipe:1",
]
try:
self._next_ffmpeg = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
)
print(f"[player] Pre-started ffmpeg for Side {next_entry.side} (gapless)")
except Exception as e:
print(f"[player] Failed to pre-start next side: {e}")
self._next_ffmpeg = None
# ── Internal: Track Boundary Detection ───────────────────────────────────
def _check_track_boundary(self):
"""Check if position has crossed into a new track, fire callback."""
if not self.playlist:
return
entry = self.playlist[self._side_idx]
pos = self._position
if not entry.tracks:
if self._current_track_idx == -1:
print(f"[player] WARNING: No tracks for Side {entry.side}")
self._current_track_idx = -2 # avoid repeated warnings
return
# Find which track we're in
new_idx = -1
for i, t in enumerate(entry.tracks):
start = t.get("start_secs") or 0.0
end = t.get("end_secs") or entry.duration_secs
if start <= pos < end:
new_idx = i
break
# If no track matched (might be in gap or before first track),
# try finding the closest preceding track
if new_idx == -1:
for i in range(len(entry.tracks) - 1, -1, -1):
if (entry.tracks[i].get("start_secs") or 0.0) <= pos:
new_idx = i
break
# Still no match: default to first track (common when timestamps
# are offsets from stream start, not from FLAC file start)
if new_idx == -1 and entry.tracks:
new_idx = 0
if new_idx != self._current_track_idx and new_idx >= 0:
# Repeat-track: if track changed naturally (not via seek/next/prev),
# loop back to start of the current track
if (self._repeat_mode == "track"
and self._current_track_idx >= 0
and not getattr(self, '_skip_repeat_check', False)):
old_track = entry.tracks[self._current_track_idx]
start = old_track.get("start_secs") or 0.0
self.seek_to(start)
return # Don't update track index: we're looping
self._current_track_idx = new_idx
track = entry.tracks[new_idx]
# Per-entry album metadata (multi-album queue) overrides global
a_id = entry.album_id or self.album_id
a_title = entry.album_title or self.album_info.get("title", "")
a_artist= entry.album_artist or self.album_info.get("artist", "")
a_art = entry.artwork_path or self.album_info.get("artwork_path")
a_uart = self.album_info.get("user_artwork_path") if not entry.artwork_path else entry.artwork_path
info = {
"track_id": track["id"],
"track_title": track["title"],
"track_artist": track.get("artist") or a_artist,
"album_id": a_id,
"album_title": a_title,
"album_artist": a_artist,
"year": self.album_info.get("year"),
"artwork_path": a_art,
"user_artwork_path": a_uart,
"side": entry.side,
}
print(f"[player] Now playing: {track['title']} "
f"(Side {entry.side}, track {new_idx + 1})")
self._on_track_change(info)
# ── Internal: Feed Loop ──────────────────────────────────────────────────
def _feed_loop(self):
"""
Main playback thread. Decodes FLAC and feeds PCM to streams
at real-time rate.
"""
self._seek_requested = False
self._seek_target = 0.0
self._side_change_requested = False
self._side_change_target = (0, 0.0)
self._fade_in_remaining = FADE_IN_FRAMES # frames left to ramp
self._restart_playback = False
while not self._stop_event.is_set() and (self._side_idx < len(self.playlist) or self._restart_playback):
if self._restart_playback:
self._restart_playback = False
self._side_idx = 0
self._position = 0.0
self._current_track_idx = -1
print("[player] Repeat album: restarting")
entry = self.playlist[self._side_idx]
print(f"[player] Starting Side {entry.side}: {entry.audio_path} "
f"(at {self._position:.1f}s, {len(entry.tracks)} tracks)")
if not Path(entry.audio_path).exists():
print(f"[player] File not found: {entry.audio_path}")
self._side_idx += 1
self._position = 0.0
continue
# If we already have ffmpeg running (from gapless pre-start), use it
if self._ffmpeg and self._ffmpeg.poll() is None:
pass # Already running from gapless swap
else:
# Translate entry-local position into source-file timestamps.
# For full-side entries source_offset_secs=0 and duration=None,
# so this matches the original "seek to position in FLAC" behavior.
src_start = entry.source_offset_secs + self._position
src_dur = None
if entry.source_duration_secs is not None:
src_dur = max(0.0, entry.source_duration_secs - self._position)
if not self._start_ffmpeg(entry.audio_path, src_start, src_dur):
print(f"[player] Failed to start ffmpeg for {entry.audio_path}")
self._side_idx += 1
self._position = 0.0
continue
# Pre-start ffmpeg for the next side (gapless transition)
self._prestart_next_side()
# Fire initial track boundary check
self._check_track_boundary()
# Set fade-in: full 500ms at start of side (covers needle drop),
# short 30ms if resuming mid-side (just anti-click)
if self._position < 1.0:
self._fade_in_remaining = FADE_IN_FRAMES
else:
self._fade_in_remaining = SILENCE_FRAMES
# Real-time feed loop
side_changed = False
t_start = time.monotonic()
pos_start = self._position
bytes_fed = 0
status_ticker = 0
while not self._stop_event.is_set():
# Handle pause
if not self._pause_event.is_set():
t_paused = time.monotonic()
self._pause_event.wait()
if self._stop_event.is_set():
break
# Adjust timing baseline for time spent paused
t_start += time.monotonic() - t_paused
# Handle side change request
with self._lock:
if self._side_change_requested:
self._side_change_requested = False
new_si, new_pos = self._side_change_target
self._side_idx = new_si
self._position = new_pos
self._current_track_idx = -1
self._kill_ffmpeg()
side_changed = True
break # restart outer loop on new side
# Handle seek within current side
with self._lock:
if self._seek_requested:
self._seek_requested = False
target = min(self._seek_target, entry.duration_secs)
self._position = target
# Update current track index based on new position after seek
self._current_track_idx = -1
pos_start = target
self._check_track_boundary()
bytes_fed = 0
t_start = time.monotonic()
# Kill only current ffmpeg, keep pre-started next side
if self._ffmpeg:
try:
self._ffmpeg.kill()
self._ffmpeg.wait(timeout=2)
except Exception:
pass
self._ffmpeg = None
# Translate entry-local target into source-file coords
src_start = entry.source_offset_secs + target
src_dur = None
if entry.source_duration_secs is not None:
src_dur = max(0.0, entry.source_duration_secs - target)
if not self._start_ffmpeg(entry.audio_path, src_start, src_dur):
break
# Short fade for seeks (just anti-click, not needle drop)
self._fade_in_remaining = SILENCE_FRAMES
self._check_track_boundary()
continue
# Read a chunk from ffmpeg
try:
data = self._ffmpeg.stdout.read(CHUNK_BYTES)
except Exception:
data = b""
if not data:
# Side finished
break
# Update position from the real bytes read, before any padding,
# so a short final chunk doesn't overshoot the side length.
bytes_fed += len(data)
self._position = pos_start + bytes_fed / BYTES_PER_SEC
# Pad a short final chunk with silence for the sinks (not counted above).
if len(data) < CHUNK_BYTES:
data += b'\x00' * (CHUNK_BYTES - len(data))
# Convert to float32 for processing
audio_f32 = np.frombuffer(data, dtype=np.int16).reshape(-1, CHANNELS).astype(np.float32) / 32767.0
# Anti-pop fade-in: ramp over ~500ms to suppress needle drop
if self._fade_in_remaining > 0:
n = len(audio_f32)
# Where we are in the overall fade (0.0 = start, 1.0 = done)
offset = FADE_IN_FRAMES - self._fade_in_remaining
apply = min(n, self._fade_in_remaining)
ramp = np.linspace(
offset / FADE_IN_FRAMES,
(offset + apply) / FADE_IN_FRAMES,
apply, dtype=np.float32,
).reshape(-1, 1)
audio_f32[:apply] *= ramp
self._fade_in_remaining -= apply
# Crossfade: blend with next side when approaching end
if (self._crossfade_secs > 0
and entry.duration_secs > self._crossfade_secs * 2
and self._position >= entry.duration_secs - self._crossfade_secs
and self._next_ffmpeg is not None
and self._next_ffmpeg.poll() is None):
try:
next_chunk = self._next_ffmpeg.stdout.read(CHUNK_BYTES)
except Exception:
next_chunk = b""
if next_chunk:
if len(next_chunk) < CHUNK_BYTES:
next_chunk += b'\x00' * (CHUNK_BYTES - len(next_chunk))
self._crossfade_bytes_consumed += CHUNK_BYTES
elapsed = self._position - (entry.duration_secs - self._crossfade_secs)
t = min(1.0, max(0.0, elapsed / self._crossfade_secs))
# Equal-power crossfade (cosine curve)
fade_out = float(np.cos(t * np.pi * 0.5))
fade_in = float(np.sin(t * np.pi * 0.5))
nxt_f32 = (
np.frombuffer(next_chunk, dtype=np.int16)
.reshape(-1, CHANNELS)
.astype(np.float32) / 32767.0
)
audio_f32 = audio_f32 * fade_out + nxt_f32 * fade_in
# Apply EQ
processed = self.eq.process(audio_f32)
pcm_out = (processed * 32767).astype(np.int16).tobytes()
# Feed all streams
for stream in self.streams:
stream.put(pcm_out)
# Check track boundaries
self._check_track_boundary()
# Broadcast position every ~1 second
status_ticker += 1
if status_ticker % 11 == 0: # ~11 chunks/sec * 1 ~ 1s
self._on_status_change(self.get_status())
# Rate limit: sleep to maintain real-time pace using
# bytes-fed-based target (self-correcting: no drift accumulation)
target_time = bytes_fed / BYTES_PER_SEC
actual_time = time.monotonic() - t_start
sleep_needed = target_time - actual_time
if sleep_needed > 0.001:
time.sleep(sleep_needed)
# If side was changed via seek_to_track, skip auto-advance
if side_changed:
self._kill_ffmpeg()
self._kill_next_ffmpeg()
print(f"[player] Side changed to idx={self._side_idx}, skipping auto-advance")
continue
# Don't kill ffmpeg yet if we have a pre-started next side
# (we only kill it if stopping or changing sides)
has_prestarted = self._next_ffmpeg is not None
if not has_prestarted:
self._kill_ffmpeg()
# If we're stopped or side-changed, don't auto-advance
if self._stop_event.is_set():
self._kill_ffmpeg()
break
with self._lock:
if self._side_change_requested:
print(f"[player] Side change pending after inner loop exit, target={self._side_change_target}")
self._kill_ffmpeg()
continue
# Clean up current ffmpeg (the pre-started one is separate)
if self._ffmpeg:
try:
self._ffmpeg.kill()
self._ffmpeg.wait(timeout=2)
except Exception:
pass
self._ffmpeg = None
# Auto-advance to next side
self._side_idx += 1
# If crossfade consumed bytes from the next side, start position there
if self._crossfade_bytes_consumed > 0:
self._position = self._crossfade_bytes_consumed / BYTES_PER_SEC
else:
self._position = 0.0
self._crossfade_bytes_consumed = 0
self._current_track_idx = -1
if self._side_idx < len(self.playlist):
# Swap pre-started ffmpeg into active slot for gapless transition
if has_prestarted:
self._ffmpeg = self._next_ffmpeg
self._next_ffmpeg = None
print(f"[player] Gapless advance to Side {self.playlist[self._side_idx].side}")
else:
print(f"[player] Auto-advancing to Side {self.playlist[self._side_idx].side}")
self._on_status_change(self.get_status())
elif self._repeat_mode == "album" and self.playlist:
self._kill_next_ffmpeg()
self._restart_playback = True
# Loop continues with next side
# Anti-pop: send a brief silence buffer so ALSA output drains
# cleanly instead of cutting off mid-sample
try:
silence = b'\x00' * (SILENCE_FRAMES * BYTES_PER_SAMPLE)
for stream in self.streams:
stream.put(silence)
time.sleep(SILENCE_MS / 1000.0)
except Exception:
pass
# Playback finished
if not self._stop_event.is_set():
self._state = "stopped"
print("[player] Playlist finished")
self._on_finished()
self._on_status_change(self.get_status())