An untouched Matroska timeline leaves as its own packets
Browse files at this commitada6ac52d10fb530bea17cb3e6c368b48165ffaaParent: 1acf384- feat
- an untouched Matroska timeline leaves as its own packets
4 changed files +1003 -13
- crates/engine/src/demux.rs +107 -0
- crates/engine/src/export.rs +265 -6
- crates/engine/src/mux.rs +101 -7
- crates/engine/tests/video_copy.rs +530 -0
crates/engine/src/demux.rsmodified+107 -0
| @@ -829,6 +829,12 @@ pub struct MkvDemuxer { | |||
| 829 | /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the | 829 | /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the |
| 830 | /// `avcC` beside it, which is that record's H.264 twin. | 830 | /// `avcC` beside it, which is that record's H.264 twin. |
| 831 | config: Vec<u8>, | 831 | config: Vec<u8>, |
| 832 | + /// The `CodecPrivate` record verbatim; see [`MkvVideo::private`]. | ||
| 833 | + private: Vec<u8>, | ||
| 834 | + /// Nanoseconds a timestamp tick is worth -- `TimestampScale`, a millisecond | ||
| 835 | + /// in every file anything writes. What turns a block's own timestamp into | ||
| 836 | + /// the nanoseconds a copy re-times it by. | ||
| 837 | + timestamp_scale: u64, | ||
| 832 | /// Bytes of the NAL length prefix an HEVC or H.264 block is written with; | 838 | /// Bytes of the NAL length prefix an HEVC or H.264 block is written with; |
| 833 | /// unused by AV1, whose block is one temporal unit and carries no prefixes. | 839 | /// unused by AV1, whose block is one temporal unit and carries no prefixes. |
| 834 | nal_length: usize, | 840 | nal_length: usize, |
| @@ -942,6 +948,8 @@ impl MkvDemuxer { | |||
| 942 | blocks: Vec::new(), | 948 | blocks: Vec::new(), |
| 943 | codec: video.codec, | 949 | codec: video.codec, |
| 944 | config: video.config, | 950 | config: video.config, |
| 951 | + private: video.private, | ||
| 952 | + timestamp_scale: video.timestamp_scale, | ||
| 945 | nal_length: video.nal_length, | 953 | nal_length: video.nal_length, |
| 946 | bit_depth: video.bit_depth, | 954 | bit_depth: video.bit_depth, |
| 947 | light: video.light, | 955 | light: video.light, |
| @@ -1399,6 +1407,95 @@ impl MkvDemuxer { | |||
| 1399 | // reordered, and never more than the reorder depth out. | 1407 | // reordered, and never more than the reorder depth out. |
| 1400 | self.base as i64 | 1408 | self.base as i64 |
| 1401 | } | 1409 | } |
| 1410 | + | ||
| 1411 | + /// The picture track's `CodecPrivate` as the file holds it: what a copied | ||
| 1412 | + /// track is declared with, so the record and the blocks under it come out of | ||
| 1413 | + /// one file rather than two ([`MkvVideo::private`]). | ||
| 1414 | + pub fn codec_private(&self) -> &[u8] { | ||
| 1415 | + &self.private | ||
| 1416 | + } | ||
| 1417 | + | ||
| 1418 | + /// How many coded blocks the picture track has -- the count | ||
| 1419 | + /// [`crate::VideoMeta::frame_count`] is, indexed the same way every seek and | ||
| 1420 | + /// every clip in point already indexes it. | ||
| 1421 | + /// | ||
| 1422 | + /// The track's own count and not the open window's: a file opened off its | ||
| 1423 | + /// `Cues` holds ten seconds of blocks and knows the length of all of them | ||
| 1424 | + /// ([`Self::count_frames`]), which is the number a clip was cut against. | ||
| 1425 | + pub fn block_count(&self) -> usize { | ||
| 1426 | + self.frames | ||
| 1427 | + } | ||
| 1428 | + | ||
| 1429 | + /// Whether block `index` is one a decoder may be started from, which is what | ||
| 1430 | + /// makes it a place a copy may begin or end. | ||
| 1431 | + /// | ||
| 1432 | + /// Asks the whole index, because it is asked about any block of the file and | ||
| 1433 | + /// a window holds one stretch of it. That is the walk this demuxer otherwise | ||
| 1434 | + /// avoids -- paid once per source, by a caller that is about to read every | ||
| 1435 | + /// block anyway, and cheap on the second export of the same file | ||
| 1436 | + /// ([`Self::complete_index`] and the sidecar under it). A file that cannot be | ||
| 1437 | + /// walked answers `false`, which is a copy refused rather than a copy of the | ||
| 1438 | + /// wrong bytes. | ||
| 1439 | + pub fn is_sync(&mut self, index: usize) -> bool { | ||
| 1440 | + if self.complete_index().is_err() { | ||
| 1441 | + return false; | ||
| 1442 | + } | ||
| 1443 | + self.blocks.get(index).is_some_and(|b| b.key) | ||
| 1444 | + } | ||
| 1445 | + | ||
| 1446 | + /// Whether the blocks are the codec's own bytes -- no `ContentEncodings` | ||
| 1447 | + /// stripping or compression over them. A copy of anything else would hand | ||
| 1448 | + /// the muxer bytes it would have to re-pack, which is no longer a copy. | ||
| 1449 | + pub fn plain_blocks(&self) -> bool { | ||
| 1450 | + self.unpack == Unpack::None | ||
| 1451 | + } | ||
| 1452 | + | ||
| 1453 | + /// Block `index` exactly as it sits in the file: its bytes, whether it is a | ||
| 1454 | + /// sync point and when it is shown, in nanoseconds off the file's own clock. | ||
| 1455 | + /// | ||
| 1456 | + /// Presentation and not decode: Matroska blocks are stored in decode order | ||
| 1457 | + /// and timestamped in display order, so a stream with B-frames hands back | ||
| 1458 | + /// timestamps that step backwards -- which is exactly what a copy has to | ||
| 1459 | + /// preserve, and why this is not "block index times the frame duration". | ||
| 1460 | + /// | ||
| 1461 | + /// The bytes are borrowed from the read scratch and live until the next | ||
| 1462 | + /// call, as [`Self::next_access_unit`]'s do. | ||
| 1463 | + /// | ||
| 1464 | + /// `index` is the file's own block number, so this holds the whole index | ||
| 1465 | + /// rather than whatever window is open ([`Self::is_sync`] says why, and this | ||
| 1466 | + /// is the caller that makes the walk worth it: a copy reads every block). | ||
| 1467 | + pub fn coded_block(&mut self, index: usize) -> crate::Result<Option<CodedBlock<'_>>> { | ||
| 1468 | + self.complete_index()?; | ||
| 1469 | + let Some(&block) = self.blocks.get(index) else { | ||
| 1470 | + return Ok(None); | ||
| 1471 | + }; | ||
| 1472 | + // The cursor moves with it, so a copy that stops and hands the file back | ||
| 1473 | + // to a decoder leaves it where a sequential read would. | ||
| 1474 | + self.next = index + 1; | ||
| 1475 | + let Self { | ||
| 1476 | + file, | ||
| 1477 | + scratch, | ||
| 1478 | + unpack, | ||
| 1479 | + .. | ||
| 1480 | + } = self; | ||
| 1481 | + scratch.resize(block.len, 0); | ||
| 1482 | + read_exact_at(file, block.at, scratch)?; | ||
| 1483 | + unpack.frame(scratch)?; | ||
| 1484 | + Ok(Some(CodedBlock { | ||
| 1485 | + bytes: &self.scratch, | ||
| 1486 | + key: block.key, | ||
| 1487 | + ts_ns: block.ts * self.timestamp_scale as i64, | ||
| 1488 | + })) | ||
| 1489 | + } | ||
| 1490 | +} | ||
| 1491 | + | ||
| 1492 | +/// One coded picture as a file holds it, for the export's copy path | ||
| 1493 | +/// ([`MkvDemuxer::coded_block`]): the very bytes the muxer writes back out, the | ||
| 1494 | +/// sync flag a container states beside them, and when the picture is shown. | ||
| 1495 | +pub struct CodedBlock<'a> { | ||
| 1496 | + pub bytes: &'a [u8], | ||
| 1497 | + pub key: bool, | ||
| 1498 | + pub ts_ns: i64, | ||
| 1402 | } | 1499 | } |
| 1403 | 1500 | ||
| 1404 | /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or | 1501 | /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or |
| @@ -1574,6 +1671,13 @@ struct MkvVideo { | |||
| 1574 | timestamp_scale: u64, | 1671 | timestamp_scale: u64, |
| 1575 | codec: Codec, | 1672 | codec: Codec, |
| 1576 | config: Vec<u8>, | 1673 | config: Vec<u8>, |
| 1674 | + /// `CodecPrivate` as the file holds it -- the `hvcC`/`avcC`/`av1C` record | ||
| 1675 | + /// itself, before [`parse_hvcc`] and its siblings turn it into the | ||
| 1676 | + /// parameter sets `config` carries. Kept because a copy hands the very same | ||
| 1677 | + /// record to the muxer ([`MkvDemuxer::codec_private`]): a track written from | ||
| 1678 | + /// a re-derived record would declare a stream subtly other than the blocks | ||
| 1679 | + /// under it. | ||
| 1680 | + private: Vec<u8>, | ||
| 1577 | nal_length: usize, | 1681 | nal_length: usize, |
| 1578 | bit_depth: u8, | 1682 | bit_depth: u8, |
| 1579 | unpack: Unpack, | 1683 | unpack: Unpack, |
| @@ -2069,6 +2173,8 @@ fn mkv_track_entry( | |||
| 2069 | let Some(known) = mkv_codec(&codec) else { | 2173 | let Some(known) = mkv_codec(&codec) else { |
| 2070 | return Ok(MkvEntry::OtherVideo(codec)); | 2174 | return Ok(MkvEntry::OtherVideo(codec)); |
| 2071 | }; | 2175 | }; |
| 2176 | + // The record itself, before any of the arms below reads it apart. | ||
| 2177 | + let private = config.clone(); | ||
| 2072 | let (codec, nal_length, config, bit_depth) = match known { | 2178 | let (codec, nal_length, config, bit_depth) = match known { |
| 2073 | Codec::Av1 => { | 2179 | Codec::Av1 => { |
| 2074 | let (sets, bit_depth) = parse_av1c(&config)?; | 2180 | let (sets, bit_depth) = parse_av1c(&config)?; |
| @@ -2103,6 +2209,7 @@ fn mkv_track_entry( | |||
| 2103 | timestamp_scale, | 2209 | timestamp_scale, |
| 2104 | codec, | 2210 | codec, |
| 2105 | config, | 2211 | config, |
| 2212 | + private, | ||
| 2106 | nal_length, | 2213 | nal_length, |
| 2107 | bit_depth, | 2214 | bit_depth, |
| 2108 | unpack, | 2215 | unpack, |
crates/engine/src/export.rsmodified+265 -6
| @@ -9,10 +9,17 @@ | |||
| 9 | //! That makes it an intraframe master in the family of ProRes and DNxHD — large | 9 | //! That makes it an intraframe master in the family of ProRes and DNxHD — large |
| 10 | //! files, every frame a cut point — and not a delivery codec. | 10 | //! files, every frame a cut point — and not a delivery codec. |
| 11 | //! | 11 | //! |
| 12 | -//! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it | 12 | +//! Picture and sound are both **copied wherever a copy says exactly what the |
| 13 | -//! is impossible — while audio is copied packet for packet wherever a copy can | 13 | +//! timeline says** — a copy is exact, free and never a generation of loss. For |
| 14 | -//! say what the timeline says: a copy is exact, free and never a generation of | 14 | +//! the sound that is packet for packet ([`copy_audio`]); for the picture it is |
| 15 | -//! loss. Where it *cannot* — a second audio lane to mix in, a speeded clip, an | 15 | +//! block for block out of a Matroska source into a Matroska file ([`CopyPlan`]), |
| 16 | +//! which is what makes a cut in a two-hour film cost the reading of it rather | ||
| 17 | +//! than the re-encoding of it. The picture's copy is all-or-nothing per export, | ||
| 18 | +//! because a copied span and an encoded one cannot share one track: what it | ||
| 19 | +//! needs of a cut is that it lands on a sync point, and everything else — a | ||
| 20 | +//! grade, a speed, a gap, a source of another size or codec, an mp4 — goes | ||
| 21 | +//! through the encoder exactly as it always did. Where the *sound* cannot be | ||
| 22 | +//! copied — a second audio lane to mix in, a speeded clip, an | ||
| 16 | //! equalized one, a source that is not AAC inside an mp4's own sample table — | 23 | //! equalized one, a source that is not AAC inside an mp4's own sample table — |
| 17 | //! the sound is decoded, mixed and encoded again with `rusty_aac` | 24 | //! the sound is decoded, mixed and encoded again with `rusty_aac` |
| 18 | //! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes | 25 | //! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes |
| @@ -65,9 +72,11 @@ use oxideav_core::Muxer as _; | |||
| 65 | 72 | ||
| 66 | use crate::audio::{AudioMeta, AudioSession}; | 73 | use crate::audio::{AudioMeta, AudioSession}; |
| 67 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; | 74 | use crate::colorspace::{ColorDescription, Matrix, Transfer}; |
| 68 | -use crate::demux::{Demuxer, VideoMeta}; | 75 | +use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta}; |
| 69 | use crate::hw::{HwEncoder, HwSession}; | 76 | use crate::hw::{HwEncoder, HwSession}; |
| 70 | -use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; | 77 | +use crate::mux::{ |
| 78 | + AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, | ||
| 79 | +}; | ||
| 71 | use crate::project::{LaneKind, Project, Rate}; | 80 | use crate::project::{LaneKind, Project, Rate}; |
| 72 | use crate::scale::Composer; | 81 | use crate::scale::Composer; |
| 73 | use crate::subtitle::{Cue, SubtitleTrack}; | 82 | use crate::subtitle::{Cue, SubtitleTrack}; |
| @@ -893,6 +902,234 @@ fn copy_audio( | |||
| 893 | } | 902 | } |
| 894 | } | 903 | } |
| 895 | 904 | ||
| 905 | +/// The picture's half of [`copy_audio`]: a Matroska export whose every span is | ||
| 906 | +/// its source's own coded blocks, written back out without a decoder or an | ||
| 907 | +/// encoder anywhere in the path. | ||
| 908 | +/// | ||
| 909 | +/// **When.** A copy is entered only where it says *exactly* what the timeline | ||
| 910 | +/// says, which is the audio gate's rule and not a looser one: the file this | ||
| 911 | +/// export writes is Matroska, the source's codec is the one that file would | ||
| 912 | +/// carry ([`Format::Hevc`] over HEVC, [`Format::Av1`] over AV1), and nothing on | ||
| 913 | +/// the way has touched a sample -- no grade, no speed, no rate conversion, no | ||
| 914 | +/// gap to fill with black, no source of another size to place on the canvas, | ||
| 915 | +/// no `ContentEncodings` packing to undo. Anything else re-encodes exactly as | ||
| 916 | +/// it always did; there is no half-copied file. | ||
| 917 | +/// | ||
| 918 | +/// **All or nothing, per export.** A copied span and an encoded one cannot | ||
| 919 | +/// share one track: this project's encoders write 8-bit SDR streams whose | ||
| 920 | +/// parameter sets are their own, so splicing them into (say) a Main 10 HDR | ||
| 921 | +/// source would change bit depth and colour mid-track, and a container states | ||
| 922 | +/// its configuration record once. So the head and tail fragments of a cut that | ||
| 923 | +/// lands mid-GOP are *not* re-encoded into the copy -- they are what makes the | ||
| 924 | +/// whole export fall back to the encoder. What a copy needs instead is that | ||
| 925 | +/// every span begins on a sync point and ends where the next one begins, which | ||
| 926 | +/// is what a cut placed on a keyframe gives it. | ||
| 927 | +/// | ||
| 928 | +/// **What a cut costs.** An open-GOP source (x265's default) writes leading | ||
| 929 | +/// pictures after a sync point that are shown *before* it and reference the | ||
| 930 | +/// group before it. At the start of a copied region those references are not in | ||
| 931 | +/// the file, so they are dropped -- the picture before the cut is held for those | ||
| 932 | +/// few frames (four at this film's B-depth, a sixth of a second) rather than | ||
| 933 | +/// being written as pictures that cannot decode. The region still starts at the | ||
| 934 | +/// timeline frame it owns, so the sound never drifts. | ||
| 935 | +/// | ||
| 936 | +/// ponytail: mp4 is not copied (its `hvc1` sample entry forbids in-band | ||
| 937 | +/// parameter sets, and the mp4 muxer here writes its sample table from a frame | ||
| 938 | +/// counter), and neither is H.264, which this project only writes into mp4. The | ||
| 939 | +/// upgrade path for both is a sample-table writer that takes explicit | ||
| 940 | +/// timestamps, which is what [`MkvMuxer::write_block`] already is for Matroska. | ||
| 941 | +struct CopyPlan { | ||
| 942 | + /// Every source a region reads, by the index the project names it with; | ||
| 943 | + /// `None` for a source no clip plays from. | ||
| 944 | + sources: Vec<Option<MkvDemuxer>>, | ||
| 945 | + regions: Vec<CopyRegion>, | ||
| 946 | + codec_id: &'static [u8], | ||
| 947 | + /// The `CodecPrivate` every region's source agrees on -- a track is declared | ||
| 948 | + /// once, so two sources that disagree about their parameter sets are not one | ||
| 949 | + /// copy. | ||
| 950 | + private: Vec<u8>, | ||
| 951 | + colour: ColorDescription, | ||
| 952 | + width: u32, | ||
| 953 | + height: u32, | ||
| 954 | +} | ||
| 955 | + | ||
| 956 | +/// A run of source blocks copied in one piece: what a cut leaves behind, and | ||
| 957 | +/// what two spans that continue each other in the same file merge back into. | ||
| 958 | +struct CopyRegion { | ||
| 959 | + source: usize, | ||
| 960 | + /// Blocks of that source, in the file's own decode order. | ||
| 961 | + blocks: std::ops::Range<usize>, | ||
| 962 | + /// The timeline frame the region's first picture is shown at. | ||
| 963 | + start: u32, | ||
| 964 | +} | ||
| 965 | + | ||
| 966 | +impl CopyPlan { | ||
| 967 | + /// The plan for this timeline, or `None` where anything at all makes a copy | ||
| 968 | + /// say something other than what the timeline says -- in which case the | ||
| 969 | + /// caller encodes, which is what it always did. | ||
| 970 | + fn of(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<Self> { | ||
| 971 | + let (codec_id, codec): (&'static [u8], Codec) = match settings.format { | ||
| 972 | + Format::Hevc => (b"V_MPEGH/ISO/HEVC", Codec::Hevc), | ||
| 973 | + Format::Av1 => (b"V_AV1", Codec::Av1), | ||
| 974 | + _ => return None, | ||
| 975 | + }; | ||
| 976 | + let entries = project.sources(); | ||
| 977 | + let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect(); | ||
| 978 | + let mut declared: Option<(Vec<u8>, ColorDescription)> = None; | ||
| 979 | + let mut regions: Vec<CopyRegion> = Vec::new(); | ||
| 980 | + for span in project.composite_spans_from(0) { | ||
| 981 | + // A gap is black frames, which only an encoder makes. | ||
| 982 | + let (source, in_frame) = span.from?; | ||
| 983 | + if !span.speed.is_normal() { | ||
| 984 | + return None; | ||
| 985 | + } | ||
| 986 | + // The grade playback shows, which a copied packet never went | ||
| 987 | + // through. `None` and the identity are the same untouched picture. | ||
| 988 | + if project | ||
| 989 | + .composite_color_at(span.start) | ||
| 990 | + .is_some_and(|params| !params.is_identity()) | ||
| 991 | + { | ||
| 992 | + return None; | ||
| 993 | + } | ||
| 994 | + let path = &entries.get(source)?.path; | ||
| 995 | + if sources.get(source)?.is_none() { | ||
| 996 | + if !crate::demux::is_matroska(path) { | ||
| 997 | + return None; | ||
| 998 | + } | ||
| 999 | + let (source_meta, demuxer) = Demuxer::open(path).ok()?; | ||
| 1000 | + let Demuxer::Mkv(demuxer) = demuxer else { | ||
| 1001 | + return None; | ||
| 1002 | + }; | ||
| 1003 | + // The stream this file would carry, at the size and the rate the | ||
| 1004 | + // timeline is in: anything else is a picture that has to be | ||
| 1005 | + // coded again to become this file's. | ||
| 1006 | + if source_meta.codec != codec | ||
| 1007 | + || source_meta.width != meta.width | ||
| 1008 | + || source_meta.height != meta.height | ||
| 1009 | + || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? | ||
| 1010 | + != Rate::REAL_TIME | ||
| 1011 | + || !demuxer.plain_blocks() | ||
| 1012 | + { | ||
| 1013 | + return None; | ||
| 1014 | + } | ||
| 1015 | + // One track, one configuration record and one `Colour`: two | ||
| 1016 | + // sources that disagree about either are two streams, and this | ||
| 1017 | + // writes one. | ||
| 1018 | + let declares = (demuxer.codec_private().to_vec(), source_meta.color); | ||
| 1019 | + if declared.get_or_insert(declares.clone()) != &declares { | ||
| 1020 | + return None; | ||
| 1021 | + } | ||
| 1022 | + sources[source] = Some(demuxer); | ||
| 1023 | + } | ||
| 1024 | + let demuxer = sources.get_mut(source)?.as_mut()?; | ||
| 1025 | + // The window this span reads, in the blocks the whole engine counts | ||
| 1026 | + // a source's frames in. It has to *be* whole groups of pictures: a | ||
| 1027 | + // copy that began between two sync points would hand a decoder | ||
| 1028 | + // pictures whose references are not in the file, and one that ended | ||
| 1029 | + // between them would drop a reference the pictures before it need. | ||
| 1030 | + let (start, end) = (in_frame as usize, in_frame as usize + span.len as usize); | ||
| 1031 | + if end > demuxer.block_count() | ||
| 1032 | + || !demuxer.is_sync(start) | ||
| 1033 | + || (end < demuxer.block_count() && !demuxer.is_sync(end)) | ||
| 1034 | + { | ||
| 1035 | + return None; | ||
| 1036 | + } | ||
| 1037 | + // Two spans that continue each other in one file are one region: | ||
| 1038 | + // nothing was cut between them, so the leading pictures across that | ||
| 1039 | + // boundary still have every reference they need. | ||
| 1040 | + match regions.last_mut() { | ||
| 1041 | + Some(last) | ||
| 1042 | + if last.source == source | ||
| 1043 | + && last.blocks.end == start | ||
| 1044 | + && last.start + (last.blocks.end - last.blocks.start) as u32 | ||
| 1045 | + == span.start => | ||
| 1046 | + { | ||
| 1047 | + last.blocks.end = end; | ||
| 1048 | + } | ||
| 1049 | + _ => regions.push(CopyRegion { | ||
| 1050 | + source, | ||
| 1051 | + blocks: start..end, | ||
| 1052 | + start: span.start, | ||
| 1053 | + }), | ||
| 1054 | + } | ||
| 1055 | + } | ||
| 1056 | + let (private, colour) = declared?; | ||
| 1057 | + Some(Self { | ||
| 1058 | + sources, | ||
| 1059 | + regions, | ||
| 1060 | + codec_id, | ||
| 1061 | + private, | ||
| 1062 | + colour, | ||
| 1063 | + width: meta.width, | ||
| 1064 | + height: meta.height, | ||
| 1065 | + }) | ||
| 1066 | + } | ||
| 1067 | + | ||
| 1068 | + /// The file itself: one Matroska muxer, every region's blocks through it in | ||
| 1069 | + /// the order and at the timing their source states. | ||
| 1070 | + fn run( | ||
| 1071 | + mut self, | ||
| 1072 | + out: &Path, | ||
| 1073 | + meta: &VideoMeta, | ||
| 1074 | + shared: &Shared, | ||
| 1075 | + audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | ||
| 1076 | + subs: Vec<SubParams>, | ||
| 1077 | + total: u32, | ||
| 1078 | + ) -> crate::Result<()> { | ||
| 1079 | + let mut muxer = MkvMuxer::create_copy( | ||
| 1080 | + out, | ||
| 1081 | + &CopyParams { | ||
| 1082 | + width: self.width, | ||
| 1083 | + height: self.height, | ||
| 1084 | + frame_rate: meta.frame_rate, | ||
| 1085 | + codec_id: self.codec_id, | ||
| 1086 | + codec_private: &self.private, | ||
| 1087 | + colour: self.colour, | ||
| 1088 | + }, | ||
| 1089 | + audio, | ||
| 1090 | + subs, | ||
| 1091 | + )?; | ||
| 1092 | + // Nanoseconds a timeline frame lasts, which is what a region's own | ||
| 1093 | + // position on the timeline is measured in. | ||
| 1094 | + let frame_ns = 1e9 / meta.frame_rate; | ||
| 1095 | + let mut done = 0u32; | ||
| 1096 | + for region in &self.regions { | ||
| 1097 | + let demuxer = self.sources[region.source] | ||
| 1098 | + .as_mut() | ||
| 1099 | + .ok_or("a copied region names a source that was never opened")?; | ||
| 1100 | + let base = (f64::from(region.start) * frame_ns).round() as i64; | ||
| 1101 | + // When the region's first picture is shown on its source's clock; | ||
| 1102 | + // everything after it is written that far along from `base`. | ||
| 1103 | + let mut origin: Option<i64> = None; | ||
| 1104 | + for index in region.blocks.clone() { | ||
| 1105 | + cancelled(shared)?; | ||
| 1106 | + let Some(block) = demuxer.coded_block(index)? else { | ||
| 1107 | + break; | ||
| 1108 | + }; | ||
| 1109 | + let origin = *origin.get_or_insert(block.ts_ns); | ||
| 1110 | + // The leading pictures of the group this region opens on: shown | ||
| 1111 | + // before it, coded against the group before it, and that group | ||
| 1112 | + // is not in this file. Dropped rather than written as pictures | ||
| 1113 | + // no decoder can put back together. | ||
| 1114 | + if block.ts_ns < origin { | ||
| 1115 | + continue; | ||
| 1116 | + } | ||
| 1117 | + muxer.write_block(block.bytes, block.key, base + block.ts_ns - origin)?; | ||
| 1118 | + done += 1; | ||
| 1119 | + shared | ||
| 1120 | + .progress | ||
| 1121 | + .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed); | ||
| 1122 | + } | ||
| 1123 | + } | ||
| 1124 | + // Everything up to here is still cancellable, exactly as the encoded | ||
| 1125 | + // path is up to its own `finish`. | ||
| 1126 | + cancelled(shared)?; | ||
| 1127 | + muxer.finish()?; | ||
| 1128 | + shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); | ||
| 1129 | + Ok(()) | ||
| 1130 | + } | ||
| 1131 | +} | ||
| 1132 | + | ||
| 896 | /// The same lane, *decoded*: what a packet copy cannot carry comes out here as | 1133 | /// The same lane, *decoded*: what a packet copy cannot carry comes out here as |
| 897 | /// AAC written by this project's own encoder. | 1134 | /// AAC written by this project's own encoder. |
| 898 | /// | 1135 | /// |
| @@ -1013,6 +1250,28 @@ fn run( | |||
| 1013 | // so the muxer needs the lot before the first picture is written. | 1250 | // so the muxer needs the lot before the first picture is written. |
| 1014 | let mut subs = export_subtitles(project, meta, settings); | 1251 | let mut subs = export_subtitles(project, meta, settings); |
| 1015 | 1252 | ||
| 1253 | + // Before an encoder is opened at all: a timeline nobody has touched, whose | ||
| 1254 | + // sources this file can hold as they are, is written by copying their coded | ||
| 1255 | + // blocks -- the picture's half of what `copy_audio` just did for the sound, | ||
| 1256 | + // and the difference between an export bounded by the *edited* spans and one | ||
| 1257 | + // that re-encodes a whole film to change a cut. [`CopyPlan`] states the | ||
| 1258 | + // whole rule; anything at all outside it falls through to the walk below. | ||
| 1259 | + if let Some(plan) = CopyPlan::of(project, meta, settings) { | ||
| 1260 | + eprintln!("export video: copy (source packets)"); | ||
| 1261 | + *shared.encoders.lock().unwrap() = Some(format!( | ||
| 1262 | + "copy · {}", | ||
| 1263 | + audio_label(project, settings.format, sound.is_some(), sound) | ||
| 1264 | + )); | ||
| 1265 | + return plan.run( | ||
| 1266 | + out, | ||
| 1267 | + meta, | ||
| 1268 | + shared, | ||
| 1269 | + audio_params.as_ref().zip(packets.take()), | ||
| 1270 | + std::mem::take(&mut subs), | ||
| 1271 | + total, | ||
| 1272 | + ); | ||
| 1273 | + } | ||
| 1274 | + | ||
| 1016 | // One header parse per source, before any of them is decoded: what rate | 1275 | // One header parse per source, before any of them is decoded: what rate |
| 1017 | // each file was shot at against the timeline's ([`Rate`]), which is how the | 1276 | // each file was shot at against the timeline's ([`Rate`]), which is how the |
| 1018 | // clip's timeline frames below become frames of the file, and what its | 1277 | // clip's timeline frames below become frames of the file, and what its |
crates/engine/src/mux.rsmodified+101 -7
| @@ -787,6 +787,31 @@ pub struct HevcParams<'a> { | |||
| 787 | pub hvcc: &'a [u8], | 787 | pub hvcc: &'a [u8], |
| 788 | } | 788 | } |
| 789 | 789 | ||
| 790 | +/// What a *copied* track declares: the source's own codec id and configuration | ||
| 791 | +/// record, in the space its samples are really in. | ||
| 792 | +/// | ||
| 793 | +/// Nothing here is derived from the timeline -- the copy exists precisely | ||
| 794 | +/// because none of it changed -- so the picture keeps the size, the rate, the | ||
| 795 | +/// curve and the parameter sets it was coded with. | ||
| 796 | +pub struct CopyParams<'a> { | ||
| 797 | + pub width: u32, | ||
| 798 | + pub height: u32, | ||
| 799 | + pub frame_rate: f64, | ||
| 800 | + /// The Matroska codec id, `V_MPEGH/ISO/HEVC` or `V_AV1`. | ||
| 801 | + pub codec_id: &'a [u8], | ||
| 802 | + /// `CodecPrivate` as the source holds it ([`crate::demux::MkvDemuxer::codec_private`]). | ||
| 803 | + pub codec_private: &'a [u8], | ||
| 804 | + /// The source's own `Colour`: a copied HDR film leaves as the HDR film it | ||
| 805 | + /// is, because not one of its samples was touched. | ||
| 806 | + /// | ||
| 807 | + /// ponytail: the `MasteringMetadata` and MaxCLL beside it are not carried -- | ||
| 808 | + /// this engine parses them ([`crate::demux::ContentLight`]) but has nowhere | ||
| 809 | + /// to write them yet, so a copied HDR file states its curve and not its | ||
| 810 | + /// grading display. Upgrade path is a `Colour` element written from that | ||
| 811 | + /// same struct. | ||
| 812 | + pub colour: ColorDescription, | ||
| 813 | +} | ||
| 814 | + | ||
| 790 | /// The soft subtitle track a file carries beside the picture: text, timed, still | 815 | /// The soft subtitle track a file carries beside the picture: text, timed, still |
| 791 | /// text in the file -- a player draws it and a user can turn it off, which is | 816 | /// text in the file -- a player draws it and a user can turn it off, which is |
| 792 | /// what "soft" means and what burning it into the pixels is not. | 817 | /// what "soft" means and what burning it into the pixels is not. |
| @@ -851,6 +876,11 @@ pub struct MkvMuxer { | |||
| 851 | cluster: Vec<u8>, | 876 | cluster: Vec<u8>, |
| 852 | cluster_ts: i64, | 877 | cluster_ts: i64, |
| 853 | frames: u64, | 878 | frames: u64, |
| 879 | + /// The latest timestamp any picture was written at. Equal to the frame | ||
| 880 | + /// counter's own for a track this project encoded; for a *copied* one the | ||
| 881 | + /// blocks carry their source's timing and a cut can leave the last picture | ||
| 882 | + /// on screen, so the duration is measured rather than counted. | ||
| 883 | + last_ts: i64, | ||
| 854 | /// The AAC track, if the timeline has sound, and how far it has been | 884 | /// The AAC track, if the timeline has sound, and how far it has been |
| 855 | /// written. | 885 | /// written. |
| 856 | audio: Option<MkvAudio>, | 886 | audio: Option<MkvAudio>, |
| @@ -897,6 +927,7 @@ impl MkvMuxer { | |||
| 897 | video.frame_rate, | 927 | video.frame_rate, |
| 898 | b"V_AV1", | 928 | b"V_AV1", |
| 899 | &av1c, | 929 | &av1c, |
| 930 | + ColorDescription::output(video.height), | ||
| 900 | audio, | 931 | audio, |
| 901 | subs, | 932 | subs, |
| 902 | ) | 933 | ) |
| @@ -925,6 +956,39 @@ impl MkvMuxer { | |||
| 925 | video.frame_rate, | 956 | video.frame_rate, |
| 926 | b"V_MPEGH/ISO/HEVC", | 957 | b"V_MPEGH/ISO/HEVC", |
| 927 | video.hvcc, | 958 | video.hvcc, |
| 959 | + ColorDescription::output(video.height), | ||
| 960 | + audio, | ||
| 961 | + subs, | ||
| 962 | + ) | ||
| 963 | + } | ||
| 964 | + | ||
| 965 | + /// The same file with a track *copied* out of another one: the source's own | ||
| 966 | + /// codec id and `CodecPrivate`, and its own `Colour` beside them | ||
| 967 | + /// ([`crate::export`]'s copy path). | ||
| 968 | + /// | ||
| 969 | + /// Not [`Self::create_hevc`] with the source's record, because the picture | ||
| 970 | + /// is not this project's own: a copy writes the file the source's samples | ||
| 971 | + /// already are -- an HDR film stays on its PQ curve rather than being | ||
| 972 | + /// declared the SDR the encoders here write -- and the blocks are timed by | ||
| 973 | + /// [`Self::write_block`] off the source's clock rather than by a frame | ||
| 974 | + /// counter, which is the other half of the same statement. | ||
| 975 | + pub fn create_copy( | ||
| 976 | + path: &Path, | ||
| 977 | + video: &CopyParams, | ||
| 978 | + audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | ||
| 979 | + subs: Vec<SubParams>, | ||
| 980 | + ) -> crate::Result<Self> { | ||
| 981 | + if video.codec_private.is_empty() { | ||
| 982 | + return Err("the source track carries no CodecPrivate to copy".into()); | ||
| 983 | + } | ||
| 984 | + Self::open( | ||
| 985 | + path, | ||
| 986 | + video.width, | ||
| 987 | + video.height, | ||
| 988 | + video.frame_rate, | ||
| 989 | + video.codec_id, | ||
| 990 | + video.codec_private, | ||
| 991 | + video.colour, | ||
| 928 | audio, | 992 | audio, |
| 929 | subs, | 993 | subs, |
| 930 | ) | 994 | ) |
| @@ -938,6 +1002,7 @@ impl MkvMuxer { | |||
| 938 | frame_rate: f64, | 1002 | frame_rate: f64, |
| 939 | codec_id: &[u8], | 1003 | codec_id: &[u8], |
| 940 | codec_private: &[u8], | 1004 | codec_private: &[u8], |
| 1005 | + colour: ColorDescription, | ||
| 941 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | 1006 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 942 | subs: Vec<SubParams>, | 1007 | subs: Vec<SubParams>, |
| 943 | ) -> crate::Result<Self> { | 1008 | ) -> crate::Result<Self> { |
| @@ -1004,11 +1069,11 @@ impl MkvMuxer { | |||
| 1004 | uint(&mut dims, PIXEL_WIDTH, u64::from(width)); | 1069 | uint(&mut dims, PIXEL_WIDTH, u64::from(width)); |
| 1005 | uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); | 1070 | uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); |
| 1006 | // What the samples in those pixels mean. Written rather than left to a | 1071 | // What the samples in those pixels mean. Written rather than left to a |
| 1007 | - // reader's own 720-line guess -- the guess is right for this file (the | 1072 | + // reader's own 720-line guess -- the guess is right for an encoded file |
| 1008 | - // export remaps every clip into exactly that space) but a remuxer or a | 1073 | + // (the export remaps every clip into exactly that space) but a remuxer |
| 1009 | - // scaler downstream has no reason to make it, and an untagged file is | 1074 | + // or a scaler downstream has no reason to make it, and an untagged file |
| 1010 | - // how a 601 source ends up displayed as 709. | 1075 | + // is how a 601 source ends up displayed as 709. A *copied* track states |
| 1011 | - let colour = ColorDescription::output(height); | 1076 | + // its source's space instead, which is the one its samples are in. |
| 1012 | let (primaries, transfer, matrix) = colour.codes(); | 1077 | let (primaries, transfer, matrix) = colour.codes(); |
| 1013 | let mut tags = Vec::new(); | 1078 | let mut tags = Vec::new(); |
| 1014 | uint(&mut tags, MATRIX_COEFFICIENTS, u64::from(matrix)); | 1079 | uint(&mut tags, MATRIX_COEFFICIENTS, u64::from(matrix)); |
| @@ -1047,6 +1112,7 @@ impl MkvMuxer { | |||
| 1047 | cluster: Vec::new(), | 1112 | cluster: Vec::new(), |
| 1048 | cluster_ts: 0, | 1113 | cluster_ts: 0, |
| 1049 | frames: 0, | 1114 | frames: 0, |
| 1115 | + last_ts: 0, | ||
| 1050 | audio: audio.map(|(params, packets)| MkvAudio { | 1116 | audio: audio.map(|(params, packets)| MkvAudio { |
| 1051 | packets, | 1117 | packets, |
| 1052 | next: 0, | 1118 | next: 0, |
| @@ -1075,6 +1141,29 @@ impl MkvMuxer { | |||
| 1075 | } | 1141 | } |
| 1076 | let ts = (self.frames * self.frame_ns + TIMESTAMP_SCALE_NS / 2) as i64 | 1142 | let ts = (self.frames * self.frame_ns + TIMESTAMP_SCALE_NS / 2) as i64 |
| 1077 | / TIMESTAMP_SCALE_NS as i64; | 1143 | / TIMESTAMP_SCALE_NS as i64; |
| 1144 | + self.put(obus, key, ts) | ||
| 1145 | + } | ||
| 1146 | + | ||
| 1147 | + /// One coded picture *copied* out of another file, shown at `ts_ns` on this | ||
| 1148 | + /// file's clock rather than at the next frame of a counter. | ||
| 1149 | + /// | ||
| 1150 | + /// A copy has to be timed by the source's own timestamps and not by the | ||
| 1151 | + /// order the blocks arrive in: a stream with B-frames is stored in decode | ||
| 1152 | + /// order, so its timestamps step backwards over a group of pictures, and | ||
| 1153 | + /// re-timing those blocks one frame apart would play the group in the order | ||
| 1154 | + /// it was coded in. Matroska times every block in presentation and the | ||
| 1155 | + /// relative timestamp in a block header is signed, so what a copy writes | ||
| 1156 | + /// here is exactly what its source said. | ||
| 1157 | + pub fn write_block(&mut self, payload: &[u8], key: bool, ts_ns: i64) -> crate::Result<()> { | ||
| 1158 | + if payload.is_empty() { | ||
| 1159 | + return Err("an empty coded block".into()); | ||
| 1160 | + } | ||
| 1161 | + let ts = (ts_ns + TIMESTAMP_SCALE_NS as i64 / 2) / TIMESTAMP_SCALE_NS as i64; | ||
| 1162 | + self.put(payload, key, ts) | ||
| 1163 | + } | ||
| 1164 | + | ||
| 1165 | + /// One block into the cluster it belongs in, whatever timed it. | ||
| 1166 | + fn put(&mut self, payload: &[u8], key: bool, ts: i64) -> crate::Result<()> { | ||
| 1078 | // A new cluster at every keyframe -- a seek lands on one, so a cluster | 1167 | // A new cluster at every keyframe -- a seek lands on one, so a cluster |
| 1079 | // is a whole GOP -- and at the two limits a cluster has whatever the | 1168 | // is a whole GOP -- and at the two limits a cluster has whatever the |
| 1080 | // encoder keys: what it may weigh, and how far a 16-bit relative | 1169 | // encoder keys: what it may weigh, and how far a 16-bit relative |
| @@ -1093,8 +1182,9 @@ impl MkvMuxer { | |||
| 1093 | // them, for the same reason. | 1182 | // them, for the same reason. |
| 1094 | self.drain_audio(ts)?; | 1183 | self.drain_audio(ts)?; |
| 1095 | self.drain_subs(ts)?; | 1184 | self.drain_subs(ts)?; |
| 1096 | - self.block(1, ts, key, obus); | 1185 | + self.block(1, ts, key, payload); |
| 1097 | self.frames += 1; | 1186 | self.frames += 1; |
| 1187 | + self.last_ts = self.last_ts.max(ts); | ||
| 1098 | Ok(()) | 1188 | Ok(()) |
| 1099 | } | 1189 | } |
| 1100 | 1190 | ||
| @@ -1230,7 +1320,11 @@ impl MkvMuxer { | |||
| 1230 | let size = (1u64 << 56) | body; | 1320 | let size = (1u64 << 56) | body; |
| 1231 | self.file.seek(SeekFrom::Start(self.segment_size_at))?; | 1321 | self.file.seek(SeekFrom::Start(self.segment_size_at))?; |
| 1232 | self.file.write_all(&size.to_be_bytes())?; | 1322 | self.file.write_all(&size.to_be_bytes())?; |
| 1233 | - let ms = self.frames as f64 * self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64; | 1323 | + // One frame past the last picture shown, which is where the file really |
| 1324 | + // ends: counting the frames instead would cut a copied track short by | ||
| 1325 | + // however many pictures a cut left the one before it on screen for. | ||
| 1326 | + let ms = (self.frames as f64 * self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64) | ||
| 1327 | + .max(self.last_ts as f64 + self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64); | ||
| 1234 | self.file.seek(SeekFrom::Start(self.duration_at))?; | 1328 | self.file.seek(SeekFrom::Start(self.duration_at))?; |
| 1235 | self.file.write_all(&ms.to_be_bytes())?; | 1329 | self.file.write_all(&ms.to_be_bytes())?; |
| 1236 | self.file.flush()?; | 1330 | self.file.flush()?; |
crates/engine/tests/video_copy.rsadded+530 -0
| @@ -0,0 +1,530 @@ | |||
| 1 | +//! The video copy path: a Matroska timeline nobody has touched leaves as the | ||
| 2 | +//! very coded blocks its source holds, and one that anybody *has* touched still | ||
| 3 | +//! goes through the encoder. | ||
| 4 | +//! | ||
| 5 | +//! What is measured here is not "a file came out": it is that the bytes of the | ||
| 6 | +//! file that came out are the source's own, that the pictures either side of a | ||
| 7 | +//! cut still decode through this project's own decoder, and that every gate the | ||
| 8 | +//! copy claims to have really refuses. | ||
| 9 | +//! | ||
| 10 | +//! ```text | ||
| 11 | +//! cargo build -p engine -p engine-hw --release | ||
| 12 | +//! LD_LIBRARY_PATH=target/release \ | ||
| 13 | +//! cargo test -p engine --release --test video_copy -- --test-threads=1 | ||
| 14 | +//! ``` | ||
| 15 | +//! | ||
| 16 | +//! The plugin is needed only by the decode-back test (there is no software HEVC | ||
| 17 | +//! decoder here); the copy itself decodes nothing and needs nothing. The | ||
| 18 | +//! multi-cut tests build their own source with the `ffmpeg` CLI -- the fixture | ||
| 19 | +//! suite's HEVC file is two groups of pictures long, which has no interior to | ||
| 20 | +//! splice -- and say so and pass where it is not installed, exactly as | ||
| 21 | +//! `tests/hevc_export.rs` does. | ||
| 22 | + | ||
| 23 | +use std::path::{Path, PathBuf}; | ||
| 24 | +use std::process::Command; | ||
| 25 | +use std::time::{Duration, Instant}; | ||
| 26 | + | ||
| 27 | +use engine::demux::Demuxer; | ||
| 28 | +use engine::export::{ExportSettings, Format}; | ||
| 29 | +use engine::hw::HwSession; | ||
| 30 | +use engine::project::{Lane, Speed}; | ||
| 31 | +use engine::scratch::Scratch; | ||
| 32 | +use engine::{DecodeSession, PlaybackSession}; | ||
| 33 | + | ||
| 34 | +fn asset(name: &str) -> PathBuf { | ||
| 35 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 36 | + .join("../../assets") | ||
| 37 | + .join(name) | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/// One coded block of a Matroska picture track, as the file holds it. | ||
| 41 | +#[derive(PartialEq)] | ||
| 42 | +struct Coded { | ||
| 43 | + bytes: Vec<u8>, | ||
| 44 | + key: bool, | ||
| 45 | + ts_ns: i64, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// Every block of `path`'s picture track, in the file's own order. | ||
| 49 | +fn blocks(path: &Path) -> Vec<Coded> { | ||
| 50 | + let (_, demuxer) = Demuxer::open(path).expect("open"); | ||
| 51 | + let Demuxer::Mkv(mut demuxer) = demuxer else { | ||
| 52 | + panic!("{} is not Matroska", path.display()); | ||
| 53 | + }; | ||
| 54 | + (0..demuxer.block_count()) | ||
| 55 | + .map(|i| { | ||
| 56 | + let block = demuxer | ||
| 57 | + .coded_block(i) | ||
| 58 | + .expect("read a block") | ||
| 59 | + .expect("a block at an index the count states"); | ||
| 60 | + Coded { | ||
| 61 | + bytes: block.bytes.to_vec(), | ||
| 62 | + key: block.key, | ||
| 63 | + ts_ns: block.ts_ns, | ||
| 64 | + } | ||
| 65 | + }) | ||
| 66 | + .collect() | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/// Runs an export to completion and hands back the encoder line it published -- | ||
| 70 | +/// which is where a copy says it was one. | ||
| 71 | +fn export(session: &PlaybackSession, out: &Path, format: Format) -> String { | ||
| 72 | + let settings = ExportSettings { | ||
| 73 | + format, | ||
| 74 | + ..Default::default() | ||
| 75 | + }; | ||
| 76 | + let handle = session.export_to_with(out, &settings); | ||
| 77 | + let started = Instant::now(); | ||
| 78 | + while !handle.is_finished() { | ||
| 79 | + assert!( | ||
| 80 | + started.elapsed() < Duration::from_secs(600), | ||
| 81 | + "the export did not finish in 600 s" | ||
| 82 | + ); | ||
| 83 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 84 | + } | ||
| 85 | + let encoders = handle.encoders().unwrap_or_default(); | ||
| 86 | + handle | ||
| 87 | + .result() | ||
| 88 | + .expect("an outcome") | ||
| 89 | + .unwrap_or_else(|e| panic!("export failed: {e}")); | ||
| 90 | + encoders | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// A source of `gops` groups of pictures at 30 fps, keyed every 30 frames, with | ||
| 94 | +/// B-frames and the open groups x265 writes by default -- which is the shape a | ||
| 95 | +/// film off a disc has and the shape the copy path has to survive. `None` where | ||
| 96 | +/// `ffmpeg` is not installed. | ||
| 97 | +fn multi_gop(name: &str, gops: u32) -> Option<Scratch> { | ||
| 98 | + let out = Scratch::file(name, "mkv"); | ||
| 99 | + let seconds = gops.to_string(); | ||
| 100 | + let ok = Command::new("ffmpeg") | ||
| 101 | + .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) | ||
| 102 | + .arg(format!("testsrc2=size=320x240:rate=30:duration={seconds}")) | ||
| 103 | + .args(["-f", "lavfi", "-i"]) | ||
| 104 | + .arg(format!("sine=frequency=440:duration={seconds}")) | ||
| 105 | + .args([ | ||
| 106 | + "-map", | ||
| 107 | + "0:v", | ||
| 108 | + "-map", | ||
| 109 | + "1:a", | ||
| 110 | + "-c:v", | ||
| 111 | + "libx265", | ||
| 112 | + "-x265-params", | ||
| 113 | + "log-level=error:keyint=30:min-keyint=30:scenecut=0", | ||
| 114 | + "-pix_fmt", | ||
| 115 | + "yuv420p", | ||
| 116 | + "-c:a", | ||
| 117 | + "aac", | ||
| 118 | + "-b:a", | ||
| 119 | + "128k", | ||
| 120 | + ]) | ||
| 121 | + .arg(&out) | ||
| 122 | + .status() | ||
| 123 | + .ok()?; | ||
| 124 | + ok.success().then_some(out) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// An untouched Matroska timeline is written by copying: the file that comes out | ||
| 128 | +/// holds its source's blocks, byte for byte, with the same sync points and the | ||
| 129 | +/// same timing -- reordered B-frames included, which is the thing a frame | ||
| 130 | +/// counter would silently get wrong. | ||
| 131 | +#[test] | ||
| 132 | +fn an_untouched_matroska_timeline_leaves_as_its_source_packets() { | ||
| 133 | + let source = asset("test_hevc.mkv"); | ||
| 134 | + let session = PlaybackSession::open(&source).expect("open the fixture"); | ||
| 135 | + let out = Scratch::file("ve_copy_untouched", "mkv"); | ||
| 136 | + let line = export(&session, &out, Format::Hevc); | ||
| 137 | + assert!( | ||
| 138 | + line.starts_with("copy · "), | ||
| 139 | + "an untouched timeline was not copied: {line}" | ||
| 140 | + ); | ||
| 141 | + let (before, after) = (blocks(&source), blocks(&out)); | ||
| 142 | + assert_eq!(before.len(), after.len(), "block count"); | ||
| 143 | + for (i, (a, b)) in before.iter().zip(&after).enumerate() { | ||
| 144 | + assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes"); | ||
| 145 | + assert_eq!(a.key, b.key, "block {i} sync flag"); | ||
| 146 | + // Millisecond ticks either side, so the comparison is the timestamp the | ||
| 147 | + // container can really state. | ||
| 148 | + assert_eq!( | ||
| 149 | + a.ts_ns / 1_000_000, | ||
| 150 | + b.ts_ns / 1_000_000, | ||
| 151 | + "block {i} is shown at another time than its source" | ||
| 152 | + ); | ||
| 153 | + } | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// The same for AV1, whose blocks are whole temporal units rather than | ||
| 157 | +/// length-prefixed NALs: one gate, two codecs, and the file says which. | ||
| 158 | +#[test] | ||
| 159 | +fn an_untouched_av1_timeline_leaves_as_its_source_packets() { | ||
| 160 | + let source = asset("test_av1.mkv"); | ||
| 161 | + let session = PlaybackSession::open(&source).expect("open the fixture"); | ||
| 162 | + let out = Scratch::file("ve_copy_av1", "mkv"); | ||
| 163 | + let line = export(&session, &out, Format::Av1); | ||
| 164 | + assert!(line.starts_with("copy · "), "AV1 was not copied: {line}"); | ||
| 165 | + let (before, after) = (blocks(&source), blocks(&out)); | ||
| 166 | + assert_eq!(before.len(), after.len(), "block count"); | ||
| 167 | + for (i, (a, b)) in before.iter().zip(&after).enumerate() { | ||
| 168 | + assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes"); | ||
| 169 | + } | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +/// A cut placed on a sync point: the middle of the film is deleted and both | ||
| 173 | +/// sides leave as copies. What is checked is the join -- the blocks either side | ||
| 174 | +/// of it are the source's own, the timestamps rise a frame at a time across it | ||
| 175 | +/// once they are put back in display order, and nothing but the leading | ||
| 176 | +/// pictures the cut orphaned is missing. | ||
| 177 | +#[test] | ||
| 178 | +fn a_cut_on_a_keyframe_copies_both_sides() { | ||
| 179 | + let Some(source) = multi_gop("ve_copy_source", 6) else { | ||
| 180 | + println!("ffmpeg is not installed: skipping the multi-cut copy test"); | ||
| 181 | + return; | ||
| 182 | + }; | ||
| 183 | + let before = blocks(&source); | ||
| 184 | + let keys: Vec<usize> = (0..before.len()).filter(|&i| before[i].key).collect(); | ||
| 185 | + assert!(keys.len() >= 4, "expected several groups, got {keys:?}"); | ||
| 186 | + // Frames 60 and 120 in the block order the whole engine counts in. | ||
| 187 | + let (first, second) = (keys[2], keys[4]); | ||
| 188 | + let mut session = PlaybackSession::open(&source).expect("open the source"); | ||
| 189 | + let fps = session.meta().frame_rate; | ||
| 190 | + assert!(session.cut_at(first as f64 / fps), "cut at the third group"); | ||
| 191 | + assert!( | ||
| 192 | + session.cut_at(second as f64 / fps), | ||
| 193 | + "cut at the fifth group" | ||
| 194 | + ); | ||
| 195 | + // One call: the picture and the sound of a take are one group, so | ||
| 196 | + // deleting the clip takes its lane partner with it. | ||
| 197 | + assert!(session.delete_clip(Lane::V1, 1), "drop the middle clip"); | ||
| 198 | + | ||
| 199 | + let out = Scratch::file("ve_copy_cut", "mkv"); | ||
| 200 | + let line = export(&session, &out, Format::Hevc); | ||
| 201 | + assert!( | ||
| 202 | + line.starts_with("copy · "), | ||
| 203 | + "a keyframe cut was not copied: {line}" | ||
| 204 | + ); | ||
| 205 | + | ||
| 206 | + // What the file should hold: the blocks before the cut, then the blocks | ||
| 207 | + // after it minus the leading pictures the second region orphaned -- those | ||
| 208 | + // are shown before their own sync point and reference the group this cut | ||
| 209 | + // threw away. | ||
| 210 | + let after = blocks(&out); | ||
| 211 | + let mut want: Vec<&Coded> = before[..first].iter().collect(); | ||
| 212 | + let origin = before[second].ts_ns; | ||
| 213 | + want.extend(before[second..].iter().filter(|b| b.ts_ns >= origin)); | ||
| 214 | + assert_eq!(after.len(), want.len(), "copied block count"); | ||
| 215 | + for (i, (a, b)) in want.iter().zip(&after).enumerate() { | ||
| 216 | + assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes"); | ||
| 217 | + assert_eq!(a.key, b.key, "block {i} sync flag"); | ||
| 218 | + } | ||
| 219 | + // Put back in display order, the file is a frame grid with one hole: the | ||
| 220 | + // frames the second region's dropped leading pictures would have filled, | ||
| 221 | + // which is where the picture before the cut is held instead. | ||
| 222 | + let mut shown: Vec<i64> = after.iter().map(|b| b.ts_ns / 1_000_000).collect(); | ||
| 223 | + shown.sort_unstable(); | ||
| 224 | + let step = (1000.0 / fps).round() as i64; | ||
| 225 | + let holes = shown | ||
| 226 | + .windows(2) | ||
| 227 | + .filter(|w| (w[1] - w[0] - step).abs() > 1) | ||
| 228 | + .count(); | ||
| 229 | + assert!( | ||
| 230 | + holes <= 1, | ||
| 231 | + "the copied file is not one run of frames: {holes} holes in {shown:?}" | ||
| 232 | + ); | ||
| 233 | + assert_eq!(shown[0], 0, "the file starts at the timeline's own zero"); | ||
| 234 | +} | ||
| 235 | + | ||
| 236 | +/// ...and that join really decodes: every picture around it comes back through | ||
| 237 | +/// this project's own demuxer and decoder, in order, without an error and | ||
| 238 | +/// without a black frame where the cut is. | ||
| 239 | +#[test] | ||
| 240 | +fn the_pictures_either_side_of_a_copied_cut_decode() { | ||
| 241 | + let Some(source) = multi_gop("ve_copy_decode_source", 6) else { | ||
| 242 | + println!("ffmpeg is not installed: skipping the copied-join decode test"); | ||
| 243 | + return; | ||
| 244 | + }; | ||
| 245 | + let before = blocks(&source); | ||
| 246 | + let keys: Vec<usize> = (0..before.len()).filter(|&i| before[i].key).collect(); | ||
| 247 | + let (first, second) = (keys[2], keys[4]); | ||
| 248 | + let mut session = PlaybackSession::open(&source).expect("open the source"); | ||
| 249 | + let fps = session.meta().frame_rate; | ||
| 250 | + assert!(session.cut_at(first as f64 / fps)); | ||
| 251 | + assert!(session.cut_at(second as f64 / fps)); | ||
| 252 | + assert!(session.delete_clip(Lane::V1, 1)); | ||
| 253 | + let out = Scratch::file("ve_copy_decode", "mkv"); | ||
| 254 | + let line = export(&session, &out, Format::Hevc); | ||
| 255 | + assert!(line.starts_with("copy · "), "not copied: {line}"); | ||
| 256 | + | ||
| 257 | + let (meta, frames) = match DecodeSession::open(&out) { | ||
| 258 | + Ok(open) => open, | ||
| 259 | + Err(e) => { | ||
| 260 | + println!("no HEVC decoder here ({e}): skipping the decode-back"); | ||
| 261 | + return; | ||
| 262 | + } | ||
| 263 | + }; | ||
| 264 | + let mut seen = Vec::new(); | ||
| 265 | + for frame in frames { | ||
| 266 | + let luma: u64 = frame | ||
| 267 | + .bgra | ||
| 268 | + .chunks_exact(4) | ||
| 269 | + .map(|px| u64::from(px[1])) | ||
| 270 | + .sum::<u64>() | ||
| 271 | + / (u64::from(frame.width) * u64::from(frame.height)); | ||
| 272 | + seen.push((frame.index, luma)); | ||
| 273 | + } | ||
| 274 | + assert!( | ||
| 275 | + seen.len() >= meta.frame_count as usize - 8, | ||
| 276 | + "{} pictures decoded of {}", | ||
| 277 | + seen.len(), | ||
| 278 | + meta.frame_count | ||
| 279 | + ); | ||
| 280 | + for (i, (index, _)) in seen.iter().enumerate() { | ||
| 281 | + assert_eq!(*index as usize, i, "pictures came back out of order"); | ||
| 282 | + } | ||
| 283 | + // The join is at the first region's length; a frame either side of it is a | ||
| 284 | + // real picture rather than the black a broken splice decodes to. | ||
| 285 | + let joint = first.min(seen.len() - 1); | ||
| 286 | + for at in [0, joint.saturating_sub(2), joint, seen.len() - 1] { | ||
| 287 | + assert!( | ||
| 288 | + seen[at].1 > 4, | ||
| 289 | + "picture {at} around the join is black ({} luma)", | ||
| 290 | + seen[at].1 | ||
| 291 | + ); | ||
| 292 | + } | ||
| 293 | +} | ||
| 294 | + | ||
| 295 | +/// Every gate the copy claims: a grade, a speed and a format whose container | ||
| 296 | +/// this path does not write all put the export back through the encoder. A copy | ||
| 297 | +/// that took any of these would write a file that is not what was watched. | ||
| 298 | +#[test] | ||
| 299 | +fn a_touched_timeline_is_still_encoded() { | ||
| 300 | + let source = asset("test_hevc.mkv"); | ||
| 301 | + let out = Scratch::file("ve_copy_gate", "mkv"); | ||
| 302 | + | ||
| 303 | + let mut graded = PlaybackSession::open(&source).expect("open"); | ||
| 304 | + assert!(graded.set_color( | ||
| 305 | + Lane::V1, | ||
| 306 | + 0, | ||
| 307 | + Some(engine::color::ColorParams { | ||
| 308 | + saturation: 1.4, | ||
| 309 | + ..Default::default() | ||
| 310 | + }) | ||
| 311 | + )); | ||
| 312 | + let line = export(&graded, &out, Format::Hevc); | ||
| 313 | + assert!( | ||
| 314 | + !line.starts_with("copy"), | ||
| 315 | + "a graded timeline was copied: {line}" | ||
| 316 | + ); | ||
| 317 | + | ||
| 318 | + let mut speeded = PlaybackSession::open(&source).expect("open"); | ||
| 319 | + speeded | ||
| 320 | + .set_speed(Lane::V1, 0, Speed::from_permille(2000)) | ||
| 321 | + .expect("speed the clip"); | ||
| 322 | + let line = export(&speeded, &out, Format::Hevc); | ||
| 323 | + assert!( | ||
| 324 | + !line.starts_with("copy"), | ||
| 325 | + "a speeded timeline was copied: {line}" | ||
| 326 | + ); | ||
| 327 | + | ||
| 328 | + // The same untouched timeline into an mp4: nothing here copies into one, | ||
| 329 | + // because a sample entry states its parameter sets once and the mp4 muxer | ||
| 330 | + // times its samples by a frame counter. | ||
| 331 | + let plain = PlaybackSession::open(&source).expect("open"); | ||
| 332 | + let mp4 = Scratch::file("ve_copy_gate_mp4", "mp4"); | ||
| 333 | + let line = export(&plain, &mp4, Format::HevcMp4); | ||
| 334 | + assert!(!line.starts_with("copy"), "an mp4 was copied: {line}"); | ||
| 335 | +} | ||
| 336 | + | ||
| 337 | +/// A cut that lands between two sync points is the case this path refuses: the | ||
| 338 | +/// head of the second region would need pictures that are not in the file, so | ||
| 339 | +/// the whole export goes back through the encoder rather than writing a file | ||
| 340 | +/// whose first second cannot be decoded. | ||
| 341 | +#[test] | ||
| 342 | +fn a_cut_off_the_keyframe_grid_falls_back_to_the_encoder() { | ||
| 343 | + let source = asset("test_hevc.mkv"); | ||
| 344 | + let mut session = PlaybackSession::open(&source).expect("open"); | ||
| 345 | + let fps = session.meta().frame_rate; | ||
| 346 | + // Block 40 of a file keyed every 30: inside the second group. | ||
| 347 | + assert!(session.cut_at(40.0 / fps), "cut mid-group"); | ||
| 348 | + assert!(session.delete_clip(Lane::V1, 0), "drop the first clip"); | ||
| 349 | + let out = Scratch::file("ve_copy_offgrid", "mkv"); | ||
| 350 | + let line = export(&session, &out, Format::Hevc); | ||
| 351 | + assert!( | ||
| 352 | + !line.starts_with("copy"), | ||
| 353 | + "a cut off the sync grid was copied: {line}" | ||
| 354 | + ); | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +/// The measurement this path exists for, on a real film rather than a fixture: | ||
| 358 | +/// a 4K HDR x265 Matroska of two and a half hours, cut once in the middle, out | ||
| 359 | +/// to Matroska. What it costs is the *edited* spans -- which for a copy is no | ||
| 360 | +/// spans at all -- plus reading and writing the bytes, against a re-encode that | ||
| 361 | +/// codes every one of its 167 thousand pictures. | ||
| 362 | +/// | ||
| 363 | +/// `#[ignore]`d and named by environment, so no path off this machine is in the | ||
| 364 | +/// repository and the suite runs without the file: | ||
| 365 | +/// | ||
| 366 | +/// ```text | ||
| 367 | +/// VE_FILM=/path/to/film.mkv VE_OUT=/somewhere/cut.mkv \ | ||
| 368 | +/// cargo test -p engine --release --test video_copy -- --ignored --nocapture \ | ||
| 369 | +/// a_real_film | ||
| 370 | +/// ``` | ||
| 371 | +#[test] | ||
| 372 | +#[ignore] | ||
| 373 | +fn a_real_film_is_cut_by_copying_its_spans() { | ||
| 374 | + let Ok(film) = std::env::var("VE_FILM") else { | ||
| 375 | + println!("VE_FILM is not set: skipping the real-film copy measurement"); | ||
| 376 | + return; | ||
| 377 | + }; | ||
| 378 | + let film = PathBuf::from(film); | ||
| 379 | + let opened = Instant::now(); | ||
| 380 | + let (meta, demuxer) = Demuxer::open(&film).expect("open the film"); | ||
| 381 | + let Demuxer::Mkv(mut source) = demuxer else { | ||
| 382 | + panic!("the film is not Matroska"); | ||
| 383 | + }; | ||
| 384 | + println!( | ||
| 385 | + "film: {}x{} {:?} {:.4} fps, {} blocks, indexed in {:?}", | ||
| 386 | + meta.width, | ||
| 387 | + meta.height, | ||
| 388 | + meta.codec, | ||
| 389 | + meta.frame_rate, | ||
| 390 | + source.block_count(), | ||
| 391 | + opened.elapsed() | ||
| 392 | + ); | ||
| 393 | + // The cut: five minutes taken out of the middle of the film, on the two | ||
| 394 | + // sync points nearest the half-hour marks -- which is what placing a cut on | ||
| 395 | + // a keyframe means, and what the copy needs of any cut. | ||
| 396 | + let mut sync_at = |from: u32| { | ||
| 397 | + (from as usize..source.block_count()) | ||
| 398 | + .find(|&i| source.is_sync(i)) | ||
| 399 | + .expect("a sync point after the mark") | ||
| 400 | + }; | ||
| 401 | + let (first, second) = ( | ||
| 402 | + sync_at((30.0 * 60.0 * meta.frame_rate) as u32), | ||
| 403 | + sync_at((35.0 * 60.0 * meta.frame_rate) as u32), | ||
| 404 | + ); | ||
| 405 | + println!( | ||
| 406 | + "cutting blocks {first}..{second} out of {}", | ||
| 407 | + meta.frame_count | ||
| 408 | + ); | ||
| 409 | + | ||
| 410 | + let mut session = PlaybackSession::open(&film).expect("open the film as a project"); | ||
| 411 | + let fps = session.meta().frame_rate; | ||
| 412 | + assert!(session.cut_at(first as f64 / fps), "cut at the first mark"); | ||
| 413 | + assert!( | ||
| 414 | + session.cut_at(second as f64 / fps), | ||
| 415 | + "cut at the second mark" | ||
| 416 | + ); | ||
| 417 | + assert!(session.delete_clip(Lane::V1, 1), "drop the middle"); | ||
| 418 | + | ||
| 419 | + let out = PathBuf::from( | ||
| 420 | + std::env::var("VE_OUT").unwrap_or_else(|_| "/tmp/ve_real_film_cut.mkv".into()), | ||
| 421 | + ); | ||
| 422 | + let started = Instant::now(); | ||
| 423 | + let line = export(&session, &out, Format::Hevc); | ||
| 424 | + let took = started.elapsed(); | ||
| 425 | + let bytes = std::fs::metadata(&out).expect("the exported file").len(); | ||
| 426 | + println!("exported {} MB in {:?} ({line})", bytes / 1_000_000, took); | ||
| 427 | + assert!( | ||
| 428 | + line.starts_with("copy · "), | ||
| 429 | + "the film was not copied: {line}" | ||
| 430 | + ); | ||
| 431 | + | ||
| 432 | + // The bytes: every block around either side of the join, and a sample | ||
| 433 | + // across the rest -- a whole-file comparison is a second read of twelve | ||
| 434 | + // gigabytes and says nothing this does not. | ||
| 435 | + let mut written = blocks(&out); | ||
| 436 | + println!("{} blocks written of {}", written.len(), meta.frame_count); | ||
| 437 | + let origin = { | ||
| 438 | + let block = source.coded_block(second).expect("read").expect("a block"); | ||
| 439 | + block.ts_ns | ||
| 440 | + }; | ||
| 441 | + let mut want: Vec<usize> = (0..first).collect(); | ||
| 442 | + want.extend((second..source.block_count()).filter(|&i| { | ||
| 443 | + let block = source.coded_block(i).expect("read").expect("a block"); | ||
| 444 | + block.ts_ns >= origin | ||
| 445 | + })); | ||
| 446 | + assert_eq!(written.len(), want.len(), "copied block count"); | ||
| 447 | + let near_join = first.saturating_sub(200)..(first + 200).min(want.len()); | ||
| 448 | + for (out_index, &source_index) in want.iter().enumerate() { | ||
| 449 | + if !near_join.contains(&out_index) && out_index % 500 != 0 { | ||
| 450 | + continue; | ||
| 451 | + } | ||
| 452 | + let block = source | ||
| 453 | + .coded_block(source_index) | ||
| 454 | + .expect("read") | ||
| 455 | + .expect("a block"); | ||
| 456 | + assert_eq!( | ||
| 457 | + block.bytes, | ||
| 458 | + written[out_index].bytes.as_slice(), | ||
| 459 | + "block {out_index} of the export is not source block {source_index}" | ||
| 460 | + ); | ||
| 461 | + assert_eq!( | ||
| 462 | + block.key, written[out_index].key, | ||
| 463 | + "block {out_index} sync flag" | ||
| 464 | + ); | ||
| 465 | + } | ||
| 466 | + // The join itself, in display order: one run of frames with at most the one | ||
| 467 | + // hole the orphaned leading pictures leave. | ||
| 468 | + written.sort_by_key(|b| b.ts_ns); | ||
| 469 | + let step = (1e9 / fps).round() as i64; | ||
| 470 | + let holes: Vec<i64> = written | ||
| 471 | + .windows(2) | ||
| 472 | + .map(|w| w[1].ts_ns - w[0].ts_ns) | ||
| 473 | + .filter(|d| (d - step).abs() > step / 2) | ||
| 474 | + .collect(); | ||
| 475 | + println!("gaps in the shown order: {holes:?} ns (one frame is {step} ns)"); | ||
| 476 | + assert!(holes.len() <= 1, "the copied film is not one run of frames"); | ||
| 477 | + | ||
| 478 | + // ...and the join really decodes: two seconds either side of it, through | ||
| 479 | + // this project's own demuxer and decoder, in order and never black. The | ||
| 480 | + // start and the end of the film with them, so the file is exercised end to | ||
| 481 | + // end and not only where it was cut. | ||
| 482 | + let seconds = fps.round() as usize * 2; | ||
| 483 | + let decode_at = |path: &Path, at: u32| -> Option<Vec<u64>> { | ||
| 484 | + let mut decoder = HwSession::open_at(path, at)?; | ||
| 485 | + let mut lumas = Vec::new(); | ||
| 486 | + while lumas.len() < seconds { | ||
| 487 | + let Some((y, _, _, w, h)) = decoder.next_frame().expect("decode") else { | ||
| 488 | + break; | ||
| 489 | + }; | ||
| 490 | + lumas | ||
| 491 | + .push(y.iter().map(|&s| u64::from(s)).sum::<u64>() / (u64::from(w) * u64::from(h))); | ||
| 492 | + } | ||
| 493 | + Some(lumas) | ||
| 494 | + }; | ||
| 495 | + // The tail is measured against the *source's* own tail rather than against | ||
| 496 | + // the count asked for: a decoder drains the last group of pictures the same | ||
| 497 | + // way in both files (45 of the last 48 on this film, measured), and a copy | ||
| 498 | + // is right when it behaves as its source does, not when it behaves better. | ||
| 499 | + let tail = decode_at(&film, meta.frame_count - seconds as u32).map(|l| l.len()); | ||
| 500 | + for (what, at, least) in [ | ||
| 501 | + ("the start", 0, seconds), | ||
| 502 | + ("the join", first as u32 - seconds as u32, seconds), | ||
| 503 | + ( | ||
| 504 | + "the end", | ||
| 505 | + written.len() as u32 - seconds as u32, | ||
| 506 | + tail.unwrap_or(seconds), | ||
| 507 | + ), | ||
| 508 | + ] { | ||
| 509 | + let Some(lumas) = decode_at(&out, at) else { | ||
| 510 | + println!("no VA-API plugin here: skipping the decode of {what}"); | ||
| 511 | + break; | ||
| 512 | + }; | ||
| 513 | + println!( | ||
| 514 | + "{what} at frame {at}: {} pictures, luma {lumas:?}", | ||
| 515 | + lumas.len() | ||
| 516 | + ); | ||
| 517 | + assert!( | ||
| 518 | + lumas.len() >= least, | ||
| 519 | + "{what} decoded {} pictures of the {least} its source gives", | ||
| 520 | + lumas.len() | ||
| 521 | + ); | ||
| 522 | + // Limited-range black is 16, and this film opens and closes on it; what | ||
| 523 | + // a broken splice decodes to is 0, and what it never does is stay in | ||
| 524 | + // step with the source's own luma. | ||
| 525 | + assert!( | ||
| 526 | + lumas.iter().all(|&l| l >= 15), | ||
| 527 | + "a black picture around {what}: {lumas:?}" | ||
| 528 | + ); | ||
| 529 | + } | ||
| 530 | +} | ||