Skip to content

Media Metadata Inspector — Python source

Inspect audio, video and image files at the byte level — MP4 boxes, ID3 tags, WAV chunks, GIF headers — parsed by our own readers, entirely in your browser.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""media-metadata-inspector — read container metadata straight from the bytes.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `media-metadata-inspector` tool,
ported from src/lib/media-meta.ts (the canonical TypeScript implementation).

Pure byte-slicing with ``int.from_bytes`` and ``bytes.decode``: sniffs the
container signature (MP4 "ftyp" box, "ID3", RIFF/WAVE, GIF8, WebM EBML
magic), then walks it for duration, dimensions, and tags. The one library
substitution: TextDecoder becomes ``decode("utf-8", "replace")`` — both
substitute U+FFFD for invalid sequences, so bad bytes never crash a probe.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import re
from dataclasses import dataclass


@dataclass
class MediaMeta:
    """kind is 'mp4' | 'mp3' | 'wav' | 'gif' | 'webm' | 'unknown'."""

    kind: str
    duration_sec: float | None = None
    width: float | None = None
    height: float | None = None
    title: str | None = None
    artist: str | None = None
    album: str | None = None


# -- readers: MP4 and ID3 fields are big-endian, RIFF/WAV + GIF little-endian.


def u16le(b: bytes, o: int) -> int:
    return int.from_bytes(b[o:o + 2], "little")


def u32be(b: bytes, o: int) -> int:
    return int.from_bytes(b[o:o + 4], "big")


def u32le(b: bytes, o: int) -> int:
    return int.from_bytes(b[o:o + 4], "little")


def ascii(b: bytes, start: int, length: int) -> str:
    return b[start:start + length].decode("latin-1")


def syncsafe(b: bytes, o: int) -> int:
    """ID3 syncsafe integer: four 7-bit groups, no byte sets the high bit."""
    return (b[o] << 21) | (b[o + 1] << 14) | (b[o + 2] << 7) | b[o + 3]


def find_boxes(b: bytes, start: int, end: int, wanted: str) -> list:
    """MP4 box walk: payload ranges [start, end) for every box of that type."""
    found: list = []
    pos = start
    while pos + 8 <= end:
        size = u32be(b, pos)
        if size == 1:  # 64-bit sizes unsupported — stop safely.
            return found
        if size == 0:  # size 0: box extends to the end
            size = end - pos
        if size < 8 or pos + size > end:
            return found
        if ascii(b, pos + 4, 4) == wanted:
            found.append((pos + 8, pos + size))
        pos += size
    return found


def probe_mp4(b: bytes) -> MediaMeta:
    """MP4: moov -> mvhd gives duration; the first trak's tkhd gives dims."""
    meta = MediaMeta(kind="mp4")
    for m_start, m_end in find_boxes(b, 0, len(b), "moov"):
        for s, e in find_boxes(b, m_start, m_end, "mvhd"):
            version = b[s]
            if version == 0 and e - s >= 20:
                timescale = u32be(b, s + 12)
                if timescale > 0:
                    meta.duration_sec = u32be(b, s + 16) / timescale
            elif version == 1 and e - s >= 32:
                timescale = u32be(b, s + 20)
                # 64-bit duration: high and low u32 halves of the u64.
                duration = u32be(b, s + 24) * 0x100000000 + u32be(b, s + 28)
                if timescale > 0:
                    meta.duration_sec = duration / timescale
        for t_start, t_end in find_boxes(b, m_start, m_end, "trak"):
            tkhds = find_boxes(b, t_start, t_end, "tkhd")
            if not tkhds:
                continue
            s, e = tkhds[0]
            # tkhd stores width/height as 16.16 fixed point — divide by 65536.
            if b[s] == 0 and e - s >= 84:
                meta.width = u32be(b, s + 76) / 65536
                meta.height = u32be(b, s + 80) / 65536
                break  # first track is enough
    return meta


def decode_id3_text(b: bytes, start: int, length: int) -> str:
    """Decode one ID3 text frame (first byte selects the encoding)."""
    if length <= 0:
        return ""
    encoding = b[start]
    text = b[start + 1:start + length]  # slicing clamps, like the lib's subarray
    if encoding == 3:  # UTF-8 (ID3v2.4); stop at the null terminator.
        return text.split(b"\x00", 1)[0].decode("utf-8", "replace")
    if encoding in (1, 2):
        # UTF-16: encoding 1 carries a BOM (sniff endianness); 2 is BOM-less BE.
        bom = encoding == 1 and text[:1] in (b"\xff", b"\xfe")
        little = bom and text[0] == 0xFF
        out = []
        for i in range(2 if bom else 0, len(text) - 1, 2):
            code = int.from_bytes(text[i:i + 2], "little" if little else "big")
            if code == 0:
                break
            out.append(chr(code))
        return "".join(out)
    # ISO-8859-1 / ASCII range: latin-1 maps every byte to its code point.
    return text.split(b"\x00", 1)[0].decode("latin-1")


def probe_id3(b: bytes) -> MediaMeta:
    """ID3v2: walk frames, keep TIT2 (title), TPE1 (artist), TALB (album)."""
    meta = MediaMeta(kind="mp3")
    version = b[3]
    tag_size = syncsafe(b, 6)
    pos = 10
    end = min(10 + tag_size, len(b))
    while pos + 10 <= end:
        frame_id = ascii(b, pos, 4)
        if not re.fullmatch(r"[A-Z0-9]{4}", frame_id):
            break
        # ID3v2.4 frame sizes are syncsafe; v2.2/v2.3 are plain big-endian.
        size = syncsafe(b, pos + 4) if version == 4 else u32be(b, pos + 4)
        if size == 0:
            break
        # Clamp declared size to the tag end: a corrupt frame stays inside the tag.
        avail = max(end - (pos + 10), 0)
        text = decode_id3_text(b, pos + 10, min(size, avail))
        if frame_id == "TIT2":
            meta.title = text
        elif frame_id == "TPE1":
            meta.artist = text
        elif frame_id == "TALB":
            meta.album = text
        pos += 10 + size
    return meta


def probe_wav(b: bytes) -> MediaMeta:
    """WAV: fmt chunk gives byteRate; data chunk size / byteRate = duration."""
    meta = MediaMeta(kind="wav")
    pos = 12  # past RIFF size + WAVE
    byte_rate = 0
    while pos + 8 <= len(b):
        chunk_id = ascii(b, pos, 4)
        size = u32le(b, pos + 4)
        if chunk_id == "fmt " and pos + 8 + 16 <= len(b):
            byte_rate = u32le(b, pos + 16)  # byteRate sits at fmt payload offset 8
        elif chunk_id == "data" and byte_rate > 0:
            meta.duration_sec = size / byte_rate
            break
        pos += 8 + size + (size % 2)  # chunks are word-aligned
    return meta


def probe(data: bytes) -> MediaMeta | None:
    """Sniff the container and parse its metadata.

    Returns ``None`` when the input is under 12 bytes — too short for any
    signature.
    """
    if len(data) < 12:
        return None
    if ascii(data, 4, 4) == "ftyp":  # MP4 / MOV
        return probe_mp4(data)
    if ascii(data, 0, 3) == "ID3":
        return probe_id3(data)
    if ascii(data, 0, 4) == "RIFF" and ascii(data, 8, 4) == "WAVE":
        return probe_wav(data)
    if ascii(data, 0, 4) == "GIF8":
        return MediaMeta(kind="gif", width=u16le(data, 6), height=u16le(data, 8))
    if data[:4] == b"\x1a\x45\xdf\xa3":  # WebM EBML magic
        return MediaMeta(kind="webm")
    return MediaMeta(kind="unknown")


# Usage:
#   meta = probe(Path("clip.mp4").read_bytes())
#   print(meta.kind, meta.duration_sec, meta.width, meta.height, meta.title)

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →