"""Bounded cell output and image validation, independent of kernel lifetime.""" from __future__ import annotations import base64 import hashlib import os import re import struct import tempfile import time from collections.abc import Callable, Sequence from dataclasses import dataclass from typing import BinaryIO, cast import albedo_api import albedo_trace PREVIEW = albedo_api.OUTPUT_PREVIEW # What a cell's result shows the model; a cell's output past it spills to the # file the result names. CELL_PREVIEW = 32 * 1024 RETAIN = albedo_api.RETAIN MAX_IMAGES = 4 # pictures go as base64 in the result frame. 5 MiB raw still fits its 8 MiB # clips go as raw parts, and a cell's clips stay inside the 64 MiB link outbox MAX_IMAGE_BYTES = 5 * 1024 * 1024 MAX_CLIP_BYTES = 20 * 1024 * 1024 MAX_CLIPS_BYTES = 40 * 1024 * 1024 # Cells spill past the preview, jobs past RETAIN. Files have the same disk cap # and lifetime; the kernel sets the directory and prunes files past SPILL_KEEP. SPILL_LIMIT = 16 * 1024 * 1024 SPILL_KEEP = 14 * 24 * 3600 # seconds, the python state expiry SPILL_DIR: str | None = None TEXT_ONLY = ( "this model reads text only, so no image would reach it; " "review changes with `git diff` and read code with files.read" ) def prune_spills(directory: str) -> None: """Make `directory` the spill directory, without the files past SPILL_KEEP.""" global SPILL_DIR SPILL_DIR = directory try: os.makedirs(directory, exist_ok=True) with os.scandir(directory) as entries: stale = [ entry.path for entry in entries if entry.is_file() and time.time() - entry.stat().st_mtime > SPILL_KEEP ] except OSError: SPILL_DIR = None return for path in stale: try: os.unlink(path) except OSError: pass @dataclass(frozen=True) class Attachment: payload: bytes | str # local bytes or daemon receipt mime: str size: int fps: float | None @property def is_clip(self) -> bool: return not self.mime.startswith("image/") class Capture: """Output as the bytes that were written: the first RETAIN of them in `data`, and once more than that has arrived, the last PREVIEW in a tail buffer that exists only from then on. A pipe reader gets the exact bytes back; text readers decode a window.""" def __init__( self, id: str, kind: str = "cell", max_edge: int | None = None, text_only: bool = False, media: tuple[str, ...] = (), max_fps: float | None = None, clip_room: int | None = None, max_clip_bytes: int = MAX_CLIP_BYTES, ) -> None: self.id: str = id self.kind: str = kind self.max_edge: int | None = max_edge self.text_only: bool = text_only self.media: tuple[str, ...] = media self.max_fps: float | None = max_fps self.clip_room: int | None = clip_room self.max_clip_bytes: int = min(max_clip_bytes, MAX_CLIP_BYTES) self.data: bytearray = bytearray() self._tail: bytearray | None = None self.seen: int = 0 self.finished: bool = False self.trace: albedo_trace.Trace = albedo_trace.Trace() self.interruption: str = "cancelled" self.images: list[Attachment] = [] # The file holding the whole output once it passed the preview, and # how much of it is there; `spill` stays set after the file closes. self.spill: str | None = None self.spilled: int = 0 self._spill_file: BinaryIO | None = None self._copy: tuple[int, str] | None = None # persist()'s file, at `seen` bytes def _new_spill_file(self) -> tuple[int, str]: readable = re.sub(r"[^a-zA-Z0-9_.-]", "_", self.id)[:40] digest = hashlib.sha256(self.id.encode()).hexdigest()[:16] return tempfile.mkstemp( prefix=f"{readable}-{digest}-", suffix=".txt", dir=SPILL_DIR ) def spills(self) -> bool: return self.kind in {"cell", "job"} and SPILL_DIR is not None def write(self, text: str) -> None: room = RETAIN - len(self.data) if text.isascii() and len(text) > room + PREVIEW and not self.spills(): # One byte per character: keep both ends without encoding the middle. self.write_bytes(text[:room].encode()) self.seen += len(text) - room - PREVIEW self.write_bytes(text[-PREVIEW:].encode()) return self.write_bytes(text.encode("utf-8", errors="replace")) def write_bytes(self, data: bytes | bytearray | memoryview) -> None: size = len(data) self.seen += size room = RETAIN - len(self.data) if size <= room: self.data += data else: if self._tail is None: # First overflow: `data` holds the whole stream so far, and from # now on never grows again, so drop its growth slack. self._tail = self.data[-PREVIEW:] self.data += data[:room] self.data = self.data[:] if size >= PREVIEW: self._tail = bytearray(data[-PREVIEW:]) else: self._tail += data del self._tail[:-PREVIEW] threshold = CELL_PREVIEW if self.kind == "cell" else RETAIN if self.seen > threshold and self.spills(): self._spill(data, size) def _spill(self, data: bytes | bytearray | memoryview, size: int) -> None: """Append `data` to the spill file, opening it with everything before it on the first write past the spill threshold. Unbuffered, so a backgrounded cell's file reads live. A file that will not open leaves `spill` unset.""" try: if self._spill_file is None: if self.spill is not None or self.spilled or SPILL_DIR is None: return # closed, full, refused, or failed fd, path = self._new_spill_file() self._spill_file = os.fdopen(fd, "wb", buffering=0) self.spill = path # Before this write the stream fit in `data` whole. prefix = self.data[: self.seen - size] self.spilled = self._spill_file.write(prefix) if self.spilled != len(prefix): raise OSError("incomplete output spill write") piece = data[: SPILL_LIMIT - self.spilled] written = self._spill_file.write(piece) self.spilled += written if written != len(piece): raise OSError("incomplete output spill write") except OSError: self.end_spill() self.spill = None # a file missing its end is not offered self.spilled = -1 # do not retry after losing bytes return if self.spilled >= SPILL_LIMIT: self.end_spill() def finish(self) -> None: self.finished = True self.end_spill() def end_spill(self) -> None: if self._spill_file is not None: self._spill_file.close() self._spill_file = None def spill_note(self) -> str: """What the result says about output past the preview, or nothing.""" if self.spill is None: return "" kept = ( f"its first {SPILL_LIMIT >> 20} MiB are" if self.spilled >= SPILL_LIMIT else "all of it is" ) return ( f"\n[output was {self.seen} bytes; {kept} in {self.spill}:" f" files.read(path, start_line=...) reads it, await files.find(pattern, path) searches it]\n" ) def tail(self, limit: int = PREVIEW) -> bytes: """The last `limit` bytes written, at most PREVIEW.""" limit = min(limit, PREVIEW) if limit <= 0: return b"" if self._tail is None and not self.data and self.spill and self.seen: # Revived: the whole output is in the spill file. start = max(0, self.seen - limit) return self.read_bytes(start, self.seen - start) source = self.data if self._tail is None else self._tail return bytes(source[-limit:]) def persist(self) -> dict[str, object] | None: """What a later kernel needs to read this output again, with the bytes held only in memory copied to a file; None when that copy fails. The capture itself is unchanged, so output still being written goes on.""" spill, spilled = self.spill, max(self.spilled, 0) if spill is None and self.data: if self._copy is not None and self._copy[0] == self.seen: spill = self._copy[1] elif SPILL_DIR is None: return None else: try: fd, spill = self._new_spill_file() with os.fdopen(fd, "wb") as file: file.write(self.data) except OSError: return None self._copy = (self.seen, spill) spilled = len(self.data) return { "id": self.id, "kind": self.kind, "seen": self.seen, "spill": spill, "spilled": spilled, # The end the file lacks: output past what was kept on disk. "tail": self.tail() if self.seen > spilled else None, } @classmethod def revive(cls, saved: dict[str, object]) -> Capture: """Read cell/job output from disk; rehydrate the writable native channel.""" capture = cls(str(saved["id"]), str(saved["kind"])) capture.seen = int(cast(int, saved["seen"])) capture.finished = capture.kind != "native" capture.spill = cast("str | None", saved["spill"]) capture.spilled = int(cast(int, saved["spilled"])) tail = saved.get("tail") if isinstance(tail, bytes): capture._tail = bytearray(tail) if capture.kind == "native": capture.data = bytearray(capture.read_bytes(0, min(capture.seen, RETAIN))) capture.spill, capture.spilled = None, 0 return capture @property def retained(self) -> int: return max(len(self.data), self.spilled if self.spill else 0) def read_bytes(self, offset: int, limit: int) -> bytes: if limit <= 0 or offset >= self.seen: return b"" end = min(offset + limit, self.seen) size = end - offset if end <= len(self.data): return bytes(self.data[offset:end]) if self.spill is None or end > self.spilled: raise ValueError("requested output was not retained") with open(self.spill, "rb") as file: file.seek(offset) data = file.read(size) if len(data) != size: raise OSError(f"output spill file is incomplete: {self.spill}") return data def read(self, offset: int = 0, limit: int = 4000) -> str: return self.read_bytes(max(0, offset), min(max(0, limit), PREVIEW)).decode( "utf-8", errors="ignore" ) def preview(self, status: str = "ok") -> str: if status == "ok": return self.read(0, CELL_PREVIEW) return self.tail(CELL_PREVIEW).decode("utf-8", errors="ignore") def accept_images(self) -> None: """Raise ValueError when this cell's model reads text only.""" if self.text_only: raise ValueError(TEXT_ONLY) def attach(self, data: bytes | os.PathLike[str], fps: float | None = None) -> str: """Queue one picture or audio or video clip, a video sampled at `fps` frames a second when given, or save overflow that would fit in an empty cell.""" return self.attach_all((data,), fps)[0] def attach_all( self, items: Sequence[bytes | os.PathLike[str]], fps: float | None = None ) -> list[str]: """Attach each of `items` as `attach` does, after checking them all, so an fps one of them cannot take attaches none.""" self._check_fps(fps) read = [self._read(data) for data in items] attachments = [ Attachment(data, self._type(data, fps), len(data), fps) for data in read ] for item in attachments: self._check_clip_bytes(item) for item in attachments: self._check_shown(item) self._check_room(attachments) return [self._queue(item) for item in attachments] def attach_host(self, media: albedo_api.HostMedia, fps: float | None = None) -> str: """Queue daemon-validated media without receiving its bytes.""" self._check_fps(fps) mime = media["mime_type"] if mime not in SUFFIXES: raise ValueError(f"albedo can't show attachments in the {mime} format") self._check_format(mime, fps) item = Attachment(media["receipt"], mime, media["bytes"], fps) self._check_clip_bytes(item) self._check_shown(item) if not item.is_clip: self.accept_images() self._check_bytes(item.size, "image", MAX_IMAGE_BYTES) self._check_edge(media["width"], media["height"]) return self._queue(item) def _type(self, data: bytes, fps: float | None) -> str: mime = image_type(data) or clip_type(data) if mime is None: raise ValueError( "attach a PNG, JPEG or WebP image, or a whole WAV, MP3, AAC (ADTS), " "FLAC, Ogg, MP4 or WebM clip; a file cut short is refused, so read " "the whole file" ) self._check_format(mime, fps) return mime def _check_format(self, mime: str, fps: float | None) -> None: if not mime.startswith("image/") and mime not in self.media: reads = ", ".join(self.media) if self.media else "no audio or video" raise ValueError(f"this model does not read {mime}; it reads {reads}") if fps is not None and not mime.startswith("video/"): raise ValueError(f"fps is for a video, not {mime}; show it without fps") def _check_clip_bytes(self, item: Attachment) -> None: if item.is_clip and item.size > self.max_clip_bytes: raise ValueError( f"this {item.size}-byte {item.mime} is over the " f"{self.max_clip_bytes / MIB:.1f} MiB this model takes in one clip; " "cut or encode it smaller before showing it" ) def room_left(self) -> int | None: """The base64 bytes of clips the session's next request still has room for beside the ones this cell attached, if the daemon said.""" if self.clip_room is None: return None return self.clip_room - sum( encoded_size(i.size) for i in self.images if i.is_clip ) def _check_room(self, items: list[Attachment]) -> None: """Refuse `items` when the clips among them this cell would attach, rather than find attached already or save as overflow, do not fit.""" room = self.room_left() if room is None: return attached = list(self.images) adding = 0 for item in items: if ( any(i.payload == item.payload for i in attached) or self._full(attached, item) is not None ): continue attached.append(item) if item.is_clip: adding += encoded_size(item.size) if adding <= room: return raise ValueError( f"these clips take {adding / MIB:.1f} MiB as base64, and the session's " f"next request has room for {max(room, 0) / MIB:.1f} MiB more; " "await commands.shake() lists the session's media and drops what it " "no longer needs" ) def _held(self, item: Attachment) -> Attachment | None: return next((i for i in self.images if i.payload == item.payload), None) def _check_shown(self, item: Attachment) -> None: """Refuse a video this cell already holds at another rate: one attachment carries one rate.""" held = self._held(item) if held is not None and held.fps != item.fps: rate = "its model's own rate" if held.fps is None else f"{held.fps:g} fps" raise ValueError( f"this video is already attached at {rate} in this cell; " "show it once per cell" ) def _check_fps(self, fps: float | None) -> None: if fps is None: return if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not fps > 0: raise ValueError(f"fps must be a number above 0, not {fps!r}") if self.max_fps is None: raise ValueError( "this model takes no fps for a video; it samples video at its own rate" ) if fps > self.max_fps: raise ValueError( f"this model samples a video at {self.max_fps:g} fps at most, not {fps:g}" ) def _check_picture(self, data: bytes, mime: str) -> None: self.accept_images() self._check_bytes(len(data), "image", MAX_IMAGE_BYTES) found = image_header(data) # A header this parser cannot read is left for the daemon to judge. if found is not None: _, width, height, _ = found if not image_complete(data, found): raise ValueError( f"this {len(data)}-byte {mime} stops before its {IMAGE_ENDS[mime]}: " "the data was cut short, so read the whole file before showing it" ) self._check_edge(width, height) def _check_edge(self, width: int, height: int) -> None: if self.max_edge is not None and max(width, height) > self.max_edge: raise ValueError( f"{width}x{height} image is over this model's {self.max_edge}px edge limit" ) def _read(self, data: bytes | os.PathLike[str]) -> bytes: if isinstance(data, os.PathLike): with open(data, "rb") as source: self._check_bytes( os.fstat(source.fileno()).st_size, "file", MAX_CLIP_BYTES ) data = source.read(MAX_CLIP_BYTES + 1) self._check_bytes(len(data), "file", MAX_CLIP_BYTES) return data def _check_bytes(self, size: int, what: str, limit: int) -> None: if size > limit: fix = ( "downscale or crop it" if what == "image" else "cut or encode it smaller" ) raise ValueError( f"this {size}-byte {what} exceeds the {limit >> 20} MiB ({limit} bytes) " f"limit; {fix} before showing it" ) def _queue(self, item: Attachment) -> str: if isinstance(item.payload, bytes) and not item.is_clip: self._check_picture(item.payload, item.mime) # A screenshot a plugin attached itself may be shown again by path. if self._held(item) is not None: return f"already attached {item.mime}, {item.size} bytes" full = self._full(self.images, item) if full is not None: if isinstance(item.payload, bytes): return self._save(item.payload, item.mime, full) raise ValueError( f"this cell is out of room ({full}). show this attachment in another cell" ) if isinstance(item.payload, str): self._check_room([item]) self.images.append(item) note = f"attached {item.mime}, {item.size} bytes" return note if item.fps is None else f"{note}, sampled at {item.fps:g} fps" def clear_images(self) -> None: self.images.clear() @staticmethod def _full(images: list[Attachment], item: Attachment) -> str | None: """What of a cell holding `images` that `item` would overflow, if any.""" if len(images) >= MAX_IMAGES: return f"{MAX_IMAGES} attachments" kind = "clip" if item.is_clip else "image" budget = MAX_CLIPS_BYTES if item.is_clip else MAX_IMAGE_BYTES held = sum(i.size for i in images if i.is_clip == item.is_clip) if held + item.size > budget: return f"{budget >> 20} MiB {kind} budget" return None def _save(self, data: bytes, mime: str, full: str) -> str: """Save an overflow attachment without adding it to this cell's result.""" fd, path = tempfile.mkstemp( prefix="clip-" if image_type(data) is None else "image-", suffix=SUFFIXES[mime], dir=SPILL_DIR, ) try: with os.fdopen(fd, "wb") as destination: destination.write(data) except BaseException: os.unlink(path) raise return f"not attached, this cell's {full} is full: saved to {path}; show_media({path!r}) in another cell" def encoded_images( self, ship: Callable[[str, bytes], str] | None = None ) -> list[object]: """The result's images: host receipts, raw clip references or base64.""" return [self._encoded(item, ship) for item in self.images] def _encoded( self, item: Attachment, ship: Callable[[str, bytes], str] | None ) -> object: entry: dict[str, object] if isinstance(item.payload, str): entry = {"host_media": item.payload} elif ship is not None and item.is_clip: entry = {"clip": ship(self.id, item.payload)} elif item.fps is None: return base64.b64encode(item.payload).decode("ascii") else: entry = {"data": base64.b64encode(item.payload).decode("ascii")} if item.fps is not None: entry["fps"] = float(item.fps) return entry MIB = 1 << 20 def encoded_size(size: int) -> int: """The bytes of `size` bytes as base64, as the daemon counts a clip.""" return 4 * ((size + 2) // 3) def image_size(data: bytes) -> tuple[str, int, int] | None: """MIME type, width and height of a whole image, or None. A port of `inspect` in image.gleam, which stays the authority: the daemon checks every image again, and image_header_parity_test holds the two equal.""" found = image_header(data) if found is None or not image_complete(data, found): return None return found[:3] def image_header(data: bytes) -> tuple[str, int, int, int] | None: """MIME type, width, height, and where image_complete looks for the end.""" if data[:16] == b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR" and len(data) >= 24: width, height = struct.unpack(">II", data[16:24]) return ("image/png", width, height, 8) if width > 0 and height > 0 else None if data[:2] == b"\xff\xd8": return jpeg_size(data, 2) if data[:4] == b"RIFF" and data[8:12] == b"WEBP" and len(data) >= 12: if struct.unpack(" bool: """A PNG's chunks run whole up to IEND; a JPEG has its end-of-image marker after the frame header (stuffed entropy data never forges one). WebP's RIFF size already covers the whole file.""" mime, _, _, at = header if mime == "image/png": while at + 12 <= len(data): size, kind = struct.unpack(">I4s", data[at : at + 8]) if size == 0 and kind == b"IEND": return True at += 12 + size return False if mime == "image/jpeg": return data.find(b"\xff\xd9", at) >= 0 return True JPEG_FRAMES = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7} JPEG_FRAMES |= {0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} def jpeg_size(data: bytes, at: int) -> tuple[str, int, int, int] | None: while True: at = data.find(b"\xff", at) if at < 0: return None at += 1 while at < len(data) and data[at] == 0xFF: at += 1 if at >= len(data): return None marker = data[at] if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7: at += 1 continue if at + 3 > len(data): return None length = struct.unpack(">H", data[at + 1 : at + 3])[0] end = at + 1 + length if length < 2 or end > len(data): return None if marker in JPEG_FRAMES: frame = data[at + 3 : end] if len(frame) < 5: return None height, width = struct.unpack(">HH", frame[1:5]) if width > 0 and height > 0: return ("image/jpeg", width, height, end) return None if marker in (0xDA, 0xD9): return None at = end def webp_size(data: bytes, at: int) -> tuple[str, int, int] | None: while at + 8 <= len(data): kind = data[at : at + 4] size = struct.unpack("= 10: width = int.from_bytes(body[4:7], "little") + 1 height = int.from_bytes(body[7:10], "little") + 1 return ("image/webp", width, height) if kind == b"VP8L" and size >= 5 and len(body) >= 5 and body[0] == 0x2F: bits = struct.unpack("> 14) & 0x3FFF) + 1) if kind == b"VP8 " and size >= 10 and len(body) >= 10: if body[3:6] == b"\x9d\x01\x2a": width, height = struct.unpack(" len(data): return None return None def image_type(data: bytes) -> str | None: if data.startswith(b"\x89PNG\r\n\x1a\n"): return "image/png" if data.startswith(b"\xff\xd8"): return "image/jpeg" if data[:4] == b"RIFF" and data[8:12] == b"WEBP": return "image/webp" return None SUFFIXES = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "audio/wav": ".wav", "audio/mpeg": ".mp3", "audio/aac": ".aac", "audio/flac": ".flac", "audio/ogg": ".ogg", "audio/mp4": ".m4a", "video/mp4": ".mp4", "video/webm": ".webm", } CLIP_TYPES = ( "audio/wav", "audio/mpeg", "audio/aac", "audio/flac", "audio/ogg", "audio/mp4", "video/mp4", "video/webm", ) def clip_type(data: bytes) -> str | None: """The MIME type of the whole audio or video clip `data` holds, or None. A port of `mime` in albedo_image/clip.gleam, which stays the authority: the daemon checks every clip again, and image_header_parity_test holds the two equal.""" if data[:4] == b"RIFF" and data[8:12] == b"WAVE" and len(data) >= 12: size = struct.unpack(" bool: while at + 8 <= len(data): kind = data[at : at + 4] size = struct.unpack("= 16 at += 8 + size + size % 2 return False def _flac(data: bytes) -> str | None: at = 4 if len(data) < 8 or data[at] & 0x7F != 0 or int.from_bytes(data[5:8], "big") != 34: return None while at + 4 <= len(data): last = data[at] & 0x80 at += 4 + int.from_bytes(data[at + 1 : at + 4], "big") if at > len(data): return None if last: frame = data[at : at + 2] return ( "audio/flac" if len(frame) == 2 and frame[0] == 0xFF and frame[1] & 0xFE == 0xF8 else None ) return None OGG_AUDIO = (b"OpusHead", b"\x01vorbis", b"\x7fFLAC", b"Speex ") def _ogg(data: bytes) -> str | None: at, first = 0, True while at < len(data): if data[at : at + 5] != b"OggS\x00" or at + 27 > len(data): return None count = data[at + 26] table = data[at + 27 : at + 27 + count] if len(table) != count: return None body = at + 27 + count if first and not data[body:].startswith(OGG_AUDIO): return None first = False at = body + sum(table) return "audio/ogg" if at == len(data) else None def _mp4_type(brand: bytes) -> str | None: if brand in (b"M4A ", b"M4B "): return "audio/mp4" return None if brand == b"qt " else "video/mp4" def _mp4(data: bytes) -> str | None: mime = _mp4_type(data[8:12]) if len(data) >= 12 else None at, movie = 0, False while mime is not None and at < len(data): if at + 8 > len(data): return None size, kind = struct.unpack(">I4s", data[at : at + 8]) movie = movie or kind == b"moov" if size == 0: return mime if movie else None if size == 1: if at + 16 > len(data): return None size = struct.unpack(">Q", data[at + 8 : at + 16])[0] if size < 16: return None elif size < 8: return None at += size return mime if mime is not None and at == len(data) and movie else None def _vint(data: bytes, at: int) -> tuple[int | None, int] | None: """An EBML size and where its body starts; None for an unknown size.""" if at >= len(data) or data[at] == 0: return None length = 8 - data[at].bit_length() + 1 if at + length > len(data): return None value = int.from_bytes(data[at : at + length], "big") & ((1 << (7 * length)) - 1) return (None if value == (1 << (7 * length)) - 1 else value), at + length def _known(data: bytes, at: int) -> tuple[int, int] | None: found = _vint(data, at) if found is None or found[0] is None or found[1] + found[0] > len(data): return None return found[1], found[1] + found[0] def _webm(data: bytes, at: int) -> str | None: header = _known(data, at) if header is None: return None start, end = header doctype = False while start < end and not doctype: if data[start : start + 2] == b"\x42\x82": body = _known(data[:end], start + 2) doctype = body is not None and data[body[0] : body[1]] == b"webm" if body is None: return None start = body[1] continue if start >= end or data[start] < 0x10: return None start += 8 - data[start].bit_length() + 1 body = _known(data[:end], start) if body is None: return None start = body[1] if not doctype or data[end : end + 4] != b"\x18\x53\x80\x67": return None segment = _vint(data, end + 4) if segment is None: return None size, body = segment return "video/webm" if size is None or body + size == len(data) else None def _skip_id3(data: bytes) -> int: if data[:3] != b"ID3" or len(data) < 10 or any(b & 0x80 for b in data[6:10]): return 0 size = (data[6] << 21) | (data[7] << 14) | (data[8] << 7) | data[9] size += 10 if data[5] & 0x10 else 0 return 10 + size if 10 + size <= len(data) else len(data) def _frame_type(second: int) -> str | None: version, layer = (second >> 3) & 3, (second >> 1) & 3 if second & 0xE0 != 0xE0: return None if layer == 0 and version in (2, 3): return "audio/aac" return "audio/mpeg" if layer == 1 and version != 1 else None def _mpeg_audio(data: bytes, at: int) -> str | None: if at + 4 > len(data) or data[at] != 0xFF: return None mime = _frame_type(data[at + 1]) if mime == "audio/mpeg": rate, sample = data[at + 2] >> 4, (data[at + 2] >> 2) & 3 return mime if rate != 15 and sample != 3 else None if mime == "audio/aac": while at < len(data): frame = data[at : at + 7] if len(frame) < 7 or frame[0] != 0xFF or frame[1] & 0xF6 != 0xF0: return None if (frame[2] >> 2) & 0xF >= 13: return None length = ((frame[3] & 3) << 11) | (frame[4] << 3) | (frame[5] >> 5) if length < 7: return None at += length return mime if at == len(data) else None return None