Skip to content

Visual Studio Code, rebuilt in Rust

Rust
21.8 KB
Raw Blame
//! mediaCodecs.ts: the container and the track codecs of an MP4, WebM, Ogg or WAV file, read from the parts of the file
//! that describe them. Browsers drop audio tracks they cannot decode without saying so; the player page warns with these.

use std::collections::HashMap;

const CHUNK_SIZE: u64 = 64 * 1024;
/// Bounds the bytes read to find the codecs.
const MAX_CHUNKS: usize = 32;
/// Bounds the structures visited on each level of a file.
const MAX_ENTRIES: usize = 64;

#[derive(Debug, PartialEq)]
pub struct MediaInfo {
    pub container: &'static str,
    /// Video tracks are read from WebM files only, which play through Media Source Extensions with every codec named.
    pub tracks: Vec<Track>,
}

#[derive(Debug, PartialEq)]
pub struct Track {
    pub kind: &'static str,
    /// The `codecs` parameter of a MIME type, `mp4a.40.2`.
    pub codec: String,
    pub name: Option<&'static str>,
}

/// The read limit was reached or a range could not be read.
struct Unreadable;

/// `readMediaInfo`: None when the file cannot be read or is no supported container. `read_range` reads `length`
/// bytes at `position`, never past `size`.
pub fn read_media_info(size: u64, read_range: impl FnMut(u64, u64) -> std::io::Result<Vec<u8>>) -> Option<MediaInfo> {
    let mut reader = Reader { size, read_range, chunks: HashMap::new() };
    let header = reader.read(0, 12).ok()?;
    if header.len() < 12 {
        return None;
    }
    let (container, tracks) = if ISO_BASE_MEDIA_BOX_TYPES.contains(&ascii(&header, 4, 8).as_str()) {
        ("mp4", read_mp4_tracks(&mut reader))
    } else if u32::from_be_bytes([header[0], header[1], header[2], header[3]]) == EBML_HEADER_ID {
        ("webm", read_webm_tracks(&mut reader))
    } else if ascii(&header, 0, 4) == "OggS" {
        ("ogg", read_ogg_tracks(&mut reader))
    } else if ascii(&header, 0, 4) == "RIFF" && ascii(&header, 8, 12) == "WAVE" {
        ("wav", read_wav_tracks(&mut reader))
    } else {
        return None;
    };
    Some(MediaInfo { container, tracks: tracks.ok()? })
}

/// `readMediaInfo` of a local file, read in ranges.
pub fn read_file_media_info(path: &std::path::Path) -> Option<MediaInfo> {
    use std::io::{Read, Seek, SeekFrom};
    let mut file = std::fs::File::open(path).ok()?;
    let size = file.metadata().ok()?.len();
    read_media_info(size, |position, length| {
        let mut bytes = Vec::new();
        file.seek(SeekFrom::Start(position))?;
        (&mut file).take(length).read_to_end(&mut bytes)?;
        Ok(bytes)
    })
}

/// `ChunkedReader`: the file in cached chunks, so many small structures do not read the same part again.
struct Reader<F> {
    size: u64,
    read_range: F,
    chunks: HashMap<u64, Vec<u8>>,
}

impl<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>> Reader<F> {
    /// `length` bytes, or fewer at the end of the file.
    fn read(&mut self, position: u64, length: u64) -> Result<Vec<u8>, Unreadable> {
        let mut bytes = Vec::new();
        let end = position.saturating_add(length).min(self.size);
        let mut offset = position;
        while offset < end {
            let index = offset / CHUNK_SIZE;
            let chunk = self.chunk(index)?;
            let start = (offset - index * CHUNK_SIZE) as usize;
            let part = chunk.get(start..((end - index * CHUNK_SIZE) as usize).min(chunk.len())).unwrap_or_default();
            // The file may have become shorter since its size was read.
            if part.is_empty() {
                break;
            }
            bytes.extend_from_slice(part);
            offset += part.len() as u64;
        }
        Ok(bytes)
    }

    fn chunk(&mut self, index: u64) -> Result<&Vec<u8>, Unreadable> {
        if !self.chunks.contains_key(&index) {
            if self.chunks.len() >= MAX_CHUNKS {
                return Err(Unreadable);
            }
            let start = index * CHUNK_SIZE;
            let chunk = (self.read_range)(start, CHUNK_SIZE.min(self.size - start)).map_err(|_| Unreadable)?;
            self.chunks.insert(index, chunk);
        }
        Ok(&self.chunks[&index])
    }
}

fn ascii(bytes: &[u8], start: usize, end: usize) -> String {
    bytes.get(start.min(bytes.len())..end.min(bytes.len())).unwrap_or_default().iter().map(|&byte| byte as char).collect()
}

const ISO_BASE_MEDIA_BOX_TYPES: [&str; 6] = ["ftyp", "moov", "mdat", "free", "skip", "wide"];

#[derive(Clone, Copy)]
struct Mp4Box {
    kind: [u8; 4],
    content_start: u64,
    end: u64,
}

/// `readBoxes`: the boxes between `start` and `end`, one `next` at a time.
struct Boxes {
    position: u64,
    end: u64,
    count: usize,
}

impl Boxes {
    fn new(start: u64, end: u64) -> Self {
        Boxes { position: start, end, count: 0 }
    }

    fn next<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(&mut self, reader: &mut Reader<F>) -> Result<Option<Mp4Box>, Unreadable> {
        if self.count >= MAX_ENTRIES || self.position.saturating_add(8) > self.end {
            return Ok(None);
        }
        self.count += 1;
        let header = reader.read(self.position, 16)?;
        if header.len() < 8 {
            self.count = MAX_ENTRIES;
            return Ok(None);
        }
        let kind = [header[4], header[5], header[6], header[7]];
        let mut size = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as u64;
        let mut content_start = self.position + 8;
        if size == 1 {
            if header.len() < 16 {
                self.count = MAX_ENTRIES;
                return Ok(None);
            }
            size = u64::from_be_bytes(header[8..16].try_into().expect("8 bytes"));
            content_start += 8;
        } else if size == 0 {
            // The box extends to the end of the file.
            self.count = MAX_ENTRIES;
            return Ok(Some(Mp4Box { kind, content_start, end: self.end }));
        }
        if self.position.saturating_add(size) < content_start {
            self.count = MAX_ENTRIES;
            return Ok(None);
        }
        let found = Mp4Box { kind, content_start, end: self.position.saturating_add(size).min(self.end) };
        self.position = self.position.saturating_add(size);
        Ok(Some(found))
    }
}

fn find_box<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>, start: u64, end: u64, path: &[&str]) -> Result<Option<Mp4Box>, Unreadable> {
    let (mut start, mut end) = (start, end);
    let mut found = None;
    for kind in path {
        found = None;
        let mut boxes = Boxes::new(start, end);
        while let Some(child) = boxes.next(reader)? {
            if child.kind == kind.as_bytes() {
                found = Some(child);
                break;
            }
        }
        let Some(parent) = found else { return Ok(None) };
        (start, end) = (parent.content_start, parent.end);
    }
    Ok(found)
}

const MP4_AUDIO_SAMPLE_ENTRIES: [(&str, &str, &str); 15] = [
    ("Opus", "opus", "Opus"),
    ("fLaC", "flac", "FLAC"),
    ("ac-3", "ac-3", "AC-3"),
    ("ec-3", "ec-3", "E-AC-3"),
    ("ac-4", "ac-4", "AC-4"),
    ("alac", "alac", "ALAC"),
    ("samr", "samr", "AMR"),
    ("sawb", "sawb", "AMR-WB"),
    ("dtsc", "dtsc", "DTS"),
    ("dtse", "dtse", "DTS"),
    ("dtsh", "dtsh", "DTS"),
    ("dtsl", "dtsl", "DTS"),
    ("dtsx", "dtsx", "DTS"),
    ("mha1", "mha1", "MPEG-H 3D Audio"),
    ("mhm1", "mhm1", "MPEG-H 3D Audio"),
];

/// The object types of an MPEG-4 elementary stream descriptor other than MPEG-4 Audio.
fn mp4_audio_object_type_name(object_type: u8) -> Option<&'static str> {
    match object_type {
        0x66..=0x68 => Some("AAC"),
        0x69 | 0x6B => Some("MP3"),
        0xA5 => Some("AC-3"),
        0xA6 => Some("E-AC-3"),
        0xA9..=0xAC => Some("DTS"),
        _ => None,
    }
}

const MPEG4_AUDIO_OBJECT_TYPE: u8 = 0x40;

/// The audio object types of MPEG-4 Audio; others, such as lossless ALS, have no name.
fn mpeg4_audio_object_type_name(audio_object_type: u32) -> Option<&'static str> {
    match audio_object_type {
        1..=6 | 17 | 19 | 20 | 23 | 29 | 39 => Some("AAC"),
        32 | 33 => Some("MPEG Audio"),
        34 => Some("MP3"),
        _ => None,
    }
}

fn read_mp4_tracks<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>) -> Result<Vec<Track>, Unreadable> {
    let Some(moov) = find_box(reader, 0, u64::MAX, &["moov"])? else { return Ok(Vec::new()) };
    let mut tracks = Vec::new();
    let mut traks = Boxes::new(moov.content_start, moov.end);
    while let Some(trak) = traks.next(reader)? {
        if &trak.kind != b"trak" {
            continue;
        }
        let Some(mdia) = find_box(reader, trak.content_start, trak.end, &["mdia"])? else { continue };
        let Some(hdlr) = find_box(reader, mdia.content_start, mdia.end, &["hdlr"])? else { continue };
        // The handler type follows the version, flags and a reserved field.
        if ascii(&reader.read(hdlr.content_start + 8, 4)?, 0, 4) != "soun" {
            continue;
        }
        let Some(stsd) = find_box(reader, mdia.content_start, mdia.end, &["minf", "stbl", "stsd"])? else { continue };
        // The sample entries follow the version, flags and entry count.
        if let Some(entry) = Boxes::new(stsd.content_start + 8, stsd.end).next(reader)?
            && let Some(track) = read_mp4_audio_sample_entry(reader, entry)?
        {
            tracks.push(track);
        }
    }
    Ok(tracks)
}

fn read_mp4_audio_sample_entry<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>, entry: Mp4Box) -> Result<Option<Track>, Unreadable> {
    if let Some((_, codec, name)) = MP4_AUDIO_SAMPLE_ENTRIES.iter().find(|(kind, ..)| kind.as_bytes() == entry.kind) {
        return Ok(Some(Track { kind: "audio", codec: (*codec).into(), name: Some(name) }));
    }
    if &entry.kind != b"mp4a" {
        return Ok(None);
    }
    // The child boxes follow 28 bytes of audio sample entry fields. Versions 1 and 2 of the QuickTime sound sample
    // description add 16 and 36 bytes; version 1 of the ISO audio sample entry adds none.
    let fields = reader.read(entry.content_start, 28)?;
    if fields.len() < 28 {
        return Ok(None);
    }
    let extra_fields_size = match u16::from_be_bytes([fields[8], fields[9]]) {
        1 => 16,
        2 => 36,
        _ => 0,
    };
    let mut esds = None;
    let mut children_starts = vec![entry.content_start + 28 + extra_fields_size];
    if extra_fields_size != 0 {
        children_starts.push(entry.content_start + 28);
    }
    for children_start in children_starts {
        esds = match find_box(reader, children_start, entry.end, &["esds"])? {
            Some(found) => Some(found),
            None => find_box(reader, children_start, entry.end, &["wave", "esds"])?,
        };
        if esds.is_some() {
            break;
        }
    }
    let Some(esds) = esds else { return Ok(None) };
    let Some((object_type, audio_object_type)) = parse_esds(&reader.read(esds.content_start, esds.end.saturating_sub(esds.content_start).min(256))?) else { return Ok(None) };
    if object_type == MPEG4_AUDIO_OBJECT_TYPE {
        return Ok(Some(match audio_object_type {
            None => Track { kind: "audio", codec: "mp4a.40".into(), name: None },
            Some(audio_object_type) => Track { kind: "audio", codec: format!("mp4a.40.{audio_object_type}"), name: mpeg4_audio_object_type_name(audio_object_type) },
        }));
    }
    Ok(mp4_audio_object_type_name(object_type).map(|name| Track { kind: "audio", codec: format!("mp4a.{object_type:X}"), name: Some(name) }))
}

/// `parseEsds`: the object type of an elementary stream descriptor and, for MPEG-4 Audio, the audio object type of
/// its decoder specific info.
fn parse_esds(bytes: &[u8]) -> Option<(u8, Option<u32>)> {
    let byte = |offset: usize| bytes.get(offset).copied().unwrap_or(0);
    // Past the version and flags.
    let mut offset = 4;
    let read_descriptor = |offset: &mut usize, tag: u8| -> Option<u32> {
        if bytes.get(*offset) != Some(&tag) {
            return None;
        }
        *offset += 1;
        let mut size = 0;
        for _ in 0..4 {
            let Some(&next) = bytes.get(*offset) else { break };
            *offset += 1;
            size = (size << 7) | (next & 0x7F) as u32;
            if next & 0x80 == 0 {
                break;
            }
        }
        Some(size)
    };
    // ES_Descriptor
    read_descriptor(&mut offset, 0x03)?;
    let flags = byte(offset + 2);
    offset += 3;
    if flags & 0x80 != 0 {
        offset += 2;
    }
    if flags & 0x40 != 0 {
        offset += 1 + byte(offset) as usize;
    }
    if flags & 0x20 != 0 {
        offset += 2;
    }
    // DecoderConfigDescriptor
    read_descriptor(&mut offset, 0x04)?;
    if offset >= bytes.len() {
        return None;
    }
    let object_type = bytes[offset];
    offset += 13;
    // DecoderSpecificInfo, which starts with the AudioSpecificConfig for MPEG-4 Audio.
    let mut audio_object_type = None;
    if object_type == MPEG4_AUDIO_OBJECT_TYPE && read_descriptor(&mut offset, 0x05).is_some() && offset < bytes.len() {
        let mut value = (bytes[offset] >> 3) as u32;
        if value == 31 && offset + 1 < bytes.len() {
            value = 32 + ((((bytes[offset] & 0x07) << 3) | (bytes[offset + 1] >> 5)) as u32);
        }
        audio_object_type = Some(value);
    }
    Some((object_type, audio_object_type))
}

const EBML_HEADER_ID: u32 = 0x1A45DFA3;
const SEGMENT_ID: u64 = 0x18538067;
const TRACKS_ID: u64 = 0x1654AE6B;
const CLUSTER_ID: u64 = 0x1F43B675;
const TRACK_ENTRY_ID: u64 = 0xAE;
const TRACK_TYPE_ID: u64 = 0x83;
const CODEC_ID_ID: u64 = 0x86;

/// `webmCodecs`: codec id, kind, codec and name.
const WEBM_CODECS: [(&str, &str, &str, &str); 13] = [
    ("V_VP8", "video", "vp8", "VP8"),
    ("V_VP9", "video", "vp9", "VP9"),
    // Media Source Extensions need a profile, level and bit depth for AV1: main profile, level 4.0, 8 bits.
    ("V_AV1", "video", "av01.0.08M.08", "AV1"),
    ("A_OPUS", "audio", "opus", "Opus"),
    ("A_VORBIS", "audio", "vorbis", "Vorbis"),
    ("A_FLAC", "audio", "flac", "FLAC"),
    ("A_AAC", "audio", "mp4a.40.2", "AAC"),
    ("A_MPEG/L3", "audio", "mp3", "MP3"),
    ("A_AC3", "audio", "ac-3", "AC-3"),
    ("A_EAC3", "audio", "ec-3", "E-AC-3"),
    ("A_DTS", "audio", "dtsc", "DTS"),
    ("A_TRUEHD", "audio", "mlpa", "Dolby TrueHD"),
    ("A_ALAC", "audio", "alac", "ALAC"),
];

#[derive(Clone, Copy)]
struct EbmlElement {
    id: u64,
    content_start: u64,
    end: u64,
}

/// `readVint`: ids keep their length marker; sizes do not, and all ones is an unknown size (`u64::MAX`).
fn read_vint(bytes: &[u8], offset: usize, is_id: bool) -> Option<(u64, usize)> {
    let first = *bytes.get(offset)?;
    let length = first.leading_zeros() as usize + 1;
    if length > 8 || offset + length > bytes.len() {
        return None;
    }
    let marker = 0x80u8 >> (length - 1);
    let mut value = if is_id { first as u64 } else { (first & (marker.wrapping_sub(1))) as u64 };
    let mut all_ones = value == marker.wrapping_sub(1) as u64;
    for &byte in &bytes[offset + 1..offset + length] {
        value = value * 256 + byte as u64;
        all_ones &= byte == 0xFF;
    }
    Some((if !is_id && all_ones { u64::MAX } else { value }, length))
}

/// `readEbmlElements`, one `next` at a time.
struct EbmlElements {
    position: u64,
    end: u64,
    count: usize,
}

impl EbmlElements {
    fn new(start: u64, end: u64) -> Self {
        EbmlElements { position: start, end, count: 0 }
    }

    fn next<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(&mut self, reader: &mut Reader<F>) -> Result<Option<EbmlElement>, Unreadable> {
        if self.count >= MAX_ENTRIES || self.position >= self.end {
            return Ok(None);
        }
        self.count += 1;
        let header = reader.read(self.position, 12)?;
        let Some((id, id_length)) = read_vint(&header, 0, true) else { return Ok(None) };
        let Some((size, size_length)) = read_vint(&header, id_length, false) else { return Ok(None) };
        let content_start = self.position + (id_length + size_length) as u64;
        let end = content_start.saturating_add(size).min(self.end);
        self.position = end;
        Ok(Some(EbmlElement { id, content_start, end }))
    }
}

fn read_webm_tracks<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>) -> Result<Vec<Track>, Unreadable> {
    let mut segment = None;
    let mut top = EbmlElements::new(0, u64::MAX);
    while let Some(element) = top.next(reader)? {
        if element.id == SEGMENT_ID {
            segment = Some(element);
            break;
        }
    }
    let Some(segment) = segment else { return Ok(Vec::new()) };
    let mut tracks_element = None;
    let mut children = EbmlElements::new(segment.content_start, segment.end);
    while let Some(element) = children.next(reader)? {
        if element.id == TRACKS_ID {
            tracks_element = Some(element);
            break;
        }
        // The tracks are described before the first cluster of media data.
        if element.id == CLUSTER_ID {
            break;
        }
    }
    let Some(tracks_element) = tracks_element else { return Ok(Vec::new()) };
    let mut tracks = Vec::new();
    let mut entries = EbmlElements::new(tracks_element.content_start, tracks_element.end);
    while let Some(entry) = entries.next(reader)? {
        if entry.id != TRACK_ENTRY_ID {
            continue;
        }
        let (mut track_type, mut codec_id) = (None, None);
        let mut fields = EbmlElements::new(entry.content_start, entry.end);
        while let Some(element) = fields.next(reader)? {
            if element.id == TRACK_TYPE_ID {
                let value = reader.read(element.content_start, element.end.saturating_sub(element.content_start).min(8))?;
                track_type = Some(value.iter().fold(0u64, |result, &byte| result * 256 + byte as u64));
            } else if element.id == CODEC_ID_ID {
                let value = reader.read(element.content_start, element.end.saturating_sub(element.content_start).min(64))?;
                codec_id = Some(ascii(&value, 0, value.len()).trim_end_matches('\0').to_owned());
            }
        }
        let kind = match track_type {
            Some(1) => "video",
            Some(2) => "audio",
            _ => continue,
        };
        // Codec ids such as `A_AAC/MPEG4/LC` name the profile after the codec.
        let Some(codec_id) = codec_id.map(|id| if id.starts_with("A_AAC/") { "A_AAC".to_owned() } else { id }) else { continue };
        if let Some(&(_, codec_kind, codec, name)) = WEBM_CODECS.iter().find(|(id, ..)| *id == codec_id)
            && codec_kind == kind
        {
            tracks.push(Track { kind, codec: codec.into(), name: Some(name) });
        }
    }
    Ok(tracks)
}

const OGG_BEGINNING_OF_STREAM: u8 = 0x02;

fn read_ogg_tracks<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>) -> Result<Vec<Track>, Unreadable> {
    let mut tracks = Vec::new();
    let mut position = 0;
    // Each logical stream starts with a page naming its codec, and these pages come before all others.
    for _ in 0..MAX_ENTRIES {
        let header = reader.read(position, 27)?;
        if header.len() < 27 || ascii(&header, 0, 4) != "OggS" || header[5] & OGG_BEGINNING_OF_STREAM == 0 {
            break;
        }
        let segment_count = header[26] as u64;
        let segments = reader.read(position + 27, segment_count)?;
        let data_start = position + 27 + segment_count;
        let signature = ascii(&reader.read(data_start, 8)?, 0, 8);
        let codec = match signature.as_str() {
            "OpusHead" => Some(("opus", "Opus")),
            "Speex   " => Some(("speex", "Speex")),
            signature if signature.starts_with("\x01vorbis") => Some(("vorbis", "Vorbis")),
            signature if signature.starts_with("\x7FFLAC") => Some(("flac", "FLAC")),
            _ => None,
        };
        if let Some((codec, name)) = codec {
            tracks.push(Track { kind: "audio", codec: codec.into(), name: Some(name) });
        }
        position = data_start + segments.iter().map(|&size| size as u64).sum::<u64>();
    }
    Ok(tracks)
}

const WAV_EXTENSIBLE_FORMAT: u16 = 0xFFFE;

/// Browsers decode these though `canPlayType` only knows PCM in WAV files: PCM, IEEE float, A-law, mu-law, MP3.
const DECODABLE_WAV_FORMATS: [u16; 5] = [0x0001, 0x0003, 0x0006, 0x0007, 0x0055];

fn wav_format_name(format: u16) -> Option<&'static str> {
    match format {
        0x0002 => Some("Microsoft ADPCM"),
        0x0011 => Some("IMA ADPCM"),
        0x0031 => Some("GSM 6.10"),
        0x0050 => Some("MPEG Audio"),
        0x00FF | 0x1610 => Some("AAC"),
        0x0160..=0x0163 => Some("Windows Media Audio"),
        0x2000 => Some("AC-3"),
        0x2001 => Some("DTS"),
        _ => None,
    }
}

fn read_wav_tracks<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>) -> Result<Vec<Track>, Unreadable> {
    // Chunks follow the RIFF header and are padded to an even size.
    let mut position = 12;
    for _ in 0..MAX_ENTRIES {
        let header = reader.read(position, 8)?;
        if header.len() < 8 {
            return Ok(Vec::new());
        }
        let size = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as u64;
        if ascii(&header, 0, 4) == "fmt " {
            let format = reader.read(position + 8, size.min(26))?;
            if format.len() < 2 {
                return Ok(Vec::new());
            }
            let mut format_tag = u16::from_le_bytes([format[0], format[1]]);
            // The extensible format keeps the actual format at the start of its sub format GUID.
            if format_tag == WAV_EXTENSIBLE_FORMAT && format.len() >= 26 {
                format_tag = u16::from_le_bytes([format[24], format[25]]);
            }
            if DECODABLE_WAV_FORMATS.contains(&format_tag) {
                return Ok(Vec::new());
            }
            return Ok(vec![Track { kind: "audio", codec: format_tag.to_string(), name: wav_format_name(format_tag) }]);
        }
        position += 8 + size + size % 2;
    }
    Ok(Vec::new())
}

#[cfg(test)]
mod tests;