Coverage for downtify/playlist_mosaic.py: 64%
128 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Spotify-style collage for a user-created playlist's sidecar JPEG.
3Imported playlists keep the artwork downloaded with the M3U. Manual
4ones have no remote cover, so the first 1–4 distinct track covers are
5composed into ``<playlist>.jpg`` beside the M3U (Navidrome, file
6browsers). The SPA also mosaics from track covers in the UI.
7"""
9from __future__ import annotations
11import hashlib
12import shutil
13import subprocess
14import tempfile
15from pathlib import Path
16from typing import Optional
18from loguru import logger
20from .cover_art import extract_cover_art
21from .library_catalog import LibraryContext, resolve_library_file
22from .m3u import read_m3u_text
24MOSAIC_SIZE = 600
25MAX_TILES = 4
28def _ffmpeg() -> Optional[str]:
29 return shutil.which('ffmpeg')
32def _filter_complex(count: int) -> str:
33 """ffmpeg graph: 1 cover fills the square; 2 split down the middle;
34 3 is left-full + two stacked on the right; 4 is a 2×2 grid."""
36 size = MOSAIC_SIZE
37 half = size // 2
38 crop = 'scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h}'
39 if count <= 1:
40 return f'[0:v]{crop.format(w=size, h=size)}[out]'
41 if count == 2:
42 cell = crop.format(w=half, h=size)
43 return f'[0:v]{cell}[l];[1:v]{cell}[r];[l][r]hstack=inputs=2[out]'
44 if count == 3:
45 left = crop.format(w=half, h=size)
46 sq = crop.format(w=half, h=half)
47 return (
48 f'[0:v]{left}[l];[1:v]{sq}[tr];[2:v]{sq}[br];'
49 '[tr][br]vstack=inputs=2[r];[l][r]hstack=inputs=2[out]'
50 )
51 cell = crop.format(w=half, h=half)
52 return (
53 f'[0:v]{cell}[a];[1:v]{cell}[b];'
54 f'[2:v]{cell}[c];[3:v]{cell}[d];'
55 '[a][b]hstack=inputs=2[top];'
56 '[c][d]hstack=inputs=2[bot];'
57 '[top][bot]vstack=inputs=2[out]'
58 )
61def unique_cover_images(
62 ctx: LibraryContext, files: list[str], *, limit: int = MAX_TILES
63) -> list[bytes]:
64 """Embedded/folder art for *files*, first distinct images in order."""
66 images: list[bytes] = []
67 seen: set[str] = set()
68 for stored in files:
69 path = resolve_library_file(stored, ctx)
70 if path is None:
71 continue
72 data, _mime = extract_cover_art(path)
73 if not data:
74 continue
75 digest = hashlib.sha256(data).hexdigest()
76 if digest in seen:
77 continue
78 seen.add(digest)
79 images.append(data)
80 if len(images) >= limit:
81 break
82 return images
85def _compose(images: list[bytes], dest: Path) -> bool:
86 ffmpeg = _ffmpeg()
87 if not ffmpeg:
88 if len(images) == 1:
89 dest.write_bytes(images[0])
90 return True
91 return False
92 with tempfile.TemporaryDirectory(prefix='downtify-mosaic-') as raw:
93 tmp = Path(raw)
94 inputs: list[str] = []
95 for index, data in enumerate(images):
96 tile = tmp / f'{index}.bin'
97 tile.write_bytes(data)
98 inputs.extend(['-i', str(tile)])
99 out = tmp / 'out.jpg'
100 cmd = [
101 ffmpeg,
102 '-nostdin',
103 '-hide_banner',
104 '-loglevel',
105 'error',
106 *inputs,
107 '-filter_complex',
108 _filter_complex(len(images)),
109 '-map',
110 '[out]',
111 '-frames:v',
112 '1',
113 '-q:v',
114 '4',
115 '-y',
116 str(out),
117 ]
118 try:
119 result = subprocess.run(
120 cmd, capture_output=True, timeout=30, check=False
121 )
122 except (OSError, subprocess.TimeoutExpired):
123 logger.opt(exception=True).debug(
124 'Playlist mosaic ffmpeg failed for {}', dest
125 )
126 if len(images) == 1:
127 dest.write_bytes(images[0])
128 return True
129 return False
130 if (
131 result.returncode != 0
132 or not out.is_file()
133 or not out.stat().st_size
134 ):
135 logger.debug(
136 'Playlist mosaic ffmpeg error for {}: {}',
137 dest,
138 (result.stderr or b'').decode('utf-8', errors='replace')[:400],
139 )
140 if len(images) == 1:
141 dest.write_bytes(images[0])
142 return True
143 return False
144 dest.write_bytes(out.read_bytes())
145 return True
148MAX_PLAYLIST_COVER_BYTES = 10 * 1024 * 1024
151def normalize_uploaded_cover(data: bytes, content_type: str) -> bytes:
152 """Validate and convert an uploaded JPEG, PNG or WebP to a sidecar JPEG."""
154 if not data or len(data) > MAX_PLAYLIST_COVER_BYTES:
155 raise ValueError('Cover image must be between 1 byte and 10 MiB')
156 signatures = {
157 'image/jpeg': data.startswith(b'\xff\xd8\xff'),
158 'image/png': data.startswith(b'\x89PNG\r\n\x1a\n'),
159 'image/webp': (
160 len(data) >= 12
161 and data.startswith(b'RIFF')
162 and data[8:12] == b'WEBP'
163 ),
164 }
165 if content_type not in signatures or not signatures[content_type]:
166 raise ValueError('Upload a valid JPEG, PNG or WebP image')
167 ffmpeg = _ffmpeg()
168 if not ffmpeg:
169 raise RuntimeError('Image conversion is unavailable')
170 try:
171 result = subprocess.run(
172 [
173 ffmpeg,
174 '-nostdin',
175 '-hide_banner',
176 '-loglevel',
177 'error',
178 '-max_pixels',
179 '40000000',
180 '-f',
181 'image2pipe',
182 '-i',
183 'pipe:0',
184 '-frames:v',
185 '1',
186 '-vf',
187 'scale=1600:1600:force_original_aspect_ratio=decrease',
188 '-q:v',
189 '3',
190 '-f',
191 'image2pipe',
192 '-vcodec',
193 'mjpeg',
194 'pipe:1',
195 ],
196 input=data,
197 capture_output=True,
198 timeout=30,
199 check=False,
200 )
201 except (OSError, subprocess.TimeoutExpired) as exc:
202 raise ValueError('Could not decode cover image') from exc
203 if result.returncode or not result.stdout.startswith(b'\xff\xd8'):
204 raise ValueError('Could not decode cover image')
205 return result.stdout
208def refresh_manual_playlist_cover(
209 ctx: LibraryContext, m3u_path: Path, files: list[str]
210) -> Optional[Path]:
211 """Write or remove ``m3u_path``'s ``.jpg`` from the playlist's tracks."""
213 dest = m3u_path.with_suffix('.jpg')
214 if has_explicit_cover(m3u_path):
215 return dest
216 images = unique_cover_images(ctx, files)
217 if not images:
218 dest.unlink(missing_ok=True)
219 return None
220 dest.parent.mkdir(parents=True, exist_ok=True)
221 if _compose(images, dest):
222 return dest
223 dest.unlink(missing_ok=True)
224 return None
227EXPLICIT_COVER_MARKER = '#EXTDOWNTIFY:cover=explicit'
230def has_explicit_cover(m3u_path: Path) -> bool:
231 """A source image takes precedence over a generated manual mosaic."""
233 if not m3u_path.with_suffix('.jpg').is_file():
234 return False
235 text = read_m3u_text(m3u_path)
236 if text is None:
237 return False
238 return any(
239 line.strip() == EXPLICIT_COVER_MARKER for line in text.splitlines()[:5]
240 )
243def keep_explicit_cover(m3u_path: Path) -> None:
244 """Remember a successfully saved source image, without changing tracks."""
246 if not m3u_path.with_suffix('.jpg').is_file():
247 return
248 text = read_m3u_text(m3u_path)
249 if text is None:
250 return
251 if EXPLICIT_COVER_MARKER not in text.splitlines()[:5]:
252 lines = text.splitlines()
253 lines.insert(1, EXPLICIT_COVER_MARKER)
254 m3u_path.write_text('\n'.join(lines) + '\n', encoding='utf-8')