Files
lintunes/lintunes/cast/controller.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

190 lines
7.1 KiB
Python

"""Owns a cast session on MainWindow's behalf.
Widget-free by design: it reports state as signals and MainWindow decides what
to show. Held as an attribute on MainWindow — a worker object that goes out of
scope stops delivering its signals.
"""
import threading
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
from lintunes.cast.discovery import CastDiscovery, is_available
from lintunes.cast.server import TrackServer
from lintunes.cast.sink import CastSink
from lintunes.eventlog import log_control
from lintunes.inhibit import INHIBIT_LOGOUT, INHIBIT_SUSPEND, SleepInhibitor
CONNECT_TIMEOUT_S = 15.0
class CastController(QObject):
"""Connects to a Chromecast, hands Player a sink, and cleans up after."""
connecting = pyqtSignal(object) # CastDevice
connected = pyqtSignal(str) # device name
disconnected = pyqtSignal(str) # reason; "" when the user asked
failed = pyqtSignal(str)
def __init__(self, player, parent=None):
super().__init__(parent)
self._player = player
self._sink: CastSink | None = None
self._server: TrackServer | None = None
self._discovery: CastDiscovery | None = None
self._attempt = 0
self._connect_done = _ConnectResult(self)
self._connect_done.ready.connect(self._on_connect_result)
# Its own instance, like the device-sync one: while casting, this
# machine is the file server for the whole room, so a suspend or a
# logout cuts the music off mid-song.
self._inhibitor = SleepInhibitor(
reason="Casting to a Chromecast",
flags=INHIBIT_LOGOUT | INHIBIT_SUSPEND)
# ---- state ----
def is_available(self) -> tuple[bool, str]:
return is_available()
def is_connected(self) -> bool:
return self._sink is not None
def device_name(self) -> str:
return self._sink.name if self._sink is not None else ""
def discovery(self) -> CastDiscovery:
"""Created lazily and shared with the picker dialog, which needs the
live browser to turn a chosen device back into a connection."""
if self._discovery is None:
self._discovery = CastDiscovery(self)
return self._discovery
# ---- connecting ----
def connect_to(self, device):
"""Connect in the background; the outcome arrives as a signal."""
if self._sink is not None:
self.disconnect()
self._attempt += 1
attempt = self._attempt
self.connecting.emit(device)
log_control("cast", "connect", f"{device.name} at {device.host}")
discovery = self.discovery()
browser, zconf = discovery.browser(), discovery.zconf()
def work():
try:
import pychromecast
info = None
if browser is not None:
info = browser.devices.get(_uuid(device.uuid))
if info is not None:
cast = pychromecast.get_chromecast_from_cast_info(info, zconf)
else:
# The browser was already torn down (the dialog closed) —
# reach the device directly by address instead.
cast = pychromecast.get_chromecast_from_host(
(device.host, device.port, _uuid(device.uuid),
device.model, device.name))
cast.wait(timeout=CONNECT_TIMEOUT_S)
self._connect_done.ready.emit({"cast": cast}, attempt)
except Exception as e: # noqa: BLE001 — report, never crash
self._connect_done.ready.emit({"error": str(e)}, attempt)
threading.Thread(target=work, daemon=True).start()
def _on_connect_result(self, result: dict, attempt: int):
# The user can cancel and re-pick while a connect is in flight; a
# result from a superseded attempt must not install a sink.
if attempt != self._attempt:
cast = result.get("cast")
if cast is not None:
try:
cast.disconnect()
except Exception: # noqa: BLE001
pass
return
if "error" in result:
self.failed.emit(f"Couldn't connect: {result['error']}")
return
server = TrackServer()
try:
server.start()
except OSError as e:
self.failed.emit(f"Couldn't start the local media server: {e}")
return
# Built here, on the GUI thread, so its timers belong to a thread that
# actually runs an event loop.
self._server = server
self._sink = CastSink(result["cast"], server, self)
# Deferred to the next event-loop turn on purpose. Player also listens
# for `unavailable` and swaps back to the local sink, which disconnects
# this signal mid-emission; whichever slot ran second would silently be
# dropped. Letting Player do the fallback first and tidying up after is
# order-independent.
self._sink.unavailable.connect(
lambda reason: QTimer.singleShot(
0, lambda: self._on_unavailable(reason)))
self._player.set_sink(self._sink)
self._inhibitor.inhibit()
self.connected.emit(self._sink.name)
# ---- disconnecting ----
def disconnect(self, reason: str = ""):
"""Drop the session and hand playback back to the local sink."""
sink, self._sink = self._sink, None
self._server = None
if sink is None:
return
log_control("cast", "disconnect", f"{sink.name} reason={reason or 'user'}")
# Player carries the position across, so playback continues locally
# from the same spot rather than restarting the track. A no-op when
# Player already fell back on its own (the device-vanished path).
self._player.set_sink(None)
self._teardown(sink, reason)
def _on_unavailable(self, reason: str):
"""The device went away on its own. Player has already fallen back by
the time this lands, so this only tidies up and reports."""
sink, self._sink = self._sink, None
self._server = None
if sink is None:
return
log_control("cast", "lost", reason)
self._teardown(sink, reason)
def _teardown(self, sink, reason: str):
sink.shutdown()
self._inhibitor.release()
self.disconnected.emit(reason)
def shutdown(self):
"""Quitting. Unlike a user disconnect, playback is not handed back:
stopping first clears the current track, so the swap to the local sink
can't fire a burst of audio out of the speakers on the way out."""
if self._discovery is not None:
self._discovery.stop()
if self._sink is not None:
self._player.stop()
self.disconnect()
self._inhibitor.release()
class _ConnectResult(QObject):
"""Marshals a background connect result onto the GUI thread."""
ready = pyqtSignal(dict, int)
def _uuid(text: str):
import uuid
try:
return uuid.UUID(text)
except (ValueError, AttributeError, TypeError):
return text