v0.5.0: send album art to the Chromecast

The device is on a TV, so it should show the cover. play_media now carries
thumb=, which pychromecast folds into metadata["images"] — the field the
receiver paints full-screen. Verified against the real device: it fetches
both the audio and the artwork URL from us on every track change.

Album art lives in the audio file's tags rather than as a file of its own,
so TrackServer tokens now resolve to an _Asset that is either a path or a
blob held in memory. Audio and art get separate eviction rings so a cover
can't push out the previous track's audio while the device is still
fetching it; Range and HEAD work on both.

The image type is sniffed from the cover's magic bytes rather than trusted
from the tag — ID3 APIC mimes are routinely wrong or blank, and the
receiver silently drops an image whose declared type doesn't match its
content. Anything unrecognized is treated as "no cover".

Best-effort throughout: no art, junk where the art should be, or an
unreadable file all just play without a cover rather than failing the
load. Also sends albumArtist and trackNumber in the metadata.

tests/test_round29.py: 74 tests; 447 pass overall.
This commit is contained in:
2026-08-13 22:06:27 -04:00
parent a42665cacc
commit 5dbe6e6366
7 changed files with 217 additions and 33 deletions
+55 -28
View File
@@ -16,8 +16,10 @@ Range requests are mandatory, not an optimization: the Chromecast seeks by
re-requesting byte ranges, and won't report a duration without ``Accept-Ranges``.
"""
import io
import secrets
import threading
from dataclasses import dataclass
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
@@ -28,11 +30,34 @@ from lintunes.cast.support import parse_range
# the device re-requests the current file when it seeks and can briefly reach
# back for the previous one across a track change; small because every live
# token is a file this machine will hand to anything on the LAN that asks.
# Audio and artwork are counted separately so a track's cover can't evict the
# audio of the track before it.
KEEP_TOKENS = 3
CHUNK = 64 * 1024
@dataclass(frozen=True)
class _Asset:
"""Something published for the device to fetch: a library file on disk, or
a blob held in memory (album art, which is extracted from tags rather than
being a file of its own)."""
content_type: str
path: Path | None = None
data: bytes | None = None
def size(self) -> int:
if self.data is not None:
return len(self.data)
return self.path.stat().st_size
def open(self):
if self.data is not None:
return io.BytesIO(self.data)
return open(self.path, "rb")
class _Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1" # Chromecast wants keep-alive + Content-Length
@@ -45,7 +70,7 @@ class _Handler(BaseHTTPRequestHandler):
def _tracks(self):
return self.server.track_server
def _resolve(self) -> Path | None:
def _resolve(self) -> "_Asset | None":
prefix = "/t/"
if not self.path.startswith(prefix):
return None
@@ -58,13 +83,13 @@ class _Handler(BaseHTTPRequestHandler):
self._serve(body=True)
def _serve(self, body: bool):
path = self._resolve()
if path is None:
asset = self._resolve()
if asset is None:
self.send_error(HTTPStatus.NOT_FOUND)
return
try:
size = path.stat().st_size
handle = open(path, "rb")
size = asset.size()
handle = asset.open()
except OSError:
# The file moved or the drive went away since it was published.
self.send_error(HTTPStatus.NOT_FOUND)
@@ -81,7 +106,7 @@ class _Handler(BaseHTTPRequestHandler):
length = end - start + 1 if size else 0
self.send_response(status)
self.send_header("Content-Type", self._tracks.content_type(path))
self.send_header("Content-Type", asset.content_type)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Length", str(length))
if status == HTTPStatus.PARTIAL_CONTENT:
@@ -116,9 +141,10 @@ class TrackServer:
self._httpd: ThreadingHTTPServer | None = None
self._thread: threading.Thread | None = None
self._lock = threading.Lock()
self._tokens: dict[str, Path] = {}
self._types: dict[Path, str] = {}
self._order: list[str] = []
self._assets: dict[str, _Asset] = {}
# One eviction ring per kind, so publishing a track's cover can't push
# the previous track's audio out from under a device still fetching it.
self._rings: dict[str, list[str]] = {"audio": [], "art": []}
# ---- lifecycle ----
@@ -147,36 +173,37 @@ class TrackServer:
httpd.server_close()
self._thread = None
with self._lock:
self._tokens.clear()
self._types.clear()
self._order.clear()
self._assets.clear()
for ring in self._rings.values():
ring.clear()
# ---- publishing ----
def publish(self, path, content_type: str) -> str:
"""Make `path` fetchable and return its token."""
path = Path(path)
"""Make a library file fetchable and return its token."""
return self._publish(
_Asset(content_type=content_type, path=Path(path)), "audio")
def publish_bytes(self, data: bytes, content_type: str) -> str:
"""Make an in-memory blob (album art) fetchable and return its token."""
return self._publish(
_Asset(content_type=content_type, data=data), "art")
def _publish(self, asset: _Asset, kind: str) -> str:
with self._lock:
token = secrets.token_urlsafe(16)
self._tokens[token] = path
self._types[path] = content_type
self._order.append(token)
self._assets[token] = asset
ring = self._rings[kind]
ring.append(token)
# Drop the oldest so a long listening session doesn't leave the
# whole played history reachable.
while len(self._order) > KEEP_TOKENS:
stale = self._order.pop(0)
dropped = self._tokens.pop(stale, None)
if dropped is not None and dropped not in self._tokens.values():
self._types.pop(dropped, None)
while len(ring) > KEEP_TOKENS:
self._assets.pop(ring.pop(0), None)
return token
def lookup(self, token: str) -> Path | None:
def lookup(self, token: str) -> _Asset | None:
with self._lock:
return self._tokens.get(token)
def content_type(self, path: Path) -> str:
with self._lock:
return self._types.get(path, "application/octet-stream")
return self._assets.get(token)
def url_for(self, host: str, token: str) -> str:
return f"http://{host}:{self.port}/t/{token}"