Coverage for downtify/cover_thumbs.py: 91%
80 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"""Cover art at the sizes a client shows it: small in lists, full size in
2Now Playing.
4The cover is read out of the audio file's tags once (the same reader
5``/cover`` uses, :func:`downtify.cover_art.extract_cover_art`) and every
6size is kept on disk under ``<data>/cover_thumbs``, keyed by the file's
7resolved path, size and modification time - so files in different folders
8never share a cover, and a re-tagged file gets new
9pictures, and nothing is re-extracted or re-scaled on later requests.
10Scaling uses the ffmpeg already in the image; without it (or if it
11fails) the full-size picture is served for every size.
12"""
14from __future__ import annotations
16import contextlib
17import hashlib
18import json
19import shutil
20import subprocess
21import threading
22from pathlib import Path
23from typing import Optional
25from loguru import logger
27from .cover_art import extract_cover_art
29#: The sizes (px, longest side) a client may ask for; ``0`` is full size.
30SIZES = (150, 300, 600)
31#: ffmpeg processes scaling covers at once. A first scroll through a
32#: large library asks for thousands of thumbnails; each is made once.
33MAX_PARALLEL_SCALES = 4
34_SCALE_SLOTS = threading.BoundedSemaphore(MAX_PARALLEL_SCALES)
37def normalize_size(value: object) -> int:
38 """The smallest allowed size at or above *value*; ``0`` (full size)
39 for ``full``, nothing, or anything larger than the biggest size."""
41 try:
42 wanted = int(str(value))
43 except (TypeError, ValueError):
44 return 0
45 for size in SIZES:
46 if wanted <= size:
47 return size
48 return 0
51class CoverThumbs:
52 """Covers by size, cached on disk."""
54 def __init__(self, cache_dir: Path, ffmpeg: Optional[str] = None) -> None:
55 self._dir = Path(cache_dir)
56 self._ffmpeg = ffmpeg if ffmpeg is not None else shutil.which('ffmpeg')
58 @staticmethod
59 def _key(source: Path) -> str:
60 st = source.stat()
61 raw = f'{source.resolve()}\n{st.st_size}\n{st.st_mtime_ns}'
62 return hashlib.sha256(raw.encode()).hexdigest()
64 def get(
65 self, source: Path, size: int = 0
66 ) -> Optional[tuple[bytes, str, str]]:
67 """``(image, media type, etag)`` for *source*'s cover at *size*,
68 or ``None`` when the file has no cover."""
70 key = self._key(source)
71 full = self._full(source, key)
72 if full is None:
73 return None
74 data, mime = full
75 if not size:
76 return data, mime, f'"{key[:16]}-full"'
77 thumb = self._dir / f'{key}-{size}.jpg'
78 if thumb.is_file():
79 return thumb.read_bytes(), 'image/jpeg', f'"{key[:16]}-{size}"'
80 scaled = self._scale(data, size)
81 if scaled is None:
82 return data, mime, f'"{key[:16]}-full"'
83 self._dir.mkdir(parents=True, exist_ok=True)
84 with contextlib.suppress(OSError):
85 thumb.write_bytes(scaled)
86 return scaled, 'image/jpeg', f'"{key[:16]}-{size}"'
88 def _full(self, source: Path, key: str) -> Optional[tuple[bytes, str]]:
89 data_path = self._dir / f'{key}-full.bin'
90 meta_path = self._dir / f'{key}-full.json'
91 if data_path.is_file() and meta_path.is_file():
92 with contextlib.suppress(OSError, ValueError):
93 mime = json.loads(meta_path.read_text())['mime']
94 return data_path.read_bytes(), mime
95 data, mime = extract_cover_art(source)
96 if not data:
97 return None
98 mime = mime or 'image/jpeg'
99 self._dir.mkdir(parents=True, exist_ok=True)
100 with contextlib.suppress(OSError):
101 data_path.write_bytes(data)
102 meta_path.write_text(json.dumps({'mime': mime}))
103 return data, mime
105 def _scale(self, data: bytes, size: int) -> Optional[bytes]:
106 if not self._ffmpeg:
107 return None
108 try:
109 with _SCALE_SLOTS:
110 result = self._run_ffmpeg(data, size)
111 except (OSError, subprocess.TimeoutExpired):
112 logger.opt(exception=True).debug('Cover scaling failed')
113 return None
114 if result.returncode != 0 or not result.stdout:
115 return None
116 return result.stdout
118 def _run_ffmpeg(
119 self, data: bytes, size: int
120 ) -> subprocess.CompletedProcess[bytes]:
121 return subprocess.run(
122 [
123 self._ffmpeg,
124 '-nostdin',
125 '-hide_banner',
126 '-loglevel',
127 'error',
128 '-i',
129 'pipe:0',
130 '-vf',
131 f'scale={size}:{size}:force_original_aspect_ratio=decrease',
132 '-frames:v',
133 '1',
134 '-q:v',
135 '4',
136 '-f',
137 'image2',
138 '-c:v',
139 'mjpeg',
140 'pipe:1',
141 ],
142 input=data,
143 capture_output=True,
144 timeout=20,
145 check=False,
146 )