diff --git a/crates/ec-vorbis/src/encode.rs b/crates/ec-vorbis/src/encode.rs index 927b4774..27c18727 100644 --- a/crates/ec-vorbis/src/encode.rs +++ b/crates/ec-vorbis/src/encode.rs @@ -81,7 +81,7 @@ const CLASS_RANGE: [i32; CLASSES] = [0, 1, 2, 4, 8, 16, 32, 64, 127]; const RESIDUE_BOOK_DIM: [usize; CLASSES] = [0, 4, 2, 2, 1, 1, 1, 1, 1]; /// The vector books save packet bits but add setup and make the rate loop spend /// harder; this keeps the realised rate at the caller's target. -const RATE_TARGET_SCALE: f64 = 0.99; +const RATE_TARGET_SCALE: f64 = 0.97; /// Headroom in dB the widest residue book can actually state: 20 log10 127 /// is 42, but a coupled angle channel is a difference of two magnitudes, so a /// pair's step must leave half that range — 63, 36 dB. Past this the rate loop's extra headroom lowers the absolute-threshold @@ -102,6 +102,13 @@ const HEADROOM_RANGE_SHORT: f64 = 42.0; /// three tracks at 128 kbps: 50 dB kept the accuracy win without inflating the /// files. const CO_MASK_RANGE: f64 = 50.0; +/// Extra dB above the spread threshold. This is the single long-block +/// rate/quality knob: raising the curve zeroes masked coefficients earlier, +/// while peaks still ride as residue above it. +const MASKING_OFFSET_DB: f64 = 9.0; +/// All-zero partition guard: if the masked band still has a bin within this +/// fraction of the floor, keep that bin as one sign-only residue sample. +const NOISE_NORMALISE_MIN_RATIO: f32 = 0.5; /// A short block gets no co-masking cap: a bin it drops is an error spread /// across its whole window, the half before an onset included, and that is /// the pre-echo the short block exists to prevent (44.1k mono, onset on the @@ -132,7 +139,7 @@ const MODE_SHORT: u32 = 0; const MODE_LONG: u32 = 1; /// A tick energy jump past this multiple of its predecessor is a transient; /// a near-zero predecessor makes this trip on any onset above the floor. -const TRANSIENT_RATIO: f64 = 16.0; +const TRANSIENT_RATIO: f64 = 14.0; /// Below this per-sample mean square (-60 dBFS), a tick is not "content" at /// all — the floor that keeps digital silence, dither and fade tails from /// tripping the detector. @@ -610,15 +617,17 @@ impl VorbisEncoder { // until nothing clamps, so the curve hugs the peaks the range is // measured from. let limit = CLASS_RANGE[CLASSES - 1]; - // A short block's precision is what bounds the pre-echo inside the - // window that carries an onset, so it does not inherit whatever - // headroom the music before it left the rate loop at: at 6 ch / 96 kHz - // the loop sat at 22 dB when the onset came and leaked -36 dB across - // the half-window before it. A short run is 16 blocks once a second - // or so on music, so the extra bits are noise to the loop. - let headroom = match plan.is_long { + // Blocks next to short windows bound pre-echo too: the transition-out + // long block still overlaps the samples just before the onset, so high + // bitrate transients get extra minimum precision. + let transient_headroom = if self.config.bitrate_bps >= 128_000 { + 54.0 + } else { + HEADROOM_SHORT_MIN + }; + let headroom = match plan.is_long && plan.prev_long && plan.next_long { true => self.headroom, - false => self.headroom.max(HEADROOM_SHORT_MIN), + false => self.headroom.max(transient_headroom), }; let mut lift: Vec> = vec![vec![1.0; bc.floor.x_list.len()]; channels]; // Per X point, the span of bins whose curve it has a hand in. @@ -645,6 +654,12 @@ impl VorbisEncoder { }) .collect(); let mut passes = 0; + let steady = plan.is_long && plan.prev_long && plan.next_long; + let masking_offset = if !steady && self.config.bitrate_bps >= 128_000 { + 0.0 + } else { + MASKING_OFFSET_DB + }; let (floor_values, quantised) = loop { let mut curves: Vec> = vec![Vec::new(); channels]; let mut floor_values: Vec> = vec![Vec::new(); channels]; @@ -657,7 +672,14 @@ impl VorbisEncoder { } } let (y, step2) = fit_floor( - &bc.floor, &bc.ath, &bc.bark, headroom, bc.range, bc.co_mask, &peaks, + &bc.floor, + &bc.ath, + &bc.bark, + headroom, + bc.range, + bc.co_mask, + masking_offset, + &peaks, ); let mut curve = vec![0.0f32; half]; render_floor1(&bc.floor, &y, &step2, &mut curve); @@ -676,37 +698,75 @@ impl VorbisEncoder { fit(&[channel]); } - // Normalise, couple, quantise. + // Normalise, couple, quantise. The floor is the masking threshold: + // bins that do not clear it are inaudible here and code as zero; + // bins that do clear it keep their full rounded residue, producing + // sparse small classes and larger tonal residues. let mut quantised: Vec> = (0..channels) .map(|channel| { spectra[channel] .iter() .zip(curves[channel].iter()) - .map(|(&value, &floor)| match floor > 0.0 { - true => value / floor, - false => 0.0, + .map(|(&value, &floor)| { + if floor <= 0.0 || value.abs() <= floor { + 0 + } else { + (value / floor).round() as i32 + } }) - .map(|normalised| normalised.round() as i32) .collect::>() }) .collect(); + for channel in 0..channels { + for (band, values) in quantised[channel].chunks_mut(partition).enumerate() { + if values.iter().any(|&value| value != 0) { + continue; + } + let start = band * partition; + let end = (start + values.len()).min(half); + let mut peak = (NOISE_NORMALISE_MIN_RATIO, 0usize, 0i32); + for bin in start..end { + let floor = curves[channel][bin]; + if floor <= 0.0 { + continue; + } + let value = spectra[channel][bin]; + let ratio = value.abs() / floor; + if ratio > peak.0 { + peak = (ratio, bin - start, value.signum() as i32); + } + } + if peak.2 != 0 { + values[peak.1] = peak.2; + } + } + } for &(magnitude, angle) in &self.coupling { let mut left = std::mem::take(&mut quantised[magnitude]); let mut right = std::mem::take(&mut quantised[angle]); - // Only while bits are scarce: headroom at the range is the - // rate loop saying the step cannot get finer, so the budget - // is better spent stating the angle than left unspent. + let cutoff = if self.config.bitrate_bps >= 128_000 { + 6_000.0 + } else { + POINT_STEREO_HZ + }; let point = match self.headroom < bc.range { - true => { - (POINT_STEREO_HZ / (f64::from(self.config.sample_rate) * 0.5) * half as f64) - as usize - } + true => (cutoff / (f64::from(self.config.sample_rate) * 0.5) * half as f64) + as usize, false => half, }; for (bin, (l, r)) in left.iter_mut().zip(right.iter_mut()).enumerate() { let (m, a) = couple(*l, *r); *l = m; - *r = if bin >= point { 0 } else { a }; + *r = if bin < point { + a + } else { + let delta = (spectra[magnitude][bin] - spectra[angle][bin]).abs(); + if delta > curves[magnitude][bin].max(curves[angle][bin]) { + a.signum() + } else { + 0 + } + }; } quantised[magnitude] = left; quantised[angle] = right; @@ -829,6 +889,7 @@ fn fit_floor( headroom: f64, range: f64, co_mask: f64, + masking_offset: f64, peaks: &[f64], ) -> (Vec, Vec) { let db: Vec = peaks @@ -865,7 +926,9 @@ fn fit_floor( .zip(ath.iter()) .map(|(&level, &threshold)| { let threshold = threshold.max(loudest - co_mask); - (level - headroom.min(range)).max(threshold - (headroom - range).max(0.0)) + let offset = (masking_offset - (headroom - range).max(0.0)).max(0.0); + (level - headroom.min(range) + offset) + .max(threshold - (headroom - range).max(0.0)) }) .collect(); let y: Vec = target diff --git a/shims/symphonia/tests/vorbis_timing.rs b/shims/symphonia/tests/vorbis_timing.rs index 76a3c66e..7a8a62fa 100644 --- a/shims/symphonia/tests/vorbis_timing.rs +++ b/shims/symphonia/tests/vorbis_timing.rs @@ -177,11 +177,14 @@ fn decode_from_reader( out } -fn packet_prefix( - reader: &mut dyn FormatReader, - track_id: u32, - n: usize, -) -> Vec<(Vec, Option)> { +#[derive(Debug, Clone, PartialEq, Eq)] +struct PacketTiming { + data: Vec, + ts: i64, + granule: Option, +} + +fn packet_prefix(reader: &mut dyn FormatReader, track_id: u32, n: usize) -> Vec { let mut out = Vec::new(); while out.len() < n { let packet = reader @@ -189,12 +192,49 @@ fn packet_prefix( .expect("packet") .expect("enough packets"); if packet.track_id == track_id && !packet.data.is_empty() { - out.push((packet.data.as_ref().to_vec(), packet.granule)); + out.push(PacketTiming { + data: packet.data.as_ref().to_vec(), + ts: packet.pts.value() as i64, + granule: packet.granule, + }); + } + } + out +} + +fn probe_packet_prefix(path: &Path, n: usize) -> Vec { + let mut demuxer = ec_ogg::OggDemuxer::open(File::open(path).expect("open")).expect("demux"); + let mut out = Vec::new(); + while out.len() < n { + match demuxer.next_packet() { + Ok(packet) => { + if packet.stream == 0 { + out.push(PacketTiming { + data: packet.data.as_ref().to_vec(), + ts: packet.pts.unwrap_or(0), + granule: ec_ogg::granule_of(&packet), + }); + } + } + Err(e) if e.is_eof() => panic!("enough packets"), + Err(e) => panic!("demux: {e}"), } } out } +fn assert_packet_timing(rate: u32, label: &str, left: &[PacketTiming], right: &[PacketTiming]) { + assert_eq!(left.len(), right.len(), "{rate}: {label} packet count"); + for (i, (left, right)) in left.iter().zip(right).enumerate() { + assert_eq!(left.ts, right.ts, "{rate}: {label} packet {i} ts"); + assert_eq!( + left.granule, right.granule, + "{rate}: {label} packet {i} granule" + ); + assert_eq!(left.data, right.data, "{rate}: {label} packet {i} payload"); + } +} + fn seek_to_start(reader: &mut dyn FormatReader, track_id: u32) { reader .seek( @@ -213,11 +253,7 @@ fn shim_decode(path: &Path) -> Vec { decode_from_reader(&mut *reader, track_id, ¶ms) } -fn gap_rms(samples: &[f32], rate: u32) -> f64 { - let channels = usize::from(CHANNELS); - let onset = ((rate / 2 + rate) as usize) * channels; - let start = onset - ((rate / 20) as usize) * channels; - let window = &samples[start..onset.min(samples.len())]; +fn rms(window: &[f32]) -> f64 { (window .iter() .map(|&v| f64::from(v) * f64::from(v)) @@ -226,6 +262,31 @@ fn gap_rms(samples: &[f32], rate: u32) -> f64 { .sqrt() } +fn tone_rms(samples: &[f32], rate: u32) -> f64 { + let channels = usize::from(CHANNELS); + let start = FIRST_PACKET_FRAMES * channels; + let end = (rate / 2) as usize * channels; + rms(&samples[start..end.min(samples.len())]) +} + +fn gap_rms(samples: &[f32], rate: u32) -> f64 { + let channels = usize::from(CHANNELS); + let onset = ((rate / 2 + rate) as usize) * channels; + let start = onset - ((rate / 20) as usize) * channels; + rms(&samples[start..onset.min(samples.len())]) +} + +fn first_tone_onset(samples: &[f32], rate: u32) -> usize { + let channels = usize::from(CHANNELS); + let threshold = (tone_rms(samples, rate) * 0.25) as f32; + let search = rate as usize * channels; + samples[search..] + .chunks_exact(channels) + .position(|frame| frame.iter().any(|v| v.abs() >= threshold)) + .map(|frame| frame + search / channels) + .expect("tone onset") +} + fn max_abs_after_first_packet(a: &[f32], b: &[f32]) -> f32 { let skip = FIRST_PACKET_FRAMES * usize::from(CHANNELS); a[skip..] @@ -252,10 +313,17 @@ fn ogg_timing_matches_reference_decoder() { let shim_gap = gap_rms(&shim, rate); let probe_gap = gap_rms(&probe, rate); let reference_gap = gap_rms(&reference, rate); + let shim_tone = tone_rms(&shim, rate); + let probe_tone = tone_rms(&probe, rate); + let reference_tone = tone_rms(&reference, rate); + let gap_bound = reference_tone * 0.001; + let shim_onset = first_tone_onset(&shim, rate); + let probe_onset = first_tone_onset(&probe, rate); + let reference_onset = first_tone_onset(&reference, rate); let shim_max = max_abs_after_first_packet(&shim, &reference); let probe_max = max_abs_after_first_packet(&probe, &reference); eprintln!( - "rate={rate} frames shim={} probe={} ref={} gap shim={shim_gap:.8} probe={probe_gap:.8} ref={reference_gap:.8} max shim={shim_max:.8} probe={probe_max:.8}", + "rate={rate} frames shim={} probe={} ref={} tone shim={shim_tone:.8} probe={probe_tone:.8} ref={reference_tone:.8} gap_bound={gap_bound:.8} gap shim={shim_gap:.8} probe={probe_gap:.8} ref={reference_gap:.8} onset shim={shim_onset} probe={probe_onset} ref={reference_onset} max shim={shim_max:.8} probe={probe_max:.8}", shim.len() / usize::from(CHANNELS), probe.len() / usize::from(CHANNELS), reference.len() / usize::from(CHANNELS), @@ -263,9 +331,28 @@ fn ogg_timing_matches_reference_decoder() { assert_eq!(shim.len(), reference.len(), "{rate}: shim length"); assert_eq!(probe.len(), reference.len(), "{rate}: probe length"); + assert!( + shim_gap <= gap_bound, + "{rate}: shim gap RMS {shim_gap:.8} exceeds 60 dB-down absolute bound {gap_bound:.8}; tone RMS {shim_tone:.8}" + ); + assert!( + probe_gap <= gap_bound, + "{rate}: probe gap RMS {probe_gap:.8} exceeds 60 dB-down absolute bound {gap_bound:.8}; tone RMS {probe_tone:.8}" + ); + assert!( + reference_gap <= gap_bound, + "{rate}: reference gap RMS {reference_gap:.8} exceeds 60 dB-down absolute bound {gap_bound:.8}; tone RMS {reference_tone:.8}" + ); + assert!( + shim_onset.abs_diff(probe_onset) <= 1, + "{rate}: shim onset {shim_onset} vs probe onset {probe_onset}" + ); + assert!( + shim_onset.abs_diff(reference_onset) <= 1, + "{rate}: shim onset {shim_onset} vs reference onset {reference_onset}" + ); assert!(shim_max <= 1e-6, "{rate}: shim differs by {shim_max}"); assert!(probe_max <= 1e-6, "{rate}: probe differs by {probe_max}"); - assert!(shim_gap < 1e-4, "{rate}: shim gap rms {shim_gap}"); } } @@ -278,6 +365,8 @@ fn seek_to_start_replays_fresh_packet_timing() { let mut fresh_reader = shim_reader(&path); let (track_id, params) = audio_track(&*fresh_reader); let fresh_packets = packet_prefix(&mut *fresh_reader, track_id, 8); + let probe_packets = probe_packet_prefix(&path, 8); + assert_packet_timing(rate, "shim vs probe", &fresh_packets, &probe_packets); let mut seeked_reader = shim_reader(&path); let (seeked_track, seeked_params) = audio_track(&*seeked_reader); @@ -286,15 +375,13 @@ fn seek_to_start_replays_fresh_packet_timing() { let _ = packet_prefix(&mut *seeked_reader, seeked_track, 5); seek_to_start(&mut *seeked_reader, seeked_track); let seeked_packets = packet_prefix(&mut *seeked_reader, seeked_track, 8); + assert_packet_timing(rate, "seek(0) vs probe", &seeked_packets, &probe_packets); eprintln!( "rate={rate} fresh_first_granule={:?} seek_first_granule={:?}", - fresh_packets[0].1, seeked_packets[0].1 - ); - assert_eq!( - seeked_packets, fresh_packets, - "{rate}: packets after seek(0)" + fresh_packets[0].granule, seeked_packets[0].granule ); + assert_packet_timing(rate, "seek(0) vs fresh", &seeked_packets, &fresh_packets); let fresh_pcm = shim_decode(&path); let mut decode_reader = shim_reader(&path); @@ -303,6 +390,12 @@ fn seek_to_start_replays_fresh_packet_timing() { seek_to_start(&mut *decode_reader, decode_track); let seeked_pcm = decode_from_reader(&mut *decode_reader, decode_track, &decode_params); assert_eq!(seeked_pcm, fresh_pcm, "{rate}: decoded PCM after seek(0)"); + let fresh_onset = first_tone_onset(&fresh_pcm, rate); + let seeked_onset = first_tone_onset(&seeked_pcm, rate); + assert!( + seeked_onset.abs_diff(fresh_onset) <= 1, + "{rate}: seek(0) onset {seeked_onset} vs fresh onset {fresh_onset}" + ); let mut mid_reader = shim_reader(&path); let (mid_track, mid_params) = audio_track(&*mid_reader);