Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871"""Bounded cell output and image validation, independent of kernel lifetime."""
from __future__ import annotations
import base64import hashlibimport osimport reimport structimport tempfileimport timefrom collections.abc import Callable, Sequencefrom dataclasses import dataclassfrom typing import BinaryIO, cast
import albedo_apiimport 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 * 1024RETAIN = albedo_api.RETAINMAX_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 outboxMAX_IMAGE_BYTES = 5 * 1024 * 1024MAX_CLIP_BYTES = 20 * 1024 * 1024MAX_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 * 1024SPILL_KEEP = 14 * 24 * 3600 # seconds, the python state expirySPILL_DIR: str | None = NoneTEXT_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("<I", data[4:8])[0] + 8 == len(data): size = webp_size(data, 12) return None if size is None else (*size, len(data)) return None
IMAGE_ENDS = {"image/png": "IEND chunk", "image/jpeg": "end-of-image marker"}
def image_complete(data: bytes, header: tuple[str, int, int, int]) -> 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("<I", data[at + 4 : at + 8])[0] body = data[at + 8 :] if kind == b"VP8X" and size == 10 and len(body) >= 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("<I", body[1:5])[0] return ("image/webp", (bits & 0x3FFF) + 1, ((bits >> 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("<HH", body[6:10]) width, height = width & 0x3FFF, height & 0x3FFF return ("image/webp", width, height) if width and height else None at += 8 + size + size % 2 if at > 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("<I", data[4:8])[0] return "audio/wav" if size + 8 == len(data) and _riff_format(data, 12) else None if data[:4] == b"fLaC": return _flac(data) if data[:4] == b"OggS": return _ogg(data) if data[4:8] == b"ftyp": return _mp4(data) if data[:4] == b"\x1a\x45\xdf\xa3": return _webm(data, 4) return _mpeg_audio(data, _skip_id3(data))
def _riff_format(data: bytes, at: int) -> bool: while at + 8 <= len(data): kind = data[at : at + 4] size = struct.unpack("<I", data[at + 4 : at + 8])[0] if kind == b"fmt ": return size >= 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