[audio] Listening: liber-audio (WSOLA time-stretch, silence trimming, voice boost, chapters, queue, sleep timer, position saving, read-aloud timeline and cache key; MP4/ID3/cue containers with DRM refused; symphonia decoding behind caps)

This commit is contained in:
2026-11-17 21:24:57 +01:00
parent 42404e8a1d
commit 92cb0b7d84
17 changed files with 2013 additions and 11 deletions
+124
View File
@@ -0,0 +1,124 @@
//! Voice boost: a high-pass at 80 Hz (rumble), a presence bell at 2.5 kHz (+5 dB, where consonants live), a
//! compressor (−24 dBFS, 3:1, 5 ms attack, 80 ms release, +6 dB make-up) and a limiter that never lets a sample past
//! ±1. Biquads after Robert Bristow-Johnson's Audio EQ Cookbook.
#[derive(Clone, Copy, Debug, Default)]
struct Biquad {
b0: f32,
b1: f32,
b2: f32,
a1: f32,
a2: f32,
}
impl Biquad {
fn highpass(rate: f32, f: f32, q: f32) -> Biquad {
let w = 2.0 * std::f32::consts::PI * f / rate;
let (s, c) = w.sin_cos();
let alpha = s / (2.0 * q);
let a0 = 1.0 + alpha;
Biquad {
b0: (1.0 + c) / 2.0 / a0,
b1: -(1.0 + c) / a0,
b2: (1.0 + c) / 2.0 / a0,
a1: -2.0 * c / a0,
a2: (1.0 - alpha) / a0,
}
}
fn peaking(rate: f32, f: f32, q: f32, gain_db: f32) -> Biquad {
let a = 10f32.powf(gain_db / 40.0);
let w = 2.0 * std::f32::consts::PI * f / rate;
let (s, c) = w.sin_cos();
let alpha = s / (2.0 * q);
let a0 = 1.0 + alpha / a;
Biquad {
b0: (1.0 + alpha * a) / a0,
b1: -2.0 * c / a0,
b2: (1.0 - alpha * a) / a0,
a1: -2.0 * c / a0,
a2: (1.0 - alpha / a) / a0,
}
}
}
/// One biquad's state per channel (direct form I).
#[derive(Clone, Copy, Debug, Default)]
struct State {
x1: f32,
x2: f32,
y1: f32,
y2: f32,
}
impl State {
fn run(&mut self, f: &Biquad, x: f32) -> f32 {
let y = f.b0 * x + f.b1 * self.x1 + f.b2 * self.x2 - f.a1 * self.y1 - f.a2 * self.y2;
self.x2 = self.x1;
self.x1 = x;
self.y2 = self.y1;
self.y1 = y;
y
}
}
pub struct Boost {
channels: usize,
hp: Biquad,
bell: Biquad,
states: Vec<(State, State)>,
env: f32,
attack: f32,
release: f32,
pub enabled: bool,
}
const THRESHOLD_DB: f32 = -24.0;
const RATIO: f32 = 3.0;
const MAKEUP_DB: f32 = 6.0;
impl Boost {
pub fn new(rate: u32, channels: u16) -> Boost {
let r = rate.max(8_000) as f32;
let channels = channels.max(1) as usize;
Boost {
channels,
hp: Biquad::highpass(r, 80.0, std::f32::consts::FRAC_1_SQRT_2),
bell: Biquad::peaking(r, 2_500.0, 1.0, 5.0),
states: vec![(State::default(), State::default()); channels],
env: 0.0,
attack: (-1.0 / (0.005 * r)).exp(),
release: (-1.0 / (0.080 * r)).exp(),
enabled: true,
}
}
/// In place, interleaved.
pub fn process(&mut self, samples: &mut [f32]) {
if !self.enabled {
return;
}
let ch = self.channels;
let makeup = 10f32.powf(MAKEUP_DB / 20.0);
for frame in samples.chunks_mut(ch) {
let mut peak = 0.0f32;
for (c, x) in frame.iter_mut().enumerate() {
let (hp, bell) = &mut self.states[c];
let y = hp.run(&self.hp, *x);
*x = bell.run(&self.bell, y);
peak = peak.max(x.abs());
}
// Envelope follower on the frame's peak, then the gain the compressor applies.
let coef = if peak > self.env { self.attack } else { self.release };
self.env = coef * self.env + (1.0 - coef) * peak;
let level_db = 20.0 * self.env.max(1e-9).log10();
let over = (level_db - THRESHOLD_DB).max(0.0);
let gain = 10f32.powf(-(over - over / RATIO) / 20.0) * makeup;
for x in frame.iter_mut() {
// The limiter: a soft knee from 0.9, never past 1.
let y = *x * gain;
*x = if y.abs() <= 0.9 { y } else { y.signum() * (0.9 + 0.1 * ((y.abs() - 0.9) / 0.1).tanh()) };
}
}
}
}
+377
View File
@@ -0,0 +1,377 @@
//! 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)
}
+174
View File
@@ -0,0 +1,174 @@
//! Decoding through `symphonia` (MPL-2.0): MP3, AAC in MP4/M4A/M4B, WAV. The source is any `Read + Seek` the app
//! hands over (a file there, a byte buffer in tests); this crate opens nothing itself. Caps keep a hostile file from
//! running away: channels, sample rate, total decoded time, and consecutive decode errors.
use crate::container::AudioError;
use std::io::{Read, Seek};
use symphonia::core::audio::SampleBuffer;
use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
use symphonia::core::errors::Error as SymError;
use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo};
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
use symphonia::core::units::Time;
#[derive(Clone, Copy, Debug)]
pub struct DecodeCaps {
pub max_channels: u16,
pub max_rate: u32,
pub max_hours: u32,
/// Decode errors in a row before the stream counts as broken.
pub max_errors: u32,
}
impl Default for DecodeCaps {
fn default() -> Self {
DecodeCaps { max_channels: 8, max_rate: 192_000, max_hours: 200, max_errors: 50 }
}
}
/// A `Read + Seek` that symphonia can use (it wants `Send + Sync`).
pub trait Source: Read + Seek + Send + Sync {}
impl<T: Read + Seek + Send + Sync> Source for T {}
struct Seekable<S: Source>(S, Option<u64>);
impl<S: Source> Read for Seekable<S> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.0.read(buf)
}
}
impl<S: Source> Seek for Seekable<S> {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
self.0.seek(pos)
}
}
impl<S: Source> symphonia::core::io::MediaSource for Seekable<S> {
fn is_seekable(&self) -> bool {
true
}
fn byte_len(&self) -> Option<u64> {
self.1
}
}
pub struct Decoder {
format: Box<dyn FormatReader>,
decoder: Box<dyn symphonia::core::codecs::Decoder>,
track: u32,
pub rate: u32,
pub channels: u16,
caps: DecodeCaps,
decoded_frames: u64,
errors: u32,
}
fn err(e: SymError) -> AudioError {
match e {
SymError::Unsupported(_) => AudioError::Unsupported,
_ => AudioError::Damaged("the audio stream cannot be read"),
}
}
impl Decoder {
/// Opens a stream. `len` is the byte length when known; `ext` only a hint (content decides).
pub fn open<S: Source + 'static>(
source: S,
len: Option<u64>,
ext: Option<&str>,
caps: DecodeCaps,
) -> Result<Decoder, AudioError> {
let mss = MediaSourceStream::new(Box::new(Seekable(source, len)), Default::default());
let mut hint = Hint::new();
if let Some(e) = ext {
hint.with_extension(e);
}
let probed = symphonia::default::get_probe()
.format(
&hint,
mss,
&FormatOptions { enable_gapless: true, ..Default::default() },
&MetadataOptions::default(),
)
.map_err(err)?;
let format = probed.format;
let track =
format.tracks().iter().find(|t| t.codec_params.codec != CODEC_TYPE_NULL).ok_or(AudioError::Unsupported)?;
let params = track.codec_params.clone();
let rate = params.sample_rate.ok_or(AudioError::Damaged("no sample rate"))?;
let channels = params.channels.map(|c| c.count() as u16).unwrap_or(1);
if rate < 4_000 || rate > caps.max_rate || channels == 0 || channels > caps.max_channels {
return Err(AudioError::Damaged("an impossible format"));
}
let decoder = symphonia::default::get_codecs().make(&params, &DecoderOptions::default()).map_err(err)?;
Ok(Decoder { track: track.id, format, decoder, rate, channels, caps, decoded_frames: 0, errors: 0 })
}
/// The next block of interleaved samples; `Ok(None)` at the end.
pub fn next_block(&mut self) -> Result<Option<Vec<f32>>, AudioError> {
loop {
if self.decoded_frames > u64::from(self.caps.max_hours) * 3600 * u64::from(self.rate) {
return Err(AudioError::Damaged("longer than any audiobook"));
}
let packet = match self.format.next_packet() {
Ok(p) => p,
Err(SymError::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
Err(SymError::ResetRequired) => return Ok(None),
Err(e) => {
self.errors += 1;
if self.errors > self.caps.max_errors {
return Err(err(e));
}
// A truncated or damaged file ends here rather than looping.
return Ok(None);
}
};
if packet.track_id() != self.track {
continue;
}
match self.decoder.decode(&packet) {
Ok(buf) => {
self.errors = 0;
let spec = *buf.spec();
let frames = buf.frames();
if frames == 0 {
continue;
}
let mut sb = SampleBuffer::<f32>::new(frames as u64, spec);
sb.copy_interleaved_ref(buf);
self.decoded_frames += frames as u64;
return Ok(Some(sb.samples().to_vec()));
}
Err(SymError::DecodeError(_)) => {
self.errors += 1;
if self.errors > self.caps.max_errors {
return Err(AudioError::Damaged("too many decode errors"));
}
}
Err(e) => return Err(err(e)),
}
}
}
/// Jumps to a position (milliseconds); the next block starts there or just before.
pub fn seek(&mut self, ms: u64) -> Result<(), AudioError> {
let time = Time::new(ms / 1000, (ms % 1000) as f64 / 1000.0);
self.format.seek(SeekMode::Accurate, SeekTo::Time { time, track_id: Some(self.track) }).map_err(err)?;
self.decoder.reset();
Ok(())
}
}
/// For callers that have only bytes (tests, short clips): decodes everything.
pub fn decode_all(bytes: Vec<u8>, caps: DecodeCaps) -> Result<(u32, u16, Vec<f32>), AudioError> {
if crate::container::inspect(&bytes, Default::default()) == Err(AudioError::Drm) {
return Err(AudioError::Drm);
}
let len = bytes.len() as u64;
let mut d = Decoder::open(std::io::Cursor::new(bytes), Some(len), None, caps)?;
let mut out = Vec::new();
while let Some(b) = d.next_block()? {
out.extend_from_slice(&b);
}
Ok((d.rate, d.channels, out))
}
+43
View File
@@ -0,0 +1,43 @@
//! Liber Domi, Day 4: the audio engine. Everything above the decoder is ours: time-stretch, silence trimming, voice
//! boost, chapters, the queue, the sleep timer and when to save a position. It has no Liber types, so the listening
//! app and the AI radio can use it later. Pure: samples and bytes in, samples and values out; no files, devices or
//! clock (`liber-format`'s purity test scans this crate too). The day page is `docs/04_listening.md` in the app repo.
pub mod boost;
pub mod container;
pub mod decode;
pub mod player;
pub mod silence;
pub mod speech;
pub mod stretch;
pub use container::{AudioError, DRM_MESSAGE};
/// Stereo or more → one channel (TTS voices and level meters).
pub fn mono(samples: &[f32], channels: u16) -> Vec<f32> {
let ch = channels.max(1) as usize;
samples.chunks(ch).map(|f| f.iter().sum::<f32>() / ch as f32).collect()
}
/// Linear resampling of interleaved samples (the output device's rate). Speech-quality, allocation-bounded by the
/// input.
pub fn resample(samples: &[f32], channels: u16, from: u32, to: u32) -> Vec<f32> {
if from == to || from == 0 || to == 0 {
return samples.to_vec();
}
let ch = channels.max(1) as usize;
let frames = samples.len() / ch;
let out_frames = (frames as u64 * u64::from(to) / u64::from(from)) as usize;
let mut out = Vec::with_capacity(out_frames * ch);
for i in 0..out_frames {
let pos = i as f64 * f64::from(from) / f64::from(to);
let j = pos as usize;
let t = (pos - j as f64) as f32;
for c in 0..ch {
let a = samples.get(j * ch + c).copied().unwrap_or(0.0);
let b = samples.get((j + 1) * ch + c).copied().unwrap_or(a);
out.push(a + (b - a) * t);
}
}
out
}
+158
View File
@@ -0,0 +1,158 @@
//! What a player knows, without a device or a clock: chapters, the queue, skips, the sleep timer and when to save
//! the position. The app drives it with the time it measures; every rule here is a pure function of that.
use serde::{Deserialize, Serialize};
/// Most chapters an item may have (hostile metadata).
pub const MAX_CHAPTERS: usize = 10_000;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Chapter {
pub title: String,
pub start_ms: u64,
pub end_ms: u64,
}
/// Chapters as found, made sane: sorted, inside the duration, no zero-length or overlapping ones, at most
/// [`MAX_CHAPTERS`]; each ends where the next starts. `None` when there is nothing usable.
pub fn tidy(mut chapters: Vec<Chapter>, duration_ms: u64) -> Option<Vec<Chapter>> {
chapters.retain(|c| c.start_ms < duration_ms);
chapters.sort_by_key(|c| c.start_ms);
chapters.dedup_by_key(|c| c.start_ms);
chapters.truncate(MAX_CHAPTERS);
if chapters.is_empty() {
return None;
}
let n = chapters.len();
for i in 0..n {
let end = if i + 1 < n { chapters[i + 1].start_ms } else { duration_ms };
chapters[i].end_ms = end;
chapters[i].title = chapters[i].title.chars().take(200).collect::<String>().trim().to_owned();
if chapters[i].title.is_empty() {
chapters[i].title = format!("Chapter {}", i + 1);
}
}
Some(chapters)
}
/// The chapter that holds a position.
pub fn chapter_at(chapters: &[Chapter], ms: u64) -> Option<usize> {
chapters.iter().rposition(|c| c.start_ms <= ms)
}
/// The position after a skip, inside `0..=duration`.
pub fn skip(ms: u64, by_ms: i64, duration_ms: u64) -> u64 {
(ms as i64 + by_ms).clamp(0, duration_ms as i64) as u64
}
/// Previous chapter: back to this chapter's start, or to the one before when within the first 3 s of it.
pub fn previous_chapter(chapters: &[Chapter], ms: u64) -> u64 {
match chapter_at(chapters, ms) {
Some(i) if ms.saturating_sub(chapters[i].start_ms) < 3_000 && i > 0 => chapters[i - 1].start_ms,
Some(i) => chapters[i].start_ms,
None => 0,
}
}
pub fn next_chapter(chapters: &[Chapter], ms: u64) -> Option<u64> {
let i = chapter_at(chapters, ms).map_or(0, |i| i + 1);
chapters.get(i).map(|c| c.start_ms)
}
/// The sleep timer.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Sleep {
Off,
/// Stop when the device's monotonic clock reaches this.
At {
until_ms: u64,
},
/// Stop at the end of the chapter playing when it was set.
EndOfChapter {
chapter_end_ms: u64,
},
}
impl Sleep {
pub fn minutes(now_ms: u64, minutes: u32) -> Sleep {
Sleep::At { until_ms: now_ms + u64::from(minutes.min(24 * 60)) * 60_000 }
}
pub fn end_of_chapter(chapters: &[Chapter], position_ms: u64, duration_ms: u64) -> Sleep {
let end = chapter_at(chapters, position_ms).map_or(duration_ms, |i| chapters[i].end_ms);
Sleep::EndOfChapter { chapter_end_ms: end }
}
/// Whether playback should stop now.
pub fn due(&self, now_ms: u64, position_ms: u64) -> bool {
match *self {
Sleep::Off => false,
Sleep::At { until_ms } => now_ms >= until_ms,
Sleep::EndOfChapter { chapter_end_ms } => position_ms >= chapter_end_ms,
}
}
}
/// When to write the position: every 900 ms while playing (locally; the app syncs it on pause, chapter change and
/// every 30 s), and at once on pause, seek, chapter change or stop.
#[derive(Clone, Copy, Debug, Default)]
pub struct Saver {
last_ms: Option<u64>,
}
/// With playback blocks of at most 100 ms, a saved position is never more than a second behind.
pub const SAVE_EVERY_MS: u64 = 900;
pub const MAX_BLOCK_MS: u64 = 100;
impl Saver {
pub fn tick(&mut self, now_ms: u64) -> bool {
let due = self.last_ms.is_none_or(|l| now_ms.saturating_sub(l) >= SAVE_EVERY_MS);
if due {
self.last_ms = Some(now_ms);
}
due
}
/// Pause, seek, chapter change, stop: save now.
pub fn now(&mut self, now_ms: u64) -> bool {
self.last_ms = Some(now_ms);
true
}
}
/// A queue of things to play (an audiobook, a book read aloud, texts other apps sent).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Queue<T> {
pub items: Vec<T>,
pub current: Option<usize>,
}
impl<T> Queue<T> {
pub fn push(&mut self, item: T) -> usize {
self.items.push(item);
if self.current.is_none() {
self.current = Some(self.items.len() - 1);
}
self.items.len() - 1
}
pub fn current(&self) -> Option<&T> {
self.current.and_then(|i| self.items.get(i))
}
pub fn advance(&mut self) -> Option<&T> {
let next = self.current.map_or(0, |i| i + 1);
self.current = (next < self.items.len()).then_some(next);
self.current()
}
pub fn remove(&mut self, i: usize) {
if i >= self.items.len() {
return;
}
self.items.remove(i);
self.current = match self.current {
Some(c) if c == i => (c < self.items.len()).then_some(c),
Some(c) if c > i => Some(c - 1),
c => c,
};
}
}
+153
View File
@@ -0,0 +1,153 @@
//! Silence trimming: pauses longer than `long` are shortened to `keep`; any frame louder than the threshold is never
//! removed. Streaming: the first `keep` of a pause goes out at once, the next part is held, and the held part is
//! dropped only once the pause has proved longer than `long`. A map turns output time back into input time, so a
//! position is always in the book's own seconds.
#[derive(Clone, Copy, Debug)]
pub struct TrimConfig {
/// A 10 ms frame quieter than this (RMS, dBFS) is silence.
pub threshold_db: f32,
/// Pauses at least this long are shortened…
pub long_ms: u32,
/// …to this.
pub keep_ms: u32,
}
impl Default for TrimConfig {
fn default() -> Self {
TrimConfig { threshold_db: -45.0, long_ms: 300, keep_ms: 150 }
}
}
pub struct Trimmer {
cfg: TrimConfig,
channels: usize,
frame: usize,
threshold: f32,
/// Input not yet a whole frame.
pending: Vec<f32>,
/// Frames of the current pause held back (past `keep`, not yet `long`).
held: Vec<f32>,
/// Silent frames in the current pause so far.
run: usize,
keep_frames: usize,
long_frames: usize,
out: Vec<f32>,
/// Input and output frame counters, and (output, input) points where the two diverge.
in_frames: u64,
out_frames: u64,
map: Vec<(u64, u64)>,
pub enabled: bool,
}
impl Trimmer {
pub fn new(rate: u32, channels: u16, cfg: TrimConfig) -> Trimmer {
let frame = (rate as usize / 100).max(1);
Trimmer {
cfg,
channels: channels.max(1) as usize,
frame,
threshold: 10f32.powf(cfg.threshold_db / 20.0),
pending: Vec::new(),
held: Vec::new(),
run: 0,
keep_frames: (cfg.keep_ms as usize).div_ceil(10),
long_frames: (cfg.long_ms as usize).div_ceil(10),
out: Vec::new(),
in_frames: 0,
out_frames: 0,
map: vec![(0, 0)],
enabled: true,
}
}
pub fn config(&self) -> TrimConfig {
self.cfg
}
fn emit(&mut self, block: &[f32]) {
self.out.extend_from_slice(block);
self.out_frames += (block.len() / self.channels) as u64;
}
fn release_held(&mut self) {
let held = std::mem::take(&mut self.held);
self.emit(&held);
}
fn step(&mut self, frame: Vec<f32>) {
let n = frame.len() / self.channels;
if !self.enabled {
self.in_frames += n as u64;
self.emit(&frame);
return;
}
let rms = (frame.iter().map(|x| x * x).sum::<f32>() / frame.len().max(1) as f32).sqrt();
let silent = rms < self.threshold;
if !silent {
// Speech: whatever was held belonged to a short pause; it goes out too.
self.release_held();
self.run = 0;
self.in_frames += n as u64;
self.emit(&frame);
return;
}
self.run += 1;
self.in_frames += n as u64;
if self.run <= self.keep_frames {
self.emit(&frame);
} else if self.run < self.long_frames {
self.held.extend_from_slice(&frame);
} else {
// A long pause: the held part and everything after it until speech is dropped.
self.held.clear();
// One map point per dropped pause: output stands still while input moves on.
match self.map.last_mut() {
Some(last) if last.0 == self.out_frames => last.1 = self.in_frames,
_ => self.map.push((self.out_frames, self.in_frames)),
}
}
}
/// Adds interleaved samples.
pub fn push(&mut self, samples: &[f32]) {
self.pending.extend_from_slice(samples);
let size = self.frame * self.channels;
while self.pending.len() >= size {
let rest = self.pending.split_off(size);
let frame = std::mem::replace(&mut self.pending, rest);
self.step(frame);
}
}
/// End of input: a held part of a short pause and the last partial frame go out.
pub fn finish(&mut self) {
self.release_held();
let rest = std::mem::take(&mut self.pending);
self.in_frames += (rest.len() / self.channels) as u64;
self.emit(&rest);
}
pub fn pull(&mut self) -> Vec<f32> {
std::mem::take(&mut self.out)
}
/// The input frame an output frame came from (to report positions in the book's own time).
pub fn input_frame(&self, out_frame: u64) -> u64 {
let i = self.map.partition_point(|&(o, _)| o <= out_frame).saturating_sub(1);
let (o, inp) = self.map[i];
// Between map points output and input run together, except across a dropped pause where the last point
// already accounts for it.
let later = self.map.get(i + 1).map(|&(_, ni)| ni);
let guess = inp + (out_frame - o);
later.map_or(guess, |ni| guess.min(ni))
}
}
/// The whole of `samples`, trimmed (tests and short clips).
pub fn trim(samples: &[f32], rate: u32, channels: u16, cfg: TrimConfig) -> Vec<f32> {
let mut t = Trimmer::new(rate, channels, cfg);
t.push(samples);
t.finish();
t.pull()
}
+86
View File
@@ -0,0 +1,86 @@
//! Read-aloud bookkeeping, voice-agnostic: the cache key of a synthesized sentence, and the timeline that says which
//! sentence is being heard at a given moment (for the highlight), with pauses between sentences, after paragraphs
//! and after chapter titles. The voice itself runs in the app.
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
/// Pauses inserted after a segment, by what ends there.
pub const PAUSE_SENTENCE_MS: u32 = 120;
pub const PAUSE_PARAGRAPH_MS: u32 = 600;
pub const PAUSE_TITLE_MS: u32 = 900;
/// The cache key of one synthesized sentence: everything that changes the audio is in it (the voice and its file
/// hash, the synthesis speed, the language, the exact text). Hex, so it is also a safe file name.
pub fn cache_key(voice: &str, voice_sha256: &str, speed: f32, lang: &str, text: &str) -> String {
let mut h = Sha256::new();
for part in [voice, voice_sha256, &format!("{speed:.3}"), lang, text] {
h.update((part.len() as u64).to_le_bytes());
h.update(part.as_bytes());
}
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Ends {
Sentence,
Paragraph,
Title,
}
/// One spoken segment: its place in the book (chapter and UTF-16 range, opaque here), how long its audio is, what it
/// ends.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Segment {
pub chapter: usize,
pub start: usize,
pub end: usize,
pub audio_ms: u32,
pub ends: Ends,
}
/// Segments laid end to end with their pauses.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Timeline {
/// (start_ms, segment index), increasing.
starts: Vec<(u64, usize)>,
pub segments: Vec<Segment>,
pub total_ms: u64,
}
impl Timeline {
pub fn new(segments: Vec<Segment>) -> Timeline {
let mut at = 0u64;
let mut starts = Vec::with_capacity(segments.len());
for (i, s) in segments.iter().enumerate() {
starts.push((at, i));
at += u64::from(s.audio_ms)
+ u64::from(match s.ends {
Ends::Sentence => PAUSE_SENTENCE_MS,
Ends::Paragraph => PAUSE_PARAGRAPH_MS,
Ends::Title => PAUSE_TITLE_MS,
});
}
Timeline { starts, segments, total_ms: at }
}
/// The segment being heard at `ms` (during its pause, still that segment); `None` past the end.
pub fn at(&self, ms: u64) -> Option<usize> {
if ms >= self.total_ms {
return None;
}
let i = self.starts.partition_point(|&(s, _)| s <= ms);
i.checked_sub(1).map(|k| self.starts[k].1)
}
/// Where a segment's audio starts.
pub fn start_of(&self, segment: usize) -> Option<u64> {
self.starts.get(segment).map(|&(s, _)| s)
}
/// Whether `ms` falls in a pause rather than in speech.
pub fn in_pause(&self, ms: u64) -> bool {
self.at(ms).is_some_and(|i| ms >= self.starts[i].0 + u64::from(self.segments[i].audio_ms))
}
}
+181
View File
@@ -0,0 +1,181 @@
//! Speed without pitch: WSOLA (waveform-similarity overlap-add). Hann-windowed frames are overlap-added at a fixed
//! output hop; each next frame is taken from near its nominal input position (input advances `speed` times the
//! output hop), shifted by up to ±12 ms to where it best continues the frame before. Streaming: push input blocks,
//! pull output; the speed can change between blocks.
/// Frame length, overlap and search window, in seconds.
const FRAME: f64 = 0.040;
const SEARCH: f64 = 0.012;
pub const MIN_SPEED: f64 = 0.5;
pub const MAX_SPEED: f64 = 3.0;
pub struct Stretcher {
channels: usize,
n: usize,
hop: usize,
search: usize,
speed: f64,
window: Vec<f32>,
/// Interleaved input not yet consumed; `base` is the absolute frame index of its first frame.
input: Vec<f32>,
base: usize,
/// Nominal analysis position of the next frame (absolute, in frames), and the start chosen for the last one.
pos: f64,
last: Option<usize>,
/// Overlap-add accumulator: `n` frames, interleaved.
acc: Vec<f32>,
out: Vec<f32>,
flushed: bool,
}
impl Stretcher {
pub fn new(rate: u32, channels: u16) -> Stretcher {
let channels = channels.max(1) as usize;
let n = ((rate as f64 * FRAME) as usize).max(64) & !1;
let window =
(0..n).map(|i| (0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / n as f64).cos()) as f32).collect();
Stretcher {
channels,
n,
hop: n / 2,
search: (rate as f64 * SEARCH) as usize,
speed: 1.0,
window,
input: Vec::new(),
base: 0,
pos: 0.0,
last: None,
acc: vec![0.0; n * channels],
out: Vec::new(),
flushed: false,
}
}
pub fn speed(&self) -> f64 {
self.speed
}
/// 0.5–3×; outside values are clamped, NaN keeps the current speed.
pub fn set_speed(&mut self, speed: f64) {
if speed.is_finite() {
self.speed = speed.clamp(MIN_SPEED, MAX_SPEED);
}
}
fn frames_in(&self) -> usize {
self.input.len() / self.channels
}
/// Mono sample at an absolute input frame (0 outside what is buffered).
fn mono(&self, abs: usize) -> f32 {
if abs < self.base {
return 0.0;
}
let i = abs - self.base;
if i >= self.frames_in() {
return 0.0;
}
let row = &self.input[i * self.channels..(i + 1) * self.channels];
row.iter().sum::<f32>() / self.channels as f32
}
/// Adds interleaved samples.
pub fn push(&mut self, samples: &[f32]) {
self.input.extend_from_slice(samples);
self.run(false);
}
/// No more input: everything buffered comes out.
pub fn finish(&mut self) {
if !self.flushed {
self.flushed = true;
self.run(true);
// The tail of the accumulator is the last frame's second half.
self.out.extend_from_slice(&self.acc[..self.hop * self.channels]);
self.acc.iter_mut().for_each(|x| *x = 0.0);
}
}
/// Takes what is ready.
pub fn pull(&mut self) -> Vec<f32> {
std::mem::take(&mut self.out)
}
fn run(&mut self, last: bool) {
let (n, hop, s, ch) = (self.n, self.hop, self.search, self.channels);
loop {
let nominal = self.pos.round() as usize;
let end_needed = nominal + s + n;
let have = self.base + self.frames_in();
if have < end_needed && !(last && nominal < have) {
break;
}
// Best start near the nominal one: the frame that best continues the last frame's natural sequel.
let start = match self.last {
None => nominal,
Some(prev) => {
let lo = nominal.saturating_sub(s).max(self.base);
let hi = (nominal + s).min(have.saturating_sub(n).max(lo));
let target = prev + hop;
let mut best = (f32::MIN, nominal.clamp(lo, hi));
let step = 2;
let overlap = hop;
let mut d = lo;
while d <= hi {
let mut c = 0.0f32;
let mut k = 0;
while k < overlap {
c += self.mono(target + k) * self.mono(d + k);
k += 4;
}
if c > best.0 {
best = (c, d);
}
d += step;
}
best.1
}
};
for i in 0..n {
let w = self.window[i];
let abs = start + i;
for c in 0..ch {
let v = if abs >= self.base && abs - self.base < self.frames_in() {
self.input[(abs - self.base) * ch + c]
} else {
0.0
};
self.acc[i * ch + c] += v * w;
}
}
// The first hop of the accumulator is complete: emit it and shift.
self.out.extend_from_slice(&self.acc[..hop * ch]);
self.acc.copy_within(hop * ch.., 0);
let len = self.acc.len();
self.acc[len - hop * ch..].iter_mut().for_each(|x| *x = 0.0);
self.last = Some(start);
self.pos += hop as f64 * self.speed;
// Drop input nothing will read again.
let keep_from = (self.pos as usize).saturating_sub(s).min(start + hop).min(self.base + self.frames_in());
if keep_from > self.base {
let drop = keep_from - self.base;
self.input.drain(..drop * ch);
self.base = keep_from;
}
if last && self.pos as usize >= have {
break;
}
}
}
}
/// The whole of `samples` at `speed` (tests and short clips).
pub fn stretch(samples: &[f32], rate: u32, channels: u16, speed: f64) -> Vec<f32> {
let mut s = Stretcher::new(rate, channels);
s.set_speed(speed);
for block in samples.chunks(4096 * channels.max(1) as usize) {
s.push(block);
}
s.finish();
s.pull()
}