diff --git a/Cargo.lock b/Cargo.lock index 817bbf6a..943570a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -707,6 +707,7 @@ name = "ec-pgs" version = "0.1.0" dependencies = [ "ec-core", + "ec-testkit", ] [[package]] @@ -758,9 +759,7 @@ dependencies = [ name = "ec-subs" version = "0.1.0" dependencies = [ - "ec-ass", "ec-core", - "ec-pgs", "ec-testkit", ] diff --git a/crates/ec-ass/examples/benchp1.rs b/crates/ec-ass/examples/benchp1.rs deleted file mode 100644 index 636270bd..00000000 --- a/crates/ec-ass/examples/benchp1.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! benchp1: ASS parse throughput for lanes/bench.md ("lane benchp1"). -//! -//! usage: benchp1 ass [reps] -//! -//! Parses the whole file `reps` times (default 5). Each timed run repeats the parse until it -//! takes at least 0.2 s, so the per-parse time is not timer noise. Prints the best per-parse -//! time, the throughput in MB/s and the cue count of the parsed track (checked against ffprobe). -use std::hint::black_box; -use std::time::Instant; - -fn main() { - let args: Vec = std::env::args().collect(); - let kind = args.get(1).map(String::as_str).unwrap_or(""); - let bytes = std::fs::read(&args[2]).expect("read subtitle file"); - let reps: usize = args.get(3).map_or(5, |s| s.parse().expect("reps")); - let parse = |b: &[u8]| match kind { - "ass" => ec_ass::parse(b), - - _ => panic!("kind must be ass"), - }; - - let first = parse(&bytes).expect("parse"); - let cues = first.cues.len(); - let skipped = first.skipped; - let t0 = Instant::now(); - black_box(parse(black_box(&bytes)).expect("parse")); - let one = t0.elapsed().as_secs_f64().max(1e-6); - let inner = ((0.2 / one).ceil() as usize).max(1); - - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - for _ in 0..inner { - black_box(parse(black_box(&bytes)).expect("parse")); - } - best = best.min(t.elapsed().as_secs_f64() / inner as f64); - } - let mb_s = bytes.len() as f64 / best / 1e6; - println!( - "kind={kind} bytes={} cues={cues} skipped={skipped} best_parse_ms={:.3} mb_s={mb_s:.2} reps={reps} inner={inner}", - bytes.len(), - best * 1e3 - ); -} diff --git a/crates/ec-ass/tests/open_media.rs b/crates/ec-ass/tests/open_media.rs new file mode 100644 index 00000000..4271eb5c --- /dev/null +++ b/crates/ec-ass/tests/open_media.rs @@ -0,0 +1,37 @@ +use ec_subs::{SourceFormat, plain_text}; + +fn fixture(rel: &str) -> Vec { + std::fs::read(ec_testkit::fixture(rel)).unwrap() +} + +#[test] +fn a_real_ass_script_parses_whole() { + let bytes = fixture("subs/tos-en.ass"); + let track = ec_ass::parse(&bytes).unwrap(); + assert_eq!(track.source, Some(SourceFormat::AssOrSsa)); + assert!(!track.styles.is_empty(), "a script declares styles"); + assert_eq!(track.cues.len(), 76, "ffmpeg reads 76 cues"); + assert_eq!(track.skipped, 0, "a whole script should have no torn rows"); + let with_text = track + .cues + .iter() + .filter(|c| !plain_text(&c.segments).trim().is_empty()) + .count(); + assert!( + with_text * 10 > track.cues.len() * 9, + "{with_text} of {}", + track.cues.len() + ); + for cue in &track.cues { + assert!(cue.end_us >= cue.start_us); + if let Some(style) = &cue.style_ref { + assert!( + track.style(style).is_some(), + "cue names undeclared style {style:?}" + ); + } + let text = plain_text(&cue.segments); + assert!(!text.contains("{\\"), "override tag in text: {text:?}"); + } + assert!(track.extradata.windows(8).any(|w| w == b"[Events]")); +} diff --git a/crates/ec-dvbsub/src/lib.rs b/crates/ec-dvbsub/src/lib.rs index cf713ddd..f314302c 100644 --- a/crates/ec-dvbsub/src/lib.rs +++ b/crates/ec-dvbsub/src/lib.rs @@ -610,10 +610,6 @@ impl Decoder for DvbSubDecoder { } } -/// A DVB subtitle decoder as the family's registry hands one out. -pub fn make_decoder(_params: &CodecParameters) -> Result> { - Ok(Box::new(DvbSubDecoder::new())) -} #[cfg(test)] mod tests { diff --git a/crates/ec-dvdsub/src/lib.rs b/crates/ec-dvdsub/src/lib.rs index 5f09bd71..30859159 100644 --- a/crates/ec-dvdsub/src/lib.rs +++ b/crates/ec-dvdsub/src/lib.rs @@ -29,6 +29,7 @@ use ec_core::{ pub const MAX_DIMENSION: u32 = 4096; /// Ticks of the SPU delay unit: 1024 periods of the 90 kHz clock. pub const DELAY_UNIT_90K: i64 = 1024; +const CLOCK_90K: TimeBase = TimeBase::new(1, 90_000); /// Finished cues kept for [`DvdSubDecoder::take_cue`]. pub const MAX_PENDING: usize = 64; @@ -475,7 +476,7 @@ pub struct DvdSubDecoder { params: CodecParameters, palette: Palette, canvas: (u32, u32), - ready: VecDeque<(Cue, Option)>, + ready: VecDeque, } impl DvdSubDecoder { @@ -498,21 +499,20 @@ impl DvdSubDecoder { pub fn push_unit(&mut self, unit: &[u8], pts: Option) -> Result<()> { let mut cue = decode_spu(unit, &self.palette, self.canvas)?; if let Some(p) = pts { - let base = TimeBase::try_new(1, 90_000).map_err(|_| Error::corrupt("dvdsub: time base"))?; - let delay = Timestamp::new(cue.start_90k, base) + let delay = Timestamp::new(cue.start_90k, CLOCK_90K) .rescale(p.base, ec_core::Rounding::Nearest); cue.frame.pts = Some(Timestamp::new(p.ticks.saturating_add(delay.ticks), p.base)); } if self.ready.len() >= MAX_PENDING { self.ready.pop_front(); } - self.ready.push_back((cue, pts)); + self.ready.push_back(cue); Ok(()) } /// The next decoded cue with its timing, oldest first. pub fn take_cue(&mut self) -> Option { - self.ready.pop_front().map(|(c, _)| c) + self.ready.pop_front() } } @@ -542,10 +542,6 @@ impl Decoder for DvdSubDecoder { } } -/// A DVD subpicture decoder as the family's registry hands one out. -pub fn make_decoder(params: &CodecParameters) -> Result> { - Ok(Box::new(DvdSubDecoder::new(params.extradata.as_deref()))) -} #[cfg(test)] mod tests { diff --git a/crates/ec-pgs/Cargo.toml b/crates/ec-pgs/Cargo.toml index 9a886c18..28aa41e7 100644 --- a/crates/ec-pgs/Cargo.toml +++ b/crates/ec-pgs/Cargo.toml @@ -8,3 +8,6 @@ authors.workspace = true [dependencies] ec-core.workspace = true + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-pgs/examples/benchp1.rs b/crates/ec-pgs/examples/benchp1.rs deleted file mode 100644 index c740cf62..00000000 --- a/crates/ec-pgs/examples/benchp1.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! benchp1: PGS (.sup) decode throughput for lanes/bench.md ("lane benchp1"). -//! -//! usage: -//! benchp1 gen write a synthetic .sup: every second one display set -//! shows a 64x32 object, 0.8 s later a clear set follows -//! (2 display sets per second, 90 kHz pts). -//! benchp1 decode [reps] decode the whole file `reps` times (default 5) with a -//! fresh decoder each time; print the best time, MB/s, the -//! rendered frame count and the stream duration from the pts. -//! -//! The generator uses the same segment layout as the crate's tests (`tests/fuzz_regressions.rs`). -//! ffmpeg has no PGS encoder, so this is the input source for the row. -use std::hint::black_box; -use std::time::Instant; - -use ec_pgs::{PgsDecoder, SEG_END, SEG_ODS, SEG_PCS, SEG_PDS}; - -fn segment(pts: u32, kind: u8, body: &[u8]) -> Vec { - let mut out = b"PG".to_vec(); - out.extend_from_slice(&pts.to_be_bytes()); - out.extend_from_slice(&pts.to_be_bytes()); - out.push(kind); - out.extend_from_slice(&(body.len() as u16).to_be_bytes()); - out.extend_from_slice(body); - out -} - -/// A 1920x1080 epoch-start composition with `objects` placed objects (0 or 1). -fn pcs(pts: u32, x: u16, y: u16, objects: u8) -> Vec { - let mut body = vec![0x07, 0x80, 0x04, 0x38, 0x10, 0, 0, 0x80, 0, 0, objects]; - if objects == 1 { - body.extend_from_slice(&[0, 0, 0, 0]); - body.extend_from_slice(&x.to_be_bytes()); - body.extend_from_slice(&y.to_be_bytes()); - } - segment(pts, SEG_PCS, &body) -} - -/// Palette entry 1 opaque white. -fn pds(pts: u32) -> Vec { - segment(pts, SEG_PDS, &[0, 0, 1, 235, 128, 128, 255]) -} - -/// One 64x32 object, RLE: each row is 64 pixels of colour 1 then an end-of-line code. -fn ods(pts: u32) -> Vec { - let (w, h) = (64u16, 32u16); - let mut rle = Vec::new(); - for _ in 0..h { - rle.extend(std::iter::repeat_n(1u8, w as usize)); - rle.extend_from_slice(&[0, 0]); - } - let mut body = vec![0, 0, 0, 0xC0]; - body.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]); - body.extend_from_slice(&w.to_be_bytes()); - body.extend_from_slice(&h.to_be_bytes()); - body.extend_from_slice(&rle); - segment(pts, SEG_ODS, &body) -} - -fn generate(path: &str, seconds: u32) { - let mut out = Vec::new(); - for s in 0..seconds { - let t = s * 90_000; - let x = ((s * 37) % 1800) as u16; - let y = ((s * 19) % 1000) as u16; - out.extend(pcs(t, x, y, 1)); - out.extend(pds(t)); - out.extend(ods(t)); - out.extend(segment(t, SEG_END, &[])); - let c = t + 72_000; - out.extend(pcs(c, 0, 0, 0)); - out.extend(segment(c, SEG_END, &[])); - } - std::fs::write(path, &out).expect("write sup"); - println!("wrote {path} bytes={} display_sets={}", out.len(), 2 * seconds); -} - -/// (segment count, the last segment's pts in seconds), walking the segment headers. -fn scan(bytes: &[u8]) -> (usize, f64) { - let mut pos = 0; - let mut last = 0u32; - let mut segments = 0; - while pos + 13 <= bytes.len() { - last = u32::from_be_bytes(bytes[pos + 2..pos + 6].try_into().unwrap()); - let size = u16::from_be_bytes([bytes[pos + 11], bytes[pos + 12]]) as usize; - pos += 13 + size; - segments += 1; - } - (segments, f64::from(last) / 90_000.0) -} - -/// One full decode with a fresh decoder: (rendered frames, push errors). The file is fed one -/// segment at a time and the finished frames are dropped after each push, as a streaming reader -/// would. A full 1920x1080 canvas is about 8 MB, so draining per segment keeps the decoder's -/// output queue at most one frame deep. -fn decode_once(bytes: &[u8]) -> (usize, usize) { - let mut d = PgsDecoder::new(); - let (mut frames, mut errors) = (0, 0); - let mut pos = 0; - while pos + 13 <= bytes.len() { - let size = u16::from_be_bytes([bytes[pos + 11], bytes[pos + 12]]) as usize; - let end = (pos + 13 + size).min(bytes.len()); - if d.push(black_box(&bytes[pos..end])).is_err() { - errors += 1; - } - pos = end; - while let Some(f) = d.take_frame() { - frames += 1; - black_box(f); - } - } - (frames, errors) -} - -fn decode(path: &str, reps: usize) { - let bytes = std::fs::read(path).expect("read sup"); - let (frames, errors) = decode_once(&bytes); - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - black_box(decode_once(black_box(&bytes))); - best = best.min(t.elapsed().as_secs_f64()); - } - let (segments, dur) = scan(&bytes); - println!( - "bytes={} segments={segments} frames={frames} push_errors={errors} duration_s={dur:.1} best_decode_s={best:.4} mb_s={:.2} reps={reps}", - bytes.len(), - bytes.len() as f64 / best / 1e6 - ); -} - -fn main() { - let args: Vec = std::env::args().collect(); - match args.get(1).map(String::as_str) { - Some("gen") => generate(&args[2], args[3].parse().expect("seconds")), - Some("decode") => decode(&args[2], args.get(3).map_or(5, |s| s.parse().expect("reps"))), - _ => panic!("usage: benchp1 gen | decode [reps]"), - } -} diff --git a/crates/ec-pgs/src/lib.rs b/crates/ec-pgs/src/lib.rs index 85c41b33..55880f33 100644 --- a/crates/ec-pgs/src/lib.rs +++ b/crates/ec-pgs/src/lib.rs @@ -519,10 +519,6 @@ impl Decoder for PgsDecoder { } } -/// A PGS decoder as the family's registry hands one out. -pub fn make_decoder(_params: &CodecParameters) -> Result> { - Ok(Box::new(PgsDecoder::new())) -} /// One palette entry: BT.601 Y'CbCr with straight alpha, the way a disc writes /// it, into RGBA. diff --git a/crates/ec-pgs/tests/open_media.rs b/crates/ec-pgs/tests/open_media.rs new file mode 100644 index 00000000..f48b8b67 --- /dev/null +++ b/crates/ec-pgs/tests/open_media.rs @@ -0,0 +1,54 @@ +fn fixture(rel: &str) -> Vec { + std::fs::read(ec_testkit::fixture(rel)).unwrap() +} + +#[test] +fn a_real_pgs_stream_decodes_to_plausible_bitmaps() { + let bytes = fixture("open/fate/sub/pgs_sub.sup"); + let mut decoder = ec_pgs::PgsDecoder::new(); + decoder.push(&bytes).unwrap(); + let mut frames = 0; + let mut painted = 0; + let mut coverage_max = 0.0f64; + while let Some(frame) = decoder.take_frame() { + frames += 1; + let (w, h) = (frame.width as usize, frame.height as usize); + let stride = frame.planes[0].stride; + assert_eq!(stride, w * 4); + let opaque = frame.planes[0] + .data + .as_chunks::<4>() + .0 + .iter() + .filter(|p| p[3] > 0) + .count(); + if opaque == 0 { + continue; + } + painted += 1; + let coverage = opaque as f64 / (w * h) as f64; + coverage_max = coverage_max.max(coverage); + assert!( + coverage > 0.000_1 && coverage < 0.25, + "display set {frames} covers {:.3}% of the canvas", + coverage * 100.0 + ); + let rows = (0..h) + .filter(|y| { + frame.planes[0].data[y * stride..(y + 1) * stride] + .as_chunks::<4>() + .0 + .iter() + .any(|p| p[3] > 0) + }) + .count(); + assert!(rows > 4, "display set {frames} paints {rows} rows"); + } + assert_eq!(frames, 1, "ffprobe reads one subtitle frame"); + assert!( + painted * 3 > frames, + "{painted} of {frames} display sets painted anything" + ); + assert!(coverage_max < 0.25, "widest cue covers {coverage_max}"); + eprintln!("pgs: {frames} display sets, {painted} painted, widest {coverage_max:.4}"); +} diff --git a/crates/ec-subs/Cargo.toml b/crates/ec-subs/Cargo.toml index e839971a..29e72bdb 100644 --- a/crates/ec-subs/Cargo.toml +++ b/crates/ec-subs/Cargo.toml @@ -11,5 +11,3 @@ ec-core.workspace = true [dev-dependencies] ec-testkit.workspace = true -ec-ass = { path = "../ec-ass", version = "0.1.0" } -ec-pgs = { path = "../ec-pgs", version = "0.1.0" } diff --git a/crates/ec-subs/examples/benchp1.rs b/crates/ec-subs/examples/benchp1.rs deleted file mode 100644 index 671f8fa8..00000000 --- a/crates/ec-subs/examples/benchp1.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! benchp1: SubRip and WebVTT parse throughput for lanes/bench.md ("lane benchp1"). -//! -//! usage: benchp1 [reps] -//! -//! Parses the whole file `reps` times (default 5). Each timed run repeats the parse until it -//! takes at least 0.2 s, so the per-parse time is not timer noise. Prints the best per-parse -//! time, the throughput in MB/s and the cue count of the parsed track (checked against ffprobe). -use std::hint::black_box; -use std::time::Instant; - -fn main() { - let args: Vec = std::env::args().collect(); - let kind = args.get(1).map(String::as_str).unwrap_or(""); - let bytes = std::fs::read(&args[2]).expect("read subtitle file"); - let reps: usize = args.get(3).map_or(5, |s| s.parse().expect("reps")); - let parse = |b: &[u8]| match kind { - "srt" => ec_subs::srt::parse(b), - "vtt" => ec_subs::webvtt::parse(b), - _ => panic!("kind must be srt or vtt"), - }; - - let first = parse(&bytes).expect("parse"); - let cues = first.cues.len(); - let skipped = first.skipped; - let t0 = Instant::now(); - black_box(parse(black_box(&bytes)).expect("parse")); - let one = t0.elapsed().as_secs_f64().max(1e-6); - let inner = ((0.2 / one).ceil() as usize).max(1); - - let mut best = f64::MAX; - for _ in 0..reps { - let t = Instant::now(); - for _ in 0..inner { - black_box(parse(black_box(&bytes)).expect("parse")); - } - best = best.min(t.elapsed().as_secs_f64() / inner as f64); - } - let mb_s = bytes.len() as f64 / best / 1e6; - println!( - "kind={kind} bytes={} cues={cues} skipped={skipped} best_parse_ms={:.3} mb_s={mb_s:.2} reps={reps} inner={inner}", - bytes.len(), - best * 1e3 - ); -} diff --git a/crates/ec-subs/tests/open_media.rs b/crates/ec-subs/tests/open_media.rs index 177eb647..84e24f3d 100644 --- a/crates/ec-subs/tests/open_media.rs +++ b/crates/ec-subs/tests/open_media.rs @@ -26,86 +26,3 @@ fn a_real_subrip_track_parses_whole() { .all(|w| w[1].start_us >= w[0].start_us) ); } - -#[test] -fn a_real_ass_script_parses_whole() { - let bytes = fixture("subs/tos-en.ass"); - let track = ec_ass::parse(&bytes).unwrap(); - assert_eq!(track.source, Some(SourceFormat::AssOrSsa)); - assert!(!track.styles.is_empty(), "a script declares styles"); - assert_eq!(track.cues.len(), 76, "ffmpeg reads 76 cues"); - assert_eq!(track.skipped, 0, "a whole script should have no torn rows"); - let with_text = track - .cues - .iter() - .filter(|c| !plain_text(&c.segments).trim().is_empty()) - .count(); - assert!( - with_text * 10 > track.cues.len() * 9, - "{with_text} of {}", - track.cues.len() - ); - for cue in &track.cues { - assert!(cue.end_us >= cue.start_us); - if let Some(style) = &cue.style_ref { - assert!( - track.style(style).is_some(), - "cue names undeclared style {style:?}" - ); - } - let text = plain_text(&cue.segments); - assert!(!text.contains("{\\"), "override tag in text: {text:?}"); - } - assert!(track.extradata.windows(8).any(|w| w == b"[Events]")); -} - -#[test] -fn a_real_pgs_stream_decodes_to_plausible_bitmaps() { - let bytes = fixture("open/fate/sub/pgs_sub.sup"); - let mut decoder = ec_pgs::PgsDecoder::new(); - decoder.push(&bytes).unwrap(); - let mut frames = 0; - let mut painted = 0; - let mut coverage_max = 0.0f64; - while let Some(frame) = decoder.take_frame() { - frames += 1; - let (w, h) = (frame.width as usize, frame.height as usize); - let stride = frame.planes[0].stride; - assert_eq!(stride, w * 4); - let opaque = frame.planes[0] - .data - .as_chunks::<4>() - .0 - .iter() - .filter(|p| p[3] > 0) - .count(); - if opaque == 0 { - continue; - } - painted += 1; - let coverage = opaque as f64 / (w * h) as f64; - coverage_max = coverage_max.max(coverage); - assert!( - coverage > 0.000_1 && coverage < 0.25, - "display set {frames} covers {:.3}% of the canvas", - coverage * 100.0 - ); - let rows = (0..h) - .filter(|y| { - frame.planes[0].data[y * stride..(y + 1) * stride] - .as_chunks::<4>() - .0 - .iter() - .any(|p| p[3] > 0) - }) - .count(); - assert!(rows > 4, "display set {frames} paints {rows} rows"); - } - assert_eq!(frames, 1, "ffprobe reads one subtitle frame"); - assert!( - painted * 3 > frames, - "{painted} of {frames} display sets painted anything" - ); - assert!(coverage_max < 0.25, "widest cue covers {coverage_max}"); - eprintln!("pgs: {frames} display sets, {painted} painted, widest {coverage_max:.4}"); -}