diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 3fc861b..f8e42e5 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -829,6 +829,12 @@ pub struct MkvDemuxer { /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the /// `avcC` beside it, which is that record's H.264 twin. config: Vec, + /// The `CodecPrivate` record verbatim; see [`MkvVideo::private`]. + private: Vec, + /// Nanoseconds a timestamp tick is worth -- `TimestampScale`, a millisecond + /// in every file anything writes. What turns a block's own timestamp into + /// the nanoseconds a copy re-times it by. + timestamp_scale: u64, /// Bytes of the NAL length prefix an HEVC or H.264 block is written with; /// unused by AV1, whose block is one temporal unit and carries no prefixes. nal_length: usize, @@ -942,6 +948,8 @@ impl MkvDemuxer { blocks: Vec::new(), codec: video.codec, config: video.config, + private: video.private, + timestamp_scale: video.timestamp_scale, nal_length: video.nal_length, bit_depth: video.bit_depth, light: video.light, @@ -1399,6 +1407,95 @@ impl MkvDemuxer { // reordered, and never more than the reorder depth out. self.base as i64 } + + /// The picture track's `CodecPrivate` as the file holds it: what a copied + /// track is declared with, so the record and the blocks under it come out of + /// one file rather than two ([`MkvVideo::private`]). + pub fn codec_private(&self) -> &[u8] { + &self.private + } + + /// How many coded blocks the picture track has -- the count + /// [`crate::VideoMeta::frame_count`] is, indexed the same way every seek and + /// every clip in point already indexes it. + /// + /// The track's own count and not the open window's: a file opened off its + /// `Cues` holds ten seconds of blocks and knows the length of all of them + /// ([`Self::count_frames`]), which is the number a clip was cut against. + pub fn block_count(&self) -> usize { + self.frames + } + + /// Whether block `index` is one a decoder may be started from, which is what + /// makes it a place a copy may begin or end. + /// + /// Asks the whole index, because it is asked about any block of the file and + /// a window holds one stretch of it. That is the walk this demuxer otherwise + /// avoids -- paid once per source, by a caller that is about to read every + /// block anyway, and cheap on the second export of the same file + /// ([`Self::complete_index`] and the sidecar under it). A file that cannot be + /// walked answers `false`, which is a copy refused rather than a copy of the + /// wrong bytes. + pub fn is_sync(&mut self, index: usize) -> bool { + if self.complete_index().is_err() { + return false; + } + self.blocks.get(index).is_some_and(|b| b.key) + } + + /// Whether the blocks are the codec's own bytes -- no `ContentEncodings` + /// stripping or compression over them. A copy of anything else would hand + /// the muxer bytes it would have to re-pack, which is no longer a copy. + pub fn plain_blocks(&self) -> bool { + self.unpack == Unpack::None + } + + /// Block `index` exactly as it sits in the file: its bytes, whether it is a + /// sync point and when it is shown, in nanoseconds off the file's own clock. + /// + /// Presentation and not decode: Matroska blocks are stored in decode order + /// and timestamped in display order, so a stream with B-frames hands back + /// timestamps that step backwards -- which is exactly what a copy has to + /// preserve, and why this is not "block index times the frame duration". + /// + /// The bytes are borrowed from the read scratch and live until the next + /// call, as [`Self::next_access_unit`]'s do. + /// + /// `index` is the file's own block number, so this holds the whole index + /// rather than whatever window is open ([`Self::is_sync`] says why, and this + /// is the caller that makes the walk worth it: a copy reads every block). + pub fn coded_block(&mut self, index: usize) -> crate::Result>> { + self.complete_index()?; + let Some(&block) = self.blocks.get(index) else { + return Ok(None); + }; + // The cursor moves with it, so a copy that stops and hands the file back + // to a decoder leaves it where a sequential read would. + self.next = index + 1; + let Self { + file, + scratch, + unpack, + .. + } = self; + scratch.resize(block.len, 0); + read_exact_at(file, block.at, scratch)?; + unpack.frame(scratch)?; + Ok(Some(CodedBlock { + bytes: &self.scratch, + key: block.key, + ts_ns: block.ts * self.timestamp_scale as i64, + })) + } +} + +/// One coded picture as a file holds it, for the export's copy path +/// ([`MkvDemuxer::coded_block`]): the very bytes the muxer writes back out, the +/// sync flag a container states beside them, and when the picture is shown. +pub struct CodedBlock<'a> { + pub bytes: &'a [u8], + pub key: bool, + pub ts_ns: i64, } /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or @@ -1574,6 +1671,13 @@ struct MkvVideo { timestamp_scale: u64, codec: Codec, config: Vec, + /// `CodecPrivate` as the file holds it -- the `hvcC`/`avcC`/`av1C` record + /// itself, before [`parse_hvcc`] and its siblings turn it into the + /// parameter sets `config` carries. Kept because a copy hands the very same + /// record to the muxer ([`MkvDemuxer::codec_private`]): a track written from + /// a re-derived record would declare a stream subtly other than the blocks + /// under it. + private: Vec, nal_length: usize, bit_depth: u8, unpack: Unpack, @@ -2069,6 +2173,8 @@ fn mkv_track_entry( let Some(known) = mkv_codec(&codec) else { return Ok(MkvEntry::OtherVideo(codec)); }; + // The record itself, before any of the arms below reads it apart. + let private = config.clone(); let (codec, nal_length, config, bit_depth) = match known { Codec::Av1 => { let (sets, bit_depth) = parse_av1c(&config)?; @@ -2103,6 +2209,7 @@ fn mkv_track_entry( timestamp_scale, codec, config, + private, nal_length, bit_depth, unpack, diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 873dbf6..4c90ee5 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -9,10 +9,17 @@ //! That makes it an intraframe master in the family of ProRes and DNxHD — large //! files, every frame a cut point — and not a delivery codec. //! -//! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it -//! is impossible — while audio is copied packet for packet wherever a copy can -//! say what the timeline says: a copy is exact, free and never a generation of -//! loss. Where it *cannot* — a second audio lane to mix in, a speeded clip, an +//! Picture and sound are both **copied wherever a copy says exactly what the +//! timeline says** — a copy is exact, free and never a generation of loss. For +//! the sound that is packet for packet ([`copy_audio`]); for the picture it is +//! block for block out of a Matroska source into a Matroska file ([`CopyPlan`]), +//! which is what makes a cut in a two-hour film cost the reading of it rather +//! than the re-encoding of it. The picture's copy is all-or-nothing per export, +//! because a copied span and an encoded one cannot share one track: what it +//! needs of a cut is that it lands on a sync point, and everything else — a +//! grade, a speed, a gap, a source of another size or codec, an mp4 — goes +//! through the encoder exactly as it always did. Where the *sound* cannot be +//! copied — a second audio lane to mix in, a speeded clip, an //! equalized one, a source that is not AAC inside an mp4's own sample table — //! the sound is decoded, mixed and encoded again with `rusty_aac` //! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes @@ -65,9 +72,11 @@ use oxideav_core::Muxer as _; use crate::audio::{AudioMeta, AudioSession}; use crate::colorspace::{ColorDescription, Matrix, Transfer}; -use crate::demux::{Demuxer, VideoMeta}; +use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; -use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; +use crate::mux::{ + AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, +}; use crate::project::{LaneKind, Project, Rate}; use crate::scale::Composer; use crate::subtitle::{Cue, SubtitleTrack}; @@ -893,6 +902,234 @@ fn copy_audio( } } +/// The picture's half of [`copy_audio`]: a Matroska export whose every span is +/// its source's own coded blocks, written back out without a decoder or an +/// encoder anywhere in the path. +/// +/// **When.** A copy is entered only where it says *exactly* what the timeline +/// says, which is the audio gate's rule and not a looser one: the file this +/// export writes is Matroska, the source's codec is the one that file would +/// carry ([`Format::Hevc`] over HEVC, [`Format::Av1`] over AV1), and nothing on +/// the way has touched a sample -- no grade, no speed, no rate conversion, no +/// gap to fill with black, no source of another size to place on the canvas, +/// no `ContentEncodings` packing to undo. Anything else re-encodes exactly as +/// it always did; there is no half-copied file. +/// +/// **All or nothing, per export.** A copied span and an encoded one cannot +/// share one track: this project's encoders write 8-bit SDR streams whose +/// parameter sets are their own, so splicing them into (say) a Main 10 HDR +/// source would change bit depth and colour mid-track, and a container states +/// its configuration record once. So the head and tail fragments of a cut that +/// lands mid-GOP are *not* re-encoded into the copy -- they are what makes the +/// whole export fall back to the encoder. What a copy needs instead is that +/// every span begins on a sync point and ends where the next one begins, which +/// is what a cut placed on a keyframe gives it. +/// +/// **What a cut costs.** An open-GOP source (x265's default) writes leading +/// pictures after a sync point that are shown *before* it and reference the +/// group before it. At the start of a copied region those references are not in +/// the file, so they are dropped -- the picture before the cut is held for those +/// few frames (four at this film's B-depth, a sixth of a second) rather than +/// being written as pictures that cannot decode. The region still starts at the +/// timeline frame it owns, so the sound never drifts. +/// +/// ponytail: mp4 is not copied (its `hvc1` sample entry forbids in-band +/// parameter sets, and the mp4 muxer here writes its sample table from a frame +/// counter), and neither is H.264, which this project only writes into mp4. The +/// upgrade path for both is a sample-table writer that takes explicit +/// timestamps, which is what [`MkvMuxer::write_block`] already is for Matroska. +struct CopyPlan { + /// Every source a region reads, by the index the project names it with; + /// `None` for a source no clip plays from. + sources: Vec>, + regions: Vec, + codec_id: &'static [u8], + /// The `CodecPrivate` every region's source agrees on -- a track is declared + /// once, so two sources that disagree about their parameter sets are not one + /// copy. + private: Vec, + colour: ColorDescription, + width: u32, + height: u32, +} + +/// A run of source blocks copied in one piece: what a cut leaves behind, and +/// what two spans that continue each other in the same file merge back into. +struct CopyRegion { + source: usize, + /// Blocks of that source, in the file's own decode order. + blocks: std::ops::Range, + /// The timeline frame the region's first picture is shown at. + start: u32, +} + +impl CopyPlan { + /// The plan for this timeline, or `None` where anything at all makes a copy + /// say something other than what the timeline says -- in which case the + /// caller encodes, which is what it always did. + fn of(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option { + let (codec_id, codec): (&'static [u8], Codec) = match settings.format { + Format::Hevc => (b"V_MPEGH/ISO/HEVC", Codec::Hevc), + Format::Av1 => (b"V_AV1", Codec::Av1), + _ => return None, + }; + let entries = project.sources(); + let mut sources: Vec> = (0..entries.len()).map(|_| None).collect(); + let mut declared: Option<(Vec, ColorDescription)> = None; + let mut regions: Vec = Vec::new(); + for span in project.composite_spans_from(0) { + // A gap is black frames, which only an encoder makes. + let (source, in_frame) = span.from?; + if !span.speed.is_normal() { + return None; + } + // The grade playback shows, which a copied packet never went + // through. `None` and the identity are the same untouched picture. + if project + .composite_color_at(span.start) + .is_some_and(|params| !params.is_identity()) + { + return None; + } + let path = &entries.get(source)?.path; + if sources.get(source)?.is_none() { + if !crate::demux::is_matroska(path) { + return None; + } + let (source_meta, demuxer) = Demuxer::open(path).ok()?; + let Demuxer::Mkv(demuxer) = demuxer else { + return None; + }; + // The stream this file would carry, at the size and the rate the + // timeline is in: anything else is a picture that has to be + // coded again to become this file's. + if source_meta.codec != codec + || source_meta.width != meta.width + || source_meta.height != meta.height + || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? + != Rate::REAL_TIME + || !demuxer.plain_blocks() + { + return None; + } + // One track, one configuration record and one `Colour`: two + // sources that disagree about either are two streams, and this + // writes one. + let declares = (demuxer.codec_private().to_vec(), source_meta.color); + if declared.get_or_insert(declares.clone()) != &declares { + return None; + } + sources[source] = Some(demuxer); + } + let demuxer = sources.get_mut(source)?.as_mut()?; + // The window this span reads, in the blocks the whole engine counts + // a source's frames in. It has to *be* whole groups of pictures: a + // copy that began between two sync points would hand a decoder + // pictures whose references are not in the file, and one that ended + // between them would drop a reference the pictures before it need. + let (start, end) = (in_frame as usize, in_frame as usize + span.len as usize); + if end > demuxer.block_count() + || !demuxer.is_sync(start) + || (end < demuxer.block_count() && !demuxer.is_sync(end)) + { + return None; + } + // Two spans that continue each other in one file are one region: + // nothing was cut between them, so the leading pictures across that + // boundary still have every reference they need. + match regions.last_mut() { + Some(last) + if last.source == source + && last.blocks.end == start + && last.start + (last.blocks.end - last.blocks.start) as u32 + == span.start => + { + last.blocks.end = end; + } + _ => regions.push(CopyRegion { + source, + blocks: start..end, + start: span.start, + }), + } + } + let (private, colour) = declared?; + Some(Self { + sources, + regions, + codec_id, + private, + colour, + width: meta.width, + height: meta.height, + }) + } + + /// The file itself: one Matroska muxer, every region's blocks through it in + /// the order and at the timing their source states. + fn run( + mut self, + out: &Path, + meta: &VideoMeta, + shared: &Shared, + audio: Option<(&AudioParams, Vec)>, + subs: Vec, + total: u32, + ) -> crate::Result<()> { + let mut muxer = MkvMuxer::create_copy( + out, + &CopyParams { + width: self.width, + height: self.height, + frame_rate: meta.frame_rate, + codec_id: self.codec_id, + codec_private: &self.private, + colour: self.colour, + }, + audio, + subs, + )?; + // Nanoseconds a timeline frame lasts, which is what a region's own + // position on the timeline is measured in. + let frame_ns = 1e9 / meta.frame_rate; + let mut done = 0u32; + for region in &self.regions { + let demuxer = self.sources[region.source] + .as_mut() + .ok_or("a copied region names a source that was never opened")?; + let base = (f64::from(region.start) * frame_ns).round() as i64; + // When the region's first picture is shown on its source's clock; + // everything after it is written that far along from `base`. + let mut origin: Option = None; + for index in region.blocks.clone() { + cancelled(shared)?; + let Some(block) = demuxer.coded_block(index)? else { + break; + }; + let origin = *origin.get_or_insert(block.ts_ns); + // The leading pictures of the group this region opens on: shown + // before it, coded against the group before it, and that group + // is not in this file. Dropped rather than written as pictures + // no decoder can put back together. + if block.ts_ns < origin { + continue; + } + muxer.write_block(block.bytes, block.key, base + block.ts_ns - origin)?; + done += 1; + shared + .progress + .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed); + } + } + // Everything up to here is still cancellable, exactly as the encoded + // path is up to its own `finish`. + cancelled(shared)?; + muxer.finish()?; + shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); + Ok(()) + } +} + /// The same lane, *decoded*: what a packet copy cannot carry comes out here as /// AAC written by this project's own encoder. /// @@ -1013,6 +1250,28 @@ fn run( // so the muxer needs the lot before the first picture is written. let mut subs = export_subtitles(project, meta, settings); + // Before an encoder is opened at all: a timeline nobody has touched, whose + // sources this file can hold as they are, is written by copying their coded + // blocks -- the picture's half of what `copy_audio` just did for the sound, + // and the difference between an export bounded by the *edited* spans and one + // that re-encodes a whole film to change a cut. [`CopyPlan`] states the + // whole rule; anything at all outside it falls through to the walk below. + if let Some(plan) = CopyPlan::of(project, meta, settings) { + eprintln!("export video: copy (source packets)"); + *shared.encoders.lock().unwrap() = Some(format!( + "copy · {}", + audio_label(project, settings.format, sound.is_some(), sound) + )); + return plan.run( + out, + meta, + shared, + audio_params.as_ref().zip(packets.take()), + std::mem::take(&mut subs), + total, + ); + } + // One header parse per source, before any of them is decoded: what rate // each file was shot at against the timeline's ([`Rate`]), which is how the // clip's timeline frames below become frames of the file, and what its diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 6d74083..b9c0f82 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -787,6 +787,31 @@ pub struct HevcParams<'a> { pub hvcc: &'a [u8], } +/// What a *copied* track declares: the source's own codec id and configuration +/// record, in the space its samples are really in. +/// +/// Nothing here is derived from the timeline -- the copy exists precisely +/// because none of it changed -- so the picture keeps the size, the rate, the +/// curve and the parameter sets it was coded with. +pub struct CopyParams<'a> { + pub width: u32, + pub height: u32, + pub frame_rate: f64, + /// The Matroska codec id, `V_MPEGH/ISO/HEVC` or `V_AV1`. + pub codec_id: &'a [u8], + /// `CodecPrivate` as the source holds it ([`crate::demux::MkvDemuxer::codec_private`]). + pub codec_private: &'a [u8], + /// The source's own `Colour`: a copied HDR film leaves as the HDR film it + /// is, because not one of its samples was touched. + /// + /// ponytail: the `MasteringMetadata` and MaxCLL beside it are not carried -- + /// this engine parses them ([`crate::demux::ContentLight`]) but has nowhere + /// to write them yet, so a copied HDR file states its curve and not its + /// grading display. Upgrade path is a `Colour` element written from that + /// same struct. + pub colour: ColorDescription, +} + /// The soft subtitle track a file carries beside the picture: text, timed, still /// text in the file -- a player draws it and a user can turn it off, which is /// what "soft" means and what burning it into the pixels is not. @@ -851,6 +876,11 @@ pub struct MkvMuxer { cluster: Vec, cluster_ts: i64, frames: u64, + /// The latest timestamp any picture was written at. Equal to the frame + /// counter's own for a track this project encoded; for a *copied* one the + /// blocks carry their source's timing and a cut can leave the last picture + /// on screen, so the duration is measured rather than counted. + last_ts: i64, /// The AAC track, if the timeline has sound, and how far it has been /// written. audio: Option, @@ -897,6 +927,7 @@ impl MkvMuxer { video.frame_rate, b"V_AV1", &av1c, + ColorDescription::output(video.height), audio, subs, ) @@ -925,6 +956,39 @@ impl MkvMuxer { video.frame_rate, b"V_MPEGH/ISO/HEVC", video.hvcc, + ColorDescription::output(video.height), + audio, + subs, + ) + } + + /// The same file with a track *copied* out of another one: the source's own + /// codec id and `CodecPrivate`, and its own `Colour` beside them + /// ([`crate::export`]'s copy path). + /// + /// Not [`Self::create_hevc`] with the source's record, because the picture + /// is not this project's own: a copy writes the file the source's samples + /// already are -- an HDR film stays on its PQ curve rather than being + /// declared the SDR the encoders here write -- and the blocks are timed by + /// [`Self::write_block`] off the source's clock rather than by a frame + /// counter, which is the other half of the same statement. + pub fn create_copy( + path: &Path, + video: &CopyParams, + audio: Option<(&AudioParams, Vec)>, + subs: Vec, + ) -> crate::Result { + if video.codec_private.is_empty() { + return Err("the source track carries no CodecPrivate to copy".into()); + } + Self::open( + path, + video.width, + video.height, + video.frame_rate, + video.codec_id, + video.codec_private, + video.colour, audio, subs, ) @@ -938,6 +1002,7 @@ impl MkvMuxer { frame_rate: f64, codec_id: &[u8], codec_private: &[u8], + colour: ColorDescription, audio: Option<(&AudioParams, Vec)>, subs: Vec, ) -> crate::Result { @@ -1004,11 +1069,11 @@ impl MkvMuxer { uint(&mut dims, PIXEL_WIDTH, u64::from(width)); uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); // What the samples in those pixels mean. Written rather than left to a - // reader's own 720-line guess -- the guess is right for this file (the - // export remaps every clip into exactly that space) but a remuxer or a - // scaler downstream has no reason to make it, and an untagged file is - // how a 601 source ends up displayed as 709. - let colour = ColorDescription::output(height); + // reader's own 720-line guess -- the guess is right for an encoded file + // (the export remaps every clip into exactly that space) but a remuxer + // or a scaler downstream has no reason to make it, and an untagged file + // is how a 601 source ends up displayed as 709. A *copied* track states + // its source's space instead, which is the one its samples are in. let (primaries, transfer, matrix) = colour.codes(); let mut tags = Vec::new(); uint(&mut tags, MATRIX_COEFFICIENTS, u64::from(matrix)); @@ -1047,6 +1112,7 @@ impl MkvMuxer { cluster: Vec::new(), cluster_ts: 0, frames: 0, + last_ts: 0, audio: audio.map(|(params, packets)| MkvAudio { packets, next: 0, @@ -1075,6 +1141,29 @@ impl MkvMuxer { } let ts = (self.frames * self.frame_ns + TIMESTAMP_SCALE_NS / 2) as i64 / TIMESTAMP_SCALE_NS as i64; + self.put(obus, key, ts) + } + + /// One coded picture *copied* out of another file, shown at `ts_ns` on this + /// file's clock rather than at the next frame of a counter. + /// + /// A copy has to be timed by the source's own timestamps and not by the + /// order the blocks arrive in: a stream with B-frames is stored in decode + /// order, so its timestamps step backwards over a group of pictures, and + /// re-timing those blocks one frame apart would play the group in the order + /// it was coded in. Matroska times every block in presentation and the + /// relative timestamp in a block header is signed, so what a copy writes + /// here is exactly what its source said. + pub fn write_block(&mut self, payload: &[u8], key: bool, ts_ns: i64) -> crate::Result<()> { + if payload.is_empty() { + return Err("an empty coded block".into()); + } + let ts = (ts_ns + TIMESTAMP_SCALE_NS as i64 / 2) / TIMESTAMP_SCALE_NS as i64; + self.put(payload, key, ts) + } + + /// One block into the cluster it belongs in, whatever timed it. + fn put(&mut self, payload: &[u8], key: bool, ts: i64) -> crate::Result<()> { // A new cluster at every keyframe -- a seek lands on one, so a cluster // is a whole GOP -- and at the two limits a cluster has whatever the // encoder keys: what it may weigh, and how far a 16-bit relative @@ -1093,8 +1182,9 @@ impl MkvMuxer { // them, for the same reason. self.drain_audio(ts)?; self.drain_subs(ts)?; - self.block(1, ts, key, obus); + self.block(1, ts, key, payload); self.frames += 1; + self.last_ts = self.last_ts.max(ts); Ok(()) } @@ -1230,7 +1320,11 @@ impl MkvMuxer { let size = (1u64 << 56) | body; self.file.seek(SeekFrom::Start(self.segment_size_at))?; self.file.write_all(&size.to_be_bytes())?; - let ms = self.frames as f64 * self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64; + // One frame past the last picture shown, which is where the file really + // ends: counting the frames instead would cut a copied track short by + // however many pictures a cut left the one before it on screen for. + let ms = (self.frames as f64 * self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64) + .max(self.last_ts as f64 + self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64); self.file.seek(SeekFrom::Start(self.duration_at))?; self.file.write_all(&ms.to_be_bytes())?; self.file.flush()?; diff --git a/crates/engine/tests/video_copy.rs b/crates/engine/tests/video_copy.rs new file mode 100644 index 0000000..d6b4a0e --- /dev/null +++ b/crates/engine/tests/video_copy.rs @@ -0,0 +1,530 @@ +//! The video copy path: a Matroska timeline nobody has touched leaves as the +//! very coded blocks its source holds, and one that anybody *has* touched still +//! goes through the encoder. +//! +//! What is measured here is not "a file came out": it is that the bytes of the +//! file that came out are the source's own, that the pictures either side of a +//! cut still decode through this project's own decoder, and that every gate the +//! copy claims to have really refuses. +//! +//! ```text +//! cargo build -p engine -p engine-hw --release +//! LD_LIBRARY_PATH=target/release \ +//! cargo test -p engine --release --test video_copy -- --test-threads=1 +//! ``` +//! +//! The plugin is needed only by the decode-back test (there is no software HEVC +//! decoder here); the copy itself decodes nothing and needs nothing. The +//! multi-cut tests build their own source with the `ffmpeg` CLI -- the fixture +//! suite's HEVC file is two groups of pictures long, which has no interior to +//! splice -- and say so and pass where it is not installed, exactly as +//! `tests/hevc_export.rs` does. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, Instant}; + +use engine::demux::Demuxer; +use engine::export::{ExportSettings, Format}; +use engine::hw::HwSession; +use engine::project::{Lane, Speed}; +use engine::scratch::Scratch; +use engine::{DecodeSession, PlaybackSession}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// One coded block of a Matroska picture track, as the file holds it. +#[derive(PartialEq)] +struct Coded { + bytes: Vec, + key: bool, + ts_ns: i64, +} + +/// Every block of `path`'s picture track, in the file's own order. +fn blocks(path: &Path) -> Vec { + let (_, demuxer) = Demuxer::open(path).expect("open"); + let Demuxer::Mkv(mut demuxer) = demuxer else { + panic!("{} is not Matroska", path.display()); + }; + (0..demuxer.block_count()) + .map(|i| { + let block = demuxer + .coded_block(i) + .expect("read a block") + .expect("a block at an index the count states"); + Coded { + bytes: block.bytes.to_vec(), + key: block.key, + ts_ns: block.ts_ns, + } + }) + .collect() +} + +/// Runs an export to completion and hands back the encoder line it published -- +/// which is where a copy says it was one. +fn export(session: &PlaybackSession, out: &Path, format: Format) -> String { + let settings = ExportSettings { + format, + ..Default::default() + }; + let handle = session.export_to_with(out, &settings); + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(600), + "the export did not finish in 600 s" + ); + std::thread::sleep(Duration::from_millis(20)); + } + let encoders = handle.encoders().unwrap_or_default(); + handle + .result() + .expect("an outcome") + .unwrap_or_else(|e| panic!("export failed: {e}")); + encoders +} + +/// A source of `gops` groups of pictures at 30 fps, keyed every 30 frames, with +/// B-frames and the open groups x265 writes by default -- which is the shape a +/// film off a disc has and the shape the copy path has to survive. `None` where +/// `ffmpeg` is not installed. +fn multi_gop(name: &str, gops: u32) -> Option { + let out = Scratch::file(name, "mkv"); + let seconds = gops.to_string(); + let ok = Command::new("ffmpeg") + .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) + .arg(format!("testsrc2=size=320x240:rate=30:duration={seconds}")) + .args(["-f", "lavfi", "-i"]) + .arg(format!("sine=frequency=440:duration={seconds}")) + .args([ + "-map", + "0:v", + "-map", + "1:a", + "-c:v", + "libx265", + "-x265-params", + "log-level=error:keyint=30:min-keyint=30:scenecut=0", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-b:a", + "128k", + ]) + .arg(&out) + .status() + .ok()?; + ok.success().then_some(out) +} + +/// An untouched Matroska timeline is written by copying: the file that comes out +/// holds its source's blocks, byte for byte, with the same sync points and the +/// same timing -- reordered B-frames included, which is the thing a frame +/// counter would silently get wrong. +#[test] +fn an_untouched_matroska_timeline_leaves_as_its_source_packets() { + let source = asset("test_hevc.mkv"); + let session = PlaybackSession::open(&source).expect("open the fixture"); + let out = Scratch::file("ve_copy_untouched", "mkv"); + let line = export(&session, &out, Format::Hevc); + assert!( + line.starts_with("copy · "), + "an untouched timeline was not copied: {line}" + ); + let (before, after) = (blocks(&source), blocks(&out)); + assert_eq!(before.len(), after.len(), "block count"); + for (i, (a, b)) in before.iter().zip(&after).enumerate() { + assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes"); + assert_eq!(a.key, b.key, "block {i} sync flag"); + // Millisecond ticks either side, so the comparison is the timestamp the + // container can really state. + assert_eq!( + a.ts_ns / 1_000_000, + b.ts_ns / 1_000_000, + "block {i} is shown at another time than its source" + ); + } +} + +/// The same for AV1, whose blocks are whole temporal units rather than +/// length-prefixed NALs: one gate, two codecs, and the file says which. +#[test] +fn an_untouched_av1_timeline_leaves_as_its_source_packets() { + let source = asset("test_av1.mkv"); + let session = PlaybackSession::open(&source).expect("open the fixture"); + let out = Scratch::file("ve_copy_av1", "mkv"); + let line = export(&session, &out, Format::Av1); + assert!(line.starts_with("copy · "), "AV1 was not copied: {line}"); + let (before, after) = (blocks(&source), blocks(&out)); + assert_eq!(before.len(), after.len(), "block count"); + for (i, (a, b)) in before.iter().zip(&after).enumerate() { + assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes"); + } +} + +/// A cut placed on a sync point: the middle of the film is deleted and both +/// sides leave as copies. What is checked is the join -- the blocks either side +/// of it are the source's own, the timestamps rise a frame at a time across it +/// once they are put back in display order, and nothing but the leading +/// pictures the cut orphaned is missing. +#[test] +fn a_cut_on_a_keyframe_copies_both_sides() { + let Some(source) = multi_gop("ve_copy_source", 6) else { + println!("ffmpeg is not installed: skipping the multi-cut copy test"); + return; + }; + let before = blocks(&source); + let keys: Vec = (0..before.len()).filter(|&i| before[i].key).collect(); + assert!(keys.len() >= 4, "expected several groups, got {keys:?}"); + // Frames 60 and 120 in the block order the whole engine counts in. + let (first, second) = (keys[2], keys[4]); + let mut session = PlaybackSession::open(&source).expect("open the source"); + let fps = session.meta().frame_rate; + assert!(session.cut_at(first as f64 / fps), "cut at the third group"); + assert!( + session.cut_at(second as f64 / fps), + "cut at the fifth group" + ); + // One call: the picture and the sound of a take are one group, so + // deleting the clip takes its lane partner with it. + assert!(session.delete_clip(Lane::V1, 1), "drop the middle clip"); + + let out = Scratch::file("ve_copy_cut", "mkv"); + let line = export(&session, &out, Format::Hevc); + assert!( + line.starts_with("copy · "), + "a keyframe cut was not copied: {line}" + ); + + // What the file should hold: the blocks before the cut, then the blocks + // after it minus the leading pictures the second region orphaned -- those + // are shown before their own sync point and reference the group this cut + // threw away. + let after = blocks(&out); + let mut want: Vec<&Coded> = before[..first].iter().collect(); + let origin = before[second].ts_ns; + want.extend(before[second..].iter().filter(|b| b.ts_ns >= origin)); + assert_eq!(after.len(), want.len(), "copied block count"); + for (i, (a, b)) in want.iter().zip(&after).enumerate() { + assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes"); + assert_eq!(a.key, b.key, "block {i} sync flag"); + } + // Put back in display order, the file is a frame grid with one hole: the + // frames the second region's dropped leading pictures would have filled, + // which is where the picture before the cut is held instead. + let mut shown: Vec = after.iter().map(|b| b.ts_ns / 1_000_000).collect(); + shown.sort_unstable(); + let step = (1000.0 / fps).round() as i64; + let holes = shown + .windows(2) + .filter(|w| (w[1] - w[0] - step).abs() > 1) + .count(); + assert!( + holes <= 1, + "the copied file is not one run of frames: {holes} holes in {shown:?}" + ); + assert_eq!(shown[0], 0, "the file starts at the timeline's own zero"); +} + +/// ...and that join really decodes: every picture around it comes back through +/// this project's own demuxer and decoder, in order, without an error and +/// without a black frame where the cut is. +#[test] +fn the_pictures_either_side_of_a_copied_cut_decode() { + let Some(source) = multi_gop("ve_copy_decode_source", 6) else { + println!("ffmpeg is not installed: skipping the copied-join decode test"); + return; + }; + let before = blocks(&source); + let keys: Vec = (0..before.len()).filter(|&i| before[i].key).collect(); + let (first, second) = (keys[2], keys[4]); + let mut session = PlaybackSession::open(&source).expect("open the source"); + let fps = session.meta().frame_rate; + assert!(session.cut_at(first as f64 / fps)); + assert!(session.cut_at(second as f64 / fps)); + assert!(session.delete_clip(Lane::V1, 1)); + let out = Scratch::file("ve_copy_decode", "mkv"); + let line = export(&session, &out, Format::Hevc); + assert!(line.starts_with("copy · "), "not copied: {line}"); + + let (meta, frames) = match DecodeSession::open(&out) { + Ok(open) => open, + Err(e) => { + println!("no HEVC decoder here ({e}): skipping the decode-back"); + return; + } + }; + let mut seen = Vec::new(); + for frame in frames { + let luma: u64 = frame + .bgra + .chunks_exact(4) + .map(|px| u64::from(px[1])) + .sum::() + / (u64::from(frame.width) * u64::from(frame.height)); + seen.push((frame.index, luma)); + } + assert!( + seen.len() >= meta.frame_count as usize - 8, + "{} pictures decoded of {}", + seen.len(), + meta.frame_count + ); + for (i, (index, _)) in seen.iter().enumerate() { + assert_eq!(*index as usize, i, "pictures came back out of order"); + } + // The join is at the first region's length; a frame either side of it is a + // real picture rather than the black a broken splice decodes to. + let joint = first.min(seen.len() - 1); + for at in [0, joint.saturating_sub(2), joint, seen.len() - 1] { + assert!( + seen[at].1 > 4, + "picture {at} around the join is black ({} luma)", + seen[at].1 + ); + } +} + +/// Every gate the copy claims: a grade, a speed and a format whose container +/// this path does not write all put the export back through the encoder. A copy +/// that took any of these would write a file that is not what was watched. +#[test] +fn a_touched_timeline_is_still_encoded() { + let source = asset("test_hevc.mkv"); + let out = Scratch::file("ve_copy_gate", "mkv"); + + let mut graded = PlaybackSession::open(&source).expect("open"); + assert!(graded.set_color( + Lane::V1, + 0, + Some(engine::color::ColorParams { + saturation: 1.4, + ..Default::default() + }) + )); + let line = export(&graded, &out, Format::Hevc); + assert!( + !line.starts_with("copy"), + "a graded timeline was copied: {line}" + ); + + let mut speeded = PlaybackSession::open(&source).expect("open"); + speeded + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) + .expect("speed the clip"); + let line = export(&speeded, &out, Format::Hevc); + assert!( + !line.starts_with("copy"), + "a speeded timeline was copied: {line}" + ); + + // The same untouched timeline into an mp4: nothing here copies into one, + // because a sample entry states its parameter sets once and the mp4 muxer + // times its samples by a frame counter. + let plain = PlaybackSession::open(&source).expect("open"); + let mp4 = Scratch::file("ve_copy_gate_mp4", "mp4"); + let line = export(&plain, &mp4, Format::HevcMp4); + assert!(!line.starts_with("copy"), "an mp4 was copied: {line}"); +} + +/// A cut that lands between two sync points is the case this path refuses: the +/// head of the second region would need pictures that are not in the file, so +/// the whole export goes back through the encoder rather than writing a file +/// whose first second cannot be decoded. +#[test] +fn a_cut_off_the_keyframe_grid_falls_back_to_the_encoder() { + let source = asset("test_hevc.mkv"); + let mut session = PlaybackSession::open(&source).expect("open"); + let fps = session.meta().frame_rate; + // Block 40 of a file keyed every 30: inside the second group. + assert!(session.cut_at(40.0 / fps), "cut mid-group"); + assert!(session.delete_clip(Lane::V1, 0), "drop the first clip"); + let out = Scratch::file("ve_copy_offgrid", "mkv"); + let line = export(&session, &out, Format::Hevc); + assert!( + !line.starts_with("copy"), + "a cut off the sync grid was copied: {line}" + ); +} + +/// The measurement this path exists for, on a real film rather than a fixture: +/// a 4K HDR x265 Matroska of two and a half hours, cut once in the middle, out +/// to Matroska. What it costs is the *edited* spans -- which for a copy is no +/// spans at all -- plus reading and writing the bytes, against a re-encode that +/// codes every one of its 167 thousand pictures. +/// +/// `#[ignore]`d and named by environment, so no path off this machine is in the +/// repository and the suite runs without the file: +/// +/// ```text +/// VE_FILM=/path/to/film.mkv VE_OUT=/somewhere/cut.mkv \ +/// cargo test -p engine --release --test video_copy -- --ignored --nocapture \ +/// a_real_film +/// ``` +#[test] +#[ignore] +fn a_real_film_is_cut_by_copying_its_spans() { + let Ok(film) = std::env::var("VE_FILM") else { + println!("VE_FILM is not set: skipping the real-film copy measurement"); + return; + }; + let film = PathBuf::from(film); + let opened = Instant::now(); + let (meta, demuxer) = Demuxer::open(&film).expect("open the film"); + let Demuxer::Mkv(mut source) = demuxer else { + panic!("the film is not Matroska"); + }; + println!( + "film: {}x{} {:?} {:.4} fps, {} blocks, indexed in {:?}", + meta.width, + meta.height, + meta.codec, + meta.frame_rate, + source.block_count(), + opened.elapsed() + ); + // The cut: five minutes taken out of the middle of the film, on the two + // sync points nearest the half-hour marks -- which is what placing a cut on + // a keyframe means, and what the copy needs of any cut. + let mut sync_at = |from: u32| { + (from as usize..source.block_count()) + .find(|&i| source.is_sync(i)) + .expect("a sync point after the mark") + }; + let (first, second) = ( + sync_at((30.0 * 60.0 * meta.frame_rate) as u32), + sync_at((35.0 * 60.0 * meta.frame_rate) as u32), + ); + println!( + "cutting blocks {first}..{second} out of {}", + meta.frame_count + ); + + let mut session = PlaybackSession::open(&film).expect("open the film as a project"); + let fps = session.meta().frame_rate; + assert!(session.cut_at(first as f64 / fps), "cut at the first mark"); + assert!( + session.cut_at(second as f64 / fps), + "cut at the second mark" + ); + assert!(session.delete_clip(Lane::V1, 1), "drop the middle"); + + let out = PathBuf::from( + std::env::var("VE_OUT").unwrap_or_else(|_| "/tmp/ve_real_film_cut.mkv".into()), + ); + let started = Instant::now(); + let line = export(&session, &out, Format::Hevc); + let took = started.elapsed(); + let bytes = std::fs::metadata(&out).expect("the exported file").len(); + println!("exported {} MB in {:?} ({line})", bytes / 1_000_000, took); + assert!( + line.starts_with("copy · "), + "the film was not copied: {line}" + ); + + // The bytes: every block around either side of the join, and a sample + // across the rest -- a whole-file comparison is a second read of twelve + // gigabytes and says nothing this does not. + let mut written = blocks(&out); + println!("{} blocks written of {}", written.len(), meta.frame_count); + let origin = { + let block = source.coded_block(second).expect("read").expect("a block"); + block.ts_ns + }; + let mut want: Vec = (0..first).collect(); + want.extend((second..source.block_count()).filter(|&i| { + let block = source.coded_block(i).expect("read").expect("a block"); + block.ts_ns >= origin + })); + assert_eq!(written.len(), want.len(), "copied block count"); + let near_join = first.saturating_sub(200)..(first + 200).min(want.len()); + for (out_index, &source_index) in want.iter().enumerate() { + if !near_join.contains(&out_index) && out_index % 500 != 0 { + continue; + } + let block = source + .coded_block(source_index) + .expect("read") + .expect("a block"); + assert_eq!( + block.bytes, + written[out_index].bytes.as_slice(), + "block {out_index} of the export is not source block {source_index}" + ); + assert_eq!( + block.key, written[out_index].key, + "block {out_index} sync flag" + ); + } + // The join itself, in display order: one run of frames with at most the one + // hole the orphaned leading pictures leave. + written.sort_by_key(|b| b.ts_ns); + let step = (1e9 / fps).round() as i64; + let holes: Vec = written + .windows(2) + .map(|w| w[1].ts_ns - w[0].ts_ns) + .filter(|d| (d - step).abs() > step / 2) + .collect(); + println!("gaps in the shown order: {holes:?} ns (one frame is {step} ns)"); + assert!(holes.len() <= 1, "the copied film is not one run of frames"); + + // ...and the join really decodes: two seconds either side of it, through + // this project's own demuxer and decoder, in order and never black. The + // start and the end of the film with them, so the file is exercised end to + // end and not only where it was cut. + let seconds = fps.round() as usize * 2; + let decode_at = |path: &Path, at: u32| -> Option> { + let mut decoder = HwSession::open_at(path, at)?; + let mut lumas = Vec::new(); + while lumas.len() < seconds { + let Some((y, _, _, w, h)) = decoder.next_frame().expect("decode") else { + break; + }; + lumas + .push(y.iter().map(|&s| u64::from(s)).sum::() / (u64::from(w) * u64::from(h))); + } + Some(lumas) + }; + // The tail is measured against the *source's* own tail rather than against + // the count asked for: a decoder drains the last group of pictures the same + // way in both files (45 of the last 48 on this film, measured), and a copy + // is right when it behaves as its source does, not when it behaves better. + let tail = decode_at(&film, meta.frame_count - seconds as u32).map(|l| l.len()); + for (what, at, least) in [ + ("the start", 0, seconds), + ("the join", first as u32 - seconds as u32, seconds), + ( + "the end", + written.len() as u32 - seconds as u32, + tail.unwrap_or(seconds), + ), + ] { + let Some(lumas) = decode_at(&out, at) else { + println!("no VA-API plugin here: skipping the decode of {what}"); + break; + }; + println!( + "{what} at frame {at}: {} pictures, luma {lumas:?}", + lumas.len() + ); + assert!( + lumas.len() >= least, + "{what} decoded {} pictures of the {least} its source gives", + lumas.len() + ); + // Limited-range black is 16, and this film opens and closes on it; what + // a broken splice decodes to is 0, and what it never does is stay in + // step with the source's own luma. + assert!( + lumas.iter().all(|&l| l >= 15), + "a black picture around {what}: {lumas:?}" + ); + } +}