Files
lintunes/lintunes/cast/sink.py
T
trav a42665cacc 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.
2026-08-13 21:49:53 -04:00

409 lines
15 KiB
Python

"""The Player sink that plays through a Chromecast.
lintunes hands the device a URL served by the local TrackServer and then acts
as a remote control: there is no local decode, so position and state are polled
from the device rather than read from Qt.
Two threading rules hold this together:
* pychromecast delivers its listener callbacks on its own socket worker
thread. Every callback here does nothing but ``emit`` a private signal,
which Qt delivers queued onto the GUI thread. No timer, no Player state and
no widget is ever touched from that thread.
* Every outbound control call is a blocking socket write. They go through a
single serialized worker thread, so a device that has vanished stalls its own
queue instead of freezing the UI — which is exactly the case the feature has
to survive.
"""
import queue
import threading
import time
from PyQt6.QtCore import QTimer, pyqtSignal
from lintunes.cast.support import content_type_for, local_ip_for, uncastable_reason
from lintunes.player import PlaybackSink
# The stock receiver lintunes launches, and the idle "backdrop" app. Anything
# else running means someone cast to the device from another app.
DEFAULT_RECEIVER_APP_ID = "CC1AD845"
BACKDROP_APP_ID = "E8C28D3C"
PLAYING_STATES = ("PLAYING", "BUFFERING")
# ---- pure status reading (no pychromecast needed; unit-tested) ----
def is_natural_end(status) -> bool:
"""True when the device finished the track by itself.
Distinguished from every other way of going idle: ERROR means the load
failed, INTERRUPTED/CANCELLED mean something replaced our media, and none
of those should count a play or advance the queue.
"""
return (getattr(status, "player_state", None) == "IDLE"
and getattr(status, "idle_reason", None) == "FINISHED")
def is_load_error(status) -> bool:
return (getattr(status, "player_state", None) == "IDLE"
and getattr(status, "idle_reason", None) == "ERROR")
def is_playing_state(status) -> bool:
"""BUFFERING counts as playing so the play button doesn't flicker to
"paused" every time the device re-fills its buffer."""
return getattr(status, "player_state", None) in PLAYING_STATES
def position_ms_from(status, fallback_ms: int) -> int:
"""Where the device is, in ms.
``adjusted_current_time`` extrapolates from the last status using the wall
clock, which is what keeps the seek slider smooth between the device's
infrequent pushes — but it keeps creeping while paused, so it is only
trusted while actually playing.
"""
if status is None:
return fallback_ms
if is_playing_state(status):
value = getattr(status, "adjusted_current_time", None)
else:
value = getattr(status, "current_time", None)
if value is None:
value = getattr(status, "current_time", None)
return int(value * 1000) if value is not None else fallback_ms
def duration_ms_from(status, fallback_ms: int) -> int:
value = getattr(status, "duration", None) if status is not None else None
return int(value * 1000) if value else fallback_ms
def app_stolen(app_id) -> bool:
"""True when a foreign receiver is running — another app took the device."""
return bool(app_id) and app_id not in (DEFAULT_RECEIVER_APP_ID,
BACKDROP_APP_ID)
def connection_verdict(status_name: str) -> str:
""""ok" | "grace" | "lost" for a pychromecast connection status.
LOST is only "grace": pychromecast retries a dropped socket on its own
every few seconds, so a brief Wi-Fi blip heals itself and dropping straight
back to the laptop speakers would be far more disruptive than waiting.
"""
if status_name == "CONNECTED":
return "ok"
if status_name in ("LOST", "CONNECTING"):
return "grace"
if status_name in ("DISCONNECTED", "FAILED", "FAILED_RESOLVE"):
return "lost"
return "ok"
class CastSink(PlaybackSink):
"""Plays through a Chromecast by serving it the original file."""
provides_pcm = False
POLL_MS = 500 # how often we ask the device where it is
LOST_GRACE_MS = 15_000 # how long a dropped socket may heal itself
SEEK_SETTLE_MS = 2_000 # trust our own seek over stale status this long
VOLUME_COALESCE_MS = 120 # a slider drag is ~60 events/s; one write is enough
# Private relays: emitted on pychromecast's thread, handled on the GUI's.
_status_arrived = pyqtSignal(object)
_connection_arrived = pyqtSignal(str)
_app_arrived = pyqtSignal(object)
def __init__(self, cast, server, parent=None):
super().__init__(parent)
self._cast = cast
self._mc = cast.media_controller
self._server = server
self.name = getattr(cast.cast_info, "friendly_name", "") or "Chromecast"
self._host = getattr(cast.cast_info, "host", "") or ""
if not self._host:
services = getattr(cast.cast_info, "services", None)
if services:
self._host = getattr(next(iter(services)), "host", "") or ""
self._position_ms = 0
self._duration_ms = 0
self._playing = False
# What lintunes last *asked* for, as opposed to what the device last
# reported. They diverge exactly when the connection dies — see _fail.
self._intent_playing = False
self._dying = False
self._optimistic_until = 0.0
self._optimistic_ms = 0
self._last_finished_session = None
self._pending_volume = 1.0
self._shutdown_done = False
# Restored on disconnect: cast.set_volume changes the device's own
# system volume, which would otherwise persist for whatever plays next.
self._device_volume_at_connect = getattr(
getattr(cast, "status", None), "volume_level", None)
# Serialized outbound control calls (see the module docstring).
self._outbox: queue.Queue = queue.Queue()
self._sender = threading.Thread(target=self._send_loop, daemon=True)
self._sender.start()
self._status_arrived.connect(self._on_status)
self._connection_arrived.connect(self._on_connection)
self._app_arrived.connect(self._on_app)
self._poll = QTimer(self)
self._poll.setInterval(self.POLL_MS)
self._poll.timeout.connect(self._on_poll)
self._poll.start()
self._lost_timer = QTimer(self)
self._lost_timer.setSingleShot(True)
self._lost_timer.setInterval(self.LOST_GRACE_MS)
self._lost_timer.timeout.connect(self._on_grace_expired)
self._volume_timer = QTimer(self)
self._volume_timer.setSingleShot(True)
self._volume_timer.setInterval(self.VOLUME_COALESCE_MS)
self._volume_timer.timeout.connect(self._flush_volume)
self._mc.register_status_listener(self)
cast.register_status_listener(self)
cast.register_connection_listener(self)
# ---- PlaybackSink ----
def can_play(self, track) -> bool:
return content_type_for(track.location, track.kind) is not None
def unplayable_reason(self, track) -> str:
return uncastable_reason(track.location, track.kind)
def load(self, track, autoplay: bool, start_ms: int):
content_type = content_type_for(track.location, track.kind)
if content_type is None: # Player gates on can_play; belt and braces
self.error.emit(self.unplayable_reason(track))
return
# Re-resolved per track so a network change (docking, VPN, new lease)
# is picked up rather than baking in a stale address for the session.
try:
host = local_ip_for(self._host) if self._host else ""
except OSError as e:
self._fail(f"Lost the network route to {self.name} ({e}).")
return
token = self._server.publish(track.location, content_type)
url = self._server.url_for(host, token)
# Report length and state straight away; the device won't say anything
# for a second or two and the transport shouldn't sit blank until then.
self._set_optimistic(start_ms)
self._duration_ms = track.total_time or 0
self.duration_changed.emit(self._duration_ms)
self._intent_playing = autoplay
self._set_playing(autoplay)
metadata = {
"metadataType": 3, # MusicTrackMediaMetadata
"title": track.name or "",
"artist": track.artist or "",
"albumName": track.album or "",
}
self._submit(
lambda: self._mc.play_media(
url, content_type,
title=track.name or "",
# NOT pychromecast's STREAM_TYPE_LIVE default: LIVE tells the
# receiver the stream is unbounded, which kills both seeking
# and the duration readout.
stream_type="BUFFERED",
autoplay=autoplay,
current_time=max(0, start_ms) / 1000.0,
metadata=metadata,
))
def play(self):
self._intent_playing = True
self._set_playing(True)
self._submit(self._mc.play)
def pause(self):
self._intent_playing = False
self._set_playing(False)
self._submit(self._mc.pause)
def stop(self):
self._intent_playing = False
self._set_playing(False)
self._submit(self._mc.stop)
def seek(self, position_ms: int):
target = max(0, position_ms)
self._set_optimistic(target)
self._submit(lambda: self._mc.seek(target / 1000.0))
def position_ms(self) -> int:
return self._position_ms
def duration_ms(self) -> int:
return self._duration_ms
def is_playing(self) -> bool:
return self._playing
def set_volume(self, level: float):
self._pending_volume = max(0.0, min(1.0, float(level)))
self._volume_timer.start()
def shutdown(self):
"""Stop the device, hand its volume back, and drop the session.
Every step is best-effort and independent: this runs while quitting and
while the device is already gone, and a failure in one step must not
leave the rest undone. Skipping it entirely would leave the Chromecast
buffering from an HTTP server that is about to die.
"""
if self._shutdown_done:
return
self._shutdown_done = True
self._poll.stop()
self._lost_timer.stop()
self._volume_timer.stop()
for step in (
lambda: (self._device_volume_at_connect is not None
and self._cast.set_volume(self._device_volume_at_connect)),
self._mc.stop,
self._cast.quit_app,
self._cast.disconnect,
):
try:
step()
except Exception: # noqa: BLE001 — teardown is best-effort
pass
self._outbox.put(None) # retire the sender thread
self._server.stop()
# ---- outbound calls, serialized off the GUI thread ----
def _submit(self, call):
if not self._shutdown_done:
self._outbox.put(call)
def _send_loop(self):
while True:
call = self._outbox.get()
if call is None:
return
try:
call()
except Exception as e: # noqa: BLE001
if not self._shutdown_done:
self._fail(f"Lost {self.name} ({e}).")
return
# ---- pychromecast listeners (foreign thread: emit only) ----
def new_media_status(self, status):
self._status_arrived.emit(status)
def load_media_failed(self, item, error_code):
self._status_arrived.emit(None)
def new_cast_status(self, status):
self._app_arrived.emit(getattr(status, "app_id", None))
def new_connection_status(self, status):
self._connection_arrived.emit(getattr(status, "status", "") or "")
# ---- GUI thread ----
def _on_status(self, status):
if status is None or self._shutdown_done or self._dying:
return
if is_load_error(status):
self.error.emit("the Chromecast couldn't play it")
return
if is_natural_end(status):
session = getattr(status, "media_session_id", None)
# The device repeats its final status; without this the track would
# be counted, scrobbled and advanced more than once.
if session is not None and session == self._last_finished_session:
return
self._last_finished_session = session
self._set_playing(False)
self.ended.emit()
return
self._set_playing(is_playing_state(status))
def _on_poll(self):
if self._shutdown_done or self._dying:
return
status = getattr(self._mc, "status", None)
if time.monotonic() * 1000 < self._optimistic_until:
# Hold our own seek target briefly: the device keeps reporting the
# old position for a beat, which snaps the slider back mid-scrub.
position = self._optimistic_ms
else:
position = position_ms_from(status, self._position_ms)
self._position_ms = position
self.position_changed.emit(position)
duration = duration_ms_from(status, self._duration_ms)
if duration != self._duration_ms:
self._duration_ms = duration
self.duration_changed.emit(duration)
def _on_connection(self, status_name: str):
verdict = connection_verdict(status_name)
if verdict == "ok":
self._lost_timer.stop()
elif verdict == "grace":
if not self._lost_timer.isActive():
self._lost_timer.start()
else:
self._lost_timer.stop()
self._fail(f"Lost the connection to {self.name}.")
def _on_grace_expired(self):
self._fail(f"{self.name} stopped responding.")
def _on_app(self, app_id):
if app_stolen(app_id):
self._fail(f"Something else started casting to {self.name}.")
def _flush_volume(self):
level = self._pending_volume
self._submit(lambda: self._cast.set_volume(level))
# ---- internals ----
def _fail(self, reason: str):
"""Give up on the device and let Player fall back to local playback.
Reports the state lintunes last *asked* for rather than whatever the
socket last said. A dying connection pushes an IDLE media status just
before the disconnect, so reading the device's own view here would make
the music stop on the fallback instead of continuing on the speakers.
"""
if self._dying:
return
self._dying = True
self._poll.stop()
self._lost_timer.stop()
self._playing = self._intent_playing
self.unavailable.emit(reason)
def _set_playing(self, playing: bool):
if playing != self._playing:
self._playing = playing
self.state_changed.emit(playing)
def _set_optimistic(self, position_ms: int):
self._optimistic_ms = max(0, position_ms)
self._position_ms = self._optimistic_ms
self._optimistic_until = time.monotonic() * 1000 + self.SEEK_SETTLE_MS
self.position_changed.emit(self._position_ms)