378 lines
14 KiB
Rust
378 lines
14 KiB
Rust
//! 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<String>,
|
|
pub duration_ms: Option<u64>,
|
|
pub chapters: Vec<Chapter>,
|
|
}
|
|
|
|
/// By content, never by the file name.
|
|
pub fn sniff(head: &[u8]) -> Option<Kind> {
|
|
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<Info, AudioError> {
|
|
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![] }),
|
|
}
|
|
}
|
|
|
|
fn be32(b: &[u8], at: usize) -> Option<u32> {
|
|
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<u64> {
|
|
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<u32>,
|
|
duration: Option<u64>,
|
|
chapters: Vec<Chapter>,
|
|
title: Option<String>,
|
|
_b: std::marker::PhantomData<&'a ()>,
|
|
}
|
|
|
|
const CONTAINERS: [&[u8; 4]; 9] = [b"moov", b"udta", b"trak", b"mdia", b"minf", b"stbl", b"ilst", b"edts", b"dinf"];
|
|
|
|
fn mp4(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
|
// 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,
|
|
_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 chapters = duration_ms.and_then(|d| tidy(std::mem::take(&mut w.chapters), d)).unwrap_or_default();
|
|
Ok(Info { kind: Kind::Mp4, title: w.title, duration_ms, chapters })
|
|
}
|
|
|
|
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"));
|
|
}
|
|
match &kind {
|
|
// 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<Info, AudioError> {
|
|
let mut info = Info { kind: Kind::Mp3, title: None, duration_ms: None, chapters: 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<String> {
|
|
let (&enc, rest) = f.split_first()?;
|
|
let s = match enc {
|
|
0 => rest.iter().map(|&c| c as char).collect::<String>(),
|
|
1 | 2 => {
|
|
let (le, body) = match rest {
|
|
[0xFF, 0xFE, r @ ..] => (true, r),
|
|
[0xFE, 0xFF, r @ ..] => (false, r),
|
|
r => (enc == 1, r),
|
|
};
|
|
let units: Vec<u16> = 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::<String>();
|
|
(!s.is_empty()).then_some(s)
|
|
}
|
|
|
|
fn wav_duration(b: &[u8]) -> Option<u64> {
|
|
// 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<Vec<Chapter>> {
|
|
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<u64> = 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)
|
|
}
|