//! What is inside an audiobook file before any decoding: the container, its duration, its chapters, and whether it //! is DRM-protected. MP4 (M4B/M4A: a walk over the boxes), MP3 (the ID3v2 tag's `CHAP` frames) and `.cue` sheets. //! Every number read from a file is checked against the bytes actually there and against [`Caps`]; nothing is //! allocated from a size a file claims. There is no decrypt path: DRM is only detected. use crate::player::{Chapter, MAX_CHAPTERS, tidy}; pub const DRM_MESSAGE: &str = "This audiobook is DRM-protected, so Liber cannot play it."; #[derive(Clone, Copy, Debug)] pub struct Caps { pub max_boxes: usize, pub max_depth: usize, /// An ID3v2 tag larger than this is refused (cover art included). pub max_tag: usize, pub max_frames: usize, } impl Default for Caps { fn default() -> Self { Caps { max_boxes: 200_000, max_depth: 16, max_tag: 16 << 20, max_frames: 20_000 } } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum AudioError { Drm, /// Not an audio file Liber reads. Unsupported, /// Broken: truncated, inconsistent sizes, or over a cap. Damaged(&'static str), } impl AudioError { pub fn message(&self) -> String { match self { AudioError::Drm => DRM_MESSAGE.into(), AudioError::Unsupported => "Liber plays MP3, M4B, M4A and WAV audiobooks.".into(), AudioError::Damaged(why) => format!("This audio file is damaged ({why})."), } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { Mp4, Mp3, Wav, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Info { pub kind: Kind, pub title: Option, pub duration_ms: Option, pub chapters: Vec, /// A QuickTime chapter *track* whose titles live in the media data (outside the metadata given): each /// chapter's start and where its title sample is in the file. Read them with [`titles_from_samples`]. pub chapter_samples: Vec, } /// One sample of a QuickTime chapter track: a 16-bit big-endian length, then the UTF-8 title. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ChapterSample { pub start_ms: u64, pub offset: u64, pub size: u32, } /// The longest chapter title sample read. pub const MAX_TITLE_SAMPLE: u32 = 1024; /// Chapters from a chapter track's samples, reading each (small) sample through `read(offset, size)`. pub fn titles_from_samples( samples: &[ChapterSample], duration_ms: u64, mut read: impl FnMut(u64, u32) -> Option>, ) -> Vec { let chapters = samples .iter() .take(MAX_CHAPTERS) .map(|c| { let title = read(c.offset, c.size.min(MAX_TITLE_SAMPLE)) .and_then(|b| { let n = u16::from_be_bytes([*b.first()?, *b.get(1)?]) as usize; b.get(2..2 + n.min(b.len().saturating_sub(2))).map(|t| String::from_utf8_lossy(t).into_owned()) }) .unwrap_or_default(); Chapter { title, start_ms: c.start_ms, end_ms: 0 } }) .collect(); tidy(chapters, duration_ms).unwrap_or_default() } /// By content, never by the file name. pub fn sniff(head: &[u8]) -> Option { if head.len() >= 12 && &head[4..8] == b"ftyp" { return Some(Kind::Mp4); } if head.starts_with(b"ID3") || (head.len() >= 2 && head[0] == 0xFF && head[1] & 0xE0 == 0xE0) { return Some(Kind::Mp3); } if head.len() >= 12 && &head[..4] == b"RIFF" && &head[8..12] == b"WAVE" { return Some(Kind::Wav); } None } /// Reads the container's facts. `bytes` is the start of the file (MP4 metadata lives in `moov`, which may be at the /// end: pass the whole file, or at least the boxes up to `moov`). pub fn inspect(bytes: &[u8], caps: Caps) -> Result { match sniff(bytes).ok_or(AudioError::Unsupported)? { Kind::Mp4 => mp4(bytes, caps), Kind::Mp3 => mp3(bytes, caps), Kind::Wav => Ok(Info { kind: Kind::Wav, title: None, duration_ms: wav_duration(bytes), chapters: vec![], chapter_samples: vec![], }), } } fn be32(b: &[u8], at: usize) -> Option { b.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])) } fn be64(b: &[u8], at: usize) -> Option { b.get(at..at + 8).map(|s| u64::from_be_bytes(s.try_into().expect("8 bytes"))) } // ---------- MP4 ---------- struct Walk<'a> { caps: Caps, boxes: usize, drm: bool, timescale: Option, duration: Option, chapters: Vec, title: Option, tracks: Vec, _b: std::marker::PhantomData<&'a ()>, } /// What a `trak` says, kept as byte ranges of its sample tables (decoded only for the chapter track). #[derive(Default)] struct Track { id: u32, handler: [u8; 4], timescale: u32, chap: Vec, stts: Option<(usize, usize)>, stsz: Option<(usize, usize)>, stsc: Option<(usize, usize)>, stco: Option<(usize, usize, bool)>, } /// Most tracks a file may have. const MAX_TRACKS: usize = 64; const CONTAINERS: [&[u8; 4]; 9] = [b"moov", b"udta", b"tref", b"mdia", b"minf", b"stbl", b"ilst", b"edts", b"dinf"]; fn mp4(b: &[u8], caps: Caps) -> Result { // The brand: Audible's AAX is `aax `, AAXC `aaxc` (major or compatible). let ftyp_size = be32(b, 0).ok_or(AudioError::Damaged("no ftyp"))? as usize; if ftyp_size < 16 || ftyp_size > b.len().min(4096) { return Err(AudioError::Damaged("ftyp size")); } let drm_brand = |c: &[u8]| c == b"aax " || c == b"aaxc"; if drm_brand(&b[8..12]) || b[16..ftyp_size].as_chunks::<4>().0.iter().any(|c| drm_brand(c)) { return Err(AudioError::Drm); } let mut w = Walk { caps, boxes: 0, drm: false, timescale: None, duration: None, chapters: vec![], title: None, tracks: vec![], _b: Default::default(), }; walk(&mut w, b, 0, b.len(), 0)?; if w.drm { return Err(AudioError::Drm); } let duration_ms = match (w.timescale, w.duration) { (Some(ts), Some(d)) if ts > 0 => Some(d.saturating_mul(1000) / u64::from(ts)), _ => None, }; let mut chapters = duration_ms.and_then(|d| tidy(std::mem::take(&mut w.chapters), d)).unwrap_or_default(); // A QuickTime chapter track (what iTunes, LibriVox and most M4B tools write) when there is no Nero list. let mut chapter_samples = Vec::new(); if chapters.is_empty() { let referenced: Vec = w.tracks.iter().flat_map(|t| t.chap.iter().copied()).collect(); if let Some(t) = w.tracks.iter().find(|t| referenced.contains(&t.id) && (t.handler == *b"text" || t.handler == *b"sbtl")) { chapter_samples = chapter_track(b, t)?; // When the titles are inside the bytes we were given (a whole file), read them now. let d = duration_ms.unwrap_or(0); if d > 0 && chapter_samples.iter().all(|c| (c.offset as usize).saturating_add(c.size as usize) <= b.len()) { chapters = titles_from_samples(&chapter_samples, d, |o, n| { b.get(o as usize..o as usize + n as usize).map(<[u8]>::to_vec) }); chapter_samples.clear(); } } } Ok(Info { kind: Kind::Mp4, title: w.title, duration_ms, chapters, chapter_samples }) } /// A chapter track's samples: start times from `stts`, file offsets from `stsc` + `stco`/`co64` + `stsz`. fn chapter_track(b: &[u8], t: &Track) -> Result, AudioError> { let bad = AudioError::Damaged("chapter track"); let (Some(stts), Some(stsz), Some(stsc), Some(stco)) = (t.stts, t.stsz, t.stsc, t.stco) else { return Ok(vec![]) }; if t.timescale == 0 { return Err(bad); } let table = |(from, to): (usize, usize), entry: usize| -> Result<(usize, usize), AudioError> { let n = be32(b, from + 4).ok_or(AudioError::Damaged("chapter track"))? as usize; if n > MAX_CHAPTERS || from + 8 + n * entry > to { return Err(AudioError::Damaged("chapter track")); } Ok((from + 8, n)) }; // Times. let (at, n) = table(stts, 8)?; let mut starts = Vec::new(); let mut t_units = 0u64; for i in 0..n { let count = be32(b, at + i * 8).ok_or(AudioError::Damaged("stts"))?; let delta = be32(b, at + i * 8 + 4).ok_or(AudioError::Damaged("stts"))? as u64; for _ in 0..count { if starts.len() >= MAX_CHAPTERS { return Err(AudioError::Damaged("too many chapters")); } starts.push(t_units * 1000 / u64::from(t.timescale)); t_units = t_units.saturating_add(delta); } } // Sizes. let fixed = be32(b, stsz.0 + 4).ok_or(AudioError::Damaged("stsz"))?; let count = be32(b, stsz.0 + 8).ok_or(AudioError::Damaged("stsz"))? as usize; if count > MAX_CHAPTERS || (fixed == 0 && stsz.0 + 12 + count * 4 > stsz.1) { return Err(AudioError::Damaged("stsz")); } let size = |i: usize| if fixed != 0 { Some(fixed) } else { be32(b, stsz.0 + 12 + i * 4) }; // Chunk offsets. let (co_from, co_to, wide) = stco; let (co_at, chunks) = table((co_from, co_to), if wide { 8 } else { 4 })?; let chunk_offset = |k: usize| if wide { be64(b, co_at + k * 8) } else { be32(b, co_at + k * 4).map(u64::from) }; // Samples per chunk: (first_chunk (1-based), samples_per_chunk) runs. let (sc_at, runs) = table(stsc, 12)?; let mut out = Vec::new(); let mut sample = 0usize; for r in 0..runs { let first = be32(b, sc_at + r * 12).ok_or(AudioError::Damaged("stsc"))? as usize; let per = be32(b, sc_at + r * 12 + 4).ok_or(AudioError::Damaged("stsc"))? as usize; let next_first = if r + 1 < runs { be32(b, sc_at + (r + 1) * 12).ok_or(AudioError::Damaged("stsc"))? as usize } else { chunks + 1 }; if first == 0 || next_first < first || per > MAX_CHAPTERS { return Err(AudioError::Damaged("stsc")); } for chunk in first..next_first.min(chunks + 1) { let mut off = chunk_offset(chunk - 1).ok_or(AudioError::Damaged("stco"))?; for _ in 0..per { if sample >= count.min(starts.len()) { return Ok(out); } let sz = size(sample).ok_or(AudioError::Damaged("stsz"))?; out.push(ChapterSample { start_ms: starts[sample], offset: off, size: sz }); off = off.saturating_add(u64::from(sz)); sample += 1; } } } Ok(out) } fn walk(w: &mut Walk, b: &[u8], from: usize, to: usize, depth: usize) -> Result<(), AudioError> { if depth > w.caps.max_depth { return Err(AudioError::Damaged("boxes nested too deep")); } let mut at = from; while at + 8 <= to { w.boxes += 1; if w.boxes > w.caps.max_boxes { return Err(AudioError::Damaged("too many boxes")); } let size32 = be32(b, at).expect("8 bytes checked") as u64; let kind: [u8; 4] = b[at + 4..at + 8].try_into().expect("4 bytes"); let (header, size) = match size32 { 1 => (16u64, be64(b, at + 8).ok_or(AudioError::Damaged("box size"))?), 0 => (8, (to - at) as u64), s => (8, s), }; if size < header { return Err(AudioError::Damaged("box size")); } // A box may claim more than the bytes we have (mdat in a partial read): read only what is here. let end = (at as u64).saturating_add(size).min(to as u64) as usize; let body = at + header as usize; if body > end { return Err(AudioError::Damaged("box size")); } let cur = w.tracks.len().checked_sub(1); match &kind { b"trak" => { if w.tracks.len() >= MAX_TRACKS { return Err(AudioError::Damaged("too many tracks")); } w.tracks.push(Track::default()); walk(w, b, body, end, depth + 1)?; } b"tkhd" => { let v = *b.get(body).ok_or(AudioError::Damaged("tkhd"))?; if let (Some(i), Some(id)) = (cur, be32(b, body + if v == 1 { 20 } else { 12 })) { w.tracks[i].id = id; } } b"chap" => { if let Some(i) = cur { w.tracks[i].chap = b[body..end] .chunks(4) .take(16) .filter_map(|c| c.try_into().ok().map(u32::from_be_bytes)) .collect(); } } b"hdlr" => { if let (Some(i), Some(h)) = (cur, b.get(body + 8..body + 12)) { w.tracks[i].handler = h.try_into().expect("4 bytes"); } } b"mdhd" => { let v = *b.get(body).ok_or(AudioError::Damaged("mdhd"))?; if let (Some(i), Some(ts)) = (cur, be32(b, body + if v == 1 { 20 } else { 12 })) { w.tracks[i].timescale = ts; } } b"stts" | b"stsz" | b"stsc" | b"stco" | b"co64" => { if let Some(i) = cur { let t = &mut w.tracks[i]; match &kind { b"stts" => t.stts = Some((body, end)), b"stsz" => t.stsz = Some((body, end)), b"stsc" => t.stsc = Some((body, end)), b"stco" => t.stco = Some((body, end, false)), _ => t.stco = Some((body, end, true)), } } } // Audible (`adrm`, `aabd`, the `aavd` sample entry), old iTunes FairPlay (`drms`, `drmi`). b"adrm" | b"aabd" | b"aavd" | b"drms" | b"drmi" => w.drm = true, k if CONTAINERS.contains(&k) => walk(w, b, body, end, depth + 1)?, b"meta" => walk(w, b, (body + 4).min(end), end, depth + 1)?, b"stsd" => { // FullBox + entry count, then sample entries: an encrypted entry means DRM. walk(w, b, (body + 8).min(end), end, depth + 1)?; } b"mp4a" | b"enca" => { if &kind == b"enca" { w.drm = true; } // An audio sample entry: 28 bytes of fields, then child boxes (esds, sinf …). walk(w, b, (body + 28).min(end), end, depth + 1)?; } b"sinf" | b"schi" => walk(w, b, body, end, depth + 1)?, b"mvhd" => { let version = *b.get(body).ok_or(AudioError::Damaged("mvhd"))?; let (ts, d) = if version == 1 { (be32(b, body + 20), be64(b, body + 24)) } else { (be32(b, body + 12), be32(b, body + 16).map(u64::from)) }; w.timescale = ts; w.duration = d; } b"chpl" => chpl(w, &b[body..end])?, b"\xa9nam" => { // ilst item: a `data` box with 8 bytes of type and locale before the text. if let Some(t) = b.get(body + 16..end).and_then(|t| std::str::from_utf8(t).ok()) { w.title = Some(t.chars().take(300).collect()); } } _ => {} } if end <= at { break; } at = end; } Ok(()) } /// Nero chapters: FullBox, (version 1: 4 reserved bytes), a count, then per chapter a start in 100 ns units and a /// length-prefixed UTF-8 title. fn chpl(w: &mut Walk, b: &[u8]) -> Result<(), AudioError> { let version = *b.first().ok_or(AudioError::Damaged("chpl"))?; let mut at = if version == 1 { 8 } else { 4 }; let count = *b.get(at).ok_or(AudioError::Damaged("chpl"))? as usize; at += 1; for _ in 0..count { let start = be64(b, at).ok_or(AudioError::Damaged("chpl truncated"))?; let len = *b.get(at + 8).ok_or(AudioError::Damaged("chpl truncated"))? as usize; let title = b.get(at + 9..at + 9 + len).ok_or(AudioError::Damaged("chpl truncated"))?; at += 9 + len; if w.chapters.len() >= MAX_CHAPTERS { return Err(AudioError::Damaged("too many chapters")); } w.chapters.push(Chapter { title: String::from_utf8_lossy(title).into_owned(), start_ms: start / 10_000, end_ms: 0, }); } Ok(()) } // ---------- MP3 (ID3v2) ---------- fn synchsafe(b: &[u8]) -> usize { b.iter().fold(0usize, |acc, &x| (acc << 7) | (x & 0x7F) as usize) } fn mp3(b: &[u8], caps: Caps) -> Result { let mut info = Info { kind: Kind::Mp3, title: None, duration_ms: None, chapters: vec![], chapter_samples: vec![] }; if !b.starts_with(b"ID3") { return Ok(info); } if b.len() < 10 { return Err(AudioError::Damaged("ID3 header")); } let major = b[3]; let size = synchsafe(&b[6..10]); if size > caps.max_tag { return Err(AudioError::Damaged("metadata block too large")); } let end = (10 + size).min(b.len()); let mut at = 10; let mut frames = 0; let mut chapters = Vec::new(); while at + 10 <= end { let id = &b[at..at + 4]; if id[0] == 0 { break; // padding } frames += 1; if frames > caps.max_frames { return Err(AudioError::Damaged("too many metadata frames")); } let fsize = if major >= 4 { synchsafe(&b[at + 4..at + 8]) } else { be32(b, at + 4).unwrap_or(0) as usize }; let body = at + 10; let fend = body.checked_add(fsize).filter(|&e| e <= end).ok_or(AudioError::Damaged("ID3 frame size"))?; match id { b"TIT2" => info.title = text_frame(&b[body..fend]), b"CHAP" => { let f = &b[body..fend]; let z = f.iter().position(|&c| c == 0).ok_or(AudioError::Damaged("CHAP"))?; let start = be32(f, z + 1).ok_or(AudioError::Damaged("CHAP"))? as u64; let stop = be32(f, z + 5).ok_or(AudioError::Damaged("CHAP"))? as u64; // Embedded frames: the chapter's TIT2. let mut title = None; let mut s = z + 17; while s + 10 <= f.len() { let sid = &f[s..s + 4]; let ssize = if major >= 4 { synchsafe(&f[s + 4..s + 8]) } else { be32(f, s + 4).unwrap_or(0) as usize }; let Some(se) = (s + 10).checked_add(ssize).filter(|&e| e <= f.len()) else { break }; if sid == b"TIT2" { title = text_frame(&f[s + 10..se]); } s = se; } if chapters.len() >= MAX_CHAPTERS { return Err(AudioError::Damaged("too many chapters")); } chapters.push(Chapter { title: title.unwrap_or_default(), start_ms: start, end_ms: stop }); } _ => {} } at = fend; } if !chapters.is_empty() { let last = chapters.iter().map(|c| c.end_ms).max().unwrap_or(0); info.duration_ms = Some(last); info.chapters = tidy(chapters, last.max(1)).unwrap_or_default(); } Ok(info) } /// An ID3 text frame: an encoding byte, then ISO-8859-1, UTF-16 (with BOM), UTF-16BE or UTF-8. fn text_frame(f: &[u8]) -> Option { let (&enc, rest) = f.split_first()?; let s = match enc { 0 => rest.iter().map(|&c| c as char).collect::(), 1 | 2 => { let (le, body) = match rest { [0xFF, 0xFE, r @ ..] => (true, r), [0xFE, 0xFF, r @ ..] => (false, r), r => (enc == 1, r), }; let units: Vec = body .as_chunks::<2>() .0 .iter() .map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) }) .collect(); String::from_utf16_lossy(&units) } 3 => String::from_utf8_lossy(rest).into_owned(), _ => return None, }; let s = s.trim_matches(char::from(0)).trim().chars().take(300).collect::(); (!s.is_empty()).then_some(s) } fn wav_duration(b: &[u8]) -> Option { // fmt at 12 in the common layout; data size from the `data` chunk. let mut at = 12; let (mut rate, mut block) = (0u32, 0u16); while at + 8 <= b.len() { let id = &b[at..at + 4]; let size = u32::from_le_bytes(b[at + 4..at + 8].try_into().ok()?) as usize; if id == b"fmt " && at + 24 <= b.len() { rate = u32::from_le_bytes(b[at + 12..at + 16].try_into().ok()?); block = u16::from_le_bytes(b[at + 20..at + 22].try_into().ok()?); } if id == b"data" { if rate == 0 || block == 0 { return None; } return Some(size as u64 * 1000 / (u64::from(rate) * u64::from(block))); } at = at.checked_add(8 + size + (size & 1))?; } None } // ---------- .cue ---------- /// A cue sheet's tracks as chapters (one audio file; `INDEX 01 mm:ss:ff`, 75 frames a second). pub fn cue(text: &str, duration_ms: u64) -> Option> { let mut out = Vec::new(); let mut title = String::new(); for line in text.lines().take(100_000) { let l = line.trim(); if let Some(t) = l.strip_prefix("TITLE ") { title = t.trim().trim_matches('"').to_owned(); } else if let Some(i) = l.strip_prefix("INDEX 01 ") { let p: Vec = i.trim().split(':').filter_map(|x| x.parse().ok()).collect(); if let [m, s, f] = p[..] { if out.len() >= MAX_CHAPTERS { return None; } out.push(Chapter { title: std::mem::take(&mut title), start_ms: m * 60_000 + s * 1_000 + f * 1_000 / 75, end_ms: 0, }); } } } tidy(out, duration_ms) }