Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 388e8e01c4 | |||
| 1d6693a195 | |||
| 7aa13d6c0a | |||
| 068dc6cfb7 | |||
| 31cf11cbbe | |||
| bb0a63a173 |
Generated
+5
-5
@@ -327,7 +327,7 @@ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-audio"
|
name = "liber-audio"
|
||||||
version = "0.4.0"
|
version = "0.4.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -337,7 +337,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-format"
|
name = "liber-format"
|
||||||
version = "0.4.0"
|
version = "0.4.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64",
|
||||||
"chardetng",
|
"chardetng",
|
||||||
@@ -357,7 +357,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-habit"
|
name = "liber-habit"
|
||||||
version = "0.4.0"
|
version = "0.4.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"liber-library",
|
"liber-library",
|
||||||
"proptest",
|
"proptest",
|
||||||
@@ -367,7 +367,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-lang"
|
name = "liber-lang"
|
||||||
version = "0.4.0"
|
version = "0.4.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proptest",
|
"proptest",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -379,7 +379,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-library"
|
name = "liber-library"
|
||||||
version = "0.4.0"
|
version = "0.4.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"csv",
|
"csv",
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
|||||||
members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit", "crates/liber-lang", "crates/liber-audio"]
|
members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit", "crates/liber-lang", "crates/liber-audio"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.4.0"
|
version = "0.4.3"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
|
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
|
||||||
|
|||||||
@@ -54,6 +54,42 @@ pub struct Info {
|
|||||||
pub title: Option<String>,
|
pub title: Option<String>,
|
||||||
pub duration_ms: Option<u64>,
|
pub duration_ms: Option<u64>,
|
||||||
pub chapters: Vec<Chapter>,
|
pub chapters: Vec<Chapter>,
|
||||||
|
/// 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<ChapterSample>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<u8>>,
|
||||||
|
) -> Vec<Chapter> {
|
||||||
|
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.
|
/// By content, never by the file name.
|
||||||
@@ -76,7 +112,13 @@ pub fn inspect(bytes: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
|||||||
match sniff(bytes).ok_or(AudioError::Unsupported)? {
|
match sniff(bytes).ok_or(AudioError::Unsupported)? {
|
||||||
Kind::Mp4 => mp4(bytes, caps),
|
Kind::Mp4 => mp4(bytes, caps),
|
||||||
Kind::Mp3 => mp3(bytes, caps),
|
Kind::Mp3 => mp3(bytes, caps),
|
||||||
Kind::Wav => Ok(Info { kind: Kind::Wav, title: None, duration_ms: wav_duration(bytes), chapters: vec![] }),
|
Kind::Wav => Ok(Info {
|
||||||
|
kind: Kind::Wav,
|
||||||
|
title: None,
|
||||||
|
duration_ms: wav_duration(bytes),
|
||||||
|
chapters: vec![],
|
||||||
|
chapter_samples: vec![],
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,10 +140,29 @@ struct Walk<'a> {
|
|||||||
duration: Option<u64>,
|
duration: Option<u64>,
|
||||||
chapters: Vec<Chapter>,
|
chapters: Vec<Chapter>,
|
||||||
title: Option<String>,
|
title: Option<String>,
|
||||||
|
tracks: Vec<Track>,
|
||||||
|
/// The `trak` being walked: track boxes elsewhere (the `hdlr` of `udta/meta`) belong to no track.
|
||||||
|
cur: Option<usize>,
|
||||||
_b: std::marker::PhantomData<&'a ()>,
|
_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"];
|
/// 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<u32>,
|
||||||
|
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<Info, AudioError> {
|
fn mp4(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
||||||
// The brand: Audible's AAX is `aax `, AAXC `aaxc` (major or compatible).
|
// The brand: Audible's AAX is `aax `, AAXC `aaxc` (major or compatible).
|
||||||
@@ -121,6 +182,8 @@ fn mp4(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
|||||||
duration: None,
|
duration: None,
|
||||||
chapters: vec![],
|
chapters: vec![],
|
||||||
title: None,
|
title: None,
|
||||||
|
tracks: vec![],
|
||||||
|
cur: None,
|
||||||
_b: Default::default(),
|
_b: Default::default(),
|
||||||
};
|
};
|
||||||
walk(&mut w, b, 0, b.len(), 0)?;
|
walk(&mut w, b, 0, b.len(), 0)?;
|
||||||
@@ -131,8 +194,97 @@ fn mp4(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
|||||||
(Some(ts), Some(d)) if ts > 0 => Some(d.saturating_mul(1000) / u64::from(ts)),
|
(Some(ts), Some(d)) if ts > 0 => Some(d.saturating_mul(1000) / u64::from(ts)),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
let chapters = duration_ms.and_then(|d| tidy(std::mem::take(&mut w.chapters), d)).unwrap_or_default();
|
let mut 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 })
|
// 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<u32> = 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<Vec<ChapterSample>, 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> {
|
fn walk(w: &mut Walk, b: &[u8], from: usize, to: usize, depth: usize) -> Result<(), AudioError> {
|
||||||
@@ -161,7 +313,55 @@ fn walk(w: &mut Walk, b: &[u8], from: usize, to: usize, depth: usize) -> Result<
|
|||||||
if body > end {
|
if body > end {
|
||||||
return Err(AudioError::Damaged("box size"));
|
return Err(AudioError::Damaged("box size"));
|
||||||
}
|
}
|
||||||
|
let cur = w.cur;
|
||||||
match &kind {
|
match &kind {
|
||||||
|
b"trak" => {
|
||||||
|
if w.tracks.len() >= MAX_TRACKS {
|
||||||
|
return Err(AudioError::Damaged("too many tracks"));
|
||||||
|
}
|
||||||
|
w.tracks.push(Track::default());
|
||||||
|
let outer = w.cur.replace(w.tracks.len() - 1);
|
||||||
|
walk(w, b, body, end, depth + 1)?;
|
||||||
|
w.cur = outer;
|
||||||
|
}
|
||||||
|
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`).
|
// 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,
|
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)?,
|
k if CONTAINERS.contains(&k) => walk(w, b, body, end, depth + 1)?,
|
||||||
@@ -236,7 +436,7 @@ fn synchsafe(b: &[u8]) -> usize {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn mp3(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
fn mp3(b: &[u8], caps: Caps) -> Result<Info, AudioError> {
|
||||||
let mut info = Info { kind: Kind::Mp3, title: None, duration_ms: None, chapters: vec![] };
|
let mut info = Info { kind: Kind::Mp3, title: None, duration_ms: None, chapters: vec![], chapter_samples: vec![] };
|
||||||
if !b.starts_with(b"ID3") {
|
if !b.starts_with(b"ID3") {
|
||||||
return Ok(info);
|
return Ok(info);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -247,3 +247,85 @@ fn cue_sheets() {
|
|||||||
assert_eq!(ch[1].start_ms, 12 * 60_000 + 30_000 + 37 * 1000 / 75);
|
assert_eq!(ch[1].start_ms, 12 * 60_000 + 30_000 + 37 * 1000 / 75);
|
||||||
assert!(cue("garbage", 1000).is_none());
|
assert!(cue("garbage", 1000).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An M4B whose chapters are a QuickTime chapter track: an audio track that refers (`tref`/`chap`) to a text track;
|
||||||
|
/// the text track's samples (a 16-bit length, then the title) sit in `mdat`.
|
||||||
|
fn m4b_with_chapter_track(titles: &[&str], starts_ms: &[u32]) -> Vec<u8> {
|
||||||
|
let full = |v: u8| vec![v, 0, 0, 0];
|
||||||
|
let tkhd = |id: u32| bx(b"tkhd", &[full(0), vec![0; 8], id.to_be_bytes().to_vec(), vec![0; 64]].concat());
|
||||||
|
let mdhd = bx(
|
||||||
|
b"mdhd",
|
||||||
|
&[full(0), vec![0; 8], 1000u32.to_be_bytes().to_vec(), 0u32.to_be_bytes().to_vec(), vec![0; 4]].concat(),
|
||||||
|
);
|
||||||
|
let hdlr = |h: &[u8; 4]| bx(b"hdlr", &[full(0), vec![0; 4], h.to_vec(), vec![0; 13]].concat());
|
||||||
|
// The text samples, laid out after ftyp + moov: we fix their offset after building moov once.
|
||||||
|
let samples: Vec<Vec<u8>> =
|
||||||
|
titles.iter().map(|t| [(t.len() as u16).to_be_bytes().to_vec(), t.as_bytes().to_vec()].concat()).collect();
|
||||||
|
let build = |mdat_at: u32| {
|
||||||
|
let mut stts = full(0);
|
||||||
|
stts.extend((starts_ms.len() as u32).to_be_bytes());
|
||||||
|
for (i, s) in starts_ms.iter().enumerate() {
|
||||||
|
let next = starts_ms.get(i + 1).copied().unwrap_or(s + 1000);
|
||||||
|
stts.extend(1u32.to_be_bytes());
|
||||||
|
stts.extend((next - s).to_be_bytes());
|
||||||
|
}
|
||||||
|
let mut stsz = full(0);
|
||||||
|
stsz.extend(0u32.to_be_bytes());
|
||||||
|
stsz.extend((samples.len() as u32).to_be_bytes());
|
||||||
|
for smp in &samples {
|
||||||
|
stsz.extend((smp.len() as u32).to_be_bytes());
|
||||||
|
}
|
||||||
|
let mut stsc = full(0);
|
||||||
|
stsc.extend(1u32.to_be_bytes());
|
||||||
|
stsc.extend([1u32, samples.len() as u32, 1].iter().flat_map(|x| x.to_be_bytes()));
|
||||||
|
let mut stco = full(0);
|
||||||
|
stco.extend(1u32.to_be_bytes());
|
||||||
|
stco.extend((mdat_at + 8).to_be_bytes());
|
||||||
|
let stbl =
|
||||||
|
bx(b"stbl", &[bx(b"stts", &stts), bx(b"stsz", &stsz), bx(b"stsc", &stsc), bx(b"stco", &stco)].concat());
|
||||||
|
let text =
|
||||||
|
bx(b"trak", &[tkhd(2), bx(b"mdia", &[mdhd.clone(), hdlr(b"text"), bx(b"minf", &stbl)].concat())].concat());
|
||||||
|
let audio = bx(
|
||||||
|
b"trak",
|
||||||
|
&[
|
||||||
|
tkhd(1),
|
||||||
|
bx(b"tref", &bx(b"chap", &2u32.to_be_bytes())),
|
||||||
|
bx(b"mdia", &[mdhd.clone(), hdlr(b"soun")].concat()),
|
||||||
|
]
|
||||||
|
.concat(),
|
||||||
|
);
|
||||||
|
let mut f = ftyp(b"M4B ");
|
||||||
|
// iTunes metadata after the tracks, with its own `hdlr` (`mdir`): it belongs to no track.
|
||||||
|
let udta = bx(b"udta", &bx(b"meta", &[full(0), hdlr(b"mdir")].concat()));
|
||||||
|
f.extend(bx(b"moov", &[mvhd(1000, 600_000), audio, text, udta].concat()));
|
||||||
|
f
|
||||||
|
};
|
||||||
|
let head_len = build(0).len() as u32;
|
||||||
|
let mut f = build(head_len);
|
||||||
|
f.extend(bx(b"mdat", &samples.concat()));
|
||||||
|
f
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn quicktime_chapter_tracks_are_read() {
|
||||||
|
let f = m4b_with_chapter_track(&["Part One", "Part Two", "Part Three"], &[0, 200_000, 400_000]);
|
||||||
|
let info = timed(|| inspect(&f, Caps::default())).expect("reads");
|
||||||
|
let titles: Vec<&str> = info.chapters.iter().map(|c| c.title.as_str()).collect();
|
||||||
|
assert_eq!(titles, ["Part One", "Part Two", "Part Three"]);
|
||||||
|
assert_eq!(info.chapters[1].start_ms, 200_000);
|
||||||
|
assert!(info.chapter_samples.is_empty(), "titles read from the bytes given");
|
||||||
|
// Given only the metadata (no mdat), the samples come back for the caller to read from the file.
|
||||||
|
let moov_end = f.len() - (8 + "Part One".len() + "Part Two".len() + "Part Three".len() + 6);
|
||||||
|
let meta = inspect(&f[..moov_end], Caps::default()).expect("reads");
|
||||||
|
assert!(meta.chapters.is_empty());
|
||||||
|
assert_eq!(meta.chapter_samples.len(), 3);
|
||||||
|
let chapters = liber_audio::container::titles_from_samples(&meta.chapter_samples, 600_000, |o, n| {
|
||||||
|
f.get(o as usize..(o + n as u64) as usize).map(<[u8]>::to_vec)
|
||||||
|
});
|
||||||
|
assert_eq!(chapters[2].title, "Part Three");
|
||||||
|
// A chapter track that lies about its sample count is refused.
|
||||||
|
let mut lying = f.clone();
|
||||||
|
let at = lying.windows(4).position(|w| w == b"stsz").unwrap() + 12;
|
||||||
|
lying[at..at + 4].copy_from_slice(&50_000u32.to_be_bytes());
|
||||||
|
assert!(matches!(timed(|| inspect(&lying, Caps::default())), Err(AudioError::Damaged(_))));
|
||||||
|
}
|
||||||
|
|||||||
@@ -180,6 +180,12 @@ pub enum Op {
|
|||||||
list: String,
|
list: String,
|
||||||
upto: u32,
|
upto: u32,
|
||||||
},
|
},
|
||||||
|
/// Day 4: where an audiobook file is, to the millisecond (the latest write wins, so any device resumes there).
|
||||||
|
AudioPosition {
|
||||||
|
book: String,
|
||||||
|
sha256: String,
|
||||||
|
ms: u64,
|
||||||
|
},
|
||||||
/// Day 3: a book file is an edition in another language (`None`: it is the book's own language again).
|
/// Day 3: a book file is an edition in another language (`None`: it is the book's own language again).
|
||||||
Edition {
|
Edition {
|
||||||
book: String,
|
book: String,
|
||||||
|
|||||||
@@ -129,6 +129,9 @@ pub fn ops_from(lib: &Library) -> Vec<Op> {
|
|||||||
if b.to_read {
|
if b.to_read {
|
||||||
ops.push(set(Field::ToRead, json!(true)));
|
ops.push(set(Field::ToRead, json!(true)));
|
||||||
}
|
}
|
||||||
|
if let Some((sha, ms)) = &b.audio_position {
|
||||||
|
ops.push(Op::AudioPosition { book: id.clone(), sha256: sha.clone(), ms: *ms });
|
||||||
|
}
|
||||||
if b.familiar {
|
if b.familiar {
|
||||||
ops.push(set(Field::Familiar, json!(true)));
|
ops.push(set(Field::Familiar, json!(true)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -212,6 +212,9 @@ pub struct Book {
|
|||||||
pub position: Option<Position>,
|
pub position: Option<Position>,
|
||||||
/// The most recent position, when it is behind the furthest: "Jump back to page X?".
|
/// The most recent position, when it is behind the furthest: "Jump back to page X?".
|
||||||
pub last_position: Option<Position>,
|
pub last_position: Option<Position>,
|
||||||
|
/// Day 4: the audiobook's place: (file sha256, milliseconds).
|
||||||
|
#[serde(default)]
|
||||||
|
pub audio_position: Option<(String, u64)>,
|
||||||
/// Day 3: read before in the reader's own language.
|
/// Day 3: read before in the reader's own language.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub familiar: bool,
|
pub familiar: bool,
|
||||||
@@ -242,6 +245,7 @@ impl Book {
|
|||||||
last_position: None,
|
last_position: None,
|
||||||
familiar: false,
|
familiar: false,
|
||||||
editions: BTreeMap::new(),
|
editions: BTreeMap::new(),
|
||||||
|
audio_position: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -773,6 +777,15 @@ impl Library {
|
|||||||
self.bands.insert(lang.clone(), Band { list: list.clone(), upto: (*upto).min(1_000_000) });
|
self.bands.insert(lang.clone(), Band { list: list.clone(), upto: (*upto).min(1_000_000) });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Op::AudioPosition { book, sha256, ms } => {
|
||||||
|
let ok =
|
||||||
|
sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit()) && *ms < 1_000 * 3_600 * 1_000;
|
||||||
|
if let Some(b) = self.book_mut(book)
|
||||||
|
&& ok
|
||||||
|
{
|
||||||
|
b.audio_position = Some((sha256.to_ascii_lowercase(), *ms));
|
||||||
|
}
|
||||||
|
}
|
||||||
Op::Edition { book, sha256, language } => {
|
Op::Edition { book, sha256, language } => {
|
||||||
let ok = sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit());
|
let ok = sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit());
|
||||||
if let Some(b) = self.book_mut(book)
|
if let Some(b) = self.book_mut(book)
|
||||||
|
|||||||
@@ -94,3 +94,23 @@ fn familiar_and_editions_on_a_book_and_through_an_export() {
|
|||||||
evs2.push(ev("7", "x", &mut c, 7, Op::Edition { book: "b".into(), sha256: sha, language: None }));
|
evs2.push(ev("7", "x", &mut c, 7, Op::Edition { book: "b".into(), sha256: sha, language: None }));
|
||||||
assert!(Library::from_events(&evs2).books["b"].editions.is_empty());
|
assert!(Library::from_events(&evs2).books["b"].editions.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_audiobook_position_is_the_latest_write_and_survives_an_export() {
|
||||||
|
let (mut pc, mut dc) = (Clock::default(), Clock::default());
|
||||||
|
let sha = "cd".repeat(32);
|
||||||
|
let pos = |ms: u64| Op::AudioPosition { book: "b".into(), sha256: sha.clone(), ms };
|
||||||
|
let evs = vec![
|
||||||
|
ev("0", "desk", &mut dc, 1, Op::BookAdd { book: "b".into(), info: info(1), restore: false }),
|
||||||
|
ev("1", "desk", &mut dc, 1_000, pos(61_000)),
|
||||||
|
ev("2", "phone", &mut pc, 2_000, pos(95_250)),
|
||||||
|
ev("3", "phone", &mut pc, 3_000, Op::AudioPosition { book: "b".into(), sha256: "nope".into(), ms: 5 }),
|
||||||
|
];
|
||||||
|
let mut rev = evs.clone();
|
||||||
|
rev.reverse();
|
||||||
|
let lib = Library::from_events(&evs);
|
||||||
|
assert_eq!(lib, Library::from_events(&rev));
|
||||||
|
assert_eq!(lib.books["b"].audio_position, Some((sha.clone(), 95_250)), "to the millisecond, the latest write");
|
||||||
|
let back = Library::from_events(&events_from(&lib, "restore", 10));
|
||||||
|
assert_eq!(back.books.values().next().and_then(|b| b.audio_position.clone()), Some((sha, 95_250)));
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user