The Device menu becomes Connections, with "Connect to Chromecast…" beside the Rabbit sync. It opens a dialog that spins while it searches and lists devices as they appear; picking one hands playback over, puts a small cast glyph under the volume slider, and clicking that glyph disconnects. Media-receiver model: lintunes serves the original file over the LAN on an ephemeral port and the Chromecast decodes it itself. Bit-exact — no transcode, no second lossy encode — and the device buffers for itself. The cost is that lintunes is a remote control while connected: no local PCM, so the visualizer shows the cast glyph instead of bars, and transport actions land with about a second of round trip. Player now walks its queue through a swappable PlaybackSink. It keeps owning the queue, shuffle walk, start/stop times and the play-count and scrobble bookkeeping, so casting counts plays and scrobbles exactly like local playback. set_sink() carries track, position and playing-state both ways, so connecting and disconnecting pick up mid-song. LocalSink stays in player.py because the Player tests stub Qt Multimedia in that namespace. The URL carries an opaque random token, never a path, so there is nothing to traverse with; only the last few played tracks stay resolvable and the whole map dies with the session. Range and HEAD are implemented because the device seeks by re-requesting ranges and won't report a duration without them. Failure handling, verified against a real device: a dropped socket gets a 15s grace period, since pychromecast retries on its own and a Wi-Fi blip heals itself. A real loss, another app taking the device, or a network change falls back to local playback still playing, at the same position — the sink reports the state lintunes last asked for rather than the IDLE status a dying connection pushes just before it goes. Quitting stops the device instead of leaving it fetching from a server that just died. The ~119 Apple Lossless / AIFF / protected-AAC tracks are skipped with a status-bar message; the other 21,000+ MP3 and AAC files cast natively. New dependency: pychromecast>=14.0.10, imported lazily so the app still launches where it isn't installed (the menu item then explains the install), and python_requires raised to >=3.11 to match its floor. NOTE: the other machine needs `pip install -e .` before casting appears. tests/test_round29.py: 67 tests; 440 pass overall.
611 lines
24 KiB
Python
611 lines
24 KiB
Python
import random
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from PyQt6.QtCore import QObject, QUrl, pyqtSignal
|
|
from PyQt6.QtMultimedia import (
|
|
QMediaPlayer, QAudioOutput, QAudioBufferOutput, QMediaDevices, QAudio)
|
|
|
|
from lintunes.eventlog import log_control
|
|
from lintunes.models import Track
|
|
|
|
|
|
# Hitting "previous" more than this far into a song restarts it instead
|
|
RESTART_THRESHOLD_MS = 3000
|
|
|
|
# Resuming after a pause at least this long does a seek-in-place first: when
|
|
# the machine sits idle, the OS suspends the audio sink and it can come back
|
|
# silently dead — decoding continues (the visualizer moves) but nothing is
|
|
# audible until a seek re-primes the sink. Seen on trav's Debian 13 machine.
|
|
RESUME_NUDGE_THRESHOLD_S = 30
|
|
|
|
|
|
def make_shuffle_order(count: int, start_index: int) -> list[int]:
|
|
"""A random permutation of range(count) that begins at start_index."""
|
|
order = [i for i in range(count) if i != start_index]
|
|
random.shuffle(order)
|
|
if 0 <= start_index < count:
|
|
order.insert(0, start_index)
|
|
return order
|
|
|
|
|
|
class PlaybackSink(QObject):
|
|
"""One audio output engine sitting behind Player.
|
|
|
|
Player owns the queue, the shuffle walk, the play-count/scrobble
|
|
bookkeeping and the custom start/stop times. A sink owns only "make this
|
|
file come out of something, and tell me where it's up to".
|
|
|
|
Everything a sink reports leaves as a Qt signal, so a sink whose events
|
|
originate on a foreign thread (the cast sink's pychromecast socket worker)
|
|
delivers them queued onto the GUI thread — the art_search/lastfm pattern.
|
|
"""
|
|
|
|
position_changed = pyqtSignal('qint64') # ms
|
|
duration_changed = pyqtSignal('qint64') # ms
|
|
state_changed = pyqtSignal(bool) # is it playing?
|
|
ended = pyqtSignal() # reached its natural end
|
|
error = pyqtSignal(str) # this track failed; Player skips
|
|
audio_buffer = pyqtSignal(object) # decoded PCM tee (local only)
|
|
unavailable = pyqtSignal(str) # the sink itself died
|
|
|
|
provides_pcm = False # does audio_buffer ever fire? (gates the visualizer)
|
|
name = "" # "" for local; the device name while casting
|
|
|
|
def load(self, track, autoplay: bool, start_ms: int):
|
|
raise NotImplementedError
|
|
|
|
def play(self):
|
|
raise NotImplementedError
|
|
|
|
def pause(self):
|
|
raise NotImplementedError
|
|
|
|
def stop(self):
|
|
raise NotImplementedError
|
|
|
|
def seek(self, position_ms: int):
|
|
raise NotImplementedError
|
|
|
|
def position_ms(self) -> int:
|
|
raise NotImplementedError
|
|
|
|
def duration_ms(self) -> int:
|
|
raise NotImplementedError
|
|
|
|
def is_playing(self) -> bool:
|
|
raise NotImplementedError
|
|
|
|
def set_volume(self, level: float):
|
|
"""Set output volume from a logical 0..1 value (0=silent, 1=full)."""
|
|
raise NotImplementedError
|
|
|
|
def can_play(self, track) -> bool:
|
|
"""False when this sink can't decode the track at all, so Player skips
|
|
past it rather than stalling on something that will never start."""
|
|
return True
|
|
|
|
def unplayable_reason(self, track) -> str:
|
|
return ""
|
|
|
|
def shutdown(self):
|
|
pass
|
|
|
|
|
|
class LocalSink(PlaybackSink):
|
|
"""The built-in sink: QMediaPlayer + QAudioOutput, with the PCM tee.
|
|
|
|
Stays in player.py on purpose — the Player tests stub the Qt Multimedia
|
|
classes with ``patch.multiple(player_module, QMediaPlayer=..., ...)``, so
|
|
they have to be looked up in this module's namespace.
|
|
"""
|
|
|
|
provides_pcm = True
|
|
|
|
def __init__(self, parent=None):
|
|
super().__init__(parent)
|
|
self._volume = 1.0 # logical 0..1; what the volume slider shows
|
|
# Custom start time (ms) for the loaded track: applied once the media
|
|
# reports itself loaded, which is when it is reliably seekable.
|
|
self._pending_start_ms = 0
|
|
self._paused_at: float | None = None # monotonic time of last pause
|
|
self._shutdown_done = False
|
|
|
|
self._audio = QAudioOutput(self)
|
|
self._media = QMediaPlayer(self)
|
|
self._media.setAudioOutput(self._audio)
|
|
# Tee of the decoded PCM, feeding the visualizer
|
|
self._buffer_output = QAudioBufferOutput(self)
|
|
self._media.setAudioBufferOutput(self._buffer_output)
|
|
self._buffer_output.audioBufferReceived.connect(
|
|
lambda buf: self.audio_buffer.emit(buf))
|
|
# Follow the system default output so audio keeps playing when the
|
|
# active device changes (e.g. headphones unplugged). Held as an
|
|
# attribute so it isn't garbage-collected and keeps emitting.
|
|
self._media_devices = QMediaDevices(self)
|
|
self._media_devices.audioOutputsChanged.connect(
|
|
self._on_audio_outputs_changed)
|
|
self._media.positionChanged.connect(self.position_changed)
|
|
self._media.durationChanged.connect(self.duration_changed)
|
|
self._media.playbackStateChanged.connect(self._on_state_changed)
|
|
self._media.mediaStatusChanged.connect(self._on_media_status)
|
|
self._media.errorOccurred.connect(self._on_error)
|
|
|
|
def load(self, track, autoplay: bool, start_ms: int):
|
|
self._pending_start_ms = max(0, start_ms)
|
|
url = QUrl.fromLocalFile(track.location)
|
|
if self._media.source() == url:
|
|
# setSource() no-ops on an unchanged URL, so LoadedMedia never
|
|
# re-fires and the armed start time would be skipped (and forcing
|
|
# a clear+reload races the FFmpeg backend, which snaps the seek
|
|
# back to 0). The media is already loaded: rewind and seek now.
|
|
self._media.stop()
|
|
if self._pending_start_ms:
|
|
self._media.setPosition(self._pending_start_ms)
|
|
self._pending_start_ms = 0
|
|
else:
|
|
self._media.setSource(url)
|
|
if autoplay:
|
|
self._media.play()
|
|
|
|
def play(self):
|
|
self._apply_volume()
|
|
if (self._paused_at is not None
|
|
and time.monotonic() - self._paused_at
|
|
>= RESUME_NUDGE_THRESHOLD_S):
|
|
# Re-prime a possibly idle-suspended sink (the manual workaround
|
|
# was "rewind slightly"); seek in place so the listener doesn't
|
|
# lose their spot.
|
|
self._media.setPosition(self._media.position())
|
|
self._paused_at = None
|
|
self._media.play()
|
|
|
|
def pause(self):
|
|
self._paused_at = time.monotonic()
|
|
self._media.pause()
|
|
|
|
def stop(self):
|
|
self._media.stop()
|
|
|
|
def seek(self, position_ms: int):
|
|
self._media.setPosition(max(0, position_ms))
|
|
|
|
def position_ms(self) -> int:
|
|
return self._media.position()
|
|
|
|
def duration_ms(self) -> int:
|
|
return self._media.duration()
|
|
|
|
def is_playing(self) -> bool:
|
|
return self._media.playbackState() == QMediaPlayer.PlaybackState.PlayingState
|
|
|
|
def set_volume(self, level: float):
|
|
"""Set output volume from a logical 0..1 value (0=silent, 1=full).
|
|
The slider scale is perceptual, so convert to the linear gain
|
|
QAudioOutput expects — that makes the knob feel iTunes-like rather
|
|
than jumping to "loud" in the first few percent."""
|
|
self._volume = max(0.0, min(1.0, float(level)))
|
|
self._apply_volume()
|
|
|
|
def _apply_volume(self):
|
|
"""Push the stored logical volume to the sink. Called again on resume
|
|
and after device swaps: some backends (seen with Bluetooth sinks)
|
|
re-create the sink with a stale/zero gain, which played silently until
|
|
a seek re-primed it."""
|
|
self._audio.setVolume(QAudio.convertVolume(
|
|
self._volume,
|
|
QAudio.VolumeScale.LogarithmicVolumeScale,
|
|
QAudio.VolumeScale.LinearVolumeScale,
|
|
))
|
|
|
|
def shutdown(self):
|
|
"""Tear down the Qt Multimedia pipeline in a safe order before Qt
|
|
destroys the objects. Without this, QObject children are destroyed in
|
|
creation order at exit — the QAudioOutput dies while the QMediaPlayer
|
|
(FFmpeg backend) still references it, which segfaults after the GUI is
|
|
gone. Idempotent; wired to both closeEvent and aboutToQuit."""
|
|
if self._shutdown_done:
|
|
return
|
|
self._shutdown_done = True
|
|
try:
|
|
self._media_devices.audioOutputsChanged.disconnect(
|
|
self._on_audio_outputs_changed)
|
|
except TypeError:
|
|
pass
|
|
self._media.stop()
|
|
self._media.setSource(QUrl()) # release the demux/decode pipeline
|
|
self._media.setAudioBufferOutput(None)
|
|
self._media.setAudioOutput(None) # detach the sink while both live
|
|
|
|
def _on_audio_outputs_changed(self):
|
|
"""Re-point the output at the current default device when the set of
|
|
available outputs changes (a device was added or removed)."""
|
|
new_default = QMediaDevices.defaultAudioOutput()
|
|
if new_default.isNull() or new_default.id() == self._audio.device().id():
|
|
return
|
|
was_playing = self.is_playing()
|
|
self._audio.setDevice(new_default)
|
|
self._apply_volume() # the new sink may come up at a stale/zero gain
|
|
# Some backends stall the sink across a device swap; nudge it back.
|
|
# play() is a no-op if playback actually continued.
|
|
if was_playing:
|
|
self._media.play()
|
|
|
|
def _on_state_changed(self, state):
|
|
self.state_changed.emit(state == QMediaPlayer.PlaybackState.PlayingState)
|
|
|
|
def _on_media_status(self, status):
|
|
if (status == QMediaPlayer.MediaStatus.LoadedMedia
|
|
and self._pending_start_ms):
|
|
# The media is only reliably seekable once loaded; jump to the
|
|
# custom start time now (works whether or not we're autoplaying).
|
|
start = self._pending_start_ms
|
|
self._pending_start_ms = 0
|
|
self._media.setPosition(start)
|
|
return
|
|
if status == QMediaPlayer.MediaStatus.BufferedMedia:
|
|
self._apply_volume() # sink can be re-created per source
|
|
return
|
|
if status == QMediaPlayer.MediaStatus.EndOfMedia:
|
|
self.ended.emit()
|
|
|
|
def _on_error(self, error, error_string):
|
|
self.error.emit(error_string)
|
|
|
|
|
|
class Player(QObject):
|
|
"""Playback engine: walks a queue of track ids through a swappable sink.
|
|
|
|
The queue is the displayed order of whatever view playback started from.
|
|
Play counts are recorded (via LibraryManager) when a track finishes
|
|
playing naturally — on whichever sink is active, so casting scrobbles and
|
|
counts plays exactly like local playback does.
|
|
"""
|
|
|
|
track_changed = pyqtSignal(object) # Track or None
|
|
playing_changed = pyqtSignal(bool)
|
|
position_changed = pyqtSignal('qint64') # ms
|
|
duration_changed = pyqtSignal('qint64') # ms
|
|
error_occurred = pyqtSignal(str)
|
|
track_missing = pyqtSignal(object) # Track whose file is gone/moved
|
|
audio_buffer = pyqtSignal(object) # QAudioBuffer (decoded PCM)
|
|
track_finished = pyqtSignal(object) # Track played to the very end
|
|
track_unplayable = pyqtSignal(object, str) # skipped: sink can't decode it
|
|
sink_changed = pyqtSignal(object) # the new PlaybackSink
|
|
|
|
# Signals relayed from whichever sink is active.
|
|
_SINK_SIGNALS = ("position_changed", "duration_changed", "state_changed",
|
|
"ended", "error", "audio_buffer", "unavailable")
|
|
|
|
def __init__(self, manager, parent=None):
|
|
super().__init__(parent)
|
|
self._manager = manager
|
|
self._queue: list[int] = []
|
|
self._index = -1
|
|
self._current_track: Track | None = None
|
|
self._shuffle = False
|
|
self._shuffle_order: list[int] = []
|
|
# Custom stop time (ms) for the loaded track: end it early. Enforced
|
|
# here rather than in a sink so both playback paths honor it.
|
|
self._stop_at_ms = 0
|
|
self._counted_finish_id: int | None = None
|
|
self._volume = 1.0 # logical 0..1; what the volume slider shows
|
|
|
|
self._local = LocalSink(self)
|
|
self._sink: PlaybackSink = self._local
|
|
self._connect_sink(self._sink)
|
|
|
|
self._shutdown_done = False
|
|
|
|
# ---- sinks ----
|
|
|
|
def _connect_sink(self, sink: PlaybackSink):
|
|
sink.position_changed.connect(self.position_changed)
|
|
sink.position_changed.connect(self._on_position)
|
|
sink.duration_changed.connect(self.duration_changed)
|
|
sink.state_changed.connect(self.playing_changed)
|
|
sink.ended.connect(self._on_sink_ended)
|
|
sink.error.connect(self._on_sink_error)
|
|
sink.audio_buffer.connect(self.audio_buffer)
|
|
sink.unavailable.connect(self._on_sink_unavailable)
|
|
|
|
def _disconnect_sink(self, sink: PlaybackSink):
|
|
for name in self._SINK_SIGNALS:
|
|
try:
|
|
getattr(sink, name).disconnect()
|
|
except TypeError:
|
|
pass
|
|
|
|
def active_sink(self) -> PlaybackSink:
|
|
return self._sink
|
|
|
|
def provides_pcm(self) -> bool:
|
|
return self._sink.provides_pcm
|
|
|
|
def set_sink(self, sink: PlaybackSink | None):
|
|
"""Swap the output engine; None restores the built-in local one.
|
|
|
|
The current track and position carry across and playback resumes in
|
|
whatever state it was in, so connecting or losing a Chromecast picks up
|
|
mid-song rather than restarting it.
|
|
|
|
`track_changed` is deliberately *not* re-emitted: to the listener this
|
|
is the same song still playing, and re-emitting would fire a second
|
|
Last.fm now-playing update and reset an in-progress bpm tap.
|
|
"""
|
|
new_sink = sink if sink is not None else self._local
|
|
if new_sink is self._sink:
|
|
return
|
|
track = self._current_track
|
|
position = self._sink.position_ms()
|
|
was_playing = self._sink.is_playing()
|
|
|
|
self._sink.stop()
|
|
self._disconnect_sink(self._sink)
|
|
self._sink = new_sink
|
|
self._connect_sink(self._sink)
|
|
# Whatever the slider last showed applies to the new output too.
|
|
self._sink.set_volume(self._volume)
|
|
|
|
if track is not None:
|
|
if self._sink.can_play(track):
|
|
self._sink.load(track, autoplay=was_playing, start_ms=position)
|
|
else:
|
|
self.track_unplayable.emit(
|
|
track, self._sink.unplayable_reason(track))
|
|
self._skip_unplayable(autoplay=was_playing)
|
|
self.sink_changed.emit(self._sink)
|
|
|
|
def shutdown(self):
|
|
"""Tear down every sink. Idempotent; wired to closeEvent/aboutToQuit."""
|
|
if self._shutdown_done:
|
|
return
|
|
self._shutdown_done = True
|
|
self._sink.shutdown()
|
|
if self._sink is not self._local:
|
|
# The local sink is kept alive across a swap so switching back is
|
|
# instant — which means its Qt Multimedia pipeline is still around
|
|
# at quit and still needs its ordered teardown.
|
|
self._local.shutdown()
|
|
|
|
# ---- queue ----
|
|
|
|
def play_queue(self, track_ids: list[int], start_index: int):
|
|
self._queue = list(track_ids)
|
|
self._index = start_index
|
|
self._reshuffle()
|
|
self._load_current(autoplay=True)
|
|
|
|
def set_queue(self, track_ids: list[int]):
|
|
"""Replace the upcoming order without interrupting the current track."""
|
|
current_id = self._queue[self._index] if 0 <= self._index < len(self._queue) else None
|
|
self._queue = list(track_ids)
|
|
if current_id is not None and current_id in self._queue:
|
|
self._index = self._queue.index(current_id)
|
|
self._reshuffle()
|
|
|
|
# ---- shuffle ----
|
|
|
|
def is_shuffle(self) -> bool:
|
|
return self._shuffle
|
|
|
|
def set_shuffle(self, on: bool):
|
|
"""Shuffle only changes how we *walk* the queue; the playlist's
|
|
order and display are untouched."""
|
|
self._shuffle = bool(on)
|
|
self._reshuffle()
|
|
|
|
def _reshuffle(self):
|
|
if self._shuffle and self._queue:
|
|
self._shuffle_order = make_shuffle_order(
|
|
len(self._queue), max(self._index, 0))
|
|
else:
|
|
self._shuffle_order = []
|
|
|
|
def _step_index(self, delta: int) -> int | None:
|
|
"""Queue index `delta` steps away in the active walking order."""
|
|
if not self._queue:
|
|
return None
|
|
if not self._shuffle:
|
|
candidate = self._index + delta
|
|
return candidate if 0 <= candidate < len(self._queue) else None
|
|
try:
|
|
pos = self._shuffle_order.index(self._index)
|
|
except ValueError:
|
|
return self._shuffle_order[0] if self._shuffle_order else None
|
|
pos += delta
|
|
if 0 <= pos < len(self._shuffle_order):
|
|
return self._shuffle_order[pos]
|
|
return None
|
|
|
|
# ---- state ----
|
|
|
|
@property
|
|
def current_track(self) -> Track | None:
|
|
return self._current_track
|
|
|
|
def is_playing(self) -> bool:
|
|
return self._sink.is_playing()
|
|
|
|
def position_ms(self) -> int:
|
|
return self._sink.position_ms()
|
|
|
|
def duration_ms(self) -> int:
|
|
return self._sink.duration_ms()
|
|
|
|
# ---- volume ----
|
|
|
|
def set_volume(self, level: float):
|
|
"""Set output volume from a logical 0..1 value (0=silent, 1=full).
|
|
The value is kept here so it survives a sink swap — the slider keeps
|
|
meaning the same thing whether audio is coming out of this machine or
|
|
a Chromecast."""
|
|
self._volume = max(0.0, min(1.0, float(level)))
|
|
self._sink.set_volume(self._volume)
|
|
|
|
def volume(self) -> float:
|
|
"""The logical 0..1 volume last set (what the slider shows)."""
|
|
return self._volume
|
|
|
|
# ---- transport ----
|
|
|
|
def toggle_play(self):
|
|
log_control("player", "toggle_play",
|
|
f"playing={self.is_playing()} pos={self.position_ms()}ms "
|
|
f"track={self._current_track.name if self._current_track else None!r}")
|
|
if self.is_playing():
|
|
self._sink.pause()
|
|
elif self._current_track is not None:
|
|
self._sink.play()
|
|
elif self._queue:
|
|
self._index = max(self._index, 0)
|
|
self._load_current(autoplay=True)
|
|
|
|
def play(self):
|
|
if not self.is_playing():
|
|
self.toggle_play()
|
|
|
|
def pause(self):
|
|
if self.is_playing():
|
|
log_control("player", "pause", f"pos={self.position_ms()}ms")
|
|
self._sink.pause()
|
|
|
|
def stop(self):
|
|
self._sink.stop()
|
|
self._current_track = None
|
|
self.track_changed.emit(None)
|
|
|
|
def next(self):
|
|
# When paused/stopped, skipping only cues the new track; audio
|
|
# starts only if we were already playing.
|
|
self._advance(autoplay=self.is_playing())
|
|
|
|
def previous(self):
|
|
if not self._queue:
|
|
return
|
|
prev_index = self._step_index(-1)
|
|
if self.position_ms() > RESTART_THRESHOLD_MS or prev_index is None:
|
|
# "Restart" means the track's custom start time, not 0:00.
|
|
start = (self._current_track.start_time
|
|
if self._current_track else 0)
|
|
self._sink.seek(max(0, start))
|
|
else:
|
|
self._index = prev_index
|
|
self._load_current(autoplay=self.is_playing())
|
|
|
|
def _advance(self, autoplay: bool):
|
|
next_index = self._step_index(1)
|
|
if next_index is not None:
|
|
self._index = next_index
|
|
self._load_current(autoplay=autoplay)
|
|
elif self._queue:
|
|
self._sink.stop()
|
|
|
|
def seek(self, position_ms: int):
|
|
self._sink.seek(max(0, position_ms))
|
|
|
|
def retry_current(self):
|
|
"""Re-attempt the track at the current queue position (e.g. after its
|
|
location was repaired). stop() leaves _queue/_index intact."""
|
|
self._load_current(autoplay=True)
|
|
|
|
# ---- internals ----
|
|
|
|
def _load_current(self, autoplay: bool):
|
|
"""Load the queue entry at _index, stepping past tracks the active
|
|
sink can't decode (a Chromecast can't play ALAC, AIFF or protected
|
|
AAC). The skip is a loop, not recursion: shuffling into a run of
|
|
unsupported tracks must not walk the stack down."""
|
|
while 0 <= self._index < len(self._queue):
|
|
track = self._manager.library.tracks.get(self._queue[self._index])
|
|
if track is None:
|
|
# The queue references a track that's no longer in the library;
|
|
# there's nothing to locate, so just report and stop.
|
|
self.error_occurred.emit(
|
|
f"Can't play “track {self._queue[self._index]}”.")
|
|
self.stop()
|
|
return
|
|
if not track.location or not Path(track.location).exists():
|
|
# Stop here rather than auto-advancing: if the whole drive is
|
|
# unmounted every queued track is missing, and skipping to the
|
|
# next would walk the entire queue for nothing.
|
|
# Stop *before* emitting: the UI shows a modal "Locate File…"
|
|
# dialog synchronously from this signal and may relocate +
|
|
# retry, which a later stop() would otherwise undo.
|
|
self.stop()
|
|
self.track_missing.emit(track)
|
|
return
|
|
if not self._sink.can_play(track):
|
|
# Reported on its own signal, not error_occurred: that one
|
|
# opens a modal dialog, and shuffling past 100 lossless files
|
|
# must not mean 100 dialogs.
|
|
self.track_unplayable.emit(
|
|
track, self._sink.unplayable_reason(track))
|
|
next_index = self._step_index(1)
|
|
if next_index is None:
|
|
self.stop()
|
|
return
|
|
self._index = next_index
|
|
continue
|
|
|
|
self._current_track = track
|
|
# Arm the custom stop time for this track. It's honored only when
|
|
# it falls before the end (otherwise the natural finish handles it).
|
|
if track.stop_time > 0 and (track.total_time == 0
|
|
or track.stop_time < track.total_time):
|
|
self._stop_at_ms = track.stop_time
|
|
else:
|
|
self._stop_at_ms = 0
|
|
self._counted_finish_id = None
|
|
self._sink.load(
|
|
track, autoplay,
|
|
track.start_time if track.start_time > 0 else 0)
|
|
self.track_changed.emit(track)
|
|
return
|
|
|
|
def _skip_unplayable(self, autoplay: bool = True):
|
|
next_index = self._step_index(1)
|
|
if next_index is not None:
|
|
self._index = next_index
|
|
self._load_current(autoplay)
|
|
else:
|
|
self.stop()
|
|
|
|
# ---- sink events ----
|
|
|
|
def _on_sink_ended(self):
|
|
"""The active sink played the track to its natural end."""
|
|
self._note_finished(self._current_track)
|
|
# Playback has already stopped at the end, so force autoplay.
|
|
self._advance(autoplay=True)
|
|
|
|
def _on_sink_error(self, message: str):
|
|
track_name = self._current_track.name if self._current_track else "?"
|
|
self.error_occurred.emit(f"Playback error on '{track_name}': {message}")
|
|
self._skip_unplayable()
|
|
|
|
def _on_sink_unavailable(self, reason: str):
|
|
"""The sink itself died (the Chromecast went away). Drop back to local
|
|
playback, which picks up at the same position, and say why."""
|
|
self.set_sink(None)
|
|
if reason:
|
|
self.error_occurred.emit(reason)
|
|
|
|
def _on_position(self, position):
|
|
"""Stop a track at its custom stop time and move on, mirroring a
|
|
natural finish (play count + scrobble)."""
|
|
if self._stop_at_ms and position >= self._stop_at_ms:
|
|
self._stop_at_ms = 0 # one-shot: don't re-fire while advancing
|
|
track = self._current_track
|
|
self._note_finished(track)
|
|
self._advance(autoplay=True)
|
|
|
|
def _note_finished(self, track):
|
|
"""Record a completed play once, guarding against a double count if
|
|
both the stop-time and end-of-media paths fire for the same track."""
|
|
if track is None or track.track_id == self._counted_finish_id:
|
|
return
|
|
self._counted_finish_id = track.track_id
|
|
self._manager.record_play(track.track_id)
|
|
self.track_finished.emit(track)
|