Files
lintunes/lintunes/andtunes/art.py
T
trav f21c31940f
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
v0.97.0: macOS port (Round 129): OS-aware paths, config and cookies; Mac now-playing, packaging (PyInstaller .app, dmg build, signing notes, CI workflow) and docs
2026-11-17 22:41:48 -08:00

108 lines
3.7 KiB
Python

"""Album covers, rendered once per album for a 2.88" screen.
Art lives in ID3/MP4/FLAC tags, not as files, so somebody has to decode it.
Doing that on the Rabbit means a MediaMetadataRetriever open per album on a
Helio P35; doing it here means the device reads a plain JPEG that is already
the right size. LinTunes has mutagen and Qt's image stack, so it does the work.
Keyed by album rather than track — one cover for a twelve-song release is one
mutagen open instead of twelve, and one file on the device instead of twelve
copies of the same picture.
Rendering uses QImage (not QPixmap), which is safe off the GUI thread — this
runs on the sync worker's daemon thread.
"""
import os
from pathlib import Path
from PyQt6.QtCore import QBuffer, QByteArray, QIODevice, Qt
from PyQt6.QtGui import QImage
from .. import paths, tagging
from .layout import album_key
# The panel is 480 px wide, so a cover never needs to be bigger than that;
# the list thumbnails downsample from the same file on the device.
ART_SIZE = 480
JPEG_QUALITY = 85
def _cache_dir() -> Path:
return paths.cache_dir() / "andtunes-art"
def render_jpeg(data: bytes) -> bytes | None:
"""Scale raw cover bytes down to ART_SIZE and re-encode as JPEG.
Never upscales: a small embedded cover stays small rather than being
blown up into a bigger file that looks no better.
"""
image = QImage()
if not image.loadFromData(QByteArray(data)):
return None
if image.width() > ART_SIZE or image.height() > ART_SIZE:
image = image.scaled(ART_SIZE, ART_SIZE,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
buffer = QBuffer()
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
if not image.save(buffer, "JPEG", JPEG_QUALITY):
return None
return bytes(buffer.data())
def album_art_jpeg(track) -> bytes | None:
"""The cover for this track's album, ready to write to the device.
Cached under $XDG_CACHE_HOME/lintunes/andtunes-art so a re-sync doesn't
re-decode every album. The cache entry is stale once the audio file is
newer than it — which is exactly right, because embedding new artwork
rewrites the file and moves its mtime. Nothing prunes this cache; it is
one small JPEG per album and `clear_cache()` empties it.
"""
if track is None or not track.location:
return None
src = Path(track.location)
try:
src_mtime = src.stat().st_mtime
except OSError:
return None
cache = _cache_dir() / f"{album_key(track)}.jpg"
# "This album has no art" is cached too, as an empty marker with the same
# freshness rule — otherwise every artless album cost a mutagen open on
# every sync, forever.
none = cache.with_suffix(".none")
for path in (cache, none):
try:
if path.stat().st_mtime >= src_mtime:
return cache.read_bytes() if path is cache else None
except OSError:
pass # not cached yet, or unreadable — fall through and re-render
raw = tagging.read_embedded_artwork(src)
jpeg = render_jpeg(raw) if raw else None
try:
cache.parent.mkdir(parents=True, exist_ok=True)
if jpeg:
tmp = cache.with_suffix(".tmp")
tmp.write_bytes(jpeg)
tmp.replace(cache)
none.unlink(missing_ok=True)
else:
none.touch()
os.utime(none)
cache.unlink(missing_ok=True)
except OSError:
pass # a cache we can't write is a slow sync, not a failed one
return jpeg
def clear_cache():
for path in [*_cache_dir().glob("*.jpg"), *_cache_dir().glob("*.none")]:
try:
path.unlink()
except OSError:
pass