v0.4.0: cast to a Chromecast from the Connections menu
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. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
+371
-144
@@ -29,40 +29,89 @@ def make_shuffle_order(count: int, start_index: int) -> list[int]:
|
||||
return order
|
||||
|
||||
|
||||
class Player(QObject):
|
||||
"""Playback engine: wraps QMediaPlayer and walks a queue of track ids.
|
||||
class PlaybackSink(QObject):
|
||||
"""One audio output engine sitting behind Player.
|
||||
|
||||
The queue is the displayed order of whatever view playback started from.
|
||||
Play counts are recorded (via LibraryManager) when a track finishes
|
||||
playing naturally.
|
||||
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.
|
||||
"""
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
def __init__(self, manager, parent=None):
|
||||
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._manager = manager
|
||||
self._queue: list[int] = []
|
||||
self._index = -1
|
||||
self._current_track: Track | None = None
|
||||
self._shuffle = False
|
||||
self._shuffle_order: list[int] = []
|
||||
# Custom start/stop times (ms) for the loaded track: seek to start once
|
||||
# the media is seekable, and end the track early at stop.
|
||||
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._stop_at_ms = 0
|
||||
self._counted_finish_id: int | None = None
|
||||
self._paused_at: float | None = None # monotonic time of last pause
|
||||
self._shutdown_done = False
|
||||
|
||||
self._audio = QAudioOutput(self)
|
||||
self._volume = 1.0 # logical 0..1; what the volume slider shows
|
||||
self._media = QMediaPlayer(self)
|
||||
self._media.setAudioOutput(self._audio)
|
||||
# Tee of the decoded PCM, feeding the visualizer
|
||||
@@ -77,13 +126,77 @@ class Player(QObject):
|
||||
self._media_devices.audioOutputsChanged.connect(
|
||||
self._on_audio_outputs_changed)
|
||||
self._media.positionChanged.connect(self.position_changed)
|
||||
self._media.positionChanged.connect(self._on_position)
|
||||
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)
|
||||
|
||||
self._shutdown_done = False
|
||||
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
|
||||
@@ -104,6 +217,157 @@ class Player(QObject):
|
||||
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):
|
||||
@@ -161,35 +425,23 @@ class Player(QObject):
|
||||
return self._current_track
|
||||
|
||||
def is_playing(self) -> bool:
|
||||
return self._media.playbackState() == QMediaPlayer.PlaybackState.PlayingState
|
||||
return self._sink.is_playing()
|
||||
|
||||
def position_ms(self) -> int:
|
||||
return self._media.position()
|
||||
return self._sink.position_ms()
|
||||
|
||||
def duration_ms(self) -> int:
|
||||
return self._media.duration()
|
||||
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 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."""
|
||||
level = max(0.0, min(1.0, float(level)))
|
||||
self._volume = 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,
|
||||
))
|
||||
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)."""
|
||||
@@ -202,19 +454,9 @@ class Player(QObject):
|
||||
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._paused_at = time.monotonic()
|
||||
self._media.pause()
|
||||
self._sink.pause()
|
||||
elif self._current_track is not None:
|
||||
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()
|
||||
self._sink.play()
|
||||
elif self._queue:
|
||||
self._index = max(self._index, 0)
|
||||
self._load_current(autoplay=True)
|
||||
@@ -226,11 +468,10 @@ class Player(QObject):
|
||||
def pause(self):
|
||||
if self.is_playing():
|
||||
log_control("player", "pause", f"pos={self.position_ms()}ms")
|
||||
self._paused_at = time.monotonic()
|
||||
self._media.pause()
|
||||
self._sink.pause()
|
||||
|
||||
def stop(self):
|
||||
self._media.stop()
|
||||
self._sink.stop()
|
||||
self._current_track = None
|
||||
self.track_changed.emit(None)
|
||||
|
||||
@@ -243,11 +484,11 @@ class Player(QObject):
|
||||
if not self._queue:
|
||||
return
|
||||
prev_index = self._step_index(-1)
|
||||
if self._media.position() > RESTART_THRESHOLD_MS or prev_index is None:
|
||||
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._media.setPosition(max(0, start))
|
||||
self._sink.seek(max(0, start))
|
||||
else:
|
||||
self._index = prev_index
|
||||
self._load_current(autoplay=self.is_playing())
|
||||
@@ -258,10 +499,10 @@ class Player(QObject):
|
||||
self._index = next_index
|
||||
self._load_current(autoplay=autoplay)
|
||||
elif self._queue:
|
||||
self._media.stop()
|
||||
self._sink.stop()
|
||||
|
||||
def seek(self, position_ms: int):
|
||||
self._media.setPosition(max(0, position_ms))
|
||||
self._sink.seek(max(0, position_ms))
|
||||
|
||||
def retry_current(self):
|
||||
"""Re-attempt the track at the current queue position (e.g. after its
|
||||
@@ -271,51 +512,56 @@ class Player(QObject):
|
||||
# ---- internals ----
|
||||
|
||||
def _load_current(self, autoplay: bool):
|
||||
if not (0 <= self._index < len(self._queue)):
|
||||
"""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
|
||||
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 recurse through the entire queue (RecursionError).
|
||||
# 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
|
||||
self._current_track = track
|
||||
# Arm the custom start/stop times for this track. Stop is honored only
|
||||
# when it falls before the end (otherwise EndOfMedia handles the finish).
|
||||
self._pending_start_ms = track.start_time if track.start_time > 0 else 0
|
||||
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
|
||||
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()
|
||||
self.track_changed.emit(track)
|
||||
|
||||
def _skip_unplayable(self, autoplay: bool = True):
|
||||
next_index = self._step_index(1)
|
||||
@@ -325,39 +571,25 @@ class Player(QObject):
|
||||
else:
|
||||
self.stop()
|
||||
|
||||
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()
|
||||
# ---- sink events ----
|
||||
|
||||
def _on_state_changed(self, state):
|
||||
self.playing_changed.emit(state == QMediaPlayer.PlaybackState.PlayingState)
|
||||
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_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._note_finished(self._current_track)
|
||||
# The player has already stopped at EndOfMedia, 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
|
||||
@@ -376,8 +608,3 @@ class Player(QObject):
|
||||
self._counted_finish_id = track.track_id
|
||||
self._manager.record_play(track.track_id)
|
||||
self.track_finished.emit(track)
|
||||
|
||||
def _on_error(self, error, error_string):
|
||||
track_name = self._current_track.name if self._current_track else "?"
|
||||
self.error_occurred.emit(f"Playback error on '{track_name}': {error_string}")
|
||||
self._skip_unplayable()
|
||||
|
||||
Reference in New Issue
Block a user