A big film gets a small stand-in to cut with
Browse files at this commit83e561d1e8722d3c7d1b793cf0d002d68872aac7Parent: 267d45b- feat
- a big film gets a small stand-in to cut with
6 changed files +615 -24
- crates/engine/src/demux.rs +53 -15
- crates/engine/src/export.rs +69 -9
- crates/engine/src/lib.rs +1 -0
- crates/engine/src/mux.rs +10 -0
- crates/engine/src/proxy.rs +325 -0
- crates/engine/tests/export.rs +157 -0
crates/engine/src/demux.rsmodified+53 -15
| @@ -771,6 +771,31 @@ impl Mp4Demuxer { | |||
| 771 | self.next_sample = chosen; | 771 | self.next_sample = chosen; |
| 772 | i64::from(chosen) - i64::from(self.first_sample) | 772 | i64::from(chosen) - i64::from(self.first_sample) |
| 773 | } | 773 | } |
| 774 | + | ||
| 775 | + /// Every frame a decoder may be started from, by the index this engine | ||
| 776 | + /// counts a source's frames in -- the sample table's own answer, which is | ||
| 777 | + /// why an mp4 costs no walk to ask ([`sync_points`]). A track with no `stss` | ||
| 778 | + /// box is every frame, which is what the box's absence means. | ||
| 779 | + fn sync_frames(&self) -> Vec<u32> { | ||
| 780 | + let frames = self.sample_count.saturating_sub(self.first_sample - 1); | ||
| 781 | + if self.sync_samples.is_empty() { | ||
| 782 | + return (0..frames).collect(); | ||
| 783 | + } | ||
| 784 | + // With composition offsets in play a sample id is not a frame index, and | ||
| 785 | + // the display-order table beside it is the one that answers -- the split | ||
| 786 | + // [`Self::seek_to_sync_at_or_before`] makes, for its reason. | ||
| 787 | + if !self.sync_display.is_empty() { | ||
| 788 | + return self | ||
| 789 | + .sync_display | ||
| 790 | + .iter() | ||
| 791 | + .filter_map(|&(display, _)| display.checked_sub(self.first_display)) | ||
| 792 | + .collect(); | ||
| 793 | + } | ||
| 794 | + self.sync_samples | ||
| 795 | + .iter() | ||
| 796 | + .filter_map(|&id| id.checked_sub(self.first_sample)) | ||
| 797 | + .collect() | ||
| 798 | + } | ||
| 774 | } | 799 | } |
| 775 | 800 | ||
| 776 | /// One Matroska block of an indexed track: where its bytes are, whether a | 801 | /// One Matroska block of an indexed track: where its bytes are, whether a |
| @@ -1504,15 +1529,18 @@ pub struct CodedBlock<'a> { | |||
| 1504 | /// ([`crate::export::planned_seats`] is the same question asked of a whole | 1529 | /// ([`crate::export::planned_seats`] is the same question asked of a whole |
| 1505 | /// timeline). | 1530 | /// timeline). |
| 1506 | /// | 1531 | /// |
| 1507 | -/// Empty for anything that is not Matroska, which is exactly the set of files | 1532 | +/// Empty for a file that will not open, and for a Matroska one whose clusters |
| 1508 | -/// the copy path refuses anyway, and for a file whose clusters cannot be walked. | 1533 | +/// cannot be walked. |
| 1509 | /// | 1534 | /// |
| 1510 | -/// Costs that walk, once per file (6.7 s on a 12.9 GB film, then a sidecar read | 1535 | +/// An mp4 answers off its `stss` table for nothing; Matroska costs the walk, |
| 1511 | -/// of a few milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render | 1536 | +/// once per file (6.7 s on a 12.9 GB film, then a sidecar read of a few |
| 1512 | -/// thread. | 1537 | +/// milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render thread. |
| 1513 | pub fn sync_points(path: &Path) -> Vec<u32> { | 1538 | pub fn sync_points(path: &Path) -> Vec<u32> { |
| 1514 | if !is_matroska(path) { | 1539 | if !is_matroska(path) { |
| 1515 | - return Vec::new(); | 1540 | + return match Demuxer::open(path) { |
| 1541 | + Ok((_, Demuxer::Mp4(mp4))) => mp4.sync_frames(), | ||
| 1542 | + _ => Vec::new(), | ||
| 1543 | + }; | ||
| 1516 | } | 1544 | } |
| 1517 | let Ok((_, Demuxer::Mkv(mut demuxer))) = Demuxer::open(path) else { | 1545 | let Ok((_, Demuxer::Mkv(mut demuxer))) = Demuxer::open(path) else { |
| 1518 | return Vec::new(); | 1546 | return Vec::new(); |
| @@ -2839,7 +2867,11 @@ impl IndexKey { | |||
| 2839 | /// picture track) and the directory is the user's own cache to delete, but a | 2867 | /// picture track) and the directory is the user's own cache to delete, but a |
| 2840 | /// size-capped LRU sweep at open is the upgrade path if it ever matters. | 2868 | /// size-capped LRU sweep at open is the upgrade path if it ever matters. |
| 2841 | fn sidecar(&self) -> Option<PathBuf> { | 2869 | fn sidecar(&self) -> Option<PathBuf> { |
| 2842 | - let dir = index_dir(std::env::var_os("XDG_CACHE_HOME"), std::env::var_os("HOME"))?; | 2870 | + let dir = cache_dir( |
| 2871 | + std::env::var_os("XDG_CACHE_HOME"), | ||
| 2872 | + std::env::var_os("HOME"), | ||
| 2873 | + "mkvindex", | ||
| 2874 | + )?; | ||
| 2843 | Some(dir.join(format!( | 2875 | Some(dir.join(format!( |
| 2844 | "{:016x}-{}.idx", | 2876 | "{:016x}-{}.idx", |
| 2845 | fnv1a(self.path.as_os_str().as_encoded_bytes()), | 2877 | fnv1a(self.path.as_os_str().as_encoded_bytes()), |
| @@ -2848,25 +2880,31 @@ impl IndexKey { | |||
| 2848 | } | 2880 | } |
| 2849 | } | 2881 | } |
| 2850 | 2882 | ||
| 2851 | -/// The path rule, with the environment handed in so it can be checked, as | 2883 | +/// The path rule for one of this engine's cache directories -- `sub` names |
| 2852 | -/// `keymap::config_path_in` is on the config side. An empty `XDG_CACHE_HOME` is | 2884 | +/// which (`mkvindex` here, `proxies` for [`crate::proxy`]) -- with the |
| 2853 | -/// one the spec says to ignore; with no `HOME` either there is nowhere to put a | 2885 | +/// environment handed in so it can be checked, as `keymap::config_path_in` is |
| 2854 | -/// cache, and `None` -- always walk -- beats littering the working directory. | 2886 | +/// on the config side. An empty `XDG_CACHE_HOME` is one the spec says to |
| 2855 | -fn index_dir(xdg: Option<OsString>, home: Option<OsString>) -> Option<PathBuf> { | 2887 | +/// ignore; with no `HOME` either there is nowhere to put a cache, and `None` -- |
| 2888 | +/// always walk -- beats littering the working directory. | ||
| 2889 | +pub(crate) fn cache_dir( | ||
| 2890 | + xdg: Option<OsString>, | ||
| 2891 | + home: Option<OsString>, | ||
| 2892 | + sub: &str, | ||
| 2893 | +) -> Option<PathBuf> { | ||
| 2856 | xdg.filter(|v| !v.is_empty()) | 2894 | xdg.filter(|v| !v.is_empty()) |
| 2857 | .map(PathBuf::from) | 2895 | .map(PathBuf::from) |
| 2858 | .or_else(|| { | 2896 | .or_else(|| { |
| 2859 | home.filter(|v| !v.is_empty()) | 2897 | home.filter(|v| !v.is_empty()) |
| 2860 | .map(|h| PathBuf::from(h).join(".cache")) | 2898 | .map(|h| PathBuf::from(h).join(".cache")) |
| 2861 | }) | 2899 | }) |
| 2862 | - .map(|dir| dir.join("edith").join("mkvindex")) | 2900 | + .map(|dir| dir.join("edith").join(sub)) |
| 2863 | } | 2901 | } |
| 2864 | 2902 | ||
| 2865 | /// FNV-1a, 64-bit: what names a sidecar and what checks it. Not a cryptographic | 2903 | /// FNV-1a, 64-bit: what names a sidecar and what checks it. Not a cryptographic |
| 2866 | /// hash and not asked to be -- nothing here is adversarial. It is the guard that | 2904 | /// hash and not asked to be -- nothing here is adversarial. It is the guard that |
| 2867 | /// turns a half-written or scrambled file into a miss; a *name* collision is | 2905 | /// turns a half-written or scrambled file into a miss; a *name* collision is |
| 2868 | /// caught by the key inside the file, which is compared field by field. | 2906 | /// caught by the key inside the file, which is compared field by field. |
| 2869 | -fn fnv1a(bytes: &[u8]) -> u64 { | 2907 | +pub(crate) fn fnv1a(bytes: &[u8]) -> u64 { |
| 2870 | let mut hash = 0xcbf2_9ce4_8422_2325u64; | 2908 | let mut hash = 0xcbf2_9ce4_8422_2325u64; |
| 2871 | for &b in bytes { | 2909 | for &b in bytes { |
| 2872 | hash ^= u64::from(b); | 2910 | hash ^= u64::from(b); |
| @@ -4362,7 +4400,7 @@ mod tests { | |||
| 4362 | #[test] | 4400 | #[test] |
| 4363 | fn the_index_directory_follows_xdg() { | 4401 | fn the_index_directory_follows_xdg() { |
| 4364 | let dir = |xdg: Option<&str>, home: Option<&str>| { | 4402 | let dir = |xdg: Option<&str>, home: Option<&str>| { |
| 4365 | - index_dir(xdg.map(OsString::from), home.map(OsString::from)) | 4403 | + cache_dir(xdg.map(OsString::from), home.map(OsString::from), "mkvindex") |
| 4366 | }; | 4404 | }; |
| 4367 | assert_eq!( | 4405 | assert_eq!( |
| 4368 | dir(Some("/x/cache"), Some("/home/u")), | 4406 | dir(Some("/x/cache"), Some("/home/u")), |
crates/engine/src/export.rsmodified+69 -9
| @@ -85,14 +85,14 @@ use crate::tonemap::{self, ToneMapper}; | |||
| 85 | 85 | ||
| 86 | /// Progress is reported in permille: an atomic integer the render loop can read | 86 | /// Progress is reported in permille: an atomic integer the render loop can read |
| 87 | /// without a lock, fine enough for any progress bar. | 87 | /// without a lock, fine enough for any progress bar. |
| 88 | -const PROGRESS_SCALE: u32 = 1_000; | 88 | +pub(crate) const PROGRESS_SCALE: u32 = 1_000; |
| 89 | 89 | ||
| 90 | /// The head of the bar the *sound* owns, before a picture is written at all. | 90 | /// The head of the bar the *sound* owns, before a picture is written at all. |
| 91 | /// The mix is decoded, encoded and measured before the muxer exists ([`run`] | 91 | /// The mix is decoded, encoded and measured before the muxer exists ([`run`] |
| 92 | /// says why), and on a feature film that is a minute or two in which a bar | 92 | /// says why), and on a feature film that is a minute or two in which a bar |
| 93 | /// pinned at zero is the only thing on screen -- which reads as an export that | 93 | /// pinned at zero is the only thing on screen -- which reads as an export that |
| 94 | /// has hung. Small, because the picture is still nearly all of the work. | 94 | /// has hung. Small, because the picture is still nearly all of the work. |
| 95 | -const AUDIO_BAND: u32 = PROGRESS_SCALE / 20; | 95 | +pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20; |
| 96 | 96 | ||
| 97 | /// Where the bar stands with `done` of `total` pictures written: the sound's | 97 | /// Where the bar stands with `done` of `total` pictures written: the sound's |
| 98 | /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is | 98 | /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is |
| @@ -300,6 +300,29 @@ pub struct ExportSettings { | |||
| 300 | /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has | 300 | /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has |
| 301 | /// no such ceiling. | 301 | /// no such ceiling. |
| 302 | pub subtitles: Vec<usize>, | 302 | pub subtitles: Vec<usize>, |
| 303 | + /// Code every picture as a key frame a decoder may be started from: no | ||
| 304 | + /// frame references another, the file is an intraframe master in the shape | ||
| 305 | + /// of ProRes, and a seek to any frame at all is one decode. | ||
| 306 | + /// | ||
| 307 | + /// Bigger files for that, so it is off for delivery and on for the | ||
| 308 | + /// stand-ins [`crate::proxy`] makes, which exist precisely to be seeked | ||
| 309 | + /// through. The HEVC seats are intra-only whatever this says | ||
| 310 | + /// ([`Enc::open_hevc`]); this is the H.264 pair's switch. | ||
| 311 | + pub intra_only: bool, | ||
| 312 | + /// Write the picture in the space its **source** declares -- no tone map to | ||
| 313 | + /// SDR, no matrix conversion -- and tag the file with it, instead of | ||
| 314 | + /// converting everything into the space the output height implies. | ||
| 315 | + /// | ||
| 316 | + /// For a preview file and nothing else ([`crate::proxy`]): it makes the | ||
| 317 | + /// stand-in a smaller copy of the film rather than a rendition of it, so | ||
| 318 | + /// the screen tone-maps it live with whatever preset the project is set to | ||
| 319 | + /// -- and it takes the per-frame conversion off the *source's* full | ||
| 320 | + /// resolution, which on a 4K HDR film was 48 ms a frame and the whole of a | ||
| 321 | + /// proxy's cost (measured 2026-08-13). | ||
| 322 | + /// | ||
| 323 | + /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for | ||
| 324 | + /// this editor to read back, not one to hand anybody. | ||
| 325 | + pub keep_source_colour: bool, | ||
| 303 | } | 326 | } |
| 304 | 327 | ||
| 305 | struct Shared { | 328 | struct Shared { |
| @@ -1665,6 +1688,16 @@ fn run( | |||
| 1665 | settings: &ExportSettings, | 1688 | settings: &ExportSettings, |
| 1666 | ) -> crate::Result<()> { | 1689 | ) -> crate::Result<()> { |
| 1667 | let total = project.timeline_frames(); | 1690 | let total = project.timeline_frames(); |
| 1691 | + // Only the mp4 pair carries a colour of its own back out | ||
| 1692 | + // ([`write_video`] tags it there), so asking any other container for a | ||
| 1693 | + // source-space file would write pictures one space and a header another. | ||
| 1694 | + if settings.keep_source_colour && settings.format != Format::Mp4 { | ||
| 1695 | + return Err(format!( | ||
| 1696 | + "{} cannot be written in its source's colour space", | ||
| 1697 | + settings.format.name() | ||
| 1698 | + ) | ||
| 1699 | + .into()); | ||
| 1700 | + } | ||
| 1668 | let sources = project.sources(); | 1701 | let sources = project.sources(); |
| 1669 | // The picture's decision first, before a sample of sound is touched: it is | 1702 | // The picture's decision first, before a sample of sound is touched: it is |
| 1670 | // the answer that decides what the whole export *is*, it costs one header | 1703 | // the answer that decides what the whole export *is*, it costs one header |
| @@ -1767,14 +1800,24 @@ fn run( | |||
| 1767 | let tone: Vec<Option<ToneMapper>> = rates | 1800 | let tone: Vec<Option<ToneMapper>> = rates |
| 1768 | .iter() | 1801 | .iter() |
| 1769 | .map(|(_, color, peak)| match color.transfer { | 1802 | .map(|(_, color, peak)| match color.transfer { |
| 1803 | + // A preview file keeps the film's own curve and is tone-mapped when | ||
| 1804 | + // it is *shown* ([`ExportSettings::keep_source_colour`]), which is | ||
| 1805 | + // both cheaper and the only way the preset can still be changed | ||
| 1806 | + // after the stand-in was made. | ||
| 1807 | + _ if settings.keep_source_colour => None, | ||
| 1770 | Transfer::Sdr => None, | 1808 | Transfer::Sdr => None, |
| 1771 | Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)), | 1809 | Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)), |
| 1772 | Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)), | 1810 | Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)), |
| 1773 | }) | 1811 | }) |
| 1774 | .collect(); | 1812 | .collect(); |
| 1775 | // ...and the one space they are all written in, the same rule a reader with | 1813 | // ...and the one space they are all written in, the same rule a reader with |
| 1776 | - // no tags to read would apply to this file's height. | 1814 | + // no tags to read would apply to this file's height -- or, for a preview |
| 1777 | - let out_color = ColorDescription::output(meta.height); | 1815 | + // file, the source's own, which is what makes every remap below the |
| 1816 | + // identity and the file's `colr` box its film's. | ||
| 1817 | + let out_color = match settings.keep_source_colour { | ||
| 1818 | + true => meta.color, | ||
| 1819 | + false => ColorDescription::output(meta.height), | ||
| 1820 | + }; | ||
| 1778 | 1821 | ||
| 1779 | let mut encoder = Enc::open(meta, settings)?; | 1822 | let mut encoder = Enc::open(meta, settings)?; |
| 1780 | // What this file is really being written by, for a progress line to name. | 1823 | // What this file is really being written by, for a progress line to name. |
| @@ -1938,7 +1981,8 @@ fn run( | |||
| 1938 | // and faster, more when the clip is slowed -- the picture is already | 1981 | // and faster, more when the clip is slowed -- the picture is already |
| 1939 | // graded and placed, so a held frame costs an encode and no decode. | 1982 | // graded and placed, so a held frame costs an encode and no decode. |
| 1940 | for _ in 0..repeats { | 1983 | for _ in 0..repeats { |
| 1941 | - if let Some((au, key)) = encoder.encode(y, u, v, width, height)? { | 1984 | + if let Some((au, key)) = encoder.encode(y, u, v, width, height, settings.intra_only)? |
| 1985 | + { | ||
| 1942 | write_video( | 1986 | write_video( |
| 1943 | &mut muxer, | 1987 | &mut muxer, |
| 1944 | out, | 1988 | out, |
| @@ -2597,6 +2641,12 @@ fn write_video( | |||
| 2597 | )?)) else { | 2641 | )?)) else { |
| 2598 | unreachable!("just inserted an mp4 muxer") | 2642 | unreachable!("just inserted an mp4 muxer") |
| 2599 | }; | 2643 | }; |
| 2644 | + // A file written in its source's own space says so, rather than | ||
| 2645 | + // claiming the space its height would imply | ||
| 2646 | + // ([`ExportSettings::keep_source_colour`]). | ||
| 2647 | + if settings.keep_source_colour { | ||
| 2648 | + mp4.set_colour(meta.color); | ||
| 2649 | + } | ||
| 2600 | mp4 | 2650 | mp4 |
| 2601 | } | 2651 | } |
| 2602 | }; | 2652 | }; |
| @@ -2730,8 +2780,13 @@ impl Enc { | |||
| 2730 | cfg.framerate = meta.frame_rate as f32; | 2780 | cfg.framerate = meta.frame_rate as f32; |
| 2731 | cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; | 2781 | cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; |
| 2732 | // Two seconds between key frames, and no B-frames on either path: the | 2782 | // Two seconds between key frames, and no B-frames on either path: the |
| 2733 | - // muxer times everything by duration alone, which reordering would break. | 2783 | + // muxer times everything by duration alone, which reordering would |
| 2734 | - cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32; | 2784 | + // break. A proxy asks for one frame a GOP, which is every frame its own |
| 2785 | + // starting point ([`ExportSettings::intra_only`]). | ||
| 2786 | + cfg.gop_size = match settings.intra_only { | ||
| 2787 | + true => 1, | ||
| 2788 | + false => (meta.frame_rate * 2.0).round().max(1.0) as u32, | ||
| 2789 | + }; | ||
| 2735 | cfg.bframes = 0; | 2790 | cfg.bframes = 0; |
| 2736 | // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same | 2791 | // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same |
| 2737 | // bitrate, so Fast is what a fallback should be. | 2792 | // bitrate, so Fast is what a fallback should be. |
| @@ -2893,6 +2948,7 @@ impl Enc { | |||
| 2893 | v: &[u8], | 2948 | v: &[u8], |
| 2894 | width: u32, | 2949 | width: u32, |
| 2895 | height: u32, | 2950 | height: u32, |
| 2951 | + intra: bool, | ||
| 2896 | ) -> crate::Result<Option<(&[u8], bool)>> { | 2952 | ) -> crate::Result<Option<(&[u8], bool)>> { |
| 2897 | match self { | 2953 | match self { |
| 2898 | Self::Av1Hw(hw) => { | 2954 | Self::Av1Hw(hw) => { |
| @@ -2942,9 +2998,13 @@ impl Enc { | |||
| 2942 | // frame -- which is what an intraframe master means. | 2998 | // frame -- which is what an intraframe master means. |
| 2943 | Ok(pop_hevc(hevc)) | 2999 | Ok(pop_hevc(hevc)) |
| 2944 | } | 3000 | } |
| 3001 | + // A key frame is asked for on every picture where the file is an | ||
| 3002 | + // intraframe one, and the flag says what was asked: the mp4 muxer | ||
| 3003 | + // reads its own sync marks off the IDR slices either way, so this | ||
| 3004 | + // is what a Matroska one would be told. | ||
| 2945 | Self::Hw(hw) => Ok(hw | 3005 | Self::Hw(hw) => Ok(hw |
| 2946 | - .encode(y, u, v, width, height, false)? | 3006 | + .encode(y, u, v, width, height, intra)? |
| 2947 | - .map(|au| (au, false))), | 3007 | + .map(|au| (au, intra))), |
| 2948 | Self::Sw { encoder, au, .. } => { | 3008 | Self::Sw { encoder, au, .. } => { |
| 2949 | let frame = YuvFrame { | 3009 | let frame = YuvFrame { |
| 2950 | width: width as usize, | 3010 | width: width as usize, |
crates/engine/src/lib.rsmodified+1 -0
| @@ -17,6 +17,7 @@ pub mod limiter; | |||
| 17 | pub mod mux; | 17 | pub mod mux; |
| 18 | pub mod playback; | 18 | pub mod playback; |
| 19 | pub mod project; | 19 | pub mod project; |
| 20 | +pub mod proxy; | ||
| 20 | pub mod real_library; | 21 | pub mod real_library; |
| 21 | pub mod scale; | 22 | pub mod scale; |
| 22 | pub mod scratch; | 23 | pub mod scratch; |
crates/engine/src/mux.rsmodified+10 -0
| @@ -308,6 +308,16 @@ impl Mp4Muxer { | |||
| 308 | }) | 308 | }) |
| 309 | } | 309 | } |
| 310 | 310 | ||
| 311 | + /// Says what this file's samples mean, where that is *not* the rule the | ||
| 312 | + /// height implies -- a picture written in its source's own space rather | ||
| 313 | + /// than converted into the output one ([`crate::proxy`] is why: a stand-in | ||
| 314 | + /// carries the film's colour and lets the screen convert it, once, at | ||
| 315 | + /// preview size). The box is written when the file is finished, so this may | ||
| 316 | + /// be said any time before then. | ||
| 317 | + pub fn set_colour(&mut self, colour: ColorDescription) { | ||
| 318 | + self.colr = colr_nclx(colour); | ||
| 319 | + } | ||
| 320 | + | ||
| 311 | /// One coded picture, Annex-B framed. Parameter sets inside it are dropped | 321 | /// One coded picture, Annex-B framed. Parameter sets inside it are dropped |
| 312 | /// (they are already in `avcC`); an IDR slice marks the sample as a sync point. | 322 | /// (they are already in `avcC`); an IDR slice marks the sample as a sync point. |
| 313 | pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> { | 323 | pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> { |
crates/engine/src/proxy.rsadded+325 -0
| @@ -0,0 +1,325 @@ | |||
| 1 | +//! Small stand-ins for big files: a half-size, every-frame-a-keyframe H.264 | ||
| 2 | +//! copy of a source, kept in the user's cache and played instead of the | ||
| 3 | +//! original while the cut is being made. | ||
| 4 | +//! | ||
| 5 | +//! Why they exist at all: a 4K HEVC film decodes at a fraction of realtime on | ||
| 6 | +//! this machine, so scrubbing it is a slideshow and every seek is a wait. A | ||
| 7 | +//! proxy is the same film at 1280 on its long edge, coded so that **every frame | ||
| 8 | +//! is a random-access point** -- which is what makes a seek land on the frame | ||
| 9 | +//! that was asked for instead of on the nearest one a decoder can start from, | ||
| 10 | +//! and what takes the whole open-GOP class of seek faults off the table by | ||
| 11 | +//! construction. | ||
| 12 | +//! | ||
| 13 | +//! Three rules, and they are the whole contract: | ||
| 14 | +//! | ||
| 15 | +//! - **Picture only.** No sound is coded into a proxy. The mix always comes off | ||
| 16 | +//! the original file ([`crate::PlaybackSession`] opens audio by its own path, | ||
| 17 | +//! which this module never touches), so nothing a listener hears has been | ||
| 18 | +//! through a second encoder. | ||
| 19 | +//! - **Never exported.** [`crate::export`] reads the project's own sources and | ||
| 20 | +//! knows nothing of this module. Delivery is the original, always. | ||
| 21 | +//! - **Derived, never authoritative.** A proxy is named after the source's | ||
| 22 | +//! path, length and modification time ([`path_for`]), so a re-encoded or | ||
| 23 | +//! re-cut original simply misses the cache and a stale proxy can never be | ||
| 24 | +//! found. Deleting the cache directory costs time and nothing else. | ||
| 25 | +//! | ||
| 26 | +//! Generation is [`crate::export`]'s own decode -> scale -> encode walk, given | ||
| 27 | +//! a one-clip project and a smaller canvas: the hardware seat where the GPU has | ||
| 28 | +//! one, the software encoder where it does not, the same progress and the same | ||
| 29 | +//! cancel a file export has ([`Job`]). | ||
| 30 | + | ||
| 31 | +use std::path::{Path, PathBuf}; | ||
| 32 | +use std::time::UNIX_EPOCH; | ||
| 33 | + | ||
| 34 | +use crate::demux::{Codec, Demuxer, VideoMeta}; | ||
| 35 | +use crate::export::{ExportHandle, ExportSettings, Format}; | ||
| 36 | +use crate::project::{Clip, LaneKind, Project, Source, Speed}; | ||
| 37 | +use crate::scale::FitPolicy; | ||
| 38 | + | ||
| 39 | +/// The long edge of a proxy picture, in samples: 1280, so a 4K source loses | ||
| 40 | +/// nine tenths of its samples and a 1080p one a little over half. Chosen as | ||
| 41 | +/// what a cut can be judged on at editing size, in the neighbourhood of every | ||
| 42 | +/// shipped proxy preset (Resolve's half-res, kdenlive's 640/1000-wide | ||
| 43 | +/// defaults). | ||
| 44 | +pub const LONG_EDGE: u32 = 1280; | ||
| 45 | + | ||
| 46 | +/// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate | ||
| 47 | +/// rule at three times the number: every frame being an IDR means no frame | ||
| 48 | +/// borrows anything from its neighbours, so the same picture at the inter rate | ||
| 49 | +/// would be mush -- and mush is not something a cut can be judged on. | ||
| 50 | +const BITS_PER_PIXEL: f64 = 0.3; | ||
| 51 | + | ||
| 52 | +/// Whether this is a file worth standing in for: bigger than 1080p, or coded in | ||
| 53 | +/// something this machine decodes slowly even at 1080p. H.264 at or under 1080p | ||
| 54 | +/// plays natively and a proxy of it would cost time and buy nothing. | ||
| 55 | +pub fn wanted(meta: &VideoMeta) -> bool { | ||
| 56 | + meta.width > 1920 || meta.height > 1080 || matches!(meta.codec, Codec::Hevc | Codec::Av1) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// The picture a proxy of `meta` is coded at: aspect kept, long edge at most | ||
| 60 | +/// [`LONG_EDGE`], both axes even because 4:2:0 has no half chroma samples. A | ||
| 61 | +/// source already that small is coded at its own size (rounded down to even), | ||
| 62 | +/// which is what makes [`generate`] safe to ask for on anything at all. | ||
| 63 | +pub fn size_for(meta: &VideoMeta) -> (u32, u32) { | ||
| 64 | + let long = meta.width.max(meta.height); | ||
| 65 | + let scale = match long > LONG_EDGE { | ||
| 66 | + true => f64::from(LONG_EDGE) / f64::from(long), | ||
| 67 | + false => 1.0, | ||
| 68 | + }; | ||
| 69 | + let even = |n: u32| (((f64::from(n) * scale).round() as u32) & !1).max(2); | ||
| 70 | + (even(meta.width), even(meta.height)) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Where the proxy of `source` lives, whether or not it has been made yet. | ||
| 74 | +/// | ||
| 75 | +/// The name is one hash of the source's canonical path, its length **and** its | ||
| 76 | +/// modification time, so an original that changed at all is a different name | ||
| 77 | +/// and its old proxy is simply never looked at again -- the staleness check is | ||
| 78 | +/// the lookup. `None` where the file cannot be stat'd or the machine has no | ||
| 79 | +/// cache directory at all, which is a source that gets no proxy rather than one | ||
| 80 | +/// littering the working directory. | ||
| 81 | +/// | ||
| 82 | +/// corner-cut: nothing evicts, exactly as the Matroska index cache beside it | ||
| 83 | +/// states. A proxy of a feature film is hundreds of megabytes and a re-encoded | ||
| 84 | +/// source leaves its old one behind; the upgrade path is a size-capped sweep of | ||
| 85 | +/// the directory at open. It is the user's own cache to delete meanwhile. | ||
| 86 | +pub fn path_for(source: &Path) -> Option<PathBuf> { | ||
| 87 | + let meta = std::fs::metadata(source).ok()?; | ||
| 88 | + let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) { | ||
| 89 | + Ok(d) => (d.as_secs() as i128, d.subsec_nanos()), | ||
| 90 | + Err(e) => (-(e.duration().as_secs() as i128), e.duration().subsec_nanos()), | ||
| 91 | + }; | ||
| 92 | + let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf()); | ||
| 93 | + let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec(); | ||
| 94 | + bytes.extend_from_slice(&meta.len().to_le_bytes()); | ||
| 95 | + bytes.extend_from_slice(&mtime.0.to_le_bytes()); | ||
| 96 | + bytes.extend_from_slice(&mtime.1.to_le_bytes()); | ||
| 97 | + let dir = crate::demux::cache_dir( | ||
| 98 | + std::env::var_os("XDG_CACHE_HOME"), | ||
| 99 | + std::env::var_os("HOME"), | ||
| 100 | + "proxies", | ||
| 101 | + )?; | ||
| 102 | + Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes)))) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// The proxy of `source` if one has already been made, `None` otherwise. The | ||
| 106 | +/// answer a session asks at open: a hit costs one `stat`. | ||
| 107 | +pub fn cached(source: &Path) -> Option<PathBuf> { | ||
| 108 | + path_for(source).filter(|p| p.is_file()) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// A proxy being made -- or one that was already there, which is the same thing | ||
| 112 | +/// to whoever is waiting for a path. | ||
| 113 | +/// | ||
| 114 | +/// Poll [`progress`](Job::progress) while [`is_finished`](Job::is_finished) is | ||
| 115 | +/// false and take the [`outcome`](Job::outcome) when it flips, exactly as an | ||
| 116 | +/// export is polled. Dropping the job does not stop the work; | ||
| 117 | +/// [`cancel`](Job::cancel) does. | ||
| 118 | +pub struct Job { | ||
| 119 | + out: PathBuf, | ||
| 120 | + /// `None` for a cache hit: there was nothing to run. | ||
| 121 | + handle: Option<ExportHandle>, | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +impl Job { | ||
| 125 | + /// Fraction of the proxy's pictures written, `0.0..=1.0`. A cache hit is | ||
| 126 | + /// done. | ||
| 127 | + /// | ||
| 128 | + /// The band an export's bar reserves for its sound is taken back out: a | ||
| 129 | + /// proxy has no sound, so that band is crossed in the first instant and | ||
| 130 | + /// showing it would be five percent no frame earned. | ||
| 131 | + pub fn progress(&self) -> f32 { | ||
| 132 | + let Some(handle) = &self.handle else { | ||
| 133 | + return 1.0; | ||
| 134 | + }; | ||
| 135 | + let band = crate::export::AUDIO_BAND as f32 / crate::export::PROGRESS_SCALE as f32; | ||
| 136 | + ((handle.progress() - band) / (1.0 - band)).clamp(0.0, 1.0) | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + /// What is coding this proxy -- the hardware seat or the software one, as | ||
| 140 | + /// the worker really opened it. `None` before the encoder is open, and for | ||
| 141 | + /// a cache hit, which coded nothing. | ||
| 142 | + pub fn encoder(&self) -> Option<String> { | ||
| 143 | + self.handle.as_ref()?.encoders() | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + /// Asks the worker to stop at its next frame and leave no file behind. The | ||
| 147 | + /// outcome then reports the cancellation as an error. | ||
| 148 | + pub fn cancel(&self) { | ||
| 149 | + if let Some(handle) = &self.handle { | ||
| 150 | + handle.cancel(); | ||
| 151 | + } | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + pub fn is_finished(&self) -> bool { | ||
| 155 | + self.handle.as_ref().is_none_or(ExportHandle::is_finished) | ||
| 156 | + } | ||
| 157 | + | ||
| 158 | + /// The proxy's path once it is written, once -- taken out of the job, so a | ||
| 159 | + /// caller that already took it sees `None`. `None` while it is still being | ||
| 160 | + /// made. | ||
| 161 | + pub fn outcome(&self) -> Option<crate::Result<PathBuf>> { | ||
| 162 | + let Some(handle) = &self.handle else { | ||
| 163 | + return Some(Ok(self.out.clone())); | ||
| 164 | + }; | ||
| 165 | + handle.result().map(|r| r.map(|()| self.out.clone())) | ||
| 166 | + } | ||
| 167 | + | ||
| 168 | + /// Where the proxy will be, whether or not it is there yet -- what a caller | ||
| 169 | + /// names in a log line while the job runs. | ||
| 170 | + pub fn path(&self) -> &Path { | ||
| 171 | + &self.out | ||
| 172 | + } | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +/// Starts making the proxy of `source`, or hands back the one already in the | ||
| 176 | +/// cache. Errors are the ones that happen before a worker exists -- a file with | ||
| 177 | +/// no picture in it, nowhere to put a cache -- and everything after them comes | ||
| 178 | +/// back through [`Job::outcome`], so a caller has two places to look and not | ||
| 179 | +/// twenty. | ||
| 180 | +pub fn generate(source: &Path) -> crate::Result<Job> { | ||
| 181 | + let out = path_for(source).ok_or("no cache directory to keep a proxy in")?; | ||
| 182 | + if out.is_file() { | ||
| 183 | + return Ok(Job { out, handle: None }); | ||
| 184 | + } | ||
| 185 | + // The source's own header: its rate and length are the proxy's (a stand-in | ||
| 186 | + // that ran at another rate or stopped early would put every cut on another | ||
| 187 | + // frame), and only its picture size changes. | ||
| 188 | + let (meta, _) = Demuxer::open(source)?; | ||
| 189 | + let (width, height) = size_for(&meta); | ||
| 190 | + if let Some(dir) = out.parent() { | ||
| 191 | + std::fs::create_dir_all(dir)?; | ||
| 192 | + } | ||
| 193 | + // One video lane, one clip, the whole file -- and *no* audio lane, which is | ||
| 194 | + // what makes the proxy picture-only: the export walk codes the lanes it is | ||
| 195 | + // given and there is no sound among them. | ||
| 196 | + let clip = Clip { | ||
| 197 | + start: 0, | ||
| 198 | + in_frame: 0, | ||
| 199 | + out_frame: meta.frame_count.max(1), | ||
| 200 | + source: 0, | ||
| 201 | + link: None, | ||
| 202 | + eq: None, | ||
| 203 | + color: None, | ||
| 204 | + fit: FitPolicy::default(), | ||
| 205 | + speed: Speed::NORMAL, | ||
| 206 | + }; | ||
| 207 | + let project = Project::from_parts( | ||
| 208 | + vec![Source::new(source, 0)], | ||
| 209 | + vec![(LaneKind::Video, vec![clip])], | ||
| 210 | + Vec::new(), | ||
| 211 | + Vec::new(), | ||
| 212 | + )?; | ||
| 213 | + let bitrate = | ||
| 214 | + (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64; | ||
| 215 | + let handle = crate::export::start( | ||
| 216 | + project, | ||
| 217 | + VideoMeta { | ||
| 218 | + width, | ||
| 219 | + height, | ||
| 220 | + ..meta | ||
| 221 | + }, | ||
| 222 | + &out, | ||
| 223 | + &ExportSettings { | ||
| 224 | + format: Format::Mp4, | ||
| 225 | + // The whole point: every frame its own random-access point. | ||
| 226 | + intra_only: true, | ||
| 227 | + // ...and the film's own colour, carried rather than converted: the | ||
| 228 | + // screen tone-maps the stand-in exactly as it tone-maps the film, | ||
| 229 | + // live and at preview size. | ||
| 230 | + keep_source_colour: true, | ||
| 231 | + bitrate: Some(bitrate), | ||
| 232 | + ..Default::default() | ||
| 233 | + }, | ||
| 234 | + ); | ||
| 235 | + Ok(Job { | ||
| 236 | + out, | ||
| 237 | + handle: Some(handle), | ||
| 238 | + }) | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +#[cfg(test)] | ||
| 242 | +mod tests { | ||
| 243 | + use super::*; | ||
| 244 | + use crate::colorspace::ColorDescription; | ||
| 245 | + | ||
| 246 | + fn meta(width: u32, height: u32, codec: Codec) -> VideoMeta { | ||
| 247 | + VideoMeta { | ||
| 248 | + width, | ||
| 249 | + height, | ||
| 250 | + frame_rate: 24.0, | ||
| 251 | + frame_count: 240, | ||
| 252 | + codec, | ||
| 253 | + color: ColorDescription::default(), | ||
| 254 | + } | ||
| 255 | + } | ||
| 256 | + | ||
| 257 | + /// What a proxy is *for*: the files this machine cannot play at speed. | ||
| 258 | + #[test] | ||
| 259 | + fn only_the_files_that_need_one_get_one() { | ||
| 260 | + assert!(wanted(&meta(3840, 2160, Codec::Hevc)), "4K HEVC"); | ||
| 261 | + assert!(wanted(&meta(3840, 2160, Codec::H264)), "4K H.264"); | ||
| 262 | + assert!(wanted(&meta(1920, 1080, Codec::Hevc)), "1080p HEVC"); | ||
| 263 | + assert!(wanted(&meta(1920, 1080, Codec::Av1)), "1080p AV1"); | ||
| 264 | + assert!( | ||
| 265 | + !wanted(&meta(1920, 1080, Codec::H264)), | ||
| 266 | + "1080p H.264 plays natively" | ||
| 267 | + ); | ||
| 268 | + assert!(!wanted(&meta(1280, 720, Codec::H264)), "720p H.264"); | ||
| 269 | + } | ||
| 270 | + | ||
| 271 | + /// Aspect kept, long edge capped, both axes even -- and a small source left | ||
| 272 | + /// alone rather than blown up. | ||
| 273 | + #[test] | ||
| 274 | + fn a_proxy_is_the_same_shape_at_a_smaller_size() { | ||
| 275 | + assert_eq!(size_for(&meta(3840, 2160, Codec::Hevc)), (1280, 720)); | ||
| 276 | + assert_eq!(size_for(&meta(1920, 1080, Codec::Hevc)), (1280, 720)); | ||
| 277 | + // A portrait source is capped on *its* long edge, which is the height. | ||
| 278 | + assert_eq!(size_for(&meta(1080, 1920, Codec::Hevc)), (720, 1280)); | ||
| 279 | + // 1916x1080 (a real film's cropped width): even both ways, and the | ||
| 280 | + // aspect it really has rather than the 16:9 it nearly has. | ||
| 281 | + let (w, h) = size_for(&meta(1916, 1080, Codec::H264)); | ||
| 282 | + assert_eq!((w, h), (1280, 722), "cropped-width 1080p"); | ||
| 283 | + assert_eq!(w % 2, 0); | ||
| 284 | + assert_eq!(h % 2, 0); | ||
| 285 | + assert!( | ||
| 286 | + (f64::from(w) / f64::from(h) - 1916. / 1080.).abs() < 0.005, | ||
| 287 | + "{w}x{h} is the source's shape" | ||
| 288 | + ); | ||
| 289 | + assert_eq!( | ||
| 290 | + size_for(&meta(640, 360, Codec::H264)), | ||
| 291 | + (640, 360), | ||
| 292 | + "already small: its own size, never upscaled" | ||
| 293 | + ); | ||
| 294 | + assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero"); | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + /// The staleness rule *is* the name: touch the source and the old proxy is | ||
| 298 | + /// unreachable rather than wrong. | ||
| 299 | + #[test] | ||
| 300 | + fn a_changed_source_names_another_proxy() { | ||
| 301 | + let dir = crate::scratch::Scratch::dir("proxy-key"); | ||
| 302 | + let file = dir.join("a.mp4"); | ||
| 303 | + std::fs::write(&file, b"one").expect("write"); | ||
| 304 | + let first = path_for(&file).expect("a key"); | ||
| 305 | + assert_eq!(path_for(&file).as_ref(), Some(&first), "stable for a file"); | ||
| 306 | + // Same length, later time: a re-encode that happened to land on the | ||
| 307 | + // same byte count is still another file. | ||
| 308 | + std::fs::write(&file, b"two").expect("rewrite"); | ||
| 309 | + filetime_bump(&file); | ||
| 310 | + assert_ne!(path_for(&file), Some(first), "touched: another name"); | ||
| 311 | + assert_eq!(cached(&file), None, "nothing written, nothing cached"); | ||
| 312 | + } | ||
| 313 | + | ||
| 314 | + /// `std::fs` has no set-mtime, and a rewrite inside the same nanosecond is | ||
| 315 | + /// possible on a fast machine -- so the stamp is moved by hand through the | ||
| 316 | + /// one door that does it without a dependency. | ||
| 317 | + fn filetime_bump(path: &Path) { | ||
| 318 | + let now = std::time::SystemTime::now() + std::time::Duration::from_secs(10); | ||
| 319 | + let file = std::fs::File::options() | ||
| 320 | + .write(true) | ||
| 321 | + .open(path) | ||
| 322 | + .expect("open"); | ||
| 323 | + file.set_modified(now).expect("set mtime"); | ||
| 324 | + } | ||
| 325 | +} | ||
crates/engine/tests/export.rsmodified+157 -0
| @@ -859,3 +859,160 @@ fn exports_a_gapped_timeline_as_black_and_silence() { | |||
| 859 | 859 | ||
| 860 | std::fs::remove_file(&out).unwrap(); | 860 | std::fs::remove_file(&out).unwrap(); |
| 861 | } | 861 | } |
| 862 | + | ||
| 863 | +/// The stand-in a proxy really is, in one pass over the fixture: a picture-only | ||
| 864 | +/// file whose *every* frame is a decoder's starting point, playable through the | ||
| 865 | +/// ordinary session, and found in the cache the second time it is asked for. | ||
| 866 | +/// | ||
| 867 | +/// Software seat, like every default test here ([`pin_software`]) -- what the | ||
| 868 | +/// hardware one buys is speed, and that is the ignored test below. | ||
| 869 | +#[test] | ||
| 870 | +fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() { | ||
| 871 | + pin_software(); | ||
| 872 | + let source = asset("test_av.mp4"); | ||
| 873 | + let out = engine::proxy::path_for(&source).expect("a cache directory"); | ||
| 874 | + // A proxy left by an earlier run would make this test assert about a file | ||
| 875 | + // it did not write -- and the cache-hit half below would be the only half | ||
| 876 | + // that ran. | ||
| 877 | + let _ = std::fs::remove_file(&out); | ||
| 878 | + | ||
| 879 | + let job = engine::proxy::generate(&source).expect("start the proxy"); | ||
| 880 | + assert_eq!(job.path(), out, "the job writes where the key says"); | ||
| 881 | + let started = Instant::now(); | ||
| 882 | + while !job.is_finished() { | ||
| 883 | + assert!( | ||
| 884 | + started.elapsed() < Duration::from_secs(300), | ||
| 885 | + "the proxy did not finish: {:.0}% in", | ||
| 886 | + job.progress() * 100.0 | ||
| 887 | + ); | ||
| 888 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 889 | + } | ||
| 890 | + let made = job | ||
| 891 | + .outcome() | ||
| 892 | + .expect("a finished job has an outcome") | ||
| 893 | + .expect("the proxy"); | ||
| 894 | + assert_eq!(made, out); | ||
| 895 | + assert_eq!(job.progress(), 1.0, "finished at full progress"); | ||
| 896 | + | ||
| 897 | + let (source_meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture"); | ||
| 898 | + let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy"); | ||
| 899 | + assert_eq!( | ||
| 900 | + (meta.width, meta.height), | ||
| 901 | + engine::proxy::size_for(&source_meta), | ||
| 902 | + "the proxy is coded at the size the rule picked" | ||
| 903 | + ); | ||
| 904 | + assert_eq!(meta.codec, engine::Codec::H264, "proxies are H.264"); | ||
| 905 | + assert_eq!( | ||
| 906 | + meta.frame_count, source_meta.frame_count, | ||
| 907 | + "a stand-in as long as the film, or every cut lands elsewhere" | ||
| 908 | + ); | ||
| 909 | + | ||
| 910 | + // The whole point: every frame its own random-access point, so a seek never | ||
| 911 | + // has to start earlier than it was asked to. | ||
| 912 | + let syncs = engine::demux::sync_points(&made); | ||
| 913 | + assert_eq!( | ||
| 914 | + syncs.len() as u32, | ||
| 915 | + meta.frame_count, | ||
| 916 | + "{} of {} frames are starting points -- the proxy is not intra-only", | ||
| 917 | + syncs.len(), | ||
| 918 | + meta.frame_count | ||
| 919 | + ); | ||
| 920 | + | ||
| 921 | + // ...and no sound in it at all: the mix is the original's, always. | ||
| 922 | + assert!( | ||
| 923 | + engine::AudioSession::open(&made) | ||
| 924 | + .expect("probe the proxy for sound") | ||
| 925 | + .is_none(), | ||
| 926 | + "a proxy carries no audio track" | ||
| 927 | + ); | ||
| 928 | + | ||
| 929 | + // It plays through the ordinary door, which is what substitution needs. | ||
| 930 | + let session = PlaybackSession::open(&made).expect("play the proxy"); | ||
| 931 | + assert_eq!(session.meta().frame_count, source_meta.frame_count); | ||
| 932 | + | ||
| 933 | + // Asked again, it is the file already there: no second encode. | ||
| 934 | + let again = engine::proxy::generate(&source).expect("ask again"); | ||
| 935 | + assert!(again.is_finished(), "a cached proxy is done on the spot"); | ||
| 936 | + assert_eq!( | ||
| 937 | + again.outcome().expect("cached outcome").expect("cached path"), | ||
| 938 | + out | ||
| 939 | + ); | ||
| 940 | + assert_eq!(engine::proxy::cached(&source), Some(out.clone())); | ||
| 941 | + | ||
| 942 | + std::fs::remove_file(&out).expect("clean the cache entry up"); | ||
| 943 | + assert_eq!(engine::proxy::cached(&source), None); | ||
| 944 | +} | ||
| 945 | + | ||
| 946 | +/// A real 4K HEVC film, on the hardware seat: a proxy of it is made **faster | ||
| 947 | +/// than the film plays**, which is the whole promise -- and a cancel stops it | ||
| 948 | +/// dead and leaves nothing behind. | ||
| 949 | +/// | ||
| 950 | +/// Measured over a window rather than to the end: the film is two hours and the | ||
| 951 | +/// number wanted is a rate, not a wall time. | ||
| 952 | +/// | ||
| 953 | +/// ```text | ||
| 954 | +/// cargo build -p engine -p engine-hw --release | ||
| 955 | +/// LD_LIBRARY_PATH=target/release cargo test -p engine --release --test export \ | ||
| 956 | +/// -- --ignored --nocapture --test-threads=1 proxy_of_real_4k | ||
| 957 | +/// ``` | ||
| 958 | +#[test] | ||
| 959 | +#[ignore = "needs the VA-API plugin and a real library"] | ||
| 960 | +fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { | ||
| 961 | + pin_hardware(); | ||
| 962 | + let Some(film) = engine::real_library::film("hevc_4k_hdr") else { | ||
| 963 | + return; | ||
| 964 | + }; | ||
| 965 | + let out = engine::proxy::path_for(&film).expect("a cache directory"); | ||
| 966 | + let _ = std::fs::remove_file(&out); | ||
| 967 | + let (meta, _) = engine::demux::Demuxer::open(&film).expect("open the film"); | ||
| 968 | + let duration = f64::from(meta.frame_count) / meta.frame_rate; | ||
| 969 | + println!( | ||
| 970 | + "film: {}x{} {:.3} fps, {duration:.0}s", | ||
| 971 | + meta.width, meta.height, meta.frame_rate | ||
| 972 | + ); | ||
| 973 | + | ||
| 974 | + let job = engine::proxy::generate(&film).expect("start the proxy"); | ||
| 975 | + let window = Duration::from_secs(60); | ||
| 976 | + let started = Instant::now(); | ||
| 977 | + while started.elapsed() < window && !job.is_finished() { | ||
| 978 | + std::thread::sleep(Duration::from_millis(200)); | ||
| 979 | + } | ||
| 980 | + let elapsed = started.elapsed().as_secs_f64(); | ||
| 981 | + let made = f64::from(job.progress()) * duration; | ||
| 982 | + let seat = job.encoder().unwrap_or_default(); | ||
| 983 | + println!( | ||
| 984 | + "proxy: {made:.0}s of film in {elapsed:.0}s = {:.2}x realtime, seat {seat}", | ||
| 985 | + made / elapsed | ||
| 986 | + ); | ||
| 987 | + // The silent-software trap: a run without the plugin on the path measures | ||
| 988 | + // the fallback and calls it hardware. | ||
| 989 | + assert!( | ||
| 990 | + seat.contains("HW encode"), | ||
| 991 | + "not the hardware seat ({seat}): LD_LIBRARY_PATH must name the plugin" | ||
| 992 | + ); | ||
| 993 | + assert!( | ||
| 994 | + made / elapsed >= 1.0, | ||
| 995 | + "{:.2}x realtime is slower than watching the film", | ||
| 996 | + made / elapsed | ||
| 997 | + ); | ||
| 998 | + | ||
| 999 | + // Cancel stops the reading, and a proxy that was not finished is not left | ||
| 1000 | + // lying around under the name a finished one would have. | ||
| 1001 | + job.cancel(); | ||
| 1002 | + let stopped = Instant::now(); | ||
| 1003 | + while !job.is_finished() { | ||
| 1004 | + assert!( | ||
| 1005 | + stopped.elapsed() < Duration::from_secs(30), | ||
| 1006 | + "the proxy did not stop when cancelled" | ||
| 1007 | + ); | ||
| 1008 | + std::thread::sleep(Duration::from_millis(50)); | ||
| 1009 | + } | ||
| 1010 | + assert!(job.outcome().expect("an outcome").is_err(), "cancelled"); | ||
| 1011 | + assert!( | ||
| 1012 | + !out.exists(), | ||
| 1013 | + "a cancelled proxy left {} behind", | ||
| 1014 | + out.display() | ||
| 1015 | + ); | ||
| 1016 | + assert!(!part_path(&out).exists(), "a cancelled proxy left its .part"); | ||
| 1017 | + assert_eq!(engine::proxy::cached(&film), None); | ||
| 1018 | +} | ||