Skip to content

Media Metadata Inspector — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! media-metadata-inspector — read container metadata straight from the bytes.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `media-metadata-inspector` tool,
//! ported from src/lib/media-meta.ts (the canonical TypeScript implementation).
//!
//! Byte-slicing with `from_be_bytes` / `from_le_bytes`: MP4 and ID3 fields
//! are big-endian, RIFF/WAV and GIF little-endian, so the readers are named
//! for the byte order they produce. UTF-8 ID3 frames use
//! `String::from_utf8_lossy` in place of TextDecoder — invalid sequences
//! become U+FFFD, exactly the lib's decode behaviour.
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// Container kind: `Mp4 | Mp3 | Wav | Gif | Webm | Unknown`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Kind {
    #[default]
    Unknown,
    Mp4,
    Mp3,
    Wav,
    Gif,
    Webm,
}

/// Probe result. `None` fields mean "container parsed, field not present".
#[derive(Debug, Clone, Default)]
pub struct MediaMeta {
    pub kind: Kind,
    pub duration_sec: Option<f64>,
    pub width: Option<f64>,
    pub height: Option<f64>,
    pub title: Option<String>,
    pub artist: Option<String>,
    pub album: Option<String>,
}

/// Big-endian u32 (MP4 / ID3); 0 past the buffer, mirroring the lib's reads.
fn u32be(b: &[u8], o: usize) -> u32 {
    if b.len() < o + 4 { return 0; }
    u32::from_be_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])
}

/// Little-endian u32 (RIFF/WAV).
fn u32le(b: &[u8], o: usize) -> u32 {
    if b.len() < o + 4 { return 0; }
    u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])
}

/// Little-endian u16 (GIF dimensions).
fn u16le(b: &[u8], o: usize) -> u16 {
    if b.len() < o + 2 { return 0; }
    u16::from_le_bytes([b[o], b[o + 1]])
}

/// MP4 box walk: payload ranges [start, end) for every box of `wanted`.
fn find_boxes(b: &[u8], start: usize, end: usize, wanted: &str) -> Vec<(usize, usize)> {
    let mut found = Vec::new();
    let mut pos = start;
    while pos + 8 <= end {
        let mut size = u32be(b, pos) as usize;
        if size == 1 { return found; } // 64-bit sizes unsupported — stop safely.
        if size == 0 { size = end - pos; } // size 0: box extends to the end
        if size < 8 || pos + size > end { return found; }
        if &b[pos + 4..pos + 8] == wanted.as_bytes() {
            found.push((pos + 8, pos + size));
        }
        pos += size;
    }
    found
}

/// MP4: moov -> mvhd gives duration; the first trak's tkhd gives dimensions.
fn probe_mp4(b: &[u8]) -> MediaMeta {
    let mut meta = MediaMeta { kind: Kind::Mp4, ..Default::default() };
    for (ms, me) in find_boxes(b, 0, b.len(), "moov") {
        for (s, e) in find_boxes(b, ms, me, "mvhd") {
            let version = b[s];
            if version == 0 && e - s >= 20 {
                let timescale = u32be(b, s + 12);
                if timescale > 0 {
                    meta.duration_sec = Some(u32be(b, s + 16) as f64 / timescale as f64);
                }
            } else if version == 1 && e - s >= 32 {
                let timescale = u32be(b, s + 20);
                // 64-bit duration: high and low u32 halves of the u64.
                let duration = ((u32be(b, s + 24) as u64) << 32) | u32be(b, s + 28) as u64;
                if timescale > 0 {
                    meta.duration_sec = Some(duration as f64 / timescale as f64);
                }
            }
        }
        for (ts, te) in find_boxes(b, ms, me, "trak") {
            if let Some(&(s, e)) = find_boxes(b, ts, te, "tkhd").first() {
                // tkhd stores width/height as 16.16 fixed point — / 65536.
                if b[s] == 0 && e - s >= 84 {
                    meta.width = Some(u32be(b, s + 76) as f64 / 65536.0);
                    meta.height = Some(u32be(b, s + 80) as f64 / 65536.0);
                    break; // first track is enough
                }
            }
        }
    }
    meta
}

/// ID3v2 syncsafe integer: four 7-bit groups, no byte sets the high bit.
fn syncsafe(b: &[u8], o: usize) -> u32 {
    ((b[o] as u32) << 21) | ((b[o + 1] as u32) << 14) | ((b[o + 2] as u32) << 7) | b[o + 3] as u32
}

/// Decode one ID3 text frame (first byte selects the encoding).
pub fn decode_id3_text(b: &[u8], start: usize, len: usize) -> String {
    if len == 0 || start >= b.len() {
        return String::new();
    }
    let encoding = b[start];
    let text = &b[start + 1..(start + len).min(b.len())]; // clamps, like the lib
    match encoding {
        3 => {
            // UTF-8 (ID3v2.4); stop at the null terminator.
            let end = text.iter().position(|&x| x == 0).unwrap_or(text.len());
            String::from_utf8_lossy(&text[..end]).into_owned()
        }
        1 | 2 => {
            // UTF-16: encoding 1 carries a BOM (sniff endianness); 2 is BE.
            let bom = encoding == 1 && matches!(text.first(), Some(0xff) | Some(0xfe));
            let little = bom && text[0] == 0xff;
            let mut out = String::new();
            let mut i = if bom { 2 } else { 0 };
            while i + 1 < text.len() {
                let code = if little {
                    u16::from_le_bytes([text[i], text[i + 1]])
                } else {
                    u16::from_be_bytes([text[i], text[i + 1]])
                };
                if code == 0 { break; }
                // Lone surrogates become U+FFFD, as TextDecoder renders them.
                out.push(char::from_u32(code as u32).unwrap_or('\u{fffd}'));
                i += 2;
            }
            out
        }
        _ => text.iter().take_while(|&&x| x != 0).map(|&x| x as char).collect(),
    }
}

/// ID3v2: walk frames, keep TIT2 (title), TPE1 (artist), TALB (album).
fn probe_id3(b: &[u8]) -> MediaMeta {
    let mut meta = MediaMeta { kind: Kind::Mp3, ..Default::default() };
    let version = b[3];
    let tag_size = syncsafe(b, 6);
    let mut pos = 10usize;
    let end = (10 + tag_size as usize).min(b.len());
    while pos + 10 <= end {
        let id = &b[pos..pos + 4];
        if !id.iter().all(|&c| c.is_ascii_uppercase() || c.is_ascii_digit()) {
            break;
        }
        // ID3v2.4 frame sizes are syncsafe; v2.2/v2.3 are plain big-endian.
        let size = if version == 4 { syncsafe(b, pos + 4) } else { u32be(b, pos + 4) } as usize;
        if size == 0 { break; }
        // Clamp declared size to the tag end: a corrupt frame stays inside the tag.
        let avail = end.saturating_sub(pos + 10);
        let text = Some(decode_id3_text(b, pos + 10, size.min(avail)));
        match id {
            b"TIT2" => meta.title = text,
            b"TPE1" => meta.artist = text,
            b"TALB" => meta.album = text,
            _ => {}
        }
        pos += 10 + size;
    }
    meta
}

/// WAV: fmt chunk gives byteRate; data chunk size / byteRate = duration.
/// RIFF fields are little-endian, unlike MP4/ID3.
fn probe_wav(b: &[u8]) -> MediaMeta {
    let mut meta = MediaMeta { kind: Kind::Wav, ..Default::default() };
    let mut pos = 12usize; // past RIFF size + WAVE
    let mut byte_rate = 0u32;
    while pos + 8 <= b.len() {
        let id = &b[pos..pos + 4];
        let size = u32le(b, pos + 4);
        if id == b"fmt " && pos + 8 + 16 <= b.len() {
            byte_rate = u32le(b, pos + 16); // byteRate sits at fmt payload offset 8
        } else if id == b"data" && byte_rate > 0 {
            meta.duration_sec = Some(size as f64 / byte_rate as f64);
            break;
        }
        pos += 8 + size as usize + (size % 2) as usize; // chunks are word-aligned
    }
    meta
}

/// Sniff the container and parse its metadata. `None` when the input is under
/// 12 bytes — too short for any signature.
pub fn probe(bytes: &[u8]) -> Option<MediaMeta> {
    if bytes.len() < 12 { return None; }
    if &bytes[4..8] == b"ftyp" { return Some(probe_mp4(bytes)); } // MP4 / MOV
    if &bytes[0..3] == b"ID3" { return Some(probe_id3(bytes)); }
    if &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WAVE" { return Some(probe_wav(bytes)); }
    if &bytes[0..4] == b"GIF8" {
        return Some(MediaMeta {
            kind: Kind::Gif,
            width: Some(u16le(bytes, 6) as f64),
            height: Some(u16le(bytes, 8) as f64),
            ..Default::default()
        });
    }
    if bytes[0] == 0x1a && bytes[1] == 0x45 && bytes[2] == 0xdf && bytes[3] == 0xa3 {
        return Some(MediaMeta { kind: Kind::Webm, ..Default::default() }); // EBML magic
    }
    Some(MediaMeta { kind: Kind::Unknown, ..Default::default() })
}

// Usage:
//   let meta = media_metadata_inspector::probe(&std::fs::read("clip.mp4")?);
//   println!("{:?}", meta.map(|m| (m.kind, m.duration_sec, m.width, m.height)));

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 →