diff options
| author | Danilo M. <danix@danix.xyz> | 2026-11-13 13:06:56 +0100 |
|---|---|---|
| committer | Danilo M. <danix@danix.xyz> | 2026-11-13 13:06:56 +0100 |
| commit | fe55526cbc6015c4268ee155f21bcb11de5609b5 (patch) | |
| tree | 64b176513e7e63e8fdf170e026d4da078bce5185 | |
| parent | ab2ebfd768bcc11f9c9124c15d9da700b9352587 (diff) | |
| download | deck-it-fe55526cbc6015c4268ee155f21bcb11de5609b5.tar.gz deck-it-fe55526cbc6015c4268ee155f21bcb11de5609b5.zip | |
feat(music): covers for embedded art and videos
Haruna sends an embedded audio cover inline as a data:image URL, which
the module dropped, and clears mpris:artUrl for every video on purpose
so the task manager shows the live window. Serve both at
/api/music/image/<key>: the data URL decoded, a local video as one
ffmpeg frame (thumbnail filter, 480 px wide), made on first request and
kept until the track changes. Only the current track's key answers, so
the tablet names a key, never a path.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | AGENTS.md | 4 | ||||
| -rw-r--r-- | deckit/modules/music.py | 53 | ||||
| -rw-r--r-- | tests/test_music.py | 22 |
3 files changed, 76 insertions, 3 deletions
@@ -103,6 +103,10 @@ Keep the server dependency-free apart from that one package. shows that tab that long and then goes back, unless the page is touched or the tab changed meanwhile. `windows.js` peeks on a window id the last poll lacked, for `[windows] peek` seconds (0 off). +- `music` drives any MPRIS player through `playerctl` (playerctld picks the + last active one). A `data:` cover, or a local video with no cover (Haruna + sends none), is served at `/api/music/image/<key>`, a video as an `ffmpeg` + frame; only the current track's key answers. - Launchers are `[launch] apps`, desktop ids run with `gtk-launch`; label and icon come from the `.desktop` file. The client sends the id, which must be configured and installed. diff --git a/deckit/modules/music.py b/deckit/modules/music.py index f590cc0..218d2c4 100644 --- a/deckit/modules/music.py +++ b/deckit/modules/music.py @@ -16,7 +16,12 @@ """Now playing and volume, via playerctl and wpctl.""" +import base64 +import hashlib +import mimetypes import subprocess +from pathlib import Path +from urllib.parse import unquote, urlsplit from ..module import Module, ModuleError @@ -41,24 +46,66 @@ def _popen(cmd): subprocess.Popen(cmd, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +def _frame(path): + """A JPEG frame from a video, for players that give videos no cover.""" + try: + return subprocess.run( + ["ffmpeg", "-v", "error", "-i", path, "-vf", "thumbnail,scale=480:-2", + "-frames:v", "1", "-f", "image2pipe", "-c:v", "mjpeg", "-"], + capture_output=True, timeout=10).stdout + except (OSError, subprocess.TimeoutExpired): + return b"" + + def make(cfg: dict) -> Module: run = cfg.get("run", _run) popen = cfg.get("popen", _popen) + frame = cfg.get("frame", _frame) + # The cover served at /api/music/image/<key>: only the current track's, + # so the tablet names a key, never a path. + cur = {"key": None, "src": None, "image": None} + + def serve(src): + key = hashlib.sha1(src.encode()).hexdigest()[:16] + if key != cur["key"]: + cur.update(key=key, src=src, image=None) + return f"/api/music/image/{key}" + + def image(key): + if key != cur["key"]: + return None + if cur["image"] is None: + src = cur["src"] + if src.startswith("data:"): + head, _, data = src.partition(",") + try: + cur["image"] = (base64.b64decode(data), head[5:].split(";")[0]) + except ValueError: + cur["image"] = () + else: + out = frame(unquote(urlsplit(src).path)) + cur["image"] = (out, "image/jpeg") if out else () + return cur["image"] or None def state(): fmt = SEP.join(["{{status}}", "{{title}}", "{{artist}}", "{{album}}", "{{mpris:length}}", - "{{position}}", "{{mpris:artUrl}}", "{{playerName}}"]) + "{{position}}", "{{mpris:artUrl}}", "{{playerName}}", "{{xesam:url}}"]) out = run(["playerctl", "metadata", "--format", fmt]) vol = run(["wpctl", "get-volume", "@DEFAULT_AUDIO_SINK@"]) volume = {"level": round(float(vol.split()[1]) * 100) if len(vol.split()) > 1 else 0, "muted": "MUTED" in vol} if not out: return {"status": "Stopped", "volume": volume} - status, title, artist, album, length, pos, art, name = (out.split(SEP) + [""] * 8)[:8] + status, title, artist, album, length, pos, art, name, url = (out.split(SEP) + [""] * 9)[:9] if art.startswith(("http://", "https://")): art_src = art elif art.startswith("file://"): art_src = "/api/art?v=" + str(abs(hash(art))) + elif art.startswith("data:image/"): + art_src = serve(art) + elif (not art and url.startswith("file://") + and (mimetypes.guess_type(Path(unquote(urlsplit(url).path)).name)[0] or "").startswith("video/")): + art_src = serve(url) else: art_src = None return {"status": status, "title": title, "artist": artist, "album": album, @@ -80,4 +127,4 @@ def make(cfg: dict) -> Module: actions = {name: (lambda cmd: (lambda body: popen(cmd)))(cmd) for name, cmd in BASE_ACTIONS.items()} actions["seek"] = seek actions["volume"] = volume - return Module(name="music", title="Music", state=state, actions=actions) + return Module(name="music", title="Music", state=state, actions=actions, image=image) diff --git a/tests/test_music.py b/tests/test_music.py index fe603cb..878c5f8 100644 --- a/tests/test_music.py +++ b/tests/test_music.py @@ -49,6 +49,28 @@ class Music(unittest.TestCase): st = music.make({"run": fake}).state() self.assertAlmostEqual(st["length"], 65.82, places=2) + def _state(self, art, url, frame=None): + out = "\x1f".join(["Playing", "t", "", "", "1", "0", art, "haruna", url]) + fake = lambda cmd, timeout=2: {"metadata": out, "get-volume": ""}[cmd[1]] + m = music.make({"run": fake, "frame": frame or (lambda path: b"")}) + return m, m.state() + + def test_embedded_cover_served_decoded(self): + m, st = self._state("data:image/png;base64,aGVsbG8=", "file:///a/song.flac") + key = st["art"].rsplit("/", 1)[1] + self.assertEqual(m.image(key), (b"hello", "image/png")) + self.assertIsNone(m.image("other")) + + def test_video_gets_a_frame(self): + paths = [] + m, st = self._state("", "file:///v/a%20clip.mp4", + lambda path: paths.append(path) or b"jpeg") + self.assertEqual(m.image(st["art"].rsplit("/", 1)[1]), (b"jpeg", "image/jpeg")) + self.assertEqual(paths, ["/v/a clip.mp4"]) + + def test_audio_without_cover_has_no_art(self): + self.assertIsNone(self._state("", "file:///a/song.flac")[1]["art"]) + def test_action_commands(self): self.assertEqual(music.BASE_ACTIONS["next"], ["playerctl", "next"]) |
