"""Where capture bytes go, and what can be read back out of them. Lives at package level rather than under ``api`` because both sides use it: the ingest route writes frames, and the worker reads them back to build thumbnails. A worker importing from ``api`` would be the wrong way round. Split by cost, deliberately. Everything above the thumbnail section runs on the ingest path, once per frame, and must never be the reason a burst is slow -- so it reads nine bytes of JPEG header rather than decoding an image. Pillow appears only below, in the worker, where the frame has to be decoded anyway. """ from __future__ import annotations import os import uuid from datetime import datetime from pathlib import Path # Matches `request_body max_size 12MB` in deploy/Caddyfile. Enforced here too, # because Caddy is not in front of the app in development and a limit that # only exists in the proxy is not a limit. MAX_IMAGE_BYTES = 12 * 1024 * 1024 # SOI. A JPEG always starts FF D8 FF; anything else is not one, whatever the # Content-Type header claims. _JPEG_MAGIC = b"\xff\xd8\xff" # Start-of-frame markers, which carry the dimensions. C4 (DHT), C8 (JPG) and # CC (DAC) share the range but are not SOF. _SOF_MARKERS = frozenset( {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} ) def looks_like_jpeg(data: bytes) -> bool: return data.startswith(_JPEG_MAGIC) def jpeg_dimensions(data: bytes) -> tuple[int, int] | None: """(width, height) from the JPEG header, or None if it cannot be read. Walks the segment chain to the first SOF. None is not an error: a frame whose dimensions we cannot parse is still a frame worth keeping, and the columns are nullable for exactly that reason. """ i, n = 2, len(data) while i + 3 < n: if data[i] != 0xFF: i += 1 continue marker = data[i + 1] # Standalone markers: no length field follows. if marker == 0x01 or 0xD0 <= marker <= 0xD8: i += 2 continue if marker == 0xD9: # EOI break segment_length = int.from_bytes(data[i + 2 : i + 4], "big") if segment_length < 2: break # malformed; a shorter length would not advance if marker in _SOF_MARKERS: if i + 9 > n: break height = int.from_bytes(data[i + 5 : i + 7], "big") width = int.from_bytes(data[i + 7 : i + 9], "big") return (width, height) if width and height else None i += 2 + segment_length return None def relative_image_path(capture_id: uuid.UUID, received_at: datetime) -> str: """``YYYY/MM/DD/.jpg`` (SPEC 3.3). Dated by ``received_at``, never by the device clock: the device may be unsynced and report nothing at all, and SPEC C7 makes server time authoritative. Stored relative to POORBIRD_IMAGE_ROOT so the root stays a deployment concern -- Caddy resolves the same relative path against the same configured root when it serves the bytes. """ return f"{received_at:%Y/%m/%d}/{capture_id}.jpg" def write_atomically(destination: Path, data: bytes) -> None: """Write via a temporary file in the same directory, then rename. A half-written JPEG is indistinguishable from a whole one until something tries to decode it, so the file must never be visible at its final path until it is complete. Same directory keeps the rename on one filesystem, which is what makes it atomic. """ destination.parent.mkdir(parents=True, exist_ok=True) temporary = destination.with_name(f".{destination.name}.part") try: temporary.write_bytes(data) os.replace(temporary, destination) except BaseException: temporary.unlink(missing_ok=True) raise # --- thumbnails ------------------------------------------------------------- # # Worker only. Nothing above this line imports Pillow, so the ingest path # never pays for it. # 400px on the long edge, WebP, matching the /thumbs/_400.webp pattern # in SPEC 3.3. The number is in the filename, so changing it means writing to # a new name rather than silently serving a differently-sized image from the # old one. THUMB_EDGE = 400 THUMB_QUALITY = 80 class UndecodableImage(Exception): """The bytes are not an image this build of Pillow can read. Distinct from an I/O error on purpose: a frame that cannot be decoded will never decode, so retrying is pointless and the worker should record the fact rather than burn its attempts. """ def relative_thumb_path(capture_id: uuid.UUID) -> str: """``_400.webp`` (SPEC 3.3), flat rather than dated. Thumbnails are addressed by capture id alone and there are far fewer of them per byte, so the dated tree that keeps the image directories to a sane size buys nothing here. """ return f"{capture_id}_{THUMB_EDGE}.webp" def make_thumbnail(source: Path) -> tuple[bytes, tuple[int, int]]: """Encode a WebP thumbnail. Returns the bytes and the SOURCE dimensions. The source size is returned because the worker is the first place that truly decodes the frame: ingest reads the JPEG header, which can be absent or unparseable, and this is the chance to fill in what it missed. """ import io from PIL import Image, UnidentifiedImageError try: with Image.open(source) as img: img.load() original = (img.width, img.height) # Never upscale. A frame smaller than the thumbnail box should # stay its own size rather than be blown up into a blurry one. thumb = img.convert("RGB") thumb.thumbnail((THUMB_EDGE, THUMB_EDGE), Image.Resampling.LANCZOS) buffer = io.BytesIO() thumb.save(buffer, format="WEBP", quality=THUMB_QUALITY, method=4) return buffer.getvalue(), original except (UnidentifiedImageError, OSError, ValueError) as exc: # Pillow raises OSError for a truncated file as well as for a real # I/O fault, and the two are not worth separating here: either way # this frame is not going to produce a thumbnail. raise UndecodableImage(f"{type(exc).__name__}: {exc}") from exc