diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 4378977..7336693 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -771,6 +771,31 @@ impl Mp4Demuxer { self.next_sample = chosen; i64::from(chosen) - i64::from(self.first_sample) } + + /// Every frame a decoder may be started from, by the index this engine + /// counts a source's frames in -- the sample table's own answer, which is + /// why an mp4 costs no walk to ask ([`sync_points`]). A track with no `stss` + /// box is every frame, which is what the box's absence means. + fn sync_frames(&self) -> Vec { + let frames = self.sample_count.saturating_sub(self.first_sample - 1); + if self.sync_samples.is_empty() { + return (0..frames).collect(); + } + // With composition offsets in play a sample id is not a frame index, and + // the display-order table beside it is the one that answers -- the split + // [`Self::seek_to_sync_at_or_before`] makes, for its reason. + if !self.sync_display.is_empty() { + return self + .sync_display + .iter() + .filter_map(|&(display, _)| display.checked_sub(self.first_display)) + .collect(); + } + self.sync_samples + .iter() + .filter_map(|&id| id.checked_sub(self.first_sample)) + .collect() + } } /// One Matroska block of an indexed track: where its bytes are, whether a @@ -1504,15 +1529,18 @@ pub struct CodedBlock<'a> { /// ([`crate::export::planned_seats`] is the same question asked of a whole /// timeline). /// -/// Empty for anything that is not Matroska, which is exactly the set of files -/// the copy path refuses anyway, and for a file whose clusters cannot be walked. +/// Empty for a file that will not open, and for a Matroska one whose clusters +/// cannot be walked. /// -/// Costs that walk, once per file (6.7 s on a 12.9 GB film, then a sidecar read -/// of a few milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render -/// thread. +/// An mp4 answers off its `stss` table for nothing; Matroska costs the walk, +/// once per file (6.7 s on a 12.9 GB film, then a sidecar read of a few +/// milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render thread. pub fn sync_points(path: &Path) -> Vec { if !is_matroska(path) { - return Vec::new(); + return match Demuxer::open(path) { + Ok((_, Demuxer::Mp4(mp4))) => mp4.sync_frames(), + _ => Vec::new(), + }; } let Ok((_, Demuxer::Mkv(mut demuxer))) = Demuxer::open(path) else { return Vec::new(); @@ -2839,7 +2867,11 @@ impl IndexKey { /// picture track) and the directory is the user's own cache to delete, but a /// size-capped LRU sweep at open is the upgrade path if it ever matters. fn sidecar(&self) -> Option { - let dir = index_dir(std::env::var_os("XDG_CACHE_HOME"), std::env::var_os("HOME"))?; + let dir = cache_dir( + std::env::var_os("XDG_CACHE_HOME"), + std::env::var_os("HOME"), + "mkvindex", + )?; Some(dir.join(format!( "{:016x}-{}.idx", fnv1a(self.path.as_os_str().as_encoded_bytes()), @@ -2848,25 +2880,31 @@ impl IndexKey { } } -/// The path rule, with the environment handed in so it can be checked, as -/// `keymap::config_path_in` is on the config side. An empty `XDG_CACHE_HOME` is -/// one the spec says to ignore; with no `HOME` either there is nowhere to put a -/// cache, and `None` -- always walk -- beats littering the working directory. -fn index_dir(xdg: Option, home: Option) -> Option { +/// The path rule for one of this engine's cache directories -- `sub` names +/// which (`mkvindex` here, `proxies` for [`crate::proxy`]) -- with the +/// environment handed in so it can be checked, as `keymap::config_path_in` is +/// on the config side. An empty `XDG_CACHE_HOME` is one the spec says to +/// ignore; with no `HOME` either there is nowhere to put a cache, and `None` -- +/// always walk -- beats littering the working directory. +pub(crate) fn cache_dir( + xdg: Option, + home: Option, + sub: &str, +) -> Option { xdg.filter(|v| !v.is_empty()) .map(PathBuf::from) .or_else(|| { home.filter(|v| !v.is_empty()) .map(|h| PathBuf::from(h).join(".cache")) }) - .map(|dir| dir.join("edith").join("mkvindex")) + .map(|dir| dir.join("edith").join(sub)) } /// FNV-1a, 64-bit: what names a sidecar and what checks it. Not a cryptographic /// hash and not asked to be -- nothing here is adversarial. It is the guard that /// turns a half-written or scrambled file into a miss; a *name* collision is /// caught by the key inside the file, which is compared field by field. -fn fnv1a(bytes: &[u8]) -> u64 { +pub(crate) fn fnv1a(bytes: &[u8]) -> u64 { let mut hash = 0xcbf2_9ce4_8422_2325u64; for &b in bytes { hash ^= u64::from(b); @@ -4362,7 +4400,7 @@ mod tests { #[test] fn the_index_directory_follows_xdg() { let dir = |xdg: Option<&str>, home: Option<&str>| { - index_dir(xdg.map(OsString::from), home.map(OsString::from)) + cache_dir(xdg.map(OsString::from), home.map(OsString::from), "mkvindex") }; assert_eq!( dir(Some("/x/cache"), Some("/home/u")), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index daa130b..b06091f 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -85,14 +85,14 @@ use crate::tonemap::{self, ToneMapper}; /// Progress is reported in permille: an atomic integer the render loop can read /// without a lock, fine enough for any progress bar. -const PROGRESS_SCALE: u32 = 1_000; +pub(crate) const PROGRESS_SCALE: u32 = 1_000; /// The head of the bar the *sound* owns, before a picture is written at all. /// The mix is decoded, encoded and measured before the muxer exists ([`run`] /// says why), and on a feature film that is a minute or two in which a bar /// pinned at zero is the only thing on screen -- which reads as an export that /// has hung. Small, because the picture is still nearly all of the work. -const AUDIO_BAND: u32 = PROGRESS_SCALE / 20; +pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20; /// Where the bar stands with `done` of `total` pictures written: the sound's /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is @@ -300,6 +300,29 @@ pub struct ExportSettings { /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has /// no such ceiling. pub subtitles: Vec, + /// Code every picture as a key frame a decoder may be started from: no + /// frame references another, the file is an intraframe master in the shape + /// of ProRes, and a seek to any frame at all is one decode. + /// + /// Bigger files for that, so it is off for delivery and on for the + /// stand-ins [`crate::proxy`] makes, which exist precisely to be seeked + /// through. The HEVC seats are intra-only whatever this says + /// ([`Enc::open_hevc`]); this is the H.264 pair's switch. + pub intra_only: bool, + /// Write the picture in the space its **source** declares -- no tone map to + /// SDR, no matrix conversion -- and tag the file with it, instead of + /// converting everything into the space the output height implies. + /// + /// For a preview file and nothing else ([`crate::proxy`]): it makes the + /// stand-in a smaller copy of the film rather than a rendition of it, so + /// the screen tone-maps it live with whatever preset the project is set to + /// -- and it takes the per-frame conversion off the *source's* full + /// resolution, which on a 4K HDR film was 48 ms a frame and the whole of a + /// proxy's cost (measured 2026-08-13). + /// + /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for + /// this editor to read back, not one to hand anybody. + pub keep_source_colour: bool, } struct Shared { @@ -1665,6 +1688,16 @@ fn run( settings: &ExportSettings, ) -> crate::Result<()> { let total = project.timeline_frames(); + // Only the mp4 pair carries a colour of its own back out + // ([`write_video`] tags it there), so asking any other container for a + // source-space file would write pictures one space and a header another. + if settings.keep_source_colour && settings.format != Format::Mp4 { + return Err(format!( + "{} cannot be written in its source's colour space", + settings.format.name() + ) + .into()); + } let sources = project.sources(); // The picture's decision first, before a sample of sound is touched: it is // the answer that decides what the whole export *is*, it costs one header @@ -1767,14 +1800,24 @@ fn run( let tone: Vec> = rates .iter() .map(|(_, color, peak)| match color.transfer { + // A preview file keeps the film's own curve and is tone-mapped when + // it is *shown* ([`ExportSettings::keep_source_colour`]), which is + // both cheaper and the only way the preset can still be changed + // after the stand-in was made. + _ if settings.keep_source_colour => None, Transfer::Sdr => None, Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)), Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)), }) .collect(); // ...and the one space they are all written in, the same rule a reader with - // no tags to read would apply to this file's height. - let out_color = ColorDescription::output(meta.height); + // no tags to read would apply to this file's height -- or, for a preview + // file, the source's own, which is what makes every remap below the + // identity and the file's `colr` box its film's. + let out_color = match settings.keep_source_colour { + true => meta.color, + false => ColorDescription::output(meta.height), + }; let mut encoder = Enc::open(meta, settings)?; // What this file is really being written by, for a progress line to name. @@ -1938,7 +1981,8 @@ fn run( // and faster, more when the clip is slowed -- the picture is already // graded and placed, so a held frame costs an encode and no decode. for _ in 0..repeats { - if let Some((au, key)) = encoder.encode(y, u, v, width, height)? { + if let Some((au, key)) = encoder.encode(y, u, v, width, height, settings.intra_only)? + { write_video( &mut muxer, out, @@ -2597,6 +2641,12 @@ fn write_video( )?)) else { unreachable!("just inserted an mp4 muxer") }; + // A file written in its source's own space says so, rather than + // claiming the space its height would imply + // ([`ExportSettings::keep_source_colour`]). + if settings.keep_source_colour { + mp4.set_colour(meta.color); + } mp4 } }; @@ -2730,8 +2780,13 @@ impl Enc { cfg.framerate = meta.frame_rate as f32; cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; // Two seconds between key frames, and no B-frames on either path: the - // muxer times everything by duration alone, which reordering would break. - cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32; + // muxer times everything by duration alone, which reordering would + // break. A proxy asks for one frame a GOP, which is every frame its own + // starting point ([`ExportSettings::intra_only`]). + cfg.gop_size = match settings.intra_only { + true => 1, + false => (meta.frame_rate * 2.0).round().max(1.0) as u32, + }; cfg.bframes = 0; // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same // bitrate, so Fast is what a fallback should be. @@ -2893,6 +2948,7 @@ impl Enc { v: &[u8], width: u32, height: u32, + intra: bool, ) -> crate::Result> { match self { Self::Av1Hw(hw) => { @@ -2942,9 +2998,13 @@ impl Enc { // frame -- which is what an intraframe master means. Ok(pop_hevc(hevc)) } + // A key frame is asked for on every picture where the file is an + // intraframe one, and the flag says what was asked: the mp4 muxer + // reads its own sync marks off the IDR slices either way, so this + // is what a Matroska one would be told. Self::Hw(hw) => Ok(hw - .encode(y, u, v, width, height, false)? - .map(|au| (au, false))), + .encode(y, u, v, width, height, intra)? + .map(|au| (au, intra))), Self::Sw { encoder, au, .. } => { let frame = YuvFrame { width: width as usize, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c836998..711ede7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,6 +17,7 @@ pub mod limiter; pub mod mux; pub mod playback; pub mod project; +pub mod proxy; pub mod real_library; pub mod scale; pub mod scratch; diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index e84df68..1c68155 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -308,6 +308,16 @@ impl Mp4Muxer { }) } + /// Says what this file's samples mean, where that is *not* the rule the + /// height implies -- a picture written in its source's own space rather + /// than converted into the output one ([`crate::proxy`] is why: a stand-in + /// carries the film's colour and lets the screen convert it, once, at + /// preview size). The box is written when the file is finished, so this may + /// be said any time before then. + pub fn set_colour(&mut self, colour: ColorDescription) { + self.colr = colr_nclx(colour); + } + /// One coded picture, Annex-B framed. Parameter sets inside it are dropped /// (they are already in `avcC`); an IDR slice marks the sample as a sync point. pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> { diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs new file mode 100644 index 0000000..d378321 --- /dev/null +++ b/crates/engine/src/proxy.rs @@ -0,0 +1,325 @@ +//! Small stand-ins for big files: a half-size, every-frame-a-keyframe H.264 +//! copy of a source, kept in the user's cache and played instead of the +//! original while the cut is being made. +//! +//! Why they exist at all: a 4K HEVC film decodes at a fraction of realtime on +//! this machine, so scrubbing it is a slideshow and every seek is a wait. A +//! proxy is the same film at 1280 on its long edge, coded so that **every frame +//! is a random-access point** -- which is what makes a seek land on the frame +//! that was asked for instead of on the nearest one a decoder can start from, +//! and what takes the whole open-GOP class of seek faults off the table by +//! construction. +//! +//! Three rules, and they are the whole contract: +//! +//! - **Picture only.** No sound is coded into a proxy. The mix always comes off +//! the original file ([`crate::PlaybackSession`] opens audio by its own path, +//! which this module never touches), so nothing a listener hears has been +//! through a second encoder. +//! - **Never exported.** [`crate::export`] reads the project's own sources and +//! knows nothing of this module. Delivery is the original, always. +//! - **Derived, never authoritative.** A proxy is named after the source's +//! path, length and modification time ([`path_for`]), so a re-encoded or +//! re-cut original simply misses the cache and a stale proxy can never be +//! found. Deleting the cache directory costs time and nothing else. +//! +//! Generation is [`crate::export`]'s own decode -> scale -> encode walk, given +//! a one-clip project and a smaller canvas: the hardware seat where the GPU has +//! one, the software encoder where it does not, the same progress and the same +//! cancel a file export has ([`Job`]). + +use std::path::{Path, PathBuf}; +use std::time::UNIX_EPOCH; + +use crate::demux::{Codec, Demuxer, VideoMeta}; +use crate::export::{ExportHandle, ExportSettings, Format}; +use crate::project::{Clip, LaneKind, Project, Source, Speed}; +use crate::scale::FitPolicy; + +/// The long edge of a proxy picture, in samples: 1280, so a 4K source loses +/// nine tenths of its samples and a 1080p one a little over half. Chosen as +/// what a cut can be judged on at editing size, in the neighbourhood of every +/// shipped proxy preset (Resolve's half-res, kdenlive's 640/1000-wide +/// defaults). +pub const LONG_EDGE: u32 = 1280; + +/// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate +/// rule at three times the number: every frame being an IDR means no frame +/// borrows anything from its neighbours, so the same picture at the inter rate +/// would be mush -- and mush is not something a cut can be judged on. +const BITS_PER_PIXEL: f64 = 0.3; + +/// Whether this is a file worth standing in for: bigger than 1080p, or coded in +/// something this machine decodes slowly even at 1080p. H.264 at or under 1080p +/// plays natively and a proxy of it would cost time and buy nothing. +pub fn wanted(meta: &VideoMeta) -> bool { + meta.width > 1920 || meta.height > 1080 || matches!(meta.codec, Codec::Hevc | Codec::Av1) +} + +/// The picture a proxy of `meta` is coded at: aspect kept, long edge at most +/// [`LONG_EDGE`], both axes even because 4:2:0 has no half chroma samples. A +/// source already that small is coded at its own size (rounded down to even), +/// which is what makes [`generate`] safe to ask for on anything at all. +pub fn size_for(meta: &VideoMeta) -> (u32, u32) { + let long = meta.width.max(meta.height); + let scale = match long > LONG_EDGE { + true => f64::from(LONG_EDGE) / f64::from(long), + false => 1.0, + }; + let even = |n: u32| (((f64::from(n) * scale).round() as u32) & !1).max(2); + (even(meta.width), even(meta.height)) +} + +/// Where the proxy of `source` lives, whether or not it has been made yet. +/// +/// The name is one hash of the source's canonical path, its length **and** its +/// modification time, so an original that changed at all is a different name +/// and its old proxy is simply never looked at again -- the staleness check is +/// the lookup. `None` where the file cannot be stat'd or the machine has no +/// cache directory at all, which is a source that gets no proxy rather than one +/// littering the working directory. +/// +/// corner-cut: nothing evicts, exactly as the Matroska index cache beside it +/// states. A proxy of a feature film is hundreds of megabytes and a re-encoded +/// source leaves its old one behind; the upgrade path is a size-capped sweep of +/// the directory at open. It is the user's own cache to delete meanwhile. +pub fn path_for(source: &Path) -> Option { + let meta = std::fs::metadata(source).ok()?; + let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) { + Ok(d) => (d.as_secs() as i128, d.subsec_nanos()), + Err(e) => (-(e.duration().as_secs() as i128), e.duration().subsec_nanos()), + }; + let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf()); + let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec(); + bytes.extend_from_slice(&meta.len().to_le_bytes()); + bytes.extend_from_slice(&mtime.0.to_le_bytes()); + bytes.extend_from_slice(&mtime.1.to_le_bytes()); + let dir = crate::demux::cache_dir( + std::env::var_os("XDG_CACHE_HOME"), + std::env::var_os("HOME"), + "proxies", + )?; + Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes)))) +} + +/// The proxy of `source` if one has already been made, `None` otherwise. The +/// answer a session asks at open: a hit costs one `stat`. +pub fn cached(source: &Path) -> Option { + path_for(source).filter(|p| p.is_file()) +} + +/// A proxy being made -- or one that was already there, which is the same thing +/// to whoever is waiting for a path. +/// +/// Poll [`progress`](Job::progress) while [`is_finished`](Job::is_finished) is +/// false and take the [`outcome`](Job::outcome) when it flips, exactly as an +/// export is polled. Dropping the job does not stop the work; +/// [`cancel`](Job::cancel) does. +pub struct Job { + out: PathBuf, + /// `None` for a cache hit: there was nothing to run. + handle: Option, +} + +impl Job { + /// Fraction of the proxy's pictures written, `0.0..=1.0`. A cache hit is + /// done. + /// + /// The band an export's bar reserves for its sound is taken back out: a + /// proxy has no sound, so that band is crossed in the first instant and + /// showing it would be five percent no frame earned. + pub fn progress(&self) -> f32 { + let Some(handle) = &self.handle else { + return 1.0; + }; + let band = crate::export::AUDIO_BAND as f32 / crate::export::PROGRESS_SCALE as f32; + ((handle.progress() - band) / (1.0 - band)).clamp(0.0, 1.0) + } + + /// What is coding this proxy -- the hardware seat or the software one, as + /// the worker really opened it. `None` before the encoder is open, and for + /// a cache hit, which coded nothing. + pub fn encoder(&self) -> Option { + self.handle.as_ref()?.encoders() + } + + /// Asks the worker to stop at its next frame and leave no file behind. The + /// outcome then reports the cancellation as an error. + pub fn cancel(&self) { + if let Some(handle) = &self.handle { + handle.cancel(); + } + } + + pub fn is_finished(&self) -> bool { + self.handle.as_ref().is_none_or(ExportHandle::is_finished) + } + + /// The proxy's path once it is written, once -- taken out of the job, so a + /// caller that already took it sees `None`. `None` while it is still being + /// made. + pub fn outcome(&self) -> Option> { + let Some(handle) = &self.handle else { + return Some(Ok(self.out.clone())); + }; + handle.result().map(|r| r.map(|()| self.out.clone())) + } + + /// Where the proxy will be, whether or not it is there yet -- what a caller + /// names in a log line while the job runs. + pub fn path(&self) -> &Path { + &self.out + } +} + +/// Starts making the proxy of `source`, or hands back the one already in the +/// cache. Errors are the ones that happen before a worker exists -- a file with +/// no picture in it, nowhere to put a cache -- and everything after them comes +/// back through [`Job::outcome`], so a caller has two places to look and not +/// twenty. +pub fn generate(source: &Path) -> crate::Result { + let out = path_for(source).ok_or("no cache directory to keep a proxy in")?; + if out.is_file() { + return Ok(Job { out, handle: None }); + } + // The source's own header: its rate and length are the proxy's (a stand-in + // that ran at another rate or stopped early would put every cut on another + // frame), and only its picture size changes. + let (meta, _) = Demuxer::open(source)?; + let (width, height) = size_for(&meta); + if let Some(dir) = out.parent() { + std::fs::create_dir_all(dir)?; + } + // One video lane, one clip, the whole file -- and *no* audio lane, which is + // what makes the proxy picture-only: the export walk codes the lanes it is + // given and there is no sound among them. + let clip = Clip { + start: 0, + in_frame: 0, + out_frame: meta.frame_count.max(1), + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let project = Project::from_parts( + vec![Source::new(source, 0)], + vec![(LaneKind::Video, vec![clip])], + Vec::new(), + Vec::new(), + )?; + let bitrate = + (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64; + let handle = crate::export::start( + project, + VideoMeta { + width, + height, + ..meta + }, + &out, + &ExportSettings { + format: Format::Mp4, + // The whole point: every frame its own random-access point. + intra_only: true, + // ...and the film's own colour, carried rather than converted: the + // screen tone-maps the stand-in exactly as it tone-maps the film, + // live and at preview size. + keep_source_colour: true, + bitrate: Some(bitrate), + ..Default::default() + }, + ); + Ok(Job { + out, + handle: Some(handle), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::colorspace::ColorDescription; + + fn meta(width: u32, height: u32, codec: Codec) -> VideoMeta { + VideoMeta { + width, + height, + frame_rate: 24.0, + frame_count: 240, + codec, + color: ColorDescription::default(), + } + } + + /// What a proxy is *for*: the files this machine cannot play at speed. + #[test] + fn only_the_files_that_need_one_get_one() { + assert!(wanted(&meta(3840, 2160, Codec::Hevc)), "4K HEVC"); + assert!(wanted(&meta(3840, 2160, Codec::H264)), "4K H.264"); + assert!(wanted(&meta(1920, 1080, Codec::Hevc)), "1080p HEVC"); + assert!(wanted(&meta(1920, 1080, Codec::Av1)), "1080p AV1"); + assert!( + !wanted(&meta(1920, 1080, Codec::H264)), + "1080p H.264 plays natively" + ); + assert!(!wanted(&meta(1280, 720, Codec::H264)), "720p H.264"); + } + + /// Aspect kept, long edge capped, both axes even -- and a small source left + /// alone rather than blown up. + #[test] + fn a_proxy_is_the_same_shape_at_a_smaller_size() { + assert_eq!(size_for(&meta(3840, 2160, Codec::Hevc)), (1280, 720)); + assert_eq!(size_for(&meta(1920, 1080, Codec::Hevc)), (1280, 720)); + // A portrait source is capped on *its* long edge, which is the height. + assert_eq!(size_for(&meta(1080, 1920, Codec::Hevc)), (720, 1280)); + // 1916x1080 (a real film's cropped width): even both ways, and the + // aspect it really has rather than the 16:9 it nearly has. + let (w, h) = size_for(&meta(1916, 1080, Codec::H264)); + assert_eq!((w, h), (1280, 722), "cropped-width 1080p"); + assert_eq!(w % 2, 0); + assert_eq!(h % 2, 0); + assert!( + (f64::from(w) / f64::from(h) - 1916. / 1080.).abs() < 0.005, + "{w}x{h} is the source's shape" + ); + assert_eq!( + size_for(&meta(640, 360, Codec::H264)), + (640, 360), + "already small: its own size, never upscaled" + ); + assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero"); + } + + /// The staleness rule *is* the name: touch the source and the old proxy is + /// unreachable rather than wrong. + #[test] + fn a_changed_source_names_another_proxy() { + let dir = crate::scratch::Scratch::dir("proxy-key"); + let file = dir.join("a.mp4"); + std::fs::write(&file, b"one").expect("write"); + let first = path_for(&file).expect("a key"); + assert_eq!(path_for(&file).as_ref(), Some(&first), "stable for a file"); + // Same length, later time: a re-encode that happened to land on the + // same byte count is still another file. + std::fs::write(&file, b"two").expect("rewrite"); + filetime_bump(&file); + assert_ne!(path_for(&file), Some(first), "touched: another name"); + assert_eq!(cached(&file), None, "nothing written, nothing cached"); + } + + /// `std::fs` has no set-mtime, and a rewrite inside the same nanosecond is + /// possible on a fast machine -- so the stamp is moved by hand through the + /// one door that does it without a dependency. + fn filetime_bump(path: &Path) { + let now = std::time::SystemTime::now() + std::time::Duration::from_secs(10); + let file = std::fs::File::options() + .write(true) + .open(path) + .expect("open"); + file.set_modified(now).expect("set mtime"); + } +} diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 1a0b518..c59aeb7 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -859,3 +859,160 @@ fn exports_a_gapped_timeline_as_black_and_silence() { std::fs::remove_file(&out).unwrap(); } + +/// The stand-in a proxy really is, in one pass over the fixture: a picture-only +/// file whose *every* frame is a decoder's starting point, playable through the +/// ordinary session, and found in the cache the second time it is asked for. +/// +/// Software seat, like every default test here ([`pin_software`]) -- what the +/// hardware one buys is speed, and that is the ignored test below. +#[test] +fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() { + pin_software(); + let source = asset("test_av.mp4"); + let out = engine::proxy::path_for(&source).expect("a cache directory"); + // A proxy left by an earlier run would make this test assert about a file + // it did not write -- and the cache-hit half below would be the only half + // that ran. + let _ = std::fs::remove_file(&out); + + let job = engine::proxy::generate(&source).expect("start the proxy"); + assert_eq!(job.path(), out, "the job writes where the key says"); + let started = Instant::now(); + while !job.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(300), + "the proxy did not finish: {:.0}% in", + job.progress() * 100.0 + ); + std::thread::sleep(Duration::from_millis(20)); + } + let made = job + .outcome() + .expect("a finished job has an outcome") + .expect("the proxy"); + assert_eq!(made, out); + assert_eq!(job.progress(), 1.0, "finished at full progress"); + + let (source_meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture"); + let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy"); + assert_eq!( + (meta.width, meta.height), + engine::proxy::size_for(&source_meta), + "the proxy is coded at the size the rule picked" + ); + assert_eq!(meta.codec, engine::Codec::H264, "proxies are H.264"); + assert_eq!( + meta.frame_count, source_meta.frame_count, + "a stand-in as long as the film, or every cut lands elsewhere" + ); + + // The whole point: every frame its own random-access point, so a seek never + // has to start earlier than it was asked to. + let syncs = engine::demux::sync_points(&made); + assert_eq!( + syncs.len() as u32, + meta.frame_count, + "{} of {} frames are starting points -- the proxy is not intra-only", + syncs.len(), + meta.frame_count + ); + + // ...and no sound in it at all: the mix is the original's, always. + assert!( + engine::AudioSession::open(&made) + .expect("probe the proxy for sound") + .is_none(), + "a proxy carries no audio track" + ); + + // It plays through the ordinary door, which is what substitution needs. + let session = PlaybackSession::open(&made).expect("play the proxy"); + assert_eq!(session.meta().frame_count, source_meta.frame_count); + + // Asked again, it is the file already there: no second encode. + let again = engine::proxy::generate(&source).expect("ask again"); + assert!(again.is_finished(), "a cached proxy is done on the spot"); + assert_eq!( + again.outcome().expect("cached outcome").expect("cached path"), + out + ); + assert_eq!(engine::proxy::cached(&source), Some(out.clone())); + + std::fs::remove_file(&out).expect("clean the cache entry up"); + assert_eq!(engine::proxy::cached(&source), None); +} + +/// A real 4K HEVC film, on the hardware seat: a proxy of it is made **faster +/// than the film plays**, which is the whole promise -- and a cancel stops it +/// dead and leaves nothing behind. +/// +/// Measured over a window rather than to the end: the film is two hours and the +/// number wanted is a rate, not a wall time. +/// +/// ```text +/// cargo build -p engine -p engine-hw --release +/// LD_LIBRARY_PATH=target/release cargo test -p engine --release --test export \ +/// -- --ignored --nocapture --test-threads=1 proxy_of_real_4k +/// ``` +#[test] +#[ignore = "needs the VA-API plugin and a real library"] +fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { + pin_hardware(); + let Some(film) = engine::real_library::film("hevc_4k_hdr") else { + return; + }; + let out = engine::proxy::path_for(&film).expect("a cache directory"); + let _ = std::fs::remove_file(&out); + let (meta, _) = engine::demux::Demuxer::open(&film).expect("open the film"); + let duration = f64::from(meta.frame_count) / meta.frame_rate; + println!( + "film: {}x{} {:.3} fps, {duration:.0}s", + meta.width, meta.height, meta.frame_rate + ); + + let job = engine::proxy::generate(&film).expect("start the proxy"); + let window = Duration::from_secs(60); + let started = Instant::now(); + while started.elapsed() < window && !job.is_finished() { + std::thread::sleep(Duration::from_millis(200)); + } + let elapsed = started.elapsed().as_secs_f64(); + let made = f64::from(job.progress()) * duration; + let seat = job.encoder().unwrap_or_default(); + println!( + "proxy: {made:.0}s of film in {elapsed:.0}s = {:.2}x realtime, seat {seat}", + made / elapsed + ); + // The silent-software trap: a run without the plugin on the path measures + // the fallback and calls it hardware. + assert!( + seat.contains("HW encode"), + "not the hardware seat ({seat}): LD_LIBRARY_PATH must name the plugin" + ); + assert!( + made / elapsed >= 1.0, + "{:.2}x realtime is slower than watching the film", + made / elapsed + ); + + // Cancel stops the reading, and a proxy that was not finished is not left + // lying around under the name a finished one would have. + job.cancel(); + let stopped = Instant::now(); + while !job.is_finished() { + assert!( + stopped.elapsed() < Duration::from_secs(30), + "the proxy did not stop when cancelled" + ); + std::thread::sleep(Duration::from_millis(50)); + } + assert!(job.outcome().expect("an outcome").is_err(), "cancelled"); + assert!( + !out.exists(), + "a cancelled proxy left {} behind", + out.display() + ); + assert!(!part_path(&out).exists(), "a cancelled proxy left its .part"); + assert_eq!(engine::proxy::cached(&film), None); +}