🔀 merge(A2): H.264 joins AV1 and HEVC in the Matroska gate
Browse files at this commit113 changed files +87194 -1270
- Cargo.lock +33 -0
- Cargo.toml +29 -5
- crates/app/src/keymap.rs +114 -10
- crates/app/src/main.rs +3549 -517
- crates/engine-hw/src/lib.rs +101 -17
- crates/engine/Cargo.toml +29 -1
- crates/engine/src/audio.rs +294 -53
- crates/engine/src/decode.rs +116 -1
- crates/engine/src/demux.rs +191 -93
- crates/engine/src/edith.rs +324 -23
- crates/engine/src/export.rs +993 -168
- crates/engine/src/lib.rs +2 -1
- crates/engine/src/limiter.rs +259 -0
- crates/engine/src/mux.rs +745 -34
- crates/engine/src/playback.rs +410 -84
- crates/engine/src/project.rs +794 -102
- crates/engine/tests/audio_decode.rs +5 -3
- crates/engine/tests/audio_export.rs +236 -6
- crates/engine/tests/audio_files.rs +17 -13
- crates/engine/tests/audio_segments.rs +1 -1
- crates/engine/tests/av1.rs +94 -32
- crates/engine/tests/backends.rs +283 -0
- crates/engine/tests/eq_audio.rs +92 -50
- crates/engine/tests/h264_mkv.rs +14 -8
- crates/engine/tests/hevc_export.rs +298 -0
- crates/engine/tests/hevc_mkv.rs +245 -0
- crates/engine/tests/images.rs +108 -0
- crates/engine/tests/lanes.rs +40 -6
- crates/engine/tests/mixed_fps.rs +419 -0
- crates/engine/tests/playback.rs +8 -7
- crates/engine/tests/saveload.rs +77 -6
- crates/engine/tests/silence.rs +14 -2
- crates/engine/tests/speed.rs +24 -19
- scripts/gen_fixtures.sh +38 -4
- vendor/cros-codecs/src/backend/vaapi/decoder.rs +7 -3
- vendor/cros-codecs/src/lib.rs +9 -0
- vendor/cros-codecs/src/video_frame.rs +12 -1
- vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs +3 -0
- vendor/oxideav-h265/Cargo.toml +17 -0
- vendor/oxideav-h265/LICENSE +21 -0
- vendor/oxideav-h265/README.md +243 -0
- vendor/oxideav-h265/src/availability.rs +569 -0
- vendor/oxideav-h265/src/availability/tests.rs +315 -0
- vendor/oxideav-h265/src/binarization.rs +8000 -0
- vendor/oxideav-h265/src/bitreader.rs +300 -0
- vendor/oxideav-h265/src/cabac.rs +820 -0
- vendor/oxideav-h265/src/ctx_init.rs +994 -0
- vendor/oxideav-h265/src/deblock.rs +2484 -0
- vendor/oxideav-h265/src/decode.rs +349 -0
- vendor/oxideav-h265/src/decoder.rs +214 -0
- vendor/oxideav-h265/src/dpb.rs +833 -0
- vendor/oxideav-h265/src/encoder.rs +440 -0
- vendor/oxideav-h265/src/encoder/bitwriter.rs +190 -0
- vendor/oxideav-h265/src/encoder/cabac.rs +323 -0
- vendor/oxideav-h265/src/encoder/ccp_streams.rs +540 -0
- vendor/oxideav-h265/src/encoder/inter.rs +3154 -0
- vendor/oxideav-h265/src/encoder/intra.rs +1514 -0
- vendor/oxideav-h265/src/encoder/loopfilter.rs +1308 -0
- vendor/oxideav-h265/src/encoder/nal.rs +114 -0
- vendor/oxideav-h265/src/encoder/palette_streams.rs +1130 -0
- vendor/oxideav-h265/src/encoder/pcm.rs +1150 -0
- vendor/oxideav-h265/src/encoder/pyramid.rs +718 -0
- vendor/oxideav-h265/src/encoder/rdpcm_streams.rs +772 -0
- vendor/oxideav-h265/src/encoder/residual.rs +641 -0
- vendor/oxideav-h265/src/encoder/scc_streams.rs +936 -0
- vendor/oxideav-h265/src/hrd.rs +1044 -0
- vendor/oxideav-h265/src/hvcc.rs +408 -0
- vendor/oxideav-h265/src/inter_pred.rs +1385 -0
- vendor/oxideav-h265/src/inter_recon.rs +1933 -0
- vendor/oxideav-h265/src/intra_mode_field.rs +371 -0
- vendor/oxideav-h265/src/intra_pred.rs +1230 -0
- vendor/oxideav-h265/src/lib.rs +616 -0
- vendor/oxideav-h265/src/motion.rs +1826 -0
- vendor/oxideav-h265/src/nal.rs +342 -0
- vendor/oxideav-h265/src/palette.rs +981 -0
- vendor/oxideav-h265/src/picture.rs +327 -0
- vendor/oxideav-h265/src/poc.rs +403 -0
- vendor/oxideav-h265/src/pps.rs +1880 -0
- vendor/oxideav-h265/src/pu_mv.rs +1228 -0
- vendor/oxideav-h265/src/recon.rs +3899 -0
- vendor/oxideav-h265/src/residual.rs +1588 -0
- vendor/oxideav-h265/src/sao.rs +762 -0
- vendor/oxideav-h265/src/scaling_list.rs +1011 -0
- vendor/oxideav-h265/src/scan.rs +552 -0
- vendor/oxideav-h265/src/sei.rs +607 -0
- vendor/oxideav-h265/src/sei/tests.rs +478 -0
- vendor/oxideav-h265/src/sequence.rs +1620 -0
- vendor/oxideav-h265/src/slice.rs +5567 -0
- vendor/oxideav-h265/src/slice_data.rs +1527 -0
- vendor/oxideav-h265/src/slice_data/tests.rs +165 -0
- vendor/oxideav-h265/src/sps.rs +3501 -0
- vendor/oxideav-h265/src/transform.rs +1152 -0
- vendor/oxideav-h265/src/transform_tree.rs +347 -0
- vendor/oxideav-h265/src/transform_tree/tests.rs +227 -0
- vendor/oxideav-h265/src/transform_unit.rs +672 -0
- vendor/oxideav-h265/src/vps.rs +1231 -0
- vendor/oxideav-h265/src/vui.rs +1017 -0
- vendor/rusty_aac/Cargo.toml +54 -0
- vendor/rusty_aac/LICENSE +201 -0
- vendor/rusty_aac/README.md +280 -0
- vendor/rusty_aac/src/bits.rs +99 -0
- vendor/rusty_aac/src/codebook.rs +258 -0
- vendor/rusty_aac/src/decode.rs +871 -0
- vendor/rusty_aac/src/dsp.rs +423 -0
- vendor/rusty_aac/src/encode.rs +4940 -0
- vendor/rusty_aac/src/error.rs +58 -0
- vendor/rusty_aac/src/huffman.rs +116 -0
- vendor/rusty_aac/src/ics.rs +175 -0
- vendor/rusty_aac/src/latm.rs +463 -0
- vendor/rusty_aac/src/lib.rs +413 -0
- vendor/rusty_aac/src/sbr.rs +405 -0
- vendor/rusty_aac/src/swb.rs +129 -0
- vendor/rusty_aac/src/tables.rs +296 -0
| @@ -1637,8 +1637,11 @@ dependencies = [ | |||
| 1637 | "mp4", | 1637 | "mp4", |
| 1638 | "oxideav-ac3", | 1638 | "oxideav-ac3", |
| 1639 | "oxideav-core", | 1639 | "oxideav-core", |
| 1640 | + "oxideav-h265", | ||
| 1640 | "rav1e", | 1641 | "rav1e", |
| 1642 | + "rusty_aac", | ||
| 1641 | "rusty_h264", | 1643 | "rusty_h264", |
| 1644 | + "rusty_mp3", | ||
| 1642 | "symphonia", | 1645 | "symphonia", |
| 1643 | "symphonia-codec-aac", | 1646 | "symphonia-codec-aac", |
| 1644 | "symphonia-core", | 1647 | "symphonia-core", |
| @@ -3948,6 +3951,13 @@ dependencies = [ | |||
| 3948 | "thiserror 2.0.20", | 3951 | "thiserror 2.0.20", |
| 3949 | ] | 3952 | ] |
| 3950 | 3953 | ||
| 3954 | +[[package]] | ||
| 3955 | +name = "oxideav-h265" | ||
| 3956 | +version = "0.0.9" | ||
| 3957 | +dependencies = [ | ||
| 3958 | + "oxideav-core", | ||
| 3959 | +] | ||
| 3960 | + | ||
| 3951 | [[package]] | 3961 | [[package]] |
| 3952 | name = "parking" | 3962 | name = "parking" |
| 3953 | version = "2.2.1" | 3963 | version = "2.2.1" |
| @@ -4880,6 +4890,10 @@ version = "1.0.23" | |||
| 4880 | source = "registry+https://github.com/rust-lang/crates.io-index" | 4890 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4881 | checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" | 4891 | checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" |
| 4882 | 4892 | ||
| 4893 | +[[package]] | ||
| 4894 | +name = "rusty_aac" | ||
| 4895 | +version = "0.5.0" | ||
| 4896 | + | ||
| 4883 | [[package]] | 4897 | [[package]] |
| 4884 | name = "rusty_h264" | 4898 | name = "rusty_h264" |
| 4885 | version = "0.8.0" | 4899 | version = "0.8.0" |
| @@ -4919,6 +4933,12 @@ dependencies = [ | |||
| 4919 | "rusty_h264-common", | 4933 | "rusty_h264-common", |
| 4920 | ] | 4934 | ] |
| 4921 | 4935 | ||
| 4936 | +[[package]] | ||
| 4937 | +name = "rusty_mp3" | ||
| 4938 | +version = "0.6.1" | ||
| 4939 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4940 | +checksum = "a99f339ec9a2d84eec8fc2a42baa92426966b25238c498e79d57b4e49b14fbad" | ||
| 4941 | + | ||
| 4922 | [[package]] | 4942 | [[package]] |
| 4923 | name = "rustybuzz" | 4943 | name = "rustybuzz" |
| 4924 | version = "0.14.1" | 4944 | version = "0.14.1" |
| @@ -5600,6 +5620,7 @@ dependencies = [ | |||
| 5600 | "symphonia-codec-vorbis", | 5620 | "symphonia-codec-vorbis", |
| 5601 | "symphonia-core", | 5621 | "symphonia-core", |
| 5602 | "symphonia-format-isomp4", | 5622 | "symphonia-format-isomp4", |
| 5623 | + "symphonia-format-mkv", | ||
| 5603 | "symphonia-format-ogg", | 5624 | "symphonia-format-ogg", |
| 5604 | "symphonia-format-riff", | 5625 | "symphonia-format-riff", |
| 5605 | "symphonia-metadata", | 5626 | "symphonia-metadata", |
| @@ -5709,6 +5730,18 @@ dependencies = [ | |||
| 5709 | "symphonia-metadata", | 5730 | "symphonia-metadata", |
| 5710 | ] | 5731 | ] |
| 5711 | 5732 | ||
| 5733 | +[[package]] | ||
| 5734 | +name = "symphonia-format-mkv" | ||
| 5735 | +version = "0.6.0" | ||
| 5736 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5737 | +checksum = "fb17713e134f5ad316c2690fa3104590ccc85842cdbcf82c3cd1a845cb08aa74" | ||
| 5738 | +dependencies = [ | ||
| 5739 | + "lazy_static", | ||
| 5740 | + "log", | ||
| 5741 | + "symphonia-common", | ||
| 5742 | + "symphonia-core", | ||
| 5743 | +] | ||
| 5744 | + | ||
| 5712 | [[package]] | 5745 | [[package]] |
| 5713 | name = "symphonia-format-ogg" | 5746 | name = "symphonia-format-ogg" |
| 5714 | version = "0.6.0" | 5747 | version = "0.6.0" |
| @@ -2,17 +2,41 @@ | |||
| 2 | resolver = "3" | 2 | resolver = "3" |
| 3 | members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"] | 3 | members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"] |
| 4 | # Vendored third-party (see [patch.crates-io]); not ours to build or test. | 4 | # Vendored third-party (see [patch.crates-io]); not ours to build or test. |
| 5 | -exclude = ["vendor/cros-libva", "vendor/cros-codecs"] | 5 | +exclude = [ |
| 6 | + "vendor/cros-libva", | ||
| 7 | + "vendor/cros-codecs", | ||
| 8 | + "vendor/rusty_aac", | ||
| 9 | + "vendor/oxideav-h265", | ||
| 10 | +] | ||
| 6 | 11 | ||
| 7 | [workspace.package] | 12 | [workspace.package] |
| 8 | version = "0.1.0" | 13 | version = "0.1.0" |
| 9 | edition = "2024" | 14 | edition = "2024" |
| 10 | 15 | ||
| 11 | -# Two upstream crates vendored verbatim except for one clearly marked fix each, | 16 | +# Four upstream crates vendored verbatim except for one clearly marked fix each, |
| 12 | -# both blockers on this machine and both still unfixed upstream as of 0.0.6/0.0.13: | 17 | +# all blockers on this machine and all still unfixed upstream as of |
| 18 | +# 0.0.6/0.0.13/0.5.0/0.0.9: | ||
| 13 | # cros-libva - fails to build against libva >= 1.23 headers | 19 | # cros-libva - fails to build against libva >= 1.23 headers |
| 14 | -# cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses | 20 | +# cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses; |
| 15 | -# Drop `vendor/` entirely once released versions handle both. | 21 | +# and creates every decode context as 8-bit 4:2:0, which no HEVC |
| 22 | +# Main 10 stream can decode into (its own TODO, its own answer) | ||
| 23 | +# rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per | ||
| 24 | +# term (the fast path in the same file serves the encoder only), | ||
| 25 | +# which is 4x slower than real time for 5.1 and therefore not | ||
| 26 | +# playable at all; the patch caches the cosine matrix | ||
| 27 | +# oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and | ||
| 28 | +# refuses any dimension that is not a multiple of the 16-sample | ||
| 29 | +# CTB, so 1920x1080 could not be written at all; the patch adds | ||
| 30 | +# the §7.4.3.2.1 conformance window (`SpsCfg::conf_win`, one | ||
| 31 | +# marked block in `encoder/intra.rs`) so the picture is coded | ||
| 32 | +# padded to 1920x1088 and *displayed* at 1920x1080. Taken from | ||
| 33 | +# git master rather than the registry -- crates.io 0.0.9 is the | ||
| 34 | +# pre-encoder release -- at rev d35963a02c872d12e6878b4ed3cf17a | ||
| 35 | +# 69bde5a6e, and it is a plain path dependency (no | ||
| 36 | +# `[patch.crates-io]` line) because nothing else in the tree | ||
| 37 | +# asks for it. | ||
| 38 | +# Drop `vendor/` entirely once released versions handle all four. | ||
| 16 | [patch.crates-io] | 39 | [patch.crates-io] |
| 17 | cros-libva = { path = "vendor/cros-libva" } | 40 | cros-libva = { path = "vendor/cros-libva" } |
| 18 | cros-codecs = { path = "vendor/cros-codecs" } | 41 | cros-codecs = { path = "vendor/cros-codecs" } |
| 42 | +rusty_aac = { path = "vendor/rusty_aac" } | ||
| @@ -63,22 +63,28 @@ pub enum ActionId { | |||
| 63 | Color, | 63 | Color, |
| 64 | Fit, | 64 | Fit, |
| 65 | Resolution, | 65 | Resolution, |
| 66 | + ZoomIn, | ||
| 67 | + ZoomOut, | ||
| 68 | + ZoomFit, | ||
| 66 | Undo, | 69 | Undo, |
| 67 | AddVideoLane, | 70 | AddVideoLane, |
| 68 | AddAudioLane, | 71 | AddAudioLane, |
| 72 | + RemoveVideoLane, | ||
| 73 | + RemoveAudioLane, | ||
| 69 | ToggleMute, | 74 | ToggleMute, |
| 70 | VolumeUp, | 75 | VolumeUp, |
| 71 | VolumeDown, | 76 | VolumeDown, |
| 72 | Equalizer, | 77 | Equalizer, |
| 73 | Speed, | 78 | Speed, |
| 74 | Silence, | 79 | Silence, |
| 80 | + Mix, | ||
| 75 | CancelExport, | 81 | CancelExport, |
| 76 | } | 82 | } |
| 77 | 83 | ||
| 78 | impl ActionId { | 84 | impl ActionId { |
| 79 | /// Display order everywhere -- the editor lists them in it and | 85 | /// Display order everywhere -- the editor lists them in it and |
| 80 | /// [`Keymap::defaults`] binds them in it. | 86 | /// [`Keymap::defaults`] binds them in it. |
| 81 | - pub const ALL: [ActionId; 33] = [ | 87 | + pub const ALL: [ActionId; 39] = [ |
| 82 | ActionId::Play, | 88 | ActionId::Play, |
| 83 | ActionId::StepBack, | 89 | ActionId::StepBack, |
| 84 | ActionId::StepForward, | 90 | ActionId::StepForward, |
| @@ -102,15 +108,21 @@ impl ActionId { | |||
| 102 | ActionId::Color, | 108 | ActionId::Color, |
| 103 | ActionId::Fit, | 109 | ActionId::Fit, |
| 104 | ActionId::Resolution, | 110 | ActionId::Resolution, |
| 111 | + ActionId::ZoomIn, | ||
| 112 | + ActionId::ZoomOut, | ||
| 113 | + ActionId::ZoomFit, | ||
| 105 | ActionId::Undo, | 114 | ActionId::Undo, |
| 106 | ActionId::AddVideoLane, | 115 | ActionId::AddVideoLane, |
| 107 | ActionId::AddAudioLane, | 116 | ActionId::AddAudioLane, |
| 117 | + ActionId::RemoveVideoLane, | ||
| 118 | + ActionId::RemoveAudioLane, | ||
| 108 | ActionId::ToggleMute, | 119 | ActionId::ToggleMute, |
| 109 | ActionId::VolumeUp, | 120 | ActionId::VolumeUp, |
| 110 | ActionId::VolumeDown, | 121 | ActionId::VolumeDown, |
| 111 | ActionId::Equalizer, | 122 | ActionId::Equalizer, |
| 112 | ActionId::Speed, | 123 | ActionId::Speed, |
| 113 | ActionId::Silence, | 124 | ActionId::Silence, |
| 125 | + ActionId::Mix, | ||
| 114 | ActionId::CancelExport, | 126 | ActionId::CancelExport, |
| 115 | ]; | 127 | ]; |
| 116 | 128 | ||
| @@ -140,15 +152,21 @@ impl ActionId { | |||
| 140 | ActionId::Color => "Colour…", | 152 | ActionId::Color => "Colour…", |
| 141 | ActionId::Fit => "Fit policy: fit → fill → stretch → centre", | 153 | ActionId::Fit => "Fit policy: fit → fill → stretch → centre", |
| 142 | ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p", | 154 | ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p", |
| 155 | + ActionId::ZoomIn => "Zoom in on the timeline (around the playhead)", | ||
| 156 | + ActionId::ZoomOut => "Zoom out of the timeline", | ||
| 157 | + ActionId::ZoomFit => "Fit the whole timeline on screen", | ||
| 143 | ActionId::Undo => "Undo", | 158 | ActionId::Undo => "Undo", |
| 144 | ActionId::AddVideoLane => "Add a video track", | 159 | ActionId::AddVideoLane => "Add a video track", |
| 145 | ActionId::AddAudioLane => "Add an audio track", | 160 | ActionId::AddAudioLane => "Add an audio track", |
| 161 | + ActionId::RemoveVideoLane => "Remove the last video track (it must be empty)", | ||
| 162 | + ActionId::RemoveAudioLane => "Remove the last audio track (it must be empty)", | ||
| 146 | ActionId::ToggleMute => "Mute / Unmute", | 163 | ActionId::ToggleMute => "Mute / Unmute", |
| 147 | ActionId::VolumeUp => "Volume up", | 164 | ActionId::VolumeUp => "Volume up", |
| 148 | ActionId::VolumeDown => "Volume down", | 165 | ActionId::VolumeDown => "Volume down", |
| 149 | ActionId::Equalizer => "Equalizer", | 166 | ActionId::Equalizer => "Equalizer", |
| 150 | ActionId::Speed => "Speed (tape)…", | 167 | ActionId::Speed => "Speed (tape)…", |
| 151 | ActionId::Silence => "Silences: cut or speed up…", | 168 | ActionId::Silence => "Silences: cut or speed up…", |
| 169 | + ActionId::Mix => "Mix: track volumes and the limiter…", | ||
| 152 | ActionId::CancelExport => "Cancel export", | 170 | ActionId::CancelExport => "Cancel export", |
| 153 | } | 171 | } |
| 154 | } | 172 | } |
| @@ -180,15 +198,21 @@ impl ActionId { | |||
| 180 | ActionId::Color => "color", | 198 | ActionId::Color => "color", |
| 181 | ActionId::Fit => "fit", | 199 | ActionId::Fit => "fit", |
| 182 | ActionId::Resolution => "resolution", | 200 | ActionId::Resolution => "resolution", |
| 201 | + ActionId::ZoomIn => "zoom-in", | ||
| 202 | + ActionId::ZoomOut => "zoom-out", | ||
| 203 | + ActionId::ZoomFit => "zoom-fit", | ||
| 183 | ActionId::Undo => "undo", | 204 | ActionId::Undo => "undo", |
| 184 | ActionId::AddVideoLane => "add-video-lane", | 205 | ActionId::AddVideoLane => "add-video-lane", |
| 185 | ActionId::AddAudioLane => "add-audio-lane", | 206 | ActionId::AddAudioLane => "add-audio-lane", |
| 207 | + ActionId::RemoveVideoLane => "remove-video-lane", | ||
| 208 | + ActionId::RemoveAudioLane => "remove-audio-lane", | ||
| 186 | ActionId::ToggleMute => "toggle-mute", | 209 | ActionId::ToggleMute => "toggle-mute", |
| 187 | ActionId::VolumeUp => "volume-up", | 210 | ActionId::VolumeUp => "volume-up", |
| 188 | ActionId::VolumeDown => "volume-down", | 211 | ActionId::VolumeDown => "volume-down", |
| 189 | ActionId::Equalizer => "equalizer", | 212 | ActionId::Equalizer => "equalizer", |
| 190 | ActionId::Speed => "speed", | 213 | ActionId::Speed => "speed", |
| 191 | ActionId::Silence => "silence", | 214 | ActionId::Silence => "silence", |
| 215 | + ActionId::Mix => "mix", | ||
| 192 | ActionId::CancelExport => "cancel-export", | 216 | ActionId::CancelExport => "cancel-export", |
| 193 | } | 217 | } |
| 194 | } | 218 | } |
| @@ -228,18 +252,29 @@ impl ActionId { | |||
| 228 | | ActionId::Silence => Category::Clips, | 252 | | ActionId::Silence => Category::Clips, |
| 229 | // The project's own picture size is not a clip's business, and not | 253 | // The project's own picture size is not a clip's business, and not |
| 230 | // a file operation either: it is what the viewer is looking at. | 254 | // a file operation either: it is what the viewer is looking at. |
| 231 | - ActionId::Resolution => Category::View, | 255 | + // Neither is how much of the timeline the panel shows: a zoom edits |
| 256 | + // nothing, it magnifies. | ||
| 257 | + ActionId::Resolution | ActionId::ZoomIn | ActionId::ZoomOut | ActionId::ZoomFit => { | ||
| 258 | + Category::View | ||
| 259 | + } | ||
| 232 | ActionId::Cut | 260 | ActionId::Cut |
| 233 | | ActionId::Regroup | 261 | | ActionId::Regroup |
| 234 | | ActionId::Detach | 262 | | ActionId::Detach |
| 235 | | ActionId::Group | 263 | | ActionId::Group |
| 236 | | ActionId::Undo | 264 | | ActionId::Undo |
| 237 | | ActionId::AddVideoLane | 265 | | ActionId::AddVideoLane |
| 238 | - | ActionId::AddAudioLane => Category::Editing, | 266 | + | ActionId::AddAudioLane |
| 267 | + | ActionId::RemoveVideoLane | ||
| 268 | + | ActionId::RemoveAudioLane => Category::Editing, | ||
| 239 | ActionId::ToggleMute | 269 | ActionId::ToggleMute |
| 240 | | ActionId::VolumeUp | 270 | | ActionId::VolumeUp |
| 241 | | ActionId::VolumeDown | 271 | | ActionId::VolumeDown |
| 242 | - | ActionId::Equalizer => Category::Audio, | 272 | + | ActionId::Equalizer |
| 273 | + // The mix is the project's sound -- what every track plays at and | ||
| 274 | + // what the whole of it is held under -- where the three above it | ||
| 275 | + // are this machine's monitoring. Both are audio, and the card says | ||
| 276 | + // which is which. | ||
| 277 | + | ActionId::Mix => Category::Audio, | ||
| 243 | ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File, | 278 | ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File, |
| 244 | } | 279 | } |
| 245 | } | 280 | } |
| @@ -291,7 +326,15 @@ pub struct Fixed { | |||
| 291 | pub category: Category, | 326 | pub category: Category, |
| 292 | } | 327 | } |
| 293 | 328 | ||
| 294 | -pub const FIXED: [Fixed; 14] = [ | 329 | +pub const FIXED: [Fixed; 21] = [ |
| 330 | + // Not a chord at all but a way of pressing one, and the only place the | ||
| 331 | + // editor can say so: holding a key that moves a *value* runs it, and | ||
| 332 | + // holding anything else still does what one press did. | ||
| 333 | + Fixed { | ||
| 334 | + chord: "hold ← → ↑ ↓", | ||
| 335 | + label: "Run a card's slider, or the volume and zoom keys, while held", | ||
| 336 | + category: Category::View, | ||
| 337 | + }, | ||
| 295 | Fixed { | 338 | Fixed { |
| 296 | chord: "esc", | 339 | chord: "esc", |
| 297 | label: "Close this card or menu, or cancel a capture", | 340 | label: "Close this card or menu, or cancel a capture", |
| @@ -303,8 +346,38 @@ pub const FIXED: [Fixed; 14] = [ | |||
| 303 | category: Category::File, | 346 | category: Category::File, |
| 304 | }, | 347 | }, |
| 305 | Fixed { | 348 | Fixed { |
| 306 | - chord: "m / a / w / f", | 349 | + chord: "m / a / h / w / f / p", |
| 307 | - label: "Pick the export format: MP4, AV1, WAV or FLAC", | 350 | + label: "Pick the export codec: H.264, AV1, HEVC, WAV, FLAC or MP3", |
| 351 | + category: Category::File, | ||
| 352 | + }, | ||
| 353 | + // The rest of the export card's own rows, each on the letter its row is | ||
| 354 | + // named after. They shadow the clip keys of the same letter while the card | ||
| 355 | + // is up, exactly as its digits shadow nothing and its arrows would: a modal | ||
| 356 | + // card owns the keyboard, and cutting a clip under it is not a thing that | ||
| 357 | + // can happen anyway. | ||
| 358 | + Fixed { | ||
| 359 | + chord: "c", | ||
| 360 | + label: "Switch the export container: Matroska or MP4", | ||
| 361 | + category: Category::File, | ||
| 362 | + }, | ||
| 363 | + Fixed { | ||
| 364 | + chord: "q", | ||
| 365 | + label: "Step through the export quality rows", | ||
| 366 | + category: Category::File, | ||
| 367 | + }, | ||
| 368 | + Fixed { | ||
| 369 | + chord: "d", | ||
| 370 | + label: "Choose where the export is written", | ||
| 371 | + category: Category::File, | ||
| 372 | + }, | ||
| 373 | + Fixed { | ||
| 374 | + chord: "g", | ||
| 375 | + label: "Export card: sections or one flat list", | ||
| 376 | + category: Category::File, | ||
| 377 | + }, | ||
| 378 | + Fixed { | ||
| 379 | + chord: "r", | ||
| 380 | + label: "Export card: the formats with no encoder as rows or as one line", | ||
| 308 | category: Category::File, | 381 | category: Category::File, |
| 309 | }, | 382 | }, |
| 310 | Fixed { | 383 | Fixed { |
| @@ -340,6 +413,11 @@ pub const FIXED: [Fixed; 14] = [ | |||
| 340 | label: "Flatten every band", | 413 | label: "Flatten every band", |
| 341 | category: Category::Audio, | 414 | category: Category::Audio, |
| 342 | }, | 415 | }, |
| 416 | + Fixed { | ||
| 417 | + chord: "s", | ||
| 418 | + label: "Show or hide the spectrum behind the curve", | ||
| 419 | + category: Category::Audio, | ||
| 420 | + }, | ||
| 343 | // The colour card's own three, which mean nothing outside it -- the same | 421 | // The colour card's own three, which mean nothing outside it -- the same |
| 344 | // card-local input the export card's digits are. | 422 | // card-local input the export card's digits are. |
| 345 | Fixed { | 423 | Fixed { |
| @@ -521,6 +599,14 @@ impl Keymap { | |||
| 521 | // it changes what every clip is composed onto. | 599 | // it changes what every clip is composed onto. |
| 522 | b(ActionId::Fit, "p", false), | 600 | b(ActionId::Fit, "p", false), |
| 523 | b(ActionId::Resolution, "r", true), | 601 | b(ActionId::Resolution, "r", true), |
| 602 | + // The zoom pair, on the chords every editor and every browser | ||
| 603 | + // magnifies with. The bare "=" and "-" are the volume keys, so | ||
| 604 | + // these take the ctrl versions of them -- and ctrl+0 is the | ||
| 605 | + // "back to 100%" of the same family, which here is the whole | ||
| 606 | + // timeline across the bed. | ||
| 607 | + b(ActionId::ZoomIn, "=", true), | ||
| 608 | + b(ActionId::ZoomOut, "-", true), | ||
| 609 | + b(ActionId::ZoomFit, "0", true), | ||
| 524 | b(ActionId::Undo, "z", false), | 610 | b(ActionId::Undo, "z", false), |
| 525 | b(ActionId::Undo, "z", true), | 611 | b(ActionId::Undo, "z", true), |
| 526 | // The unshifted initials of what they add. Both were free -- | 612 | // The unshifted initials of what they add. Both were free -- |
| @@ -528,6 +614,13 @@ impl Keymap { | |||
| 528 | // is added often enough to deserve a key that is one press. | 614 | // is added often enough to deserve a key that is one press. |
| 529 | b(ActionId::AddVideoLane, "v", false), | 615 | b(ActionId::AddVideoLane, "v", false), |
| 530 | b(ActionId::AddAudioLane, "a", false), | 616 | b(ActionId::AddAudioLane, "a", false), |
| 617 | + // ...and the pair that takes one back, on ctrl chords: removing | ||
| 618 | + // a track is not a stroke to hit by accident (the resolution key | ||
| 619 | + // is out of the way for the same reason). Ctrl+v would be the | ||
| 620 | + // matching initial and is the paste, so the video one takes the | ||
| 621 | + // key beside it. | ||
| 622 | + b(ActionId::RemoveVideoLane, "b", true), | ||
| 623 | + b(ActionId::RemoveAudioLane, "a", true), | ||
| 531 | b(ActionId::ToggleMute, "m", false), | 624 | b(ActionId::ToggleMute, "m", false), |
| 532 | // The unshifted pair, which is what gpui reports for those two | 625 | // The unshifted pair, which is what gpui reports for those two |
| 533 | // keys ("=" and "-", platform.rs:862): the volume keys every | 626 | // keys ("=" and "-", platform.rs:862): the volume keys every |
| @@ -547,6 +640,11 @@ impl Keymap { | |||
| 547 | // delete (x and delete) -- what it opens is a card that can cut | 640 | // delete (x and delete) -- what it opens is a card that can cut |
| 548 | // forty places at once. | 641 | // forty places at once. |
| 549 | b(ActionId::Silence, "u", false), | 642 | b(ActionId::Silence, "u", false), |
| 643 | + // The mix card takes "f", for the faders on it: "m" would be | ||
| 644 | + // the word but it is the monitoring mute, which is this | ||
| 645 | + // machine's volume and not the project's -- two things one key | ||
| 646 | + // must not mean. | ||
| 647 | + b(ActionId::Mix, "f", false), | ||
| 550 | b(ActionId::CancelExport, "escape", false), | 648 | b(ActionId::CancelExport, "escape", false), |
| 551 | ], | 649 | ], |
| 552 | } | 650 | } |
| @@ -809,7 +907,7 @@ mod tests { | |||
| 809 | #[test] | 907 | #[test] |
| 810 | fn every_default_stroke_reaches_its_action() { | 908 | fn every_default_stroke_reaches_its_action() { |
| 811 | let k = Keymap::defaults(); | 909 | let k = Keymap::defaults(); |
| 812 | - assert_eq!(k.entries().len(), 35); | 910 | + assert_eq!(k.entries().len(), 41); |
| 813 | assert_eq!(k.lookup("space", false), Some(ActionId::Play)); | 911 | assert_eq!(k.lookup("space", false), Some(ActionId::Play)); |
| 814 | // The seek keys: bare arrows a frame, ctrl arrows a second, and the two | 912 | // The seek keys: bare arrows a frame, ctrl arrows a second, and the two |
| 815 | // ends of the timeline. | 913 | // ends of the timeline. |
| @@ -843,6 +941,10 @@ mod tests { | |||
| 843 | // The track keys are the bare letters; the ctrl ones stay copy/paste. | 941 | // The track keys are the bare letters; the ctrl ones stay copy/paste. |
| 844 | assert_eq!(k.lookup("v", false), Some(ActionId::AddVideoLane)); | 942 | assert_eq!(k.lookup("v", false), Some(ActionId::AddVideoLane)); |
| 845 | assert_eq!(k.lookup("a", false), Some(ActionId::AddAudioLane)); | 943 | assert_eq!(k.lookup("a", false), Some(ActionId::AddAudioLane)); |
| 944 | + // ...and the ctrl ones take a track away, out of the way of a stray | ||
| 945 | + // press. Ctrl+v is the paste, so the video one sits beside it. | ||
| 946 | + assert_eq!(k.lookup("b", true), Some(ActionId::RemoveVideoLane)); | ||
| 947 | + assert_eq!(k.lookup("a", true), Some(ActionId::RemoveAudioLane)); | ||
| 846 | assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); | 948 | assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); |
| 847 | assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer)); | 949 | assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer)); |
| 848 | // The volume pair is the unshifted one, so neither needs a modifier | 950 | // The volume pair is the unshifted one, so neither needs a modifier |
| @@ -981,7 +1083,8 @@ mod tests { | |||
| 981 | // A bindable chord is one `rebind_action` may keep: what it writes is | 1083 | // A bindable chord is one `rebind_action` may keep: what it writes is |
| 982 | // what the next load reads, for every stroke that passes here. | 1084 | // what the next load reads, for every stroke that passes here. |
| 983 | let mut k = Keymap::defaults(); | 1085 | let mut k = Keymap::defaults(); |
| 984 | - k.rebind_action(ActionId::Play, chord("=", true)).unwrap(); | 1086 | + // Any free chord will do here; ctrl+= is the zoom's. |
| 1087 | + k.rebind_action(ActionId::Play, chord("w", true)).unwrap(); | ||
| 985 | assert_eq!(whole(&emit(&k)), k); | 1088 | assert_eq!(whole(&emit(&k)), k); |
| 986 | } | 1089 | } |
| 987 | 1090 | ||
| @@ -1038,7 +1141,8 @@ mod tests { | |||
| 1038 | assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); | 1141 | assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); |
| 1039 | // The label is the editor's column, and never the file's word for it. | 1142 | // The label is the editor's column, and never the file's word for it. |
| 1040 | assert_eq!(ActionId::CancelExport.label(), "Cancel export"); | 1143 | assert_eq!(ActionId::CancelExport.label(), "Cancel export"); |
| 1041 | - assert_eq!(ActionId::ALL.len(), 33); | 1144 | + assert_eq!(ActionId::ALL.len(), 39); |
| 1145 | + assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); | ||
| 1042 | } | 1146 | } |
| 1043 | 1147 | ||
| 1044 | #[test] | 1148 | #[test] |
Diff too large; view file
| @@ -11,17 +11,19 @@ use std::time::{Duration, Instant}; | |||
| 11 | 11 | ||
| 12 | use engine::audio::StreamInfo; | 12 | use engine::audio::StreamInfo; |
| 13 | use engine::color::ColorParams; | 13 | use engine::color::ColorParams; |
| 14 | +use engine::decode::Backend; | ||
| 14 | use engine::eq::{Band, BandKind, EqParams}; | 15 | use engine::eq::{Band, BandKind, EqParams}; |
| 15 | use engine::export::{ExportSettings, Format}; | 16 | use engine::export::{ExportSettings, Format}; |
| 17 | +use engine::limiter::Limiter; | ||
| 16 | use engine::project::{Edge, Lane, LaneKind, Source, Speed}; | 18 | use engine::project::{Edge, Lane, LaneKind, Source, Speed}; |
| 17 | use engine::scale::FitPolicy; | 19 | use engine::scale::FitPolicy; |
| 18 | -use engine::{Clip, ExportHandle, Frame, PlaybackSession}; | 20 | +use engine::{Clip, Codec, ExportHandle, Frame, PlaybackSession}; |
| 19 | use gpui::{ | 21 | use gpui::{ |
| 20 | AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, | 22 | AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, |
| 21 | KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, | 23 | KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, |
| 22 | - Point, RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, | 24 | + Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign, |
| 23 | - WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, | 25 | + TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, |
| 24 | - size, | 26 | + relative, rgb, rgba, size, |
| 25 | }; | 27 | }; |
| 26 | 28 | ||
| 27 | /// Editor chrome: three grays and one accent, all darker than the picture so the | 29 | /// Editor chrome: three grays and one accent, all darker than the picture so the |
| @@ -74,6 +76,11 @@ const LABEL_MIN_W: f32 = 36.; | |||
| 74 | /// allocates one bucket per window, so a rate taken from anything the user can | 76 | /// allocates one bucket per window, so a rate taken from anything the user can |
| 75 | /// influence is an allocation bomb -- and 40 is already finer than the pixels a | 77 | /// influence is an allocation bomb -- and 40 is already finer than the pixels a |
| 76 | /// clip is ever given. | 78 | /// clip is ever given. |
| 79 | +/// | ||
| 80 | +/// ponytail: "finer than the pixels" stops being true once the timeline is | ||
| 81 | +/// zoomed -- past ~25 ms per bucket the envelope reads as steps rather than as | ||
| 82 | +/// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade | ||
| 83 | +/// is a second, finer pass over the visible span only, cached like `waves` is. | ||
| 77 | const WAVE_BPS: u32 = 40; | 84 | const WAVE_BPS: u32 = 40; |
| 78 | /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, | 85 | /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, |
| 79 | /// and a path with a point per pixel is a path per repaint. | 86 | /// and a path with a point per pixel is a path per repaint. |
| @@ -95,6 +102,9 @@ const ROW_H: f32 = 32.; | |||
| 95 | /// wear in the lanes, which is the whole of the panel<->timeline association. | 102 | /// wear in the lanes, which is the whole of the panel<->timeline association. |
| 96 | const SWATCH_W: f32 = 4.; | 103 | const SWATCH_W: f32 = 4.; |
| 97 | const CONTROL_H: f32 = 28.; | 104 | const CONTROL_H: f32 = 28.; |
| 105 | +/// The volume slider beside its button: a hundred steps across it, so a pixel | ||
| 106 | +/// is finer than a step and the drag reads as continuous. | ||
| 107 | +const VOLUME_W: f32 = 110.; | ||
| 98 | const RULER_HIT_H: f32 = HIT_MIN; | 108 | const RULER_HIT_H: f32 = HIT_MIN; |
| 99 | /// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits | 109 | /// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits |
| 100 | /// cannot push the layout around. | 110 | /// cannot push the layout around. |
| @@ -107,16 +117,39 @@ const KEYS_ROW_H: f32 = HIT_MIN; | |||
| 107 | /// keeps the card inside the smallest window no matter how many actions the | 117 | /// keeps the card inside the smallest window no matter how many actions the |
| 108 | /// editor grows -- ten rows fit here, and the eleventh is a scroll away. | 118 | /// editor grows -- ten rows fit here, and the eleventh is a scroll away. |
| 109 | const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; | 119 | const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; |
| 110 | -/// The same for the export card, which carries a fixed-format line and a button | 120 | +/// The same for the export card, which carries two summary lines and a button |
| 111 | -/// under its list and so has less room: destination, nine formats and five | 121 | +/// under its list and so has less room: a section header, six codecs, the |
| 112 | -/// qualities are fifteen rows, eight of them on screen. | 122 | +/// container, five qualities and the destination are more rows than a 360 px |
| 123 | +/// window holds. Eight on screen, which is the whole format section and its | ||
| 124 | +/// header -- what a user picks first is never behind a scroll. | ||
| 113 | const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; | 125 | const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; |
| 126 | +/// The export card is wider than the keybindings one: its rows carry a key, a | ||
| 127 | +/// name *and* what the choice means, and the two summary lines under them state | ||
| 128 | +/// the whole file. At `KEYS_W` every one of those wrapped to two lines, which is | ||
| 129 | +/// the card the user called unfriendly. Still inside the 640 px floor with the | ||
| 130 | +/// scrim showing either side of it. | ||
| 131 | +const EXPORT_W: f32 = 420.; | ||
| 132 | +/// The column the key of a row is printed in, wide enough for `0–9`: every row | ||
| 133 | +/// in the export card says what picks it, so the card is drivable by keyboard | ||
| 134 | +/// without a legend to memorise. | ||
| 135 | +const EXPORT_KEY_W: f32 = 26.; | ||
| 136 | +/// Everything in the export card that is *not* the row list: the title, the | ||
| 137 | +/// status line, the head and tail of the summary, the button, the gaps between | ||
| 138 | +/// them and the padding around the lot. What the list may be is the window | ||
| 139 | +/// minus this -- and never less than [`EXPORT_ROWS_H`], which is the number | ||
| 140 | +/// that makes the card fit the 360 px floor. | ||
| 141 | +const EXPORT_FIXED_H: f32 = 17. + 28. + 15. + 30. + CONTROL_H + 4. + 10. + 24.; | ||
| 114 | /// The menu a right-click on a clip opens: wide enough for the longest label | 142 | /// The menu a right-click on a clip opens: wide enough for the longest label |
| 115 | /// beside the stroke that does the same thing, with the click targets `HIT_MIN` | 143 | /// beside the stroke that does the same thing, with the click targets `HIT_MIN` |
| 116 | /// binds like every other list here. | 144 | /// binds like every other list here. |
| 117 | const MENU_W: f32 = 260.; | 145 | const MENU_W: f32 = 260.; |
| 118 | const MENU_ROW_H: f32 = HIT_MIN; | 146 | const MENU_ROW_H: f32 = HIT_MIN; |
| 119 | const MENU_PAD: f32 = 6.; | 147 | const MENU_PAD: f32 = 6.; |
| 148 | +/// How much of the item list is on screen at once, capped and scrolling like the | ||
| 149 | +/// keybindings and export lists: every action the pointer can reach is an item | ||
| 150 | +/// here, and a menu taller than the 640x360 floor would hang its last items off | ||
| 151 | +/// the bottom edge, where nobody can click them. | ||
| 152 | +const MENU_ROWS_H: f32 = 12. * MENU_ROW_H; | ||
| 120 | 153 | ||
| 121 | /// The one key name this file still spells out, and gpui's spelling of it: it | 154 | /// The one key name this file still spells out, and gpui's spelling of it: it |
| 122 | /// is the way out of a capture and out of the overlay, and both have to work | 155 | /// is the way out of a capture and out of the overlay, and both have to work |
| @@ -128,6 +161,18 @@ const ESCAPE: &str = "escape"; | |||
| 128 | /// as a program name rather than as a file name. | 161 | /// as a program name rather than as a file name. |
| 129 | const NO_FILE: &str = "no file open"; | 162 | const NO_FILE: &str = "no file open"; |
| 130 | 163 | ||
| 164 | +/// What a press of play says when there is nothing to play: no timeline at all | ||
| 165 | +/// and an emptied one are the same answer to the user, so they are one line. | ||
| 166 | +const NOTHING_TO_PLAY: &str = "NOTHING TO PLAY — put a clip on the timeline first"; | ||
| 167 | + | ||
| 168 | +/// Whether a press of play would have anything to play. No timeline at all and | ||
| 169 | +/// one every clip has been taken off are the same state to a transport, and the | ||
| 170 | +/// button and the key both have to give the same answer to it -- so there is | ||
| 171 | +/// one of them, and it is free of the window so it can be checked without one. | ||
| 172 | +fn nothing_to_play(session: Option<&PlaybackSession>) -> bool { | ||
| 173 | + session.is_none_or(PlaybackSession::is_empty) | ||
| 174 | +} | ||
| 175 | + | ||
| 131 | /// What the monitoring output is set to. Two things, not one: the level the | 176 | /// What the monitoring output is set to. Two things, not one: the level the |
| 132 | /// user picked, and whether it is being held silent -- so unmuting comes back | 177 | /// user picked, and whether it is being held silent -- so unmuting comes back |
| 133 | /// to the level rather than to a guess. | 178 | /// to the level rather than to a guess. |
| @@ -146,29 +191,45 @@ struct Volume { | |||
| 146 | } | 191 | } |
| 147 | 192 | ||
| 148 | impl Volume { | 193 | impl Volume { |
| 149 | - /// 5% a press: twenty of them across the range. | 194 | + /// One step is one percent: fine enough that a drag along the slider reads |
| 150 | - const MAX_STEPS: u8 = 20; | 195 | + /// as continuous, and still a count rather than a float. |
| 196 | + const MAX_STEPS: u8 = 100; | ||
| 197 | + | ||
| 198 | + /// 5% a press: twenty presses across the range, which is what the keys have | ||
| 199 | + /// always moved. The slider is what the finer grid is for. | ||
| 200 | + const KEY_STEP: u8 = 5; | ||
| 151 | 201 | ||
| 152 | /// What the device is set to: mute wins, and the level is what it returns | 202 | /// What the device is set to: mute wins, and the level is what it returns |
| 153 | /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts. | 203 | /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts. |
| 154 | fn gain(self) -> f32 { | 204 | fn gain(self) -> f32 { |
| 155 | - if self.muted { | 205 | + if self.muted { 0. } else { self.along() } |
| 156 | - 0. | ||
| 157 | - } else { | ||
| 158 | - f32::from(self.steps) / f32::from(Self::MAX_STEPS) | ||
| 159 | - } | ||
| 160 | } | 206 | } |
| 161 | 207 | ||
| 162 | /// One press up or down, clamped at both ends -- saturating, so the count | 208 | /// One press up or down, clamped at both ends -- saturating, so the count |
| 163 | /// cannot wrap past silence into full volume. | 209 | /// cannot wrap past silence into full volume. |
| 164 | fn step(&mut self, up: bool) { | 210 | fn step(&mut self, up: bool) { |
| 165 | self.steps = if up { | 211 | self.steps = if up { |
| 166 | - self.steps.saturating_add(1).min(Self::MAX_STEPS) | 212 | + self.steps.saturating_add(Self::KEY_STEP).min(Self::MAX_STEPS) |
| 167 | } else { | 213 | } else { |
| 168 | - self.steps.saturating_sub(1) | 214 | + self.steps.saturating_sub(Self::KEY_STEP) |
| 169 | }; | 215 | }; |
| 170 | } | 216 | } |
| 171 | 217 | ||
| 218 | + /// Where the hand let go along the slider, 0..1 from silence to full. The | ||
| 219 | + /// grid is the same one the keys land on, so a drag to the top and a key | ||
| 220 | + /// held up reach the very same number -- and a drag never touches mute: | ||
| 221 | + /// asking for a level while muted is not asking for sound. | ||
| 222 | + fn set_along(&mut self, frac: f32) { | ||
| 223 | + self.steps = (frac.clamp(0., 1.) * f32::from(Self::MAX_STEPS)).round() as u8; | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + /// How full the slider is drawn, 0..1. The level and not the gain: a muted | ||
| 227 | + /// slider still shows what unmuting comes back to, exactly as the label | ||
| 228 | + /// does. | ||
| 229 | + fn along(self) -> f32 { | ||
| 230 | + f32::from(self.steps) / f32::from(Self::MAX_STEPS) | ||
| 231 | + } | ||
| 232 | + | ||
| 172 | /// What the button reads. The level shows while muted too: it is what the | 233 | /// What the button reads. The level shows while muted too: it is what the |
| 173 | /// next press of the mute key brings back. | 234 | /// next press of the mute key brings back. |
| 174 | fn label(self) -> String { | 235 | fn label(self) -> String { |
| @@ -209,8 +270,9 @@ struct AssetDrag(PathBuf, usize); | |||
| 209 | 270 | ||
| 210 | /// A clip already on the timeline being dragged: the lane it is on and its index | 271 | /// A clip already on the timeline being dragged: the lane it is on and its index |
| 211 | /// there, which is how every other edit names a clip. Unlike an [`AssetDrag`] | 272 | /// there, which is how every other edit names a clip. Unlike an [`AssetDrag`] |
| 212 | -/// nothing is inserted -- the same clip changes lane and keeps its frames -- so | 273 | +/// nothing is inserted -- the same clip changes lane and keeps the frames it |
| 213 | -/// where along the bed it is let go says nothing here either. | 274 | +/// plays -- but where along the bed it is let go is exactly where it lands, less |
| 275 | +/// the offset the hand grabbed it at ([`Player::grab`]). | ||
| 214 | #[derive(Clone, Copy)] | 276 | #[derive(Clone, Copy)] |
| 215 | struct ClipDrag { | 277 | struct ClipDrag { |
| 216 | lane: Lane, | 278 | lane: Lane, |
| @@ -242,6 +304,12 @@ struct Trim { | |||
| 242 | /// still the body. | 304 | /// still the body. |
| 243 | const EDGE_W: f32 = 6.; | 305 | const EDGE_W: f32 = 6.; |
| 244 | 306 | ||
| 307 | +/// How close to an edge a dragged clip has to be let go for it to land *on* it: | ||
| 308 | +/// the snap every timeline has, in pixels rather than frames so that it feels | ||
| 309 | +/// the same at every zoom. Narrower than [`EDGE_W`] -- a hand aiming between two | ||
| 310 | +/// takes must still be able to leave a gap of a few frames there. | ||
| 311 | +const SNAP_PX: f64 = 5.; | ||
| 312 | + | ||
| 245 | /// An open clip menu: which clip it was opened on, where it hangs, and whether | 313 | /// An open clip menu: which clip it was opened on, where it hangs, and whether |
| 246 | /// it has been turned over to show what that clip *is* instead of what can be | 314 | /// it has been turned over to show what that clip *is* instead of what can be |
| 247 | /// done to it. The lane and index are the ones the same click selected, so | 315 | /// done to it. The lane and index are the ones the same click selected, so |
| @@ -311,8 +379,13 @@ impl RowItem { | |||
| 311 | /// action a stroke already reaches -- the menu is a second way *to* the actions | 379 | /// action a stroke already reaches -- the menu is a second way *to* the actions |
| 312 | /// and never a second version of them -- so both the label and the hint come | 380 | /// and never a second version of them -- so both the label and the hint come |
| 313 | /// out of the keymap registry and the two can never disagree. | 381 | /// out of the keymap registry and the two can never disagree. |
| 314 | -const MENU_ITEMS: [ActionId; 11] = [ | 382 | +const MENU_ITEMS: [ActionId; 14] = [ |
| 315 | ActionId::Cut, | 383 | ActionId::Cut, |
| 384 | + // The clipboard pair, which had no door but a chord: copy takes the clip the | ||
| 385 | + // menu names, and paste is the timeline's rather than this clip's -- the | ||
| 386 | + // same kind of global item the mute below already is. | ||
| 387 | + ActionId::Copy, | ||
| 388 | + ActionId::Paste, | ||
| 316 | ActionId::Delete, | 389 | ActionId::Delete, |
| 317 | ActionId::Lift, | 390 | ActionId::Lift, |
| 318 | ActionId::Regroup, | 391 | ActionId::Regroup, |
| @@ -320,6 +393,10 @@ const MENU_ITEMS: [ActionId; 11] = [ | |||
| 320 | ActionId::Group, | 393 | ActionId::Group, |
| 321 | ActionId::Equalizer, | 394 | ActionId::Equalizer, |
| 322 | ActionId::Speed, | 395 | ActionId::Speed, |
| 396 | + // The scan is a clip card like the two above it -- opened on whichever half | ||
| 397 | + // was clicked -- and a card only a stroke could open is one a pointer never | ||
| 398 | + // finds. | ||
| 399 | + ActionId::Silence, | ||
| 323 | ActionId::Color, | 400 | ActionId::Color, |
| 324 | ActionId::Fit, | 401 | ActionId::Fit, |
| 325 | ActionId::ToggleMute, | 402 | ActionId::ToggleMute, |
| @@ -358,9 +435,10 @@ fn speed_at(permille: i32) -> Speed { | |||
| 358 | } | 435 | } |
| 359 | 436 | ||
| 360 | /// The silence card's rows, in the order it lists them: how wide the apply | 437 | /// The silence card's rows, in the order it lists them: how wide the apply |
| 361 | -/// reaches, the four settings a scan is told, and the rate the speed-up plays | 438 | +/// reaches, the threshold and the unit it is read in, the three durations a |
| 362 | -/// at. What `silence_field` indexes and what [`Player::nudge_silence`] moves. | 439 | +/// scan is told, and the rate the speed-up plays at. What `silence_field` |
| 363 | -const SILENCE_ROWS: usize = 6; | 440 | +/// indexes and what [`Player::nudge_silence`] moves. |
| 441 | +const SILENCE_ROWS: usize = 7; | ||
| 364 | 442 | ||
| 365 | /// How wide a jumpcut reaches. A ripple used to be the whole timeline's | 443 | /// How wide a jumpcut reaches. A ripple used to be the whole timeline's |
| 366 | /// business and nothing else; it is a *choice* now, because a podcast track's | 444 | /// business and nothing else; it is a *choice* now, because a podcast track's |
| @@ -408,11 +486,24 @@ const SILENCE_DB_STEP: f32 = 1.; | |||
| 408 | const SILENCE_SECS_STEP: f64 = 0.05; | 486 | const SILENCE_SECS_STEP: f64 = 0.05; |
| 409 | 487 | ||
| 410 | /// How far each of them may be pushed. UI decisions, all of them: the engine | 488 | /// How far each of them may be pushed. UI decisions, all of them: the engine |
| 411 | -/// takes any finite number, but a threshold at 0 dBFS calls a whole take silent | 489 | +/// takes any finite number, but a forgiveness of ten seconds finds nothing in a |
| 412 | -/// and a forgiveness of ten seconds finds nothing in a talking head. | 490 | +/// talking head. The threshold reaches full scale, which calls a whole take |
| 413 | -const SILENCE_DB_RANGE: (f32, f32) = (-80., -10.); | 491 | +/// silent -- that is a thing someone may want to ask for (the preview on the |
| 492 | +/// lane says what it would cost before anything is cut), so the top is 0 rather | ||
| 493 | +/// than a number this card picked for them. | ||
| 494 | +const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.); | ||
| 414 | const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.); | 495 | const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.); |
| 415 | 496 | ||
| 497 | +/// One press of a nudge key on the mix card, in dB: the step every fader and | ||
| 498 | +/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone | ||
| 499 | +/// hears as a move -- and it lands on round numbers, so a track set by ear | ||
| 500 | +/// still reads as a number a person would say. | ||
| 501 | +const MIX_DB_STEP: f32 = 1.; | ||
| 502 | + | ||
| 503 | +/// The mix card's rows below the faders: the limiter's ceiling and its switch. | ||
| 504 | +/// One fader per audio track comes first, however many there are. | ||
| 505 | +const MIX_MASTER_ROWS: usize = 2; | ||
| 506 | + | ||
| 416 | /// The speed-up rate is bounded *below* by real time: a "speed-up" that slows | 507 | /// The speed-up rate is bounded *below* by real time: a "speed-up" that slows |
| 417 | /// the silence down would make the timeline longer, which is the one thing | 508 | /// the silence down would make the timeline longer, which is the one thing |
| 418 | /// neither button may do. The top is [`Speed::MAX`]. | 509 | /// neither button may do. The top is [`Speed::MAX`]. |
| @@ -451,6 +542,36 @@ const EQ_TICKS: [(f32, &str); 5] = [ | |||
| 451 | (20000., "20k"), | 542 | (20000., "20k"), |
| 452 | ]; | 543 | ]; |
| 453 | 544 | ||
| 545 | +/// The gains the graph rules a line across, besides the 0 dB one it already | ||
| 546 | +/// had: half way to each limit, so a boost can be read as "about six" without | ||
| 547 | +/// counting pixels. The limits themselves are the box's own edges and are | ||
| 548 | +/// named at the corners instead. | ||
| 549 | +const EQ_DB_GRID: [f32; 2] = [6., -6.]; | ||
| 550 | + | ||
| 551 | +/// The grid's ink: above the card's background and below everything drawn on | ||
| 552 | +/// it, so the lines are a ruling rather than a thing to look at. | ||
| 553 | +const EQ_GRID: u32 = 0x3a3a3a; | ||
| 554 | + | ||
| 555 | +/// How many played samples one spectrum frame is transformed from. A power of | ||
| 556 | +/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz | ||
| 557 | +/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough | ||
| 558 | +/// (21 ms) that the analyser moves with the music. | ||
| 559 | +const EQ_FFT: usize = 1024; | ||
| 560 | + | ||
| 561 | +/// The level range the analyser is drawn across, floor to ceiling in dBFS: the | ||
| 562 | +/// bottom of the box is silence and the top is a bin at -12 dBFS, which is | ||
| 563 | +/// about where a mixed track's loudest band sits. A look, not a measurement -- | ||
| 564 | +/// the numbers on the axis are the curve's dB, never the analyser's. | ||
| 565 | +const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.); | ||
| 566 | + | ||
| 567 | +/// The analyser's fill, behind the curve: a dim blue-grey with enough alpha to | ||
| 568 | +/// read as a haze the accent line sits on top of. | ||
| 569 | +const EQ_SPECTRUM_INK: u32 = 0x7f95ad66; | ||
| 570 | + | ||
| 571 | +/// The area under the response curve, same accent as the line at a tenth of | ||
| 572 | +/// its weight: it is what makes a boost read as a hill rather than as a wire. | ||
| 573 | +const EQ_FILL_INK: u32 = 0x4a9eff26; | ||
| 574 | + | ||
| 454 | /// The colour card's four controls, in the order it lists them: what each is | 575 | /// The colour card's four controls, in the order it lists them: what each is |
| 455 | /// called and the range it moves in. The order is `ColorParams`' own, which is | 576 | /// called and the range it moves in. The order is `ColorParams`' own, which is |
| 456 | /// what [`color_band`] indexes. | 577 | /// what [`color_band`] indexes. |
| @@ -515,6 +636,10 @@ struct Player { | |||
| 515 | /// The ruler's own box, recorded at prepaint: a mouse listener is handed | 636 | /// The ruler's own box, recorded at prepaint: a mouse listener is handed |
| 516 | /// the window position and nothing else. | 637 | /// the window position and nothing else. |
| 517 | ruler: Rc<Cell<Bounds<Pixels>>>, | 638 | ruler: Rc<Cell<Bounds<Pixels>>>, |
| 639 | + /// How much of the timeline the ruler and the lanes are showing. Held here | ||
| 640 | + /// and nowhere else: every frame-to-pixel answer in the panel comes out of | ||
| 641 | + /// it, so the boxes, the playhead and the pointer cannot disagree. | ||
| 642 | + view: View, | ||
| 518 | /// Which clip the edit keys act on: the lane it is in and its index there. | 643 | /// Which clip the edit keys act on: the lane it is in and its index there. |
| 519 | /// The *clicked* half, not the group -- a group is what gets marked on | 644 | /// The *clicked* half, not the group -- a group is what gets marked on |
| 520 | /// screen, but Lift has to know which half it was aimed at. Indices move | 645 | /// screen, but Lift has to know which half it was aimed at. Indices move |
| @@ -549,6 +674,19 @@ struct Player { | |||
| 549 | /// `None` is a file with no picture to report (every source that is not an | 674 | /// `None` is a file with no picture to report (every source that is not an |
| 550 | /// image, and one whose header would not read). | 675 | /// image, and one whose header would not read). |
| 551 | sizes: HashMap<PathBuf, Option<(u32, u32)>>, | 676 | sizes: HashMap<PathBuf, Option<(u32, u32)>>, |
| 677 | + /// Which decoder each source will run on, probed once at import and kept: | ||
| 678 | + /// the codec (`None` for a still) and the seat the engine picked for it. | ||
| 679 | + /// What a library row says *before* anything plays; the running answer is | ||
| 680 | + /// the session's own (`PlaybackSession::decode_backend`), which follows a | ||
| 681 | + /// fallback this cannot. Filled like `sizes`: presence means "asked", and | ||
| 682 | + /// `None` is a source with no decoder to name -- a song, or one the probe | ||
| 683 | + /// refused -- which must stay in the map or every repaint would ask again. | ||
| 684 | + decoders: HashMap<PathBuf, Option<(Option<Codec>, Backend)>>, | ||
| 685 | + /// Which encoder an export of the picked settings would open, and what it | ||
| 686 | + /// was asked about: the probe opens a real VA-API encoder (~100 ms), so it | ||
| 687 | + /// runs off the render thread and only while the export card is up. The | ||
| 688 | + /// inner `None` is "asked, not answered yet". | ||
| 689 | + export_seat: Option<(ExportSettings, (u32, u32), Option<&'static str>)>, | ||
| 552 | /// The copied clip. Frame ranges only, so it survives the clip it was taken | 690 | /// The copied clip. Frame ranges only, so it survives the clip it was taken |
| 553 | /// from being deleted -- and it outlives the selection. | 691 | /// from being deleted -- and it outlives the selection. |
| 554 | clipboard: Option<Clip>, | 692 | clipboard: Option<Clip>, |
| @@ -559,6 +697,13 @@ struct Player { | |||
| 559 | /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See | 697 | /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See |
| 560 | /// [`Trim`]. | 698 | /// [`Trim`]. |
| 561 | trim: Option<Trim>, | 699 | trim: Option<Trim>, |
| 700 | + /// How far into the clip the last press on a box landed, in timeline | ||
| 701 | + /// frames: what a drag lets go of is the *point that was grabbed*, so the | ||
| 702 | + /// head lands that much in front of the pointer and the clip does not jump | ||
| 703 | + /// under the hand. Recorded at the press because gpui hands the drop only | ||
| 704 | + /// the value being dragged, and stale between drags, which costs nothing -- | ||
| 705 | + /// no drag starts without a press on the box it moves. | ||
| 706 | + grab: u32, | ||
| 562 | last_scrub: Instant, | 707 | last_scrub: Instant, |
| 563 | last_target: u32, | 708 | last_target: u32, |
| 564 | /// The running export. While it owns the UI the editor is read-only. | 709 | /// The running export. While it owns the UI the editor is read-only. |
| @@ -584,6 +729,11 @@ struct Player { | |||
| 584 | /// also why it is not written to the project file and cannot reach an | 729 | /// also why it is not written to the project file and cannot reach an |
| 585 | /// export. [`Player::apply_volume`] is what pushes it at a session. | 730 | /// export. [`Player::apply_volume`] is what pushes it at a session. |
| 586 | volume: Volume, | 731 | volume: Volume, |
| 732 | + /// Where the volume slider was last painted, and whether a hand is on it -- | ||
| 733 | + /// the speed bar's pair, for the speed bar's reason: the pointer moves | ||
| 734 | + /// arrive at the root, so the bar's own geometry has to be readable there. | ||
| 735 | + volume_bar: Rc<Cell<Bounds<Pixels>>>, | ||
| 736 | + volume_dragging: bool, | ||
| 587 | /// The keybindings overlay is up. While it is, it owns the keyboard and the | 737 | /// The keybindings overlay is up. While it is, it owns the keyboard and the |
| 588 | /// pointer: a stroke or a click meant for a row must not also cut the | 738 | /// pointer: a stroke or a click meant for a row must not also cut the |
| 589 | /// timeline. | 739 | /// timeline. |
| @@ -593,6 +743,15 @@ struct Player { | |||
| 593 | /// time -- opening either closes the other, since both are the whole window | 743 | /// time -- opening either closes the other, since both are the whole window |
| 594 | /// and two stacked scrims say nothing about which one is listening. | 744 | /// and two stacked scrims say nothing about which one is listening. |
| 595 | export_open: bool, | 745 | export_open: bool, |
| 746 | + /// How the card lays its rows out, and where the formats this program | ||
| 747 | + /// cannot write are said. Two shapes of the same card, kept behind `g` and | ||
| 748 | + /// `r` so the choice between them can be made by looking at both rather | ||
| 749 | + /// than by argument: sections with headers against one flat list, and a | ||
| 750 | + /// collapsed "cannot write" footer against a dimmed row each. The defaults | ||
| 751 | + /// are grouped and collapsed -- the five dead rows used to eat the fold. | ||
| 752 | + /// Not persisted: this is a look, not a setting. | ||
| 753 | + export_grouped: bool, | ||
| 754 | + export_refusals_inline: bool, | ||
| 596 | /// Which quality row the card has picked, and the megabits typed against | 755 | /// Which quality row the card has picked, and the megabits typed against |
| 597 | /// the custom one. Kept across closes, so a second export offers what the | 756 | /// the custom one. Kept across closes, so a second export offers what the |
| 598 | /// first one chose. | 757 | /// first one chose. |
| @@ -622,6 +781,11 @@ struct Player { | |||
| 622 | /// window position only, so this is what a press and a drag are read | 781 | /// window position only, so this is what a press and a drag are read |
| 623 | /// against ([`frac_along`], [`frac_down`]). | 782 | /// against ([`frac_along`], [`frac_down`]). |
| 624 | eq_graph: Rc<Cell<Bounds<Pixels>>>, | 783 | eq_graph: Rc<Cell<Bounds<Pixels>>>, |
| 784 | + /// Whether the analyser is drawn behind the curve. On by default -- what | ||
| 785 | + /// the curve is being *shaped against* is the point of drawing it -- and | ||
| 786 | + /// off with one press for anyone who would rather read the curve alone. | ||
| 787 | + /// Card state, not the project's: it changes nothing that plays. | ||
| 788 | + eq_spectrum: bool, | ||
| 625 | /// The colour card is up on this clip -- the lane it is on and its index | 789 | /// The colour card is up on this clip -- the lane it is on and its index |
| 626 | /// there. `None` when it is closed, which is the only place that state | 790 | /// there. `None` when it is closed, which is the only place that state |
| 627 | /// lives: the grade itself is the project's. | 791 | /// lives: the grade itself is the project's. |
| @@ -637,6 +801,14 @@ struct Player { | |||
| 637 | /// The bar is being dragged. On the root like the colour card's, for the | 801 | /// The bar is being dragged. On the root like the colour card's, for the |
| 638 | /// same reason: the pointer leaves a 4 px bar on the first move. | 802 | /// same reason: the pointer leaves a 4 px bar on the first move. |
| 639 | speed_dragging: bool, | 803 | speed_dragging: bool, |
| 804 | + /// The mix card is up: every audio track's own volume and the master | ||
| 805 | + /// limiter, which are project settings and not any clip's -- so unlike the | ||
| 806 | + /// four clip cards there is no handle to hold, only whether it is open. | ||
| 807 | + mix_open: bool, | ||
| 808 | + /// Which of its rows the arrow keys move -- a fader, the limiter's ceiling | ||
| 809 | + /// or its switch. The card's own focus, since nothing in it takes gpui's | ||
| 810 | + /// (ledger:182). | ||
| 811 | + mix_field: usize, | ||
| 640 | /// The silence card is up on this clip -- the lane it is on and its index | 812 | /// The silence card is up on this clip -- the lane it is on and its index |
| 641 | /// there, exactly as the speed card's handle is. | 813 | /// there, exactly as the speed card's handle is. |
| 642 | silence_open: Option<(Lane, usize)>, | 814 | silence_open: Option<(Lane, usize)>, |
| @@ -652,6 +824,14 @@ struct Player { | |||
| 652 | /// Which of the card's [`SILENCE_ROWS`] the arrow keys move. The card's own | 824 | /// Which of the card's [`SILENCE_ROWS`] the arrow keys move. The card's own |
| 653 | /// focus, since nothing in it takes gpui's (ledger:182). | 825 | /// focus, since nothing in it takes gpui's (ledger:182). |
| 654 | silence_field: usize, | 826 | silence_field: usize, |
| 827 | + /// Whether the threshold is *labelled* dBFS or dB. Display only, and the | ||
| 828 | + /// number is the same either way: the setting is a level below full scale, | ||
| 829 | + /// so 0 is the loudest sample a file can hold and -40 is forty decibels | ||
| 830 | + /// under it -- "dBFS" names that reference out loud, "dB" leaves it unsaid. | ||
| 831 | + /// No conversion is hiding behind the row (there is no reference here worth | ||
| 832 | + /// inventing, and a made-up SPL would be a lie about what was measured); | ||
| 833 | + /// what it changes is which of the two spellings a person reads. | ||
| 834 | + silence_dbfs: bool, | ||
| 655 | /// What the last scan found, in timeline frames: what the lane draws marks | 835 | /// What the last scan found, in timeline frames: what the lane draws marks |
| 656 | /// over and what an apply acts on -- *exactly* the previewed set, never a | 836 | /// over and what an apply acts on -- *exactly* the previewed set, never a |
| 657 | /// second scan at the moment of the press. | 837 | /// second scan at the moment of the press. |
| @@ -819,15 +999,27 @@ impl Player { | |||
| 819 | ActionId::Color => self.open_color(cx), | 999 | ActionId::Color => self.open_color(cx), |
| 820 | ActionId::Fit => self.cycle_fit(cx), | 1000 | ActionId::Fit => self.cycle_fit(cx), |
| 821 | ActionId::Resolution => self.cycle_resolution(cx), | 1001 | ActionId::Resolution => self.cycle_resolution(cx), |
| 1002 | + // The playhead is what a key zoom is aimed at: it is the one place | ||
| 1003 | + // on the timeline the user is certainly looking at, and keeping it | ||
| 1004 | + // still is what every editor does. | ||
| 1005 | + ActionId::ZoomIn => self.zoom(ZOOM_STEP, None, cx), | ||
| 1006 | + ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx), | ||
| 1007 | + ActionId::ZoomFit => self.zoom_fit(cx), | ||
| 822 | ActionId::Undo => self.undo(cx), | 1008 | ActionId::Undo => self.undo(cx), |
| 823 | ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx), | 1009 | ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx), |
| 824 | ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx), | 1010 | ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx), |
| 1011 | + // The last track of that kind: the one the add key put there, so the | ||
| 1012 | + // two strokes undo each other press for press. Any other track goes | ||
| 1013 | + // through the × in its own header. | ||
| 1014 | + ActionId::RemoveVideoLane => self.remove_last_lane(LaneKind::Video, cx), | ||
| 1015 | + ActionId::RemoveAudioLane => self.remove_last_lane(LaneKind::Audio, cx), | ||
| 825 | ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx), | 1016 | ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx), |
| 826 | ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx), | 1017 | ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx), |
| 827 | ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx), | 1018 | ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx), |
| 828 | ActionId::Equalizer => self.open_eq(cx), | 1019 | ActionId::Equalizer => self.open_eq(cx), |
| 829 | ActionId::Speed => self.open_speed(cx), | 1020 | ActionId::Speed => self.open_speed(cx), |
| 830 | ActionId::Silence => self.open_silence(cx), | 1021 | ActionId::Silence => self.open_silence(cx), |
| 1022 | + ActionId::Mix => self.open_mix(None, cx), | ||
| 831 | // Nothing to cancel while nothing is exporting; the export guard in | 1023 | // Nothing to cancel while nothing is exporting; the export guard in |
| 832 | // the key handler is what answers this one while there is. | 1024 | // the key handler is what answers this one while there is. |
| 833 | ActionId::CancelExport => {} | 1025 | ActionId::CancelExport => {} |
| @@ -937,6 +1129,26 @@ impl Player { | |||
| 937 | cx.notify(); | 1129 | cx.notify(); |
| 938 | } | 1130 | } |
| 939 | 1131 | ||
| 1132 | + /// Magnifies the timeline about a point that stays put: `anchor` is where | ||
| 1133 | + /// along the bed to hold still (a ctrl+wheel holds the pointer), and with | ||
| 1134 | + /// none it is the playhead -- so the frame being worked on is still the | ||
| 1135 | + /// frame on screen after the zoom. Clamped at both ends by [`View`]: out | ||
| 1136 | + /// stops at the whole timeline, in at a handful of frames. | ||
| 1137 | + fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) { | ||
| 1138 | + let duration = self.drawn_duration(); | ||
| 1139 | + let at = self.playhead(duration); | ||
| 1140 | + let anchor = anchor.unwrap_or_else(|| self.view.frac_at(at, duration).clamp(0., 1.)); | ||
| 1141 | + self.view = self.view.zoomed(factor, anchor, duration, self.fps); | ||
| 1142 | + cx.notify(); | ||
| 1143 | + } | ||
| 1144 | + | ||
| 1145 | + /// All the way back out: the whole timeline across the bed, which is what | ||
| 1146 | + /// the panel shows before anyone has zoomed at all. | ||
| 1147 | + fn zoom_fit(&mut self, cx: &mut Context<Self>) { | ||
| 1148 | + self.view = View::default(); | ||
| 1149 | + cx.notify(); | ||
| 1150 | + } | ||
| 1151 | + | ||
| 940 | /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from | 1152 | /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from |
| 941 | /// the media's own -- the one size that must stay reachable, since a project | 1153 | /// the media's own -- the one size that must stay reachable, since a project |
| 942 | /// moved off it has no other way back (the resolution is not an undo step). | 1154 | /// moved off it has no other way back (the resolution is not an undo step). |
| @@ -1216,6 +1428,82 @@ impl Player { | |||
| 1216 | cx.notify(); | 1428 | cx.notify(); |
| 1217 | } | 1429 | } |
| 1218 | 1430 | ||
| 1431 | + /// Opens the mix card. `lane` is the row it lands on -- the track whose | ||
| 1432 | + /// header was clicked -- and `None` starts at the top, which is what the | ||
| 1433 | + /// stroke means. | ||
| 1434 | + /// | ||
| 1435 | + /// Nothing here is a clip's, so nothing is refused for want of a selection: | ||
| 1436 | + /// a timeline with no audio track at all still has a limiter to set, and a | ||
| 1437 | + /// fader on an empty track is the level the next take lands at. | ||
| 1438 | + fn open_mix(&mut self, lane: Option<Lane>, cx: &mut Context<Self>) { | ||
| 1439 | + if self.exporting().is_some() { | ||
| 1440 | + return; | ||
| 1441 | + } | ||
| 1442 | + self.mix_open = true; | ||
| 1443 | + self.mix_field = lane | ||
| 1444 | + .and_then(|lane| self.mix_lanes().iter().position(|&l| l == lane)) | ||
| 1445 | + .unwrap_or(0); | ||
| 1446 | + // One card at a time, the rule the other five follow. | ||
| 1447 | + self.keys_open = false; | ||
| 1448 | + self.export_open = false; | ||
| 1449 | + self.eq_open = None; | ||
| 1450 | + self.color_open = None; | ||
| 1451 | + self.speed_open = None; | ||
| 1452 | + self.close_silence(); | ||
| 1453 | + self.context_menu = None; | ||
| 1454 | + cx.notify(); | ||
| 1455 | + } | ||
| 1456 | + | ||
| 1457 | + /// The audio tracks the card shows a fader for, top to bottom: *every* one | ||
| 1458 | + /// of them, empty ones included -- what the timeline lays out, not what the | ||
| 1459 | + /// mixer happens to open (`Project::audio_lanes` leaves an empty track out, | ||
| 1460 | + /// and a fader that disappeared when a track was cleared would be a setting | ||
| 1461 | + /// nobody could reach). | ||
| 1462 | + fn mix_lanes(&self) -> Vec<Lane> { | ||
| 1463 | + self.session.as_ref().map_or_else(Vec::new, |session| { | ||
| 1464 | + session | ||
| 1465 | + .lanes() | ||
| 1466 | + .into_iter() | ||
| 1467 | + .filter(|l| l.kind == LaneKind::Audio) | ||
| 1468 | + .collect() | ||
| 1469 | + }) | ||
| 1470 | + } | ||
| 1471 | + | ||
| 1472 | + /// Moves the row the card has picked: a fader by [`MIX_DB_STEP`], the | ||
| 1473 | + /// ceiling by the same, and the switch either way (a ring of two, like the | ||
| 1474 | + /// silence card's unit row). | ||
| 1475 | + /// | ||
| 1476 | + /// Every one of them goes through the session, so it reseeks: what the ear | ||
| 1477 | + /// hears while the arrow is held is the mix that is being set. | ||
| 1478 | + fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) { | ||
| 1479 | + let lanes = self.mix_lanes(); | ||
| 1480 | + let Some(session) = self.session.as_mut() else { | ||
| 1481 | + return; | ||
| 1482 | + }; | ||
| 1483 | + match lanes.get(self.mix_field) { | ||
| 1484 | + Some(&lane) => { | ||
| 1485 | + let at = session.lane_gain_db(lane) + steps as f32 * MIX_DB_STEP; | ||
| 1486 | + session.set_lane_gain_db(lane, at); | ||
| 1487 | + } | ||
| 1488 | + None => { | ||
| 1489 | + let limiter = session.limiter(); | ||
| 1490 | + let at = match self.mix_field - lanes.len() { | ||
| 1491 | + 0 => Limiter { | ||
| 1492 | + on: limiter.on, | ||
| 1493 | + ..limiter | ||
| 1494 | + } | ||
| 1495 | + .with_ceiling(limiter.ceiling_db + steps as f32 * MIX_DB_STEP), | ||
| 1496 | + _ => Limiter { | ||
| 1497 | + on: !limiter.on, | ||
| 1498 | + ..limiter | ||
| 1499 | + }, | ||
| 1500 | + }; | ||
| 1501 | + session.set_limiter(at); | ||
| 1502 | + } | ||
| 1503 | + } | ||
| 1504 | + cx.notify(); | ||
| 1505 | + } | ||
| 1506 | + | ||
| 1219 | /// Closes it and drops the preview with it: marks left on the lane after | 1507 | /// Closes it and drops the preview with it: marks left on the lane after |
| 1220 | /// the card is gone would name frames the next edit has already moved. | 1508 | /// the card is gone would name frames the next edit has already moved. |
| 1221 | fn close_silence(&mut self) { | 1509 | fn close_silence(&mut self) { |
| @@ -1314,9 +1602,12 @@ impl Player { | |||
| 1314 | + steps as f32 * SILENCE_DB_STEP) | 1602 | + steps as f32 * SILENCE_DB_STEP) |
| 1315 | .clamp(SILENCE_DB_RANGE.0, SILENCE_DB_RANGE.1) | 1603 | .clamp(SILENCE_DB_RANGE.0, SILENCE_DB_RANGE.1) |
| 1316 | } | 1604 | } |
| 1317 | - 2 => self.silence.min_silence = secs(self.silence.min_silence), | 1605 | + // Two spellings of the same level, so either arrow flips it -- a |
| 1318 | - 3 => self.silence.padding = secs(self.silence.padding), | 1606 | + // ring of two, like the scope row's. |
| 1319 | - 4 => self.silence.min_keep = secs(self.silence.min_keep), | 1607 | + 2 => self.silence_dbfs = !self.silence_dbfs, |
| 1608 | + 3 => self.silence.min_silence = secs(self.silence.min_silence), | ||
| 1609 | + 4 => self.silence.padding = secs(self.silence.padding), | ||
| 1610 | + 5 => self.silence.min_keep = secs(self.silence.min_keep), | ||
| 1320 | _ => { | 1611 | _ => { |
| 1321 | self.silence_factor = | 1612 | self.silence_factor = |
| 1322 | silence_rate(i32::from(self.silence_factor.permille()) + steps * SPEED_STEP) | 1613 | silence_rate(i32::from(self.silence_factor.permille()) + steps * SPEED_STEP) |
| @@ -1408,6 +1699,11 @@ impl Player { | |||
| 1408 | match session.cut_regions(®ions, &lanes) { | 1699 | match session.cut_regions(®ions, &lanes) { |
| 1409 | Ok(()) => { | 1700 | Ok(()) => { |
| 1410 | self.close_silence(); | 1701 | self.close_silence(); |
| 1702 | + // Every hole closed moves the clips after it up a place, so the | ||
| 1703 | + // selection now names a different clip than the one that is | ||
| 1704 | + // highlighted -- dropped here as after every other edit that | ||
| 1705 | + // moves indexes (a delete, a paste, an undo). | ||
| 1706 | + self.selected = None; | ||
| 1411 | self.reset_after_reseek(); | 1707 | self.reset_after_reseek(); |
| 1412 | self.notice = Some( | 1708 | self.notice = Some( |
| 1413 | format!( | 1709 | format!( |
| @@ -1442,6 +1738,10 @@ impl Player { | |||
| 1442 | match session.speed_regions(®ions, rate, &lanes) { | 1738 | match session.speed_regions(®ions, rate, &lanes) { |
| 1443 | Ok(()) => { | 1739 | Ok(()) => { |
| 1444 | self.close_silence(); | 1740 | self.close_silence(); |
| 1741 | + // Splitting each silence out and closing the room it no longer | ||
| 1742 | + // needs moves indexes exactly as the cut does: the selection | ||
| 1743 | + // goes with them. | ||
| 1744 | + self.selected = None; | ||
| 1445 | self.reset_after_reseek(); | 1745 | self.reset_after_reseek(); |
| 1446 | self.notice = Some( | 1746 | self.notice = Some( |
| 1447 | format!( | 1747 | format!( |
| @@ -1466,7 +1766,32 @@ impl Player { | |||
| 1466 | || self.color_open.is_some() | 1766 | || self.color_open.is_some() |
| 1467 | || self.speed_open.is_some() | 1767 | || self.speed_open.is_some() |
| 1468 | || self.silence_open.is_some() | 1768 | || self.silence_open.is_some() |
| 1769 | + || self.mix_open | ||
| 1770 | + || self.exporting().is_some() | ||
| 1771 | + } | ||
| 1772 | + | ||
| 1773 | + /// Which of [`Repeat`]'s three the window is in, for the hold gate at the | ||
| 1774 | + /// top of the key handler. Not [`Player::modal`]: that asks whether an | ||
| 1775 | + /// overlay is up at all, and here the cards with sliders in them are | ||
| 1776 | + /// exactly the ones that answer differently from the keys menu and the | ||
| 1777 | + /// export card. | ||
| 1778 | + fn repeat_scope(&self) -> Repeat { | ||
| 1779 | + if self.rebinding.is_some() | ||
| 1780 | + || self.keys_open | ||
| 1781 | + || self.export_open | ||
| 1469 | || self.exporting().is_some() | 1782 | || self.exporting().is_some() |
| 1783 | + { | ||
| 1784 | + Repeat::Nothing | ||
| 1785 | + } else if self.eq_open.is_some() | ||
| 1786 | + || self.color_open.is_some() | ||
| 1787 | + || self.speed_open.is_some() | ||
| 1788 | + || self.silence_open.is_some() | ||
| 1789 | + || self.mix_open | ||
| 1790 | + { | ||
| 1791 | + Repeat::Card | ||
| 1792 | + } else { | ||
| 1793 | + Repeat::Keymap | ||
| 1794 | + } | ||
| 1470 | } | 1795 | } |
| 1471 | 1796 | ||
| 1472 | /// Opens the equalizer on the selected clip. Audio only, and it says so | 1797 | /// Opens the equalizer on the selected clip. Audio only, and it says so |
| @@ -1825,6 +2150,28 @@ impl Player { | |||
| 1825 | }) | 2150 | }) |
| 1826 | .detach(); | 2151 | .detach(); |
| 1827 | } | 2152 | } |
| 2153 | + // Which decoder each file will run on, for the row that says so before | ||
| 2154 | + // a frame of it plays. Off the render thread like the streams above: a | ||
| 2155 | + // stream the plugin takes costs one VA-API init (~90 ms) to answer. | ||
| 2156 | + for path in unseen_paths(session.sources(), &self.decoders) { | ||
| 2157 | + self.decoders.insert(path.clone(), None); | ||
| 2158 | + let probed = cx.background_executor().spawn({ | ||
| 2159 | + let path = path.clone(); | ||
| 2160 | + // A song and a source no decoder here takes are both `None`: | ||
| 2161 | + // the row says nothing about them rather than guessing, and | ||
| 2162 | + // import refused the second at the door anyway. | ||
| 2163 | + async move { engine::decode::probe(&path).ok() } | ||
| 2164 | + }); | ||
| 2165 | + cx.spawn(async move |this, cx| { | ||
| 2166 | + let probed = probed.await; | ||
| 2167 | + this.update(cx, |this, cx| { | ||
| 2168 | + this.decoders.insert(path, probed); | ||
| 2169 | + cx.notify(); | ||
| 2170 | + }) | ||
| 2171 | + .ok(); | ||
| 2172 | + }) | ||
| 2173 | + .detach(); | ||
| 2174 | + } | ||
| 1828 | for key in unseen_sources(session.sources(), &self.waves) { | 2175 | for key in unseen_sources(session.sources(), &self.waves) { |
| 1829 | self.waves.insert(key.clone(), Wave::Loading); | 2176 | self.waves.insert(key.clone(), Wave::Loading); |
| 1830 | let decoded = cx.background_executor().spawn({ | 2177 | let decoded = cx.background_executor().spawn({ |
| @@ -1857,6 +2204,59 @@ impl Player { | |||
| 1857 | } | 2204 | } |
| 1858 | } | 2205 | } |
| 1859 | 2206 | ||
| 2207 | + /// Probes the encoder an export would open, once per (settings, | ||
| 2208 | + /// resolution) and only while the export card is up -- it opens the very | ||
| 2209 | + /// VA-API encoder the export would, which is what makes the card's line a | ||
| 2210 | + /// measurement instead of a promise, and also what makes it too slow for | ||
| 2211 | + /// the render thread. Written before the spawn, like the probes above, so | ||
| 2212 | + /// the repaints during it start no second one. | ||
| 2213 | + fn cache_export_seat(&mut self, cx: &mut Context<Self>) { | ||
| 2214 | + let Some(session) = &self.session else { | ||
| 2215 | + return; | ||
| 2216 | + }; | ||
| 2217 | + let settings = export_settings(self.quality, self.custom_mbps, self.format); | ||
| 2218 | + if !self.export_open { | ||
| 2219 | + return; | ||
| 2220 | + } | ||
| 2221 | + // A format with no picture has no seat to probe -- and the *last* | ||
| 2222 | + // format's is not its answer: cleared rather than left standing, or | ||
| 2223 | + // picking MP3 after AV1 would read "SW encode (rav1e) · MP3 · SW | ||
| 2224 | + // (rusty_mp3)", which names an encoder that will not run. | ||
| 2225 | + if !settings.format.has_video() { | ||
| 2226 | + self.export_seat = None; | ||
| 2227 | + return; | ||
| 2228 | + } | ||
| 2229 | + let meta = *session.meta(); | ||
| 2230 | + let key = (settings, (meta.width, meta.height)); | ||
| 2231 | + if self | ||
| 2232 | + .export_seat | ||
| 2233 | + .is_some_and(|(asked, size, _)| (asked, size) == key) | ||
| 2234 | + { | ||
| 2235 | + return; | ||
| 2236 | + } | ||
| 2237 | + self.export_seat = Some((key.0, key.1, None)); | ||
| 2238 | + let probed = cx | ||
| 2239 | + .background_executor() | ||
| 2240 | + .spawn(async move { engine::export::planned_video(&meta, &settings) }); | ||
| 2241 | + cx.spawn(async move |this, cx| { | ||
| 2242 | + let probed = probed.await; | ||
| 2243 | + this.update(cx, |this, cx| { | ||
| 2244 | + // Only if the card is still asking the same question: a format | ||
| 2245 | + // changed while the plugin opened has a probe of its own. | ||
| 2246 | + if let Some(seat) = this | ||
| 2247 | + .export_seat | ||
| 2248 | + .as_mut() | ||
| 2249 | + .filter(|(asked, size, _)| (*asked, *size) == key) | ||
| 2250 | + { | ||
| 2251 | + seat.2 = probed; | ||
| 2252 | + } | ||
| 2253 | + cx.notify(); | ||
| 2254 | + }) | ||
| 2255 | + .ok(); | ||
| 2256 | + }) | ||
| 2257 | + .detach(); | ||
| 2258 | + } | ||
| 2259 | + | ||
| 1860 | /// The group id of the clicked clip, which is what marks the other half. | 2260 | /// The group id of the clicked clip, which is what marks the other half. |
| 1861 | fn selected_link(&self) -> Option<u32> { | 2261 | fn selected_link(&self) -> Option<u32> { |
| 1862 | let (lane, idx) = self.selected?; | 2262 | let (lane, idx) = self.selected?; |
| @@ -1878,19 +2278,29 @@ impl Player { | |||
| 1878 | cx.notify(); | 2278 | cx.notify(); |
| 1879 | } | 2279 | } |
| 1880 | 2280 | ||
| 1881 | - /// A clip dragged off one lane and let go over another: it changes track and | 2281 | + /// A clip let go at window `x` over lane `to`: it lands with its head where |
| 1882 | - /// keeps the frames it covers, as one undo step. Dropped back on its own | 2282 | + /// the hand is carrying it ([`Player::drop_frame`]), on the track it was |
| 1883 | - /// lane it is not an edit at all, so nothing is said about it. The engine | 2283 | + /// dropped on, taking its whole take with it -- one undo step for the |
| 1884 | - /// reseeks, so all this owes is the flag reset -- and the selection, whose | 2284 | + /// gesture. Dropped back where it was picked up it is not an edit at all, so |
| 1885 | - /// index was that lane's own and now names a different clip there. | 2285 | + /// nothing is said about it. The engine reseeks, so all this owes is the |
| 1886 | - fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, cx: &mut Context<Self>) { | 2286 | + /// flag reset -- and the selection, whose index was that lane's own and now |
| 1887 | - if self.exporting().is_some() || from == to { | 2287 | + /// names a different clip there. |
| 2288 | + fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, x: Pixels, cx: &mut Context<Self>) { | ||
| 2289 | + if self.exporting().is_some() { | ||
| 1888 | return; | 2290 | return; |
| 1889 | } | 2291 | } |
| 2292 | + let (Some(start), Some(was)) = ( | ||
| 2293 | + self.drop_frame(from, idx, to, x), | ||
| 2294 | + self.session | ||
| 2295 | + .as_ref() | ||
| 2296 | + .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)), | ||
| 2297 | + ) else { | ||
| 2298 | + return; | ||
| 2299 | + }; | ||
| 1890 | let moved = self | 2300 | let moved = self |
| 1891 | .session | 2301 | .session |
| 1892 | .as_mut() | 2302 | .as_mut() |
| 1893 | - .is_some_and(|session| session.move_clip_to_lane(from, idx, to)); | 2303 | + .is_some_and(|session| session.move_clip_to(from, idx, to, start)); |
| 1894 | let (kind, lanes) = match from.kind { | 2304 | let (kind, lanes) = match from.kind { |
| 1895 | LaneKind::Video => ("picture", "video"), | 2305 | LaneKind::Video => ("picture", "video"), |
| 1896 | LaneKind::Audio => ("sound", "audio"), | 2306 | LaneKind::Audio => ("sound", "audio"), |
| @@ -1900,9 +2310,10 @@ impl Player { | |||
| 1900 | self.selected = None; | 2310 | self.selected = None; |
| 1901 | self.reset_after_reseek(); | 2311 | self.reset_after_reseek(); |
| 1902 | } | 2312 | } |
| 1903 | - // The two ways a drag is refused, told apart by the one thing the | 2313 | + // The three ways a drag is refused, told apart by what the |
| 1904 | - // front-end already knows: a lane's kind. Everything else that | 2314 | + // front-end already knows: a lane's kind, and where the clip was. |
| 1905 | - // could refuse (a clip that is not there) cannot be dragged. | 2315 | + // Everything else that could refuse (a clip that is not there) |
| 2316 | + // cannot be dragged. | ||
| 1906 | false if from.kind != to.kind => { | 2317 | false if from.kind != to.kind => { |
| 1907 | self.notice = Some( | 2318 | self.notice = Some( |
| 1908 | format!( | 2319 | format!( |
| @@ -1912,6 +2323,9 @@ impl Player { | |||
| 1912 | .into(), | 2323 | .into(), |
| 1913 | ) | 2324 | ) |
| 1914 | } | 2325 | } |
| 2326 | + // Picked up and put back down where it was: a click, and a click | ||
| 2327 | + // says nothing. | ||
| 2328 | + false if from == to && start == was => {} | ||
| 1915 | false => { | 2329 | false => { |
| 1916 | self.notice = Some( | 2330 | self.notice = Some( |
| 1917 | format!( | 2331 | format!( |
| @@ -1925,6 +2339,55 @@ impl Player { | |||
| 1925 | cx.notify(); | 2339 | cx.notify(); |
| 1926 | } | 2340 | } |
| 1927 | 2341 | ||
| 2342 | + /// Where a clip let go at window `x` over lane `to` wants its head: the | ||
| 2343 | + /// frame under the pointer, less however far into the box the hand grabbed | ||
| 2344 | + /// it (so the clip does not jump under the pointer), pulled onto a | ||
| 2345 | + /// neighbouring edge when it lands within [`SNAP_PX`] of one. `None` when | ||
| 2346 | + /// there is no such clip to move. The engine has the last word on where it | ||
| 2347 | + /// may actually go -- this is the ask, not the answer. | ||
| 2348 | + /// | ||
| 2349 | + /// ponytail: the bed ends where the timeline does, so a clip cannot be | ||
| 2350 | + /// dragged *past* the last frame -- the pointer has no pixel out there to | ||
| 2351 | + /// name and [`View::time_at`] clamps to the duration. Room to the right is | ||
| 2352 | + /// made by pulling a tail out first ([`Player::drawn_duration`] already | ||
| 2353 | + /// lengthens the bed for exactly that gesture). The upgrade is to draw the | ||
| 2354 | + /// bed past the end while a clip drag is in flight, the way a trim already | ||
| 2355 | + /// does: `drawn_duration` would take the dragged clip's length the same way | ||
| 2356 | + /// it takes a trim's reach. | ||
| 2357 | + fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option<u32> { | ||
| 2358 | + let session = self.session.as_ref()?; | ||
| 2359 | + let clip = session.lane_clips(from).get(idx).copied()?; | ||
| 2360 | + let raw = self.frame_under(x).saturating_sub(self.grab); | ||
| 2361 | + // The edges worth landing on: both ends of every clip already on the | ||
| 2362 | + // lane it is being let go over, the playhead, and the head of the | ||
| 2363 | + // timeline. Never the group's own boxes -- a clip does not snap to | ||
| 2364 | + // where it already is. | ||
| 2365 | + let mut marks: Vec<u32> = session | ||
| 2366 | + .lane_clips(to) | ||
| 2367 | + .iter() | ||
| 2368 | + .enumerate() | ||
| 2369 | + .filter(|&(i, c)| { | ||
| 2370 | + (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link) | ||
| 2371 | + }) | ||
| 2372 | + .flat_map(|(_, c)| [c.start, c.end()]) | ||
| 2373 | + .collect(); | ||
| 2374 | + marks.push(frame_at(session.now(), self.fps)); | ||
| 2375 | + marks.push(0); | ||
| 2376 | + Some(snapped(raw, clip.frames(), self.snap_frames(), &marks)) | ||
| 2377 | + } | ||
| 2378 | + | ||
| 2379 | + /// [`SNAP_PX`] in timeline frames at the zoom the bed is drawn at: a snap is | ||
| 2380 | + /// a distance on screen, so zoomed right in it is worth less than a frame | ||
| 2381 | + /// (no snap at all, which is what a hand placing single frames wants) and | ||
| 2382 | + /// zoomed out to the whole timeline it is worth many. | ||
| 2383 | + fn snap_frames(&self) -> u32 { | ||
| 2384 | + let bed = f64::from(f32::from(self.ruler.get().size.width)); | ||
| 2385 | + if bed <= 0. { | ||
| 2386 | + return 0; | ||
| 2387 | + } | ||
| 2388 | + (SNAP_PX / bed * self.view.span(self.drawn_duration()) * self.fps) as u32 | ||
| 2389 | + } | ||
| 2390 | + | ||
| 1928 | /// Opens the clip menu on the box under the pointer, from the right button | 2391 | /// Opens the clip menu on the box under the pointer, from the right button |
| 1929 | /// wherever it was pressed on that box -- its middle or one of its edge | 2392 | /// wherever it was pressed on that box -- its middle or one of its edge |
| 1930 | /// strips, which cover the middle's own listener. Selecting first is part of | 2393 | /// strips, which cover the middle's own listener. Selecting first is part of |
| @@ -1979,18 +2442,30 @@ impl Player { | |||
| 1979 | /// against the same duration the boxes are drawn to, so the edge tracks the | 2442 | /// against the same duration the boxes are drawn to, so the edge tracks the |
| 1980 | /// pointer exactly. | 2443 | /// pointer exactly. |
| 1981 | fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) { | 2444 | fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) { |
| 1982 | - let (duration, fps) = (self.drawn_duration(), self.fps); | 2445 | + let at = self.frame_under(x); |
| 1983 | - let frac = frac_along(x, self.ruler.get()); | ||
| 1984 | let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else { | 2446 | let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else { |
| 1985 | return; | 2447 | return; |
| 1986 | }; | 2448 | }; |
| 1987 | let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else { | 2449 | let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else { |
| 1988 | return; | 2450 | return; |
| 1989 | }; | 2451 | }; |
| 1990 | - trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi); | 2452 | + trim.to = at.clamp(lo, hi); |
| 1991 | cx.notify(); | 2453 | cx.notify(); |
| 1992 | } | 2454 | } |
| 1993 | 2455 | ||
| 2456 | + /// The timeline frame a pointer at window x is on: along the same bed the | ||
| 2457 | + /// ruler is measured on, through the same [`View`] every box is drawn | ||
| 2458 | + /// through, so a zoomed-in panel answers with the frame under the pointer | ||
| 2459 | + /// and not with the one that would have been there unzoomed. The one | ||
| 2460 | + /// question a trim, a grab and a drop all ask. | ||
| 2461 | + fn frame_under(&self, x: Pixels) -> u32 { | ||
| 2462 | + let duration = self.drawn_duration(); | ||
| 2463 | + frame_at( | ||
| 2464 | + self.view.time_at(frac_along(x, self.ruler.get()), duration), | ||
| 2465 | + self.fps, | ||
| 2466 | + ) | ||
| 2467 | + } | ||
| 2468 | + | ||
| 1994 | /// The release: the whole drag reaches the engine as one edit, so it is one | 2469 | /// The release: the whole drag reaches the engine as one edit, so it is one |
| 1995 | /// undo step. The selection survives it -- a trim inserts and removes | 2470 | /// undo step. The selection survives it -- a trim inserts and removes |
| 1996 | /// nothing, so every index a lane had still names the clip it named. | 2471 | /// nothing, so every index a lane had still names the clip it named. |
| @@ -2018,6 +2493,25 @@ impl Player { | |||
| 2018 | return clip; | 2493 | return clip; |
| 2019 | }; | 2494 | }; |
| 2020 | match trim.edge { | 2495 | match trim.edge { |
| 2496 | + // A still grows forward from source frame 0 instead, exactly as | ||
| 2497 | + // `Project::trim` writes it: with the in-point clamped at 0 the box | ||
| 2498 | + // below would slide left rather than stretch, and the release would | ||
| 2499 | + // then commit a wider clip than the drag drew. | ||
| 2500 | + Edge::Start | ||
| 2501 | + if self.session.as_ref().is_some_and(|session| { | ||
| 2502 | + session | ||
| 2503 | + .sources() | ||
| 2504 | + .get(clip.source) | ||
| 2505 | + .is_some_and(|s| engine::is_image(&s.path)) | ||
| 2506 | + }) => | ||
| 2507 | + { | ||
| 2508 | + Clip { | ||
| 2509 | + in_frame: 0, | ||
| 2510 | + out_frame: clip.end().saturating_sub(trim.to).max(1), | ||
| 2511 | + start: trim.to, | ||
| 2512 | + ..clip | ||
| 2513 | + } | ||
| 2514 | + } | ||
| 2021 | // The in-point follows the head, exactly as `Project::trim` moves | 2515 | // The in-point follows the head, exactly as `Project::trim` moves |
| 2022 | // it: what stays on screen plays what it always played. | 2516 | // it: what stays on screen plays what it always played. |
| 2023 | Edge::Start => Clip { | 2517 | Edge::Start => Clip { |
| @@ -2054,18 +2548,35 @@ impl Player { | |||
| 2054 | } | 2548 | } |
| 2055 | } | 2549 | } |
| 2056 | 2550 | ||
| 2551 | + /// Where the playhead is, as the panel draws it. The clock keeps running | ||
| 2552 | + /// after the last frame (wall time takes over at audio EOF) while the | ||
| 2553 | + /// picture is frozen, so what the UI shows is the clamped one, pinned to | ||
| 2554 | + /// the out-point once playback is done. | ||
| 2555 | + fn playhead(&self, duration: f64) -> f64 { | ||
| 2556 | + if self.done { | ||
| 2557 | + duration | ||
| 2558 | + } else { | ||
| 2559 | + self.session | ||
| 2560 | + .as_ref() | ||
| 2561 | + .map_or(0., PlaybackSession::now) | ||
| 2562 | + .clamp(0., duration) | ||
| 2563 | + } | ||
| 2564 | + } | ||
| 2565 | + | ||
| 2057 | /// The one way a library row reaches the timeline: the Add button and a row | 2566 | /// The one way a library row reaches the timeline: the Add button and a row |
| 2058 | /// dragged onto a lane both come here, so there is a single answer to what | 2567 | /// dragged onto a lane both come here, so there is a single answer to what |
| 2059 | - /// "add this source" does. The whole source goes in at the playhead as one | 2568 | + /// "add this source" does. The whole source goes in as one grouped take at |
| 2060 | - /// grouped take -- the same insert a paste makes, so everything after it | 2569 | + /// `at` -- the frame the pointer let it go on, or the playhead for the |
| 2061 | - /// moves along rather than being painted over. Reseeks like every other | 2570 | + /// button, which names no place. It is the same insert a paste makes, so |
| 2062 | - /// edit, and drops the timeline's selection with it: the insert has just | 2571 | + /// everything after it moves along rather than being painted over. Reseeks |
| 2063 | - /// moved the indices it pointed at. | 2572 | + /// like every other edit, and drops the timeline's selection with it: the |
| 2573 | + /// insert has just moved the indices it pointed at. | ||
| 2064 | fn insert_source( | 2574 | fn insert_source( |
| 2065 | &mut self, | 2575 | &mut self, |
| 2066 | path: &Path, | 2576 | path: &Path, |
| 2067 | stream: usize, | 2577 | stream: usize, |
| 2068 | onto: Option<Lane>, | 2578 | onto: Option<Lane>, |
| 2579 | + at: Option<u32>, | ||
| 2069 | cx: &mut Context<Self>, | 2580 | cx: &mut Context<Self>, |
| 2070 | ) { | 2581 | ) { |
| 2071 | if self.exporting().is_some() { | 2582 | if self.exporting().is_some() { |
| @@ -2100,8 +2611,16 @@ impl Player { | |||
| 2100 | // in: a row that has never been on a lane is placeable at its full | 2611 | // in: a row that has never been on a lane is placeable at its full |
| 2101 | // length, which is the whole point of an import that only fills the | 2612 | // length, which is the whole point of an import that only fills the |
| 2102 | // library. | 2613 | // library. |
| 2614 | + let fps = self.fps; | ||
| 2103 | let placed = match &mut self.session { | 2615 | let placed = match &mut self.session { |
| 2104 | - Some(session) => session.place_stream_at(session.now(), path, stream, onto), | 2616 | + // Seconds, because that is what the engine's own door takes: the |
| 2617 | + // frame the pointer named goes back through the same rate every box | ||
| 2618 | + // on the bed is drawn at, so it lands on the frame it was let go on | ||
| 2619 | + // rather than a neighbouring one. | ||
| 2620 | + Some(session) => { | ||
| 2621 | + let at = at.map_or_else(|| session.now(), |frame| f64::from(frame) / fps); | ||
| 2622 | + session.place_stream_at(at, path, stream, onto) | ||
| 2623 | + } | ||
| 2105 | None => Ok(false), | 2624 | None => Ok(false), |
| 2106 | }; | 2625 | }; |
| 2107 | match placed { | 2626 | match placed { |
| @@ -2133,20 +2652,43 @@ impl Player { | |||
| 2133 | .as_mut() | 2652 | .as_mut() |
| 2134 | .map(|session| session.remove_source(path, stream)); | 2653 | .map(|session| session.remove_source(path, stream)); |
| 2135 | let text = match removed { | 2654 | let text = match removed { |
| 2136 | - Some(Ok(())) => { | 2655 | + Some(Ok(idx)) => { |
| 2137 | // The picked row may be the one that just went, and the engine | 2656 | // The picked row may be the one that just went, and the engine |
| 2138 | // reseeks, so this owes the flag reset like every other edit. | 2657 | // reseeks, so this owes the flag reset like every other edit. |
| 2139 | if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) { | 2658 | if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) { |
| 2140 | self.selected_asset = None; | 2659 | self.selected_asset = None; |
| 2141 | } | 2660 | } |
| 2661 | + // A copied clip names its source by *index*, and every index | ||
| 2662 | + // past the one that went has just moved down: without this the | ||
| 2663 | + // next paste puts some other file on the timeline. | ||
| 2664 | + self.clipboard = clipboard_after_remove(self.clipboard, idx); | ||
| 2142 | self.reset_after_reseek(); | 2665 | self.reset_after_reseek(); |
| 2143 | - // The undo stack goes with it (`Project::remove_source`): said | 2666 | + // The last row leaves a session naming no file: nothing to |
| 2144 | - // here, because a `z` that does nothing afterwards would | 2667 | + // play, nothing to save and nothing to show, which is the empty |
| 2145 | - // otherwise read as a bug. | 2668 | + // window the editor launches as. The next import scaffolds a |
| 2146 | - format!( | 2669 | + // fresh timeline from whatever file it is, at that file's own |
| 2147 | - "REMOVED {} — there is nothing left to undo", | 2670 | + // rate -- which is why the session goes rather than lingering |
| 2148 | - file_name(path) | 2671 | + // on with the gone file's parameters. |
| 2149 | - ) | 2672 | + match self |
| 2673 | + .session | ||
| 2674 | + .as_ref() | ||
| 2675 | + .is_some_and(|s| s.sources().is_empty()) | ||
| 2676 | + { | ||
| 2677 | + true => { | ||
| 2678 | + self.close_session(); | ||
| 2679 | + format!( | ||
| 2680 | + "REMOVED {} — the library is empty; import a file to start again", | ||
| 2681 | + file_name(path) | ||
| 2682 | + ) | ||
| 2683 | + } | ||
| 2684 | + // The undo stack goes with it (`Project::remove_source`): | ||
| 2685 | + // said here, because a `z` that does nothing afterwards | ||
| 2686 | + // would otherwise read as a bug. | ||
| 2687 | + false => format!( | ||
| 2688 | + "REMOVED {} — there is nothing left to undo", | ||
| 2689 | + file_name(path) | ||
| 2690 | + ), | ||
| 2691 | + } | ||
| 2150 | } | 2692 | } |
| 2151 | Some(Err(e)) => format!("NOT REMOVED — {e}"), | 2693 | Some(Err(e)) => format!("NOT REMOVED — {e}"), |
| 2152 | None => "NO TIMELINE — open a file first".to_string(), | 2694 | None => "NO TIMELINE — open a file first".to_string(), |
| @@ -2155,6 +2697,64 @@ impl Player { | |||
| 2155 | cx.notify(); | 2697 | cx.notify(); |
| 2156 | } | 2698 | } |
| 2157 | 2699 | ||
| 2700 | + /// Back to the window the editor launches as: no timeline, no library, no | ||
| 2701 | + /// picture -- and the hint that says to open a file. What removing the last | ||
| 2702 | + /// library row leaves, since a session whose library is empty has nothing | ||
| 2703 | + /// left to be ([`Player::remove_source`]). | ||
| 2704 | + /// | ||
| 2705 | + /// Everything a *loaded project* resets goes here for its reasons (an index | ||
| 2706 | + /// into a timeline that is gone names nothing), plus the three per-file | ||
| 2707 | + /// caches: they are keyed by path, and the next file to arrive fills them | ||
| 2708 | + /// again. | ||
| 2709 | + fn close_session(&mut self) { | ||
| 2710 | + self.session = None; | ||
| 2711 | + // The picture goes with it, or the empty window would keep showing the | ||
| 2712 | + // last frame of a timeline that no longer exists. | ||
| 2713 | + // | ||
| 2714 | + // ponytail: its atlas tile is not released -- `window.drop_image` wants | ||
| 2715 | + // a `&mut Window` this door has no other reason to take. One tile per | ||
| 2716 | + // emptied library, against one per displayed frame in `pump`; the | ||
| 2717 | + // upgrade path is threading the window through `act_on_row`. | ||
| 2718 | + self.image = None; | ||
| 2719 | + self.clipboard = None; | ||
| 2720 | + self.selected = None; | ||
| 2721 | + self.selected_asset = None; | ||
| 2722 | + self.context_menu = None; | ||
| 2723 | + self.library_menu = None; | ||
| 2724 | + self.eq_open = None; | ||
| 2725 | + self.color_open = None; | ||
| 2726 | + self.speed_open = None; | ||
| 2727 | + self.close_silence(); | ||
| 2728 | + self.waves.clear(); | ||
| 2729 | + self.streams.clear(); | ||
| 2730 | + self.sizes.clear(); | ||
| 2731 | + // Scanned off a source that is not in the library any more. | ||
| 2732 | + self.silence_levels = None; | ||
| 2733 | + // Every gesture in flight, dropped for `reset_after_reseek`'s reason | ||
| 2734 | + // (it drops the trim below): a drag holds a bar, a clip or a band of a | ||
| 2735 | + // timeline that has just stopped existing. | ||
| 2736 | + self.scrubbing = false; | ||
| 2737 | + self.volume_dragging = false; | ||
| 2738 | + self.eq_dragging = false; | ||
| 2739 | + self.speed_dragging = false; | ||
| 2740 | + self.color_dragging = false; | ||
| 2741 | + self.displayed = 0; | ||
| 2742 | + self.dropped = 0; | ||
| 2743 | + self.started = None; | ||
| 2744 | + // The empty window's own: no name in the titlebar, nowhere chosen to | ||
| 2745 | + // export or save to yet, and a rate that only keeps the timecode | ||
| 2746 | + // reading in frames until a file brings its own (`main`). | ||
| 2747 | + self.name = NO_FILE.into(); | ||
| 2748 | + self.export_path = PathBuf::new(); | ||
| 2749 | + self.project_path = PathBuf::new(); | ||
| 2750 | + self.fps = 30.; | ||
| 2751 | + // No decoder to wait for a frame from: the hint is what shows. | ||
| 2752 | + self.reset_after_reseek(); | ||
| 2753 | + self.pending_seek = false; | ||
| 2754 | + self.eos = false; | ||
| 2755 | + self.done = false; | ||
| 2756 | + } | ||
| 2757 | + | ||
| 2158 | /// One item of a library row's menu, done. Every one of them closes the | 2758 | /// One item of a library row's menu, done. Every one of them closes the |
| 2159 | /// menu first -- the list under it is about to be rebuilt -- except the one | 2759 | /// menu first -- the list under it is about to be rebuilt -- except the one |
| 2160 | /// that turns the card over. | 2760 | /// that turns the card over. |
| @@ -2170,7 +2770,7 @@ impl Player { | |||
| 2170 | } | 2770 | } |
| 2171 | RowItem::Add => { | 2771 | RowItem::Add => { |
| 2172 | self.library_menu = None; | 2772 | self.library_menu = None; |
| 2173 | - self.insert_source(&menu.path, menu.stream, None, cx); | 2773 | + self.insert_source(&menu.path, menu.stream, None, None, cx); |
| 2174 | } | 2774 | } |
| 2175 | RowItem::Remove => { | 2775 | RowItem::Remove => { |
| 2176 | self.library_menu = None; | 2776 | self.library_menu = None; |
| @@ -2188,11 +2788,22 @@ impl Player { | |||
| 2188 | cx.notify(); | 2788 | cx.notify(); |
| 2189 | } | 2789 | } |
| 2190 | 2790 | ||
| 2191 | - /// The rate and layout the whole timeline's audio is, taken from source 0's | 2791 | + /// The rate and layout the whole timeline's audio is, taken from the stream |
| 2192 | - /// own stream: what a library row has to match to be placeable. `None` | 2792 | + /// of the first source that could have one: what a library row has to match |
| 2193 | - /// until that file has been probed, and then nothing is greyed for it. | 2793 | + /// to be placeable. `None` until that file has been probed, and then nothing |
| 2794 | + /// is greyed for it. | ||
| 2795 | + /// | ||
| 2796 | + /// The first source that is *not a still*, which is the rule the engine | ||
| 2797 | + /// holds every import to (`playback::audio_source_of`) -- a picture at the | ||
| 2798 | + /// head of the list (a removal moves indexes) has no stream to describe | ||
| 2799 | + /// anything with. | ||
| 2194 | fn timeline_audio(&self) -> Option<(u32, u16)> { | 2800 | fn timeline_audio(&self) -> Option<(u32, u16)> { |
| 2195 | - let first = self.session.as_ref()?.sources().first()?; | 2801 | + let first = self |
| 2802 | + .session | ||
| 2803 | + .as_ref()? | ||
| 2804 | + .sources() | ||
| 2805 | + .iter() | ||
| 2806 | + .find(|s| !engine::is_image(&s.path))?; | ||
| 2196 | let info = self | 2807 | let info = self |
| 2197 | .streams | 2808 | .streams |
| 2198 | .get(&first.path)? | 2809 | .get(&first.path)? |
| @@ -2397,6 +3008,64 @@ impl Player { | |||
| 2397 | cx.notify(); | 3008 | cx.notify(); |
| 2398 | } | 3009 | } |
| 2399 | 3010 | ||
| 3011 | + /// The × in a track's header: the add taken back, one undo step, and the | ||
| 3012 | + /// engine's own words when it refuses -- those name the clips still on the | ||
| 3013 | + /// track, so the notice says what to delete first. A removal never deletes a | ||
| 3014 | + /// clip. | ||
| 3015 | + /// | ||
| 3016 | + /// Everything holding a `(lane, idx)` is dropped, because the tracks below | ||
| 3017 | + /// the one that went have just moved up an `ord` | ||
| 3018 | + /// ([`engine::Project::remove_lane`]): a selection or an open card kept | ||
| 3019 | + /// across it would be pointing at the *next* track's clip. | ||
| 3020 | + fn remove_lane(&mut self, lane: Lane, cx: &mut Context<Self>) { | ||
| 3021 | + if self.exporting().is_some() { | ||
| 3022 | + return; | ||
| 3023 | + } | ||
| 3024 | + let removed = self | ||
| 3025 | + .session | ||
| 3026 | + .as_mut() | ||
| 3027 | + .map(|session| session.remove_lane(lane)); | ||
| 3028 | + let text = match removed { | ||
| 3029 | + Some(Ok(())) => { | ||
| 3030 | + self.selected = None; | ||
| 3031 | + self.context_menu = None; | ||
| 3032 | + self.eq_open = None; | ||
| 3033 | + self.color_open = None; | ||
| 3034 | + self.speed_open = None; | ||
| 3035 | + self.close_silence(); | ||
| 3036 | + format!( | ||
| 3037 | + "{} REMOVED — {} brings it back", | ||
| 3038 | + lane.label(), | ||
| 3039 | + self.keymap.display(ActionId::Undo) | ||
| 3040 | + ) | ||
| 3041 | + } | ||
| 3042 | + Some(Err(e)) => format!("NO TRACK REMOVED — {e}"), | ||
| 3043 | + None => "NO TRACK REMOVED — open a file first".to_string(), | ||
| 3044 | + }; | ||
| 3045 | + self.notice = Some(text.into()); | ||
| 3046 | + cx.notify(); | ||
| 3047 | + } | ||
| 3048 | + | ||
| 3049 | + /// What the remove keys act on: the last track of that kind, which is the | ||
| 3050 | + /// one the matching add key appended. Nothing at all before a file is open, | ||
| 3051 | + /// where the timeline drawn is a placeholder pair. | ||
| 3052 | + fn remove_last_lane(&mut self, kind: LaneKind, cx: &mut Context<Self>) { | ||
| 3053 | + let last = self.session.as_ref().and_then(|session| { | ||
| 3054 | + session | ||
| 3055 | + .lanes() | ||
| 3056 | + .into_iter() | ||
| 3057 | + .filter(|l| l.kind == kind) | ||
| 3058 | + .next_back() | ||
| 3059 | + }); | ||
| 3060 | + match last { | ||
| 3061 | + Some(lane) => self.remove_lane(lane, cx), | ||
| 3062 | + None => { | ||
| 3063 | + self.notice = Some("NO TRACK REMOVED — open a file first".into()); | ||
| 3064 | + cx.notify(); | ||
| 3065 | + } | ||
| 3066 | + } | ||
| 3067 | + } | ||
| 3068 | + | ||
| 2400 | fn undo(&mut self, cx: &mut Context<Self>) { | 3069 | fn undo(&mut self, cx: &mut Context<Self>) { |
| 2401 | if self.session.as_mut().is_some_and(PlaybackSession::undo) { | 3070 | if self.session.as_mut().is_some_and(PlaybackSession::undo) { |
| 2402 | self.reset_after_reseek(); | 3071 | self.reset_after_reseek(); |
| @@ -2452,7 +3121,9 @@ impl Player { | |||
| 2452 | let Some(session) = &self.session else { | 3121 | let Some(session) = &self.session else { |
| 2453 | return; | 3122 | return; |
| 2454 | }; | 3123 | }; |
| 2455 | - let t = f64::from(frac_along(x, self.ruler.get())) * session.timeline_duration(); | 3124 | + let t = self |
| 3125 | + .view | ||
| 3126 | + .time_at(frac_along(x, self.ruler.get()), session.timeline_duration()); | ||
| 2456 | let target = (t * self.fps) as u32; | 3127 | let target = (t * self.fps) as u32; |
| 2457 | if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) { | 3128 | if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) { |
| 2458 | self.last_target = target; | 3129 | self.last_target = target; |
| @@ -2483,10 +3154,33 @@ impl Player { | |||
| 2483 | cx.notify(); | 3154 | cx.notify(); |
| 2484 | } | 3155 | } |
| 2485 | 3156 | ||
| 3157 | + /// Where the pointer sits along the slider, as a level. The press and every | ||
| 3158 | + /// sample after it come here, so the sound follows the hand rather than the | ||
| 3159 | + /// release -- there is nothing to undo about a monitoring level, which is | ||
| 3160 | + /// why this writes live and keeps no gesture state beyond the flag. | ||
| 3161 | + fn drag_volume(&mut self, x: Pixels, cx: &mut Context<Self>) { | ||
| 3162 | + let along = frac_along(x, self.volume_bar.get()); | ||
| 3163 | + self.set_volume(|volume| volume.set_along(along), cx); | ||
| 3164 | + } | ||
| 3165 | + | ||
| 2486 | fn toggle_or_restart(&mut self, cx: &mut Context<Self>) { | 3166 | fn toggle_or_restart(&mut self, cx: &mut Context<Self>) { |
| 2487 | if self.exporting().is_some() { | 3167 | if self.exporting().is_some() { |
| 2488 | return; | 3168 | return; |
| 2489 | } | 3169 | } |
| 3170 | + // Nothing to play is a message, not a transport state. An empty | ||
| 3171 | + // timeline is `done` from its one black frame onward, so the restart | ||
| 3172 | + // below would start a clock against a zero-length timeline -- and it is | ||
| 3173 | + // `done` again by the next repaint, so no later press could ever stop | ||
| 3174 | + // it: the button would read "Pause" and never pause. A delete can empty | ||
| 3175 | + // the timeline mid-play, and that press must still stop it. | ||
| 3176 | + if nothing_to_play(self.session.as_ref()) { | ||
| 3177 | + match self.session.as_mut().filter(|s| s.is_playing()) { | ||
| 3178 | + Some(session) => session.pause(), | ||
| 3179 | + None => self.notice = Some(NOTHING_TO_PLAY.into()), | ||
| 3180 | + } | ||
| 3181 | + cx.notify(); | ||
| 3182 | + return; | ||
| 3183 | + } | ||
| 2490 | if self.done { | 3184 | if self.done { |
| 2491 | self.seek(0., cx); | 3185 | self.seek(0., cx); |
| 2492 | if let Some(session) = &mut self.session { | 3186 | if let Some(session) = &mut self.session { |
| @@ -2545,6 +3239,38 @@ impl Player { | |||
| 2545 | self.export_path = retarget(&self.export_path, format); | 3239 | self.export_path = retarget(&self.export_path, format); |
| 2546 | } | 3240 | } |
| 2547 | 3241 | ||
| 3242 | + /// The container row: the same codec in the other box, which retargets the | ||
| 3243 | + /// destination exactly as picking a codec does -- and does nothing at all | ||
| 3244 | + /// for a codec with only one box, so the stroke cannot invent a choice the | ||
| 3245 | + /// card is not offering. | ||
| 3246 | + fn cycle_container(&mut self) { | ||
| 3247 | + self.set_format(next_container(self.format)); | ||
| 3248 | + } | ||
| 3249 | + | ||
| 3250 | + /// The quality rows by keyboard, wrapping. Refused by name where the format | ||
| 3251 | + /// has no bitrate to pick: a key that silently does nothing is the card | ||
| 3252 | + /// looking broken. | ||
| 3253 | + fn cycle_quality(&mut self) { | ||
| 3254 | + if let Some(why) = bitrate_refusal(self.format) { | ||
| 3255 | + self.notice = Some(why.into()); | ||
| 3256 | + return; | ||
| 3257 | + } | ||
| 3258 | + let at = Quality::ALL | ||
| 3259 | + .iter() | ||
| 3260 | + .position(|&q| q == self.quality) | ||
| 3261 | + .unwrap_or(0); | ||
| 3262 | + self.quality = Quality::ALL[(at + 1) % Quality::ALL.len()]; | ||
| 3263 | + } | ||
| 3264 | + | ||
| 3265 | + /// The custom bitrate by pointer: the typed digits were the only control in | ||
| 3266 | + /// this card a mouse could not reach. Clamped to the range the row states | ||
| 3267 | + /// (the engine's own 1..20 Mbps), and picking the row is part of the step -- | ||
| 3268 | + /// a stepper that moves a number nobody is using would move nothing. | ||
| 3269 | + fn nudge_mbps(&mut self, step: i32) { | ||
| 3270 | + self.custom_mbps = (self.custom_mbps as i32 + step).clamp(1, 20) as u32; | ||
| 3271 | + self.quality = Quality::Custom; | ||
| 3272 | + } | ||
| 3273 | + | ||
| 2548 | /// The card's Destination row: the desktop's save dialog, on a background | 3274 | /// The card's Destination row: the desktop's save dialog, on a background |
| 2549 | /// thread like the import chooser -- the user may sit in it and the window | 3275 | /// thread like the import chooser -- the user may sit in it and the window |
| 2550 | /// behind must not freeze. No chooser at all leaves the default path, which | 3276 | /// behind must not freeze. No chooser at all leaves the default path, which |
| @@ -2672,6 +3398,7 @@ impl Render for Player { | |||
| 2672 | // has been through a repaint by the time its clips are drawn, so this | 3398 | // has been through a repaint by the time its clips are drawn, so this |
| 2673 | // is the one place that has to notice a new one. | 3399 | // is the one place that has to notice a new one. |
| 2674 | self.cache_media(cx); | 3400 | self.cache_media(cx); |
| 3401 | + self.cache_export_seat(cx); | ||
| 2675 | // What the compositor calls this window. Pushed only when it changes: | 3402 | // What the compositor calls this window. Pushed only when it changes: |
| 2676 | // it is a protocol round trip and this runs at vsync. | 3403 | // it is a protocol round trip and this runs at vsync. |
| 2677 | let title = window_title(&self.name); | 3404 | let title = window_title(&self.name); |
| @@ -2699,24 +3426,29 @@ impl Render for Player { | |||
| 2699 | // timecode, the ruler and the clamp below all have to follow it -- and | 3426 | // timecode, the ruler and the clamp below all have to follow it -- and |
| 2700 | // so does the room a tail being dragged needs to grow into. | 3427 | // so does the room a tail being dragged needs to grow into. |
| 2701 | let duration = self.drawn_duration(); | 3428 | let duration = self.drawn_duration(); |
| 2702 | - // The clock keeps running after the last frame (wall time takes over at | 3429 | + let position = self.playhead(duration); |
| 2703 | - // audio EOF) while the picture is frozen, so the timeline the UI shows is | 3430 | + // Re-settled every frame against the duration this one is drawing: an |
| 2704 | - // the clamped one, pinned to the out-point once playback is done. | 3431 | + // edit that shortens the timeline moves the far end of the view, and a |
| 2705 | - let position = if self.done { | 3432 | + // playhead that has run off the bed pulls the view after it -- which is |
| 2706 | - duration | 3433 | + // what makes a zoomed-in timeline scroll while it plays. |
| 2707 | - } else { | 3434 | + self.view = self.view.following(position, duration, self.fps); |
| 2708 | - self.session | ||
| 2709 | - .as_ref() | ||
| 2710 | - .map_or(0., PlaybackSession::now) | ||
| 2711 | - .clamp(0., duration) | ||
| 2712 | - }; | ||
| 2713 | 3435 | ||
| 2714 | div() | 3436 | div() |
| 2715 | .track_focus(&self.focus) | 3437 | .track_focus(&self.focus) |
| 2716 | .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { | 3438 | .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { |
| 2717 | - // `is_held` filters auto-repeat, which would otherwise toggle | 3439 | + let key = event.keystroke.key.as_str(); |
| 2718 | - // playback -- or cut the timeline -- many times a second. | 3440 | + let ctrl = event.keystroke.modifiers.control; |
| 2719 | - if event.is_held { | 3441 | + // `is_held` is the auto-repeat, and a value is the one thing |
| 3442 | + // worth running on it: a held arrow on a card moves the slider | ||
| 3443 | + // it picked, and a held volume key runs the volume. Everything | ||
| 3444 | + // else is filtered exactly as it always was -- a repeat that | ||
| 3445 | + // toggled playback, or cut the timeline, many times a second is | ||
| 3446 | + // what this guard is for, and a row waiting for a stroke takes | ||
| 3447 | + // none of it either (it would bind the key, then fire what it | ||
| 3448 | + // just bound). See [`repeats`]. | ||
| 3449 | + if event.is_held | ||
| 3450 | + && !repeats(this.repeat_scope(), key, this.keymap.lookup(key, ctrl)) | ||
| 3451 | + { | ||
| 2720 | return; | 3452 | return; |
| 2721 | } | 3453 | } |
| 2722 | // Any key retires the last message, whatever it was -- and owes | 3454 | // Any key retires the last message, whatever it was -- and owes |
| @@ -2726,7 +3458,6 @@ impl Render for Player { | |||
| 2726 | if this.notice.take().is_some() { | 3458 | if this.notice.take().is_some() { |
| 2727 | cx.notify(); | 3459 | cx.notify(); |
| 2728 | } | 3460 | } |
| 2729 | - let key = event.keystroke.key.as_str(); | ||
| 2730 | // A row is waiting for a stroke, and while it is, that stroke is | 3461 | // A row is waiting for a stroke, and while it is, that stroke is |
| 2731 | // data: it means the binding and nothing else, which is why this | 3462 | // data: it means the binding and nothing else, which is why this |
| 2732 | // answers before the export guard and before the keymap is | 3463 | // answers before the export guard and before the keymap is |
| @@ -2735,7 +3466,7 @@ impl Render for Player { | |||
| 2735 | if key == ESCAPE { | 3466 | if key == ESCAPE { |
| 2736 | this.rebinding = None; | 3467 | this.rebinding = None; |
| 2737 | } else if !is_bare_modifier(key) { | 3468 | } else if !is_bare_modifier(key) { |
| 2738 | - this.capture(action, key, event.keystroke.modifiers.control); | 3469 | + this.capture(action, key, ctrl); |
| 2739 | } | 3470 | } |
| 2740 | cx.notify(); | 3471 | cx.notify(); |
| 2741 | return; | 3472 | return; |
| @@ -2744,7 +3475,7 @@ impl Render for Player { | |||
| 2744 | // control modifier set (the control code is mapped back), which | 3475 | // control modifier set (the control code is mapped back), which |
| 2745 | // is why the keymap is keyed on the pair and never on the key | 3476 | // is why the keymap is keyed on the pair and never on the key |
| 2746 | // alone. | 3477 | // alone. |
| 2747 | - let action = this.keymap.lookup(key, event.keystroke.modifiers.control); | 3478 | + let action = this.keymap.lookup(key, ctrl); |
| 2748 | // An export is reading the edit list every other action here | 3479 | // An export is reading the edit list every other action here |
| 2749 | // would change, so cancelling is the only one that means | 3480 | // would change, so cancelling is the only one that means |
| 2750 | // anything until it is over. | 3481 | // anything until it is over. |
| @@ -2778,16 +3509,35 @@ impl Render for Player { | |||
| 2778 | // The card's own button, by keyboard: the one thing in | 3509 | // The card's own button, by keyboard: the one thing in |
| 2779 | // it that writes a file must not be pointer-only either. | 3510 | // it that writes a file must not be pointer-only either. |
| 2780 | this.start_export(cx); | 3511 | this.start_export(cx); |
| 2781 | - } else if let Some(format) = format_key(key) { | 3512 | + } else if let Some(format) = format_key(key, this.format) { |
| 2782 | - // The format rows by their initial, so the card can be | 3513 | + // The codec rows by their own letter, so the card can be |
| 2783 | // driven without a mouse -- the same card-local input | 3514 | // driven without a mouse -- the same card-local input |
| 2784 | // the typed bitrate is, and for the same reason: a | 3515 | // the typed bitrate is, and for the same reason: a |
| 2785 | // choice reachable only by pointer is not reachable by | 3516 | // choice reachable only by pointer is not reachable by |
| 2786 | // everyone. Not a keymap binding: it means nothing | 3517 | // everyone. Not a keymap binding: it means nothing |
| 2787 | // outside this card, exactly like the digits. | 3518 | // outside this card, exactly like the digits. |
| 2788 | this.set_format(format); | 3519 | this.set_format(format); |
| 3520 | + } else if key == "c" { | ||
| 3521 | + this.cycle_container(); | ||
| 3522 | + } else if key == "q" { | ||
| 3523 | + this.cycle_quality(); | ||
| 3524 | + } else if key == "d" { | ||
| 3525 | + // The save dialog, which was the one row here a | ||
| 3526 | + // keyboard could not open. | ||
| 3527 | + this.pick_destination(cx); | ||
| 3528 | + } else if key == "g" { | ||
| 3529 | + this.export_grouped = !this.export_grouped; | ||
| 3530 | + } else if key == "r" { | ||
| 3531 | + this.export_refusals_inline = !this.export_refusals_inline; | ||
| 2789 | } else if let Ok(digit) = key.parse::<u32>() { | 3532 | } else if let Ok(digit) = key.parse::<u32>() { |
| 2790 | - this.custom_mbps = push_digit(this.custom_mbps, digit); | 3533 | + let next = push_digit(this.custom_mbps, digit); |
| 3534 | + // A refused third digit says so: it used to be dropped | ||
| 3535 | + // in silence, which left the card showing a number the | ||
| 3536 | + // user had already typed past. | ||
| 3537 | + if next == this.custom_mbps && this.custom_mbps > 0 { | ||
| 3538 | + this.notice = Some("1–20 Mbps — a third digit is refused".into()); | ||
| 3539 | + } | ||
| 3540 | + this.custom_mbps = next; | ||
| 2791 | this.quality = Quality::Custom; | 3541 | this.quality = Quality::Custom; |
| 2792 | } else if key == "backspace" { | 3542 | } else if key == "backspace" { |
| 2793 | this.custom_mbps /= 10; | 3543 | this.custom_mbps /= 10; |
| @@ -2816,6 +3566,11 @@ impl Render for Player { | |||
| 2816 | band.gain_db = 0.; | 3566 | band.gain_db = 0.; |
| 2817 | } | 3567 | } |
| 2818 | this.commit_eq(cx); | 3568 | this.commit_eq(cx); |
| 3569 | + } else if key == "s" { | ||
| 3570 | + // The analyser off and on. Nothing is committed: it is | ||
| 3571 | + // what the card *shows*, so it survives no further than | ||
| 3572 | + // this window. | ||
| 3573 | + this.eq_spectrum = !this.eq_spectrum; | ||
| 2819 | } else if let Ok(digit) = key.parse::<usize>() { | 3574 | } else if let Ok(digit) = key.parse::<usize>() { |
| 2820 | // 1-based, as the rows are numbered on screen; a digit | 3575 | // 1-based, as the rows are numbered on screen; a digit |
| 2821 | // past the last band picks nothing rather than panics. | 3576 | // past the last band picks nothing rather than panics. |
| @@ -2899,6 +3654,25 @@ impl Render for Player { | |||
| 2899 | cx.notify(); | 3654 | cx.notify(); |
| 2900 | return; | 3655 | return; |
| 2901 | } | 3656 | } |
| 3657 | + // The mix card, the same way again: ↑↓ pick a row -- a track's | ||
| 3658 | + // fader, the limiter's ceiling or its switch -- and ←→ move it, | ||
| 3659 | + // held or pressed. Card-local like the four above it. | ||
| 3660 | + if this.mix_open { | ||
| 3661 | + let rows = this.mix_lanes().len() + MIX_MASTER_ROWS; | ||
| 3662 | + if key == ESCAPE { | ||
| 3663 | + this.mix_open = false; | ||
| 3664 | + } else if key == "down" { | ||
| 3665 | + this.mix_field = (this.mix_field + 1) % rows; | ||
| 3666 | + } else if key == "up" { | ||
| 3667 | + this.mix_field = (this.mix_field + rows - 1) % rows; | ||
| 3668 | + } else if key == "right" { | ||
| 3669 | + this.nudge_mix(1, cx); | ||
| 3670 | + } else if key == "left" { | ||
| 3671 | + this.nudge_mix(-1, cx); | ||
| 3672 | + } | ||
| 3673 | + cx.notify(); | ||
| 3674 | + return; | ||
| 3675 | + } | ||
| 2902 | // A clip menu names an index, and every edit below moves | 3676 | // A clip menu names an index, and every edit below moves |
| 2903 | // indices -- so a stroke closes it before it acts. Escape means | 3677 | // indices -- so a stroke closes it before it acts. Escape means |
| 2904 | // that and nothing else, which is the `esc` the keys menu | 3678 | // that and nothing else, which is the `esc` the keys menu |
| @@ -2991,6 +3765,16 @@ impl Render for Player { | |||
| 2991 | } | 3765 | } |
| 2992 | return; | 3766 | return; |
| 2993 | } | 3767 | } |
| 3768 | + // The volume slider, the same live writes: what the hand is on | ||
| 3769 | + // is what the speakers are doing, and there is nothing to undo. | ||
| 3770 | + if this.volume_dragging { | ||
| 3771 | + if event.pressed_button == Some(MouseButton::Left) { | ||
| 3772 | + this.drag_volume(event.position.x, cx); | ||
| 3773 | + } else { | ||
| 3774 | + this.volume_dragging = false; | ||
| 3775 | + } | ||
| 3776 | + return; | ||
| 3777 | + } | ||
| 2994 | if !this.scrubbing { | 3778 | if !this.scrubbing { |
| 2995 | return; | 3779 | return; |
| 2996 | } | 3780 | } |
| @@ -3031,6 +3815,10 @@ impl Render for Player { | |||
| 3031 | this.drag_speed(event.position.x, false, cx); | 3815 | this.drag_speed(event.position.x, false, cx); |
| 3032 | return; | 3816 | return; |
| 3033 | } | 3817 | } |
| 3818 | + if std::mem::take(&mut this.volume_dragging) { | ||
| 3819 | + this.drag_volume(event.position.x, cx); | ||
| 3820 | + return; | ||
| 3821 | + } | ||
| 3034 | if std::mem::take(&mut this.scrubbing) { | 3822 | if std::mem::take(&mut this.scrubbing) { |
| 3035 | this.scrub_to(event.position.x, true, cx); | 3823 | this.scrub_to(event.position.x, true, cx); |
| 3036 | } | 3824 | } |
| @@ -3106,11 +3894,12 @@ impl Render for Player { | |||
| 3106 | // Last, so they are over everything -- they take no room in the | 3894 | // Last, so they are over everything -- they take no room in the |
| 3107 | // column, and only one of the two is ever up. | 3895 | // column, and only one of the two is ever up. |
| 3108 | .children(self.keys_overlay(cx)) | 3896 | .children(self.keys_overlay(cx)) |
| 3109 | - .children(self.export_card(cx)) | 3897 | + .children(self.export_card(window.viewport_size(), cx)) |
| 3110 | .children(self.eq_card(cx)) | 3898 | .children(self.eq_card(cx)) |
| 3111 | .children(self.color_card(cx)) | 3899 | .children(self.color_card(cx)) |
| 3112 | .children(self.speed_card(cx)) | 3900 | .children(self.speed_card(cx)) |
| 3113 | .children(self.silence_card(cx)) | 3901 | .children(self.silence_card(cx)) |
| 3902 | + .children(self.mix_card(cx)) | ||
| 3114 | } | 3903 | } |
| 3115 | } | 3904 | } |
| 3116 | 3905 | ||
| @@ -3139,11 +3928,17 @@ impl Player { | |||
| 3139 | // Its own length, not one derived from what is on the lanes: a row | 3928 | // Its own length, not one derived from what is on the lanes: a row |
| 3140 | // imported and never placed is a row with a length, and it is the | 3929 | // imported and never placed is a row with a length, and it is the |
| 3141 | // length a drag would put down. | 3930 | // length a drag would put down. |
| 3142 | - let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| { | 3931 | + let rows: Vec<_> = library_rows( |
| 3143 | - self.session | 3932 | + sources, |
| 3144 | - .as_ref() | 3933 | + &self.streams, |
| 3145 | - .map_or(0, |session| session.file_frames(path)) | 3934 | + &self.decoders, |
| 3146 | - }) | 3935 | + self.timeline_audio(), |
| 3936 | + |path| { | ||
| 3937 | + self.session | ||
| 3938 | + .as_ref() | ||
| 3939 | + .map_or(0, |session| session.file_frames(path)) | ||
| 3940 | + }, | ||
| 3941 | + ) | ||
| 3147 | .into_iter() | 3942 | .into_iter() |
| 3148 | .enumerate() | 3943 | .enumerate() |
| 3149 | .map(|(i, row)| { | 3944 | .map(|(i, row)| { |
| @@ -3174,12 +3969,18 @@ impl Player { | |||
| 3174 | None => String::new(), | 3969 | None => String::new(), |
| 3175 | } | 3970 | } |
| 3176 | ), | 3971 | ), |
| 3972 | + // The file's *own* frame rate, not the timeline's: a clip shot | ||
| 3973 | + // at another rate plays at the speed it was shot at, and the | ||
| 3974 | + // row that says where it came from has to say which rate that | ||
| 3975 | + // was. | ||
| 3177 | (None, Some(meta)) => format!( | 3976 | (None, Some(meta)) => format!( |
| 3178 | - "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", | 3977 | + "{} — {}x{} @ {:.2} fps · drag it where you want it, or Add at playhead", |
| 3179 | row.path.display(), | 3978 | row.path.display(), |
| 3180 | meta.width, | 3979 | meta.width, |
| 3181 | meta.height, | 3980 | meta.height, |
| 3182 | - meta.frame_rate | 3981 | + self.session |
| 3982 | + .as_ref() | ||
| 3983 | + .map_or(meta.frame_rate, |session| session.file_fps(&row.path)) | ||
| 3183 | ), | 3984 | ), |
| 3184 | (None, None) => row.path.display().to_string(), | 3985 | (None, None) => row.path.display().to_string(), |
| 3185 | }; | 3986 | }; |
| @@ -3357,7 +4158,7 @@ impl Player { | |||
| 3357 | "Add at playhead", | 4158 | "Add at playhead", |
| 3358 | match self.selected_asset { | 4159 | match self.selected_asset { |
| 3359 | Some(_) => "inserts the picked file at the playhead".to_string(), | 4160 | Some(_) => "inserts the picked file at the playhead".to_string(), |
| 3360 | - None => "click a file above first — or drag one onto a lane".to_string(), | 4161 | + None => "click a file above first — or drag one where you want it".to_string(), |
| 3361 | }, | 4162 | }, |
| 3362 | can_add( | 4163 | can_add( |
| 3363 | self.selected_asset.as_ref(), | 4164 | self.selected_asset.as_ref(), |
| @@ -3368,12 +4169,36 @@ impl Player { | |||
| 3368 | if let Some((path, stream)) = this.selected_asset.clone() { | 4169 | if let Some((path, stream)) = this.selected_asset.clone() { |
| 3369 | // No lane: the button means "wherever this belongs", | 4170 | // No lane: the button means "wherever this belongs", |
| 3370 | // which for a file with no picture is the audio lane. | 4171 | // which for a file with no picture is the audio lane. |
| 3371 | - this.insert_source(&path, stream, None, cx); | 4172 | + this.insert_source(&path, stream, None, None, cx); |
| 3372 | } | 4173 | } |
| 3373 | }), | 4174 | }), |
| 3374 | )) | 4175 | )) |
| 3375 | } | 4176 | } |
| 3376 | 4177 | ||
| 4178 | + /// What is decoding the picture right now, for the transport line: the | ||
| 4179 | + /// backend is the running worker's own (it is written where a hardware | ||
| 4180 | + /// session falls back to software, so this follows reality), and the codec | ||
| 4181 | + /// comes from the clip under the playhead. Empty when nothing is playing -- | ||
| 4182 | + /// the question is about what is happening, not about what would. | ||
| 4183 | + fn live_decode(&self, position: f64, playing: bool) -> String { | ||
| 4184 | + let Some(session) = self.session.as_ref().filter(|_| playing) else { | ||
| 4185 | + return String::new(); | ||
| 4186 | + }; | ||
| 4187 | + let backend = session.decode_backend(); | ||
| 4188 | + let codec = session | ||
| 4189 | + .video_clip_at(position) | ||
| 4190 | + .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| clip.source)) | ||
| 4191 | + .and_then(|source| session.sources().get(source)) | ||
| 4192 | + .and_then(|source| self.decoders.get(&source.path).copied().flatten()) | ||
| 4193 | + .and_then(|(codec, _)| codec); | ||
| 4194 | + match backend { | ||
| 4195 | + // Neither is a decode, and saying "SW" of them would be a lie. | ||
| 4196 | + Backend::Gap => "gap · nothing to decode".to_string(), | ||
| 4197 | + Backend::Still => "still · one decode, held".to_string(), | ||
| 4198 | + _ => format!("{} decode", decode_label(codec, backend)), | ||
| 4199 | + } | ||
| 4200 | + } | ||
| 4201 | + | ||
| 3377 | /// Transport, edit and file buttons, timecode, playhead, clips lane. | 4202 | /// Transport, edit and file buttons, timecode, playhead, clips lane. |
| 3378 | fn panel( | 4203 | fn panel( |
| 3379 | &self, | 4204 | &self, |
| @@ -3382,11 +4207,11 @@ impl Player { | |||
| 3382 | playing: bool, | 4207 | playing: bool, |
| 3383 | cx: &mut Context<Self>, | 4208 | cx: &mut Context<Self>, |
| 3384 | ) -> impl IntoElement { | 4209 | ) -> impl IntoElement { |
| 3385 | - let filled = if duration > 0. { | 4210 | + // Where the playhead is *on the bed*, which at the fit is where along |
| 3386 | - (position / duration) as f32 | 4211 | + // the timeline it is and zoomed in is where along the visible slice. |
| 3387 | - } else { | 4212 | + // Clamped because it is drawn as a width as well as an offset, and the |
| 3388 | - 0. | 4213 | + // view follows the playhead anyway, so it is never off the bed. |
| 3389 | - }; | 4214 | + let filled = self.view.frac_at(position, duration).clamp(0., 1.); |
| 3390 | // An export owns the hint slot and the ruler while it runs: the | 4215 | // An export owns the hint slot and the ruler while it runs: the |
| 3391 | // percentage and the accent bar are the same number, so the playhead | 4216 | // percentage and the accent bar are the same number, so the playhead |
| 3392 | // fill doubles as the progress bar for free. | 4217 | // fill doubles as the progress bar for free. |
| @@ -3394,6 +4219,10 @@ impl Player { | |||
| 3394 | // Everything but Import and Keys needs a timeline to act on: with none | 4219 | // Everything but Import and Keys needs a timeline to act on: with none |
| 3395 | // open they are dimmed rather than silently doing nothing. | 4220 | // open they are dimmed rather than silently doing nothing. |
| 3396 | let live = self.session.is_some() && !exporting; | 4221 | let live = self.session.is_some() && !exporting; |
| 4222 | + // The project's own picture size, for the button that cycles it: read | ||
| 4223 | + // per render like everything else here, so a cycle shows on the button | ||
| 4224 | + // that made it. | ||
| 4225 | + let resolution = self.session.as_ref().map(PlaybackSession::resolution); | ||
| 3397 | let key = |action| self.keymap.display(action); | 4226 | let key = |action| self.keymap.display(action); |
| 3398 | // The lanes the project has, or the pair a fresh one starts with so the | 4227 | // The lanes the project has, or the pair a fresh one starts with so the |
| 3399 | // panel reads the same before a file is open as after. | 4228 | // panel reads the same before a file is open as after. |
| @@ -3411,8 +4240,16 @@ impl Player { | |||
| 3411 | let progress = export.progress(); | 4240 | let progress = export.progress(); |
| 3412 | ( | 4241 | ( |
| 3413 | format!( | 4242 | format!( |
| 3414 | - "EXPORTING {}% — {} cancels", | 4243 | + "EXPORTING {}% · {} · {} — {} cancels", |
| 3415 | (progress * 100.) as u32, | 4244 | (progress * 100.) as u32, |
| 4245 | + // The row that was picked; the engine's line below names the | ||
| 4246 | + // seats alone, since the library is what identifies a codec. | ||
| 4247 | + format_label(self.format), | ||
| 4248 | + // What the worker actually opened, so a fallback to the | ||
| 4249 | + // software encoder shows here rather than being invisible. | ||
| 4250 | + export | ||
| 4251 | + .encoders() | ||
| 4252 | + .unwrap_or_else(|| "opening the encoder".to_string()), | ||
| 3416 | key(ActionId::CancelExport) | 4253 | key(ActionId::CancelExport) |
| 3417 | ), | 4254 | ), |
| 3418 | progress, | 4255 | progress, |
| @@ -3422,12 +4259,19 @@ impl Player { | |||
| 3422 | // tooltips. Keys first: at a 640 px window the tail is what a | 4259 | // tooltips. Keys first: at a 640 px window the tail is what a |
| 3423 | // truncation eats, and the two hints at the end are also on the | 4260 | // truncation eats, and the two hints at the end are also on the |
| 3424 | // ruler's and Import's tooltips. | 4261 | // ruler's and Import's tooltips. |
| 4262 | + // While it plays, what is decoding it goes first: it is the | ||
| 4263 | + // answer that changes as the playhead crosses a cut, and the tail | ||
| 4264 | + // of this line is what a narrow window truncates. | ||
| 3425 | ( | 4265 | ( |
| 3426 | - format!( | 4266 | + join_detail( |
| 3427 | - "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import", | 4267 | + &self.live_decode(position, playing), |
| 3428 | - key(ActionId::Copy), | 4268 | + &format!( |
| 3429 | - key(ActionId::Paste), | 4269 | + "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ |
| 3430 | - key(ActionId::Undo) | 4270 | + import", |
| 4271 | + key(ActionId::Copy), | ||
| 4272 | + key(ActionId::Paste), | ||
| 4273 | + key(ActionId::Undo) | ||
| 4274 | + ), | ||
| 3431 | ), | 4275 | ), |
| 3432 | filled, | 4276 | filled, |
| 3433 | ) | 4277 | ) |
| @@ -3443,18 +4287,35 @@ impl Player { | |||
| 3443 | .bg(rgb(CHROME)) | 4287 | .bg(rgb(CHROME)) |
| 3444 | // Transport | edit | file: three groups, so the eye can skip two of | 4288 | // Transport | edit | file: three groups, so the eye can skip two of |
| 3445 | // them. Every button says what it does; the tooltip adds its key. | 4289 | // them. Every button says what it does; the tooltip adds its key. |
| 4290 | + // | ||
| 4291 | + // The row scrolls rather than losing its tail: at the 640 px floor | ||
| 4292 | + // this window is sized for it is wider than the panel, and a button | ||
| 4293 | + // off the right edge is a button a pointer cannot press. A plain | ||
| 4294 | + // wheel moves it -- gpui puts a vertical delta on the x axis when | ||
| 4295 | + // that is the only one scrolling (div.rs:2424). | ||
| 3446 | .child( | 4296 | .child( |
| 3447 | div() | 4297 | div() |
| 4298 | + .id("controls") | ||
| 3448 | .flex_none() | 4299 | .flex_none() |
| 3449 | .flex() | 4300 | .flex() |
| 3450 | .items_center() | 4301 | .items_center() |
| 3451 | .gap(px(8.)) | 4302 | .gap(px(8.)) |
| 4303 | + .overflow_x_scroll() | ||
| 3452 | .child(control( | 4304 | .child(control( |
| 3453 | "transport", | 4305 | "transport", |
| 3454 | Some(transport_glyph(playing).into_any_element()), | 4306 | Some(transport_glyph(playing).into_any_element()), |
| 3455 | if playing { "Pause" } else { "Play" }, | 4307 | if playing { "Pause" } else { "Play" }, |
| 3456 | - key(ActionId::Play), | 4308 | + if nothing_to_play(self.session.as_ref()) && !playing { |
| 3457 | - live, | 4309 | + format!("{} — put a clip on a lane first", key(ActionId::Play)) |
| 4310 | + } else { | ||
| 4311 | + key(ActionId::Play) | ||
| 4312 | + }, | ||
| 4313 | + // An empty timeline has nothing to play, so the button | ||
| 4314 | + // says so by being dim rather than by starting a clock | ||
| 4315 | + // against nothing (the key press answers with the | ||
| 4316 | + // notice). Still live while it *is* playing: a delete | ||
| 4317 | + // can empty the timeline mid-play and that has to stop. | ||
| 4318 | + live && (playing || !nothing_to_play(self.session.as_ref())), | ||
| 3458 | cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)), | 4319 | cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)), |
| 3459 | )) | 4320 | )) |
| 3460 | .child(separator()) | 4321 | .child(separator()) |
| @@ -3481,6 +4342,17 @@ impl Player { | |||
| 3481 | live && self.selected.is_some(), | 4342 | live && self.selected.is_some(), |
| 3482 | cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)), | 4343 | cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)), |
| 3483 | )) | 4344 | )) |
| 4345 | + // The way back from every one of them. It was a stroke and | ||
| 4346 | + // nothing else, which made the whole edit group a one-way | ||
| 4347 | + // door for anyone working with a pointer. | ||
| 4348 | + .child(control( | ||
| 4349 | + "undo", | ||
| 4350 | + None, | ||
| 4351 | + "Undo", | ||
| 4352 | + format!("{} — takes the last edit back", key(ActionId::Undo)), | ||
| 4353 | + live, | ||
| 4354 | + cx.listener(|this, _: &ClickEvent, _, cx| this.undo(cx)), | ||
| 4355 | + )) | ||
| 3484 | // With the edit group, beside the buttons that change the | 4356 | // With the edit group, beside the buttons that change the |
| 3485 | // edit list: a track is a row of it, and adding one is an | 4357 | // edit list: a track is a row of it, and adding one is an |
| 3486 | // undoable edit like the rest. Two buttons rather than one | 4358 | // undoable edit like the rest. Two buttons rather than one |
| @@ -3529,20 +4401,115 @@ impl Player { | |||
| 3529 | this.set_volume(|volume| volume.muted = !volume.muted, cx) | 4401 | this.set_volume(|volume| volume.muted = !volume.muted, cx) |
| 3530 | }), | 4402 | }), |
| 3531 | )) | 4403 | )) |
| 4404 | + // The level itself, to drag. The button beside it stays the | ||
| 4405 | + // mute -- one gesture each -- and the label above is what | ||
| 4406 | + // this writes, live, so the number follows the hand. | ||
| 4407 | + .child(volume_slider( | ||
| 4408 | + self.volume, | ||
| 4409 | + self.volume_bar.clone(), | ||
| 4410 | + live, | ||
| 4411 | + cx, | ||
| 4412 | + )) | ||
| 3532 | .child(separator()) | 4413 | .child(separator()) |
| 4414 | + // The size every clip is composed onto, which is also the | ||
| 4415 | + // size the export comes out at: the one project setting a | ||
| 4416 | + // stroke used to be the only way to. Cycles exactly as the | ||
| 4417 | + // key does, and says where it is now rather than opening a | ||
| 4418 | + // list to close again. | ||
| 4419 | + .child(control( | ||
| 4420 | + "resolution", | ||
| 4421 | + None, | ||
| 4422 | + resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")), | ||
| 4423 | + match resolution { | ||
| 4424 | + Some((w, h)) => format!( | ||
| 4425 | + "{} — the project is {w}x{h}; cycles source → 2160p → 1080p → 720p → 480p", | ||
| 4426 | + key(ActionId::Resolution) | ||
| 4427 | + ), | ||
| 4428 | + None => format!("{} — open a file first", key(ActionId::Resolution)), | ||
| 4429 | + }, | ||
| 4430 | + live, | ||
| 4431 | + cx.listener(|this, _: &ClickEvent, _, cx| this.cycle_resolution(cx)), | ||
| 4432 | + )) | ||
| 4433 | + // How much of the timeline the panel below is showing -- | ||
| 4434 | + // beside the resolution, since neither of them edits | ||
| 4435 | + // anything: they are both what is being looked at. The | ||
| 4436 | + // middle one reads as the state (1.0x is the whole | ||
| 4437 | + // timeline) and is the way back to it. | ||
| 4438 | + .child(control( | ||
| 4439 | + "zoom-out", | ||
| 4440 | + None, | ||
| 4441 | + "−", | ||
| 4442 | + format!( | ||
| 4443 | + "{} — show more of the timeline; stops at the whole of it", | ||
| 4444 | + key(ActionId::ZoomOut) | ||
| 4445 | + ), | ||
| 4446 | + live, | ||
| 4447 | + cx.listener(|this, _: &ClickEvent, _, cx| { | ||
| 4448 | + this.zoom(1. / ZOOM_STEP, None, cx) | ||
| 4449 | + }), | ||
| 4450 | + )) | ||
| 4451 | + .child(control( | ||
| 4452 | + "zoom-fit", | ||
| 4453 | + None, | ||
| 4454 | + format!("{:.1}x", self.view.zoom), | ||
| 4455 | + format!( | ||
| 4456 | + "{} — fit the whole timeline; showing {} to {}", | ||
| 4457 | + key(ActionId::ZoomFit), | ||
| 4458 | + timecode(self.view.start, self.fps), | ||
| 4459 | + timecode( | ||
| 4460 | + (self.view.start + self.view.span(duration)).min(duration), | ||
| 4461 | + self.fps | ||
| 4462 | + ) | ||
| 4463 | + ), | ||
| 4464 | + live, | ||
| 4465 | + cx.listener(|this, _: &ClickEvent, _, cx| this.zoom_fit(cx)), | ||
| 4466 | + )) | ||
| 4467 | + .child(control( | ||
| 4468 | + "zoom-in", | ||
| 4469 | + None, | ||
| 4470 | + "+", | ||
| 4471 | + format!( | ||
| 4472 | + "{} — magnify around the playhead; ctrl+wheel on the bar zooms at the pointer", | ||
| 4473 | + key(ActionId::ZoomIn) | ||
| 4474 | + ), | ||
| 4475 | + live, | ||
| 4476 | + cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)), | ||
| 4477 | + )) | ||
| 3533 | // Import is not here: it belongs to the media list it adds | 4478 | // Import is not here: it belongs to the media list it adds |
| 3534 | // to, and two doors into one action is a question about | 4479 | // to, and two doors into one action is a question about |
| 3535 | // which one is the real one. | 4480 | // which one is the real one. |
| 4481 | + // | ||
| 4482 | + // While one runs, this button is the way out of it: the | ||
| 4483 | + // progress line promised esc and nothing else, which left a | ||
| 4484 | + // pointer no way to stop an export it had started. | ||
| 3536 | .child(control( | 4485 | .child(control( |
| 3537 | "export", | 4486 | "export", |
| 3538 | None, | 4487 | None, |
| 3539 | - "Export", | 4488 | + if exporting { "Cancel" } else { "Export" }, |
| 3540 | - format!( | 4489 | + if exporting { |
| 3541 | - "{} — quality and destination, then writes the timeline out", | 4490 | + format!( |
| 3542 | - key(ActionId::Export) | 4491 | + "{} — stops the export; the part-written file goes", |
| 3543 | - ), | 4492 | + key(ActionId::CancelExport) |
| 3544 | - live && self.export.is_none(), | 4493 | + ) |
| 3545 | - cx.listener(|this, _: &ClickEvent, _, cx| this.open_export(cx)), | 4494 | + } else { |
| 4495 | + format!( | ||
| 4496 | + "{} — quality and destination, then writes the timeline out", | ||
| 4497 | + key(ActionId::Export) | ||
| 4498 | + ) | ||
| 4499 | + }, | ||
| 4500 | + if exporting { | ||
| 4501 | + true | ||
| 4502 | + } else { | ||
| 4503 | + live && self.export.is_none() | ||
| 4504 | + }, | ||
| 4505 | + cx.listener(|this, _: &ClickEvent, _, cx| { | ||
| 4506 | + if this.exporting().is_some() { | ||
| 4507 | + this.cancel_export(); | ||
| 4508 | + cx.notify(); | ||
| 4509 | + } else { | ||
| 4510 | + this.open_export(cx); | ||
| 4511 | + } | ||
| 4512 | + }), | ||
| 3546 | )) | 4513 | )) |
| 3547 | .child(control( | 4514 | .child(control( |
| 3548 | "save", | 4515 | "save", |
| @@ -3620,7 +4587,32 @@ impl Player { | |||
| 3620 | .hover(|s| s.bg(rgb(HOVER_DIM))) | 4587 | .hover(|s| s.bg(rgb(HOVER_DIM))) |
| 3621 | // The strip carries no text, so the tooltip is the only | 4588 | // The strip carries no text, so the tooltip is the only |
| 3622 | // place it can say what it is. | 4589 | // place it can say what it is. |
| 3623 | - .tooltip(|_, cx| cx.new(|_| Tip("Seek — click or drag".into())).into()) | 4590 | + .tooltip(|_, cx| { |
| 4591 | + cx.new(|_| Tip("Seek — click or drag; ctrl+wheel zooms".into())) | ||
| 4592 | + .into() | ||
| 4593 | + }) | ||
| 4594 | + // Ctrl+wheel is what every timeline zooms with, and | ||
| 4595 | + // the point held still is the one under the pointer | ||
| 4596 | + // rather than the playhead. Only with ctrl: a bare | ||
| 4597 | + // wheel here is the window's to scroll, and the | ||
| 4598 | + // controls row above scrolls on exactly that. | ||
| 4599 | + .on_scroll_wheel(cx.listener( | ||
| 4600 | + |this, event: &ScrollWheelEvent, _, cx| { | ||
| 4601 | + if !event.modifiers.control { | ||
| 4602 | + return; | ||
| 4603 | + } | ||
| 4604 | + let dy = match event.delta { | ||
| 4605 | + ScrollDelta::Lines(d) => d.y, | ||
| 4606 | + ScrollDelta::Pixels(d) => f32::from(d.y), | ||
| 4607 | + }; | ||
| 4608 | + if dy == 0. { | ||
| 4609 | + return; | ||
| 4610 | + } | ||
| 4611 | + let anchor = frac_along(event.position.x, this.ruler.get()); | ||
| 4612 | + let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP }; | ||
| 4613 | + this.zoom(factor, Some(anchor), cx); | ||
| 4614 | + }, | ||
| 4615 | + )) | ||
| 3624 | .on_mouse_down( | 4616 | .on_mouse_down( |
| 3625 | MouseButton::Left, | 4617 | MouseButton::Left, |
| 3626 | cx.listener(|this, event: &MouseDownEvent, _, cx| { | 4618 | cx.listener(|this, event: &MouseDownEvent, _, cx| { |
| @@ -3885,16 +4877,33 @@ impl Player { | |||
| 3885 | ) | 4877 | ) |
| 3886 | } | 4878 | } |
| 3887 | 4879 | ||
| 3888 | - /// What an export is going to be, before there is one: the destination, the | 4880 | + /// What an export is going to be, before there is one: the codec, the box |
| 3889 | - /// quality rows, and the two things that are not a choice at all. The same | 4881 | + /// it goes into, the bitrate, where it lands -- and, above the button, the |
| 3890 | - /// scrim, width and row shape as the keybindings overlay -- two cards of | 4882 | + /// two lines that state the file all of that adds up to. The same scrim and |
| 3891 | - /// different builds over one window read as two different programs -- and | 4883 | + /// row shape as the keybindings overlay (two cards of different builds over |
| 3892 | - /// the same plain divs, so the root keeps the keyboard and a typed digit | 4884 | + /// one window read as two different programs) and the same plain divs, so |
| 3893 | - /// reaches the custom row. | 4885 | + /// the root keeps the keyboard and a typed digit reaches the custom row. |
| 3894 | - fn export_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> { | 4886 | + /// |
| 4887 | + /// Every row carries the key that picks it, so the card is drivable end to | ||
| 4888 | + /// end without a pointer *and* without a legend to memorise -- and every | ||
| 4889 | + /// row is clickable, the bitrate's steppers included, so it is drivable end | ||
| 4890 | + /// to end without a keyboard as well. | ||
| 4891 | + /// | ||
| 4892 | + /// Two shapes of it, behind `g` and `r`: sections against one flat list, | ||
| 4893 | + /// and the codecs with no encoder collapsed into a footer against a dimmed | ||
| 4894 | + /// row each. Grouped and collapsed is what opens. | ||
| 4895 | + fn export_card( | ||
| 4896 | + &self, | ||
| 4897 | + viewport: Size<Pixels>, | ||
| 4898 | + cx: &mut Context<Self>, | ||
| 4899 | + ) -> Option<impl IntoElement> { | ||
| 3895 | if !self.export_open { | 4900 | if !self.export_open { |
| 3896 | return None; | 4901 | return None; |
| 3897 | } | 4902 | } |
| 4903 | + // The cap is what keeps the card inside the smallest window; a taller | ||
| 4904 | + // one gets a taller list rather than a scroll past empty space, and the | ||
| 4905 | + // card is still only as tall as the rows it has. | ||
| 4906 | + let rows_h = (f32::from(viewport.height) - EXPORT_FIXED_H - 24.).max(EXPORT_ROWS_H); | ||
| 3898 | let row = |id: (&'static str, usize)| { | 4907 | let row = |id: (&'static str, usize)| { |
| 3899 | div() | 4908 | div() |
| 3900 | .id(id) | 4909 | .id(id) |
| @@ -3911,70 +4920,261 @@ impl Player { | |||
| 3911 | // A row that cannot be picked is dimmed and takes no click, exactly as | 4920 | // A row that cannot be picked is dimmed and takes no click, exactly as |
| 3912 | // an inapplicable item in the clip menu is: it still says its piece. | 4921 | // an inapplicable item in the clip menu is: it still says its piece. |
| 3913 | let live = |d: Stateful<Div>, enabled: bool| { | 4922 | let live = |d: Stateful<Div>, enabled: bool| { |
| 3914 | - d.when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) | 4923 | + d.when(!enabled, |d| { |
| 3915 | - .when(enabled, |d| d.cursor_pointer().hover(|s| s.bg(rgb(HOVER)))) | 4924 | + d.cursor_not_allowed().text_color(rgb(INK_DIM)) |
| 4925 | + }) | ||
| 4926 | + .when(enabled, |d| d.cursor_pointer().hover(|s| s.bg(rgb(HOVER)))) | ||
| 3916 | }; | 4927 | }; |
| 3917 | - // The formats first: the quality rows below are *video* bitrate, so | 4928 | + // A row as this card writes them: the mark saying which one is picked, |
| 3918 | - // which file is being written decides whether they mean anything. | 4929 | + // the key that picks it, its name, and what the choice means. The mark |
| 3919 | - // An mp4 this timeline cannot be written as reads exactly like the | 4930 | + // is a glyph and not only a colour -- a background alone is gone the |
| 3920 | - // formats there is no encoder for: dimmed, unclickable, and carrying its | 4931 | + // moment a hover lands on the row, and invisible to anyone who cannot |
| 3921 | - // own reason instead of the detail line. | 4932 | + // tell the two greys apart (WCAG 1.4.1). |
| 3922 | - let formats: Vec<_> = FORMATS | 4933 | + let entry = |id: (&'static str, usize), |
| 3923 | - .into_iter() | 4934 | + key: &str, |
| 3924 | - .enumerate() | 4935 | + label: SharedString, |
| 3925 | - .map(|(i, (format, label, detail))| { | 4936 | + detail: SharedString, |
| 3926 | - // Per row, because the two picture formats are refused by | 4937 | + picked: bool, |
| 3927 | - // different things: an audio-only timeline greys both, a second | 4938 | + enabled: bool| { |
| 3928 | - // audio lane only the mp4. | 4939 | + // The small print of a picked row sits on the highlight, where the |
| 3929 | - let refused = format | 4940 | + // dim ink is only 3.3:1 -- the row it lands on lifts it (WCAG |
| 3930 | - .zip(self.session.as_ref()) | 4941 | + // 1.4.3, and the fit test pins both numbers). |
| 3931 | - .and_then(|(f, s)| format_refusal(s, f)); | 4942 | + let ink = match picked { |
| 3932 | - let blocked = refused.is_some(); | 4943 | + true => INK, |
| 3933 | - let detail: SharedString = match &refused { | 4944 | + false => INK_DIM, |
| 3934 | - Some(why) => why.clone().into(), | 4945 | + }; |
| 3935 | - None => detail.into(), | 4946 | + live(row(id), enabled) |
| 3936 | - }; | 4947 | + .when(picked, |d| d.bg(rgb(SELECTED))) |
| 3937 | - let picked = format == Some(self.format) && !blocked; | 4948 | + .child( |
| 3938 | - let format = format.filter(|_| !blocked); | 4949 | + div() |
| 3939 | - live(row(("format", i)), format.is_some()) | 4950 | + .flex() |
| 3940 | - .when(picked, |d| d.bg(rgb(SELECTED))) | 4951 | + .flex_none() |
| 3941 | - .when_some(format, |d, format| { | 4952 | + .items_center() |
| 3942 | - d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | 4953 | + .gap(px(8.)) |
| 3943 | - this.set_format(format); | 4954 | + .child(div().w(px(10.)).child(match picked { |
| 3944 | - cx.notify(); | 4955 | + true => "✓", |
| 4956 | + false => " ", | ||
| 3945 | })) | 4957 | })) |
| 3946 | - }) | 4958 | + .child( |
| 3947 | - .child(label) | 4959 | + div() |
| 3948 | - .child( | 4960 | + .w(px(EXPORT_KEY_W)) |
| 3949 | - div() | 4961 | + .text_size(px(11.)) |
| 3950 | - .text_size(px(11.)) | 4962 | + .text_color(rgb(ink)) |
| 3951 | - .text_color(rgb(INK_DIM)) | 4963 | + .child(SharedString::from(key.to_string())), |
| 3952 | - .child(detail), | 4964 | + ) |
| 4965 | + .child(label), | ||
| 4966 | + ) | ||
| 4967 | + // Wraps rather than runs off the row: a refusal is the longest | ||
| 4968 | + // thing in this column and the half of it past the edge is the | ||
| 4969 | + // half that says what to do instead. | ||
| 4970 | + .child( | ||
| 4971 | + div() | ||
| 4972 | + .min_w(px(0.)) | ||
| 4973 | + .flex_shrink() | ||
| 4974 | + .text_size(px(11.)) | ||
| 4975 | + .text_color(rgb(ink)) | ||
| 4976 | + .child(detail), | ||
| 4977 | + ) | ||
| 4978 | + }; | ||
| 4979 | + let header = |text: &'static str| { | ||
| 4980 | + div() | ||
| 4981 | + .flex_none() | ||
| 4982 | + .px(px(6.)) | ||
| 4983 | + .pt(px(4.)) | ||
| 4984 | + .text_size(px(10.)) | ||
| 4985 | + .text_color(rgb(INK_DIM)) | ||
| 4986 | + .child(text) | ||
| 4987 | + .into_any_element() | ||
| 4988 | + }; | ||
| 4989 | + let mut list: Vec<AnyElement> = Vec::new(); | ||
| 4990 | + if self.export_grouped { | ||
| 4991 | + list.push(header("FORMAT")); | ||
| 4992 | + } | ||
| 4993 | + // The codecs first: which one is being written decides whether every | ||
| 4994 | + // row under it means anything. One a *this* timeline cannot be written | ||
| 4995 | + // as (an audio-only edit, for a picture codec) reads exactly like one | ||
| 4996 | + // there is no encoder for -- dimmed, unclickable, and carrying its own | ||
| 4997 | + // reason where its detail was, with nothing to click to find that out. | ||
| 4998 | + let mut refusals: Vec<String> = Vec::new(); | ||
| 4999 | + for (i, (boxes, key, label, detail)) in FORMATS.into_iter().enumerate() { | ||
| 5000 | + let format = same_box(boxes, self.format); | ||
| 5001 | + let refused = format | ||
| 5002 | + .zip(self.session.as_ref()) | ||
| 5003 | + .and_then(|(f, s)| format_refusal(s, f)); | ||
| 5004 | + // A codec with no encoder here at all is the other kind of refusal, | ||
| 5005 | + // and the one the footer collects: it can never become pickable, so | ||
| 5006 | + // a row each is dead rows above the fold. | ||
| 5007 | + if format.is_none() { | ||
| 5008 | + refusals.push(format!("{label} — {detail}")); | ||
| 5009 | + if !self.export_refusals_inline { | ||
| 5010 | + continue; | ||
| 5011 | + } | ||
| 5012 | + } | ||
| 5013 | + let detail: SharedString = match &refused { | ||
| 5014 | + Some(why) => why.clone().into(), | ||
| 5015 | + None => detail.into(), | ||
| 5016 | + }; | ||
| 5017 | + let format = format.filter(|_| refused.is_none()); | ||
| 5018 | + let mut r = entry( | ||
| 5019 | + ("format", i), | ||
| 5020 | + key, | ||
| 5021 | + label.into(), | ||
| 5022 | + detail, | ||
| 5023 | + boxes.contains(&self.format), | ||
| 5024 | + format.is_some(), | ||
| 5025 | + ); | ||
| 5026 | + if let Some(format) = format { | ||
| 5027 | + r = r.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | ||
| 5028 | + this.set_format(format); | ||
| 5029 | + cx.notify(); | ||
| 5030 | + })); | ||
| 5031 | + } | ||
| 5032 | + list.push(r.into_any_element()); | ||
| 5033 | + } | ||
| 5034 | + if self.export_grouped { | ||
| 5035 | + list.push(header("DETAILS")); | ||
| 5036 | + } | ||
| 5037 | + // The container, and only where the picked codec has more than one box: | ||
| 5038 | + // a row offering a single choice reads as a choice. | ||
| 5039 | + let boxes = containers(self.format); | ||
| 5040 | + if boxes.len() > 1 { | ||
| 5041 | + let next = next_container(self.format); | ||
| 5042 | + list.push( | ||
| 5043 | + entry( | ||
| 5044 | + ("container", 0), | ||
| 5045 | + "c", | ||
| 5046 | + "Container".into(), | ||
| 5047 | + format!( | ||
| 5048 | + "{} — c for {}", | ||
| 5049 | + self.format.ext().to_uppercase(), | ||
| 5050 | + next.ext().to_uppercase() | ||
| 3953 | ) | 5051 | ) |
| 3954 | - }) | 5052 | + .into(), |
| 3955 | - .collect(); | 5053 | + false, |
| 3956 | - let video = self.format.has_video(); | 5054 | + true, |
| 3957 | - let rows: Vec<_> = Quality::ALL | 5055 | + ) |
| 3958 | - .into_iter() | 5056 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { |
| 3959 | - .enumerate() | 5057 | + this.cycle_container(); |
| 3960 | - .map(|(i, quality)| { | 5058 | + cx.notify(); |
| 3961 | - live(row(("quality", i)), video) | 5059 | + })) |
| 3962 | - .when(video && self.quality == quality, |d| d.bg(rgb(SELECTED))) | 5060 | + .into_any_element(), |
| 3963 | - .when(video, |d| { | 5061 | + ); |
| 3964 | - d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { | 5062 | + } |
| 5063 | + match bitrate_refusal(self.format) { | ||
| 5064 | + // One dimmed row carrying the reason, rather than five rows of a | ||
| 5065 | + // figure that will not be written: the quality rows are the | ||
| 5066 | + // *picture's* bitrate, and this file has no picture in it. | ||
| 5067 | + Some(why) => list.push( | ||
| 5068 | + entry( | ||
| 5069 | + ("quality", 0), | ||
| 5070 | + "q", | ||
| 5071 | + "Quality".into(), | ||
| 5072 | + why.into(), | ||
| 5073 | + false, | ||
| 5074 | + false, | ||
| 5075 | + ) | ||
| 5076 | + .into_any_element(), | ||
| 5077 | + ), | ||
| 5078 | + None => { | ||
| 5079 | + for (i, quality) in Quality::ALL.into_iter().enumerate() { | ||
| 5080 | + let mut r = entry( | ||
| 5081 | + ("quality", i), | ||
| 5082 | + match quality { | ||
| @@ -35,7 +35,8 @@ use cros_codecs::encoder::{ | |||
| 35 | }; | 35 | }; |
| 36 | use cros_codecs::image_processing::nv12_to_i420; | 36 | use cros_codecs::image_processing::nv12_to_i420; |
| 37 | use cros_codecs::libva::{ | 37 | use cros_codecs::libva::{ |
| 38 | - Display, Image, Surface, VA_FOURCC_NV12, VAEntrypoint, VAImageFormat, VAProfile, | 38 | + Display, Image, Surface, VA_FOURCC_NV12, VA_FOURCC_P010, VAEntrypoint, VAImageFormat, |
| 39 | + VAProfile, | ||
| 39 | }; | 40 | }; |
| 40 | use cros_codecs::video_frame::VideoFrame; | 41 | use cros_codecs::video_frame::VideoFrame; |
| 41 | use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame}; | 42 | use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame}; |
| @@ -58,11 +59,16 @@ type Handle = <Dec<H264> as StatelessVideoDecoder>::Handle; | |||
| 58 | /// still loads and still decodes H.264 (it simply refuses the newer codecs' | 59 | /// still loads and still decodes H.264 (it simply refuses the newer codecs' |
| 59 | /// files at `Demuxer`). | 60 | /// files at `Demuxer`). |
| 60 | /// | 61 | /// |
| 61 | -/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0, HEVC Main, AV1 Main. VP9 | 62 | +/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0, AV1 Main. |
| 62 | -/// profile 2, HEVC Main 10 and AV1 Professional decode 10-bit, which the NV12 | 63 | +/// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit |
| 63 | -/// pool and the `vaGetImage` read-back here cannot carry (`Demuxer` refuses | 64 | +/// I420 every frame here is ([`Session::emit`]). |
| 64 | -/// both HEVC Main 10 and 10-bit AV1 by name); the upgrade path is a P010 pool | 65 | +/// |
| 65 | -/// selected from the stream info. | 66 | +/// ponytail: 10-bit is *carried* 8-bit, because [`VhFrame`] is a byte-per-sample |
| 67 | +/// interface all the way to the renderer. That costs the low two bits of a Main | ||
| 68 | +/// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every | ||
| 69 | +/// stage between here and the texture upload, not to this file. | ||
| 70 | +/// VP9 profile 2 and 10-bit AV1 are still refused by `Demuxer`: neither codec | ||
| 71 | +/// states its depth where this reads it. | ||
| 66 | enum Decoder { | 72 | enum Decoder { |
| 67 | H264(Dec<H264>), | 73 | H264(Dec<H264>), |
| 68 | Hevc(Dec<H265>), | 74 | Hevc(Dec<H265>), |
| @@ -97,8 +103,12 @@ const STALL_LIMIT: u32 = 10_000; | |||
| 97 | 103 | ||
| 98 | struct Session { | 104 | struct Session { |
| 99 | decoder: Decoder, | 105 | decoder: Decoder, |
| 100 | - /// NV12 descriptor for `vaGetImage`, queried once at open. | 106 | + /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`, |
| 107 | + /// queried once at open. | ||
| 101 | nv12_format: VAImageFormat, | 108 | nv12_format: VAImageFormat, |
| 109 | + /// Whether the surfaces are P010 rather than NV12, which is the one thing | ||
| 110 | + /// the read-back has to do differently. | ||
| 111 | + ten_bit: bool, | ||
| 102 | pool: FramePool<GenericDmaVideoFrame>, | 112 | pool: FramePool<GenericDmaVideoFrame>, |
| 103 | demuxer: Demuxer, | 113 | demuxer: Demuxer, |
| 104 | meta: VhMeta, | 114 | meta: VhMeta, |
| @@ -122,23 +132,35 @@ struct Session { | |||
| 122 | /// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object | 132 | /// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object |
| 123 | /// with two planes at known offsets, which is exactly what the descriptor in | 133 | /// with two planes at known offsets, which is exactly what the descriptor in |
| 124 | /// `GenericDmaVideoFrame` emits. | 134 | /// `GenericDmaVideoFrame` emits. |
| 135 | +/// | ||
| 136 | +/// `ten_bit` asks for the same thing in P010: the very same two-plane 4:2:0 | ||
| 137 | +/// shape with 16-bit samples, so the buffer is simply twice as wide. | ||
| 125 | fn alloc_nv12( | 138 | fn alloc_nv12( |
| 126 | gbm: &gbm::Device<std::fs::File>, | 139 | gbm: &gbm::Device<std::fs::File>, |
| 127 | coded: Resolution, | 140 | coded: Resolution, |
| 141 | + ten_bit: bool, | ||
| 128 | ) -> Result<GenericDmaVideoFrame, String> { | 142 | ) -> Result<GenericDmaVideoFrame, String> { |
| 129 | let rows = coded.height + coded.height.div_ceil(2); | 143 | let rows = coded.height + coded.height.div_ceil(2); |
| 144 | + let width = coded.width * if ten_bit { 2 } else { 1 }; | ||
| 130 | let bo = gbm | 145 | let bo = gbm |
| 131 | - .create_buffer_object::<()>(coded.width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR) | 146 | + .create_buffer_object::<()>(width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR) |
| 132 | - .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?; | 147 | + .map_err(|e| format!("gbm R8 {width}x{rows} allocation failed: {e}"))?; |
| 133 | let pitch = bo.stride().map_err(|e| e.to_string())? as usize; | 148 | let pitch = bo.stride().map_err(|e| e.to_string())? as usize; |
| 134 | let fd = bo.fd().map_err(|e| e.to_string())?; | 149 | let fd = bo.fd().map_err(|e| e.to_string())?; |
| 135 | - GenericDmaVideoFrame::new(vec![std::fs::File::from(fd)], nv12_layout(coded, pitch)) | 150 | + GenericDmaVideoFrame::new( |
| 151 | + vec![std::fs::File::from(fd)], | ||
| 152 | + nv12_layout(coded, pitch, ten_bit), | ||
| 153 | + ) | ||
| 136 | } | 154 | } |
| 137 | 155 | ||
| 138 | -/// Two NV12 planes packed one after the other in a single buffer object. | 156 | +/// Two NV12 (or P010) planes packed one after the other in a single buffer |
| 139 | -fn nv12_layout(coded: Resolution, pitch: usize) -> FrameLayout { | 157 | +/// object. |
| 158 | +fn nv12_layout(coded: Resolution, pitch: usize, ten_bit: bool) -> FrameLayout { | ||
| 140 | FrameLayout { | 159 | FrameLayout { |
| 141 | - format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */), | 160 | + format: ( |
| 161 | + Fourcc::from(if ten_bit { b"P010" } else { b"NV12" }), | ||
| 162 | + 0, /* DRM_FORMAT_MOD_LINEAR */ | ||
| 163 | + ), | ||
| 142 | size: coded, | 164 | size: coded, |
| 143 | planes: vec![ | 165 | planes: vec![ |
| 144 | PlaneLayout { | 166 | PlaneLayout { |
| @@ -186,11 +208,21 @@ impl Session { | |||
| 186 | fn open(path: &Path) -> Option<Self> { | 208 | fn open(path: &Path) -> Option<Self> { |
| 187 | let (meta, demuxer) = Demuxer::open(path).ok()?; | 209 | let (meta, demuxer) = Demuxer::open(path).ok()?; |
| 188 | let (display, gbm) = open_devices()?; | 210 | let (display, gbm) = open_devices()?; |
| 211 | + // A 10-bit stream decodes into P010 surfaces and is read back through a | ||
| 212 | + // P010 image; a driver that has no such image format is one this cannot | ||
| 213 | + // read 10-bit off at all, which is a null session and a software | ||
| 214 | + // fallback like any other refusal here. | ||
| 215 | + let ten_bit = demuxer.bit_depth() > 8; | ||
| 216 | + let want = if ten_bit { | ||
| 217 | + VA_FOURCC_P010 | ||
| 218 | + } else { | ||
| 219 | + VA_FOURCC_NV12 | ||
| 220 | + }; | ||
| 189 | let nv12_format = display | 221 | let nv12_format = display |
| 190 | .query_image_formats() | 222 | .query_image_formats() |
| 191 | .ok()? | 223 | .ok()? |
| 192 | .into_iter() | 224 | .into_iter() |
| 193 | - .find(|f| f.fourcc == VA_FOURCC_NV12)?; | 225 | + .find(|f| f.fourcc == want)?; |
| 194 | let decoder = match meta.codec { | 226 | let decoder = match meta.codec { |
| 195 | Codec::H264 => { | 227 | Codec::H264 => { |
| 196 | Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?) | 228 | Decoder::H264(Dec::<H264>::new_vaapi(display, BlockingMode::Blocking).ok()?) |
| @@ -206,11 +238,12 @@ impl Session { | |||
| 206 | } | 238 | } |
| 207 | }; | 239 | }; |
| 208 | let pool = FramePool::new(move |info: &StreamInfo| { | 240 | let pool = FramePool::new(move |info: &StreamInfo| { |
| 209 | - alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed") | 241 | + alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed") |
| 210 | }); | 242 | }); |
| 211 | Some(Self { | 243 | Some(Self { |
| 212 | decoder, | 244 | decoder, |
| 213 | nv12_format, | 245 | nv12_format, |
| 246 | + ten_bit, | ||
| 214 | pool, | 247 | pool, |
| 215 | demuxer, | 248 | demuxer, |
| 216 | meta: VhMeta { | 249 | meta: VhMeta { |
| @@ -350,6 +383,20 @@ impl Session { | |||
| 350 | 383 | ||
| 351 | let (dst_y, rest) = self.out.split_at_mut(self.luma); | 384 | let (dst_y, rest) = self.out.split_at_mut(self.luma); |
| 352 | let (dst_u, dst_v) = rest.split_at_mut(self.chroma); | 385 | let (dst_u, dst_v) = rest.split_at_mut(self.chroma); |
| 386 | + if self.ten_bit { | ||
| 387 | + p010_to_i420( | ||
| 388 | + &data[va.offsets[Y_PLANE] as usize..], | ||
| 389 | + va.pitches[Y_PLANE] as usize, | ||
| 390 | + dst_y, | ||
| 391 | + &data[va.offsets[UV_PLANE] as usize..], | ||
| 392 | + va.pitches[UV_PLANE] as usize, | ||
| 393 | + dst_u, | ||
| 394 | + dst_v, | ||
| 395 | + w, | ||
| 396 | + h, | ||
| 397 | + ); | ||
| 398 | + return; | ||
| 399 | + } | ||
| 353 | nv12_to_i420( | 400 | nv12_to_i420( |
| 354 | &data[va.offsets[Y_PLANE] as usize..], | 401 | &data[va.offsets[Y_PLANE] as usize..], |
| 355 | va.pitches[Y_PLANE] as usize, | 402 | va.pitches[Y_PLANE] as usize, |
| @@ -383,6 +430,43 @@ impl Session { | |||
| 383 | } | 430 | } |
| 384 | } | 431 | } |
| 385 | 432 | ||
| 433 | +/// One P010 picture down to packed 8-bit I420: [`nv12_to_i420`] for a surface | ||
| 434 | +/// whose samples are 16-bit little-endian with the value in the **high** bits, | ||
| 435 | +/// which is what P010 means. The high byte of each pair is therefore the 10-bit | ||
| 436 | +/// sample shifted down by two, i.e. the 8-bit one -- no rounding, because a | ||
| 437 | +/// second read of the low byte costs more than the half-bit it would buy. | ||
| 438 | +fn p010_to_i420( | ||
| 439 | + src_y: &[u8], | ||
| 440 | + src_y_pitch: usize, | ||
| 441 | + dst_y: &mut [u8], | ||
| 442 | + src_uv: &[u8], | ||
| 443 | + src_uv_pitch: usize, | ||
| 444 | + dst_u: &mut [u8], | ||
| 445 | + dst_v: &mut [u8], | ||
| 446 | + width: usize, | ||
| 447 | + height: usize, | ||
| 448 | +) { | ||
| 449 | + for row in 0..height { | ||
| 450 | + let src = &src_y[row * src_y_pitch..]; | ||
| 451 | + let dst = &mut dst_y[row * width..row * width + width]; | ||
| 452 | + for (x, out) in dst.iter_mut().enumerate() { | ||
| 453 | + *out = src[2 * x + 1]; | ||
| 454 | + } | ||
| 455 | + } | ||
| 456 | + let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); | ||
| 457 | + for row in 0..ch { | ||
| 458 | + let src = &src_uv[row * src_uv_pitch..]; | ||
| 459 | + let (u, v) = ( | ||
| 460 | + &mut dst_u[row * cw..row * cw + cw], | ||
| 461 | + &mut dst_v[row * cw..row * cw + cw], | ||
| 462 | + ); | ||
| 463 | + for x in 0..cw { | ||
| 464 | + u[x] = src[4 * x + 1]; | ||
| 465 | + v[x] = src[4 * x + 3]; | ||
| 466 | + } | ||
| 467 | + } | ||
| 468 | +} | ||
| 469 | + | ||
| 386 | /// Opens `path` for hardware decode, positioned so the first | 470 | /// Opens `path` for hardware decode, positioned so the first |
| 387 | /// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean | 471 | /// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean |
| 388 | /// the start of the stream). Returns null on any failure at all: no libva | 472 | /// the start of the stream). Returns null on any failure at all: no libva |
| @@ -657,8 +741,8 @@ impl EncSession { | |||
| 657 | }; | 741 | }; |
| 658 | // Allocated at the aligned size, so the buffer's pitch is never smaller | 742 | // Allocated at the aligned size, so the buffer's pitch is never smaller |
| 659 | // than a padded row. | 743 | // than a padded row. |
| 660 | - let frame = alloc_nv12(&gbm, coded).ok()?; | 744 | + let frame = alloc_nv12(&gbm, coded, false).ok()?; |
| 661 | - let layout = nv12_layout(coded, frame.get_plane_pitch()[0]); | 745 | + let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false); |
| 662 | Some(Self { | 746 | Some(Self { |
| 663 | encoder, | 747 | encoder, |
| 664 | h264: !av1, | 748 | h264: !av1, |
| @@ -23,12 +23,31 @@ image = { version = "0.25", default-features = false, features = [ | |||
| 23 | ] } | 23 | ] } |
| 24 | mp4 = "0.14" | 24 | mp4 = "0.14" |
| 25 | rusty_h264 = { version = "0.8", default-features = false } | 25 | rusty_h264 = { version = "0.8", default-features = false } |
| 26 | +# Both halves of AAC, and the only crate here that is asked for both. The | ||
| 27 | +# *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or | ||
| 28 | +# otherwise processed) lane has to be decoded, and what is decoded has to be | ||
| 29 | +# encoded again. The *decoder*, because symphonia's own refuses anything wider | ||
| 30 | +# than stereo outright (`aac/mod.rs:93`, "aac: aac too complex") and a 5.1 film | ||
| 31 | +# soundtrack in an mkv is exactly that -- this one hands 5.1 back already | ||
| 32 | +# reordered into FL, FR, FC, LFE, BL, BR, which is the order the downmix in | ||
| 33 | +# `audio` folds. Pure Rust with no C or FFI, Apache-2.0, same family as | ||
| 34 | +# `rusty_h264` above. Nothing else in the ecosystem encodes AAC without linking | ||
| 35 | +# Fraunhofer's C library, which this project's no-install rule forbids. Built | ||
| 36 | +# from `vendor/rusty_aac` -- see the patch table in the workspace manifest. | ||
| 37 | +rusty_aac = "0.5" | ||
| 38 | +# The MP3 encoder, so that format is a row a user can pick rather than a licence | ||
| 39 | +# note: pure Rust, Apache-2.0, CBR and VBR. The decoder side of mp3 is | ||
| 40 | +# symphonia's below -- an mp3 has always been importable here, and until this it | ||
| 41 | +# was the one format the editor could read and never write. | ||
| 42 | +rusty_mp3 = "0.6" | ||
| 26 | symphonia-core = "0.6" | 43 | symphonia-core = "0.6" |
| 27 | symphonia-codec-aac = "0.6" | 44 | symphonia-codec-aac = "0.6" |
| 28 | # The umbrella crate for the standalone audio files: one dependency instead of | 45 | # The umbrella crate for the standalone audio files: one dependency instead of |
| 29 | # seven, and its `default::get_probe`/`get_codecs` are the registries this would | 46 | # seven, and its `default::get_probe`/`get_codecs` are the registries this would |
| 30 | # otherwise hand-build. Explicit feature list rather than the default one -- no | 47 | # otherwise hand-build. Explicit feature list rather than the default one -- no |
| 31 | -# mkv, no ape, no adpcm: what is listed here is exactly what `is_audio` admits. | 48 | +# ape, no adpcm: what is listed here is exactly what `is_audio` admits, plus |
| 49 | +# `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of | ||
| 50 | +# a Matroska video file is read, the picture having its own demuxer here. | ||
| 32 | # There is no opus/ac3/dts feature at any symphonia version, which is why those | 51 | # There is no opus/ac3/dts feature at any symphonia version, which is why those |
| 33 | # are refused rather than promised. | 52 | # are refused rather than promised. |
| 34 | symphonia = { version = "0.6", default-features = false, features = [ | 53 | symphonia = { version = "0.6", default-features = false, features = [ |
| @@ -38,6 +57,7 @@ symphonia = { version = "0.6", default-features = false, features = [ | |||
| 38 | "id3v1", | 57 | "id3v1", |
| 39 | "id3v2", | 58 | "id3v2", |
| 40 | "isomp4", | 59 | "isomp4", |
| 60 | + "mkv", | ||
| 41 | "mp3", | 61 | "mp3", |
| 42 | "ogg", | 62 | "ogg", |
| 43 | "pcm", | 63 | "pcm", |
| @@ -54,6 +74,14 @@ oxideav-core = "0.1.34" | |||
| 54 | # inside rav1e itself and is what keeps an export minutes rather than tens of | 74 | # inside rav1e itself and is what keeps an export minutes rather than tens of |
| 55 | # minutes; the cost of no assembly is measured in `export::Enc::open_av1`. | 75 | # minutes; the cost of no assembly is measured in `export::Enc::open_av1`. |
| 56 | rav1e = { version = "0.8.1", default-features = false, features = ["threading"] } | 76 | rav1e = { version = "0.8.1", default-features = false, features = ["threading"] } |
| 77 | +# The software HEVC encoder, intra-only: OxideAV's pure-Rust H.265, MIT, no C | ||
| 78 | +# and no FFI like everything else here. Its *inter* modes run at 0.81 fps on | ||
| 79 | +# 1080p across 12 cores (measured 2026-08-11) and are therefore not an export | ||
| 80 | +# anyone would wait for; its intra AU is a stateless free function that fans out | ||
| 81 | +# across cores at 4.30 fps for the same picture, which is the export this | ||
| 82 | +# project offers -- an intraframe master, ProRes-shaped, large files and all. | ||
| 83 | +# Built from `vendor/oxideav-h265`; see the note in the workspace manifest. | ||
| 84 | +oxideav-h265 = { path = "../../vendor/oxideav-h265" } | ||
| 57 | 85 | ||
| 58 | [dev-dependencies] | 86 | [dev-dependencies] |
| 59 | # The still-image suite compares what the timeline shows against the file's own | 87 | # The still-image suite compares what the timeline shows against the file's own |
| @@ -6,7 +6,9 @@ | |||
| 6 | //! it always has -- that path also yields the raw access units the export | 6 | //! it always has -- that path also yields the raw access units the export |
| 7 | //! copies, which is the only reason it is kept separate -- and a standalone | 7 | //! copies, which is the only reason it is kept separate -- and a standalone |
| 8 | //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through | 8 | //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through |
| 9 | -//! symphonia's own format probe. An mp4's **AC-3** track is the third: the same | 9 | +//! symphonia's own format probe, as does the AAC track of a **Matroska** file: |
| 10 | +//! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to | ||
| 11 | +//! stereo on the way out ([`SymDecoder`]). An mp4's **AC-3** track is the third: the same | ||
| 10 | //! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the | 12 | //! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the |
| 11 | //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo | 13 | //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo |
| 12 | //! timeline. Everything downstream of [`Track`] sees the | 14 | //! timeline. Everything downstream of [`Track`] sees the |
| @@ -48,6 +50,7 @@ use symphonia_core::units; | |||
| 48 | use symphonia_core::units::{Time, TimeBase}; | 50 | use symphonia_core::units::{Time, TimeBase}; |
| 49 | 51 | ||
| 50 | use crate::eq::{EqParams, EqState}; | 52 | use crate::eq::{EqParams, EqState}; |
| 53 | +use crate::limiter::{Limiter, LimiterState}; | ||
| 51 | 54 | ||
| 52 | /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. | 55 | /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. |
| 53 | /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) | 56 | /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) |
| @@ -268,14 +271,23 @@ impl AudioSession { | |||
| 268 | eqs: &[Option<EqParams>], | 271 | eqs: &[Option<EqParams>], |
| 269 | speeds: &[Option<crate::project::Stretch>], | 272 | speeds: &[Option<crate::project::Stretch>], |
| 270 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 273 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 271 | - let Some((path, stream)) = sources.first() else { | 274 | + // The first source that could have a track, which is not always index 0: |
| 275 | + // a still image has none, and one at the front of the list (a save | ||
| 276 | + // renumbers, a library removal moves indexes) would be opened as a | ||
| 277 | + // broken audio file and take the whole timeline's sound down with it. | ||
| 278 | + // The same rule `PlaybackSession` probes by (`audio_source_of`). | ||
| 279 | + let Some((at, (path, stream))) = sources | ||
| 280 | + .iter() | ||
| 281 | + .enumerate() | ||
| 282 | + .find(|(_, (path, _))| !crate::is_image(path)) | ||
| 283 | + else { | ||
| 272 | return Ok(None); | 284 | return Ok(None); |
| 273 | }; | 285 | }; |
| 274 | let Some(first) = Track::open(path, *stream)? else { | 286 | let Some(first) = Track::open(path, *stream)? else { |
| 275 | return Ok(None); | 287 | return Ok(None); |
| 276 | }; | 288 | }; |
| 277 | - // The timeline's meta is the first source's: policy makes every other | 289 | + // The timeline's meta is that source's: policy makes every other source |
| 278 | - // source match it, and the checks below hold them to that. | 290 | + // match it, and the checks below hold them to that. |
| 279 | let meta = AudioMeta { | 291 | let meta = AudioMeta { |
| 280 | sample_rate: first.sample_rate(), | 292 | sample_rate: first.sample_rate(), |
| 281 | channels: first.channels()?, | 293 | channels: first.channels()?, |
| @@ -286,7 +298,7 @@ impl AudioSession { | |||
| 286 | first.check_decoder()?; | 298 | first.check_decoder()?; |
| 287 | 299 | ||
| 288 | let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); | 300 | let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect(); |
| 289 | - tracks[0] = Some(first); | 301 | + tracks[at] = Some(first); |
| 290 | for &(source, ..) in segs { | 302 | for &(source, ..) in segs { |
| 291 | let Some(source) = source else { | 303 | let Some(source) = source else { |
| 292 | continue; // a gap opens no file | 304 | continue; // a gap opens no file |
| @@ -442,11 +454,41 @@ impl AudioSession { | |||
| 442 | lanes: &[Vec<(Option<usize>, f64, f64)>], | 454 | lanes: &[Vec<(Option<usize>, f64, f64)>], |
| 443 | eqs: &[Vec<Option<EqParams>>], | 455 | eqs: &[Vec<Option<EqParams>>], |
| 444 | speeds: &[Vec<Option<crate::project::Stretch>>], | 456 | speeds: &[Vec<Option<crate::project::Stretch>>], |
| 457 | + ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | ||
| 458 | + Self::open_mixed_streams_master(sources, lanes, eqs, speeds, &[], Limiter::default()) | ||
| 459 | + } | ||
| 460 | + | ||
| 461 | + /// [`open_mixed_streams_speed`](Self::open_mixed_streams_speed) with the two | ||
| 462 | + /// settings that belong to the *mix* rather than to a clip: what each lane | ||
| 463 | + /// is turned up or down by on its way into the sum (`gains[i]`, an | ||
| 464 | + /// amplitude, [`crate::Project::audio_gains`] builds it) and the master | ||
| 465 | + /// limiter the sum comes out through. | ||
| 466 | + /// | ||
| 467 | + /// Both live at the sum and nowhere else, which is what makes a lane volume | ||
| 468 | + /// a *lane* volume and a limiter a master one: a gain applied per segment | ||
| 469 | + /// would have to agree with itself across a lane's cuts, and a limiter | ||
| 470 | + /// applied per lane would pump each lane against the others. A short or | ||
| 471 | + /// empty gain list means the rest play as they are, exactly as a short eq | ||
| 472 | + /// list means flat. | ||
| 473 | + /// | ||
| 474 | + /// Flat settings take the same path the mixer always took, down to the bit: | ||
| 475 | + /// one lane at unity with the limiter off is still `open_multi_streams` | ||
| 476 | + /// verbatim, with no mixer thread at all. A lane that is *not* at unity, or | ||
| 477 | + /// a limiter that is on, is what puts a single-lane timeline through the | ||
| 478 | + /// mixer -- a sum of one, which is where both settings live. | ||
| 479 | + pub fn open_mixed_streams_master( | ||
| 480 | + sources: &[(PathBuf, usize)], | ||
| 481 | + lanes: &[Vec<(Option<usize>, f64, f64)>], | ||
| 482 | + eqs: &[Vec<Option<EqParams>>], | ||
| 483 | + speeds: &[Vec<Option<crate::project::Stretch>>], | ||
| 484 | + gains: &[f32], | ||
| 485 | + limiter: Limiter, | ||
| 445 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 486 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 446 | let [first, rest @ ..] = lanes else { | 487 | let [first, rest @ ..] = lanes else { |
| 447 | return Ok(None); | 488 | return Ok(None); |
| 448 | }; | 489 | }; |
| 449 | - if rest.is_empty() { | 490 | + let mastered = limiter.is_active() || gains.iter().any(|&g| g != 1.0); |
| 491 | + if rest.is_empty() && !mastered { | ||
| 450 | let flat = Vec::new(); | 492 | let flat = Vec::new(); |
| 451 | let plain = Vec::new(); | 493 | let plain = Vec::new(); |
| 452 | return Self::open_multi_streams_speed( | 494 | return Self::open_multi_streams_speed( |
| @@ -459,8 +501,9 @@ impl AudioSession { | |||
| 459 | let mut meta = None; | 501 | let mut meta = None; |
| 460 | let mut rxs = Vec::with_capacity(lanes.len()); | 502 | let mut rxs = Vec::with_capacity(lanes.len()); |
| 461 | for (i, segs) in lanes.iter().enumerate() { | 503 | for (i, segs) in lanes.iter().enumerate() { |
| 462 | - // Every lane probes the same source 0, so the metas agree by | 504 | + // Every lane takes its meta from the same source, so the metas |
| 463 | - // construction; `None` from any of them is a silent timeline. | 505 | + // agree by construction; `None` from any of them is a silent |
| 506 | + // timeline. | ||
| 464 | let flat = Vec::new(); | 507 | let flat = Vec::new(); |
| 465 | let plain = Vec::new(); | 508 | let plain = Vec::new(); |
| 466 | let Some((lane_meta, rx)) = Self::open_multi_streams_speed( | 509 | let Some((lane_meta, rx)) = Self::open_multi_streams_speed( |
| @@ -475,12 +518,20 @@ impl AudioSession { | |||
| 475 | meta = Some(lane_meta); | 518 | meta = Some(lane_meta); |
| 476 | rxs.push(rx); | 519 | rxs.push(rx); |
| 477 | } | 520 | } |
| 478 | - let meta = meta.expect("at least two lanes opened above"); | 521 | + let meta = meta.expect("at least one lane opened above"); |
| 479 | let (tx, rx) = sync_channel(32); | 522 | let (tx, rx) = sync_channel(32); |
| 480 | let channels = usize::from(meta.channels); | 523 | let channels = usize::from(meta.channels); |
| 524 | + // One per lane, in the lanes' own order, padded with unity: a short | ||
| 525 | + // list is "as it is from here on", the eq list's rule. | ||
| 526 | + let mut gains = gains.to_vec(); | ||
| 527 | + gains.resize(lanes.len(), 1.0); | ||
| 528 | + // Built here, off the thread that will run it, where the rate is known. | ||
| 529 | + let limiter = limiter | ||
| 530 | + .is_active() | ||
| 531 | + .then(|| LimiterState::new(&limiter, meta.sample_rate, channels)); | ||
| 481 | thread::Builder::new() | 532 | thread::Builder::new() |
| 482 | .name("audio-mix".into()) | 533 | .name("audio-mix".into()) |
| 483 | - .spawn(move || mix(&rxs, channels, &tx))?; | 534 | + .spawn(move || mix(&rxs, channels, &gains, limiter, &tx))?; |
| 484 | Ok(Some((meta, rx))) | 535 | Ok(Some((meta, rx))) |
| 485 | } | 536 | } |
| 486 | 537 | ||
| @@ -490,14 +541,15 @@ impl AudioSession { | |||
| 490 | /// -- nothing to tell the user there. Header only, and only worth calling | 541 | /// -- nothing to tell the user there. Header only, and only worth calling |
| 491 | /// once the open has already returned no audio. | 542 | /// once the open has already returned no audio. |
| 492 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { | 543 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { |
| 493 | - // Matroska: the demuxer reads its picture and nothing else yet, so a | 544 | + // Matroska: AAC is read out of one ([`Track::open`]) and everything |
| 494 | - // file that has sound is told so by name rather than playing silent | 545 | + // else -- Opus, AC-3, DTS, none of which symphonia decodes at any |
| 495 | - // with no reason given. A Matroska file with no audio track at all | 546 | + // version -- is named rather than left playing silent with no reason |
| 496 | - // returns `None` here like any other silent file. | 547 | + // given. A Matroska file with no audio track at all returns `None` here |
| 548 | + // like any other silent file. | ||
| 497 | if crate::demux::is_matroska(path.as_ref()) { | 549 | if crate::demux::is_matroska(path.as_ref()) { |
| 498 | return Ok( | 550 | return Ok( |
| 499 | crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| { | 551 | crate::demux::matroska_audio_codec(path.as_ref())?.map(|codec| { |
| 500 | - format!("{codec} audio in a Matroska file is not wired to the decoder yet") | 552 | + format!("the {codec} track of this Matroska file cannot be decoded (AAC only)") |
| 501 | }), | 553 | }), |
| 502 | ); | 554 | ); |
| 503 | } | 555 | } |
| @@ -546,11 +598,22 @@ impl AudioSession { | |||
| 546 | /// and an ALAC `.m4a` only half is. | 598 | /// and an ALAC `.m4a` only half is. |
| 547 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { | 599 | pub fn probe_streams(path: impl AsRef<Path>) -> crate::Result<Vec<StreamInfo>> { |
| 548 | let path = path.as_ref(); | 600 | let path = path.as_ref(); |
| 549 | - // A Matroska file's audio tracks are not readable here yet ([`Track`]), | 601 | + // A Matroska file has exactly one readable audio stream here -- the |
| 550 | - // and a stream nothing can open is not one to offer: an mkv lists as | 602 | + // reader's default track ([`SymTrack::open`]) -- so it lists like a |
| 551 | - // the silent source it currently is. | 603 | + // standalone audio file rather than like an mp4, and one with no |
| 604 | + // readable track at all lists as the silent source it is. | ||
| 552 | if crate::demux::is_matroska(path) { | 605 | if crate::demux::is_matroska(path) { |
| 553 | - return Ok(Vec::new()); | 606 | + let Ok(track) = SymTrack::open(path) else { |
| 607 | + return Ok(Vec::new()); | ||
| 608 | + }; | ||
| 609 | + return Ok(vec![StreamInfo { | ||
| 610 | + index: 0, | ||
| 611 | + codec: track.codec.into(), | ||
| 612 | + channels: track.channels, | ||
| 613 | + sample_rate: track.sample_rate, | ||
| 614 | + lang: None, | ||
| 615 | + decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(), | ||
| 616 | + }]); | ||
| 554 | } | 617 | } |
| 555 | if crate::is_audio(path) { | 618 | if crate::is_audio(path) { |
| 556 | let track = SymTrack::open(path)?; | 619 | let track = SymTrack::open(path)?; |
| @@ -647,8 +710,9 @@ impl AudioSession { | |||
| 647 | /// The raw AAC packets covering `segs` — the same half-open source-second | 710 | /// The raw AAC packets covering `segs` — the same half-open source-second |
| 648 | /// windows [`open_segments`](Self::open_segments) decodes — copied out | 711 | /// windows [`open_segments`](Self::open_segments) decodes — copied out |
| 649 | /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go | 712 | /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go |
| 650 | - /// straight into an mp4 writer, which is the only way to keep audio in an | 713 | + /// straight into an mp4 writer, which is how an export keeps its sound exact |
| 651 | - /// export at all (no pure-Rust AAC encoder exists). | 714 | + /// wherever the edit lets it (a lane carrying an equalizer cannot be copied |
| 715 | + /// and is re-encoded instead -- `export::encode_audio`). | ||
| 652 | /// | 716 | /// |
| 653 | /// Cut points do not land on 1024-sample boundaries, so each segment is | 717 | /// Cut points do not land on 1024-sample boundaries, so each segment is |
| 654 | /// rounded to whole packets against an error carried across the joins (see | 718 | /// rounded to whole packets against an error carried across the joins (see |
| @@ -777,8 +841,9 @@ impl AudioSession { | |||
| 777 | } | 841 | } |
| 778 | 842 | ||
| 779 | /// One AAC-LC access unit of silence, for the gaps in an exported timeline — | 843 | /// One AAC-LC access unit of silence, for the gaps in an exported timeline — |
| 780 | -/// the export copies packets and has no AAC encoder, so the only silence it can | 844 | +/// this is the *copy* path, which never encodes anything, so the only silence it |
| 781 | -/// write is one spelled out by hand. | 845 | +/// can write is one spelled out by hand. (The re-encode path next door has a |
| 846 | +/// real encoder and needs none of this: its gaps are zero samples.) | ||
| 782 | /// | 847 | /// |
| 783 | /// It is the shortest legal `raw_data_block` there is: one element carrying | 848 | /// It is the shortest legal `raw_data_block` there is: one element carrying |
| 784 | /// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no | 849 | /// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no |
| @@ -823,30 +888,52 @@ fn source_at<'a>( | |||
| 823 | 888 | ||
| 824 | /// A source's track for the *copy* path, which needs raw AAC access units. | 889 | /// A source's track for the *copy* path, which needs raw AAC access units. |
| 825 | /// | 890 | /// |
| 826 | -/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by | 891 | +/// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name |
| 827 | -/// name and by format rather than exported silent or, worse, exported as noise: | 892 | +/// and by format. That is no longer the end of the road: `export::copy_audio` |
| 828 | -/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]), | 893 | +/// takes it as the answer "not copyable" and decodes and re-encodes the timeline |
| 829 | -/// so a timeline carrying one of those simply cannot become an mp4 today. The | 894 | +/// instead, so these words are a fallback's reason rather than a user's refusal. |
| 830 | -/// wording is what a front-end shows. | 895 | +/// They are still worded for a person, because a caller with no encoder to fall |
| 896 | +/// back on shows them verbatim. | ||
| 831 | /// | 897 | /// |
| 832 | /// `Ok(None)` for a file with no audio at all, which is a silent export. | 898 | /// `Ok(None)` for a file with no audio at all, which is a silent export. |
| 833 | fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> { | 899 | fn copy_track(path: &Path, stream: usize) -> crate::Result<Option<AacTrack>> { |
| 834 | match Track::open(path, stream)? { | 900 | match Track::open(path, stream)? { |
| 835 | None => Ok(None), | 901 | None => Ok(None), |
| 836 | Some(Track::Aac(track)) => Ok(Some(track)), | 902 | Some(Track::Aac(track)) => Ok(Some(track)), |
| 903 | + // A Matroska source gets its own words: its packets *are* AAC, so | ||
| 904 | + // "export needs AAC audio today" would read as a contradiction. What | ||
| 905 | + // they are not is packets of an mp4 sample table, which is what the | ||
| 906 | + // copy walks. The export decodes such a source and encodes it again | ||
| 907 | + // rather than showing this, so a film's sound reaches an mp4 either way; | ||
| 908 | + // the words stay for a caller that copies and cannot re-encode. | ||
| 909 | + // | ||
| 910 | + // ponytail: the ceiling is the copy path being written against the mp4 | ||
| 911 | + // reader, not anything about the bytes. Upgrade path is a | ||
| 912 | + // `copy_segments` that walks a Matroska track, which would make this a | ||
| 913 | + // copy again instead of a re-encode. | ||
| 914 | + Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!( | ||
| 915 | + "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \ | ||
| 916 | + a copy walks an mp4's own sample table. It is decoded and encoded again \ | ||
| 917 | + instead", | ||
| 918 | + path.file_name() | ||
| 919 | + .unwrap_or(path.as_os_str()) | ||
| 920 | + .to_string_lossy(), | ||
| 921 | + ) | ||
| 922 | + .into()), | ||
| 837 | Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)), | 923 | Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)), |
| 838 | // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` | 924 | // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` |
| 839 | - // sample table can hold, and there is no AAC encoder here to turn it | 925 | + // sample table can hold. The export decodes it and encodes AAC, exactly |
| 840 | - // into one. A WAV/FLAC export of the same timeline decodes fine. | 926 | + // as it does for every other source no copy reaches. |
| 841 | Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), | 927 | Some(Track::Ac3(_)) => Err(uncopyable(path, "AC-3")), |
| 842 | } | 928 | } |
| 843 | } | 929 | } |
| 844 | 930 | ||
| 845 | -/// The one wording for "this source's audio cannot be copied into an mp4", | 931 | +/// The one wording for "this source's audio cannot be *copied* into an mp4", |
| 846 | -/// shared by every format that cannot be: a front-end shows it verbatim. | 932 | +/// shared by every format that cannot be. What the export does about it is |
| 933 | +/// decode and re-encode; this is the reason it had to. | ||
| 847 | fn uncopyable(path: &Path, codec: &str) -> crate::Error { | 934 | fn uncopyable(path: &Path, codec: &str) -> crate::Error { |
| 848 | format!( | 935 | format!( |
| 849 | - "export needs AAC audio today; {} is {codec}", | 936 | + "a packet copy needs AAC in an mp4; {} is {codec}", |
| 850 | path.file_name() | 937 | path.file_name() |
| 851 | .unwrap_or(path.as_os_str()) | 938 | .unwrap_or(path.as_os_str()) |
| 852 | .to_string_lossy(), | 939 | .to_string_lossy(), |
| @@ -878,11 +965,20 @@ impl Track { | |||
| 878 | /// has exactly one, so any `stream` above 0 there is a promise the file | 965 | /// has exactly one, so any `stream` above 0 there is a promise the file |
| 879 | /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. | 966 | /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. |
| 880 | fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { | 967 | fn open(path: &Path, stream: usize) -> crate::Result<Option<Self>> { |
| 881 | - // A Matroska file's sound is not wired to either reader yet: its picture | 968 | + // A Matroska file goes straight to symphonia, whose `mkv` reader is the |
| 882 | - // is what this slice delivers, and the source counts as a silent one -- | 969 | + // one thing here that reads its packets -- neither mp4 reader can open |
| 883 | - // which `AudioSession::unsupported` puts into words for the user. | 970 | + // the file at all. Sound this cannot decode (Opus, AC-3, DTS: symphonia |
| 971 | + // has no such decoder at any version) leaves the source the silent one | ||
| 972 | + // it always was, which `AudioSession::unsupported` puts into words, | ||
| 973 | + // rather than failing the import of a file whose picture is fine. | ||
| 884 | if crate::demux::is_matroska(path) { | 974 | if crate::demux::is_matroska(path) { |
| 885 | - return Ok(None); | 975 | + if stream > 0 { |
| 976 | + return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); | ||
| 977 | + } | ||
| 978 | + return Ok(SymTrack::open(path) | ||
| 979 | + .ok() | ||
| 980 | + .filter(|t| t.decoder().is_ok()) | ||
| 981 | + .map(Self::Sym)); | ||
| 886 | } | 982 | } |
| 887 | let audio_file = crate::is_audio(path); | 983 | let audio_file = crate::is_audio(path); |
| 888 | // Ahead of the AAC reader, because that one answers "not AAC" for a | 984 | // Ahead of the AAC reader, because that one answers "not AAC" for a |
| @@ -995,7 +1091,12 @@ struct SymTrack { | |||
| 995 | reader: Box<dyn FormatReader>, | 1091 | reader: Box<dyn FormatReader>, |
| 996 | track_id: u32, | 1092 | track_id: u32, |
| 997 | sample_rate: u32, | 1093 | sample_rate: u32, |
| 1094 | + /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track, | ||
| 1095 | + /// which is folded down by [`SymDecoder`] exactly as the AC-3 reader's | ||
| 1096 | + /// decoder folds its own. | ||
| 998 | channels: u16, | 1097 | channels: u16, |
| 1098 | + /// What the decoder emits, which is what the fold reads. | ||
| 1099 | + source_channels: u16, | ||
| 999 | /// Frames per channel of audible audio, `None` when the header does not say. | 1100 | /// Frames per channel of audible audio, `None` when the header does not say. |
| 1000 | total_samples: Option<u64>, | 1101 | total_samples: Option<u64>, |
| 1001 | /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the | 1102 | /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the |
| @@ -1050,7 +1151,11 @@ impl SymTrack { | |||
| 1050 | reader, | 1151 | reader, |
| 1051 | track_id, | 1152 | track_id, |
| 1052 | sample_rate, | 1153 | sample_rate, |
| 1053 | - channels, | 1154 | + // 5.1 arrives as a stereo source, whatever it was stored as; every |
| 1155 | + // other layout is passed through and refused above stereo by | ||
| 1156 | + // [`Track::channels`], where it always was. | ||
| 1157 | + channels: if channels == 6 { 2 } else { channels }, | ||
| 1158 | + source_channels: channels, | ||
| 1054 | total_samples: num_frames, | 1159 | total_samples: num_frames, |
| 1055 | priming: u64::from(delay.unwrap_or(0)), | 1160 | priming: u64::from(delay.unwrap_or(0)), |
| 1056 | time_base, | 1161 | time_base, |
| @@ -1061,9 +1166,28 @@ impl SymTrack { | |||
| 1061 | 1166 | ||
| 1062 | /// A fresh decoder: seeking mid-stream leaves state that belongs to the | 1167 | /// A fresh decoder: seeking mid-stream leaves state that belongs to the |
| 1063 | /// packets we skipped, exactly as on the AAC path. | 1168 | /// packets we skipped, exactly as on the AAC path. |
| 1064 | - fn decoder(&self) -> crate::Result<Box<dyn AudioDecoder>> { | 1169 | + /// |
| 1065 | - Ok(symphonia::default::get_codecs() | 1170 | + /// Which decoder is not the caller's business, and it is not always |
| 1066 | - .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?) | 1171 | + /// symphonia's: its AAC decoder refuses anything wider than stereo outright |
| 1172 | + /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track | ||
| 1173 | + /// of a film in an mkv, so that one goes to `rusty_aac` instead. | ||
| 1174 | + fn decoder(&self) -> crate::Result<SymDecoder> { | ||
| 1175 | + let fold = self.source_channels != self.channels; | ||
| 1176 | + if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 { | ||
| 1177 | + let asc = self | ||
| 1178 | + .params | ||
| 1179 | + .extra_data | ||
| 1180 | + .as_deref() | ||
| 1181 | + .ok_or("a multichannel AAC track with no AudioSpecificConfig")?; | ||
| 1182 | + let decoder = rusty_aac::AacDecoder::with_config_bytes(asc) | ||
| 1183 | + .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?; | ||
| 1184 | + return Ok(SymDecoder::Aac(Box::new(decoder), fold)); | ||
| 1185 | + } | ||
| 1186 | + Ok(SymDecoder::Sym( | ||
| 1187 | + symphonia::default::get_codecs() | ||
| 1188 | + .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?, | ||
| 1189 | + fold, | ||
| 1190 | + )) | ||
| 1067 | } | 1191 | } |
| 1068 | 1192 | ||
| 1069 | /// `secs` on this source's audible timeline into media samples (priming | 1193 | /// `secs` on this source's audible timeline into media samples (priming |
| @@ -1079,6 +1203,65 @@ impl SymTrack { | |||
| 1079 | } | 1203 | } |
| 1080 | } | 1204 | } |
| 1081 | 1205 | ||
| 1206 | +/// One packet in, interleaved f32 out — whichever library did the decoding, and | ||
| 1207 | +/// already folded to the layout [`SymTrack::channels`] promised. The flag is | ||
| 1208 | +/// that fold: `true` for a 5.1 track, and there is nothing else it can be. | ||
| 1209 | +enum SymDecoder { | ||
| 1210 | + Sym(Box<dyn AudioDecoder>, bool), | ||
| 1211 | + /// Boxed because the decoder carries its own IMDCT tables and this enum is | ||
| 1212 | + /// moved into the worker. | ||
| 1213 | + Aac(Box<rusty_aac::AacDecoder>, bool), | ||
| 1214 | +} | ||
| 1215 | + | ||
| 1216 | +impl SymDecoder { | ||
| 1217 | + fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> crate::Result<()> { | ||
| 1218 | + match self { | ||
| 1219 | + Self::Sym(decoder, fold) => { | ||
| 1220 | + decoder.decode(packet)?.copy_to_vec_interleaved::<f32>(out); | ||
| 1221 | + fold_5_1(out, *fold); | ||
| 1222 | + } | ||
| 1223 | + Self::Aac(decoder, fold) => { | ||
| 1224 | + let pcm = decoder | ||
| 1225 | + .decode(&packet.data, None) | ||
| 1226 | + .map_err(|e| format!("AAC decode failed: {e}"))?; | ||
| 1227 | + *out = pcm.samples; | ||
| 1228 | + fold_5_1(out, *fold); | ||
| 1229 | + } | ||
| 1230 | + } | ||
| 1231 | + Ok(()) | ||
| 1232 | + } | ||
| 1233 | +} | ||
| 1234 | + | ||
| 1235 | +/// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of | ||
| 1236 | +/// each side join that side at -3 dB, and the LFE is dropped -- it carries no | ||
| 1237 | +/// programme a stereo pair could put anywhere. Both outputs are divided by the | ||
| 1238 | +/// sum of their own coefficients, so a source at full scale cannot come out | ||
| 1239 | +/// clipped; that is what every player does by default. | ||
| 1240 | +/// | ||
| 1241 | +/// The layout is FL, FR, FC, LFE, BL, BR, which is what symphonia's decoders | ||
| 1242 | +/// and `rusty_aac` both hand back (the latter reorders AAC's own C, L, R, Ls, | ||
| 1243 | +/// Rs, LFE element order into it: `decode.rs:779`). | ||
| 1244 | +/// | ||
| 1245 | +/// ponytail: that normalisation costs 7.7 dB against what ffmpeg's `-ac 2` hands | ||
| 1246 | +/// out, which does not normalise and can overload -- so a film plays quieter | ||
| 1247 | +/// here than in a player beside it. It is the loudness the AC-3 5.1 path already | ||
| 1248 | +/// has (measured within 1.3 dB), so the two agree; the upgrade path is a | ||
| 1249 | +/// limiter on the output, at which point the coefficients can go back to 1.0. | ||
| 1250 | +fn fold_5_1(samples: &mut Vec<f32>, fold: bool) { | ||
| 1251 | + if !fold { | ||
| 1252 | + return; | ||
| 1253 | + } | ||
| 1254 | + const CENTRE: f32 = std::f32::consts::FRAC_1_SQRT_2; | ||
| 1255 | + const NORM: f32 = 1.0 / (1.0 + 2.0 * CENTRE); | ||
| 1256 | + for frame in 0..samples.len() / 6 { | ||
| 1257 | + let [fl, fr, fc, _lfe, bl, br] = <[f32; 6]>::try_from(&samples[frame * 6..frame * 6 + 6]) | ||
| 1258 | + .expect("six samples of a 5.1 frame"); | ||
| 1259 | + samples[2 * frame] = (fl + CENTRE * (fc + bl)) * NORM; | ||
| 1260 | + samples[2 * frame + 1] = (fr + CENTRE * (fc + br)) * NORM; | ||
| 1261 | + } | ||
| 1262 | + samples.truncate(samples.len() / 6 * 2); | ||
| 1263 | +} | ||
| 1264 | + | ||
| 1082 | /// One source's AC-3 track: the same mp4 sample tables the AAC track is read | 1265 | /// One source's AC-3 track: the same mp4 sample tables the AAC track is read |
| 1083 | /// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder | 1266 | /// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder |
| 1084 | /// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and | 1267 | /// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and |
| @@ -1711,7 +1894,13 @@ struct Worker { | |||
| 1711 | /// The accumulator is reused across turns; the one allocation per chunk is the | 1894 | /// The accumulator is reused across turns; the one allocation per chunk is the |
| 1712 | /// buffer the channel takes ownership of, and none of this is the RT path (the | 1895 | /// buffer the channel takes ownership of, and none of this is the RT path (the |
| 1713 | /// device callback reads the ring the feeder has already filled). | 1896 | /// device callback reads the ring the feeder has already filled). |
| 1714 | -fn mix(rxs: &[Receiver<AudioChunk>], channels: usize, tx: &SyncSender<AudioChunk>) { | 1897 | +fn mix( |
| 1898 | + rxs: &[Receiver<AudioChunk>], | ||
| 1899 | + channels: usize, | ||
| 1900 | + gains: &[f32], | ||
| 1901 | + mut limiter: Option<LimiterState>, | ||
| 1902 | + tx: &SyncSender<AudioChunk>, | ||
| 1903 | +) { | ||
| 1715 | let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect(); | 1904 | let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect(); |
| 1716 | let mut live: Vec<bool> = rxs.iter().map(|_| true).collect(); | 1905 | let mut live: Vec<bool> = rxs.iter().map(|_| true).collect(); |
| 1717 | // Numbering follows lane 0, whose first chunk says where it starts. | 1906 | // Numbering follows lane 0, whose first chunk says where it starts. |
| @@ -1746,11 +1935,31 @@ fn mix(rxs: &[Receiver<AudioChunk>], channels: usize, tx: &SyncSender<AudioChunk | |||
| 1746 | let block = frames * channels; | 1935 | let block = frames * channels; |
| 1747 | out.clear(); | 1936 | out.clear(); |
| 1748 | out.resize(block, 0.0); | 1937 | out.resize(block, 0.0); |
| 1749 | - for lane in pending.iter_mut().filter(|p| !p.is_empty()) { | 1938 | + for (i, lane) in pending |
| 1939 | + .iter_mut() | ||
| 1940 | + .enumerate() | ||
| 1941 | + .filter(|(_, p)| !p.is_empty()) | ||
| 1942 | + { | ||
| 1943 | + // The lane's own volume, applied on its way into the sum: this is | ||
| 1944 | + // the one place every lane's samples pass through, so a lane that | ||
| 1945 | + // is turned down is turned down in an export exactly as it is in | ||
| 1946 | + // the room. Unity is a multiply by 1.0, which f32 leaves alone. | ||
| 1947 | + let gain = gains.get(i).copied().unwrap_or(1.0); | ||
| 1750 | for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) { | 1948 | for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) { |
| 1751 | - *sum += sample; | 1949 | + *sum += sample * gain; |
| 1752 | } | 1950 | } |
| 1753 | } | 1951 | } |
| 1952 | + // ...and the master limiter over the sum, before the clamp: what the | ||
| 1953 | + // clamp used to catch by squaring it off is held under the ceiling | ||
| 1954 | + // here instead ([`crate::limiter`]). Off, this is not even a branch | ||
| 1955 | + // per sample. | ||
| 1956 | + if let Some(limiter) = limiter.as_mut() { | ||
| 1957 | + limiter.process(&mut out); | ||
| 1958 | + } | ||
| 1959 | + let frames = out.len() / channels; | ||
| 1960 | + if frames == 0 { | ||
| 1961 | + continue; // the limiter's delay line is still filling | ||
| 1962 | + } | ||
| 1754 | let chunk = AudioChunk { | 1963 | let chunk = AudioChunk { |
| 1755 | start_sample: base + emitted, | 1964 | start_sample: base + emitted, |
| 1756 | // Clamped, not wrapped: two lanes at full scale are what a mix has | 1965 | // Clamped, not wrapped: two lanes at full scale are what a mix has |
| @@ -2085,14 +2294,10 @@ fn run_sym( | |||
| 2085 | if pos >= seg.media_end { | 2294 | if pos >= seg.media_end { |
| 2086 | return true; // segment done, on to the next one | 2295 | return true; // segment done, on to the next one |
| 2087 | } | 2296 | } |
| 2088 | - let buf = match decoder.decode(&packet) { | 2297 | + if let Err(e) = decoder.decode(&packet, &mut interleaved) { |
| 2089 | - Ok(buf) => buf, | 2298 | + eprintln!("audio decode error at sample {pos}: {e}"); |
| 2090 | - Err(e) => { | 2299 | + return true; |
| 2091 | - eprintln!("audio decode error at sample {pos}: {e}"); | 2300 | + } |
| 2092 | - return true; | ||
| 2093 | - } | ||
| 2094 | - }; | ||
| 2095 | - buf.copy_to_vec_interleaved::<f32>(&mut interleaved); | ||
| 2096 | let next = pos + (interleaved.len() / channels) as u64; | 2301 | let next = pos + (interleaved.len() / channels) as u64; |
| 2097 | // Reborrowed per packet: the filter memory has to carry across the | 2302 | // Reborrowed per packet: the filter memory has to carry across the |
| 2098 | // packet boundary, so this is one `EqState` for the whole segment. | 2303 | // packet boundary, so this is one `EqState` for the whole segment. |
| @@ -2114,7 +2319,43 @@ fn run_sym( | |||
| 2114 | 2319 | ||
| 2115 | #[cfg(test)] | 2320 | #[cfg(test)] |
| 2116 | mod tests { | 2321 | mod tests { |
| 2117 | - use super::{PRE_ROLL, SAMPLES_PER_PACKET, packet_at, packet_run}; | 2322 | + use super::{PRE_ROLL, SAMPLES_PER_PACKET, fold_5_1, packet_at, packet_run}; |
| 2323 | + | ||
| 2324 | + /// The 5.1 fold: each side keeps its own front channel, takes the centre | ||
| 2325 | + /// and its own surround at -3 dB, drops the LFE, and comes out unable to | ||
| 2326 | + /// clip a full-scale source. The channel order is FL, FR, FC, LFE, BL, BR. | ||
| 2327 | + #[test] | ||
| 2328 | + fn five_one_folds_to_stereo_without_clipping() { | ||
| 2329 | + // One frame per channel at full scale, one channel at a time. | ||
| 2330 | + for (channel, (left, right)) in [ | ||
| 2331 | + (0, (1.0, 0.0)), // FL | ||
| 2332 | + (1, (0.0, 1.0)), // FR | ||
| 2333 | + (2, (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2)), // FC | ||
| 2334 | + (3, (0.0, 0.0)), // LFE, dropped | ||
| 2335 | + (4, (std::f32::consts::FRAC_1_SQRT_2, 0.0)), // BL | ||
| 2336 | + (5, (0.0, std::f32::consts::FRAC_1_SQRT_2)), // BR | ||
| 2337 | + ] { | ||
| 2338 | + let mut frame = vec![0.0f32; 6]; | ||
| 2339 | + frame[channel] = 1.0; | ||
| 2340 | + fold_5_1(&mut frame, true); | ||
| 2341 | + let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2); | ||
| 2342 | + assert_eq!(frame.len(), 2, "one 5.1 frame is one stereo frame"); | ||
| 2343 | + assert!((frame[0] - left * norm).abs() < 1e-6, "ch{channel}: {frame:?}"); | ||
| 2344 | + assert!((frame[1] - right * norm).abs() < 1e-6, "ch{channel}: {frame:?}"); | ||
| 2345 | + } | ||
| 2346 | + // Every channel at once is what a normalised fold exists for. | ||
| 2347 | + let mut loud = vec![1.0f32; 12]; | ||
| 2348 | + fold_5_1(&mut loud, true); | ||
| 2349 | + assert_eq!(loud.len(), 4); | ||
| 2350 | + assert!( | ||
| 2351 | + loud.iter().all(|s| (*s - 1.0).abs() < 1e-6), | ||
| 2352 | + "full scale in, full scale out, never past it: {loud:?}" | ||
| 2353 | + ); | ||
| 2354 | + // A track that is not 5.1 is handed over untouched. | ||
| 2355 | + let mut stereo = vec![0.5f32, -0.5]; | ||
| 2356 | + fold_5_1(&mut stereo, false); | ||
| 2357 | + assert_eq!(stereo, [0.5, -0.5]); | ||
| 2358 | + } | ||
| 2118 | 2359 | ||
| 2119 | /// A real AAC track: one stts entry, N packets of 1024. | 2360 | /// A real AAC track: one stts entry, N packets of 1024. |
| 2120 | fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> { | 2361 | fn aac(count: u32) -> impl IntoIterator<Item = (u32, u32)> { |
| @@ -3,7 +3,7 @@ | |||
| 3 | 3 | ||
| 4 | use std::path::{Path, PathBuf}; | 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::sync::Arc; | 5 | use std::sync::Arc; |
| 6 | -use std::sync::atomic::{AtomicBool, Ordering}; | 6 | +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; |
| 7 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; | 7 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; |
| 8 | use std::thread; | 8 | use std::thread; |
| 9 | 9 | ||
| @@ -25,6 +25,106 @@ pub struct Frame { | |||
| 25 | pub bgra: Vec<u8>, | 25 | pub bgra: Vec<u8>, |
| 26 | } | 26 | } |
| 27 | 27 | ||
| 28 | +/// Which decoder a source is really running on. Read-only introspection: it | ||
| 29 | +/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose -- | ||
| 30 | +/// a hardware session that opened and then failed before its first picture | ||
| 31 | +/// falls back to software and this says so, because it is written where the | ||
| 32 | +/// fallback happens rather than where it was hoped for. | ||
| 33 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 34 | +pub enum Backend { | ||
| 35 | + /// The worker has not reached its decoder yet: the plugin's VA-API init is | ||
| 36 | + /// ~90 ms, and this is what a caller reads in that window. | ||
| 37 | + #[default] | ||
| 38 | + Opening, | ||
| 39 | + /// The VA-API plugin (`libengine_hw.so`). | ||
| 40 | + Hardware, | ||
| 41 | + /// `rusty_h264`, in this process. | ||
| 42 | + Software, | ||
| 43 | + /// A still image: one `image` decode, no stream and no decoder to pick. | ||
| 44 | + Still, | ||
| 45 | + /// A gap: black frames, nothing decoded at all. | ||
| 46 | + Gap, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +impl Backend { | ||
| 50 | + /// Short enough for a library row and a transport line. | ||
| 51 | + pub fn label(self) -> &'static str { | ||
| 52 | + match self { | ||
| 53 | + Self::Opening => "opening", | ||
| 54 | + Self::Hardware => "HW", | ||
| 55 | + Self::Software => "SW", | ||
| 56 | + Self::Still => "still", | ||
| 57 | + Self::Gap => "gap", | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + | ||
| 61 | + fn code(self) -> u8 { | ||
| 62 | + match self { | ||
| 63 | + Self::Opening => 0, | ||
| 64 | + Self::Hardware => 1, | ||
| 65 | + Self::Software => 2, | ||
| 66 | + Self::Still => 3, | ||
| 67 | + Self::Gap => 4, | ||
| 68 | + } | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + fn from_code(code: u8) -> Self { | ||
| 72 | + match code { | ||
| 73 | + 1 => Self::Hardware, | ||
| 74 | + 2 => Self::Software, | ||
| 75 | + 3 => Self::Still, | ||
| 76 | + 4 => Self::Gap, | ||
| 77 | + _ => Self::Opening, | ||
| 78 | + } | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// Where a worker publishes the decoder it opened, for whoever holds the other | ||
| 83 | +/// end of its channel. One atomic byte, written once at open (and once more if | ||
| 84 | +/// hardware hands the range back to software), read whenever a caller repaints | ||
| 85 | +/// -- never per frame on either side. | ||
| 86 | +#[derive(Clone, Default)] | ||
| 87 | +pub struct BackendCell(Arc<AtomicU8>); | ||
| 88 | + | ||
| 89 | +impl BackendCell { | ||
| 90 | + fn new(backend: Backend) -> Self { | ||
| 91 | + Self(Arc::new(AtomicU8::new(backend.code()))) | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + fn set(&self, backend: Backend) { | ||
| 95 | + self.0.store(backend.code(), Ordering::Relaxed); | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + pub fn get(&self) -> Backend { | ||
| 99 | + Backend::from_code(self.0.load(Ordering::Relaxed)) | ||
| 100 | + } | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`] | ||
| 104 | +/// decides it: the same `VE_SW` pin and the same plugin probe against this very | ||
| 105 | +/// file. What lets a front-end name the decoder *before* anything plays. | ||
| 106 | +/// | ||
| 107 | +/// The codec is `None` for a still image, which has no coded stream. A stream | ||
| 108 | +/// no decoder here can take is an `Err` naming the plugin, exactly as opening | ||
| 109 | +/// it would be -- the same refusal, one VA-API init earlier. | ||
| 110 | +/// | ||
| 111 | +/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per | ||
| 112 | +/// file, off a render thread, and keep the answer. | ||
| 113 | +pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> { | ||
| 114 | + if crate::is_image(path) { | ||
| 115 | + return Ok((None, Backend::Still)); | ||
| 116 | + } | ||
| 117 | + let path = path.to_path_buf(); | ||
| 118 | + let (meta, _demuxer) = Demuxer::open(&path)?; | ||
| 119 | + if open_hw(&path, 0).is_some() { | ||
| 120 | + return Ok((Some(meta.codec), Backend::Hardware)); | ||
| 121 | + } | ||
| 122 | + if meta.codec != Codec::H264 { | ||
| 123 | + return Err(meta.codec.needs_plugin().into()); | ||
| 124 | + } | ||
| 125 | + Ok((Some(meta.codec), Backend::Software)) | ||
| 126 | +} | ||
| 127 | + | ||
| 28 | /// A running decode worker: the flag that stops it, and the handle to wait on. | 128 | /// A running decode worker: the flag that stops it, and the handle to wait on. |
| 29 | /// | 129 | /// |
| 30 | /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize` | 130 | /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize` |
| @@ -85,6 +185,9 @@ impl Drop for Worker { | |||
| 85 | pub(crate) struct FrameStream { | 185 | pub(crate) struct FrameStream { |
| 86 | pub(crate) frames: Receiver<Frame>, | 186 | pub(crate) frames: Receiver<Frame>, |
| 87 | pub(crate) worker: Worker, | 187 | pub(crate) worker: Worker, |
| 188 | + /// What this stream's pictures are being decoded by. Dropped last and read | ||
| 189 | + /// by the caller, so it outlives nothing and blocks nothing. | ||
| 190 | + pub(crate) backend: BackendCell, | ||
| 88 | } | 191 | } |
| 89 | 192 | ||
| 90 | pub struct DecodeSession; | 193 | pub struct DecodeSession; |
| @@ -152,6 +255,7 @@ impl DecodeSession { | |||
| 152 | cancel, | 255 | cancel, |
| 153 | handle: None, | 256 | handle: None, |
| 154 | }, | 257 | }, |
| 258 | + backend: BackendCell::new(Backend::Gap), | ||
| 155 | }; | 259 | }; |
| 156 | } | 260 | } |
| 157 | let worker_cancel = Arc::clone(&cancel); | 261 | let worker_cancel = Arc::clone(&cancel); |
| @@ -180,6 +284,7 @@ impl DecodeSession { | |||
| 180 | FrameStream { | 284 | FrameStream { |
| 181 | frames: rx, | 285 | frames: rx, |
| 182 | worker: Worker { cancel, handle }, | 286 | worker: Worker { cancel, handle }, |
| 287 | + backend: BackendCell::new(Backend::Gap), | ||
| 183 | } | 288 | } |
| 184 | } | 289 | } |
| 185 | 290 | ||
| @@ -209,6 +314,7 @@ impl DecodeSession { | |||
| 209 | cancel, | 314 | cancel, |
| 210 | handle: None, | 315 | handle: None, |
| 211 | }, | 316 | }, |
| 317 | + backend: BackendCell::new(Backend::Still), | ||
| 212 | }); | 318 | }); |
| 213 | } | 319 | } |
| 214 | // The one conversion, on this thread: it is a few milliseconds and the | 320 | // The one conversion, on this thread: it is a few milliseconds and the |
| @@ -245,6 +351,7 @@ impl DecodeSession { | |||
| 245 | Ok(FrameStream { | 351 | Ok(FrameStream { |
| 246 | frames: rx, | 352 | frames: rx, |
| 247 | worker: Worker { cancel, handle }, | 353 | worker: Worker { cancel, handle }, |
| 354 | + backend: BackendCell::new(Backend::Still), | ||
| 248 | }) | 355 | }) |
| 249 | } | 356 | } |
| 250 | 357 | ||
| @@ -285,6 +392,9 @@ impl DecodeSession { | |||
| 285 | // decoder run ahead of the display without limit. | 392 | // decoder run ahead of the display without limit. |
| 286 | let (tx, rx) = sync_channel(2); | 393 | let (tx, rx) = sync_channel(2); |
| 287 | let cancel = Arc::new(AtomicBool::new(false)); | 394 | let cancel = Arc::new(AtomicBool::new(false)); |
| 395 | + // Written by the worker below the moment it knows, so a caller reading | ||
| 396 | + // it sees what opened rather than what was hoped for. | ||
| 397 | + let backend = BackendCell::default(); | ||
| 288 | if end_frame <= start_frame { | 398 | if end_frame <= start_frame { |
| 289 | // Nothing to decode: dropping `tx` here closes the channel cleanly, | 399 | // Nothing to decode: dropping `tx` here closes the channel cleanly, |
| 290 | // so the caller sees an immediate end of stream rather than an error. | 400 | // so the caller sees an immediate end of stream rather than an error. |
| @@ -296,10 +406,12 @@ impl DecodeSession { | |||
| 296 | cancel, | 406 | cancel, |
| 297 | handle: None, | 407 | handle: None, |
| 298 | }, | 408 | }, |
| 409 | + backend, | ||
| 299 | }, | 410 | }, |
| 300 | )); | 411 | )); |
| 301 | } | 412 | } |
| 302 | let worker_cancel = Arc::clone(&cancel); | 413 | let worker_cancel = Arc::clone(&cancel); |
| 414 | + let worker_backend = backend.clone(); | ||
| 303 | let handle = thread::Builder::new() | 415 | let handle = thread::Builder::new() |
| 304 | .name("decode".into()) | 416 | .name("decode".into()) |
| 305 | .spawn(move || { | 417 | .spawn(move || { |
| @@ -320,6 +432,7 @@ impl DecodeSession { | |||
| 320 | return; | 432 | return; |
| 321 | } | 433 | } |
| 322 | eprintln!("decode backend: hardware (VA-API plugin)"); | 434 | eprintln!("decode backend: hardware (VA-API plugin)"); |
| 435 | + worker_backend.set(Backend::Hardware); | ||
| 323 | if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) { | 436 | if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) { |
| 324 | return; | 437 | return; |
| 325 | } | 438 | } |
| @@ -334,6 +447,7 @@ impl DecodeSession { | |||
| 334 | return; | 447 | return; |
| 335 | } | 448 | } |
| 336 | eprintln!("decode backend: software (rusty_h264)"); | 449 | eprintln!("decode backend: software (rusty_h264)"); |
| 450 | + worker_backend.set(Backend::Software); | ||
| 337 | run( | 451 | run( |
| 338 | demuxer, | 452 | demuxer, |
| 339 | tx, | 453 | tx, |
| @@ -351,6 +465,7 @@ impl DecodeSession { | |||
| 351 | cancel, | 465 | cancel, |
| 352 | handle: Some(handle), | 466 | handle: Some(handle), |
| 353 | }, | 467 | }, |
| 468 | + backend, | ||
| 354 | }, | 469 | }, |
| 355 | )) | 470 | )) |
| 356 | } | 471 | } |
| @@ -6,7 +6,11 @@ | |||
| 6 | //! Two containers, one interface: mp4 through the `mp4` crate, Matroska | 6 | //! Two containers, one interface: mp4 through the `mp4` crate, Matroska |
| 7 | //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists -- | 7 | //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists -- |
| 8 | //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in | 8 | //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in |
| 9 | -//! practice. | 9 | +//! practice -- and HEVC rides the same walk, because that is the other codec a |
| 10 | +//! `.mkv` off a disc arrives in. An AV1 *mp4* is read here too, its sample entry | ||
| 11 | +//! picked out of the `stsd` by hand for the same reason `mux` writes it by hand: | ||
| 12 | +//! this project exports one, and a file this cannot reopen is a file it had no | ||
| 13 | +//! business writing. | ||
| 10 | 14 | ||
| 11 | use std::fs::File; | 15 | use std::fs::File; |
| 12 | use std::io::{BufReader, Read, Seek, SeekFrom}; | 16 | use std::io::{BufReader, Read, Seek, SeekFrom}; |
| @@ -97,12 +101,24 @@ impl Demuxer { | |||
| 97 | Self::Mkv(d) => d.seek_to_sync_at_or_before(frame), | 101 | Self::Mkv(d) => d.seek_to_sync_at_or_before(frame), |
| 98 | } | 102 | } |
| 99 | } | 103 | } |
| 104 | + | ||
| 105 | + /// Bits per luma sample the stream is coded at: 8 for everything but an | ||
| 106 | + /// HEVC Main 10 track, which decodes into a P010 surface rather than an | ||
| 107 | + /// NV12 one. Not part of [`VideoMeta`] because nothing above the plugin has | ||
| 108 | + /// a use for it -- what comes out of the read-back is 8-bit either way. | ||
| 109 | + pub fn bit_depth(&self) -> u8 { | ||
| 110 | + match self { | ||
| 111 | + Self::Mp4(d) => d.bit_depth, | ||
| 112 | + Self::Mkv(d) => d.bit_depth, | ||
| 113 | + } | ||
| 114 | + } | ||
| 100 | } | 115 | } |
| 101 | 116 | ||
| 102 | -/// Whether a path names a Matroska file, which is where AV1 arrives. Extension | 117 | +/// Whether a path names a Matroska file, which is where AV1 arrives and where a |
| 103 | -/// only, like [`crate::is_audio`]: the demuxer is what really decides, but the | 118 | +/// film off a disc arrives as HEVC. Extension only, like [`crate::is_audio`]: |
| 104 | -/// audio path has to know before it opens anything that this file's sound is | 119 | +/// the demuxer is what really decides, but the audio path has to know before it |
| 105 | -/// not one it reads (see [`crate::audio::AudioSession::unsupported`]). | 120 | +/// opens anything that this file's sound is read by symphonia's `mkv` reader |
| 121 | +/// and not by either mp4 one (see [`crate::audio::Track::open`]). | ||
| 106 | pub fn is_matroska(path: &Path) -> bool { | 122 | pub fn is_matroska(path: &Path) -> bool { |
| 107 | path.extension() | 123 | path.extension() |
| 108 | .and_then(|e| e.to_str()) | 124 | .and_then(|e| e.to_str()) |
| @@ -118,9 +134,9 @@ pub struct Mp4Demuxer { | |||
| 118 | /// (`audio::priming_samples`), and frame indices count from there. | 134 | /// (`audio::priming_samples`), and frame indices count from there. |
| 119 | first_sample: u32, | 135 | first_sample: u32, |
| 120 | codec: Codec, | 136 | codec: Codec, |
| 121 | - /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), | 137 | + /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), or |
| 122 | - /// re-injected ahead of every sync sample. Empty for VP9, which carries no | 138 | + /// the sequence header OBU for AV1, re-injected ahead of every sync sample. |
| 123 | - /// out-of-band parameter sets. | 139 | + /// Empty for VP9, which carries no out-of-band parameter sets. |
| 124 | parameter_sets: Vec<u8>, | 140 | parameter_sets: Vec<u8>, |
| 125 | /// Bytes of the NAL length prefix each sample is written with, off `avcC` | 141 | /// Bytes of the NAL length prefix each sample is written with, off `avcC` |
| 126 | /// or `hvcC`. Unused by VP9. | 142 | /// or `hvcC`. Unused by VP9. |
| @@ -129,6 +145,8 @@ pub struct Mp4Demuxer { | |||
| 129 | /// at all, i.e. every sample is a sync sample. | 145 | /// at all, i.e. every sample is a sync sample. |
| 130 | sync_samples: Vec<u32>, | 146 | sync_samples: Vec<u32>, |
| 131 | next_sample: u32, | 147 | next_sample: u32, |
| 148 | + /// Bits per luma sample; see [`Demuxer::bit_depth`]. | ||
| 149 | + bit_depth: u8, | ||
| 132 | } | 150 | } |
| 133 | 151 | ||
| 134 | impl Mp4Demuxer { | 152 | impl Mp4Demuxer { |
| @@ -145,20 +163,26 @@ impl Mp4Demuxer { | |||
| 145 | Ok(MediaType::H265) => Some((t, Codec::Hevc)), | 163 | Ok(MediaType::H265) => Some((t, Codec::Hevc)), |
| 146 | Ok(MediaType::VP9) => Some((t, Codec::Vp9)), | 164 | Ok(MediaType::VP9) => Some((t, Codec::Vp9)), |
| 147 | // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry | 165 | // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry |
| 148 | - // (`stsd.rs:107`), so an `hvc1`-tagged HEVC track -- what Apple | 166 | + // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC |
| 149 | - // and ffmpeg's mov muxer write in practice -- reports no media | 167 | + // track -- what Apple and ffmpeg's mov muxer write in practice |
| 150 | - // type at all, and the file used to read back as having no | 168 | + // -- and every AV1 track report no media type, and such a file |
| 151 | - // video. Its sample tables (`stts`/`stsz`/`stsc`/`stss`) are | 169 | + // used to read back as having no video. Its sample tables |
| 152 | - // parsed regardless of the entry the crate dropped, so only the | 170 | + // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the |
| 153 | - // fourcc has to be read here by hand. hvc1 differs from hev1 in | 171 | + // entry the crate dropped, so only the fourcc has to be read |
| 154 | - // that the parameter sets may not repeat in-band, which costs | 172 | + // here by hand. hvc1 differs from hev1 in that the parameter |
| 155 | - // nothing: they are re-injected out of `hvcC` ahead of every | 173 | + // sets may not repeat in-band, which costs nothing: they are |
| 156 | - // sync sample either way. | 174 | + // re-injected out of `hvcC` ahead of every sync sample either |
| 157 | - _ => (matches!(t.track_type(), Ok(TrackType::Video)) | 175 | + // way, exactly as an AV1 sequence header is out of `av1C`. |
| 158 | - && sample_entry(path, t.track_id()).is_ok_and(|(kind, _)| &kind == b"hvc1")) | 176 | + _ => matches!(t.track_type(), Ok(TrackType::Video)) |
| 159 | - .then_some((t, Codec::Hevc)), | 177 | + .then(|| sample_entry(path, t.track_id()).ok()) |
| 178 | + .flatten() | ||
| 179 | + .and_then(|(kind, _)| match &kind { | ||
| 180 | + b"hvc1" => Some((t, Codec::Hevc)), | ||
| 181 | + b"av01" => Some((t, Codec::Av1)), | ||
| 182 | + _ => None, | ||
| 183 | + }), | ||
| 160 | }) | 184 | }) |
| 161 | - .ok_or("no H.264, HEVC or VP9 video track in file")?; | 185 | + .ok_or("no H.264, HEVC, VP9 or AV1 video track in file")?; |
| 162 | let (track, codec) = track; | 186 | let (track, codec) = track; |
| 163 | 187 | ||
| 164 | let track_id = track.track_id(); | 188 | let track_id = track.track_id(); |
| @@ -172,6 +196,7 @@ impl Mp4Demuxer { | |||
| 172 | let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); | 196 | let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); |
| 173 | let mut parameter_sets = Vec::new(); | 197 | let mut parameter_sets = Vec::new(); |
| 174 | let mut nal_length = 4; | 198 | let mut nal_length = 4; |
| 199 | + let mut bit_depth = 8; | ||
| 175 | match codec { | 200 | match codec { |
| 176 | Codec::H264 => { | 201 | Codec::H264 => { |
| 177 | let avcc = &track | 202 | let avcc = &track |
| @@ -195,14 +220,24 @@ impl Mp4Demuxer { | |||
| 195 | // start without are read out of the file by hand. | 220 | // start without are read out of the file by hand. |
| 196 | Codec::Hevc => { | 221 | Codec::Hevc => { |
| 197 | let hvcc = hvcc_record(path, track_id)?; | 222 | let hvcc = hvcc_record(path, track_id)?; |
| 198 | - let (len, sets) = parse_hvcc(&hvcc)?; | 223 | + let (len, sets, depth) = parse_hvcc(&hvcc)?; |
| 199 | nal_length = len; | 224 | nal_length = len; |
| 200 | parameter_sets = sets; | 225 | parameter_sets = sets; |
| 226 | + bit_depth = depth; | ||
| 227 | + } | ||
| 228 | + // The sequence header OBU out of `av1C`, re-injected ahead of every | ||
| 229 | + // sync sample exactly as [`MkvDemuxer`] does it off `CodecPrivate` -- | ||
| 230 | + // the same record in the same bytes, which is what makes an AV1 mp4 | ||
| 231 | + // written here and an AV1 Matroska written here one stream in two | ||
| 232 | + // containers. | ||
| 233 | + Codec::Av1 => { | ||
| 234 | + let (_, entry) = sample_entry(path, track_id)?; | ||
| 235 | + let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C") | ||
| 236 | + .ok_or("no av1C box in the AV1 sample entry")?; | ||
| 237 | + parameter_sets = parse_av1c(av1c)?; | ||
| 201 | } | 238 | } |
| 202 | - // No parameter sets: a VP9 sample is self-contained, and AV1 never | 239 | + // No parameter sets: a VP9 sample is self-contained. |
| 203 | - // reaches this arm at all -- `mp4 0.14` knows no `av01` sample | 240 | + Codec::Vp9 => {} |
| 204 | - // entry, so AV1 only ever arrives through [`MkvDemuxer`]. | ||
| 205 | - Codec::Vp9 | Codec::Av1 => {} | ||
| 206 | } | 241 | } |
| 207 | let sync_samples = track | 242 | let sync_samples = track |
| 208 | .trak | 243 | .trak |
| @@ -235,6 +270,7 @@ impl Mp4Demuxer { | |||
| 235 | nal_length, | 270 | nal_length, |
| 236 | sync_samples, | 271 | sync_samples, |
| 237 | next_sample, | 272 | next_sample, |
| 273 | + bit_depth, | ||
| 238 | }, | 274 | }, |
| 239 | )) | 275 | )) |
| 240 | } | 276 | } |
| @@ -255,6 +291,16 @@ impl Mp4Demuxer { | |||
| 255 | if self.codec == Codec::Vp9 { | 291 | if self.codec == Codec::Vp9 { |
| 256 | return Ok(Some(sample.bytes.to_vec())); | 292 | return Ok(Some(sample.bytes.to_vec())); |
| 257 | } | 293 | } |
| 294 | + // An AV1 one is a whole temporal unit, likewise unframed -- with the | ||
| 295 | + // sequence header in front of it where a decoder may start. | ||
| 296 | + if self.codec == Codec::Av1 { | ||
| 297 | + let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len()); | ||
| 298 | + if sample.is_sync { | ||
| 299 | + au.extend_from_slice(&self.parameter_sets); | ||
| 300 | + } | ||
| 301 | + au.extend_from_slice(&sample.bytes); | ||
| 302 | + return Ok(Some(au)); | ||
| 303 | + } | ||
| 258 | 304 | ||
| 259 | let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16); | 305 | let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16); |
| 260 | if sample.is_sync { | 306 | if sample.is_sync { |
| @@ -291,7 +337,7 @@ struct Block { | |||
| 291 | key: bool, | 337 | key: bool, |
| 292 | } | 338 | } |
| 293 | 339 | ||
| 294 | -/// AV1 or H.264 out of a Matroska file (`.mkv`/`.webm`). | 340 | +/// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`). |
| 295 | /// | 341 | /// |
| 296 | /// The whole segment is walked once at open -- element *headers* only, the block | 342 | /// The whole segment is walked once at open -- element *headers* only, the block |
| 297 | /// payloads are seeked over -- because Matroska carries no sample table: the | 343 | /// payloads are seeked over -- because Matroska carries no sample table: the |
| @@ -300,17 +346,27 @@ struct Block { | |||
| 300 | pub struct MkvDemuxer { | 346 | pub struct MkvDemuxer { |
| 301 | file: File, | 347 | file: File, |
| 302 | blocks: Vec<Block>, | 348 | blocks: Vec<Block>, |
| 349 | + codec: Codec, | ||
| 303 | /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of | 350 | /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of |
| 304 | /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream | 351 | /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream |
| 305 | /// repeats its sequence header at every keyframe anyway, and cros-codecs | 352 | /// repeats its sequence header at every keyframe anyway, and cros-codecs |
| 306 | /// ignores one identical to the sequence in force (`av1.rs:381`), so this is | 353 | /// ignores one identical to the sequence in force (`av1.rs:381`), so this is |
| 307 | /// free when the encoder already wrote one and load-bearing when it did not. | 354 | /// free when the encoder already wrote one and load-bearing when it did not. |
| 308 | - /// For H.264 it is the Annex-B SPS/PPS out of `avcC` instead, re-injected the | 355 | + /// |
| 309 | - /// same way and for the same reason. | 356 | + /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is |
| 357 | + /// an `hvcC` record verbatim -- the same blob, re-injected for the same | ||
| 358 | + /// reason, as the one [`Mp4Demuxer`] carries; for H.264 the SPS/PPS off the | ||
| 359 | + /// `avcC` beside it, which is that record's H.264 twin. | ||
| 310 | config: Vec<u8>, | 360 | config: Vec<u8>, |
| 311 | - /// Bytes of the NAL length prefix an H.264 block is written with, off | 361 | + /// Bytes of the NAL length prefix an HEVC or H.264 block is written with; |
| 312 | - /// `avcC`. Zero for AV1, whose blocks are handed over as they lie. | 362 | + /// unused by AV1, whose block is one temporal unit and carries no prefixes. |
| 313 | nal_length: usize, | 363 | nal_length: usize, |
| 364 | + /// Bits per luma sample; see [`Demuxer::bit_depth`]. | ||
| 365 | + bit_depth: u8, | ||
| 366 | + /// One block's bytes, reused across access units: a 4K HEVC keyframe is a | ||
| 367 | + /// megabyte and it is reframed, not handed over, so the read needs a | ||
| 368 | + /// landing place of its own. | ||
| 369 | + scratch: Vec<u8>, | ||
| 314 | next: usize, | 370 | next: usize, |
| 315 | } | 371 | } |
| 316 | 372 | ||
| @@ -319,10 +375,21 @@ impl MkvDemuxer { | |||
| 319 | let mut file = File::open(path)?; | 375 | let mut file = File::open(path)?; |
| 320 | let end = file.metadata()?.len(); | 376 | let end = file.metadata()?.len(); |
| 321 | let segment = mkv_segment(&mut file, end)?; | 377 | let segment = mkv_segment(&mut file, end)?; |
| 322 | - let (video, _) = mkv_tracks(&mut file, segment)?; | 378 | + let (video, _, other) = mkv_tracks(&mut file, segment)?; |
| 323 | - let video = video.ok_or( | 379 | + let video = match video { |
| 324 | - "no AV1 or H.264 video track in this Matroska file — those are the codecs read from one", | 380 | + Some(video) => video, |
| 325 | - )?; | 381 | + // Named, because "no video track" is a lie about a file that has one |
| 382 | + // in a codec this does not read. | ||
| 383 | + None => { | ||
| 384 | + return Err(match other { | ||
| 385 | + Some(codec) => format!( | ||
| 386 | + "{codec} video in a Matroska file is not supported — AV1, HEVC and H.264 are" | ||
| 387 | + ), | ||
| 388 | + None => "this Matroska file has no video track".to_string(), | ||
| 389 | + } | ||
| 390 | + .into()); | ||
| 391 | + } | ||
| 392 | + }; | ||
| 326 | let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?; | 393 | let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?; |
| 327 | if blocks.is_empty() { | 394 | if blocks.is_empty() { |
| 328 | return Err(format!( | 395 | return Err(format!( |
| @@ -366,33 +433,37 @@ impl MkvDemuxer { | |||
| 366 | Self { | 433 | Self { |
| 367 | file, | 434 | file, |
| 368 | blocks, | 435 | blocks, |
| 436 | + codec: video.codec, | ||
| 369 | config: video.config, | 437 | config: video.config, |
| 370 | nal_length: video.nal_length, | 438 | nal_length: video.nal_length, |
| 439 | + bit_depth: video.bit_depth, | ||
| 440 | + scratch: Vec::new(), | ||
| 371 | next: 0, | 441 | next: 0, |
| 372 | }, | 442 | }, |
| 373 | )) | 443 | )) |
| 374 | } | 444 | } |
| 375 | 445 | ||
| 446 | + /// Next access unit in decode order: the block verbatim for AV1, which is | ||
| 447 | + /// one temporal unit already, and Annex-B for HEVC, whose block holds the | ||
| 448 | + /// same length-prefixed NALs an mp4 sample does. | ||
| 376 | fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> { | 449 | fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> { |
| 377 | let Some(&block) = self.blocks.get(self.next) else { | 450 | let Some(&block) = self.blocks.get(self.next) else { |
| 378 | return Ok(None); | 451 | return Ok(None); |
| 379 | }; | 452 | }; |
| 380 | self.next += 1; | 453 | self.next += 1; |
| 381 | let head = if block.key { self.config.len() } else { 0 }; | 454 | let head = if block.key { self.config.len() } else { 0 }; |
| 382 | - // An H.264 block is `avcC`-framed like an mp4 sample, so it is reframed | 455 | + if self.codec == Codec::Av1 { |
| 383 | - // to Annex-B behind the parameter sets exactly as `Mp4Demuxer` does. An | 456 | + let mut au = vec![0u8; head + block.len]; |
| 384 | - // AV1 one is a temporal unit already and goes over as it lies, below. | 457 | + au[..head].copy_from_slice(&self.config[..head]); |
| 385 | - if self.nal_length > 0 { | 458 | + read_exact_at(&mut self.file, block.at, &mut au[head..])?; |
| 386 | - let mut block_bytes = vec![0u8; block.len]; | ||
| 387 | - read_exact_at(&mut self.file, block.at, &mut block_bytes)?; | ||
| 388 | - let mut au = Vec::with_capacity(head + block.len + 16); | ||
| 389 | - au.extend_from_slice(&self.config[..head]); | ||
| 390 | - append_annex_b(&block_bytes, self.nal_length, &mut au)?; | ||
| 391 | return Ok(Some(au)); | 459 | return Ok(Some(au)); |
| 392 | } | 460 | } |
| 393 | - let mut au = vec![0u8; head + block.len]; | 461 | + let Self { file, scratch, .. } = self; |
| 394 | - au[..head].copy_from_slice(&self.config[..head]); | 462 | + scratch.resize(block.len, 0); |
| 395 | - read_exact_at(&mut self.file, block.at, &mut au[head..])?; | 463 | + read_exact_at(file, block.at, scratch)?; |
| 464 | + let mut au = Vec::with_capacity(head + block.len + 16); | ||
| 465 | + au.extend_from_slice(&self.config[..head]); | ||
| 466 | + append_annex_b(&self.scratch, self.nal_length, &mut au)?; | ||
| 396 | Ok(Some(au)) | 467 | Ok(Some(au)) |
| 397 | } | 468 | } |
| 398 | 469 | ||
| @@ -432,6 +503,7 @@ struct MkvVideo { | |||
| 432 | codec: Codec, | 503 | codec: Codec, |
| 433 | config: Vec<u8>, | 504 | config: Vec<u8>, |
| 434 | nal_length: usize, | 505 | nal_length: usize, |
| 506 | + bit_depth: u8, | ||
| 435 | } | 507 | } |
| 436 | 508 | ||
| 437 | // Matroska element IDs, written with the leading length marker they carry in | 509 | // Matroska element IDs, written with the leading length marker they carry in |
| @@ -468,17 +540,18 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { | |||
| 468 | Err("no Segment element: not a Matroska file".into()) | 540 | Err("no Segment element: not a Matroska file".into()) |
| 469 | } | 541 | } |
| 470 | 542 | ||
| 471 | -/// The AV1 video track of `segment`, and how a *non*-AV1 audio track would be | 543 | +/// The video track of `segment`, the codec id of its first audio track, and the |
| 472 | -/// named -- the second is what tells a user why a file with sound plays silent | 544 | +/// codec id of a video track this cannot read -- the last two are what tell a |
| 473 | -/// ([`crate::audio::AudioSession::unsupported`]). | 545 | +/// user why a file plays silent ([`crate::audio::AudioSession::unsupported`]) |
| 546 | +/// or refuses to open at all. | ||
| 474 | /// | 547 | /// |
| 475 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful | 548 | /// Header only: the walk stops at the first `Cluster`, so this costs a handful |
| 476 | /// of seeks whatever the file weighs. | 549 | /// of seeks whatever the file weighs. |
| 477 | fn mkv_tracks( | 550 | fn mkv_tracks( |
| 478 | file: &mut File, | 551 | file: &mut File, |
| 479 | segment: (u64, u64), | 552 | segment: (u64, u64), |
| 480 | -) -> crate::Result<(Option<MkvVideo>, Option<String>)> { | 553 | +) -> crate::Result<(Option<MkvVideo>, Option<String>, Option<String>)> { |
| 481 | - let (mut video, mut audio) = (None, None); | 554 | + let (mut video, mut audio, mut other) = (None, None, None); |
| 482 | let mut timestamp_scale = 1_000_000; | 555 | let mut timestamp_scale = 1_000_000; |
| 483 | let mut at = segment.0; | 556 | let mut at = segment.0; |
| 484 | while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { | 557 | while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { |
| @@ -498,8 +571,9 @@ fn mkv_tracks( | |||
| 498 | while let Some(e) = ebml_element(file, at, stop)? { | 571 | while let Some(e) = ebml_element(file, at, stop)? { |
| 499 | if e.0 == TRACK_ENTRY { | 572 | if e.0 == TRACK_ENTRY { |
| 500 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { | 573 | match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { |
| 501 | - (Some(track), _) if video.is_none() => video = Some(track), | 574 | + MkvEntry::Video(track) if video.is_none() => video = Some(track), |
| 502 | - (_, Some(codec)) if audio.is_none() => audio = Some(codec), | 575 | + MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), |
| 576 | + MkvEntry::Audio(codec) if audio.is_none() => audio = Some(codec), | ||
| 503 | _ => {} | 577 | _ => {} |
| 504 | } | 578 | } |
| 505 | } | 579 | } |
| @@ -510,17 +584,27 @@ fn mkv_tracks( | |||
| 510 | } | 584 | } |
| 511 | at = stop; | 585 | at = stop; |
| 512 | } | 586 | } |
| 513 | - Ok((video, audio)) | 587 | + Ok((video, audio, other)) |
| 514 | } | 588 | } |
| 515 | 589 | ||
| 516 | -/// One `TrackEntry`: `Some` video only for an 8-bit AV1 or an H.264 track, and | 590 | +/// What one `TrackEntry` turned out to be. |
| 517 | -/// the codec id of an audio track otherwise. | 591 | +enum MkvEntry { |
| 592 | + Video(MkvVideo), | ||
| 593 | + /// A video track in a codec this does not read, by the name it gives itself. | ||
| 594 | + OtherVideo(String), | ||
| 595 | + /// An audio track, likewise by its codec id (`A_AAC`, `A_OPUS`, ...). | ||
| 596 | + Audio(String), | ||
| 597 | + /// Subtitles, buttons: nobody's here. | ||
| 598 | + Other, | ||
| 599 | +} | ||
| 600 | + | ||
| 601 | +/// One `TrackEntry`, read for what it is. | ||
| 518 | fn mkv_track_entry( | 602 | fn mkv_track_entry( |
| 519 | file: &mut File, | 603 | file: &mut File, |
| 520 | body: u64, | 604 | body: u64, |
| 521 | end: u64, | 605 | end: u64, |
| 522 | timestamp_scale: u64, | 606 | timestamp_scale: u64, |
| 523 | -) -> crate::Result<(Option<MkvVideo>, Option<String>)> { | 607 | +) -> crate::Result<MkvEntry> { |
| 524 | let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); | 608 | let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); |
| 525 | let (mut width, mut height, mut config) = (0, 0, Vec::new()); | 609 | let (mut width, mut height, mut config) = (0, 0, Vec::new()); |
| 526 | let mut at = body; | 610 | let mut at = body; |
| @@ -551,30 +635,37 @@ fn mkv_track_entry( | |||
| 551 | at = stop; | 635 | at = stop; |
| 552 | } | 636 | } |
| 553 | // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here. | 637 | // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here. |
| 554 | - let (codec, config, nal_length) = match (kind, codec.as_str()) { | 638 | + // A Matroska `CodecPrivate` is the codec's own configuration record -- |
| 555 | - (1, "V_AV1") => (Codec::Av1, parse_av1c(&config)?, 0), | 639 | + // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4 |
| 556 | - // The same `avcC` an mp4 carries, `CodecPrivate` being where Matroska | 640 | + // sample entry carries, so it parses with the very same reader. |
| 557 | - // puts it: length-prefixed blocks and the SPS/PPS out of the record. | 641 | + let (codec, nal_length, config, bit_depth) = match (kind, codec.as_str()) { |
| 642 | + (1, "V_AV1") => (Codec::Av1, 4, parse_av1c(&config)?, 8), | ||
| 643 | + (1, "V_MPEGH/ISO/HEVC") => { | ||
| 644 | + let (nal_length, sets, bit_depth) = parse_hvcc(&config)?; | ||
| 645 | + (Codec::Hevc, nal_length, sets, bit_depth) | ||
| 646 | + } | ||
| 647 | + // The `avcC` beside them, and the same story: length-prefixed blocks and | ||
| 648 | + // the SPS/PPS out of the record. Taken as 8-bit, which is what the whole | ||
| 649 | + // H.264 path here assumes of an mp4's `avc1` too. | ||
| 558 | (1, "V_MPEG4/ISO/AVC") => { | 650 | (1, "V_MPEG4/ISO/AVC") => { |
| 559 | let (nal_length, sets) = parse_avcc(&config)?; | 651 | let (nal_length, sets) = parse_avcc(&config)?; |
| 560 | - (Codec::H264, sets, nal_length) | 652 | + (Codec::H264, nal_length, sets, 8) |
| 561 | } | 653 | } |
| 562 | - (2, _) => return Ok((None, Some(codec))), | 654 | + (1, _) => return Ok(MkvEntry::OtherVideo(codec)), |
| 563 | - _ => return Ok((None, None)), | 655 | + (2, _) => return Ok(MkvEntry::Audio(codec)), |
| 656 | + _ => return Ok(MkvEntry::Other), | ||
| 564 | }; | 657 | }; |
| 565 | - Ok(( | 658 | + Ok(MkvEntry::Video(MkvVideo { |
| 566 | - Some(MkvVideo { | 659 | + number, |
| 567 | - number, | 660 | + width, |
| 568 | - width, | 661 | + height, |
| 569 | - height, | 662 | + default_duration, |
| 570 | - default_duration, | 663 | + timestamp_scale, |
| 571 | - timestamp_scale, | 664 | + codec, |
| 572 | - codec, | 665 | + config, |
| 573 | - config, | 666 | + nal_length, |
| 574 | - nal_length, | 667 | + bit_depth, |
| 575 | - }), | 668 | + })) |
| 576 | - None, | ||
| 577 | - )) | ||
| 578 | } | 669 | } |
| 579 | 670 | ||
| 580 | /// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length | 671 | /// AVCDecoderConfigurationRecord (ISO 14496-15 §5.3.3.1) -> the NAL length |
| @@ -972,21 +1063,22 @@ pub(crate) fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4] | |||
| 972 | } | 1063 | } |
| 973 | 1064 | ||
| 974 | /// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length | 1065 | /// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length |
| 975 | -/// prefix width and the VPS/SPS/PPS arrays as one Annex-B blob. | 1066 | +/// prefix width, the VPS/SPS/PPS arrays as one Annex-B blob, and the luma bit |
| 976 | -fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> { | 1067 | +/// depth the plugin picks its surface pool from. |
| 1068 | +fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>, u8)> { | ||
| 977 | // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays. | 1069 | // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays. |
| 978 | let (&flags, &arrays) = rec | 1070 | let (&flags, &arrays) = rec |
| 979 | .get(21) | 1071 | .get(21) |
| 980 | .zip(rec.get(22)) | 1072 | .zip(rec.get(22)) |
| 981 | .ok_or("hvcC box shorter than its fixed header")?; | 1073 | .ok_or("hvcC box shorter than its fixed header")?; |
| 982 | - // 17 is bit_depth_luma_minus8 in its low 3 bits: the plugin's NV12 pool and | 1074 | + // 17 is bit_depth_luma_minus8 in its low 3 bits. 8-bit decodes into the |
| 983 | - // its vaGetImage read-back are 8-bit, so a Main 10 stream would decode into | 1075 | + // plugin's NV12 pool and 10-bit (Main 10) into its P010 one; 12-bit has |
| 984 | - // a surface nothing here can carry -- refused by name instead of shown as | 1076 | + // neither a pool here nor, on the hardware this was written against, a |
| 985 | - // garbage. Upgrade path: a P010 pool chosen from the stream info. | 1077 | + // VA-API profile -- refused by name rather than shown as garbage. |
| 986 | - if rec[17] & 0x7 != 0 { | 1078 | + let bit_depth = 8 + (rec[17] & 0x7); |
| 1079 | + if bit_depth > 10 { | ||
| 987 | return Err(format!( | 1080 | return Err(format!( |
| 988 | - "10-bit HEVC (Main 10) is not supported yet — this file is {}-bit", | 1081 | + "{bit_depth}-bit HEVC is not supported — 8- and 10-bit are what the decoder carries" |
| 989 | - 8 + (rec[17] & 0x7) | ||
| 990 | ) | 1082 | ) |
| 991 | .into()); | 1083 | .into()); |
| 992 | } | 1084 | } |
| @@ -1021,7 +1113,7 @@ fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec<u8>)> { | |||
| 1021 | if sets.is_empty() { | 1113 | if sets.is_empty() { |
| 1022 | return Err("hvcC box carries no VPS/SPS/PPS".into()); | 1114 | return Err("hvcC box carries no VPS/SPS/PPS".into()); |
| 1023 | } | 1115 | } |
| 1024 | - Ok((usize::from(flags & 0x3) + 1, sets)) | 1116 | + Ok((usize::from(flags & 0x3) + 1, sets, bit_depth)) |
| 1025 | } | 1117 | } |
| 1026 | 1118 | ||
| 1027 | /// Payload of the first top-level box of type `want`, or `None` if the file has | 1119 | /// Payload of the first top-level box of type `want`, or `None` if the file has |
| @@ -1061,7 +1153,7 @@ fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result<Option<Vec<u8>>> | |||
| 1061 | /// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first | 1153 | /// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first |
| 1062 | /// malformed header rather than erroring: every caller is looking for one box | 1154 | /// malformed header rather than erroring: every caller is looking for one box |
| 1063 | /// and reports its own absence. | 1155 | /// and reports its own absence. |
| 1064 | -fn boxes(mut buf: &[u8]) -> impl Iterator<Item = (&[u8; 4], &[u8])> { | 1156 | +pub(crate) fn boxes(mut buf: &[u8]) -> impl Iterator<Item = (&[u8; 4], &[u8])> { |
| 1065 | std::iter::from_fn(move || { | 1157 | std::iter::from_fn(move || { |
| 1066 | let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?; | 1158 | let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?; |
| 1067 | let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize | 1159 | let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize |
| @@ -1126,8 +1218,9 @@ mod tests { | |||
| 1126 | rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength | 1218 | rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength |
| 1127 | rec.extend_from_slice(&[kind << 1, nal]); | 1219 | rec.extend_from_slice(&[kind << 1, nal]); |
| 1128 | } | 1220 | } |
| 1129 | - let (len, sets) = parse_hvcc(&rec).unwrap(); | 1221 | + let (len, sets, depth) = parse_hvcc(&rec).unwrap(); |
| 1130 | assert_eq!(len, 2); | 1222 | assert_eq!(len, 2); |
| 1223 | + assert_eq!(depth, 8); | ||
| 1131 | assert_eq!( | 1224 | assert_eq!( |
| 1132 | sets, | 1225 | sets, |
| 1133 | [ | 1226 | [ |
| @@ -1137,11 +1230,16 @@ mod tests { | |||
| 1137 | ] | 1230 | ] |
| 1138 | ); | 1231 | ); |
| 1139 | 1232 | ||
| 1140 | - // 10-bit is refused by name rather than decoded into an 8-bit surface. | 1233 | + // Main 10 is read, and read as 10-bit: that is what picks the P010 |
| 1234 | + // surface pool over the NV12 one. | ||
| 1141 | let mut main10 = rec.clone(); | 1235 | let mut main10 = rec.clone(); |
| 1142 | main10[17] = 0xf8 | 2; | 1236 | main10[17] = 0xf8 | 2; |
| 1143 | - let refused = parse_hvcc(&main10).unwrap_err().to_string(); | 1237 | + assert_eq!(parse_hvcc(&main10).unwrap().2, 10); |
| 1144 | - assert!(refused.contains("10-bit"), "{refused}"); | 1238 | + // 12-bit has no pool and no profile here, and is refused by name. |
| 1239 | + let mut main12 = rec.clone(); | ||
| 1240 | + main12[17] = 0xf8 | 4; | ||
| 1241 | + let refused = parse_hvcc(&main12).unwrap_err().to_string(); | ||
| 1242 | + assert!(refused.contains("12-bit"), "{refused}"); | ||
| 1145 | // Nothing is read past the end of a truncated box. | 1243 | // Nothing is read past the end of a truncated box. |
| 1146 | assert!(parse_hvcc(&rec[..20]).is_err()); | 1244 | assert!(parse_hvcc(&rec[..20]).is_err()); |
| 1147 | assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); | 1245 | assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); |
| @@ -1,9 +1,11 @@ | |||
| 1 | //! The project file: a line of text per thing, and nothing else. | 1 | //! The project file: a line of text per thing, and nothing else. |
| 2 | //! | 2 | //! |
| 3 | //! ```text | 3 | //! ```text |
| 4 | -//! edith 8 | 4 | +//! edith 9 |
| 5 | //! playhead 90 | 5 | //! playhead 90 |
| 6 | //! resolution 1920 1080 | 6 | //! resolution 1920 1080 |
| 7 | +//! fps 30.0 | ||
| 8 | +//! limiter -1.0 on | ||
| 7 | //! source 0 test_av.mp4 | 9 | //! source 0 test_av.mp4 |
| 8 | //! source 1 /elsewhere/test_av2.mp4 | 10 | //! source 1 /elsewhere/test_av2.mp4 |
| 9 | //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk | 11 | //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk |
| @@ -12,8 +14,27 @@ | |||
| 12 | //! audio 1 0 0 120 0 0 0 - fit 1000 | 14 | //! audio 1 0 0 120 0 0 0 - fit 1000 |
| 13 | //! video 2 120 0 120 1 - - - fill 2000 | 15 | //! video 2 120 0 120 1 - - - fill 2000 |
| 14 | //! audio 2 | 16 | //! audio 2 |
| 17 | +//! gain audio 1 -3.0 | ||
| 15 | //! ``` | 18 | //! ``` |
| 16 | //! | 19 | //! |
| 20 | +//! The `fps` line is the rate the timeline was cut at, printed so it reads back | ||
| 21 | +//! bit-exactly. A file without one (every dialect before v9) means "whatever | ||
| 22 | +//! the scaffolding source runs at", which is what such a project always was and | ||
| 23 | +//! is an answer only a project holding a video has | ||
| 24 | +//! ([`crate::PlaybackSession::open_project`]). | ||
| 25 | +//! | ||
| 26 | +//! The `limiter` line is the master limiter over the whole mix | ||
| 27 | +//! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, | ||
| 28 | +//! spelled `on` or `off`. Left out when it is the default, which is off. | ||
| 29 | +//! | ||
| 30 | +//! A `gain` line is `gain <kind> <lane> <dB>`: how loud that whole lane plays, | ||
| 31 | +//! everything on it and every frequency of it -- a different thing from a | ||
| 32 | +//! clip's `eq` line, which is one take and one band. It names its lane the way | ||
| 33 | +//! a clip line does and comes *after* the lanes, because a lane is declared by | ||
| 34 | +//! its clips and a gain declares nothing. Only a lane somebody has turned gets | ||
| 35 | +//! one; the rest are at 0 dB, which is where every lane of every dialect before | ||
| 36 | +//! v9 is. | ||
| 37 | +//! | ||
| 17 | //! The `resolution` line is the **project's** picture size, which is a | 38 | //! The `resolution` line is the **project's** picture size, which is a |
| 18 | //! different thing from any source's: media of other sizes are placed on it. | 39 | //! different thing from any source's: media of other sizes are placed on it. |
| 19 | //! It belongs once, beside the playhead, and a file without one (every dialect | 40 | //! It belongs once, beside the playhead, and a file without one (every dialect |
| @@ -58,7 +79,10 @@ | |||
| 58 | //! is the only way an empty lane could still be there on the way back. A lane | 79 | //! is the only way an empty lane could still be there on the way back. A lane |
| 59 | //! number may not skip one of its kind. | 80 | //! number may not skip one of its kind. |
| 60 | //! | 81 | //! |
| 61 | -//! **Version 7** was this without the clip's speed field -- every clip of such | 82 | +//! **Version 8** was this without the `fps` and `limiter` lines and without |
| 83 | +//! the `gain` ones: such a project mixes every lane at unity, limits nothing, | ||
| 84 | +//! and comes back at the rate its scaffolding source runs at. | ||
| 85 | +//! **Version 7** was that without the clip's speed field -- every clip of such | ||
| 62 | //! a project plays at real time, which is the only rate there was. | 86 | //! a project plays at real time, which is the only rate there was. |
| 63 | //! **Version 6** was that without the `resolution` line and without the clip's | 87 | //! **Version 6** was that without the `resolution` line and without the clip's |
| 64 | //! fit field -- such a project is the size of its first source and letterboxes | 88 | //! fit field -- such a project is the size of its first source and letterboxes |
| @@ -72,9 +96,9 @@ | |||
| 72 | //! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out | 96 | //! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out |
| 73 | //! cumulatively and copied onto both lanes as one group each, which is exactly | 97 | //! cumulatively and copied onto both lanes as one group each, which is exactly |
| 74 | //! what a v1 timeline meant, and an older file simply equalizes and grades | 98 | //! what a v1 timeline meant, and an older file simply equalizes and grades |
| 75 | -//! nothing, and an older one plays everything at real time -- and saving any of | 99 | +//! nothing, and an older one plays everything at real time, and an older one |
| 76 | -//! them writes v8. An older reader refuses a newer | 100 | +//! mixes flat -- and saving any of them writes v9. An older reader refuses a |
| 77 | -//! file by name. | 101 | +//! newer file by name. |
| 78 | //! | 102 | //! |
| 79 | //! Text because an edit list is a few integers and a path, and a path is | 103 | //! Text because an edit list is a few integers and a path, and a path is |
| 80 | //! *bytes* on this platform -- a JSON string would have to lossily decode one. | 104 | //! *bytes* on this platform -- a JSON string would have to lossily decode one. |
| @@ -102,12 +126,14 @@ use std::path::{Path, PathBuf}; | |||
| 102 | 126 | ||
| 103 | use crate::color::ColorParams; | 127 | use crate::color::ColorParams; |
| 104 | use crate::eq::{Band, BandKind, EqParams}; | 128 | use crate::eq::{Band, BandKind, EqParams}; |
| 129 | +use crate::limiter::Limiter; | ||
| 105 | use crate::project::{Clip, Lane, LaneKind, Source, Speed}; | 130 | use crate::project::{Clip, Lane, LaneKind, Source, Speed}; |
| 106 | use crate::scale::FitPolicy; | 131 | use crate::scale::FitPolicy; |
| 107 | 132 | ||
| 108 | /// What [`save`] writes. Read support goes back to `edith 1`; see the module | 133 | /// What [`save`] writes. Read support goes back to `edith 1`; see the module |
| 109 | /// docs for what those dialects looked like. | 134 | /// docs for what those dialects looked like. |
| 110 | -const MAGIC: &[u8] = b"edith 8"; | 135 | +const MAGIC: &[u8] = b"edith 9"; |
| 136 | +const MAGIC_V8: &[u8] = b"edith 8"; | ||
| 111 | const MAGIC_V7: &[u8] = b"edith 7"; | 137 | const MAGIC_V7: &[u8] = b"edith 7"; |
| 112 | const MAGIC_V6: &[u8] = b"edith 6"; | 138 | const MAGIC_V6: &[u8] = b"edith 6"; |
| 113 | const MAGIC_V5: &[u8] = b"edith 5"; | 139 | const MAGIC_V5: &[u8] = b"edith 5"; |
| @@ -136,18 +162,37 @@ pub struct Document { | |||
| 136 | /// The project's own picture size. `None` for every dialect before v7 and | 162 | /// The project's own picture size. `None` for every dialect before v7 and |
| 137 | /// for a v7 file that leaves it out, which both mean "source 0's picture". | 163 | /// for a v7 file that leaves it out, which both mean "source 0's picture". |
| 138 | pub resolution: Option<(u32, u32)>, | 164 | pub resolution: Option<(u32, u32)>, |
| 165 | + /// Every lane's own volume in dB, in the order `lanes` is in and as long as | ||
| 166 | + /// it; `0.0` for a lane nobody has turned, which is every lane of every | ||
| 167 | + /// dialect before v9. | ||
| 168 | + pub gains: Vec<f32>, | ||
| 169 | + /// The master limiter. Off for every dialect before v9, and for a v9 file | ||
| 170 | + /// that leaves the line out. | ||
| 171 | + pub limiter: Limiter, | ||
| 172 | + /// The timeline's frame rate. `None` for every dialect before v9 and for a | ||
| 173 | + /// v9 file that leaves it out, which both mean "whatever the scaffolding | ||
| 174 | + /// source runs at" -- the inference a project of nothing but stills and | ||
| 175 | + /// songs has no answer for (see | ||
| 176 | + /// [`crate::PlaybackSession::open_project`]). | ||
| 177 | + pub fps: Option<f64>, | ||
| 139 | pub playhead: u32, | 178 | pub playhead: u32, |
| 140 | } | 179 | } |
| 141 | 180 | ||
| 142 | /// Writes the project to `path`, atomically. `sources`, `eq` and `color` should | 181 | /// Writes the project to `path`, atomically. `sources`, `eq` and `color` should |
| 143 | -/// already be orphan-free ([`crate::Project::without_orphan_sources`]). | 182 | +/// already be orphan-free ([`crate::Project::without_orphan_sources`]); |
| 183 | +/// `gains` is one dB per lane in the same order the lanes are in | ||
| 184 | +/// ([`crate::Project::lane_gains`]). | ||
| 185 | +#[allow(clippy::too_many_arguments)] | ||
| 144 | pub fn save( | 186 | pub fn save( |
| 145 | path: &Path, | 187 | path: &Path, |
| 146 | sources: &[Source], | 188 | sources: &[Source], |
| 147 | lanes: &[(LaneKind, Vec<Clip>)], | 189 | lanes: &[(LaneKind, Vec<Clip>)], |
| 190 | + gains: &[f32], | ||
| 148 | eq: &[EqParams], | 191 | eq: &[EqParams], |
| 149 | color: &[ColorParams], | 192 | color: &[ColorParams], |
| 150 | resolution: (u32, u32), | 193 | resolution: (u32, u32), |
| 194 | + fps: Option<f64>, | ||
| 195 | + limiter: Limiter, | ||
| 151 | playhead: u32, | 196 | playhead: u32, |
| 152 | ) -> crate::Result<()> { | 197 | ) -> crate::Result<()> { |
| 153 | let dir = project_dir(path); | 198 | let dir = project_dir(path); |
| @@ -160,7 +205,9 @@ pub fn save( | |||
| 160 | // the second one puts the name itself there. | 205 | // the second one puts the name itself there. |
| 161 | let result = std::fs::File::create(&part) | 206 | let result = std::fs::File::create(&part) |
| 162 | .and_then(|mut f| { | 207 | .and_then(|mut f| { |
| 163 | - f.write_all(&emit(&dir, sources, lanes, eq, color, resolution, playhead))?; | 208 | + f.write_all(&emit( |
| 209 | + &dir, sources, lanes, gains, eq, color, resolution, fps, limiter, playhead, | ||
| 210 | + ))?; | ||
| 164 | f.sync_all() | 211 | f.sync_all() |
| 165 | }) | 212 | }) |
| 166 | .and_then(|()| std::fs::rename(&part, path)) | 213 | .and_then(|()| std::fs::rename(&part, path)) |
| @@ -190,13 +237,17 @@ fn project_dir(path: &Path) -> PathBuf { | |||
| 190 | dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()) | 237 | dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()) |
| 191 | } | 238 | } |
| 192 | 239 | ||
| 240 | +#[allow(clippy::too_many_arguments)] | ||
| 193 | fn emit( | 241 | fn emit( |
| 194 | dir: &Path, | 242 | dir: &Path, |
| 195 | sources: &[Source], | 243 | sources: &[Source], |
| 196 | lanes: &[(LaneKind, Vec<Clip>)], | 244 | lanes: &[(LaneKind, Vec<Clip>)], |
| 245 | + gains: &[f32], | ||
| 197 | eq: &[EqParams], | 246 | eq: &[EqParams], |
| 198 | color: &[ColorParams], | 247 | color: &[ColorParams], |
| 199 | resolution: (u32, u32), | 248 | resolution: (u32, u32), |
| 249 | + fps: Option<f64>, | ||
| 250 | + limiter: Limiter, | ||
| 200 | playhead: u32, | 251 | playhead: u32, |
| 201 | ) -> Vec<u8> { | 252 | ) -> Vec<u8> { |
| 202 | let mut out = Vec::new(); | 253 | let mut out = Vec::new(); |
| @@ -204,6 +255,26 @@ fn emit( | |||
| 204 | out.push(b'\n'); | 255 | out.push(b'\n'); |
| 205 | out.extend_from_slice(format!("playhead {playhead}\n").as_bytes()); | 256 | out.extend_from_slice(format!("playhead {playhead}\n").as_bytes()); |
| 206 | out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes()); | 257 | out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes()); |
| 258 | + // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read | ||
| 259 | + // back as the very number, or every clip on it lands on another frame. | ||
| 260 | + if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) { | ||
| 261 | + out.extend_from_slice(format!("fps {fps:?}\n").as_bytes()); | ||
| 262 | + } | ||
| 263 | + // Written only when it is not the default, so a project nobody has limited | ||
| 264 | + // is the same bytes it was in v8 bar the version line. | ||
| 265 | + if limiter != Limiter::default() { | ||
| 266 | + out.extend_from_slice( | ||
| 267 | + format!( | ||
| 268 | + "limiter {:?} {}\n", | ||
| 269 | + limiter.ceiling_db, | ||
| 270 | + match limiter.on { | ||
| 271 | + true => "on", | ||
| 272 | + false => "off", | ||
| 273 | + } | ||
| 274 | + ) | ||
| 275 | + .as_bytes(), | ||
| 276 | + ); | ||
| 277 | + } | ||
| 207 | for s in sources { | 278 | for s in sources { |
| 208 | out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes()); | 279 | out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes()); |
| 209 | escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); | 280 | escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); |
| @@ -276,6 +347,25 @@ fn emit( | |||
| 276 | ); | 347 | ); |
| 277 | } | 348 | } |
| 278 | } | 349 | } |
| 350 | + // After the lanes, not before them: a gain line names a lane that has to be | ||
| 351 | + // there already, and a lane is declared by its own lines. Only the lanes | ||
| 352 | + // somebody has turned get one. | ||
| 353 | + let (mut video, mut audio) = (0, 0); | ||
| 354 | + for ((kind, _), &db) in lanes.iter().zip(gains) { | ||
| 355 | + let (keyword, ord) = match kind { | ||
| 356 | + LaneKind::Video => { | ||
| 357 | + video += 1; | ||
| 358 | + ("video", video) | ||
| 359 | + } | ||
| 360 | + LaneKind::Audio => { | ||
| 361 | + audio += 1; | ||
| 362 | + ("audio", audio) | ||
| 363 | + } | ||
| 364 | + }; | ||
| 365 | + if db != 0.0 { | ||
| 366 | + out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes()); | ||
| 367 | + } | ||
| 368 | + } | ||
| 279 | out | 369 | out |
| 280 | } | 370 | } |
| 281 | 371 | ||
| @@ -289,8 +379,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 289 | // The dialects that wrote a source line without its stream field. Reading | 379 | // The dialects that wrote a source line without its stream field. Reading |
| 290 | // one is the whole of what "an old project still opens" means here. | 380 | // one is the whole of what "an old project still opens" means here. |
| 291 | let streamless = v1 || first == MAGIC_V2; | 381 | let streamless = v1 || first == MAGIC_V2; |
| 292 | - // The one that carries a per-clip speed... | 382 | + // The one that carries the mix -- lane volumes, the master limiter and the |
| 293 | - let v8 = first == MAGIC; | 383 | + // rate the timeline was cut at... |
| 384 | + let v9 = first == MAGIC; | ||
| 385 | + // ...the ones that carry a per-clip speed... | ||
| 386 | + let v8 = v9 || first == MAGIC_V8; | ||
| 294 | // ...the ones that carry a project resolution and per-clip fit policies... | 387 | // ...the ones that carry a project resolution and per-clip fit policies... |
| 295 | let v7 = v8 || first == MAGIC_V7; | 388 | let v7 = v8 || first == MAGIC_V7; |
| 296 | // ...the ones that carry colour grades... | 389 | // ...the ones that carry colour grades... |
| @@ -322,6 +415,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 322 | // Nothing before v7 has a resolution of its own: source 0's picture is | 415 | // Nothing before v7 has a resolution of its own: source 0's picture is |
| 323 | // what those projects were, and `None` is how the loader is told so. | 416 | // what those projects were, and `None` is how the loader is told so. |
| 324 | resolution: None, | 417 | resolution: None, |
| 418 | + // ...and nothing before v9 carries a mix or a rate: every lane at unity, | ||
| 419 | + // no limiter, and the rate inferred from the scaffold as it always was. | ||
| 420 | + gains: Vec::new(), | ||
| 421 | + limiter: Limiter::default(), | ||
| 422 | + fps: None, | ||
| 325 | playhead: 0, | 423 | playhead: 0, |
| 326 | }; | 424 | }; |
| 327 | let mut playhead_seen = false; | 425 | let mut playhead_seen = false; |
| @@ -360,6 +458,76 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 360 | } | 458 | } |
| 361 | doc.resolution = Some((width, height)); | 459 | doc.resolution = Some((width, height)); |
| 362 | } | 460 | } |
| 461 | + b"fps" if v9 => { | ||
| 462 | + if doc.fps.is_some() || !doc.sources.is_empty() { | ||
| 463 | + return Err(format!("line {n}: fps belongs once, before the sources").into()); | ||
| 464 | + } | ||
| 465 | + let f = fields(rest, 1, "fps", n)?; | ||
| 466 | + let fps = std::str::from_utf8(f[0]) | ||
| 467 | + .ok() | ||
| 468 | + .and_then(|s| s.parse::<f64>().ok()) | ||
| 469 | + .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0) | ||
| 470 | + .ok_or_else(|| { | ||
| 471 | + format!( | ||
| 472 | + "line {n}: {:?} is not a frame rate", | ||
| 473 | + String::from_utf8_lossy(f[0]) | ||
| 474 | + ) | ||
| 475 | + })?; | ||
| 476 | + doc.fps = Some(fps); | ||
| 477 | + } | ||
| 478 | + b"limiter" if v9 => { | ||
| 479 | + if !doc.sources.is_empty() { | ||
| 480 | + return Err( | ||
| 481 | + format!("line {n}: limiter belongs once, before the sources").into(), | ||
| 482 | + ); | ||
| 483 | + } | ||
| 484 | + let f = fields(rest, 2, "limiter", n)?; | ||
| 485 | + let on = match f[1] { | ||
| 486 | + b"on" => true, | ||
| 487 | + b"off" => false, | ||
| 488 | + other => { | ||
| 489 | + return Err(format!( | ||
| 490 | + "line {n}: limiter is on or off, not {:?}", | ||
| 491 | + String::from_utf8_lossy(other) | ||
| 492 | + ) | ||
| 493 | + .into()); | ||
| 494 | + } | ||
| 495 | + }; | ||
| 496 | + // Through the same clamp a nudge goes through: a hand-written | ||
| 497 | + // ceiling above full scale is a ceiling that limits nothing. | ||
| 498 | + doc.limiter = Limiter { | ||
| 499 | + on, | ||
| 500 | + ..Limiter::default() | ||
| 501 | + } | ||
| 502 | + .with_ceiling(float(f[0], n)?); | ||
| 503 | + } | ||
| 504 | + // After the lanes it names, which is where `emit` writes it: a lane | ||
| 505 | + // is declared by its own lines, and a gain declares nothing. | ||
| 506 | + b"gain" if v9 => { | ||
| 507 | + let f = fields(rest, 3, "gain", n)?; | ||
| 508 | + let kind = match f[0] { | ||
| 509 | + b"video" => LaneKind::Video, | ||
| 510 | + b"audio" => LaneKind::Audio, | ||
| 511 | + other => { | ||
| 512 | + return Err(format!( | ||
| 513 | + "line {n}: gain names {:?}, not a lane kind", | ||
| 514 | + String::from_utf8_lossy(other) | ||
| 515 | + ) | ||
| 516 | + .into()); | ||
| 517 | + } | ||
| 518 | + }; | ||
| 519 | + let ord = number(f[1], n)?; | ||
| 520 | + let at = doc | ||
| 521 | + .lanes | ||
| 522 | + .iter() | ||
| 523 | + .enumerate() | ||
| 524 | + .filter(|(_, (k, _))| *k == kind) | ||
| 525 | + .nth(ord.saturating_sub(1) as usize) | ||
| 526 | + .map(|(at, _)| at) | ||
| 527 | + .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?; | ||
| 528 | + doc.gains.resize(doc.lanes.len(), 0.0); | ||
| 529 | + doc.gains[at] = float(f[2], n)?; | ||
| 530 | + } | ||
| 363 | b"source" => { | 531 | b"source" => { |
| 364 | if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { | 532 | if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { |
| 365 | return Err(format!("line {n}: source after a clip").into()); | 533 | return Err(format!("line {n}: source after a clip").into()); |
| @@ -518,6 +686,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> { | |||
| 518 | } | 686 | } |
| 519 | } | 687 | } |
| 520 | } | 688 | } |
| 689 | + // One per lane whatever the file said, so a caller may zip the two. | ||
| 690 | + doc.gains.resize(doc.lanes.len(), 0.0); | ||
| 521 | // A file whose lanes are all empty *is* a project -- the emptied timeline, | 691 | // A file whose lanes are all empty *is* a project -- the emptied timeline, |
| 522 | // saved. What it may not be is laneless; [`crate::Project::from_parts`] | 692 | // saved. What it may not be is laneless; [`crate::Project::from_parts`] |
| 523 | // refuses that one, by the name it has there. | 693 | // refuses that one, by the name it has there. |
| @@ -773,6 +943,35 @@ fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> { | |||
| 773 | mod tests { | 943 | mod tests { |
| 774 | use super::*; | 944 | use super::*; |
| 775 | 945 | ||
| 946 | + /// [`super::emit`] for a project whose mix is flat: every lane at unity, no | ||
| 947 | + /// limiter, no rate written. Shadows the real one for the tests that were | ||
| 948 | + /// written before there was a mix to write -- the dialect they are about is | ||
| 949 | + /// the one this emits, and a v9 file with flat settings is a v8 file bar | ||
| 950 | + /// its version line, which is exactly what they assert. | ||
| 951 | + #[allow(clippy::too_many_arguments)] | ||
| 952 | + fn emit( | ||
| 953 | + dir: &Path, | ||
| 954 | + sources: &[Source], | ||
| 955 | + lanes: &[(LaneKind, Vec<Clip>)], | ||
| 956 | + eq: &[EqParams], | ||
| 957 | + color: &[ColorParams], | ||
| 958 | + resolution: (u32, u32), | ||
| 959 | + playhead: u32, | ||
| 960 | + ) -> Vec<u8> { | ||
| 961 | + super::emit( | ||
| 962 | + dir, | ||
| 963 | + sources, | ||
| 964 | + lanes, | ||
| 965 | + &[], | ||
| 966 | + eq, | ||
| 967 | + color, | ||
| 968 | + resolution, | ||
| 969 | + None, | ||
| 970 | + Limiter::default(), | ||
| 971 | + playhead, | ||
| 972 | + ) | ||
| 973 | + } | ||
| 974 | + | ||
| 776 | fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip { | 975 | fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip { |
| 777 | Clip { | 976 | Clip { |
| 778 | start, | 977 | start, |
| @@ -833,7 +1032,7 @@ mod tests { | |||
| 833 | let bytes = flat(&dir, &sources, &lanes, 12); | 1032 | let bytes = flat(&dir, &sources, &lanes, 12); |
| 834 | assert_eq!( | 1033 | assert_eq!( |
| 835 | String::from_utf8_lossy(&bytes), | 1034 | String::from_utf8_lossy(&bytes), |
| 836 | - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1035 | + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 837 | source 2 /elsewhere/b.mp4\n\ | 1036 | source 2 /elsewhere/b.mp4\n\ |
| 838 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1037 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 839 | audio 1 0 0 30 0 0 - - fit 1000\n", | 1038 | audio 1 0 0 30 0 0 - - fit 1000\n", |
| @@ -870,7 +1069,7 @@ mod tests { | |||
| 870 | let bytes = flat(&dir, &sources, &lanes, 7); | 1069 | let bytes = flat(&dir, &sources, &lanes, 7); |
| 871 | assert_eq!( | 1070 | assert_eq!( |
| 872 | String::from_utf8_lossy(&bytes), | 1071 | String::from_utf8_lossy(&bytes), |
| 873 | - "edith 8\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ | 1072 | + "edith 9\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 874 | video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ | 1073 | video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ |
| 875 | video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", | 1074 | video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", |
| 876 | "an empty lane is a line of its own; everything else is its clips" | 1075 | "an empty lane is a line of its own; everything else is its clips" |
| @@ -978,7 +1177,7 @@ mod tests { | |||
| 978 | let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); | 1177 | let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); |
| 979 | assert_eq!( | 1178 | assert_eq!( |
| 980 | String::from_utf8_lossy(&bytes), | 1179 | String::from_utf8_lossy(&bytes), |
| 981 | - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1180 | + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 982 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ | 1181 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ |
| 983 | eq 16777215.0:-0.1:3.918315e-39:hs\n\ | 1182 | eq 16777215.0:-0.1:3.918315e-39:hs\n\ |
| 984 | eq\n\ | 1183 | eq\n\ |
| @@ -1082,7 +1281,7 @@ mod tests { | |||
| 1082 | let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); | 1281 | let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); |
| 1083 | assert_eq!( | 1282 | assert_eq!( |
| 1084 | String::from_utf8_lossy(&bytes), | 1283 | String::from_utf8_lossy(&bytes), |
| 1085 | - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1284 | + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1086 | color 0.1:1.2:0.9:-0.3\n\ | 1285 | color 0.1:1.2:0.9:-0.3\n\ |
| 1087 | color -1e-7:16777215.0:3.918315e-39:-0.0\n\ | 1286 | color -1e-7:16777215.0:3.918315e-39:-0.0\n\ |
| 1088 | color 0.0:1.0:1.0:0.0\n\ | 1287 | color 0.0:1.0:1.0:0.0\n\ |
| @@ -1147,7 +1346,7 @@ mod tests { | |||
| 1147 | (1280, 720), | 1346 | (1280, 720), |
| 1148 | old.playhead | 1347 | old.playhead |
| 1149 | )), | 1348 | )), |
| 1150 | - "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | 1349 | + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1151 | eq 80.0:-3.0:0.707:ls\n\ | 1350 | eq 80.0:-3.0:0.707:ls\n\ |
| 1152 | video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" | 1351 | video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" |
| 1153 | ); | 1352 | ); |
| @@ -1185,7 +1384,7 @@ mod tests { | |||
| 1185 | let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); | 1384 | let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); |
| 1186 | assert_eq!( | 1385 | assert_eq!( |
| 1187 | String::from_utf8_lossy(&bytes), | 1386 | String::from_utf8_lossy(&bytes), |
| 1188 | - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ | 1387 | + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1189 | video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ | 1388 | video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ |
| 1190 | audio 1 0 0 30 0 - - - fit 2000\n", | 1389 | audio 1 0 0 30 0 - - - fit 2000\n", |
| 1191 | "the rate is the clip line's last field, in thousandths" | 1390 | "the rate is the clip line's last field, in thousandths" |
| @@ -1214,7 +1413,7 @@ mod tests { | |||
| 1214 | (1280, 720), | 1413 | (1280, 720), |
| 1215 | old.playhead | 1414 | old.playhead |
| 1216 | )), | 1415 | )), |
| 1217 | - "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | 1416 | + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1218 | video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" | 1417 | video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" |
| 1219 | ); | 1418 | ); |
| 1220 | // A rate outside what the editor can set is a corrupt line, by name. | 1419 | // A rate outside what the editor can set is a corrupt line, by name. |
| @@ -1225,6 +1424,105 @@ mod tests { | |||
| 1225 | ); | 1424 | ); |
| 1226 | } | 1425 | } |
| 1227 | 1426 | ||
| 1427 | + /// The whole of the v9 bump, the speed test's twin: the mix a project was | ||
| 1428 | + /// left at -- every track's own volume and the master limiter -- plus the | ||
| 1429 | + /// rate it was cut at, all written, all read back as the very numbers, and | ||
| 1430 | + /// a v8 file (which has none of them) loading flat and unlimited. | ||
| 1431 | + #[test] | ||
| 1432 | + fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() { | ||
| 1433 | + let dir = PathBuf::from("/proj"); | ||
| 1434 | + let sources = vec![Source::new("/proj/a.mp4", 0)]; | ||
| 1435 | + let lanes = vec![ | ||
| 1436 | + (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]), | ||
| 1437 | + (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]), | ||
| 1438 | + // A second audio track, turned down: the gain lines are per lane, | ||
| 1439 | + // so the two must not run into one another. | ||
| 1440 | + (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]), | ||
| 1441 | + ]; | ||
| 1442 | + let limiter = Limiter { | ||
| 1443 | + ceiling_db: -1.5, | ||
| 1444 | + on: true, | ||
| 1445 | + }; | ||
| 1446 | + let bytes = super::emit( | ||
| 1447 | + &dir, | ||
| 1448 | + &sources, | ||
| 1449 | + &lanes, | ||
| 1450 | + &[0.0, 3.0, -6.5], | ||
| 1451 | + &[], | ||
| 1452 | + &[], | ||
| 1453 | + (1280, 720), | ||
| 1454 | + Some(23.976023976023978), | ||
| 1455 | + limiter, | ||
| 1456 | + 0, | ||
| 1457 | + ); | ||
| 1458 | + assert_eq!( | ||
| 1459 | + String::from_utf8_lossy(&bytes), | ||
| 1460 | + "edith 9\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ | ||
| 1461 | + limiter -1.5 on\nsource 0 a.mp4\n\ | ||
| 1462 | + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ | ||
| 1463 | + audio 2 0 0 30 0 - - - fit 1000\n\ | ||
| 1464 | + gain audio 1 3.0\ngain audio 2 -6.5\n", | ||
| 1465 | + "the mix is lines of its own, the gains after the lanes they name" | ||
| 1466 | + ); | ||
| 1467 | + let back = parse(&bytes, &dir).expect("parse"); | ||
| 1468 | + assert_eq!(back.lanes, lanes); | ||
| 1469 | + assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order"); | ||
| 1470 | + assert_eq!(back.limiter, limiter); | ||
| 1471 | + assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976"); | ||
| 1472 | + | ||
| 1473 | + // ...and the dialect before it, which carried none of the three: a v8 | ||
| 1474 | + // file mixes flat, limits nothing, and says nothing about its rate. | ||
| 1475 | + let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | ||
| 1476 | + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"; | ||
| 1477 | + let old = parse(v8, &dir).expect("v8 parses"); | ||
| 1478 | + assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity"); | ||
| 1479 | + assert_eq!(old.limiter, Limiter::default()); | ||
| 1480 | + assert_eq!(old.fps, None); | ||
| 1481 | + // A v9 file may leave all three out too, and means the same thing. | ||
| 1482 | + assert_eq!( | ||
| 1483 | + String::from_utf8_lossy(&emit( | ||
| 1484 | + &dir, | ||
| 1485 | + &old.sources, | ||
| 1486 | + &old.lanes, | ||
| 1487 | + &old.eq, | ||
| 1488 | + &old.color, | ||
| 1489 | + (1280, 720), | ||
| 1490 | + old.playhead | ||
| 1491 | + )), | ||
| 1492 | + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ | ||
| 1493 | + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" | ||
| 1494 | + ); | ||
| 1495 | + | ||
| 1496 | + // Each of the three refuses by name, on its own line. | ||
| 1497 | + for (text, want) in [ | ||
| 1498 | + ( | ||
| 1499 | + "edith 9\nfps nope\nsource 0 a.mp4\n", | ||
| 1500 | + "line 2: \"nope\" is not a frame rate", | ||
| 1501 | + ), | ||
| 1502 | + ( | ||
| 1503 | + "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n", | ||
| 1504 | + "line 2: limiter is on or off, not \"maybe\"", | ||
| 1505 | + ), | ||
| 1506 | + ( | ||
| 1507 | + "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n", | ||
| 1508 | + "line 4: gain names a lane that is not there", | ||
| 1509 | + ), | ||
| 1510 | + ( | ||
| 1511 | + "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n", | ||
| 1512 | + "line 4: gain names \"lane\", not a lane kind", | ||
| 1513 | + ), | ||
| 1514 | + ] { | ||
| 1515 | + assert_eq!( | ||
| 1516 | + parse(text.as_bytes(), &dir).unwrap_err().to_string(), | ||
| 1517 | + want, | ||
| 1518 | + "{text:?}" | ||
| 1519 | + ); | ||
| 1520 | + } | ||
| 1521 | + // A hand-written ceiling nothing could limit at is clamped, not taken. | ||
| 1522 | + let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses"); | ||
| 1523 | + assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB); | ||
| 1524 | + } | ||
| 1525 | + | ||
| 1228 | /// The refusals the colour grammar adds, each naming its line. | 1526 | /// The refusals the colour grammar adds, each naming its line. |
| 1229 | #[test] | 1527 | #[test] |
| 1230 | fn a_malformed_colour_names_its_line() { | 1528 | fn a_malformed_colour_names_its_line() { |
| @@ -1355,7 +1653,7 @@ mod tests { | |||
| 1355 | assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); | 1653 | assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); |
| 1356 | assert_eq!( | 1654 | assert_eq!( |
| 1357 | String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), | 1655 | String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), |
| 1358 | - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1656 | + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1359 | source 2 /elsewhere/b.mp4\n\ | 1657 | source 2 /elsewhere/b.mp4\n\ |
| 1360 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1658 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 1361 | audio 1 0 0 30 0 0 - - fit 1000\n" | 1659 | audio 1 0 0 30 0 0 - - fit 1000\n" |
| @@ -1408,7 +1706,7 @@ mod tests { | |||
| 1408 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); | 1706 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); |
| 1409 | assert_eq!( | 1707 | assert_eq!( |
| 1410 | String::from_utf8_lossy(&v5), | 1708 | String::from_utf8_lossy(&v5), |
| 1411 | - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ | 1709 | + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ |
| 1412 | source 0 /elsewhere/b.mp4\n\ | 1710 | source 0 /elsewhere/b.mp4\n\ |
| 1413 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ | 1711 | video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ |
| 1414 | audio 1 0 0 30 0 0 - - fit 1000\n", | 1712 | audio 1 0 0 30 0 0 - - fit 1000\n", |
| @@ -1440,7 +1738,7 @@ mod tests { | |||
| 1440 | // Saved again it is the current version, which round-trips to the | 1738 | // Saved again it is the current version, which round-trips to the |
| 1441 | // same document. | 1739 | // same document. |
| 1442 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); | 1740 | let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); |
| 1443 | - assert!(v5.starts_with(b"edith 8\n")); | 1741 | + assert!(v5.starts_with(b"edith 9\n")); |
| 1444 | let again = parse(&v5, &dir).expect("v5 parses"); | 1742 | let again = parse(&v5, &dir).expect("v5 parses"); |
| 1445 | assert_eq!(again.lanes, back.lanes); | 1743 | assert_eq!(again.lanes, back.lanes); |
| 1446 | // A dialect may not be mixed: lane lines under v1, `clip` under v2. | 1744 | // A dialect may not be mixed: lane lines under v1, `clip` under v2. |
| @@ -1535,14 +1833,17 @@ mod tests { | |||
| 1535 | &two(one.to_vec(), one.to_vec()), | 1833 | &two(one.to_vec(), one.to_vec()), |
| 1536 | &[], | 1834 | &[], |
| 1537 | &[], | 1835 | &[], |
| 1836 | + &[], | ||
| 1538 | (1280, 720), | 1837 | (1280, 720), |
| 1838 | + None, | ||
| 1839 | + Limiter::default(), | ||
| 1539 | 0, | 1840 | 0, |
| 1540 | ) | 1841 | ) |
| 1541 | .expect("save"); | 1842 | .expect("save"); |
| 1542 | let bytes = std::fs::read(&path).expect("read back"); | 1843 | let bytes = std::fs::read(&path).expect("read back"); |
| 1543 | assert_eq!( | 1844 | assert_eq!( |
| 1544 | String::from_utf8_lossy(&bytes), | 1845 | String::from_utf8_lossy(&bytes), |
| 1545 | - "edith 8\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ | 1846 | + "edith 9\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ |
| 1546 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" | 1847 | video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" |
| 1547 | ); | 1848 | ); |
| 1548 | // Loading rejoins the *given* directory, so the file is reached by the | 1849 | // Loading rejoins the *given* directory, so the file is reached by the |
| @@ -1587,10 +1888,10 @@ mod tests { | |||
| 1587 | #[test] | 1888 | #[test] |
| 1588 | fn a_wrong_first_line_is_refused_by_name() { | 1889 | fn a_wrong_first_line_is_refused_by_name() { |
| 1589 | let dir = PathBuf::from("/proj"); | 1890 | let dir = PathBuf::from("/proj"); |
| 1590 | - let err = parse(b"edith 9\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) | 1891 | + let err = parse(b"edith 10\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) |
| 1591 | .unwrap_err() | 1892 | .unwrap_err() |
| 1592 | .to_string(); | 1893 | .to_string(); |
| 1593 | - assert_eq!(err, "line 1: unsupported version 9"); | 1894 | + assert_eq!(err, "line 1: unsupported version 10"); |
| 1594 | for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { | 1895 | for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { |
| 1595 | assert_eq!( | 1896 | assert_eq!( |
| 1596 | parse(junk, &dir).unwrap_err().to_string(), | 1897 | parse(junk, &dir).unwrap_err().to_string(), |
| @@ -1,23 +1,43 @@ | |||
| 1 | -//! Export: the edit list rendered back out as one mp4 or one AV1-in-Matroska — | 1 | +//! Export: the edit list rendered back out as one mp4 (H.264, AV1 or HEVC) or |
| 2 | -//! or, picture left behind, as one WAV or FLAC of the timeline's audio alone. | 2 | +//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC |
| 3 | +//! or MP3 of the timeline's audio alone. | ||
| 4 | +//! | ||
| 5 | +//! The HEVC pair is **intra-only**, and says so wherever it is offered: every | ||
| 6 | +//! frame is a self-contained IDR from the vendored `oxideav-h265`, which is the | ||
| 7 | +//! only shape of a pure-Rust HEVC encode fast enough to wait for (its inter | ||
| 8 | +//! modes code 1080p at 0.81 fps across 12 cores against the intra path's 4.30). | ||
| 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. | ||
| 3 | //! | 11 | //! |
| 4 | //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it | 12 | //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it |
| 5 | -//! is impossible — while audio is copied packet for packet, because there is no | 13 | +//! is impossible — while audio is copied packet for packet wherever a copy can |
| 6 | -//! pure-Rust AAC encoder to re-encode with. The audio-only formats have no such | 14 | +//! say what the timeline says: a copy is exact, free and never a generation of |
| 7 | -//! trouble: `hound` writes PCM and `flacenc` encodes FLAC, both pure Rust, so | 15 | +//! loss. Where it *cannot* — a second audio lane to mix in, a speeded clip, an |
| 8 | -//! those are *decoded* out of the timeline instead of copied. The worker owns | 16 | +//! equalized one, a source that is not AAC inside an mp4's own sample table — |
| 9 | -//! everything: the caller gets an [`ExportHandle`] and polls it from its render | 17 | +//! the sound is decoded, mixed and encoded again with `rusty_aac` |
| 10 | -//! loop. | 18 | +//! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes |
| 19 | +//! PCM, `flacenc` encodes FLAC and `rusty_mp3` encodes MP3, so those are always | ||
| 20 | +//! *decoded* out of the timeline. The worker owns everything: the caller gets an | ||
| 21 | +//! [`ExportHandle`] and polls it from its render loop. | ||
| 22 | +//! | ||
| 23 | +//! **Every video format here carries the timeline's sound**, in whichever | ||
| 24 | +//! container: the mp4 muxer writes an AAC track and so does the Matroska one. | ||
| 25 | +//! Nothing is written picture-only and nothing is left silent without saying so | ||
| 26 | +//! — the only sound that does not come out is sound this engine cannot decode at | ||
| 27 | +//! all (Opus and AC-3 inside a Matroska file), and that is an error by name. | ||
| 11 | //! | 28 | //! |
| 12 | //! A **speeded** clip splits along the same line, and for the same reason. The | 29 | //! A **speeded** clip splits along the same line, and for the same reason. The |
| 13 | //! picture is re-encoded, so the frame walk honours a rate: it takes the source | 30 | //! picture is re-encoded, so the frame walk honours a rate: it takes the source |
| 14 | //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the | 31 | //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the |
| 15 | //! very frame preview holds there) and encodes a held one again rather than | 32 | //! very frame preview holds there) and encodes a held one again rather than |
| 16 | -//! decoding it twice. The sound is *copied*, and a packet carries no rate -- so | 33 | +//! decoding it twice. A clip whose *file* was shot at another rate than the |
| 17 | -//! a speeded clip on the one audio lane an mp4 copies is refused by name | 34 | +//! timeline goes through the same walk with one more conversion on the end |
| 18 | -//! ([`copy_audio`]) rather than written out at 1.00x under a re-timed picture. | 35 | +//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at. |
| 19 | -//! AV1 carries no audio at all and never meets that refusal; WAV and FLAC are | 36 | +//! The sound is *copied* unless something forces a decode, and a packet carries |
| 20 | -//! decoded and resampled, so they honour a rate like the picture does. | 37 | +//! no rate — so a speeded lane is one of the things that forces one |
| 38 | +//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed | ||
| 39 | +//! picture. WAV, FLAC and MP3 are decoded and resampled, so they honour a rate | ||
| 40 | +//! like the picture does. | ||
| 21 | //! | 41 | //! |
| 22 | //! Nothing partial survives a failure: the worker writes to `<out>.part` and | 42 | //! Nothing partial survives a failure: the worker writes to `<out>.part` and |
| 23 | //! renames it onto `out` only once the file is closed and complete, so the | 43 | //! renames it onto `out` only once the file is closed and complete, so the |
| @@ -27,6 +47,8 @@ | |||
| 27 | //! behind (only in-process cleanup is promised), which is an orphan a user can | 47 | //! behind (only in-process cleanup is promised), which is an orphan a user can |
| 28 | //! delete rather than a file that plays for two seconds and stops. | 48 | //! delete rather than a file that plays for two seconds and stops. |
| 29 | 49 | ||
| 50 | +use std::fs::File; | ||
| 51 | +use std::io::{BufWriter, Write}; | ||
| 30 | use std::path::{Path, PathBuf}; | 52 | use std::path::{Path, PathBuf}; |
| 31 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; | 53 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; |
| 32 | use std::sync::{Arc, Mutex}; | 54 | use std::sync::{Arc, Mutex}; |
| @@ -40,8 +62,8 @@ use flacenc::error::Verify; | |||
| 40 | use crate::audio::{AudioMeta, AudioSession}; | 62 | use crate::audio::{AudioMeta, AudioSession}; |
| 41 | use crate::demux::{Demuxer, VideoMeta}; | 63 | use crate::demux::{Demuxer, VideoMeta}; |
| 42 | use crate::hw::{HwEncoder, HwSession}; | 64 | use crate::hw::{HwEncoder, HwSession}; |
| 43 | -use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams}; | 65 | +use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, VideoParams}; |
| 44 | -use crate::project::{LaneKind, Project}; | 66 | +use crate::project::{LaneKind, Project, Rate}; |
| 45 | use crate::scale::Composer; | 67 | use crate::scale::Composer; |
| 46 | 68 | ||
| 47 | /// Progress is reported in permille: an atomic integer the render loop can read | 69 | /// Progress is reported in permille: an atomic integer the render loop can read |
| @@ -58,30 +80,65 @@ const MAX_BITRATE: u64 = 20_000_000; | |||
| 58 | /// on a build with no assembly, which is what this one is. | 80 | /// on a build with no assembly, which is what this one is. |
| 59 | const AV1_SPEED: u8 = 10; | 81 | const AV1_SPEED: u8 = 10; |
| 60 | 82 | ||
| 61 | -/// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are | 83 | +/// The HEVC coding tree block this encoder is fixed at: the coded picture is a |
| 62 | -/// the only *video* pairs with both an encoder and a decoder under this | 84 | +/// whole number of them, which is what the conformance window crops back. |
| 63 | -/// project's no-install rule, and WAV and FLAC are the only audio formats with | 85 | +const CTB: usize = 16; |
| 64 | -/// a pure-Rust encoder at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is | 86 | +/// How many frames the intra HEVC encoder codes at once. Twelve is where the |
| 65 | -/// a licensing decision this project has not taken; Vorbis, Opus and AAC have | 87 | +/// 2026-08-11 bench stopped scaling on this box (4.30 fps at 1080p); more lanes |
| 66 | -/// none. HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import through | 88 | +/// only holds more decoded frames in memory. |
| 67 | -/// the plugin and stop there). A front-end says so rather than hiding the rows. | 89 | +const HEVC_LANES: usize = 12; |
| 90 | +/// Bits per pixel the intra encoder spends at QP 27, measured on the same bench: | ||
| 91 | +/// 0.607 at 720p and 0.586 at 1080p. What [`hevc_qp`] maps a bitrate row through. | ||
| 92 | +const HEVC_BPP_AT_27: f64 = 0.6; | ||
| 93 | +/// The band [`hevc_qp`] is clamped into, for the reason stated there. | ||
| 94 | +const HEVC_QP_MIN: i32 = 22; | ||
| 95 | +const HEVC_QP_MAX: i32 = 40; | ||
| 96 | + | ||
| 97 | +/// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in | ||
| 98 | +/// Matroska or in mp4, the user's pick of container -- are the *video* pairs | ||
| 99 | +/// with both an encoder and a decoder under this project's no-install rule, and | ||
| 100 | +/// WAV, FLAC and MP3 are the standalone audio formats with a pure-Rust encoder: | ||
| 101 | +/// `hound`, `flacenc` and `rusty_mp3`. Vorbis and Opus have none. (AAC does -- | ||
| 102 | +/// `rusty_aac`, which is what a re-encoded video track's sound leaves through -- | ||
| 103 | +/// but AAC is a container's own audio, never a file of its own here.) VP9 is the | ||
| 104 | +/// one codec left that comes in through the plugin and stops there, HEVC having | ||
| 105 | +/// gained an encoder (an intra-only one, which the rows say). A front-end says | ||
| 106 | +/// so rather than hiding the row. | ||
| 107 | +/// | ||
| 108 | +/// **Every video format carries sound.** Which way it carries it is the only | ||
| 109 | +/// difference: copied packet for packet where a copy can say what the timeline | ||
| 110 | +/// says, decoded and encoded again ([`encode_audio`]) where it cannot. | ||
| 68 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | 111 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 69 | pub enum Format { | 112 | pub enum Format { |
| 70 | - /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries | 113 | + /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too, |
| 71 | - /// **one** audio lane: a timeline whose sound is spread over two is refused | 114 | + /// where a copy could not carry the edit (a second audio lane to mix in, a |
| 72 | - /// by name here and mixed by the other two formats, which decode. | 115 | + /// speeded clip, an equalized one, a source no mp4 sample table holds). |
| 73 | #[default] | 116 | #[default] |
| 74 | Mp4, | 117 | Mp4, |
| 75 | - /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound | 118 | + /// AV1 in Matroska, with the timeline's AAC beside it: this engine's |
| 76 | - /// this project can write: there is no AAC or Opus encoder here, and an AAC | 119 | + /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its |
| 77 | - /// track copied in would be one *this engine's own reader* leaves silent | 120 | + /// reader reads one back, symphonia's `mkv` reader being what |
| 78 | - /// (`audio::AudioSession::open` refuses Matroska audio). The sound of an AV1 | 121 | + /// `audio::Track::open` opens it with. |
| 79 | - /// export is a WAV or FLAC beside it, which a front-end says up front. | ||
| 80 | Av1, | 122 | Av1, |
| 81 | - /// The audio lane alone, 16-bit PCM. | 123 | + /// The same AV1 stream in an mp4, for everything that plays mp4 and not |
| 124 | + /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand | ||
| 125 | + /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own, | ||
| 126 | + /// unchanged. | ||
| 127 | + Av1Mp4, | ||
| 128 | + /// HEVC in Matroska, **intra-only**: every frame is a self-contained IDR | ||
| 129 | + /// picture ([`Enc::open_hevc`]), which is what makes a pure-Rust HEVC | ||
| 130 | + /// encoder fast enough to be an export at all. An intraframe master, like | ||
| 131 | + /// ProRes or DNxHD -- large files, and every frame a cut point. | ||
| 132 | + Hevc, | ||
| 133 | + /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4 | ||
| 134 | + /// and not Matroska -- the AV1 pair's split, for the same reason. | ||
| 135 | + HevcMp4, | ||
| 136 | + /// The audio lanes alone, 16-bit PCM. | ||
| 82 | Wav, | 137 | Wav, |
| 83 | - /// The audio lane alone, losslessly compressed. | 138 | + /// The audio lanes alone, losslessly compressed. |
| 84 | Flac, | 139 | Flac, |
| 140 | + /// The audio lanes alone, MPEG-1 Layer III at 256 kbps CBR (`rusty_mp3`). | ||
| 141 | + Mp3, | ||
| 85 | } | 142 | } |
| 86 | 143 | ||
| 87 | impl Format { | 144 | impl Format { |
| @@ -89,26 +146,47 @@ impl Format { | |||
| 89 | /// the destination path from it, so the name never disagrees with the bytes. | 146 | /// the destination path from it, so the name never disagrees with the bytes. |
| 90 | pub fn ext(self) -> &'static str { | 147 | pub fn ext(self) -> &'static str { |
| 91 | match self { | 148 | match self { |
| 92 | - Self::Mp4 => "mp4", | 149 | + Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4", |
| 93 | - Self::Av1 => "mkv", | 150 | + Self::Av1 | Self::Hevc => "mkv", |
| 94 | Self::Wav => "wav", | 151 | Self::Wav => "wav", |
| 95 | Self::Flac => "flac", | 152 | Self::Flac => "flac", |
| 153 | + Self::Mp3 => "mp3", | ||
| 96 | } | 154 | } |
| 97 | } | 155 | } |
| 98 | 156 | ||
| 99 | /// Whether this format carries the picture. The bitrate settings are video | 157 | /// Whether this format carries the picture. The bitrate settings are video |
| 100 | - /// settings and mean nothing to the audio two. | 158 | + /// settings and mean nothing to the audio-only ones. |
| 101 | pub fn has_video(self) -> bool { | 159 | pub fn has_video(self) -> bool { |
| 102 | - matches!(self, Self::Mp4 | Self::Av1) | 160 | + matches!( |
| 161 | + self, | ||
| 162 | + Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4 | ||
| 163 | + ) | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs | ||
| 167 | + /// and which of the two AV1 containers is being written are separate | ||
| 168 | + /// questions, and this is the first. | ||
| 169 | + fn is_av1(self) -> bool { | ||
| 170 | + matches!(self, Self::Av1 | Self::Av1Mp4) | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + /// The same question for HEVC, and the same answer for both its containers: | ||
| 174 | + /// one encoder, two boxes to put its stream in. | ||
| 175 | + fn is_hevc(self) -> bool { | ||
| 176 | + matches!(self, Self::Hevc | Self::HevcMp4) | ||
| 103 | } | 177 | } |
| 104 | 178 | ||
| 105 | /// What the format is called where a refusal names it. | 179 | /// What the format is called where a refusal names it. |
| 106 | pub fn name(self) -> &'static str { | 180 | pub fn name(self) -> &'static str { |
| 107 | match self { | 181 | match self { |
| 108 | Self::Mp4 => "an mp4", | 182 | Self::Mp4 => "an mp4", |
| 109 | - Self::Av1 => "an AV1 export", | 183 | + Self::Av1 => "an AV1 Matroska", |
| 184 | + Self::Av1Mp4 => "an AV1 mp4", | ||
| 185 | + Self::Hevc => "an HEVC Matroska", | ||
| 186 | + Self::HevcMp4 => "an HEVC mp4", | ||
| 110 | Self::Wav => "a WAV", | 187 | Self::Wav => "a WAV", |
| 111 | Self::Flac => "a FLAC", | 188 | Self::Flac => "a FLAC", |
| 189 | + Self::Mp3 => "an MP3", | ||
| 112 | } | 190 | } |
| 113 | } | 191 | } |
| 114 | } | 192 | } |
| @@ -134,6 +212,10 @@ struct Shared { | |||
| 134 | cancel: AtomicBool, | 212 | cancel: AtomicBool, |
| 135 | finished: AtomicBool, | 213 | finished: AtomicBool, |
| 136 | outcome: Mutex<Option<crate::Result<()>>>, | 214 | outcome: Mutex<Option<crate::Result<()>>>, |
| 215 | + /// The encoders this job really opened, published the moment they are | ||
| 216 | + /// chosen and never changed after -- one seat for the whole file, which is | ||
| 217 | + /// what [`Enc`] states. `None` until then. | ||
| 218 | + encoders: Mutex<Option<String>>, | ||
| 137 | } | 219 | } |
| 138 | 220 | ||
| 139 | /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per | 221 | /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per |
| @@ -162,6 +244,13 @@ impl ExportHandle { | |||
| 162 | self.shared.finished.load(Ordering::Acquire) | 244 | self.shared.finished.load(Ordering::Acquire) |
| 163 | } | 245 | } |
| 164 | 246 | ||
| 247 | + /// What this export is encoding with -- the video seat and what the sound | ||
| 248 | + /// is doing -- as the worker chose them, hardware fallback included. | ||
| 249 | + /// `None` for the first instants of a job, before the encoder is open. | ||
| 250 | + pub fn encoders(&self) -> Option<String> { | ||
| 251 | + self.shared.encoders.lock().unwrap().clone() | ||
| 252 | + } | ||
| 253 | + | ||
| 165 | /// The outcome, once — taken out of the handle, so a caller that already | 254 | /// The outcome, once — taken out of the handle, so a caller that already |
| 166 | /// reported it sees `None` afterwards. `None` while the export is running. | 255 | /// reported it sees `None` afterwards. `None` while the export is running. |
| 167 | pub fn result(&self) -> Option<crate::Result<()>> { | 256 | pub fn result(&self) -> Option<crate::Result<()>> { |
| @@ -185,6 +274,7 @@ pub fn start( | |||
| 185 | cancel: AtomicBool::new(false), | 274 | cancel: AtomicBool::new(false), |
| 186 | finished: AtomicBool::new(false), | 275 | finished: AtomicBool::new(false), |
| 187 | outcome: Mutex::new(None), | 276 | outcome: Mutex::new(None), |
| 277 | + encoders: Mutex::new(None), | ||
| 188 | }); | 278 | }); |
| 189 | let worker = Arc::clone(&shared); | 279 | let worker = Arc::clone(&shared); |
| 190 | let out = out.to_path_buf(); | 280 | let out = out.to_path_buf(); |
| @@ -217,12 +307,12 @@ pub fn start( | |||
| 217 | Err("the timeline is empty: there is nothing to export".into()) | 307 | Err("the timeline is empty: there is nothing to export".into()) |
| 218 | } | 308 | } |
| 219 | format if format.has_video() && !has_picture(&project) => Err(format!( | 309 | format if format.has_video() && !has_picture(&project) => Err(format!( |
| 220 | - "the timeline has no picture: {} would be black. Export WAV or \ | 310 | + "the timeline has no picture: {} would be black. Export WAV, \ |
| 221 | - FLAC, which are the sound itself", | 311 | + FLAC or MP3, which are the sound itself", |
| 222 | format.name() | 312 | format.name() |
| 223 | ) | 313 | ) |
| 224 | .into()), | 314 | .into()), |
| 225 | - Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings), | 315 | + format if format.has_video() => run(&project, &meta, &part, &worker, &settings), |
| 226 | format => run_audio(&project, &meta, &part, &worker, format), | 316 | format => run_audio(&project, &meta, &part, &worker, format), |
| 227 | }; | 317 | }; |
| 228 | let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); | 318 | let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); |
| @@ -249,23 +339,185 @@ fn has_picture(project: &Project) -> bool { | |||
| 249 | .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) | 339 | .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) |
| 250 | } | 340 | } |
| 251 | 341 | ||
| 342 | +/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a | ||
| 343 | +/// timeline whose export will carry sound from one whose file has none. | ||
| 344 | +fn has_sound(project: &Project) -> bool { | ||
| 345 | + project | ||
| 346 | + .lanes() | ||
| 347 | + .into_iter() | ||
| 348 | + .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty()) | ||
| 349 | +} | ||
| 350 | + | ||
| 351 | +/// Whether any equalizer on the sound is doing something -- the one edit a | ||
| 352 | +/// packet copy cannot carry, so an mp4 whose lane has one is decoded and | ||
| 353 | +/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane: | ||
| 354 | +/// the copy path has exactly one by the time it asks, and [`planned_audio`] is | ||
| 355 | +/// asked before that is settled. | ||
| 356 | +fn equalized(project: &Project) -> bool { | ||
| 357 | + project.audio_lanes().into_iter().any(|lane| { | ||
| 358 | + (0..project.lane(lane).len()) | ||
| 359 | + .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())) | ||
| 360 | + }) | ||
| 361 | +} | ||
| 362 | + | ||
| 363 | +/// Whether the *mix* is doing something -- a lane turned off unity, or a | ||
| 364 | +/// limiter in circuit. [`equalized`]'s pair, and a copy cannot carry either of | ||
| 365 | +/// them: both live where the lanes are summed | ||
| 366 | +/// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never | ||
| 367 | +/// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded. | ||
| 368 | +fn mastered(project: &Project) -> bool { | ||
| 369 | + project.limiter().is_active() || project.audio_gains().iter().any(|&g| g != 1.0) | ||
| 370 | +} | ||
| 371 | + | ||
| 372 | +/// The bitrate an export codes at: the caller's number through the same clamp | ||
| 373 | +/// as the computed one, for the reason [`Enc::open`] states. | ||
| 374 | +fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 { | ||
| 375 | + settings | ||
| 376 | + .bitrate | ||
| 377 | + .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)) | ||
| 378 | +} | ||
| 379 | + | ||
| 380 | +/// The hardware seat for these settings, opened exactly as the export opens it | ||
| 381 | +/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may | ||
| 382 | +/// refuse -- or `None` where the software encoder takes the file. The single | ||
| 383 | +/// place that choice is made, which is what lets [`planned_video`] *measure* it | ||
| 384 | +/// instead of promising it. | ||
| 385 | +fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> { | ||
| 386 | + if settings.force_sw || forced("VE_SW_ENC") { | ||
| 387 | + return None; | ||
| 388 | + } | ||
| 389 | + let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; | ||
| 390 | + let bitrate = bitrate_of(meta, settings); | ||
| 391 | + match settings.format { | ||
| 392 | + // The HEVC pair is software only, and not for want of a GPU: the plugin | ||
| 393 | + // has no HEVC *encode* entry point at all (`hw::HwEncoder` opens H.264 | ||
| 394 | + // and AV1), so there is no seat to probe. Said here rather than left to | ||
| 395 | + // a failed open, which would read as a driver refusal. | ||
| 396 | + format if format.is_hevc() => None, | ||
| 397 | + // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both | ||
| 398 | + // AV1 formats sit on it: the container is not the encoder's business. | ||
| 399 | + format if format.is_av1() && !forced("VE_HW_AV1") => None, | ||
| 400 | + format if format.is_av1() => { | ||
| 401 | + HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) | ||
| 402 | + } | ||
| 403 | + _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate), | ||
| 404 | + } | ||
| 405 | +} | ||
| 406 | + | ||
| 407 | +/// How a front-end names a video seat: which of the two encoders has the file, | ||
| 408 | +/// and which library that is. Not the codec -- a caller shows this beside the | ||
| 409 | +/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One | ||
| 410 | +/// place, so what a card says before an export and what its progress line says | ||
| 411 | +/// during one cannot drift apart. | ||
| 412 | +fn video_label(format: Format, hw: bool) -> &'static str { | ||
| 413 | + match (format, hw) { | ||
| 414 | + (_, true) => "HW encode (VA-API)", | ||
| 415 | + (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)", | ||
| 416 | + (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)", | ||
| 417 | + (_, false) => "SW encode (rusty_h264)", | ||
| 418 | + } | ||
| 419 | +} | ||
| 420 | + | ||
| 421 | +/// The cheap half of "does this timeline's sound have to be re-encoded": what | ||
| 422 | +/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a | ||
| 423 | +/// copy; a speeded lane is resampled; an equalizer is sample math. The other | ||
| 424 | +/// half -- whether the sources can be copied out of at all -- costs a file open | ||
| 425 | +/// each and belongs to [`copy_audio`], which may re-encode where this says copy. | ||
| 426 | +fn forces_encode(project: &Project) -> bool { | ||
| 427 | + let lanes: Vec<_> = project | ||
| 428 | + .audio_lanes() | ||
| 429 | + .into_iter() | ||
| 430 | + .filter(|&lane| !project.lane(lane).is_empty()) | ||
| 431 | + .collect(); | ||
| 432 | + lanes.len() > 1 | ||
| 433 | + || lanes | ||
| 434 | + .iter() | ||
| 435 | + .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal())) | ||
| 436 | + || equalized(project) | ||
| 437 | + || mastered(project) | ||
| 438 | +} | ||
| 439 | + | ||
| 440 | +/// What the sound is written by. Every audio encoder here is software -- there | ||
| 441 | +/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and | ||
| 442 | +/// whether a container escapes encoding altogether by copying the packets it was | ||
| 443 | +/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the | ||
| 444 | +/// timeline's sound too, so leaving it unnamed would be the old lie. | ||
| 445 | +/// | ||
| 446 | +/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a | ||
| 447 | +/// card asking before the export has no way to know (a source that cannot be | ||
| 448 | +/// copied out of is only found by opening it). `None` predicts from the edit | ||
| 449 | +/// alone. | ||
| 450 | +fn audio_label( | ||
| 451 | + project: &Project, | ||
| 452 | + format: Format, | ||
| 453 | + sound: bool, | ||
| 454 | + copied: Option<bool>, | ||
| 455 | +) -> &'static str { | ||
| 456 | + if !sound { | ||
| 457 | + return "no sound to write"; | ||
| 458 | + } | ||
| 459 | + match format { | ||
| 460 | + Format::Wav => "PCM · SW (hound)", | ||
| 461 | + Format::Flac => "FLAC · SW (flacenc)", | ||
| 462 | + Format::Mp3 => "MP3 · SW (rusty_mp3)", | ||
| 463 | + _ => match copied.unwrap_or(!forces_encode(project)) { | ||
| 464 | + true => "AAC copy", | ||
| 465 | + false => "AAC · SW encode (rusty_aac)", | ||
| 466 | + }, | ||
| 467 | + } | ||
| 468 | +} | ||
| 469 | + | ||
| 470 | +/// What [`start`] would write this timeline's sound with, before one is | ||
| 471 | +/// started. Pure: no probe and no file opened, so a card may ask it per repaint. | ||
| 472 | +pub fn planned_audio(project: &Project, format: Format) -> &'static str { | ||
| 473 | + audio_label(project, format, has_sound(project), None) | ||
| 474 | +} | ||
| 475 | + | ||
| 476 | +/// What [`start`] would encode the picture with, probed the way the export | ||
| 477 | +/// probes it -- the very encoder is opened and closed again -- so this is a | ||
| 478 | +/// measurement and not a promise. `None` for a format that carries no picture. | ||
| 479 | +/// | ||
| 480 | +/// Costs that open (~100 ms here): ask it off a render thread and keep the | ||
| 481 | +/// answer until the format, the resolution or the bitrate changes. | ||
| 482 | +pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> { | ||
| 483 | + settings | ||
| 484 | + .format | ||
| 485 | + .has_video() | ||
| 486 | + .then(|| video_label(settings.format, hw_seat(meta, settings).is_some())) | ||
| 487 | +} | ||
| 488 | + | ||
| 252 | fn settle(shared: &Shared, result: crate::Result<()>) { | 489 | fn settle(shared: &Shared, result: crate::Result<()>) { |
| 253 | *shared.outcome.lock().unwrap() = Some(result); | 490 | *shared.outcome.lock().unwrap() = Some(result); |
| 254 | // Published last: a caller that sees the flag is guaranteed the outcome. | 491 | // Published last: a caller that sees the flag is guaranteed the outcome. |
| 255 | shared.finished.store(true, Ordering::Release); | 492 | shared.finished.store(true, Ordering::Release); |
| 256 | } | 493 | } |
| 257 | 494 | ||
| 258 | -/// The timeline's one audio lane, copied packet for packet: the mp4 path's | 495 | +/// The audio track an export writes, and how it was made -- a copy is the |
| 259 | -/// sound, and the reason that path carries only one lane of it. | 496 | +/// source's own packets, bit for bit, and anything else is this project's |
| 497 | +/// encoder over the decoded mix. [`run`] publishes which of the two really | ||
| 498 | +/// happened, so the encoder line a user reads is measured and not promised. | ||
| 499 | +pub(crate) struct ExportAudio { | ||
| 500 | + pub params: crate::AacTrackParams, | ||
| 501 | + pub packets: Vec<crate::AacPacket>, | ||
| 502 | + /// Whether those packets are the source's, untouched. | ||
| 503 | + pub copied: bool, | ||
| 504 | +} | ||
| 505 | + | ||
| 506 | +/// The timeline's audio track for a file that carries picture: copied packet for | ||
| 507 | +/// packet where a copy says exactly what the timeline says, and decoded, mixed | ||
| 508 | +/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane, | ||
| 509 | +/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample | ||
| 510 | +/// table. Nothing is refused for being uncopyable any more; the only refusals | ||
| 511 | +/// left below the copy are about sound this engine cannot *decode* either, and | ||
| 512 | +/// those come out of the decode path by name. | ||
| 513 | +/// | ||
| 514 | +/// The copy is still the default and still bit-exact: a timeline nobody has | ||
| 515 | +/// touched leaves as the very packets its source holds. | ||
| 260 | /// | 516 | /// |
| 261 | /// ponytail: this holds the whole exported AAC track in memory (~3 kB per | 517 | /// ponytail: this holds the whole exported AAC track in memory (~3 kB per |
| 262 | /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming | 518 | /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming |
| 263 | /// `copy_segments` that yields packets instead of collecting them. | 519 | /// `copy_segments` that yields packets instead of collecting them. |
| 264 | -#[allow(clippy::type_complexity)] | 520 | +fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<ExportAudio>> { |
| 265 | -fn copy_audio( | ||
| 266 | - project: &Project, | ||
| 267 | - meta: &VideoMeta, | ||
| 268 | -) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> { | ||
| 269 | // The segments name their source, and the copy carries its packet-rounding | 521 | // The segments name their source, and the copy carries its packet-rounding |
| 270 | // debt across a source join exactly as across a cut, so a timeline spanning | 522 | // debt across a source join exactly as across a cut, so a timeline spanning |
| 271 | // files stays in sync. A source whose AAC parameters disagree with the | 523 | // files stays in sync. A source whose AAC parameters disagree with the |
| @@ -276,11 +528,10 @@ fn copy_audio( | |||
| 276 | // is the same list `PlaybackSession::seek` hands the decoder, so an export | 528 | // is the same list `PlaybackSession::seek` hands the decoder, so an export |
| 277 | // of a timeline playing a file's second audio track carries *that* track. | 529 | // of a timeline playing a file's second audio track carries *that* track. |
| 278 | // | 530 | // |
| 279 | - // One lane, because this path *copies* AAC packets and a mix is not a copy: | 531 | + // One lane is the only shape a *copy* has: summing two means decoding both, |
| 280 | - // summing two lanes means decoding both and encoding the result, and there | 532 | + // and a sum is not a copy. Two or more go to [`encode_audio`], which is the |
| 281 | - // is no AAC encoder here to encode it with. Refused by name rather than | 533 | + // very mix the WAV path writes -- it used to be a refusal, and a refusal is |
| 282 | - // silently exporting the first lane -- a file missing half its sound is the | 534 | + // what a file missing half its sound deserves, not what a mix does. |
| 283 | - // one failure a user would not notice. | ||
| 284 | // | 535 | // |
| 285 | // *Which* lane is the same question `audio_segments_from` answers for | 536 | // *Which* lane is the same question `audio_segments_from` answers for |
| 286 | // playback, and it is asked here rather than assumed: the lane that holds | 537 | // playback, and it is asked here rather than assumed: the lane that holds |
| @@ -290,67 +541,151 @@ fn copy_audio( | |||
| 290 | // whole comment is about. | 541 | // whole comment is about. |
| 291 | let lanes = project.audio_segments_from(0, meta.frame_rate); | 542 | let lanes = project.audio_segments_from(0, meta.frame_rate); |
| 292 | let [segments] = &lanes[..] else { | 543 | let [segments] = &lanes[..] else { |
| 293 | - return Err(format!( | 544 | + return encode_audio(project, meta); |
| 294 | - "this timeline has {} audio lanes and an mp4 export copies one: \ | ||
| 295 | - there is no AAC encoder here to mix them with. Export WAV or FLAC, \ | ||
| 296 | - which are mixed, or put the sound on one lane", | ||
| 297 | - lanes.len() | ||
| 298 | - ) | ||
| 299 | - .into()); | ||
| 300 | }; | 545 | }; |
| 301 | - // ...and the same list decides which clips this would be copying, which is | 546 | + // ...and the same list names *which* lane those clips sit on, which is the |
| 302 | - // the only way to ask whether any of them carries an equalizer. An EQ is | 547 | + // only way to ask what has been done to them. |
| 303 | - // sample math and a copy never decodes: exporting it here would write the | ||
| 304 | - // clip flat, silently -- the same failure a missing audio track is. Named by | ||
| 305 | - // where it sits on the timeline, because "some clip" is not a thing a user | ||
| 306 | - // can go and fix. | ||
| 307 | let lane = project.audio_lanes()[0]; | 548 | let lane = project.audio_lanes()[0]; |
| 308 | // ...and the same list decides whether any clip this would copy plays at a | 549 | // ...and the same list decides whether any clip this would copy plays at a |
| 309 | - // rate other than the one it was recorded at. A copy hands the mp4 the very | 550 | + // rate other than the one it was recorded at. A copy hands the muxer the |
| 310 | - // AAC packets the source holds and there is no rate inside a packet to | 551 | + // very AAC packets the source holds and there is no rate inside a packet to |
| 311 | // change: the picture would come out re-timed (the walk in [`run`] honours | 552 | // change: the picture would come out re-timed (the walk in [`run`] honours |
| 312 | // it) over sound at 1.00x, which is the drift a person finds only after the | 553 | // it) over sound at 1.00x, which is the drift a person finds only after the |
| 313 | - // file has gone somewhere. Refused by name, exactly as the equalizer below | 554 | + // file has gone somewhere. Decoded and resampled instead, by the same worker |
| 314 | - // is -- and only *here*, on the lane being copied: AV1 carries no audio at | 555 | + // playback feeds from. |
| 315 | - // all and never reaches this, so it honours a speed like WAV and FLAC do. | ||
| 316 | // | 556 | // |
| 317 | - // ponytail: the ceiling is the packet copy itself, not the rate. Upgrade | 557 | + // ...and whether any clip on it carries an equalizer, which is sample math a |
| 318 | - // path is the same one the equalizer below wants -- an AAC encoder (or a | 558 | + // copy never reaches: copying such a lane would write the clip *flat*, |
| 319 | - // decode-and-re-encode of this lane) -- at which point the resample the WAV | 559 | + // silently. |
| 320 | - // path already runs feeds it and this refusal goes. | 560 | + // |
| 321 | - if let Some((at, speed)) = project | 561 | + // A frame *rate* of its own is not one of those, and that is deliberate: do |
| 322 | - .lane(lane) | 562 | + // not "fix" this into a re-encode. A clip counts the **timeline's** frames |
| 323 | - .iter() | 563 | + // whatever its file was shot at ([`crate::project::Rate`]), so the window |
| 324 | - .find(|c| !c.speed.is_normal()) | 564 | + // this copy trims a source's sound to is `start..end` in whole timeline |
| 325 | - .map(|c| (c.start, c.speed)) | 565 | + // frames -- exactly the seconds the picture covers -- and the file is read |
| 326 | - { | 566 | + // at the pitch it was recorded at, which is what playing at the rate it was |
| 327 | - return Err(format!( | 567 | + // shot at means. There is no per-clip stretch to express, so the packets are |
| 328 | - "the clip at {} plays at {speed} and an mp4 export copies AAC packets, which carry \ | 568 | + // already the right sound in the right place; re-encoding a conformed lane |
| 329 | - no rate: export WAV or FLAC, which are decoded and resampled, or set it back to 1.00x", | 569 | + // would buy nothing and cost a generation of loss on every mixed-rate export |
| 330 | - timecode(at, meta.frame_rate) | 570 | + // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot` |
| 331 | - ) | 571 | + // measures the copied sound against the picture). A *speed* is different |
| 332 | - .into()); | 572 | + // because it resamples, which is why it leaves through the re-encode above. |
| 573 | + // | ||
| 574 | + // Only these: a timeline nobody has touched still leaves through the copy | ||
| 575 | + // below, packet for packet, so no passthrough quietly becomes a generation | ||
| 576 | + // of loss. | ||
| 577 | + // ...and whether the mix itself does anything a packet never went through: | ||
| 578 | + // a lane volume is applied at the sum and a limiter over it, so copying | ||
| 579 | + // such a lane would write it at unity and unlimited, silently. | ||
| 580 | + let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal()); | ||
| 581 | + if speeded || equalized(project) || mastered(project) { | ||
| 582 | + return encode_audio(project, meta); | ||
| 333 | } | 583 | } |
| 334 | - if let Some((at, _)) = project | 584 | + // What is left is a copy the *sources* may still not be able to give: AAC |
| 335 | - .lane(lane) | 585 | + // inside a Matroska file (readable, but not out of a sample table this walks |
| 336 | - .iter() | 586 | + // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two |
| 337 | - .enumerate() | 587 | + // sources whose AAC parameters disagree. Every one of them decodes, and what |
| 338 | - .find(|(idx, _)| { | 588 | + // decodes can be encoded again, so the copy's refusal is now a route: the |
| 339 | - project | 589 | + // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file, |
| 340 | - .eq_of(lane, *idx) | 590 | + // which symphonia has no decoder for at any version -- is the one that comes |
| 341 | - .is_some_and(|eq| !eq.is_identity()) | 591 | + // back, by name, from [`encode_audio`]. |
| 342 | - }) | 592 | + match AudioSession::copy_multi_streams(&project.audio_sources(), segments) { |
| 343 | - .map(|(idx, clip)| (clip.start, idx)) | 593 | + Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio { |
| 344 | - { | 594 | + params, |
| 345 | - return Err(format!( | 595 | + packets, |
| 346 | - "the clip at {} has an equalizer and an mp4 export copies AAC packets, \ | 596 | + copied: true, |
| 347 | - which no filter can reach: export WAV or FLAC, which are decoded and \ | 597 | + })), |
| 348 | - mixed, or clear the equalizer", | 598 | + Err(_) => encode_audio(project, meta), |
| 349 | - timecode(at, meta.frame_rate) | 599 | + } |
| 600 | +} | ||
| 601 | + | ||
| 602 | +/// The same lane, *decoded*: what a packet copy cannot carry comes out here as | ||
| 603 | +/// AAC written by this project's own encoder. | ||
| 604 | +/// | ||
| 605 | +/// The samples are the very ones [`run_audio`] would put in a WAV -- the same | ||
| 606 | +/// opener with the same equalizers, the same rates and the same resize onto the | ||
| 607 | +/// timeline's own length -- so an mp4 and a WAV of one timeline are one mix, | ||
| 608 | +/// not two that could disagree. | ||
| 609 | +/// | ||
| 610 | +/// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming | ||
| 611 | +/// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`, | ||
| 612 | +/// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so | ||
| 613 | +/// the sound starts at timeline frame 0 as a copied track's does. | ||
| 614 | +/// | ||
| 615 | +/// ponytail: the mix sits in memory as f32 before it is encoded (~46 MB a | ||
| 616 | +/// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers | ||
| 617 | +/// the whole stream anyway, since it encodes its frames in parallel. Upgrade | ||
| 618 | +/// path is a chunked push once that encoder streams. | ||
| 619 | +fn encode_audio(project: &Project, meta: &VideoMeta) -> crate::Result<Option<ExportAudio>> { | ||
| 620 | + let sources = project.audio_sources(); | ||
| 621 | + let segs = project.audio_segments_from(0, meta.frame_rate); | ||
| 622 | + let eqs = project.audio_eqs_from(0, meta.frame_rate); | ||
| 623 | + let speeds = project.audio_speeds_from(0, meta.frame_rate); | ||
| 624 | + let Some((audio, chunks)) = AudioSession::open_mixed_streams_master( | ||
| 625 | + &sources, | ||
| 626 | + &segs, | ||
| 627 | + &eqs, | ||
| 628 | + &speeds, | ||
| 629 | + &project.audio_gains(), | ||
| 630 | + project.limiter(), | ||
| 631 | + )? | ||
| 632 | + else { | ||
| 633 | + return Ok(None); // no audio to write, exactly as a copy of nothing is | ||
| 634 | + }; | ||
| 635 | + let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| { | ||
| 636 | + format!( | ||
| 637 | + "{} Hz is not an AAC sample rate: export WAV, FLAC or MP3, which write it as \ | ||
| 638 | + it is", | ||
| 639 | + audio.sample_rate | ||
| 350 | ) | 640 | ) |
| 351 | - .into()); | 641 | + })?; |
| 642 | + let channels = usize::from(audio.channels.max(1)); | ||
| 643 | + // The timeline's length, not the mix's: a segment resolves its window to | ||
| 644 | + // whole samples on its own, so the sum can miss by a sample or two and a | ||
| 645 | + // source that ran out early would leave the track short under a picture | ||
| 646 | + // that is not. One resize settles both, as [`run_audio`]'s does. | ||
| 647 | + let total = (f64::from(project.timeline_frames()) / meta.frame_rate | ||
| 648 | + * f64::from(audio.sample_rate)) | ||
| 649 | + .round() as usize | ||
| 650 | + * channels; | ||
| 651 | + let mut samples: Vec<f32> = Vec::with_capacity(total); | ||
| 652 | + for chunk in chunks { | ||
| 653 | + samples.extend(chunk.samples); | ||
| 352 | } | 654 | } |
| 353 | - AudioSession::copy_multi_streams(&project.audio_sources(), segments) | 655 | + samples.resize(total, 0.0); |
| 656 | + | ||
| 657 | + // 256 kbps, not the encoder's 128 default: this is a *second* generation of | ||
| 658 | + // lossy coding over a source that was already AAC, and the export is a | ||
| 659 | + // master a person edits from again, not a delivery file. Measured on the | ||
| 660 | + // suite's fixtures, an untouched clip re-encoded here moves 0.15 dB at this | ||
| 661 | + // rate against 0.46 dB at 128 -- and 32 KB/s beside a 2.76 Mbps picture is | ||
| 662 | + // not a size anyone is counting. | ||
| 663 | + let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig { | ||
| 664 | + bitrate_bps: 256_000, | ||
| 665 | + ..Default::default() | ||
| 666 | + }); | ||
| 667 | + encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?; | ||
| 668 | + encoder.finish(); | ||
| 669 | + let mut packets = Vec::new(); | ||
| 670 | + // `next_packet` after `finish` yields packets until `Eof` and nothing else, | ||
| 671 | + // so the loop ends on the only error it can see. | ||
| 672 | + while let Ok(packet) = encoder.next_packet() { | ||
| 673 | + packets.push(crate::AacPacket { | ||
| 674 | + bytes: packet.data, | ||
| 675 | + samples: packet.duration, | ||
| 676 | + }); | ||
| 677 | + } | ||
| 678 | + Ok(Some(ExportAudio { | ||
| 679 | + params: crate::AacTrackParams { | ||
| 680 | + freq_index, | ||
| 681 | + // 1 and 2 are the ISO channel configurations for mono and stereo, | ||
| 682 | + // and the opener refuses anything wider than stereo already. | ||
| 683 | + chan_conf: audio.channels.max(1) as u8, | ||
| 684 | + sample_rate: audio.sample_rate, | ||
| 685 | + }, | ||
| 686 | + packets, | ||
| 687 | + copied: false, | ||
| 688 | + })) | ||
| 354 | } | 689 | } |
| 355 | 690 | ||
| 356 | fn run( | 691 | fn run( |
| @@ -363,21 +698,44 @@ fn run( | |||
| 363 | let total = project.timeline_frames(); | 698 | let total = project.timeline_frames(); |
| 364 | let sources = project.sources(); | 699 | let sources = project.sources(); |
| 365 | // Audio first: a track has to be declared when the muxer is created, which | 700 | // Audio first: a track has to be declared when the muxer is created, which |
| 366 | - // happens as soon as the first coded picture arrives. None of it for AV1 -- | 701 | + // happens as soon as the first coded picture arrives -- and the Matroska |
| 367 | - // that one is picture only, for the reason [`Format::Av1`] states -- and no | 702 | + // muxer wants the packets themselves that early too, because it interleaves |
| 368 | - // refusal of it either: a timeline with sound is exported as the video it | 703 | + // them into the clusters as it writes. Every video format gets the same |
| 369 | - // also is, and the front-end says the sound is not in the file *before* the | 704 | + // track: none of them is picture-only any more. |
| 370 | - // export starts rather than failing it here. | 705 | + let audio = copy_audio(project, meta)?; |
| 371 | - let audio = match settings.format { | 706 | + let audio_params = audio.as_ref().map(|track| AudioParams { |
| 372 | - Format::Av1 => None, | 707 | + freq_index: track.params.freq_index, |
| 373 | - _ => copy_audio(project, meta)?, | 708 | + chan_conf: track.params.chan_conf, |
| 374 | - }; | 709 | + sample_rate: track.params.sample_rate, |
| 375 | - let audio_params = audio.as_ref().map(|(track, _)| AudioParams { | ||
| 376 | - freq_index: track.freq_index, | ||
| 377 | - chan_conf: track.chan_conf, | ||
| 378 | }); | 710 | }); |
| 711 | + // What the track *is*, kept before the packets are handed to a muxer: the | ||
| 712 | + // encoder line names a copy or an encode and only `copy_audio` knows which. | ||
| 713 | + let sound = audio.as_ref().map(|track| track.copied); | ||
| 714 | + // Taken by the Matroska muxer at creation; the mp4 one writes its track | ||
| 715 | + // after the picture, so for that path this is still `Some` at the end. | ||
| 716 | + let mut packets = audio.map(|track| track.packets); | ||
| 717 | + | ||
| 718 | + // One header parse per source, before any of them is decoded: what rate | ||
| 719 | + // each file was shot at against the timeline's ([`Rate`]), which is how the | ||
| 720 | + // clip's timeline frames below become frames of the file. Real time for a | ||
| 721 | + // still, a song and a single-rate project, where every conversion below is | ||
| 722 | + // the identity. | ||
| 723 | + let rates: Vec<Rate> = sources | ||
| 724 | + .iter() | ||
| 725 | + .map(|source| source_rate(&source.path, meta.frame_rate)) | ||
| 726 | + .collect(); | ||
| 379 | 727 | ||
| 380 | let mut encoder = Enc::open(meta, settings)?; | 728 | let mut encoder = Enc::open(meta, settings)?; |
| 729 | + // What this file is really being written by, for a progress line to name. | ||
| 730 | + // Published *after* the seat is open, so a hardware encoder the driver | ||
| 731 | + // refused reads as the software one that took over rather than as the hope | ||
| 732 | + // it replaced -- and the sound says whether it was copied or encoded, which | ||
| 733 | + // `copy_audio` decided a few lines up. | ||
| 734 | + *shared.encoders.lock().unwrap() = Some(format!( | ||
| 735 | + "{} · {}", | ||
| 736 | + encoder.label(), | ||
| 737 | + audio_label(project, settings.format, sound.is_some(), sound) | ||
| 738 | + )); | ||
| 381 | let mut muxer = None; | 739 | let mut muxer = None; |
| 382 | let mut done = 0u32; | 740 | let mut done = 0u32; |
| 383 | let black = Black::new(meta); | 741 | let black = Black::new(meta); |
| @@ -391,14 +749,18 @@ fn run( | |||
| 391 | // encoder is *not* reopened, so the export is one continuous stream | 749 | // encoder is *not* reopened, so the export is one continuous stream |
| 392 | // whose GOP boundaries need not line up with the cuts -- nor with the | 750 | // whose GOP boundaries need not line up with the cuts -- nor with the |
| 393 | // file boundaries, which are just cuts that change the path. | 751 | // file boundaries, which are just cuts that change the path. |
| 394 | - let mut pictures = match span.from { | 752 | + let (mut pictures, rate, in_frame) = match span.from { |
| 395 | Some((source, in_frame)) => { | 753 | Some((source, in_frame)) => { |
| 396 | let entry = sources | 754 | let entry = sources |
| 397 | .get(source) | 755 | .get(source) |
| 398 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; | 756 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 399 | - Some(ClipDecoder::open(&entry.path, in_frame)?) | 757 | + let rate = rates[source]; |
| 758 | + // Opened at the file's own frame, which is the only place the | ||
| 759 | + // file's numbering is used -- the span's are the timeline's. | ||
| 760 | + let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; | ||
| 761 | + (Some(pictures), rate, in_frame) | ||
| 400 | } | 762 | } |
| 401 | - None => None, | 763 | + None => (None, Rate::REAL_TIME, 0), |
| 402 | }; | 764 | }; |
| 403 | // What this span is graded by -- the same answer playback's decoder | 765 | // What this span is graded by -- the same answer playback's decoder |
| 404 | // carries, so the export is the picture that was watched. `None` for a | 766 | // carries, so the export is the picture that was watched. `None` for a |
| @@ -429,10 +791,24 @@ fn run( | |||
| 429 | let mut done_here = 0u32; | 791 | let mut done_here = 0u32; |
| 430 | // Source frames already taken out of this span's decoder. | 792 | // Source frames already taken out of this span's decoder. |
| 431 | let mut taken = 0u32; | 793 | let mut taken = 0u32; |
| 794 | + // The whole of the mapping, in the order it composes: the speed says | ||
| 795 | + // which of the clip's (timeline-rate) frames a timeline frame shows, | ||
| 796 | + // and the rate says which frame of the *file* that is -- counted from | ||
| 797 | + // the one the decoder was opened at. At real time and at the timeline's | ||
| 798 | + // own rate this is `Speed::source_at` and nothing else, which is the | ||
| 799 | + // walk a single-rate project has always taken. | ||
| 800 | + let opened_at = rate.source_at(in_frame); | ||
| 801 | + let source_at = | ||
| 802 | + |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at; | ||
| 432 | while done_here < span.len { | 803 | while done_here < span.len { |
| 433 | cancelled(shared)?; | 804 | cancelled(shared)?; |
| 434 | - let want = span.speed.source_at(done_here); | 805 | + let want = source_at(done_here); |
| 435 | - let repeats = span.speed.repeats(done_here, span.len); | 806 | + // How many timeline frames from here show that same picture: one at |
| 807 | + // real time, more when the clip is slowed or its file is slower | ||
| 808 | + // than the timeline. Encoded again rather than decoded twice. | ||
| 809 | + let repeats = (done_here..span.len) | ||
| 810 | + .take_while(|&offset| source_at(offset) == want) | ||
| 811 | + .count() as u32; | ||
| 436 | let picture = match &mut pictures { | 812 | let picture = match &mut pictures { |
| 437 | Some(pictures) => { | 813 | Some(pictures) => { |
| 438 | let mut ran_out = false; | 814 | let mut ran_out = false; |
| @@ -485,6 +861,7 @@ fn run( | |||
| 485 | meta, | 861 | meta, |
| 486 | settings, | 862 | settings, |
| 487 | audio_params.as_ref(), | 863 | audio_params.as_ref(), |
| 864 | + &mut packets, | ||
| 488 | au, | 865 | au, |
| 489 | key, | 866 | key, |
| 490 | )?; | 867 | )?; |
| @@ -504,6 +881,7 @@ fn run( | |||
| 504 | meta, | 881 | meta, |
| 505 | settings, | 882 | settings, |
| 506 | audio_params.as_ref(), | 883 | audio_params.as_ref(), |
| 884 | + &mut packets, | ||
| 507 | au, | 885 | au, |
| 508 | key, | 886 | key, |
| 509 | )?; | 887 | )?; |
| @@ -515,8 +893,10 @@ fn run( | |||
| 515 | let Some(muxer) = muxer else { | 893 | let Some(muxer) = muxer else { |
| 516 | return Err("export produced no coded pictures".into()); | 894 | return Err("export produced no coded pictures".into()); |
| 517 | }; | 895 | }; |
| 518 | - let muxer = match (muxer, audio) { | 896 | + // The mp4's audio track after its picture -- the Matroska one interleaved |
| 519 | - (Muxer::Mp4(mut mp4), Some((_, packets))) => { | 897 | + // its own as it went and left `packets` empty behind it. |
| 898 | + let muxer = match (muxer, packets) { | ||
| 899 | + (Muxer::Mp4(mut mp4), Some(packets)) => { | ||
| 520 | for packet in packets { | 900 | for packet in packets { |
| 521 | mp4.write_audio_packet(&packet.bytes)?; | 901 | mp4.write_audio_packet(&packet.bytes)?; |
| 522 | } | 902 | } |
| @@ -530,16 +910,22 @@ fn run( | |||
| 530 | Ok(()) | 910 | Ok(()) |
| 531 | } | 911 | } |
| 532 | 912 | ||
| 533 | -/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short | 913 | +/// What rate `path` was shot at against a timeline at `timeline_fps` |
| 534 | -/// enough to sit inside a refusal and exact enough to go and find the clip. | 914 | +/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own |
| 535 | -/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a | 915 | +/// -- a still, a song -- and for one that will not open here: the decoder is |
| 536 | -/// `00:00:12:07` in the middle of a sentence is a serial number. | 916 | +/// opened a few lines later and fails the export by name, which is a better |
| 537 | -fn timecode(frame: u32, fps: f64) -> String { | 917 | +/// error than this one could raise. |
| 538 | - let secs = match fps.is_finite() && fps > 0.0 { | 918 | +fn source_rate(path: &Path, timeline_fps: f64) -> Rate { |
| 539 | - true => (f64::from(frame) / fps) as u32, | 919 | + if crate::is_image(path) || crate::is_audio(path) { |
| 540 | - false => 0, | 920 | + return Rate::REAL_TIME; |
| 541 | - }; | 921 | + } |
| 542 | - format!("{:02}:{:02}", secs / 60, secs % 60) | 922 | + match Demuxer::open(path) { |
| 923 | + // ...and one whose rate cannot be named against the timeline's, which | ||
| 924 | + // `matches_timeline` refuses at import, so nothing on a timeline is on | ||
| 925 | + // this arm either. | ||
| 926 | + Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), | ||
| 927 | + Err(_) => Rate::REAL_TIME, | ||
| 928 | + } | ||
| 543 | } | 929 | } |
| 544 | 930 | ||
| 545 | /// The audio lanes alone, summed, as a WAV or a FLAC. | 931 | /// The audio lanes alone, summed, as a WAV or a FLAC. |
| @@ -576,11 +962,24 @@ fn run_audio( | |||
| 576 | // 2x is half as long and holds the samples that were heard -- not a | 962 | // 2x is half as long and holds the samples that were heard -- not a |
| 577 | // second pass here that could disagree with what the ear got. | 963 | // second pass here that could disagree with what the ear got. |
| 578 | let speeds = project.audio_speeds_from(0, meta.frame_rate); | 964 | let speeds = project.audio_speeds_from(0, meta.frame_rate); |
| 579 | - let Some((audio, chunks)) = | 965 | + // ...and the mix over both: each lane's volume into the sum, the master |
| 580 | - AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)? | 966 | + // limiter out of it. The same opener playback's feeder reads from, so a |
| 967 | + // file is written at the levels it was heard at -- there is no second | ||
| 968 | + // place here that could mix it differently. | ||
| 969 | + let Some((audio, chunks)) = AudioSession::open_mixed_streams_master( | ||
| 970 | + &sources, | ||
| 971 | + &segs, | ||
| 972 | + &eqs, | ||
| 973 | + &speeds, | ||
| 974 | + &project.audio_gains(), | ||
| 975 | + project.limiter(), | ||
| 976 | + )? | ||
| 581 | else { | 977 | else { |
| 582 | return Err("this timeline has no audio to export".into()); | 978 | return Err("this timeline has no audio to export".into()); |
| 583 | }; | 979 | }; |
| 980 | + // The picture path's line, for a file that is sound alone: there is sound | ||
| 981 | + // by the line above, so this names the encoder writing it. | ||
| 982 | + *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string()); | ||
| 584 | let channels = usize::from(audio.channels); | 983 | let channels = usize::from(audio.channels); |
| 585 | let frames = (f64::from(project.timeline_frames()) / meta.frame_rate | 984 | let frames = (f64::from(project.timeline_frames()) / meta.frame_rate |
| 586 | * f64::from(audio.sample_rate)) | 985 | * f64::from(audio.sample_rate)) |
| @@ -612,7 +1011,8 @@ fn run_audio( | |||
| 612 | match format { | 1011 | match format { |
| 613 | Format::Wav => write_wav(out, &samples, &audio)?, | 1012 | Format::Wav => write_wav(out, &samples, &audio)?, |
| 614 | Format::Flac => write_flac(out, &samples, &audio)?, | 1013 | Format::Flac => write_flac(out, &samples, &audio)?, |
| 615 | - Format::Mp4 | Format::Av1 => unreachable!("the picture formats are `run`"), | 1014 | + Format::Mp3 => write_mp3(out, &samples, &audio)?, |
| 1015 | + _ => unreachable!("the picture formats are `run`"), | ||
| 616 | } | 1016 | } |
| 617 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); | 1017 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 618 | Ok(()) | 1018 | Ok(()) |
| @@ -639,6 +1039,42 @@ fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<() | |||
| 639 | Ok(()) | 1039 | Ok(()) |
| 640 | } | 1040 | } |
| 641 | 1041 | ||
| 1042 | +/// The same samples as MPEG-1 Layer III, `rusty_mp3` doing the encoding -- pure | ||
| 1043 | +/// Rust like every other encoder here, and the reason this format is a row at | ||
| 1044 | +/// all: the LGPL `shine-rs` was the only one when it was not. | ||
| 1045 | +/// | ||
| 1046 | +/// 256 kbps CBR, for [`encode_audio`]'s reason: an export is a master a person | ||
| 1047 | +/// edits from again, not a delivery file, and this is a lossy generation over | ||
| 1048 | +/// sources that may already have been one. The rate is snapped to a legal Layer | ||
| 1049 | +/// III value by the encoder, and a sample rate MPEG has no frame for (anything | ||
| 1050 | +/// but 8-48 kHz) is refused there by name rather than written as something else. | ||
| 1051 | +/// | ||
| 1052 | +/// ponytail: CBR only, and no rate is offered to the caller -- the export card | ||
| 1053 | +/// has one bitrate control and it is the *picture's*. Upgrade path is | ||
| 1054 | +/// `Mp3EncoderConfig::vbr_quality` behind a setting of its own. | ||
| 1055 | +fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { | ||
| 1056 | + let mut encoder = rusty_mp3::Mp3Encoder::new(rusty_mp3::Mp3EncoderConfig { | ||
| 1057 | + bitrate_kbps: 256, | ||
| 1058 | + vbr_quality: None, | ||
| 1059 | + }); | ||
| 1060 | + // The samples are the 16-bit ones a WAV of this timeline holds, so the two | ||
| 1061 | + // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this | ||
| 1062 | + // engine's own decoders do. | ||
| 1063 | + let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect(); | ||
| 1064 | + encoder | ||
| 1065 | + .push_pcm_s16(&pcm, audio.channels, audio.sample_rate) | ||
| 1066 | + .map_err(|e| format!("mp3 encode: {e}"))?; | ||
| 1067 | + encoder.finish(); | ||
| 1068 | + let mut file = BufWriter::new(File::create(out)?); | ||
| 1069 | + // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info | ||
| 1070 | + // header first: the loop ends on the only error it can see. | ||
| 1071 | + while let Ok(frame) = encoder.next_packet() { | ||
| 1072 | + file.write_all(&frame)?; | ||
| 1073 | + } | ||
| 1074 | + file.flush()?; | ||
| 1075 | + Ok(()) | ||
| 1076 | +} | ||
| 1077 | + | ||
| 642 | /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to | 1078 | /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to |
| 643 | /// text: they are not `Send + Sync`, and every one of them fails the export the | 1079 | /// text: they are not `Send + Sync`, and every one of them fails the export the |
| 644 | /// same way. | 1080 | /// same way. |
| @@ -739,34 +1175,113 @@ fn write_video( | |||
| 739 | meta: &VideoMeta, | 1175 | meta: &VideoMeta, |
| 740 | settings: &ExportSettings, | 1176 | settings: &ExportSettings, |
| 741 | audio: Option<&AudioParams>, | 1177 | audio: Option<&AudioParams>, |
| 1178 | + packets: &mut Option<Vec<crate::AacPacket>>, | ||
| 742 | au: &[u8], | 1179 | au: &[u8], |
| 743 | key: bool, | 1180 | key: bool, |
| 744 | ) -> crate::Result<()> { | 1181 | ) -> crate::Result<()> { |
| 745 | - if settings.format == Format::Av1 { | 1182 | + if settings.format.is_hevc() { |
| 1183 | + // The parameter sets are in the access unit -- every intra AU carries | ||
| 1184 | + // VPS, SPS and PPS -- and the record built from them is what *both* | ||
| 1185 | + // containers declare the track with: an mp4's `hvcC` box and a | ||
| 1186 | + // Matroska `CodecPrivate` are the same bytes, so the two files are one | ||
| 1187 | + // stream written twice rather than two. | ||
| 1188 | + let sample = | ||
| 1189 | + crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?; | ||
| 1190 | + if settings.format == Format::Hevc { | ||
| 1191 | + let muxer = match muxer { | ||
| 1192 | + Some(Muxer::Mkv(mkv)) => mkv, | ||
| 1193 | + Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), | ||
| 1194 | + none => { | ||
| 1195 | + let hvcc = hevc_params(au)?; | ||
| 1196 | + let sound = audio.zip(packets.take()); | ||
| 1197 | + let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc( | ||
| 1198 | + out, | ||
| 1199 | + &HevcParams { | ||
| 1200 | + width: meta.width, | ||
| 1201 | + height: meta.height, | ||
| 1202 | + frame_rate: meta.frame_rate, | ||
| 1203 | + hvcc: &hvcc, | ||
| 1204 | + }, | ||
| 1205 | + sound, | ||
| 1206 | + )?)) else { | ||
| 1207 | + unreachable!("just inserted a Matroska muxer") | ||
| 1208 | + }; | ||
| 1209 | + mkv | ||
| 1210 | + } | ||
| 1211 | + }; | ||
| 1212 | + return muxer.write_frame(&sample, key); | ||
| 1213 | + } | ||
| 746 | let muxer = match muxer { | 1214 | let muxer = match muxer { |
| 747 | - Some(Muxer::Mkv(mkv)) => mkv, | 1215 | + Some(Muxer::Mp4(mp4)) => mp4, |
| 748 | - Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), | 1216 | + Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), |
| 749 | none => { | 1217 | none => { |
| 750 | - // Every AV1 stream opens on a keyframe, and a keyframe carries | 1218 | + let hvcc = hevc_params(au)?; |
| 751 | - // the sequence header the track has to declare: an encoder that | 1219 | + let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc( |
| 752 | - // handed back neither has produced nothing a decoder can start. | ||
| 753 | - let config = crate::mux::av1_sequence_header(au) | ||
| 754 | - .ok_or("the first coded picture carries no AV1 sequence header")?; | ||
| 755 | - let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create( | ||
| 756 | out, | 1220 | out, |
| 757 | - &Av1Params { | 1221 | + &HevcParams { |
| 758 | width: meta.width, | 1222 | width: meta.width, |
| 759 | height: meta.height, | 1223 | height: meta.height, |
| 760 | frame_rate: meta.frame_rate, | 1224 | frame_rate: meta.frame_rate, |
| 761 | - config, | 1225 | + hvcc: &hvcc, |
| 762 | }, | 1226 | }, |
| 1227 | + audio, | ||
| 1228 | + )?)) else { | ||
| 1229 | + unreachable!("just inserted an mp4 muxer") | ||
| 1230 | + }; | ||
| 1231 | + mp4 | ||
| 1232 | + } | ||
| 1233 | + }; | ||
| 1234 | + return muxer.write_coded_sample(&sample, key); | ||
| 1235 | + } | ||
| 1236 | + if settings.format.is_av1() { | ||
| 1237 | + // Every AV1 stream opens on a keyframe, and a keyframe carries the | ||
| 1238 | + // sequence header the track has to declare: an encoder that handed back | ||
| 1239 | + // neither has produced nothing a decoder can start. The same header goes | ||
| 1240 | + // into a `CodecPrivate` and into an `av1C` -- one record, two containers. | ||
| 1241 | + fn params<'a>(meta: &VideoMeta, au: &'a [u8]) -> crate::Result<Av1Params<'a>> { | ||
| 1242 | + Ok(Av1Params { | ||
| 1243 | + width: meta.width, | ||
| 1244 | + height: meta.height, | ||
| 1245 | + frame_rate: meta.frame_rate, | ||
| 1246 | + config: crate::mux::av1_sequence_header(au) | ||
| 1247 | + .ok_or("the first coded picture carries no AV1 sequence header")?, | ||
| 1248 | + }) | ||
| 1249 | + } | ||
| 1250 | + if settings.format == Format::Av1 { | ||
| 1251 | + let muxer = match muxer { | ||
| 1252 | + Some(Muxer::Mkv(mkv)) => mkv, | ||
| 1253 | + Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), | ||
| 1254 | + none => { | ||
| 1255 | + // The sound with it, all of it: the Matroska muxer writes the | ||
| 1256 | + // packets into the clusters of the pictures they play under. | ||
| 1257 | + let sound = audio.zip(packets.take()); | ||
| 1258 | + let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create( | ||
| 1259 | + out, | ||
| 1260 | + ¶ms(meta, au)?, | ||
| 1261 | + sound, | ||
| 1262 | + )?)) else { | ||
| 1263 | + unreachable!("just inserted a Matroska muxer") | ||
| 1264 | + }; | ||
| 1265 | + mkv | ||
| 1266 | + } | ||
| 1267 | + }; | ||
| 1268 | + return muxer.write_frame(au, key); | ||
| 1269 | + } | ||
| 1270 | + let muxer = match muxer { | ||
| 1271 | + Some(Muxer::Mp4(mp4)) => mp4, | ||
| 1272 | + Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), | ||
| 1273 | + none => { | ||
| 1274 | + let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1( | ||
| 1275 | + out, | ||
| 1276 | + ¶ms(meta, au)?, | ||
| 1277 | + audio, | ||
| 763 | )?)) else { | 1278 | )?)) else { |
| 764 | - unreachable!("just inserted a Matroska muxer") | 1279 | + unreachable!("just inserted an mp4 muxer") |
| 765 | }; | 1280 | }; |
| 766 | - mkv | 1281 | + mp4 |
| 767 | } | 1282 | } |
| 768 | }; | 1283 | }; |
| 769 | - return muxer.write_frame(au, key); | 1284 | + return muxer.write_coded_sample(au, key); |
| 770 | } | 1285 | } |
| 771 | if !crate::mux::has_coded_slice(au) { | 1286 | if !crate::mux::has_coded_slice(au) { |
| 772 | return Ok(()); | 1287 | return Ok(()); |
| @@ -796,6 +1311,13 @@ fn write_video( | |||
| 796 | muxer.write_video_au(au) | 1311 | muxer.write_video_au(au) |
| 797 | } | 1312 | } |
| 798 | 1313 | ||
| 1314 | +/// The `hvcC` record of the first coded unit, or the refusal by name. Split out | ||
| 1315 | +/// because both HEVC containers ask it in the same words. | ||
| 1316 | +fn hevc_params(au: &[u8]) -> crate::Result<Vec<u8>> { | ||
| 1317 | + crate::mux::hvcc_record(au) | ||
| 1318 | + .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS")) | ||
| 1319 | +} | ||
| 1320 | + | ||
| 799 | fn bitrate_for(meta: &VideoMeta) -> u64 { | 1321 | fn bitrate_for(meta: &VideoMeta) -> u64 { |
| 800 | let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL; | 1322 | let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL; |
| 801 | (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE) | 1323 | (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE) |
| @@ -832,28 +1354,73 @@ enum Enc { | |||
| 832 | au: Vec<u8>, | 1354 | au: Vec<u8>, |
| 833 | flushed: bool, | 1355 | flushed: bool, |
| 834 | }, | 1356 | }, |
| 1357 | + /// HEVC, intra-only and software only: `encode_idr_intra_au_cropped` is a | ||
| 1358 | + /// *stateless* function of one picture, so a batch of frames is coded on as | ||
| 1359 | + /// many cores as there are lanes and collected back in order. | ||
| 1360 | + Hevc(HevcEnc), | ||
| 1361 | +} | ||
| 1362 | + | ||
| 1363 | +/// The intra HEVC seat. Frames arrive one at a time (the export walk is one | ||
| 1364 | +/// picture per timeline frame) and are held until there are [`lanes`] of them, | ||
| 1365 | +/// then coded in parallel and queued in **display order** -- fanning out is the | ||
| 1366 | +/// only thing that makes a pure-Rust HEVC export bearable (4.30 fps at 1080p on | ||
| 1367 | +/// 12 lanes against 0.55 fps on one, measured 2026-08-11), and an export whose | ||
| 1368 | +/// frames came back shuffled would be no export at all. | ||
| 1369 | +/// | ||
| 1370 | +/// ponytail: a batch of padded planes sits in memory (~3 MB a frame at 1080p, | ||
| 1371 | +/// so ~37 MB at 12 lanes) and the tail of a timeline is coded on fewer lanes | ||
| 1372 | +/// than the middle. Upgrade path is a pipeline that keeps every lane fed from a | ||
| 1373 | +/// decoder running ahead of the encoder rather than a batch barrier. | ||
| 1374 | +struct HevcEnc { | ||
| 1375 | + /// Padded I420 planes waiting for a lane, in display order. | ||
| 1376 | + pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>, | ||
| 1377 | + /// Coded access units not yet collected, in the same order. | ||
| 1378 | + ready: std::collections::VecDeque<Vec<u8>>, | ||
| 1379 | + /// The unit currently lent out, for the reason `Sw` owns one. | ||
| 1380 | + au: Vec<u8>, | ||
| 1381 | + /// The *coded* size: the picture's, rounded up to the 16-sample CTB grid. | ||
| 1382 | + width: usize, | ||
| 1383 | + height: usize, | ||
| 1384 | + /// Luma samples the conformance window crops off the right and the bottom, | ||
| 1385 | + /// so a decoder outputs the picture's own size ([`pad_to_ctb`]). | ||
| 1386 | + crop: (usize, usize), | ||
| 1387 | + qp: i32, | ||
| 1388 | + lanes: usize, | ||
| 835 | } | 1389 | } |
| 836 | 1390 | ||
| 837 | impl Enc { | 1391 | impl Enc { |
| 1392 | + /// Which seat this *is*, said the way [`video_label`] says it -- so the | ||
| 1393 | + /// name a running export shows is the name the card showed, or the honest | ||
| 1394 | + /// difference where the probe and the open disagreed. | ||
| 1395 | + fn label(&self) -> &'static str { | ||
| 1396 | + match self { | ||
| 1397 | + Self::Hw(_) => video_label(Format::Mp4, true), | ||
| 1398 | + Self::Sw { .. } => video_label(Format::Mp4, false), | ||
| 1399 | + Self::Av1Hw(_) => video_label(Format::Av1, true), | ||
| 1400 | + Self::Av1Sw { .. } => video_label(Format::Av1, false), | ||
| 1401 | + Self::Hevc(_) => video_label(Format::Hevc, false), | ||
| 1402 | + } | ||
| 1403 | + } | ||
| 1404 | + | ||
| 838 | fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> { | 1405 | fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> { |
| 839 | - if settings.format == Format::Av1 { | 1406 | + // Which *codec* the picture is, not which container it goes in: both AV1 |
| 1407 | + // formats run the same encoder, and so do both HEVC ones. | ||
| 1408 | + if settings.format.is_av1() { | ||
| 840 | return Self::open_av1(meta, settings); | 1409 | return Self::open_av1(meta, settings); |
| 841 | } | 1410 | } |
| 1411 | + if settings.format.is_hevc() { | ||
| 1412 | + return Self::open_hevc(meta, settings); | ||
| 1413 | + } | ||
| 842 | // A caller's number goes through the same clamp as the computed one: a | 1414 | // A caller's number goes through the same clamp as the computed one: a |
| 843 | // zero bitrate switches the software encoder's lookahead on, which would | 1415 | // zero bitrate switches the software encoder's lookahead on, which would |
| 844 | // break the one-picture-per-call contract `encode` documents below. | 1416 | // break the one-picture-per-call contract `encode` documents below. |
| 845 | - let bitrate = settings | 1417 | + let bitrate = bitrate_of(meta, settings); |
| 846 | - .bitrate | ||
| 847 | - .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); | ||
| 848 | // The plugin wants an exact rational, and the muxer already picks one | 1418 | // The plugin wants an exact rational, and the muxer already picks one |
| 849 | // that is exact at every rate we can read -- `fps * 1000 / 1000` would | 1419 | // that is exact at every rate we can read -- `fps * 1000 / 1000` would |
| 850 | // hand 24000/1001 over as a rounded 23.976, which is the same | 1420 | // hand 24000/1001 over as a rounded 23.976, which is the same |
| 851 | // truncation the container timing had. | 1421 | // truncation the container timing had. |
| 852 | - let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; | 1422 | + crate::mux::frame_timing(meta.frame_rate)?; |
| 853 | - if !settings.force_sw | 1423 | + if let Some(hw) = hw_seat(meta, settings) { |
| 854 | - && !forced("VE_SW_ENC") | ||
| 855 | - && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate) | ||
| 856 | - { | ||
| 857 | eprintln!("export encoder: hardware (VA-API plugin)"); | 1424 | eprintln!("export encoder: hardware (VA-API plugin)"); |
| 858 | return Ok(Self::Hw(hw)); | 1425 | return Ok(Self::Hw(hw)); |
| 859 | } | 1426 | } |
| @@ -894,19 +1461,12 @@ impl Enc { | |||
| 894 | /// cros-codecs release that fixes it) plus a probe encode of one frame at | 1461 | /// cros-codecs release that fixes it) plus a probe encode of one frame at |
| 895 | /// open, after which this can prefer hardware the way H.264 does. | 1462 | /// open, after which this can prefer hardware the way H.264 does. |
| 896 | fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> { | 1463 | fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> { |
| 897 | - let bitrate = settings | 1464 | + let bitrate = bitrate_of(meta, settings); |
| 898 | - .bitrate | ||
| 899 | - .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); | ||
| 900 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; | 1465 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; |
| 901 | // Two seconds between keyframes, as the H.264 seat does: a seek may only | 1466 | // Two seconds between keyframes, as the H.264 seat does: a seek may only |
| 902 | // land on one, and this is what a cluster of the Matroska file is. | 1467 | // land on one, and this is what a cluster of the Matroska file is. |
| 903 | let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64; | 1468 | let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64; |
| 904 | - if forced("VE_HW_AV1") | 1469 | + if let Some(hw) = hw_seat(meta, settings) { |
| 905 | - && !settings.force_sw | ||
| 906 | - && !forced("VE_SW_ENC") | ||
| 907 | - && let Some(hw) = | ||
| 908 | - HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) | ||
| 909 | - { | ||
| 910 | eprintln!("export encoder: hardware AV1 (VA-API plugin)"); | 1470 | eprintln!("export encoder: hardware AV1 (VA-API plugin)"); |
| 911 | return Ok(Self::Av1Hw(hw)); | 1471 | return Ok(Self::Av1Hw(hw)); |
| 912 | } | 1472 | } |
| @@ -942,6 +1502,53 @@ impl Enc { | |||
| 942 | }) | 1502 | }) |
| 943 | } | 1503 | } |
| 944 | 1504 | ||
| 1505 | + /// The intra HEVC seat, software and frame-parallel. There is no hardware | ||
| 1506 | + /// half: the plugin encodes H.264 and AV1 and nothing else, which | ||
| 1507 | + /// [`hw_seat`] says by refusing to probe one. | ||
| 1508 | + /// | ||
| 1509 | + /// **Intra-only, deliberately.** The vendored encoder's inter modes code | ||
| 1510 | + /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of | ||
| 1511 | + /// timeline in half an hour, which is not an export anybody waits for -- | ||
| 1512 | + /// while the intra path does 4.30 fps on the same picture and the same | ||
| 1513 | + /// cores. So every frame is an IDR, the file is an intraframe master in the | ||
| 1514 | + /// shape of ProRes or DNxHD, and the card says so where a user picks it. | ||
| 1515 | + /// | ||
| 1516 | + /// The picture is coded **padded** to the 16-sample CTB grid and the SPS | ||
| 1517 | + /// crops it back ([`pad_to_ctb`], the vendored conformance-window patch), so | ||
| 1518 | + /// 1920x1080 is a legal export rather than a refusal. | ||
| 1519 | + fn open_hevc(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> { | ||
| 1520 | + // The muxers time by it and the mp4 one wants an exact rational: asked | ||
| 1521 | + // here so an impossible rate fails before a frame is coded. | ||
| 1522 | + crate::mux::frame_timing(meta.frame_rate)?; | ||
| 1523 | + // 4:2:0 addresses its conformance window in *chroma* samples, so an odd | ||
| 1524 | + // picture cannot be cropped back to itself -- and an odd dimension has | ||
| 1525 | + // no chroma plane of its own to begin with. Named rather than padded to | ||
| 1526 | + // something a decoder would then show a column of. | ||
| 1527 | + if meta.width % 2 != 0 || meta.height % 2 != 0 { | ||
| 1528 | + return Err(format!( | ||
| 1529 | + "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions", | ||
| 1530 | + meta.width, meta.height | ||
| 1531 | + ) | ||
| 1532 | + .into()); | ||
| 1533 | + } | ||
| 1534 | + let (width, height) = ( | ||
| 1535 | + (meta.width as usize).next_multiple_of(CTB), | ||
| 1536 | + (meta.height as usize).next_multiple_of(CTB), | ||
| 1537 | + ); | ||
| 1538 | + let lanes = std::thread::available_parallelism().map_or(1, |n| n.get()); | ||
| 1539 | + eprintln!("export encoder: software HEVC intra (oxideav-h265)"); | ||
| 1540 | + Ok(Self::Hevc(HevcEnc { | ||
| 1541 | + pending: Vec::new(), | ||
| 1542 | + ready: std::collections::VecDeque::new(), | ||
| 1543 | + au: Vec::new(), | ||
| 1544 | + width, | ||
| 1545 | + height, | ||
| 1546 | + crop: (width - meta.width as usize, height - meta.height as usize), | ||
| 1547 | + qp: hevc_qp(meta, settings), | ||
| 1548 | + lanes: lanes.min(HEVC_LANES), | ||
| 1549 | + })) | ||
| 1550 | + } | ||
| 1551 | + | ||
| 945 | /// One picture in, at most one access unit out, and whether that unit is one | 1552 | /// One picture in, at most one access unit out, and whether that unit is one |
| 946 | /// a decoder may be started from -- which only the Matroska muxer asks, the | 1553 | /// a decoder may be started from -- which only the Matroska muxer asks, the |
| 947 | /// mp4 one reading its own sync flag off the IDR slice. | 1554 | /// mp4 one reading its own sync flag off the IDR slice. |
| @@ -984,6 +1591,23 @@ impl Enc { | |||
| 984 | collect_av1(context, ready)?; | 1591 | collect_av1(context, ready)?; |
| 985 | Ok(pop_av1(ready, au)) | 1592 | Ok(pop_av1(ready, au)) |
| 986 | } | 1593 | } |
| 1594 | + Self::Hevc(hevc) => { | ||
| 1595 | + hevc.pending.push(pad_to_ctb( | ||
| 1596 | + y, | ||
| 1597 | + u, | ||
| 1598 | + v, | ||
| 1599 | + width as usize, | ||
| 1600 | + height as usize, | ||
| 1601 | + hevc.width, | ||
| 1602 | + hevc.height, | ||
| 1603 | + )); | ||
| 1604 | + if hevc.pending.len() >= hevc.lanes { | ||
| 1605 | + hevc.code_batch()?; | ||
| 1606 | + } | ||
| 1607 | + // Every intra AU is an IDR, so every one of them is a key | ||
| 1608 | + // frame -- which is what an intraframe master means. | ||
| 1609 | + Ok(pop_hevc(hevc)) | ||
| 1610 | + } | ||
| 987 | Self::Hw(hw) => Ok(hw | 1611 | Self::Hw(hw) => Ok(hw |
| 988 | .encode(y, u, v, width, height, false)? | 1612 | .encode(y, u, v, width, height, false)? |
| 989 | .map(|au| (au, false))), | 1613 | .map(|au| (au, false))), |
| @@ -1023,6 +1647,14 @@ impl Enc { | |||
| 1023 | } | 1647 | } |
| 1024 | Ok(pop_av1(ready, au)) | 1648 | Ok(pop_av1(ready, au)) |
| 1025 | } | 1649 | } |
| 1650 | + Self::Hevc(hevc) => { | ||
| 1651 | + // The tail batch: fewer frames than lanes, coded on as many | ||
| 1652 | + // cores as there are frames left. | ||
| 1653 | + if !hevc.pending.is_empty() { | ||
| 1654 | + hevc.code_batch()?; | ||
| 1655 | + } | ||
| 1656 | + Ok(pop_hevc(hevc)) | ||
| 1657 | + } | ||
| 1026 | Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), | 1658 | Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), |
| 1027 | Self::Sw { | 1659 | Self::Sw { |
| 1028 | encoder, | 1660 | encoder, |
| @@ -1042,6 +1674,103 @@ impl Enc { | |||
| 1042 | } | 1674 | } |
| 1043 | } | 1675 | } |
| 1044 | 1676 | ||
| 1677 | +impl HevcEnc { | ||
| 1678 | + /// The whole pending batch, one frame per lane, collected back in the order | ||
| 1679 | + /// it went out -- `std::thread::scope`, because the encode borrows the | ||
| 1680 | + /// planes rather than copying them again. A panic inside a lane comes back | ||
| 1681 | + /// as an error rather than unwinding the export thread. | ||
| 1682 | + fn code_batch(&mut self) -> crate::Result<()> { | ||
| 1683 | + let (width, height, qp, crop) = (self.width, self.height, self.qp, self.crop); | ||
| 1684 | + let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| { | ||
| 1685 | + let lanes: Vec<_> = self | ||
| 1686 | + .pending | ||
| 1687 | + .iter() | ||
| 1688 | + .map(|(y, cb, cr)| { | ||
| 1689 | + scope.spawn(move || { | ||
| 1690 | + oxideav_h265::encoder::intra::encode_idr_intra_au_cropped( | ||
| 1691 | + y, cb, cr, width, height, qp, crop.0, crop.1, | ||
| 1692 | + ) | ||
| 1693 | + .map(|coded| coded.au) | ||
| 1694 | + .map_err(|e| crate::Error::from(format!("HEVC intra encode: {e:?}"))) | ||
| 1695 | + }) | ||
| 1696 | + }) | ||
| 1697 | + .collect(); | ||
| 1698 | + lanes | ||
| 1699 | + .into_iter() | ||
| 1700 | + .map(|lane| { | ||
| 1701 | + lane.join() | ||
| 1702 | + .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into())) | ||
| 1703 | + }) | ||
| 1704 | + .collect() | ||
| 1705 | + }); | ||
| 1706 | + for au in coded { | ||
| 1707 | + self.ready.push_back(au?); | ||
| 1708 | + } | ||
| 1709 | + self.pending.clear(); | ||
| 1710 | + Ok(()) | ||
| 1711 | + } | ||
| 1712 | +} | ||
| 1713 | + | ||
| 1714 | +/// The oldest coded intra AU, lent out under the same "valid until the next | ||
| 1715 | +/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key flag | ||
| 1716 | +/// is not a guess. | ||
| 1717 | +fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> { | ||
| 1718 | + hevc.au = hevc.ready.pop_front()?; | ||
| 1719 | + Some((&hevc.au[..], true)) | ||
| 1720 | +} | ||
| 1721 | + | ||
| 1722 | +/// One I420 picture copied onto the padded plane sizes the CTB grid needs, the | ||
| 1723 | +/// added rows and columns filled by **replicating the edge** rather than with | ||
| 1724 | +/// black: the padding is coded and then cropped away, and a black border would | ||
| 1725 | +/// bleed into the last real column through the intra prediction and the | ||
| 1726 | +/// transform that straddles it. | ||
| 1727 | +fn pad_to_ctb( | ||
| 1728 | + y: &[u8], | ||
| 1729 | + u: &[u8], | ||
| 1730 | + v: &[u8], | ||
| 1731 | + width: usize, | ||
| 1732 | + height: usize, | ||
| 1733 | + padded_w: usize, | ||
| 1734 | + padded_h: usize, | ||
| 1735 | +) -> (Vec<u8>, Vec<u8>, Vec<u8>) { | ||
| 1736 | + let plane = |src: &[u8], w: usize, h: usize, pw: usize, ph: usize| { | ||
| 1737 | + let mut out = vec![0u8; pw * ph]; | ||
| 1738 | + for row in 0..ph { | ||
| 1739 | + let src_row = &src[row.min(h - 1) * w..][..w]; | ||
| 1740 | + let dst = &mut out[row * pw..][..pw]; | ||
| 1741 | + dst[..w].copy_from_slice(src_row); | ||
| 1742 | + dst[w..].fill(src_row[w - 1]); | ||
| 1743 | + } | ||
| 1744 | + out | ||
| 1745 | + }; | ||
| 1746 | + ( | ||
| 1747 | + plane(y, width, height, padded_w, padded_h), | ||
| 1748 | + plane(u, width / 2, height / 2, padded_w / 2, padded_h / 2), | ||
| 1749 | + plane(v, width / 2, height / 2, padded_w / 2, padded_h / 2), | ||
| 1750 | + ) | ||
| 1751 | +} | ||
| 1752 | + | ||
| 1753 | +/// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a | ||
| 1754 | +/// user picked -- the card has no QP control and this codec has no rate control, | ||
| 1755 | +/// so the two are joined by measurement rather than promised to each other. | ||
| 1756 | +/// | ||
| 1757 | +/// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured | ||
| 1758 | +/// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP | ||
| 1759 | +/// is a factor of two in rate, which is the classic HEVC relation. So the QP | ||
| 1760 | +/// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is | ||
| 1761 | +/// clamped, because this is a *quality* dial and not a rate controller: below QP | ||
| 1762 | +/// 22 the file grows without a picture to show for it, and past QP 40 an | ||
| 1763 | +/// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30 | ||
| 1764 | +/// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out | ||
| 1765 | +/// bigger than that, which is what "intra-only, large files" on the format row | ||
| 1766 | +/// means: the row buys quality, not a size. | ||
| 1767 | +fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 { | ||
| 1768 | + let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate; | ||
| 1769 | + let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0); | ||
| 1770 | + let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2(); | ||
| 1771 | + (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX) | ||
| 1772 | +} | ||
| 1773 | + | ||
| 1045 | /// Every temporal unit `rav1e` has finished, moved into the queue in display | 1774 | /// Every temporal unit `rav1e` has finished, moved into the queue in display |
| 1046 | /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is | 1775 | /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is |
| 1047 | /// through) are the two ways it says there is nothing more; `Encoded` means a | 1776 | /// through) are the two ways it says there is nothing more; `Encoded` means a |
| @@ -1198,4 +1927,100 @@ mod tests { | |||
| 1198 | assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny"); | 1927 | assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny"); |
| 1199 | assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); | 1928 | assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); |
| 1200 | } | 1929 | } |
| 1930 | + | ||
| 1931 | + fn meta(width: u32, height: u32) -> VideoMeta { | ||
| 1932 | + VideoMeta { | ||
| 1933 | + width, | ||
| 1934 | + height, | ||
| 1935 | + frame_rate: 30.0, | ||
| 1936 | + frame_count: 1, | ||
| 1937 | + codec: crate::demux::Codec::H264, | ||
| 1938 | + } | ||
| 1939 | + } | ||
| 1940 | + | ||
| 1941 | + /// The bitrate row a user picked, read as the quality tier it is: a higher | ||
| 1942 | + /// row is a lower QP, the band is honoured at both ends, and the same | ||
| 1943 | + /// picture at the same rate gets the same number whatever its size (the | ||
| 1944 | + /// mapping is bits per *pixel*, which is what makes 720p and 1080p one | ||
| 1945 | + /// table). | ||
| 1946 | + #[test] | ||
| 1947 | + fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() { | ||
| 1948 | + let at = |width, height, mbps: Option<u64>| { | ||
| 1949 | + hevc_qp( | ||
| 1950 | + &meta(width, height), | ||
| 1951 | + &ExportSettings { | ||
| 1952 | + bitrate: mbps.map(|m| m * 1_000_000), | ||
| 1953 | + ..Default::default() | ||
| 1954 | + }, | ||
| 1955 | + ) | ||
| 1956 | + }; | ||
| 1957 | + // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at | ||
| 1958 | + // QP 27, which is just over half: five QP up, and QP is not an | ||
| 1959 | + // arithmetic scale, so this is the number the formula gives. | ||
| 1960 | + assert_eq!(at(1920, 1080, Some(20)), 32); | ||
| 1961 | + // Every step down the card is a step up in QP, never sideways. | ||
| 1962 | + let rows: Vec<i32> = [20, 12, 8, 4, 2, 1] | ||
| 1963 | + .into_iter() | ||
| 1964 | + .map(|mbps| at(1920, 1080, Some(mbps))) | ||
| 1965 | + .collect(); | ||
| 1966 | + assert!( | ||
| 1967 | + rows.windows(2).all(|w| w[0] <= w[1]), | ||
| 1968 | + "a lower bitrate row must never code at a lower QP: {rows:?}" | ||
| 1969 | + ); | ||
| 1970 | + assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped"); | ||
| 1971 | + // ...and the top of the range is the clamp, not an unbounded number: 20 | ||
| 1972 | + // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs. | ||
| 1973 | + assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN); | ||
| 1974 | + // The same bits per pixel is the same quantiser at any size: 1080p at | ||
| 1975 | + // 20 Mbps and 720p at 8.9 Mbps are one picture quality. | ||
| 1976 | + assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9))); | ||
| 1977 | + // The automatic bitrate is 0.1 bpp at every size, so it is one QP | ||
| 1978 | + // everywhere -- the honest end of "intra-only, large files": the file | ||
| 1979 | + // will be bigger than the row says, and the row buys quality. | ||
| 1980 | + assert_eq!(at(1920, 1080, None), at(1280, 720, None)); | ||
| 1981 | + } | ||
| 1982 | + | ||
| 1983 | + /// The padding a non-%16 picture is coded with replicates the edge instead | ||
| 1984 | + /// of filling black: the coded rows past the picture carry its last row, so | ||
| 1985 | + /// nothing bleeds into the last real line through the intra prediction. | ||
| 1986 | + #[test] | ||
| 1987 | + fn the_ctb_padding_replicates_the_edge() { | ||
| 1988 | + // 6x2 luma, values 1..=12, padded to 8x4 (CTB is 16, so this checks the | ||
| 1989 | + // copy itself with numbers small enough to read). | ||
| 1990 | + let y: Vec<u8> = (1..=12).collect(); | ||
| 1991 | + let u: Vec<u8> = vec![40, 41, 42]; | ||
| 1992 | + let v: Vec<u8> = vec![50, 51, 52]; | ||
| 1993 | + let (py, pu, pv) = pad_to_ctb(&y, &u, &v, 6, 2, 8, 4); | ||
| 1994 | + assert_eq!( | ||
| 1995 | + py, | ||
| 1996 | + vec![ | ||
| 1997 | + 1, 2, 3, 4, 5, 6, 6, 6, // the row, then its last sample twice | ||
| 1998 | + 7, 8, 9, 10, 11, 12, 12, 12, // | ||
| 1999 | + 7, 8, 9, 10, 11, 12, 12, 12, // the last row, replicated | ||
| 2000 | + 7, 8, 9, 10, 11, 12, 12, 12, | ||
| 2001 | + ] | ||
| 2002 | + ); | ||
| 2003 | + // Chroma is half of everything, padded the same way. | ||
| 2004 | + assert_eq!(pu, vec![40, 41, 42, 42, 40, 41, 42, 42]); | ||
| 2005 | + assert_eq!(pv, vec![50, 51, 52, 52, 50, 51, 52, 52]); | ||
| 2006 | + } | ||
| 2007 | + | ||
| 2008 | + /// An odd picture cannot be cropped back to itself in 4:2:0 -- the | ||
| 2009 | + /// conformance window is stated in chroma samples -- so it is refused by | ||
| 2010 | + /// name rather than written a column wider than the timeline. | ||
| 2011 | + #[test] | ||
| 2012 | + fn an_odd_picture_is_refused_an_hevc_export_by_name() { | ||
| 2013 | + let settings = ExportSettings { | ||
| 2014 | + format: Format::Hevc, | ||
| 2015 | + ..Default::default() | ||
| 2016 | + }; | ||
| 2017 | + let refused = Enc::open(&meta(1919, 1080), &settings) | ||
| 2018 | + .err() | ||
| 2019 | + .expect("an odd width has no chroma plane") | ||
| 2020 | + .to_string(); | ||
| 2021 | + assert!(refused.contains("1919x1080"), "{refused}"); | ||
| 2022 | + assert!(refused.contains("even"), "{refused}"); | ||
| 2023 | + // ...and the even one it neighbours opens. | ||
| 2024 | + assert!(Enc::open(&meta(1920, 1080), &settings).is_ok()); | ||
| 2025 | + } | ||
| 1201 | } | 2026 | } |
| @@ -11,6 +11,7 @@ pub mod edith; | |||
| 11 | pub mod eq; | 11 | pub mod eq; |
| 12 | pub mod export; | 12 | pub mod export; |
| 13 | pub mod hw; | 13 | pub mod hw; |
| 14 | +pub mod limiter; | ||
| 14 | pub mod mux; | 15 | pub mod mux; |
| 15 | pub mod playback; | 16 | pub mod playback; |
| 16 | pub mod project; | 17 | pub mod project; |
| @@ -27,7 +28,7 @@ pub use demux::{Codec, VideoMeta}; | |||
| 27 | pub use export::ExportHandle; | 28 | pub use export::ExportHandle; |
| 28 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; | 29 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; |
| 29 | pub use playback::PlaybackSession; | 30 | pub use playback::PlaybackSession; |
| 30 | -pub use project::{Clip, Project, Speed}; | 31 | +pub use project::{Clip, Project, Rate, Speed}; |
| 31 | 32 | ||
| 32 | /// Whether a path names a standalone audio file -- a source with no picture, | 33 | /// Whether a path names a standalone audio file -- a source with no picture, |
| 33 | /// which belongs on the audio lane and nowhere else. Extension only, lowercased: | 34 | /// which belongs on the audio lane and nowhere else. Extension only, lowercased: |
| @@ -0,0 +1,259 @@ | |||
| 1 | +//! The master limiter: one ceiling the whole mix is held under, applied where | ||
| 2 | +//! the lanes are summed and nowhere else ([`crate::audio::mix`]). | ||
| 3 | +//! | ||
| 4 | +//! A mix is an add, and two lanes at full scale add past full scale: what used | ||
| 5 | +//! to happen there was a hard `clamp`, which is a squared-off waveform and the | ||
| 6 | +//! worst-sounding thing an editor can do to a hot timeline. This holds the sum | ||
| 7 | +//! down *before* it reaches the clamp instead, and the clamp stays behind it as | ||
| 8 | +//! the backstop it always was. | ||
| 9 | +//! | ||
| 10 | +//! Per sample, no FFT, no allocation while it runs: | ||
| 11 | +//! | ||
| 12 | +//! * **Lookahead.** The mix is written into a delay line [`LOOKAHEAD_MS`] long | ||
| 13 | +//! and read out of it that much later, so the gain a peak needs is already in | ||
| 14 | +//! force by the time the peak itself is emitted. No attack overshoot -- the | ||
| 15 | +//! first sample over the ceiling is the first sample held under it, which is | ||
| 16 | +//! what makes the peak of an exported file a *measurement* and not a hope. | ||
| 17 | +//! * **Linked channels.** One gain for the frame, off the loudest channel in | ||
| 18 | +//! it: a per-channel gain would move the stereo image every time one side | ||
| 19 | +//! peaked. | ||
| 20 | +//! * **Soft knee.** [`KNEE_DB`] wide and centred on the ceiling, so the gain | ||
| 21 | +//! comes in gradually instead of switching on at one sample and off at the | ||
| 22 | +//! next. The knee's own curve never lets the output past the ceiling (at the | ||
| 23 | +//! centre it is already `KNEE_DB/8` under it), which is what keeps the | ||
| 24 | +//! guarantee a hard knee would give. | ||
| 25 | +//! * **Release**, not a per-sample snap back: `RELEASE_MS` of exponential | ||
| 26 | +//! recovery, so one loud transient does not pump the whole bar around it. | ||
| 27 | +//! | ||
| 28 | +//! The latency is *taken out again*, not paid: the first `lookahead` frames of | ||
| 29 | +//! output -- the empty delay line -- are dropped, so what comes out is sample | ||
| 30 | +//! aligned with what went in and the sound stays locked to the picture. What | ||
| 31 | +//! that costs is the last couple of milliseconds of the timeline's tail, which | ||
| 32 | +//! is the trade every lookahead limiter makes. | ||
| 33 | + | ||
| 34 | +/// How far ahead the gain looks. 2 ms is ~96 frames at 48 kHz: long enough to | ||
| 35 | +/// ride a transient in smoothly, short enough that the tail it eats is nothing. | ||
| 36 | +const LOOKAHEAD_MS: f32 = 2.0; | ||
| 37 | +/// How wide the knee is, centred on the ceiling. | ||
| 38 | +const KNEE_DB: f32 = 6.0; | ||
| 39 | +/// How fast the gain comes back once the loud part is over. | ||
| 40 | +const RELEASE_MS: f32 = 120.0; | ||
| 41 | + | ||
| 42 | +/// What a project's master limiter is set to: a ceiling in dBFS and whether it | ||
| 43 | +/// is in circuit at all. Off by default -- a timeline nobody has asked to limit | ||
| 44 | +/// mixes exactly as it always did, down to the bit. | ||
| 45 | +#[derive(Clone, Copy, Debug, PartialEq)] | ||
| 46 | +pub struct Limiter { | ||
| 47 | + /// The level nothing may pass, in dBFS (0 dBFS is full scale). | ||
| 48 | + pub ceiling_db: f32, | ||
| 49 | + pub on: bool, | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +impl Default for Limiter { | ||
| 53 | + fn default() -> Self { | ||
| 54 | + Self { | ||
| 55 | + ceiling_db: -1.0, | ||
| 56 | + on: false, | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +impl Limiter { | ||
| 62 | + /// The ceilings a front-end may set, and what a file may name: a limiter | ||
| 63 | + /// above full scale would limit nothing, and one 24 dB down is already a | ||
| 64 | + /// fader. | ||
| 65 | + pub const MIN_DB: f32 = -24.0; | ||
| 66 | + pub const MAX_DB: f32 = 0.0; | ||
| 67 | + | ||
| 68 | + /// The setting with `ceiling_db` put inside the range above, which is what | ||
| 69 | + /// a nudge and a parsed line both go through. Not finite means the default. | ||
| 70 | + pub fn with_ceiling(self, ceiling_db: f32) -> Self { | ||
| 71 | + Self { | ||
| 72 | + ceiling_db: match ceiling_db.is_finite() { | ||
| 73 | + true => ceiling_db.clamp(Self::MIN_DB, Self::MAX_DB), | ||
| 74 | + false => Self::default().ceiling_db, | ||
| 75 | + }, | ||
| 76 | + ..self | ||
| 77 | + } | ||
| 78 | + } | ||
| 79 | + | ||
| 80 | + /// Whether it is doing anything to the sound -- what an export asks before | ||
| 81 | + /// it decides a packet copy would be a lie. | ||
| 82 | + pub fn is_active(self) -> bool { | ||
| 83 | + self.on | ||
| 84 | + } | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// dBFS as an amplitude. `db_to_linear(0.0)` is exactly 1.0, which is what | ||
| 88 | +/// keeps a flat setting a bit-exact passthrough. | ||
| 89 | +pub fn db_to_linear(db: f32) -> f32 { | ||
| 90 | + match db == 0.0 { | ||
| 91 | + true => 1.0, | ||
| 92 | + false => 10f32.powf(db / 20.0), | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// One running limiter: the delay line, the peak window and the gain. | ||
| 97 | +pub struct LimiterState { | ||
| 98 | + channels: usize, | ||
| 99 | + /// The delayed mix, one frame per slot, `lookahead + 1` frames round. | ||
| 100 | + line: Vec<f32>, | ||
| 101 | + /// The loudest channel of each frame in `line`, same indexing. | ||
| 102 | + peaks: Vec<f32>, | ||
| 103 | + /// Where the next frame is written; the frame read out is the one after it. | ||
| 104 | + at: usize, | ||
| 105 | + /// Frames still to be swallowed before anything is emitted -- the empty | ||
| 106 | + /// delay line, which is how the latency is paid back (module docs). | ||
| 107 | + warm: usize, | ||
| 108 | + gain: f32, | ||
| 109 | + ceiling: f32, | ||
| 110 | + /// Where the knee starts, as an amplitude: under this the fast path runs | ||
| 111 | + /// and no logarithm is taken. | ||
| 112 | + knee_floor: f32, | ||
| 113 | + release: f32, | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +impl LimiterState { | ||
| 117 | + pub fn new(params: &Limiter, sample_rate: u32, channels: usize) -> Self { | ||
| 118 | + let channels = channels.max(1); | ||
| 119 | + let frames = ((LOOKAHEAD_MS / 1000.0 * sample_rate as f32) as usize).max(1) + 1; | ||
| 120 | + let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db; | ||
| 121 | + Self { | ||
| 122 | + channels, | ||
| 123 | + line: vec![0.0; frames * channels], | ||
| 124 | + peaks: vec![0.0; frames], | ||
| 125 | + at: 0, | ||
| 126 | + warm: frames - 1, | ||
| 127 | + gain: 1.0, | ||
| 128 | + ceiling: db_to_linear(ceiling_db), | ||
| 129 | + knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0), | ||
| 130 | + // One time constant per sample: the gain covers 63% of the way back | ||
| 131 | + // in `RELEASE_MS`. | ||
| 132 | + release: 1.0 - (-1000.0 / (RELEASE_MS * sample_rate as f32)).exp(), | ||
| 133 | + } | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than | ||
| 137 | + /// what came in by the delay line's length, once, at the first call. | ||
| 138 | + pub fn process(&mut self, buf: &mut Vec<f32>) { | ||
| 139 | + let channels = self.channels; | ||
| 140 | + let frames = buf.len() / channels; | ||
| 141 | + let mut out: Vec<f32> = Vec::with_capacity(buf.len()); | ||
| 142 | + for f in 0..frames { | ||
| 143 | + let frame = &buf[f * channels..(f + 1) * channels]; | ||
| 144 | + let peak = frame.iter().fold(0.0f32, |m, s| m.max(s.abs())); | ||
| 145 | + self.line[self.at * channels..(self.at + 1) * channels].copy_from_slice(frame); | ||
| 146 | + self.peaks[self.at] = peak; | ||
| 147 | + self.at = (self.at + 1) % self.peaks.len(); | ||
| 148 | + | ||
| 149 | + // Every frame still in the line, the one about to leave included: | ||
| 150 | + // the gain below is therefore never larger than what the *emitted* | ||
| 151 | + // frame needs, which is the whole no-overshoot guarantee. | ||
| 152 | + let window = self.peaks.iter().fold(0.0f32, |m, &p| m.max(p)); | ||
| 153 | + let want = match window <= self.knee_floor { | ||
| 154 | + true => 1.0, | ||
| 155 | + false => self.reduction(window), | ||
| 156 | + }; | ||
| 157 | + // Up is the release, down is instant -- and instant is safe here | ||
| 158 | + // only because the frame it is for has not been emitted yet. | ||
| 159 | + self.gain += (want - self.gain).max(0.0) * self.release; | ||
| 160 | + self.gain = self.gain.min(want); | ||
| 161 | + | ||
| 162 | + if self.warm > 0 { | ||
| 163 | + self.warm -= 1; | ||
| 164 | + continue; | ||
| 165 | + } | ||
| 166 | + for c in 0..channels { | ||
| 167 | + out.push(self.line[self.at * channels + c] * self.gain); | ||
| 168 | + } | ||
| 169 | + } | ||
| 170 | + *buf = out; | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + /// The gain the loudest frame in the window needs: 1.0 under the knee, the | ||
| 174 | + /// knee's own curve across it, `ceiling/peak` above it. | ||
| 175 | + fn reduction(&self, peak: f32) -> f32 { | ||
| 176 | + let level = 20.0 * peak.log10(); | ||
| 177 | + let ceiling = 20.0 * self.ceiling.log10(); | ||
| 178 | + let over = level - ceiling; | ||
| 179 | + let out = match over >= KNEE_DB / 2.0 { | ||
| 180 | + true => ceiling, | ||
| 181 | + // The cookbook's quadratic knee. At `over == 0` this is already | ||
| 182 | + // `KNEE_DB/8` under the ceiling and it never crosses it, so nothing | ||
| 183 | + // the knee passes needs a clamp behind it. | ||
| 184 | + false => level - (over + KNEE_DB / 2.0).powi(2) / (2.0 * KNEE_DB), | ||
| 185 | + }; | ||
| 186 | + 10f32.powf((out - level) / 20.0) | ||
| 187 | + } | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +#[cfg(test)] | ||
| 191 | +mod tests { | ||
| 192 | + use super::*; | ||
| 193 | + | ||
| 194 | + /// The promise the whole file exists for: a sum well past full scale comes | ||
| 195 | + /// out under the ceiling, sample for sample, and the quiet part of the same | ||
| 196 | + /// stream is left where it was. | ||
| 197 | + #[test] | ||
| 198 | + fn a_hot_mix_comes_out_under_the_ceiling() { | ||
| 199 | + let rate = 48_000; | ||
| 200 | + let params = Limiter { | ||
| 201 | + ceiling_db: -3.0, | ||
| 202 | + on: true, | ||
| 203 | + }; | ||
| 204 | + let mut state = LimiterState::new(¶ms, rate, 2); | ||
| 205 | + // Half a second of quiet, then half a second at 4x full scale: the | ||
| 206 | + // join is where an attack overshoot would show. | ||
| 207 | + let mut buf: Vec<f32> = (0..rate) | ||
| 208 | + .flat_map(|i| { | ||
| 209 | + let t = i as f32 / rate as f32; | ||
| 210 | + let amp = match i < rate / 2 { | ||
| 211 | + true => 0.05, | ||
| 212 | + false => 4.0, | ||
| 213 | + }; | ||
| 214 | + let s = amp * (t * 440.0 * std::f32::consts::TAU).sin(); | ||
| 215 | + [s, s] | ||
| 216 | + }) | ||
| 217 | + .collect(); | ||
| 218 | + let quiet_in = buf[..rate as usize / 2].to_vec(); | ||
| 219 | + state.process(&mut buf); | ||
| 220 | + let ceiling = db_to_linear(-3.0); | ||
| 221 | + let peak = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); | ||
| 222 | + assert!( | ||
| 223 | + peak <= ceiling + 1e-6, | ||
| 224 | + "peak {peak} passed the {ceiling} ceiling" | ||
| 225 | + ); | ||
| 226 | + // ...and it is not simply silence: the loud half is right at the wall. | ||
| 227 | + assert!( | ||
| 228 | + peak > ceiling * 0.99, | ||
| 229 | + "peak {peak} is nowhere near the wall" | ||
| 230 | + ); | ||
| 231 | + // The quiet half is untouched, bar the frames the lookahead eats and | ||
| 232 | + // the ones where the gain has already started coming down for the loud | ||
| 233 | + // part that is about to arrive. | ||
| 234 | + let head = quiet_in.len() / 2; | ||
| 235 | + for (a, b) in buf[..head].iter().zip(&quiet_in[..head]) { | ||
| 236 | + assert!((a - b).abs() < 1e-6, "{a} != {b} under the knee"); | ||
| 237 | + } | ||
| 238 | + // The delay line is paid back, not carried: the output is shorter by | ||
| 239 | + // exactly the lookahead and nothing else. | ||
| 240 | + assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2); | ||
| 241 | + } | ||
| 242 | + | ||
| 243 | + /// Flat settings are a passthrough, which is what the export invariant | ||
| 244 | + /// rests on: 0 dB is exactly 1.0, never 0.9999999. | ||
| 245 | + #[test] | ||
| 246 | + fn zero_db_is_exactly_unity() { | ||
| 247 | + assert_eq!(db_to_linear(0.0), 1.0); | ||
| 248 | + assert!((db_to_linear(-6.0) - 0.5011872).abs() < 1e-6); | ||
| 249 | + assert!(!Limiter::default().is_active(), "off until asked for"); | ||
| 250 | + assert_eq!( | ||
| 251 | + Limiter::default().with_ceiling(-99.0).ceiling_db, | ||
| 252 | + Limiter::MIN_DB | ||
| 253 | + ); | ||
| 254 | + assert_eq!( | ||
| 255 | + Limiter::default().with_ceiling(f32::NAN).ceiling_db, | ||
| 256 | + Limiter::default().ceiling_db | ||
| 257 | + ); | ||
| 258 | + } | ||
| 259 | +} | ||
| @@ -5,10 +5,17 @@ | |||
| 5 | //! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all, | 5 | //! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all, |
| 6 | //! so an AV1 export is written as EBML by hand exactly as an AV1 import is read | 6 | //! so an AV1 export is written as EBML by hand exactly as an AV1 import is read |
| 7 | //! as EBML by hand ([`MkvMuxer`]). | 7 | //! as EBML by hand ([`MkvMuxer`]). |
| 8 | +//! | ||
| 9 | +//! AV1 goes into an **mp4** too, and the missing sample entry is written by hand | ||
| 10 | +//! there as well ([`Mp4Muxer::create_av1`]): the crate writes the file with an | ||
| 11 | +//! `avc1` entry and this patches that entry into the `av01` + `av1C` pair the | ||
| 12 | +//! spec asks for, which is the only box in a whole mp4 the crate cannot spell. | ||
| 13 | +//! Both containers carry the timeline's AAC, so no format here writes a picture | ||
| 14 | +//! whose sound was silently left behind. | ||
| 8 | 15 | ||
| 9 | -use std::fs::File; | 16 | +use std::fs::{File, OpenOptions}; |
| 10 | -use std::io::{BufWriter, Seek, SeekFrom, Write}; | 17 | +use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; |
| 11 | -use std::path::Path; | 18 | +use std::path::{Path, PathBuf}; |
| 12 | 19 | ||
| 13 | use mp4::{ | 20 | use mp4::{ |
| 14 | AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config, | 21 | AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config, |
| @@ -41,20 +48,32 @@ pub struct VideoParams<'a> { | |||
| 41 | pub pps: &'a [u8], | 48 | pub pps: &'a [u8], |
| 42 | } | 49 | } |
| 43 | 50 | ||
| 44 | -/// Read straight off the source file's `esds`: export copies AAC packets, it | 51 | +/// What the audio track declares: read straight off the source file's `esds` |
| 45 | -/// never re-encodes, so the decoder config is passed through unchanged. | 52 | +/// where the export copies packets, and off this project's own encoder where it |
| 53 | +/// re-encodes ([`crate::export`] decides which). `sample_rate` says the same | ||
| 54 | +/// thing `freq_index` does and is carried beside it because Matroska states the | ||
| 55 | +/// rate as a number rather than as an index into the AAC table. | ||
| 46 | pub struct AudioParams { | 56 | pub struct AudioParams { |
| 47 | pub freq_index: u8, | 57 | pub freq_index: u8, |
| 48 | pub chan_conf: u8, | 58 | pub chan_conf: u8, |
| 59 | + pub sample_rate: u32, | ||
| 49 | } | 60 | } |
| 50 | 61 | ||
| 51 | -/// Writes one H.264 track plus an optional AAC track. mp4 0.14 ignores | 62 | +/// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores |
| 52 | /// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so | 63 | /// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so |
| 53 | /// every sample handed over must carry an exact duration or the tracks drift. | 64 | /// every sample handed over must carry an exact duration or the tracks drift. |
| 54 | pub struct Mp4Muxer { | 65 | pub struct Mp4Muxer { |
| 55 | writer: Mp4Writer<BufWriter<File>>, | 66 | writer: Mp4Writer<BufWriter<File>>, |
| 56 | frame_duration: u32, | 67 | frame_duration: u32, |
| 57 | has_audio: bool, | 68 | has_audio: bool, |
| 69 | + /// The sample entry an AV1 or HEVC file's is patched into at | ||
| 70 | + /// [`finish`](Mp4Muxer::finish) -- entry type, configuration box type and | ||
| 71 | + /// its payload (`av01`/`av1C`, `hvc1`/`hvcC`). `None` for H.264, which the | ||
| 72 | + /// crate spells itself. See [`create_av1`](Mp4Muxer::create_av1). | ||
| 73 | + entry: Option<([u8; 4], [u8; 4], Vec<u8>)>, | ||
| 74 | + /// Where the file is, for that patch: the writer owns the handle it wrote | ||
| 75 | + /// through and the patch reopens the finished file. | ||
| 76 | + path: PathBuf, | ||
| 58 | } | 77 | } |
| 59 | 78 | ||
| 60 | const VIDEO_TRACK: u32 = 1; | 79 | const VIDEO_TRACK: u32 = 1; |
| @@ -65,6 +84,91 @@ impl Mp4Muxer { | |||
| 65 | path: &Path, | 84 | path: &Path, |
| 66 | video: &VideoParams, | 85 | video: &VideoParams, |
| 67 | audio: Option<&AudioParams>, | 86 | audio: Option<&AudioParams>, |
| 87 | + ) -> crate::Result<Self> { | ||
| 88 | + Self::open(path, video, audio, None) | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + /// The same file with an AV1 track in it. `mp4 0.14` writes no `av01` sample | ||
| 92 | + /// entry -- it has no AV1 anything -- so the file is written with an `avc1` | ||
| 93 | + /// entry of placeholder parameter sets and that one entry is rewritten at | ||
| 94 | + /// [`finish`](Mp4Muxer::finish) into the `av01` + `av1C` pair AV1-ISOBMFF | ||
| 95 | + /// §2.2 asks for. Everything else in an mp4 is codec-blind (the sample | ||
| 96 | + /// tables, the audio track, the movie header), so the entry is the only box | ||
| 97 | + /// this has to spell by hand -- and the `moov` it lives in is written *after* | ||
| 98 | + /// `mdat`, so growing it moves no sample and invalidates no chunk offset. | ||
| 99 | + /// | ||
| 100 | + /// The record's layout is the one OxideAV's `oxideav-mp4` writes | ||
| 101 | + /// (`src/sample_entries.rs`, MIT): a `VisualSampleEntry` header verbatim, | ||
| 102 | + /// then `av1C` -- the very four bytes and sequence header OBU [`MkvMuxer`] | ||
| 103 | + /// puts in `CodecPrivate`, which is what makes the two containers' AV1 one | ||
| 104 | + /// stream written twice rather than two. | ||
| 105 | + /// | ||
| 106 | + /// ponytail: the ceiling is that one entry. A second video track, or an AV1 | ||
| 107 | + /// track beside an H.264 one, would need the walk in [`patch_av01`] to be | ||
| 108 | + /// told *which* track it is patching; the upgrade path is passing the track | ||
| 109 | + /// id it already knows down that walk. | ||
| 110 | + pub fn create_av1( | ||
| 111 | + path: &Path, | ||
| 112 | + video: &Av1Params, | ||
| 113 | + audio: Option<&AudioParams>, | ||
| 114 | + ) -> crate::Result<Self> { | ||
| 115 | + if video.config.is_empty() { | ||
| 116 | + return Err("no AV1 sequence header for the track's av1C record".into()); | ||
| 117 | + } | ||
| 118 | + let mut av1c = AV1C_HEAD.to_vec(); | ||
| 119 | + av1c.extend_from_slice(video.config); | ||
| 120 | + Self::open( | ||
| 121 | + path, | ||
| 122 | + &VideoParams { | ||
| 123 | + width: video.width, | ||
| 124 | + height: video.height, | ||
| 125 | + frame_rate: video.frame_rate, | ||
| 126 | + // Never read by anything: the entry that holds them is replaced | ||
| 127 | + // whole at `finish`. Four bytes because `AvcCBox::new` indexes | ||
| 128 | + // `sps[1..=3]` for the profile it will never be asked for. | ||
| 129 | + sps: &[0x67, 0x42, 0x00, 0x1E], | ||
| 130 | + pps: &[0x68, 0xCE, 0x3C, 0x80], | ||
| 131 | + }, | ||
| 132 | + audio, | ||
| 133 | + Some((*b"av01", *b"av1C", av1c)), | ||
| 134 | + ) | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + /// ...and the same trick for HEVC, which `mp4 0.14` cannot spell either: | ||
| 138 | + /// the file is written with an `avc1` entry and that entry is rewritten at | ||
| 139 | + /// [`finish`](Mp4Muxer::finish) into the `hvc1` + `hvcC` pair ISO/IEC | ||
| 140 | + /// 14496-15 §8.4.1 asks for -- the record being the very bytes the Matroska | ||
| 141 | + /// file puts in `CodecPrivate`, so the two containers carry one stream. | ||
| 142 | + /// `hvc1` rather than `hev1`: the samples this writes carry no parameter | ||
| 143 | + /// sets (they are dropped into `hvcC`), which is exactly what the `hvc1` | ||
| 144 | + /// name promises a reader. | ||
| 145 | + pub fn create_hevc( | ||
| 146 | + path: &Path, | ||
| 147 | + video: &HevcParams, | ||
| 148 | + audio: Option<&AudioParams>, | ||
| 149 | + ) -> crate::Result<Self> { | ||
| 150 | + if video.hvcc.is_empty() { | ||
| 151 | + return Err("no hvcC record for the track's sample entry".into()); | ||
| 152 | + } | ||
| 153 | + Self::open( | ||
| 154 | + path, | ||
| 155 | + &VideoParams { | ||
| 156 | + width: video.width, | ||
| 157 | + height: video.height, | ||
| 158 | + frame_rate: video.frame_rate, | ||
| 159 | + sps: &[0x67, 0x42, 0x00, 0x1E], | ||
| 160 | + pps: &[0x68, 0xCE, 0x3C, 0x80], | ||
| 161 | + }, | ||
| 162 | + audio, | ||
| 163 | + Some((*b"hvc1", *b"hvcC", video.hvcc.to_vec())), | ||
| 164 | + ) | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + fn open( | ||
| 168 | + path: &Path, | ||
| 169 | + video: &VideoParams, | ||
| 170 | + audio: Option<&AudioParams>, | ||
| 171 | + entry: Option<([u8; 4], [u8; 4], Vec<u8>)>, | ||
| 68 | ) -> crate::Result<Self> { | 172 | ) -> crate::Result<Self> { |
| 69 | if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { | 173 | if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { |
| 70 | return Err(format!("bad frame rate {}", video.frame_rate).into()); | 174 | return Err(format!("bad frame rate {}", video.frame_rate).into()); |
| @@ -88,10 +192,15 @@ impl Mp4Muxer { | |||
| 88 | &Mp4Config { | 192 | &Mp4Config { |
| 89 | major_brand: FourCC::from(*b"isom"), | 193 | major_brand: FourCC::from(*b"isom"), |
| 90 | minor_version: 512, | 194 | minor_version: 512, |
| 195 | + // The codec's own brand among them, so a reader that picks a | ||
| 196 | + // parser off `ftyp` is told which of the two this is. | ||
| 91 | compatible_brands: vec![ | 197 | compatible_brands: vec![ |
| 92 | FourCC::from(*b"isom"), | 198 | FourCC::from(*b"isom"), |
| 93 | FourCC::from(*b"iso2"), | 199 | FourCC::from(*b"iso2"), |
| 94 | - FourCC::from(*b"avc1"), | 200 | + FourCC::from(match &entry { |
| 201 | + Some((kind, ..)) => *kind, | ||
| 202 | + None => *b"avc1", | ||
| 203 | + }), | ||
| 95 | FourCC::from(*b"mp41"), | 204 | FourCC::from(*b"mp41"), |
| 96 | ], | 205 | ], |
| 97 | // The video track's own, deliberately: `mp4` converts every | 206 | // The video track's own, deliberately: `mp4` converts every |
| @@ -116,6 +225,9 @@ impl Mp4Muxer { | |||
| 116 | })?; | 225 | })?; |
| 117 | if let Some(audio) = audio { | 226 | if let Some(audio) = audio { |
| 118 | let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; | 227 | let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; |
| 228 | + // The index's own rate, not `audio.sample_rate`: this is the clock | ||
| 229 | + // an `stts` counts in and the `esds` states the index, so the two | ||
| 230 | + // must not be able to disagree. | ||
| 119 | let sample_rate = freq_index.freq(); | 231 | let sample_rate = freq_index.freq(); |
| 120 | writer.add_track(&TrackConfig { | 232 | writer.add_track(&TrackConfig { |
| 121 | track_type: TrackType::Audio, | 233 | track_type: TrackType::Audio, |
| @@ -134,6 +246,8 @@ impl Mp4Muxer { | |||
| 134 | writer, | 246 | writer, |
| 135 | frame_duration, | 247 | frame_duration, |
| 136 | has_audio: audio.is_some(), | 248 | has_audio: audio.is_some(), |
| 249 | + entry, | ||
| 250 | + path: path.to_path_buf(), | ||
| 137 | }) | 251 | }) |
| 138 | } | 252 | } |
| 139 | 253 | ||
| @@ -154,6 +268,29 @@ impl Mp4Muxer { | |||
| 154 | Ok(()) | 268 | Ok(()) |
| 155 | } | 269 | } |
| 156 | 270 | ||
| 271 | + /// One coded picture already framed the way its sample carries it: an AV1 | ||
| 272 | + /// temporal unit is the low-overhead OBU stream the encoder handed over | ||
| 273 | + /// (nothing to reframe, exactly as a Matroska block holds it), and an HEVC | ||
| 274 | + /// sample is the length-prefixed NALs [`annex_b_to_hvcc`] made. `key` is the | ||
| 275 | + /// encoder's own word for a unit a decoder may start on -- an mp4 says it in | ||
| 276 | + /// `stss` where Matroska says it in the block flags. | ||
| 277 | + pub fn write_coded_sample(&mut self, obus: &[u8], key: bool) -> crate::Result<()> { | ||
| 278 | + if obus.is_empty() { | ||
| 279 | + return Err("an empty coded picture".into()); | ||
| 280 | + } | ||
| 281 | + self.writer.write_sample( | ||
| 282 | + VIDEO_TRACK, | ||
| 283 | + &Mp4Sample { | ||
| 284 | + start_time: 0, | ||
| 285 | + duration: self.frame_duration, | ||
| 286 | + rendering_offset: 0, | ||
| 287 | + is_sync: key, | ||
| 288 | + bytes: Bytes::copy_from_slice(obus), | ||
| 289 | + }, | ||
| 290 | + )?; | ||
| 291 | + Ok(()) | ||
| 292 | + } | ||
| 293 | + | ||
| 157 | /// One raw AAC packet (no ADTS header), copied verbatim from the source -- | 294 | /// One raw AAC packet (no ADTS header), copied verbatim from the source -- |
| 158 | /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC | 295 | /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC |
| 159 | /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not. | 296 | /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not. |
| @@ -178,10 +315,138 @@ impl Mp4Muxer { | |||
| 178 | 315 | ||
| 179 | pub fn finish(mut self) -> crate::Result<()> { | 316 | pub fn finish(mut self) -> crate::Result<()> { |
| 180 | self.writer.write_end()?; | 317 | self.writer.write_end()?; |
| 181 | - Ok(()) | 318 | + let Self { |
| 319 | + writer, | ||
| 320 | + entry, | ||
| 321 | + path, | ||
| 322 | + .. | ||
| 323 | + } = self; | ||
| 324 | + // Not a `drop`: the buffered tail of `moov` has to be on disk before the | ||
| 325 | + // patch below reads it back, and a `BufWriter` swallows the error of | ||
| 326 | + // flushing it on drop. | ||
| 327 | + writer.into_writer().flush()?; | ||
| 328 | + match entry { | ||
| 329 | + Some((kind, config_kind, config)) => patch_entry(&path, &kind, &config_kind, &config), | ||
| 330 | + None => Ok(()), | ||
| 331 | + } | ||
| 182 | } | 332 | } |
| 183 | } | 333 | } |
| 184 | 334 | ||
| 335 | +/// Rewrites the finished file's one video sample entry from the `avc1` the crate | ||
| 336 | +/// wrote into the `av01` + `av1C` an AV1 track declares -- or the `hvc1` + | ||
| 337 | +/// `hvcC` an HEVC one does. Called once, on a complete file, and only for a file | ||
| 338 | +/// [`Mp4Muxer::create_av1`] or [`Mp4Muxer::create_hevc`] opened. | ||
| 339 | +/// | ||
| 340 | +/// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only | ||
| 341 | +/// ever rewrites the tail of the file: no sample moves and no chunk offset in | ||
| 342 | +/// `co64` changes. The box tree is rebuilt rather than patched in place, which | ||
| 343 | +/// is what keeps every ancestor's size right by construction. | ||
| 344 | +fn patch_entry( | ||
| 345 | + path: &Path, | ||
| 346 | + kind: &[u8; 4], | ||
| 347 | + config_kind: &[u8; 4], | ||
| 348 | + config: &[u8], | ||
| 349 | +) -> crate::Result<()> { | ||
| 350 | + let mut file = OpenOptions::new().read(true).write(true).open(path)?; | ||
| 351 | + let end = file.metadata()?.len(); | ||
| 352 | + let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?; | ||
| 353 | + let patched = swap_entry(&payload, 0, kind, config_kind, config) | ||
| 354 | + .ok_or("no avc1 sample entry to rewrite")?; | ||
| 355 | + let mut out = Vec::with_capacity(patched.len() + 8); | ||
| 356 | + push_box(&mut out, b"moov", &patched); | ||
| 357 | + file.seek(SeekFrom::Start(at))?; | ||
| 358 | + file.write_all(&out)?; | ||
| 359 | + file.set_len(at + out.len() as u64)?; | ||
| 360 | + file.flush()?; | ||
| 361 | + Ok(()) | ||
| 362 | +} | ||
| 363 | + | ||
| 364 | +/// Offset and payload of the first top-level box of type `want`. | ||
| 365 | +fn top_level(file: &mut File, end: u64, want: &[u8; 4]) -> crate::Result<Option<(u64, Vec<u8>)>> { | ||
| 366 | + let mut at = 0u64; | ||
| 367 | + while at + 8 <= end { | ||
| 368 | + let mut header = [0u8; 8]; | ||
| 369 | + file.seek(SeekFrom::Start(at))?; | ||
| 370 | + file.read_exact(&mut header)?; | ||
| 371 | + let (size, head_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) { | ||
| 372 | + 0 => (end - at, 8), | ||
| 373 | + 1 => { | ||
| 374 | + let mut large = [0u8; 8]; | ||
| 375 | + file.read_exact(&mut large)?; | ||
| 376 | + (u64::from_be_bytes(large), 16) | ||
| 377 | + } | ||
| 378 | + size => (u64::from(size), 8), | ||
| 379 | + }; | ||
| 380 | + if size < head_len || at + size > end { | ||
| 381 | + return Err("truncated box in the file's top level".into()); | ||
| 382 | + } | ||
| 383 | + if &header[4..8] == want { | ||
| 384 | + let mut payload = vec![0u8; (size - head_len) as usize]; | ||
| 385 | + file.read_exact(&mut payload)?; | ||
| 386 | + return Ok(Some((at, payload))); | ||
| 387 | + } | ||
| 388 | + at += size; | ||
| 389 | + } | ||
| 390 | + Ok(None) | ||
| 391 | +} | ||
| 392 | + | ||
| 393 | +/// `moov` down to the sample descriptions, which is where the entry lives. | ||
| 394 | +const STSD_PATH: [&[u8; 4]; 5] = [b"trak", b"mdia", b"minf", b"stbl", b"stsd"]; | ||
| 395 | + | ||
| 396 | +/// The box at `depth` of [`STSD_PATH`], rebuilt with its `avc1` entry replaced. | ||
| 397 | +/// `None` where this branch holds no such entry -- an audio `trak` is walked | ||
| 398 | +/// into and comes back untouched, which is how the *video* track is found | ||
| 399 | +/// without being told which id it has. | ||
| 400 | +fn swap_entry( | ||
| 401 | + payload: &[u8], | ||
| 402 | + depth: usize, | ||
| 403 | + want: &[u8; 4], | ||
| 404 | + config_kind: &[u8; 4], | ||
| 405 | + config: &[u8], | ||
| 406 | +) -> Option<Vec<u8>> { | ||
| 407 | + if depth == STSD_PATH.len() { | ||
| 408 | + // stsd is a FullBox (4) plus entry_count (4), then the sample entries. | ||
| 409 | + let mut out = payload.get(..8)?.to_vec(); | ||
| 410 | + let (kind, entry) = crate::demux::boxes(payload.get(8..)?).next()?; | ||
| 411 | + if kind != b"avc1" { | ||
| 412 | + return None; | ||
| 413 | + } | ||
| 414 | + // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all) | ||
| 415 | + // before its codec box, and `av01` and `hvc1` carry exactly the same | ||
| 416 | + // ones -- so the header is kept and only the configuration box is | ||
| 417 | + // swapped. | ||
| 418 | + let mut swapped = entry.get(..78)?.to_vec(); | ||
| 419 | + push_box(&mut swapped, config_kind, config); | ||
| 420 | + push_box(&mut out, want, &swapped); | ||
| 421 | + return Some(out); | ||
| 422 | + } | ||
| 423 | + let mut out = Vec::with_capacity(payload.len()); | ||
| 424 | + let mut done = false; | ||
| 425 | + for (kind, child) in crate::demux::boxes(payload) { | ||
| 426 | + let patched = match !done && kind == STSD_PATH[depth] { | ||
| 427 | + true => swap_entry(child, depth + 1, want, config_kind, config), | ||
| 428 | + false => None, | ||
| 429 | + }; | ||
| 430 | + match patched { | ||
| 431 | + Some(child) => { | ||
| 432 | + push_box(&mut out, kind, &child); | ||
| 433 | + done = true; | ||
| 434 | + } | ||
| 435 | + None => push_box(&mut out, kind, child), | ||
| 436 | + } | ||
| 437 | + } | ||
| 438 | + done.then_some(out) | ||
| 439 | +} | ||
| 440 | + | ||
| 441 | +/// One mp4 box: 32-bit size, four-character type, payload. Every box inside a | ||
| 442 | +/// `moov` fits that form -- the 64-bit one exists for `mdat`, which this never | ||
| 443 | +/// rewrites. | ||
| 444 | +fn push_box(out: &mut Vec<u8>, kind: &[u8; 4], payload: &[u8]) { | ||
| 445 | + out.extend_from_slice(&(payload.len() as u32 + 8).to_be_bytes()); | ||
| 446 | + out.extend_from_slice(kind); | ||
| 447 | + out.extend_from_slice(payload); | ||
| 448 | +} | ||
| 449 | + | ||
| 185 | // Matroska element ids, written with the leading length marker they carry in the | 450 | // Matroska element ids, written with the leading length marker they carry in the |
| 186 | // file -- the same spelling `demux` reads them back with. | 451 | // file -- the same spelling `demux` reads them back with. |
| 187 | const EBML: u32 = 0x1A45_DFA3; | 452 | const EBML: u32 = 0x1A45_DFA3; |
| @@ -210,6 +475,10 @@ const DEFAULT_DURATION: u32 = 0x23E383; | |||
| 210 | const VIDEO: u32 = 0xE0; | 475 | const VIDEO: u32 = 0xE0; |
| 211 | const PIXEL_WIDTH: u32 = 0xB0; | 476 | const PIXEL_WIDTH: u32 = 0xB0; |
| 212 | const PIXEL_HEIGHT: u32 = 0xBA; | 477 | const PIXEL_HEIGHT: u32 = 0xBA; |
| 478 | +const AUDIO: u32 = 0xE1; | ||
| 479 | +const SAMPLING_FREQUENCY: u32 = 0xB5; | ||
| 480 | +const CHANNELS: u32 = 0x9F; | ||
| 481 | +const CODEC_DELAY: u32 = 0x56AA; | ||
| 213 | const CLUSTER: u32 = 0x1F43_B675; | 482 | const CLUSTER: u32 = 0x1F43_B675; |
| 214 | const CLUSTER_TIMESTAMP: u32 = 0xE7; | 483 | const CLUSTER_TIMESTAMP: u32 = 0xE7; |
| 215 | const SIMPLE_BLOCK: u32 = 0xA3; | 484 | const SIMPLE_BLOCK: u32 = 0xA3; |
| @@ -251,11 +520,29 @@ pub struct Av1Params<'a> { | |||
| 251 | pub config: &'a [u8], | 520 | pub config: &'a [u8], |
| 252 | } | 521 | } |
| 253 | 522 | ||
| 254 | -/// Writes one AV1 video track as Matroska (`.mkv`). Picture only: this project | 523 | +/// What an HEVC track declares in either container: the `hvcC` record |
| 255 | -/// has no encoder for any sound Matroska carries, and copying the timeline's AAC | 524 | +/// [`hvcc_record`] built out of the encoder's own VPS/SPS/PPS. The dimensions |
| 256 | -/// in would write a track its own reader refuses (`audio::AudioSession::open` | 525 | +/// are the *displayed* ones -- the coded picture is padded up to the 16-sample |
| 257 | -/// leaves a Matroska file silent) -- so the sound is named as left out by the | 526 | +/// CTB grid and the SPS crops it back with a conformance window, which is the |
| 258 | -/// front-end rather than written unplayable. | 527 | +/// size a decoder outputs and therefore the size the container states. |
| 528 | +pub struct HevcParams<'a> { | ||
| 529 | + pub width: u32, | ||
| 530 | + pub height: u32, | ||
| 531 | + pub frame_rate: f64, | ||
| 532 | + pub hvcc: &'a [u8], | ||
| 533 | +} | ||
| 534 | + | ||
| 535 | +/// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC | ||
| 536 | +/// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the | ||
| 537 | +/// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what | ||
| 538 | +/// symphonia's `mkv` reader -- this project's own way back in -- configures its | ||
| 539 | +/// decoder from. An AV1 export used to be picture alone; a video file whose | ||
| 540 | +/// sound was silently left behind is exactly the failure nobody notices until | ||
| 541 | +/// the file has gone somewhere. | ||
| 542 | +/// | ||
| 543 | +/// The sound is *interleaved*: each packet is written into the cluster of the | ||
| 544 | +/// picture it plays under, so a player has both by the time it needs them rather | ||
| 545 | +/// than a file it must read to the end of to hear. | ||
| 259 | /// | 546 | /// |
| 260 | /// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size | 547 | /// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size |
| 261 | /// and the duration -- so a killed process leaves an unfinished file rather than | 548 | /// and the duration -- so a killed process leaves an unfinished file rather than |
| @@ -272,22 +559,96 @@ pub struct MkvMuxer { | |||
| 272 | cluster: Vec<u8>, | 559 | cluster: Vec<u8>, |
| 273 | cluster_ts: i64, | 560 | cluster_ts: i64, |
| 274 | frames: u64, | 561 | frames: u64, |
| 562 | + /// The AAC track, if the timeline has sound, and how far it has been | ||
| 563 | + /// written. | ||
| 564 | + audio: Option<MkvAudio>, | ||
| 565 | +} | ||
| 566 | + | ||
| 567 | +/// The sound waiting to be interleaved into the clusters. | ||
| 568 | +struct MkvAudio { | ||
| 569 | + packets: Vec<crate::AacPacket>, | ||
| 570 | + /// Packets already written. | ||
| 571 | + next: usize, | ||
| 572 | + /// Frames already written, which is what the next packet's timestamp is | ||
| 573 | + /// counted from: every AAC-LC packet says its own length and they are not | ||
| 574 | + /// assumed equal here. | ||
| 575 | + samples: u64, | ||
| 576 | + sample_rate: u32, | ||
| 275 | } | 577 | } |
| 276 | 578 | ||
| 277 | impl MkvMuxer { | 579 | impl MkvMuxer { |
| 278 | - pub fn create(path: &Path, video: &Av1Params) -> crate::Result<Self> { | 580 | + /// `audio` is the whole track at once -- the export has it before it has a |
| 279 | - if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { | 581 | + /// single coded picture, and interleaving needs to look ahead of the frame |
| 280 | - return Err(format!("bad frame rate {}", video.frame_rate).into()); | 582 | + /// being written. |
| 583 | + /// | ||
| 584 | + /// ponytail: that is the copy path's own ceiling reappearing (the track sits | ||
| 585 | + /// in memory, ~500 MB an hour); the upgrade path is the same streaming | ||
| 586 | + /// `copy_segments` `export::copy_audio` names. | ||
| 587 | + pub fn create( | ||
| 588 | + path: &Path, | ||
| 589 | + video: &Av1Params, | ||
| 590 | + audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | ||
| 591 | + ) -> crate::Result<Self> { | ||
| 592 | + if video.config.is_empty() { | ||
| 593 | + return Err("no AV1 sequence header for the track's CodecPrivate".into()); | ||
| 281 | } | 594 | } |
| 282 | - if video.width == 0 || video.height == 0 { | 595 | + let mut av1c = AV1C_HEAD.to_vec(); |
| 283 | - return Err(format!("bad dimensions {}x{}", video.width, video.height).into()); | 596 | + av1c.extend_from_slice(video.config); |
| 597 | + Self::open( | ||
| 598 | + path, | ||
| 599 | + video.width, | ||
| 600 | + video.height, | ||
| 601 | + video.frame_rate, | ||
| 602 | + b"V_AV1", | ||
| 603 | + &av1c, | ||
| 604 | + audio, | ||
| 605 | + ) | ||
| 606 | + } | ||
| 607 | + | ||
| 608 | + /// The same file with an HEVC track in it: `V_MPEGH/ISO/HEVC`, whose | ||
| 609 | + /// `CodecPrivate` is the very `hvcC` record an mp4 puts in its sample entry | ||
| 610 | + /// ([`hvcc_record`]) -- and whose blocks are therefore length-prefixed NALs | ||
| 611 | + /// like an mp4 sample's, not Annex B. That is what this engine's own reader | ||
| 612 | + /// expects back (`demux`'s Matroska branch parses `CodecPrivate` as `hvcC` | ||
| 613 | + /// and reframes the blocks by the length it states), and what every other | ||
| 614 | + /// Matroska reader expects too. | ||
| 615 | + pub fn create_hevc( | ||
| 616 | + path: &Path, | ||
| 617 | + video: &HevcParams, | ||
| 618 | + audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | ||
| 619 | + ) -> crate::Result<Self> { | ||
| 620 | + if video.hvcc.is_empty() { | ||
| 621 | + return Err("no hvcC record for the track's CodecPrivate".into()); | ||
| 284 | } | 622 | } |
| 285 | - let frame_ns = (1e9 / video.frame_rate).round() as u64; | 623 | + Self::open( |
| 286 | - if frame_ns == 0 { | 624 | + path, |
| 287 | - return Err(format!("frame rate {} is too fast to time", video.frame_rate).into()); | 625 | + video.width, |
| 626 | + video.height, | ||
| 627 | + video.frame_rate, | ||
| 628 | + b"V_MPEGH/ISO/HEVC", | ||
| 629 | + video.hvcc, | ||
| 630 | + audio, | ||
| 631 | + ) | ||
| 632 | + } | ||
| 633 | + | ||
| 634 | + fn open( | ||
| 635 | + path: &Path, | ||
| 636 | + width: u32, | ||
| 637 | + height: u32, | ||
| 638 | + frame_rate: f64, | ||
| 639 | + codec_id: &[u8], | ||
| 640 | + codec_private: &[u8], | ||
| 641 | + audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | ||
| 642 | + ) -> crate::Result<Self> { | ||
| 643 | + if !frame_rate.is_finite() || frame_rate <= 0.0 { | ||
| 644 | + return Err(format!("bad frame rate {frame_rate}").into()); | ||
| 288 | } | 645 | } |
| 289 | - if video.config.is_empty() { | 646 | + if width == 0 || height == 0 { |
| 290 | - return Err("no AV1 sequence header for the track's CodecPrivate".into()); | 647 | + return Err(format!("bad dimensions {width}x{height}").into()); |
| 648 | + } | ||
| 649 | + let frame_ns = (1e9 / frame_rate).round() as u64; | ||
| 650 | + if frame_ns == 0 { | ||
| 651 | + return Err(format!("frame rate {frame_rate} is too fast to time").into()); | ||
| 291 | } | 652 | } |
| 292 | 653 | ||
| 293 | let mut head = Vec::new(); | 654 | let mut head = Vec::new(); |
| @@ -324,17 +685,18 @@ impl MkvMuxer { | |||
| 324 | uint(&mut entry, TRACK_UID, 1); | 685 | uint(&mut entry, TRACK_UID, 1); |
| 325 | uint(&mut entry, TRACK_TYPE, 1); // video | 686 | uint(&mut entry, TRACK_TYPE, 1); // video |
| 326 | uint(&mut entry, FLAG_LACING, 0); | 687 | uint(&mut entry, FLAG_LACING, 0); |
| 327 | - elem(&mut entry, CODEC_ID, b"V_AV1"); | 688 | + elem(&mut entry, CODEC_ID, codec_id); |
| 328 | - let mut av1c = AV1C_HEAD.to_vec(); | 689 | + elem(&mut entry, CODEC_PRIVATE, codec_private); |
| 329 | - av1c.extend_from_slice(video.config); | ||
| 330 | - elem(&mut entry, CODEC_PRIVATE, &av1c); | ||
| 331 | uint(&mut entry, DEFAULT_DURATION, frame_ns); | 690 | uint(&mut entry, DEFAULT_DURATION, frame_ns); |
| 332 | let mut dims = Vec::new(); | 691 | let mut dims = Vec::new(); |
| 333 | - uint(&mut dims, PIXEL_WIDTH, u64::from(video.width)); | 692 | + uint(&mut dims, PIXEL_WIDTH, u64::from(width)); |
| 334 | - uint(&mut dims, PIXEL_HEIGHT, u64::from(video.height)); | 693 | + uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); |
| 335 | elem(&mut entry, VIDEO, &dims); | 694 | elem(&mut entry, VIDEO, &dims); |
| 336 | let mut tracks = Vec::new(); | 695 | let mut tracks = Vec::new(); |
| 337 | elem(&mut tracks, TRACK_ENTRY, &entry); | 696 | elem(&mut tracks, TRACK_ENTRY, &entry); |
| 697 | + if let Some((audio, _)) = &audio { | ||
| 698 | + elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); | ||
| 699 | + } | ||
| 338 | elem(&mut head, TRACKS, &tracks); | 700 | elem(&mut head, TRACKS, &tracks); |
| 339 | 701 | ||
| 340 | let mut file = File::create(path)?; | 702 | let mut file = File::create(path)?; |
| @@ -347,6 +709,12 @@ impl MkvMuxer { | |||
| 347 | cluster: Vec::new(), | 709 | cluster: Vec::new(), |
| 348 | cluster_ts: 0, | 710 | cluster_ts: 0, |
| 349 | frames: 0, | 711 | frames: 0, |
| 712 | + audio: audio.map(|(params, packets)| MkvAudio { | ||
| 713 | + packets, | ||
| 714 | + next: 0, | ||
| 715 | + samples: 0, | ||
| 716 | + sample_rate: params.sample_rate.max(1), | ||
| 717 | + }), | ||
| 350 | }) | 718 | }) |
| 351 | } | 719 | } |
| 352 | 720 | ||
| @@ -373,14 +741,58 @@ impl MkvMuxer { | |||
| 373 | self.cluster_ts = ts; | 741 | self.cluster_ts = ts; |
| 374 | uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | 742 | uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); |
| 375 | } | 743 | } |
| 376 | - let mut block = Vec::with_capacity(obus.len() + 4); | 744 | + // The sound this picture plays under goes in first, into the cluster the |
| 377 | - block.push(0x81); // track number 1, as a one-byte EBML integer | 745 | + // picture opened: a player reads the two together. |
| 746 | + self.drain_audio(ts)?; | ||
| 747 | + self.block(1, ts, key, obus); | ||
| 748 | + self.frames += 1; | ||
| 749 | + Ok(()) | ||
| 750 | + } | ||
| 751 | + | ||
| 752 | + /// Every audio packet whose timestamp has been reached, into the current | ||
| 753 | + /// cluster. `i64::MAX` at [`finish`](MkvMuxer::finish) drains what is left -- | ||
| 754 | + /// the sound of a timeline can outlast its last picture by a packet. | ||
| 755 | + fn drain_audio(&mut self, until: i64) -> crate::Result<()> { | ||
| 756 | + loop { | ||
| 757 | + let Some(audio) = &mut self.audio else { | ||
| 758 | + return Ok(()); | ||
| 759 | + }; | ||
| 760 | + let Some(packet) = audio.packets.get_mut(audio.next) else { | ||
| 761 | + return Ok(()); | ||
| 762 | + }; | ||
| 763 | + // The packet's own start, in whole milliseconds: every AAC-LC packet | ||
| 764 | + // states its length, so a track of them is counted rather than | ||
| 765 | + // assumed to be 1024 frames each. | ||
| 766 | + let rate = i64::from(audio.sample_rate); | ||
| 767 | + let ts = (audio.samples as i64 * 1000 + rate / 2) / rate; | ||
| 768 | + if ts > until { | ||
| 769 | + return Ok(()); | ||
| 770 | + } | ||
| 771 | + // Taken, not copied: the packet is written once and the track can be | ||
| 772 | + // hundreds of megabytes. | ||
| 773 | + let bytes = std::mem::take(&mut packet.bytes); | ||
| 774 | + audio.samples += u64::from(packet.samples); | ||
| 775 | + audio.next += 1; | ||
| 776 | + // A cluster of its own where the sound has run past what a 16-bit | ||
| 777 | + // relative timestamp reaches, which only the tail drain can do. | ||
| 778 | + if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { | ||
| 779 | + self.flush()?; | ||
| 780 | + self.cluster_ts = ts; | ||
| 781 | + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | ||
| 782 | + } | ||
| 783 | + self.block(2, ts, true, &bytes); | ||
| 784 | + } | ||
| 785 | + } | ||
| 786 | + | ||
| 787 | + /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC | ||
| 788 | + /// packet is a keyframe; a picture is one when the encoder said so. | ||
| 789 | + fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { | ||
| 790 | + let mut block = Vec::with_capacity(payload.len() + 4); | ||
| 791 | + block.push(0x80 | track); // the track number as a one-byte EBML integer | ||
| 378 | block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); | 792 | block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); |
| 379 | block.push(if key { 0x80 } else { 0 }); | 793 | block.push(if key { 0x80 } else { 0 }); |
| 380 | - block.extend_from_slice(obus); | 794 | + block.extend_from_slice(payload); |
| 381 | elem(&mut self.cluster, SIMPLE_BLOCK, &block); | 795 | elem(&mut self.cluster, SIMPLE_BLOCK, &block); |
| 382 | - self.frames += 1; | ||
| 383 | - Ok(()) | ||
| 384 | } | 796 | } |
| 385 | 797 | ||
| 386 | fn flush(&mut self) -> crate::Result<()> { | 798 | fn flush(&mut self) -> crate::Result<()> { |
| @@ -399,6 +811,9 @@ impl MkvMuxer { | |||
| 399 | /// Closes the last cluster and patches the two fields that could not be | 811 | /// Closes the last cluster and patches the two fields that could not be |
| 400 | /// known while writing: the segment's size and the presentation duration. | 812 | /// known while writing: the segment's size and the presentation duration. |
| 401 | pub fn finish(mut self) -> crate::Result<()> { | 813 | pub fn finish(mut self) -> crate::Result<()> { |
| 814 | + // Whatever sound outlasts the last picture, before the last cluster is | ||
| 815 | + // closed: a track cut short here is a file that goes silent at the end. | ||
| 816 | + self.drain_audio(i64::MAX)?; | ||
| 402 | self.flush()?; | 817 | self.flush()?; |
| 403 | if self.frames == 0 { | 818 | if self.frames == 0 { |
| 404 | return Err("no frames were written to the Matroska file".into()); | 819 | return Err("no frames were written to the Matroska file".into()); |
| @@ -417,6 +832,52 @@ impl MkvMuxer { | |||
| 417 | } | 832 | } |
| 418 | } | 833 | } |
| 419 | 834 | ||
| 835 | +/// The `TrackEntry` of the AAC track: `A_AAC`, whose `CodecPrivate` is the | ||
| 836 | +/// two-byte `AudioSpecificConfig` an mp4 states inside its `esds` -- object type | ||
| 837 | +/// 2 (AAC-LC), the sample rate as its index into the AAC table, and the channel | ||
| 838 | +/// configuration. symphonia's `mkv` reader hands exactly these bytes to its AAC | ||
| 839 | +/// decoder, which is how a file written here reads back here. | ||
| 840 | +/// | ||
| 841 | +/// `CodecDelay` is one packet: the first AAC access unit of both paths that | ||
| 842 | +/// reach this -- a copy, whose head packet is the source's priming, and this | ||
| 843 | +/// project's own encoder, whose delay is one 1024-frame block -- is that delay, | ||
| 844 | +/// and an mp4 reader drops it by convention where Matroska has to be told in | ||
| 845 | +/// nanoseconds. | ||
| 846 | +fn aac_track_entry(audio: &AudioParams) -> crate::Result<Vec<u8>> { | ||
| 847 | + let rate = audio.sample_rate; | ||
| 848 | + if rate == 0 || audio.chan_conf == 0 { | ||
| 849 | + return Err(format!( | ||
| 850 | + "an AAC track at {rate} Hz with {} channels", | ||
| 851 | + audio.chan_conf | ||
| 852 | + ) | ||
| 853 | + .into()); | ||
| 854 | + } | ||
| 855 | + let mut entry = Vec::new(); | ||
| 856 | + uint(&mut entry, TRACK_NUMBER, 2); | ||
| 857 | + uint(&mut entry, TRACK_UID, 2); | ||
| 858 | + uint(&mut entry, TRACK_TYPE, 2); // audio | ||
| 859 | + uint(&mut entry, FLAG_LACING, 0); | ||
| 860 | + elem(&mut entry, CODEC_ID, b"A_AAC"); | ||
| 861 | + // 5 bits object type, 4 bits sample rate index, 4 bits channel config, and | ||
| 862 | + // three zero bits to the byte -- the whole of an AAC-LC AudioSpecificConfig. | ||
| 863 | + let asc = (2u16 << 11) | ||
| 864 | + | (u16::from(audio.freq_index & 0xF) << 7) | ||
| 865 | + | (u16::from(audio.chan_conf & 0xF) << 3); | ||
| 866 | + elem(&mut entry, CODEC_PRIVATE, &asc.to_be_bytes()); | ||
| 867 | + uint( | ||
| 868 | + &mut entry, | ||
| 869 | + CODEC_DELAY, | ||
| 870 | + u64::from(AAC_PACKET_SAMPLES) * 1_000_000_000 / u64::from(rate), | ||
| 871 | + ); | ||
| 872 | + let mut audio_elem = Vec::new(); | ||
| 873 | + put_id(&mut audio_elem, SAMPLING_FREQUENCY); | ||
| 874 | + put_size(&mut audio_elem, 8); | ||
| 875 | + audio_elem.extend_from_slice(&f64::from(rate).to_be_bytes()); | ||
| 876 | + uint(&mut audio_elem, CHANNELS, u64::from(audio.chan_conf)); | ||
| 877 | + elem(&mut entry, AUDIO, &audio_elem); | ||
| 878 | + Ok(entry) | ||
| 879 | +} | ||
| 880 | + | ||
| 420 | /// The sequence header OBU of a coded temporal unit, for the track's | 881 | /// The sequence header OBU of a coded temporal unit, for the track's |
| 421 | /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe | 882 | /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe |
| 422 | /// of a stream never may -- no decoder can start without it. | 883 | /// of a stream never may -- no decoder can start without it. |
| @@ -528,6 +989,91 @@ pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { | |||
| 528 | Some((sps, pps)) | 989 | Some((sps, pps)) |
| 529 | } | 990 | } |
| 530 | 991 | ||
| 992 | +/// The `HEVCDecoderConfigurationRecord` an HEVC track declares, built out of the | ||
| 993 | +/// parameter sets the encoder put in its first access unit -- the exact record | ||
| 994 | +/// `demux::parse_hvcc` reads back, which is what makes an export of this | ||
| 995 | +/// project's own something it can re-open. | ||
| 996 | +/// | ||
| 997 | +/// The 22 fixed bytes before the arrays: the 12-byte `profile_tier_level` is | ||
| 998 | +/// copied straight out of the SPS (its first 12 bytes after the two-byte NAL | ||
| 999 | +/// header and the four `sps_video_parameter_set_id`/`sps_max_sub_layers_minus1` | ||
| 1000 | +/// /`sps_temporal_id_nesting_flag` bits -- §7.3.2.2 puts the PTL there and the | ||
| 1001 | +/// hvcC header states the same fields in the same order), and the rest is what | ||
| 1002 | +/// this encoder is: 4:2:0, 8-bit, one temporal layer, 4-byte NAL lengths. Only | ||
| 1003 | +/// the *arrays* are read by anything here, but a record whose header lied about | ||
| 1004 | +/// the profile would be a file `ffprobe` disagrees with. | ||
| 1005 | +/// | ||
| 1006 | +/// `None` where the unit carries no VPS, SPS or PPS -- the first coded intra AU | ||
| 1007 | +/// always carries all three. | ||
| 1008 | +pub fn hvcc_record(annex_b: &[u8]) -> Option<Vec<u8>> { | ||
| 1009 | + let nals = split_annex_b(annex_b); | ||
| 1010 | + let of = |kind: u8| nals.iter().copied().find(|n| hevc_nal_type(n) == kind); | ||
| 1011 | + let (vps, sps, pps) = (of(HEVC_VPS)?, of(HEVC_SPS)?, of(HEVC_PPS)?); | ||
| 1012 | + // The SPS as a decoder reads it: the emulation-prevention bytes the encoder | ||
| 1013 | + // escaped it with are not part of the syntax, and a run of zeros in the | ||
| 1014 | + // constraint flags is exactly where one lands. | ||
| 1015 | + let rbsp = unescape(sps.get(2..)?); | ||
| 1016 | + let mut rec = vec![1u8]; // configurationVersion | ||
| 1017 | + rec.extend_from_slice(rbsp.get(1..13)?); // profile_tier_level, verbatim | ||
| 1018 | + rec.extend_from_slice(&[0xF0, 0x00]); // min_spatial_segmentation_idc = 0 | ||
| 1019 | + rec.push(0xFC); // parallelismType = 0 (unknown) | ||
| 1020 | + rec.push(0xFC | 1); // chroma_format_idc = 1 (4:2:0) | ||
| 1021 | + rec.push(0xF8); // bit_depth_luma_minus8 = 0 | ||
| 1022 | + rec.push(0xF8); // bit_depth_chroma_minus8 = 0 | ||
| 1023 | + rec.extend_from_slice(&0u16.to_be_bytes()); // avgFrameRate: unstated | ||
| 1024 | + // constantFrameRate 0, numTemporalLayers 1, temporalIdNested 1, | ||
| 1025 | + // lengthSizeMinusOne 3 -- the same 4-byte prefix `annex_b_to_hvcc` writes. | ||
| 1026 | + rec.push(0b00_001_1_11); | ||
| 1027 | + rec.push(3); // numOfArrays | ||
| 1028 | + for (kind, nal) in [(HEVC_VPS, vps), (HEVC_SPS, sps), (HEVC_PPS, pps)] { | ||
| 1029 | + rec.push(0x80 | kind); // array_completeness = 1, NAL_unit_type | ||
| 1030 | + rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus | ||
| 1031 | + rec.extend_from_slice(&(nal.len() as u16).to_be_bytes()); | ||
| 1032 | + rec.extend_from_slice(nal); | ||
| 1033 | + } | ||
| 1034 | + Some(rec) | ||
| 1035 | +} | ||
| 1036 | + | ||
| 1037 | +/// One HEVC access unit as a sample of both containers: 4-byte length prefixes, | ||
| 1038 | +/// parameter sets dropped (they are in the `hvcC`, which is what `hvc1` and a | ||
| 1039 | +/// Matroska `CodecPrivate` both promise). `None` where the unit holds no coded | ||
| 1040 | +/// slice at all. | ||
| 1041 | +pub(crate) fn annex_b_to_hvcc(annex_b: &[u8]) -> Option<Vec<u8>> { | ||
| 1042 | + let mut out = Vec::with_capacity(annex_b.len()); | ||
| 1043 | + for nal in split_annex_b(annex_b) { | ||
| 1044 | + // 32 VPS, 33 SPS, 34 PPS, 35 AUD -- and everything from 40 up is | ||
| 1045 | + // non-VCL padding no decoder needs to start. | ||
| 1046 | + if matches!(hevc_nal_type(nal), HEVC_VPS | HEVC_SPS | HEVC_PPS | 35) { | ||
| 1047 | + continue; | ||
| 1048 | + } | ||
| 1049 | + out.extend_from_slice(&(nal.len() as u32).to_be_bytes()); | ||
| 1050 | + out.extend_from_slice(nal); | ||
| 1051 | + } | ||
| 1052 | + (!out.is_empty()).then_some(out) | ||
| 1053 | +} | ||
| 1054 | + | ||
| 1055 | +/// §7.3.1.2 `nal_unit_type`, the six bits after the forbidden_zero_bit. | ||
| 1056 | +fn hevc_nal_type(nal: &[u8]) -> u8 { | ||
| 1057 | + nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F) | ||
| 1058 | +} | ||
| 1059 | + | ||
| 1060 | +const HEVC_VPS: u8 = 32; | ||
| 1061 | +const HEVC_SPS: u8 = 33; | ||
| 1062 | +const HEVC_PPS: u8 = 34; | ||
| 1063 | + | ||
| 1064 | +/// A coded NAL payload back to its RBSP: every `00 00 03` loses the `03` | ||
| 1065 | +/// (§7.3.1.1). Only ever asked of an SPS, which is short. | ||
| 1066 | +fn unescape(nal: &[u8]) -> Vec<u8> { | ||
| 1067 | + let mut out = Vec::with_capacity(nal.len()); | ||
| 1068 | + for (i, &byte) in nal.iter().enumerate() { | ||
| 1069 | + if byte == 3 && i >= 2 && nal[i - 1] == 0 && nal[i - 2] == 0 { | ||
| 1070 | + continue; | ||
| 1071 | + } | ||
| 1072 | + out.push(byte); | ||
| 1073 | + } | ||
| 1074 | + out | ||
| 1075 | +} | ||
| 1076 | + | ||
| 531 | /// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that | 1077 | /// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that |
| 532 | /// buffered instead of coding hands back an empty buffer, and one that emitted | 1078 | /// buffered instead of coding hands back an empty buffer, and one that emitted |
| 533 | /// only parameter sets has no sample to write -- both are for the caller to skip | 1079 | /// only parameter sets has no sample to write -- both are for the caller to skip |
| @@ -750,6 +1296,7 @@ mod tests { | |||
| 750 | Some(&AudioParams { | 1296 | Some(&AudioParams { |
| 751 | freq_index: 4, // 44100 | 1297 | freq_index: 4, // 44100 |
| 752 | chan_conf: 2, | 1298 | chan_conf: 2, |
| 1299 | + sample_rate: 44_100, | ||
| 753 | }), | 1300 | }), |
| 754 | ) | 1301 | ) |
| 755 | .unwrap(); | 1302 | .unwrap(); |
| @@ -840,6 +1387,168 @@ mod tests { | |||
| 840 | assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]); | 1387 | assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]); |
| 841 | } | 1388 | } |
| 842 | 1389 | ||
| 1390 | + /// One second of a 440 Hz tone as AAC-LC packets, through the very encoder | ||
| 1391 | + /// an export re-encodes with: real bitstream, so a file written with it is | ||
| 1392 | + /// one a decoder either plays or does not. | ||
| 1393 | + fn tone_packets(rate: u32, channels: u16) -> Vec<crate::AacPacket> { | ||
| 1394 | + let frames = rate as usize; | ||
| 1395 | + let mut pcm = Vec::with_capacity(frames * usize::from(channels)); | ||
| 1396 | + for i in 0..frames { | ||
| 1397 | + let s = (i as f32 * 440.0 * std::f32::consts::TAU / rate as f32).sin() * 0.5; | ||
| 1398 | + for _ in 0..channels { | ||
| 1399 | + pcm.push(s); | ||
| 1400 | + } | ||
| 1401 | + } | ||
| 1402 | + let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig::default()); | ||
| 1403 | + encoder.push_pcm(&pcm, channels, rate).unwrap(); | ||
| 1404 | + encoder.finish(); | ||
| 1405 | + let mut packets = Vec::new(); | ||
| 1406 | + while let Ok(packet) = encoder.next_packet() { | ||
| 1407 | + packets.push(crate::AacPacket { | ||
| 1408 | + bytes: packet.data, | ||
| 1409 | + samples: packet.duration, | ||
| 1410 | + }); | ||
| 1411 | + } | ||
| 1412 | + assert!(packets.len() > 10, "a second of audio is many packets"); | ||
| 1413 | + packets | ||
| 1414 | + } | ||
| 1415 | + | ||
| 1416 | + /// The Matroska file carries **sound**, and this project's own reader is | ||
| 1417 | + /// what hears it: picture and an AAC track out through the muxer, then the | ||
| 1418 | + /// picture back through our EBML reader and the sound back through the | ||
| 1419 | + /// symphonia `mkv` reader `audio::Track::open` uses. An AV1 export used to be | ||
| 1420 | + /// picture alone, which is a file whose sound went missing with nobody told. | ||
| 1421 | + #[test] | ||
| 1422 | + fn a_matroska_file_carries_its_picture_and_its_sound() { | ||
| 1423 | + let sequence = obu(1, &[0x11, 0x22, 0x33]); | ||
| 1424 | + let mut key = sequence.clone(); | ||
| 1425 | + key.extend_from_slice(&obu(6, &[0xAA; 8])); | ||
| 1426 | + let inter = obu(6, &[0xBB; 5]); | ||
| 1427 | + let packets = tone_packets(48_000, 2); | ||
| 1428 | + let heard: usize = packets.iter().map(|p| p.samples as usize).sum(); | ||
| 1429 | + | ||
| 1430 | + let out = std::env::temp_dir().join(format!("ve_mkv_sound_{}.mkv", std::process::id())); | ||
| 1431 | + let mut muxer = MkvMuxer::create( | ||
| 1432 | + &out, | ||
| 1433 | + &Av1Params { | ||
| 1434 | + width: 640, | ||
| 1435 | + height: 360, | ||
| 1436 | + frame_rate: 30.0, | ||
| 1437 | + config: av1_sequence_header(&key).unwrap(), | ||
| 1438 | + }, | ||
| 1439 | + Some(( | ||
| 1440 | + &AudioParams { | ||
| 1441 | + freq_index: 3, // 48000 | ||
| 1442 | + chan_conf: 2, | ||
| 1443 | + sample_rate: 48_000, | ||
| 1444 | + }, | ||
| 1445 | + packets, | ||
| 1446 | + )), | ||
| 1447 | + ) | ||
| 1448 | + .unwrap(); | ||
| 1449 | + // Half a second of picture under a second of sound: the tail of the | ||
| 1450 | + // audio outlives the last frame and must still be in the file. | ||
| 1451 | + muxer.write_frame(&key, true).unwrap(); | ||
| 1452 | + for _ in 0..14 { | ||
| 1453 | + muxer.write_frame(&inter, false).unwrap(); | ||
| 1454 | + } | ||
| 1455 | + muxer.finish().unwrap(); | ||
| 1456 | + | ||
| 1457 | + // The picture is untouched by the sound beside it: same units, same | ||
| 1458 | + // count, same sequence header in front of the keyframe. | ||
| 1459 | + let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen"); | ||
| 1460 | + assert_eq!(meta.frame_count, 15); | ||
| 1461 | + assert_eq!(meta.codec, crate::demux::Codec::Av1); | ||
| 1462 | + let first = demuxer.next_access_unit().unwrap().unwrap(); | ||
| 1463 | + assert_eq!(&first[sequence.len()..], &key[..]); | ||
| 1464 | + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); | ||
| 1465 | + | ||
| 1466 | + // ...and the sound is there, by name and then by ear. | ||
| 1467 | + assert_eq!( | ||
| 1468 | + crate::demux::matroska_audio_codec(&out).unwrap().as_deref(), | ||
| 1469 | + Some("A_AAC") | ||
| 1470 | + ); | ||
| 1471 | + let probe = crate::audio::AudioSession::probe(&out, 0) | ||
| 1472 | + .unwrap() | ||
| 1473 | + .expect("the file has an audio track"); | ||
| 1474 | + assert_eq!((probe.sample_rate, probe.channels), (48_000, 2)); | ||
| 1475 | + let (audio, chunks) = crate::audio::AudioSession::open(&out) | ||
| 1476 | + .unwrap() | ||
| 1477 | + .expect("decodes through symphonia's mkv reader"); | ||
| 1478 | + assert_eq!((audio.sample_rate, audio.channels), (48_000, 2)); | ||
| 1479 | + let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect(); | ||
| 1480 | + let frames = samples.len() / 2; | ||
| 1481 | + assert!( | ||
| 1482 | + frames + 1024 >= heard && frames <= heard + 2048, | ||
| 1483 | + "{frames} frames read back of {heard} written" | ||
| 1484 | + ); | ||
| 1485 | + let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32).sqrt(); | ||
| 1486 | + assert!(rms > 0.1, "the tone came back silent (rms {rms})"); | ||
| 1487 | + std::fs::remove_file(&out).unwrap(); | ||
| 1488 | + } | ||
| 1489 | + | ||
| 1490 | + /// The same stream in the other container: AV1 into an mp4, whose `av01` | ||
| 1491 | + /// sample entry is written by hand, read back through our own demuxer -- | ||
| 1492 | + /// which is the only test that the patched box tree is still an mp4. | ||
| 1493 | + #[test] | ||
| 1494 | + fn an_av1_track_round_trips_through_an_mp4() { | ||
| 1495 | + let sequence = obu(1, &[0x11, 0x22, 0x33]); | ||
| 1496 | + let mut key = sequence.clone(); | ||
| 1497 | + key.extend_from_slice(&obu(6, &[0xAA; 8])); | ||
| 1498 | + let inter = obu(6, &[0xBB; 5]); | ||
| 1499 | + let packets = tone_packets(48_000, 2); | ||
| 1500 | + | ||
| 1501 | + let out = std::env::temp_dir().join(format!("ve_mp4_av1_{}.mp4", std::process::id())); | ||
| 1502 | + let mut muxer = Mp4Muxer::create_av1( | ||
| 1503 | + &out, | ||
| 1504 | + &Av1Params { | ||
| 1505 | + width: 640, | ||
| 1506 | + height: 360, | ||
| 1507 | + frame_rate: 30.0, | ||
| 1508 | + config: av1_sequence_header(&key).unwrap(), | ||
| 1509 | + }, | ||
| 1510 | + Some(&AudioParams { | ||
| 1511 | + freq_index: 3, | ||
| 1512 | + chan_conf: 2, | ||
| 1513 | + sample_rate: 48_000, | ||
| 1514 | + }), | ||
| 1515 | + ) | ||
| 1516 | + .unwrap(); | ||
| 1517 | + muxer.write_coded_sample(&key, true).unwrap(); | ||
| 1518 | + muxer.write_coded_sample(&inter, false).unwrap(); | ||
| 1519 | + muxer.write_coded_sample(&inter, false).unwrap(); | ||
| 1520 | + for packet in &packets { | ||
| 1521 | + muxer.write_audio_packet(&packet.bytes).unwrap(); | ||
| 1522 | + } | ||
| 1523 | + muxer.finish().unwrap(); | ||
| 1524 | + | ||
| 1525 | + let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen"); | ||
| 1526 | + assert_eq!(meta.codec, crate::demux::Codec::Av1, "read back as AV1"); | ||
| 1527 | + assert_eq!((meta.width, meta.height), (640, 360)); | ||
| 1528 | + assert!((meta.frame_rate - 30.0).abs() < 1e-6, "{}", meta.frame_rate); | ||
| 1529 | + assert_eq!(meta.frame_count, 3); | ||
| 1530 | + // The sequence header off `av1C` in front of the keyframe, exactly as | ||
| 1531 | + // the Matroska reader puts the one off `CodecPrivate` there. | ||
| 1532 | + let first = demuxer.next_access_unit().unwrap().unwrap(); | ||
| 1533 | + assert_eq!(&first[..sequence.len()], &sequence[..]); | ||
| 1534 | + assert_eq!(&first[sequence.len()..], &key[..]); | ||
| 1535 | + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); | ||
| 1536 | + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); | ||
| 1537 | + assert!(demuxer.next_access_unit().unwrap().is_none()); | ||
| 1538 | + assert_eq!(demuxer.seek_to_sync_at_or_before(2), 0, "one keyframe"); | ||
| 1539 | + | ||
| 1540 | + // ...and the audio track beside it is the mp4 path's own, unchanged by | ||
| 1541 | + // the patch: same packets, playable through the same reader. | ||
| 1542 | + let (audio, chunks) = crate::audio::AudioSession::open(&out) | ||
| 1543 | + .unwrap() | ||
| 1544 | + .expect("the mp4's AAC track"); | ||
| 1545 | + assert_eq!((audio.sample_rate, audio.channels), (48_000, 2)); | ||
| 1546 | + let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect(); | ||
| 1547 | + let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32).sqrt(); | ||
| 1548 | + assert!(rms > 0.1, "the tone came back silent (rms {rms})"); | ||
| 1549 | + std::fs::remove_file(&out).unwrap(); | ||
| 1550 | + } | ||
| 1551 | + | ||
| 843 | /// The Matroska half of the round trip, with no encoder in it: three coded | 1552 | /// The Matroska half of the round trip, with no encoder in it: three coded |
| 844 | /// units out through the muxer and back in through our own demuxer, which is | 1553 | /// units out through the muxer and back in through our own demuxer, which is |
| 845 | /// where the hand-written EBML meets the hand-written EBML reader. | 1554 | /// where the hand-written EBML meets the hand-written EBML reader. |
| @@ -861,6 +1570,7 @@ mod tests { | |||
| 861 | frame_rate: 30.0, | 1570 | frame_rate: 30.0, |
| 862 | config, | 1571 | config, |
| 863 | }, | 1572 | }, |
| 1573 | + None, | ||
| 864 | ) | 1574 | ) |
| 865 | .unwrap(); | 1575 | .unwrap(); |
| 866 | muxer.write_frame(&key, true).unwrap(); | 1576 | muxer.write_frame(&key, true).unwrap(); |
| @@ -903,6 +1613,7 @@ mod tests { | |||
| 903 | frame_rate: 30.0, | 1613 | frame_rate: 30.0, |
| 904 | config: &[], | 1614 | config: &[], |
| 905 | }, | 1615 | }, |
| 1616 | + None, | ||
| 906 | ) | 1617 | ) |
| 907 | .is_err() | 1618 | .is_err() |
| 908 | ); | 1619 | ); |
| @@ -22,10 +22,10 @@ use crate::ao::AoSession; | |||
| 22 | use crate::audio::{AudioChunk, AudioSession}; | 22 | use crate::audio::{AudioChunk, AudioSession}; |
| 23 | use crate::clock::{ClockSource, PlaybackClock}; | 23 | use crate::clock::{ClockSource, PlaybackClock}; |
| 24 | use crate::color::ColorParams; | 24 | use crate::color::ColorParams; |
| 25 | -use crate::decode::{DecodeSession, Frame, Worker}; | 25 | +use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; |
| 26 | use crate::demux::{Codec, Demuxer, VideoMeta}; | 26 | use crate::demux::{Codec, Demuxer, VideoMeta}; |
| 27 | use crate::eq::EqParams; | 27 | use crate::eq::EqParams; |
| 28 | -use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed}; | 28 | +use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed}; |
| 29 | use crate::scale::{Composer, FitPolicy}; | 29 | use crate::scale::{Composer, FitPolicy}; |
| 30 | 30 | ||
| 31 | /// How long the feeder waits out a full ring. The ring holds a second, so this | 31 | /// How long the feeder waits out a full ring. The ring holds a second, so this |
| @@ -40,10 +40,11 @@ const RING_FULL_WAIT: Duration = Duration::from_millis(10); | |||
| 40 | /// honest; both are what a video imported onto such a timeline is held to | 40 | /// honest; both are what a video imported onto such a timeline is held to |
| 41 | /// ([`matches_timeline`]). | 41 | /// ([`matches_timeline`]). |
| 42 | /// | 42 | /// |
| 43 | -/// ponytail: a 25 fps video refused by an audio-only timeline it could have | 43 | +/// ponytail: a 25 fps video imported onto an audio-only timeline it could have |
| 44 | -/// defined is the ceiling here. Upgrade path is adopting the first *picture's* | 44 | +/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read |
| 45 | -/// rate and codec on import, which means retiming every audio clip already | 45 | +/// through [`Rate`] like any other file shot at another rate rather than |
| 46 | -/// placed in frames. | 46 | +/// defining one. Upgrade path is adopting the first *picture's* rate and codec |
| 47 | +/// on import, which means retiming every audio clip already placed in frames. | ||
| 47 | const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); | 48 | const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); |
| 48 | 49 | ||
| 49 | /// The frame rate a timeline scaffolded from a still image runs at, for | 50 | /// The frame rate a timeline scaffolded from a still image runs at, for |
| @@ -90,8 +91,18 @@ struct Audio { | |||
| 90 | /// Bumped by every seek. A feeder only owns the device while this still | 91 | /// Bumped by every seek. A feeder only owns the device while this still |
| 91 | /// matches the value it started with; see [`feed`]. | 92 | /// matches the value it started with; see [`feed`]. |
| 92 | epoch: Arc<AtomicU64>, | 93 | epoch: Arc<AtomicU64>, |
| 94 | + /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest | ||
| 95 | + /// first: what a meter or an analyser draws. Written by the feeder, which | ||
| 96 | + /// is not the device's own callback -- the plugin's RT thread never sees | ||
| 97 | + /// this lock, and the feeder holds it for one memcpy per write. | ||
| 98 | + tap: Arc<Mutex<Vec<f32>>>, | ||
| 93 | } | 99 | } |
| 94 | 100 | ||
| 101 | +/// How much of the played signal the tap keeps. A power of two, because what | ||
| 102 | +/// reads it transforms it, and long enough that the lowest band the editor | ||
| 103 | +/// draws (20 Hz) has a whole cycle in the window at any rate we open. | ||
| 104 | +const TAP_SAMPLES: usize = 2048; | ||
| 105 | + | ||
| 95 | impl Audio { | 106 | impl Audio { |
| 96 | /// Whether the device has played everything there will ever be, i.e. the | 107 | /// Whether the device has played everything there will ever be, i.e. the |
| 97 | /// audio clock is about to stop meaning anything. | 108 | /// audio clock is about to stop meaning anything. |
| @@ -100,6 +111,21 @@ impl Audio { | |||
| 100 | && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) | 111 | && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) |
| 101 | } | 112 | } |
| 102 | 113 | ||
| 114 | + /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to | ||
| 115 | + /// mono. Called from the feeder only, once per accepted write. | ||
| 116 | + fn note_tap(&self, accepted: &[f32]) { | ||
| 117 | + let channels = self.channels.max(1) as usize; | ||
| 118 | + let mut tap = self.tap.lock().unwrap(); | ||
| 119 | + // Only the tail can survive anyway: a big write replaces the window | ||
| 120 | + // outright rather than being summed into it and then thrown away. | ||
| 121 | + let from = accepted.len().saturating_sub(TAP_SAMPLES * channels); | ||
| 122 | + for frame in accepted[from..].chunks_exact(channels) { | ||
| 123 | + tap.push(frame.iter().sum::<f32>() / channels as f32); | ||
| 124 | + } | ||
| 125 | + let over = tap.len().saturating_sub(TAP_SAMPLES); | ||
| 126 | + tap.drain(..over); | ||
| 127 | + } | ||
| 128 | + | ||
| 103 | /// Starts a feeder for the current epoch, draining `rx` into the device. | 129 | /// Starts a feeder for the current epoch, draining `rx` into the device. |
| 104 | /// `false` if the thread would not start, i.e. nothing will ever be fed. | 130 | /// `false` if the thread would not start, i.e. nothing will ever be fed. |
| 105 | fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool { | 131 | fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool { |
| @@ -135,6 +161,11 @@ pub struct PlaybackSession { | |||
| 135 | frames: Receiver<Frame>, | 161 | frames: Receiver<Frame>, |
| 136 | /// The current decode worker. | 162 | /// The current decode worker. |
| 137 | worker: Worker, | 163 | worker: Worker, |
| 164 | + /// What that worker opened -- hardware, software, a still, a gap -- written | ||
| 165 | + /// by the worker itself and read by [`decode_backend`](Self::decode_backend). | ||
| 166 | + /// Replaced with the stream at every seek, so it always describes the | ||
| 167 | + /// pictures currently arriving and never the clip before them. | ||
| 168 | + backend: BackendCell, | ||
| 138 | /// Workers cancelled by a seek or a clip change, waiting to be reaped. | 169 | /// Workers cancelled by a seek or a clip change, waiting to be reaped. |
| 139 | /// Joining one inline costs whatever VA-API init it is still inside (98 ms | 170 | /// Joining one inline costs whatever VA-API init it is still inside (98 ms |
| 140 | /// measured worst case), which is a visible hitch on the caller's thread; | 171 | /// measured worst case), which is a visible hitch on the caller's thread; |
| @@ -168,6 +199,20 @@ pub struct PlaybackSession { | |||
| 168 | /// not -- with the single exception `sources` itself has, | 199 | /// not -- with the single exception `sources` itself has, |
| 169 | /// [`Self::remove_source`], which takes the same entry out of both. | 200 | /// [`Self::remove_source`], which takes the same entry out of both. |
| 170 | counts: Vec<u32>, | 201 | counts: Vec<u32>, |
| 202 | + /// What each source's own frame rate is against this timeline's, indexed | ||
| 203 | + /// and grown exactly as [`Self::counts`] is (and shortened with it by | ||
| 204 | + /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the | ||
| 205 | + /// timeline's rate -- and for a still and a song, which have no rate of | ||
| 206 | + /// their own -- so a single-rate project converts nothing anywhere. | ||
| 207 | + /// | ||
| 208 | + /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that | ||
| 209 | + /// knows which frames of the file those are, and only | ||
| 210 | + /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask. | ||
| 211 | + rates: Vec<Rate>, | ||
| 212 | + /// The rate of the source the current worker is decoding, kept beside | ||
| 213 | + /// [`Self::span`] because the frames coming back are numbered in *its* | ||
| 214 | + /// file's frames and nothing else can put them back on the timeline. | ||
| 215 | + span_rate: Rate, | ||
| 171 | /// What the current video worker was opened for: where it sits on the | 216 | /// What the current video worker was opened for: where it sits on the |
| 172 | /// timeline, how long it runs, and which source frame it started at -- | 217 | /// timeline, how long it runs, and which source frame it started at -- |
| 173 | /// together they rewrite a source frame index into a timeline one. Not a | 218 | /// together they rewrite a source frame index into a timeline one. Not a |
| @@ -234,12 +279,16 @@ impl PlaybackSession { | |||
| 234 | native: (meta.width, meta.height), | 279 | native: (meta.width, meta.height), |
| 235 | frames: stream.frames, | 280 | frames: stream.frames, |
| 236 | worker: stream.worker, | 281 | worker: stream.worker, |
| 282 | + backend: stream.backend, | ||
| 237 | retired: Vec::new(), | 283 | retired: Vec::new(), |
| 238 | clock: PlaybackClock::new(source), | 284 | clock: PlaybackClock::new(source), |
| 239 | audio, | 285 | audio, |
| 240 | audio_disabled, | 286 | audio_disabled, |
| 241 | project, | 287 | project, |
| 242 | counts: vec![meta.frame_count], | 288 | counts: vec![meta.frame_count], |
| 289 | + // Source 0 *is* the timeline's rate: it defined it. | ||
| 290 | + rates: vec![Rate::REAL_TIME], | ||
| 291 | + span_rate: Rate::REAL_TIME, | ||
| 243 | span, | 292 | span, |
| 244 | eos: false, | 293 | eos: false, |
| 245 | }) | 294 | }) |
| @@ -328,6 +377,7 @@ impl PlaybackSession { | |||
| 328 | native: (width, height), | 377 | native: (width, height), |
| 329 | frames: stream.frames, | 378 | frames: stream.frames, |
| 330 | worker: stream.worker, | 379 | worker: stream.worker, |
| 380 | + backend: stream.backend, | ||
| 331 | retired: Vec::new(), | 381 | retired: Vec::new(), |
| 332 | // The song keeps the clock, as a video's own sound does -- and wall | 382 | // The song keeps the clock, as a video's own sound does -- and wall |
| 333 | // time keeps it on a machine with no device, where the picture | 383 | // time keeps it on a machine with no device, where the picture |
| @@ -340,6 +390,9 @@ impl PlaybackSession { | |||
| 340 | audio_disabled, | 390 | audio_disabled, |
| 341 | project, | 391 | project, |
| 342 | counts: vec![meta.frame_count], | 392 | counts: vec![meta.frame_count], |
| 393 | + // Source 0 *is* the timeline's rate: it defined it. | ||
| 394 | + rates: vec![Rate::REAL_TIME], | ||
| 395 | + span_rate: Rate::REAL_TIME, | ||
| 343 | span, | 396 | span, |
| 344 | eos: false, | 397 | eos: false, |
| 345 | }) | 398 | }) |
| @@ -400,12 +453,16 @@ impl PlaybackSession { | |||
| 400 | native: (meta.width, meta.height), | 453 | native: (meta.width, meta.height), |
| 401 | frames: stream.frames, | 454 | frames: stream.frames, |
| 402 | worker: stream.worker, | 455 | worker: stream.worker, |
| 456 | + backend: stream.backend, | ||
| 403 | retired: Vec::new(), | 457 | retired: Vec::new(), |
| 404 | clock: PlaybackClock::new(ClockSource::Wall), | 458 | clock: PlaybackClock::new(ClockSource::Wall), |
| 405 | audio: None, | 459 | audio: None, |
| 406 | audio_disabled: None, | 460 | audio_disabled: None, |
| 407 | project, | 461 | project, |
| 408 | counts: vec![meta.frame_count], | 462 | counts: vec![meta.frame_count], |
| 463 | + // Source 0 *is* the timeline's rate: it defined it. | ||
| 464 | + rates: vec![Rate::REAL_TIME], | ||
| 465 | + span_rate: Rate::REAL_TIME, | ||
| 409 | span, | 466 | span, |
| 410 | eos: false, | 467 | eos: false, |
| 411 | }) | 468 | }) |
| @@ -417,10 +474,12 @@ impl PlaybackSession { | |||
| 417 | /// | 474 | /// |
| 418 | /// A *new* session rather than a reload of this one, so a load that fails | 475 | /// A *new* session rather than a reload of this one, so a load that fails |
| 419 | /// leaves the caller's current session untouched -- atomic by | 476 | /// leaves the caller's current session untouched -- atomic by |
| 420 | - /// construction. Every named file is opened and checked here: source 0 | 477 | + /// construction. Every named file is opened and checked here: the |
| 421 | - /// defines the timeline exactly as `open` does, every other source has to | 478 | + /// *scaffolding* source -- the first that is not a still, since a picture |
| 422 | - /// match it the way [`import`](Self::import) demands, and every clip has to | 479 | + /// carries no rate -- defines the timeline exactly as `open` does, every |
| 423 | - /// still be inside the file it plays from. A source that vanished or | 480 | + /// other source has to match it the way [`import`](Self::import) demands |
| 481 | + /// (a save renumbers, so which index that is says nothing), and every clip | ||
| 482 | + /// has to still be inside the file it plays from. A source that vanished or | ||
| 424 | /// shrank since the save is a refusal naming it, not a silently shorter | 483 | /// shrank since the save is a refusal naming it, not a silently shorter |
| 425 | /// timeline -- the disappearing-file tolerance elsewhere in this type | 484 | /// timeline -- the disappearing-file tolerance elsewhere in this type |
| 426 | /// applies only *after* a project has loaded. | 485 | /// applies only *after* a project has loaded. |
| @@ -428,15 +487,38 @@ impl PlaybackSession { | |||
| 428 | /// The undo history is not saved: `undo` is `false` on a fresh load. | 487 | /// The undo history is not saved: `undo` is `false` on a fresh load. |
| 429 | pub fn open_project(path: &Path) -> crate::Result<Self> { | 488 | pub fn open_project(path: &Path) -> crate::Result<Self> { |
| 430 | let doc = crate::edith::load(path)?; | 489 | let doc = crate::edith::load(path)?; |
| 490 | + // *Which* source scaffolds it: the first that is not a still, and index | ||
| 491 | + // 0 only when there is no other. A still defines no frame rate -- it is | ||
| 492 | + // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps | ||
| 493 | + // footage off a PNG that a save happened to renumber to index 0 | ||
| 494 | + // (`Project::without_orphan_sources` numbers by first use, and a | ||
| 495 | + // library removal moves indexes too) reads the timeline as 30 fps and | ||
| 496 | + // then refuses every file on it for not matching. The rule this and | ||
| 497 | + // [`audio_source_of`] share: nothing may assume what source 0 *is*. | ||
| 498 | + // | ||
| 499 | + // A v9 file says what rate it was cut at, and that answer beats the | ||
| 500 | + // scaffold's *where the scaffold has none to give*: a still and a song | ||
| 501 | + // are both given a made-up rate (`IMAGE_ONLY_RATE`, | ||
| 502 | + // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come | ||
| 503 | + // back at 30 fps however it was cut. A scaffold with a picture keeps | ||
| 504 | + // defining the timeline as it always did -- it is the file every clip | ||
| 505 | + // on the lane was conformed to, and the two agree by construction. | ||
| 506 | + let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0); | ||
| 507 | + let scaffold = doc | ||
| 508 | + .sources | ||
| 509 | + .iter() | ||
| 510 | + .position(|s| !crate::is_image(&s.path)) | ||
| 511 | + .unwrap_or(0); | ||
| 431 | // Owned: the sources move into the `Project` below, and the device is | 512 | // Owned: the sources move into the `Project` below, and the device is |
| 432 | // opened after that (see the comment there). | 513 | // opened after that (see the comment there). |
| 433 | let first = doc | 514 | let first = doc |
| 434 | .sources | 515 | .sources |
| 435 | - .first() | 516 | + .get(scaffold) |
| 436 | .cloned() | 517 | .cloned() |
| 437 | .ok_or("the project names no sources")?; | 518 | .ok_or("the project names no sources")?; |
| 438 | - // Source 0 both scaffolds the session and defines the timeline, so it | 519 | + // The scaffolding source both defines the timeline and is what the |
| 439 | - // is opened for playback rather than merely probed. | 520 | + // playhead's first picture comes from, so it is opened for playback |
| 521 | + // rather than merely probed. | ||
| 440 | // One value, not two locals: everything below this line can refuse, and | 522 | // One value, not two locals: everything below this line can refuse, and |
| 441 | // locals drop in reverse declaration order -- a bare worker would join | 523 | // locals drop in reverse declaration order -- a bare worker would join |
| 442 | // its decode thread while the receiver next to it was still holding | 524 | // its decode thread while the receiver next to it was still holding |
| @@ -451,7 +533,8 @@ impl PlaybackSession { | |||
| 451 | // like every other worker opened here. | 533 | // like every other worker opened here. |
| 452 | let (mut meta, stream) = match crate::is_audio(&first.path) { | 534 | let (mut meta, stream) = match crate::is_audio(&first.path) { |
| 453 | true => { | 535 | true => { |
| 454 | - let (width, height, frame_rate) = AUDIO_ONLY_CANVAS; | 536 | + let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS; |
| 537 | + let frame_rate = saved_fps.unwrap_or(canvas_fps); | ||
| 455 | let meta = VideoMeta { | 538 | let meta = VideoMeta { |
| 456 | width, | 539 | width, |
| 457 | height, | 540 | height, |
| @@ -468,11 +551,12 @@ impl PlaybackSession { | |||
| 468 | false if crate::is_image(&first.path) => { | 551 | false if crate::is_image(&first.path) => { |
| 469 | let still = crate::decode::Still::open(&first.path) | 552 | let still = crate::decode::Still::open(&first.path) |
| 470 | .map_err(|e| format!("source {}: {e}", first.path.display()))?; | 553 | .map_err(|e| format!("source {}: {e}", first.path.display()))?; |
| 554 | + let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE); | ||
| 471 | let meta = VideoMeta { | 555 | let meta = VideoMeta { |
| 472 | width: still.width, | 556 | width: still.width, |
| 473 | height: still.height, | 557 | height: still.height, |
| 474 | - frame_rate: IMAGE_ONLY_RATE, | 558 | + frame_rate, |
| 475 | - frame_count: image_frames(IMAGE_ONLY_RATE), | 559 | + frame_count: image_frames(frame_rate), |
| 476 | codec: Codec::H264, | 560 | codec: Codec::H264, |
| 477 | }; | 561 | }; |
| 478 | let stream = DecodeSession::open_still( | 562 | let stream = DecodeSession::open_still( |
| @@ -503,8 +587,22 @@ impl PlaybackSession { | |||
| 503 | } | 587 | } |
| 504 | let first_audio = first_audio_of(&doc.sources)?; | 588 | let first_audio = first_audio_of(&doc.sources)?; |
| 505 | 589 | ||
| 506 | - let mut counts = vec![meta.frame_count]; | 590 | + // In source order, with the scaffold's own count in its own slot: the |
| 507 | - for source in &doc.sources[1..] { | 591 | + // clip check below indexes this list by source, so it must line up with |
| 592 | + // `doc.sources` whichever entry the scaffolding came from. | ||
| 593 | + let mut counts = Vec::with_capacity(doc.sources.len()); | ||
| 594 | + // Beside it, one entry per source, grown at every `push` below: the | ||
| 595 | + // scaffold defines the rate, so it is read frame for frame; every other | ||
| 596 | + // one is however long it is *in this timeline's frames*, which is the | ||
| 597 | + // length `import` noted for it and the wall the clip check below holds | ||
| 598 | + // it to. | ||
| 599 | + let mut rates = Vec::with_capacity(doc.sources.len()); | ||
| 600 | + for (i, source) in doc.sources.iter().enumerate() { | ||
| 601 | + if i == scaffold { | ||
| 602 | + counts.push(meta.frame_count); | ||
| 603 | + rates.push(Rate::REAL_TIME); | ||
| 604 | + continue; | ||
| 605 | + } | ||
| 508 | // A still has neither a rate to match nor a track to match with: | 606 | // A still has neither a rate to match nor a track to match with: |
| 509 | // its length is the one it is held to, recomputed exactly as the | 607 | // its length is the one it is held to, recomputed exactly as the |
| 510 | // import that first noted it did ([`image_frames`]), which is what | 608 | // import that first noted it did ([`image_frames`]), which is what |
| @@ -513,6 +611,7 @@ impl PlaybackSession { | |||
| 513 | crate::decode::image_size(&source.path) | 611 | crate::decode::image_size(&source.path) |
| 514 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; | 612 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 515 | counts.push(image_frames(meta.frame_rate)); | 613 | counts.push(image_frames(meta.frame_rate)); |
| 614 | + rates.push(Rate::REAL_TIME); | ||
| 516 | continue; | 615 | continue; |
| 517 | } | 616 | } |
| 518 | // A source with no picture is checked on what it does have, and | 617 | // A source with no picture is checked on what it does have, and |
| @@ -522,13 +621,15 @@ impl PlaybackSession { | |||
| 522 | audio_matches(source, &first_audio) | 621 | audio_matches(source, &first_audio) |
| 523 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; | 622 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 524 | counts.push(audio_frames(&source.path, meta.frame_rate)?); | 623 | counts.push(audio_frames(&source.path, meta.frame_rate)?); |
| 624 | + rates.push(Rate::REAL_TIME); | ||
| 525 | continue; | 625 | continue; |
| 526 | } | 626 | } |
| 527 | let (other, _) = Demuxer::open(&source.path) | 627 | let (other, _) = Demuxer::open(&source.path) |
| 528 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; | 628 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 529 | - matches_timeline(source, &other, &meta, &first_audio) | 629 | + let rate = matches_timeline(source, &other, &meta, &first_audio) |
| 530 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; | 630 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 531 | - counts.push(other.frame_count); | 631 | + counts.push(rate.timeline_at(other.frame_count)); |
| 632 | + rates.push(rate); | ||
| 532 | } | 633 | } |
| 533 | // The video lane can only play files that have pictures. Hand-written | 634 | // The video lane can only play files that have pictures. Hand-written |
| 534 | // (or hand-edited) project files are the one door this can come in | 635 | // (or hand-edited) project files are the one door this can come in |
| @@ -572,19 +673,29 @@ impl PlaybackSession { | |||
| 572 | } | 673 | } |
| 573 | 674 | ||
| 574 | let playhead = doc.playhead; | 675 | let playhead = doc.playhead; |
| 575 | - let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?; | 676 | + let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? |
| 677 | + .with_mix(&doc.gains, doc.limiter); | ||
| 576 | let span = project.composite_span_at(0); | 678 | let span = project.composite_span_at(0); |
| 577 | // Last, because it is the one thing here that cannot be taken back: the | 679 | // Last, because it is the one thing here that cannot be taken back: the |
| 578 | // feeder thread outlives the `Audio` value (it holds its own clones) and | 680 | // feeder thread outlives the `Audio` value (it holds its own clones) and |
| 579 | // only a session's `drop` retires it, so a refusal above this line would | 681 | // only a session's `drop` retires it, so a refusal above this line would |
| 580 | // leave a PipeWire stream and a thread behind for a project that never | 682 | // leave a PipeWire stream and a thread behind for a project that never |
| 581 | // opened. Nothing before it needs the device. | 683 | // opened. Nothing before it needs the device. |
| 582 | - let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream); | 684 | + // |
| 685 | + // On the source the timeline's *sound* is defined by, which is the | ||
| 686 | + // scaffold unless that one is a still ([`audio_source_of`]): opening a | ||
| 687 | + // PNG as the device is a session with no audio at all, however many | ||
| 688 | + // clips with sound are on its lanes. | ||
| 689 | + let (audio, audio_disabled) = match audio_source_of(project.sources()) { | ||
| 690 | + Some(source) => open_audio(&source.path, source.audio_stream), | ||
| 691 | + None => (None, None), | ||
| 692 | + }; | ||
| 583 | let mut session = Self { | 693 | let mut session = Self { |
| 584 | meta, | 694 | meta, |
| 585 | native, | 695 | native, |
| 586 | frames: stream.frames, | 696 | frames: stream.frames, |
| 587 | worker: stream.worker, | 697 | worker: stream.worker, |
| 698 | + backend: stream.backend, | ||
| 588 | retired: Vec::new(), | 699 | retired: Vec::new(), |
| 589 | clock: PlaybackClock::new(match audio { | 700 | clock: PlaybackClock::new(match audio { |
| 590 | Some(_) => ClockSource::Audio, | 701 | Some(_) => ClockSource::Audio, |
| @@ -594,6 +705,8 @@ impl PlaybackSession { | |||
| 594 | audio_disabled, | 705 | audio_disabled, |
| 595 | project, | 706 | project, |
| 596 | counts, | 707 | counts, |
| 708 | + rates, | ||
| 709 | + span_rate: Rate::REAL_TIME, | ||
| 597 | span, | 710 | span, |
| 598 | eos: false, | 711 | eos: false, |
| 599 | }; | 712 | }; |
| @@ -610,6 +723,24 @@ impl PlaybackSession { | |||
| 610 | &self.meta | 723 | &self.meta |
| 611 | } | 724 | } |
| 612 | 725 | ||
| 726 | + /// What the pictures now arriving are being decoded by: the clip under the | ||
| 727 | + /// playhead, since one video worker feeds the composite at a time. An | ||
| 728 | + /// atomic load -- a front-end may ask it every repaint -- and it is what | ||
| 729 | + /// *opened*, so a clip whose hardware session fell back to software reads | ||
| 730 | + /// [`Backend::Software`] from the frame that fallback happened. | ||
| 731 | + pub fn decode_backend(&self) -> Backend { | ||
| 732 | + self.backend.get() | ||
| 733 | + } | ||
| 734 | + | ||
| 735 | + /// What an export of this timeline would encode the *sound* with, before | ||
| 736 | + /// one is started: the copy an mp4 normally makes, or the software encoder | ||
| 737 | + /// the format (or an equalized lane) forces. Pure -- no probe, no file | ||
| 738 | + /// opened -- so a card may ask it per repaint; the picture's half costs a | ||
| 739 | + /// plugin open and lives in [`crate::export::planned_video`]. | ||
| 740 | + pub fn planned_audio(&self, format: crate::export::Format) -> &'static str { | ||
| 741 | + crate::export::planned_audio(&self.project, format) | ||
| 742 | + } | ||
| 743 | + | ||
| 613 | /// Why this session plays silent although the file has sound -- an audio | 744 | /// Why this session plays silent although the file has sound -- an audio |
| 614 | /// track in a codec we cannot decode, or one the decoder refused. `None` | 745 | /// track in a codec we cannot decode, or one the decoder refused. `None` |
| 615 | /// when there is audio, and for a file that never had any. A front-end | 746 | /// when there is audio, and for a file that never had any. A front-end |
| @@ -627,7 +758,16 @@ impl PlaybackSession { | |||
| 627 | /// Writes the timeline to `path` as a `.edith`, atomically (see | 758 | /// Writes the timeline to `path` as a `.edith`, atomically (see |
| 628 | /// [`crate::edith`]). Sources no clip plays from are left out, and the | 759 | /// [`crate::edith`]). Sources no clip plays from are left out, and the |
| 629 | /// playhead is saved with it so a reopened project resumes where it stood. | 760 | /// playhead is saved with it so a reopened project resumes where it stood. |
| 761 | + /// | ||
| 762 | + /// Refused, writing nothing, for a session whose library is empty (every | ||
| 763 | + /// row removed, [`Project::remove_source`]): a file naming no source has no | ||
| 764 | + /// timeline in it and [`open_project`](Self::open_project) could only | ||
| 765 | + /// refuse it, so the refusal belongs here, where nothing has been | ||
| 766 | + /// overwritten yet. | ||
| 630 | pub fn save_project(&self, path: &Path) -> crate::Result<()> { | 767 | pub fn save_project(&self, path: &Path) -> crate::Result<()> { |
| 768 | + if self.project.sources().is_empty() { | ||
| 769 | + return Err("this project names no file: there is nothing to save".into()); | ||
| 770 | + } | ||
| 631 | let (sources, lanes, eq, color) = self.project.without_orphan_sources(); | 771 | let (sources, lanes, eq, color) = self.project.without_orphan_sources(); |
| 632 | let playhead = secs_to_frame(self.now(), self.meta.frame_rate) | 772 | let playhead = secs_to_frame(self.now(), self.meta.frame_rate) |
| 633 | .min(self.project.timeline_frames().saturating_sub(1)); | 773 | .min(self.project.timeline_frames().saturating_sub(1)); |
| @@ -635,9 +775,19 @@ impl PlaybackSession { | |||
| 635 | path, | 775 | path, |
| 636 | &sources, | 776 | &sources, |
| 637 | &lanes, | 777 | &lanes, |
| 778 | + // The lane volumes and the limiter with them: a mix that vanished | ||
| 779 | + // on a reload would be a mix nobody could keep, and both are the | ||
| 780 | + // project's, not this machine's (the monitoring volume is not | ||
| 781 | + // written and never will be). | ||
| 782 | + &self.project.lane_gains(), | ||
| 638 | &eq, | 783 | &eq, |
| 639 | &color, | 784 | &color, |
| 640 | (self.meta.width, self.meta.height), | 785 | (self.meta.width, self.meta.height), |
| 786 | + // ...and the rate it was cut at, which nothing else in the file | ||
| 787 | + // says: a timeline of stills and songs used to come back at | ||
| 788 | + // whatever its scaffold implied (`open_project`). | ||
| 789 | + Some(self.meta.frame_rate), | ||
| 790 | + self.project.limiter(), | ||
| 641 | playhead, | 791 | playhead, |
| 642 | ) | 792 | ) |
| 643 | } | 793 | } |
| @@ -662,9 +812,15 @@ impl PlaybackSession { | |||
| 662 | // (`speed_maps_both_ways`). An empty timeline has no span, | 812 | // (`speed_maps_both_ways`). An empty timeline has no span, |
| 663 | // and its one black frame is frame 0. Real time is the | 813 | // and its one black frame is frame 0. Real time is the |
| 664 | // arithmetic this always did, frame for frame. | 814 | // arithmetic this always did, frame for frame. |
| 665 | - frame.index = self | 815 | + // ...through the file's own rate first, which is the ceil |
| 666 | - .span | 816 | + // half of *that* pair: the picture at source frame `i` is |
| 667 | - .map_or(frame.index, |s| s.timeline_at(frame.index)); | 817 | + // due at the first timeline-rate frame that shows it, and a |
| 818 | + // slower file's picture is therefore held for the frames in | ||
| 819 | + // between. Real time for a gap and for a single-rate | ||
| 820 | + // project, where this is the identity. | ||
| 821 | + frame.index = self.span.map_or(frame.index, |s| { | ||
| 822 | + s.timeline_at(self.span_rate.timeline_at(frame.index)) | ||
| 823 | + }); | ||
| 668 | return Some(frame); | 824 | return Some(frame); |
| 669 | } | 825 | } |
| 670 | Err(TryRecvError::Empty) => return None, | 826 | Err(TryRecvError::Empty) => return None, |
| @@ -734,6 +890,14 @@ impl PlaybackSession { | |||
| 734 | /// timeline still moves, there are simply no more pictures, and the | 890 | /// timeline still moves, there are simply no more pictures, and the |
| 735 | /// disconnected receiver carries the session on to the next span. | 891 | /// disconnected receiver carries the session on to the next span. |
| 736 | fn start_span(&mut self, span: Option<Span>) { | 892 | fn start_span(&mut self, span: Option<Span>) { |
| 893 | + // Which file's frames the worker about to be opened will number its | ||
| 894 | + // pictures in: the span's own source, and real time for a gap, whose | ||
| 895 | + // black worker counts timeline frames already. Set before the open, | ||
| 896 | + // because the open is the first thing that converts with it. | ||
| 897 | + self.span_rate = match span.and_then(|s| s.from) { | ||
| 898 | + Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME), | ||
| 899 | + None => Rate::REAL_TIME, | ||
| 900 | + }; | ||
| 737 | let opened = match span { | 901 | let opened = match span { |
| 738 | // The grade is the composite's at this frame -- the same clip the | 902 | // The grade is the composite's at this frame -- the same clip the |
| 739 | // span itself came from -- and it is constant across the span, so | 903 | // span itself came from -- and it is constant across the span, so |
| @@ -770,10 +934,17 @@ impl PlaybackSession { | |||
| 770 | .. | 934 | .. |
| 771 | }) => DecodeSession::open_worker( | 935 | }) => DecodeSession::open_worker( |
| 772 | &self.project.sources()[source].path, | 936 | &self.project.sources()[source].path, |
| 773 | - in_frame, | 937 | + // The file's own frames, which is the only place they exist: |
| 938 | + // a clip counts the timeline's ([`Rate`]). | ||
| 939 | + self.span_rate.source_at(in_frame), | ||
| 774 | // Source frames, which a speed makes more (or fewer) than the | 940 | // Source frames, which a speed makes more (or fewer) than the |
| 775 | - // timeline frames the span covers. | 941 | + // timeline frames the span covers -- and which a file shot at |
| 776 | - in_frame + span.expect("matched above").source_len(), | 942 | + // another rate makes fewer (or more) again. One past the last |
| 943 | + // frame this span shows, not one past its length: at another | ||
| 944 | + // rate those are two different frames. | ||
| 945 | + self.span_rate.source_at( | ||
| 946 | + in_frame + span.expect("matched above").source_len().saturating_sub(1), | ||
| 947 | + ) + 1, | ||
| 777 | self.project | 948 | self.project |
| 778 | .composite_color_at(start) | 949 | .composite_color_at(start) |
| 779 | .copied() | 950 | .copied() |
| @@ -804,6 +975,7 @@ impl PlaybackSession { | |||
| 804 | // then can it return and be reaped by a later sweep. Nothing here | 975 | // then can it return and be reaped by a later sweep. Nothing here |
| 805 | // joins, so this ordering costs the seek nothing. | 976 | // joins, so this ordering costs the seek nothing. |
| 806 | self.frames = stream.frames; | 977 | self.frames = stream.frames; |
| 978 | + self.backend = stream.backend; | ||
| 807 | self.retire(stream.worker); | 979 | self.retire(stream.worker); |
| 808 | } | 980 | } |
| 809 | self.span = span; | 981 | self.span = span; |
| @@ -876,6 +1048,13 @@ impl PlaybackSession { | |||
| 876 | self.project.add_lane(kind) | 1048 | self.project.add_lane(kind) |
| 877 | } | 1049 | } |
| 878 | 1050 | ||
| 1051 | + /// Drops that empty lane again, in [`Project::remove_lane`]'s words when it | ||
| 1052 | + /// refuses. One undo step, and no reseek for the same reason the add needs | ||
| 1053 | + /// none: an empty lane was playing nothing. | ||
| 1054 | + pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> { | ||
| 1055 | + self.project.remove_lane(lane) | ||
| 1056 | + } | ||
| 1057 | + | ||
| 879 | /// Splits every lane at `timeline_secs`, so the two sides become two | 1058 | /// Splits every lane at `timeline_secs`, so the two sides become two |
| 880 | /// groups. Metadata only: a split never changes the timeline->source | 1059 | /// groups. Metadata only: a split never changes the timeline->source |
| 881 | /// mapping, so the running decoder stays correct and playback does not | 1060 | /// mapping, so the running decoder stays correct and playback does not |
| @@ -931,6 +1110,31 @@ impl PlaybackSession { | |||
| 931 | self.edit(|p| p.set_eq(lane, idx, params)) | 1110 | self.edit(|p| p.set_eq(lane, idx, params)) |
| 932 | } | 1111 | } |
| 933 | 1112 | ||
| 1113 | + /// How loud that lane plays, in dB -- everything on it, every frequency of | ||
| 1114 | + /// it. See [`Project::lane_gain_db`] for what it is *not*. | ||
| 1115 | + pub fn lane_gain_db(&self, lane: Lane) -> f32 { | ||
| 1116 | + self.project.lane_gain_db(lane) | ||
| 1117 | + } | ||
| 1118 | + | ||
| 1119 | + /// Sets it. One undo step and a reseek, the equalizer's rule for the | ||
| 1120 | + /// equalizer's reason: the mixer is rebuilt from the new volumes right | ||
| 1121 | + /// where the playhead is, so a track turned down during playback is heard | ||
| 1122 | + /// turned down from the next chunk on. | ||
| 1123 | + pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { | ||
| 1124 | + self.edit(|p| p.set_lane_gain_db(lane, db)) | ||
| 1125 | + } | ||
| 1126 | + | ||
| 1127 | + /// The master limiter the whole mix is summed through. | ||
| 1128 | + pub fn limiter(&self) -> crate::limiter::Limiter { | ||
| 1129 | + self.project.limiter() | ||
| 1130 | + } | ||
| 1131 | + | ||
| 1132 | + /// Sets it, live like a lane volume and for the same reason -- the ceiling | ||
| 1133 | + /// a person is dragging has to be the ceiling they are hearing. | ||
| 1134 | + pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool { | ||
| 1135 | + self.edit(|p| p.set_limiter(limiter)) | ||
| 1136 | + } | ||
| 1137 | + | ||
| 934 | /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, | 1138 | /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, |
| 935 | /// silence on the audio one, and nothing else moves. Reseeks, because what | 1139 | /// silence on the audio one, and nothing else moves. Reseeks, because what |
| 936 | /// the playhead sits on has changed. `false` for a bad index -- the lift of | 1140 | /// the playhead sits on has changed. `false` for a bad index -- the lift of |
| @@ -940,14 +1144,20 @@ impl PlaybackSession { | |||
| 940 | self.edit(|p| p.lift(lane, idx)) | 1144 | self.edit(|p| p.lift(lane, idx)) |
| 941 | } | 1145 | } |
| 942 | 1146 | ||
| 943 | - /// Moves that clip onto another lane of the same kind, keeping the frames it | 1147 | + /// Moves that clip onto lane `to` with its head at timeline frame `start` -- |
| 944 | - /// covers -- the drag between tracks. One undo step, and it reseeks like | 1148 | + /// the drag that carries a take along its track or onto another one, and its |
| 945 | - /// every other edit: which lane a clip sits on is what the compositor's | 1149 | + /// whole group with it. See [`Project::move_clip`] for the walls `start` is |
| 946 | - /// topmost-lane-wins rule reads, so the frame on screen is recomposed at | 1150 | + /// clamped to and the ways a drop is refused. One undo step, and it reseeks |
| 947 | - /// once. `false` for a bad index, for a move across kinds and for one that | 1151 | + /// like every other edit: which lane a clip sits on is what the compositor's |
| 948 | - /// would land on another clip; nothing changes. | 1152 | + /// topmost-lane-wins rule reads, and where it starts is what the playhead |
| 949 | - pub fn move_clip_to_lane(&mut self, from: Lane, idx: usize, to: Lane) -> bool { | 1153 | + /// reads, so the frame on screen is recomposed at once. |
| 950 | - self.edit(|p| p.move_to_lane(from, idx, to)) | 1154 | + /// |
| 1155 | + /// A *frame*, where the rest of this type takes seconds, for | ||
| 1156 | + /// [`trim_clip`](Self::trim_clip)'s reason: the drag has already put the | ||
| 1157 | + /// pointer on a frame, and converting it back through seconds would be a | ||
| 1158 | + /// rounding step between the box let go of and the box committed. | ||
| 1159 | + pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { | ||
| 1160 | + self.edit(|p| p.move_clip(from, idx, to, start)) | ||
| 951 | } | 1161 | } |
| 952 | 1162 | ||
| 953 | /// Drags one end of that clip to timeline frame `to`, changing how much of | 1163 | /// Drags one end of that clip to timeline frame `to`, changing how much of |
| @@ -1042,13 +1252,36 @@ impl PlaybackSession { | |||
| 1042 | self.project.trim_room(lane, idx, edge, &self.counts) | 1252 | self.project.trim_room(lane, idx, edge, &self.counts) |
| 1043 | } | 1253 | } |
| 1044 | 1254 | ||
| 1045 | - /// Records how long a source is, for a source index that may be one | 1255 | + /// Records how long a source is and what rate it was shot at, for a source |
| 1046 | - /// `Project::import` just made or one it handed back. See [`Self::counts`]. | 1256 | + /// index that may be one `Project::import` just made or one it handed back. |
| 1047 | - fn note_frames(&mut self, source: usize, frames: u32) { | 1257 | + /// See [`Self::counts`] and [`Self::rates`], which are one table in two |
| 1258 | + /// vectors and grow together. | ||
| 1259 | + fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) { | ||
| 1048 | if source == self.counts.len() { | 1260 | if source == self.counts.len() { |
| 1049 | self.counts.push(frames); | 1261 | self.counts.push(frames); |
| 1262 | + self.rates.push(rate); | ||
| 1050 | } | 1263 | } |
| 1051 | debug_assert_eq!(self.counts.len(), self.project.sources().len()); | 1264 | debug_assert_eq!(self.counts.len(), self.project.sources().len()); |
| 1265 | + debug_assert_eq!(self.rates.len(), self.counts.len()); | ||
| 1266 | + } | ||
| 1267 | + | ||
| 1268 | + /// The rate noted for whichever source plays `path`, by | ||
| 1269 | + /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however | ||
| 1270 | + /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session | ||
| 1271 | + /// has never taken in. | ||
| 1272 | + fn file_rate(&self, path: &Path) -> Rate { | ||
| 1273 | + self.source_of(path) | ||
| 1274 | + .map_or(Rate::REAL_TIME, |i| self.rates[i]) | ||
| 1275 | + } | ||
| 1276 | + | ||
| 1277 | + /// Which source `path` is, canonicalising only if it has to: a source's own | ||
| 1278 | + /// path is canonical ([`Source::new`]), so a caller handing one back from | ||
| 1279 | + /// [`sources`](Self::sources) -- which is every library row -- hits on the | ||
| 1280 | + /// first walk and never pays for the `canonicalize` syscall the second one | ||
| 1281 | + /// makes. One rule, so a path that names a length names a rate too. | ||
| 1282 | + fn source_of(&self, path: &Path) -> Option<usize> { | ||
| 1283 | + let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); | ||
| 1284 | + at(path).or_else(|| at(&Source::new(path, 0).path)) | ||
| 1052 | } | 1285 | } |
| 1053 | 1286 | ||
| 1054 | /// How long the whole of `path` is, in timeline frames: the length noted | 1287 | /// How long the whole of `path` is, in timeline frames: the length noted |
| @@ -1060,14 +1293,20 @@ impl PlaybackSession { | |||
| 1060 | /// audio tracks it carries -- the picture's frame count for an mp4, the | 1293 | /// audio tracks it carries -- the picture's frame count for an mp4, the |
| 1061 | /// playing time for a song. | 1294 | /// playing time for a song. |
| 1062 | pub fn file_frames(&self, path: &Path) -> u32 { | 1295 | pub fn file_frames(&self, path: &Path) -> u32 { |
| 1063 | - let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); | 1296 | + self.source_of(path).map_or(0, |i| self.counts[i]) |
| 1064 | - // A source's own path is canonical ([`Source::new`]), so a caller | 1297 | + } |
| 1065 | - // handing one back from [`sources`](Self::sources) -- which is every | 1298 | + |
| 1066 | - // library row -- hits on the first walk and never pays for the | 1299 | + /// What rate the file at `path` was *shot* at, in frames per second -- which |
| 1067 | - // `canonicalize` syscall the second one makes. | 1300 | + /// is the timeline's own rate for every source that shares it, and is not |
| 1068 | - at(path) | 1301 | + /// for one placed at another ([`Rate`]). By path like |
| 1069 | - .or_else(|| at(&Source::new(path, 0).path)) | 1302 | + /// [`file_frames`](Self::file_frames), and the timeline's rate for a file |
| 1070 | - .map_or(0, |i| self.counts[i]) | 1303 | + /// this session has never taken in (and for a still and a song, which were |
| 1304 | + /// shot at no rate at all). | ||
| 1305 | + /// | ||
| 1306 | + /// What a library row names the file with: the timeline's rate there would | ||
| 1307 | + /// be a lie about a 23.976 fps file the moment one can join. | ||
| 1308 | + pub fn file_fps(&self, path: &Path) -> f64 { | ||
| 1309 | + self.file_rate(path).as_f64() * self.meta.frame_rate | ||
| 1071 | } | 1310 | } |
| 1072 | 1311 | ||
| 1073 | /// The clip the picture is coming from at `timeline_secs`: the lane it sits | 1312 | /// The clip the picture is coming from at `timeline_secs`: the lane it sits |
| @@ -1186,7 +1425,7 @@ impl PlaybackSession { | |||
| 1186 | /// [`import`](Self::import) refuses a file with. One output device and one | 1425 | /// [`import`](Self::import) refuses a file with. One output device and one |
| 1187 | /// copied AAC track mean one set of audio parameters for the whole | 1426 | /// copied AAC track mean one set of audio parameters for the whole |
| 1188 | /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one -- | 1427 | /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one -- |
| 1189 | - /// there is no resampler here, and no AAC encoder to write the join with. | 1428 | + /// there is no resampler here to make one rate of two. |
| 1190 | /// A front-end greys such a row out; this is the backstop that keeps a | 1429 | /// A front-end greys such a row out; this is the backstop that keeps a |
| 1191 | /// stale one from making the whole timeline silent. | 1430 | /// stale one from making the whole timeline silent. |
| 1192 | /// | 1431 | /// |
| @@ -1226,8 +1465,9 @@ impl PlaybackSession { | |||
| 1226 | let first = self.first_audio()?; | 1465 | let first = self.first_audio()?; |
| 1227 | audio_matches(&wanted, &first)?; | 1466 | audio_matches(&wanted, &first)?; |
| 1228 | } | 1467 | } |
| 1468 | + let rate = self.file_rate(&wanted.path); | ||
| 1229 | let source = self.project.import(path, stream); | 1469 | let source = self.project.import(path, stream); |
| 1230 | - self.note_frames(source, frames); | 1470 | + self.note_frames(source, frames, rate); |
| 1231 | let clip = Clip { | 1471 | let clip = Clip { |
| 1232 | start: 0, | 1472 | start: 0, |
| 1233 | in_frame: 0, | 1473 | in_frame: 0, |
| @@ -1286,7 +1526,14 @@ impl PlaybackSession { | |||
| 1286 | /// Reseeks like an edit even though nothing playable changed: the clip | 1526 | /// Reseeks like an edit even though nothing playable changed: the clip |
| 1287 | /// indexes into the source list have just moved, and the running workers | 1527 | /// indexes into the source list have just moved, and the running workers |
| 1288 | /// were opened against the old numbering. | 1528 | /// were opened against the old numbering. |
| 1289 | - pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> { | 1529 | + /// |
| 1530 | + /// The index that went, because everything past it moved down: a caller | ||
| 1531 | + /// holding a source index of its own (a clipboard) has to fix it up or drop | ||
| 1532 | + /// it, or it names a different file afterwards. The **last** row goes like | ||
| 1533 | + /// any other and leaves a session with an empty library -- silent, empty of | ||
| 1534 | + /// clips, and unsaveable ([`save_project`](Self::save_project)); a | ||
| 1535 | + /// front-end showing one is showing an empty window. | ||
| 1536 | + pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> { | ||
| 1290 | let wanted = Source::new(path, stream); | 1537 | let wanted = Source::new(path, stream); |
| 1291 | let idx = self | 1538 | let idx = self |
| 1292 | .project | 1539 | .project |
| @@ -1302,14 +1549,16 @@ impl PlaybackSession { | |||
| 1302 | // count one index late. | 1549 | // count one index late. |
| 1303 | if idx < self.counts.len() { | 1550 | if idx < self.counts.len() { |
| 1304 | self.counts.remove(idx); | 1551 | self.counts.remove(idx); |
| 1552 | + self.rates.remove(idx); | ||
| 1305 | } | 1553 | } |
| 1306 | let now = self.now(); | 1554 | let now = self.now(); |
| 1307 | self.seek(now); | 1555 | self.seek(now); |
| 1308 | - Ok(()) | 1556 | + Ok(idx) |
| 1309 | } | 1557 | } |
| 1310 | 1558 | ||
| 1311 | - /// What the timeline's audio *is*: source 0's chosen stream, probed. Every | 1559 | + /// What the timeline's audio *is*: the chosen stream of the first source |
| 1312 | - /// other source is held to it. | 1560 | + /// that could have any ([`audio_source_of`]), probed. Every other source is |
| 1561 | + /// held to it. | ||
| 1313 | fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> { | 1562 | fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> { |
| 1314 | first_audio_of(self.project.sources()) | 1563 | first_audio_of(self.project.sources()) |
| 1315 | } | 1564 | } |
| @@ -1355,11 +1604,14 @@ impl PlaybackSession { | |||
| 1355 | /// nothing playable, so there is nothing for [`undo`](Self::undo) to take | 1604 | /// nothing playable, so there is nothing for [`undo`](Self::undo) to take |
| 1356 | /// back, and nothing reseeks. | 1605 | /// back, and nothing reseeks. |
| 1357 | /// | 1606 | /// |
| 1358 | - /// Refused unless it can join the timeline -- same codec, same frame rate, | 1607 | + /// Refused unless it can join the timeline -- same codec, same audio |
| 1359 | - /// same audio parameters or both silent; the `Err` names the property that | 1608 | + /// parameters or both silent; the `Err` names the property that disagrees, |
| 1360 | - /// disagrees, for a caller to show. Nothing is changed by a refusal. A | 1609 | + /// for a caller to show. Nothing is changed by a refusal. A *resolution* of |
| 1361 | - /// *resolution* of its own is not a refusal: the clip is placed on the | 1610 | + /// its own is not a refusal: the clip is placed on the project canvas by its |
| 1362 | - /// project canvas by its fit policy ([`PlaybackSession::set_fit`]). | 1611 | + /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame |
| 1612 | + /// rate* of its own: the file is placed for the seconds it lasts and read at | ||
| 1613 | + /// [`Rate`] against the timeline's rate, so it plays at the speed it was | ||
| 1614 | + /// shot at. | ||
| 1363 | pub fn import(&mut self, path: &Path) -> crate::Result<usize> { | 1615 | pub fn import(&mut self, path: &Path) -> crate::Result<usize> { |
| 1364 | if crate::is_audio(path) { | 1616 | if crate::is_audio(path) { |
| 1365 | return self.import_audio(path); | 1617 | return self.import_audio(path); |
| @@ -1372,9 +1624,15 @@ impl PlaybackSession { | |||
| 1372 | // Stream 0: an import brings a file in on its first audio track, and | 1624 | // Stream 0: an import brings a file in on its first audio track, and |
| 1373 | // [`place_stream_at`](Self::place_stream_at) is how any other one of | 1625 | // [`place_stream_at`](Self::place_stream_at) is how any other one of |
| 1374 | // its streams reaches the timeline afterwards. | 1626 | // its streams reaches the timeline afterwards. |
| 1375 | - matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; | 1627 | + // ...and the rate it will be read at comes back from the check that |
| 1628 | + // accepted it, so the number the refusal was decided on is the number | ||
| 1629 | + // the file is played by. | ||
| 1630 | + let rate = matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; | ||
| 1376 | let source = self.project.import(path, 0); | 1631 | let source = self.project.import(path, 0); |
| 1377 | - self.note_frames(source, meta.frame_count); | 1632 | + // Its length *on this timeline*: a file shot slower than the timeline |
| 1633 | + // runs covers more frames than it holds, which is the whole of what | ||
| 1634 | + // placing it at another rate means ([`Rate`]). | ||
| 1635 | + self.note_frames(source, rate.timeline_at(meta.frame_count), rate); | ||
| 1378 | Ok(source) | 1636 | Ok(source) |
| 1379 | } | 1637 | } |
| 1380 | 1638 | ||
| @@ -1394,7 +1652,7 @@ impl PlaybackSession { | |||
| 1394 | audio_matches(&Source::new(path, 0), &first)?; | 1652 | audio_matches(&Source::new(path, 0), &first)?; |
| 1395 | let frames = audio_frames(path, self.meta.frame_rate)?; | 1653 | let frames = audio_frames(path, self.meta.frame_rate)?; |
| 1396 | let source = self.project.import(path, 0); | 1654 | let source = self.project.import(path, 0); |
| 1397 | - self.note_frames(source, frames); | 1655 | + self.note_frames(source, frames, Rate::REAL_TIME); |
| 1398 | Ok(source) | 1656 | Ok(source) |
| 1399 | } | 1657 | } |
| 1400 | 1658 | ||
| @@ -1418,7 +1676,7 @@ impl PlaybackSession { | |||
| 1418 | .into()); | 1676 | .into()); |
| 1419 | } | 1677 | } |
| 1420 | let source = self.project.import(path, 0); | 1678 | let source = self.project.import(path, 0); |
| 1421 | - self.note_frames(source, image_frames(self.meta.frame_rate)); | 1679 | + self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME); |
| 1422 | Ok(source) | 1680 | Ok(source) |
| 1423 | } | 1681 | } |
| 1424 | 1682 | ||
| @@ -1493,6 +1751,21 @@ impl PlaybackSession { | |||
| 1493 | } | 1751 | } |
| 1494 | } | 1752 | } |
| 1495 | 1753 | ||
| 1754 | + /// A copy of the most recent mono samples the device was handed, and the | ||
| 1755 | + /// rate they play at: the signal *after* every clip's equalizer, speed and | ||
| 1756 | + /// the mix, which is what an analyser drawn behind an EQ curve has to show. | ||
| 1757 | + /// `None` with no audio output at all, and empty until the feeder has | ||
| 1758 | + /// written once (right after a seek, for instance). | ||
| 1759 | + /// | ||
| 1760 | + /// Never blocks anything that matters: the feeder holds this lock for one | ||
| 1761 | + /// memcpy and the device's own callback lives in the plugin, on the far | ||
| 1762 | + /// side of a ring buffer, where it cannot see this at all. | ||
| 1763 | + pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> { | ||
| 1764 | + let audio = self.audio.as_ref()?; | ||
| 1765 | + let tap = audio.tap.lock().unwrap().clone(); | ||
| 1766 | + Some((tap, audio.sample_rate)) | ||
| 1767 | + } | ||
| 1768 | + | ||
| 1496 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode | 1769 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode |
| 1497 | /// workers are replaced rather than steered: a fresh channel cannot hold a | 1770 | /// workers are replaced rather than steered: a fresh channel cannot hold a |
| 1498 | /// stale frame, and it works just as well after EOF, where the old workers | 1771 | /// stale frame, and it works just as well after EOF, where the old workers |
| @@ -1515,6 +1788,9 @@ impl PlaybackSession { | |||
| 1515 | // carrying can no longer reach the ring after this point. | 1788 | // carrying can no longer reach the ring after this point. |
| 1516 | audio.epoch.fetch_add(1, Ordering::Release); | 1789 | audio.epoch.fetch_add(1, Ordering::Release); |
| 1517 | ao.flush(); | 1790 | ao.flush(); |
| 1791 | + // The flushed samples are not being played any more, so nothing may | ||
| 1792 | + // still be drawn from them. | ||
| 1793 | + audio.tap.lock().unwrap().clear(); | ||
| 1518 | } | 1794 | } |
| 1519 | 1795 | ||
| 1520 | // Cancel first, drop second: the old worker may be parked in `send` on | 1796 | // Cancel first, drop second: the old worker may be parked in `send` on |
| @@ -1562,11 +1838,18 @@ impl PlaybackSession { | |||
| 1562 | // Each source on the stream it was placed with: what plays is what | 1838 | // Each source on the stream it was placed with: what plays is what |
| 1563 | // the library row said, and what an export copies (`export::run`). | 1839 | // the library row said, and what an export copies (`export::run`). |
| 1564 | let sources = self.project.audio_sources(); | 1840 | let sources = self.project.audio_sources(); |
| 1565 | - audio_running = | 1841 | + // ...and the mix settings over the lot: each lane's own volume on |
| 1566 | - match AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds) { | 1842 | + // its way into the sum and the master limiter over the sum, both |
| 1567 | - Ok(Some((_, rx))) => audio.spawn_feeder(rx), | 1843 | + // rebuilt here like the curves above, which is what makes a lane |
| 1568 | - _ => false, | 1844 | + // fader and a ceiling audible while the timeline runs. |
| 1569 | - }; | 1845 | + let gains = self.project.audio_gains(); |
| 1846 | + let limiter = self.project.limiter(); | ||
| 1847 | + audio_running = match AudioSession::open_mixed_streams_master( | ||
| 1848 | + &sources, &segs, &eqs, &speeds, &gains, limiter, | ||
| 1849 | + ) { | ||
| 1850 | + Ok(Some((_, rx))) => audio.spawn_feeder(rx), | ||
| 1851 | + _ => false, | ||
| 1852 | + }; | ||
| 1570 | if !audio_running { | 1853 | if !audio_running { |
| 1571 | // Nothing will ever be fed again; let `tick` fall to wall time | 1854 | // Nothing will ever be fed again; let `tick` fall to wall time |
| 1572 | // instead of waiting on a device that has no more work coming. | 1855 | // instead of waiting on a device that has no more work coming. |
| @@ -1662,15 +1945,16 @@ impl Drop for PlaybackSession { | |||
| 1662 | 1945 | ||
| 1663 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose | 1946 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose |
| 1664 | /// parameters are `timeline` and whose audio probes as `first`: same codec, | 1947 | /// parameters are `timeline` and whose audio probes as `first`: same codec, |
| 1665 | -/// same frame rate, same audio parameters or both silent. | 1948 | +/// same audio parameters or both silent, and a frame rate that can be named |
| 1949 | +/// against the timeline's. The [`Rate`] it will be read at comes back with the | ||
| 1950 | +/// answer, so the number the check was decided on is the number it plays by. | ||
| 1666 | /// | 1951 | /// |
| 1667 | /// *Not* the same size any more. A project has its own resolution | 1952 | /// *Not* the same size any more. A project has its own resolution |
| 1668 | /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its | 1953 | /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its |
| 1669 | /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a | 1954 | /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a |
| 1670 | -/// letterboxed clip rather than a refusal. The frame rate stays refused on | 1955 | +/// letterboxed clip rather than a refusal, and so is a frame rate of its own: |
| 1671 | -/// purpose: mixing rates means resampling the *timeline*, which is a different | 1956 | +/// the timeline keeps its own rate and the file is read at [`Rate`] against it |
| 1672 | -/// problem from resampling a picture, and a refusal is the honest answer until | 1957 | +/// ([`PlaybackSession::import`] notes how long it is *here*). |
| 1673 | -/// it is solved. | ||
| 1674 | /// | 1958 | /// |
| 1675 | /// The `Err` names the property that disagrees, and those strings are what a | 1959 | /// The `Err` names the property that disagrees, and those strings are what a |
| 1676 | /// front-end shows verbatim; [`PlaybackSession::import`] and | 1960 | /// front-end shows verbatim; [`PlaybackSession::import`] and |
| @@ -1681,7 +1965,7 @@ fn matches_timeline( | |||
| 1681 | meta: &VideoMeta, | 1965 | meta: &VideoMeta, |
| 1682 | timeline: &VideoMeta, | 1966 | timeline: &VideoMeta, |
| 1683 | first: &Option<crate::AudioProbe>, | 1967 | first: &Option<crate::AudioProbe>, |
| 1684 | -) -> crate::Result<()> { | 1968 | +) -> crate::Result<Rate> { |
| 1685 | // Codec first: one timeline is one kind of source. Mixing them would decode | 1969 | // Codec first: one timeline is one kind of source. Mixing them would decode |
| 1686 | // (every clip opens its own decoder) but on a machine without the VA-API | 1970 | // (every clip opens its own decoder) but on a machine without the VA-API |
| 1687 | // plugin the VP9 half would be black frames with the refusal only on | 1971 | // plugin the VP9 half would be black frames with the refusal only on |
| @@ -1694,15 +1978,20 @@ fn matches_timeline( | |||
| 1694 | ) | 1978 | ) |
| 1695 | .into()); | 1979 | .into()); |
| 1696 | } | 1980 | } |
| 1697 | - // Container frame rates are computed from timescales, so never `==`. | 1981 | + // The frame rate is *not* a refusal any more: a file shot at another rate is |
| 1698 | - if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 { | 1982 | + // placed for the seconds it lasts and read through [`Rate`] at the |
| 1699 | - return Err(format!( | 1983 | + // decoder's door, so it plays at the speed it was shot at on a timeline |
| 1700 | - "{:.3} fps does not match the timeline's {:.3} fps", | 1984 | + // that counts frames faster or slower. |
| 1701 | - meta.frame_rate, timeline.frame_rate | 1985 | + // |
| 1702 | - ) | 1986 | + // A rate that cannot be *named* still is, and this is the one place it is |
| 1703 | - .into()); | 1987 | + // caught: `Rate::from_fps` builds itself out of the muxer's own timescales, |
| 1704 | - } | 1988 | + // and a file whose rate has none of those (a container that says nothing and |
| 1705 | - audio_matches(source, first) | 1989 | + // holds one block, so the demuxer measures 0 fps) would otherwise be read |
| 1990 | + // 1:1 in silence -- the old rate gate refused those too, by arithmetic | ||
| 1991 | + // accident. The `Err` is `mux::frame_timing`'s own words. | ||
| 1992 | + let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?; | ||
| 1993 | + audio_matches(source, first)?; | ||
| 1994 | + Ok(rate) | ||
| 1706 | } | 1995 | } |
| 1707 | 1996 | ||
| 1708 | /// Whether a candidate's audio may join a timeline whose first source probes as | 1997 | /// Whether a candidate's audio may join a timeline whose first source probes as |
| @@ -1729,12 +2018,26 @@ fn matches_timeline( | |||
| 1729 | /// source 0 has always given. This function widens which source is asked, not | 2018 | /// source 0 has always given. This function widens which source is asked, not |
| 1730 | /// what the answer means. | 2019 | /// what the answer means. |
| 1731 | fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> { | 2020 | fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> { |
| 1732 | - match sources.iter().find(|s| !crate::is_image(&s.path)) { | 2021 | + match audio_source_of(sources) { |
| 1733 | Some(first) => AudioSession::probe(&first.path, first.audio_stream), | 2022 | Some(first) => AudioSession::probe(&first.path, first.audio_stream), |
| 1734 | None => Ok(None), | 2023 | None => Ok(None), |
| 1735 | } | 2024 | } |
| 1736 | } | 2025 | } |
| 1737 | 2026 | ||
| 2027 | +/// *Which* source that is: the first one that is not a still. The single answer | ||
| 2028 | +/// to "what does this timeline's sound come from", so that probing it | ||
| 2029 | +/// ([`first_audio_of`]) and opening the device on it | ||
| 2030 | +/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only | ||
| 2031 | +/// the scaffolding file until a save renumbers it or a library removal takes it | ||
| 2032 | +/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the | ||
| 2033 | +/// device is a timeline that plays silent although every clip on it has sound. | ||
| 2034 | +/// | ||
| 2035 | +/// `None` for a library of nothing but stills, and for one with no file at all: | ||
| 2036 | +/// both are silent timelines. | ||
| 2037 | +fn audio_source_of(sources: &[Source]) -> Option<&Source> { | ||
| 2038 | + sources.iter().find(|s| !crate::is_image(&s.path)) | ||
| 2039 | +} | ||
| 2040 | + | ||
| 1738 | fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> { | 2041 | fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> { |
| 1739 | // Whole-probe equality: rate and layout, which the audio worker holds every | 2042 | // Whole-probe equality: rate and layout, which the audio worker holds every |
| 1740 | // source to anyway. Both silent is a match. | 2043 | // source to anyway. Both silent is a match. |
| @@ -1832,6 +2135,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) { | |||
| 1832 | fed_all: Arc::new(AtomicBool::new(false)), | 2135 | fed_all: Arc::new(AtomicBool::new(false)), |
| 1833 | died: Arc::new(AtomicBool::new(false)), | 2136 | died: Arc::new(AtomicBool::new(false)), |
| 1834 | epoch: Arc::new(AtomicU64::new(0)), | 2137 | epoch: Arc::new(AtomicU64::new(0)), |
| 2138 | + tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))), | ||
| 1835 | }; | 2139 | }; |
| 1836 | (audio.spawn_feeder(rx).then_some(audio), None) | 2140 | (audio.spawn_feeder(rx).then_some(audio), None) |
| 1837 | } | 2141 | } |
| @@ -1866,6 +2170,7 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) { | |||
| 1866 | } | 2170 | } |
| 1867 | }; | 2171 | }; |
| 1868 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); | 2172 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); |
| 2173 | + audio.note_tap(&pending[..accepted]); | ||
| 1869 | pending.drain(..accepted); | 2174 | pending.drain(..accepted); |
| 1870 | if !pending.is_empty() { | 2175 | if !pending.is_empty() { |
| 1871 | // Ring full: nothing to do but let the device drain it. | 2176 | // Ring full: nothing to do but let the device drain it. |
| @@ -1885,7 +2190,7 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 { | |||
| 1885 | 2190 | ||
| 1886 | #[cfg(test)] | 2191 | #[cfg(test)] |
| 1887 | mod tests { | 2192 | mod tests { |
| 1888 | - use super::{Edge, Lane, PlaybackSession, secs_to_frame}; | 2193 | + use super::{Edge, Lane, PlaybackSession, Source, audio_source_of, secs_to_frame}; |
| 1889 | use std::path::PathBuf; | 2194 | use std::path::PathBuf; |
| 1890 | 2195 | ||
| 1891 | fn asset(name: &str) -> PathBuf { | 2196 | fn asset(name: &str) -> PathBuf { |
| @@ -1894,6 +2199,27 @@ mod tests { | |||
| 1894 | .join(name) | 2199 | .join(name) |
| 1895 | } | 2200 | } |
| 1896 | 2201 | ||
| 2202 | + /// Which source the timeline's sound is opened on -- the one rule | ||
| 2203 | + /// [`open_project`](PlaybackSession::open_project), the probe every import | ||
| 2204 | + /// is held to and the audio worker all read through. A still at index 0 is | ||
| 2205 | + /// a picture, not a silent timeline: opening the device on it is a project | ||
| 2206 | + /// that plays silent although every clip on it has sound. | ||
| 2207 | + #[test] | ||
| 2208 | + fn the_audio_reference_is_never_a_still() { | ||
| 2209 | + let (video, still) = (asset("test_av.mp4"), asset("test_still.png")); | ||
| 2210 | + let sources = [Source::new(&still, 0), Source::new(&video, 3)]; | ||
| 2211 | + assert_eq!( | ||
| 2212 | + audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)), | ||
| 2213 | + Some((&sources[1].path, 3)), | ||
| 2214 | + "the first source that could have a track, with its own stream" | ||
| 2215 | + ); | ||
| 2216 | + assert!( | ||
| 2217 | + audio_source_of(&sources[..1]).is_none(), | ||
| 2218 | + "nothing but stills" | ||
| 2219 | + ); | ||
| 2220 | + assert!(audio_source_of(&[]).is_none(), "and no file at all"); | ||
| 2221 | + } | ||
| 2222 | + | ||
| 1897 | /// The seam between the two lists a source index reaches: dropping a file | 2223 | /// The seam between the two lists a source index reaches: dropping a file |
| 1898 | /// from the library shortens `sources`, and `counts` -- the frame length | 2224 | /// from the library shortens `sources`, and `counts` -- the frame length |
| 1899 | /// per source, which is what a trim is walled by -- has to lose the same | 2225 | /// per source, which is what a trim is walled by -- has to lose the same |
| @@ -66,8 +66,18 @@ use std::path::{Path, PathBuf}; | |||
| 66 | 66 | ||
| 67 | use crate::color::ColorParams; | 67 | use crate::color::ColorParams; |
| 68 | use crate::eq::EqParams; | 68 | use crate::eq::EqParams; |
| 69 | +use crate::limiter::{Limiter, db_to_linear}; | ||
| 69 | use crate::scale::FitPolicy; | 70 | use crate::scale::FitPolicy; |
| 70 | 71 | ||
| 72 | +/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]). | ||
| 73 | +/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix | ||
| 74 | +/// for every purpose but the honest one, which is that it is still a level and | ||
| 75 | +/// not a mute. | ||
| 76 | +pub const MIN_GAIN_DB: f32 = -60.0; | ||
| 77 | +/// ...and how far up. +12 dB is four times the amplitude, which is as much as | ||
| 78 | +/// a mix bus can take before the limiter is doing all the work. | ||
| 79 | +pub const MAX_GAIN_DB: f32 = 12.0; | ||
| 80 | + | ||
| 71 | /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it | 81 | /// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it |
| 72 | /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for | 82 | /// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for |
| 73 | /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly | 83 | /// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly |
| @@ -221,9 +231,120 @@ impl std::fmt::Display for Speed { | |||
| 221 | } | 231 | } |
| 222 | } | 232 | } |
| 223 | 233 | ||
| 234 | +/// What a file's own frame rate is against the timeline's, as an exact | ||
| 235 | +/// rational: how many frames of the *file* one frame of the timeline is worth. | ||
| 236 | +/// | ||
| 237 | +/// Every frame number in this module counts **timeline** frames -- a clip's | ||
| 238 | +/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps | ||
| 239 | +/// timeline is as many frames long as the seconds it lasts, and every edit | ||
| 240 | +/// (trim, split, speed, paste) is the same arithmetic it always was. This is the | ||
| 241 | +/// one conversion, and it happens at the decoder's door: [`PlaybackSession`] | ||
| 242 | +/// opens a worker with it and [`crate::export`] pulls pictures through it. The | ||
| 243 | +/// file's own numbering exists nowhere else. | ||
| 244 | +/// | ||
| 245 | +/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an | ||
| 246 | +/// export encodes at a timeline frame has to be the frame playback is holding | ||
| 247 | +/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps | ||
| 248 | +/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`). | ||
| 249 | +/// | ||
| 250 | +/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and | ||
| 251 | +/// stays `800/1001` however far the timeline runs, where a rate rounded to | ||
| 252 | +/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a | ||
| 253 | +/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`). | ||
| 254 | +/// | ||
| 255 | +/// [`PlaybackSession`]: crate::PlaybackSession | ||
| 256 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 257 | +pub struct Rate { | ||
| 258 | + /// Frames of the file... | ||
| 259 | + source: u32, | ||
| 260 | + /// ...per this many frames of the timeline it plays on. Never zero. | ||
| 261 | + timeline: u32, | ||
| 262 | +} | ||
| 263 | + | ||
| 264 | +impl Rate { | ||
| 265 | + /// A file shot at the timeline's own rate: every conversion below is the | ||
| 266 | + /// identity, which is the path a single-rate project is on. | ||
| 267 | + pub const REAL_TIME: Self = Self { | ||
| 268 | + source: 1, | ||
| 269 | + timeline: 1, | ||
| 270 | + }; | ||
| 271 | + | ||
| 272 | + /// The rate of a file at `source_fps` on a timeline at `timeline_fps`, | ||
| 273 | + /// exactly. | ||
| 274 | + /// | ||
| 275 | + /// Both rates come out of a container as a division, so neither is ever the | ||
| 276 | + /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what | ||
| 277 | + /// already knows how to name one exactly -- it is the same pair the muxer | ||
| 278 | + /// counts an export's frames in -- and this is that pair divided by that | ||
| 279 | + /// pair, reduced. A rate no timescale can name is an `Err` in that | ||
| 280 | + /// function's own words rather than a silent 1:1 -- `matches_timeline` is | ||
| 281 | + /// where a file carrying one is refused by name, beside the codec. | ||
| 282 | + /// | ||
| 283 | + /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every | ||
| 284 | + /// timeline that had ever opened in this editor before mixed rates. | ||
| 285 | + pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> { | ||
| 286 | + let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?; | ||
| 287 | + let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?; | ||
| 288 | + // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks). | ||
| 289 | + let num = u64::from(src_scale) * u64::from(tl_ticks); | ||
| 290 | + let den = u64::from(src_ticks) * u64::from(tl_scale); | ||
| 291 | + let g = gcd(num, den); | ||
| 292 | + let (mut num, mut den) = (num / g, den / g); | ||
| 293 | + // A ratio no pair of real frame rates produces, but the fields are `u32` | ||
| 294 | + // so that every multiplication below fits a `u64` at any frame count. | ||
| 295 | + while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) { | ||
| 296 | + (num, den) = (num.div_ceil(2), den.div_ceil(2)); | ||
| 297 | + } | ||
| 298 | + Ok(Self { | ||
| 299 | + source: num.max(1) as u32, | ||
| 300 | + timeline: den.max(1) as u32, | ||
| 301 | + }) | ||
| 302 | + } | ||
| 303 | + | ||
| 304 | + pub fn is_real_time(self) -> bool { | ||
| 305 | + self.source == self.timeline | ||
| 306 | + } | ||
| 307 | + | ||
| 308 | + /// As a multiplier of the timeline's rate: what a *file's* own frame rate | ||
| 309 | + /// is, given the timeline's, for a library row that names it. | ||
| 310 | + pub fn as_f64(self) -> f64 { | ||
| 311 | + f64::from(self.source) / f64::from(self.timeline) | ||
| 312 | + } | ||
| 313 | + | ||
| 314 | + /// Which frame of the file the `frame`th timeline-rate frame of it is: | ||
| 315 | + /// floored, [`Speed::source_at`]'s half of the pair. | ||
| 316 | + pub fn source_at(self, frame: u32) -> u32 { | ||
| 317 | + (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline)) | ||
| 318 | + .min(u64::from(u32::MAX)) as u32 | ||
| 319 | + } | ||
| 320 | + | ||
| 321 | + /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first | ||
| 322 | + /// timeline-rate frame that shows source frame `source_frame` -- which is | ||
| 323 | + /// the stamp playback puts on a decoded picture, and, applied to a file's | ||
| 324 | + /// frame *count*, how long that file is in timeline frames. | ||
| 325 | + pub fn timeline_at(self, source_frame: u32) -> u32 { | ||
| 326 | + (u64::from(source_frame) * u64::from(self.timeline)) | ||
| 327 | + .div_ceil(u64::from(self.source)) | ||
| 328 | + .min(u64::from(u32::MAX)) as u32 | ||
| 329 | + } | ||
| 330 | +} | ||
| 331 | + | ||
| 332 | +/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its | ||
| 333 | +/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it. | ||
| 334 | +fn gcd(a: u64, b: u64) -> u64 { | ||
| 335 | + match b { | ||
| 336 | + 0 => a.max(1), | ||
| 337 | + b => gcd(b, a % b), | ||
| 338 | + } | ||
| 339 | +} | ||
| 340 | + | ||
| 224 | /// A half-open `[in_frame, out_frame)` range of frames of source | 341 | /// A half-open `[in_frame, out_frame)` range of frames of source |
| 225 | /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). | 342 | /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). |
| 226 | /// Never empty. | 343 | /// Never empty. |
| 344 | +/// | ||
| 345 | +/// Counted at the **timeline's** frame rate, not the file's: a source shot at | ||
| 346 | +/// another rate is converted at the decoder's door ([`Rate`]), so every edit | ||
| 347 | +/// here is frames of one clock. | ||
| 227 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] | 348 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 228 | pub struct Clip { | 349 | pub struct Clip { |
| 229 | /// Timeline frame the clip's first frame is shown at. Meaningless on a | 350 | /// Timeline frame the clip's first frame is shown at. Meaningless on a |
| @@ -366,21 +487,29 @@ struct LaneData { | |||
| 366 | kind: LaneKind, | 487 | kind: LaneKind, |
| 367 | /// Sorted by `start` and disjoint ([`sorted_disjoint`]). | 488 | /// Sorted by `start` and disjoint ([`sorted_disjoint`]). |
| 368 | clips: Vec<Clip>, | 489 | clips: Vec<Clip>, |
| 490 | + /// How loud this lane plays, in dB, `0.0` for one nobody has touched -- | ||
| 491 | + /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what | ||
| 492 | + /// makes it a different thing from a clip's equalizer: it moves everything | ||
| 493 | + /// on the track by the same amount, cuts included. Meaningless on a video | ||
| 494 | + /// lane, where it is kept at 0 and asked by nothing. | ||
| 495 | + gain_db: f32, | ||
| 369 | } | 496 | } |
| 370 | 497 | ||
| 371 | impl LaneData { | 498 | impl LaneData { |
| 499 | + fn new(kind: LaneKind, clips: Vec<Clip>) -> Self { | ||
| 500 | + Self { | ||
| 501 | + kind, | ||
| 502 | + clips, | ||
| 503 | + gain_db: 0.0, | ||
| 504 | + } | ||
| 505 | + } | ||
| 506 | + | ||
| 372 | /// The two lanes a project starts with: `V1` then `A1`, in display order. | 507 | /// The two lanes a project starts with: `V1` then `A1`, in display order. |
| 373 | /// One place, because a freshly opened file is exactly this pair. | 508 | /// One place, because a freshly opened file is exactly this pair. |
| 374 | fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> { | 509 | fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> { |
| 375 | vec![ | 510 | vec![ |
| 376 | - LaneData { | 511 | + LaneData::new(LaneKind::Video, video), |
| 377 | - kind: LaneKind::Video, | 512 | + LaneData::new(LaneKind::Audio, audio), |
| 378 | - clips: video, | ||
| 379 | - }, | ||
| 380 | - LaneData { | ||
| 381 | - kind: LaneKind::Audio, | ||
| 382 | - clips: audio, | ||
| 383 | - }, | ||
| 384 | ] | 513 | ] |
| 385 | } | 514 | } |
| 386 | } | 515 | } |
| @@ -489,6 +618,12 @@ pub struct Project { | |||
| 489 | /// Never rolled back by an undo: an id retired by an undone split must not | 618 | /// Never rolled back by an undo: an id retired by an undone split must not |
| 490 | /// come back and group two clips that were never together. | 619 | /// come back and group two clips that were never together. |
| 491 | next_link: u32, | 620 | next_link: u32, |
| 621 | + /// The master limiter every lane's sound is summed *through* | ||
| 622 | + /// ([`Project::limiter`]). Off by default, and not in the lane list, which | ||
| 623 | + /// is what the history snapshots hold: it is a setting on the mix, like the | ||
| 624 | + /// project's resolution is a setting on the picture, and neither is an undo | ||
| 625 | + /// step. | ||
| 626 | + limiter: Limiter, | ||
| 492 | } | 627 | } |
| 493 | 628 | ||
| 494 | impl Project { | 629 | impl Project { |
| @@ -517,6 +652,7 @@ impl Project { | |||
| 517 | color: Vec::new(), | 652 | color: Vec::new(), |
| 518 | history: Vec::new(), | 653 | history: Vec::new(), |
| 519 | next_link: 1, | 654 | next_link: 1, |
| 655 | + limiter: Limiter::default(), | ||
| 520 | } | 656 | } |
| 521 | } | 657 | } |
| 522 | 658 | ||
| @@ -554,7 +690,7 @@ impl Project { | |||
| 554 | } | 690 | } |
| 555 | let lanes: Vec<LaneData> = lanes | 691 | let lanes: Vec<LaneData> = lanes |
| 556 | .into_iter() | 692 | .into_iter() |
| 557 | - .map(|(kind, clips)| LaneData { kind, clips }) | 693 | + .map(|(kind, clips)| LaneData::new(kind, clips)) |
| 558 | .collect(); | 694 | .collect(); |
| 559 | for (data, lane) in lanes.iter().zip(handles(&lanes)) { | 695 | for (data, lane) in lanes.iter().zip(handles(&lanes)) { |
| 560 | let name = lane.label(); | 696 | let name = lane.label(); |
| @@ -624,6 +760,7 @@ impl Project { | |||
| 624 | color, | 760 | color, |
| 625 | history: Vec::new(), | 761 | history: Vec::new(), |
| 626 | next_link, | 762 | next_link, |
| 763 | + limiter: Limiter::default(), | ||
| 627 | }) | 764 | }) |
| 628 | } | 765 | } |
| 629 | 766 | ||
| @@ -659,13 +796,71 @@ impl Project { | |||
| 659 | /// ([`Project::from_parts`]); nothing plays until something is placed. | 796 | /// ([`Project::from_parts`]); nothing plays until something is placed. |
| 660 | pub fn add_lane(&mut self, kind: LaneKind) -> Lane { | 797 | pub fn add_lane(&mut self, kind: LaneKind) -> Lane { |
| 661 | self.snapshot(); | 798 | self.snapshot(); |
| 662 | - self.lanes.push(LaneData { | 799 | + self.lanes.push(LaneData::new(kind, Vec::new())); |
| 663 | - kind, | ||
| 664 | - clips: Vec::new(), | ||
| 665 | - }); | ||
| 666 | Lane::new(kind, self.lane_count(kind) - 1) | 800 | Lane::new(kind, self.lane_count(kind) - 1) |
| 667 | } | 801 | } |
| 668 | 802 | ||
| 803 | + /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and | ||
| 804 | + /// one undo step like it, which restores the lane where it stood. | ||
| 805 | + /// | ||
| 806 | + /// Refused, changing nothing, while the lane holds anything: the refusal | ||
| 807 | + /// names the clips (file and first frame), because a track removal that | ||
| 808 | + /// deleted takes with it would be the one edit nobody sees coming. Refused | ||
| 809 | + /// too for the last lane of its kind, which is `V1` or `A1`: those two are | ||
| 810 | + /// where an import and a paste land ([`Project::paste`] takes lane 0 of each | ||
| 811 | + /// kind and *skips* a kind that is not there), so a project without one | ||
| 812 | + /// would swallow half of every file dropped on it, silently. | ||
| 813 | + /// | ||
| 814 | + /// The lanes below it move up one `ord`, so a handle a caller was holding | ||
| 815 | + /// (a selection, an open card) names the lane after it from here on -- the | ||
| 816 | + /// one thing a front-end owes this call. | ||
| 817 | + pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> { | ||
| 818 | + let Some(i) = self.index(lane) else { | ||
| 819 | + return Err(format!("there is no {} to remove", lane.label()).into()); | ||
| 820 | + }; | ||
| 821 | + if self.lane_count(lane.kind) == 1 { | ||
| 822 | + return Err(format!( | ||
| 823 | + "{} is the only {} track: every import lands on it", | ||
| 824 | + lane.label(), | ||
| 825 | + match lane.kind { | ||
| 826 | + LaneKind::Video => "video", | ||
| 827 | + LaneKind::Audio => "audio", | ||
| 828 | + } | ||
| 829 | + ) | ||
| 830 | + .into()); | ||
| 831 | + } | ||
| 832 | + let clips = &self.lanes[i].clips; | ||
| 833 | + if !clips.is_empty() { | ||
| 834 | + // Three names and a count: a lane can hold forty clips and a | ||
| 835 | + // refusal nobody reads to the end says nothing at all. | ||
| 836 | + let named: Vec<String> = clips | ||
| 837 | + .iter() | ||
| 838 | + .take(3) | ||
| 839 | + .map(|c| { | ||
| 840 | + let name = self.sources.get(c.source).map_or_else( | ||
| 841 | + || format!("source {}", c.source), | ||
| 842 | + |s| s.path.display().to_string(), | ||
| 843 | + ); | ||
| 844 | + format!("{name} at frame {}", c.start) | ||
| 845 | + }) | ||
| 846 | + .collect(); | ||
| 847 | + let rest = match clips.len().saturating_sub(named.len()) { | ||
| 848 | + 0 => String::new(), | ||
| 849 | + n => format!(" and {n} more"), | ||
| 850 | + }; | ||
| 851 | + return Err(format!( | ||
| 852 | + "{} still holds {}{rest}: delete those clips (or drag them to \ | ||
| 853 | + another track) first", | ||
| 854 | + lane.label(), | ||
| 855 | + named.join(", ") | ||
| 856 | + ) | ||
| 857 | + .into()); | ||
| 858 | + } | ||
| 859 | + self.snapshot(); | ||
| 860 | + self.lanes.remove(i); | ||
| 861 | + Ok(()) | ||
| 862 | + } | ||
| 863 | + | ||
| 669 | /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is | 864 | /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is |
| 670 | /// not there. The one place a handle becomes a position. | 865 | /// not there. The one place a handle becomes a position. |
| 671 | fn index(&self, lane: Lane) -> Option<usize> { | 866 | fn index(&self, lane: Lane) -> Option<usize> { |
| @@ -748,10 +943,20 @@ impl Project { | |||
| 748 | /// | 943 | /// |
| 749 | /// Refused, changing nothing, while any clip still plays from it: the | 944 | /// Refused, changing nothing, while any clip still plays from it: the |
| 750 | /// refusal names the lanes and how many clips each holds, so a caller can | 945 | /// refusal names the lanes and how many clips each holds, so a caller can |
| 751 | - /// say what has to be deleted first. Refused too for the last entry left, | 946 | + /// say what has to be deleted first. The *last* entry goes like any other |
| 752 | - /// because a project that names no file cannot be reopened | 947 | + /// -- a project may name no file at all, which is an empty library over an |
| 753 | - /// (`PlaybackSession::open_project`) and the timeline's audio parameters | 948 | + /// empty timeline (nothing can play, since a clip would have refused the |
| 754 | - /// are read off source 0. | 949 | + /// removal). What a front-end does with that is its own decision: `edith`'s |
| 950 | + /// window goes back to the empty state it launches in, and | ||
| 951 | + /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project) | ||
| 952 | + /// refuses to write a project that names nothing, because no such file | ||
| 953 | + /// could be opened again. | ||
| 954 | + /// | ||
| 955 | + /// Every index past `idx` moves down by one, so a caller holding a *raw* | ||
| 956 | + /// source index of its own -- a clipboard, which is the one thing outside | ||
| 957 | + /// this type that does -- has to fix it up or drop it, or a paste plays a | ||
| 958 | + /// different file. [`PlaybackSession::remove_source`] hands back the index | ||
| 959 | + /// that went for exactly that. | ||
| 755 | /// | 960 | /// |
| 756 | /// ponytail: this retires the undo stack. `history` holds lanes alone, so a | 961 | /// ponytail: this retires the undo stack. `history` holds lanes alone, so a |
| 757 | /// snapshot older than the removal can name the very source being removed | 962 | /// snapshot older than the removal can name the very source being removed |
| @@ -766,12 +971,6 @@ impl Project { | |||
| 766 | return Err(format!("there is no source {idx} to remove").into()); | 971 | return Err(format!("there is no source {idx} to remove").into()); |
| 767 | }; | 972 | }; |
| 768 | let name = source.path.display().to_string(); | 973 | let name = source.path.display().to_string(); |
| 769 | - // Asked before the clips are counted: with one file left the answer is | ||
| 770 | - // the same whatever plays, and "the only file" is the more useful half | ||
| 771 | - // of it. | ||
| 772 | - if self.sources.len() == 1 { | ||
| 773 | - return Err(format!("{name} is the only file this project names").into()); | ||
| 774 | - } | ||
| 775 | let used: Vec<String> = handles(&self.lanes) | 974 | let used: Vec<String> = handles(&self.lanes) |
| 776 | .into_iter() | 975 | .into_iter() |
| 777 | .zip(&self.lanes) | 976 | .zip(&self.lanes) |
| @@ -815,9 +1014,16 @@ impl Project { | |||
| 815 | /// only the ones a clip names. | 1014 | /// only the ones a clip names. |
| 816 | /// | 1015 | /// |
| 817 | /// One exception, and it is the emptied timeline's: a project no clip plays | 1016 | /// One exception, and it is the emptied timeline's: a project no clip plays |
| 818 | - /// from still keeps source 0. It is the file a session is scaffolded from -- | 1017 | + /// from still keeps its first source, if it has one. A file is what a |
| 819 | - /// its frame rate is the timeline's and is written nowhere else -- so a save | 1018 | + /// reopened project scaffolds itself from -- the frame rate is written |
| 820 | - /// that pruned it would write a project that cannot be loaded back at all. | 1019 | + /// nowhere else -- so a save that pruned the last of them would write a |
| 1020 | + /// project that cannot be loaded back at all. | ||
| 1021 | + /// | ||
| 1022 | + /// What comes out is *not* ordered by anything a reader may assume: first | ||
| 1023 | + /// use, lane by lane, means the entry at index 0 can be a still or a song | ||
| 1024 | + /// whatever the session was scaffolded from. `PlaybackSession::open_project` | ||
| 1025 | + /// picks its rate and its audio reference by what a source *is*, never by | ||
| 1026 | + /// where it sits. | ||
| 821 | pub fn without_orphan_sources(&self) -> Parts { | 1027 | pub fn without_orphan_sources(&self) -> Parts { |
| 822 | let mut moved = vec![None; self.sources.len()]; | 1028 | let mut moved = vec![None; self.sources.len()]; |
| 823 | let mut sources = Vec::new(); | 1029 | let mut sources = Vec::new(); |
| @@ -870,6 +1076,92 @@ impl Project { | |||
| 870 | ) | 1076 | ) |
| 871 | } | 1077 | } |
| 872 | 1078 | ||
| 1079 | + /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for | ||
| 1080 | + /// a lane that is not there. Whole-lane and whole-band -- every clip on the | ||
| 1081 | + /// track moves by it, which is what makes it a different control from a | ||
| 1082 | + /// clip's equalizer (one frequency range of one take) and from the master | ||
| 1083 | + /// volume (what this machine monitors at, which no file carries). | ||
| 1084 | + pub fn lane_gain_db(&self, lane: Lane) -> f32 { | ||
| 1085 | + self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db) | ||
| 1086 | + } | ||
| 1087 | + | ||
| 1088 | + /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`]. | ||
| 1089 | + /// One undo step like every other edit -- it is in the lane list, so an | ||
| 1090 | + /// undo restores it with the rest. `false`, and no history, for a lane that | ||
| 1091 | + /// is not there, for a value that is not finite, and for one already set. | ||
| 1092 | + pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { | ||
| 1093 | + let Some(i) = self.index(lane) else { | ||
| 1094 | + return false; | ||
| 1095 | + }; | ||
| 1096 | + if !db.is_finite() { | ||
| 1097 | + return false; | ||
| 1098 | + } | ||
| 1099 | + let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB); | ||
| 1100 | + if self.lanes[i].gain_db == db { | ||
| 1101 | + return false; | ||
| 1102 | + } | ||
| 1103 | + self.snapshot(); | ||
| 1104 | + self.lanes[i].gain_db = db; | ||
| 1105 | + true | ||
| 1106 | + } | ||
| 1107 | + | ||
| 1108 | + /// Every lane's volume in dB, in display order -- what a save writes, | ||
| 1109 | + /// beside the lanes [`Project::without_orphan_sources`] hands back. | ||
| 1110 | + pub fn lane_gains(&self) -> Vec<f32> { | ||
| 1111 | + self.lanes.iter().map(|l| l.gain_db).collect() | ||
| 1112 | + } | ||
| 1113 | + | ||
| 1114 | + /// The mix settings a *load* puts back: lane volumes in display order (a | ||
| 1115 | + /// short list leaves the rest at unity) and the master limiter, both | ||
| 1116 | + /// clamped as their setters clamp them. | ||
| 1117 | + /// | ||
| 1118 | + /// The load's own door, beside [`from_parts`](Project::from_parts): the | ||
| 1119 | + /// setters push an undo step, and a project that arrives one undo away from | ||
| 1120 | + /// a state it was never in is a project whose first ctrl+z is a surprise. | ||
| 1121 | + pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self { | ||
| 1122 | + for (data, &db) in self.lanes.iter_mut().zip(gains) { | ||
| 1123 | + if db.is_finite() { | ||
| 1124 | + data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB); | ||
| 1125 | + } | ||
| 1126 | + } | ||
| 1127 | + self.limiter = limiter.with_ceiling(limiter.ceiling_db); | ||
| 1128 | + self | ||
| 1129 | + } | ||
| 1130 | + | ||
| 1131 | + /// What each of [`audio_segments_from`](Project::audio_segments_from)'s | ||
| 1132 | + /// lanes is multiplied by on its way into the mix: the same lanes in the | ||
| 1133 | + /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0` | ||
| 1134 | + /// for a lane nobody has turned, which is a multiply f32 leaves alone -- | ||
| 1135 | + /// the bit-exact path. | ||
| 1136 | + pub fn audio_gains(&self) -> Vec<f32> { | ||
| 1137 | + self.audio_lanes() | ||
| 1138 | + .into_iter() | ||
| 1139 | + .map(|lane| db_to_linear(self.lane_gain_db(lane))) | ||
| 1140 | + .collect() | ||
| 1141 | + } | ||
| 1142 | + | ||
| 1143 | + /// The master limiter the mix is summed through. A project setting, not a | ||
| 1144 | + /// clip's and not a lane's: there is one mix. | ||
| 1145 | + pub fn limiter(&self) -> Limiter { | ||
| 1146 | + self.limiter | ||
| 1147 | + } | ||
| 1148 | + | ||
| 1149 | + /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false` | ||
| 1150 | + /// for a setting already in force. | ||
| 1151 | + /// | ||
| 1152 | + /// ponytail: not an undo step, for the reason the project resolution is not | ||
| 1153 | + /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the | ||
| 1154 | + /// lane list the history snapshots. Upgrade path is a history entry that | ||
| 1155 | + /// holds the mix settings beside the lanes. | ||
| 1156 | + pub fn set_limiter(&mut self, limiter: Limiter) -> bool { | ||
| 1157 | + let limiter = limiter.with_ceiling(limiter.ceiling_db); | ||
| 1158 | + if self.limiter == limiter { | ||
| 1159 | + return false; | ||
| 1160 | + } | ||
| 1161 | + self.limiter = limiter; | ||
| 1162 | + true | ||
| 1163 | + } | ||
| 1164 | + | ||
| 873 | /// What the clip at `idx` of `lane` plays through, or `None` for one that | 1165 | /// What the clip at `idx` of `lane` plays through, or `None` for one that |
| 874 | /// plays flat (and for an index that is not there) -- what a feeder and an | 1166 | /// plays flat (and for an index that is not there) -- what a feeder and an |
| 875 | /// export ask before they build an [`crate::eq::EqState`]. | 1167 | /// export ask before they build an [`crate::eq::EqState`]. |
| @@ -1541,42 +1833,106 @@ impl Project { | |||
| 1541 | true | 1833 | true |
| 1542 | } | 1834 | } |
| 1543 | 1835 | ||
| 1544 | - /// Move the clip at `idx` of `from` onto `to`, keeping the timeline frames | 1836 | + /// Move the clip at `idx` of `from` onto `to` with its head at timeline |
| 1545 | - /// it covers: the drag that rearranges takes across tracks. One snapshot, so | 1837 | + /// frame `start`: the drag that rearranges takes, along a track and across |
| 1546 | - /// one [`Project::undo`] puts it back where it was. | 1838 | + /// them alike. One snapshot, so one [`Project::undo`] puts it back where it |
| 1839 | + /// was. `start` at the clip's own is the pure lane change. | ||
| 1840 | + /// | ||
| 1841 | + /// The whole group travels the same distance, each half on the lane it | ||
| 1842 | + /// already sits on -- a link means "these cover one span on however many | ||
| 1843 | + /// lanes" ([`links_are_consistent`]), so a picture that slid away from its | ||
| 1844 | + /// sound would be a group no save could load. Only the dragged half changes | ||
| 1845 | + /// lane, and that is not a desync: a link names no lane at all. | ||
| 1547 | /// | 1846 | /// |
| 1548 | - /// Its group id travels with it, and that is not a desync: a link means | 1847 | + /// `start` is **clamped**, never refused, to the room the group has: no |
| 1549 | - /// "these cover one span on however many lanes" and names no lane at all | 1848 | + /// member crosses a neighbour on the lane it lands on, exactly as |
| 1550 | - /// (see [`links_are_consistent`]), so a picture moved from `V1` to `V2` is | 1849 | + /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand |
| 1551 | - /// still the same take as the sound under it. The span never changes here -- | 1850 | + /// dragging past a neighbour means "as far as it goes", and butting up |
| 1552 | - /// only which lane draws it. | 1851 | + /// against the take next door is how clips are laid end to end. The |
| 1852 | + /// tightest member's wall wins, so a sound half boxed in between two others | ||
| 1853 | + /// holds its picture still. | ||
| 1553 | /// | 1854 | /// |
| 1554 | - /// Refused, changing nothing, for a lane that is not there, an index that is | 1855 | + /// Refused, changing nothing and costing no undo step, for a lane that is |
| 1555 | - /// not there, a move onto the lane it is already on, a move across *kinds* | 1856 | + /// not there, an index that is not there, a move across *kinds* (a picture |
| 1556 | - /// (a picture cannot play on an audio lane, and the save it wrote would not | 1857 | + /// cannot play on an audio lane, and the save it wrote would not open |
| 1557 | - /// open again), and a landing that would touch another clip -- a move that | 1858 | + /// again), a head let go *inside* another clip or into a gap too narrow to |
| 1558 | - /// overwrote what it landed on would destroy a take the pointer never named, | 1859 | + /// hold this one -- a move that overwrote what it landed on would destroy a |
| 1559 | - /// which is what [`place`](Project::place) may do and a drag may not. | 1860 | + /// take the pointer never named, which is what [`place`](Project::place) |
| 1560 | - pub fn move_to_lane(&mut self, from: Lane, idx: usize, to: Lane) -> bool { | 1861 | + /// may do and a drag may not -- a half let go onto the lane its own partner |
| 1561 | - if from.kind != to.kind || from == to || self.index(to).is_none() { | 1862 | + /// is on, and a drop that changes neither lane nor frame, which is a clip |
| 1863 | + /// picked up and put back down, i.e. a click. | ||
| 1864 | + pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { | ||
| 1865 | + let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else { | ||
| 1866 | + return false; | ||
| 1867 | + }; | ||
| 1868 | + if from.kind != to.kind { | ||
| 1562 | return false; | 1869 | return false; |
| 1563 | } | 1870 | } |
| 1564 | - let Some(clip) = self.lane(from).get(idx).copied() else { | 1871 | + let members = self.group_of(from, idx).expect("the clip was found"); |
| 1872 | + let held = self.index(from).expect("the clip was found on it"); | ||
| 1873 | + // The two halves of one group would land on one span of one lane, which | ||
| 1874 | + // is the one thing a link may never mean. Refused rather than clamped: | ||
| 1875 | + // the partner moves the same distance, so there is no room for it | ||
| 1876 | + // anywhere on that lane. | ||
| 1877 | + if dest != held && members.iter().any(|&(l, _)| l == dest) { | ||
| 1565 | return false; | 1878 | return false; |
| 1566 | - }; | 1879 | + } |
| 1567 | - if self | 1880 | + let want = i64::from(start) - i64::from(clip.start); |
| 1568 | - .lane(to) | 1881 | + // How far the group may travel, in timeline frames and signed: every |
| 1569 | - .iter() | 1882 | + // member narrows it to the gap it is landing in, and what is left is |
| 1570 | - .any(|c| c.start < clip.end() && clip.start < c.end()) | 1883 | + // what the pointer is clamped to. |
| 1571 | - { | 1884 | + let (mut lo, mut hi) = (i64::MIN, i64::MAX); |
| 1885 | + for &(l, i) in &members { | ||
| 1886 | + let c = self.lanes[l].clips[i]; | ||
| 1887 | + let land = if (l, i) == (held, idx) { dest } else { l }; | ||
| 1888 | + // Which gap this member's walls are read off: its own place on the | ||
| 1889 | + // lane it stays on, and the frame the pointer named on the lane it | ||
| 1890 | + // is let go over. | ||
| 1891 | + let at = if land == l { c.start } else { start }; | ||
| 1892 | + let (mut wall_lo, mut wall_hi) = (0, u32::MAX); | ||
| 1893 | + for (j, other) in self.lanes[land].clips.iter().enumerate() { | ||
| 1894 | + if members.contains(&(land, j)) { | ||
| 1895 | + continue; | ||
| 1896 | + } | ||
| 1897 | + if other.start <= at && at < other.end() { | ||
| 1898 | + return false; | ||
| 1899 | + } | ||
| 1900 | + match other.end() <= at { | ||
| 1901 | + true => wall_lo = wall_lo.max(other.end()), | ||
| 1902 | + false => wall_hi = wall_hi.min(other.start), | ||
| 1903 | + } | ||
| 1904 | + } | ||
| 1905 | + if wall_hi - wall_lo < c.frames() { | ||
| 1906 | + return false; | ||
| 1907 | + } | ||
| 1908 | + lo = lo.max(i64::from(wall_lo) - i64::from(c.start)); | ||
| 1909 | + hi = hi.min(i64::from(wall_hi - c.frames()) - i64::from(c.start)); | ||
| 1910 | + } | ||
| 1911 | + if lo > hi { | ||
| 1912 | + return false; | ||
| 1913 | + } | ||
| 1914 | + let delta = want.clamp(lo, hi); | ||
| 1915 | + if delta == 0 && dest == held { | ||
| 1572 | return false; | 1916 | return false; |
| 1573 | } | 1917 | } |
| 1574 | self.snapshot(); | 1918 | self.snapshot(); |
| 1575 | - self.lane_mut(from).expect("checked above").remove(idx); | 1919 | + for &(l, i) in &members { |
| 1576 | - let clips = self.lane_mut(to).expect("checked above"); | 1920 | + let c = &mut self.lanes[l].clips[i]; |
| 1577 | - let at = clips.partition_point(|c| c.start < clip.start); | 1921 | + // In range by the walls above, which are `u32` frames throughout. |
| 1578 | - clips.insert(at, clip); | 1922 | + c.start = (i64::from(c.start) + delta) as u32; |
| 1579 | - debug_assert!(sorted_disjoint(clips)); | 1923 | + } |
| 1924 | + if dest != held { | ||
| 1925 | + let clip = self.lanes[held].clips.remove(idx); | ||
| 1926 | + let clips = &mut self.lanes[dest].clips; | ||
| 1927 | + let at = clips.partition_point(|c| c.start < clip.start); | ||
| 1928 | + clips.insert(at, clip); | ||
| 1929 | + } | ||
| 1930 | + debug_assert!(sorted_disjoint(&self.lanes[dest].clips)); | ||
| 1931 | + debug_assert!( | ||
| 1932 | + members | ||
| 1933 | + .iter() | ||
| 1934 | + .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)) | ||
| 1935 | + ); | ||
| 1580 | true | 1936 | true |
| 1581 | } | 1937 | } |
| 1582 | 1938 | ||
| @@ -1658,8 +2014,19 @@ impl Project { | |||
| 1658 | } | 2014 | } |
| 1659 | self.snapshot(); | 2015 | self.snapshot(); |
| 1660 | for (&(l, i), keep) in members.iter().zip(fitted) { | 2016 | for (&(l, i), keep) in members.iter().zip(fitted) { |
| 2017 | + let still = self.is_still(&self.lanes[l].clips[i]); | ||
| 1661 | let c = &mut self.lanes[l].clips[i]; | 2018 | let c = &mut self.lanes[l].clips[i]; |
| 1662 | match edge { | 2019 | match edge { |
| 2020 | + // A still has no earlier frame to walk an in-point back to -- | ||
| 2021 | + // every frame of it is the same picture -- so its head grows | ||
| 2022 | + // *forward*: the range it plays is however long the new room | ||
| 2023 | + // is, anchored at the source's frame 0. Bounded by `lo`, which | ||
| 2024 | + // is where the cap in `source_frames` is applied. | ||
| 2025 | + Edge::Start if still => { | ||
| 2026 | + c.in_frame = 0; | ||
| 2027 | + c.out_frame = keep; | ||
| 2028 | + c.start = to; | ||
| 2029 | + } | ||
| 1663 | Edge::Start => { | 2030 | Edge::Start => { |
| 1664 | // Non-negative by `lo`, which is what keeps the in-point on | 2031 | // Non-negative by `lo`, which is what keeps the in-point on |
| 1665 | // the source. | 2032 | // the source. |
| @@ -1700,9 +2067,24 @@ impl Project { | |||
| 1700 | // head than the timeline has room for -- a ripple delete | 2067 | // head than the timeline has room for -- a ripple delete |
| 1701 | // slides a clip back to frame 0 with its in-point wherever | 2068 | // slides a clip back to frame 0 with its in-point wherever |
| 1702 | // the cut left it -- and frame 0 is the other wall. | 2069 | // the cut left it -- and frame 0 is the other wall. |
| 1703 | - c.start | 2070 | + // |
| 1704 | - .saturating_sub(c.speed.room(c.in_frame)) | 2071 | + // A still is measured from its *tail* instead: it has no |
| 1705 | - .max(i.checked_sub(1).map_or(0, |p| clips[p].end())), | 2072 | + // in-point worth the name (every frame the same picture), so |
| 2073 | + // its head reaches exactly as far as its tail does -- out to | ||
| 2074 | + // the length the caller's table gives it, whole. Measured | ||
| 2075 | + // from the in-point it would have no head room at all, which | ||
| 2076 | + // is a placed picture whose left edge cannot be dragged out. | ||
| 2077 | + // No entry in the table means no growth, as it does at the | ||
| 2078 | + // other end. | ||
| 2079 | + if self.is_still(&c) { | ||
| 2080 | + c.end().saturating_sub( | ||
| 2081 | + c.speed | ||
| 2082 | + .room(source_frames.get(c.source).copied().unwrap_or(c.len())), | ||
| 2083 | + ) | ||
| 2084 | + } else { | ||
| 2085 | + c.start.saturating_sub(c.speed.room(c.in_frame)) | ||
| 2086 | + } | ||
| 2087 | + .max(i.checked_sub(1).map_or(0, |p| clips[p].end())), | ||
| 1706 | // One *frame of clip* always survives, and at a rate below | 2088 | // One *frame of clip* always survives, and at a rate below |
| 1707 | // real time one frame of clip is several frames of timeline | 2089 | // real time one frame of clip is several frames of timeline |
| 1708 | // ([`Speed::room`]): an edge dragged closer than that would | 2090 | // ([`Speed::room`]): an edge dragged closer than that would |
| @@ -1739,6 +2121,16 @@ impl Project { | |||
| 1739 | Some((lo, hi.max(lo))) | 2121 | Some((lo, hi.max(lo))) |
| 1740 | } | 2122 | } |
| 1741 | 2123 | ||
| 2124 | + /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose | ||
| 2125 | + /// every frame is the same picture, so which frame of it a clip's in-point | ||
| 2126 | + /// names is not a question -- what [`Project::trim`] lets grow at either | ||
| 2127 | + /// end. `false` for a source that is not there. | ||
| 2128 | + fn is_still(&self, clip: &Clip) -> bool { | ||
| 2129 | + self.sources | ||
| 2130 | + .get(clip.source) | ||
| 2131 | + .is_some_and(|s| crate::is_image(&s.path)) | ||
| 2132 | + } | ||
| 2133 | + | ||
| 1742 | /// The clips that move as one with the clip at `idx` of `lane` -- itself and | 2134 | /// The clips that move as one with the clip at `idx` of `lane` -- itself and |
| 1743 | /// whatever carries its link on the other lanes -- as `(lane storage index, | 2135 | /// whatever carries its link on the other lanes -- as `(lane storage index, |
| 1744 | /// clip index)` pairs. `None` for an index that is not there. | 2136 | /// clip index)` pairs. `None` for an index that is not there. |
| @@ -1881,7 +2273,12 @@ impl Project { | |||
| 1881 | // Nothing reaches past `at`: there is nothing to cut and nothing to | 2273 | // Nothing reaches past `at`: there is nothing to cut and nothing to |
| 1882 | // slide back, and a delete that changes nothing must not cost an undo | 2274 | // slide back, and a delete that changes nothing must not cost an undo |
| 1883 | // step (see [`snapshot`](Project::snapshot)). | 2275 | // step (see [`snapshot`](Project::snapshot)). |
| 1884 | - if !self.lanes.iter().flat_map(|l| &l.clips).any(|c| c.end() > at) { | 2276 | + if !self |
| 2277 | + .lanes | ||
| 2278 | + .iter() | ||
| 2279 | + .flat_map(|l| &l.clips) | ||
| 2280 | + .any(|c| c.end() > at) | ||
| 2281 | + { | ||
| 1885 | return false; | 2282 | return false; |
| 1886 | } | 2283 | } |
| 1887 | self.snapshot(); | 2284 | self.snapshot(); |
| @@ -3233,7 +3630,11 @@ mod tests { | |||
| 3233 | // A gap on one lane leaves the other's clip selectable there. | 3630 | // A gap on one lane leaves the other's clip selectable there. |
| 3234 | assert!(p.lift(Lane::A1, 0)); | 3631 | assert!(p.lift(Lane::A1, 0)); |
| 3235 | assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing"); | 3632 | assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing"); |
| 3236 | - assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(0), "indices moved with it"); | 3633 | + assert_eq!( |
| 3634 | + p.lane_clip_at(Lane::A1, 3), | ||
| 3635 | + Some(0), | ||
| 3636 | + "indices moved with it" | ||
| 3637 | + ); | ||
| 3237 | assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0)); | 3638 | assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0)); |
| 3238 | // A lane that is not there is not a panic. | 3639 | // A lane that is not there is not a panic. |
| 3239 | assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None); | 3640 | assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None); |
| @@ -3280,16 +3681,17 @@ mod tests { | |||
| 3280 | assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip"); | 3681 | assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip"); |
| 3281 | } | 3682 | } |
| 3282 | 3683 | ||
| 3283 | - /// The drag between tracks: the clip keeps its frames, one undo takes it | 3684 | + /// The drag between tracks: let go at the frames it already covers the clip |
| 3284 | - /// back, and every way it can be refused leaves the project untouched. | 3685 | + /// keeps them, one undo takes it back, and every way it can be refused |
| 3686 | + /// leaves the project untouched. | ||
| 3285 | #[test] | 3687 | #[test] |
| 3286 | - fn move_to_lane_keeps_the_frames_and_refuses_the_rest() { | 3688 | + fn move_clip_keeps_the_frames_and_refuses_the_rest() { |
| 3287 | let v2 = Lane::new(LaneKind::Video, 1); | 3689 | let v2 = Lane::new(LaneKind::Video, 1); |
| 3288 | let mut p = three(); | 3690 | let mut p = three(); |
| 3289 | assert_eq!(p.add_lane(LaneKind::Video), v2); | 3691 | assert_eq!(p.add_lane(LaneKind::Video), v2); |
| 3290 | let before = shape(&p); | 3692 | let before = shape(&p); |
| 3291 | 3693 | ||
| 3292 | - assert!(p.move_to_lane(Lane::V1, 1, v2), "V1's middle clip moves up"); | 3694 | + assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up"); |
| 3293 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]); | 3695 | assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]); |
| 3294 | assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2"); | 3696 | assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2"); |
| 3295 | assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched"); | 3697 | assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched"); |
| @@ -3298,17 +3700,21 @@ mod tests { | |||
| 3298 | assert!(p.undo()); | 3700 | assert!(p.undo()); |
| 3299 | assert_eq!(shape(&p), before); | 3701 | assert_eq!(shape(&p), before); |
| 3300 | 3702 | ||
| 3301 | - // A lane that is not there, the lane it is already on, an index that is | 3703 | + // A lane that is not there, the lane and frame it is already at, an |
| 3302 | - // not there, and a move across kinds: all refused, nothing changed. | 3704 | + // index that is not there, and a move across kinds: all refused, |
| 3705 | + // nothing changed. | ||
| 3303 | let history = p.history.len(); | 3706 | let history = p.history.len(); |
| 3304 | - for (from, idx, to) in [ | 3707 | + for (from, idx, to, start) in [ |
| 3305 | - (Lane::V1, 1, Lane::new(LaneKind::Video, 7)), | 3708 | + (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3), |
| 3306 | - (Lane::V1, 1, Lane::V1), | 3709 | + (Lane::V1, 1, Lane::V1, 3), |
| 3307 | - (Lane::V1, 9, v2), | 3710 | + (Lane::V1, 9, v2, 3), |
| 3308 | - (Lane::V1, 1, Lane::A1), | 3711 | + (Lane::V1, 1, Lane::A1, 3), |
| 3309 | - (Lane::A1, 1, v2), | 3712 | + (Lane::A1, 1, v2, 3), |
| 3310 | ] { | 3713 | ] { |
| 3311 | - assert!(!p.move_to_lane(from, idx, to), "{from:?} {idx} -> {to:?}"); | 3714 | + assert!( |
| 3715 | + !p.move_clip(from, idx, to, start), | ||
| 3716 | + "{from:?} {idx} -> {to:?} at {start}" | ||
| 3717 | + ); | ||
| 3312 | } | 3718 | } |
| 3313 | assert_eq!(shape(&p), before); | 3719 | assert_eq!(shape(&p), before); |
| 3314 | assert_eq!(p.history.len(), history, "a refusal snapshots nothing"); | 3720 | assert_eq!(p.history.len(), history, "a refusal snapshots nothing"); |
| @@ -3316,12 +3722,87 @@ mod tests { | |||
| 3316 | // Landing on another clip is refused rather than overwriting it: the | 3722 | // Landing on another clip is refused rather than overwriting it: the |
| 3317 | // pointer named the lane, never the take already sitting there. | 3723 | // pointer named the lane, never the take already sitting there. |
| 3318 | assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)"); | 3724 | assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)"); |
| 3319 | - assert!(!p.move_to_lane(Lane::V1, 1, v2), "[3,5) would land on it"); | 3725 | + assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it"); |
| 3320 | - assert!(p.move_to_lane(Lane::V1, 0, v2), "[0,3) merely abuts it"); | 3726 | + assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it"); |
| 3321 | assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]); | 3727 | assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]); |
| 3322 | assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]); | 3728 | assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]); |
| 3323 | } | 3729 | } |
| 3324 | 3730 | ||
| 3731 | + /// The drag *along* a track, which is the one every other editor has: the | ||
| 3732 | + /// clip lands on the frame the pointer let it go at, and stops dead against | ||
| 3733 | + /// the neighbour rather than overwriting it. | ||
| 3734 | + #[test] | ||
| 3735 | + fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() { | ||
| 3736 | + let sources = vec![Source::new(FILE, 0)]; | ||
| 3737 | + let lanes = vec![ | ||
| 3738 | + (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]), | ||
| 3739 | + (LaneKind::Audio, vec![clip(0, 0, 3, 0)]), | ||
| 3740 | + ]; | ||
| 3741 | + let mut p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts"); | ||
| 3742 | + let before = shape(&p); | ||
| 3743 | + | ||
| 3744 | + // Into the gap, exactly where it was let go -- nothing else moves. | ||
| 3745 | + assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5)); | ||
| 3746 | + assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]); | ||
| 3747 | + assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched"); | ||
| 3748 | + // Dragged past the clip in front of it: clamped to its wall, laid end | ||
| 3749 | + // to end with it, never over it. | ||
| 3750 | + assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0)); | ||
| 3751 | + assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]); | ||
| 3752 | + // One undo per drag, and both of them together are the state it started | ||
| 3753 | + // in -- the frames each clip plays never changed. | ||
| 3754 | + assert!(p.undo() && p.undo()); | ||
| 3755 | + assert_eq!(shape(&p), before); | ||
| 3756 | + | ||
| 3757 | + // A drop that changes nothing is a click, not an edit. | ||
| 3758 | + let history = p.history.len(); | ||
| 3759 | + assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10)); | ||
| 3760 | + assert_eq!(p.history.len(), history, "a refusal snapshots nothing"); | ||
| 3761 | + } | ||
| 3762 | + | ||
| 3763 | + /// A drag carries the whole take: the sound half travels exactly as far as | ||
| 3764 | + /// the picture does, and the tighter of their two walls stops both. | ||
| 3765 | + #[test] | ||
| 3766 | + fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() { | ||
| 3767 | + let mut p = three(); | ||
| 3768 | + assert!( | ||
| 3769 | + p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2), | ||
| 3770 | + "room to the right" | ||
| 3771 | + ); | ||
| 3772 | + let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids"); | ||
| 3773 | + assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped"); | ||
| 3774 | + // Something in the sound's way, and nothing at all in the picture's. | ||
| 3775 | + assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)"); | ||
| 3776 | + let before = shape(&p); | ||
| 3777 | + | ||
| 3778 | + assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right"); | ||
| 3779 | + assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did"); | ||
| 3780 | + assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it"); | ||
| 3781 | + links_are_consistent(&p.lanes).expect("one id per lane, one span"); | ||
| 3782 | + assert!(p.undo()); | ||
| 3783 | + assert_eq!(shape(&p), before, "one undo for the whole take"); | ||
| 3784 | + } | ||
| 3785 | + | ||
| 3786 | + /// The drag that does both at once -- another lane *and* another frame -- | ||
| 3787 | + /// which is what a pointer let go over a lane always names. | ||
| 3788 | + #[test] | ||
| 3789 | + fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() { | ||
| 3790 | + let v2 = Lane::new(LaneKind::Video, 1); | ||
| 3791 | + let mut p = three(); | ||
| 3792 | + assert_eq!(p.add_lane(LaneKind::Video), v2); | ||
| 3793 | + | ||
| 3794 | + assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20"); | ||
| 3795 | + assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]); | ||
| 3796 | + assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer"); | ||
| 3797 | + assert_eq!( | ||
| 3798 | + p.lane(Lane::A1)[2].start, | ||
| 3799 | + 20, | ||
| 3800 | + "its sound travelled the same distance" | ||
| 3801 | + ); | ||
| 3802 | + links_are_consistent(&p.lanes).expect("one id per lane, one span"); | ||
| 3803 | + assert_eq!(p.timeline_frames(), 24, "a move is not an insert"); | ||
| 3804 | + } | ||
| 3805 | + | ||
| 3325 | /// How long `FILE` is, which is what a trim's tail is allowed to reach: | 3806 | /// How long `FILE` is, which is what a trim's tail is allowed to reach: |
| 3326 | /// [`three`] cuts up all nine of its frames. | 3807 | /// [`three`] cuts up all nine of its frames. |
| 3327 | const SRC: &[u32] = &[9]; | 3808 | const SRC: &[u32] = &[9]; |
| @@ -3344,8 +3825,15 @@ mod tests { | |||
| 3344 | 3825 | ||
| 3345 | // ...and back out, no further than the clip behind it. | 3826 | // ...and back out, no further than the clip behind it. |
| 3346 | assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC)); | 3827 | assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC)); |
| 3347 | - assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour"); | 3828 | + assert_eq!( |
| 3348 | - assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall"); | 3829 | + shape(&p)[0][1], |
| 3830 | + clip(3, 3, 5, 0), | ||
| 3831 | + "stopped at the neighbour" | ||
| 3832 | + ); | ||
| 3833 | + assert!( | ||
| 3834 | + !p.trim(Lane::V1, 1, Edge::End, 8, SRC), | ||
| 3835 | + "already at the wall" | ||
| 3836 | + ); | ||
| 3349 | 3837 | ||
| 3350 | // One frame of clip always survives, however far back the pointer went. | 3838 | // One frame of clip always survives, however far back the pointer went. |
| 3351 | assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC)); | 3839 | assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC)); |
| @@ -3369,7 +3857,11 @@ mod tests { | |||
| 3369 | fn trimming_the_head_moves_the_in_point() { | 3857 | fn trimming_the_head_moves_the_in_point() { |
| 3370 | let mut p = three(); | 3858 | let mut p = three(); |
| 3371 | assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); | 3859 | assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); |
| 3372 | - assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front"); | 3860 | + assert_eq!( |
| 3861 | + shape(&p)[0][0], | ||
| 3862 | + clip(2, 2, 3, 0), | ||
| 3863 | + "two frames off the front" | ||
| 3864 | + ); | ||
| 3373 | assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2"); | 3865 | assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2"); |
| 3374 | assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap"); | 3866 | assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap"); |
| 3375 | assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again"); | 3867 | assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again"); |
| @@ -3406,11 +3898,69 @@ mod tests { | |||
| 3406 | ); | 3898 | ); |
| 3407 | assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there"); | 3899 | assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there"); |
| 3408 | assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); | 3900 | assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC)); |
| 3409 | - assert_eq!(shape(&p)[0], vec![clip(2, 7, 9, 0)], "the in-point followed"); | 3901 | + assert_eq!( |
| 3902 | + shape(&p)[0], | ||
| 3903 | + vec![clip(2, 7, 9, 0)], | ||
| 3904 | + "the in-point followed" | ||
| 3905 | + ); | ||
| 3410 | assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out"); | 3906 | assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out"); |
| 3411 | assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]); | 3907 | assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]); |
| 3412 | } | 3908 | } |
| 3413 | 3909 | ||
| 3910 | + /// A still is trimmed from its head exactly as it is from its tail: it has | ||
| 3911 | + /// no earlier frame to walk an in-point back to, so the wall is the length | ||
| 3912 | + /// the caller's table allows it, measured back from the tail. Measured from | ||
| 3913 | + /// the in-point -- which a placed picture has at 0 -- its left edge could | ||
| 3914 | + /// never be dragged outwards at all. | ||
| 3915 | + #[test] | ||
| 3916 | + fn a_stills_head_stretches_out_like_its_tail() { | ||
| 3917 | + const STILL: &str = "/nonexistent/card.png"; | ||
| 3918 | + /// What a still is held to, as `PlaybackSession` fills the table in. | ||
| 3919 | + const CAP: &[u32] = &[60]; | ||
| 3920 | + | ||
| 3921 | + let mut p = Project::single(STILL, 20); | ||
| 3922 | + assert!(p.lift(Lane::A1, 0), "a picture is silent"); | ||
| 3923 | + assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0"); | ||
| 3924 | + assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0))); | ||
| 3925 | + | ||
| 3926 | + // A source with no entry in the table may not grow, here as at the tail. | ||
| 3927 | + assert_eq!( | ||
| 3928 | + p.trim_room(Lane::V1, 0, Edge::Start, &[]), | ||
| 3929 | + Some((100, 119)), | ||
| 3930 | + "a length nobody told us buys no head room" | ||
| 3931 | + ); | ||
| 3932 | + assert_eq!( | ||
| 3933 | + p.trim_room(Lane::V1, 0, Edge::Start, CAP), | ||
| 3934 | + Some((60, 119)), | ||
| 3935 | + "back to a whole cap's worth, one frame of clip surviving" | ||
| 3936 | + ); | ||
| 3937 | + assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP)); | ||
| 3938 | + assert_eq!( | ||
| 3939 | + shape(&p)[0][0], | ||
| 3940 | + clip(80, 0, 40, 0), | ||
| 3941 | + "twenty frames longer, and still read from the source's first frame" | ||
| 3942 | + ); | ||
| 3943 | + // Past the cap is clamped, exactly as the tail is -- not refused. | ||
| 3944 | + assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP)); | ||
| 3945 | + assert_eq!( | ||
| 3946 | + shape(&p)[0][0], | ||
| 3947 | + clip(60, 0, 60, 0), | ||
| 3948 | + "a cap's worth, no more" | ||
| 3949 | + ); | ||
| 3950 | + // ...and the clip in front is the nearer wall of the two: no head trim | ||
| 3951 | + // may open an overlap. | ||
| 3952 | + assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP)); | ||
| 3953 | + assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0))); | ||
| 3954 | + assert_eq!( | ||
| 3955 | + p.trim_room(Lane::V1, 1, Edge::Start, CAP), | ||
| 3956 | + Some((85, 119)), | ||
| 3957 | + "up to the neighbour's last frame and not over it" | ||
| 3958 | + ); | ||
| 3959 | + assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP)); | ||
| 3960 | + assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it"); | ||
| 3961 | + assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap"); | ||
| 3962 | + } | ||
| 3963 | + | ||
| 3414 | /// Linked halves trim as one: a link is one span on however many lanes, so | 3964 | /// Linked halves trim as one: a link is one span on however many lanes, so |
| 3415 | /// the sound follows the picture's edge -- and the tightest wall of the two | 3965 | /// the sound follows the picture's edge -- and the tightest wall of the two |
| 3416 | /// is what stops both. | 3966 | /// is what stops both. |
| @@ -3423,7 +3973,10 @@ mod tests { | |||
| 3423 | assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC)); | 3973 | assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC)); |
| 3424 | assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0)); | 3974 | assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0)); |
| 3425 | assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed"); | 3975 | assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed"); |
| 3426 | - assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it"); | 3976 | + assert!( |
| 3977 | + p.trim(Lane::A1, 2, Edge::End, 8, SRC), | ||
| 3978 | + "either half drags it" | ||
| 3979 | + ); | ||
| 3427 | assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows"); | 3980 | assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows"); |
| 3428 | links_are_consistent(&p.lanes).expect("one id per lane, one span"); | 3981 | links_are_consistent(&p.lanes).expect("one id per lane, one span"); |
| 3429 | 3982 | ||
| @@ -3458,13 +4011,13 @@ mod tests { | |||
| 3458 | /// A moved half stays in its group: a link names a span, not a lane, so the | 4011 | /// A moved half stays in its group: a link names a span, not a lane, so the |
| 3459 | /// picture on `V2` is still the same take as the sound under it on `A1`. | 4012 | /// picture on `V2` is still the same take as the sound under it on `A1`. |
| 3460 | #[test] | 4013 | #[test] |
| 3461 | - fn move_to_lane_keeps_the_group() { | 4014 | + fn move_clip_keeps_the_group() { |
| 3462 | let v2 = Lane::new(LaneKind::Video, 1); | 4015 | let v2 = Lane::new(LaneKind::Video, 1); |
| 3463 | let mut p = three(); | 4016 | let mut p = three(); |
| 3464 | p.add_lane(LaneKind::Video); | 4017 | p.add_lane(LaneKind::Video); |
| 3465 | let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids"); | 4018 | let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids"); |
| 3466 | assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped"); | 4019 | assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped"); |
| 3467 | - assert!(p.move_to_lane(Lane::V1, 1, v2)); | 4020 | + assert!(p.move_clip(Lane::V1, 1, v2, 3)); |
| 3468 | assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it"); | 4021 | assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it"); |
| 3469 | links_are_consistent(&p.lanes).expect("one id per lane, one span"); | 4022 | links_are_consistent(&p.lanes).expect("one id per lane, one span"); |
| 3470 | assert_eq!( | 4023 | assert_eq!( |
| @@ -3784,10 +4337,10 @@ mod tests { | |||
| 3784 | } | 4337 | } |
| 3785 | 4338 | ||
| 3786 | /// The two edges of a removal: it retires the undo stack (the ponytail on | 4339 | /// The two edges of a removal: it retires the undo stack (the ponytail on |
| 3787 | - /// [`Project::remove_source`]), and the last entry standing cannot go -- | 4340 | + /// [`Project::remove_source`]), and the last entry goes like any other |
| 3788 | - /// source 0 is where a reopened project reads its frame rate. | 4341 | + /// once nothing plays it -- a project may name no file at all. |
| 3789 | #[test] | 4342 | #[test] |
| 3790 | - fn remove_source_retires_undo_and_keeps_the_last_file() { | 4343 | + fn remove_source_retires_undo_and_empties_the_library() { |
| 3791 | let mut p = two_sources(); | 4344 | let mut p = two_sources(); |
| 3792 | assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first"); | 4345 | assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first"); |
| 3793 | assert!(!p.history.is_empty(), "there is something to undo"); | 4346 | assert!(!p.history.is_empty(), "there is something to undo"); |
| @@ -3798,18 +4351,25 @@ mod tests { | |||
| 3798 | ); | 4351 | ); |
| 3799 | assert!(!p.undo(), "and so there is nothing left to undo"); | 4352 | assert!(!p.undo(), "and so there is nothing left to undo"); |
| 3800 | 4353 | ||
| 3801 | - // The last file standing stays, whatever plays from it: | 4354 | + // The last file standing is held to the one rule every row is -- what |
| 3802 | - // `PlaybackSession::open_project` refuses a project that names no | 4355 | + // plays cannot go -- and to no other. |
| 3803 | - // sources at all, and the timeline's frame rate lives in source 0. | ||
| 3804 | assert_eq!(p.sources().len(), 1); | 4356 | assert_eq!(p.sources().len(), 1); |
| 3805 | let refusal = p | 4357 | let refusal = p |
| 3806 | .remove_source(0) | 4358 | .remove_source(0) |
| 3807 | - .expect_err("the only source must stay") | 4359 | + .expect_err("its clips are still on the lanes") |
| 3808 | .to_string(); | 4360 | .to_string(); |
| 3809 | - assert!(refusal.contains("only file"), "{refusal}"); | 4361 | + assert!(refusal.contains("still plays"), "{refusal}"); |
| 3810 | - assert_eq!(p.sources().len(), 1); | 4362 | + assert_eq!(p.sources().len(), 1, "a refusal changes nothing"); |
| 4363 | + while p.delete_in(Lane::V1, 0) {} | ||
| 4364 | + p.remove_source(0) | ||
| 4365 | + .expect("the last row goes like any other"); | ||
| 3811 | assert!( | 4366 | assert!( |
| 3812 | - p.remove_source(1).is_err(), | 4367 | + p.sources().is_empty(), |
| 4368 | + "a project may name no file at all: an empty library over an empty timeline" | ||
| 4369 | + ); | ||
| 4370 | + assert_eq!(p.timeline_frames(), 0); | ||
| 4371 | + assert!( | ||
| 4372 | + p.remove_source(0).is_err(), | ||
| 3813 | "and an index that is not there is refused, not panicked on" | 4373 | "and an index that is not there is refused, not panicked on" |
| 3814 | ); | 4374 | ); |
| 3815 | } | 4375 | } |
| @@ -4392,6 +4952,87 @@ mod tests { | |||
| 4392 | assert_eq!(Speed::from_permille(2500).to_string(), "2.50x"); | 4952 | assert_eq!(Speed::from_permille(2500).to_string(), "2.50x"); |
| 4393 | } | 4953 | } |
| 4394 | 4954 | ||
| 4955 | + /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an | ||
| 4956 | + /// export encodes at a timeline frame is the one playback is holding there, | ||
| 4957 | + /// a file is as long in timeline frames as the seconds it lasts, and the two | ||
| 4958 | + /// compose so a speeded clip at another rate is exactly both. | ||
| 4959 | + #[test] | ||
| 4960 | + fn rate_composes_with_speed() { | ||
| 4961 | + // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976, | ||
| 4962 | + // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be | ||
| 4963 | + // the identity map or a single-rate project would move. | ||
| 4964 | + for (source_fps, timeline_fps) in [ | ||
| 4965 | + (24000. / 1001., 30.), | ||
| 4966 | + (30., 24000. / 1001.), | ||
| 4967 | + (60., 30.), | ||
| 4968 | + (25., 30.), | ||
| 4969 | + (30., 30.), | ||
| 4970 | + ] { | ||
| 4971 | + let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate"); | ||
| 4972 | + for n in 0..2000u32 { | ||
| 4973 | + let source = rate.source_at(n); | ||
| 4974 | + // The stamp is the *first* timeline-rate frame that shows it, so | ||
| 4975 | + // the picture on screen at `n` is the picture encoded at `n`. | ||
| 4976 | + let held = (0..=source + 4) | ||
| 4977 | + .filter(|&s| rate.timeline_at(s) <= n) | ||
| 4978 | + .next_back(); | ||
| 4979 | + assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}"); | ||
| 4980 | + } | ||
| 4981 | + // A file of `count` frames is `timeline_at(count)` frames long here, | ||
| 4982 | + // and its last one still reads a frame the file has. | ||
| 4983 | + for count in 1..500u32 { | ||
| 4984 | + let frames = rate.timeline_at(count); | ||
| 4985 | + assert!(frames >= 1, "a file is never zero frames long"); | ||
| 4986 | + assert!( | ||
| 4987 | + rate.source_at(frames - 1) < count, | ||
| 4988 | + "{source_fps} on {timeline_fps}: {count} frames reads past the file" | ||
| 4989 | + ); | ||
| 4990 | + } | ||
| 4991 | + // No drift: the mapping is one exact division of the *rate itself*, | ||
| 4992 | + // not an accumulation and not a rounded rate, so an hour in is as | ||
| 4993 | + // true as the first second. (Held to the real ratio of the two rates | ||
| 4994 | + // the caller asked for -- `as_f64` would be true of a wrong rate.) | ||
| 4995 | + for n in [1u32, 100, 10_000, 500_000, 3_000_000] { | ||
| 4996 | + let want = f64::from(n) * source_fps / timeline_fps; | ||
| 4997 | + assert!( | ||
| 4998 | + (f64::from(rate.source_at(n)) - want).abs() < 1., | ||
| 4999 | + "{source_fps} on {timeline_fps}: frame {n} drifted" | ||
| 5000 | + ); | ||
| 5001 | + } | ||
| 5002 | + } | ||
| 5003 | + // The timeline's own rate is the identity, whichever way it is written. | ||
| 5004 | + assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time()); | ||
| 5005 | + assert!( | ||
| 5006 | + Rate::from_fps(30.0004, 30.) | ||
| 5007 | + .expect("30.0004 over 30") | ||
| 5008 | + .is_real_time(), | ||
| 5009 | + "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001" | ||
| 5010 | + ); | ||
| 5011 | + // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the | ||
| 5012 | + // one thing `matches_timeline` refuses a file for now that the rate gate | ||
| 5013 | + // is gone. | ||
| 5014 | + assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all"); | ||
| 5015 | + assert!(Rate::from_fps(30., f64::NAN).is_err()); | ||
| 5016 | + for n in 0..1000 { | ||
| 5017 | + assert_eq!(Rate::REAL_TIME.source_at(n), n); | ||
| 5018 | + assert_eq!(Rate::REAL_TIME.timeline_at(n), n); | ||
| 5019 | + } | ||
| 5020 | + // ...and the composition, in the order the decoder's door applies it: | ||
| 5021 | + // the speed picks the clip's (timeline-rate) frame, the rate picks the | ||
| 5022 | + // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two | ||
| 5023 | + // timeline frames per frame shown, each of them exactly 800/1001 of a | ||
| 5024 | + // file frame. | ||
| 5025 | + let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30"); | ||
| 5026 | + let speed = Speed::from_permille(2000); | ||
| 5027 | + for d in 0..100u32 { | ||
| 5028 | + assert_eq!( | ||
| 5029 | + rate.source_at(speed.source_at(d)), | ||
| 5030 | + (u64::from(d) * 2 * 800 / 1001) as u32, | ||
| 5031 | + "2x of a 23.976 fps file at timeline frame {d}" | ||
| 5032 | + ); | ||
| 5033 | + } | ||
| 5034 | + } | ||
| 5035 | + | ||
| 4395 | /// The mapping a speed changes, and the one it does not: a 2x clip reads two | 5036 | /// The mapping a speed changes, and the one it does not: a 2x clip reads two |
| 4396 | /// source frames per timeline frame and still starts at its own in-point, | 5037 | /// source frames per timeline frame and still starts at its own in-point, |
| 4397 | /// and a half-speed one shows every source frame twice. | 5038 | /// and a half-speed one shows every source frame twice. |
| @@ -4521,7 +5162,12 @@ mod tests { | |||
| 4521 | } | 5162 | } |
| 4522 | let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 }; | 5163 | let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 }; |
| 4523 | let idx = next(4) as usize; | 5164 | let idx = next(4) as usize; |
| 4524 | - let _ = match next(15) { | 5165 | + let _ = match next(16) { |
| 5166 | + // A clip dragged along its own lane to wherever the pointer | ||
| 5167 | + // let it go: the op that moves a placement without changing | ||
| 5168 | + // what it plays, so what it may not do is land on top of the | ||
| 5169 | + // neighbour it was dragged at. | ||
| 5170 | + 15 => p.move_clip(lane, idx, lane, frame), | ||
| 4525 | // ...and a second `place`, so a punch lands inside a clip | 5171 | // ...and a second `place`, so a punch lands inside a clip |
| 4526 | // far more often than one op in fourteen would put it there. | 5172 | // far more often than one op in fourteen would put it there. |
| 4527 | 14 => p.place(lane, frame, copied), | 5173 | 14 => p.place(lane, frame, copied), |
| @@ -4697,6 +5343,53 @@ mod tests { | |||
| 4697 | assert_eq!(shape(&p), shape(&three())); | 5343 | assert_eq!(shape(&p), shape(&three())); |
| 4698 | } | 5344 | } |
| 4699 | 5345 | ||
| 5346 | + /// The add taken back: an empty lane comes off, a lane holding clips never | ||
| 5347 | + /// does (and says which clips), the last lane of a kind never does, the | ||
| 5348 | + /// lanes below the one that went move up an `ord`, and one undo puts it | ||
| 5349 | + /// back where it stood. | ||
| 5350 | + #[test] | ||
| 5351 | + fn an_empty_lane_comes_off_again() { | ||
| 5352 | + let mut p = three(); | ||
| 5353 | + let v2 = p.add_lane(LaneKind::Video); | ||
| 5354 | + let v3 = p.add_lane(LaneKind::Video); | ||
| 5355 | + assert!(p.place(v3, 0, clip(0, 0, 3, 0))); | ||
| 5356 | + let why = |r: crate::Result<()>| r.expect_err("refused").to_string(); | ||
| 5357 | + let history = p.history.len(); | ||
| 5358 | + | ||
| 5359 | + // The last lane of its kind stays: `V1`/`A1` are where an import and a | ||
| 5360 | + // paste land, and a project missing one would swallow half of a file | ||
| 5361 | + // dropped on it. | ||
| 5362 | + assert!(why(p.remove_lane(Lane::A1)).contains("only audio track")); | ||
| 5363 | + assert_eq!( | ||
| 5364 | + why(p.remove_lane(Lane::new(LaneKind::Video, 9))), | ||
| 5365 | + "there is no V10 to remove" | ||
| 5366 | + ); | ||
| 5367 | + | ||
| 5368 | + // A lane with clips on it refuses and names them: a track removal never | ||
| 5369 | + // deletes a take. | ||
| 5370 | + let refusal = why(p.remove_lane(v3)); | ||
| 5371 | + assert!(refusal.contains("V3 still holds"), "{refusal}"); | ||
| 5372 | + assert!(refusal.contains(FILE), "{refusal}"); | ||
| 5373 | + assert!(refusal.contains("at frame 0"), "{refusal}"); | ||
| 5374 | + assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there"); | ||
| 5375 | + assert_eq!(p.history.len(), history, "a refusal snapshots nothing"); | ||
| 5376 | + | ||
| 5377 | + // The empty one in the middle goes, and `V3` becomes `V2` -- clip and | ||
| 5378 | + // all. | ||
| 5379 | + p.remove_lane(v2).expect("V2 is empty"); | ||
| 5380 | + assert_eq!(p.lane_count(LaneKind::Video), 2); | ||
| 5381 | + assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]); | ||
| 5382 | + assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up"); | ||
| 5383 | + assert_eq!(p.history.len(), history + 1, "one snapshot per removal"); | ||
| 5384 | + invariants_hold(&p, "remove V2"); | ||
| 5385 | + | ||
| 5386 | + // ...and one stroke puts the empty lane back above it. | ||
| 5387 | + assert!(p.undo()); | ||
| 5388 | + assert_eq!(p.lane_count(LaneKind::Video), 3); | ||
| 5389 | + assert!(p.lane(v2).is_empty(), "back where it stood, still empty"); | ||
| 5390 | + assert_eq!(p.lane_spans(v3), vec![(0, 3)]); | ||
| 5391 | + } | ||
| 5392 | + | ||
| 4700 | /// The grouping rule across more than two lanes: a link id is one *span*, | 5393 | /// The grouping rule across more than two lanes: a link id is one *span*, |
| 4701 | /// on however many lanes carry it -- not a video/audio pair and not a | 5394 | /// on however many lanes carry it -- not a video/audio pair and not a |
| 4702 | /// pairing by `ord`. So a split shares an id with every lane whose half | 5395 | /// pairing by `ord`. So a split shares an id with every lane whose half |
| @@ -4758,14 +5451,8 @@ mod tests { | |||
| 4758 | speed: Speed::NORMAL, | 5451 | speed: Speed::NORMAL, |
| 4759 | }; | 5452 | }; |
| 4760 | let lanes = vec![ | 5453 | let lanes = vec![ |
| 4761 | - LaneData { | 5454 | + LaneData::new(LaneKind::Video, vec![linked(3, 4)]), |
| 4762 | - kind: LaneKind::Video, | 5455 | + LaneData::new(LaneKind::Video, vec![linked(5, 4)]), |
| 4763 | - clips: vec![linked(3, 4)], | ||
| 4764 | - }, | ||
| 4765 | - LaneData { | ||
| 4766 | - kind: LaneKind::Video, | ||
| 4767 | - clips: vec![linked(5, 4)], | ||
| 4768 | - }, | ||
| 4769 | ]; | 5456 | ]; |
| 4770 | assert_eq!( | 5457 | assert_eq!( |
| 4771 | links_are_consistent(&lanes).unwrap_err().to_string(), | 5458 | links_are_consistent(&lanes).unwrap_err().to_string(), |
| @@ -4780,7 +5467,7 @@ mod tests { | |||
| 4780 | /// checked at the untrusted door and no edit can produce these. | 5467 | /// checked at the untrusted door and no edit can produce these. |
| 4781 | #[test] | 5468 | #[test] |
| 4782 | fn a_group_may_span_any_lane() { | 5469 | fn a_group_may_span_any_lane() { |
| 4783 | - let lane = |kind, clips: Vec<Clip>| LaneData { kind, clips }; | 5470 | + let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips); |
| 4784 | let one = |start: u32, end: u32, link| Clip { | 5471 | let one = |start: u32, end: u32, link| Clip { |
| 4785 | start, | 5472 | start, |
| 4786 | in_frame: start, | 5473 | in_frame: start, |
| @@ -4894,7 +5581,12 @@ mod tests { | |||
| 4894 | .unwrap_or(&clip(0, 0, 5, 0)); | 5581 | .unwrap_or(&clip(0, 0, 5, 0)); |
| 4895 | let lane = lanes[next(3) as usize]; | 5582 | let lane = lanes[next(3) as usize]; |
| 4896 | let idx = next(4) as usize; | 5583 | let idx = next(4) as usize; |
| 4897 | - let _ = match next(13) { | 5584 | + let _ = match next(14) { |
| 5585 | + // The drag, in the mix: a clip dragged along its own lane | ||
| 5586 | + // and onto another one, at a frame the pointer picked -- | ||
| 5587 | + // which is where the group rule and the sorted+disjoint one | ||
| 5588 | + // meet, since every half travels the same distance. | ||
| 5589 | + 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame), | ||
| 4898 | 10 => p.set_eq(lane, idx, Some(band_at(next(4)))), | 5590 | 10 => p.set_eq(lane, idx, Some(band_at(next(4)))), |
| 4899 | 11 => p.set_eq(lane, idx, None), | 5591 | 11 => p.set_eq(lane, idx, None), |
| 4900 | // A rate, which on many lanes is the group rule as well: | 5592 | // A rate, which on many lanes is the group rule as well: |
| @@ -160,8 +160,10 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { | |||
| 160 | } | 160 | } |
| 161 | } | 161 | } |
| 162 | 162 | ||
| 163 | -/// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC | 163 | +/// An AC-3 syncframe is not something an `mp4a` sample table holds, so the |
| 164 | -/// encoder here -- and that refusal is named, never a silent silent export. | 164 | +/// *copy* path names it and hands the export on to the re-encode (which decodes |
| 165 | +/// this very source: the downmix above is what it encodes). Named either way -- | ||
| 166 | +/// never a silent export. | ||
| 165 | #[test] | 167 | #[test] |
| 166 | fn an_ac3_source_refuses_an_mp4_audio_copy() { | 168 | fn an_ac3_source_refuses_an_mp4_audio_copy() { |
| 167 | let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else { | 169 | let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else { |
| @@ -169,7 +171,7 @@ fn an_ac3_source_refuses_an_mp4_audio_copy() { | |||
| 169 | }; | 171 | }; |
| 170 | let err = err.to_string(); | 172 | let err = err.to_string(); |
| 171 | assert!( | 173 | assert!( |
| 172 | - err.contains("needs AAC audio") && err.contains("AC-3"), | 174 | + err.contains("needs AAC in an mp4") && err.contains("AC-3"), |
| 173 | "unhelpful refusal: {err}" | 175 | "unhelpful refusal: {err}" |
| 174 | ); | 176 | ); |
| 175 | } | 177 | } |
| @@ -15,7 +15,7 @@ use std::path::{Path, PathBuf}; | |||
| 15 | use std::time::{Duration, Instant}; | 15 | use std::time::{Duration, Instant}; |
| 16 | 16 | ||
| 17 | use engine::export::{ExportSettings, Format}; | 17 | use engine::export::{ExportSettings, Format}; |
| 18 | -use engine::project::{LaneKind, Source, Speed}; | 18 | +use engine::project::{Lane, LaneKind, Source, Speed}; |
| 19 | use engine::scale::FitPolicy; | 19 | use engine::scale::FitPolicy; |
| 20 | use engine::{AudioSession, Clip, ExportHandle, Project}; | 20 | use engine::{AudioSession, Clip, ExportHandle, Project}; |
| 21 | 21 | ||
| @@ -55,8 +55,8 @@ fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { | |||
| 55 | /// One second of `test_av`, one second of hole, one second of `test_tone.mp3`. | 55 | /// One second of `test_av`, one second of hole, one second of `test_tone.mp3`. |
| 56 | /// | 56 | /// |
| 57 | /// Three things at once: a cut, a gap (which must arrive as silence), and a | 57 | /// Three things at once: a cut, a gap (which must arrive as silence), and a |
| 58 | -/// source the mp4 export flatly refuses — there is no AAC encoder here, so an | 58 | +/// source no mp4 sample table holds — an mp3, which the mp4 path decodes and |
| 59 | -/// mp3 on the timeline can *only* leave through this door. | 59 | +/// re-encodes today and once refused outright. |
| 60 | fn mixed_project() -> Project { | 60 | fn mixed_project() -> Project { |
| 61 | let clip = |start, source| Clip { | 61 | let clip = |start, source| Clip { |
| 62 | start, | 62 | start, |
| @@ -252,9 +252,239 @@ fn exports_the_timeline_as_a_flac() { | |||
| 252 | std::fs::remove_file(&out).unwrap(); | 252 | std::fs::remove_file(&out).unwrap(); |
| 253 | } | 253 | } |
| 254 | 254 | ||
| 255 | +/// The third audio row, and the one that used to be a licence note: `rusty_mp3` | ||
| 256 | +/// encodes it, and the file is read straight back through symphonia's mp3 | ||
| 257 | +/// decoder -- the very door an mp3 *import* comes in through, so an export can | ||
| 258 | +/// be dropped back onto the timeline it came from. | ||
| 259 | +/// | ||
| 260 | +/// The shape is checked loosely where MP3 cannot be exact: the encoder pads its | ||
| 261 | +/// tail to a whole 1152-frame frame and the decoder hands back the padding, so | ||
| 262 | +/// the length is asserted to within a frame instead of to the sample. What is | ||
| 263 | +/// exact is the edit -- audible, silent, audible -- and the fixtures' 1 Hz | ||
| 264 | +/// pulse inside the first second. | ||
| 265 | +#[test] | ||
| 266 | +fn exports_the_timeline_as_an_mp3() { | ||
| 267 | + let out = out_path("mp3", "mp3"); | ||
| 268 | + let handle = engine::export::start( | ||
| 269 | + mixed_project(), | ||
| 270 | + meta(), | ||
| 271 | + &out, | ||
| 272 | + &ExportSettings { | ||
| 273 | + format: Format::Mp3, | ||
| 274 | + ..Default::default() | ||
| 275 | + }, | ||
| 276 | + ); | ||
| 277 | + wait(&handle, Duration::from_secs(120)).expect("mp3 export"); | ||
| 278 | + assert_eq!(handle.progress(), 1.0, "finished at full progress"); | ||
| 279 | + assert!(!part_path(&out).exists(), "the .part was renamed away"); | ||
| 280 | + | ||
| 281 | + let (meta, samples) = decode(&out); | ||
| 282 | + assert_eq!((meta.sample_rate, meta.channels), (RATE, 2)); | ||
| 283 | + let channels = usize::from(meta.channels); | ||
| 284 | + let frames = samples.len() / channels; | ||
| 285 | + let timeline = (3.0 * f64::from(RATE)) as usize; | ||
| 286 | + assert!( | ||
| 287 | + frames >= timeline && frames <= timeline + 2 * 1152, | ||
| 288 | + "{frames} frames for a three-second timeline ({timeline})" | ||
| 289 | + ); | ||
| 290 | + let av = rms(&samples, channels, 0.05, 0.95); | ||
| 291 | + let gap = rms(&samples, channels, 1.1, 1.9); | ||
| 292 | + let tone = rms(&samples, channels, 2.05, 2.95); | ||
| 293 | + println!("mp3 rms: av {av:.4} gap {gap:.6} mp3 second {tone:.4}"); | ||
| 294 | + assert!(av > 0.01, "the first second is audible"); | ||
| 295 | + assert!(tone > 0.01, "the mp3 second is audible"); | ||
| 296 | + assert!(gap < av / 20.0, "the hole is silence: {gap:.6}"); | ||
| 297 | + let peak = rms(&samples, channels, 0.2, 0.3); | ||
| 298 | + let dip = rms(&samples, channels, 0.7, 0.8); | ||
| 299 | + assert!( | ||
| 300 | + peak > dip * 4.0, | ||
| 301 | + "the 1 Hz pulse survived: peak {peak:.4} vs dip {dip:.4}" | ||
| 302 | + ); | ||
| 303 | + std::fs::remove_file(&out).unwrap(); | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +/// The failure a user hit, as a test: a still picture and a song, exported as an | ||
| 307 | +/// **mp4**. There is no AAC track anywhere in that timeline to copy -- an mp3 | ||
| 308 | +/// holds no such packets and a png holds nothing at all -- so this used to be | ||
| 309 | +/// refused by name and the only way out was a WAV beside a picture nobody had. | ||
| 310 | +/// The song is decoded and encoded as AAC instead (`export::copy_audio` falls | ||
| 311 | +/// through to `encode_audio`), and the file comes back with picture *and* sound. | ||
| 312 | +#[test] | ||
| 313 | +fn a_still_and_a_song_export_as_an_mp4_with_sound() { | ||
| 314 | + let song = asset("test_tone.mp3"); | ||
| 315 | + let still = asset("test_still.png"); | ||
| 316 | + let clip = |source, frames| Clip { | ||
| 317 | + start: 0, | ||
| 318 | + in_frame: 0, | ||
| 319 | + out_frame: frames, | ||
| 320 | + source, | ||
| 321 | + link: None, | ||
| 322 | + eq: None, | ||
| 323 | + color: None, | ||
| 324 | + fit: FitPolicy::default(), | ||
| 325 | + speed: Speed::NORMAL, | ||
| 326 | + }; | ||
| 327 | + // Two seconds of each at the project's own 30 fps: a still has no length of | ||
| 328 | + // its own and the song is longer than what is placed. | ||
| 329 | + let project = Project::from_parts( | ||
| 330 | + vec![Source::new(still, 0), Source::new(song, 0)], | ||
| 331 | + vec![ | ||
| 332 | + (LaneKind::Video, vec![clip(0, 60)]), | ||
| 333 | + (LaneKind::Audio, vec![clip(1, 60)]), | ||
| 334 | + ], | ||
| 335 | + Vec::new(), | ||
| 336 | + Vec::new(), | ||
| 337 | + ) | ||
| 338 | + .expect("a still under a song"); | ||
| 339 | + // The project's own picture size and rate: the still decides the one and | ||
| 340 | + // the scaffold the other, exactly as opening a png in the editor does. | ||
| 341 | + let meta = engine::VideoMeta { | ||
| 342 | + width: 640, | ||
| 343 | + height: 360, | ||
| 344 | + frame_rate: 30.0, | ||
| 345 | + frame_count: 60, | ||
| 346 | + codec: engine::Codec::H264, | ||
| 347 | + }; | ||
| 348 | + let out = out_path("still_song", "mp4"); | ||
| 349 | + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); | ||
| 350 | + wait(&handle, Duration::from_secs(300)).expect("an mp4 of a still under a song"); | ||
| 351 | + | ||
| 352 | + // Picture: two seconds of it, through the demuxer an import uses. | ||
| 353 | + let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen the export"); | ||
| 354 | + assert_eq!((written.width, written.height), (640, 360)); | ||
| 355 | + assert_eq!(written.frame_count, 60, "two seconds at 30 fps"); | ||
| 356 | + // ...and sound, which is the half that used to be missing. | ||
| 357 | + let (audio, samples) = decode(&out); | ||
| 358 | + let channels = usize::from(audio.channels); | ||
| 359 | + let heard = rms(&samples, channels, 0.2, 1.8); | ||
| 360 | + println!("still+song: {} Hz, rms {heard:.4}", audio.sample_rate); | ||
| 361 | + assert!(heard > 0.01, "the song is in the file (rms {heard:.4})"); | ||
| 362 | + std::fs::remove_file(&out).unwrap(); | ||
| 363 | +} | ||
| 364 | + | ||
| 255 | /// Cancel leaves nothing behind -- not the output, not the `.part`. The | 365 | /// Cancel leaves nothing behind -- not the output, not the `.part`. The |
| 256 | /// timeline is long enough (a minute of audio) that the escape lands mid-decode | 366 | /// timeline is long enough (a minute of audio) that the escape lands mid-decode |
| 257 | /// rather than after the file is already closed. | 367 | /// rather than after the file is already closed. |
| 368 | +/// What the two mix settings do to a *written file*, which is the only place | ||
| 369 | +/// the claim can be checked: a track's fader is that track's alone, and the | ||
| 370 | +/// master limiter holds the sum of them under its ceiling instead of letting it | ||
| 371 | +/// square off at full scale. | ||
| 372 | +/// | ||
| 373 | +/// Four audio tracks of the same second, so the sum is four times one file and | ||
| 374 | +/// well past what a sample can hold. Measured as the peak of the WAV read back | ||
| 375 | +/// through the engine's own reader -- a level, not a shape, because that is | ||
| 376 | +/// exactly what a limiter promises. | ||
| 377 | +#[test] | ||
| 378 | +fn a_fader_is_one_tracks_own_and_the_limiter_holds_the_sum() { | ||
| 379 | + let clip = Clip { | ||
| 380 | + start: 0, | ||
| 381 | + in_frame: 0, | ||
| 382 | + out_frame: 30, | ||
| 383 | + source: 0, | ||
| 384 | + link: None, | ||
| 385 | + eq: None, | ||
| 386 | + color: None, | ||
| 387 | + fit: FitPolicy::default(), | ||
| 388 | + speed: Speed::NORMAL, | ||
| 389 | + }; | ||
| 390 | + let four = || { | ||
| 391 | + Project::from_parts( | ||
| 392 | + vec![Source::new(asset("test_av.mp4"), 0)], | ||
| 393 | + vec![ | ||
| 394 | + (LaneKind::Video, vec![clip]), | ||
| 395 | + (LaneKind::Audio, vec![clip]), | ||
| 396 | + (LaneKind::Audio, vec![clip]), | ||
| 397 | + (LaneKind::Audio, vec![clip]), | ||
| 398 | + (LaneKind::Audio, vec![clip]), | ||
| 399 | + ], | ||
| 400 | + Vec::new(), | ||
| 401 | + Vec::new(), | ||
| 402 | + ) | ||
| 403 | + .expect("one second on four audio tracks") | ||
| 404 | + }; | ||
| 405 | + let write = |project: Project, name: &str| { | ||
| 406 | + let out = out_path(name, "wav"); | ||
| 407 | + let handle = engine::export::start( | ||
| 408 | + project, | ||
| 409 | + meta(), | ||
| 410 | + &out, | ||
| 411 | + &ExportSettings { | ||
| 412 | + format: Format::Wav, | ||
| 413 | + ..Default::default() | ||
| 414 | + }, | ||
| 415 | + ); | ||
| 416 | + wait(&handle, Duration::from_secs(60)).unwrap_or_else(|e| panic!("{name}: {e}")); | ||
| 417 | + let (audio, samples) = decode(&out); | ||
| 418 | + let peak = samples.iter().fold(0.0f32, |m, s| m.max(s.abs())); | ||
| 419 | + let level = rms(&samples, usize::from(audio.channels), 0.05, 0.95); | ||
| 420 | + let _ = std::fs::remove_file(&out); | ||
| 421 | + (peak, level) | ||
| 422 | + }; | ||
| 423 | + | ||
| 424 | + // Four copies of one file, each fader all the way up: the sum is well past | ||
| 425 | + // what a sample can hold, and with no limiter it is clamped at full scale | ||
| 426 | + // by the mixer's own backstop -- which is the clipping this exists for. | ||
| 427 | + let hot = || { | ||
| 428 | + let mut project = four(); | ||
| 429 | + for ord in 0..4 { | ||
| 430 | + assert!(project.set_lane_gain_db( | ||
| 431 | + Lane::new(LaneKind::Audio, ord), | ||
| 432 | + engine::project::MAX_GAIN_DB | ||
| 433 | + )); | ||
| 434 | + } | ||
| 435 | + project | ||
| 436 | + }; | ||
| 437 | + let (flat_peak, flat_level) = write(hot(), "mix_flat"); | ||
| 438 | + println!("flat: peak {flat_peak:.4} rms {flat_level:.4}"); | ||
| 439 | + | ||
| 440 | + // One track's fader, and one track's only: A2, A3 and A4 all the way down | ||
| 441 | + // leaves a quarter of the sum, so the level drops by ~12 dB against the | ||
| 442 | + // four of them at the same setting. A whole-band | ||
| 443 | + // change -- there is no frequency in this claim, which is what makes it a | ||
| 444 | + // different control from the equalizer. | ||
| 445 | + let (unity_peak, unity_level) = write(four(), "mix_unity"); | ||
| 446 | + let mut down = four(); | ||
| 447 | + for ord in 1..4 { | ||
| 448 | + assert!(down.set_lane_gain_db( | ||
| 449 | + Lane::new(LaneKind::Audio, ord), | ||
| 450 | + engine::project::MIN_GAIN_DB | ||
| 451 | + )); | ||
| 452 | + } | ||
| 453 | + let (_, quiet_level) = write(down, "mix_fader"); | ||
| 454 | + let drop_db = 20.0 * (quiet_level / unity_level).log10(); | ||
| 455 | + println!("one track alone: rms {quiet_level:.4} ({drop_db:.1} dB)"); | ||
| 456 | + assert!( | ||
| 457 | + (drop_db + 12.0).abs() < 1.5, | ||
| 458 | + "three of four tracks down left {drop_db:.1} dB, not ~-12" | ||
| 459 | + ); | ||
| 460 | + | ||
| 461 | + // The limiter over the same hot sum: the peak lands under the ceiling, and | ||
| 462 | + // the sound is still there (a limiter that silenced the mix would pass a | ||
| 463 | + // peak test and fail every ear). | ||
| 464 | + let ceiling_db = -3.0; | ||
| 465 | + let mut limited = hot(); | ||
| 466 | + assert!(limited.set_limiter(engine::limiter::Limiter { | ||
| 467 | + ceiling_db, | ||
| 468 | + on: true, | ||
| 469 | + })); | ||
| 470 | + let (peak, level) = write(limited, "mix_limited"); | ||
| 471 | + let ceiling = 10f32.powf(ceiling_db / 20.0); | ||
| 472 | + println!("limited: peak {peak:.4} vs ceiling {ceiling:.4} rms {level:.4}"); | ||
| 473 | + assert!( | ||
| 474 | + flat_peak > ceiling, | ||
| 475 | + "the flat mix was not hot to begin with" | ||
| 476 | + ); | ||
| 477 | + assert!( | ||
| 478 | + peak <= ceiling + 1e-3, | ||
| 479 | + "peak {peak:.4} passed the {ceiling:.4} ceiling" | ||
| 480 | + ); | ||
| 481 | + assert!(level > unity_level, "the limiter took the mix out"); | ||
| 482 | + assert!( | ||
| 483 | + unity_peak < 1.0, | ||
| 484 | + "four at unity fit; the +12 dB four did not" | ||
| 485 | + ); | ||
| 486 | +} | ||
| 487 | + | ||
| 258 | #[test] | 488 | #[test] |
| 259 | fn a_cancelled_audio_export_leaves_no_file() { | 489 | fn a_cancelled_audio_export_leaves_no_file() { |
| 260 | let source = asset("test_av.mp4"); | 490 | let source = asset("test_av.mp4"); |
| @@ -307,9 +537,9 @@ fn a_silent_timeline_refuses_an_audio_export() { | |||
| 307 | ); | 537 | ); |
| 308 | } | 538 | } |
| 309 | 539 | ||
| 310 | -/// An AC-3 source leaves through this door and no other: the mp4 export cannot | 540 | +/// An AC-3 source through the audio-only door: the mp4 export cannot |
| 311 | -/// copy a syncframe into an `mp4a` track (no AAC encoder here), but a WAV of the | 541 | +/// copy a syncframe into an `mp4a` track, but a WAV of the same timeline |
| 312 | -/// same timeline decodes, downmixes and reopens through the engine's own reader. | 542 | +/// decodes, downmixes and reopens through the engine's own reader. |
| 313 | #[test] | 543 | #[test] |
| 314 | fn a_51_ac3_source_round_trips_through_a_wav() { | 544 | fn a_51_ac3_source_round_trips_through_a_wav() { |
| 315 | let source = asset("test_ac3_51.mp4"); | 545 | let source = asset("test_ac3_51.mp4"); |
| @@ -273,7 +273,7 @@ fn an_audio_only_project_saves_reloads_and_exports_its_sound() { | |||
| 273 | assert_eq!( | 273 | assert_eq!( |
| 274 | e.to_string(), | 274 | e.to_string(), |
| 275 | "the timeline has no picture: an mp4 would be black. \ | 275 | "the timeline has no picture: an mp4 would be black. \ |
| 276 | - Export WAV or FLAC, which are the sound itself" | 276 | + Export WAV, FLAC or MP3, which are the sound itself" |
| 277 | ); | 277 | ); |
| 278 | assert!(!mp4.exists(), "the refusal wrote a file anyway"); | 278 | assert!(!mp4.exists(), "the refusal wrote a file anyway"); |
| 279 | 279 | ||
| @@ -386,20 +386,21 @@ fn a_video_joins_a_timeline_a_song_started() { | |||
| 386 | import_and_place(&mut session, &asset("test_av.mp4")); | 386 | import_and_place(&mut session, &asset("test_av.mp4")); |
| 387 | assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); | 387 | assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); |
| 388 | assert_eq!(session.lane_clips(Lane::A1).len(), 2); | 388 | assert_eq!(session.lane_clips(Lane::A1).len(), 2); |
| 389 | - // And a file at another rate is refused in the timeline's own words rather | 389 | + // A sample rate the device cannot have two of is still refused in the |
| 390 | - // than silently retiming the song already on the lane -- the sample rate at | 390 | + // timeline's own words... |
| 391 | - // one door, the *frame* rate at the other: the canvas a song scaffolds has | ||
| 392 | - // a frame rate of its own (30 fps), and a 25 fps picture cannot join it. | ||
| 393 | let e = refusal(session.import(&asset("test_tone_48k.wav"))); | 391 | let e = refusal(session.import(&asset("test_tone_48k.wav"))); |
| 394 | assert_eq!( | 392 | assert_eq!( |
| 395 | e, | 393 | e, |
| 396 | "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" | 394 | "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" |
| 397 | ); | 395 | ); |
| 398 | - assert_eq!( | ||
| 399 | - refusal(session.import(&asset("test_25fps.mp4"))), | ||
| 400 | - "25.000 fps does not match the timeline's 30.000 fps" | ||
| 401 | - ); | ||
| 402 | assert_eq!(session.sources().len(), 2, "a refusal left a library row"); | 396 | assert_eq!(session.sources().len(), 2, "a refusal left a library row"); |
| 397 | + // ...but a *frame* rate of its own is not a refusal: the canvas a song | ||
| 398 | + // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it | ||
| 399 | + // lasts in seconds (50 frames of file, 60 of timeline). | ||
| 400 | + session | ||
| 401 | + .import(&asset("test_25fps.mp4")) | ||
| 402 | + .expect("25 fps joins the 30 fps canvas a song scaffolded"); | ||
| 403 | + assert_eq!(session.file_frames(&asset("test_25fps.mp4")), 60); | ||
| 403 | } | 404 | } |
| 404 | 405 | ||
| 405 | /// Blocks until the export settles, whichever way it settled. | 406 | /// Blocks until the export settles, whichever way it settled. |
| @@ -414,16 +415,19 @@ fn wait(handle: &engine::ExportHandle) -> engine::Result<()> { | |||
| 414 | } | 415 | } |
| 415 | } | 416 | } |
| 416 | 417 | ||
| 417 | -/// The export copies AAC packets and has no encoder, so a timeline carrying an | 418 | +/// The *copy* path names what it cannot copy, by file and by format. That is a |
| 418 | -/// mp3 cannot become an mp4 -- named, with its format, rather than exported | 419 | +/// fallback's reason rather than a user's refusal now -- `export::copy_audio` |
| 419 | -/// silent or exported wrong. | 420 | +/// takes this `Err` as "not copyable" and decodes and re-encodes the timeline |
| 421 | +/// instead (`tests/audio_export.rs` exports exactly this shape as an mp4 with | ||
| 422 | +/// sound in it) -- but the words are what a caller with no encoder shows, so | ||
| 423 | +/// they are still asserted here. | ||
| 420 | #[test] | 424 | #[test] |
| 421 | fn an_export_refuses_audio_it_cannot_copy() { | 425 | fn an_export_refuses_audio_it_cannot_copy() { |
| 422 | let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")]; | 426 | let sources = vec![asset("test_av.mp4"), asset("test_tone.mp3")]; |
| 423 | let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; | 427 | let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; |
| 424 | assert_eq!( | 428 | assert_eq!( |
| 425 | refusal(AudioSession::copy_multi_segments(&sources, &segs)), | 429 | refusal(AudioSession::copy_multi_segments(&sources, &segs)), |
| 426 | - "export needs AAC audio today; test_tone.mp3 is mp3" | 430 | + "a packet copy needs AAC in an mp4; test_tone.mp3 is mp3" |
| 427 | ); | 431 | ); |
| 428 | // A timeline of nothing but mp4 still exports, which is the invariant this | 432 | // A timeline of nothing but mp4 still exports, which is the invariant this |
| 429 | // refusal must not have cost. | 433 | // refusal must not have cost. |
| @@ -185,7 +185,7 @@ fn a_gap_segment_is_silence_of_its_own_length() { | |||
| 185 | ); | 185 | ); |
| 186 | } | 186 | } |
| 187 | 187 | ||
| 188 | -/// The copy side of a gap: there is no AAC encoder here, so the hole is copied | 188 | +/// The copy side of a gap: a copy never encodes, so the hole is copied |
| 189 | /// as hand-written silent packets -- real access units, one 1024-frame stts | 189 | /// as hand-written silent packets -- real access units, one 1024-frame stts |
| 190 | /// entry each, the rounding debt carried through them like any other segment. | 190 | /// entry each, the rounding debt carried through them like any other segment. |
| 191 | /// Every packet after the gap therefore still lands at its timeline position. | 191 | /// Every packet after the gap therefore still lands at its timeline position. |
| @@ -57,28 +57,19 @@ fn the_demuxer_reports_an_av1_track_in_matroska() { | |||
| 57 | assert_eq!(vp9.codec, Codec::Vp9); | 57 | assert_eq!(vp9.codec, Codec::Vp9); |
| 58 | } | 58 | } |
| 59 | 59 | ||
| 60 | -/// The delivered audio scope, as an assert: this slice reads a Matroska file's | 60 | +/// The delivered audio scope, as an assert: a Matroska file's AAC track is read |
| 61 | -/// picture and not its sound, so the fixture's AAC track is *named* in the | 61 | +/// like any other file's (`tests/hevc_mkv.rs` is where that lives), and its |
| 62 | -/// notice a session shows rather than half-played or reported as an mp4 error. | 62 | +/// *picture* being AV1 changes nothing about it. |
| 63 | #[test] | 63 | #[test] |
| 64 | -fn matroska_audio_is_not_wired_and_says_so() { | 64 | +fn matroska_audio_is_read_whatever_the_picture_is() { |
| 65 | let path = asset("test_av1.mkv"); | 65 | let path = asset("test_av1.mkv"); |
| 66 | - assert!( | 66 | + let probe = AudioSession::probe(&path, 0) |
| 67 | - AudioSession::probe(&path, 0) | 67 | + .expect("probe must not fail") |
| 68 | - .expect("probe must not fail") | 68 | + .expect("the fixture has an AAC track"); |
| 69 | - .is_none(), | 69 | + assert_eq!((probe.sample_rate, probe.channels), (44_100, 2)); |
| 70 | - "an mkv is a silent source for now, not an error" | 70 | + let streams = AudioSession::probe_streams(&path).expect("streams"); |
| 71 | - ); | 71 | + assert_eq!(streams.len(), 1, "one readable audio stream: {streams:?}"); |
| 72 | - assert!( | 72 | + assert!(streams[0].decodable); |
| 73 | - AudioSession::probe_streams(&path) | ||
| 74 | - .expect("streams") | ||
| 75 | - .is_empty() | ||
| 76 | - ); | ||
| 77 | - let reason = AudioSession::unsupported(&path) | ||
| 78 | - .expect("unsupported") | ||
| 79 | - .expect("the fixture has an AAC track to name"); | ||
| 80 | - assert!(reason.contains("A_AAC"), "{reason}"); | ||
| 81 | - assert!(reason.contains("not wired"), "{reason}"); | ||
| 82 | } | 73 | } |
| 83 | 74 | ||
| 84 | /// Every block comes back, keyframes carry the sequence header, and the sync | 75 | /// Every block comes back, keyframes carry the sequence header, and the sync |
| @@ -204,30 +195,45 @@ fn a_seek_lands_on_the_frame_it_asked_for() { | |||
| 204 | assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for"); | 195 | assert_eq!(frames[0].index, KEYFRAME + 7, "the frame asked for"); |
| 205 | } | 196 | } |
| 206 | 197 | ||
| 207 | -/// Export re-encodes to H.264 whatever the source was coded with -- and out of | 198 | +/// An mp4 export of a Matroska source carries its sound. |
| 208 | -/// a Matroska source it also has to write an mp4 the demuxer reads back. | 199 | +/// |
| 200 | +/// Three lives, this one. It used to *succeed* silently and write picture with | ||
| 201 | +/// no sound, because this engine could not read a Matroska file's audio at all. | ||
| 202 | +/// Then the sound became readable and this became a refusal by name, because | ||
| 203 | +/// the mp4 path could only *copy* AAC out of an mp4's own sample table and a | ||
| 204 | +/// Matroska file has none. Now the copy that cannot be made is a decode and a | ||
| 205 | +/// re-encode (`export::copy_audio` -> `encode_audio`), so the export carries the | ||
| 206 | +/// film's sound instead of naming what it cannot do with it. The picture half of | ||
| 207 | +/// the same export is [`an_av1_export_reopens_through_our_own_demuxer`]. | ||
| 209 | #[test] | 208 | #[test] |
| 210 | #[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] | 209 | #[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] |
| 211 | -fn an_av1_source_exports_as_h264() { | 210 | +fn an_mp4_export_of_a_matroska_source_carries_its_sound() { |
| 212 | let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv"); | 211 | let session = PlaybackSession::open(asset("test_av1.mkv")).expect("open test_av1.mkv"); |
| 213 | let meta = *session.meta(); | 212 | let meta = *session.meta(); |
| 214 | - let project = Project::single(asset("test_av1.mkv"), meta.frame_count); | 213 | + // A short one: the picture is re-encoded frame by frame and what is under |
| 214 | + // test here is the sound reaching the file, not H.264 throughput. | ||
| 215 | + let project = Project::single(asset("test_av1.mkv"), 15); | ||
| 215 | let out = std::env::temp_dir().join(format!("ve_export_av1_{}.mp4", std::process::id())); | 216 | let out = std::env::temp_dir().join(format!("ve_export_av1_{}.mp4", std::process::id())); |
| 216 | let _ = std::fs::remove_file(&out); | 217 | let _ = std::fs::remove_file(&out); |
| 217 | 218 | ||
| 218 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); | 219 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); |
| 219 | let started = Instant::now(); | 220 | let started = Instant::now(); |
| 220 | while !handle.is_finished() { | 221 | while !handle.is_finished() { |
| 221 | - assert!(started.elapsed() < Duration::from_secs(120), "export hung"); | 222 | + assert!(started.elapsed() < Duration::from_secs(300), "export hung"); |
| 222 | std::thread::sleep(Duration::from_millis(20)); | 223 | std::thread::sleep(Duration::from_millis(20)); |
| 223 | } | 224 | } |
| 224 | - handle.result().expect("outcome").expect("export"); | 225 | + handle |
| 225 | - | 226 | + .result() |
| 226 | - let (written, _) = Demuxer::open(&out).expect("reopen the export"); | 227 | + .expect("outcome") |
| 227 | - assert_eq!(written.codec, Codec::H264, "the default format is H.264"); | 228 | + .expect("an mkv's AAC is decoded and encoded again into the mp4"); |
| 228 | - assert_eq!(written.frame_count, FRAMES, "every timeline frame written"); | 229 | + let (audio, chunks) = AudioSession::open(&out) |
| 229 | - assert_eq!((written.width, written.height), (1280, 720)); | 230 | + .expect("reopen the export") |
| 230 | - let _ = std::fs::remove_file(&out); | 231 | + .expect("the export has an audio track"); |
| 232 | + let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect(); | ||
| 233 | + let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt(); | ||
| 234 | + println!("mkv -> mp4: {} Hz, rms {rms:.4}", audio.sample_rate); | ||
| 235 | + assert!(rms > 0.001, "the film's sound is in the mp4 (rms {rms})"); | ||
| 236 | + std::fs::remove_file(&out).unwrap(); | ||
| 231 | } | 237 | } |
| 232 | 238 | ||
| 233 | /// A short timeline out of the H.264 fixture, which is what the AV1 export tests | 239 | /// A short timeline out of the H.264 fixture, which is what the AV1 export tests |
| @@ -323,6 +329,62 @@ fn an_av1_export_reopens_through_our_own_demuxer() { | |||
| 323 | std::fs::remove_file(&out).unwrap(); | 329 | std::fs::remove_file(&out).unwrap(); |
| 324 | } | 330 | } |
| 325 | 331 | ||
| 332 | +/// A timeline with sound, exported as AV1 into **both** containers: the file | ||
| 333 | +/// carries the picture *and* the timeline's audio, and this project's own | ||
| 334 | +/// readers are what say so -- the demuxer for the picture, the audio session for | ||
| 335 | +/// the sound. An AV1 export used to be picture only, which is a file whose sound | ||
| 336 | +/// went missing with nobody told. | ||
| 337 | +/// | ||
| 338 | +/// Two frames of 720p: `rav1e` is built here without its assembly, so the length | ||
| 339 | +/// of the timeline is the length of the test, and what is under test is the | ||
| 340 | +/// wiring from the format to the muxer, not the encoder. | ||
| 341 | +#[test] | ||
| 342 | +fn an_av1_export_carries_the_timelines_sound_in_either_container() { | ||
| 343 | + for (format, ext) in [ | ||
| 344 | + (engine::export::Format::Av1, "mkv"), | ||
| 345 | + (engine::export::Format::Av1Mp4, "mp4"), | ||
| 346 | + ] { | ||
| 347 | + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av"); | ||
| 348 | + assert!(session.cut_at(2.0 / 30.0), "two frames of it"); | ||
| 349 | + assert!(session.delete_clip(engine::project::Lane::V1, 1)); | ||
| 350 | + let out = std::env::temp_dir().join(format!("ve_av1_sound_{}.{ext}", std::process::id())); | ||
| 351 | + let _ = std::fs::remove_file(&out); | ||
| 352 | + let settings = ExportSettings { | ||
| 353 | + format, | ||
| 354 | + force_sw: true, | ||
| 355 | + ..Default::default() | ||
| 356 | + }; | ||
| 357 | + let handle = session.export_to_with(&out, &settings); | ||
| 358 | + let started = Instant::now(); | ||
| 359 | + while !handle.is_finished() { | ||
| 360 | + assert!(started.elapsed() < Duration::from_secs(300), "export hung"); | ||
| 361 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 362 | + } | ||
| 363 | + handle.result().expect("outcome").expect("an AV1 export"); | ||
| 364 | + | ||
| 365 | + // The picture, through the demuxer an import comes in by -- an `av01` | ||
| 366 | + // sample entry in the mp4 and a `V_AV1` track in the Matroska file, both | ||
| 367 | + // of them written by hand and read back by hand. | ||
| 368 | + let (meta, _) = Demuxer::open(&out).expect("reopen the export"); | ||
| 369 | + assert_eq!(meta.codec, Codec::Av1, "{ext}: an AV1 export is AV1"); | ||
| 370 | + assert_eq!((meta.width, meta.height), (1280, 720), "{ext}"); | ||
| 371 | + assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there"); | ||
| 372 | + | ||
| 373 | + // ...and the sound beside it, which is the half that used to be absent. | ||
| 374 | + let (audio, chunks) = AudioSession::open(&out) | ||
| 375 | + .expect("reopen for its sound") | ||
| 376 | + .expect("an AV1 export has an audio track"); | ||
| 377 | + let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect(); | ||
| 378 | + let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt(); | ||
| 379 | + println!( | ||
| 380 | + "{ext}: {} Hz x{}, rms {rms:.4}", | ||
| 381 | + audio.sample_rate, audio.channels | ||
| 382 | + ); | ||
| 383 | + assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})"); | ||
| 384 | + std::fs::remove_file(&out).unwrap(); | ||
| 385 | + } | ||
| 386 | +} | ||
| 387 | + | ||
| 326 | /// An audio-only timeline is refused an AV1 export by name, exactly as it is | 388 | /// An audio-only timeline is refused an AV1 export by name, exactly as it is |
| 327 | /// refused an mp4: every frame of it is a gap, so the file would be black. | 389 | /// refused an mp4: every frame of it is a gap, so the file would be black. |
| 328 | #[test] | 390 | #[test] |
| @@ -0,0 +1,283 @@ | |||
| 1 | +//! Which decoder and which encoder a job really runs on -- the introspection a | ||
| 2 | +//! front-end shows before an operation and while it runs. | ||
| 3 | +//! | ||
| 4 | +//! The point of every assertion here is *truthfulness*, not a particular seat: | ||
| 5 | +//! this box may or may not have a working plugin, and a test that demanded | ||
| 6 | +//! hardware would only be measuring the machine. What must hold is that the | ||
| 7 | +//! answer given before an operation is the answer the operation then gives, and | ||
| 8 | +//! that neither of them ever names a decoder that could not have run (software | ||
| 9 | +//! HEVC, for one, does not exist here). | ||
| 10 | + | ||
| 11 | +use std::path::PathBuf; | ||
| 12 | +use std::time::{Duration, Instant}; | ||
| 13 | + | ||
| 14 | +use engine::Codec; | ||
| 15 | +use engine::decode::{Backend, probe}; | ||
| 16 | +use engine::export::{ExportSettings, Format}; | ||
| 17 | +use engine::{ExportHandle, PlaybackSession}; | ||
| 18 | + | ||
| 19 | +fn asset(name: &str) -> PathBuf { | ||
| 20 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 21 | + .join("../../assets") | ||
| 22 | + .join(name) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +fn out_path(name: &str, ext: &str) -> PathBuf { | ||
| 26 | + let path = std::env::temp_dir().join(format!("ve_backend_{name}_{}.{ext}", std::process::id())); | ||
| 27 | + let _ = std::fs::remove_file(&path); | ||
| 28 | + let _ = std::fs::remove_file(format!("{}.part", path.display())); | ||
| 29 | + path | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/// A still has no coded stream and no decoder to pick, and it must say so | ||
| 33 | +/// rather than borrowing the picture path's answer. | ||
| 34 | +#[test] | ||
| 35 | +fn a_still_probes_as_a_still() { | ||
| 36 | + let (codec, backend) = probe(&asset("test_still.png")).expect("probe the still"); | ||
| 37 | + assert_eq!(codec, None, "an image has no coded stream to name"); | ||
| 38 | + assert_eq!(backend, Backend::Still); | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// H.264 has both seats, so the probe may legitimately answer either -- but it | ||
| 42 | +/// must answer one of them, and it must name the codec. | ||
| 43 | +#[test] | ||
| 44 | +fn an_h264_source_probes_as_one_of_the_two_seats() { | ||
| 45 | + let (codec, backend) = probe(&asset("test_baseline.mp4")).expect("probe the baseline fixture"); | ||
| 46 | + assert_eq!(codec, Some(Codec::H264)); | ||
| 47 | + assert!( | ||
| 48 | + matches!(backend, Backend::Hardware | Backend::Software), | ||
| 49 | + "a probe that returned must have picked a seat, got {backend:?}" | ||
| 50 | + ); | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// HEVC has no software decoder here at all. A box with the plugin answers | ||
| 54 | +/// hardware; a box without it is refused by name -- and *never* told that | ||
| 55 | +/// `rusty_h264` will take it, which is the one answer that would be a lie. | ||
| 56 | +#[test] | ||
| 57 | +fn hevc_probes_as_hardware_or_as_a_refusal() { | ||
| 58 | + match probe(&asset("test_hevc.mkv")) { | ||
| 59 | + Ok((codec, backend)) => { | ||
| 60 | + assert_eq!(codec, Some(Codec::Hevc)); | ||
| 61 | + assert_eq!(backend, Backend::Hardware, "there is no software HEVC here"); | ||
| 62 | + } | ||
| 63 | + Err(e) => assert!( | ||
| 64 | + e.to_string().contains("plugin"), | ||
| 65 | + "a refusal names the plugin, got {e}" | ||
| 66 | + ), | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// The running session reports the decoder its *worker* opened, and it agrees | ||
| 71 | +/// with what the probe said before anything played. This is the whole point of | ||
| 72 | +/// the cell: the worker writes it where the fallback happens, so a hardware | ||
| 73 | +/// session that dropped to software could only be seen here. | ||
| 74 | +#[test] | ||
| 75 | +fn a_playing_session_reports_the_seat_the_probe_named() { | ||
| 76 | + let path = asset("test_baseline.mp4"); | ||
| 77 | + let (_codec, probed) = probe(&path).expect("probe the baseline fixture"); | ||
| 78 | + let session = PlaybackSession::open(&path).expect("open the fixture"); | ||
| 79 | + let started = Instant::now(); | ||
| 80 | + loop { | ||
| 81 | + let live = session.decode_backend(); | ||
| 82 | + if live != Backend::Opening { | ||
| 83 | + assert_eq!(live, probed, "the running seat is not the probed one"); | ||
| 84 | + break; | ||
| 85 | + } | ||
| 86 | + assert!( | ||
| 87 | + started.elapsed() < Duration::from_secs(20), | ||
| 88 | + "the worker never published a decode backend" | ||
| 89 | + ); | ||
| 90 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 91 | + } | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +/// What the export card says before the button and what the progress line says | ||
| 95 | +/// during the job are the same two answers, from the same two functions: the | ||
| 96 | +/// picture's seat is probed by opening the very encoder the export opens, and | ||
| 97 | +/// the sound's is decided outright. A drift between them is a front-end lying | ||
| 98 | +/// about the machine, which is exactly what this whole surface is for. | ||
| 99 | +/// | ||
| 100 | +/// Every picture format, because each one is a different pair of seats: H.264 | ||
| 101 | +/// through `rusty_h264` or the plugin, and AV1 through `rav1e` in either | ||
| 102 | +/// container -- a container is not an encoder, and the card must not say it is. | ||
| 103 | +#[test] | ||
| 104 | +fn the_planned_encoders_are_the_ones_the_job_opens() { | ||
| 105 | + for (format, ext) in [ | ||
| 106 | + (Format::Mp4, "mp4"), | ||
| 107 | + (Format::Av1, "mkv"), | ||
| 108 | + (Format::Av1Mp4, "mp4"), | ||
| 109 | + // Both HEVC containers, whose seat is software whatever the box has: | ||
| 110 | + // the plugin encodes H.264 and AV1 and no HEVC, so a card that offered | ||
| 111 | + // a hardware seat here would be promising one that cannot exist. | ||
| 112 | + (Format::Hevc, "mkv"), | ||
| 113 | + (Format::HevcMp4, "mp4"), | ||
| 114 | + ] { | ||
| 115 | + let settings = ExportSettings { | ||
| 116 | + format, | ||
| 117 | + ..ExportSettings::default() | ||
| 118 | + }; | ||
| 119 | + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); | ||
| 120 | + let planned = format!( | ||
| 121 | + "{} · {}", | ||
| 122 | + engine::export::planned_video(session.meta(), &settings) | ||
| 123 | + .expect("these formats carry picture"), | ||
| 124 | + session.planned_audio(format) | ||
| 125 | + ); | ||
| 126 | + let out = out_path("planned", ext); | ||
| 127 | + let handle = session.export_to_with(&out, &settings); | ||
| 128 | + let started = Instant::now(); | ||
| 129 | + let opened = loop { | ||
| 130 | + if let Some(line) = handle.encoders() { | ||
| 131 | + break line; | ||
| 132 | + } | ||
| 133 | + assert!( | ||
| 134 | + !handle.is_finished(), | ||
| 135 | + "the export settled before it opened an encoder: {:?}", | ||
| 136 | + handle.result().map(|r| r.err()) | ||
| 137 | + ); | ||
| 138 | + assert!( | ||
| 139 | + started.elapsed() < Duration::from_secs(60), | ||
| 140 | + "no encoder was published" | ||
| 141 | + ); | ||
| 142 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 143 | + }; | ||
| 144 | + // Nothing here wants the file, only the seat it was going to be written | ||
| 145 | + // with: cancelling deletes the `.part` the worker had started. | ||
| 146 | + handle.cancel(); | ||
| 147 | + wind_down(&handle); | ||
| 148 | + assert_eq!(opened, planned, "{ext}"); | ||
| 149 | + // ...and the sound is named on both, AV1 included: an AV1 export | ||
| 150 | + // carries the timeline's audio now, so a line that said nothing about | ||
| 151 | + // it would be the old picture-only lie in a new place. | ||
| 152 | + assert!(planned.contains("AAC"), "{ext}: {planned}"); | ||
| 153 | + if matches!(format, Format::Hevc | Format::HevcMp4) { | ||
| 154 | + assert!( | ||
| 155 | + planned.contains("oxideav-h265 intra"), | ||
| 156 | + "{ext}: an HEVC job names the intra encoder that writes it: {planned}" | ||
| 157 | + ); | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// A WAV job has no picture at all and still names what writes it, so an audio | ||
| 163 | +/// export is not a progress line with nothing to say. | ||
| 164 | +#[test] | ||
| 165 | +fn an_audio_only_job_names_its_encoder() { | ||
| 166 | + for format in [Format::Wav, Format::Flac, Format::Mp3] { | ||
| 167 | + audio_only_job_names_its_encoder(format); | ||
| 168 | + } | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +fn audio_only_job_names_its_encoder(format: Format) { | ||
| 172 | + let settings = ExportSettings { | ||
| 173 | + format, | ||
| 174 | + ..ExportSettings::default() | ||
| 175 | + }; | ||
| 176 | + assert_eq!( | ||
| 177 | + engine::export::planned_video( | ||
| 178 | + &engine::demux::Demuxer::open(&asset("test_av.mp4")) | ||
| 179 | + .expect("open the fixture") | ||
| 180 | + .0, | ||
| 181 | + &settings | ||
| 182 | + ), | ||
| 183 | + None, | ||
| 184 | + "an audio-only format has no video seat to name" | ||
| 185 | + ); | ||
| 186 | + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); | ||
| 187 | + let planned = session.planned_audio(format); | ||
| 188 | + let out = out_path("audio", format.ext()); | ||
| 189 | + let handle = session.export_to_with(&out, &settings); | ||
| 190 | + let started = Instant::now(); | ||
| 191 | + let opened = loop { | ||
| 192 | + if let Some(line) = handle.encoders() { | ||
| 193 | + break line; | ||
| 194 | + } | ||
| 195 | + assert!( | ||
| 196 | + started.elapsed() < Duration::from_secs(60), | ||
| 197 | + "no encoder was published" | ||
| 198 | + ); | ||
| 199 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 200 | + }; | ||
| 201 | + handle.cancel(); | ||
| 202 | + wind_down(&handle); | ||
| 203 | + let _ = std::fs::remove_file(&out); | ||
| 204 | + assert_eq!(opened, planned, "{}", format.ext()); | ||
| 205 | +} | ||
| 206 | + | ||
| 207 | +/// A mixed timeline cannot be copied, and the card must say so *before* the | ||
| 208 | +/// export: a fader and a limiter both live where the lanes are summed, and a | ||
| 209 | +/// copied AAC packet was never summed at all -- so an mp4 of such a timeline is | ||
| 210 | +/// decoded and re-encoded, and the line names the encoder that will do it. | ||
| 211 | +/// | ||
| 212 | +/// The truthfulness rule of this whole file, applied to the one edit that used | ||
| 213 | +/// to be invisible to it. | ||
| 214 | +#[test] | ||
| 215 | +fn a_mixed_timeline_says_it_re_encodes_and_then_does() { | ||
| 216 | + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); | ||
| 217 | + assert_eq!( | ||
| 218 | + session.planned_audio(Format::Mp4), | ||
| 219 | + "AAC copy", | ||
| 220 | + "a timeline nobody has mixed is still a copy" | ||
| 221 | + ); | ||
| 222 | + // A fader off unity... | ||
| 223 | + assert!(session.set_lane_gain_db(engine::project::Lane::A1, -3.0)); | ||
| 224 | + let planned = session.planned_audio(Format::Mp4); | ||
| 225 | + assert!(planned.contains("encode"), "a faded lane: {planned}"); | ||
| 226 | + // ...and back at unity it is a copy again: the answer follows the edit, it | ||
| 227 | + // is not a latch. | ||
| 228 | + assert!(session.set_lane_gain_db(engine::project::Lane::A1, 0.0)); | ||
| 229 | + assert_eq!(session.planned_audio(Format::Mp4), "AAC copy"); | ||
| 230 | + // ...and the limiter alone does it too. | ||
| 231 | + assert!(session.set_limiter(engine::limiter::Limiter { | ||
| 232 | + ceiling_db: -1.0, | ||
| 233 | + on: true, | ||
| 234 | + })); | ||
| 235 | + assert_eq!(session.planned_audio(Format::Mp4), planned); | ||
| 236 | + | ||
| 237 | + // ...and the job opens exactly that, which is the pin the whole file is | ||
| 238 | + // about: the encoders line published by the running export. | ||
| 239 | + let out = out_path("mixed", "mp4"); | ||
| 240 | + let handle = session.export_to_with( | ||
| 241 | + &out, | ||
| 242 | + &ExportSettings { | ||
| 243 | + format: Format::Mp4, | ||
| 244 | + ..ExportSettings::default() | ||
| 245 | + }, | ||
| 246 | + ); | ||
| 247 | + let started = Instant::now(); | ||
| 248 | + let opened = loop { | ||
| 249 | + if let Some(line) = handle.encoders() { | ||
| 250 | + break line; | ||
| 251 | + } | ||
| 252 | + assert!( | ||
| 253 | + !handle.is_finished(), | ||
| 254 | + "the export settled before it opened an encoder: {:?}", | ||
| 255 | + handle.result().map(|r| r.err()) | ||
| 256 | + ); | ||
| 257 | + assert!( | ||
| 258 | + started.elapsed() < Duration::from_secs(60), | ||
| 259 | + "no encoder was published" | ||
| 260 | + ); | ||
| 261 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 262 | + }; | ||
| 263 | + handle.cancel(); | ||
| 264 | + wind_down(&handle); | ||
| 265 | + assert!( | ||
| 266 | + opened.ends_with(&planned), | ||
| 267 | + "{opened} does not end in {planned}" | ||
| 268 | + ); | ||
| 269 | +} | ||
| 270 | + | ||
| 271 | +/// Waits for a cancelled job to settle, so its `.part` is gone before the test | ||
| 272 | +/// ends -- and so no worker outlives the process holding a VA-API session. | ||
| 273 | +fn wind_down(handle: &ExportHandle) { | ||
| 274 | + let started = Instant::now(); | ||
| 275 | + while !handle.is_finished() { | ||
| 276 | + assert!( | ||
| 277 | + started.elapsed() < Duration::from_secs(60), | ||
| 278 | + "a cancelled export did not settle" | ||
| 279 | + ); | ||
| 280 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 281 | + } | ||
| 282 | + let _ = handle.result(); | ||
| 283 | +} | ||
| @@ -277,72 +277,114 @@ fn a_lane_is_equalized_before_the_mix_and_never_after_it() { | |||
| 277 | } | 277 | } |
| 278 | 278 | ||
| 279 | /// The export half of the same claim, through `export::start`: what is written | 279 | /// The export half of the same claim, through `export::start`: what is written |
| 280 | -/// is what is heard, so the WAV carries the boost at the same ratio the feeder | 280 | +/// is what is heard, so both audio-only formats carry the boost at the same |
| 281 | -/// path measured. | 281 | +/// ratio the feeder path measured. Both, because both are lossless and both are |
| 282 | +/// one `run_audio` -- a FLAC that disagreed with the WAV beside it would be the | ||
| 283 | +/// writer, and this is where that would show. | ||
| 282 | #[test] | 284 | #[test] |
| 283 | -fn a_wav_export_carries_the_same_boost_playback_does() { | 285 | +fn the_audio_only_exports_carry_the_same_boost_playback_does() { |
| 284 | let flat = project(vec![clip(0, 0, 30)]); | 286 | let flat = project(vec![clip(0, 0, 30)]); |
| 285 | let mut eqd = flat.clone(); | 287 | let mut eqd = flat.clone(); |
| 286 | assert!(eqd.set_eq(Lane::A1, 0, Some(boost()))); | 288 | assert!(eqd.set_eq(Lane::A1, 0, Some(boost()))); |
| 287 | 289 | ||
| 290 | + for format in [Format::Wav, Format::Flac] { | ||
| 291 | + let mut written = Vec::new(); | ||
| 292 | + for (name, project) in [("flat", &flat), ("eqd", &eqd)] { | ||
| 293 | + let out = out_path(name, format.ext()); | ||
| 294 | + let handle = engine::export::start( | ||
| 295 | + project.clone(), | ||
| 296 | + meta(), | ||
| 297 | + &out, | ||
| 298 | + &ExportSettings { | ||
| 299 | + format, | ||
| 300 | + ..Default::default() | ||
| 301 | + }, | ||
| 302 | + ); | ||
| 303 | + wait(&handle, Duration::from_secs(60)).expect("an audio-only export"); | ||
| 304 | + written.push(decode(&out)); | ||
| 305 | + std::fs::remove_file(&out).unwrap(); | ||
| 306 | + } | ||
| 307 | + let [plain, boosted] = &written[..] else { | ||
| 308 | + unreachable!("two exports") | ||
| 309 | + }; | ||
| 310 | + assert_boosted( | ||
| 311 | + rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95), | ||
| 312 | + format.name(), | ||
| 313 | + ); | ||
| 314 | + // ...and the same number to the ear: the export is not a second, kinder | ||
| 315 | + // filter run at a different point in the chain. | ||
| 316 | + let played = rms(&play(&eqd), 0.05, 0.95) / rms(&play(&flat), 0.05, 0.95); | ||
| 317 | + let exported = rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95); | ||
| 318 | + assert!( | ||
| 319 | + (played - exported).abs() < 0.05, | ||
| 320 | + "playback boosted by {played:.3} and {} by {exported:.3}", | ||
| 321 | + format.name() | ||
| 322 | + ); | ||
| 323 | + } | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +/// An mp4 export *copies* AAC packets and no filter can reach a copy, so an | ||
| 327 | +/// equalized lane is decoded, mixed and encoded again instead | ||
| 328 | +/// (`export::encode_audio`). The claim is the same one the WAV makes: the boost | ||
| 329 | +/// is in the file, on the clip that was given it and on no other -- and the | ||
| 330 | +/// track still starts where the picture does, which is what the encoder's own | ||
| 331 | +/// priming packet is for. | ||
| 332 | +#[test] | ||
| 333 | +fn an_mp4_export_carries_the_boost_a_packet_copy_could_not() { | ||
| 334 | + let flat = project(vec![clip(0, 0, 30), clip(30, 0, 30)]); | ||
| 335 | + let mut eqd = flat.clone(); | ||
| 336 | + assert!(eqd.set_eq(Lane::A1, 1, Some(boost()))); | ||
| 337 | + | ||
| 288 | let mut written = Vec::new(); | 338 | let mut written = Vec::new(); |
| 289 | for (name, project) in [("flat", &flat), ("eqd", &eqd)] { | 339 | for (name, project) in [("flat", &flat), ("eqd", &eqd)] { |
| 290 | - let out = out_path(name, "wav"); | 340 | + let out = out_path(name, "mp4"); |
| 291 | - let handle = engine::export::start( | 341 | + let settings = ExportSettings::default(); |
| 292 | - project.clone(), | 342 | + let handle = engine::export::start(project.clone(), meta(), &out, &settings); |
| 293 | - meta(), | 343 | + wait(&handle, Duration::from_secs(180)).expect("an equalized timeline exports as mp4"); |
| 294 | - &out, | ||
| 295 | - &ExportSettings { | ||
| 296 | - format: Format::Wav, | ||
| 297 | - ..Default::default() | ||
| 298 | - }, | ||
| 299 | - ); | ||
| 300 | - wait(&handle, Duration::from_secs(60)).expect("wav export"); | ||
| 301 | written.push(decode(&out)); | 344 | written.push(decode(&out)); |
| 302 | std::fs::remove_file(&out).unwrap(); | 345 | std::fs::remove_file(&out).unwrap(); |
| 303 | } | 346 | } |
| 304 | let [plain, boosted] = &written[..] else { | 347 | let [plain, boosted] = &written[..] else { |
| 305 | unreachable!("two exports") | 348 | unreachable!("two exports") |
| 306 | }; | 349 | }; |
| 307 | - assert_boosted( | 350 | + |
| 308 | - rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95), | 351 | + // Two seconds of timeline, to within the one 1024-frame packet the length |
| 309 | - "wav export", | 352 | + // rounds up to: an encoder delay left uncompensated would show up here as a |
| 353 | + // whole packet of shift, and in the windows below as a smeared cut. | ||
| 354 | + let secs = |s: &[f32]| s.len() as f64 / 2.0 / f64::from(RATE); | ||
| 355 | + println!( | ||
| 356 | + "mp4 lengths: flat {:.3}s, eqd {:.3}s", | ||
| 357 | + secs(plain), | ||
| 358 | + secs(boosted) | ||
| 310 | ); | 359 | ); |
| 311 | - // ...and the same number to the ear: the export is not a second, kinder | 360 | + for samples in [plain, boosted] { |
| 312 | - // filter run at a different point in the chain. | 361 | + assert!( |
| 313 | - let played = rms(&play(&eqd), 0.05, 0.95) / rms(&play(&flat), 0.05, 0.95); | 362 | + (secs(samples) - 2.0).abs() < 1024.0 / f64::from(RATE), |
| 314 | - let exported = rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95); | 363 | + "the exported track is {:.3}s of a 2.000s timeline", |
| 364 | + secs(samples) | ||
| 365 | + ); | ||
| 366 | + } | ||
| 367 | + | ||
| 368 | + // The boost itself. Not to `assert_boosted`'s fifth of a dB: this file is | ||
| 369 | + // AAC at 128 kbps measured against a *copied* one, so a fraction of a dB is | ||
| 370 | + // the codec, not the filter. A dB either way is far tighter than the 12 the | ||
| 371 | + // band asks for and far wider than any coding noise. | ||
| 372 | + let db = 20.0 * (rms(boosted, 1.05, 1.95) / rms(plain, 1.05, 1.95)).log10(); | ||
| 373 | + println!("mp4 equalized clip: {db:+.2} dB"); | ||
| 315 | assert!( | 374 | assert!( |
| 316 | - (played - exported).abs() < 0.05, | 375 | + (db - f64::from(BOOST_DB)).abs() < 1.0, |
| 317 | - "playback boosted by {played:.3} and the export by {exported:.3}" | 376 | + "the equalized clip in the mp4 measured {db:+.2} dB, the band asks for {BOOST_DB:+.1}" |
| 318 | ); | 377 | ); |
| 319 | -} | 378 | + // The clip before it is the same sound: not to the bit -- this file is a |
| 320 | - | 379 | + // re-encode and that one is a copy -- but to a fraction of a dB, which is |
| 321 | -/// An mp4 export *copies* AAC packets, and no filter can reach a packet copy. | 380 | + // what says the filter stopped at the cut rather than lifting the lot. |
| 322 | -/// Refused by name, with the clip's own position in it -- silently writing the | 381 | + let leak = 20.0 * (rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95)).log10(); |
| 323 | -/// clip flat is the one failure nobody would notice. | 382 | + println!("mp4 flat clip moved {leak:+.2} dB"); |
| 324 | -#[test] | 383 | + assert!(leak.abs() < 0.5, "the flat clip moved {leak:+.2} dB"); |
| 325 | -fn an_mp4_export_refuses_an_equalized_clip_and_names_where_it_is() { | 384 | + |
| 326 | - let mut p = project(vec![clip(0, 0, 30), clip(30, 0, 30)]); | 385 | + // ...and a timeline nobody equalized never reaches the encoder at all: its |
| 327 | - assert!(p.set_eq(Lane::A1, 1, Some(boost()))); | 386 | + // audio track is still the source's own packets, which |
| 328 | - | 387 | + // `export::exported_packets_are_the_copied_stream` holds to the byte. |
| 329 | - let out = out_path("refused", "mp4"); | ||
| 330 | - let handle = engine::export::start(p.clone(), meta(), &out, &ExportSettings::default()); | ||
| 331 | - let err = wait(&handle, Duration::from_secs(60)) | ||
| 332 | - .expect_err("an equalized clip cannot leave through the copy path") | ||
| 333 | - .to_string(); | ||
| 334 | - println!("mp4 refusal: {err}"); | ||
| 335 | - assert!(err.contains("00:01"), "the refusal names the clip: {err}"); | ||
| 336 | - assert!(err.contains("equalizer"), "{err}"); | ||
| 337 | - assert!(err.contains("WAV or FLAC"), "and the way out: {err}"); | ||
| 338 | - assert!(!out.exists(), "a refused export leaves no file"); | ||
| 339 | - | ||
| 340 | - // Taking the curve off is all it takes -- the refusal is about the setting, | ||
| 341 | - // never about the clip having once had one. | ||
| 342 | - assert!(p.set_eq(Lane::A1, 1, None)); | ||
| 343 | - let handle = engine::export::start(p, meta(), &out, &ExportSettings::default()); | ||
| 344 | - wait(&handle, Duration::from_secs(120)).expect("a flat timeline exports as mp4"); | ||
| 345 | - std::fs::remove_file(&out).unwrap(); | ||
| 346 | } | 388 | } |
| 347 | 389 | ||
| 348 | /// A band moved while the timeline is playing: `PlaybackSession::set_eq` writes | 390 | /// A band moved while the timeline is playing: `PlaybackSession::set_eq` writes |
| @@ -131,13 +131,19 @@ fn opening_an_h264_matroska_file_shows_frames() { | |||
| 131 | ); | 131 | ); |
| 132 | } | 132 | } |
| 133 | 133 | ||
| 134 | -/// The delivered scope, unchanged by this arm: a Matroska file's *sound* is | 134 | +/// The sound comes with it: a Matroska file's audio is read whatever its picture |
| 135 | -/// still not read, and the notice names the track rather than half-playing it. | 135 | +/// is coded with, so nothing is left for the "cannot be decoded" notice to name. |
| 136 | #[test] | 136 | #[test] |
| 137 | -fn matroska_audio_is_still_not_wired_and_says_so() { | 137 | +fn the_matroska_audio_path_takes_this_file_too() { |
| 138 | - let reason = AudioSession::unsupported(&asset("test_h264.mkv")) | 138 | + let stereo = AudioSession::probe(asset("test_h264.mkv"), 0) |
| 139 | - .expect("unsupported") | 139 | + .expect("probe") |
| 140 | - .expect("the fixture has an AAC track to name"); | 140 | + .expect("the fixture has an AAC track"); |
| 141 | - assert!(reason.contains("A_AAC"), "{reason}"); | 141 | + assert_eq!((stereo.sample_rate, stereo.channels), (44_100, 2)); |
| 142 | - assert!(reason.contains("not wired"), "{reason}"); | 142 | + // ...and it really opens, which is what says the sound plays rather than |
| 143 | + // merely being described. | ||
| 144 | + assert!( | ||
| 145 | + AudioSession::open(asset("test_h264.mkv")) | ||
| 146 | + .expect("open") | ||
| 147 | + .is_some() | ||
| 148 | + ); | ||
| 143 | } | 149 | } |
| @@ -0,0 +1,298 @@ | |||
| 1 | +//! HEVC export: the codec this project could read and not write until OxideAV's | ||
| 2 | +//! pure-Rust H.265 gave it an encoder -- an **intra-only** one, every frame a | ||
| 3 | +//! self-contained IDR, which is the only shape of it fast enough to wait for | ||
| 4 | +//! (the inter modes code 1080p at 0.81 fps across 12 cores; the intra path does | ||
| 5 | +//! 4.30 fps on the same picture). | ||
| 6 | +//! | ||
| 7 | +//! Two things are under test here and neither of them is the encoder's picture | ||
| 8 | +//! quality: that the *containers* say HEVC in the words their readers expect | ||
| 9 | +//! (this project's own demuxer, and ffprobe where it is installed), and that a | ||
| 10 | +//! picture whose height is not a multiple of the 16-sample coding tree block -- | ||
| 11 | +//! 1080, the resolution -- comes back out at its own size, coded padded to 1088 | ||
| 12 | +//! and cropped by the SPS conformance window. | ||
| 13 | +//! | ||
| 14 | +//! ```text | ||
| 15 | +//! cargo test -p engine --release --test hevc_export -- --test-threads=1 | ||
| 16 | +//! ``` | ||
| 17 | +//! | ||
| 18 | +//! Release, always: a debug intra encode is minutes a frame. The 1080p twin | ||
| 19 | +//! needs the `ffmpeg` CLI to make its source and `ffprobe` to read the coded | ||
| 20 | +//! size back; without them it says so and passes, exactly as the hardware tests | ||
| 21 | +//! here do. | ||
| 22 | + | ||
| 23 | +use std::path::{Path, PathBuf}; | ||
| 24 | +use std::process::Command; | ||
| 25 | +use std::time::{Duration, Instant}; | ||
| 26 | + | ||
| 27 | +use engine::demux::{Codec, Demuxer}; | ||
| 28 | +use engine::export::{ExportSettings, Format}; | ||
| 29 | +use engine::{AudioSession, PlaybackSession}; | ||
| 30 | + | ||
| 31 | +fn asset(name: &str) -> PathBuf { | ||
| 32 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 33 | + .join("../../assets") | ||
| 34 | + .join(name) | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +fn out_path(name: &str, ext: &str) -> PathBuf { | ||
| 38 | + let path = std::env::temp_dir().join(format!("ve_hevc_{name}_{}.{ext}", std::process::id())); | ||
| 39 | + let _ = std::fs::remove_file(&path); | ||
| 40 | + let _ = std::fs::remove_file(format!("{}.part", path.display())); | ||
| 41 | + path | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// Runs an export to completion, failing on the deadline rather than hanging. | ||
| 45 | +fn export(session: &PlaybackSession, out: &Path, format: Format) { | ||
| 46 | + let settings = ExportSettings { | ||
| 47 | + format, | ||
| 48 | + ..Default::default() | ||
| 49 | + }; | ||
| 50 | + let handle = session.export_to_with(out, &settings); | ||
| 51 | + let started = Instant::now(); | ||
| 52 | + while !handle.is_finished() { | ||
| 53 | + assert!( | ||
| 54 | + started.elapsed() < Duration::from_secs(300), | ||
| 55 | + "the export did not finish in 300 s" | ||
| 56 | + ); | ||
| 57 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 58 | + } | ||
| 59 | + handle | ||
| 60 | + .result() | ||
| 61 | + .expect("an outcome") | ||
| 62 | + .expect("an HEVC export"); | ||
| 63 | + assert_eq!(handle.progress(), 1.0, "finished at full progress"); | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// Two frames of the A/V fixture: what is under test is the wiring from the | ||
| 67 | +/// format to the muxer, not how long an encoder takes. | ||
| 68 | +fn two_frames() -> PlaybackSession { | ||
| 69 | + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); | ||
| 70 | + assert!(session.cut_at(2.0 / 30.0), "cut two frames off the front"); | ||
| 71 | + assert!(session.delete_clip(engine::project::Lane::V1, 1)); | ||
| 72 | + session | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// The container half, in both boxes: an HEVC export is read back as HEVC, at | ||
| 76 | +/// the size and the count it was written at, with the timeline's sound beside | ||
| 77 | +/// it. The `hvcC` record this writes is the one `demux` parses -- Matroska in | ||
| 78 | +/// `CodecPrivate`, mp4 in the sample entry -- so this is where the writer and | ||
| 79 | +/// the reader either agree or do not. | ||
| 80 | +#[test] | ||
| 81 | +fn an_hevc_export_reopens_through_our_own_demuxer_in_either_container() { | ||
| 82 | + for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] { | ||
| 83 | + let session = two_frames(); | ||
| 84 | + let out = out_path("container", ext); | ||
| 85 | + export(&session, &out, format); | ||
| 86 | + | ||
| 87 | + let (meta, mut demuxer) = Demuxer::open(&out).expect("reopen the export"); | ||
| 88 | + assert_eq!(meta.codec, Codec::Hevc, "{ext}: an HEVC export is HEVC"); | ||
| 89 | + assert_eq!((meta.width, meta.height), (1280, 720), "{ext}"); | ||
| 90 | + assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there"); | ||
| 91 | + // Every access unit comes back, and every one of them is a sync point: | ||
| 92 | + // that is what intra-only means, and it is what makes any frame of the | ||
| 93 | + // file a cut point. | ||
| 94 | + let mut count = 0; | ||
| 95 | + while demuxer.next_access_unit().expect("read").is_some() { | ||
| 96 | + count += 1; | ||
| 97 | + } | ||
| 98 | + assert_eq!(count, 2, "{ext}: every coded picture comes back out"); | ||
| 99 | + assert_eq!( | ||
| 100 | + demuxer.seek_to_sync_at_or_before(1), | ||
| 101 | + 1, | ||
| 102 | + "{ext}: an intra-only file syncs on every frame" | ||
| 103 | + ); | ||
| 104 | + | ||
| 105 | + // ...and the sound with it, through the reader an import opens it by. | ||
| 106 | + let (audio, chunks) = AudioSession::open(&out) | ||
| 107 | + .expect("reopen for its sound") | ||
| 108 | + .expect("an HEVC export has an audio track"); | ||
| 109 | + let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect(); | ||
| 110 | + let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt(); | ||
| 111 | + eprintln!( | ||
| 112 | + "{ext}: {} Hz x{}, rms {rms:.4}, {} bytes", | ||
| 113 | + audio.sample_rate, | ||
| 114 | + audio.channels, | ||
| 115 | + std::fs::metadata(&out).unwrap().len() | ||
| 116 | + ); | ||
| 117 | + assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})"); | ||
| 118 | + std::fs::remove_file(&out).unwrap(); | ||
| 119 | + } | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// The %16 half, and the reason the vendored encoder carries a patch at all: | ||
| 123 | +/// 1080 is not a multiple of the 16-sample CTB, so the picture is coded at | ||
| 124 | +/// 1920x1088 and the SPS crops it back with a §7.4.3.2.1 conformance window. | ||
| 125 | +/// ffprobe is what says whether that worked -- it reads the *bitstream*, not | ||
| 126 | +/// the container's own claim -- and ffmpeg decoding the file without a | ||
| 127 | +/// complaint is what says the stream is legal. | ||
| 128 | +#[test] | ||
| 129 | +fn a_1080p_export_states_1920x1080_through_the_conformance_window() { | ||
| 130 | + let Some(source) = fixture_1080p() else { | ||
| 131 | + eprintln!("no ffmpeg: skipping the 1080p conformance-window twin"); | ||
| 132 | + return; | ||
| 133 | + }; | ||
| 134 | + for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] { | ||
| 135 | + let mut session = PlaybackSession::open(&source).expect("open the 1080p fixture"); | ||
| 136 | + assert!(session.cut_at(2.0 / 30.0)); | ||
| 137 | + assert!(session.delete_clip(engine::project::Lane::V1, 1)); | ||
| 138 | + let out = out_path("1080p", ext); | ||
| 139 | + export(&session, &out, format); | ||
| 140 | + | ||
| 141 | + // The container's own claim first: this project's reader. | ||
| 142 | + let (meta, _) = Demuxer::open(&out).expect("reopen the 1080p export"); | ||
| 143 | + assert_eq!((meta.width, meta.height), (1920, 1080), "{ext}"); | ||
| 144 | + | ||
| 145 | + // ...and the coded size, out of the SPS, by a reader that is not ours. | ||
| 146 | + let probed = probe(&out); | ||
| 147 | + assert_eq!( | ||
| 148 | + probed.as_deref(), | ||
| 149 | + Some("hevc,1920,1080"), | ||
| 150 | + "{ext}: ffprobe reads the cropped size out of the bitstream" | ||
| 151 | + ); | ||
| 152 | + // ...and the whole file decoded, with ffmpeg's own stderr as the test: | ||
| 153 | + // a stream a decoder complains about is not an export. | ||
| 154 | + let decoded = Command::new("ffmpeg") | ||
| 155 | + .args(["-v", "error", "-i"]) | ||
| 156 | + .arg(&out) | ||
| 157 | + .args(["-f", "null", "-"]) | ||
| 158 | + .output() | ||
| 159 | + .expect("run ffmpeg"); | ||
| 160 | + let complaints = String::from_utf8_lossy(&decoded.stderr); | ||
| 161 | + assert!( | ||
| 162 | + decoded.status.success() && complaints.is_empty(), | ||
| 163 | + "{ext}: ffmpeg complained: {complaints}" | ||
| 164 | + ); | ||
| 165 | + std::fs::remove_file(&out).unwrap(); | ||
| 166 | + } | ||
| 167 | + let _ = std::fs::remove_file(&source); | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +/// The loop closed where it matters to a user: the file this wrote is opened | ||
| 171 | +/// again *by edith*, picture and all. HEVC has no software decoder here at all, | ||
| 172 | +/// so the way back in is the plugin -- which is what makes this the twin that | ||
| 173 | +/// needs one, and what makes the test above (the containers, read by the | ||
| 174 | +/// demuxer) the one that does not. | ||
| 175 | +#[test] | ||
| 176 | +#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"] | ||
| 177 | +fn an_hevc_export_decodes_back_into_pictures_through_edith() { | ||
| 178 | + for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] { | ||
| 179 | + let session = two_frames(); | ||
| 180 | + let out = out_path("roundtrip", ext); | ||
| 181 | + export(&session, &out, format); | ||
| 182 | + | ||
| 183 | + let (meta, frames) = engine::DecodeSession::open(&out).expect("decode the export"); | ||
| 184 | + assert_eq!(meta.codec, Codec::Hevc, "{ext}"); | ||
| 185 | + let frames: Vec<_> = frames.into_iter().collect(); | ||
| 186 | + assert_eq!(frames.len(), 2, "{ext}: every written frame decodes back"); | ||
| 187 | + // The picture is the fixture's colour pattern, not black: a conformance | ||
| 188 | + // window read wrong would show as a shifted or empty picture. | ||
| 189 | + for (i, frame) in frames.iter().enumerate() { | ||
| 190 | + assert_eq!((frame.width, frame.height), (1280, 720), "{ext} frame {i}"); | ||
| 191 | + assert!( | ||
| 192 | + frame.bgra.iter().any(|&p| p > 32), | ||
| 193 | + "{ext} frame {i} carries picture" | ||
| 194 | + ); | ||
| 195 | + } | ||
| 196 | + std::fs::remove_file(&out).unwrap(); | ||
| 197 | + } | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// An audio-only timeline has no picture to code, and an HEVC export says so by | ||
| 201 | +/// name exactly as the mp4 and AV1 ones do -- and writes nothing. | ||
| 202 | +#[test] | ||
| 203 | +fn an_audio_only_timeline_is_refused_an_hevc_export_by_name() { | ||
| 204 | + let session = PlaybackSession::open(asset("test_tone.wav")).expect("open the tone"); | ||
| 205 | + let out = out_path("refused", "mkv"); | ||
| 206 | + let settings = ExportSettings { | ||
| 207 | + format: Format::Hevc, | ||
| 208 | + ..Default::default() | ||
| 209 | + }; | ||
| 210 | + let handle = session.export_to_with(&out, &settings); | ||
| 211 | + while !handle.is_finished() { | ||
| 212 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 213 | + } | ||
| 214 | + let refused = handle | ||
| 215 | + .result() | ||
| 216 | + .expect("an outcome") | ||
| 217 | + .expect_err("an audio-only timeline has no picture to code") | ||
| 218 | + .to_string(); | ||
| 219 | + assert!(refused.contains("no picture"), "{refused}"); | ||
| 220 | + assert!(refused.contains("HEVC"), "{refused}"); | ||
| 221 | + assert!(!out.exists(), "nothing is written for a refusal"); | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// A cancelled HEVC export leaves nothing behind -- not the file and not the | ||
| 225 | +/// `.part` the worker was writing. An intra-only export of a whole fixture is | ||
| 226 | +/// long enough to catch mid-flight, and the frame loop checks for a cancel | ||
| 227 | +/// every picture, so this stops in a frame or two rather than at the end. | ||
| 228 | +#[test] | ||
| 229 | +fn a_cancelled_hevc_export_leaves_no_file_behind() { | ||
| 230 | + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); | ||
| 231 | + let out = out_path("cancelled", "mkv"); | ||
| 232 | + let settings = ExportSettings { | ||
| 233 | + format: Format::Hevc, | ||
| 234 | + ..Default::default() | ||
| 235 | + }; | ||
| 236 | + let handle = session.export_to_with(&out, &settings); | ||
| 237 | + handle.cancel(); | ||
| 238 | + let started = Instant::now(); | ||
| 239 | + while !handle.is_finished() { | ||
| 240 | + assert!(started.elapsed() < Duration::from_secs(60), "cancel hung"); | ||
| 241 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 242 | + } | ||
| 243 | + let stopped = handle | ||
| 244 | + .result() | ||
| 245 | + .expect("an outcome") | ||
| 246 | + .expect_err("a cancelled export is an error"); | ||
| 247 | + assert!(stopped.to_string().contains("cancelled"), "{stopped}"); | ||
| 248 | + assert!(!out.exists(), "no output for a cancelled export"); | ||
| 249 | + assert!( | ||
| 250 | + !PathBuf::from(format!("{}.part", out.display())).exists(), | ||
| 251 | + "no partial file either" | ||
| 252 | + ); | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +/// `codec,width,height` of the file's video stream as ffprobe reads it, or | ||
| 256 | +/// `None` where ffprobe is not installed. | ||
| 257 | +fn probe(path: &Path) -> Option<String> { | ||
| 258 | + let out = Command::new("ffprobe") | ||
| 259 | + .args([ | ||
| 260 | + "-v", | ||
| 261 | + "error", | ||
| 262 | + "-select_streams", | ||
| 263 | + "v:0", | ||
| 264 | + "-show_entries", | ||
| 265 | + "stream=codec_name,width,height", | ||
| 266 | + "-of", | ||
| 267 | + "csv=p=0", | ||
| 268 | + ]) | ||
| 269 | + .arg(path) | ||
| 270 | + .output() | ||
| 271 | + .ok()?; | ||
| 272 | + Some(String::from_utf8_lossy(&out.stdout).trim().to_string()) | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +/// A two-second 1920x1080 H.264 fixture in the temp directory -- the assets are | ||
| 276 | +/// all 720p, which is a multiple of 16 in both directions and would leave the | ||
| 277 | +/// crop path untested. `None` where ffmpeg is not installed. | ||
| 278 | +fn fixture_1080p() -> Option<PathBuf> { | ||
| 279 | + let path = out_path("source1080", "mp4"); | ||
| 280 | + let made = Command::new("ffmpeg") | ||
| 281 | + .args([ | ||
| 282 | + "-y", | ||
| 283 | + "-f", | ||
| 284 | + "lavfi", | ||
| 285 | + "-i", | ||
| 286 | + "testsrc2=size=1920x1080:rate=30:duration=1", | ||
| 287 | + "-c:v", | ||
| 288 | + "libx264", | ||
| 289 | + "-profile:v", | ||
| 290 | + "baseline", | ||
| 291 | + "-pix_fmt", | ||
| 292 | + "yuv420p", | ||
| 293 | + ]) | ||
| 294 | + .arg(&path) | ||
| 295 | + .output() | ||
| 296 | + .ok()?; | ||
| 297 | + made.status.success().then_some(path) | ||
| 298 | +} | ||
| @@ -0,0 +1,245 @@ | |||
| 1 | +//! HEVC in Matroska, 8- and 10-bit, sound included: the shape a film off a disc | ||
| 2 | +//! arrives in, and the one the AV1 walk was written for one codec too early. | ||
| 3 | +//! | ||
| 4 | +//! Three things meet here and each is checked on its own: the demuxer reads an | ||
| 5 | +//! `hvcC` out of a `CodecPrivate` and reframes Matroska blocks to Annex-B, the | ||
| 6 | +//! plugin decodes Main 10 through a P010 surface pool, and the sound -- 5.1 AAC | ||
| 7 | +//! at 48 kHz -- is read by symphonia's mkv reader, decoded by `rusty_aac` and | ||
| 8 | +//! folded to the stereo one output device carries. | ||
| 9 | +//! | ||
| 10 | +//! The container and audio checks need nothing installed. The decode twins need | ||
| 11 | +//! a built `libengine_hw.so` and a VA-API driver with an HEVC decode entrypoint | ||
| 12 | +//! (`vainfo | grep HEVC`), so they are `#[ignore]`d: | ||
| 13 | +//! | ||
| 14 | +//! ```text | ||
| 15 | +//! cargo build -p engine -p engine-hw --release | ||
| 16 | +//! LD_LIBRARY_PATH=target/release \ | ||
| 17 | +//! cargo test -p engine --release --test hevc_mkv -- --include-ignored --nocapture | ||
| 18 | +//! ``` | ||
| 19 | + | ||
| 20 | +use std::path::PathBuf; | ||
| 21 | + | ||
| 22 | +use engine::demux::{Codec, Demuxer}; | ||
| 23 | +use engine::hw::HwSession; | ||
| 24 | +use engine::{AudioSession, DecodeSession}; | ||
| 25 | + | ||
| 26 | +/// 1280x720@30, 2 s, keyed twice -- see `scripts/gen_fixtures.sh`. | ||
| 27 | +const FRAMES: u32 = 60; | ||
| 28 | + | ||
| 29 | +fn asset(name: &str) -> PathBuf { | ||
| 30 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 31 | + .join("../../assets") | ||
| 32 | + .join(name) | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// The container half: an HEVC track in an mkv is found, named, measured, and | ||
| 36 | +/// its blocks come back as Annex-B access units with the parameter sets in | ||
| 37 | +/// front of every keyframe. Matroska indexes nothing, so all four numbers come | ||
| 38 | +/// out of the walk. | ||
| 39 | +#[test] | ||
| 40 | +fn the_demuxer_reads_hevc_out_of_a_matroska_file() { | ||
| 41 | + for (name, depth) in [("test_hevc.mkv", 8), ("test_hevc10.mkv", 10)] { | ||
| 42 | + let (meta, mut demuxer) = Demuxer::open(&asset(name)).unwrap_or_else(|e| panic!("{name}: {e}")); | ||
| 43 | + assert_eq!(meta.codec, Codec::Hevc, "{name}"); | ||
| 44 | + assert_eq!((meta.width, meta.height), (1280, 720), "{name}"); | ||
| 45 | + assert!((meta.frame_rate - 30.0).abs() < 1e-6, "{name}: {}", meta.frame_rate); | ||
| 46 | + assert_eq!(meta.frame_count, FRAMES, "{name}"); | ||
| 47 | + // What picks the P010 surface pool over the NV12 one. | ||
| 48 | + assert_eq!(demuxer.bit_depth(), depth, "{name}"); | ||
| 49 | + | ||
| 50 | + let first = demuxer | ||
| 51 | + .next_access_unit() | ||
| 52 | + .expect("read") | ||
| 53 | + .expect("a first access unit"); | ||
| 54 | + // A Matroska block is length-prefixed NALs, exactly as an mp4 sample is, | ||
| 55 | + // and what a decoder has to be handed is Annex-B with the VPS (NAL type | ||
| 56 | + // 32) out of the `CodecPrivate` in front. | ||
| 57 | + assert_eq!(&first[..4], [0, 0, 0, 1], "{name}: Annex-B start code"); | ||
| 58 | + assert_eq!( | ||
| 59 | + (first[4] >> 1) & 0x3f, | ||
| 60 | + 32, | ||
| 61 | + "{name}: the keyframe leads with the VPS off the CodecPrivate" | ||
| 62 | + ); | ||
| 63 | + let mut count = 1; | ||
| 64 | + while demuxer.next_access_unit().expect("read").is_some() { | ||
| 65 | + count += 1; | ||
| 66 | + } | ||
| 67 | + assert_eq!(count, FRAMES, "{name}: every block came back out"); | ||
| 68 | + | ||
| 69 | + // The fixture is keyed twice (`-g 30`), and a seek may only ever land on | ||
| 70 | + // a keyframe. *Which* block that is, is the encoder's business: an HEVC | ||
| 71 | + // stream with B-frames is stored in decode order and the second IDR | ||
| 72 | + // lands a couple of blocks before the display frame it shows, so the | ||
| 73 | + // check is on the rule rather than on the number. | ||
| 74 | + let second = demuxer.seek_to_sync_at_or_before(FRAMES - 1); | ||
| 75 | + assert!( | ||
| 76 | + second > 0 && second < i64::from(FRAMES), | ||
| 77 | + "{name}: a second keyframe, at {second}" | ||
| 78 | + ); | ||
| 79 | + assert_eq!( | ||
| 80 | + demuxer.seek_to_sync_at_or_before(second as u32), | ||
| 81 | + second, | ||
| 82 | + "{name}: landing on a keyframe stays on it" | ||
| 83 | + ); | ||
| 84 | + assert_eq!( | ||
| 85 | + demuxer.seek_to_sync_at_or_before(second as u32 - 1), | ||
| 86 | + 0, | ||
| 87 | + "{name}: one block earlier there is only the first keyframe" | ||
| 88 | + ); | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + // The invariant: the AV1 mkv and the HEVC mp4 still read as themselves. | ||
| 92 | + let (av1, _) = Demuxer::open(&asset("test_av1.mkv")).expect("open test_av1.mkv"); | ||
| 93 | + assert_eq!(av1.codec, Codec::Av1); | ||
| 94 | + let (mp4, hevc) = Demuxer::open(&asset("test_hevc.mp4")).expect("open test_hevc.mp4"); | ||
| 95 | + assert_eq!(mp4.codec, Codec::Hevc); | ||
| 96 | + assert_eq!(hevc.bit_depth(), 8); | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// A Matroska file's sound is read now, and a 5.1 track joins the timeline as | ||
| 100 | +/// the stereo source the fold makes of it. | ||
| 101 | +#[test] | ||
| 102 | +fn matroska_audio_is_read_and_five_one_arrives_as_stereo() { | ||
| 103 | + let stereo = AudioSession::probe(asset("test_hevc.mkv"), 0) | ||
| 104 | + .expect("probe") | ||
| 105 | + .expect("the fixture has an AAC track"); | ||
| 106 | + assert_eq!((stereo.sample_rate, stereo.channels), (44_100, 2)); | ||
| 107 | + | ||
| 108 | + let wide = AudioSession::probe(asset("test_hevc10.mkv"), 0) | ||
| 109 | + .expect("probe") | ||
| 110 | + .expect("the fixture has a 5.1 AAC track"); | ||
| 111 | + assert_eq!( | ||
| 112 | + (wide.sample_rate, wide.channels), | ||
| 113 | + (48_000, 2), | ||
| 114 | + "5.1 is folded to the layout one output device carries" | ||
| 115 | + ); | ||
| 116 | + | ||
| 117 | + // The picker's row, which is what a user chooses a stream from. | ||
| 118 | + let streams = AudioSession::probe_streams(asset("test_hevc10.mkv")).expect("streams"); | ||
| 119 | + assert_eq!(streams.len(), 1); | ||
| 120 | + assert_eq!(streams[0].codec, "aac"); | ||
| 121 | + assert_eq!(streams[0].channels, 2); | ||
| 122 | + assert!(streams[0].decodable); | ||
| 123 | + | ||
| 124 | + // ...and nothing is left to explain away: a file whose sound plays is not | ||
| 125 | + // one the "cannot be decoded" notice may name. | ||
| 126 | + assert!( | ||
| 127 | + AudioSession::open(asset("test_hevc10.mkv")) | ||
| 128 | + .expect("open") | ||
| 129 | + .is_some() | ||
| 130 | + ); | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// The fold, measured on the tones the fixture puts one per channel: every | ||
| 134 | +/// channel but the LFE reaches the stereo pair, the surrounds and the centre at | ||
| 135 | +/// -3 dB of the fronts, and nothing crosses sides. | ||
| 136 | +/// | ||
| 137 | +/// Which tone is which *position* is the encoder's business (ffmpeg's AAC | ||
| 138 | +/// encoder does not keep the order they were written in), so the check is on | ||
| 139 | +/// the shape: two full-weight tones, one per side; one tone in both at -3 dB; | ||
| 140 | +/// two more at -3 dB, one per side; and the 60 Hz LFE nowhere. | ||
| 141 | +#[test] | ||
| 142 | +fn the_five_one_fold_keeps_every_channel_but_the_lfe() { | ||
| 143 | + let (meta, rx) = AudioSession::open(asset("test_hevc10.mkv")) | ||
| 144 | + .expect("open") | ||
| 145 | + .expect("the fixture has sound"); | ||
| 146 | + assert_eq!((meta.sample_rate, meta.channels), (48_000, 2)); | ||
| 147 | + let mut left = Vec::new(); | ||
| 148 | + let mut right = Vec::new(); | ||
| 149 | + for chunk in rx { | ||
| 150 | + for pair in chunk.samples.chunks_exact(2) { | ||
| 151 | + left.push(pair[0]); | ||
| 152 | + right.push(pair[1]); | ||
| 153 | + } | ||
| 154 | + } | ||
| 155 | + // Past the encoder priming, and a whole number of cycles of every tone. | ||
| 156 | + let (left, right) = (&left[9_600..57_600], &right[9_600..57_600]); | ||
| 157 | + let tones = [60.0, 220.0, 440.0, 880.0, 1320.0, 1760.0]; | ||
| 158 | + let l: Vec<f32> = tones.iter().map(|f| tone(left, *f)).collect(); | ||
| 159 | + let r: Vec<f32> = tones.iter().map(|f| tone(right, *f)).collect(); | ||
| 160 | + | ||
| 161 | + // The source tones are at 0.125 (lavfi's `sine`), and the fold divides by | ||
| 162 | + // the sum of its own coefficients so a full-scale source cannot clip. | ||
| 163 | + let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2); | ||
| 164 | + let full = 0.125 * norm; | ||
| 165 | + let quiet = full * std::f32::consts::FRAC_1_SQRT_2; | ||
| 166 | + let near = |got: f32, want: f32| (got - want).abs() < 0.01; | ||
| 167 | + | ||
| 168 | + assert!( | ||
| 169 | + near(l[0], 0.0) && near(r[0], 0.0), | ||
| 170 | + "the LFE is dropped: {} {}", | ||
| 171 | + l[0], | ||
| 172 | + r[0] | ||
| 173 | + ); | ||
| 174 | + let both = tones | ||
| 175 | + .iter() | ||
| 176 | + .enumerate() | ||
| 177 | + .filter(|(i, _)| near(l[*i], quiet) && near(r[*i], quiet)) | ||
| 178 | + .count(); | ||
| 179 | + assert_eq!(both, 1, "exactly the centre reaches both sides: {l:?} {r:?}"); | ||
| 180 | + let fronts = tones | ||
| 181 | + .iter() | ||
| 182 | + .enumerate() | ||
| 183 | + .filter(|(i, _)| near(l[*i], full) != near(r[*i], full)) | ||
| 184 | + .count(); | ||
| 185 | + assert_eq!(fronts, 2, "one front channel per side: {l:?} {r:?}"); | ||
| 186 | + let surrounds = tones | ||
| 187 | + .iter() | ||
| 188 | + .enumerate() | ||
| 189 | + .filter(|(i, _)| { | ||
| 190 | + (near(l[*i], quiet) && near(r[*i], 0.0)) || (near(r[*i], quiet) && near(l[*i], 0.0)) | ||
| 191 | + }) | ||
| 192 | + .count(); | ||
| 193 | + assert_eq!(surrounds, 2, "one surround per side, at -3 dB: {l:?} {r:?}"); | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +/// Amplitude of one frequency in `x` (Goertzel), which is what "this channel | ||
| 197 | +/// reached that output" is measured with. | ||
| 198 | +fn tone(x: &[f32], freq: f32) -> f32 { | ||
| 199 | + let w = 2.0 * std::f32::consts::PI * freq / 48_000.0; | ||
| 200 | + let (cos, sin) = (w.cos(), w.sin()); | ||
| 201 | + let (mut s1, mut s2) = (0.0f32, 0.0f32); | ||
| 202 | + for &v in x { | ||
| 203 | + let s0 = v + 2.0 * cos * s1 - s2; | ||
| 204 | + s2 = s1; | ||
| 205 | + s1 = s0; | ||
| 206 | + } | ||
| 207 | + let (re, im) = (s1 - s2 * cos, s2 * sin); | ||
| 208 | + 2.0 * (re * re + im * im).sqrt() / x.len() as f32 | ||
| 209 | +} | ||
| 210 | + | ||
| 211 | +/// The picture, on the hardware that decodes it: every frame of both files, at | ||
| 212 | +/// the size the container declared. Main 10 goes through the P010 pool and is | ||
| 213 | +/// read back to the same 8-bit I420 the 8-bit path hands out, so the only thing | ||
| 214 | +/// this can tell them apart by is that neither errors. | ||
| 215 | +#[test] | ||
| 216 | +#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"] | ||
| 217 | +fn the_plugin_decodes_hevc_in_matroska_at_both_depths() { | ||
| 218 | + for name in ["test_hevc.mkv", "test_hevc10.mkv"] { | ||
| 219 | + let mut hw = HwSession::open(&asset(name)).expect("no hardware decode plugin available"); | ||
| 220 | + let mut count = 0; | ||
| 221 | + let mut lit = 0; | ||
| 222 | + while let Some((y, _, _, w, h)) = hw.next_frame().expect("hardware decode") { | ||
| 223 | + assert_eq!((w, h), (1280, 720), "{name} frame {count}"); | ||
| 224 | + // Not a black frame: the fixture is a colour pattern, and a P010 | ||
| 225 | + // surface read back through the NV12 path would come out as noise | ||
| 226 | + // or as nothing at all. | ||
| 227 | + if y.iter().any(|&s| s > 32) { | ||
| 228 | + lit += 1; | ||
| 229 | + } | ||
| 230 | + count += 1; | ||
| 231 | + } | ||
| 232 | + assert_eq!(count, FRAMES as usize, "{name}"); | ||
| 233 | + assert_eq!(lit, count, "{name}: every frame carries picture"); | ||
| 234 | + } | ||
| 235 | +} | ||
| 236 | + | ||
| 237 | +/// ...and the same file through the session a clip actually plays from, which | ||
| 238 | +/// is where a codec that only the plugin can decode is refused if it cannot. | ||
| 239 | +#[test] | ||
| 240 | +#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"] | ||
| 241 | +fn a_ten_bit_matroska_clip_decodes_through_the_ordinary_session() { | ||
| 242 | + let (meta, frames) = DecodeSession::open(asset("test_hevc10.mkv")).expect("open"); | ||
| 243 | + assert_eq!(meta.codec, Codec::Hevc); | ||
| 244 | + assert_eq!(frames.iter().count(), FRAMES as usize); | ||
| 245 | +} | ||
| @@ -208,6 +208,25 @@ fn a_still_trims_out_to_its_cap_and_no_further() { | |||
| 208 | // ...and back in, which is the half a five-second title card actually uses. | 208 | // ...and back in, which is the half a five-second title card actually uses. |
| 209 | assert!(session.trim_clip(Lane::V1, 0, Edge::End, clip.start + 60)); | 209 | assert!(session.trim_clip(Lane::V1, 0, Edge::End, clip.start + 60)); |
| 210 | assert_eq!(session.lane_clips(Lane::V1)[0].len(), 60); | 210 | assert_eq!(session.lane_clips(Lane::V1)[0].len(), 60); |
| 211 | + | ||
| 212 | + // The *head* is the same story from the other side: a still has no first | ||
| 213 | + // frame to walk an in-point back to, so its left edge stretches out to the | ||
| 214 | + // same cap. Pulled in first, since a clip at frame 0 has nowhere to go. | ||
| 215 | + assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 20)); | ||
| 216 | + let clip = session.lane_clips(Lane::V1)[0]; | ||
| 217 | + assert_eq!((clip.start, clip.len()), (20, 40)); | ||
| 218 | + assert_eq!( | ||
| 219 | + session.trim_room(Lane::V1, 0, Edge::Start), | ||
| 220 | + Some((0, clip.end() - 1)), | ||
| 221 | + "out to frame 0: the cap is further off than the timeline reaches" | ||
| 222 | + ); | ||
| 223 | + assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 0), "dragged out"); | ||
| 224 | + let clip = session.lane_clips(Lane::V1)[0]; | ||
| 225 | + assert_eq!( | ||
| 226 | + (clip.start, clip.in_frame, clip.len()), | ||
| 227 | + (0, 0, 60), | ||
| 228 | + "longer by what the head took, and still read from the first frame" | ||
| 229 | + ); | ||
| 211 | } | 230 | } |
| 212 | 231 | ||
| 213 | /// The *clipboard* door, which is the second way a clip picks its lanes and | 232 | /// The *clipboard* door, which is the second way a clip picks its lanes and |
| @@ -341,6 +360,95 @@ fn a_still_survives_the_project_round_trip() { | |||
| 341 | let _ = std::fs::remove_dir_all(&dir); | 360 | let _ = std::fs::remove_dir_all(&dir); |
| 342 | } | 361 | } |
| 343 | 362 | ||
| 363 | +/// The save renumbers sources by first use, so a still at the head of `V1` | ||
| 364 | +/// comes back as **source 0** however the session was scaffolded -- and source | ||
| 365 | +/// 0 is what everything used to read the timeline off. A picture defines no | ||
| 366 | +/// frame rate and has no sound, so the reload used to read this project as 30 | ||
| 367 | +/// fps (refusing the 25 fps footage still on `A1` by name) and open the output | ||
| 368 | +/// device on a PNG (a timeline that plays silent although its clips have | ||
| 369 | +/// sound). Nothing may assume what source 0 *is*: the rate comes from the first | ||
| 370 | +/// source that has one, and the sound from the first that could have any. | ||
| 371 | +#[test] | ||
| 372 | +fn a_still_at_saved_source_zero_keeps_the_rate_and_the_sound() { | ||
| 373 | + pin_software(); | ||
| 374 | + let dir = std::env::temp_dir().join(format!("ve_still_first_{}", std::process::id())); | ||
| 375 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 376 | + std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 377 | + let media = dir.join("test_25fps.mp4"); | ||
| 378 | + let still = dir.join("test_still.png"); | ||
| 379 | + std::fs::copy(asset("test_25fps.mp4"), &media).expect("copy the video"); | ||
| 380 | + std::fs::copy(asset("test_still.png"), &still).expect("copy the still"); | ||
| 381 | + | ||
| 382 | + // 25 fps, which no still is ever given: the rate alone says which source | ||
| 383 | + // the reload scaffolded from. | ||
| 384 | + let mut session = PlaybackSession::open(&media).expect("open the fixture"); | ||
| 385 | + session.set_gain(0.0); | ||
| 386 | + assert!((session.meta().frame_rate - 25.0).abs() < 0.01); | ||
| 387 | + session.import(&still).expect("a picture"); | ||
| 388 | + // Over the head of V1, where it takes the whole take's picture: the sound | ||
| 389 | + // stays on A1, so the still is the first clip in save order and the video | ||
| 390 | + // is a source only the audio lane names. | ||
| 391 | + assert!( | ||
| 392 | + session | ||
| 393 | + .place_stream_at(0.0, &still, 0, Some(Lane::V1)) | ||
| 394 | + .expect("a still joins any timeline") | ||
| 395 | + ); | ||
| 396 | + assert!(session.lane_clips(Lane::V1).len() == 1 && session.lane_clips(Lane::A1).len() == 1); | ||
| 397 | + | ||
| 398 | + let project = dir.join("still_first.edith"); | ||
| 399 | + session.save_project(&project).expect("save"); | ||
| 400 | + let text = std::fs::read_to_string(&project).expect("read the project"); | ||
| 401 | + let source_0 = text | ||
| 402 | + .lines() | ||
| 403 | + .find(|l| l.starts_with("source ")) | ||
| 404 | + .expect("a source line"); | ||
| 405 | + assert!( | ||
| 406 | + source_0.contains("test_still.png"), | ||
| 407 | + "the premise: the save put the still at index 0 -- {source_0}" | ||
| 408 | + ); | ||
| 409 | + | ||
| 410 | + let reopened = PlaybackSession::open_project(&project).expect("a saved project always reopens"); | ||
| 411 | + assert!( | ||
| 412 | + (reopened.meta().frame_rate - 25.0).abs() < 0.01, | ||
| 413 | + "the footage's rate, not the still's 30: {}", | ||
| 414 | + reopened.meta().frame_rate | ||
| 415 | + ); | ||
| 416 | + // The same sound, at the same place, playing the same file -- by a *new* | ||
| 417 | + // index, which is the renumbering this whole test is about. | ||
| 418 | + let (sound, was) = ( | ||
| 419 | + reopened.lane_clips(Lane::A1)[0], | ||
| 420 | + session.lane_clips(Lane::A1)[0], | ||
| 421 | + ); | ||
| 422 | + assert_eq!( | ||
| 423 | + (sound.start, sound.in_frame, sound.out_frame), | ||
| 424 | + (was.start, was.in_frame, was.out_frame) | ||
| 425 | + ); | ||
| 426 | + assert!( | ||
| 427 | + reopened.sources()[sound.source] | ||
| 428 | + .path | ||
| 429 | + .ends_with("test_25fps.mp4"), | ||
| 430 | + "the take's sound still names the video" | ||
| 431 | + ); | ||
| 432 | + assert!( | ||
| 433 | + reopened.audio_disabled_reason().is_none(), | ||
| 434 | + "a still is not a reason a timeline is silent: {:?}", | ||
| 435 | + reopened.audio_disabled_reason() | ||
| 436 | + ); | ||
| 437 | + // And the sound itself, through the very opener a seek builds its worker | ||
| 438 | + // with: source 0 is the PNG here, and one opened unconditionally is an | ||
| 439 | + // error that takes every lane's audio down with it. | ||
| 440 | + let sources: Vec<_> = reopened | ||
| 441 | + .sources() | ||
| 442 | + .iter() | ||
| 443 | + .map(|s| (s.path.clone(), s.audio_stream)) | ||
| 444 | + .collect(); | ||
| 445 | + let (meta, _rx) = engine::AudioSession::open_multi_streams(&sources, &[(Some(1), 0.0, 1.0)]) | ||
| 446 | + .expect("the worker opens over a still at index 0") | ||
| 447 | + .expect("the take on A1 has sound"); | ||
| 448 | + assert_eq!(meta.sample_rate, 44_100, "the take's own rate"); | ||
| 449 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 450 | +} | ||
| 451 | + | ||
| 344 | /// The export is what was watched: a timeline of video then still comes back | 452 | /// The export is what was watched: a timeline of video then still comes back |
| 345 | /// out of the mp4 as video then still, with the still's own colours in it. | 453 | /// out of the mp4 as video then still, with the still's own colours in it. |
| 346 | #[test] | 454 | #[test] |
| @@ -363,14 +363,48 @@ fn two_audio_lanes_are_summed() { | |||
| 363 | out_two / out_one | 363 | out_two / out_one |
| 364 | ); | 364 | ); |
| 365 | 365 | ||
| 366 | - // The mp4 path *copies* AAC packets and cannot mix: it refuses by name | 366 | + // ...and the mp4 of the same timeline carries that very mix. It used to be |
| 367 | - // rather than writing a file missing half its sound. | 367 | + // a refusal by name -- the mp4 path *copies* AAC packets and a mix is not a |
| 368 | + // copy -- and a refusal is what a file missing half its sound deserves; | ||
| 369 | + // this decodes both lanes and encodes the sum instead (`export::copy_audio` | ||
| 370 | + // routes to `encode_audio`), which is the same mix the WAV above measured. | ||
| 368 | let out = out_path("mixed", "mp4"); | 371 | let out = out_path("mixed", "mp4"); |
| 369 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); | 372 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); |
| 370 | - let err = wait(&handle, Duration::from_secs(120)).expect_err("mp4 cannot mix"); | 373 | + wait(&handle, Duration::from_secs(180)).expect("an mp4 of two audio lanes"); |
| 371 | - println!("mp4 refusal: {err}"); | 374 | + let (audio, chunks) = engine::AudioSession::open(&out) |
| 372 | - assert!(err.to_string().contains("2 audio lanes"), "{err}"); | 375 | + .expect("reopen the export") |
| 373 | - assert!(!out.exists(), "a refused export leaves no file"); | 376 | + .expect("it has an audio track"); |
| 377 | + let coded: Vec<f64> = chunks | ||
| 378 | + .into_iter() | ||
| 379 | + .flat_map(|c| c.samples) | ||
| 380 | + .map(|s| f64::from(s) * f64::from(i16::MAX)) | ||
| 381 | + .collect(); | ||
| 382 | + let per = f64::from(audio.sample_rate) / FPS * f64::from(audio.channels); | ||
| 383 | + let window = |from: u32, to: u32| { | ||
| 384 | + let (a, b) = ( | ||
| 385 | + (f64::from(from) * per) as usize, | ||
| 386 | + (f64::from(to) * per) as usize, | ||
| 387 | + ); | ||
| 388 | + let w = &coded[a.min(coded.len())..b.min(coded.len())]; | ||
| 389 | + (w.iter().map(|s| s * s).sum::<f64>() / w.len().max(1) as f64).sqrt() | ||
| 390 | + }; | ||
| 391 | + let (coded_over, coded_out) = ( | ||
| 392 | + window(TOP_IN + 5, TOP_OUT - 5), | ||
| 393 | + window(TOP_OUT + 5, TOTAL - 5), | ||
| 394 | + ); | ||
| 395 | + println!("mp4 rms: under A2 {coded_over:.1}, past it {coded_out:.1}"); | ||
| 396 | + // Against the WAV of the same timeline, not against a figure: one lossy | ||
| 397 | + // generation moves the level by a fraction of a dB and nothing here is | ||
| 398 | + // measuring the encoder. | ||
| 399 | + assert!( | ||
| 400 | + (coded_over / over_two - 1.0).abs() < 0.1, | ||
| 401 | + "the mp4's overlap is {coded_over:.1} against the mix's {over_two:.1}" | ||
| 402 | + ); | ||
| 403 | + assert!( | ||
| 404 | + (coded_out / out_two - 1.0).abs() < 0.1, | ||
| 405 | + "past A2 the mp4 is {coded_out:.1} against the mix's {out_two:.1}" | ||
| 406 | + ); | ||
| 407 | + std::fs::remove_file(&out).unwrap(); | ||
| 374 | } | 408 | } |
| 375 | 409 | ||
| 376 | /// A project with one lane of each kind is what it always was: the composite of | 410 | /// A project with one lane of each kind is what it always was: the composite of |
| @@ -0,0 +1,419 @@ | |||
| 1 | +//! Clips shot at other frame rates on one timeline: what a 25 fps and a 23.976 | ||
| 2 | +//! fps file do on the 30 fps timeline `test_av.mp4` scaffolds. | ||
| 3 | +//! | ||
| 4 | +//! Everything goes through the front door -- `import`, `place_stream_at`, | ||
| 5 | +//! `seek`, `export_to_with`, `open_project` -- because the whole claim is that a | ||
| 6 | +//! *user* can put two rates on one timeline and watch both at the speed they | ||
| 7 | +//! were shot at. `project.rs`'s own `rate_composes_with_speed` owns the | ||
| 8 | +//! arithmetic; what is measured here is that the pictures and the file agree | ||
| 9 | +//! with it. | ||
| 10 | +//! | ||
| 11 | +//! ```text | ||
| 12 | +//! cargo test -p engine --test mixed_fps | ||
| 13 | +//! ``` | ||
| 14 | + | ||
| 15 | +use std::path::{Path, PathBuf}; | ||
| 16 | +use std::thread::sleep; | ||
| 17 | +use std::time::{Duration, Instant}; | ||
| 18 | + | ||
| 19 | +use engine::export::{ExportSettings, Format}; | ||
| 20 | +use engine::project::{Edge, Lane, Rate, Speed}; | ||
| 21 | +use engine::{DecodeSession, Frame, PlaybackSession}; | ||
| 22 | + | ||
| 23 | +/// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines. | ||
| 24 | +const FPS: f64 = 30.0; | ||
| 25 | + | ||
| 26 | +fn asset(name: &str) -> PathBuf { | ||
| 27 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 28 | + .join("../../assets") | ||
| 29 | + .join(name) | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/// Silent, for `tests/playback.rs`'s reason: the suite plays real files. | ||
| 33 | +fn open(path: impl AsRef<Path>) -> PlaybackSession { | ||
| 34 | + let session = PlaybackSession::open(path).expect("open"); | ||
| 35 | + session.set_gain(0.0); | ||
| 36 | + session | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame { | ||
| 40 | + let deadline = Instant::now() + Duration::from_secs(10); | ||
| 41 | + loop { | ||
| 42 | + if let Some(frame) = session.try_frame() { | ||
| 43 | + return frame; | ||
| 44 | + } | ||
| 45 | + assert!(Instant::now() < deadline, "no frame after {what}"); | ||
| 46 | + sleep(Duration::from_millis(4)); | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// One frame of a file, decoded straight from it: the picture a mapping is | ||
| 51 | +/// checked against, in the file's *own* numbering. | ||
| 52 | +fn source_frame(path: &Path, index: u32) -> Vec<u8> { | ||
| 53 | + let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range"); | ||
| 54 | + let frame = rx | ||
| 55 | + .recv_timeout(Duration::from_secs(10)) | ||
| 56 | + .expect("reference frame"); | ||
| 57 | + assert_eq!(frame.index, index, "open_range starts where it is told"); | ||
| 58 | + frame.bgra | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// Imports `path` and drags it onto the end of the timeline, the way a library | ||
| 62 | +/// row reaches a lane. | ||
| 63 | +fn import_and_place(session: &mut PlaybackSession, path: &Path) { | ||
| 64 | + session.import(path).expect("the file joins this timeline"); | ||
| 65 | + let end = session.timeline_duration(); | ||
| 66 | + assert!( | ||
| 67 | + session | ||
| 68 | + .place_stream_at(end, path, 0, None) | ||
| 69 | + .expect("a file just imported is on this timeline"), | ||
| 70 | + "the drag onto the end of the timeline" | ||
| 71 | + ); | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +fn wait(handle: &engine::ExportHandle) -> engine::Result<()> { | ||
| 75 | + let deadline = Instant::now() + Duration::from_secs(180); | ||
| 76 | + while !handle.is_finished() { | ||
| 77 | + assert!(Instant::now() < deadline, "export did not finish"); | ||
| 78 | + sleep(Duration::from_millis(20)); | ||
| 79 | + } | ||
| 80 | + handle.result().expect("a finished export has an outcome") | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// How different two pictures are, sampled: a re-encode moves every pixel a | ||
| 84 | +/// little and a *different* picture of `testsrc2` moves them a lot, so the two | ||
| 85 | +/// are never close to the threshold below. | ||
| 86 | +fn difference(a: &[u8], b: &[u8]) -> f64 { | ||
| 87 | + assert_eq!(a.len(), b.len(), "two pictures of one size"); | ||
| 88 | + let (mut sum, mut n) = (0f64, 0u32); | ||
| 89 | + for i in (0..a.len()).step_by(997) { | ||
| 90 | + sum += f64::from(a[i].abs_diff(b[i])); | ||
| 91 | + n += 1; | ||
| 92 | + } | ||
| 93 | + sum / f64::from(n.max(1)) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// A file's length is the seconds it lasts, in the timeline's frames -- not the | ||
| 97 | +/// frames it holds. That is the whole of what placing another rate means: 50 | ||
| 98 | +/// frames of 25 fps and 48 of 23.976 fps are both two seconds, and two seconds | ||
| 99 | +/// of a 30 fps timeline is 60 frames. | ||
| 100 | +#[test] | ||
| 101 | +fn a_file_at_another_rate_is_placed_for_the_seconds_it_lasts() { | ||
| 102 | + let mut session = open(asset("test_av.mp4")); | ||
| 103 | + assert_eq!(session.file_frames(&asset("test_av.mp4")), 150, "5 s at 30"); | ||
| 104 | + | ||
| 105 | + let pal = asset("test_25fps.mp4"); | ||
| 106 | + session | ||
| 107 | + .import(&pal) | ||
| 108 | + .expect("25 fps joins a 30 fps timeline"); | ||
| 109 | + assert_eq!(session.file_frames(&pal), 60, "50 frames at 25 fps is 2 s"); | ||
| 110 | + | ||
| 111 | + // 24000/1001: 48 frames is 2.002 s, which is 60.06 frames of 30 fps -- | ||
| 112 | + // rounded *up*, so the last picture is still reachable by a trim. | ||
| 113 | + let ntsc = asset("test_23976fps.mp4"); | ||
| 114 | + session.import(&ntsc).expect("23.976 joins it too"); | ||
| 115 | + assert_eq!(session.file_frames(&ntsc), 61); | ||
| 116 | + | ||
| 117 | + // ...and placed, both are as long on the timeline as they are in the ear. | ||
| 118 | + let end = session.timeline_duration(); | ||
| 119 | + session | ||
| 120 | + .place_stream_at(end, &pal, 0, None) | ||
| 121 | + .expect("the drag"); | ||
| 122 | + assert!( | ||
| 123 | + (session.timeline_duration() - (5.0 + 2.0)).abs() < 1e-9, | ||
| 124 | + "a 2 s clip made the timeline {} s", | ||
| 125 | + session.timeline_duration() | ||
| 126 | + ); | ||
| 127 | + let end = session.timeline_duration(); | ||
| 128 | + session | ||
| 129 | + .place_stream_at(end, &ntsc, 0, None) | ||
| 130 | + .expect("the drag"); | ||
| 131 | + assert!( | ||
| 132 | + (session.timeline_duration() - (5.0 + 2.0 + 61. / FPS)).abs() < 1e-9, | ||
| 133 | + "{} s", | ||
| 134 | + session.timeline_duration() | ||
| 135 | + ); | ||
| 136 | + // ...and the sound that came down with each take is the same length as its | ||
| 137 | + // picture: a placed take is one linked group, so a rate that stretched only | ||
| 138 | + // the picture would slide the two apart on the very first drag. | ||
| 139 | + let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)); | ||
| 140 | + assert_eq!(video.len(), 3, "the 30 fps take and the two others"); | ||
| 141 | + assert_eq!(audio.len(), video.len(), "one audio clip per take"); | ||
| 142 | + for (v, a) in video.iter().zip(audio) { | ||
| 143 | + assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}"); | ||
| 144 | + } | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +/// The NTSC ratio, which the 23.976 fps fixture is shot at: 24000/1001 over 30 | ||
| 148 | +/// is exactly 800/1001, and it stays exact however far the timeline runs. A rate | ||
| 149 | +/// rounded to a float -- or to milli-fps -- would leave a fraction of a frame | ||
| 150 | +/// per clip to pile up into a visible drift over an hour, which is why the | ||
| 151 | +/// mapping is built out of the muxer's own timescales and not a division. | ||
| 152 | +#[test] | ||
| 153 | +fn a_23_976_rate_is_exact_and_never_drifts() { | ||
| 154 | + let ntsc = Rate::from_fps(24_000.0 / 1001.0, FPS).expect("23.976 over 30"); | ||
| 155 | + assert!( | ||
| 156 | + (ntsc.as_f64() - 800.0 / 1001.0).abs() < 1e-15, | ||
| 157 | + "{}", | ||
| 158 | + ntsc.as_f64() | ||
| 159 | + ); | ||
| 160 | + // Independent integer arithmetic, out to an hour of source and past it: 800 | ||
| 161 | + // source frames per 1001 timeline ones, and a file's length is that ceiled | ||
| 162 | + // (the last picture must still be reachable by a trim). | ||
| 163 | + for source in [1u64, 2, 24, 1000, 86_486, 500_000, 1_000_000] { | ||
| 164 | + assert_eq!( | ||
| 165 | + u64::from(ntsc.timeline_at(source as u32)), | ||
| 166 | + (source * 1001).div_ceil(800), | ||
| 167 | + "{source} source frames" | ||
| 168 | + ); | ||
| 169 | + } | ||
| 170 | + // ...and the two directions stay each other's inverse at every one of them: | ||
| 171 | + // the frame an export writes at timeline frame `d` is the frame playback is | ||
| 172 | + // holding there, which is what `timeline_at`'s ceil buys. | ||
| 173 | + for d in [0u32, 1, 2, 3, 1000, 100_000, 1_000_000] { | ||
| 174 | + let source = ntsc.source_at(d); | ||
| 175 | + assert!(ntsc.timeline_at(source) <= d, "frame {d} is not yet due"); | ||
| 176 | + assert!( | ||
| 177 | + ntsc.timeline_at(source + 1) > d, | ||
| 178 | + "the next frame is due too early at {d}" | ||
| 179 | + ); | ||
| 180 | + } | ||
| 181 | + // A timeline's own rate conforms by nothing at all, exactly -- whichever of | ||
| 182 | + // the two rates it is written at. | ||
| 183 | + assert!(Rate::from_fps(FPS, FPS).expect("30 over 30").is_real_time()); | ||
| 184 | + assert!( | ||
| 185 | + Rate::from_fps(24_000.0 / 1001.0, 24_000.0 / 1001.0) | ||
| 186 | + .expect("ntsc over ntsc") | ||
| 187 | + .is_real_time() | ||
| 188 | + ); | ||
| 189 | + // A rate no timescale can name is refused rather than read 1:1 in silence: | ||
| 190 | + // the one thing `matches_timeline` still turns a file away for. | ||
| 191 | + assert!(Rate::from_fps(0.0, FPS).is_err(), "not a rate at all"); | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// The picture on screen at a timeline frame is the picture the *file* holds | ||
| 195 | +/// there: frame `floor(offset * 25/30)` of a 25 fps clip, which is what playing | ||
| 196 | +/// at the speed it was shot at means, frame for frame. | ||
| 197 | +#[test] | ||
| 198 | +fn playback_shows_the_frame_the_file_holds_there() { | ||
| 199 | + let pal = asset("test_25fps.mp4"); | ||
| 200 | + let mut session = open(asset("test_av.mp4")); | ||
| 201 | + import_and_place(&mut session, &pal); | ||
| 202 | + session.pause(); | ||
| 203 | + // The clip starts at timeline frame 150 (5 s) and runs 60 frames. | ||
| 204 | + let start = 150u32; | ||
| 205 | + for offset in [0u32, 1, 5, 6, 29, 30, 47, 59] { | ||
| 206 | + let at = start + offset; | ||
| 207 | + session.seek(f64::from(at) / FPS); | ||
| 208 | + let landed = next_frame(&mut session, "a seek into the 25 fps clip"); | ||
| 209 | + assert_eq!(landed.index, at, "a seek lands on the frame it asked for"); | ||
| 210 | + let want = (u64::from(offset) * 25_000 / 30_000) as u32; | ||
| 211 | + assert!( | ||
| 212 | + landed.bgra == source_frame(&pal, want), | ||
| 213 | + "timeline frame {at} (offset {offset}) is not source frame {want}" | ||
| 214 | + ); | ||
| 215 | + } | ||
| 216 | + // Past the last picture the file holds, the clip is still on the timeline: | ||
| 217 | + // its last frame is shown, not black and not a panic. | ||
| 218 | + session.seek(f64::from(start + 59) / FPS); | ||
| 219 | + let last = next_frame(&mut session, "the last frame of the clip"); | ||
| 220 | + assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last"); | ||
| 221 | + // ...and the frame in front of it is the 30 fps take, frame for frame: a | ||
| 222 | + // rate belongs to the source that has one, so the clip beside it is read | ||
| 223 | + // exactly as it was before any of this existed. | ||
| 224 | + let av = asset("test_av.mp4"); | ||
| 225 | + session.seek(f64::from(start - 1) / FPS); | ||
| 226 | + let before = next_frame(&mut session, "the last frame of the 30 fps take"); | ||
| 227 | + assert_eq!(before.index, start - 1); | ||
| 228 | + assert!( | ||
| 229 | + before.bgra == source_frame(&av, start - 1), | ||
| 230 | + "the 30 fps clip is still frame for frame" | ||
| 231 | + ); | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +/// A trim of a clip at another rate is dragged in *timeline* frames and commits | ||
| 235 | +/// the source range those frames are worth -- so the box is exactly the room it | ||
| 236 | +/// was dragged to, and the picture at its new edge is the file's own frame | ||
| 237 | +/// there. | ||
| 238 | +#[test] | ||
| 239 | +fn a_clip_at_another_rate_trims_to_the_room_it_was_dragged_to() { | ||
| 240 | + let pal = asset("test_25fps.mp4"); | ||
| 241 | + let mut session = open(asset("test_av.mp4")); | ||
| 242 | + import_and_place(&mut session, &pal); | ||
| 243 | + session.pause(); | ||
| 244 | + let start = 150u32; | ||
| 245 | + // Drag its tail back to 30 timeline frames of room: one second, which at 25 | ||
| 246 | + // fps is the file's first 25 pictures. | ||
| 247 | + assert!( | ||
| 248 | + session.trim_clip(Lane::V1, 1, Edge::End, start + 30), | ||
| 249 | + "trim the tail of the 25 fps clip" | ||
| 250 | + ); | ||
| 251 | + let clip = session.lane_clips(Lane::V1)[1]; | ||
| 252 | + assert_eq!((clip.start, clip.len()), (start, 30), "{clip:?}"); | ||
| 253 | + session.seek(f64::from(start + 29) / FPS); | ||
| 254 | + let last = next_frame(&mut session, "the trimmed tail"); | ||
| 255 | + assert!( | ||
| 256 | + last.bgra == source_frame(&pal, 24), | ||
| 257 | + "one second of a 25 fps file ends on its frame 24" | ||
| 258 | + ); | ||
| 259 | + // ...and its head, dragged forward into source it keeps: 6 timeline frames | ||
| 260 | + // in is 5 source frames in, and the tail did not move. | ||
| 261 | + assert!(session.trim_clip(Lane::V1, 1, Edge::Start, start + 6)); | ||
| 262 | + let clip = session.lane_clips(Lane::V1)[1]; | ||
| 263 | + assert_eq!((clip.start, clip.len()), (start + 6, 24), "{clip:?}"); | ||
| 264 | + session.seek(f64::from(start + 6) / FPS); | ||
| 265 | + let head = next_frame(&mut session, "the trimmed head"); | ||
| 266 | + assert!( | ||
| 267 | + head.bgra == source_frame(&pal, 5), | ||
| 268 | + "6 frames of a 30 fps timeline is 5 frames of a 25 fps file" | ||
| 269 | + ); | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is | ||
| 273 | +/// half as many timeline frames and reads twice as far into the file for each | ||
| 274 | +/// of them. | ||
| 275 | +#[test] | ||
| 276 | +fn a_speeded_clip_at_another_rate_is_exactly_both() { | ||
| 277 | + let pal = asset("test_25fps.mp4"); | ||
| 278 | + let mut session = open(asset("test_av.mp4")); | ||
| 279 | + import_and_place(&mut session, &pal); | ||
| 280 | + session | ||
| 281 | + .set_speed(Lane::V1, 1, Speed::from_permille(2000)) | ||
| 282 | + .expect("nothing is in the way of a clip that got shorter"); | ||
| 283 | + session.pause(); | ||
| 284 | + let start = 150u32; | ||
| 285 | + assert!( | ||
| 286 | + (session.timeline_duration() - (5.0 + 1.0)).abs() < 1e-9, | ||
| 287 | + "2 s at 2x is 1 s: {}", | ||
| 288 | + session.timeline_duration() | ||
| 289 | + ); | ||
| 290 | + for offset in [0u32, 3, 14, 29] { | ||
| 291 | + let at = start + offset; | ||
| 292 | + session.seek(f64::from(at) / FPS); | ||
| 293 | + let landed = next_frame(&mut session, "a seek into the speeded clip"); | ||
| 294 | + assert_eq!(landed.index, at); | ||
| 295 | + // The speed picks the clip's (timeline-rate) frame, the rate picks the | ||
| 296 | + // file's -- in that order, which is the order the decoder's door | ||
| 297 | + // applies them. | ||
| 298 | + let want = (u64::from(offset) * 2 * 25_000 / 30_000) as u32; | ||
| 299 | + assert!( | ||
| 300 | + landed.bgra == source_frame(&pal, want), | ||
| 301 | + "2x at offset {offset} is not source frame {want}" | ||
| 302 | + ); | ||
| 303 | + } | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +/// A saved project reloads at the same lengths: `open_project` recomputes every | ||
| 307 | +/// source's rate from the file, so a mixed-rate timeline is not one that only | ||
| 308 | +/// the session that built it could hold. | ||
| 309 | +#[test] | ||
| 310 | +fn a_mixed_rate_project_reloads_unchanged() { | ||
| 311 | + let pal = asset("test_25fps.mp4"); | ||
| 312 | + let mut session = open(asset("test_av.mp4")); | ||
| 313 | + import_and_place(&mut session, &pal); | ||
| 314 | + let duration = session.timeline_duration(); | ||
| 315 | + let spans = session.clip_spans(); | ||
| 316 | + let path = std::env::temp_dir().join(format!("edith-mixed-{}.edith", std::process::id())); | ||
| 317 | + session.save_project(&path).expect("save"); | ||
| 318 | + | ||
| 319 | + let reloaded = PlaybackSession::open_project(&path).expect("a mixed-rate project reopens"); | ||
| 320 | + assert_eq!(reloaded.clip_spans(), spans, "the same clips, in seconds"); | ||
| 321 | + assert!((reloaded.timeline_duration() - duration).abs() < 1e-9); | ||
| 322 | + assert_eq!(reloaded.file_frames(&pal), 60, "the length was recomputed"); | ||
| 323 | + std::fs::remove_file(&path).ok(); | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +/// The export is what was watched: as many frames as the timeline has, and the | ||
| 327 | +/// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames, | ||
| 328 | +/// not 30 of them and not 25 held to the end. | ||
| 329 | +#[test] | ||
| 330 | +fn an_export_of_two_rates_runs_at_the_speed_it_was_shot() { | ||
| 331 | + let pal = asset("test_25fps.mp4"); | ||
| 332 | + let mut session = open(asset("test_av.mp4")); | ||
| 333 | + // A short head of the 30 fps take, then the whole of the 25 fps one -- | ||
| 334 | + // enough of each to be a mixed timeline, short enough to encode in a test. | ||
| 335 | + // The sound comes with it: a placed take is one linked group. | ||
| 336 | + assert!( | ||
| 337 | + session.trim_clip(Lane::V1, 0, Edge::End, 15), | ||
| 338 | + "trim the 30 fps take to half a second" | ||
| 339 | + ); | ||
| 340 | + import_and_place(&mut session, &pal); | ||
| 341 | + assert!( | ||
| 342 | + session.trim_clip(Lane::V1, 1, Edge::End, 45), | ||
| 343 | + "one second of the 25 fps clip" | ||
| 344 | + ); | ||
| 345 | + let total = (session.timeline_duration() * FPS).round() as u32; | ||
| 346 | + assert_eq!(total, 45, "15 frames of 30 fps and 30 of the 25 fps clip"); | ||
| 347 | + | ||
| 348 | + let out = std::env::temp_dir().join(format!("edith-mixed-{}.mp4", std::process::id())); | ||
| 349 | + wait(&session.export_to_with( | ||
| 350 | + &out, | ||
| 351 | + &ExportSettings { | ||
| 352 | + format: Format::Mp4, | ||
| 353 | + ..ExportSettings::default() | ||
| 354 | + }, | ||
| 355 | + )) | ||
| 356 | + .expect("the export"); | ||
| 357 | + | ||
| 358 | + // Duration first: the file is as long as the timeline, so the mixed rates | ||
| 359 | + // did not stretch or shorten it. | ||
| 360 | + let (meta, rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen"); | ||
| 361 | + assert!( | ||
| 362 | + (meta.frame_rate - FPS).abs() < 0.01, | ||
| 363 | + "the export runs at the timeline's rate: {}", | ||
| 364 | + meta.frame_rate | ||
| 365 | + ); | ||
| 366 | + assert_eq!( | ||
| 367 | + meta.frame_count, total, | ||
| 368 | + "the export is the timeline's length" | ||
| 369 | + ); | ||
| 370 | + let written: Vec<Vec<u8>> = rx.into_iter().map(|frame| frame.bgra).collect(); | ||
| 371 | + assert_eq!(written.len() as u32, total, "every frame came back"); | ||
| 372 | + | ||
| 373 | + // ...and motion: inside the 25 fps clip, 30 exported frames show 25 | ||
| 374 | + // pictures, so 5 of them are a picture held from the frame before. A clip | ||
| 375 | + // played at the wrong rate would hold none (too fast, and it would run out | ||
| 376 | + // of file) or hold half of them (too slow). | ||
| 377 | + let held = (16..total as usize) | ||
| 378 | + .filter(|&i| difference(&written[i - 1], &written[i]) < 2.0) | ||
| 379 | + .count(); | ||
| 380 | + assert_eq!( | ||
| 381 | + held, 5, | ||
| 382 | + "30 timeline frames of a 25 fps clip hold 5 pictures over" | ||
| 383 | + ); | ||
| 384 | + | ||
| 385 | + // ...and *which* picture each of those frames is: the very one playback | ||
| 386 | + // holds there, which is the whole reason the two conversions are one | ||
| 387 | + // floor/ceil pair. Nearer its own source frame than either neighbour rather | ||
| 388 | + // than equal to it -- the export is re-encoded, so no pixel survives whole. | ||
| 389 | + for offset in [0u32, 1, 6, 12, 24, 29] { | ||
| 390 | + let want = (u64::from(offset) * 25_000 / 30_000) as u32; | ||
| 391 | + let mine = difference(&written[(15 + offset) as usize], &source_frame(&pal, want)); | ||
| 392 | + for other in [want.saturating_sub(1), want + 1] { | ||
| 393 | + if other == want { | ||
| 394 | + continue; | ||
| 395 | + } | ||
| 396 | + assert!( | ||
| 397 | + mine < difference(&written[(15 + offset) as usize], &source_frame(&pal, other)), | ||
| 398 | + "exported frame {offset} of the 25 fps clip is nearer source \ | ||
| 399 | + frame {other} than its own {want}" | ||
| 400 | + ); | ||
| 401 | + } | ||
| 402 | + } | ||
| 403 | + | ||
| 404 | + // The sound came out as long as the picture, from a *packet copy*: a clip | ||
| 405 | + // counts timeline frames whatever its file was shot at, so the window this | ||
| 406 | + // export trimmed the 25 fps file's AAC to is whole timeline frames and the | ||
| 407 | + // copy is in sync. This is the assertion behind the note in | ||
| 408 | + // `export::copy_audio` that says not to turn a conformed lane into a | ||
| 409 | + // re-encode. | ||
| 410 | + let secs = engine::AudioSession::duration_secs(&out) | ||
| 411 | + .expect("probe the export") | ||
| 412 | + .expect("the export has sound"); | ||
| 413 | + let want = f64::from(total) / FPS; | ||
| 414 | + assert!( | ||
| 415 | + (secs - want).abs() < 0.05, | ||
| 416 | + "sound is {secs} s under {want} s of picture" | ||
| 417 | + ); | ||
| 418 | + std::fs::remove_file(&out).ok(); | ||
| 419 | +} | ||
| @@ -813,14 +813,15 @@ fn import_refuses_what_does_not_match() { | |||
| 813 | "a resolution of its own is not a refusal any more: {err}" | 813 | "a resolution of its own is not a refusal any more: {err}" |
| 814 | ); | 814 | ); |
| 815 | 815 | ||
| 816 | - // Same codec, same audio, 25 fps: the one property left, named with both | 816 | + // A frame rate of its own is no longer a refusal either: 25 fps joins a |
| 817 | - // rates. Mixing rates would mean retiming the timeline itself, and there is | 817 | + // 30 fps timeline and is read at `Rate` against it -- see |
| 818 | - // no resampler for that, so the refusal is the honest answer. | 818 | + // `tests/mixed_fps.rs` for what it then plays like. |
| 819 | - let err = session | 819 | + session |
| 820 | .import(&asset("test_25fps.mp4")) | 820 | .import(&asset("test_25fps.mp4")) |
| 821 | - .expect_err("25 fps must not join a 30 fps timeline") | 821 | + .expect("25 fps may join a 30 fps timeline"); |
| 822 | - .to_string(); | 822 | + session |
| 823 | - assert_eq!(err, "25.000 fps does not match the timeline's 30.000 fps"); | 823 | + .remove_source(&asset("test_25fps.mp4"), 0) |
| 824 | + .expect("...and the row it made comes back off"); | ||
| 824 | 825 | ||
| 825 | // Same size and rate, no audio track: the timeline has one. | 826 | // Same size and rate, no audio track: the timeline has one. |
| 826 | let err = session | 827 | let err = session |
| @@ -209,7 +209,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() { | |||
| 209 | let v2 = dir.join("new.edith"); | 209 | let v2 = dir.join("new.edith"); |
| 210 | loaded.save_project(&v2).expect("save"); | 210 | loaded.save_project(&v2).expect("save"); |
| 211 | let text = std::fs::read_to_string(&v2).expect("read back"); | 211 | let text = std::fs::read_to_string(&v2).expect("read back"); |
| 212 | - assert!(text.starts_with("edith 8\n"), "{text}"); | 212 | + assert!(text.starts_with("edith 9\n"), "{text}"); |
| 213 | assert!( | 213 | assert!( |
| 214 | text.contains("\nresolution 1280 720\n"), | 214 | text.contains("\nresolution 1280 720\n"), |
| 215 | "a project with no resolution of its own is saved at source 0's: {text}" | 215 | "a project with no resolution of its own is saved at source 0's: {text}" |
| @@ -297,7 +297,7 @@ fn a_version_4_project_holds_more_than_two_lanes() { | |||
| 297 | loaded.save_project(&again).expect("save"); | 297 | loaded.save_project(&again).expect("save"); |
| 298 | assert_eq!( | 298 | assert_eq!( |
| 299 | std::fs::read_to_string(&again).expect("read back"), | 299 | std::fs::read_to_string(&again).expect("read back"), |
| 300 | - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ | 300 | + "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 301 | video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ | 301 | video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\ |
| 302 | video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", | 302 | video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n", |
| 303 | "a four-lane project is written as it was read, three versions on" | 303 | "a four-lane project is written as it was read, three versions on" |
| @@ -327,7 +327,7 @@ fn a_version_5_project_carries_per_clip_equalizers() { | |||
| 327 | loaded.save_project(&again).expect("save"); | 327 | loaded.save_project(&again).expect("save"); |
| 328 | assert_eq!( | 328 | assert_eq!( |
| 329 | std::fs::read_to_string(&again).expect("read back"), | 329 | std::fs::read_to_string(&again).expect("read back"), |
| 330 | - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ | 330 | + "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 331 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ | 331 | eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ |
| 332 | eq 12000.0:6.25:0.5:hs\n\ | 332 | eq 12000.0:6.25:0.5:hs\n\ |
| 333 | video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ | 333 | video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\ |
| @@ -362,7 +362,7 @@ fn a_version_6_project_carries_per_clip_colours() { | |||
| 362 | loaded.save_project(&again).expect("save"); | 362 | loaded.save_project(&again).expect("save"); |
| 363 | assert_eq!( | 363 | assert_eq!( |
| 364 | std::fs::read_to_string(&again).expect("read back"), | 364 | std::fs::read_to_string(&again).expect("read back"), |
| 365 | - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 test_av.mp4\n\ | 365 | + "edith 9\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 366 | eq 80.0:-3.0:0.707:ls\n\ | 366 | eq 80.0:-3.0:0.707:ls\n\ |
| 367 | color 0.1:1.2:0.9:-0.3\n\ | 367 | color 0.1:1.2:0.9:-0.3\n\ |
| 368 | color -0.25:1.0:0.0:0.5\n\ | 368 | color -0.25:1.0:0.0:0.5\n\ |
| @@ -412,7 +412,7 @@ fn a_version_7_project_carries_a_resolution_and_fit_policies() { | |||
| 412 | loaded.save_project(&again).expect("save"); | 412 | loaded.save_project(&again).expect("save"); |
| 413 | assert_eq!( | 413 | assert_eq!( |
| 414 | std::fs::read_to_string(&again).expect("read back"), | 414 | std::fs::read_to_string(&again).expect("read back"), |
| 415 | - "edith 8\nplayhead 0\nresolution 960 720\nsource 0 test_av.mp4\n\ | 415 | + "edith 9\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\ |
| 416 | video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ | 416 | video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\ |
| 417 | audio 1 0 0 60 0 - - - fit 1000\n", | 417 | audio 1 0 0 60 0 - - - fit 1000\n", |
| 418 | "a v7 project is written back as the v8 it now is: the same clips, each \ | 418 | "a v7 project is written back as the v8 it now is: the same clips, each \ |
| @@ -670,7 +670,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { | |||
| 670 | 670 | ||
| 671 | for (text, want) in [ | 671 | for (text, want) in [ |
| 672 | ( | 672 | ( |
| 673 | - "edith 9\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", | 673 | + "edith 10\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n", |
| 674 | "line 1", | 674 | "line 1", |
| 675 | ), | 675 | ), |
| 676 | // An eq index the table does not hold, and a band shape there is none. | 676 | // An eq index the table does not hold, and a band shape there is none. |
| @@ -755,3 +755,74 @@ fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() { | |||
| 755 | ) | 755 | ) |
| 756 | ); | 756 | ); |
| 757 | } | 757 | } |
| 758 | + | ||
| 759 | +/// The mix a project was left at comes back with it: a track's fader, the | ||
| 760 | +/// master limiter and the rate the timeline was cut at. A fader that vanished | ||
| 761 | +/// on a reload would be a setting nobody could keep. | ||
| 762 | +#[test] | ||
| 763 | +fn the_mix_survives_a_save_and_an_open() { | ||
| 764 | + use engine::project::{Lane, LaneKind}; | ||
| 765 | + let dir = scratch("mix"); | ||
| 766 | + let source = copy_in(&dir, "test_av.mp4"); | ||
| 767 | + let mut saved = PlaybackSession::open(&source).expect("open the fixture"); | ||
| 768 | + let a2 = saved.add_lane(LaneKind::Audio); | ||
| 769 | + assert!(saved.set_lane_gain_db(Lane::A1, -6.0)); | ||
| 770 | + assert!(saved.set_lane_gain_db(a2, 3.0)); | ||
| 771 | + let limiter = engine::limiter::Limiter { | ||
| 772 | + ceiling_db: -2.0, | ||
| 773 | + on: true, | ||
| 774 | + }; | ||
| 775 | + assert!(saved.set_limiter(limiter)); | ||
| 776 | + let path = dir.join("mix.edith"); | ||
| 777 | + saved.save_project(&path).expect("save"); | ||
| 778 | + | ||
| 779 | + let mut loaded = PlaybackSession::open_project(&path).expect("open the project"); | ||
| 780 | + assert_eq!(loaded.lane_gain_db(Lane::A1), -6.0, "A1's fader"); | ||
| 781 | + assert_eq!(loaded.lane_gain_db(a2), 3.0, "A2's own, not A1's"); | ||
| 782 | + assert_eq!(loaded.limiter(), limiter); | ||
| 783 | + assert!(!loaded.undo(), "a loaded mix is not an undo step"); | ||
| 784 | + // ...and saving it again is the same bytes: the format holds all of it. | ||
| 785 | + let again = dir.join("again.edith"); | ||
| 786 | + loaded | ||
| 787 | + .save_project(&again) | ||
| 788 | + .expect("save the loaded project"); | ||
| 789 | + assert_eq!( | ||
| 790 | + std::fs::read(&path).unwrap(), | ||
| 791 | + std::fs::read(&again).unwrap(), | ||
| 792 | + "save -> load -> save is not a fixed point" | ||
| 793 | + ); | ||
| 794 | +} | ||
| 795 | + | ||
| 796 | +/// The other half of the v9 bump, and the debt it pays: a timeline holding | ||
| 797 | +/// nothing but a song has no file to take a frame rate from, so it used to come | ||
| 798 | +/// back at the canvas rate whatever it was cut at. The written `fps` is now | ||
| 799 | +/// preferred over that inference -- and a project whose scaffold *does* have a | ||
| 800 | +/// picture still takes the rate from the file, which is what every clip on it | ||
| 801 | +/// was conformed to. | ||
| 802 | +#[test] | ||
| 803 | +fn a_song_only_project_comes_back_at_the_rate_it_names() { | ||
| 804 | + let dir = scratch("song_fps"); | ||
| 805 | + copy_in(&dir, "test_tone.mp3"); | ||
| 806 | + let path = dir.join("song.edith"); | ||
| 807 | + std::fs::write( | ||
| 808 | + &path, | ||
| 809 | + "edith 9\nplayhead 0\nresolution 1920 1080\nfps 24.0\nsource 0 test_tone.mp3\n\ | ||
| 810 | + video 1\naudio 1 0 0 24 0 - - - fit 1000\n", | ||
| 811 | + ) | ||
| 812 | + .expect("write a v9 song project"); | ||
| 813 | + let loaded = PlaybackSession::open_project(&path).expect("a song-only project opens"); | ||
| 814 | + assert_eq!(loaded.meta().frame_rate, 24.0, "the rate the file names"); | ||
| 815 | + assert_eq!(loaded.timeline_duration(), 1.0, "one second at 24 fps"); | ||
| 816 | + | ||
| 817 | + // The same file without the line -- which is every dialect before v9 -- | ||
| 818 | + // still comes back at the canvas rate, so an old project is unchanged. | ||
| 819 | + let old = dir.join("song8.edith"); | ||
| 820 | + std::fs::write( | ||
| 821 | + &old, | ||
| 822 | + "edith 8\nplayhead 0\nresolution 1920 1080\nsource 0 test_tone.mp3\n\ | ||
| 823 | + video 1\naudio 1 0 0 24 0 - - - fit 1000\n", | ||
| 824 | + ) | ||
| 825 | + .expect("write a v8 song project"); | ||
| 826 | + let loaded = PlaybackSession::open_project(&old).expect("a v8 song project opens"); | ||
| 827 | + assert_eq!(loaded.meta().frame_rate, 30.0, "the canvas rate, as before"); | ||
| 828 | +} | ||
| @@ -360,10 +360,22 @@ fn scanning_a_clip_and_cutting_what_it_finds() { | |||
| 360 | std::fs::create_dir_all(&dir).expect("a place to save"); | 360 | std::fs::create_dir_all(&dir).expect("a place to save"); |
| 361 | let file = dir.join("cut.edith"); | 361 | let file = dir.join("cut.edith"); |
| 362 | let (sources, lanes, eq, color) = p.without_orphan_sources(); | 362 | let (sources, lanes, eq, color) = p.without_orphan_sources(); |
| 363 | - engine::edith::save(&file, &sources, &lanes, &eq, &color, (1920, 1080), 0).expect("save"); | 363 | + engine::edith::save( |
| 364 | + &file, | ||
| 365 | + &sources, | ||
| 366 | + &lanes, | ||
| 367 | + &p.lane_gains(), | ||
| 368 | + &eq, | ||
| 369 | + &color, | ||
| 370 | + (1920, 1080), | ||
| 371 | + None, | ||
| 372 | + p.limiter(), | ||
| 373 | + 0, | ||
| 374 | + ) | ||
| 375 | + .expect("save"); | ||
| 364 | let text = std::fs::read_to_string(&file).expect("read it back"); | 376 | let text = std::fs::read_to_string(&file).expect("read it back"); |
| 365 | assert!( | 377 | assert!( |
| 366 | - text.starts_with("edith 8"), | 378 | + text.starts_with("edith 9"), |
| 367 | "{:?}", | 379 | "{:?}", |
| 368 | &text[..16.min(text.len())] | 380 | &text[..16.min(text.len())] |
| 369 | ); | 381 | ); |
| @@ -301,25 +301,33 @@ fn a_wav_export_of_a_2x_timeline_matches_the_preview() { | |||
| 301 | std::fs::remove_file(&out).ok(); | 301 | std::fs::remove_file(&out).ok(); |
| 302 | } | 302 | } |
| 303 | 303 | ||
| 304 | -/// The half that refuses: an mp4 *copies* AAC packets and a packet carries no | 304 | +/// The other half of the same rule, and it used to be a refusal: an mp4 *copies* |
| 305 | -/// rate, so a speeded clip **on the lane being copied** is refused by name -- | 305 | +/// AAC packets and a packet carries no rate, so a speeded clip on the lane being |
| 306 | -/// never written out at 1.00x under a re-timed picture. Only that lane: the | 306 | +/// copied could only have come out at 1.00x under a re-timed picture. It is |
| 307 | -/// picture honours a rate (below), and AV1 has no audio to copy at all. | 307 | +/// decoded, resampled and encoded again now (`export::copy_audio` routes a |
| 308 | +/// speeded lane to `encode_audio`), so the file carries the sound that was | ||
| 309 | +/// heard -- measured the way the WAV above is, by where the beep lands. | ||
| 308 | #[test] | 310 | #[test] |
| 309 | -fn an_mp4_export_refuses_a_speeded_sound_clip_by_name() { | 311 | +fn an_mp4_export_resamples_a_speeded_sound_clip() { |
| 310 | let (mut project, meta) = sync_project(); | 312 | let (mut project, meta) = sync_project(); |
| 311 | project | 313 | project |
| 312 | .set_speed(Lane::A1, 0, Speed::from_permille(2000)) | 314 | .set_speed(Lane::A1, 0, Speed::from_permille(2000)) |
| 313 | .expect("room enough"); | 315 | .expect("room enough"); |
| 314 | - let out = out_path("refuse", "mp4"); | 316 | + let heard = beep_at(&play(&project)); |
| 317 | + let out = out_path("speeded", "mp4"); | ||
| 315 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); | 318 | let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); |
| 316 | - let text = wait(&handle, Duration::from_secs(120)) | 319 | + wait(&handle, Duration::from_secs(180)).expect("an mp4 of a speeded sound clip"); |
| 317 | - .expect_err("an mp4 export cannot carry a rate in a copied packet") | 320 | + let (audio, chunks) = AudioSession::open(&out) |
| 318 | - .to_string(); | 321 | + .expect("reopen the export") |
| 319 | - assert!(text.contains("2.00x"), "{text}"); | 322 | + .expect("it has an audio track"); |
| 320 | - assert!(text.contains("00:00"), "{text}"); | 323 | + assert_eq!(audio.sample_rate, RATE); |
| 321 | - assert!(text.contains("WAV or FLAC"), "{text}"); | 324 | + let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect(); |
| 322 | - assert!(!out.exists(), "a refused export writes no file"); | 325 | + let in_file = beep_at(&samples); |
| 326 | + assert!( | ||
| 327 | + (in_file - heard).abs() <= 1.0 / FPS, | ||
| 328 | + "the beep is at {in_file:.3}s in the file and was at {heard:.3}s in the preview" | ||
| 329 | + ); | ||
| 330 | + std::fs::remove_file(&out).ok(); | ||
| 323 | } | 331 | } |
| 324 | 332 | ||
| 325 | /// The half that honours, and the shape that catches a walk that only works at | 333 | /// The half that honours, and the shape that catches a walk that only works at |
| @@ -393,8 +401,8 @@ fn an_mp4_export_honours_a_speeded_picture_across_a_rate_change() { | |||
| 393 | std::fs::remove_file(&out).ok(); | 401 | std::fs::remove_file(&out).ok(); |
| 394 | } | 402 | } |
| 395 | 403 | ||
| 396 | -/// AV1 carries no audio at all, so nothing about a rate reaches a packet copy | 404 | +/// AV1 honours a speeded picture with no detaching and no refusal -- and its |
| 397 | -/// there: it honours a speeded picture with no detaching and no refusal. | 405 | +/// sound, which it now carries, is resampled exactly as the mp4's is. |
| 398 | #[test] | 406 | #[test] |
| 399 | fn an_av1_export_honours_a_speeded_take_whole() { | 407 | fn an_av1_export_honours_a_speeded_take_whole() { |
| 400 | let (mut project, meta) = sync_project(); | 408 | let (mut project, meta) = sync_project(); |
| @@ -413,10 +421,7 @@ fn an_av1_export_honours_a_speeded_take_whole() { | |||
| 413 | }, | 421 | }, |
| 414 | ); | 422 | ); |
| 415 | wait(&handle, Duration::from_secs(600)).expect("an AV1 export of a speeded take"); | 423 | wait(&handle, Duration::from_secs(600)).expect("an AV1 export of a speeded take"); |
| 416 | - assert!( | 424 | + assert!(out.exists(), "AV1 never refuses a rate"); |
| 417 | - out.exists(), | ||
| 418 | - "AV1 never refuses a rate: it has no audio lane" | ||
| 419 | - ); | ||
| 420 | assert!( | 425 | assert!( |
| 421 | std::fs::metadata(&out).expect("the export").len() > 0, | 426 | std::fs::metadata(&out).expect("the export").len() > 0, |
| 422 | "and it wrote something" | 427 | "and it wrote something" |
| @@ -116,13 +116,39 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | |||
| 116 | # H.264 in Matroska: the same stream the mp4 fixtures carry, in the container | 116 | # H.264 in Matroska: the same stream the mp4 fixtures carry, in the container |
| 117 | # that used to refuse it. Baseline profile so `rusty_h264` reads it with nothing | 117 | # that used to refuse it. Baseline profile so `rusty_h264` reads it with nothing |
| 118 | # installed, `-g 30` for the second keyframe the sync index is checked against, | 118 | # installed, `-g 30` for the second keyframe the sync index is checked against, |
| 119 | -# and the AAC track again so the "not wired" audio notice has one to name. | 119 | +# and the AAC track for the sound an mkv's audio path reads back. |
| 120 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | 120 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ |
| 121 | -f lavfi -i "sine=frequency=440:duration=2" \ | 121 | -f lavfi -i "sine=frequency=440:duration=2" \ |
| 122 | -f lavfi -i "sine=frequency=880:duration=2" \ | 122 | -f lavfi -i "sine=frequency=880:duration=2" \ |
| 123 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | 123 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ |
| 124 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ | 124 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -g 30 -pix_fmt yuv420p \ |
| 125 | -c:a aac -b:a 128k assets/test_h264.mkv | 125 | -c:a aac -b:a 128k assets/test_h264.mkv |
| 126 | +# HEVC in Matroska: the shape a film off a disc arrives in. Same A/V shape as | ||
| 127 | +# test_hevc.mp4 so the tests measure the container and nothing else, `-g 30` for | ||
| 128 | +# the same reason test_av1.mkv has it (a second keyframe to seek to), and the | ||
| 129 | +# AAC track is read out of the mkv now rather than named as unsupported. | ||
| 130 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 131 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 132 | + -f lavfi -i "sine=frequency=880:duration=2" \ | ||
| 133 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | ||
| 134 | + -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p \ | ||
| 135 | + -c:a aac -b:a 128k assets/test_hevc.mkv | ||
| 136 | +# ...and the same file in the shape the ask came from: HEVC **Main 10** with a | ||
| 137 | +# 5.1 AAC track, which is a 4K BluRay remux in miniature. The picture decodes | ||
| 138 | +# through a P010 surface pool and the sound is folded to stereo, so both halves | ||
| 139 | +# of that file have a fixture. One tone per channel -- 440 FL, 880 FR, 220 FC, | ||
| 140 | +# 60 LFE, 1320 BL, 1760 BR as written, whatever the encoder's own element order | ||
| 141 | +# does with them -- so a test can say which channel reached which output. | ||
| 142 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | ||
| 143 | + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | ||
| 144 | + -f lavfi -i "sine=frequency=880:duration=2:sample_rate=48000" \ | ||
| 145 | + -f lavfi -i "sine=frequency=220:duration=2:sample_rate=48000" \ | ||
| 146 | + -f lavfi -i "sine=frequency=60:duration=2:sample_rate=48000" \ | ||
| 147 | + -f lavfi -i "sine=frequency=1320:duration=2:sample_rate=48000" \ | ||
| 148 | + -f lavfi -i "sine=frequency=1760:duration=2:sample_rate=48000" \ | ||
| 149 | + -filter_complex "[1:a][2:a][3:a][4:a][5:a][6:a]join=inputs=6:channel_layout=5.1[a]" \ | ||
| 150 | + -map 0:v -map "[a]" -c:v libx265 -x265-params log-level=error -g 30 -pix_fmt yuv420p10le \ | ||
| 151 | + -c:a aac -b:a 384k assets/test_hevc10.mkv | ||
| 126 | # Sync fixture: one flash and one beep, at the same instant. Black picture with | 152 | # Sync fixture: one flash and one beep, at the same instant. Black picture with |
| 127 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that | 153 | # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that |
| 128 | # stretch — so a test can find each of them and say how far apart they came out. | 154 | # stretch — so a test can find each of them and say how far apart they came out. |
| @@ -145,15 +171,23 @@ enable='between(t,1,1.1)'[v];\ | |||
| 145 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ | 171 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ |
| 146 | -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4 | 172 | -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4 |
| 147 | # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same | 173 | # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same |
| 148 | -# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps. | 174 | +# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps, |
| 149 | -# The only thing left for an import to refuse is the rate, which is what makes | 175 | +# so a timeline of 30 fps clips has one at another rate to read through `Rate`. |
| 150 | -# the refusal's wording testable. | ||
| 151 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \ | 176 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \ |
| 152 | -f lavfi -i "sine=frequency=440:duration=2" \ | 177 | -f lavfi -i "sine=frequency=440:duration=2" \ |
| 153 | -f lavfi -i "sine=frequency=880:duration=2" \ | 178 | -f lavfi -i "sine=frequency=880:duration=2" \ |
| 154 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | 179 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ |
| 155 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | 180 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ |
| 156 | -c:a aac -b:a 128k assets/test_25fps.mp4 | 181 | -c:a aac -b:a 128k assets/test_25fps.mp4 |
| 182 | +# ...and the same again at 23.976 fps (24000/1001), the rate whose ratio to a | ||
| 183 | +# 30 fps timeline does not terminate: what the frame mapping's rounding is | ||
| 184 | +# actually tested against. | ||
| 185 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=24000/1001:duration=2 \ | ||
| 186 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 187 | + -f lavfi -i "sine=frequency=880:duration=2" \ | ||
| 188 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | ||
| 189 | + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 190 | + -c:a aac -b:a 128k assets/test_23976fps.mp4 | ||
| 157 | # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the | 191 | # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the |
| 158 | # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song | 192 | # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song |
| 159 | # can share a timeline with the video clips and the peaks tests can reuse the | 193 | # can share a timeline with the video clips and the peaks tests can reuse the |
| @@ -73,7 +73,6 @@ pub(crate) trait VaStreamInfo { | |||
| 73 | /// Returns the VA profile of the stream. | 73 | /// Returns the VA profile of the stream. |
| 74 | fn va_profile(&self) -> anyhow::Result<i32>; | 74 | fn va_profile(&self) -> anyhow::Result<i32>; |
| 75 | /// Returns the RT format of the stream. | 75 | /// Returns the RT format of the stream. |
| 76 | - #[allow(dead_code)] | ||
| 77 | fn rt_format(&self) -> anyhow::Result<u32>; | 76 | fn rt_format(&self) -> anyhow::Result<u32>; |
| 78 | /// Returns the minimum number of surfaces required to decode the stream. | 77 | /// Returns the minimum number of surfaces required to decode the stream. |
| 79 | fn min_num_surfaces(&self) -> usize; | 78 | fn min_num_surfaces(&self) -> usize; |
| @@ -255,13 +254,18 @@ impl<V: VideoFrame> VaapiBackend<V> { | |||
| 255 | self.stream_info.min_num_frames = stream_params.min_num_surfaces(); | 254 | self.stream_info.min_num_frames = stream_params.min_num_surfaces(); |
| 256 | 255 | ||
| 257 | // TODO: Handle context re-use | 256 | // TODO: Handle context re-use |
| 258 | - // TODO: We should obtain RT_FORMAT from stream_info | 257 | + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the RT format comes |
| 258 | + // from the stream rather than being assumed 8-bit 4:2:0, which is what | ||
| 259 | + // an HEVC Main 10 stream needs -- its surfaces are P010 and a | ||
| 260 | + // YUV420-only config rejects them. This is upstream's own TODO, and | ||
| 261 | + // `VaStreamInfo::rt_format` is upstream's own answer to it. | ||
| 262 | + let rt_format = stream_params.rt_format().unwrap_or(libva::VA_RT_FORMAT_YUV420); | ||
| 259 | let config = self | 263 | let config = self |
| 260 | .display | 264 | .display |
| 261 | .create_config( | 265 | .create_config( |
| 262 | vec![libva::VAConfigAttrib { | 266 | vec![libva::VAConfigAttrib { |
| 263 | type_: libva::VAConfigAttribType::VAConfigAttribRTFormat, | 267 | type_: libva::VAConfigAttribType::VAConfigAttribRTFormat, |
| 264 | - value: libva::VA_RT_FORMAT_YUV420, | 268 | + value: rt_format, |
| 265 | }], | 269 | }], |
| 266 | stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?, | 270 | stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?, |
| 267 | libva::VAEntrypoint::VAEntrypointVLD, | 271 | libva::VAEntrypoint::VAEntrypointVLD, |
| @@ -222,6 +222,10 @@ pub enum DecodedFormat { | |||
| 222 | I410, | 222 | I410, |
| 223 | /// Y, U and V planes, 4:4:4 sampling, 16 bits per sample, LE. Only the 12 LSBs are used. | 223 | /// Y, U and V planes, 4:4:4 sampling, 16 bits per sample, LE. Only the 12 LSBs are used. |
| 224 | I412, | 224 | I412, |
| 225 | + /// One Y and one interleaved UV plane, 4:2:0 sampling, 16 bits per sample, | ||
| 226 | + /// LE. Only the 10 MSBs are used. LOCAL PATCH (see /Cargo.toml | ||
| 227 | + /// [patch.crates-io]): what an HEVC Main 10 stream decodes into. | ||
| 228 | + P010, | ||
| 225 | /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample. | 229 | /// One Y and one interleaved UV plane, 4:2:0 sampling, 8 bits per sample. |
| 226 | /// In a tiled format. | 230 | /// In a tiled format. |
| 227 | MM21, | 231 | MM21, |
| @@ -242,6 +246,7 @@ impl FromStr for DecodedFormat { | |||
| 242 | "i212" | "I212" => Ok(DecodedFormat::I212), | 246 | "i212" | "I212" => Ok(DecodedFormat::I212), |
| 243 | "i410" | "I410" => Ok(DecodedFormat::I410), | 247 | "i410" | "I410" => Ok(DecodedFormat::I410), |
| 244 | "i412" | "I412" => Ok(DecodedFormat::I412), | 248 | "i412" | "I412" => Ok(DecodedFormat::I412), |
| 249 | + "p010" | "P010" => Ok(DecodedFormat::P010), | ||
| 245 | "mm21" | "MM21" => Ok(DecodedFormat::MM21), | 250 | "mm21" | "MM21" => Ok(DecodedFormat::MM21), |
| 246 | _ => Err("unrecognized output format. \ | 251 | _ => Err("unrecognized output format. \ |
| 247 | Valid values: i420, nv12, i422, i444, i010, i012, i210, i212, i410, i412, mm21"), | 252 | Valid values: i420, nv12, i422, i444, i010, i012, i210, i212, i410, i412, mm21"), |
| @@ -254,6 +259,7 @@ impl From<Fourcc> for DecodedFormat { | |||
| 254 | match fourcc.to_string().as_str() { | 259 | match fourcc.to_string().as_str() { |
| 255 | "I420" => DecodedFormat::I420, | 260 | "I420" => DecodedFormat::I420, |
| 256 | "NV12" | "NM12" => DecodedFormat::NV12, | 261 | "NV12" | "NM12" => DecodedFormat::NV12, |
| 262 | + "P010" => DecodedFormat::P010, | ||
| 257 | "MM21" => DecodedFormat::MM21, | 263 | "MM21" => DecodedFormat::MM21, |
| 258 | _ => todo!("Fourcc {} not yet supported", fourcc), | 264 | _ => todo!("Fourcc {} not yet supported", fourcc), |
| 259 | } | 265 | } |
| @@ -265,6 +271,7 @@ impl From<DecodedFormat> for Fourcc { | |||
| 265 | match format { | 271 | match format { |
| 266 | DecodedFormat::I420 => Fourcc::from(b"I420"), | 272 | DecodedFormat::I420 => Fourcc::from(b"I420"), |
| 267 | DecodedFormat::NV12 => Fourcc::from(b"NV12"), | 273 | DecodedFormat::NV12 => Fourcc::from(b"NV12"), |
| 274 | + DecodedFormat::P010 => Fourcc::from(b"P010"), | ||
| 268 | DecodedFormat::MM21 => Fourcc::from(b"MM21"), | 275 | DecodedFormat::MM21 => Fourcc::from(b"MM21"), |
| 269 | _ => todo!(), | 276 | _ => todo!(), |
| 270 | } | 277 | } |
| @@ -417,6 +424,8 @@ pub fn decoded_frame_size(format: DecodedFormat, width: usize, height: usize) -> | |||
| 417 | u_size + uv_size | 424 | u_size + uv_size |
| 418 | } | 425 | } |
| 419 | DecodedFormat::I410 | DecodedFormat::I412 => (width * height * 2) * 3, | 426 | DecodedFormat::I410 | DecodedFormat::I412 => (width * height * 2) * 3, |
| 427 | + // LOCAL PATCH: NV12 with 16-bit samples. | ||
| 428 | + DecodedFormat::P010 => decoded_frame_size(DecodedFormat::NV12, width, height) * 2, | ||
| 420 | DecodedFormat::MM21 => panic!("Unable to convert to MM21"), | 429 | DecodedFormat::MM21 => panic!("Unable to convert to MM21"), |
| 421 | } | 430 | } |
| 422 | } | 431 | } |
| @@ -134,7 +134,7 @@ pub trait VideoFrame: Send + Sync + Sized + Debug + 'static { | |||
| 134 | | DecodedFormat::I212 | 134 | | DecodedFormat::I212 |
| 135 | | DecodedFormat::I410 | 135 | | DecodedFormat::I410 |
| 136 | | DecodedFormat::I412 => 3, | 136 | | DecodedFormat::I412 => 3, |
| 137 | - DecodedFormat::NV12 | DecodedFormat::MM21 => 2, | 137 | + DecodedFormat::NV12 | DecodedFormat::P010 | DecodedFormat::MM21 => 2, |
| 138 | } | 138 | } |
| 139 | } | 139 | } |
| 140 | 140 | ||
| @@ -152,6 +152,7 @@ pub trait VideoFrame: Send + Sync + Sized + Debug + 'static { | |||
| 152 | | DecodedFormat::I012 | 152 | | DecodedFormat::I012 |
| 153 | | DecodedFormat::I210 | 153 | | DecodedFormat::I210 |
| 154 | | DecodedFormat::I212 | 154 | | DecodedFormat::I212 |
| 155 | + | DecodedFormat::P010 | ||
| 155 | | DecodedFormat::MM21 => { | 156 | | DecodedFormat::MM21 => { |
| 156 | if plane_idx == 0 { | 157 | if plane_idx == 0 { |
| 157 | 1 | 158 | 1 |
| @@ -177,6 +178,7 @@ pub trait VideoFrame: Send + Sync + Sized + Debug + 'static { | |||
| 177 | | DecodedFormat::NV12 | 178 | | DecodedFormat::NV12 |
| 178 | | DecodedFormat::I010 | 179 | | DecodedFormat::I010 |
| 179 | | DecodedFormat::I012 | 180 | | DecodedFormat::I012 |
| 181 | + | DecodedFormat::P010 | ||
| 180 | | DecodedFormat::MM21 => { | 182 | | DecodedFormat::MM21 => { |
| 181 | if plane_idx == 0 { | 183 | if plane_idx == 0 { |
| 182 | 1 | 184 | 1 |
| @@ -217,6 +219,15 @@ pub trait VideoFrame: Send + Sync + Sized + Debug + 'static { | |||
| 217 | 2 | 219 | 2 |
| 218 | } | 220 | } |
| 219 | } | 221 | } |
| 222 | + // LOCAL PATCH: P010 is NV12 with 16-bit samples, so its | ||
| 223 | + // chroma element -- one UV pair -- is four bytes wide. | ||
| 224 | + DecodedFormat::P010 => { | ||
| 225 | + if plane_idx == 0 { | ||
| 226 | + 2 | ||
| 227 | + } else { | ||
| 228 | + 4 | ||
| 229 | + } | ||
| 230 | + } | ||
| 220 | }) | 231 | }) |
| 221 | } | 232 | } |
| 222 | } | 233 | } |
| @@ -528,6 +528,9 @@ impl VideoFrame for GenericDmaVideoFrame { | |||
| 528 | // TODO: Add more supported formats | 528 | // TODO: Add more supported formats |
| 529 | let rt_format = match self.decoded_format().unwrap() { | 529 | let rt_format = match self.decoded_format().unwrap() { |
| 530 | DecodedFormat::I420 | DecodedFormat::NV12 => libva::VA_RT_FORMAT_YUV420, | 530 | DecodedFormat::I420 | DecodedFormat::NV12 => libva::VA_RT_FORMAT_YUV420, |
| 531 | + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the 10-bit | ||
| 532 | + // surface an HEVC Main 10 stream decodes into. | ||
| 533 | + DecodedFormat::P010 => libva::VA_RT_FORMAT_YUV420_10, | ||
| 531 | _ => return Err("Format unsupported for VA-API export".to_string()), | 534 | _ => return Err("Format unsupported for VA-API export".to_string()), |
| 532 | }; | 535 | }; |
| 533 | 536 | ||
| @@ -0,0 +1,17 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "oxideav-h265" | ||
| 3 | +version = "0.0.9" | ||
| 4 | +edition = "2021" | ||
| 5 | +rust-version = "1.80" | ||
| 6 | +license = "MIT" | ||
| 7 | +repository = "https://github.com/OxideAV/oxideav-h265" | ||
| 8 | +authors = ["Mark Karpeles"] | ||
| 9 | +description = "Pure-Rust H.265 / HEVC (ITU-T H.265 | ISO/IEC 23008-2) bitstream parser + decoder scaffold for oxideav" | ||
| 10 | + | ||
| 11 | +readme = "README.md" | ||
| 12 | +homepage = "https://github.com/OxideAV/oxideav-h265" | ||
| 13 | +keywords = ["multimedia", "video", "h265", "hevc", "codec"] | ||
| 14 | +categories = ["multimedia::encoding", "multimedia::video"] | ||
| 15 | + | ||
| 16 | +[dependencies] | ||
| 17 | +oxideav-core = "0.1" | ||
| @@ -0,0 +1,21 @@ | |||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 Karpelès Lab Inc. | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. | ||
| @@ -0,0 +1,243 @@ | |||
| 1 | +# oxideav-h265 | ||
| 2 | + | ||
| 3 | +[](https://github.com/OxideAV/oxideav-h265/actions/workflows/ci.yml) [](https://crates.io/crates/oxideav-h265) [](https://docs.rs/oxideav-h265) [](LICENSE) | ||
| 4 | + | ||
| 5 | +A pure-Rust H.265 / HEVC video codec for the | ||
| 6 | +[oxideav](https://github.com/OxideAV/oxideav) framework, built | ||
| 7 | +clean-room against ITU-T Recommendation H.265 | ISO/IEC 23008-2. | ||
| 8 | + | ||
| 9 | +## Status | ||
| 10 | + | ||
| 11 | +**Decoder: end to end.** Every Annex B bitstream in the staged | ||
| 12 | +16-fixture conformance corpus decodes byte-exact to its expected YUV | ||
| 13 | +through the whole-bitstream driver (`decode_annexb_sequence` / | ||
| 14 | +`SequenceDecoder`) and the `oxideav_core::Decoder` registry entry | ||
| 15 | +(`make_decoder`, ids `"h265"` / `"hevc"`, `hvc1` / `hev1` / `HEVC` | ||
| 16 | +FourCCs, MP4 ObjectTypeIndication, Matroska tag) — plus self-built | ||
| 17 | +conformance pins for the features the corpus lacks (rounds 413 / 416: | ||
| 18 | +RDPCM, palette, cross-component prediction, adaptive colour | ||
| 19 | +transform, intra block copy), and a 37-stream black-box tool-axis | ||
| 20 | +sweep (round 410) held byte-exact by nine embedded pins. Against the | ||
| 21 | +staged **official JCT-VC RExt / SCC conformance corpus** (61 | ||
| 22 | +decodable bitstreams with published output digests, | ||
| 23 | +`docs/video/h265/conformance/`), 26 streams decode byte-exact | ||
| 24 | +(round 437; docs-gated pins in `tests/conformance_official.rs`) — | ||
| 25 | +including the transform-skip-context, wavefronts-inside-tiles / | ||
| 26 | +aligned-bypass / high-throughput, persistent-Rice-seeded, | ||
| 27 | +Monochrome 8/12-bit, Main 4:2:2 10 and 8-bit | ||
| 28 | +extended-precision-intra families. Coverage: | ||
| 29 | + | ||
| 30 | +* intra pictures at every staged geometry / CTB size (16 / 32 / 64) | ||
| 31 | + and QP extreme (slice QP 1 and 45), with SAO on and off; | ||
| 32 | +* multi-picture sequences: all-intra IDR runs, an IDR+P pair, and an | ||
| 33 | + eight-picture I/P/B pyramid with two reference lists, temporal MVP, | ||
| 34 | + AMVP MVDs, skip/merge CUs and POC output reordering; | ||
| 35 | +* Main10 and the 4:2:2 / 4:4:4 10-bit Range-Extensions streams; | ||
| 36 | +* multi-CTU slices, four-independent-slice pictures, dependent slice | ||
| 37 | + segments (§9.3.2.4/.5 `TableStateIdxDs` context carry + §7.4.7.1 | ||
| 38 | + header inheritance), per-slice loop-filter-across flags, and | ||
| 39 | + `entropy_coding_sync_enabled_flag` (WPP) streams with per-row | ||
| 40 | + entry-point substreams; | ||
| 41 | +* **true tiles**: the staged `true-tiles-2x2` fixture (2×2 uniform | ||
| 42 | + grid, one slice per tile, `loop_filter_across_tiles == 0`) decodes | ||
| 43 | + byte-exact, and multi-tile SINGLE-slice streams work end to end — | ||
| 44 | + §7.3.8.1 tile-boundary subsets (`end_of_subset_one_bit` + byte | ||
| 45 | + alignment), §9.3.2.2 per-tile CABAC re-initialization, tile-relative | ||
| 46 | + WPP row conditions, §8.6.1 per-tile `qPY_PREV` resets; | ||
| 47 | +* §8.5.3.3.4.3 explicit weighted prediction (P uni and B uni/bi, with | ||
| 48 | + non-default per-slice weights / offsets / denominators); | ||
| 49 | +* B pyramids / temporal layers / open-GOP CRA + leading pictures / | ||
| 50 | + RADL streams (a bi-predicted reference B as the §8.5.3.2.9 | ||
| 51 | + collocated picture), §7.4.5 scaling lists (default + explicit, all | ||
| 52 | + TB sizes, intra + inter), §8.4.4.2.3 strong intra smoothing, | ||
| 53 | + §8.4.4.2.1 constrained intra prediction, §7.3.8.11 transform skip, | ||
| 54 | + rectangular/AMP partitions with deep inter RQTs (§7.3.8.10 deferred | ||
| 55 | + chroma), WPP combined with multiple slices per picture, and | ||
| 56 | + 4:2:2 stacked chroma halves (per-half cbf gating and placement); | ||
| 57 | +* §7.3.8.7 PCM coding units, incl. the §8.7.2.5.4 / §8.7.3.1 | ||
| 58 | + loop-filter suppression (`pcm_loop_filter_disabled_flag`, and | ||
| 59 | + transquant-bypass CUs); | ||
| 60 | +* range-extension RDPCM (§8.6.5 implicit intra + explicit inter | ||
| 61 | + directional residual modification) and SCC **palette mode** | ||
| 62 | + (§7.3.8.13 parse incl. the predictor-palette machinery with WPP / | ||
| 63 | + dependent-slice synchronization, §8.4.4.2.7 reconstruction with | ||
| 64 | + transpose and bypass / quantized escapes) — pinned by self-built | ||
| 65 | + conformance streams (`tests/fixture_bytes/r413-*.hevc`), the | ||
| 66 | + implicit-RDPCM stream byte-exact against a black-box reference | ||
| 67 | + decode; | ||
| 68 | +* the Rext/SCC application tail: §8.6.6 **cross-component | ||
| 69 | + prediction** (eq. 8-324 applied on the intra and inter residual | ||
| 70 | + paths, cbf-clear chroma blocks included), §8.6.8 **adaptive colour | ||
| 71 | + transform** (the §8.6.8.2 lifting inverse with ACT-adjusted | ||
| 72 | + quantization, eqs 8-287/8-288/8-291), and **intra block copy** | ||
| 73 | + (current-picture referencing: the §8.3.4 currPic list append, | ||
| 74 | + `use_integer_mv_flag`, the eqs 8-98..8-101 / 8-124..8-125 integer | ||
| 75 | + MV paths, the eqs 8-102/8-103 reduction, prediction from the | ||
| 76 | + pre-filter reconstruction) — pinned by self-built conformance | ||
| 77 | + streams (`tests/fixture_bytes/r416-*.hevc`), the CCP stream | ||
| 78 | + byte-exact against a black-box reference decode (the surveyed | ||
| 79 | + reference decoder rejects SCC streams outright, so the ACT / IBC | ||
| 80 | + pins are decoder-pins); | ||
| 81 | +* both transport forms: Annex B extradata/packets AND `hvcC` | ||
| 82 | + (`HEVCDecoderConfigurationRecord`, ISO/IEC 14496-15 §8.3.3.1) | ||
| 83 | + extradata with length-prefixed packets. | ||
| 84 | + | ||
| 85 | +**Encoder: intra + low-delay inter + hierarchical-B GOPs with AMP | ||
| 86 | +and in-loop filters, registered.** `make_encoder` / `H265Encoder` | ||
| 87 | +with three modes: | ||
| 88 | + | ||
| 89 | +* `mode = "inter"` (`qp` 0..=51, `gop` IDR period, `bslices`, `amp`, | ||
| 90 | + `pyramid`) — low-delay `IDR, P, P, …` / `IDR, B, B, …` GOPs | ||
| 91 | + (`encoder::inter::LowDelayPEncoder`, one frame in / one AU out) or | ||
| 92 | + dyadic **hierarchical-B pyramids** | ||
| 93 | + (`encoder::pyramid::PyramidEncoder`, `pyramid = 2/4/8/16`): | ||
| 94 | + per-CTU **skip / merge / AMVP / two-PU-partition / intra** | ||
| 95 | + decisions under an SSD + λ·rate heuristic, with **two active | ||
| 96 | + reference pictures** on the low-delay path (POC − 1 / POC − 2, | ||
| 97 | + `ref_idx_l0` signalled). Motion candidates are resolved through | ||
| 98 | + the crate's own DECODE-side §8.5.3.2 merge/AMVP derivation against | ||
| 99 | + the in-progress motion field (§6.4.2 availability included), | ||
| 100 | + motion estimation is a seeded greedy integer diamond plus | ||
| 101 | + half-/quarter-pel refinement against the crate's §8.5.3.3.3 | ||
| 102 | + interpolation, two-PU CUs carry the §7.4.9.8 forced depth-1 RQT, | ||
| 103 | + and a `pred_mode_flag == 1` intra fallback rescues scene changes. | ||
| 104 | + The **AMP configuration** (`amp` option / `with_amp`) moves the | ||
| 105 | + stream to `MinCbSizeY == 8` + `amp_enabled_flag == 1` (explicit | ||
| 106 | + `split_cu_flag`, the Table 9-45 big-CU `part_mode` column) and | ||
| 107 | + elects `PART_2NxnU / PART_2NxnD / PART_nLx2N / PART_nRx2N` | ||
| 108 | + alongside the symmetric shapes — on quarter-offset motion-boundary | ||
| 109 | + content the shapes buy **−20 to −29 % bytes at equal PSNR**. The | ||
| 110 | + **pyramid** codes each mini-GOP out of display order (next anchor | ||
| 111 | + as P first, then the midpoint B recursion with the past boundary | ||
| 112 | + on `RefPicList0` and the FUTURE boundary on `RefPicList1`), | ||
| 113 | + signals per-slice negative + positive short-term RPS with | ||
| 114 | + `sps_max_num_reorder_pics = log2(gop)`, allocates rate by | ||
| 115 | + per-layer QP offsets, and searches uni-L0 / uni-L1 / **bi AMVP** | ||
| 116 | + per PU (`inter_pred_idc` `PRED_L0/L1/BI` all emitted); on a | ||
| 117 | + noisy-pan clip the GOP-8 pyramid takes **−11.5 % bytes** vs the | ||
| 118 | + low-delay chain at qp 27. Every stream decodes **bit-exact** to | ||
| 119 | + the encoder reconstruction through this crate's decoder AND a | ||
| 120 | + black-box reference decoder (multi-QP, multi-shape sweeps; golden | ||
| 121 | + GOP / AMP / pyramid / composition streams CI-pinned). Per-frame | ||
| 122 | + `FrameStats` expose the skip/merge/AMVP/intra/bi/rect/amp/ref1 | ||
| 123 | + decisions. | ||
| 124 | +* `mode = "intra"` — per-CTU §8.4 intra prediction over the | ||
| 125 | + encoder's own reconstruction (all 35 modes, per-CTB `PART_2Nx2N` | ||
| 126 | + vs `PART_NxN` rate-distortion decision with per-PB modes, §8.4.2 | ||
| 127 | + MPM signalling, mode-dependent scans), forward DCT-II + reciprocal | ||
| 128 | + quantization, full §7.3.8 syntax through the bin-exact §7.3.8.11 | ||
| 129 | + residual encoder (golden interop stream CI-pinned). | ||
| 130 | +* `mode = "pcm"` (default) — the lossless PCM-IDR bootstrap | ||
| 131 | + (every CTB a 16×16 PCM CU; options for dependent segments, | ||
| 132 | + multi-slice plans, deblocking, band / edge SAO syntax, and true | ||
| 133 | + multi-tile single-slice pictures with §7.4.7.1 entry points). | ||
| 134 | + | ||
| 135 | +Both coding modes accept the §8.7 **in-loop filters** (`deblock` / | ||
| 136 | +`sao` codec options, `LoopFilterCfg` on the direct APIs): the encoder | ||
| 137 | +reconstructs through its own decode-side §8.7.2 deblocking (per-slice | ||
| 138 | +election over off + a {−2, 0, 2}² β/tC-offset sweep, signalled via | ||
| 139 | +the §7.3.6.1 override group) and §8.7.3 SAO (per-CTB statistics-driven band / edge | ||
| 140 | +offset estimation with merge-left/up pricing, every candidate | ||
| 141 | +measured with the decoder's own apply, `encode_sao_ctb` the bin-exact | ||
| 142 | +§7.3.8.3 dual of the parse) — so the filtered pictures its references | ||
| 143 | +and outputs hold are exactly a conforming decoder's. Filtered P/B | ||
| 144 | +GOPs across a 72-configuration sweep decode byte-exact through a | ||
| 145 | +black-box reference decoder (three golden filtered streams | ||
| 146 | +CI-pinned); on the interop clip the filters buy up to +1.5 dB luma | ||
| 147 | +PSNR at equal rate. | ||
| 148 | + | ||
| 149 | +4:2:0 8-bit, dimensions multiples of 16. | ||
| 150 | + | ||
| 151 | +## What's implemented | ||
| 152 | + | ||
| 153 | +* **Whole-bitstream decode driver** (`sequence`) — Annex B demux → | ||
| 154 | + SPS/PPS activation → §7.3.6.1 slice headers (independent and | ||
| 155 | + dependent segments) → the §7.3.8.1 CTU loop (tile-scan addressing, | ||
| 156 | + per-slice CABAC init, the §9.3.2.4/.5 WPP and dependent-segment | ||
| 157 | + context storage/sync, WPP substreams via the §7.4.7.1 entry | ||
| 158 | + points) → picture reconstruction → §8.3.1..§8.3.5 reference | ||
| 159 | + cycle → output reorder. Tile-scan CTU addressing with §9.3.2.2 | ||
| 160 | + per-tile context re-initialization and entry-point subsets shared | ||
| 161 | + with WPP. | ||
| 162 | +* **Registry codec** (`decoder` / `encoder`) — the | ||
| 163 | + `oxideav_core::Decoder` + `Encoder` contracts: Annex B or | ||
| 164 | + hvcC/length-prefixed packets in, output-order `VideoFrame`s out | ||
| 165 | + (reorder queue bounded by `sps_max_num_reorder_pics`, packet-PTS | ||
| 166 | + re-attachment, flush-then-`Eof`); frames in, IDR keyframe packets | ||
| 167 | + out (`mode = "pcm"` lossless or `mode = "intra"` at a chosen QP). | ||
| 168 | + `make_decoder` / `make_encoder` are the direct factory endpoints. | ||
| 169 | +* **Headers** — VPS / SPS / PPS (§7.3.2, incl. range + SCC extension | ||
| 170 | + bodies), VUI + HRD (§E.2), slice segment headers (§7.3.6, all slice | ||
| 171 | + types, RPS forms, `ref_pic_lists_modification()`, | ||
| 172 | + `pred_weight_table()`, entry points incl. dependent segments), | ||
| 173 | + §7.4.8 RPS materialization, scaling lists (§7.3.4 / §7.4.5), and | ||
| 174 | + the `hvcC` record (`hvcc`, ISO/IEC 14496-15 §8.3.3.1). | ||
| 175 | +* **CABAC, both directions** — the §9.3 decode engine and the §9.3.5 | ||
| 176 | + encode engine (decision / bypass / terminate + flush, PCM | ||
| 177 | + align-and-reinit), per-syntax-element binarizations (§9.3.4.2), the | ||
| 178 | + complete §7.3.8 decode syntax tree, and the write-side §7.3.8.11 | ||
| 179 | + `residual_coding( )` dual (`encoder::residual`, differential-tested | ||
| 180 | + to identical levels + context evolution). | ||
| 181 | +* **Reconstruction** — §8.4 intra prediction (all 35 modes), §8.4.1 | ||
| 182 | + PCM sample write-back, §8.5 inter prediction (merge / MVP / | ||
| 183 | + temporal candidates with the §8.5.3.2.3 raw-availability redundancy | ||
| 184 | + gates, §8.5.3.3.3 interpolation, §8.5.3.3.4.2 default AND | ||
| 185 | + §8.5.3.3.4.3 explicit weighted combines with the §7.4.7.3 table | ||
| 186 | + resolution), §8.6 dequant / inverse transform, §8.6.1 per-QG QP | ||
| 187 | + derivation. | ||
| 188 | +* **In-loop filters** — §8.7.2 deblocking and §8.7.3 SAO with | ||
| 189 | + per-slice `slice_loop_filter_across_slices_enabled_flag` gates | ||
| 190 | + (deblocking per the current CU's slice; SAO per the §8.7.3.2 | ||
| 191 | + directional later-slice rule) and the PCM / transquant-bypass | ||
| 192 | + sample suppression (`NoFilterMap`). | ||
| 193 | +* **Reference machinery** — §8.3.1 POC, §8.3.2 RPS marking, §8.3.4 | ||
| 194 | + reference lists, §8.3.5 collocated picture, the DPB, and the | ||
| 195 | + per-picture decode cycle threading motion fields for temporal MVP. | ||
| 196 | + | ||
| 197 | +Thirty-six embedded-fixture regression pins (the 17-stream staged | ||
| 198 | +corpus incl. true tiles + self-built weighted-prediction, | ||
| 199 | +per-slice-loop-filter, hvcC, golden-intra-interop, golden-P-GOP | ||
| 200 | +interop, the round-431 AMP / pyramid / composition interop pins, and | ||
| 201 | +the nine round-410 tool-axis conformance pins), lossless PCM / | ||
| 202 | +exact-reconstruction intra / bit-exact low-delay- and | ||
| 203 | +hierarchical-B-GOP encoder↔decoder roundtrips at multiple | ||
| 204 | +geometries / QPs / partitions / slice types, and ~930 unit tests. | ||
| 205 | + | ||
| 206 | +## Not yet implemented | ||
| 207 | + | ||
| 208 | +* Larger encoder CTB sizes, deeper encoder RQTs / coding quadtrees | ||
| 209 | + (the AMP configuration codes 16x16 CUs above an 8x8 MinCb, but | ||
| 210 | + never splits), 4x4-luma DST TUs, encoder temporal MVP, more than | ||
| 211 | + one active reference per list on the pyramid path, and adaptive | ||
| 212 | + (non-dyadic) GOP structures. | ||
| 213 | +* Non-uniform (`uniform_spacing_flag == 0`) tile-grid *encoding* | ||
| 214 | + (decode side is implemented). | ||
| 215 | +* Known corner: on the §8.7.3.2 SAO cross-slice neighbour rule with | ||
| 216 | + heterogeneous per-slice flags, a black-box reference decoder | ||
| 217 | + consults the current sample's slice flag where the spec text (both | ||
| 218 | + 08/2021 and 01/2026 editions) names the later (decode-order) | ||
| 219 | + slice's flag; this implementation follows the spec text. | ||
| 220 | +* Known corner (RDPCM, spec text followed): §8.4.4.2.6 sets | ||
| 221 | + `disableIntraBoundaryFilter` when implicit RDPCM combines with | ||
| 222 | + transquant bypass, suppressing the mode-10/26 edge filters — a | ||
| 223 | + black-box reference decoder applies those filters regardless. | ||
| 224 | + (The r413 note claiming a reference deviation on explicit-RDPCM | ||
| 225 | + *vertical* blocks is retired: the official `ExplicitRdpcm_A` | ||
| 226 | + conformance stream matches the black-box decode exactly, this | ||
| 227 | + crate's luma decode agrees byte-for-byte, and the remaining | ||
| 228 | + divergence is an unrelated ±1 chroma artifact on isolated rows, | ||
| 229 | + still under investigation.) | ||
| 230 | +* Official-corpus families not yet byte-exact: the 4:4:4 | ||
| 231 | + multi-tool `GENERAL_*_444` / `WAVETILES` / `QMATRIX` parse | ||
| 232 | + desync (mid-picture, first reproduces in a busy 4:4:4 intra CTB), | ||
| 233 | + 16-bit extended-precision reconstruction (the 8-bit | ||
| 234 | + extended-precision streams pass; 10/12/16-bit diverge on their | ||
| 235 | + first picture), unequal luma/chroma bit depths (first divergence | ||
| 236 | + at frame 4), the official CCP / SAO-offset-scale / persistent-Rice | ||
| 237 | + single-stream anchors, and most SCC streams (palette-heavy parse | ||
| 238 | + still desyncs mid-slice; two streams decode all 33 frames with | ||
| 239 | + subtle reconstruction deltas). | ||
| 240 | + | ||
| 241 | +## License | ||
| 242 | + | ||
| 243 | +MIT — see [LICENSE](./LICENSE). | ||
| @@ -0,0 +1,569 @@ | |||
| 1 | +//! §6.4 availability processes + the §6.5.1 / §6.5.2 picture-level | ||
| 2 | +//! scanning conversions they depend on. | ||
| 3 | +//! | ||
| 4 | +//! Intra (and, later, inter) sample prediction asks, for each candidate | ||
| 5 | +//! neighbour location `( xNbY, yNbY )`, whether that neighbour is | ||
| 6 | +//! *available for prediction* — i.e. it lies inside the picture, has | ||
| 7 | +//! already been decoded in the current decoding order, and sits in the | ||
| 8 | +//! same slice segment and tile as the current block. ITU-T Rec. H.265 | ||
| 9 | +//! §6.4.1 answers that question, and it does so in terms of a | ||
| 10 | +//! *minimum-transform-block address in z-scan order*, `MinTbAddrZs`. | ||
| 11 | +//! | ||
| 12 | +//! `MinTbAddrZs` (§6.5.2) in turn is built from `CtbAddrRsToTs` | ||
| 13 | +//! (§6.5.1) — the CTB raster-scan ↔ tile-scan address conversion that | ||
| 14 | +//! folds the picture's tile layout into the decoding order. So this | ||
| 15 | +//! module implements three layers, bottom-up: | ||
| 16 | +//! | ||
| 17 | +//! * [`PictureTiling`] — §6.5.1. From the picture geometry in CTBs and | ||
| 18 | +//! the §7.3.2.3.1 tile-partitioning parameters it derives `colWidth` | ||
| 19 | +//! / `rowHeight` (eqs. 6-3 / 6-4), `colBd` / `rowBd` (eqs. 6-5 / | ||
| 20 | +//! 6-6), `CtbAddrRsToTs` / `CtbAddrTsToRs` (eqs. 6-7 / 6-8), and | ||
| 21 | +//! `TileId` (eq. 6-9). | ||
| 22 | +//! * [`PictureTiling::min_tb_addr_zs`] — §6.5.2. The | ||
| 23 | +//! `MinTbAddrZs[ x ][ y ]` array (eq. 6-10) mapping a minimum-block | ||
| 24 | +//! `( x, y )` to its z-scan address, interleaving the within-CTB | ||
| 25 | +//! Morton (z) order with the tile-scan CTB order. | ||
| 26 | +//! * [`PictureTiling::z_scan_availability`] — §6.4.1, and | ||
| 27 | +//! [`PictureTiling::prediction_block_availability`] — §6.4.2. | ||
| 28 | +//! | ||
| 29 | +//! ## Scope | ||
| 30 | +//! | ||
| 31 | +//! The numerics are self-contained. The caller supplies the picture | ||
| 32 | +//! geometry (in CTBs and in luma samples), the `Log2SizeY` shifts, the | ||
| 33 | +//! tile parameters from the active PPS, and a `slice_addr_rs` lookup | ||
| 34 | +//! that maps a CTB raster address to the `SliceAddrRs` of the slice | ||
| 35 | +//! segment that owns it (§6.4.1's slice-boundary test). For §6.4.2 the | ||
| 36 | +//! caller additionally supplies a `CuPredMode` lookup (the final | ||
| 37 | +//! `MODE_INTRA` masking step). Building those lookups is the slice-data | ||
| 38 | +//! walk's responsibility; this module starts at the geometry and stops | ||
| 39 | +//! at `availableN`. | ||
| 40 | + | ||
| 41 | +/// `CuPredMode` value `MODE_INTRA` — used by the §6.4.2 final masking | ||
| 42 | +/// step. Mirrors the Table 7-10 enumeration without depending on the | ||
| 43 | +/// slice module's richer type. | ||
| 44 | +pub const MODE_INTRA: u8 = 1; | ||
| 45 | + | ||
| 46 | +/// Errors from constructing a [`PictureTiling`]. | ||
| 47 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 48 | +pub enum AvailabilityError { | ||
| 49 | + /// A geometry input was zero where the spec requires a positive | ||
| 50 | + /// value (`PicWidthInCtbsY` / `PicHeightInCtbsY` must be ≥ 1). | ||
| 51 | + ZeroGeometry { | ||
| 52 | + /// Name of the offending field. | ||
| 53 | + field: &'static str, | ||
| 54 | + }, | ||
| 55 | + /// `CtbLog2SizeY` is smaller than `MinTbLog2SizeY`, which would make | ||
| 56 | + /// the §6.5.2 `( CtbLog2SizeY − MinTbLog2SizeY )` shift negative. | ||
| 57 | + InvalidLog2Sizes { | ||
| 58 | + /// `CtbLog2SizeY`. | ||
| 59 | + ctb_log2: u32, | ||
| 60 | + /// `MinTbLog2SizeY`. | ||
| 61 | + min_tb_log2: u32, | ||
| 62 | + }, | ||
| 63 | + /// The explicit (`uniform_spacing_flag == 0`) tile-size array had a | ||
| 64 | + /// length other than the required `num_tile_*_minus1`. | ||
| 65 | + TileArrayLength { | ||
| 66 | + /// Name of the offending array. | ||
| 67 | + field: &'static str, | ||
| 68 | + /// Length the spec requires. | ||
| 69 | + expected: usize, | ||
| 70 | + /// Length that was supplied. | ||
| 71 | + got: usize, | ||
| 72 | + }, | ||
| 73 | + /// An explicit tile column/row was wider/taller than the picture, so | ||
| 74 | + /// the implied last tile would have a non-positive size. | ||
| 75 | + TileOverflow { | ||
| 76 | + /// `"column"` or `"row"`. | ||
| 77 | + dimension: &'static str, | ||
| 78 | + }, | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +impl core::fmt::Display for AvailabilityError { | ||
| 82 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| 83 | + match self { | ||
| 84 | + Self::ZeroGeometry { field } => { | ||
| 85 | + write!(f, "picture geometry field {field} must be positive") | ||
| 86 | + } | ||
| 87 | + Self::InvalidLog2Sizes { | ||
| 88 | + ctb_log2, | ||
| 89 | + min_tb_log2, | ||
| 90 | + } => write!( | ||
| 91 | + f, | ||
| 92 | + "CtbLog2SizeY ({ctb_log2}) must be >= MinTbLog2SizeY ({min_tb_log2})" | ||
| 93 | + ), | ||
| 94 | + Self::TileArrayLength { | ||
| 95 | + field, | ||
| 96 | + expected, | ||
| 97 | + got, | ||
| 98 | + } => write!(f, "tile array {field} length {got} != expected {expected}"), | ||
| 99 | + Self::TileOverflow { dimension } => { | ||
| 100 | + write!(f, "explicit tile {dimension} sizes overflow the picture") | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + } | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +impl std::error::Error for AvailabilityError {} | ||
| 107 | + | ||
| 108 | +/// The §7.3.2.3.1 tile-partitioning parameters needed to build the | ||
| 109 | +/// CTB-scan conversion, as carried by the active PPS. | ||
| 110 | +/// | ||
| 111 | +/// When `tiles_enabled_flag == 0` the picture is a single tile; pass | ||
| 112 | +/// [`TilingParams::single_tile`] (one column, one row). | ||
| 113 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 114 | +pub struct TilingParams { | ||
| 115 | + /// `num_tile_columns_minus1` — the number of tile columns is this | ||
| 116 | + /// plus one. | ||
| 117 | + pub num_tile_columns_minus1: u32, | ||
| 118 | + /// `num_tile_rows_minus1` — the number of tile rows is this plus | ||
| 119 | + /// one. | ||
| 120 | + pub num_tile_rows_minus1: u32, | ||
| 121 | + /// `uniform_spacing_flag`. When `true` the columns/rows are spread | ||
| 122 | + /// as evenly as possible (eqs. 6-3 / 6-4 uniform branch) and the | ||
| 123 | + /// explicit arrays are ignored. | ||
| 124 | + pub uniform_spacing_flag: bool, | ||
| 125 | + /// `column_width_minus1[ i ]` for `i` in | ||
| 126 | + /// `0..num_tile_columns_minus1` (only when not uniform). | ||
| 127 | + pub column_width_minus1: Vec<u32>, | ||
| 128 | + /// `row_height_minus1[ j ]` for `j` in `0..num_tile_rows_minus1` | ||
| 129 | + /// (only when not uniform). | ||
| 130 | + pub row_height_minus1: Vec<u32>, | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +impl TilingParams { | ||
| 134 | + /// The single-tile layout used when `tiles_enabled_flag == 0`. | ||
| 135 | + pub fn single_tile() -> Self { | ||
| 136 | + Self { | ||
| 137 | + num_tile_columns_minus1: 0, | ||
| 138 | + num_tile_rows_minus1: 0, | ||
| 139 | + uniform_spacing_flag: true, | ||
| 140 | + column_width_minus1: Vec::new(), | ||
| 141 | + row_height_minus1: Vec::new(), | ||
| 142 | + } | ||
| 143 | + } | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +/// Picture-level geometry plus the derived §6.5.1 / §6.5.2 conversion | ||
| 147 | +/// tables. Construct with [`PictureTiling::new`], then query availability | ||
| 148 | +/// with [`PictureTiling::z_scan_availability`] / | ||
| 149 | +/// [`PictureTiling::prediction_block_availability`]. | ||
| 150 | +#[derive(Debug, Clone)] | ||
| 151 | +pub struct PictureTiling { | ||
| 152 | + pic_width_in_ctbs_y: u32, | ||
| 153 | + pic_height_in_ctbs_y: u32, | ||
| 154 | + pic_width_in_luma_samples: u32, | ||
| 155 | + pic_height_in_luma_samples: u32, | ||
| 156 | + ctb_log2_size_y: u32, | ||
| 157 | + min_tb_log2_size_y: u32, | ||
| 158 | + /// `colBd[ 0..=num_tile_columns_minus1 + 1 ]` (eq. 6-5). | ||
| 159 | + col_bd: Vec<u32>, | ||
| 160 | + /// `rowBd[ 0..=num_tile_rows_minus1 + 1 ]` (eq. 6-6). | ||
| 161 | + row_bd: Vec<u32>, | ||
| 162 | + /// `CtbAddrRsToTs[ ctbAddrRs ]` (eq. 6-7). | ||
| 163 | + ctb_addr_rs_to_ts: Vec<u32>, | ||
| 164 | + /// `CtbAddrTsToRs[ ctbAddrTs ]` (eq. 6-8). | ||
| 165 | + ctb_addr_ts_to_rs: Vec<u32>, | ||
| 166 | + /// `TileId[ ctbAddrTs ]` (eq. 6-9). | ||
| 167 | + tile_id: Vec<u32>, | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +impl PictureTiling { | ||
| 171 | + /// Build the §6.5.1 conversion tables from the picture geometry and | ||
| 172 | + /// tile parameters. | ||
| 173 | + /// | ||
| 174 | + /// * `pic_width_in_ctbs_y` / `pic_height_in_ctbs_y` — | ||
| 175 | + /// `PicWidthInCtbsY` / `PicHeightInCtbsY` (eqs. 7-20 / 7-21). | ||
| 176 | + /// * `pic_width_in_luma_samples` / `pic_height_in_luma_samples` — | ||
| 177 | + /// the SPS conformance-relevant `pic_width_in_luma_samples` / | ||
| 178 | + /// `pic_height_in_luma_samples` used by §6.4.1's boundary test. | ||
| 179 | + /// * `ctb_log2_size_y` — `CtbLog2SizeY` (eq. 7-11). | ||
| 180 | + /// * `min_tb_log2_size_y` — `MinTbLog2SizeY` | ||
| 181 | + /// (= `log2_min_luma_transform_block_size_minus2 + 2`). | ||
| 182 | + /// * `tiles` — the active PPS tile-partitioning parameters. | ||
| 183 | + pub fn new( | ||
| 184 | + pic_width_in_ctbs_y: u32, | ||
| 185 | + pic_height_in_ctbs_y: u32, | ||
| 186 | + pic_width_in_luma_samples: u32, | ||
| 187 | + pic_height_in_luma_samples: u32, | ||
| 188 | + ctb_log2_size_y: u32, | ||
| 189 | + min_tb_log2_size_y: u32, | ||
| 190 | + tiles: &TilingParams, | ||
| 191 | + ) -> Result<Self, AvailabilityError> { | ||
| 192 | + if pic_width_in_ctbs_y == 0 { | ||
| 193 | + return Err(AvailabilityError::ZeroGeometry { | ||
| 194 | + field: "PicWidthInCtbsY", | ||
| 195 | + }); | ||
| 196 | + } | ||
| 197 | + if pic_height_in_ctbs_y == 0 { | ||
| 198 | + return Err(AvailabilityError::ZeroGeometry { | ||
| 199 | + field: "PicHeightInCtbsY", | ||
| 200 | + }); | ||
| 201 | + } | ||
| 202 | + if ctb_log2_size_y < min_tb_log2_size_y { | ||
| 203 | + return Err(AvailabilityError::InvalidLog2Sizes { | ||
| 204 | + ctb_log2: ctb_log2_size_y, | ||
| 205 | + min_tb_log2: min_tb_log2_size_y, | ||
| 206 | + }); | ||
| 207 | + } | ||
| 208 | + | ||
| 209 | + let num_cols = (tiles.num_tile_columns_minus1 + 1) as usize; | ||
| 210 | + let num_rows = (tiles.num_tile_rows_minus1 + 1) as usize; | ||
| 211 | + | ||
| 212 | + // §6.5.1 eqs. 6-3 / 6-4 — colWidth / rowHeight (in CTBs). | ||
| 213 | + let col_width = derive_tile_sizes( | ||
| 214 | + pic_width_in_ctbs_y, | ||
| 215 | + tiles.num_tile_columns_minus1, | ||
| 216 | + tiles.uniform_spacing_flag, | ||
| 217 | + &tiles.column_width_minus1, | ||
| 218 | + "column_width_minus1", | ||
| 219 | + "column", | ||
| 220 | + )?; | ||
| 221 | + let row_height = derive_tile_sizes( | ||
| 222 | + pic_height_in_ctbs_y, | ||
| 223 | + tiles.num_tile_rows_minus1, | ||
| 224 | + tiles.uniform_spacing_flag, | ||
| 225 | + &tiles.row_height_minus1, | ||
| 226 | + "row_height_minus1", | ||
| 227 | + "row", | ||
| 228 | + )?; | ||
| 229 | + | ||
| 230 | + // §6.5.1 eqs. 6-5 / 6-6 — colBd / rowBd (cumulative boundaries). | ||
| 231 | + let mut col_bd = vec![0u32; num_cols + 1]; | ||
| 232 | + for i in 0..num_cols { | ||
| 233 | + col_bd[i + 1] = col_bd[i] + col_width[i]; | ||
| 234 | + } | ||
| 235 | + let mut row_bd = vec![0u32; num_rows + 1]; | ||
| 236 | + for j in 0..num_rows { | ||
| 237 | + row_bd[j + 1] = row_bd[j] + row_height[j]; | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + let pic_size_in_ctbs_y = (pic_width_in_ctbs_y * pic_height_in_ctbs_y) as usize; | ||
| 241 | + | ||
| 242 | + // §6.5.1 eq. 6-7 — CtbAddrRsToTs. | ||
| 243 | + let mut ctb_addr_rs_to_ts = vec![0u32; pic_size_in_ctbs_y]; | ||
| 244 | + for ctb_addr_rs in 0..pic_size_in_ctbs_y as u32 { | ||
| 245 | + let tb_x = ctb_addr_rs % pic_width_in_ctbs_y; | ||
| 246 | + let tb_y = ctb_addr_rs / pic_width_in_ctbs_y; | ||
| 247 | + let mut tile_x = 0usize; | ||
| 248 | + for (i, &bd) in col_bd.iter().take(num_cols).enumerate() { | ||
| 249 | + if tb_x >= bd { | ||
| 250 | + tile_x = i; | ||
| 251 | + } | ||
| 252 | + } | ||
| 253 | + let mut tile_y = 0usize; | ||
| 254 | + for (j, &bd) in row_bd.iter().take(num_rows).enumerate() { | ||
| 255 | + if tb_y >= bd { | ||
| 256 | + tile_y = j; | ||
| 257 | + } | ||
| 258 | + } | ||
| 259 | + let mut val = 0u32; | ||
| 260 | + for &cw in col_width.iter().take(tile_x) { | ||
| 261 | + val += row_height[tile_y] * cw; | ||
| 262 | + } | ||
| 263 | + for &rh in row_height.iter().take(tile_y) { | ||
| 264 | + val += pic_width_in_ctbs_y * rh; | ||
| 265 | + } | ||
| 266 | + val += (tb_y - row_bd[tile_y]) * col_width[tile_x] + tb_x - col_bd[tile_x]; | ||
| 267 | + ctb_addr_rs_to_ts[ctb_addr_rs as usize] = val; | ||
| 268 | + } | ||
| 269 | + | ||
| 270 | + // §6.5.1 eq. 6-8 — CtbAddrTsToRs (inverse permutation). | ||
| 271 | + let mut ctb_addr_ts_to_rs = vec![0u32; pic_size_in_ctbs_y]; | ||
| 272 | + for ctb_addr_rs in 0..pic_size_in_ctbs_y as u32 { | ||
| 273 | + ctb_addr_ts_to_rs[ctb_addr_rs_to_ts[ctb_addr_rs as usize] as usize] = ctb_addr_rs; | ||
| 274 | + } | ||
| 275 | + | ||
| 276 | + // §6.5.1 eq. 6-9 — TileId. | ||
| 277 | + let mut tile_id = vec![0u32; pic_size_in_ctbs_y]; | ||
| 278 | + let mut tile_idx = 0u32; | ||
| 279 | + for j in 0..num_rows { | ||
| 280 | + for i in 0..num_cols { | ||
| 281 | + for y in row_bd[j]..row_bd[j + 1] { | ||
| 282 | + for x in col_bd[i]..col_bd[i + 1] { | ||
| 283 | + let rs = (y * pic_width_in_ctbs_y + x) as usize; | ||
| 284 | + tile_id[ctb_addr_rs_to_ts[rs] as usize] = tile_idx; | ||
| 285 | + } | ||
| 286 | + } | ||
| 287 | + tile_idx += 1; | ||
| 288 | + } | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + Ok(Self { | ||
| 292 | + pic_width_in_ctbs_y, | ||
| 293 | + pic_height_in_ctbs_y, | ||
| 294 | + pic_width_in_luma_samples, | ||
| 295 | + pic_height_in_luma_samples, | ||
| 296 | + ctb_log2_size_y, | ||
| 297 | + min_tb_log2_size_y, | ||
| 298 | + col_bd, | ||
| 299 | + row_bd, | ||
| 300 | + ctb_addr_rs_to_ts, | ||
| 301 | + ctb_addr_ts_to_rs, | ||
| 302 | + tile_id, | ||
| 303 | + }) | ||
| 304 | + } | ||
| 305 | + | ||
| 306 | + /// `CtbAddrRsToTs[ ctbAddrRs ]` (eq. 6-7). Panics on out-of-range | ||
| 307 | + /// `ctb_addr_rs`; valid indices are `0..PicSizeInCtbsY`. | ||
| 308 | + pub fn ctb_addr_rs_to_ts(&self, ctb_addr_rs: u32) -> u32 { | ||
| 309 | + self.ctb_addr_rs_to_ts[ctb_addr_rs as usize] | ||
| 310 | + } | ||
| 311 | + | ||
| 312 | + /// `CtbAddrTsToRs[ ctbAddrTs ]` (eq. 6-8). | ||
| 313 | + pub fn ctb_addr_ts_to_rs(&self, ctb_addr_ts: u32) -> u32 { | ||
| 314 | + self.ctb_addr_ts_to_rs[ctb_addr_ts as usize] | ||
| 315 | + } | ||
| 316 | + | ||
| 317 | + /// `TileId[ ctbAddrTs ]` (eq. 6-9) — the tile a tile-scan CTB | ||
| 318 | + /// address belongs to. | ||
| 319 | + pub fn tile_id(&self, ctb_addr_ts: u32) -> u32 { | ||
| 320 | + self.tile_id[ctb_addr_ts as usize] | ||
| 321 | + } | ||
| 322 | + | ||
| 323 | + /// `colBd[ i ]` (eq. 6-5) — the i-th tile-column boundary in units | ||
| 324 | + /// of CTBs, for `i` in `0..=num_tile_columns_minus1 + 1`. | ||
| 325 | + pub fn col_bd(&self) -> &[u32] { | ||
| 326 | + &self.col_bd | ||
| 327 | + } | ||
| 328 | + | ||
| 329 | + /// `rowBd[ j ]` (eq. 6-6) — the j-th tile-row boundary in units of | ||
| 330 | + /// CTBs, for `j` in `0..=num_tile_rows_minus1 + 1`. | ||
| 331 | + pub fn row_bd(&self) -> &[u32] { | ||
| 332 | + &self.row_bd | ||
| 333 | + } | ||
| 334 | + | ||
| 335 | + /// `PicWidthInCtbsY`. | ||
| 336 | + pub fn pic_width_in_ctbs_y(&self) -> u32 { | ||
| 337 | + self.pic_width_in_ctbs_y | ||
| 338 | + } | ||
| 339 | + | ||
| 340 | + /// `PicHeightInCtbsY`. | ||
| 341 | + pub fn pic_height_in_ctbs_y(&self) -> u32 { | ||
| 342 | + self.pic_height_in_ctbs_y | ||
| 343 | + } | ||
| 344 | + | ||
| 345 | + /// The TileId of the tile covering luma sample `( xY, yY )`. | ||
| 346 | + /// Convenience over [`Self::tile_id`] that converts the luma | ||
| 347 | + /// location through the CTB raster→tile-scan conversion. The caller | ||
| 348 | + /// is responsible for keeping `( xY, yY )` inside the picture. | ||
| 349 | + fn tile_id_at_luma(&self, x_y: u32, y_y: u32) -> u32 { | ||
| 350 | + let ctb_x = x_y >> self.ctb_log2_size_y; | ||
| 351 | + let ctb_y = y_y >> self.ctb_log2_size_y; | ||
| 352 | + let ctb_addr_rs = ctb_y * self.pic_width_in_ctbs_y + ctb_x; | ||
| 353 | + self.tile_id[self.ctb_addr_rs_to_ts[ctb_addr_rs as usize] as usize] | ||
| 354 | + } | ||
| 355 | + | ||
| 356 | + /// `MinTbAddrZs[ x ][ y ]` (§6.5.2 eq. 6-10) — the minimum-block | ||
| 357 | + /// location `( x, y )` (in units of `MinTbLog2SizeY`-sized blocks) | ||
| 358 | + /// converted to a minimum-block address in z-scan order. | ||
| 359 | + /// | ||
| 360 | + /// Combines the tile-scan CTB order (high bits) with the within-CTB | ||
| 361 | + /// Morton / z interleave of the block's `( x, y )` low bits. The | ||
| 362 | + /// caller is responsible for keeping `( x, y )` within the picture's | ||
| 363 | + /// minimum-block grid. | ||
| 364 | + pub fn min_tb_addr_zs(&self, x: u32, y: u32) -> u32 { | ||
| 365 | + let shift = self.ctb_log2_size_y - self.min_tb_log2_size_y; | ||
| 366 | + let tb_x = (x << self.min_tb_log2_size_y) >> self.ctb_log2_size_y; | ||
| 367 | + let tb_y = (y << self.min_tb_log2_size_y) >> self.ctb_log2_size_y; | ||
| 368 | + let ctb_addr_rs = self.pic_width_in_ctbs_y * tb_y + tb_x; | ||
| 369 | + let mut addr = self.ctb_addr_rs_to_ts[ctb_addr_rs as usize] << (shift * 2); | ||
| 370 | + let mut p = 0u32; | ||
| 371 | + for i in 0..shift { | ||
| 372 | + let m = 1u32 << i; | ||
| 373 | + p += if m & x != 0 { m * m } else { 0 } + if m & y != 0 { 2 * m * m } else { 0 }; | ||
| 374 | + } | ||
| 375 | + addr += p; | ||
| 376 | + addr | ||
| 377 | + } | ||
| 378 | + | ||
| 379 | + /// §6.4.1 — derivation process for z-scan order block availability. | ||
| 380 | + /// | ||
| 381 | + /// Returns whether the neighbouring block covering luma location | ||
| 382 | + /// `( x_nb_y, y_nb_y )` is available for the current block whose | ||
| 383 | + /// top-left luma sample is `( x_curr, y_curr )`. | ||
| 384 | + /// | ||
| 385 | + /// `slice_addr_rs` maps a CTB raster-scan address to the | ||
| 386 | + /// `SliceAddrRs` of the slice segment that owns that CTB — the | ||
| 387 | + /// slice-boundary test of §6.4.1. The caller's slice-data walk | ||
| 388 | + /// builds it; for a single-slice picture it is the constant `0`. | ||
| 389 | + pub fn z_scan_availability<F>( | ||
| 390 | + &self, | ||
| 391 | + x_curr: u32, | ||
| 392 | + y_curr: u32, | ||
| 393 | + x_nb_y: i32, | ||
| 394 | + y_nb_y: i32, | ||
| 395 | + slice_addr_rs: F, | ||
| 396 | + ) -> bool | ||
| 397 | + where | ||
| 398 | + F: Fn(u32) -> u32, | ||
| 399 | + { | ||
| 400 | + // eq. 6-1. | ||
| 401 | + let min_block_addr_curr = self.min_tb_addr_zs( | ||
| 402 | + x_curr >> self.min_tb_log2_size_y, | ||
| 403 | + y_curr >> self.min_tb_log2_size_y, | ||
| 404 | + ); | ||
| 405 | + | ||
| 406 | + // eq. 6-2 — out-of-picture neighbours get minBlockAddrN = −1. | ||
| 407 | + if x_nb_y < 0 | ||
| 408 | + || y_nb_y < 0 | ||
| 409 | + || x_nb_y as u32 >= self.pic_width_in_luma_samples | ||
| 410 | + || y_nb_y as u32 >= self.pic_height_in_luma_samples | ||
| 411 | + { | ||
| 412 | + return false; | ||
| 413 | + } | ||
| 414 | + let x_nb_y = x_nb_y as u32; | ||
| 415 | + let y_nb_y = y_nb_y as u32; | ||
| 416 | + let min_block_addr_n = self.min_tb_addr_zs( | ||
| 417 | + x_nb_y >> self.min_tb_log2_size_y, | ||
| 418 | + y_nb_y >> self.min_tb_log2_size_y, | ||
| 419 | + ); | ||
| 420 | + | ||
| 421 | + // The neighbour must already be decoded (z-scan order test). | ||
| 422 | + if min_block_addr_n > min_block_addr_curr { | ||
| 423 | + return false; | ||
| 424 | + } | ||
| 425 | + | ||
| 426 | + // Slice-segment boundary: compare the SliceAddrRs of the CTBs | ||
| 427 | + // owning each block. The block addresses are in z-scan order; | ||
| 428 | + // map them back to the owning CTB raster address. | ||
| 429 | + let ctb_rs_curr = self.ctb_rs_of_z(min_block_addr_curr); | ||
| 430 | + let ctb_rs_n = self.ctb_rs_of_z(min_block_addr_n); | ||
| 431 | + if slice_addr_rs(ctb_rs_n) != slice_addr_rs(ctb_rs_curr) { | ||
| 432 | + return false; | ||
| 433 | + } | ||
| 434 | + | ||
| 435 | + // Tile boundary: the neighbour must be in the same tile. | ||
| 436 | + if self.tile_id_at_luma(x_nb_y, y_nb_y) != self.tile_id_at_luma(x_curr, y_curr) { | ||
| 437 | + return false; | ||
| 438 | + } | ||
| 439 | + | ||
| 440 | + true | ||
| 441 | + } | ||
| 442 | + | ||
| 443 | + /// §6.4.2 — derivation process for prediction block availability. | ||
| 444 | + /// | ||
| 445 | + /// Wraps [`Self::z_scan_availability`] with the `sameCb` short-cut | ||
| 446 | + /// (a neighbour in the *same* coding block is unavailable when it | ||
| 447 | + /// would not yet have been decoded under the §7.4.9 partitioning | ||
| 448 | + /// order) and the final `MODE_INTRA` masking. | ||
| 449 | + /// | ||
| 450 | + /// * `( x_cb, y_cb )` / `n_cb_s` — the current coding block. | ||
| 451 | + /// * `( x_pb, y_pb )` / `n_pb_w` / `n_pb_h` / `part_idx` — the | ||
| 452 | + /// current prediction block and its partition index. | ||
| 453 | + /// * `( x_nb_y, y_nb_y )` — the neighbour location. | ||
| 454 | + /// * `slice_addr_rs` — as in [`Self::z_scan_availability`]. | ||
| 455 | + /// * `cu_pred_mode` — maps a luma location to its `CuPredMode` | ||
| 456 | + /// (`MODE_INTRA` / `MODE_INTER` / `MODE_SKIP`). Only consulted for | ||
| 457 | + /// in-picture neighbours that are otherwise available. | ||
| 458 | + #[allow(clippy::too_many_arguments)] | ||
| 459 | + pub fn prediction_block_availability<S, M>( | ||
| 460 | + &self, | ||
| 461 | + x_cb: u32, | ||
| 462 | + y_cb: u32, | ||
| 463 | + n_cb_s: u32, | ||
| 464 | + x_pb: u32, | ||
| 465 | + y_pb: u32, | ||
| 466 | + n_pb_w: u32, | ||
| 467 | + n_pb_h: u32, | ||
| 468 | + part_idx: u32, | ||
| 469 | + x_nb_y: i32, | ||
| 470 | + y_nb_y: i32, | ||
| 471 | + slice_addr_rs: S, | ||
| 472 | + cu_pred_mode: M, | ||
| 473 | + ) -> bool | ||
| 474 | + where | ||
| 475 | + S: Fn(u32) -> u32, | ||
| 476 | + M: Fn(u32, u32) -> u8, | ||
| 477 | + { | ||
| 478 | + // sameCb: does the neighbour cover the current coding block? | ||
| 479 | + let same_cb = x_nb_y >= 0 | ||
| 480 | + && y_nb_y >= 0 | ||
| 481 | + && x_cb <= x_nb_y as u32 | ||
| 482 | + && y_cb <= y_nb_y as u32 | ||
| 483 | + && (x_cb + n_cb_s) > x_nb_y as u32 | ||
| 484 | + && (y_cb + n_cb_s) > y_nb_y as u32; | ||
| 485 | + | ||
| 486 | + let mut available_n = if !same_cb { | ||
| 487 | + self.z_scan_availability(x_pb, y_pb, x_nb_y, y_nb_y, slice_addr_rs) | ||
| 488 | + } else if (n_pb_w << 1) == n_cb_s | ||
| 489 | + && (n_pb_h << 1) == n_cb_s | ||
| 490 | + && part_idx == 1 | ||
| 491 | + && (y_cb + n_pb_h) <= y_nb_y as u32 | ||
| 492 | + && (x_cb + n_pb_w) > x_nb_y as u32 | ||
| 493 | + { | ||
| 494 | + // The Nx2N / 2NxN second partition cannot reference the not- | ||
| 495 | + // yet-decoded partition-0 region inside the same CU. | ||
| 496 | + false | ||
| 497 | + } else { | ||
| 498 | + true | ||
| 499 | + }; | ||
| 500 | + | ||
| 501 | + // Final §6.4.2 step: intra neighbours are unavailable for the | ||
| 502 | + // (inter) prediction-block availability query. | ||
| 503 | + if available_n { | ||
| 504 | + let x = x_nb_y as u32; | ||
| 505 | + let y = y_nb_y as u32; | ||
| 506 | + if cu_pred_mode(x, y) == MODE_INTRA { | ||
| 507 | + available_n = false; | ||
| 508 | + } | ||
| 509 | + } | ||
| 510 | + | ||
| 511 | + available_n | ||
| 512 | + } | ||
| 513 | + | ||
| 514 | + /// Map a minimum-block z-scan address back to the CTB raster-scan | ||
| 515 | + /// address that contains it. The high | ||
| 516 | + /// `( CtbLog2SizeY − MinTbLog2SizeY ) * 2` bits of a z-scan block | ||
| 517 | + /// address are the tile-scan CTB address (see eq. 6-10). | ||
| 518 | + fn ctb_rs_of_z(&self, min_block_addr_z: u32) -> u32 { | ||
| 519 | + let shift = (self.ctb_log2_size_y - self.min_tb_log2_size_y) * 2; | ||
| 520 | + let ctb_addr_ts = min_block_addr_z >> shift; | ||
| 521 | + self.ctb_addr_ts_to_rs[ctb_addr_ts as usize] | ||
| 522 | + } | ||
| 523 | +} | ||
| 524 | + | ||
| 525 | +/// §6.5.1 eqs. 6-3 / 6-4 — derive the per-tile sizes (`colWidth` / | ||
| 526 | +/// `rowHeight`) in CTBs, for one dimension. | ||
| 527 | +fn derive_tile_sizes( | ||
| 528 | + pic_size_in_ctbs: u32, | ||
| 529 | + num_tiles_minus1: u32, | ||
| 530 | + uniform_spacing_flag: bool, | ||
| 531 | + explicit_minus1: &[u32], | ||
| 532 | + array_field: &'static str, | ||
| 533 | + dimension: &'static str, | ||
| 534 | +) -> Result<Vec<u32>, AvailabilityError> { | ||
| 535 | + let num_tiles = (num_tiles_minus1 + 1) as usize; | ||
| 536 | + let mut sizes = vec![0u32; num_tiles]; | ||
| 537 | + if uniform_spacing_flag { | ||
| 538 | + for (i, slot) in sizes.iter_mut().enumerate() { | ||
| 539 | + let i = i as u32; | ||
| 540 | + *slot = ((i + 1) * pic_size_in_ctbs) / (num_tiles_minus1 + 1) | ||
| 541 | + - (i * pic_size_in_ctbs) / (num_tiles_minus1 + 1); | ||
| 542 | + } | ||
| 543 | + } else { | ||
| 544 | + if explicit_minus1.len() != num_tiles_minus1 as usize { | ||
| 545 | + return Err(AvailabilityError::TileArrayLength { | ||
| 546 | + field: array_field, | ||
| 547 | + expected: num_tiles_minus1 as usize, | ||
| 548 | + got: explicit_minus1.len(), | ||
| 549 | + }); | ||
| 550 | + } | ||
| 551 | + // The last tile takes the remainder; the first num_tiles_minus1 | ||
| 552 | + // are explicit. | ||
| 553 | + sizes[num_tiles - 1] = pic_size_in_ctbs; | ||
| 554 | + for i in 0..num_tiles_minus1 as usize { | ||
| 555 | + sizes[i] = explicit_minus1[i] + 1; | ||
| 556 | + if sizes[i] > sizes[num_tiles - 1] { | ||
| 557 | + return Err(AvailabilityError::TileOverflow { dimension }); | ||
| 558 | + } | ||
| 559 | + sizes[num_tiles - 1] -= sizes[i]; | ||
| 560 | + } | ||
| 561 | + if sizes[num_tiles - 1] == 0 { | ||
| 562 | + return Err(AvailabilityError::TileOverflow { dimension }); | ||
| 563 | + } | ||
| 564 | + } | ||
| 565 | + Ok(sizes) | ||
| 566 | +} | ||
| 567 | + | ||
| 568 | +#[cfg(test)] | ||
| 569 | +mod tests; | ||
| @@ -0,0 +1,315 @@ | |||
| 1 | +//! Tests for §6.4 availability + §6.5.1 / §6.5.2 scan conversions. | ||
| 2 | +//! | ||
| 3 | +//! Expected values are hand-derived from the ITU-T H.265 equations, not | ||
| 4 | +//! taken from any implementation. | ||
| 5 | + | ||
| 6 | +use super::*; | ||
| 7 | + | ||
| 8 | +/// Build the simplest single-tile geometry: `w`×`h` CTBs, CtbLog2 = 6 | ||
| 9 | +/// (64-sample CTBs), MinTbLog2 = 2 (4-sample minimum blocks). | ||
| 10 | +fn single_tile(w: u32, h: u32) -> PictureTiling { | ||
| 11 | + PictureTiling::new(w, h, w * 64, h * 64, 6, 2, &TilingParams::single_tile()).unwrap() | ||
| 12 | +} | ||
| 13 | + | ||
| 14 | +#[test] | ||
| 15 | +fn single_tile_rs_to_ts_is_identity() { | ||
| 16 | + let t = single_tile(3, 2); | ||
| 17 | + for rs in 0..6 { | ||
| 18 | + assert_eq!(t.ctb_addr_rs_to_ts(rs), rs, "rs->ts identity at {rs}"); | ||
| 19 | + assert_eq!(t.ctb_addr_ts_to_rs(rs), rs, "ts->rs identity at {rs}"); | ||
| 20 | + assert_eq!(t.tile_id(rs), 0, "single tile id at {rs}"); | ||
| 21 | + } | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +#[test] | ||
| 25 | +fn min_tb_addr_zs_within_one_ctb_is_morton() { | ||
| 26 | + // One 64-sample CTB = 16×16 4-sample min-blocks. shift = 4. | ||
| 27 | + // Within a single CTB (tile-scan addr 0), MinTbAddrZs is the pure | ||
| 28 | + // Morton interleave of the block (x, y) bits (eq. 6-10 with the | ||
| 29 | + // CtbAddrRsToTs term zero). | ||
| 30 | + let t = single_tile(1, 1); | ||
| 31 | + // (0,0) -> 0 | ||
| 32 | + assert_eq!(t.min_tb_addr_zs(0, 0), 0); | ||
| 33 | + // (1,0): x bit0 set -> p += 1*1 = 1 | ||
| 34 | + assert_eq!(t.min_tb_addr_zs(1, 0), 1); | ||
| 35 | + // (0,1): y bit0 set -> p += 2*1*1 = 2 | ||
| 36 | + assert_eq!(t.min_tb_addr_zs(0, 1), 2); | ||
| 37 | + // (1,1): 1 + 2 = 3 | ||
| 38 | + assert_eq!(t.min_tb_addr_zs(1, 1), 3); | ||
| 39 | + // (2,0): x bit1 (m=2) set -> p += 2*2 = 4 | ||
| 40 | + assert_eq!(t.min_tb_addr_zs(2, 0), 4); | ||
| 41 | + // (0,2): y bit1 set -> p += 2*2*2 = 8 | ||
| 42 | + assert_eq!(t.min_tb_addr_zs(0, 2), 8); | ||
| 43 | + // (3,3): x bits 0,1 -> 1 + 4 = 5; y bits 0,1 -> 2 + 8 = 10; sum 15 | ||
| 44 | + assert_eq!(t.min_tb_addr_zs(3, 3), 15); | ||
| 45 | + // (15,15): all four x bits -> 1+4+16+64 = 85; y doubles -> 170; 255 | ||
| 46 | + assert_eq!(t.min_tb_addr_zs(15, 15), 255); | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +#[test] | ||
| 50 | +fn min_tb_addr_zs_second_ctb_offsets_by_256() { | ||
| 51 | + // Two CTBs wide, single tile/slice. The min-block grid is 32 wide. | ||
| 52 | + // A block in the second CTB (x >= 16) sits at tile-scan CTB addr 1, | ||
| 53 | + // so its z-address starts at 1 << (shift*2) = 256. | ||
| 54 | + let t = single_tile(2, 1); | ||
| 55 | + assert_eq!(t.min_tb_addr_zs(16, 0), 256); | ||
| 56 | + assert_eq!(t.min_tb_addr_zs(17, 0), 257); | ||
| 57 | + // First CTB still occupies 0..255. | ||
| 58 | + assert_eq!(t.min_tb_addr_zs(15, 15), 255); | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +#[test] | ||
| 62 | +fn uniform_two_column_tiles_split_evenly() { | ||
| 63 | + // 4 CTBs wide, 1 tall, 2 uniform columns -> colWidth = [2, 2]. | ||
| 64 | + // colBd = [0, 2, 4]. CtbAddrRsToTs: tile 0 holds CTBs (0,1), tile 1 | ||
| 65 | + // holds (2,3); tile scan visits tile 0 fully then tile 1. | ||
| 66 | + let tiles = TilingParams { | ||
| 67 | + num_tile_columns_minus1: 1, | ||
| 68 | + num_tile_rows_minus1: 0, | ||
| 69 | + uniform_spacing_flag: true, | ||
| 70 | + column_width_minus1: vec![], | ||
| 71 | + row_height_minus1: vec![], | ||
| 72 | + }; | ||
| 73 | + let t = PictureTiling::new(4, 1, 256, 64, 6, 2, &tiles).unwrap(); | ||
| 74 | + // rs 0,1 (tile 0) -> ts 0,1; rs 2,3 (tile 1) -> ts 2,3 (here the | ||
| 75 | + // single row keeps tile-scan == raster for this layout). | ||
| 76 | + assert_eq!(t.ctb_addr_rs_to_ts(0), 0); | ||
| 77 | + assert_eq!(t.ctb_addr_rs_to_ts(1), 1); | ||
| 78 | + assert_eq!(t.ctb_addr_rs_to_ts(2), 2); | ||
| 79 | + assert_eq!(t.ctb_addr_rs_to_ts(3), 3); | ||
| 80 | + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(0)), 0); | ||
| 81 | + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(2)), 1); | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +#[test] | ||
| 85 | +fn uniform_two_by_two_tiles_reorder_tile_scan() { | ||
| 86 | + // 4×4 CTBs, 2×2 uniform tiles. colWidth = rowHeight = [2, 2]. | ||
| 87 | + // Tile scan visits tile (0,0)'s 4 CTBs, then (1,0), then (0,1), | ||
| 88 | + // then (1,1). So raster CTB 2 (top-right tile) maps to tile-scan 4. | ||
| 89 | + let tiles = TilingParams { | ||
| 90 | + num_tile_columns_minus1: 1, | ||
| 91 | + num_tile_rows_minus1: 1, | ||
| 92 | + uniform_spacing_flag: true, | ||
| 93 | + column_width_minus1: vec![], | ||
| 94 | + row_height_minus1: vec![], | ||
| 95 | + }; | ||
| 96 | + let t = PictureTiling::new(4, 4, 256, 256, 6, 2, &tiles).unwrap(); | ||
| 97 | + // Raster addr of CTB at (col=0,row=0) = 0 -> ts 0, tile 0. | ||
| 98 | + assert_eq!(t.ctb_addr_rs_to_ts(0), 0); | ||
| 99 | + assert_eq!(t.tile_id(0), 0); | ||
| 100 | + // CTB at (col=2,row=0) raster = 2; it is tile (1,0) = tile idx 1, | ||
| 101 | + // first CTB after tile 0's 4 -> ts 4. | ||
| 102 | + assert_eq!(t.ctb_addr_rs_to_ts(2), 4); | ||
| 103 | + assert_eq!(t.tile_id(4), 1); | ||
| 104 | + // CTB at (col=0,row=2) raster = 8; tile (0,1) = tile idx 2 -> ts 8. | ||
| 105 | + assert_eq!(t.ctb_addr_rs_to_ts(8), 8); | ||
| 106 | + assert_eq!(t.tile_id(8), 2); | ||
| 107 | + // CTB at (col=2,row=2) raster = 10; tile (1,1) = tile idx 3 -> ts 12. | ||
| 108 | + assert_eq!(t.ctb_addr_rs_to_ts(10), 12); | ||
| 109 | + assert_eq!(t.tile_id(12), 3); | ||
| 110 | + // ts->rs is the inverse permutation. | ||
| 111 | + for rs in 0..16 { | ||
| 112 | + assert_eq!(t.ctb_addr_ts_to_rs(t.ctb_addr_rs_to_ts(rs)), rs); | ||
| 113 | + } | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +#[test] | ||
| 117 | +fn explicit_tile_widths() { | ||
| 118 | + // 5 CTBs wide, 1 tall, 2 columns, column_width_minus1[0] = 0 | ||
| 119 | + // -> colWidth = [1, 4]. | ||
| 120 | + let tiles = TilingParams { | ||
| 121 | + num_tile_columns_minus1: 1, | ||
| 122 | + num_tile_rows_minus1: 0, | ||
| 123 | + uniform_spacing_flag: false, | ||
| 124 | + column_width_minus1: vec![0], | ||
| 125 | + row_height_minus1: vec![], | ||
| 126 | + }; | ||
| 127 | + let t = PictureTiling::new(5, 1, 320, 64, 6, 2, &tiles).unwrap(); | ||
| 128 | + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(0)), 0); // first CTB, tile 0 | ||
| 129 | + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(1)), 1); // rest, tile 1 | ||
| 130 | + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(4)), 1); | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +#[test] | ||
| 134 | +fn explicit_tile_overflow_rejected() { | ||
| 135 | + // column_width_minus1[0] = 5 implies first tile is 6 CTBs wide in a | ||
| 136 | + // 5-CTB-wide picture -> overflow. | ||
| 137 | + let tiles = TilingParams { | ||
| 138 | + num_tile_columns_minus1: 1, | ||
| 139 | + num_tile_rows_minus1: 0, | ||
| 140 | + uniform_spacing_flag: false, | ||
| 141 | + column_width_minus1: vec![5], | ||
| 142 | + row_height_minus1: vec![], | ||
| 143 | + }; | ||
| 144 | + assert!(matches!( | ||
| 145 | + PictureTiling::new(5, 1, 320, 64, 6, 2, &tiles), | ||
| 146 | + Err(AvailabilityError::TileOverflow { | ||
| 147 | + dimension: "column" | ||
| 148 | + }) | ||
| 149 | + )); | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +#[test] | ||
| 153 | +fn explicit_array_length_mismatch_rejected() { | ||
| 154 | + let tiles = TilingParams { | ||
| 155 | + num_tile_columns_minus1: 2, // expects 2 entries | ||
| 156 | + num_tile_rows_minus1: 0, | ||
| 157 | + uniform_spacing_flag: false, | ||
| 158 | + column_width_minus1: vec![0], // only 1 supplied | ||
| 159 | + row_height_minus1: vec![], | ||
| 160 | + }; | ||
| 161 | + assert!(matches!( | ||
| 162 | + PictureTiling::new(6, 1, 384, 64, 6, 2, &tiles), | ||
| 163 | + Err(AvailabilityError::TileArrayLength { .. }) | ||
| 164 | + )); | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +#[test] | ||
| 168 | +fn invalid_log2_sizes_rejected() { | ||
| 169 | + // CtbLog2 < MinTbLog2. | ||
| 170 | + assert!(matches!( | ||
| 171 | + PictureTiling::new(1, 1, 64, 64, 2, 4, &TilingParams::single_tile()), | ||
| 172 | + Err(AvailabilityError::InvalidLog2Sizes { .. }) | ||
| 173 | + )); | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +#[test] | ||
| 177 | +fn zero_geometry_rejected() { | ||
| 178 | + assert!(matches!( | ||
| 179 | + PictureTiling::new(0, 1, 0, 64, 6, 2, &TilingParams::single_tile()), | ||
| 180 | + Err(AvailabilityError::ZeroGeometry { | ||
| 181 | + field: "PicWidthInCtbsY" | ||
| 182 | + }) | ||
| 183 | + )); | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +// ---- §6.4.1 z-scan availability ---- | ||
| 187 | + | ||
| 188 | +#[test] | ||
| 189 | +fn neighbour_outside_picture_is_unavailable() { | ||
| 190 | + let t = single_tile(2, 2); | ||
| 191 | + let same_slice = |_rs: u32| 0u32; | ||
| 192 | + // Current block at (64, 64). Left neighbour at x = -1 -> out. | ||
| 193 | + assert!(!t.z_scan_availability(64, 64, -1, 64, same_slice)); | ||
| 194 | + // Top neighbour at y = -1 -> out. | ||
| 195 | + assert!(!t.z_scan_availability(64, 64, 64, -1, same_slice)); | ||
| 196 | + // Right of picture (picture is 128 wide). | ||
| 197 | + assert!(!t.z_scan_availability(64, 64, 128, 64, same_slice)); | ||
| 198 | + // Below picture (128 tall). | ||
| 199 | + assert!(!t.z_scan_availability(64, 64, 64, 128, same_slice)); | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +#[test] | ||
| 203 | +fn already_decoded_left_and_above_are_available() { | ||
| 204 | + // 2×2 CTBs, single slice/tile. Current block top-left at (64, 64) | ||
| 205 | + // (the bottom-right CTB, decoded last in raster order). Its left | ||
| 206 | + // (63, 64) and above (64, 63) neighbours decode earlier -> available. | ||
| 207 | + let t = single_tile(2, 2); | ||
| 208 | + let same_slice = |_rs: u32| 0u32; | ||
| 209 | + assert!(t.z_scan_availability(64, 64, 63, 64, same_slice)); // left | ||
| 210 | + assert!(t.z_scan_availability(64, 64, 64, 63, same_slice)); // above | ||
| 211 | + assert!(t.z_scan_availability(64, 64, 63, 63, same_slice)); // above-left | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +#[test] | ||
| 215 | +fn not_yet_decoded_neighbour_is_unavailable() { | ||
| 216 | + // Current at the top-left CTB (0,0). The below-right neighbour at | ||
| 217 | + // (64, 64) decodes later -> minBlockAddrN > minBlockAddrCurr -> | ||
| 218 | + // unavailable even though it is inside the picture. | ||
| 219 | + let t = single_tile(2, 2); | ||
| 220 | + let same_slice = |_rs: u32| 0u32; | ||
| 221 | + assert!(!t.z_scan_availability(0, 0, 64, 64, same_slice)); | ||
| 222 | + // The above-right of the bottom-left CTB: current (0,64), | ||
| 223 | + // neighbour (64, 63) is in the top-right CTB which decodes before | ||
| 224 | + // the bottom-left CTB in raster order -> available. | ||
| 225 | + assert!(t.z_scan_availability(0, 64, 64, 63, same_slice)); | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +#[test] | ||
| 229 | +fn different_slice_is_unavailable() { | ||
| 230 | + // 2×2 CTBs. Put the second slice starting at raster CTB 3 (the | ||
| 231 | + // bottom-right). Current block in CTB 3, left neighbour in CTB 2. | ||
| 232 | + let t = single_tile(2, 2); | ||
| 233 | + let slice_of = |rs: u32| if rs >= 3 { 1u32 } else { 0u32 }; | ||
| 234 | + // current (64,64) is CTB 3 (slice 1); left (63,64) is CTB 2 (slice 0) | ||
| 235 | + assert!(!t.z_scan_availability(64, 64, 63, 64, slice_of)); | ||
| 236 | + // within-slice neighbour: above (64,63) is CTB 1 (slice 0) too, but | ||
| 237 | + // it differs from current's slice 1 -> still unavailable. | ||
| 238 | + assert!(!t.z_scan_availability(64, 64, 64, 63, slice_of)); | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +#[test] | ||
| 242 | +fn different_tile_is_unavailable() { | ||
| 243 | + // 2 columns × 1 row of tiles over 2×1 CTBs: each CTB is its own | ||
| 244 | + // tile. Current block in the right CTB, left neighbour in the left | ||
| 245 | + // CTB -> different tile -> unavailable even within one slice. | ||
| 246 | + let tiles = TilingParams { | ||
| 247 | + num_tile_columns_minus1: 1, | ||
| 248 | + num_tile_rows_minus1: 0, | ||
| 249 | + uniform_spacing_flag: true, | ||
| 250 | + column_width_minus1: vec![], | ||
| 251 | + row_height_minus1: vec![], | ||
| 252 | + }; | ||
| 253 | + let t = PictureTiling::new(2, 1, 128, 64, 6, 2, &tiles).unwrap(); | ||
| 254 | + let same_slice = |_rs: u32| 0u32; | ||
| 255 | + // current (64,0) right tile; left (63,0) left tile. | ||
| 256 | + assert!(!t.z_scan_availability(64, 0, 63, 0, same_slice)); | ||
| 257 | + // within the same (right) tile a left neighbour is available. | ||
| 258 | + assert!(t.z_scan_availability(127, 0, 126, 0, same_slice)); | ||
| 259 | +} | ||
| 260 | + | ||
| 261 | +// ---- §6.4.2 prediction block availability ---- | ||
| 262 | + | ||
| 263 | +#[test] | ||
| 264 | +fn prediction_block_intra_neighbour_masked_out() { | ||
| 265 | + // 2×2 CTBs single slice/tile. Current PB top-left (64,64). Left | ||
| 266 | + // neighbour (63,64) would be z-scan available, but its CuPredMode | ||
| 267 | + // is MODE_INTRA -> masked to unavailable for the inter query. | ||
| 268 | + let t = single_tile(2, 2); | ||
| 269 | + let same_slice = |_rs: u32| 0u32; | ||
| 270 | + let all_intra = |_x: u32, _y: u32| MODE_INTRA; | ||
| 271 | + let all_inter = |_x: u32, _y: u32| 0u8; // MODE_INTER | ||
| 272 | + // 64×64 CU == one 64×64 PB (2Nx2N), partIdx 0. | ||
| 273 | + assert!(!t.prediction_block_availability( | ||
| 274 | + 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_intra, | ||
| 275 | + )); | ||
| 276 | + assert!(t.prediction_block_availability( | ||
| 277 | + 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_inter, | ||
| 278 | + )); | ||
| 279 | +} | ||
| 280 | + | ||
| 281 | +#[test] | ||
| 282 | +fn prediction_block_second_partition_cannot_see_first() { | ||
| 283 | + // The §6.4.2 same-CB forced-FALSE branch fires only for the NxN | ||
| 284 | + // partitioning ((nPbW << 1) == nCbS AND (nPbH << 1) == nCbS): a | ||
| 285 | + // 64×64 CU split into four 32×32 PBs. The top-right PB (partIdx 1, | ||
| 286 | + // top-left (32, 0)) must not reference the bottom-left PB region | ||
| 287 | + // (yNbY >= yCb + nPbH = 32, xNbY < xCb + nPbW = 32), which the | ||
| 288 | + // §7.4.9 partitioning order has not decoded yet. | ||
| 289 | + let t = single_tile(2, 2); | ||
| 290 | + let same_slice = |_rs: u32| 0u32; | ||
| 291 | + let all_inter = |_x: u32, _y: u32| 0u8; | ||
| 292 | + // CU (0,0) size 64; PB1 (32,0) 32×32, partIdx 1. Neighbour (31, 32) | ||
| 293 | + // is the bottom-left PB region — same CB, the forced-FALSE branch. | ||
| 294 | + assert!(!t | ||
| 295 | + .prediction_block_availability(0, 0, 64, 32, 0, 32, 32, 1, 31, 32, same_slice, all_inter,)); | ||
| 296 | + // The bottom-right region (xNbY >= 32) is NOT forced false by this | ||
| 297 | + // branch (it sits at xNbY = 32, failing xCb+nPbW > xNbY); it falls | ||
| 298 | + // through to availableN = TRUE since it is the same CB. | ||
| 299 | + assert!( | ||
| 300 | + t.prediction_block_availability(0, 0, 64, 32, 0, 32, 32, 1, 32, 32, same_slice, all_inter,) | ||
| 301 | + ); | ||
| 302 | +} | ||
| 303 | + | ||
| 304 | +#[test] | ||
| 305 | +fn prediction_block_normal_left_neighbour_available() { | ||
| 306 | + // Same-CB short-cut not triggered (neighbour outside the CU): a | ||
| 307 | + // normal left neighbour of an inter 2Nx2N PB resolves through | ||
| 308 | + // §6.4.1 and is available. | ||
| 309 | + let t = single_tile(2, 2); | ||
| 310 | + let same_slice = |_rs: u32| 0u32; | ||
| 311 | + let all_inter = |_x: u32, _y: u32| 0u8; | ||
| 312 | + assert!(t.prediction_block_availability( | ||
| 313 | + 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_inter, | ||
| 314 | + )); | ||
| 315 | +} | ||
Diff too large; view file
| @@ -0,0 +1,8000 @@ | |||
| 1 | +//! §9.3.4.2 per-syntax-element binarization + context-index derivation. | ||
| 2 | +//! | ||
| 3 | +//! Sits one layer above the §9.3 arithmetic decoding engine | ||
| 4 | +//! ([`crate::cabac::CabacEngine`]). For each entropy-coded syntax | ||
| 5 | +//! element this module supplies the §9.3.3 binarization shape (truncated | ||
| 6 | +//! rice, fixed length, Exp-Golomb of order *k*, …) plus the §9.3.4.2.X | ||
| 7 | +//! per-bin `ctxInc` derivation, returning a context-index into the | ||
| 8 | +//! per-slice context-model array. | ||
| 9 | +//! | ||
| 10 | +//! Round 26 ships the two syntax elements unblocked by the clean-room | ||
| 11 | +//! CABAC trace `docs/video/h265/fixtures/main-422-10bit/cabac-cu-qp-delta-last-sig-trace.md`: | ||
| 12 | +//! | ||
| 13 | +//! * **`cu_qp_delta_abs` / `cu_qp_delta_sign_flag`** (H.265 §7.3.8.14, | ||
| 14 | +//! §7.4.9.14). Binarization: §9.3.3.10 TR prefix (`cMax = 5`, | ||
| 15 | +//! `cRiceParam = 0`) followed, when the prefix is the all-ones escape | ||
| 16 | +//! (`prefixVal == 5`), by an EGk suffix with `k = 0` (§9.3.3.11). The | ||
| 17 | +//! per-bin `ctxInc` (§9.3.4.2.2, Table 9-32): bin 0 uses `ctxInc = 0`, | ||
| 18 | +//! bins 1..=4 share `ctxInc = 1`. The sign flag is bypass-coded. | ||
| 19 | +//! `CuQpDeltaVal = cu_qp_delta_abs * (1 − 2 * cu_qp_delta_sign_flag)`. | ||
| 20 | +//! | ||
| 21 | +//! * **`last_sig_coeff_{x,y}_prefix`** (H.265 §7.3.8.11, §7.4.9.11). | ||
| 22 | +//! Binarization: §9.3.3.10 TR prefix with | ||
| 23 | +//! `cMax = (log2TrafoSize << 1) − 1` and `cRiceParam = 0`. The per-bin | ||
| 24 | +//! `ctxInc` (§9.3.4.2.3) is | ||
| 25 | +//! `ctxInc = (binIdx >> ctxShift) + ctxOffset`. For luma: | ||
| 26 | +//! `ctxOffset = 3 * (log2TrafoSize − 2) + ((log2TrafoSize − 1) >> 2)`, | ||
| 27 | +//! `ctxShift = (log2TrafoSize + 1) >> 2`. For chroma (cIdx > 0): | ||
| 28 | +//! `ctxOffset = 15`, `ctxShift = log2TrafoSize − 2`. The X and Y | ||
| 29 | +//! prefix bins live in separate context banks; this module hands back | ||
| 30 | +//! only the bank-relative `ctxInc` and the matching | ||
| 31 | +//! [`LastSigCoeffBank`] tag for caller-side routing. | ||
| 32 | +//! | ||
| 33 | +//! * **`last_sig_coeff_{x,y}_suffix`** (H.265 §7.3.8.11, §7.4.9.11). A | ||
| 34 | +//! `nBits = (prefix >> 1) − 1`-bit fixed-length bypass field, present | ||
| 35 | +//! only when `prefix > 3`. Together with the prefix the final | ||
| 36 | +//! `LastSignificantCoeffX` / `Y` position is derived per equations | ||
| 37 | +//! 7-74..7-77. | ||
| 38 | +//! | ||
| 39 | +//! Both elements live downstream of the §9.3.4.2 binarization layer | ||
| 40 | +//! that the slice-data parser (§7.3.8) drives; this module is the | ||
| 41 | +//! reusable per-element building block. | ||
| 42 | +//! | ||
| 43 | +//! Round 27 extends the ctxInc-derivation surface with three more | ||
| 44 | +//! syntax elements that are pure-functional given their neighbour / | ||
| 45 | +//! sub-block context (no CABAC engine drive needed at this layer — | ||
| 46 | +//! callers compose the engine call themselves): | ||
| 47 | +//! | ||
| 48 | +//! * **`coded_sub_block_flag`** (H.265 §7.3.8.11, §7.4.9.11) — the | ||
| 49 | +//! §9.3.4.2.4 derivation of `ctxInc` from the colour-component | ||
| 50 | +//! index, the current sub-block scan location `(xS, yS)`, the | ||
| 51 | +//! transform-block size, and the previously decoded | ||
| 52 | +//! `coded_sub_block_flag[xS+1][yS]` / `coded_sub_block_flag[xS][yS+1]` | ||
| 53 | +//! neighbours. Implemented in | ||
| 54 | +//! [`coded_sub_block_flag_ctx_inc`] following equations 9-35..9-39. | ||
| 55 | +//! | ||
| 56 | +//! * **`split_cu_flag` / `cu_skip_flag`** (H.265 §7.3.8.4, §7.4.9.4, | ||
| 57 | +//! §7.3.8.5, §7.4.9.5) — the §9.3.4.2.2 Table 9-49 derivation of | ||
| 58 | +//! `ctxInc` from the left and above neighbours' `condL` / `condA` | ||
| 59 | +//! booleans plus their availability: | ||
| 60 | +//! `ctxInc = (condL && availableL) + (condA && availableA)`. | ||
| 61 | +//! Implemented as the shared | ||
| 62 | +//! [`left_above_ctx_inc`] helper (the body of Table 9-49) plus | ||
| 63 | +//! the [`split_cu_flag_cond`] and [`cu_skip_flag_cond`] callbacks | ||
| 64 | +//! the caller wires into it. The Table 9-49 row for | ||
| 65 | +//! `split_cu_flag` compares each neighbour's `CtDepth[xNb][yNb]` | ||
| 66 | +//! to the current `cqtDepth`; the row for `cu_skip_flag` reads | ||
| 67 | +//! each neighbour's `cu_skip_flag[xNb][yNb]` directly. Both rows | ||
| 68 | +//! produce a `ctxInc` in `{0, 1, 2}`. | ||
| 69 | +//! | ||
| 70 | +//! Round 28 extends the ctxInc-derivation surface with six more | ||
| 71 | +//! syntax elements whose Table 9-48 entry is itself a closed-form | ||
| 72 | +//! expression on parameters the caller already has in hand (no | ||
| 73 | +//! neighbour table walk, no CABAC engine drive at this layer): | ||
| 74 | +//! | ||
| 75 | +//! * **`split_transform_flag[ ][ ][ ]`** (H.265 §7.3.8.10, §7.4.9.10) | ||
| 76 | +//! — Table 9-48 row: `ctxInc = 5 − log2TrafoSize`. Valid | ||
| 77 | +//! `log2TrafoSize ∈ {2, 3, 4, 5}` for the residual-quadtree | ||
| 78 | +//! transform-block sizes, so `ctxInc ∈ {0, 1, 2, 3}`. Implemented | ||
| 79 | +//! in [`split_transform_flag_ctx_inc`]. | ||
| 80 | +//! | ||
| 81 | +//! * **`cbf_luma[ ][ ][ ]`** (H.265 §7.3.8.10, §7.4.9.10) — Table | ||
| 82 | +//! 9-48 row: `ctxInc = (trafoDepth == 0) ? 1 : 0`. Implemented in | ||
| 83 | +//! [`cbf_luma_ctx_inc`]. | ||
| 84 | +//! | ||
| 85 | +//! * **`cbf_cb[ ][ ][ ]` / `cbf_cr[ ][ ][ ]`** (H.265 §7.3.8.10, | ||
| 86 | +//! §7.4.9.10) — Table 9-48 row: `ctxInc = trafoDepth`. The two | ||
| 87 | +//! syntax elements live in separate context banks (Table 9-22 | ||
| 88 | +//! shares the bank shape but each chroma component has its own | ||
| 89 | +//! `ctxIdxOffset`); this layer hands back the bank-relative | ||
| 90 | +//! `ctxInc` only. Implemented in [`cbf_cb_ctx_inc`] and | ||
| 91 | +//! [`cbf_cr_ctx_inc`] (each is a wafer over the shared | ||
| 92 | +//! [`cbf_chroma_ctx_inc`] helper). | ||
| 93 | +//! | ||
| 94 | +//! * **`inter_pred_idc[ x0 ][ y0 ]`** (H.265 §7.3.8.6, §7.4.9.6) — | ||
| 95 | +//! Table 9-48 row: bin 0 uses | ||
| 96 | +//! `ctxInc = (nPbW + nPbH != 12) ? CtDepth[x0][y0] : 4`; bin 1 | ||
| 97 | +//! uses `ctxInc = 4`. The `nPbW + nPbH == 12` condition picks out | ||
| 98 | +//! the prediction-block shapes whose luma area is 16 samples | ||
| 99 | +//! (8×4 and 4×8 PUs), which are encoded with the bin-0 escape | ||
| 100 | +//! onto the bin-1 context bank. Implemented in | ||
| 101 | +//! [`inter_pred_idc_ctx_inc`]. | ||
| 102 | +//! | ||
| 103 | +//! * **`log2_res_scale_abs_plus1[ c ]`** (H.265 §7.3.8.13, | ||
| 104 | +//! §7.4.9.13) — Table 9-48 row: `ctxInc = 4*c + binIdx` for | ||
| 105 | +//! `binIdx ∈ {0, 1, 2, 3}` and `c ∈ {0, 1}` (Cb / Cr). The four | ||
| 106 | +//! bins of the TR(`cMax = 4`) prefix occupy four consecutive | ||
| 107 | +//! contexts per chroma component, so the per-component banks are | ||
| 108 | +//! `{0, 1, 2, 3}` (Cb) and `{4, 5, 6, 7}` (Cr). Implemented in | ||
| 109 | +//! [`log2_res_scale_abs_plus1_ctx_inc`]. | ||
| 110 | +//! | ||
| 111 | +//! * **`res_scale_sign_flag[ c ]`** (H.265 §7.3.8.13, §7.4.9.13) — | ||
| 112 | +//! Table 9-48 row: `ctxInc = c` for `c ∈ {0, 1}`. One bit per | ||
| 113 | +//! chroma component, each on its own context. Implemented in | ||
| 114 | +//! [`res_scale_sign_flag_ctx_inc`]. | ||
| 115 | +//! | ||
| 116 | +//! All round-28 entries are bin-0 (and bin-1 for `inter_pred_idc` / | ||
| 117 | +//! `log2_res_scale_abs_plus1`) ctxInc derivations only; the matching | ||
| 118 | +//! binarization shapes (FL for the flags, TR(`cMax = 4`) for | ||
| 119 | +//! `log2_res_scale_abs_plus1` followed by a bypass tail) are driven | ||
| 120 | +//! by the slice-data parser the same way as the round-26 / 27 | ||
| 121 | +//! elements. | ||
| 122 | +//! | ||
| 123 | +//! Round 30 extends the surface with the §7.3.4 `sao()` per-CTU | ||
| 124 | +//! syntax-element family. Every element has either a single | ||
| 125 | +//! context-coded bin-0 followed by zero or more bypass-coded bins | ||
| 126 | +//! (Table 9-48) or is fully bypass-coded; no neighbour walk is | ||
| 127 | +//! needed at this layer. | ||
| 128 | +//! | ||
| 129 | +//! * **`sao_merge_left_flag` / `sao_merge_up_flag`** (H.265 §7.3.4, | ||
| 130 | +//! §7.4.9.3) — Table 9-48 row: bin 0 `ctxInc = 0`. The FL | ||
| 131 | +//! binarization has `cMax = 1` (single bin). The two merge flags | ||
| 132 | +//! share the Table 9-5 context bank (Table 9-4). Implemented in | ||
| 133 | +//! [`sao_merge_flag_ctx_inc`] + [`SAO_MERGE_FLAG_FL_CMAX`]. | ||
| 134 | +//! | ||
| 135 | +//! * **`sao_type_idx_luma` / `sao_type_idx_chroma`** (H.265 §7.3.4, | ||
| 136 | +//! §7.4.9.3) — Table 9-48 row: bin 0 `ctxInc = 0`, bin 1 bypass. | ||
| 137 | +//! The TR(`cMax = 2`, `cRiceParam = 0`) binarization caps the | ||
| 138 | +//! prefix at two bins, encoding `SaoTypeIdx ∈ {0, 1, 2}`. The two | ||
| 139 | +//! variants share the Table 9-6 context bank. Implemented in | ||
| 140 | +//! [`sao_type_idx_ctx_inc`] + [`SAO_TYPE_IDX_TR_CMAX`]. | ||
| 141 | +//! | ||
| 142 | +//! * **`sao_offset_abs`** (H.265 §7.3.4, §7.4.9.3) — Table 9-48 row: | ||
| 143 | +//! all bins bypass. TR(`cMax = (1 << min(bitDepth, 10) − 5) − 1`, | ||
| 144 | +//! `cRiceParam = 0`). Implemented in [`sao_offset_abs_tr_cmax`]. | ||
| 145 | +//! | ||
| 146 | +//! * **`sao_offset_sign`**, **`sao_band_position`**, | ||
| 147 | +//! **`sao_eo_class_luma` / `sao_eo_class_chroma`** (H.265 §7.3.4, | ||
| 148 | +//! §7.4.9.3) — Table 9-48 row: all bins bypass; FL binarizations | ||
| 149 | +//! with `cMax = 1`, `cMax = 31`, `cMax = 3` respectively. | ||
| 150 | +//! Implemented as [`SAO_OFFSET_SIGN_FL_CMAX`], | ||
| 151 | +//! [`SAO_BAND_POSITION_FL_CMAX`] + [`SAO_BAND_POSITION_FL_NBITS`], | ||
| 152 | +//! and [`SAO_EO_CLASS_FL_CMAX`] + [`SAO_EO_CLASS_FL_NBITS`]. | ||
| 153 | +//! | ||
| 154 | +//! Round 31 extends the surface with the two §9.3.4.2.6 / | ||
| 155 | +//! §9.3.4.2.7 derivations whose `ctxInc` carries *persistent* | ||
| 156 | +//! per-transform-block state across sub-block invocations: the | ||
| 157 | +//! greater-than-1 / greater-than-2 absolute-level flags. Both | ||
| 158 | +//! elements are FL binarized with `cMax = 1` (one context-coded | ||
| 159 | +//! bin) per Table 9-43, but the bin's ctxInc is driven by a small | ||
| 160 | +//! sub-block-scoped state machine (`ctxSet`, `greater1Ctx`, | ||
| 161 | +//! `lastGreater1Ctx`, `lastGreater1Flag`) that the residual-coding | ||
| 162 | +//! loop threads from sub-block to sub-block within the same | ||
| 163 | +//! transform block. | ||
| 164 | +//! | ||
| 165 | +//! * **`coeff_abs_level_greater1_flag[ n ]`** (H.265 §7.3.8.11, | ||
| 166 | +//! §7.4.9.11) — §9.3.4.2.6, equations 9-56..9-60. The per-bin | ||
| 167 | +//! `ctxInc = (ctxSet * 4) + min(3, greater1Ctx)` for luma; chroma | ||
| 168 | +//! adds `+16`. `ctxSet` is initialised at the start of each | ||
| 169 | +//! sub-block from the previous sub-block's terminal `greater1Ctx` | ||
| 170 | +//! value, and rotates within `{0, 1, 2, 3}` per the spec's | ||
| 171 | +//! `lastGreater1Ctx == 0` increment rule. Implemented as a | ||
| 172 | +//! pure-functional state machine in [`Greater1State`] (the | ||
| 173 | +//! walker the slice-data parser carries across the residual | ||
| 174 | +//! sub-blocks of one transform block) plus the per-flag step | ||
| 175 | +//! functions [`Greater1State::on_subblock_entry`] + | ||
| 176 | +//! [`Greater1State::on_coeff_abs_level_greater1_flag`]. | ||
| 177 | +//! | ||
| 178 | +//! * **`coeff_abs_level_greater2_flag[ lastGreater1ScanPos ]`** | ||
| 179 | +//! (H.265 §7.3.8.11, §7.4.9.11) — §9.3.4.2.7, equations | ||
| 180 | +//! 9-61..9-62. `ctxInc = ctxSet` (luma) / `ctxInc = ctxSet + 4` | ||
| 181 | +//! (chroma). The element is signalled at most once per sub-block | ||
| 182 | +//! at the first scan position that took the greater-1 escape | ||
| 183 | +//! (`lastGreater1ScanPos`). Implemented in | ||
| 184 | +//! [`coeff_abs_level_greater2_flag_ctx_inc`], reading the | ||
| 185 | +//! `ctxSet` value the §9.3.4.2.6 walker has already produced for | ||
| 186 | +//! that same sub-block. | ||
| 187 | +//! | ||
| 188 | +//! Round 32 extends the residual-coding surface with the | ||
| 189 | +//! §9.3.4.2.5 `sig_coeff_flag` ctxInc derivation: the per-scan-position | ||
| 190 | +//! significance bin that the §7.3.8.11 residual-coding loop emits | ||
| 191 | +//! before any greater-1 / greater-2 step. The derivation is a | ||
| 192 | +//! four-branch dispatch on `(log2TrafoSize, xC + yC, | ||
| 193 | +//! transform_skip_context_enabled_flag && (transform_skip_flag || | ||
| 194 | +//! cu_transquant_bypass_flag))`: | ||
| 195 | +//! | ||
| 196 | +//! * **transform-skip / transquant-bypass fast path** (eq. 9-40): | ||
| 197 | +//! `sigCtx = 42` (luma) / `sigCtx = 16` (chroma). One context | ||
| 198 | +//! per colour component, position-independent. Implemented in | ||
| 199 | +//! [`sig_coeff_flag_sig_ctx_transform_skip`]. | ||
| 200 | +//! | ||
| 201 | +//! * **`log2TrafoSize == 2`** (eq. 9-41) — the 4×4 TB case reads | ||
| 202 | +//! `sigCtx` from the 16-entry Table 9-50 lookup at | ||
| 203 | +//! `(yC << 2) + xC`. Implemented in | ||
| 204 | +//! [`sig_coeff_flag_sig_ctx_log2_2`] + | ||
| 205 | +//! [`SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2`]. | ||
| 206 | +//! | ||
| 207 | +//! * **DC position** (eq. 9-42) — `xC + yC == 0` on `log2 > 2` skips | ||
| 208 | +//! the eq.-9-43..9-48 neighbour walk; `sigCtx` starts at 0 and | ||
| 209 | +//! only the colour / size tail (eq.-9-49..9-53) applies. | ||
| 210 | +//! Implemented in [`sig_coeff_flag_sig_ctx_dc`]. | ||
| 211 | +//! | ||
| 212 | +//! * **general case** (eq. 9-43..9-53) — for `log2 > 2`, `xC + | ||
| 213 | +//! yC > 0` the `prevCsbf` parity of the right / below sub-block | ||
| 214 | +//! neighbours plus the inner sub-block position `(xC & 3, yC & 3)` | ||
| 215 | +//! route through one of four `sigCtx` rules (eq. 9-45..9-48), then | ||
| 216 | +//! the colour / size / scan-order tail (eq. 9-49..9-53). Implemented | ||
| 217 | +//! in [`sig_coeff_flag_sig_ctx_general`], with the eq.-9-43 / 9-44 | ||
| 218 | +//! edge gates on `xS / yS < (1 << (log2TrafoSize − 2)) − 1` | ||
| 219 | +//! applied internally. | ||
| 220 | +//! | ||
| 221 | +//! Eq. 9-54 / 9-55 carry the per-component `ctxInc` offset | ||
| 222 | +//! (`ctxInc = sigCtx` for luma, `ctxInc = 27 + sigCtx` for chroma); | ||
| 223 | +//! see [`sig_coeff_flag_ctx_inc_from_sig_ctx`]. Table 9-43 captures | ||
| 224 | +//! the `sig_coeff_flag` binarization shape as FL with `cMax = 1` via | ||
| 225 | +//! [`SIG_COEFF_FLAG_FL_CMAX`]. | ||
| 226 | +//! | ||
| 227 | +//! Round 33 extends the ctxInc-derivation surface with the | ||
| 228 | +//! §9.3.4.2.8 `palette_run_prefix` derivation — the §7.3.8.13 | ||
| 229 | +//! palette-coding (SCC) syntax element that signals the unary part | ||
| 230 | +//! of the run length following a palette index or copy-above | ||
| 231 | +//! decision. Inputs are the bin index `binIdx`, the per-pixel | ||
| 232 | +//! `copy_above_palette_indices_flag`, and the `palette_idx_idc` | ||
| 233 | +//! decoded at the start of the run. The `ctxInc` is: | ||
| 234 | +//! | ||
| 235 | +//! * **`copy_above_palette_indices_flag == 0` and `binIdx == 0`** | ||
| 236 | +//! (eq. 9-63) — a piecewise function of `palette_idx_idc` in | ||
| 237 | +//! `{0, 1, 2}`: | ||
| 238 | +//! `ctxInc = (palette_idx_idc < 1) ? 0 : ((palette_idx_idc < 3) | ||
| 239 | +//! ? 1 : 2)`. Implemented in | ||
| 240 | +//! [`palette_run_prefix_ctx_inc_eq_9_63`]. | ||
| 241 | +//! | ||
| 242 | +//! * **otherwise** — `ctxInc = ctxIdxMap[copy_above_palette_indices_flag][binIdx]` | ||
| 243 | +//! per Table 9-51, captured verbatim in | ||
| 244 | +//! [`PALETTE_RUN_PREFIX_CTX_IDX_MAP`]. The `binIdx >= 5` cells of | ||
| 245 | +//! Table 9-51 are bypass-coded per Table 9-48, so the lookup | ||
| 246 | +//! covers `binIdx ∈ {0, 1, 2, 3, 4}` and the public entry point | ||
| 247 | +//! [`palette_run_prefix_ctx_inc`] dispatches both branches with | ||
| 248 | +//! an `Option<u32>` return (`None` ⇒ bypass). | ||
| 249 | +//! | ||
| 250 | +//! Round 33 also captures the matching Table 9-43 binarization | ||
| 251 | +//! shape: `palette_run_prefix` is a TR with | ||
| 252 | +//! `cMax = Floor(Log2(PaletteMaxRunMinus1)) + 1` and `cRiceParam = 0`; | ||
| 253 | +//! the helper [`palette_run_prefix_tr_cmax`] returns the per-block | ||
| 254 | +//! `cMax` from the `PaletteMaxRunMinus1` input. | ||
| 255 | +//! | ||
| 256 | +//! Round 34 adds the §9.3.3.11 `coeff_abs_level_remaining[ n ]` | ||
| 257 | +//! Rice-adaptive binarization + decode primitive (non-persistent | ||
| 258 | +//! branch: `persistent_rice_adaptation_enabled_flag == 0`): | ||
| 259 | +//! | ||
| 260 | +//! * [`coeff_abs_level_remaining_c_rice_param_eq_9_24`] — eq. 9-24 | ||
| 261 | +//! adapts `cRiceParam` from the previous coefficient in the | ||
| 262 | +//! sub-block: `cRiceParam = Min(cLastRiceParam + (cLastAbsLevel > | ||
| 263 | +//! (3 << cLastRiceParam) ? 1 : 0), 4)`. | ||
| 264 | +//! * [`coeff_abs_level_remaining_c_max_eq_9_26`] — eq. 9-26: | ||
| 265 | +//! `cMax = 4 << cRiceParam`. | ||
| 266 | +//! * [`coeff_abs_level_remaining_prefix_val_eq_9_27`] — eq. 9-27: | ||
| 267 | +//! `prefixVal = Min(cMax, level)` (the value the §9.3.3.2 TR | ||
| 268 | +//! prefix is built from). | ||
| 269 | +//! * [`coeff_abs_level_remaining_suffix_val_eq_9_28`] — eq. 9-28: | ||
| 270 | +//! `suffixVal = level - cMax` (only meaningful when the prefix is | ||
| 271 | +//! the all-ones escape). | ||
| 272 | +//! * [`decode_coeff_abs_level_remaining`] — full bypass-coded decode | ||
| 273 | +//! driver: reads a unary prefix capped at | ||
| 274 | +//! `COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN = 4`, and when | ||
| 275 | +//! the prefix terminates short, returns | ||
| 276 | +//! `prefix << cRiceParam`; otherwise reads an EGk suffix with | ||
| 277 | +//! `k = cRiceParam + 1` and returns `cMax + suffixVal`. | ||
| 278 | +//! | ||
| 279 | +//! The persistent-Rice branch (eq. 9-25; the | ||
| 280 | +//! `persistent_rice_adaptation_enabled_flag == 1` path that walks | ||
| 281 | +//! the SCC `StatCoeff[sbType]` state via eq. 9-22/9-23) is left for | ||
| 282 | +//! a follow-up round; the non-persistent branch is the Main-profile | ||
| 283 | +//! path the slice-data parser drives by default. | ||
| 284 | +//! | ||
| 285 | +//! Round 35 adds the §9.3.4.2 / Table 9-48 entry for | ||
| 286 | +//! `coeff_sign_flag[ n ]` — the per-scan-position sign bit that | ||
| 287 | +//! pairs with `coeff_abs_level_remaining[ n ]` to form the signed | ||
| 288 | +//! transform-coefficient level per §7.4.9.11. The element is fully | ||
| 289 | +//! bypass-coded (Table 9-48 marks bin 0 `bypass`, all later columns | ||
| 290 | +//! `na`) and FL binarized with `cMax = 1` (Table 9-43), so the | ||
| 291 | +//! on-wire string is a single bin per invocation. The §9.3.4.3.6 | ||
| 292 | +//! alignment process (`ivlCurrRange := 256`) runs prior to the | ||
| 293 | +//! bypass tail at slice-data-loop scope; the per-flag entry point | ||
| 294 | +//! [`decode_coeff_sign_flag`] consumes one [`CabacEngine::decode_bypass`] | ||
| 295 | +//! bin from the post-alignment engine state. The signed level is | ||
| 296 | +//! composed via [`signed_level_from_sign_flag`] applying the | ||
| 297 | +//! §7.4.9.11 `(1 − 2 * coeff_sign_flag[n])` factor; the FL shape | ||
| 298 | +//! is captured as [`COEFF_SIGN_FLAG_FL_CMAX`] + | ||
| 299 | +//! [`COEFF_SIGN_FLAG_FL_NBITS`]. | ||
| 300 | +//! | ||
| 301 | +//! Round 36 adds the §9.3.4.2 / Table 9-48 entries for the | ||
| 302 | +//! `cu_chroma_qp_offset_flag` / `cu_chroma_qp_offset_idx` transform-unit | ||
| 303 | +//! syntax pair (H.265 §7.3.8.11, §7.4.9.10). Both elements have a | ||
| 304 | +//! Table 9-48 row whose context-coded bins are all `ctxInc = 0` — the | ||
| 305 | +//! flag occupies a single context (Table 9-34, three ctxIdx slots | ||
| 306 | +//! across initType), and the idx occupies a single context (Table | ||
| 307 | +//! 9-35, three ctxIdx slots across initType). The flag is FL | ||
| 308 | +//! `cMax = 1`; the idx is TR with `cMax = | ||
| 309 | +//! chroma_qp_offset_list_len_minus1`, `cRiceParam = 0`. The §7.4.9.10 | ||
| 310 | +//! derivation pair the flag + idx feed is `CuQpOffsetCb = (flag == 1) | ||
| 311 | +//! ? cb_qp_offset_list[idx] : 0` (and symmetric for Cr). The new | ||
| 312 | +//! public surface: [`CU_CHROMA_QP_OFFSET_FLAG_FL_CMAX`] (= 1, Table | ||
| 313 | +//! 9-43 shape) and [`CU_CHROMA_QP_OFFSET_FLAG_FL_NBITS`] (= 1); | ||
| 314 | +//! [`cu_chroma_qp_offset_flag_ctx_inc`] returns the Table 9-48 bin-0 | ||
| 315 | +//! `ctxInc = 0` for the FL flag; [`cu_chroma_qp_offset_idx_tr_cmax`] | ||
| 316 | +//! returns the per-TU `cMax` from the PPS-resolved | ||
| 317 | +//! `chroma_qp_offset_list_len_minus1`; [`cu_chroma_qp_offset_idx_ctx_inc`] | ||
| 318 | +//! returns the Table 9-48 `ctxInc = 0` (constant across the TR-prefix | ||
| 319 | +//! bins 0..=4, since Table 9-48 lists `0` for every context-coded | ||
| 320 | +//! binIdx column); and [`decode_cu_chroma_qp_offset`] drives the | ||
| 321 | +//! CABAC engine to produce the typed [`CuChromaQpOffset`] (the | ||
| 322 | +//! flag plus, when the flag is 1, the idx with the §7.4.9.10 | ||
| 323 | +//! derivation gates surfaced via [`CuChromaQpOffset::offset_indices`]). | ||
| 324 | +//! | ||
| 325 | +//! Round 37 adds the §9.3.4.2 / Table 9-48 entry for | ||
| 326 | +//! `cu_transquant_bypass_flag` — the per-CU bypass switch that, when | ||
| 327 | +//! set, replaces the scaling + transform + in-loop-filter path with a | ||
| 328 | +//! verbatim residual passthrough (H.265 §7.3.8.5, §7.4.9.5). Per | ||
| 329 | +//! Table 9-43 the flag is FL with `cMax = 1` (a single context-coded | ||
| 330 | +//! bin); Table 9-48's row lists `ctxInc = 0` for bin 0 and `na` for | ||
| 331 | +//! every later binIdx column. The flag occupies a single context | ||
| 332 | +//! (Table 9-8: `initValue = 154` at all three initType slots) which | ||
| 333 | +//! sits at the slice-init-allocated bank entry the parser hands to | ||
| 334 | +//! the decode primitive. The PPS gate is | ||
| 335 | +//! `transquant_bypass_enabled_flag` (§7.4.3.3.1): the flag is read | ||
| 336 | +//! from the bitstream only when that PPS field is 1, otherwise | ||
| 337 | +//! §7.4.9.5 infers the value to 0 (the normal scaling-and-transform | ||
| 338 | +//! path). The new public surface: | ||
| 339 | +//! [`CU_TRANSQUANT_BYPASS_FLAG_FL_CMAX`] (= 1, Table 9-43 shape) and | ||
| 340 | +//! [`CU_TRANSQUANT_BYPASS_FLAG_FL_NBITS`] (= 1); | ||
| 341 | +//! [`cu_transquant_bypass_flag_ctx_inc`] returns the Table 9-48 bin-0 | ||
| 342 | +//! `ctxInc = 0`; [`decode_cu_transquant_bypass_flag`] drives one | ||
| 343 | +//! [`CabacEngine::decode_decision`] against the caller's context and | ||
| 344 | +//! returns the decoded `u8`; [`cu_transquant_bypass_flag_inferred`] | ||
| 345 | +//! surfaces the §7.4.9.5 "PPS gate off ⇒ value is 0" inference as a | ||
| 346 | +//! pure helper for callers that branch on the PPS without entering | ||
| 347 | +//! the engine. | ||
| 348 | +//! | ||
| 349 | +//! Round 38 adds the §9.3.4.2 / Table 9-48 entry for `rqt_root_cbf` — | ||
| 350 | +//! the inter-CU gate that signals whether the `transform_tree( )` | ||
| 351 | +//! syntax structure follows the current coding unit (H.265 §7.3.8.5, | ||
| 352 | +//! §7.4.9.5). Per Table 9-43 the flag is FL with `cMax = 1` (a single | ||
| 353 | +//! context-coded bin); Table 9-48's row lists `ctxInc = 0` for bin 0 | ||
| 354 | +//! and `na` for every later binIdx column. Table 9-14 supplies a | ||
| 355 | +//! single ctxIdx slot with `initValue = 79` at both initType 1 and | ||
| 356 | +//! initType 2 (initType 0 is `na` in Table 9-4 — `rqt_root_cbf` is | ||
| 357 | +//! only ever read in inter slices, where §7.3.8.5 wires it under | ||
| 358 | +//! `CuPredMode != MODE_INTRA && !cu_skip_flag`). When the §7.3.8.5 | ||
| 359 | +//! guard fails (intra CU, or skip CU) the flag is not present on the | ||
| 360 | +//! wire and the §7.4.9.5 inferred value is 1 (the `transform_tree( )` | ||
| 361 | +//! syntax structure is taken to be present). The new public surface: | ||
| 362 | +//! [`RQT_ROOT_CBF_FL_CMAX`] (= 1, Table 9-43 shape) and | ||
| 363 | +//! [`RQT_ROOT_CBF_FL_NBITS`] (= 1); [`rqt_root_cbf_ctx_inc`] returns | ||
| 364 | +//! the Table 9-48 bin-0 `ctxInc = 0`; [`decode_rqt_root_cbf`] drives | ||
| 365 | +//! one [`CabacEngine::decode_decision`] against the caller's context | ||
| 366 | +//! and returns the decoded `u8`; [`rqt_root_cbf_inferred`] surfaces | ||
| 367 | +//! the §7.4.9.5 "not present ⇒ value is 1" inference as a pure helper | ||
| 368 | +//! for callers that branch on the §7.3.8.5 guard without entering the | ||
| 369 | +//! engine. | ||
| 370 | +//! | ||
| 371 | +//! Round 39 adds the §9.3.4.2 / Table 9-48 entry for `pred_mode_flag` — | ||
| 372 | +//! the per-CU bit that selects between MODE_INTER (value 0) and | ||
| 373 | +//! MODE_INTRA (value 1) inside a P or B slice (H.265 §7.3.8.5, | ||
| 374 | +//! §7.4.9.5). Per Table 9-43 the flag is FL with `cMax = 1` (a single | ||
| 375 | +//! context-coded bin); Table 9-48's row lists `ctxInc = 0` for bin 0 | ||
| 376 | +//! and `na` for every later binIdx column. Table 9-10 supplies two | ||
| 377 | +//! ctxIdx slots with `initValue = {149, 134}` for initType 1 and | ||
| 378 | +//! initType 2 (initType 0 is `na` in Table 9-4 — the §7.3.8.5 | ||
| 379 | +//! `slice_type != I` guard skips the read for I slices, where the | ||
| 380 | +//! mode is unconditionally intra). When the §7.3.8.5 guard fails the | ||
| 381 | +//! flag is not present on the wire and §7.4.9.5 derives `CuPredMode` | ||
| 382 | +//! directly: I slice ⇒ MODE_INTRA; P or B slice with | ||
| 383 | +//! `cu_skip_flag == 1` ⇒ MODE_SKIP. The new public surface: | ||
| 384 | +//! [`PRED_MODE_FLAG_FL_CMAX`] (= 1, Table 9-43 shape) and | ||
| 385 | +//! [`PRED_MODE_FLAG_FL_NBITS`] (= 1); [`pred_mode_flag_ctx_inc`] | ||
| 386 | +//! returns the Table 9-48 bin-0 `ctxInc = 0`; | ||
| 387 | +//! [`decode_pred_mode_flag`] drives one | ||
| 388 | +//! [`CabacEngine::decode_decision`] against the caller's context and | ||
| 389 | +//! returns the decoded `u8`; the [`CuPredMode`] enum captures the | ||
| 390 | +//! §7.4.9.5 mapping (`0 ⇒ MODE_INTER`, `1 ⇒ MODE_INTRA`, plus the | ||
| 391 | +//! not-present-only MODE_SKIP state); [`cu_pred_mode_from_flag`] | ||
| 392 | +//! applies the present-on-wire mapping; and | ||
| 393 | +//! [`pred_mode_flag_inferred_cu_pred_mode`] applies the §7.4.9.5 | ||
| 394 | +//! not-present inference branching on `slice_type` and `cu_skip_flag`. | ||
| 395 | +//! | ||
| 396 | +//! Round 40 adds the §9.3.4.2 / Table 9-48 entry for | ||
| 397 | +//! `prev_intra_luma_pred_flag` — the per-luma-prediction-block bit that | ||
| 398 | +//! selects, for an intra CU, whether the luma intra prediction mode is | ||
| 399 | +//! taken from the most-probable-mode list (`mpm_idx` follows) or from | ||
| 400 | +//! the remaining-mode field (`rem_intra_luma_pred_mode` follows), per | ||
| 401 | +//! H.265 §7.3.8.5, §7.4.9.2. Per Table 9-43 the flag is FL with | ||
| 402 | +//! `cMax = 1` (a single context-coded bin); Table 9-48's row lists | ||
| 403 | +//! `ctxInc = 0` for bin 0 and `na` for every later binIdx column. | ||
| 404 | +//! Table 9-12 supplies three ctxIdx slots with | ||
| 405 | +//! `initValue = {184, 154, 183}` for initType 0, 1 and 2 — unlike | ||
| 406 | +//! `pred_mode_flag`, this element is read in I, P and B slices (intra | ||
| 407 | +//! CUs occur in every slice type), so all three initType slots are | ||
| 408 | +//! populated. The flag is always present when the §7.3.8.5 intra-PB | ||
| 409 | +//! loop reaches it (no inferred-value rule); when it is 1 the §8.4.2 | ||
| 410 | +//! candidate-mode derivation supplies `IntraPredModeY` and `mpm_idx` | ||
| 411 | +//! selects among the candidates, when it is 0 | ||
| 412 | +//! `rem_intra_luma_pred_mode` carries the mode directly. The new | ||
| 413 | +//! public surface: [`PREV_INTRA_LUMA_PRED_FLAG_FL_CMAX`] (= 1, Table | ||
| 414 | +//! 9-43 shape) and [`PREV_INTRA_LUMA_PRED_FLAG_FL_NBITS`] (= 1); | ||
| 415 | +//! [`prev_intra_luma_pred_flag_ctx_inc`] returns the Table 9-48 bin-0 | ||
| 416 | +//! `ctxInc = 0`; the [`LumaIntraModeSource`] enum captures the | ||
| 417 | +//! §7.4.9.2 selection (`1 ⇒ Mpm`, `0 ⇒ Remaining`); | ||
| 418 | +//! [`luma_intra_mode_source_from_flag`] folds a decoded flag into the | ||
| 419 | +//! enum; and [`decode_prev_intra_luma_pred_flag`] drives one | ||
| 420 | +//! [`CabacEngine::decode_decision`] against the caller's context and | ||
| 421 | +//! returns the decoded `u8`. | ||
| 422 | +//! | ||
| 423 | +//! Round 41 adds the two §7.3.8.5 luma-mode fields the round-40 flag | ||
| 424 | +//! gates: `mpm_idx` (Table 9-43 TR with `cMax = 2`, `cRiceParam = 0`) | ||
| 425 | +//! and `rem_intra_luma_pred_mode` (Table 9-43 FL with `cMax = 31`), | ||
| 426 | +//! per H.265 §7.4.9.2 / §8.4.2. Both are fully bypass-coded (Table 9-48 | ||
| 427 | +//! marks every bin `bypass`), so neither consumes a context model and | ||
| 428 | +//! presence is exactly the [`LumaIntraModeSource`] selection. The new | ||
| 429 | +//! public surface: [`MPM_IDX_TR_CMAX`] (= 2) + | ||
| 430 | +//! [`MPM_IDX_TR_C_RICE_PARAM`] (= 0) and [`decode_mpm_idx`] (the | ||
| 431 | +//! truncated-unary prefix through the bypass decoder, output `0..=2`); | ||
| 432 | +//! [`REM_INTRA_LUMA_PRED_MODE_FL_CMAX`] (= 31) + | ||
| 433 | +//! [`REM_INTRA_LUMA_PRED_MODE_FL_NBITS`] (= 5) and | ||
| 434 | +//! [`decode_rem_intra_luma_pred_mode`] (five FL bypass bins MSB-first, | ||
| 435 | +//! output `0..=31`). | ||
| 436 | +//! | ||
| 437 | +//! Round 42 adds the §7.3.8.5 chroma-mode field that follows the | ||
| 438 | +//! round-40/41 luma-mode group: `intra_chroma_pred_mode`, per H.265 | ||
| 439 | +//! §7.4.9.5 / §9.3.3.8 / §8.4.3. Unlike the Table 9-43 generic shapes, | ||
| 440 | +//! this element has its own binarization process (§9.3.3.8 / Table | ||
| 441 | +//! 9-46): the single-bin string `0` signals value 4, and a `1` prefix | ||
| 442 | +//! followed by a two-bit FL suffix signals values 0..=3. Table 9-48 | ||
| 443 | +//! marks bin 0 context-coded with `ctxInc = 0` (Table 9-13 supplies | ||
| 444 | +//! `initValue = {63, 152, 152}` for initType 0, 1 and 2) and bins 1..2 | ||
| 445 | +//! `bypass`. The §8.4.3 derivation maps the decoded value plus | ||
| 446 | +//! `IntraPredModeY` to `modeIdx` via Table 8-2 (value 4 tracks the luma | ||
| 447 | +//! mode; values 0..=3 select from {0, 26, 10, 1} with a collision | ||
| 448 | +//! substitute of 34), then — when `ChromaArrayType == 2` — remaps | ||
| 449 | +//! `modeIdx` through Table 8-3. The new public surface: | ||
| 450 | +//! [`INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA`] (= 4, the Table 9-46 | ||
| 451 | +//! single-bin value), [`INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS`] (= 2), | ||
| 452 | +//! [`intra_chroma_pred_mode_ctx_inc`] (the Table 9-48 bin-0 | ||
| 453 | +//! `ctxInc = 0`), [`decode_intra_chroma_pred_mode`] (one | ||
| 454 | +//! [`CabacEngine::decode_decision`] then, for the `1` prefix, two | ||
| 455 | +//! bypass bins; output `{0, 1, 2, 3, 4}`), | ||
| 456 | +//! [`intra_pred_mode_c_mode_idx`] (Table 8-2), | ||
| 457 | +//! [`INTRA_PRED_MODE_C_CHROMA_422_MAP`] / | ||
| 458 | +//! [`intra_pred_mode_c_chroma_422`] (Table 8-3), and | ||
| 459 | +//! [`derive_intra_pred_mode_c`] (the full §8.4.3 output). | ||
| 460 | + | ||
| 461 | +use crate::cabac::{CabacEngine, CabacError, ContextModel}; | ||
| 462 | + | ||
| 463 | +// --------------------------------------------------------------------- | ||
| 464 | +// Truncated-rice helper — §9.3.3.10 | ||
| 465 | +// --------------------------------------------------------------------- | ||
| 466 | + | ||
| 467 | +/// §9.3.3.10 — read a truncated-rice prefix with `cMax` and | ||
| 468 | +/// `cRiceParam = 0` (the only configuration this module currently | ||
| 469 | +/// needs). The prefix is unary up to a maximum of `cMax >> 0` = `cMax` | ||
| 470 | +/// bins; a value of `cMax / (1 << 0)` = `cMax` is the "escape" form | ||
| 471 | +/// signalling that a suffix follows for callers that pair TR with an | ||
| 472 | +/// EGk continuation. | ||
| 473 | +/// | ||
| 474 | +/// `read_bin(bin_idx)` decodes the bin at index `bin_idx` (0-based) | ||
| 475 | +/// using the caller's choice of context-coded or bypass-coded path, and | ||
| 476 | +/// returns the decoded bin (0 = continue, 1 = terminate / escape). | ||
| 477 | +/// | ||
| 478 | +/// Returns `(prefix_val, is_escape)`. `is_escape` is `true` exactly | ||
| 479 | +/// when `prefix_val == cMax`: i.e. all `cMax` bins were 1, signalling | ||
| 480 | +/// that a TR + EGk continuation suffix must be read by the caller. | ||
| 481 | +pub(crate) fn read_truncated_rice_prefix<F>( | ||
| 482 | + c_max: u32, | ||
| 483 | + mut read_bin: F, | ||
| 484 | +) -> Result<(u32, bool), CabacError> | ||
| 485 | +where | ||
| 486 | + F: FnMut(u32) -> Result<u8, CabacError>, | ||
| 487 | +{ | ||
| 488 | + // Unary: count leading 1s up to c_max. The decoded bin tally is | ||
| 489 | + // simultaneously the prefix value (number of leading 1s) and the | ||
| 490 | + // escape signal (all-ones when value == c_max). | ||
| 491 | + let mut value: u32 = 0; | ||
| 492 | + while value < c_max { | ||
| 493 | + let bin = read_bin(value)?; | ||
| 494 | + if bin == 0 { | ||
| 495 | + return Ok((value, false)); | ||
| 496 | + } | ||
| 497 | + value += 1; | ||
| 498 | + } | ||
| 499 | + Ok((value, true)) | ||
| 500 | +} | ||
| 501 | + | ||
| 502 | +// --------------------------------------------------------------------- | ||
| 503 | +// §9.3.3.3 — Exp-Golomb of order k (bypass-coded, MSB-first prefix then | ||
| 504 | +// suffix). Per the §9.3.3.3 NOTE the EGk prefix uses 1's and 0's in the | ||
| 505 | +// reverse meaning of the §9.2 EG0 prefix: it is a unary run of `1` bins | ||
| 506 | +// terminated by a single `0`, followed by `prefix_ones + k` suffix bits. | ||
| 507 | +// --------------------------------------------------------------------- | ||
| 508 | + | ||
| 509 | +/// §9.3.3.3 — decode an EGk-coded value from the bypass stream for | ||
| 510 | +/// arbitrary Exp-Golomb order `k`. | ||
| 511 | +/// | ||
| 512 | +/// The reader counts leading `1` bypass bins until a terminating `0` | ||
| 513 | +/// (call this count `prefix_ones`); reads `prefix_ones + k` more | ||
| 514 | +/// bypass bins as the suffix; and returns | ||
| 515 | +/// `((1 << prefix_ones) - 1) << k + suffix`. | ||
| 516 | +/// | ||
| 517 | +/// For `k = 0` the reader collapses to the `cu_qp_delta_abs`-style | ||
| 518 | +/// "(1 << lz) - 1 + suffix" form (suffix length == `leading_zeros`, | ||
| 519 | +/// `<< 0` factor disappears) — preserved as | ||
| 520 | +/// [`decode_eg_k0`] for callers that only need the `k = 0` case. | ||
| 521 | +/// | ||
| 522 | +/// `leading_zeros` is capped at 32 to keep the decoder defensive | ||
| 523 | +/// against runaway encodings; the cap is comfortably above any legal | ||
| 524 | +/// HEVC bypass-coded suffix value (§7.4.9.11 puts the practical | ||
| 525 | +/// ceiling well below `2^31`). | ||
| 526 | +pub(crate) fn decode_eg_k(engine: &mut CabacEngine<'_>, k: u32) -> Result<u32, CabacError> { | ||
| 527 | + read_eg_k_with(k, || engine.decode_bypass()) | ||
| 528 | +} | ||
| 529 | + | ||
| 530 | +/// §9.3.3.3 — decode an EGk-coded value of order `k` from a generic | ||
| 531 | +/// bin reader (each call yields the next bypass bin). Factored out of | ||
| 532 | +/// [`decode_eg_k`] so the §7.3.8.9 `abs_mvd_minus2` EG1 escape can be | ||
| 533 | +/// composed and unit-tested without driving the arithmetic engine's | ||
| 534 | +/// range/offset state. The decode follows the equation-9-13 do-while: | ||
| 535 | +/// per the §9.3.3.3 NOTE the EGk unary prefix uses 1's and 0's in the | ||
| 536 | +/// reverse meaning of the §9.2 EG0 prefix, so the prefix is a run of | ||
| 537 | +/// `1` bins terminated by a single `0`. Count those leading `1` bins | ||
| 538 | +/// (`prefix_ones`), then read `prefix_ones + k` suffix bins, yielding | ||
| 539 | +/// `((1 << prefix_ones) − 1) << k + suffix`. | ||
| 540 | +pub(crate) fn read_eg_k_with<F>(k: u32, mut read_bin: F) -> Result<u32, CabacError> | ||
| 541 | +where | ||
| 542 | + F: FnMut() -> Result<u8, CabacError>, | ||
| 543 | +{ | ||
| 544 | + let mut prefix_ones: u32 = 0; | ||
| 545 | + while prefix_ones < 32 { | ||
| 546 | + let bin = read_bin()?; | ||
| 547 | + if bin == 0 { | ||
| 548 | + break; | ||
| 549 | + } | ||
| 550 | + prefix_ones += 1; | ||
| 551 | + } | ||
| 552 | + // Guard against accidental >32-bit reads (cap `prefix_ones` at | ||
| 553 | + // 32 already bounds this; the saturate keeps the read width inside | ||
| 554 | + // a single `u32` if `k` is unusually large). | ||
| 555 | + let suffix_bits = (prefix_ones + k).min(32); | ||
| 556 | + let mut suffix: u32 = 0; | ||
| 557 | + for _ in 0..suffix_bits { | ||
| 558 | + suffix = (suffix << 1) | u32::from(read_bin()?); | ||
| 559 | + } | ||
| 560 | + let base = ((1u64 << prefix_ones) - 1) << k; | ||
| 561 | + let value = base + u64::from(suffix); | ||
| 562 | + // The defensive cap above keeps `value` inside `u32`; the | ||
| 563 | + // saturate keeps us inside the public return type if the | ||
| 564 | + // pathological 32-bit edge is ever reached. | ||
| 565 | + Ok(u32::try_from(value).unwrap_or(u32::MAX)) | ||
| 566 | +} | ||
| 567 | + | ||
| 568 | +/// §9.3.3.11 — decode an EGk-coded value with `k = 0` from the bypass | ||
| 569 | +/// stream. Preserved as a named alias for the `cu_qp_delta_abs` / | ||
| 570 | +/// `palette_escape_val` callers that historically used the `k = 0` | ||
| 571 | +/// fast path; equivalent to `decode_eg_k(engine, 0)`. | ||
| 572 | +fn decode_eg_k0(engine: &mut CabacEngine<'_>) -> Result<u32, CabacError> { | ||
| 573 | + decode_eg_k(engine, 0) | ||
| 574 | +} | ||
| 575 | + | ||
| 576 | +// --------------------------------------------------------------------- | ||
| 577 | +// cu_qp_delta_abs / cu_qp_delta_sign_flag (§7.3.8.14, §7.4.9.14) | ||
| 578 | +// --------------------------------------------------------------------- | ||
| 579 | + | ||
| 580 | +/// §9.3.4.2.2 Table 9-32 — per-bin `ctxInc` for `cu_qp_delta_abs`. Bin | ||
| 581 | +/// 0 uses a dedicated context (`ctxInc = 0`); bins 1..=4 share a second | ||
| 582 | +/// dedicated context (`ctxInc = 1`). The TR prefix carries at most | ||
| 583 | +/// `cMax = 5` bins; the EGk(k=0) suffix is bypass-coded and not | ||
| 584 | +/// indexed. | ||
| 585 | +#[must_use] | ||
| 586 | +pub fn cu_qp_delta_abs_ctx_inc(bin_idx: u32) -> u32 { | ||
| 587 | + if bin_idx == 0 { | ||
| 588 | + 0 | ||
| 589 | + } else { | ||
| 590 | + 1 | ||
| 591 | + } | ||
| 592 | +} | ||
| 593 | + | ||
| 594 | +/// `cu_qp_delta_abs` TR prefix `cMax`. §9.3.3.10 (with §9.3.4.2.2 | ||
| 595 | +/// row). | ||
| 596 | +pub const CU_QP_DELTA_ABS_TR_CMAX: u32 = 5; | ||
| 597 | + | ||
| 598 | +/// Decoded `cu_qp_delta` pair plus the §7.4.9.14 derived | ||
| 599 | +/// `CuQpDeltaVal`. | ||
| 600 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 601 | +pub struct CuQpDelta { | ||
| 602 | + /// `cu_qp_delta_abs` from the wire. | ||
| 603 | + pub abs: u32, | ||
| 604 | + /// `cu_qp_delta_sign_flag` from the wire; `None` when | ||
| 605 | + /// `abs == 0` (the flag is not signalled in that case). | ||
| 606 | + pub sign_flag: Option<u8>, | ||
| 607 | + /// Derived signed delta: | ||
| 608 | + /// `cu_qp_delta_abs * (1 − 2 * cu_qp_delta_sign_flag)`. | ||
| 609 | + /// Equals `0` when `abs == 0`. | ||
| 610 | + pub value: i32, | ||
| 611 | +} | ||
| 612 | + | ||
| 613 | +/// Decode the `cu_qp_delta` syntax pair (§7.3.8.14 / §7.4.9.14) from | ||
| 614 | +/// the CABAC engine, consuming the two context variables for the | ||
| 615 | +/// `cu_qp_delta_abs` TR prefix (bin 0 + bins 1..=4) and any required | ||
| 616 | +/// bypass bins for the EGk(k=0) suffix and the sign flag. | ||
| 617 | +/// | ||
| 618 | +/// `ctx_bin0` and `ctx_bin_rest` are the caller's | ||
| 619 | +/// `(pStateIdx, valMps)` state for the two `cu_qp_delta_abs` contexts; | ||
| 620 | +/// they are mutated in place per §9.3.4.3.2.2 state transition. | ||
| 621 | +/// | ||
| 622 | +/// Returns the decoded [`CuQpDelta`] including the §7.4.9.14 | ||
| 623 | +/// `CuQpDeltaVal` derivation. | ||
| 624 | +pub fn decode_cu_qp_delta( | ||
| 625 | + engine: &mut CabacEngine<'_>, | ||
| 626 | + ctx_bin0: &mut ContextModel, | ||
| 627 | + ctx_bin_rest: &mut ContextModel, | ||
| 628 | +) -> Result<CuQpDelta, CabacError> { | ||
| 629 | + // Decode the §9.3.3.10 TR prefix using two contexts: bin 0 uses | ||
| 630 | + // ctx_bin0, all subsequent bins share ctx_bin_rest. | ||
| 631 | + let (prefix, is_escape) = read_truncated_rice_prefix(CU_QP_DELTA_ABS_TR_CMAX, |bin_idx| { | ||
| 632 | + if cu_qp_delta_abs_ctx_inc(bin_idx) == 0 { | ||
| 633 | + engine.decode_decision(ctx_bin0) | ||
| 634 | + } else { | ||
| 635 | + engine.decode_decision(ctx_bin_rest) | ||
| 636 | + } | ||
| 637 | + })?; | ||
| 638 | + | ||
| 639 | + // §9.3.3.10: if the prefix is the all-ones escape (== cMax), an | ||
| 640 | + // EGk(k=0) suffix follows; the decoded value is prefix + suffix. | ||
| 641 | + let abs = if is_escape { | ||
| 642 | + prefix + decode_eg_k0(engine)? | ||
| 643 | + } else { | ||
| 644 | + prefix | ||
| 645 | + }; | ||
| 646 | + | ||
| 647 | + // §7.4.9.14: the sign flag is signalled only when abs != 0. | ||
| 648 | + let (sign_flag, signed) = if abs == 0 { | ||
| 649 | + (None, 0i32) | ||
| 650 | + } else { | ||
| 651 | + let s = engine.decode_bypass()?; | ||
| 652 | + // CuQpDeltaVal = abs * (1 − 2 * sign_flag) | ||
| 653 | + let sign_factor = 1i32 - 2 * (s as i32); | ||
| 654 | + (Some(s), abs as i32 * sign_factor) | ||
| 655 | + }; | ||
| 656 | + | ||
| 657 | + Ok(CuQpDelta { | ||
| 658 | + abs, | ||
| 659 | + sign_flag, | ||
| 660 | + value: signed, | ||
| 661 | + }) | ||
| 662 | +} | ||
| 663 | + | ||
| 664 | +// --------------------------------------------------------------------- | ||
| 665 | +// cu_chroma_qp_offset_flag / cu_chroma_qp_offset_idx | ||
| 666 | +// (§7.3.8.11 transform_unit() / §7.4.9.10 — PPS chroma-QP-offset list | ||
| 667 | +// gating). Table 9-43 binarizations + Table 9-48 ctxInc derivations. | ||
| 668 | +// --------------------------------------------------------------------- | ||
| 669 | + | ||
| 670 | +/// Table 9-43 binarization shape for `cu_chroma_qp_offset_flag`: FL | ||
| 671 | +/// with `cMax = 1` (a single context-coded bin). | ||
| 672 | +pub const CU_CHROMA_QP_OFFSET_FLAG_FL_CMAX: u32 = 1; | ||
| 673 | + | ||
| 674 | +/// FL-binarization bit count for `cu_chroma_qp_offset_flag`: one | ||
| 675 | +/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. | ||
| 676 | +pub const CU_CHROMA_QP_OFFSET_FLAG_FL_NBITS: u32 = 1; | ||
| 677 | + | ||
| 678 | +/// §9.3.4.2.1 / Table 9-48 row for `cu_chroma_qp_offset_flag`. Bin 0 | ||
| 679 | +/// is context-coded with `ctxInc = 0`; later bin-index columns are | ||
| 680 | +/// `na` (the FL `cMax = 1` shape only emits a single bin). | ||
| 681 | +/// | ||
| 682 | +/// The flag's Table 9-34 ctxIdx layout (`initValue = 154` at every | ||
| 683 | +/// initType slot) is consumed at slice-init scope; this layer hands | ||
| 684 | +/// back the bank-relative `ctxInc` only. | ||
| 685 | +#[must_use] | ||
| 686 | +pub fn cu_chroma_qp_offset_flag_ctx_inc() -> u32 { | ||
| 687 | + 0 | ||
| 688 | +} | ||
| 689 | + | ||
| 690 | +/// §9.3.4.2.1 / Table 9-48 row for `cu_chroma_qp_offset_idx`. Every | ||
| 691 | +/// context-coded bin column (binIdx 0..=4 of the TR prefix) lists | ||
| 692 | +/// `ctxInc = 0`; binIdx 5 is `na` (the §7.4.9.10 idx range tops out | ||
| 693 | +/// at `chroma_qp_offset_list_len_minus1 <= 5`, so the spec-mandated | ||
| 694 | +/// `cMax <= 5` TR prefix can produce at most five bins). | ||
| 695 | +/// | ||
| 696 | +/// The idx's Table 9-35 ctxIdx layout (`initValue = 154` at every | ||
| 697 | +/// initType slot) is consumed at slice-init scope; this layer hands | ||
| 698 | +/// back the bank-relative `ctxInc` only. | ||
| 699 | +/// | ||
| 700 | +/// `bin_idx` is the §9.3.4.2 binIdx of the bin being coded; values | ||
| 701 | +/// outside `0..=4` are `na` per Table 9-48. | ||
| 702 | +#[must_use] | ||
| 703 | +pub fn cu_chroma_qp_offset_idx_ctx_inc(bin_idx: u32) -> u32 { | ||
| 704 | + debug_assert!( | ||
| 705 | + bin_idx <= 4, | ||
| 706 | + "cu_chroma_qp_offset_idx Table 9-48 row: binIdx > 4 is na" | ||
| 707 | + ); | ||
| 708 | + 0 | ||
| 709 | +} | ||
| 710 | + | ||
| 711 | +/// §9.3.3.10 / Table 9-43 row for `cu_chroma_qp_offset_idx`: TR with | ||
| 712 | +/// `cMax = chroma_qp_offset_list_len_minus1`, `cRiceParam = 0`. | ||
| 713 | +/// `chroma_qp_offset_list_len_minus1` is the PPS-signalled length of | ||
| 714 | +/// `cb_qp_offset_list[ ]` / `cr_qp_offset_list[ ]` minus one | ||
| 715 | +/// (§7.4.3.3.1: a `u(3)` field, bounded by `<= 5`). | ||
| 716 | +#[must_use] | ||
| 717 | +pub fn cu_chroma_qp_offset_idx_tr_cmax(chroma_qp_offset_list_len_minus1: u32) -> u32 { | ||
| 718 | + chroma_qp_offset_list_len_minus1 | ||
| 719 | +} | ||
| 720 | + | ||
| 721 | +/// Decoded `cu_chroma_qp_offset_flag` / `cu_chroma_qp_offset_idx` pair | ||
| 722 | +/// with the §7.4.9.10 chroma-QP-offset-list dereference surfaced as a | ||
| 723 | +/// typed accessor. | ||
| 724 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 725 | +pub struct CuChromaQpOffset { | ||
| 726 | + /// `cu_chroma_qp_offset_flag` from the wire. | ||
| 727 | + pub flag: u8, | ||
| 728 | + /// `cu_chroma_qp_offset_idx` from the wire; `None` when the flag | ||
| 729 | + /// is 0 (the idx is not signalled in that case per §7.3.8.11). | ||
| 730 | + /// When the flag is 1 and `chroma_qp_offset_list_len_minus1 == 0` | ||
| 731 | + /// the idx is also not signalled (the TR prefix has `cMax = 0`, | ||
| 732 | + /// emitting zero bins) and the value is inferred to be 0. | ||
| 733 | + pub idx: Option<u32>, | ||
| 734 | +} | ||
| 735 | + | ||
| 736 | +impl CuChromaQpOffset { | ||
| 737 | + /// §7.4.9.10 — return the `(cb_qp_offset_list, cr_qp_offset_list)` | ||
| 738 | + /// indices to dereference for `CuQpOffsetCb` / `CuQpOffsetCr`. | ||
| 739 | + /// `None` is returned when the flag is 0: per §7.4.9.10 the | ||
| 740 | + /// offsets are then both 0 (no list dereference). | ||
| 741 | + #[must_use] | ||
| 742 | + pub fn offset_indices(&self) -> Option<u32> { | ||
| 743 | + if self.flag == 0 { | ||
| 744 | + None | ||
| 745 | + } else { | ||
| 746 | + // §7.4.9.10: when present, idx defaults to 0; absent ⇒ | ||
| 747 | + // also 0 (the cMax = 0 / not-signalled paths share the | ||
| 748 | + // same inferred value). | ||
| 749 | + Some(self.idx.unwrap_or(0)) | ||
| 750 | + } | ||
| 751 | + } | ||
| 752 | +} | ||
| 753 | + | ||
| 754 | +/// Decode the `cu_chroma_qp_offset` syntax pair (§7.3.8.11 / | ||
| 755 | +/// §7.4.9.10) from the CABAC engine, consuming one context for the | ||
| 756 | +/// FL `cu_chroma_qp_offset_flag` bin and (when the flag is 1 and | ||
| 757 | +/// `chroma_qp_offset_list_len_minus1 > 0`) one context for the TR | ||
| 758 | +/// prefix of `cu_chroma_qp_offset_idx`. All bins of both elements | ||
| 759 | +/// share `ctxInc = 0` per Table 9-48; the contexts live in separate | ||
| 760 | +/// Table 9-4 banks (Table 9-34 for the flag, Table 9-35 for the | ||
| 761 | +/// idx). | ||
| 762 | +/// | ||
| 763 | +/// `ctx_flag` and `ctx_idx` are the caller's | ||
| 764 | +/// `(pStateIdx, valMps)` state for the two contexts; they are | ||
| 765 | +/// mutated in place per §9.3.4.3.2.2 state transition. | ||
| 766 | +/// | ||
| 767 | +/// `chroma_qp_offset_list_len_minus1` is the PPS field that bounds | ||
| 768 | +/// the TR prefix; the function panics in debug if it exceeds 5 | ||
| 769 | +/// (the §7.4.3.3.1 `u(3)` field's upper bound). | ||
| 770 | +/// | ||
| 771 | +/// Returns the decoded [`CuChromaQpOffset`]. | ||
| 772 | +pub fn decode_cu_chroma_qp_offset( | ||
| 773 | + engine: &mut CabacEngine<'_>, | ||
| 774 | + ctx_flag: &mut ContextModel, | ||
| 775 | + ctx_idx: &mut ContextModel, | ||
| 776 | + chroma_qp_offset_list_len_minus1: u32, | ||
| 777 | +) -> Result<CuChromaQpOffset, CabacError> { | ||
| 778 | + debug_assert!( | ||
| 779 | + chroma_qp_offset_list_len_minus1 <= 5, | ||
| 780 | + "chroma_qp_offset_list_len_minus1 is a u(3) field bounded by 5 per §7.4.3.3.1" | ||
| 781 | + ); | ||
| 782 | + | ||
| 783 | + // §9.3.4.2.1 + Table 9-48 + Table 9-43: bin 0 of the FL flag | ||
| 784 | + // uses ctxInc = 0 and the FL cMax = 1 shape emits exactly one | ||
| 785 | + // bin. | ||
| 786 | + let flag = engine.decode_decision(ctx_flag)?; | ||
| 787 | + | ||
| 788 | + // §7.3.8.11: the idx is signalled only when the flag is 1 and | ||
| 789 | + // the list has more than one entry (else the TR cMax = 0 shape | ||
| 790 | + // emits no bins and the idx is inferred to be 0 per §7.4.9.10). | ||
| 791 | + let idx = if flag == 1 && chroma_qp_offset_list_len_minus1 > 0 { | ||
| 792 | + let c_max = cu_chroma_qp_offset_idx_tr_cmax(chroma_qp_offset_list_len_minus1); | ||
| 793 | + // §9.3.3.10 TR prefix with cRiceParam = 0; every bin uses | ||
| 794 | + // ctx_idx (Table 9-48 ctxInc = 0). | ||
| 795 | + let (prefix, _is_escape) = | ||
| 796 | + read_truncated_rice_prefix(c_max, |_bin_idx| engine.decode_decision(ctx_idx))?; | ||
| 797 | + // The TR escape (all-ones prefix == cMax) terminates the | ||
| 798 | + // idx — there is no suffix continuation for this element | ||
| 799 | + // (Table 9-43 has no follow-on EGk row). | ||
| 800 | + Some(prefix) | ||
| 801 | + } else { | ||
| 802 | + None | ||
| 803 | + }; | ||
| 804 | + | ||
| 805 | + Ok(CuChromaQpOffset { flag, idx }) | ||
| 806 | +} | ||
| 807 | + | ||
| 808 | +// --------------------------------------------------------------------- | ||
| 809 | +// cu_transquant_bypass_flag (§7.3.8.5 coding_unit() / §7.4.9.5) | ||
| 810 | +// PPS gate: transquant_bypass_enabled_flag (§7.4.3.3.1). Table 9-43 | ||
| 811 | +// FL binarization + Table 9-48 ctxInc + Table 9-8 ctxIdx initValue. | ||
| 812 | +// --------------------------------------------------------------------- | ||
| 813 | + | ||
| 814 | +/// Table 9-43 binarization shape for `cu_transquant_bypass_flag`: FL | ||
| 815 | +/// with `cMax = 1` (a single context-coded bin per CU). | ||
| 816 | +pub const CU_TRANSQUANT_BYPASS_FLAG_FL_CMAX: u32 = 1; | ||
| 817 | + | ||
| 818 | +/// FL-binarization bit count for `cu_transquant_bypass_flag`: one | ||
| 819 | +/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. | ||
| 820 | +pub const CU_TRANSQUANT_BYPASS_FLAG_FL_NBITS: u32 = 1; | ||
| 821 | + | ||
| 822 | +/// §9.3.4.2.1 / Table 9-48 row for `cu_transquant_bypass_flag`. Bin 0 | ||
| 823 | +/// is context-coded with `ctxInc = 0`; every later binIdx column is | ||
| 824 | +/// `na` (the FL `cMax = 1` shape only emits a single bin). | ||
| 825 | +/// | ||
| 826 | +/// The flag's Table 9-8 ctxIdx layout (`initValue = 154` at every | ||
| 827 | +/// initType slot — same `pStateIdx`/`valMps` start at all three | ||
| 828 | +/// slice-type initialisation rows) is consumed at slice-init scope; | ||
| 829 | +/// this layer hands back the bank-relative `ctxInc` only. | ||
| 830 | +#[must_use] | ||
| 831 | +pub fn cu_transquant_bypass_flag_ctx_inc() -> u32 { | ||
| 832 | + 0 | ||
| 833 | +} | ||
| 834 | + | ||
| 835 | +/// §7.4.9.5 — inferred value of `cu_transquant_bypass_flag` when the | ||
| 836 | +/// PPS gate `transquant_bypass_enabled_flag` is 0 and the element is | ||
| 837 | +/// not present on the wire. The spec mandates an inferred value of | ||
| 838 | +/// `0` (normal scaling-and-transform path). | ||
| 839 | +/// | ||
| 840 | +/// Exposed as a pure helper so the parser can branch on the PPS | ||
| 841 | +/// without entering the CABAC engine: when the PPS gate is off the | ||
| 842 | +/// caller skips [`decode_cu_transquant_bypass_flag`] entirely and | ||
| 843 | +/// records the inferred `0`. | ||
| 844 | +#[must_use] | ||
| 845 | +pub fn cu_transquant_bypass_flag_inferred() -> u8 { | ||
| 846 | + 0 | ||
| 847 | +} | ||
| 848 | + | ||
| 849 | +/// Decode `cu_transquant_bypass_flag` (§7.3.8.5 / §7.4.9.5) from the | ||
| 850 | +/// CABAC engine, consuming one context for the FL bin. | ||
| 851 | +/// | ||
| 852 | +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single | ||
| 853 | +/// Table 9-8 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per | ||
| 854 | +/// §9.3.4.3.2.2 state transition. | ||
| 855 | +/// | ||
| 856 | +/// The PPS gate `transquant_bypass_enabled_flag` (§7.4.3.3.1) is | ||
| 857 | +/// upstream of this primitive: when the gate is 0 the parser does | ||
| 858 | +/// **not** call this function — see [`cu_transquant_bypass_flag_inferred`] | ||
| 859 | +/// for the §7.4.9.5 inferred value. | ||
| 860 | +/// | ||
| 861 | +/// Returns the decoded `u8` (0 or 1) — 1 selects the §8.6 / §8.7 | ||
| 862 | +/// transquant-bypass passthrough for the current CU per §7.4.9.5. | ||
| 863 | +pub fn decode_cu_transquant_bypass_flag( | ||
| 864 | + engine: &mut CabacEngine<'_>, | ||
| 865 | + ctx: &mut ContextModel, | ||
| 866 | +) -> Result<u8, CabacError> { | ||
| 867 | + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape | ||
| 868 | + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table | ||
| 869 | + // 9-8 entry) per the Table 9-48 row. | ||
| 870 | + debug_assert_eq!( | ||
| 871 | + cu_transquant_bypass_flag_ctx_inc(), | ||
| 872 | + 0, | ||
| 873 | + "Table 9-48 row for cu_transquant_bypass_flag: bin 0 ctxInc = 0" | ||
| 874 | + ); | ||
| 875 | + engine.decode_decision(ctx) | ||
| 876 | +} | ||
| 877 | + | ||
| 878 | +// --------------------------------------------------------------------- | ||
| 879 | +// rqt_root_cbf (§7.3.8.5 coding_unit() / §7.4.9.5) | ||
| 880 | +// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-14 ctxIdx | ||
| 881 | +// initValue. Present only when the current coding unit is not | ||
| 882 | +// IntraPredMode (i.e. CuPredMode == MODE_INTER) and the cu_skip_flag | ||
| 883 | +// is 0; absent ⇒ inferred to 1 (the §7.4.9.5 / 2021 spec wording). | ||
| 884 | +// --------------------------------------------------------------------- | ||
| 885 | + | ||
| 886 | +/// Table 9-43 binarization shape for `rqt_root_cbf`: FL with `cMax = 1` | ||
| 887 | +/// (a single context-coded bin per inter CU). Marks whether the | ||
| 888 | +/// `transform_tree( )` syntax structure is present for the current | ||
| 889 | +/// coding unit (§7.4.9.5). | ||
| 890 | +pub const RQT_ROOT_CBF_FL_CMAX: u32 = 1; | ||
| 891 | + | ||
| 892 | +/// FL-binarization bit count for `rqt_root_cbf`: one context-coded bin | ||
| 893 | +/// per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. | ||
| 894 | +pub const RQT_ROOT_CBF_FL_NBITS: u32 = 1; | ||
| 895 | + | ||
| 896 | +/// §9.3.4.2.1 / Table 9-48 row for `rqt_root_cbf`. Bin 0 is | ||
| 897 | +/// context-coded with `ctxInc = 0`; every later binIdx column is `na` | ||
| 898 | +/// (the FL `cMax = 1` shape only emits a single bin). | ||
| 899 | +/// | ||
| 900 | +/// The flag's Table 9-14 ctxIdx layout has only the initType 1 and | ||
| 901 | +/// initType 2 slots populated (`initValue = 79` at both); initType 0 | ||
| 902 | +/// is `na` per Table 9-4, since `rqt_root_cbf` is only ever read in | ||
| 903 | +/// inter slices (§7.3.8.5 routes the read under | ||
| 904 | +/// `CuPredMode != MODE_INTRA && !cu_skip_flag`). This layer hands back | ||
| 905 | +/// the bank-relative `ctxInc` only; the Table 9-14 initValue plus | ||
| 906 | +/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init | ||
| 907 | +/// scope. | ||
| 908 | +#[must_use] | ||
| 909 | +pub fn rqt_root_cbf_ctx_inc() -> u32 { | ||
| 910 | + 0 | ||
| 911 | +} | ||
| 912 | + | ||
| 913 | +/// §7.4.9.5 — inferred value of `rqt_root_cbf` when the element is not | ||
| 914 | +/// present on the wire. The 2021 spec wording (V8/v8.0) mandates an | ||
| 915 | +/// inferred value of `1` (the `transform_tree( )` syntax structure is | ||
| 916 | +/// taken to be present); the V11/2026 revision conditions the | ||
| 917 | +/// inference on `!DcOnlyFlag[ x0 ][ y0 ]`, but the V8 baseline this | ||
| 918 | +/// rebuild targets is the unconditional 1. | ||
| 919 | +/// | ||
| 920 | +/// Exposed as a pure helper so the parser can branch without entering | ||
| 921 | +/// the CABAC engine when the §7.3.8.5 guard (`CuPredMode == MODE_INTRA | ||
| 922 | +/// || cu_skip_flag == 1`) selects the not-present path. | ||
| 923 | +#[must_use] | ||
| 924 | +pub fn rqt_root_cbf_inferred() -> u8 { | ||
| 925 | + 1 | ||
| 926 | +} | ||
| 927 | + | ||
| 928 | +/// Decode `rqt_root_cbf` (§7.3.8.5 / §7.4.9.5) from the CABAC engine, | ||
| 929 | +/// consuming one context for the FL bin. | ||
| 930 | +/// | ||
| 931 | +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single | ||
| 932 | +/// Table 9-14 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per | ||
| 933 | +/// §9.3.4.3.2.2 state transition. | ||
| 934 | +/// | ||
| 935 | +/// The §7.3.8.5 guard (`CuPredMode != MODE_INTRA && !cu_skip_flag`) is | ||
| 936 | +/// upstream of this primitive: when the guard fails the parser does | ||
| 937 | +/// **not** call this function — see [`rqt_root_cbf_inferred`] for the | ||
| 938 | +/// §7.4.9.5 inferred value. | ||
| 939 | +/// | ||
| 940 | +/// Returns the decoded `u8` (0 or 1) — 1 means the `transform_tree( )` | ||
| 941 | +/// syntax structure follows the current coding-unit body; 0 means the | ||
| 942 | +/// CU has no transform-tree (samples derive from prediction only per | ||
| 943 | +/// §7.4.9.5). | ||
| 944 | +pub fn decode_rqt_root_cbf( | ||
| 945 | + engine: &mut CabacEngine<'_>, | ||
| 946 | + ctx: &mut ContextModel, | ||
| 947 | +) -> Result<u8, CabacError> { | ||
| 948 | + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape | ||
| 949 | + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table | ||
| 950 | + // 9-14 entry) per the Table 9-48 row. | ||
| 951 | + debug_assert_eq!( | ||
| 952 | + rqt_root_cbf_ctx_inc(), | ||
| 953 | + 0, | ||
| 954 | + "Table 9-48 row for rqt_root_cbf: bin 0 ctxInc = 0" | ||
| 955 | + ); | ||
| 956 | + engine.decode_decision(ctx) | ||
| 957 | +} | ||
| 958 | + | ||
| 959 | +// --------------------------------------------------------------------- | ||
| 960 | +// merge_flag (§7.3.8.6 prediction_unit() / §7.4.9.6) | ||
| 961 | +// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-15 ctxIdx | ||
| 962 | +// initValue. Read in the §7.3.8.6 `else /* MODE_INTER */` branch | ||
| 963 | +// (i.e. cu_skip_flag == 0); when present and 1 the inter-prediction | ||
| 964 | +// parameters are inferred from a neighbouring inter partition | ||
| 965 | +// (merge_idx follows), when 0 the explicit motion fields | ||
| 966 | +// (inter_pred_idc / ref_idx / mvp) are coded. Absent ⇒ inferred per | ||
| 967 | +// §7.4.9.6 from CuPredMode (MODE_SKIP ⇒ 1, otherwise 0). | ||
| 968 | +// --------------------------------------------------------------------- | ||
| 969 | + | ||
| 970 | +/// Table 9-43 binarization shape for `merge_flag`: FL with `cMax = 1` | ||
| 971 | +/// (a single context-coded bin per non-skip inter prediction unit). | ||
| 972 | +/// Selects between the merge path (value 1 — inter-prediction | ||
| 973 | +/// parameters inferred from a neighbouring inter-predicted partition) | ||
| 974 | +/// and the explicit-motion path (value 0) per §7.4.9.6. | ||
| 975 | +pub const MERGE_FLAG_FL_CMAX: u32 = 1; | ||
| 976 | + | ||
| 977 | +/// FL-binarization bit count for `merge_flag`: one context-coded bin | ||
| 978 | +/// per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. | ||
| 979 | +pub const MERGE_FLAG_FL_NBITS: u32 = 1; | ||
| 980 | + | ||
| 981 | +/// §9.3.4.2.1 / Table 9-48 row for `merge_flag`. Bin 0 is | ||
| 982 | +/// context-coded with `ctxInc = 0`; every later binIdx column is `na` | ||
| 983 | +/// (the FL `cMax = 1` shape only emits a single bin). | ||
| 984 | +/// | ||
| 985 | +/// The flag's Table 9-15 ctxIdx layout has only the initType 1 and | ||
| 986 | +/// initType 2 slots populated (`initValue = 110` at initType 1, | ||
| 987 | +/// `initValue = 154` at initType 2); initType 0 is `na` in Table 9-4 | ||
| 988 | +/// because `merge_flag` is only ever read in inter (P/B) slices — the | ||
| 989 | +/// §7.3.8.6 `prediction_unit( )` read sits under the coding-unit's | ||
| 990 | +/// inter path (`CuPredMode != MODE_INTRA && !cu_skip_flag`), which is | ||
| 991 | +/// unreachable in an I slice. This layer hands back the bank-relative | ||
| 992 | +/// `ctxInc` only; the Table 9-15 initValue plus Table 9-4 | ||
| 993 | +/// initType-to-ctxIdx mapping is consumed at slice-init scope (see | ||
| 994 | +/// `ctx_init::TABLE_9_15_MERGE_FLAG`). | ||
| 995 | +#[must_use] | ||
| 996 | +pub fn merge_flag_ctx_inc() -> u32 { | ||
| 997 | + 0 | ||
| 998 | +} | ||
| 999 | + | ||
| 1000 | +/// §7.4.9.6 — inferred value of `merge_flag` when the element is not | ||
| 1001 | +/// present on the wire. The §7.3.8.6 guard that suppresses the read is | ||
| 1002 | +/// `cu_skip_flag == 1` (the skip path codes only `merge_idx`); the | ||
| 1003 | +/// §7.4.9.6 inference is then: | ||
| 1004 | +/// | ||
| 1005 | +/// * If `CuPredMode[ x0 ][ y0 ]` is equal to `MODE_SKIP`, | ||
| 1006 | +/// `merge_flag` is inferred to be equal to 1. | ||
| 1007 | +/// * Otherwise, `merge_flag` is inferred to be equal to 0. | ||
| 1008 | +/// | ||
| 1009 | +/// `cu_pred_mode` is the §7.4.9.5 prediction mode of the current | ||
| 1010 | +/// coding unit. The only not-present path the §7.3.8.6 syntax reaches | ||
| 1011 | +/// is the `cu_skip_flag == 1` branch, whose CuPredMode is | ||
| 1012 | +/// [`CuPredMode::Skip`] per §7.4.9.5 — so this returns 1 for | ||
| 1013 | +/// [`CuPredMode::Skip`] and 0 for the inter/intra modes (which would | ||
| 1014 | +/// only arise from a caller bug, since a present `merge_flag` is | ||
| 1015 | +/// decoded rather than inferred on those paths). | ||
| 1016 | +/// | ||
| 1017 | +/// Exposed as a pure helper so the parser can branch without entering | ||
| 1018 | +/// the CABAC engine when the §7.3.8.6 skip path selects the | ||
| 1019 | +/// not-present case. | ||
| 1020 | +#[must_use] | ||
| 1021 | +pub fn merge_flag_inferred(cu_pred_mode: CuPredMode) -> u8 { | ||
| 1022 | + // §7.4.9.6: CuPredMode == MODE_SKIP ⇒ 1, otherwise ⇒ 0. | ||
| 1023 | + u8::from(cu_pred_mode == CuPredMode::Skip) | ||
| 1024 | +} | ||
| 1025 | + | ||
| 1026 | +/// Decode `merge_flag` (§7.3.8.6 / §7.4.9.6) from the CABAC engine, | ||
| 1027 | +/// consuming one context for the FL bin. | ||
| 1028 | +/// | ||
| 1029 | +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single | ||
| 1030 | +/// Table 9-15 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per | ||
| 1031 | +/// §9.3.4.3.2.2 state transition. | ||
| 1032 | +/// | ||
| 1033 | +/// The §7.3.8.6 guard (the `else /* MODE_INTER */` branch — i.e. | ||
| 1034 | +/// `cu_skip_flag == 0`) is upstream of this primitive: when the CU | ||
| 1035 | +/// takes the skip path the parser does **not** call this function — | ||
| 1036 | +/// see [`merge_flag_inferred`] for the §7.4.9.6 not-present value. | ||
| 1037 | +/// | ||
| 1038 | +/// Returns the decoded `u8` (0 or 1) — 1 selects the merge path (the | ||
| 1039 | +/// inter-prediction parameters are inferred from a neighbouring | ||
| 1040 | +/// inter-predicted partition, `merge_idx` follows per §7.3.8.6); 0 | ||
| 1041 | +/// selects the explicit-motion path (`inter_pred_idc` / `ref_idx_lX` / | ||
| 1042 | +/// `mvp_lX_flag` / `mvd_coding` are coded). | ||
| 1043 | +pub fn decode_merge_flag( | ||
| 1044 | + engine: &mut CabacEngine<'_>, | ||
| 1045 | + ctx: &mut ContextModel, | ||
| 1046 | +) -> Result<u8, CabacError> { | ||
| 1047 | + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape | ||
| 1048 | + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table | ||
| 1049 | + // 9-15 entry) per the Table 9-48 row. | ||
| 1050 | + debug_assert_eq!( | ||
| 1051 | + merge_flag_ctx_inc(), | ||
| 1052 | + 0, | ||
| 1053 | + "Table 9-48 row for merge_flag: bin 0 ctxInc = 0" | ||
| 1054 | + ); | ||
| 1055 | + engine.decode_decision(ctx) | ||
| 1056 | +} | ||
| 1057 | + | ||
| 1058 | +// --------------------------------------------------------------------- | ||
| 1059 | +// pred_mode_flag (§7.3.8.5 coding_unit() / §7.4.9.5) | ||
| 1060 | +// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-10 ctxIdx | ||
| 1061 | +// initValue. Present only when the slice is P or B (slice_type != I) | ||
| 1062 | +// and cu_skip_flag == 0; absent ⇒ CuPredMode is derived per §7.4.9.5 | ||
| 1063 | +// from slice_type and cu_skip_flag without entering the engine. | ||
| 1064 | +// --------------------------------------------------------------------- | ||
| 1065 | + | ||
| 1066 | +/// Table 9-43 binarization shape for `pred_mode_flag`: FL with | ||
| 1067 | +/// `cMax = 1` (a single context-coded bin per non-skip P/B coding | ||
| 1068 | +/// unit). Selects between MODE_INTER (value 0) and MODE_INTRA (value | ||
| 1069 | +/// 1) per §7.4.9.5. | ||
| 1070 | +pub const PRED_MODE_FLAG_FL_CMAX: u32 = 1; | ||
| 1071 | + | ||
| 1072 | +/// FL-binarization bit count for `pred_mode_flag`: one context-coded | ||
| 1073 | +/// bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. | ||
| 1074 | +pub const PRED_MODE_FLAG_FL_NBITS: u32 = 1; | ||
| 1075 | + | ||
| 1076 | +/// §9.3.4.2.1 / Table 9-48 row for `pred_mode_flag`. Bin 0 is | ||
| 1077 | +/// context-coded with `ctxInc = 0`; every later binIdx column is `na` | ||
| 1078 | +/// (the FL `cMax = 1` shape only emits a single bin). | ||
| 1079 | +/// | ||
| 1080 | +/// The flag's Table 9-10 ctxIdx layout has only the initType 1 and | ||
| 1081 | +/// initType 2 slots populated (`initValue = 149` at initType 1, | ||
| 1082 | +/// `initValue = 134` at initType 2); initType 0 is `na` in Table 9-4 | ||
| 1083 | +/// because the §7.3.8.5 `slice_type != I` guard skips the read for I | ||
| 1084 | +/// slices entirely. This layer hands back the bank-relative `ctxInc` | ||
| 1085 | +/// only; the Table 9-10 initValue plus Table 9-4 initType-to-ctxIdx | ||
| 1086 | +/// mapping is consumed at slice-init scope. | ||
| 1087 | +#[must_use] | ||
| 1088 | +pub fn pred_mode_flag_ctx_inc() -> u32 { | ||
| 1089 | + 0 | ||
| 1090 | +} | ||
| 1091 | + | ||
| 1092 | +/// §7.4.9.5 / §9.5.1 — the coding-unit prediction mode. Selected by | ||
| 1093 | +/// `pred_mode_flag` (when present on the wire) or inferred from | ||
| 1094 | +/// slice-level state (when not present), per §7.4.9.5. | ||
| 1095 | +/// | ||
| 1096 | +/// `pred_mode_flag == 0` maps to [`CuPredMode::Inter`]; | ||
| 1097 | +/// `pred_mode_flag == 1` maps to [`CuPredMode::Intra`]. | ||
| 1098 | +/// [`CuPredMode::Skip`] is reachable only via the §7.4.9.5 | ||
| 1099 | +/// not-present inference path: a P or B slice CU whose `cu_skip_flag` | ||
| 1100 | +/// is 1 and whose `pred_mode_flag` was therefore not coded. | ||
| 1101 | +/// | ||
| 1102 | +/// The enum is local to the binarization module because no other | ||
| 1103 | +/// module currently expresses CuPredMode in code; the | ||
| 1104 | +/// `coding_unit( )` syntax walker may promote it to a wider type in | ||
| 1105 | +/// a future round. | ||
| 1106 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 1107 | +pub enum CuPredMode { | ||
| 1108 | + /// MODE_INTER — inter-picture prediction (samples derived from a | ||
| 1109 | + /// reference picture). Reachable from `pred_mode_flag == 0` (P | ||
| 1110 | + /// or B slice, non-skip CU). | ||
| 1111 | + Inter, | ||
| 1112 | + /// MODE_INTRA — intra-picture prediction (samples derived from | ||
| 1113 | + /// neighbouring reconstructed samples in the current picture). | ||
| 1114 | + /// Reachable from `pred_mode_flag == 1` and from the I-slice | ||
| 1115 | + /// not-present inference (§7.4.9.5). | ||
| 1116 | + Intra, | ||
| 1117 | + /// MODE_SKIP — inter-prediction skip path (no residual, no | ||
| 1118 | + /// `pred_mode_flag`, no transform tree). Reachable only from | ||
| 1119 | + /// §7.4.9.5 not-present inference when `slice_type != I` and | ||
| 1120 | + /// `cu_skip_flag == 1`. | ||
| 1121 | + Skip, | ||
| 1122 | +} | ||
| 1123 | + | ||
| 1124 | +/// Map a decoded `pred_mode_flag` value to [`CuPredMode`] per | ||
| 1125 | +/// §7.4.9.5: `0 ⇒ MODE_INTER`, `1 ⇒ MODE_INTRA`. The mapping is | ||
| 1126 | +/// total over the FL `cMax = 1` shape (any other input is rejected | ||
| 1127 | +/// in debug builds; release builds fall back to MODE_INTRA to keep | ||
| 1128 | +/// the function `must_use`-friendly without panicking on accidental | ||
| 1129 | +/// out-of-range inputs). | ||
| 1130 | +#[must_use] | ||
| 1131 | +pub fn cu_pred_mode_from_flag(pred_mode_flag: u8) -> CuPredMode { | ||
| 1132 | + debug_assert!( | ||
| 1133 | + pred_mode_flag <= 1, | ||
| 1134 | + "pred_mode_flag is FL cMax = 1 (Table 9-43); decoded value must be 0 or 1" | ||
| 1135 | + ); | ||
| 1136 | + if pred_mode_flag == 0 { | ||
| 1137 | + CuPredMode::Inter | ||
| 1138 | + } else { | ||
| 1139 | + CuPredMode::Intra | ||
| 1140 | + } | ||
| 1141 | +} | ||
| 1142 | + | ||
| 1143 | +/// §7.4.9.5 — derive [`CuPredMode`] for a coding unit whose | ||
| 1144 | +/// `pred_mode_flag` is not present on the wire. The §7.3.8.5 guard | ||
| 1145 | +/// that suppresses the read is `slice_type == I` (no flag is coded | ||
| 1146 | +/// because the slice is purely intra) or `cu_skip_flag == 1` (the | ||
| 1147 | +/// skip path bypasses the flag). | ||
| 1148 | +/// | ||
| 1149 | +/// `slice_type_is_i` is `true` iff the current slice has | ||
| 1150 | +/// `slice_type == I` per §7.4.7.1. | ||
| 1151 | +/// `cu_skip_flag` is the §7.3.8.5 / §7.4.9.5 decoded skip flag (or | ||
| 1152 | +/// the 0-inferred value when `slice_type == I`). | ||
| 1153 | +/// | ||
| 1154 | +/// The §7.4.9.5 derivation: | ||
| 1155 | +/// | ||
| 1156 | +/// * If the slice is I, `CuPredMode` is inferred to MODE_INTRA | ||
| 1157 | +/// regardless of `cu_skip_flag` (which is itself not coded for | ||
| 1158 | +/// I slices and inferred to 0 per §7.4.9.5). | ||
| 1159 | +/// * Otherwise (P or B slice), the only path that reaches this | ||
| 1160 | +/// helper is `cu_skip_flag == 1`; the spec then infers | ||
| 1161 | +/// `CuPredMode = MODE_SKIP`. A `cu_skip_flag == 0` input would | ||
| 1162 | +/// contradict the §7.3.8.5 guard (the flag *would* be present | ||
| 1163 | +/// and decoded); the function asserts this in debug builds and | ||
| 1164 | +/// falls back to MODE_INTER in release builds to avoid panicking | ||
| 1165 | +/// on a caller bug. | ||
| 1166 | +#[must_use] | ||
| 1167 | +pub fn pred_mode_flag_inferred_cu_pred_mode(slice_type_is_i: bool, cu_skip_flag: u8) -> CuPredMode { | ||
| 1168 | + if slice_type_is_i { | ||
| 1169 | + // §7.4.9.5: "If slice_type is equal to I, CuPredMode[ x ][ y ] | ||
| 1170 | + // is inferred to be equal to MODE_INTRA." cu_skip_flag is not | ||
| 1171 | + // coded for I slices (§7.3.8.5 `if( slice_type != I )` guard) | ||
| 1172 | + // and is itself inferred to 0; the I-slice branch is therefore | ||
| 1173 | + // unconditional on the skip flag. | ||
| 1174 | + CuPredMode::Intra | ||
| 1175 | + } else { | ||
| 1176 | + // §7.4.9.5: "Otherwise (slice_type is equal to P or B), when | ||
| 1177 | + // cu_skip_flag[ x0 ][ y0 ] is equal to 1, CuPredMode[ x ][ y ] | ||
| 1178 | + // is inferred to be equal to MODE_SKIP." The §7.3.8.5 | ||
| 1179 | + // pred_mode_flag read is gated on `!cu_skip_flag[ x0 ][ y0 ]`, | ||
| 1180 | + // so the only way this branch is reached on a P/B slice is | ||
| 1181 | + // with cu_skip_flag == 1. | ||
| 1182 | + debug_assert_eq!( | ||
| 1183 | + cu_skip_flag, 1, | ||
| 1184 | + "§7.4.9.5: pred_mode_flag not-present on a P/B slice requires cu_skip_flag == 1" | ||
| 1185 | + ); | ||
| 1186 | + CuPredMode::Skip | ||
| 1187 | + } | ||
| 1188 | +} | ||
| 1189 | + | ||
| 1190 | +/// Decode `pred_mode_flag` (§7.3.8.5 / §7.4.9.5) from the CABAC | ||
| 1191 | +/// engine, consuming one context for the FL bin. | ||
| 1192 | +/// | ||
| 1193 | +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single | ||
| 1194 | +/// Table 9-10 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place | ||
| 1195 | +/// per §9.3.4.3.2.2 state transition. | ||
| 1196 | +/// | ||
| 1197 | +/// The §7.3.8.5 guard (`slice_type != I && !cu_skip_flag`) is | ||
| 1198 | +/// upstream of this primitive: when the guard fails the parser does | ||
| 1199 | +/// **not** call this function — see | ||
| 1200 | +/// [`pred_mode_flag_inferred_cu_pred_mode`] for the §7.4.9.5 | ||
| 1201 | +/// not-present derivation. | ||
| 1202 | +/// | ||
| 1203 | +/// Returns the decoded `u8` (0 or 1) — 0 selects MODE_INTER per | ||
| 1204 | +/// §7.4.9.5 (`CuPredMode = MODE_INTER`), 1 selects MODE_INTRA | ||
| 1205 | +/// (`CuPredMode = MODE_INTRA`). See [`cu_pred_mode_from_flag`] to | ||
| 1206 | +/// fold the result into the [`CuPredMode`] enum. | ||
| 1207 | +pub fn decode_pred_mode_flag( | ||
| 1208 | + engine: &mut CabacEngine<'_>, | ||
| 1209 | + ctx: &mut ContextModel, | ||
| 1210 | +) -> Result<u8, CabacError> { | ||
| 1211 | + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape | ||
| 1212 | + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table | ||
| 1213 | + // 9-10 entry) per the Table 9-48 row. | ||
| 1214 | + debug_assert_eq!( | ||
| 1215 | + pred_mode_flag_ctx_inc(), | ||
| 1216 | + 0, | ||
| 1217 | + "Table 9-48 row for pred_mode_flag: bin 0 ctxInc = 0" | ||
| 1218 | + ); | ||
| 1219 | + engine.decode_decision(ctx) | ||
| 1220 | +} | ||
| 1221 | + | ||
| 1222 | +// --------------------------------------------------------------------- | ||
| 1223 | +// prev_intra_luma_pred_flag (§7.3.8.5 coding_unit() / §7.4.9.2) | ||
| 1224 | +// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-12 ctxIdx | ||
| 1225 | +// initValue. Read once per luma prediction block of an intra CU (the | ||
| 1226 | +// §7.3.8.5 `for( j ) for( i )` PB loop). When the flag is 1 the luma | ||
| 1227 | +// intra mode is taken from the §8.4.2 most-probable-mode list (mpm_idx | ||
| 1228 | +// follows); when 0 it comes from rem_intra_luma_pred_mode. There is no | ||
| 1229 | +// not-present inference: the §7.3.8.5 loop always reads it. | ||
| 1230 | +// --------------------------------------------------------------------- | ||
| 1231 | + | ||
| 1232 | +/// Table 9-43 binarization shape for `prev_intra_luma_pred_flag`: FL | ||
| 1233 | +/// with `cMax = 1` (a single context-coded bin per luma prediction | ||
| 1234 | +/// block of an intra CU). Selects between the MPM-list mode source | ||
| 1235 | +/// (value 1) and the remaining-mode field (value 0) per §7.4.9.2. | ||
| 1236 | +pub const PREV_INTRA_LUMA_PRED_FLAG_FL_CMAX: u32 = 1; | ||
| 1237 | + | ||
| 1238 | +/// FL-binarization bit count for `prev_intra_luma_pred_flag`: one | ||
| 1239 | +/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. | ||
| 1240 | +pub const PREV_INTRA_LUMA_PRED_FLAG_FL_NBITS: u32 = 1; | ||
| 1241 | + | ||
| 1242 | +/// §9.3.4.2.1 / Table 9-48 row for `prev_intra_luma_pred_flag`. Bin 0 | ||
| 1243 | +/// is context-coded with `ctxInc = 0`; every later binIdx column is | ||
| 1244 | +/// `na` (the FL `cMax = 1` shape only emits a single bin). | ||
| 1245 | +/// | ||
| 1246 | +/// Table 9-12 lists three ctxIdx slots with | ||
| 1247 | +/// `initValue = {184, 154, 183}` for initType 0, 1 and 2 — the element | ||
| 1248 | +/// is read in I, P and B slices (intra CUs occur in every slice type), | ||
| 1249 | +/// so all three initType slots are populated (unlike `pred_mode_flag`, | ||
| 1250 | +/// whose initType 0 column is `na`). This layer hands back the | ||
| 1251 | +/// bank-relative `ctxInc` only; the Table 9-12 initValue plus the | ||
| 1252 | +/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init | ||
| 1253 | +/// scope. | ||
| 1254 | +#[must_use] | ||
| 1255 | +pub fn prev_intra_luma_pred_flag_ctx_inc() -> u32 { | ||
| 1256 | + 0 | ||
| 1257 | +} | ||
| 1258 | + | ||
| 1259 | +/// §7.4.9.2 — the source of a luma prediction block's intra mode, | ||
| 1260 | +/// selected by `prev_intra_luma_pred_flag`. | ||
| 1261 | +/// | ||
| 1262 | +/// `prev_intra_luma_pred_flag == 1` maps to [`LumaIntraModeSource::Mpm`] | ||
| 1263 | +/// (the §8.4.2 most-probable-mode candidate list; `mpm_idx` follows in | ||
| 1264 | +/// the §7.3.8.5 syntax to select among the candidates). | ||
| 1265 | +/// `prev_intra_luma_pred_flag == 0` maps to | ||
| 1266 | +/// [`LumaIntraModeSource::Remaining`] (the §7.3.8.5 | ||
| 1267 | +/// `rem_intra_luma_pred_mode` field carries the mode directly). | ||
| 1268 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| 1269 | +pub enum LumaIntraModeSource { | ||
| 1270 | + /// The luma intra mode is taken from the §8.4.2 most-probable-mode | ||
| 1271 | + /// candidate list. Reachable from `prev_intra_luma_pred_flag == 1`; | ||
| 1272 | + /// the §7.3.8.5 `mpm_idx` element follows to pick a candidate. | ||
| 1273 | + Mpm, | ||
| 1274 | + /// The luma intra mode is carried directly by the §7.3.8.5 | ||
| 1275 | + /// `rem_intra_luma_pred_mode` field. Reachable from | ||
| 1276 | + /// `prev_intra_luma_pred_flag == 0`. | ||
| 1277 | + Remaining, | ||
| 1278 | +} | ||
| 1279 | + | ||
| 1280 | +/// Map a decoded `prev_intra_luma_pred_flag` value to | ||
| 1281 | +/// [`LumaIntraModeSource`] per §7.4.9.2 / §7.3.8.5: `1 ⇒ Mpm`, | ||
| 1282 | +/// `0 ⇒ Remaining`. The mapping is total over the FL `cMax = 1` shape | ||
| 1283 | +/// (any other input is rejected in debug builds; release builds fall | ||
| 1284 | +/// back to [`LumaIntraModeSource::Remaining`] to avoid panicking on an | ||
| 1285 | +/// accidental out-of-range input). | ||
| 1286 | +#[must_use] | ||
| 1287 | +pub fn luma_intra_mode_source_from_flag(prev_intra_luma_pred_flag: u8) -> LumaIntraModeSource { | ||
| 1288 | + debug_assert!( | ||
| 1289 | + prev_intra_luma_pred_flag <= 1, | ||
| 1290 | + "prev_intra_luma_pred_flag is FL cMax = 1 (Table 9-43); decoded value must be 0 or 1" | ||
| 1291 | + ); | ||
| 1292 | + if prev_intra_luma_pred_flag == 1 { | ||
| 1293 | + LumaIntraModeSource::Mpm | ||
| 1294 | + } else { | ||
| 1295 | + LumaIntraModeSource::Remaining | ||
| 1296 | + } | ||
| 1297 | +} | ||
| 1298 | + | ||
| 1299 | +/// Decode `prev_intra_luma_pred_flag` (§7.3.8.5 / §7.4.9.2) from the | ||
| 1300 | +/// CABAC engine, consuming one context for the FL bin. | ||
| 1301 | +/// | ||
| 1302 | +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single | ||
| 1303 | +/// Table 9-12 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per | ||
| 1304 | +/// the §9.3.4.3.2.2 state transition. | ||
| 1305 | +/// | ||
| 1306 | +/// The §7.3.8.5 intra-PB loop always reaches this read for an intra CU | ||
| 1307 | +/// (there is no not-present inference rule for this element), so the | ||
| 1308 | +/// parser unconditionally calls this primitive once per luma | ||
| 1309 | +/// prediction block. | ||
| 1310 | +/// | ||
| 1311 | +/// Returns the decoded `u8` (0 or 1) — 1 selects the §8.4.2 | ||
| 1312 | +/// most-probable-mode source (`mpm_idx` follows), 0 selects the | ||
| 1313 | +/// `rem_intra_luma_pred_mode` source. See | ||
| 1314 | +/// [`luma_intra_mode_source_from_flag`] to fold the result into the | ||
| 1315 | +/// [`LumaIntraModeSource`] enum. | ||
| 1316 | +pub fn decode_prev_intra_luma_pred_flag( | ||
| 1317 | + engine: &mut CabacEngine<'_>, | ||
| 1318 | + ctx: &mut ContextModel, | ||
| 1319 | +) -> Result<u8, CabacError> { | ||
| 1320 | + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape | ||
| 1321 | + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table | ||
| 1322 | + // 9-12 entry) per the Table 9-48 row. | ||
| 1323 | + debug_assert_eq!( | ||
| 1324 | + prev_intra_luma_pred_flag_ctx_inc(), | ||
| 1325 | + 0, | ||
| 1326 | + "Table 9-48 row for prev_intra_luma_pred_flag: bin 0 ctxInc = 0" | ||
| 1327 | + ); | ||
| 1328 | + engine.decode_decision(ctx) | ||
| 1329 | +} | ||
| 1330 | + | ||
| 1331 | +// --------------------------------------------------------------------- | ||
| 1332 | +// mpm_idx / rem_intra_luma_pred_mode (§7.3.8.5 coding_unit() / §7.4.9.2) | ||
| 1333 | +// Table 9-43 binarization + Table 9-48 (both fully bypass-coded). These | ||
| 1334 | +// are the two §7.3.8.5 intra-PB luma-mode fields that follow | ||
| 1335 | +// prev_intra_luma_pred_flag: when the flag is 1 the §8.4.2 candidate | ||
| 1336 | +// list is selected and `mpm_idx` (TR cMax = 2, cRiceParam = 0) picks | ||
| 1337 | +// among the three candidates; when 0 `rem_intra_luma_pred_mode` | ||
| 1338 | +// (FL cMax = 31) carries the residual mode directly. Neither element is | ||
| 1339 | +// context-coded — Table 9-48 marks every bin `bypass` — so the slice | ||
| 1340 | +// parser reads them through the §9.3.4.3.4 bypass arithmetic decoder | ||
| 1341 | +// without allocating a context model. Presence is exactly the | ||
| 1342 | +// LumaIntraModeSource selection: Mpm ⇒ mpm_idx present, Remaining ⇒ | ||
| 1343 | +// rem_intra_luma_pred_mode present (the two are mutually exclusive per | ||
| 1344 | +// the §7.3.8.5 `if( prev_intra_luma_pred_flag ) … else …` syntax). | ||
| 1345 | +// --------------------------------------------------------------------- | ||
| 1346 | + | ||
| 1347 | +/// Table 9-43 binarization shape for `mpm_idx`: TR with `cMax = 2` and | ||
| 1348 | +/// `cRiceParam = 0`. The TR prefix with `cRiceParam = 0` collapses to | ||
| 1349 | +/// truncated-unary, so the on-wire string is `0`, `10`, or `11` for the | ||
| 1350 | +/// three values 0, 1, 2 — at most two bypass bins (Table 9-48 marks | ||
| 1351 | +/// bin 0 and bin 1 `bypass`, binIdx ≥ 2 `na`). | ||
| 1352 | +pub const MPM_IDX_TR_CMAX: u32 = 2; | ||
| 1353 | + | ||
| 1354 | +/// `cRiceParam` for the `mpm_idx` TR binarization (Table 9-43): 0. With | ||
| 1355 | +/// `cRiceParam = 0` the §9.3.3.10 TR has no Rice suffix and the prefix | ||
| 1356 | +/// is plain truncated-unary. | ||
| 1357 | +pub const MPM_IDX_TR_C_RICE_PARAM: u32 = 0; | ||
| 1358 | + | ||
| 1359 | +/// Table 9-43 binarization shape for `rem_intra_luma_pred_mode`: FL with | ||
| 1360 | +/// `cMax = 31`. The §9.3.3.5 derivation gives | ||
| 1361 | +/// `fixedLength = Ceil(Log2(cMax + 1)) = Ceil(Log2(32)) = 5`, so the | ||
| 1362 | +/// on-wire string is exactly five bypass bins (Table 9-48 marks | ||
| 1363 | +/// binIdx 0..=4 `bypass`, binIdx 5 `na`) read MSB-first. | ||
| 1364 | +pub const REM_INTRA_LUMA_PRED_MODE_FL_CMAX: u32 = 31; | ||
| 1365 | + | ||
| 1366 | +/// §9.3.3.5 — bit width of the FL string for `rem_intra_luma_pred_mode`. | ||
| 1367 | +/// | ||
| 1368 | +/// `Ceil(Log2(REM_INTRA_LUMA_PRED_MODE_FL_CMAX + 1)) = Ceil(Log2(32)) | ||
| 1369 | +/// = 5`. The decoded 5-bit value is the §8.4.2 step-2 starting point | ||
| 1370 | +/// (`IntraPredModeY` before the candModeList increment pass). | ||
| 1371 | +pub const REM_INTRA_LUMA_PRED_MODE_FL_NBITS: u32 = 5; | ||
| 1372 | + | ||
| 1373 | +/// Decode `mpm_idx` (§7.3.8.5 / §7.4.9.2) from the CABAC engine. | ||
| 1374 | +/// | ||
| 1375 | +/// Read when `prev_intra_luma_pred_flag == 1` | ||
| 1376 | +/// ([`LumaIntraModeSource::Mpm`]): the §8.4.2 derivation sets | ||
| 1377 | +/// `IntraPredModeY = candModeList[ mpm_idx ]`, so the returned value is | ||
| 1378 | +/// the index into the three-entry most-probable-mode candidate list and | ||
| 1379 | +/// is always in `0..=2`. | ||
| 1380 | +/// | ||
| 1381 | +/// Binarization is TR with `cMax = 2`, `cRiceParam = 0` (Table 9-43) and | ||
| 1382 | +/// every bin is bypass-coded (Table 9-48), so this reads the | ||
| 1383 | +/// truncated-unary prefix straight from the §9.3.4.3.4 bypass decoder: | ||
| 1384 | +/// a `0` bin terminates immediately (value 0), otherwise a second bin | ||
| 1385 | +/// distinguishes value 1 (`10`) from value 2 (`11`). No context model is | ||
| 1386 | +/// consumed. | ||
| 1387 | +pub fn decode_mpm_idx(engine: &mut CabacEngine<'_>) -> Result<u8, CabacError> { | ||
| 1388 | + // §9.3.3.10 TR prefix with cRiceParam = 0 driven entirely by the | ||
| 1389 | + // bypass decoder. `is_escape` (all `cMax` bins were 1) is the | ||
| 1390 | + // value == cMax case; with cRiceParam = 0 there is no suffix to | ||
| 1391 | + // read, so the prefix value is the final value either way. | ||
| 1392 | + let (value, _is_escape) = | ||
| 1393 | + read_truncated_rice_prefix(MPM_IDX_TR_CMAX, |_bin_idx| engine.decode_bypass())?; | ||
| 1394 | + debug_assert!( | ||
| 1395 | + value <= MPM_IDX_TR_CMAX, | ||
| 1396 | + "mpm_idx is TR cMax = 2 (Table 9-43); decoded value must be in 0..=2" | ||
| 1397 | + ); | ||
| 1398 | + Ok(value as u8) | ||
| 1399 | +} | ||
| 1400 | + | ||
| 1401 | +/// Decode `rem_intra_luma_pred_mode` (§7.3.8.5 / §7.4.9.2) from the | ||
| 1402 | +/// CABAC engine. | ||
| 1403 | +/// | ||
| 1404 | +/// Read when `prev_intra_luma_pred_flag == 0` | ||
| 1405 | +/// ([`LumaIntraModeSource::Remaining`]): the §8.4.2 step-2 derivation | ||
| 1406 | +/// seeds `IntraPredModeY = rem_intra_luma_pred_mode`, then increments it | ||
| 1407 | +/// once for each sorted candModeList entry it meets or exceeds. The | ||
| 1408 | +/// returned value is the pre-increment seed and is always in `0..=31`. | ||
| 1409 | +/// | ||
| 1410 | +/// Binarization is FL with `cMax = 31` (Table 9-43) and every bin is | ||
| 1411 | +/// bypass-coded (Table 9-48), so this reads exactly five bypass bins | ||
| 1412 | +/// MSB-first via [`CabacEngine::decode_bypass_bits`]. No context model | ||
| 1413 | +/// is consumed. | ||
| 1414 | +pub fn decode_rem_intra_luma_pred_mode(engine: &mut CabacEngine<'_>) -> Result<u8, CabacError> { | ||
| 1415 | + let value = engine.decode_bypass_bits(REM_INTRA_LUMA_PRED_MODE_FL_NBITS as u8)?; | ||
| 1416 | + debug_assert!( | ||
| 1417 | + value <= REM_INTRA_LUMA_PRED_MODE_FL_CMAX, | ||
| 1418 | + "rem_intra_luma_pred_mode is FL cMax = 31 (Table 9-43); decoded value must be in 0..=31" | ||
| 1419 | + ); | ||
| 1420 | + Ok(value as u8) | ||
| 1421 | +} | ||
| 1422 | + | ||
| 1423 | +// --------------------------------------------------------------------- | ||
| 1424 | +// IntraPredModeY derivation (§8.4.2 — derivation process for luma intra | ||
| 1425 | +// prediction mode). This is the process the §7.3.8.5 luma-mode signalling | ||
| 1426 | +// group (prev_intra_luma_pred_flag, mpm_idx, rem_intra_luma_pred_mode) | ||
| 1427 | +// feeds: given the two §8.4.2-step-2 candidate neighbour modes | ||
| 1428 | +// candIntraPredModeA / candIntraPredModeB it builds the three-entry | ||
| 1429 | +// candModeList (step 3) and then resolves IntraPredModeY from the | ||
| 1430 | +// signalled fields (step 4 — either candModeList[ mpm_idx ] on the Mpm | ||
| 1431 | +// path, or rem_intra_luma_pred_mode passed through the sorted-list | ||
| 1432 | +// increment pass on the Remaining path). | ||
| 1433 | +// | ||
| 1434 | +// Table 8-1 names the modes: 0 = INTRA_PLANAR, 1 = INTRA_DC, | ||
| 1435 | +// 2..34 = INTRA_ANGULAR2..INTRA_ANGULAR34 (35 modes total). The | ||
| 1436 | +// §8.4.2-step-2 candidate reduction (availability via §6.4.1, | ||
| 1437 | +// CuPredMode / pcm_flag tests, the CTB-row-boundary B clamp) is the | ||
| 1438 | +// slice-data parser's responsibility — it holds the neighbour state and | ||
| 1439 | +// the §6.4.1 z-scan availability — and yields the two candidate mode | ||
| 1440 | +// values this process consumes, matching the availability-as-input | ||
| 1441 | +// convention the §9.3.4.2.2 neighbour ctxInc derivations use. | ||
| 1442 | +// --------------------------------------------------------------------- | ||
| 1443 | + | ||
| 1444 | +/// Table 8-1 — `INTRA_PLANAR`, the mode-0 planar predictor. | ||
| 1445 | +pub const INTRA_PLANAR: u8 = 0; | ||
| 1446 | + | ||
| 1447 | +/// Table 8-1 — `INTRA_DC`, the mode-1 DC predictor. This is also the | ||
| 1448 | +/// §8.4.2-step-2 substitute value `candIntraPredModeX` takes when the | ||
| 1449 | +/// neighbour is unavailable, inter-coded, PCM, or (for B) lies in the | ||
| 1450 | +/// CTB row above the current one. | ||
| 1451 | +pub const INTRA_DC: u8 = 1; | ||
| 1452 | + | ||
| 1453 | +/// Table 8-1 — `INTRA_ANGULAR26`, the mode-26 vertical angular | ||
| 1454 | +/// predictor. §8.4.2 step 3 uses it as `candModeList[ 2 ]` in the | ||
| 1455 | +/// equal-and-low-candidate (eq. 8-23) and the both-PLANAR-and-DC-present | ||
| 1456 | +/// (final step-3 else) fall-throughs. | ||
| 1457 | +pub const INTRA_ANGULAR26: u8 = 26; | ||
| 1458 | + | ||
| 1459 | +/// Table 8-1 — the highest luma intra prediction mode index | ||
| 1460 | +/// (`INTRA_ANGULAR34`); modes run `0..=34` inclusive. | ||
| 1461 | +pub const INTRA_PRED_MODE_MAX: u8 = 34; | ||
| 1462 | + | ||
| 1463 | +/// §8.4.2 step 3 — build the three-entry most-probable-mode candidate | ||
| 1464 | +/// list `candModeList[ 0..=2 ]` from the two §8.4.2-step-2 candidate | ||
| 1465 | +/// neighbour modes `candIntraPredModeA` (left, location `(xPb − 1, yPb)`) | ||
| 1466 | +/// and `candIntraPredModeB` (above, location `(xPb, yPb − 1)`). | ||
| 1467 | +/// | ||
| 1468 | +/// Both candidate inputs are already the reduced step-2 values (an | ||
| 1469 | +/// available intra neighbour's `IntraPredModeY`, else `INTRA_DC`); this | ||
| 1470 | +/// function implements only the step-3 list construction: | ||
| 1471 | +/// | ||
| 1472 | +/// * `candIntraPredModeB == candIntraPredModeA`: | ||
| 1473 | +/// * candidate `< 2` (PLANAR or DC) ⇒ `{PLANAR, DC, ANGULAR26}` | ||
| 1474 | +/// (eqs. 8-21..8-23). | ||
| 1475 | +/// * otherwise (an angular candidate) ⇒ the candidate plus its two | ||
| 1476 | +/// neighbouring angular modes (eqs. 8-24..8-26): | ||
| 1477 | +/// `{candA, 2 + ((candA + 29) % 32), 2 + ((candA − 2 + 1) % 32)}`. | ||
| 1478 | +/// * `candIntraPredModeB != candIntraPredModeA`: | ||
| 1479 | +/// * `candModeList[ 0 ] = candA`, `candModeList[ 1 ] = candB` | ||
| 1480 | +/// (eqs. 8-27/8-28); `candModeList[ 2 ]` is the first of | ||
| 1481 | +/// `{PLANAR, DC, ANGULAR26}` not already present in the first two | ||
| 1482 | +/// entries. | ||
| 1483 | +/// | ||
| 1484 | +/// Both candidate inputs must be valid Table 8-1 modes (`0..=34`). | ||
| 1485 | +#[must_use] | ||
| 1486 | +pub fn intra_luma_cand_mode_list( | ||
| 1487 | + cand_intra_pred_mode_a: u8, | ||
| 1488 | + cand_intra_pred_mode_b: u8, | ||
| 1489 | +) -> [u8; 3] { | ||
| 1490 | + debug_assert!( | ||
| 1491 | + cand_intra_pred_mode_a <= INTRA_PRED_MODE_MAX, | ||
| 1492 | + "candIntraPredModeA is a Table 8-1 mode; must be in 0..=34" | ||
| 1493 | + ); | ||
| 1494 | + debug_assert!( | ||
| 1495 | + cand_intra_pred_mode_b <= INTRA_PRED_MODE_MAX, | ||
| 1496 | + "candIntraPredModeB is a Table 8-1 mode; must be in 0..=34" | ||
| 1497 | + ); | ||
| 1498 | + | ||
| 1499 | + if cand_intra_pred_mode_b == cand_intra_pred_mode_a { | ||
| 1500 | + if cand_intra_pred_mode_a < 2 { | ||
| 1501 | + // eqs. 8-21..8-23 — equal low candidate. | ||
| 1502 | + [INTRA_PLANAR, INTRA_DC, INTRA_ANGULAR26] | ||
| 1503 | + } else { | ||
| 1504 | + // eqs. 8-24..8-26 — equal angular candidate; the `% 32` | ||
| 1505 | + // arithmetic wraps the two neighbouring angular modes back | ||
| 1506 | + // into the 2..=33 angular band (the `2 +` re-bases the | ||
| 1507 | + // 0..=31 residue onto INTRA_ANGULAR2). | ||
| 1508 | + let a = u32::from(cand_intra_pred_mode_a); | ||
| 1509 | + let one = 2 + ((a + 29) % 32); | ||
| 1510 | + let two = 2 + ((a - 2 + 1) % 32); | ||
| 1511 | + [cand_intra_pred_mode_a, one as u8, two as u8] | ||
| 1512 | + } | ||
| 1513 | + } else { | ||
| 1514 | + // eqs. 8-27/8-28 — distinct candidates fill slots 0 and 1; slot | ||
| 1515 | + // 2 is the first default mode (PLANAR, then DC, then ANGULAR26) | ||
| 1516 | + // not already present. | ||
| 1517 | + let zero = cand_intra_pred_mode_a; | ||
| 1518 | + let one = cand_intra_pred_mode_b; | ||
| 1519 | + let two = if zero != INTRA_PLANAR && one != INTRA_PLANAR { | ||
| 1520 | + INTRA_PLANAR | ||
| 1521 | + } else if zero != INTRA_DC && one != INTRA_DC { | ||
| 1522 | + INTRA_DC | ||
| 1523 | + } else { | ||
| 1524 | + INTRA_ANGULAR26 | ||
| 1525 | + }; | ||
| 1526 | + [zero, one, two] | ||
| 1527 | + } | ||
| 1528 | +} | ||
| 1529 | + | ||
| 1530 | +/// §8.4.2 step 4 — derive `IntraPredModeY[ xPb ][ yPb ]` from the step-3 | ||
| 1531 | +/// `candModeList` and the §7.3.8.5 signalled luma-mode fields. | ||
| 1532 | +/// | ||
| 1533 | +/// `cand_mode_list` is the [`intra_luma_cand_mode_list`] output; `source` | ||
| 1534 | +/// is the [`LumaIntraModeSource`] the round-40 `prev_intra_luma_pred_flag` | ||
| 1535 | +/// selects. | ||
| 1536 | +/// | ||
| 1537 | +/// * [`LumaIntraModeSource::Mpm`] — `IntraPredModeY = candModeList[ | ||
| 1538 | +/// mpm_idx ]` (the `mpm_idx` field, `0..=2`, indexes the candidate | ||
| 1539 | +/// list directly). `field` carries the decoded `mpm_idx`. | ||
| 1540 | +/// * [`LumaIntraModeSource::Remaining`] — the step-4 ordered procedure: | ||
| 1541 | +/// the candidate list is sorted ascending (the eqs. 8-29..8-31 | ||
| 1542 | +/// three-compare-and-swap sort), `IntraPredModeY` is seeded with | ||
| 1543 | +/// `rem_intra_luma_pred_mode` (`field`, `0..=31`), then incremented by | ||
| 1544 | +/// one for every sorted candidate it meets or exceeds (low-to-high, so | ||
| 1545 | +/// the running value is re-compared against each successive candidate). | ||
| 1546 | +/// This re-injects the three excluded most-probable modes, mapping the | ||
| 1547 | +/// 31-value remaining field onto the 35-mode space. | ||
| 1548 | +/// | ||
| 1549 | +/// The returned value is always a valid Table 8-1 mode (`0..=34`). | ||
| 1550 | +#[must_use] | ||
| 1551 | +pub fn derive_intra_pred_mode_y( | ||
| 1552 | + cand_mode_list: [u8; 3], | ||
| 1553 | + source: LumaIntraModeSource, | ||
| 1554 | + field: u8, | ||
| 1555 | +) -> u8 { | ||
| 1556 | + match source { | ||
| 1557 | + LumaIntraModeSource::Mpm => { | ||
| 1558 | + debug_assert!( | ||
| 1559 | + field <= MPM_IDX_TR_CMAX as u8, | ||
| 1560 | + "mpm_idx is TR cMax = 2 (Table 9-43); must index the three-entry candModeList" | ||
| 1561 | + ); | ||
| 1562 | + cand_mode_list[field as usize] | ||
| 1563 | + } | ||
| 1564 | + LumaIntraModeSource::Remaining => { | ||
| 1565 | + debug_assert!( | ||
| 1566 | + field <= REM_INTRA_LUMA_PRED_MODE_FL_CMAX as u8, | ||
| 1567 | + "rem_intra_luma_pred_mode is FL cMax = 31 (Table 9-43); must be in 0..=31" | ||
| 1568 | + ); | ||
| 1569 | + // eqs. 8-29..8-31 — sort the three candidates ascending. | ||
| 1570 | + let mut sorted = cand_mode_list; | ||
| 1571 | + if sorted[0] > sorted[1] { | ||
| 1572 | + sorted.swap(0, 1); | ||
| 1573 | + } | ||
| 1574 | + if sorted[0] > sorted[2] { | ||
| 1575 | + sorted.swap(0, 2); | ||
| 1576 | + } | ||
| 1577 | + if sorted[1] > sorted[2] { | ||
| 1578 | + sorted.swap(1, 2); | ||
| 1579 | + } | ||
| 1580 | + // step-4 increment pass: seed with rem_intra_luma_pred_mode, | ||
| 1581 | + // then bump once per sorted candidate at-or-below the running | ||
| 1582 | + // value. The candidates are distinct and ascending, so the | ||
| 1583 | + // bump count is monotone and the result is the unsigned | ||
| 1584 | + // remaining field shifted up past the three excluded modes. | ||
| 1585 | + let mut mode = field; | ||
| 1586 | + for &cand in &sorted { | ||
| 1587 | + if mode >= cand { | ||
| 1588 | + mode += 1; | ||
| 1589 | + } | ||
| 1590 | + } | ||
| 1591 | + mode | ||
| 1592 | + } | ||
| 1593 | + } | ||
| 1594 | +} | ||
| 1595 | + | ||
| 1596 | +// --------------------------------------------------------------------- | ||
| 1597 | +// intra_chroma_pred_mode (§7.3.8.5 coding_unit() / §7.4.9.5) | ||
| 1598 | +// §9.3.3.8 / Table 9-46 binarization + Table 9-48 + §8.4.3 derivation. | ||
| 1599 | +// The chroma-mode field that follows the luma-mode group in §7.3.8.5: | ||
| 1600 | +// present once per CU when ChromaArrayType != 0 and != 3, and once per | ||
| 1601 | +// luma prediction block (the same i/j loop as the luma fields) when | ||
| 1602 | +// ChromaArrayType == 3; absent entirely when ChromaArrayType == 0 | ||
| 1603 | +// (monochrome — §8.4.3 is only invoked when ChromaArrayType != 0). | ||
| 1604 | +// --------------------------------------------------------------------- | ||
| 1605 | + | ||
| 1606 | +/// Table 9-46 — the `intra_chroma_pred_mode` value signalled by the | ||
| 1607 | +/// single-bin string `0`: 4. Per Table 8-2 row 4 the §8.4.3 `modeIdx` | ||
| 1608 | +/// for this value is `IntraPredModeY` itself (the chroma prediction | ||
| 1609 | +/// mode tracks the luma mode; for `ChromaArrayType == 2` the tracked | ||
| 1610 | +/// mode is then remapped through Table 8-3). | ||
| 1611 | +pub const INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA: u8 = 4; | ||
| 1612 | + | ||
| 1613 | +/// §9.3.3.8 / Table 9-46 — bit width of the FL suffix that follows the | ||
| 1614 | +/// `1` prefix bin: 2. The suffix carries values 0..=3 MSB-first | ||
| 1615 | +/// (`100`⇒0, `101`⇒1, `110`⇒2, `111`⇒3); both suffix bins are | ||
| 1616 | +/// bypass-coded per Table 9-48. | ||
| 1617 | +pub const INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS: u32 = 2; | ||
| 1618 | + | ||
| 1619 | +/// §9.3.4.2.1 / Table 9-48 row for `intra_chroma_pred_mode`. Bin 0 is | ||
| 1620 | +/// context-coded with `ctxInc = 0`; bins 1 and 2 are `bypass` and bins | ||
| 1621 | +/// beyond binIdx 2 are `na` (the Table 9-46 strings are at most three | ||
| 1622 | +/// bins long). | ||
| 1623 | +/// | ||
| 1624 | +/// Table 9-13 lists three ctxIdx slots with | ||
| 1625 | +/// `initValue = {63, 152, 152}` for initType 0, 1 and 2 — the element | ||
| 1626 | +/// is read in I, P and B slices (intra CUs occur in every slice type), | ||
| 1627 | +/// so all three initType slots are populated. This layer hands back | ||
| 1628 | +/// the bank-relative `ctxInc` only; the Table 9-13 initValue plus the | ||
| 1629 | +/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init | ||
| 1630 | +/// scope. | ||
| 1631 | +/// | ||
| 1632 | +/// Returns the ctxInc when called with `bin_idx == 0`; any other value | ||
| 1633 | +/// is bypass (1, 2) or `na` per Table 9-48 and the function returns 0 | ||
| 1634 | +/// defensively (callers should not invoke this for the bypass bins). | ||
| 1635 | +#[must_use] | ||
| 1636 | +pub fn intra_chroma_pred_mode_ctx_inc(bin_idx: u32) -> u32 { | ||
| 1637 | + debug_assert!( | ||
| 1638 | + bin_idx == 0, | ||
| 1639 | + "intra_chroma_pred_mode Table 9-48 row: only bin 0 is context-coded; bins 1..2 are bypass" | ||
| 1640 | + ); | ||
| 1641 | + 0 | ||
| 1642 | +} | ||
| 1643 | + | ||
| 1644 | +/// Decode `intra_chroma_pred_mode` (§7.3.8.5 / §7.4.9.5) from the | ||
| 1645 | +/// CABAC engine. | ||
| 1646 | +/// | ||
| 1647 | +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single | ||
| 1648 | +/// Table 9-13 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per | ||
| 1649 | +/// the §9.3.4.3.2.2 state transition. | ||
| 1650 | +/// | ||
| 1651 | +/// Binarization is the §9.3.3.8 / Table 9-46 process: one | ||
| 1652 | +/// context-coded prefix bin, then — only when that bin is 1 — a | ||
| 1653 | +/// two-bit bypass FL suffix. A `0` prefix decodes to value 4 | ||
| 1654 | +/// ([`INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA`]; no suffix bins are read); | ||
| 1655 | +/// a `1` prefix is followed by the MSB-first two-bit suffix carrying | ||
| 1656 | +/// values 0..=3. The returned value is therefore always in | ||
| 1657 | +/// `{0, 1, 2, 3, 4}` — feed it to [`intra_pred_mode_c_mode_idx`] / | ||
| 1658 | +/// [`derive_intra_pred_mode_c`] for the §8.4.3 `IntraPredModeC` | ||
| 1659 | +/// derivation. | ||
| 1660 | +pub fn decode_intra_chroma_pred_mode( | ||
| 1661 | + engine: &mut CabacEngine<'_>, | ||
| 1662 | + ctx: &mut ContextModel, | ||
| 1663 | +) -> Result<u8, CabacError> { | ||
| 1664 | + // §9.3.4.2.1 + Table 9-48: bin 0 is context-coded with ctxInc = 0. | ||
| 1665 | + debug_assert_eq!( | ||
| 1666 | + intra_chroma_pred_mode_ctx_inc(0), | ||
| 1667 | + 0, | ||
| 1668 | + "Table 9-48 row for intra_chroma_pred_mode: bin 0 ctxInc = 0" | ||
| 1669 | + ); | ||
| 1670 | + let prefix = engine.decode_decision(ctx)?; | ||
| 1671 | + if prefix == 0 { | ||
| 1672 | + // Table 9-46: the single-bin string `0` is value 4. | ||
| 1673 | + return Ok(INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA); | ||
| 1674 | + } | ||
| 1675 | + // Table 9-46: `1` prefix + two-bit FL bypass suffix ⇒ values 0..=3. | ||
| 1676 | + let suffix = engine.decode_bypass_bits(INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS as u8)?; | ||
| 1677 | + debug_assert!( | ||
| 1678 | + suffix <= 3, | ||
| 1679 | + "intra_chroma_pred_mode suffix is two FL bins (Table 9-46); value must be in 0..=3" | ||
| 1680 | + ); | ||
| 1681 | + Ok(suffix as u8) | ||
| 1682 | +} | ||
| 1683 | + | ||
| 1684 | +/// §8.4.3 Table 8-2 — derive `modeIdx` from `intra_chroma_pred_mode` | ||
| 1685 | +/// and `IntraPredModeY`. | ||
| 1686 | +/// | ||
| 1687 | +/// Row 4 (`intra_chroma_pred_mode == 4`) yields `IntraPredModeY` | ||
| 1688 | +/// itself. Rows 0..=3 select the base mode from `{0, 26, 10, 1}` | ||
| 1689 | +/// (planar, vertical, horizontal, DC angular indices in | ||
| 1690 | +/// `intra_chroma_pred_mode` order); when the selected base mode equals | ||
| 1691 | +/// `IntraPredModeY` the table substitutes 34 instead (each Table 8-2 | ||
| 1692 | +/// column places 34 exactly where the row's base mode would collide | ||
| 1693 | +/// with the luma mode). | ||
| 1694 | +/// | ||
| 1695 | +/// `intra_pred_mode_y` must be a valid §8.4.2 mode (0..=34) and | ||
| 1696 | +/// `intra_chroma_pred_mode` a decoded Table 9-46 value | ||
| 1697 | +/// (`{0, 1, 2, 3, 4}`); out-of-range inputs are rejected in debug | ||
| 1698 | +/// builds (release builds fall back to the luma-tracking row to avoid | ||
| 1699 | +/// panicking on an accidental out-of-range input). | ||
| 1700 | +#[must_use] | ||
| 1701 | +pub fn intra_pred_mode_c_mode_idx(intra_chroma_pred_mode: u8, intra_pred_mode_y: u8) -> u8 { | ||
| 1702 | + debug_assert!( | ||
| 1703 | + intra_chroma_pred_mode <= 4, | ||
| 1704 | + "intra_chroma_pred_mode is a Table 9-46 value; must be in 0..=4" | ||
| 1705 | + ); | ||
| 1706 | + debug_assert!( | ||
| 1707 | + intra_pred_mode_y <= 34, | ||
| 1708 | + "IntraPredModeY is a §8.4.2 mode index; must be in 0..=34" | ||
| 1709 | + ); | ||
| 1710 | + // Table 8-2 rows 0..=3 base modes, in intra_chroma_pred_mode order. | ||
| 1711 | + const BASE_MODES: [u8; 4] = [0, 26, 10, 1]; | ||
| 1712 | + match BASE_MODES.get(intra_chroma_pred_mode as usize) { | ||
| 1713 | + Some(&base) if base == intra_pred_mode_y => 34, | ||
| 1714 | + Some(&base) => base, | ||
| 1715 | + // Row 4 (and the release-build out-of-range fallback): modeIdx | ||
| 1716 | + // tracks the luma mode. | ||
| 1717 | + None => intra_pred_mode_y, | ||
| 1718 | + } | ||
| 1719 | +} | ||
| 1720 | + | ||
| 1721 | +/// §8.4.3 Table 8-3 — `IntraPredModeC` as a function of `modeIdx` when | ||
| 1722 | +/// `ChromaArrayType == 2`. Indexed by `modeIdx` 0..=34; entries 0..=2 | ||
| 1723 | +/// pass through unchanged (the Table 8-3 `X <= 2` column). | ||
| 1724 | +pub const INTRA_PRED_MODE_C_CHROMA_422_MAP: [u8; 35] = [ | ||
| 1725 | + 0, 1, 2, // X <= 2 passes through | ||
| 1726 | + 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, // modeIdx 3..=14 | ||
| 1727 | + 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25, // modeIdx 15..=25 | ||
| 1728 | + 26, 27, 27, 28, 28, 29, 29, 30, 31, // modeIdx 26..=34 | ||
| 1729 | +]; | ||
| 1730 | + | ||
| 1731 | +/// §8.4.3 Table 8-3 — remap `modeIdx` to `IntraPredModeC` for | ||
| 1732 | +/// `ChromaArrayType == 2` streams. `mode_idx` must be in 0..=34; | ||
| 1733 | +/// out-of-range inputs are rejected in debug builds (release builds | ||
| 1734 | +/// pass the value through unchanged to avoid panicking). | ||
| 1735 | +#[must_use] | ||
| 1736 | +pub fn intra_pred_mode_c_chroma_422(mode_idx: u8) -> u8 { | ||
| 1737 | + debug_assert!( | ||
| 1738 | + mode_idx <= 34, | ||
| 1739 | + "modeIdx is a §8.4.3 Table 8-2 output; must be in 0..=34" | ||
| 1740 | + ); | ||
| 1741 | + INTRA_PRED_MODE_C_CHROMA_422_MAP | ||
| 1742 | + .get(mode_idx as usize) | ||
| 1743 | + .copied() | ||
| 1744 | + .unwrap_or(mode_idx) | ||
| 1745 | +} | ||
| 1746 | + | ||
| 1747 | +/// §8.4.3 — the full `IntraPredModeC` derivation: Table 8-2 `modeIdx` | ||
| 1748 | +/// from the decoded `intra_chroma_pred_mode` and the §8.4.2 | ||
| 1749 | +/// `IntraPredModeY`, then — when `ChromaArrayType == 2` — the Table | ||
| 1750 | +/// 8-3 remap; otherwise `IntraPredModeC` is `modeIdx` itself. | ||
| 1751 | +/// | ||
| 1752 | +/// §8.4.3 is only invoked when `ChromaArrayType != 0`; the §7.3.8.5 | ||
| 1753 | +/// syntax never emits `intra_chroma_pred_mode` for a monochrome | ||
| 1754 | +/// stream, so a caller holding a decoded value is already past that | ||
| 1755 | +/// gate. | ||
| 1756 | +#[must_use] | ||
| 1757 | +pub fn derive_intra_pred_mode_c( | ||
| 1758 | + intra_chroma_pred_mode: u8, | ||
| 1759 | + intra_pred_mode_y: u8, | ||
| 1760 | + chroma_array_type_is_2: bool, | ||
| 1761 | +) -> u8 { | ||
| 1762 | + let mode_idx = intra_pred_mode_c_mode_idx(intra_chroma_pred_mode, intra_pred_mode_y); | ||
| 1763 | + if chroma_array_type_is_2 { | ||
| 1764 | + intra_pred_mode_c_chroma_422(mode_idx) | ||
| 1765 | + } else { | ||
| 1766 | + mode_idx | ||
| 1767 | + } | ||
| 1768 | +} | ||
| 1769 | + | ||
| 1770 | +// --------------------------------------------------------------------- | ||
| 1771 | +// last_sig_coeff_{x,y}_{prefix,suffix} (§7.3.8.11, §7.4.9.11) | ||
| 1772 | +// --------------------------------------------------------------------- | ||
| 1773 | + | ||
| 1774 | +/// Which `last_sig_coeff_*_prefix` bank the caller's context-model | ||
| 1775 | +/// slice corresponds to. The X and Y prefixes live in separate banks | ||
| 1776 | +/// of contexts; we tag the request so the caller can pick the right | ||
| 1777 | +/// slice. | ||
| 1778 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 1779 | +pub enum LastSigCoeffBank { | ||
| 1780 | + /// `last_sig_coeff_x_prefix` bank. | ||
| 1781 | + X, | ||
| 1782 | + /// `last_sig_coeff_y_prefix` bank. | ||
| 1783 | + Y, | ||
| 1784 | +} | ||
| 1785 | + | ||
| 1786 | +/// §9.3.4.2.3 — `(ctxOffset, ctxShift)` for the | ||
| 1787 | +/// `last_sig_coeff_{x,y}_prefix` ctxInc derivation. `log2_trafo_size` | ||
| 1788 | +/// is the transform-block log2 dimension (2..=5; 2 = 4×4, 5 = 32×32); | ||
| 1789 | +/// `is_chroma` selects the chroma bank when `cIdx > 0`. | ||
| 1790 | +/// | ||
| 1791 | +/// Spec equations (§9.3.4.2.3 Table 9-26 / 9-27): | ||
| 1792 | +/// | ||
| 1793 | +/// ```text | ||
| 1794 | +/// // luma (cIdx == 0): | ||
| 1795 | +/// ctxOffset = 3 * (log2TrafoSize - 2) + ((log2TrafoSize - 1) >> 2) | ||
| 1796 | +/// ctxShift = (log2TrafoSize + 1) >> 2 | ||
| 1797 | +/// | ||
| 1798 | +/// // chroma (cIdx > 0): | ||
| 1799 | +/// ctxOffset = 15 | ||
| 1800 | +/// ctxShift = log2TrafoSize - 2 | ||
| 1801 | +/// ``` | ||
| 1802 | +#[must_use] | ||
| 1803 | +pub fn last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size: u32, is_chroma: bool) -> (u32, u32) { | ||
| 1804 | + if is_chroma { | ||
| 1805 | + // §9.3.4.2.3 — chroma TBs always sit at ctxOffset = 15, | ||
| 1806 | + // ctxShift = log2TrafoSize − 2. | ||
| 1807 | + (15, log2_trafo_size - 2) | ||
| 1808 | + } else { | ||
| 1809 | + // §9.3.4.2.3 — luma: piecewise linear in log2TrafoSize. | ||
| 1810 | + let offset = 3 * (log2_trafo_size - 2) + ((log2_trafo_size - 1) >> 2); | ||
| 1811 | + let shift = (log2_trafo_size + 1) >> 2; | ||
| 1812 | + (offset, shift) | ||
| 1813 | + } | ||
| 1814 | +} | ||
| 1815 | + | ||
| 1816 | +/// §9.3.4.2.3 — bank-relative `ctxInc` for a single | ||
| 1817 | +/// `last_sig_coeff_*_prefix` bin: | ||
| 1818 | +/// | ||
| 1819 | +/// ```text | ||
| 1820 | +/// ctxInc = (binIdx >> ctxShift) + ctxOffset | ||
| 1821 | +/// ``` | ||
| 1822 | +#[must_use] | ||
| 1823 | +pub fn last_sig_coeff_prefix_ctx_inc(bin_idx: u32, ctx_offset: u32, ctx_shift: u32) -> u32 { | ||
| 1824 | + (bin_idx >> ctx_shift) + ctx_offset | ||
| 1825 | +} | ||
| 1826 | + | ||
| 1827 | +/// §9.3.3.10 — `cMax` for `last_sig_coeff_{x,y}_prefix`: | ||
| 1828 | +/// `(log2TrafoSize << 1) − 1`. For a 4×4 TB (log2=2) the prefix is at | ||
| 1829 | +/// most 3 bins; for a 32×32 TB (log2=5) at most 9 bins. | ||
| 1830 | +#[must_use] | ||
| 1831 | +pub fn last_sig_coeff_prefix_cmax(log2_trafo_size: u32) -> u32 { | ||
| 1832 | + (log2_trafo_size << 1) - 1 | ||
| 1833 | +} | ||
| 1834 | + | ||
| 1835 | +/// §7.4.9.11 equations 7-74..7-77 — derive the final | ||
| 1836 | +/// `LastSignificantCoeffX/Y` position from a decoded | ||
| 1837 | +/// `(prefix, optional suffix)` pair. When `prefix <= 3` no suffix is | ||
| 1838 | +/// signalled and the position equals the prefix. When `prefix > 3` the | ||
| 1839 | +/// suffix is `nBits = (prefix >> 1) − 1` bits, and the position is | ||
| 1840 | +/// | ||
| 1841 | +/// ```text | ||
| 1842 | +/// pos = ( ( 2 + ( prefix & 1 ) ) << ( (prefix >> 1) - 1 ) ) + suffix | ||
| 1843 | +/// ``` | ||
| 1844 | +/// | ||
| 1845 | +/// `suffix` is the unsigned suffix value (caller already decoded the | ||
| 1846 | +/// `nBits` bypass bins, MSB-first); pass `None` when `prefix <= 3`. | ||
| 1847 | +#[must_use] | ||
| 1848 | +pub fn last_sig_coeff_position(prefix: u32, suffix: Option<u32>) -> u32 { | ||
| 1849 | + if prefix <= 3 { | ||
| 1850 | + // §7.4.9.11: no suffix, the prefix is the final value. | ||
| 1851 | + prefix | ||
| 1852 | + } else { | ||
| 1853 | + let n_bits = (prefix >> 1) - 1; | ||
| 1854 | + let base = (2 + (prefix & 1)) << n_bits; | ||
| 1855 | + base + suffix.unwrap_or(0) | ||
| 1856 | + } | ||
| 1857 | +} | ||
| 1858 | + | ||
| 1859 | +/// Suffix bit count for `last_sig_coeff_{x,y}_suffix`: `nBits = | ||
| 1860 | +/// (prefix >> 1) − 1` when `prefix > 3`, otherwise 0 (no suffix | ||
| 1861 | +/// signalled). | ||
| 1862 | +#[must_use] | ||
| 1863 | +pub fn last_sig_coeff_suffix_n_bits(prefix: u32) -> u32 { | ||
| 1864 | + if prefix > 3 { | ||
| 1865 | + (prefix >> 1) - 1 | ||
| 1866 | + } else { | ||
| 1867 | + 0 | ||
| 1868 | + } | ||
| 1869 | +} | ||
| 1870 | + | ||
| 1871 | +/// Decoded `last_sig_coeff_*` element (one of X or Y; same shape for | ||
| 1872 | +/// both banks). | ||
| 1873 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 1874 | +pub struct LastSigCoeff { | ||
| 1875 | + /// `last_sig_coeff_*_prefix` from the wire. | ||
| 1876 | + pub prefix: u32, | ||
| 1877 | + /// `last_sig_coeff_*_suffix` from the wire (`None` when | ||
| 1878 | + /// `prefix <= 3`, the no-suffix-signalled case). | ||
| 1879 | + pub suffix: Option<u32>, | ||
| 1880 | + /// §7.4.9.11 derived `LastSignificantCoeff{X,Y}` position. Range | ||
| 1881 | + /// 0..=(1 << log2TrafoSize) - 1. | ||
| 1882 | + pub position: u32, | ||
| 1883 | +} | ||
| 1884 | + | ||
| 1885 | +/// Decode one `last_sig_coeff_*_{prefix,suffix}` pair from the CABAC | ||
| 1886 | +/// engine. `ctx_bank` is the caller-supplied slice of context variables | ||
| 1887 | +/// for the active bank ([`LastSigCoeffBank`]); the bin at index | ||
| 1888 | +/// `binIdx` consumes the context at index | ||
| 1889 | +/// `ctx_inc = (binIdx >> ctxShift) + ctxOffset` within that slice (the | ||
| 1890 | +/// caller is responsible for sizing the slice so the highest used | ||
| 1891 | +/// `ctx_inc` index is in-bounds). | ||
| 1892 | +/// | ||
| 1893 | +/// Returns the decoded prefix, optional suffix, and the §7.4.9.11 | ||
| 1894 | +/// derived position. The arguments | ||
| 1895 | +/// `log2_trafo_size` and `is_chroma` drive both the TR-prefix `cMax` | ||
| 1896 | +/// and the §9.3.4.2.3 `(ctxOffset, ctxShift)` derivation. | ||
| 1897 | +/// | ||
| 1898 | +/// The §7.4.9.11 swap for `scanIdx == 2` (the diagonal scan reflection | ||
| 1899 | +/// of `LastSignificantCoeff{X,Y}`) is **not** applied here; the caller | ||
| 1900 | +/// receives the on-wire X / Y positions and applies the swap at the | ||
| 1901 | +/// residual-coding level where `scanIdx` is known. | ||
| 1902 | +pub fn decode_last_sig_coeff( | ||
| 1903 | + engine: &mut CabacEngine<'_>, | ||
| 1904 | + log2_trafo_size: u32, | ||
| 1905 | + is_chroma: bool, | ||
| 1906 | + ctx_bank: &mut [ContextModel], | ||
| 1907 | +) -> Result<LastSigCoeff, CabacError> { | ||
| 1908 | + let c_max = last_sig_coeff_prefix_cmax(log2_trafo_size); | ||
| 1909 | + let (ctx_offset, ctx_shift) = | ||
| 1910 | + last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size, is_chroma); | ||
| 1911 | + | ||
| 1912 | + let (prefix, _is_escape) = read_truncated_rice_prefix(c_max, |bin_idx| { | ||
| 1913 | + let ctx_inc = last_sig_coeff_prefix_ctx_inc(bin_idx, ctx_offset, ctx_shift) as usize; | ||
| 1914 | + engine.decode_decision(&mut ctx_bank[ctx_inc]) | ||
| 1915 | + })?; | ||
| 1916 | + | ||
| 1917 | + let n_bits = last_sig_coeff_suffix_n_bits(prefix); | ||
| 1918 | + let suffix = if n_bits > 0 { | ||
| 1919 | + Some(engine.decode_bypass_bits(n_bits as u8)?) | ||
| 1920 | + } else { | ||
| 1921 | + None | ||
| 1922 | + }; | ||
| 1923 | + let position = last_sig_coeff_position(prefix, suffix); | ||
| 1924 | + Ok(LastSigCoeff { | ||
| 1925 | + prefix, | ||
| 1926 | + suffix, | ||
| 1927 | + position, | ||
| 1928 | + }) | ||
| 1929 | +} | ||
| 1930 | + | ||
| 1931 | +// --------------------------------------------------------------------- | ||
| 1932 | +// coded_sub_block_flag ctxInc — §9.3.4.2.4 | ||
| 1933 | +// --------------------------------------------------------------------- | ||
| 1934 | + | ||
| 1935 | +/// §9.3.4.2.4 — derive the `ctxInc` for one bin of | ||
| 1936 | +/// `coded_sub_block_flag` from the colour-component index, the | ||
| 1937 | +/// current sub-block scan location `(xS, yS)`, the transform-block | ||
| 1938 | +/// size `log2TrafoSize`, and the two previously decoded neighbour | ||
| 1939 | +/// bins in sub-block scan order. | ||
| 1940 | +/// | ||
| 1941 | +/// Spec equations: | ||
| 1942 | +/// | ||
| 1943 | +/// ```text | ||
| 1944 | +/// // §9.3.4.2.4, equations 9-35..9-39 | ||
| 1945 | +/// csbfCtx = 0 | ||
| 1946 | +/// if xS < (1 << (log2TrafoSize - 2)) - 1: | ||
| 1947 | +/// csbfCtx += coded_sub_block_flag[xS + 1][yS] | ||
| 1948 | +/// if yS < (1 << (log2TrafoSize - 2)) - 1: | ||
| 1949 | +/// csbfCtx += coded_sub_block_flag[xS][yS + 1] | ||
| 1950 | +/// if cIdx == 0: | ||
| 1951 | +/// ctxInc = min(csbfCtx, 1) | ||
| 1952 | +/// else: | ||
| 1953 | +/// ctxInc = 2 + min(csbfCtx, 1) | ||
| 1954 | +/// ``` | ||
| 1955 | +/// | ||
| 1956 | +/// `right_neighbour` is the previously decoded | ||
| 1957 | +/// `coded_sub_block_flag[xS + 1][yS]` (0/1); pass `0` whenever the | ||
| 1958 | +/// current sub-block sits on the right edge of the TB | ||
| 1959 | +/// (`xS == (1 << (log2TrafoSize - 2)) - 1`), where equation 9-36 does | ||
| 1960 | +/// not apply. `below_neighbour` is the previously decoded | ||
| 1961 | +/// `coded_sub_block_flag[xS][yS + 1]` (0/1); pass `0` whenever the | ||
| 1962 | +/// current sub-block sits on the bottom edge of the TB | ||
| 1963 | +/// (`yS == (1 << (log2TrafoSize - 2)) - 1`). | ||
| 1964 | +/// | ||
| 1965 | +/// Returns `ctxInc` in `{0, 1}` for luma (`cIdx == 0`) or | ||
| 1966 | +/// `{2, 3}` for chroma (`cIdx > 0`). | ||
| 1967 | +/// | ||
| 1968 | +/// # Panics | ||
| 1969 | +/// Does not panic; both neighbour inputs are clamped via the boolean | ||
| 1970 | +/// `>= 1` comparison. | ||
| 1971 | +#[must_use] | ||
| 1972 | +pub fn coded_sub_block_flag_ctx_inc( | ||
| 1973 | + is_chroma: bool, | ||
| 1974 | + right_neighbour: u8, | ||
| 1975 | + below_neighbour: u8, | ||
| 1976 | +) -> u32 { | ||
| 1977 | + // §9.3.4.2.4: csbfCtx is the unsigned sum of the two neighbour | ||
| 1978 | + // bins (each either 0 or 1), so it lies in {0, 1, 2}. The final | ||
| 1979 | + // ctxInc clamps to {0, 1} via min(csbfCtx, 1). | ||
| 1980 | + let csbf_ctx = (right_neighbour & 1) as u32 + (below_neighbour & 1) as u32; | ||
| 1981 | + let clipped = csbf_ctx.min(1); | ||
| 1982 | + if is_chroma { | ||
| 1983 | + // §9.3.4.2.4 equation 9-39: chroma uses the {2, 3} bank. | ||
| 1984 | + 2 + clipped | ||
| 1985 | + } else { | ||
| 1986 | + // §9.3.4.2.4 equation 9-38: luma uses the {0, 1} bank. | ||
| 1987 | + clipped | ||
| 1988 | + } | ||
| 1989 | +} | ||
| 1990 | + | ||
| 1991 | +/// §9.3.4.2.4 — helper that takes the full sub-block location and | ||
| 1992 | +/// transform-block size and applies the edge-gating from equations | ||
| 1993 | +/// 9-36 / 9-37 before delegating to [`coded_sub_block_flag_ctx_inc`]. | ||
| 1994 | +/// The caller passes the previously decoded | ||
| 1995 | +/// `coded_sub_block_flag[xS + 1][yS]` and | ||
| 1996 | +/// `coded_sub_block_flag[xS][yS + 1]` values regardless of the edge | ||
| 1997 | +/// condition; this function zeroes them when the corresponding | ||
| 1998 | +/// equation 9-36 / 9-37 does not apply (sub-block on the right / | ||
| 1999 | +/// bottom TB edge). | ||
| 2000 | +/// | ||
| @@ -0,0 +1,300 @@ | |||
| 1 | +//! MSB-first bit reader for H.265 syntax-element parsing. | ||
| 2 | +//! | ||
| 3 | +//! H.265 syntax elements are read most-significant-bit-first from the | ||
| 4 | +//! RBSP byte stream (see ITU-T Rec. H.265 §7.2 — the `read_bits(n)` | ||
| 5 | +//! function described there returns the next `n` bits as an unsigned | ||
| 6 | +//! integer with the MSB written first). This module provides the | ||
| 7 | +//! minimum surface needed for §7.3.2.1 (VPS) and §7.3.3 | ||
| 8 | +//! (profile_tier_level): | ||
| 9 | +//! | ||
| 10 | +//! * [`BitReader::u`] — fixed-width unsigned integer (the `u(n)` | ||
| 11 | +//! descriptor of §7.2). | ||
| 12 | +//! * [`BitReader::ue`] — 0-th-order unsigned Exp-Golomb (the `ue(v)` | ||
| 13 | +//! descriptor, parsed per §9.2). | ||
| 14 | +//! | ||
| 15 | +//! The reader takes an already-unescaped RBSP buffer (see | ||
| 16 | +//! [`crate::nal::strip_emulation_prevention`]) and does not attempt to | ||
| 17 | +//! locate the RBSP stop bit — that is left to the calling parser. | ||
| 18 | + | ||
| 19 | +/// Errors that can arise while consuming bits from an RBSP buffer. | ||
| 20 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 21 | +pub enum BitReaderError { | ||
| 22 | + /// A read requested more bits than remained in the buffer. | ||
| 23 | + EndOfBuffer, | ||
| 24 | + /// More than 32 bits requested in a single `u()` read. | ||
| 25 | + TooManyBits, | ||
| 26 | + /// A 0-th-order Exp-Golomb code's leading-zero run exceeded 32 | ||
| 27 | + /// (the §9.2 contract caps `codeNum` at `2^32 - 2`). A run of 33 | ||
| 28 | + /// zeros would overflow the 32-bit return type. | ||
| 29 | + ExpGolombOverflow, | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +impl core::fmt::Display for BitReaderError { | ||
| 33 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| 34 | + match self { | ||
| 35 | + Self::EndOfBuffer => f.write_str("read past end of RBSP buffer"), | ||
| 36 | + Self::TooManyBits => f.write_str("u(n) called with n > 32"), | ||
| 37 | + Self::ExpGolombOverflow => f.write_str("ue(v) leading-zero run exceeded 32"), | ||
| 38 | + } | ||
| 39 | + } | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +impl std::error::Error for BitReaderError {} | ||
| 43 | + | ||
| 44 | +/// MSB-first bit reader. | ||
| 45 | +#[derive(Debug, Clone)] | ||
| 46 | +pub struct BitReader<'a> { | ||
| 47 | + buf: &'a [u8], | ||
| 48 | + /// Bit cursor measured from the start of `buf` (0 == MSB of | ||
| 49 | + /// `buf[0]`). | ||
| 50 | + bit_pos: usize, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +impl<'a> BitReader<'a> { | ||
| 54 | + /// Construct a bit reader over `buf`. | ||
| 55 | + pub fn new(buf: &'a [u8]) -> Self { | ||
| 56 | + Self { buf, bit_pos: 0 } | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + /// Number of bits still available. | ||
| 60 | + pub fn bits_left(&self) -> usize { | ||
| 61 | + self.buf | ||
| 62 | + .len() | ||
| 63 | + .saturating_mul(8) | ||
| 64 | + .saturating_sub(self.bit_pos) | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + /// Read a single bit (the `u(1)` descriptor). | ||
| 68 | + pub fn u1(&mut self) -> Result<u8, BitReaderError> { | ||
| 69 | + if self.bit_pos >= self.buf.len() * 8 { | ||
| 70 | + return Err(BitReaderError::EndOfBuffer); | ||
| 71 | + } | ||
| 72 | + let byte = self.buf[self.bit_pos / 8]; | ||
| 73 | + let bit = 7 - (self.bit_pos % 8); | ||
| 74 | + self.bit_pos += 1; | ||
| 75 | + Ok((byte >> bit) & 0x01) | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + /// Read `n` bits MSB-first as an unsigned integer (the `u(n)` | ||
| 79 | + /// descriptor, with `n` in `0..=32`). `n == 0` returns 0 and does | ||
| 80 | + /// not advance the cursor. | ||
| 81 | + pub fn u(&mut self, n: u8) -> Result<u32, BitReaderError> { | ||
| 82 | + if n > 32 { | ||
| 83 | + return Err(BitReaderError::TooManyBits); | ||
| 84 | + } | ||
| 85 | + if n == 0 { | ||
| 86 | + return Ok(0); | ||
| 87 | + } | ||
| 88 | + if self.bits_left() < n as usize { | ||
| 89 | + return Err(BitReaderError::EndOfBuffer); | ||
| 90 | + } | ||
| 91 | + let mut value: u32 = 0; | ||
| 92 | + for _ in 0..n { | ||
| 93 | + value = (value << 1) | (self.u1()? as u32); | ||
| 94 | + } | ||
| 95 | + Ok(value) | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + /// Skip `n` bits without interpreting them. Useful when a syntax | ||
| 99 | + /// element appears in the bitstream but is not needed by the | ||
| 100 | + /// caller (e.g. the 32 profile_compatibility flags after the | ||
| 101 | + /// caller has already recorded the few of interest). | ||
| 102 | + pub fn skip(&mut self, n: usize) -> Result<(), BitReaderError> { | ||
| 103 | + if self.bits_left() < n { | ||
| 104 | + return Err(BitReaderError::EndOfBuffer); | ||
| 105 | + } | ||
| 106 | + self.bit_pos += n; | ||
| 107 | + Ok(()) | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + /// Read a 0-th-order unsigned Exp-Golomb code (the `ue(v)` | ||
| 111 | + /// descriptor). Per ITU-T Rec. H.265 §9.2: count `leadingZeroBits` | ||
| 112 | + /// 0 bits until the first 1 bit is seen; then read another | ||
| 113 | + /// `leadingZeroBits` bits and compute | ||
| 114 | + /// `codeNum = 2^leadingZeroBits + read_bits(leadingZeroBits) - 1`. | ||
| 115 | + pub fn ue(&mut self) -> Result<u32, BitReaderError> { | ||
| 116 | + let mut leading_zero_bits: u32 = 0; | ||
| 117 | + loop { | ||
| 118 | + if leading_zero_bits > 32 { | ||
| 119 | + return Err(BitReaderError::ExpGolombOverflow); | ||
| 120 | + } | ||
| 121 | + let b = self.u1()?; | ||
| 122 | + if b == 1 { | ||
| 123 | + break; | ||
| 124 | + } | ||
| 125 | + leading_zero_bits += 1; | ||
| 126 | + } | ||
| 127 | + if leading_zero_bits == 0 { | ||
| 128 | + return Ok(0); | ||
| 129 | + } | ||
| 130 | + if leading_zero_bits == 32 { | ||
| 131 | + // 2^32 would overflow u32; the suffix must therefore be 0 | ||
| 132 | + // to keep `codeNum` representable. Treat any other input | ||
| 133 | + // as an overflow. | ||
| 134 | + let suffix = self.u(32)?; | ||
| 135 | + return suffix | ||
| 136 | + .checked_sub(1) | ||
| 137 | + .and_then(|v| (1u64 << 32).checked_add(v as u64)) | ||
| 138 | + .and_then(|big| u32::try_from(big).ok()) | ||
| 139 | + .ok_or(BitReaderError::ExpGolombOverflow); | ||
| 140 | + } | ||
| 141 | + let suffix = self.u(leading_zero_bits as u8)?; | ||
| 142 | + Ok((1u32 << leading_zero_bits) - 1 + suffix) | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + /// Read a 0-th-order signed Exp-Golomb code (the `se(v)` | ||
| 146 | + /// descriptor). Per ITU-T Rec. H.265 §9.2.2: read a `ue(v)` | ||
| 147 | + /// `codeNum`, then map it to a signed value per Table 9-3 as | ||
| 148 | + /// `(-1)^(codeNum + 1) * Ceil(codeNum / 2)` — `codeNum` 0 → 0, | ||
| 149 | + /// 1 → +1, 2 → -1, 3 → +2, 4 → -2, … | ||
| 150 | + pub fn se(&mut self) -> Result<i32, BitReaderError> { | ||
| 151 | + let code_num = self.ue()?; | ||
| 152 | + // Ceil(codeNum / 2) without overflow: (codeNum + 1) / 2. | ||
| 153 | + let magnitude = ((code_num as i64) + 1) / 2; | ||
| 154 | + let value = if code_num % 2 == 0 { | ||
| 155 | + // Even codeNum (0, 2, 4, …) maps to a non-positive value | ||
| 156 | + // (0, -1, -2, …). | ||
| 157 | + -magnitude | ||
| 158 | + } else { | ||
| 159 | + // Odd codeNum (1, 3, 5, …) maps to a positive value. | ||
| 160 | + magnitude | ||
| 161 | + }; | ||
| 162 | + // `value` is bounded by ±2^31 because `ue()` caps `codeNum` | ||
| 163 | + // at `2^32 - 2`, whose mapped magnitude is `2^31 - 1`. | ||
| 164 | + i32::try_from(value).map_err(|_| BitReaderError::ExpGolombOverflow) | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + /// Current bit position from the start of the buffer. | ||
| 168 | + pub fn bit_pos(&self) -> usize { | ||
| 169 | + self.bit_pos | ||
| 170 | + } | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +#[cfg(test)] | ||
| 174 | +mod tests { | ||
| 175 | + use super::*; | ||
| 176 | + | ||
| 177 | + #[test] | ||
| 178 | + fn reads_individual_bits_msb_first() { | ||
| 179 | + // 0b1010_0110, 0b1100_0011 → bits: 1 0 1 0 0 1 1 0 1 1 0 0 0 0 1 1 | ||
| 180 | + let buf = [0xA6, 0xC3]; | ||
| 181 | + let mut br = BitReader::new(&buf); | ||
| 182 | + let want = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1]; | ||
| 183 | + for &w in &want { | ||
| 184 | + assert_eq!(br.u1().unwrap(), w); | ||
| 185 | + } | ||
| 186 | + assert!(br.u1().is_err()); | ||
| 187 | + } | ||
| 188 | + | ||
| 189 | + #[test] | ||
| 190 | + fn reads_u_n_across_byte_boundary() { | ||
| 191 | + // Two bytes: 0xAB, 0xCD → 0b1010_1011_1100_1101 | ||
| 192 | + let buf = [0xAB, 0xCD]; | ||
| 193 | + let mut br = BitReader::new(&buf); | ||
| 194 | + // Take 12 bits: 0b1010_1011_1100 = 0xABC | ||
| 195 | + assert_eq!(br.u(12).unwrap(), 0xABC); | ||
| 196 | + // Remaining 4 bits: 0xD | ||
| 197 | + assert_eq!(br.u(4).unwrap(), 0xD); | ||
| 198 | + } | ||
| 199 | + | ||
| 200 | + #[test] | ||
| 201 | + fn u_zero_returns_zero_and_does_not_consume() { | ||
| 202 | + let buf = [0xFF]; | ||
| 203 | + let mut br = BitReader::new(&buf); | ||
| 204 | + assert_eq!(br.u(0).unwrap(), 0); | ||
| 205 | + assert_eq!(br.bit_pos(), 0); | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + #[test] | ||
| 209 | + fn u_thirty_two_full_word() { | ||
| 210 | + let buf = [0x12, 0x34, 0x56, 0x78]; | ||
| 211 | + let mut br = BitReader::new(&buf); | ||
| 212 | + assert_eq!(br.u(32).unwrap(), 0x1234_5678); | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + #[test] | ||
| 216 | + fn ue_table_b9_2() { | ||
| 217 | + // Per H.265 §9.2 Table 9-2 first few codewords: | ||
| 218 | + // codeNum=0 → '1' (1 bit) | ||
| 219 | + // codeNum=1 → '010' (3 bits) | ||
| 220 | + // codeNum=2 → '011' (3 bits) | ||
| 221 | + // codeNum=3 → '00100' (5 bits) | ||
| 222 | + // codeNum=4 → '00101' (5 bits) | ||
| 223 | + // codeNum=5 → '00110' (5 bits) | ||
| 224 | + // codeNum=6 → '00111' (5 bits) | ||
| 225 | + // Pack codewords 0..=6 into a byte stream MSB-first: | ||
| 226 | + // Bits: 1 010 011 00100 00101 00110 00111 = 27 bits, padded | ||
| 227 | + // with 5 zero bits to land on a 32-bit byte boundary. | ||
| 228 | + // Group as bytes (MSB first): | ||
| 229 | + // bit 0..7 : 1 0 1 0 0 1 1 0 = 0xA6 | ||
| 230 | + // bit 8..15 : 0 1 0 0 0 0 1 0 = 0x42 | ||
| 231 | + // bit 16..23: 1 0 0 1 1 0 0 0 = 0x98 | ||
| 232 | + // bit 24..31: 1 1 1 0 0 0 0 0 = 0xE0 (last 5 bits are pad) | ||
| 233 | + let buf = [0xA6, 0x42, 0x98, 0xE0]; | ||
| 234 | + let mut br = BitReader::new(&buf); | ||
| 235 | + let got: Vec<u32> = (0..7).map(|_| br.ue().unwrap()).collect(); | ||
| 236 | + assert_eq!(got, vec![0, 1, 2, 3, 4, 5, 6]); | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + #[test] | ||
| 240 | + fn ue_zero_is_single_one_bit() { | ||
| 241 | + let buf = [0b1000_0000]; | ||
| 242 | + let mut br = BitReader::new(&buf); | ||
| 243 | + assert_eq!(br.ue().unwrap(), 0); | ||
| 244 | + assert_eq!(br.bit_pos(), 1); | ||
| 245 | + } | ||
| 246 | + | ||
| 247 | + #[test] | ||
| 248 | + fn end_of_buffer_errors() { | ||
| 249 | + let buf = [0xFF]; | ||
| 250 | + let mut br = BitReader::new(&buf); | ||
| 251 | + assert_eq!(br.u(8).unwrap(), 0xFF); | ||
| 252 | + assert_eq!(br.u(1), Err(BitReaderError::EndOfBuffer)); | ||
| 253 | + } | ||
| 254 | + | ||
| 255 | + #[test] | ||
| 256 | + fn too_many_bits_errors() { | ||
| 257 | + let buf = [0xFF; 8]; | ||
| 258 | + let mut br = BitReader::new(&buf); | ||
| 259 | + assert_eq!(br.u(33), Err(BitReaderError::TooManyBits)); | ||
| 260 | + } | ||
| 261 | + | ||
| 262 | + #[test] | ||
| 263 | + fn skip_advances_cursor() { | ||
| 264 | + let buf = [0xFF, 0xAA]; | ||
| 265 | + let mut br = BitReader::new(&buf); | ||
| 266 | + br.skip(8).unwrap(); | ||
| 267 | + assert_eq!(br.u(8).unwrap(), 0xAA); | ||
| 268 | + } | ||
| 269 | + | ||
| 270 | + #[test] | ||
| 271 | + fn se_table_9_3() { | ||
| 272 | + // Per H.265 §9.2.2 Table 9-3, codeNum → se(v) value: | ||
| 273 | + // 0 → 0, 1 → +1, 2 → -1, 3 → +2, 4 → -2, 5 → +3, 6 → -3. | ||
| 274 | + // codeNum is itself ue(v); reuse the codewords 0..=6 packing | ||
| 275 | + // from `ue_table_b9_2` (bits 1 010 011 00100 00101 00110 00111). | ||
| 276 | + let buf = [0xA6, 0x42, 0x98, 0xE0]; | ||
| 277 | + let mut br = BitReader::new(&buf); | ||
| 278 | + let got: Vec<i32> = (0..7).map(|_| br.se().unwrap()).collect(); | ||
| 279 | + assert_eq!(got, vec![0, 1, -1, 2, -2, 3, -3]); | ||
| 280 | + } | ||
| 281 | + | ||
| 282 | + #[test] | ||
| 283 | + fn se_zero_is_single_one_bit() { | ||
| 284 | + // codeNum 0 ('1') maps to value 0 and consumes one bit. | ||
| 285 | + let buf = [0b1000_0000]; | ||
| 286 | + let mut br = BitReader::new(&buf); | ||
| 287 | + assert_eq!(br.se().unwrap(), 0); | ||
| 288 | + assert_eq!(br.bit_pos(), 1); | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + #[test] | ||
| 292 | + fn ue_overflow_run_too_long() { | ||
| 293 | + // 33 leading zero bits with no terminating 1 in the buffer. | ||
| 294 | + // The reader should surface ExpGolombOverflow before running | ||
| 295 | + // off the end (we never reach the suffix read). | ||
| 296 | + let buf = [0u8; 8]; // 64 zero bits | ||
| 297 | + let mut br = BitReader::new(&buf); | ||
| 298 | + assert_eq!(br.ue(), Err(BitReaderError::ExpGolombOverflow)); | ||
| 299 | + } | ||
| 300 | +} | ||
| @@ -0,0 +1,820 @@ | |||
| 1 | +//! §9.3 CABAC arithmetic decoding engine. | ||
| 2 | +//! | ||
| 3 | +//! This module is a clean-room transcription of the ITU-T Rec. H.265 | | ||
| 4 | +//! ISO/IEC 23008-2 §9.3 context-adaptive binary arithmetic coding | ||
| 5 | +//! *decode* engine — the lowest layer of HEVC entropy decoding, the | ||
| 6 | +//! gateway through which all slice-data syntax elements (§7.3.8) are | ||
| 7 | +//! read. It deliberately stops at the engine boundary: it exposes the | ||
| 8 | +//! four arithmetic-decode primitives plus the context-variable model, | ||
| 9 | +//! but does not implement the §9.3.4.2 binarization / context-index | ||
| 10 | +//! derivation for any specific syntax element (those sit one layer up, | ||
| 11 | +//! in the slice-data parser). | ||
| 12 | +//! | ||
| 13 | +//! The pieces transcribed here are: | ||
| 14 | +//! | ||
| 15 | +//! * §9.3.2.6 — [`CabacEngine::new`] / [`CabacEngine::init_engine`]: | ||
| 16 | +//! `ivlCurrRange = 510`, `ivlOffset = read_bits(9)`. | ||
| 17 | +//! * §9.3.2.2 — [`ContextModel::init`] (equations 9-4, 9-5, 9-6) plus | ||
| 18 | +//! the §9.3.2.2 `initType` derivation (equation 9-7, | ||
| 19 | +//! [`init_type`]). A context variable is a `(pStateIdx, valMps)` | ||
| 20 | +//! pair derived from an 8-bit `initValue` and the slice QP. | ||
| 21 | +//! * §9.3.4.3.2 — [`CabacEngine::decode_decision`] (DecodeDecision): | ||
| 22 | +//! the regular context-coded bin, with the Table 9-52 `rangeTabLps` | ||
| 23 | +//! interval split, the §9.3.4.3.2.2 state transition (Table 9-53), | ||
| 24 | +//! and the §9.3.4.3.3 renormalization. | ||
| 25 | +//! * §9.3.4.3.4 — [`CabacEngine::decode_bypass`] (DecodeBypass): the | ||
| 26 | +//! equal-probability bin. | ||
| 27 | +//! * §9.3.4.3.5 — [`CabacEngine::decode_terminate`] (DecodeTerminate): | ||
| 28 | +//! the `end_of_slice_segment_flag` / `end_of_subset_one_bit` / | ||
| 29 | +//! `pcm_flag` decision before termination. | ||
| 30 | +//! * §9.3.4.3.6 — [`CabacEngine::align`] (the alignment process prior | ||
| 31 | +//! to aligned bypass decoding for `coeff_abs_level_remaining[ ]` / | ||
| 32 | +//! `coeff_sign_flag[ ]`): `ivlCurrRange = 256`. | ||
| 33 | +//! | ||
| 34 | +//! The Table 9-52 / Table 9-53 values are transcribed directly from the | ||
| 35 | +//! H.265 specification text (`docs/video/h265/`). They are arithmetic | ||
| 36 | +//! constants of the format, not external-library code. | ||
| 37 | +//! | ||
| 38 | +//! # Bit source | ||
| 39 | +//! | ||
| 40 | +//! The engine reads raw bits via [`BitReader`] (`read_bits(1)` in the | ||
| 41 | +//! spec is [`BitReader::u1`], `read_bits(9)` is `BitReader::u(9)`). The | ||
| 42 | +//! caller positions the reader at the first byte of `slice_segment_data()` | ||
| 43 | +//! — for example via | ||
| 44 | +//! [`crate::slice::SliceSegmentHeader::byte_offset_to_slice_data`] — and | ||
| 45 | +//! then constructs the engine, which immediately consumes the 9-bit | ||
| 46 | +//! initial `ivlOffset` per §9.3.2.6. | ||
| 47 | + | ||
| 48 | +use crate::bitreader::{BitReader, BitReaderError}; | ||
| 49 | + | ||
| 50 | +/// Errors that can arise while running the CABAC decode engine. | ||
| 51 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 52 | +pub enum CabacError { | ||
| 53 | + /// The bit reader ran out of bits (a `read_bits()` past the end of | ||
| 54 | + /// the slice-segment-data buffer). A conforming bitstream never | ||
| 55 | + /// reaches this state during a valid decode, so it indicates a | ||
| 56 | + /// truncated or malformed stream. | ||
| 57 | + EndOfBuffer, | ||
| 58 | + /// §9.3.2.6 forbids `ivlOffset` taking the value 510 or 511 after | ||
| 59 | + /// the initial 9-bit read ("The bitstream shall not contain data | ||
| 60 | + /// that result in a value of ivlOffset being equal to 510 or | ||
| 61 | + /// 511."). | ||
| 62 | + InvalidInitOffset(u16), | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +impl core::fmt::Display for CabacError { | ||
| 66 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| 67 | + match self { | ||
| 68 | + Self::EndOfBuffer => f.write_str("CABAC engine read past end of slice-data buffer"), | ||
| 69 | + Self::InvalidInitOffset(v) => { | ||
| 70 | + write!(f, "CABAC init ivlOffset {v} is forbidden (must be < 510)") | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +impl std::error::Error for CabacError {} | ||
| 77 | + | ||
| 78 | +impl From<BitReaderError> for CabacError { | ||
| 79 | + fn from(_: BitReaderError) -> Self { | ||
| 80 | + // The only `BitReaderError` the engine can provoke is running | ||
| 81 | + // out of bits — every other `BitReader` failure mode (too many | ||
| 82 | + // bits, Exp-Golomb overflow) is unreachable from `u1()` / | ||
| 83 | + // `u(9)`. | ||
| 84 | + Self::EndOfBuffer | ||
| 85 | + } | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// The §9.3.2.2 `initType` selector (equation 9-7). `slice_type` is the | ||
| 89 | +/// §7.4.7.1 enum (0 = B, 1 = P, 2 = I); `cabac_init_flag` is the | ||
| 90 | +/// slice-header flag (only present for P / B slices). | ||
| 91 | +/// | ||
| 92 | +/// ```text | ||
| 93 | +/// if( slice_type == I ) initType = 0 | ||
| 94 | +/// else if( slice_type == P ) initType = cabac_init_flag ? 2 : 1 | ||
| 95 | +/// else /* B */ initType = cabac_init_flag ? 1 : 2 | ||
| 96 | +/// ``` | ||
| 97 | +/// | ||
| 98 | +/// `slice_type` here uses [`crate::slice::SliceType`]'s numeric values: | ||
| 99 | +/// `SliceType::B == 0`, `SliceType::P == 1`, `SliceType::I == 2`. | ||
| 100 | +#[must_use] | ||
| 101 | +pub fn init_type(slice_type: u8, cabac_init_flag: bool) -> u8 { | ||
| 102 | + match slice_type { | ||
| 103 | + // I slice. | ||
| 104 | + 2 => 0, | ||
| 105 | + // P slice. | ||
| 106 | + 1 => { | ||
| 107 | + if cabac_init_flag { | ||
| 108 | + 2 | ||
| 109 | + } else { | ||
| 110 | + 1 | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + // B slice (any other slice_type value funnels here). | ||
| 114 | + _ => { | ||
| 115 | + if cabac_init_flag { | ||
| 116 | + 1 | ||
| 117 | + } else { | ||
| 118 | + 2 | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + } | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// A single CABAC context variable: the §9.3.4.3 probability-state | ||
| 125 | +/// index `pStateIdx` (0..=63) paired with the most-probable-symbol | ||
| 126 | +/// value `valMps` (0 or 1). | ||
| 127 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 128 | +pub struct ContextModel { | ||
| 129 | + /// §9.3.4.3 probability state index, 0..=63. State 0 is the | ||
| 130 | + /// `pLPS == 0.5` extreme; higher indices have lower LPS | ||
| 131 | + /// probability. | ||
| 132 | + pub p_state_idx: u8, | ||
| 133 | + /// The value of the most probable symbol (0 or 1). | ||
| 134 | + pub val_mps: u8, | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +impl ContextModel { | ||
| 138 | + /// §9.3.2.2 context-variable initialization (equations 9-4, 9-5, | ||
| 139 | + /// 9-6). `init_value` is the 8-bit `initValue` table entry for the | ||
| 140 | + /// context; `slice_qp_y` is `SliceQpY` (equation 7-54). | ||
| 141 | + /// | ||
| 142 | + /// ```text | ||
| 143 | + /// slopeIdx = initValue >> 4 | ||
| 144 | + /// offsetIdx = initValue & 15 (9-4) | ||
| 145 | + /// m = slopeIdx * 5 − 45 | ||
| 146 | + /// n = ( offsetIdx << 3 ) − 16 (9-5) | ||
| 147 | + /// preCtxState = Clip3( 1, 126, | ||
| 148 | + /// ( ( m * Clip3( 0, 51, SliceQpY ) ) >> 4 ) + n ) | ||
| 149 | + /// valMps = ( preCtxState <= 63 ) ? 0 : 1 | ||
| 150 | + /// pStateIdx = valMps ? ( preCtxState − 64 ) : ( 63 − preCtxState ) (9-6) | ||
| 151 | + /// ``` | ||
| 152 | + /// | ||
| 153 | + /// The `>> 4` in equation 9-6 is an arithmetic shift of a signed | ||
| 154 | + /// product (`m` can be negative); this is reproduced with signed | ||
| 155 | + /// arithmetic. | ||
| 156 | + #[must_use] | ||
| 157 | + pub fn init(init_value: u8, slice_qp_y: i32) -> Self { | ||
| 158 | + // Equation 9-4. | ||
| 159 | + let slope_idx = (init_value >> 4) as i32; | ||
| 160 | + let offset_idx = (init_value & 15) as i32; | ||
| 161 | + // Equation 9-5. | ||
| 162 | + let m = slope_idx * 5 - 45; | ||
| 163 | + let n = (offset_idx << 3) - 16; | ||
| 164 | + // Equation 9-6: Clip3(0, 51, SliceQpY) then the signed | ||
| 165 | + // arithmetic-shift product, then Clip3(1, 126, …). | ||
| 166 | + let qp = slice_qp_y.clamp(0, 51); | ||
| 167 | + let pre_ctx_state = (((m * qp) >> 4) + n).clamp(1, 126); | ||
| 168 | + let (val_mps, p_state_idx) = if pre_ctx_state <= 63 { | ||
| 169 | + (0u8, (63 - pre_ctx_state) as u8) | ||
| 170 | + } else { | ||
| 171 | + (1u8, (pre_ctx_state - 64) as u8) | ||
| 172 | + }; | ||
| 173 | + Self { | ||
| 174 | + p_state_idx, | ||
| 175 | + val_mps, | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | + | ||
| 179 | + /// The non-adapting state described in §9.3.2.2 NOTE 2 for | ||
| 180 | + /// `ctxTable == 0`, `ctxIdx == 0` (the `end_of_slice_segment_flag` | ||
| 181 | + /// / `end_of_subset_one_bit` / `pcm_flag` decision when emulated | ||
| 182 | + /// through DecodeDecision): `pStateIdx = 63`, `valMps = 0`. | ||
| 183 | + /// `decode_terminate` does not need this state — it is provided for | ||
| 184 | + /// completeness of the model. | ||
| 185 | + #[must_use] | ||
| 186 | + pub fn terminate_state() -> Self { | ||
| 187 | + Self { | ||
| 188 | + p_state_idx: 63, | ||
| 189 | + val_mps: 0, | ||
| 190 | + } | ||
| 191 | + } | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// Table 9-52 — `rangeTabLps[ pStateIdx ][ qRangeIdx ]`. 64 states × | ||
| 195 | +/// 4 quantized-range columns. Transcribed from the H.265 specification | ||
| 196 | +/// text (§9.3.4.3.2.1). | ||
| 197 | +#[rustfmt::skip] | ||
| 198 | +pub(crate) const RANGE_TAB_LPS: [[u8; 4]; 64] = [ | ||
| 199 | + [128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205], | ||
| 200 | + [116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166], | ||
| 201 | + [ 95, 116, 137, 158], [ 90, 110, 130, 150], [ 85, 104, 123, 142], [ 81, 99, 117, 135], | ||
| 202 | + [ 77, 94, 111, 128], [ 73, 89, 105, 122], [ 69, 85, 100, 116], [ 66, 80, 95, 110], | ||
| 203 | + [ 62, 76, 90, 104], [ 59, 72, 86, 99], [ 56, 69, 81, 94], [ 53, 65, 77, 89], | ||
| 204 | + [ 51, 62, 73, 85], [ 48, 59, 69, 80], [ 46, 56, 66, 76], [ 43, 53, 63, 72], | ||
| 205 | + [ 41, 50, 59, 69], [ 39, 48, 56, 65], [ 37, 45, 54, 62], [ 35, 43, 51, 59], | ||
| 206 | + [ 33, 41, 48, 56], [ 32, 39, 46, 53], [ 30, 37, 43, 50], [ 29, 35, 41, 48], | ||
| 207 | + [ 27, 33, 39, 45], [ 26, 31, 37, 43], [ 24, 30, 35, 41], [ 23, 28, 33, 39], | ||
| 208 | + [ 22, 27, 32, 37], [ 21, 26, 30, 35], [ 20, 24, 29, 33], [ 19, 23, 27, 31], | ||
| 209 | + [ 18, 22, 26, 30], [ 17, 21, 25, 28], [ 16, 20, 23, 27], [ 15, 19, 22, 25], | ||
| 210 | + [ 14, 18, 21, 24], [ 14, 17, 20, 23], [ 13, 16, 19, 22], [ 12, 15, 18, 21], | ||
| 211 | + [ 12, 14, 17, 20], [ 11, 14, 16, 19], [ 11, 13, 15, 18], [ 10, 12, 15, 17], | ||
| 212 | + [ 10, 12, 14, 16], [ 9, 11, 13, 15], [ 9, 11, 12, 14], [ 8, 10, 12, 14], | ||
| 213 | + [ 8, 9, 11, 13], [ 7, 9, 11, 12], [ 7, 9, 10, 12], [ 7, 8, 10, 11], | ||
| 214 | + [ 6, 8, 9, 11], [ 6, 7, 9, 10], [ 6, 7, 8, 9], [ 2, 2, 2, 2], | ||
| 215 | +]; | ||
| 216 | + | ||
| 217 | +/// Table 9-53 — `transIdxLps[ pStateIdx ]`, the probability-state | ||
| 218 | +/// transition after decoding the LPS (`1 − valMps`). Transcribed from | ||
| 219 | +/// the H.265 specification text (§9.3.4.3.2.2). | ||
| 220 | +#[rustfmt::skip] | ||
| 221 | +pub(crate) const TRANS_IDX_LPS: [u8; 64] = [ | ||
| 222 | + 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, | ||
| 223 | + 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24, | ||
| 224 | + 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, | ||
| 225 | + 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, | ||
| 226 | +]; | ||
| 227 | + | ||
| 228 | +/// Table 9-53 — `transIdxMps[ pStateIdx ]`, the probability-state | ||
| 229 | +/// transition after decoding the MPS (`valMps`). Transcribed from the | ||
| 230 | +/// H.265 specification text (§9.3.4.3.2.2). | ||
| 231 | +#[rustfmt::skip] | ||
| 232 | +pub(crate) const TRANS_IDX_MPS: [u8; 64] = [ | ||
| 233 | + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, | ||
| 234 | + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, | ||
| 235 | + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, | ||
| 236 | + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, | ||
| 237 | +]; | ||
| 238 | + | ||
| 239 | +/// The §9.3.4.3 arithmetic decoding engine state plus its bit source. | ||
| 240 | +/// | ||
| 241 | +/// The engine holds the two §9.3.2.6 registers `ivlCurrRange` and | ||
| 242 | +/// `ivlOffset` and the [`BitReader`] from which renormalization / | ||
| 243 | +/// bypass pull `read_bits(1)`. Context variables ([`ContextModel`]) | ||
| 244 | +/// live in the caller's context-model array; each | ||
| 245 | +/// [`decode_decision`](CabacEngine::decode_decision) call takes and | ||
| 246 | +/// mutates one in place. | ||
| 247 | +#[derive(Debug)] | ||
| 248 | +pub struct CabacEngine<'a> { | ||
| 249 | + reader: BitReader<'a>, | ||
| 250 | + /// §9.3.2.6 `ivlCurrRange` (held in a 16-bit-wide register; values | ||
| 251 | + /// stay within 9 bits during decode). | ||
| 252 | + ivl_curr_range: u16, | ||
| 253 | + /// §9.3.2.6 `ivlOffset` (10-bit register precision is required for | ||
| 254 | + /// bypass). | ||
| 255 | + ivl_offset: u16, | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +impl<'a> CabacEngine<'a> { | ||
| 259 | + /// §9.3.2.6 — construct and initialize the arithmetic decoding | ||
| 260 | + /// engine over `reader`, which the caller has positioned at the | ||
| 261 | + /// first bit of `slice_segment_data()`. Sets `ivlCurrRange = 510` | ||
| 262 | + /// and `ivlOffset = read_bits(9)`, and validates the §9.3.2.6 | ||
| 263 | + /// constraint that `ivlOffset` is not 510 or 511. | ||
| 264 | + pub fn new(mut reader: BitReader<'a>) -> Result<Self, CabacError> { | ||
| 265 | + let ivl_offset = reader.u(9)? as u16; | ||
| 266 | + if ivl_offset >= 510 { | ||
| 267 | + return Err(CabacError::InvalidInitOffset(ivl_offset)); | ||
| 268 | + } | ||
| 269 | + Ok(Self { | ||
| 270 | + reader, | ||
| 271 | + ivl_curr_range: 510, | ||
| 272 | + ivl_offset, | ||
| 273 | + }) | ||
| 274 | + } | ||
| 275 | + | ||
| 276 | + /// §9.3.2.6 — re-initialize the engine registers on an already | ||
| 277 | + /// constructed engine (e.g. after `pcm_flag == 1` data is consumed, | ||
| 278 | + /// per §9.3.2.5 / §9.3.2.6). The bit reader is *not* repositioned; | ||
| 279 | + /// the caller is responsible for having advanced it to the byte | ||
| 280 | + /// boundary following the PCM samples before calling this. | ||
| 281 | + pub fn init_engine(&mut self) -> Result<(), CabacError> { | ||
| 282 | + let ivl_offset = self.reader.u(9)? as u16; | ||
| 283 | + if ivl_offset >= 510 { | ||
| 284 | + return Err(CabacError::InvalidInitOffset(ivl_offset)); | ||
| 285 | + } | ||
| 286 | + self.ivl_curr_range = 510; | ||
| 287 | + self.ivl_offset = ivl_offset; | ||
| 288 | + Ok(()) | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + /// Current `ivlCurrRange` register value (for tests / inspection). | ||
| 292 | + #[must_use] | ||
| 293 | + pub fn ivl_curr_range(&self) -> u16 { | ||
| 294 | + self.ivl_curr_range | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + /// §9.3.4.3.6 — alignment process prior to aligned bypass | ||
| 298 | + /// decoding: `ivlCurrRange` is set equal to 256. Invoked when | ||
| 299 | + /// `cabac_bypass_alignment_enabled_flag == 1` before the bypass | ||
| 300 | + /// decoding of `coeff_sign_flag[ ]` / `coeff_abs_level_remaining[ | ||
| 301 | + /// ]` (and the §7.3.8.13 palette escape group) when | ||
| 302 | + /// `escapeDataPresent == 1`. After alignment every bypass bin | ||
| 303 | + /// consumes exactly one stream bit (the NOTE's shift-register | ||
| 304 | + /// view); bypass decoding itself never changes `ivlCurrRange`, so | ||
| 305 | + /// repeated invocations inside one aligned run are no-ops. | ||
| 306 | + pub fn align_bypass(&mut self) { | ||
| 307 | + self.ivl_curr_range = 256; | ||
| 308 | + } | ||
| 309 | + | ||
| 310 | + /// Current `ivlOffset` register value (for tests / inspection). | ||
| 311 | + #[must_use] | ||
| 312 | + pub fn ivl_offset(&self) -> u16 { | ||
| 313 | + self.ivl_offset | ||
| 314 | + } | ||
| 315 | + | ||
| 316 | + /// Bit position of the underlying reader (for tests / locating the | ||
| 317 | + /// engine's consumption point in the buffer). | ||
| 318 | + #[must_use] | ||
| 319 | + pub fn bit_pos(&self) -> usize { | ||
| 320 | + self.reader.bit_pos() | ||
| 321 | + } | ||
| 322 | + | ||
| 323 | + /// §7.3.8.7 support — consume `pcm_alignment_zero_bit` from the | ||
| 324 | + /// raw bit source until it is byte-aligned. Called right after a | ||
| 325 | + /// `pcm_flag == 1` terminate bin: §9.3.4.3.5 leaves the bitstream | ||
| 326 | + /// pointer directly after the terminating one bit, so the raw | ||
| 327 | + /// reader position is authoritative for `byte_aligned()`. | ||
| 328 | + /// | ||
| 329 | + /// # Errors | ||
| 330 | + /// [`CabacError::EndOfBuffer`] on a truncated stream. | ||
| 331 | + pub fn pcm_align(&mut self) -> Result<(), CabacError> { | ||
| 332 | + while self.reader.bit_pos() % 8 != 0 { | ||
| 333 | + let _ = self.reader.u1()?; | ||
| 334 | + } | ||
| 335 | + Ok(()) | ||
| 336 | + } | ||
| 337 | + | ||
| 338 | + /// §7.3.8.7 support — read one raw `u(n)` field (a | ||
| 339 | + /// `pcm_sample_luma` / `pcm_sample_chroma` value) directly from the | ||
| 340 | + /// bit source, bypassing the arithmetic engine. | ||
| 341 | + /// | ||
| 342 | + /// # Errors | ||
| 343 | + /// [`CabacError::EndOfBuffer`] on a truncated stream. | ||
| 344 | + pub fn read_raw_bits(&mut self, n: u8) -> Result<u32, CabacError> { | ||
| 345 | + Ok(self.reader.u(n)?) | ||
| 346 | + } | ||
| 347 | + | ||
| 348 | + /// Consume the engine and hand back its bit source (tests / callers | ||
| 349 | + /// that continue non-CABAC parsing after termination). | ||
| 350 | + #[must_use] | ||
| 351 | + pub fn into_reader(self) -> BitReader<'a> { | ||
| 352 | + self.reader | ||
| 353 | + } | ||
| 354 | + | ||
| 355 | + /// §9.3.4.3.3 — renormalization in the arithmetic decoding engine | ||
| 356 | + /// (RenormD). While `ivlCurrRange < 256`, double `ivlCurrRange` and | ||
| 357 | + /// shift one fresh bit into `ivlOffset`. | ||
| 358 | + fn renorm(&mut self) -> Result<(), CabacError> { | ||
| 359 | + while self.ivl_curr_range < 256 { | ||
| 360 | + self.ivl_curr_range <<= 1; | ||
| 361 | + let bit = self.reader.u1()? as u16; | ||
| 362 | + self.ivl_offset = (self.ivl_offset << 1) | bit; | ||
| 363 | + } | ||
| 364 | + Ok(()) | ||
| 365 | + } | ||
| 366 | + | ||
| 367 | + /// §9.3.4.3.2 — DecodeDecision: decode one regular context-coded | ||
| 368 | + /// bin against the supplied context variable `ctx`, mutating it | ||
| 369 | + /// per the §9.3.4.3.2.2 state-transition process. Returns the | ||
| 370 | + /// decoded bin value (0 or 1). | ||
| 371 | + pub fn decode_decision(&mut self, ctx: &mut ContextModel) -> Result<u8, CabacError> { | ||
| 372 | + // Step 1 (equations 9-64, 9-65): the LPS sub-range. | ||
| 373 | + let q_range_idx = ((self.ivl_curr_range >> 6) & 3) as usize; | ||
| 374 | + let ivl_lps_range = RANGE_TAB_LPS[ctx.p_state_idx as usize][q_range_idx] as u16; | ||
| 375 | + | ||
| 376 | + // Step 2: subtract the LPS range; compare ivlOffset. | ||
| 377 | + self.ivl_curr_range -= ivl_lps_range; | ||
| 378 | + let bin_val; | ||
| 379 | + if self.ivl_offset >= self.ivl_curr_range { | ||
| 380 | + // LPS path. | ||
| 381 | + bin_val = 1 - ctx.val_mps; | ||
| 382 | + self.ivl_offset -= self.ivl_curr_range; | ||
| 383 | + self.ivl_curr_range = ivl_lps_range; | ||
| 384 | + } else { | ||
| 385 | + // MPS path. | ||
| 386 | + bin_val = ctx.val_mps; | ||
| 387 | + } | ||
| 388 | + | ||
| 389 | + // §9.3.4.3.2.2 state transition (equation 9-66). | ||
| 390 | + if bin_val == ctx.val_mps { | ||
| 391 | + ctx.p_state_idx = TRANS_IDX_MPS[ctx.p_state_idx as usize]; | ||
| 392 | + } else { | ||
| 393 | + if ctx.p_state_idx == 0 { | ||
| 394 | + ctx.val_mps = 1 - ctx.val_mps; | ||
| 395 | + } | ||
| 396 | + ctx.p_state_idx = TRANS_IDX_LPS[ctx.p_state_idx as usize]; | ||
| 397 | + } | ||
| 398 | + | ||
| 399 | + // §9.3.4.3.3 renormalization. | ||
| 400 | + self.renorm()?; | ||
| 401 | + Ok(bin_val) | ||
| 402 | + } | ||
| 403 | + | ||
| 404 | + /// §9.3.4.3.4 — DecodeBypass: decode one equal-probability bin. | ||
| 405 | + /// Doubles `ivlOffset` (shifting in one fresh bit), then compares | ||
| 406 | + /// against `ivlCurrRange`. Returns the decoded bin (0 or 1). | ||
| 407 | + pub fn decode_bypass(&mut self) -> Result<u8, CabacError> { | ||
| 408 | + let bit = self.reader.u1()? as u16; | ||
| 409 | + self.ivl_offset = (self.ivl_offset << 1) | bit; | ||
| 410 | + if self.ivl_offset >= self.ivl_curr_range { | ||
| 411 | + self.ivl_offset -= self.ivl_curr_range; | ||
| 412 | + Ok(1) | ||
| 413 | + } else { | ||
| 414 | + Ok(0) | ||
| 415 | + } | ||
| 416 | + } | ||
| 417 | + | ||
| 418 | + /// §9.3.4.3.4 — convenience wrapper: decode `n` bypass bins | ||
| 419 | + /// MSB-first and accumulate them into an integer (`n` in 0..=32). | ||
| 420 | + /// This is the common pattern for fixed-length bypass-coded fields. | ||
| 421 | + /// `n == 0` returns 0 and consumes nothing. | ||
| 422 | + pub fn decode_bypass_bits(&mut self, n: u8) -> Result<u32, CabacError> { | ||
| 423 | + let mut value: u32 = 0; | ||
| 424 | + for _ in 0..n { | ||
| 425 | + value = (value << 1) | (self.decode_bypass()? as u32); | ||
| 426 | + } | ||
| 427 | + Ok(value) | ||
| 428 | + } | ||
| 429 | + | ||
| 430 | + /// §9.3.4.3.5 — DecodeTerminate: the decision before termination | ||
| 431 | + /// (`end_of_slice_segment_flag`, `end_of_subset_one_bit`, | ||
| 432 | + /// `pcm_flag`; `ctxTable == 0`, `ctxIdx == 0`). Decrements | ||
| 433 | + /// `ivlCurrRange` by 2; if `ivlOffset >= ivlCurrRange` the result | ||
| 434 | + /// is 1 (no renormalization, decoding is terminated), otherwise the | ||
| 435 | + /// result is 0 and renormalization is applied. | ||
| 436 | + pub fn decode_terminate(&mut self) -> Result<u8, CabacError> { | ||
| 437 | + self.ivl_curr_range -= 2; | ||
| 438 | + if self.ivl_offset >= self.ivl_curr_range { | ||
| 439 | + Ok(1) | ||
| 440 | + } else { | ||
| 441 | + self.renorm()?; | ||
| 442 | + Ok(0) | ||
| 443 | + } | ||
| 444 | + } | ||
| 445 | + | ||
| 446 | + /// §9.3.4.3.6 — alignment process prior to aligned bypass decoding | ||
| 447 | + /// (applied before `coeff_abs_level_remaining[ ]` and | ||
| 448 | + /// `coeff_sign_flag[ ]`): `ivlCurrRange = 256`. The bit reader and | ||
| 449 | + /// `ivlOffset` are left untouched. | ||
| 450 | + pub fn align(&mut self) { | ||
| 451 | + self.ivl_curr_range = 256; | ||
| 452 | + } | ||
| 453 | +} | ||
| 454 | + | ||
| 455 | +#[cfg(test)] | ||
| 456 | +mod tests { | ||
| 457 | + use super::*; | ||
| 458 | + | ||
| 459 | + // --- §9.3.2.2 context-variable init (equations 9-4..9-6) --- | ||
| 460 | + | ||
| 461 | + #[test] | ||
| 462 | + fn init_type_eq_9_7() { | ||
| 463 | + // I slice (slice_type == 2) → 0 regardless of cabac_init_flag. | ||
| 464 | + assert_eq!(init_type(2, false), 0); | ||
| 465 | + assert_eq!(init_type(2, true), 0); | ||
| 466 | + // P slice (slice_type == 1). | ||
| 467 | + assert_eq!(init_type(1, false), 1); | ||
| 468 | + assert_eq!(init_type(1, true), 2); | ||
| 469 | + // B slice (slice_type == 0). | ||
| 470 | + assert_eq!(init_type(0, false), 2); | ||
| 471 | + assert_eq!(init_type(0, true), 1); | ||
| 472 | + } | ||
| 473 | + | ||
| 474 | + #[test] | ||
| 475 | + fn context_init_worked_example() { | ||
| 476 | + // Hand-evaluate equations 9-4..9-6 for initValue = 154, | ||
| 477 | + // SliceQpY = 26 (a common mid-range QP). | ||
| 478 | + // slopeIdx = 154 >> 4 = 9 | ||
| 479 | + // offsetIdx = 154 & 15 = 10 | ||
| 480 | + // m = 9*5 - 45 = 0 | ||
| 481 | + // n = (10 << 3) - 16 = 64 | ||
| 482 | + // preCtxState = Clip3(1,126, (0*26 >> 4) + 64) = 64 | ||
| 483 | + // valMps = (64 <= 63) ? 0 : 1 = 1 | ||
| 484 | + // pStateIdx = 1 ? (64-64) : … = 0 | ||
| 485 | + let c = ContextModel::init(154, 26); | ||
| 486 | + assert_eq!(c.val_mps, 1); | ||
| 487 | + assert_eq!(c.p_state_idx, 0); | ||
| 488 | + } | ||
| 489 | + | ||
| 490 | + #[test] | ||
| 491 | + fn context_init_negative_slope() { | ||
| 492 | + // initValue = 0, SliceQpY = 51 (max). Exercises a negative m | ||
| 493 | + // and the signed arithmetic shift in equation 9-6. | ||
| 494 | + // slopeIdx = 0, offsetIdx = 0 | ||
| 495 | + // m = -45, n = -16 | ||
| 496 | + // m*Clip3(0,51,51) = -45*51 = -2295 | ||
| 497 | + // -2295 >> 4 = -144 (arithmetic shift toward -inf) | ||
| 498 | + // preCtxState = Clip3(1,126, -144 + -16) = Clip3(1,126,-160) = 1 | ||
| 499 | + // valMps = (1 <= 63) ? 0 : 1 = 0 | ||
| 500 | + // pStateIdx = 0 ? … : (63 - 1) = 62 | ||
| 501 | + let c = ContextModel::init(0, 51); | ||
| 502 | + assert_eq!(c.val_mps, 0); | ||
| 503 | + assert_eq!(c.p_state_idx, 62); | ||
| 504 | + } | ||
| 505 | + | ||
| 506 | + #[test] | ||
| 507 | + fn context_init_high_initvalue() { | ||
| 508 | + // initValue = 255, SliceQpY = 0. Drives preCtxState toward the | ||
| 509 | + // high clip. | ||
| 510 | + // slopeIdx = 15, offsetIdx = 15 | ||
| 511 | + // m = 15*5 - 45 = 30 | ||
| 512 | + // n = (15 << 3) - 16 = 104 | ||
| 513 | + // preCtxState = Clip3(1,126, (30*0 >> 4) + 104) = 104 | ||
| 514 | + // valMps = (104 <= 63) ? 0 : 1 = 1 | ||
| 515 | + // pStateIdx = 104 - 64 = 40 | ||
| 516 | + let c = ContextModel::init(255, 0); | ||
| 517 | + assert_eq!(c.val_mps, 1); | ||
| 518 | + assert_eq!(c.p_state_idx, 40); | ||
| 519 | + } | ||
| 520 | + | ||
| 521 | + #[test] | ||
| 522 | + fn context_init_clips_low_qp_range() { | ||
| 523 | + // SliceQpY below 0 is clipped to 0 by Clip3(0,51,SliceQpY); | ||
| 524 | + // verify the negative-QP input lands at the same state as QP 0. | ||
| 525 | + let c_neg = ContextModel::init(154, -10); | ||
| 526 | + let c_zero = ContextModel::init(154, 0); | ||
| 527 | + assert_eq!(c_neg, c_zero); | ||
| 528 | + } | ||
| 529 | + | ||
| 530 | + #[test] | ||
| 531 | + fn terminate_state_is_non_adapting() { | ||
| 532 | + // §9.3.2.2 NOTE 2: pStateIdx = 63, valMps = 0. | ||
| 533 | + let c = ContextModel::terminate_state(); | ||
| 534 | + assert_eq!(c.p_state_idx, 63); | ||
| 535 | + assert_eq!(c.val_mps, 0); | ||
| 536 | + } | ||
| 537 | + | ||
| 538 | + // --- Table integrity --- | ||
| 539 | + | ||
| 540 | + #[test] | ||
| 541 | + fn range_tab_lps_corner_values() { | ||
| 542 | + // Spot-check the four corners of Table 9-52. | ||
| 543 | + assert_eq!(RANGE_TAB_LPS[0], [128, 176, 208, 240]); | ||
| 544 | + assert_eq!(RANGE_TAB_LPS[31], [29, 35, 41, 48]); | ||
| 545 | + assert_eq!(RANGE_TAB_LPS[32], [27, 33, 39, 45]); | ||
| 546 | + assert_eq!(RANGE_TAB_LPS[63], [2, 2, 2, 2]); | ||
| 547 | + // The whole table is non-increasing down each column (a | ||
| 548 | + // structural property of the LPS-range quantization). | ||
| 549 | + for (s, row) in RANGE_TAB_LPS.iter().enumerate().skip(1) { | ||
| 550 | + let prev = &RANGE_TAB_LPS[s - 1]; | ||
| 551 | + for (col, (cur, p)) in row.iter().zip(prev.iter()).enumerate() { | ||
| 552 | + assert!(cur <= p, "column {col} not non-increasing at state {s}"); | ||
| 553 | + } | ||
| 554 | + } | ||
| 555 | + } | ||
| 556 | + | ||
| 557 | + #[test] | ||
| 558 | + fn trans_idx_tables_bounds_and_endpoints() { | ||
| 559 | + // Every transition target is a valid state index (0..=63). | ||
| 560 | + for s in 0..64usize { | ||
| 561 | + assert!(TRANS_IDX_LPS[s] < 64); | ||
| 562 | + assert!(TRANS_IDX_MPS[s] < 64); | ||
| 563 | + } | ||
| 564 | + // State 0 LPS stays at 0; state 63 is the absorbing terminal | ||
| 565 | + // state for both transitions. | ||
| 566 | + assert_eq!(TRANS_IDX_LPS[0], 0); | ||
| 567 | + assert_eq!(TRANS_IDX_MPS[63], 63); | ||
| 568 | + assert_eq!(TRANS_IDX_LPS[63], 63); | ||
| 569 | + // transIdxMps is monotonically non-decreasing — confidence | ||
| 570 | + // never goes backward after an MPS. (Equality is allowed near | ||
| 571 | + // the upper extreme: index 62 maps to 62 in Table 9-53.) | ||
| 572 | + for (s, &mps) in TRANS_IDX_MPS.iter().enumerate().take(63) { | ||
| 573 | + assert!( | ||
| 574 | + mps >= s as u8, | ||
| 575 | + "transIdxMps[{s}] = {mps} is below the state" | ||
| 576 | + ); | ||
| 577 | + } | ||
| 578 | + // transIdxLps is monotonically non-decreasing too (LPS at a | ||
| 579 | + // high-confidence state drops to a less-confident state, but | ||
| 580 | + // not below the LPS landing at a lower state). | ||
| 581 | + for win in TRANS_IDX_LPS.windows(2) { | ||
| 582 | + assert!(win[1] >= win[0]); | ||
| 583 | + } | ||
| 584 | + } | ||
| 585 | + | ||
| 586 | + // --- §9.3.2.6 engine init --- | ||
| 587 | + | ||
| 588 | + #[test] | ||
| 589 | + fn engine_init_reads_nine_bit_offset() { | ||
| 590 | + // First 9 bits = "1 01010101" = 341; ivlCurrRange = 510. | ||
| 591 | + // byte0 = 0b10101010, byte1 MSB = 1 → 9-bit value 0x155 = 341. | ||
| 592 | + let buf = [0b1010_1010, 0b1000_0000]; | ||
| 593 | + let eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 594 | + assert_eq!(eng.ivl_curr_range(), 510); | ||
| 595 | + assert_eq!(eng.ivl_offset(), 341); | ||
| 596 | + assert_eq!(eng.bit_pos(), 9); | ||
| 597 | + } | ||
| 598 | + | ||
| 599 | + #[test] | ||
| 600 | + fn engine_init_rejects_offset_510_511() { | ||
| 601 | + // 9 bits = 0x1FE = 510 → forbidden. byte0 = 0xFF, byte1 MSB | ||
| 602 | + // = 0. | ||
| 603 | + let buf = [0xFF, 0b0000_0000]; | ||
| 604 | + match CabacEngine::new(BitReader::new(&buf)) { | ||
| 605 | + Err(CabacError::InvalidInitOffset(510)) => {} | ||
| 606 | + other => panic!("expected InvalidInitOffset(510), got {other:?}"), | ||
| 607 | + } | ||
| 608 | + // 9 bits = 0x1FF = 511 → forbidden. byte0 = 0xFF, byte1 MSB | ||
| 609 | + // = 1. | ||
| 610 | + let buf = [0xFF, 0b1000_0000]; | ||
| 611 | + match CabacEngine::new(BitReader::new(&buf)) { | ||
| 612 | + Err(CabacError::InvalidInitOffset(511)) => {} | ||
| 613 | + other => panic!("expected InvalidInitOffset(511), got {other:?}"), | ||
| 614 | + } | ||
| 615 | + // 509 is allowed: 0x1FD; byte0 = 0xFE, byte1 MSB = 1. | ||
| 616 | + let buf = [0xFE, 0b1000_0000]; | ||
| 617 | + assert!(CabacEngine::new(BitReader::new(&buf)).is_ok()); | ||
| 618 | + } | ||
| 619 | + | ||
| 620 | + // --- §9.3.4.3.4 bypass --- | ||
| 621 | + | ||
| 622 | + #[test] | ||
| 623 | + fn bypass_reads_bits_msb_first() { | ||
| 624 | + // After init, ivlCurrRange = 510, ivlOffset is the first 9 | ||
| 625 | + // bits. Each bypass doubles ivlOffset (shift in one bit) and | ||
| 626 | + // compares to 510. | ||
| 627 | + // | ||
| 628 | + // Construct so the bypass bins are deterministic. Init offset | ||
| 629 | + // = 0 (9 zero bits at stream bits 0..=8). The next 4 stream | ||
| 630 | + // bits feed four bypass decisions and must come out MSB-first. | ||
| 631 | + // 9 init bits use byte0 (bits 0..=7) and bit 8 = byte1 MSB. | ||
| 632 | + // For init = 0, byte0 = 0x00 and byte1 MSB = 0. The bypass | ||
| 633 | + // bits start at stream bit 9 = byte1 bits 1..=4. We want them | ||
| 634 | + // to be 1, 0, 1, 1 → byte1 bits 1..=4 = 1011 → byte1 LSBs are | ||
| 635 | + // ignored, byte1 = 0b0_1011_000 = 0x58. | ||
| 636 | + // bin0: offset = (0<<1)|1 = 1; 1 < 510 → 0 | ||
| 637 | + // bin1: offset = (1<<1)|0 = 2; 2 < 510 → 0 | ||
| 638 | + // bin2: offset = (2<<1)|1 = 5; 5 < 510 → 0 | ||
| 639 | + // bin3: offset = (5<<1)|1 = 11; 11 < 510 → 0 | ||
| 640 | + // Small offsets always yield 0 — verify offset accumulation. | ||
| 641 | + let buf = [0x00, 0x58, 0x00]; | ||
| 642 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 643 | + assert_eq!(eng.ivl_offset(), 0); | ||
| 644 | + assert_eq!(eng.decode_bypass().unwrap(), 0); | ||
| 645 | + assert_eq!(eng.ivl_offset(), 1); | ||
| 646 | + assert_eq!(eng.decode_bypass().unwrap(), 0); | ||
| 647 | + assert_eq!(eng.ivl_offset(), 2); | ||
| 648 | + assert_eq!(eng.decode_bypass().unwrap(), 0); | ||
| 649 | + assert_eq!(eng.ivl_offset(), 5); | ||
| 650 | + assert_eq!(eng.decode_bypass().unwrap(), 0); | ||
| 651 | + assert_eq!(eng.ivl_offset(), 11); | ||
| 652 | + } | ||
| 653 | + | ||
| 654 | + #[test] | ||
| 655 | + fn bypass_one_when_offset_exceeds_range() { | ||
| 656 | + // Init offset = 256. After one bypass shifting in a 1: offset | ||
| 657 | + // = (256<<1)|1 = 513 >= 510 → bin 1, offset -= 510 → 3. | ||
| 658 | + // | ||
| 659 | + // 9-bit offset stream bits 0..=8: 1, 0, 0, 0, 0, 0, 0, 0, 0 | ||
| 660 | + // → byte0 = 0b1000_0000, byte1 MSB = 0. We then want bypass | ||
| 661 | + // bit (stream bit 9) = 1 → byte1 bit1 = 1 → byte1 = 0b0100_0000. | ||
| 662 | + let buf = [0b1000_0000, 0b0100_0000]; | ||
| 663 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 664 | + assert_eq!(eng.ivl_offset(), 256); | ||
| 665 | + let bin = eng.decode_bypass().unwrap(); | ||
| 666 | + assert_eq!(bin, 1); | ||
| 667 | + assert_eq!(eng.ivl_offset(), 513 - 510); | ||
| 668 | + } | ||
| 669 | + | ||
| 670 | + #[test] | ||
| 671 | + fn bypass_bits_accumulates_msb_first() { | ||
| 672 | + // decode_bypass_bits(0) is a no-op returning 0. | ||
| 673 | + let buf = [0x00, 0x00, 0xFF]; | ||
| 674 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 675 | + assert_eq!(eng.decode_bypass_bits(0).unwrap(), 0); | ||
| 676 | + assert_eq!(eng.bit_pos(), 9); | ||
| 677 | + } | ||
| 678 | + | ||
| 679 | + // --- §9.3.4.3.5 terminate --- | ||
| 680 | + | ||
| 681 | + #[test] | ||
| 682 | + fn terminate_returns_one_and_stops() { | ||
| 683 | + // Init offset = 509 (max legal). ivlCurrRange = 510. terminate: | ||
| 684 | + // range -= 2 → 508; offset (509) >= 508 → return 1, no renorm. | ||
| 685 | + let buf = [0xFE, 0b1000_0000]; | ||
| 686 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 687 | + assert_eq!(eng.ivl_offset(), 509); | ||
| 688 | + let pos_before = eng.bit_pos(); | ||
| 689 | + assert_eq!(eng.decode_terminate().unwrap(), 1); | ||
| 690 | + assert_eq!(eng.ivl_curr_range(), 508); | ||
| 691 | + // No renormalization → no further bits consumed. | ||
| 692 | + assert_eq!(eng.bit_pos(), pos_before); | ||
| 693 | + } | ||
| 694 | + | ||
| 695 | + #[test] | ||
| 696 | + fn terminate_returns_zero_and_renorms() { | ||
| 697 | + // Init offset = 0. ivlCurrRange = 510. terminate: range -= 2 → | ||
| 698 | + // 508; offset (0) < 508 → return 0, then renorm: 508 >= 256 so | ||
| 699 | + // no renorm bits consumed. | ||
| 700 | + let buf = [0x00, 0x00, 0x00]; | ||
| 701 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 702 | + assert_eq!(eng.decode_terminate().unwrap(), 0); | ||
| 703 | + assert_eq!(eng.ivl_curr_range(), 508); | ||
| 704 | + assert_eq!(eng.bit_pos(), 9); | ||
| 705 | + } | ||
| 706 | + | ||
| 707 | + // --- §9.3.4.3.6 alignment --- | ||
| 708 | + | ||
| 709 | + #[test] | ||
| 710 | + fn align_sets_range_256() { | ||
| 711 | + let buf = [0x00, 0x00, 0x00]; | ||
| 712 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 713 | + eng.align(); | ||
| 714 | + assert_eq!(eng.ivl_curr_range(), 256); | ||
| 715 | + // ivlOffset and the reader are untouched. | ||
| 716 | + assert_eq!(eng.ivl_offset(), 0); | ||
| 717 | + assert_eq!(eng.bit_pos(), 9); | ||
| 718 | + } | ||
| 719 | + | ||
| 720 | + // --- §9.3.4.3.2 DecodeDecision: MPS / LPS paths + renorm --- | ||
| 721 | + | ||
| 722 | + #[test] | ||
| 723 | + fn decode_decision_mps_path_no_renorm() { | ||
| 724 | + // Init offset = 0, ivlCurrRange = 510. Context: pStateIdx = 0, | ||
| 725 | + // valMps = 0. | ||
| 726 | + // qRangeIdx = (510 >> 6) & 3 = 7 & 3 = 3 | ||
| 727 | + // ivlLpsRange = RANGE_TAB_LPS[0][3] = 240 | ||
| 728 | + // ivlCurrRange = 510 - 240 = 270 | ||
| 729 | + // offset (0) < 270 → MPS → binVal = valMps = 0 | ||
| 730 | + // transition: binVal == valMps → pStateIdx = transIdxMps[0]=1 | ||
| 731 | + // renorm: 270 >= 256 → none | ||
| 732 | + let buf = [0x00, 0x00, 0x00]; | ||
| 733 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 734 | + let mut ctx = ContextModel { | ||
| 735 | + p_state_idx: 0, | ||
| 736 | + val_mps: 0, | ||
| 737 | + }; | ||
| 738 | + let bin = eng.decode_decision(&mut ctx).unwrap(); | ||
| 739 | + assert_eq!(bin, 0); | ||
| 740 | + assert_eq!(eng.ivl_curr_range(), 270); | ||
| 741 | + assert_eq!(ctx.p_state_idx, 1); | ||
| 742 | + assert_eq!(ctx.val_mps, 0); | ||
| 743 | + assert_eq!(eng.bit_pos(), 9); // no renorm bits | ||
| 744 | + } | ||
| 745 | + | ||
| 746 | + #[test] | ||
| 747 | + fn decode_decision_lps_path_flips_mps_and_renorms() { | ||
| 748 | + // Drive the LPS path with pStateIdx = 0 (so valMps flips). | ||
| 749 | + // Init offset must be >= ivlCurrRange after the LPS subtraction. | ||
| 750 | + // qRangeIdx = (510 >> 6) & 3 = 3 | ||
| 751 | + // ivlLpsRange = RANGE_TAB_LPS[0][3] = 240 | ||
| 752 | + // ivlCurrRange = 510 - 240 = 270 | ||
| 753 | + // Need offset >= 270. Use init offset = 300 (0b1_0010_1100). | ||
| 754 | + // LPS: binVal = 1 - valMps = 1 | ||
| 755 | + // offset = 300 - 270 = 30 | ||
| 756 | + // ivlCurrRange = 240 | ||
| 757 | + // transition: binVal != valMps, pStateIdx==0 → valMps flips | ||
| 758 | + // to 1; pStateIdx = transIdxLps[0] = 0 | ||
| 759 | + // renorm: 240 < 256 → one doubling: range = 480, offset = | ||
| 760 | + // (30<<1)|nextbit. | ||
| 761 | + // 9-bit offset 300 = 0b1_0010_1100. Pack into bytes: | ||
| 762 | + // byte0 = 0b1001_0110 (bits 0..7), byte1 MSB = 0 (bit 8). | ||
| 763 | + // 300 binary (9 bits): 1 0010 1100. | ||
| 764 | + // bit0=1 bit1=0 bit2=0 bit3=1 bit4=0 bit5=1 bit6=1 bit7=0 → 0x96 | ||
| 765 | + // bit8=0 → byte1 MSB 0. | ||
| 766 | + // The renorm bit (stream bit 9) = byte1 bit1; set it to 1. | ||
| 767 | + let buf = [0x96, 0b0100_0000, 0x00]; | ||
| 768 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 769 | + assert_eq!(eng.ivl_offset(), 300); | ||
| 770 | + let mut ctx = ContextModel { | ||
| 771 | + p_state_idx: 0, | ||
| 772 | + val_mps: 0, | ||
| 773 | + }; | ||
| 774 | + let bin = eng.decode_decision(&mut ctx).unwrap(); | ||
| 775 | + assert_eq!(bin, 1); | ||
| 776 | + assert_eq!(ctx.val_mps, 1); // flipped | ||
| 777 | + assert_eq!(ctx.p_state_idx, 0); // transIdxLps[0] | ||
| 778 | + assert_eq!(eng.ivl_curr_range(), 480); // 240 << 1 | ||
| 779 | + assert_eq!(eng.ivl_offset(), (30 << 1) | 1); | ||
| 780 | + assert_eq!(eng.bit_pos(), 10); // one renorm bit | ||
| 781 | + } | ||
| 782 | + | ||
| 783 | + #[test] | ||
| 784 | + fn end_of_buffer_surfaces_error() { | ||
| 785 | + // Provide exactly 9 bits (one byte + one bit). After init, the | ||
| 786 | + // bit reader is at its end, so the next bypass fails. We pad | ||
| 787 | + // the buffer to 9 bits by giving 2 bytes but truncating the | ||
| 788 | + // BitReader via `skip` would be circular — instead exercise | ||
| 789 | + // the path that needs more than the buffer holds by consuming | ||
| 790 | + // enough bypass bits to overrun. | ||
| 791 | + let buf = [0x00, 0x00]; | ||
| 792 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 793 | + // 16 - 9 = 7 bits left; the 8th bypass call must fail. | ||
| 794 | + for _ in 0..7 { | ||
| 795 | + eng.decode_bypass().unwrap(); | ||
| 796 | + } | ||
| 797 | + assert_eq!(eng.decode_bypass(), Err(CabacError::EndOfBuffer)); | ||
| 798 | + } | ||
| 799 | + | ||
| 800 | + #[test] | ||
| 801 | + fn round_trips_a_known_state_sequence() { | ||
| 802 | + // Decode several MPS bins in a row from an all-zero stream with | ||
| 803 | + // a fresh I-slice-style context and confirm the probability | ||
| 804 | + // state walks up the transIdxMps ladder deterministically. | ||
| 805 | + let buf = [0u8; 8]; | ||
| 806 | + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); | ||
| 807 | + let mut ctx = ContextModel { | ||
| 808 | + p_state_idx: 0, | ||
| 809 | + val_mps: 0, | ||
| 810 | + }; | ||
| 811 | + let mut states = Vec::new(); | ||
| 812 | + for _ in 0..5 { | ||
| 813 | + let bin = eng.decode_decision(&mut ctx).unwrap(); | ||
| 814 | + assert_eq!(bin, 0); // all-zero offset always takes MPS here | ||
| 815 | + states.push(ctx.p_state_idx); | ||
| 816 | + } | ||
| 817 | + // transIdxMps ladder from 0: 1, 2, 3, 4, 5. | ||
| 818 | + assert_eq!(states, vec![1, 2, 3, 4, 5]); | ||
| 819 | + } | ||
| 820 | +} | ||
| @@ -0,0 +1,994 @@ | |||
| 1 | +//! §9.3.2.2 context-variable initialization — the `initValue` tables | ||
| 2 | +//! (Tables 9-5 .. 9-42) and the per-slice context-array setup. | ||
| 3 | +//! | ||
| 4 | +//! This module is a clean-room transcription from the ITU-T Rec. H.265 | ||
| 5 | +//! | ISO/IEC 23008-2 specification text (`docs/video/h265/`): | ||
| 6 | +//! | ||
| 7 | +//! * The 8-bit `initValue` tables for every context-coded syntax | ||
| 8 | +//! element of clauses 7.3.8.1 through 7.3.8.12 (except | ||
| 9 | +//! `end_of_slice_segment_flag`, `end_of_subset_one_bit` and | ||
| 10 | +//! `pcm_flag`, which use the §9.3.2.2 NOTE 2 non-adapting | ||
| 11 | +//! `ctxTable == 0` state — [`ContextModel::terminate_state`]). | ||
| 12 | +//! Each constant is laid out flat over the table's printed ctxIdx | ||
| 13 | +//! axis, exactly as in the spec. | ||
| 14 | +//! * The Table 9-4 association of ctxIdx ranges to the three | ||
| 15 | +//! initialization types: most tables devote a contiguous span of | ||
| 16 | +//! `N` ctxIdx slots to each `initType` column, but several are | ||
| 17 | +//! irregular (`part_mode`, `cbf_cb`/`cbf_cr`, the | ||
| 18 | +//! `abs_mvd_greater0_flag`/`abs_mvd_greater1_flag` interleave, | ||
| 19 | +//! `transform_skip_flag`, the `explicit_rdpcm_*` pairs and the | ||
| 20 | +//! `sig_coeff_flag` transform-skip tail) — see the per-bank | ||
| 21 | +//! helpers. | ||
| 22 | +//! * [`SliceContexts`] — the whole per-slice context array, one bank | ||
| 23 | +//! per syntax element (or per Table 9-4 shared-variable group), | ||
| 24 | +//! initialised for a given `initType` and `SliceQpY` through the | ||
| 25 | +//! §9.3.2.2 process ([`ContextModel::init`], equations 9-4..9-6). | ||
| 26 | +//! [`SliceContexts::for_slice`] additionally applies the | ||
| 27 | +//! equation 9-7 `initType` derivation from `slice_type` and | ||
| 28 | +//! `cabac_init_flag` ([`crate::cabac::init_type`]). | ||
| 29 | +//! | ||
| 30 | +//! # Shared context variables | ||
| 31 | +//! | ||
| 32 | +//! Table 9-4 assigns the *same* `(ctxTable, ctxIdx)` slots to a few | ||
| 33 | +//! element groups, which therefore share one adapting context | ||
| 34 | +//! variable per `initType`: | ||
| 35 | +//! | ||
| 36 | +//! * `sao_merge_left_flag` / `sao_merge_up_flag` (Table 9-5), | ||
| 37 | +//! * `sao_type_idx_luma` / `sao_type_idx_chroma` (Table 9-6), | ||
| 38 | +//! * `ref_idx_l0` / `ref_idx_l1` (Table 9-18), | ||
| 39 | +//! * `mvp_l0_flag` / `mvp_l1_flag` (Table 9-19), | ||
| 40 | +//! * `cbf_cb` / `cbf_cr` (Table 9-22), | ||
| 41 | +//! * `copy_above_palette_indices_flag` / | ||
| 42 | +//! `copy_above_indices_for_final_run_flag` (Table 9-41), | ||
| 43 | +//! * the chroma planes of `transform_skip_flag[ ][ ][ 1 ]` / | ||
| 44 | +//! `[ 2 ]` (Table 9-25), `explicit_rdpcm_flag[ ][ ][ 1 ]` / `[ 2 ]` | ||
| 45 | +//! (Table 9-32) and `explicit_rdpcm_dir_flag[ ][ ][ 1 ]` / `[ 2 ]` | ||
| 46 | +//! (Table 9-33). | ||
| 47 | +//! | ||
| 48 | +//! # Inter-only elements in I slices | ||
| 49 | +//! | ||
| 50 | +//! Table 9-4 leaves the `initType == 0` column empty for the elements | ||
| 51 | +//! that can only occur in P / B slices (`cu_skip_flag`, | ||
| 52 | +//! `pred_mode_flag`, `rqt_root_cbf`, `merge_flag`, `merge_idx`, | ||
| 53 | +//! `inter_pred_idc`, `ref_idx_l0`/`l1`, `mvp_l0_flag`/`l1`, | ||
| 54 | +//! `abs_mvd_greater0_flag`/`greater1_flag`, `explicit_rdpcm_flag` and | ||
| 55 | +//! `explicit_rdpcm_dir_flag`) — no initialization is specified | ||
| 56 | +//! because a conforming I slice never decodes them. [`SliceContexts`] | ||
| 57 | +//! still materialises those banks so the array shape is | ||
| 58 | +//! `initType`-independent; at `initType == 0` they are populated with | ||
| 59 | +//! the §9.3.2.2 NOTE 2 non-adapting state | ||
| 60 | +//! ([`ContextModel::terminate_state`], `pStateIdx = 63`, | ||
| 61 | +//! `valMps = 0`), which no table-derived context can take | ||
| 62 | +//! (equations 9-4..9-6 bound `pStateIdx` to 0..=62), making an | ||
| 63 | +//! accidental read recognisable. The same placeholder fills the | ||
| 64 | +//! `part_mode` slots 1..=3 at `initType == 0` (Table 9-4 gives | ||
| 65 | +//! `part_mode` only ctxIdx 0 there: the I-slice §9.3.4.2 binarization | ||
| 66 | +//! uses a single context-coded bin). | ||
| 67 | + | ||
| 68 | +use crate::cabac::{init_type, ContextModel}; | ||
| 69 | +use crate::residual::ResidualContexts; | ||
| 70 | +use crate::slice::SliceType; | ||
| 71 | + | ||
| 72 | +// --------------------------------------------------------------------- | ||
| 73 | +// initValue tables (Tables 9-5 .. 9-42) | ||
| 74 | +// --------------------------------------------------------------------- | ||
| 75 | + | ||
| 76 | +/// Table 9-5 — `initValue` for ctxIdx of `sao_merge_left_flag` and | ||
| 77 | +/// `sao_merge_up_flag` (one shared context per `initType`; ctxIdx | ||
| 78 | +/// 0 / 1 / 2 for `initType` 0 / 1 / 2). | ||
| 79 | +pub const TABLE_9_5_SAO_MERGE_FLAG: [u8; 3] = [153, 153, 153]; | ||
| 80 | + | ||
| 81 | +/// Table 9-6 — `initValue` for ctxIdx of `sao_type_idx_luma` and | ||
| 82 | +/// `sao_type_idx_chroma` (one shared context per `initType`). | ||
| 83 | +pub const TABLE_9_6_SAO_TYPE_IDX: [u8; 3] = [200, 185, 160]; | ||
| 84 | + | ||
| 85 | +/// Table 9-7 — `initValue` for ctxIdx of `split_cu_flag` (ctxIdx | ||
| 86 | +/// 0..2 / 3..5 / 6..8 for `initType` 0 / 1 / 2 per Table 9-4). | ||
| 87 | +pub const TABLE_9_7_SPLIT_CU_FLAG: [u8; 9] = [139, 141, 157, 107, 139, 126, 107, 139, 126]; | ||
| 88 | + | ||
| 89 | +/// Table 9-8 — `initValue` for ctxIdx of `cu_transquant_bypass_flag`. | ||
| 90 | +pub const TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG: [u8; 3] = [154, 154, 154]; | ||
| 91 | + | ||
| 92 | +/// Table 9-9 — `initValue` for ctxIdx of `cu_skip_flag` (ctxIdx 0..2 / | ||
| 93 | +/// 3..5 for `initType` 1 / 2; the element does not occur in I slices). | ||
| 94 | +pub const TABLE_9_9_CU_SKIP_FLAG: [u8; 6] = [197, 185, 201, 197, 185, 201]; | ||
| 95 | + | ||
| 96 | +/// Table 9-10 — `initValue` for ctxIdx of `pred_mode_flag` (ctxIdx | ||
| 97 | +/// 0 / 1 for `initType` 1 / 2; inter-only). | ||
| 98 | +pub const TABLE_9_10_PRED_MODE_FLAG: [u8; 2] = [149, 134]; | ||
| 99 | + | ||
| 100 | +/// Table 9-11 — `initValue` for ctxIdx of `part_mode`. Irregular | ||
| 101 | +/// Table 9-4 mapping: ctxIdx 0 for `initType` 0 (the I-slice | ||
| 102 | +/// binarization has one context-coded bin), ctxIdx 1..4 / 5..8 for | ||
| 103 | +/// `initType` 1 / 2. | ||
| 104 | +pub const TABLE_9_11_PART_MODE: [u8; 9] = [184, 154, 139, 154, 154, 154, 139, 154, 154]; | ||
| 105 | + | ||
| 106 | +/// Table 9-12 — `initValue` for ctxIdx of `prev_intra_luma_pred_flag`. | ||
| 107 | +pub const TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG: [u8; 3] = [184, 154, 183]; | ||
| 108 | + | ||
| 109 | +/// Table 9-13 — `initValue` for ctxIdx of `intra_chroma_pred_mode`. | ||
| 110 | +pub const TABLE_9_13_INTRA_CHROMA_PRED_MODE: [u8; 3] = [63, 152, 152]; | ||
| 111 | + | ||
| 112 | +/// Table 9-14 — `initValue` for ctxIdx of `rqt_root_cbf` (ctxIdx 0 / 1 | ||
| 113 | +/// for `initType` 1 / 2; inter-only). | ||
| 114 | +pub const TABLE_9_14_RQT_ROOT_CBF: [u8; 2] = [79, 79]; | ||
| 115 | + | ||
| 116 | +/// Table 9-15 — `initValue` for ctxIdx of `merge_flag` (`initType` | ||
| 117 | +/// 1 / 2; inter-only). | ||
| 118 | +pub const TABLE_9_15_MERGE_FLAG: [u8; 2] = [110, 154]; | ||
| 119 | + | ||
| 120 | +/// Table 9-16 — `initValue` for ctxIdx of `merge_idx` (`initType` | ||
| 121 | +/// 1 / 2; inter-only). | ||
| 122 | +pub const TABLE_9_16_MERGE_IDX: [u8; 2] = [122, 137]; | ||
| 123 | + | ||
| 124 | +/// Table 9-17 — `initValue` for ctxIdx of `inter_pred_idc` (ctxIdx | ||
| 125 | +/// 0..4 / 5..9 for `initType` 1 / 2; inter-only). | ||
| 126 | +pub const TABLE_9_17_INTER_PRED_IDC: [u8; 10] = [95, 79, 63, 31, 31, 95, 79, 63, 31, 31]; | ||
| 127 | + | ||
| 128 | +/// Table 9-18 — `initValue` for ctxIdx of `ref_idx_l0` and | ||
| 129 | +/// `ref_idx_l1` (shared bank; ctxIdx 0..1 / 2..3 for `initType` 1 / 2; | ||
| 130 | +/// inter-only). | ||
| 131 | +pub const TABLE_9_18_REF_IDX: [u8; 4] = [153, 153, 153, 153]; | ||
| 132 | + | ||
| 133 | +/// Table 9-19 — `initValue` for ctxIdx of `mvp_l0_flag` and | ||
| 134 | +/// `mvp_l1_flag` (shared bank; ctxIdx 0 / 1 for `initType` 1 / 2; | ||
| 135 | +/// inter-only). | ||
| 136 | +pub const TABLE_9_19_MVP_FLAG: [u8; 2] = [168, 168]; | ||
| 137 | + | ||
| 138 | +/// Table 9-20 — `initValue` for ctxIdx of `split_transform_flag` | ||
| 139 | +/// (ctxIdx 0..2 / 3..5 / 6..8 for `initType` 0 / 1 / 2). | ||
| 140 | +pub const TABLE_9_20_SPLIT_TRANSFORM_FLAG: [u8; 9] = [153, 138, 138, 124, 138, 94, 224, 167, 122]; | ||
| 141 | + | ||
| 142 | +/// Table 9-21 — `initValue` for ctxIdx of `cbf_luma` (ctxIdx 0..1 / | ||
| 143 | +/// 2..3 / 4..5 for `initType` 0 / 1 / 2). | ||
| 144 | +pub const TABLE_9_21_CBF_LUMA: [u8; 6] = [111, 141, 153, 111, 153, 111]; | ||
| 145 | + | ||
| 146 | +/// Table 9-22 — `initValue` for ctxIdx of `cbf_cb` and `cbf_cr` | ||
| 147 | +/// (shared bank). Irregular Table 9-4 mapping: ctxIdx 0..3 / 4..7 / | ||
| 148 | +/// 8..11 carry the four trafo-depth contexts for `initType` 0 / 1 / 2 | ||
| 149 | +/// and ctxIdx 12 / 13 / 14 carry the fifth (`ctxInc == 4`) context | ||
| 150 | +/// for `initType` 0 / 1 / 2. | ||
| 151 | +#[rustfmt::skip] | ||
| 152 | +pub const TABLE_9_22_CBF_CHROMA: [u8; 15] = [ | ||
| 153 | + 94, 138, 182, 154, | ||
| 154 | + 149, 107, 167, 154, | ||
| 155 | + 149, 92, 167, 154, | ||
| 156 | + 154, 154, 154, | ||
| 157 | +]; | ||
| 158 | + | ||
| 159 | +/// Table 9-23 — `initValue` for ctxIdx of `abs_mvd_greater0_flag` and | ||
| 160 | +/// `abs_mvd_greater1_flag`. Irregular Table 9-4 mapping (inter-only): | ||
| 161 | +/// `abs_mvd_greater0_flag` takes ctxIdx 0 / 2 for `initType` 1 / 2 and | ||
| 162 | +/// `abs_mvd_greater1_flag` takes ctxIdx 1 / 3. | ||
| 163 | +pub const TABLE_9_23_ABS_MVD_GREATER_FLAG: [u8; 4] = [140, 198, 169, 198]; | ||
| 164 | + | ||
| 165 | +/// Table 9-24 — `initValue` for ctxIdx of `cu_qp_delta_abs` (ctxIdx | ||
| 166 | +/// 0..1 / 2..3 / 4..5 for `initType` 0 / 1 / 2). | ||
| 167 | +pub const TABLE_9_24_CU_QP_DELTA_ABS: [u8; 6] = [154, 154, 154, 154, 154, 154]; | ||
| 168 | + | ||
| 169 | +/// Table 9-25 — `initValue` for ctxIdx of `transform_skip_flag`. | ||
| 170 | +/// Irregular Table 9-4 mapping: ctxIdx 0 / 1 / 2 carry the luma | ||
| 171 | +/// (`cIdx == 0`) context for `initType` 0 / 1 / 2 and ctxIdx 3 / 4 / 5 | ||
| 172 | +/// the context shared by both chroma planes (`cIdx == 1` / `2`). | ||
| 173 | +pub const TABLE_9_25_TRANSFORM_SKIP_FLAG: [u8; 6] = [139, 139, 139, 139, 139, 139]; | ||
| 174 | + | ||
| 175 | +/// Table 9-26 — `initValue` for ctxIdx of `last_sig_coeff_x_prefix` | ||
| 176 | +/// (ctxIdx 0..17 / 18..35 / 36..53 for `initType` 0 / 1 / 2). | ||
| 177 | +#[rustfmt::skip] | ||
| 178 | +pub const TABLE_9_26_LAST_SIG_COEFF_X_PREFIX: [u8; 54] = [ | ||
| 179 | + 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, | ||
| 180 | + 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108, | ||
| 181 | + 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93, | ||
| 182 | +]; | ||
| 183 | + | ||
| 184 | +/// Table 9-27 — `initValue` for ctxIdx of `last_sig_coeff_y_prefix` | ||
| 185 | +/// (ctxIdx 0..17 / 18..35 / 36..53 for `initType` 0 / 1 / 2). The | ||
| 186 | +/// printed values coincide with Table 9-26 entry-for-entry, but the | ||
| 187 | +/// two elements adapt separate context variables. | ||
| 188 | +#[rustfmt::skip] | ||
| 189 | +pub const TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX: [u8; 54] = [ | ||
| 190 | + 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, | ||
| 191 | + 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108, | ||
| 192 | + 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93, | ||
| 193 | +]; | ||
| 194 | + | ||
| 195 | +/// Table 9-28 — `initValue` for ctxIdx of `coded_sub_block_flag` | ||
| 196 | +/// (ctxIdx 0..3 / 4..7 / 8..11 for `initType` 0 / 1 / 2). | ||
| 197 | +#[rustfmt::skip] | ||
| 198 | +pub const TABLE_9_28_CODED_SUB_BLOCK_FLAG: [u8; 12] = [ | ||
| 199 | + 91, 171, 134, 141, | ||
| 200 | + 121, 140, 61, 154, | ||
| 201 | + 121, 140, 61, 154, | ||
| 202 | +]; | ||
| 203 | + | ||
| 204 | +/// Table 9-29 — `initValue` for ctxIdx of `sig_coeff_flag`. Irregular | ||
| 205 | +/// Table 9-4 mapping: ctxIdx 0..41 / 42..83 / 84..125 carry the 42 | ||
| 206 | +/// §9.3.4.2.5 contexts for `initType` 0 / 1 / 2 and ctxIdx 126..127 / | ||
| 207 | +/// 128..129 / 130..131 carry the two equation 9-40 transform-skip | ||
| 208 | +/// contexts (luma, chroma) for `initType` 0 / 1 / 2. | ||
| 209 | +#[rustfmt::skip] | ||
| 210 | +pub const TABLE_9_29_SIG_COEFF_FLAG: [u8; 132] = [ | ||
| 211 | + 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, | ||
| 212 | + 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152, | ||
| 213 | + 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 155, 154, 139, 153, 139, 123, | ||
| 214 | + 123, 63, 153, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, | ||
| 215 | + 183, 140, 136, 153, 154, 170, 153, 123, 123, 107, 121, 107, 121, 167, 151, 183, | ||
| 216 | + 140, 151, 183, 140, 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, | ||
| 217 | + 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, | ||
| 218 | + 153, 138, 138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 141, 111, | ||
| 219 | + 140, 140, 140, 140, | ||
| 220 | +]; | ||
| 221 | + | ||
| 222 | +/// Table 9-30 — `initValue` for ctxIdx of | ||
| 223 | +/// `coeff_abs_level_greater1_flag` (ctxIdx 0..23 / 24..47 / 48..71 for | ||
| 224 | +/// `initType` 0 / 1 / 2). | ||
| 225 | +#[rustfmt::skip] | ||
| 226 | +pub const TABLE_9_30_COEFF_ABS_LEVEL_GREATER1_FLAG: [u8; 72] = [ | ||
| 227 | + 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152, | ||
| 228 | + 140, 179, 166, 182, 140, 227, 122, 197, 154, 196, 196, 167, 154, 152, 167, 182, | ||
| 229 | + 182, 134, 149, 136, 153, 121, 136, 137, 169, 194, 166, 167, 154, 167, 137, 182, | ||
| 230 | + 154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 122, | ||
| 231 | + 169, 208, 166, 167, 154, 152, 167, 182, | ||
| 232 | +]; | ||
| 233 | + | ||
| 234 | +/// Table 9-31 — `initValue` for ctxIdx of | ||
| 235 | +/// `coeff_abs_level_greater2_flag` (ctxIdx 0..5 / 6..11 / 12..17 for | ||
| 236 | +/// `initType` 0 / 1 / 2). | ||
| 237 | +#[rustfmt::skip] | ||
| 238 | +pub const TABLE_9_31_COEFF_ABS_LEVEL_GREATER2_FLAG: [u8; 18] = [ | ||
| 239 | + 138, 153, 136, 167, 152, 152, | ||
| 240 | + 107, 167, 91, 122, 107, 167, | ||
| 241 | + 107, 167, 91, 107, 107, 167, | ||
| 242 | +]; | ||
| 243 | + | ||
| 244 | +/// Table 9-32 — `initValue` for ctxIdx of `explicit_rdpcm_flag`. | ||
| 245 | +/// Irregular Table 9-4 mapping (inter-only): ctxIdx 0 / 1 carry the | ||
| 246 | +/// luma (`cIdx == 0`) context for `initType` 1 / 2 and ctxIdx 2 / 3 | ||
| 247 | +/// the context shared by both chroma planes. | ||
| 248 | +pub const TABLE_9_32_EXPLICIT_RDPCM_FLAG: [u8; 4] = [139, 139, 139, 139]; | ||
| 249 | + | ||
| 250 | +/// Table 9-33 — `initValue` for ctxIdx of `explicit_rdpcm_dir_flag` | ||
| 251 | +/// (same irregular mapping as Table 9-32; inter-only). | ||
| 252 | +pub const TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG: [u8; 4] = [139, 139, 139, 139]; | ||
| 253 | + | ||
| 254 | +/// Table 9-34 — `initValue` for ctxIdx of `cu_chroma_qp_offset_flag`. | ||
| 255 | +pub const TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG: [u8; 3] = [154, 154, 154]; | ||
| 256 | + | ||
| 257 | +/// Table 9-35 — `initValue` for ctxIdx of `cu_chroma_qp_offset_idx`. | ||
| 258 | +pub const TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX: [u8; 3] = [154, 154, 154]; | ||
| 259 | + | ||
| 260 | +/// Table 9-36 — `initValue` for ctxIdx of `log2_res_scale_abs_plus1` | ||
| 261 | +/// (ctxIdx 0..7 / 8..15 / 16..23 for `initType` 0 / 1 / 2). | ||
| 262 | +pub const TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1: [u8; 24] = [154; 24]; | ||
| 263 | + | ||
| 264 | +/// Table 9-37 — `initValue` for ctxIdx of `res_scale_sign_flag` | ||
| 265 | +/// (ctxIdx 0..1 / 2..3 / 4..5 for `initType` 0 / 1 / 2). | ||
| 266 | +pub const TABLE_9_37_RES_SCALE_SIGN_FLAG: [u8; 6] = [154; 6]; | ||
| 267 | + | ||
| 268 | +/// Table 9-38 — `initValue` for ctxIdx of `palette_mode_flag`. | ||
| 269 | +pub const TABLE_9_38_PALETTE_MODE_FLAG: [u8; 3] = [154, 154, 154]; | ||
| 270 | + | ||
| 271 | +/// Table 9-39 — `initValue` for ctxIdx of `tu_residual_act_flag`. | ||
| 272 | +pub const TABLE_9_39_TU_RESIDUAL_ACT_FLAG: [u8; 3] = [154, 154, 154]; | ||
| 273 | + | ||
| 274 | +/// Table 9-40 — `initValue` for ctxIdx of `palette_run_prefix` (ctxIdx | ||
| 275 | +/// 0..7 / 8..15 / 16..23 for `initType` 0 / 1 / 2). | ||
| 276 | +pub const TABLE_9_40_PALETTE_RUN_PREFIX: [u8; 24] = [154; 24]; | ||
| 277 | + | ||
| 278 | +/// Table 9-41 — `initValue` for ctxIdx of | ||
| 279 | +/// `copy_above_palette_indices_flag` and | ||
| 280 | +/// `copy_above_indices_for_final_run_flag` (shared bank: Table 9-4 | ||
| 281 | +/// assigns both elements ctxIdx 0 / 1 / 2 of this table). | ||
| 282 | +pub const TABLE_9_41_PALETTE_COPY_ABOVE_FLAG: [u8; 3] = [154, 154, 154]; | ||
| 283 | + | ||
| 284 | +/// Table 9-42 — `initValue` for ctxIdx of `palette_transpose_flag`. | ||
| 285 | +pub const TABLE_9_42_PALETTE_TRANSPOSE_FLAG: [u8; 3] = [154, 154, 154]; | ||
| 286 | + | ||
| 287 | +// --------------------------------------------------------------------- | ||
| 288 | +// Table 9-4 ctxIdx-span selection helpers | ||
| 289 | +// --------------------------------------------------------------------- | ||
| 290 | + | ||
| 291 | +/// Select the `N` per-`initType` `initValue` entries from a table | ||
| 292 | +/// whose Table 9-4 mapping is the regular contiguous layout (ctxIdx | ||
| 293 | +/// `0..N` / `N..2N` / `2N..3N` for `initType` 0 / 1 / 2). | ||
| 294 | +/// | ||
| 295 | +/// # Panics | ||
| 296 | +/// | ||
| 297 | +/// Panics when `init_type > 2` or `table.len() != 3 * N`. | ||
| 298 | +#[must_use] | ||
| 299 | +pub fn uniform_init_values<const N: usize>(table: &[u8], init_type: u8) -> [u8; N] { | ||
| 300 | + assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)"); | ||
| 301 | + assert_eq!(table.len(), 3 * N, "table is not a 3-initType layout"); | ||
| 302 | + let base = N * init_type as usize; | ||
| 303 | + core::array::from_fn(|i| table[base + i]) | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +/// Select the `N` per-`initType` `initValue` entries from a table for | ||
| 307 | +/// an inter-only element (Table 9-4 leaves `initType == 0` empty; | ||
| 308 | +/// ctxIdx `0..N` / `N..2N` map to `initType` 1 / 2). Returns `None` | ||
| 309 | +/// for `init_type == 0` — the element cannot occur in an I slice. | ||
| 310 | +/// | ||
| 311 | +/// # Panics | ||
| 312 | +/// | ||
| 313 | +/// Panics when `init_type > 2` or `table.len() != 2 * N`. | ||
| 314 | +#[must_use] | ||
| 315 | +pub fn inter_init_values<const N: usize>(table: &[u8], init_type: u8) -> Option<[u8; N]> { | ||
| 316 | + assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)"); | ||
| 317 | + assert_eq!(table.len(), 2 * N, "table is not a 2-initType layout"); | ||
| 318 | + if init_type == 0 { | ||
| 319 | + return None; | ||
| 320 | + } | ||
| 321 | + let base = N * (init_type as usize - 1); | ||
| 322 | + Some(core::array::from_fn(|i| table[base + i])) | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +/// The per-`initType` `sig_coeff_flag` `initValue` bank (44 entries): | ||
| 326 | +/// the 42 §9.3.4.2.5 contexts from the Table 9-29 ctxIdx span | ||
| 327 | +/// `42 * initType ..`, followed by the two equation 9-40 | ||
| 328 | +/// transform-skip contexts (luma then chroma) from ctxIdx | ||
| 329 | +/// `126 + 2 * initType ..`. Matches the | ||
| 330 | +/// [`crate::residual::ResidualContexts`] bank layout (slots 42 / 43 | ||
| 331 | +/// are the transform-skip contexts). | ||
| 332 | +/// | ||
| 333 | +/// # Panics | ||
| 334 | +/// | ||
| 335 | +/// Panics when `init_type > 2`. | ||
| 336 | +#[must_use] | ||
| 337 | +pub fn sig_coeff_flag_init_values(init_type: u8) -> [u8; 44] { | ||
| 338 | + assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)"); | ||
| 339 | + let t = init_type as usize; | ||
| 340 | + core::array::from_fn(|i| { | ||
| 341 | + if i < 42 { | ||
| 342 | + TABLE_9_29_SIG_COEFF_FLAG[42 * t + i] | ||
| 343 | + } else { | ||
| 344 | + TABLE_9_29_SIG_COEFF_FLAG[126 + 2 * t + (i - 42)] | ||
| 345 | + } | ||
| 346 | + }) | ||
| 347 | +} | ||
| 348 | + | ||
| 349 | +/// Initialize an inter-only bank: table entries through | ||
| 350 | +/// [`ContextModel::init`] for `initType` 1 / 2, the | ||
| 351 | +/// [`ContextModel::terminate_state`] placeholder for `initType` 0 | ||
| 352 | +/// (see the module docs). | ||
| 353 | +fn inter_bank<const N: usize>(table: &[u8], init_type: u8, slice_qp_y: i32) -> [ContextModel; N] { | ||
| 354 | + match inter_init_values::<N>(table, init_type) { | ||
| 355 | + Some(values) => values.map(|v| ContextModel::init(v, slice_qp_y)), | ||
| 356 | + None => [ContextModel::terminate_state(); N], | ||
| 357 | + } | ||
| 358 | +} | ||
| 359 | + | ||
| 360 | +/// Initialize a regular three-`initType` bank. | ||
| 361 | +fn uniform_bank<const N: usize>(table: &[u8], init_type: u8, slice_qp_y: i32) -> [ContextModel; N] { | ||
| 362 | + uniform_init_values::<N>(table, init_type).map(|v| ContextModel::init(v, slice_qp_y)) | ||
| 363 | +} | ||
| 364 | + | ||
| 365 | +// --------------------------------------------------------------------- | ||
| 366 | +// SliceContexts | ||
| 367 | +// --------------------------------------------------------------------- | ||
| 368 | + | ||
| 369 | +/// The complete per-slice CABAC context array of §9.3.2.2 / Table 9-4: | ||
| 370 | +/// one bank per syntax element (or per Table 9-4 shared-variable | ||
| 371 | +/// group; see the module docs), each slot a `(pStateIdx, valMps)` | ||
| 372 | +/// [`ContextModel`]. Bank-internal indices are the *bank-relative* | ||
| 373 | +/// ctxIdx (the §9.3.4.2 `ctxInc` value), not the absolute Table 9-4 | ||
| 374 | +/// ctxIdx. | ||
| 375 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 376 | +pub struct SliceContexts { | ||
| 377 | + /// `sao_merge_left_flag` / `sao_merge_up_flag` (Table 9-5, shared). | ||
| 378 | + pub sao_merge_flag: [ContextModel; 1], | ||
| 379 | + /// `sao_type_idx_luma` / `sao_type_idx_chroma` (Table 9-6, shared). | ||
| 380 | + pub sao_type_idx: [ContextModel; 1], | ||
| 381 | + /// `split_cu_flag` (Table 9-7). | ||
| 382 | + pub split_cu_flag: [ContextModel; 3], | ||
| 383 | + /// `cu_transquant_bypass_flag` (Table 9-8). | ||
| 384 | + pub cu_transquant_bypass_flag: [ContextModel; 1], | ||
| 385 | + /// `cu_skip_flag` (Table 9-9; inter-only). | ||
| 386 | + pub cu_skip_flag: [ContextModel; 3], | ||
| 387 | + /// `palette_mode_flag` (Table 9-38). | ||
| 388 | + pub palette_mode_flag: [ContextModel; 1], | ||
| 389 | + /// `pred_mode_flag` (Table 9-10; inter-only). | ||
| 390 | + pub pred_mode_flag: [ContextModel; 1], | ||
| 391 | + /// `part_mode` (Table 9-11; slot 0 only at `initType == 0`). | ||
| 392 | + pub part_mode: [ContextModel; 4], | ||
| 393 | + /// `prev_intra_luma_pred_flag` (Table 9-12). | ||
| 394 | + pub prev_intra_luma_pred_flag: [ContextModel; 1], | ||
| 395 | + /// `intra_chroma_pred_mode` (Table 9-13). | ||
| 396 | + pub intra_chroma_pred_mode: [ContextModel; 1], | ||
| 397 | + /// `rqt_root_cbf` (Table 9-14; inter-only). | ||
| 398 | + pub rqt_root_cbf: [ContextModel; 1], | ||
| 399 | + /// `merge_flag` (Table 9-15; inter-only). | ||
| 400 | + pub merge_flag: [ContextModel; 1], | ||
| 401 | + /// `merge_idx` (Table 9-16; inter-only). | ||
| 402 | + pub merge_idx: [ContextModel; 1], | ||
| 403 | + /// `inter_pred_idc` (Table 9-17; inter-only). | ||
| 404 | + pub inter_pred_idc: [ContextModel; 5], | ||
| 405 | + /// `ref_idx_l0` / `ref_idx_l1` (Table 9-18, shared; inter-only). | ||
| 406 | + pub ref_idx: [ContextModel; 2], | ||
| 407 | + /// `mvp_l0_flag` / `mvp_l1_flag` (Table 9-19, shared; inter-only). | ||
| 408 | + pub mvp_flag: [ContextModel; 1], | ||
| 409 | + /// `split_transform_flag` (Table 9-20). | ||
| 410 | + pub split_transform_flag: [ContextModel; 3], | ||
| 411 | + /// `cbf_luma` (Table 9-21). | ||
| 412 | + pub cbf_luma: [ContextModel; 2], | ||
| 413 | + /// `cbf_cb` / `cbf_cr` (Table 9-22, shared; slot 4 is the | ||
| 414 | + /// Table 9-4 ctxIdx 12 / 13 / 14 fifth context). | ||
| 415 | + pub cbf_chroma: [ContextModel; 5], | ||
| 416 | + /// `abs_mvd_greater0_flag` (Table 9-23 ctxIdx 0 / 2; inter-only). | ||
| 417 | + pub abs_mvd_greater0_flag: [ContextModel; 1], | ||
| 418 | + /// `abs_mvd_greater1_flag` (Table 9-23 ctxIdx 1 / 3; inter-only). | ||
| 419 | + pub abs_mvd_greater1_flag: [ContextModel; 1], | ||
| 420 | + /// `tu_residual_act_flag` (Table 9-39). | ||
| 421 | + pub tu_residual_act_flag: [ContextModel; 1], | ||
| 422 | + /// `log2_res_scale_abs_plus1` (Table 9-36). | ||
| 423 | + pub log2_res_scale_abs_plus1: [ContextModel; 8], | ||
| 424 | + /// `res_scale_sign_flag` (Table 9-37). | ||
| 425 | + pub res_scale_sign_flag: [ContextModel; 2], | ||
| 426 | + /// `transform_skip_flag` (Table 9-25; slot 0 luma, slot 1 the | ||
| 427 | + /// shared chroma context). | ||
| 428 | + pub transform_skip_flag: [ContextModel; 2], | ||
| 429 | + /// `explicit_rdpcm_flag` (Table 9-32; slot 0 luma, slot 1 the | ||
| 430 | + /// shared chroma context; inter-only). | ||
| 431 | + pub explicit_rdpcm_flag: [ContextModel; 2], | ||
| 432 | + /// `explicit_rdpcm_dir_flag` (Table 9-33; same layout; inter-only). | ||
| 433 | + pub explicit_rdpcm_dir_flag: [ContextModel; 2], | ||
| 434 | + /// The §7.3.8.11 `residual_coding( )` banks (Tables 9-26..9-31). | ||
| 435 | + pub residual: ResidualContexts, | ||
| 436 | + /// `palette_run_prefix` (Table 9-40). | ||
| 437 | + pub palette_run_prefix: [ContextModel; 8], | ||
| 438 | + /// `copy_above_palette_indices_flag` / | ||
| 439 | + /// `copy_above_indices_for_final_run_flag` (Table 9-41, shared). | ||
| 440 | + pub palette_copy_above_flag: [ContextModel; 1], | ||
| 441 | + /// `palette_transpose_flag` (Table 9-42). | ||
| 442 | + pub palette_transpose_flag: [ContextModel; 1], | ||
| 443 | + /// `cu_qp_delta_abs` (Table 9-24). | ||
| 444 | + pub cu_qp_delta_abs: [ContextModel; 2], | ||
| 445 | + /// `cu_chroma_qp_offset_flag` (Table 9-34). | ||
| 446 | + pub cu_chroma_qp_offset_flag: [ContextModel; 1], | ||
| 447 | + /// `cu_chroma_qp_offset_idx` (Table 9-35). | ||
| 448 | + pub cu_chroma_qp_offset_idx: [ContextModel; 1], | ||
| 449 | + /// §9.3.2.1 palette predictor variables (`PredictorPaletteSize` / | ||
| 450 | + /// `PredictorPaletteEntries`) — parse state that initializes, | ||
| 451 | + /// stores and synchronizes ALONGSIDE the context variables | ||
| 452 | + /// (§9.3.2.3 / §9.3.2.4 / §9.3.2.5), so it travels inside this | ||
| 453 | + /// struct. [`Self::init`] leaves it empty; the slice driver | ||
| 454 | + /// assigns the PPS / SPS initializer-derived predictor at every | ||
| 455 | + /// §9.3.2.2 re-initialization point. | ||
| 456 | + pub palette_predictor: crate::palette::PalettePredictor, | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +impl SliceContexts { | ||
| 460 | + /// The number of distinct adapting context variables per | ||
| 461 | + /// `initType` (shared Table 9-4 groups counted once). | ||
| 462 | + pub const CONTEXT_COUNT: usize = 185; | ||
| 463 | + | ||
| 464 | + /// §9.3.2.2 initialization of the whole context array for one | ||
| 465 | + /// `initType` (0, 1 or 2) and `SliceQpY` (equation 7-54). Every | ||
| 466 | + /// table entry goes through [`ContextModel::init`] | ||
| 467 | + /// (equations 9-4..9-6); inter-only banks at `initType == 0` take | ||
| 468 | + /// the non-adapting placeholder described in the module docs. | ||
| 469 | + /// | ||
| 470 | + /// # Panics | ||
| 471 | + /// | ||
| 472 | + /// Panics when `init_type > 2`. | ||
| 473 | + #[must_use] | ||
| 474 | + pub fn init(init_type: u8, slice_qp_y: i32) -> Self { | ||
| 475 | + assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)"); | ||
| 476 | + let t = init_type as usize; | ||
| 477 | + let init = |v: u8| ContextModel::init(v, slice_qp_y); | ||
| 478 | + // Table 9-11 `part_mode`: ctxIdx 0 at initType 0, 1..4 / 5..8 | ||
| 479 | + // at initType 1 / 2. | ||
| 480 | + let part_mode = if init_type == 0 { | ||
| 481 | + let mut bank = [ContextModel::terminate_state(); 4]; | ||
| 482 | + bank[0] = init(TABLE_9_11_PART_MODE[0]); | ||
| 483 | + bank | ||
| 484 | + } else { | ||
| 485 | + core::array::from_fn(|i| init(TABLE_9_11_PART_MODE[1 + 4 * (t - 1) + i])) | ||
| 486 | + }; | ||
| 487 | + // Table 9-22 `cbf_cb` / `cbf_cr`: ctxIdx 4t..4t+3 plus 12 + t. | ||
| 488 | + let cbf_chroma = core::array::from_fn(|i| { | ||
| 489 | + init(if i < 4 { | ||
| 490 | + TABLE_9_22_CBF_CHROMA[4 * t + i] | ||
| 491 | + } else { | ||
| 492 | + TABLE_9_22_CBF_CHROMA[12 + t] | ||
| 493 | + }) | ||
| 494 | + }); | ||
| 495 | + // Table 9-23 interleave: greater0 at ctxIdx 0 / 2, greater1 at | ||
| 496 | + // ctxIdx 1 / 3 for initType 1 / 2. | ||
| 497 | + let (abs_mvd_greater0_flag, abs_mvd_greater1_flag) = if init_type == 0 { | ||
| 498 | + ( | ||
| 499 | + [ContextModel::terminate_state(); 1], | ||
| 500 | + [ContextModel::terminate_state(); 1], | ||
| 501 | + ) | ||
| 502 | + } else { | ||
| 503 | + ( | ||
| 504 | + [init(TABLE_9_23_ABS_MVD_GREATER_FLAG[2 * (t - 1)])], | ||
| 505 | + [init(TABLE_9_23_ABS_MVD_GREATER_FLAG[2 * (t - 1) + 1])], | ||
| 506 | + ) | ||
| 507 | + }; | ||
| 508 | + // Table 9-25 `transform_skip_flag`: luma at ctxIdx t, the | ||
| 509 | + // shared chroma context at ctxIdx 3 + t. | ||
| 510 | + let transform_skip_flag = [ | ||
| 511 | + init(TABLE_9_25_TRANSFORM_SKIP_FLAG[t]), | ||
| 512 | + init(TABLE_9_25_TRANSFORM_SKIP_FLAG[3 + t]), | ||
| 513 | + ]; | ||
| 514 | + // Tables 9-32 / 9-33 (inter-only): luma at ctxIdx t − 1, the | ||
| 515 | + // shared chroma context at ctxIdx 2 + (t − 1). | ||
| 516 | + let rdpcm_bank = |table: &[u8; 4]| { | ||
| 517 | + if init_type == 0 { | ||
| 518 | + [ContextModel::terminate_state(); 2] | ||
| 519 | + } else { | ||
| 520 | + [init(table[t - 1]), init(table[2 + (t - 1)])] | ||
| 521 | + } | ||
| 522 | + }; | ||
| 523 | + Self { | ||
| 524 | + sao_merge_flag: uniform_bank(&TABLE_9_5_SAO_MERGE_FLAG, init_type, slice_qp_y), | ||
| 525 | + sao_type_idx: uniform_bank(&TABLE_9_6_SAO_TYPE_IDX, init_type, slice_qp_y), | ||
| 526 | + split_cu_flag: uniform_bank(&TABLE_9_7_SPLIT_CU_FLAG, init_type, slice_qp_y), | ||
| 527 | + cu_transquant_bypass_flag: uniform_bank( | ||
| 528 | + &TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG, | ||
| 529 | + init_type, | ||
| 530 | + slice_qp_y, | ||
| 531 | + ), | ||
| 532 | + cu_skip_flag: inter_bank(&TABLE_9_9_CU_SKIP_FLAG, init_type, slice_qp_y), | ||
| 533 | + palette_mode_flag: uniform_bank(&TABLE_9_38_PALETTE_MODE_FLAG, init_type, slice_qp_y), | ||
| 534 | + pred_mode_flag: inter_bank(&TABLE_9_10_PRED_MODE_FLAG, init_type, slice_qp_y), | ||
| 535 | + part_mode, | ||
| 536 | + prev_intra_luma_pred_flag: uniform_bank( | ||
| 537 | + &TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG, | ||
| 538 | + init_type, | ||
| 539 | + slice_qp_y, | ||
| 540 | + ), | ||
| 541 | + intra_chroma_pred_mode: uniform_bank( | ||
| 542 | + &TABLE_9_13_INTRA_CHROMA_PRED_MODE, | ||
| 543 | + init_type, | ||
| 544 | + slice_qp_y, | ||
| 545 | + ), | ||
| 546 | + rqt_root_cbf: inter_bank(&TABLE_9_14_RQT_ROOT_CBF, init_type, slice_qp_y), | ||
| 547 | + merge_flag: inter_bank(&TABLE_9_15_MERGE_FLAG, init_type, slice_qp_y), | ||
| 548 | + merge_idx: inter_bank(&TABLE_9_16_MERGE_IDX, init_type, slice_qp_y), | ||
| 549 | + inter_pred_idc: inter_bank(&TABLE_9_17_INTER_PRED_IDC, init_type, slice_qp_y), | ||
| 550 | + ref_idx: inter_bank(&TABLE_9_18_REF_IDX, init_type, slice_qp_y), | ||
| 551 | + mvp_flag: inter_bank(&TABLE_9_19_MVP_FLAG, init_type, slice_qp_y), | ||
| 552 | + split_transform_flag: uniform_bank( | ||
| 553 | + &TABLE_9_20_SPLIT_TRANSFORM_FLAG, | ||
| 554 | + init_type, | ||
| 555 | + slice_qp_y, | ||
| 556 | + ), | ||
| 557 | + cbf_luma: uniform_bank(&TABLE_9_21_CBF_LUMA, init_type, slice_qp_y), | ||
| 558 | + cbf_chroma, | ||
| 559 | + abs_mvd_greater0_flag, | ||
| 560 | + abs_mvd_greater1_flag, | ||
| 561 | + tu_residual_act_flag: uniform_bank( | ||
| 562 | + &TABLE_9_39_TU_RESIDUAL_ACT_FLAG, | ||
| 563 | + init_type, | ||
| 564 | + slice_qp_y, | ||
| 565 | + ), | ||
| 566 | + log2_res_scale_abs_plus1: uniform_bank( | ||
| 567 | + &TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1, | ||
| 568 | + init_type, | ||
| 569 | + slice_qp_y, | ||
| 570 | + ), | ||
| 571 | + res_scale_sign_flag: uniform_bank( | ||
| 572 | + &TABLE_9_37_RES_SCALE_SIGN_FLAG, | ||
| 573 | + init_type, | ||
| 574 | + slice_qp_y, | ||
| 575 | + ), | ||
| 576 | + transform_skip_flag, | ||
| 577 | + explicit_rdpcm_flag: rdpcm_bank(&TABLE_9_32_EXPLICIT_RDPCM_FLAG), | ||
| 578 | + explicit_rdpcm_dir_flag: rdpcm_bank(&TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG), | ||
| 579 | + residual: ResidualContexts::init(init_type, slice_qp_y), | ||
| 580 | + palette_run_prefix: uniform_bank(&TABLE_9_40_PALETTE_RUN_PREFIX, init_type, slice_qp_y), | ||
| 581 | + palette_copy_above_flag: uniform_bank( | ||
| 582 | + &TABLE_9_41_PALETTE_COPY_ABOVE_FLAG, | ||
| 583 | + init_type, | ||
| 584 | + slice_qp_y, | ||
| 585 | + ), | ||
| 586 | + palette_transpose_flag: uniform_bank( | ||
| 587 | + &TABLE_9_42_PALETTE_TRANSPOSE_FLAG, | ||
| 588 | + init_type, | ||
| 589 | + slice_qp_y, | ||
| 590 | + ), | ||
| 591 | + cu_qp_delta_abs: uniform_bank(&TABLE_9_24_CU_QP_DELTA_ABS, init_type, slice_qp_y), | ||
| 592 | + cu_chroma_qp_offset_flag: uniform_bank( | ||
| 593 | + &TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG, | ||
| 594 | + init_type, | ||
| 595 | + slice_qp_y, | ||
| 596 | + ), | ||
| 597 | + cu_chroma_qp_offset_idx: uniform_bank( | ||
| 598 | + &TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX, | ||
| 599 | + init_type, | ||
| 600 | + slice_qp_y, | ||
| 601 | + ), | ||
| 602 | + palette_predictor: crate::palette::PalettePredictor::default(), | ||
| 603 | + } | ||
| 604 | + } | ||
| 605 | + | ||
| 606 | + /// Initialize the context array for a slice: derives `initType` | ||
| 607 | + /// from `slice_type` and `cabac_init_flag` per equation 9-7 | ||
| 608 | + /// ([`init_type`]), then runs [`SliceContexts::init`]. | ||
| 609 | + /// `cabac_init_flag` is the §7.3.6.1 header flag (inferred 0 when | ||
| 610 | + /// absent — pass `false` for I slices or when | ||
| 611 | + /// `cabac_init_present_flag == 0`); `slice_qp_y` is `SliceQpY` | ||
| 612 | + /// per equation 7-54 (`26 + init_qp_minus26 + slice_qp_delta`). | ||
| 613 | + #[must_use] | ||
| 614 | + pub fn for_slice(slice_type: SliceType, cabac_init_flag: bool, slice_qp_y: i32) -> Self { | ||
| 615 | + let raw = match slice_type { | ||
| 616 | + SliceType::B => 0, | ||
| 617 | + SliceType::P => 1, | ||
| 618 | + SliceType::I => 2, | ||
| 619 | + }; | ||
| 620 | + Self::init(init_type(raw, cabac_init_flag), slice_qp_y) | ||
| 621 | + } | ||
| 622 | +} | ||
| 623 | + | ||
| 624 | +// --------------------------------------------------------------------- | ||
| 625 | +// Tests | ||
| 626 | +// --------------------------------------------------------------------- | ||
| 627 | + | ||
| 628 | +#[cfg(test)] | ||
| 629 | +mod tests { | ||
| 630 | + use super::*; | ||
| 631 | + | ||
| 632 | + /// Every table's printed ctxIdx span (Tables 9-5..9-42). | ||
| 633 | + #[test] | ||
| 634 | + fn table_shapes() { | ||
| 635 | + assert_eq!(TABLE_9_5_SAO_MERGE_FLAG.len(), 3); | ||
| 636 | + assert_eq!(TABLE_9_6_SAO_TYPE_IDX.len(), 3); | ||
| 637 | + assert_eq!(TABLE_9_7_SPLIT_CU_FLAG.len(), 9); | ||
| 638 | + assert_eq!(TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG.len(), 3); | ||
| 639 | + assert_eq!(TABLE_9_9_CU_SKIP_FLAG.len(), 6); | ||
| 640 | + assert_eq!(TABLE_9_10_PRED_MODE_FLAG.len(), 2); | ||
| 641 | + assert_eq!(TABLE_9_11_PART_MODE.len(), 9); | ||
| 642 | + assert_eq!(TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG.len(), 3); | ||
| 643 | + assert_eq!(TABLE_9_13_INTRA_CHROMA_PRED_MODE.len(), 3); | ||
| 644 | + assert_eq!(TABLE_9_14_RQT_ROOT_CBF.len(), 2); | ||
| 645 | + assert_eq!(TABLE_9_15_MERGE_FLAG.len(), 2); | ||
| 646 | + assert_eq!(TABLE_9_16_MERGE_IDX.len(), 2); | ||
| 647 | + assert_eq!(TABLE_9_17_INTER_PRED_IDC.len(), 10); | ||
| 648 | + assert_eq!(TABLE_9_18_REF_IDX.len(), 4); | ||
| 649 | + assert_eq!(TABLE_9_19_MVP_FLAG.len(), 2); | ||
| 650 | + assert_eq!(TABLE_9_20_SPLIT_TRANSFORM_FLAG.len(), 9); | ||
| 651 | + assert_eq!(TABLE_9_21_CBF_LUMA.len(), 6); | ||
| 652 | + assert_eq!(TABLE_9_22_CBF_CHROMA.len(), 15); | ||
| 653 | + assert_eq!(TABLE_9_23_ABS_MVD_GREATER_FLAG.len(), 4); | ||
| 654 | + assert_eq!(TABLE_9_24_CU_QP_DELTA_ABS.len(), 6); | ||
| 655 | + assert_eq!(TABLE_9_25_TRANSFORM_SKIP_FLAG.len(), 6); | ||
| 656 | + assert_eq!(TABLE_9_26_LAST_SIG_COEFF_X_PREFIX.len(), 54); | ||
| 657 | + assert_eq!(TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX.len(), 54); | ||
| 658 | + assert_eq!(TABLE_9_28_CODED_SUB_BLOCK_FLAG.len(), 12); | ||
| 659 | + assert_eq!(TABLE_9_29_SIG_COEFF_FLAG.len(), 132); | ||
| 660 | + assert_eq!(TABLE_9_30_COEFF_ABS_LEVEL_GREATER1_FLAG.len(), 72); | ||
| 661 | + assert_eq!(TABLE_9_31_COEFF_ABS_LEVEL_GREATER2_FLAG.len(), 18); | ||
| 662 | + assert_eq!(TABLE_9_32_EXPLICIT_RDPCM_FLAG.len(), 4); | ||
| 663 | + assert_eq!(TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG.len(), 4); | ||
| 664 | + assert_eq!(TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG.len(), 3); | ||
| 665 | + assert_eq!(TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX.len(), 3); | ||
| 666 | + assert_eq!(TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1.len(), 24); | ||
| 667 | + assert_eq!(TABLE_9_37_RES_SCALE_SIGN_FLAG.len(), 6); | ||
| 668 | + assert_eq!(TABLE_9_38_PALETTE_MODE_FLAG.len(), 3); | ||
| 669 | + assert_eq!(TABLE_9_39_TU_RESIDUAL_ACT_FLAG.len(), 3); | ||
| 670 | + assert_eq!(TABLE_9_40_PALETTE_RUN_PREFIX.len(), 24); | ||
| 671 | + assert_eq!(TABLE_9_41_PALETTE_COPY_ABOVE_FLAG.len(), 3); | ||
| 672 | + assert_eq!(TABLE_9_42_PALETTE_TRANSPOSE_FLAG.len(), 3); | ||
| 673 | + // The all-154 tables really are uniform. | ||
| 674 | + assert!(TABLE_9_24_CU_QP_DELTA_ABS.iter().all(|&v| v == 154)); | ||
| 675 | + assert!(TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1 | ||
| 676 | + .iter() | ||
| 677 | + .all(|&v| v == 154)); | ||
| 678 | + assert!(TABLE_9_37_RES_SCALE_SIGN_FLAG.iter().all(|&v| v == 154)); | ||
| 679 | + assert!(TABLE_9_40_PALETTE_RUN_PREFIX.iter().all(|&v| v == 154)); | ||
| 680 | + // The all-139 tables (transform-skip / RDPCM group). | ||
| 681 | + assert!(TABLE_9_25_TRANSFORM_SKIP_FLAG.iter().all(|&v| v == 139)); | ||
| 682 | + assert!(TABLE_9_32_EXPLICIT_RDPCM_FLAG.iter().all(|&v| v == 139)); | ||
| 683 | + assert!(TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG.iter().all(|&v| v == 139)); | ||
| 684 | + } | ||
| 685 | + | ||
| 686 | + /// Tables 9-26 and 9-27 print identical values (the elements still | ||
| 687 | + /// adapt independent variables). | ||
| 688 | + #[test] | ||
| 689 | + fn last_sig_coeff_tables_print_identically() { | ||
| 690 | + assert_eq!( | ||
| 691 | + TABLE_9_26_LAST_SIG_COEFF_X_PREFIX, | ||
| 692 | + TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX | ||
| 693 | + ); | ||
| 694 | + } | ||
| 695 | + | ||
| 696 | + fn cm(p_state_idx: u8, val_mps: u8) -> ContextModel { | ||
| 697 | + ContextModel { | ||
| 698 | + p_state_idx, | ||
| 699 | + val_mps, | ||
| 700 | + } | ||
| 701 | + } | ||
| 702 | + | ||
| 703 | + /// §9.3.2.2 derived `(pStateIdx, valMps)` pins across QPs for | ||
| 704 | + /// elements drawn from regular three-`initType` tables. Expected | ||
| 705 | + /// values hand-evaluated from equations 9-4..9-6 on the cited | ||
| 706 | + /// table entries. | ||
| 707 | + #[test] | ||
| 708 | + fn derived_state_pins_uniform_tables() { | ||
| 709 | + // Table 9-7 `split_cu_flag`, initType 0 slot 0 (initValue 139). | ||
| 710 | + assert_eq!(SliceContexts::init(0, 0).split_cu_flag[0], cm(8, 1)); | ||
| 711 | + assert_eq!(SliceContexts::init(0, 26).split_cu_flag[0], cm(0, 0)); | ||
| 712 | + assert_eq!(SliceContexts::init(0, 51).split_cu_flag[0], cm(7, 0)); | ||
| 713 | + // Table 9-7 `split_cu_flag`, initType 2 slot 0 (initValue 107). | ||
| 714 | + assert_eq!(SliceContexts::init(2, 17).split_cu_flag[0], cm(7, 0)); | ||
| 715 | + assert_eq!(SliceContexts::init(2, 26).split_cu_flag[0], cm(16, 0)); | ||
| 716 | + assert_eq!(SliceContexts::init(2, 51).split_cu_flag[0], cm(39, 0)); | ||
| 717 | + // Table 9-6 `sao_type_idx`, initType 0 (initValue 200): the | ||
| 718 | + // valMps flip across the QP range. | ||
| 719 | + assert_eq!(SliceContexts::init(0, 0).sao_type_idx[0], cm(15, 0)); | ||
| 720 | + assert_eq!(SliceContexts::init(0, 26).sao_type_idx[0], cm(8, 1)); | ||
| 721 | + assert_eq!(SliceContexts::init(0, 51).sao_type_idx[0], cm(31, 1)); | ||
| 722 | + // Table 9-6 `sao_type_idx`, initType 2 (initValue 160): | ||
| 723 | + // slopeIdx 10 ⇒ m == 5; the state barely moves with QP. | ||
| 724 | + assert_eq!(SliceContexts::init(2, 0).sao_type_idx[0], cm(62, 0)); | ||
| 725 | + assert_eq!(SliceContexts::init(2, 51).sao_type_idx[0], cm(62, 0)); | ||
| 726 | + // Table 9-20 `split_transform_flag`, initType 2 slot 0 | ||
| 727 | + // (initValue 224). | ||
| 728 | + assert_eq!(SliceContexts::init(2, 0).split_transform_flag[0], cm(62, 0)); | ||
| 729 | + assert_eq!( | ||
| 730 | + SliceContexts::init(2, 37).split_transform_flag[0], | ||
| 731 | + cm(22, 0) | ||
| 732 | + ); | ||
| 733 | + assert_eq!(SliceContexts::init(2, 51).split_transform_flag[0], cm(0, 0)); | ||
| 734 | + // Table 9-21 `cbf_luma`, initType 0 slot 0 (initValue 111). | ||
| 735 | + assert_eq!(SliceContexts::init(0, 17).cbf_luma[0], cm(24, 1)); | ||
| 736 | + assert_eq!(SliceContexts::init(0, 51).cbf_luma[0], cm(7, 0)); | ||
| 737 | + // QP clamp (equation 9-6 Clip3( 0, 51, SliceQpY )): out-of-range | ||
| 738 | + // QPs pin to the endpoints. | ||
| 739 | + assert_eq!( | ||
| 740 | + SliceContexts::init(0, -7).cbf_luma[0], | ||
| 741 | + SliceContexts::init(0, 0).cbf_luma[0] | ||
| 742 | + ); | ||
| 743 | + assert_eq!( | ||
| 744 | + SliceContexts::init(0, 60).cbf_luma[0], | ||
| 745 | + SliceContexts::init(0, 51).cbf_luma[0] | ||
| 746 | + ); | ||
| 747 | + } | ||
| 748 | + | ||
| 749 | + /// Pins for the inter-only banks (Table 9-4 `initType` 1 / 2 | ||
| 750 | + /// columns). | ||
| 751 | + #[test] | ||
| 752 | + fn derived_state_pins_inter_tables() { | ||
| 753 | + // Table 9-9 `cu_skip_flag`, initType 1 slot 0 (initValue 197). | ||
| 754 | + assert_eq!(SliceContexts::init(1, 17).cu_skip_flag[0], cm(24, 0)); | ||
| 755 | + assert_eq!(SliceContexts::init(1, 26).cu_skip_flag[0], cm(15, 0)); | ||
| 756 | + assert_eq!(SliceContexts::init(1, 51).cu_skip_flag[0], cm(7, 1)); | ||
| 757 | + // Table 9-16 `merge_idx`, initType 1 (initValue 122). | ||
| 758 | + assert_eq!(SliceContexts::init(1, 0).merge_idx[0], cm(0, 1)); | ||
| 759 | + assert_eq!(SliceContexts::init(1, 26).merge_idx[0], cm(16, 0)); | ||
| 760 | + assert_eq!(SliceContexts::init(1, 51).merge_idx[0], cm(31, 0)); | ||
| 761 | + // Table 9-17 `inter_pred_idc`, initType 1 slot 0 (initValue 95). | ||
| 762 | + assert_eq!(SliceContexts::init(1, 26).inter_pred_idc[0], cm(7, 1)); | ||
| 763 | + assert_eq!(SliceContexts::init(1, 51).inter_pred_idc[0], cm(23, 0)); | ||
| 764 | + // The initType 2 column starts at the table's second span: | ||
| 765 | + // Table 9-17 ctxIdx 5 also holds 95. | ||
| 766 | + assert_eq!( | ||
| 767 | + SliceContexts::init(2, 26).inter_pred_idc[0], | ||
| 768 | + SliceContexts::init(1, 26).inter_pred_idc[0] | ||
| 769 | + ); | ||
| 770 | + // Table 9-23 interleave: `abs_mvd_greater0_flag` initType 2 | ||
| 771 | + // reads ctxIdx 2 (initValue 169), `abs_mvd_greater1_flag` | ||
| 772 | + // initType 1 reads ctxIdx 1 (initValue 198). | ||
| 773 | + assert_eq!( | ||
| 774 | + SliceContexts::init(2, 26).abs_mvd_greater0_flag[0], | ||
| 775 | + cm(0, 1) | ||
| 776 | + ); | ||
| 777 | + assert_eq!( | ||
| 778 | + SliceContexts::init(2, 51).abs_mvd_greater0_flag[0], | ||
| 779 | + cm(7, 1) | ||
| 780 | + ); | ||
| 781 | + assert_eq!( | ||
| 782 | + SliceContexts::init(1, 26).abs_mvd_greater1_flag[0], | ||
| 783 | + cm(7, 0) | ||
| 784 | + ); | ||
| 785 | + assert_eq!( | ||
| 786 | + SliceContexts::init(1, 51).abs_mvd_greater1_flag[0], | ||
| 787 | + cm(15, 1) | ||
| 788 | + ); | ||
| 789 | + } | ||
| 790 | + | ||
| 791 | + /// Pins for the irregular Table 9-4 layouts (`part_mode`, | ||
| 792 | + /// `cbf_cb`/`cbf_cr`). | ||
| 793 | + #[test] | ||
| 794 | + fn derived_state_pins_irregular_tables() { | ||
| 795 | + // Table 9-11 `part_mode` initType 0: only ctxIdx 0 | ||
| 796 | + // (initValue 184) is initialized; slots 1..3 take the | ||
| 797 | + // non-adapting placeholder. | ||
| 798 | + let i_slice = SliceContexts::init(0, 26); | ||
| 799 | + assert_eq!(i_slice.part_mode[0], cm(0, 1)); | ||
| 800 | + for slot in 1..4 { | ||
| 801 | + assert_eq!(i_slice.part_mode[slot], ContextModel::terminate_state()); | ||
| 802 | + } | ||
| 803 | + assert_eq!(SliceContexts::init(0, 0).part_mode[0], cm(15, 0)); | ||
| 804 | + assert_eq!(SliceContexts::init(0, 51).part_mode[0], cm(15, 1)); | ||
| 805 | + // `part_mode` initType 1 slot 1 reads Table 9-11 ctxIdx 2 | ||
| 806 | + // (initValue 139); initType 2 slot 1 reads ctxIdx 6 (also 139). | ||
| 807 | + assert_eq!(SliceContexts::init(1, 26).part_mode[1], cm(0, 0)); | ||
| 808 | + assert_eq!( | ||
| 809 | + SliceContexts::init(2, 26).part_mode[1], | ||
| 810 | + SliceContexts::init(1, 26).part_mode[1] | ||
| 811 | + ); | ||
| 812 | + // Table 9-22 `cbf_cb`/`cbf_cr` initType 0: slot 0 reads ctxIdx 0 | ||
| 813 | + // (initValue 94), slot 4 reads ctxIdx 12 (initValue 154). | ||
| 814 | + assert_eq!(SliceContexts::init(0, 0).cbf_chroma[0], cm(32, 1)); | ||
| 815 | + assert_eq!(SliceContexts::init(0, 26).cbf_chroma[0], cm(0, 0)); | ||
| 816 | + assert_eq!(SliceContexts::init(0, 51).cbf_chroma[0], cm(31, 0)); | ||
| 817 | + for qp in [0, 26, 51] { | ||
| 818 | + // initValue 154 ⇒ m == 0, n == 64 ⇒ preCtxState == 64 at | ||
| 819 | + // every QP: pStateIdx 0, valMps 1. | ||
| 820 | + assert_eq!(SliceContexts::init(0, qp).cbf_chroma[4], cm(0, 1)); | ||
| 821 | + } | ||
| 822 | + // Table 9-25 `transform_skip_flag` (initValue 139 everywhere): | ||
| 823 | + // luma and chroma slots agree at each initType. | ||
| 824 | + let b = SliceContexts::init(2, 26); | ||
| 825 | + assert_eq!(b.transform_skip_flag[0], b.transform_skip_flag[1]); | ||
| 826 | + assert_eq!(b.transform_skip_flag[0], cm(0, 0)); | ||
| 827 | + } | ||
| 828 | + | ||
| 829 | + /// Whole-array smoke test per `initType`: every table-derived | ||
| 830 | + /// context lands in the equations-9-4..9-6 range | ||
| 831 | + /// (`pStateIdx <= 62`), and the `initType == 0` placeholder | ||
| 832 | + /// (`pStateIdx == 63`) appears exactly on the inter-only banks. | ||
| 833 | + #[test] | ||
| 834 | + fn whole_array_smoke_per_init_type() { | ||
| 835 | + for init_type in 0u8..=2 { | ||
| 836 | + for qp in [0, 26, 51] { | ||
| 837 | + let ctx = SliceContexts::init(init_type, qp); | ||
| 838 | + let inter_only: Vec<&[ContextModel]> = vec![ | ||
| 839 | + &ctx.cu_skip_flag, | ||
| 840 | + &ctx.pred_mode_flag, | ||
| 841 | + &ctx.rqt_root_cbf, | ||
| 842 | + &ctx.merge_flag, | ||
| 843 | + &ctx.merge_idx, | ||
| 844 | + &ctx.inter_pred_idc, | ||
| 845 | + &ctx.ref_idx, | ||
| 846 | + &ctx.mvp_flag, | ||
| 847 | + &ctx.abs_mvd_greater0_flag, | ||
| 848 | + &ctx.abs_mvd_greater1_flag, | ||
| 849 | + &ctx.explicit_rdpcm_flag, | ||
| 850 | + &ctx.explicit_rdpcm_dir_flag, | ||
| 851 | + ]; | ||
| 852 | + let every_type: Vec<&[ContextModel]> = vec![ | ||
| 853 | + &ctx.sao_merge_flag, | ||
| 854 | + &ctx.sao_type_idx, | ||
| 855 | + &ctx.split_cu_flag, | ||
| 856 | + &ctx.cu_transquant_bypass_flag, | ||
| 857 | + &ctx.palette_mode_flag, | ||
| 858 | + &ctx.prev_intra_luma_pred_flag, | ||
| 859 | + &ctx.intra_chroma_pred_mode, | ||
| 860 | + &ctx.split_transform_flag, | ||
| 861 | + &ctx.cbf_luma, | ||
| 862 | + &ctx.cbf_chroma, | ||
| 863 | + &ctx.tu_residual_act_flag, | ||
| 864 | + &ctx.log2_res_scale_abs_plus1, | ||
| 865 | + &ctx.res_scale_sign_flag, | ||
| 866 | + &ctx.transform_skip_flag, | ||
| 867 | + &ctx.residual.last_sig_coeff_x_prefix, | ||
| 868 | + &ctx.residual.last_sig_coeff_y_prefix, | ||
| 869 | + &ctx.residual.coded_sub_block_flag, | ||
| 870 | + &ctx.residual.sig_coeff_flag, | ||
| 871 | + &ctx.residual.coeff_abs_level_greater1_flag, | ||
| 872 | + &ctx.residual.coeff_abs_level_greater2_flag, | ||
| 873 | + &ctx.palette_run_prefix, | ||
| 874 | + &ctx.palette_copy_above_flag, | ||
| 875 | + &ctx.palette_transpose_flag, | ||
| 876 | + &ctx.cu_qp_delta_abs, | ||
| 877 | + &ctx.cu_chroma_qp_offset_flag, | ||
| 878 | + &ctx.cu_chroma_qp_offset_idx, | ||
| 879 | + ]; | ||
| 880 | + let mut total = 0usize; | ||
| 881 | + for bank in &every_type { | ||
| 882 | + for c in bank.iter() { | ||
| 883 | + assert!(c.p_state_idx <= 62, "table-derived state out of range"); | ||
| 884 | + assert!(c.val_mps <= 1); | ||
| 885 | + total += 1; | ||
| 886 | + } | ||
| 887 | + } | ||
| 888 | + // `part_mode` slot 0 is table-derived at every | ||
| 889 | + // initType; slots 1..3 only for initType 1 / 2. | ||
| 890 | + assert!(ctx.part_mode[0].p_state_idx <= 62); | ||
| 891 | + total += 4; | ||
| 892 | + for bank in &inter_only { | ||
| 893 | + for c in bank.iter() { | ||
| 894 | + if init_type == 0 { | ||
| 895 | + assert_eq!(*c, ContextModel::terminate_state()); | ||
| 896 | + } else { | ||
| 897 | + assert!(c.p_state_idx <= 62); | ||
| 898 | + } | ||
| 899 | + total += 1; | ||
| 900 | + } | ||
| 901 | + } | ||
| 902 | + if init_type == 0 { | ||
| 903 | + for slot in 1..4 { | ||
| 904 | + assert_eq!(ctx.part_mode[slot], ContextModel::terminate_state()); | ||
| 905 | + } | ||
| 906 | + } else { | ||
| 907 | + for slot in 1..4 { | ||
| 908 | + assert!(ctx.part_mode[slot].p_state_idx <= 62); | ||
| 909 | + } | ||
| 910 | + } | ||
| 911 | + assert_eq!(total, SliceContexts::CONTEXT_COUNT); | ||
| 912 | + } | ||
| 913 | + } | ||
| 914 | + } | ||
| 915 | + | ||
| 916 | + /// Equation 9-7 routing through [`SliceContexts::for_slice`]: the | ||
| 917 | + /// `cabac_init_flag` swap between P and B, and its irrelevance for | ||
| 918 | + /// I slices. | ||
| 919 | + #[test] | ||
| 920 | + fn for_slice_eq_9_7_routing() { | ||
| 921 | + let qp = 30; | ||
| 922 | + assert_eq!( | ||
| 923 | + SliceContexts::for_slice(SliceType::I, false, qp), | ||
| 924 | + SliceContexts::init(0, qp) | ||
| 925 | + ); | ||
| 926 | + assert_eq!( | ||
| 927 | + SliceContexts::for_slice(SliceType::I, true, qp), | ||
| 928 | + SliceContexts::init(0, qp) | ||
| 929 | + ); | ||
| 930 | + assert_eq!( | ||
| 931 | + SliceContexts::for_slice(SliceType::P, false, qp), | ||
| 932 | + SliceContexts::init(1, qp) | ||
| 933 | + ); | ||
| 934 | + assert_eq!( | ||
| 935 | + SliceContexts::for_slice(SliceType::P, true, qp), | ||
| 936 | + SliceContexts::init(2, qp) | ||
| 937 | + ); | ||
| 938 | + assert_eq!( | ||
| 939 | + SliceContexts::for_slice(SliceType::B, false, qp), | ||
| 940 | + SliceContexts::init(2, qp) | ||
| 941 | + ); | ||
| 942 | + assert_eq!( | ||
| 943 | + SliceContexts::for_slice(SliceType::B, true, qp), | ||
| 944 | + SliceContexts::init(1, qp) | ||
| 945 | + ); | ||
| 946 | + // P with the flag and B without select the same array; P | ||
| 947 | + // without and B with likewise. | ||
| 948 | + assert_eq!( | ||
| 949 | + SliceContexts::for_slice(SliceType::P, true, qp), | ||
| 950 | + SliceContexts::for_slice(SliceType::B, false, qp) | ||
| 951 | + ); | ||
| 952 | + assert_eq!( | ||
| 953 | + SliceContexts::for_slice(SliceType::P, false, qp), | ||
| 954 | + SliceContexts::for_slice(SliceType::B, true, qp) | ||
| 955 | + ); | ||
| 956 | + // The three initTypes produce three distinct arrays. | ||
| 957 | + assert_ne!(SliceContexts::init(0, qp), SliceContexts::init(1, qp)); | ||
| 958 | + assert_ne!(SliceContexts::init(1, qp), SliceContexts::init(2, qp)); | ||
| 959 | + assert_ne!(SliceContexts::init(0, qp), SliceContexts::init(2, qp)); | ||
| 960 | + } | ||
| 961 | + | ||
| 962 | + /// The span-selection helpers reject malformed inputs and slice | ||
| 963 | + /// the right ctxIdx ranges. | ||
| 964 | + #[test] | ||
| 965 | + fn span_selection_helpers() { | ||
| 966 | + assert_eq!( | ||
| 967 | + uniform_init_values::<3>(&TABLE_9_7_SPLIT_CU_FLAG, 1), | ||
| 968 | + [107, 139, 126] | ||
| 969 | + ); | ||
| 970 | + assert_eq!( | ||
| 971 | + inter_init_values::<3>(&TABLE_9_9_CU_SKIP_FLAG, 2), | ||
| 972 | + Some([197, 185, 201]) | ||
| 973 | + ); | ||
| 974 | + assert_eq!(inter_init_values::<3>(&TABLE_9_9_CU_SKIP_FLAG, 0), None); | ||
| 975 | + let sig0 = sig_coeff_flag_init_values(0); | ||
| 976 | + assert_eq!(sig0[0], 111); | ||
| 977 | + assert_eq!(sig0[41], 111); | ||
| 978 | + // The transform-skip tail: Table 9-29 ctxIdx 126 / 127. | ||
| 979 | + assert_eq!(sig0[42], 141); | ||
| 980 | + assert_eq!(sig0[43], 111); | ||
| 981 | + let sig1 = sig_coeff_flag_init_values(1); | ||
| 982 | + assert_eq!(sig1[0], 155); | ||
| 983 | + assert_eq!(sig1[41], 140); | ||
| 984 | + let sig2 = sig_coeff_flag_init_values(2); | ||
| 985 | + assert_eq!(sig2[0], 170); | ||
| 986 | + assert_eq!(sig2[41], 140); | ||
| 987 | + } | ||
| 988 | + | ||
| 989 | + #[test] | ||
| 990 | + #[should_panic(expected = "initType must be 0, 1 or 2")] | ||
| 991 | + fn init_rejects_init_type_3() { | ||
| 992 | + let _ = SliceContexts::init(3, 26); | ||
| 993 | + } | ||
| 994 | +} | ||
Diff too large; view file
| @@ -0,0 +1,2484 @@ | |||
| 1 | +//! §8.7.2.4 — derivation of the deblocking boundary filtering strength. | ||
| 2 | +//! | ||
| 3 | +//! The deblocking filter (§8.7.2) operates on an 8×8 luma grid: vertical | ||
| 4 | +//! edges first, then horizontal edges. For each candidate edge segment | ||
| 5 | +//! the boundary filtering strength `bS ∈ {0, 1, 2}` is derived per | ||
| 6 | +//! §8.7.2.4 from the intra/inter mode, the transform coded-block flags, | ||
| 7 | +//! and the motion vectors / reference pictures of the two prediction | ||
| 8 | +//! blocks straddling the edge. This module implements that derivation — | ||
| 9 | +//! [`derive_boundary_strength`] — reading the per-4×4-block motion / mode | ||
| 10 | +//! state from a [`crate::motion::MotionField`]. | ||
| 11 | +//! | ||
| 12 | +//! The §8.7.2.2 / §8.7.2.3 edge-flag derivation (which marks the | ||
| 13 | +//! transform-block / prediction-block boundaries an edge falls on, from | ||
| 14 | +//! the coding / transform tree geometry) is the input `edgeFlags` array; | ||
| 15 | +//! producing it from the decoded partition tree is the picture driver's | ||
| 16 | +//! follow-up. The §8.7.2.5 edge filtering process (the actual sample | ||
| 17 | +//! modification using `bS`, `β` and `tC`) is implemented by the | ||
| 18 | +//! per-sample primitives [`luma_beta_tc`] (§8.7.2.5.3 β/tC, Table 8-12 | ||
| 19 | +//! via [`beta_prime`] / [`tc_prime`]), [`luma_sample_decision`] | ||
| 20 | +//! (§8.7.2.5.6), [`luma_edge_decision`] (§8.7.2.5.3 `dE`/`dEp`/`dEq`) | ||
| 21 | +//! and [`filter_luma_sample`] (§8.7.2.5.7 strong/weak), plus the chroma | ||
| 22 | +//! path [`chroma_tc`] (§8.7.2.5.5, Table 8-10 via [`chroma_qpc_420`]) | ||
| 23 | +//! and [`filter_chroma_sample`] (§8.7.2.5.8). The plane-level block-edge | ||
| 24 | +//! drivers [`filter_luma_block_edge`] (§8.7.2.5.4) and | ||
| 25 | +//! [`filter_chroma_block_edge`] (§8.7.2.5.5) gather/apply those | ||
| 26 | +//! primitives across a 4-row edge segment of a [`SamplePlane`] in place. | ||
| 27 | + | ||
| 28 | +use crate::binarization::PartMode; | ||
| 29 | +use crate::motion::MotionField; | ||
| 30 | +use crate::picture::{sub_wh_c, Picture, Plane}; | ||
| 31 | + | ||
| 32 | +/// §8.7.2.1 — the edge orientation being filtered. | ||
| 33 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 34 | +pub enum EdgeType { | ||
| 35 | + /// `EDGE_VER` — a vertical edge (filtered left-to-right). | ||
| 36 | + Vertical, | ||
| 37 | + /// `EDGE_HOR` — a horizontal edge (filtered top-to-bottom). | ||
| 38 | + Horizontal, | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// The transform-tree split geometry of one luma coding block, used by the | ||
| 42 | +/// §8.7.2.2 edge-flag derivation. | ||
| 43 | +/// | ||
| 44 | +/// Each node is either a `Split` (a `split_transform_flag == 1` node whose | ||
| 45 | +/// four quadrants recurse) or a `Leaf` (a `split_transform_flag == 0` | ||
| 46 | +/// transform block). The deblocker only needs the split structure, not the | ||
| 47 | +/// residual coefficients — the leaves mark where transform-block edges | ||
| 48 | +/// fall on the 8×8 grid. | ||
| 49 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 50 | +pub enum TransformSplit { | ||
| 51 | + /// A `split_transform_flag == 1` node: four quadrants in raster order | ||
| 52 | + /// (top-left, top-right, bottom-left, bottom-right), each spanning | ||
| 53 | + /// `1 << (log2TrafoSize − 1)` luma samples. | ||
| 54 | + Split(Box<[TransformSplit; 4]>), | ||
| 55 | + /// A `split_transform_flag == 0` transform-block leaf. | ||
| 56 | + Leaf, | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +impl TransformSplit { | ||
| 60 | + /// A leaf spanning the whole coding block (no transform split). | ||
| 61 | + #[inline] | ||
| 62 | + #[must_use] | ||
| 63 | + pub fn leaf() -> Self { | ||
| 64 | + TransformSplit::Leaf | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + /// A single-level split into four equal quadrants, each a leaf. | ||
| 68 | + #[inline] | ||
| 69 | + #[must_use] | ||
| 70 | + pub fn split_once() -> Self { | ||
| 71 | + TransformSplit::Split(Box::new([ | ||
| 72 | + TransformSplit::Leaf, | ||
| 73 | + TransformSplit::Leaf, | ||
| 74 | + TransformSplit::Leaf, | ||
| 75 | + TransformSplit::Leaf, | ||
| 76 | + ])) | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + /// Map a parsed §7.3.8.8 [`crate::transform_tree::TransformTree`] to the | ||
| 80 | + /// deblocking transform-split structure the §8.7.2.2 transform-block | ||
| 81 | + /// boundary recursion consumes (only the split topology matters, not the | ||
| 82 | + /// per-leaf residual). A CU with no transform tree (skip / `rqt_root_cbf | ||
| 83 | + /// == 0`) is a single whole-CB leaf. | ||
| 84 | + #[must_use] | ||
| 85 | + pub fn from_tree(tree: Option<&crate::transform_tree::TransformTree>) -> Self { | ||
| 86 | + use crate::transform_tree::TransformTree; | ||
| 87 | + match tree { | ||
| 88 | + None | Some(TransformTree::Leaf { .. }) => TransformSplit::Leaf, | ||
| 89 | + Some(TransformTree::Split { children, .. }) => TransformSplit::Split(Box::new([ | ||
| 90 | + Self::from_tree(Some(&children[0])), | ||
| 91 | + Self::from_tree(Some(&children[1])), | ||
| 92 | + Self::from_tree(Some(&children[2])), | ||
| 93 | + Self::from_tree(Some(&children[3])), | ||
| 94 | + ])), | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// The invariant context threaded through the §8.7.2.2 recursion. | ||
| 100 | +struct TbBoundaryCtx<'a> { | ||
| 101 | + filter_edge_flag: bool, | ||
| 102 | + edge_type: EdgeType, | ||
| 103 | + n_cbs: usize, | ||
| 104 | + edge_flags: &'a mut [bool], | ||
| 105 | + tb_edge: &'a mut [bool], | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// §8.7.2.2 transform-block-boundary recursion: walk one node of the | ||
| 109 | +/// transform tree, marking the `edge_flags` (any block boundary the edge | ||
| 110 | +/// falls on) and `tb_edge` (transform-block boundaries only) grids. | ||
| 111 | +/// | ||
| 112 | +/// `(xb0, yb0)` is the node's top-left luma sample relative to the coding | ||
| 113 | +/// block; `log2_trafo_size` is the node side. The `ctx.filter_edge_flag` | ||
| 114 | +/// is the §8.7.2.1 `filterLeftCbEdgeFlag` / `filterTopCbEdgeFlag` that | ||
| 115 | +/// gates the coding-block boundary (xB0/yB0 == 0) edge. | ||
| 116 | +fn transform_block_boundary( | ||
| 117 | + node: &TransformSplit, | ||
| 118 | + xb0: usize, | ||
| 119 | + yb0: usize, | ||
| 120 | + log2_trafo_size: u32, | ||
| 121 | + ctx: &mut TbBoundaryCtx<'_>, | ||
| 122 | +) { | ||
| 123 | + if let TransformSplit::Split(children) = node { | ||
| 124 | + let half = 1usize << (log2_trafo_size - 1); | ||
| 125 | + let xb1 = xb0 + half; | ||
| 126 | + let yb1 = yb0 + half; | ||
| 127 | + let quad_origins = [(xb0, yb0), (xb1, yb0), (xb0, yb1), (xb1, yb1)]; | ||
| 128 | + for (child, &(cx, cy)) in children.iter().zip(quad_origins.iter()) { | ||
| 129 | + transform_block_boundary(child, cx, cy, log2_trafo_size - 1, ctx); | ||
| 130 | + } | ||
| 131 | + return; | ||
| 132 | + } | ||
| 133 | + // Leaf: mark the leading edge of this transform block. EDGE_VER marks | ||
| 134 | + // the column xB0 for k = 0..size; EDGE_HOR marks the row yB0. | ||
| 135 | + let size = 1usize << log2_trafo_size; | ||
| 136 | + let n_cbs = ctx.n_cbs; | ||
| 137 | + match ctx.edge_type { | ||
| 138 | + EdgeType::Vertical => { | ||
| 139 | + // edgeFlags[xB0][yB0+k]: filterEdgeFlag at the CB boundary | ||
| 140 | + // (xB0 == 0), else 1. | ||
| 141 | + let val = if xb0 == 0 { ctx.filter_edge_flag } else { true }; | ||
| 142 | + for k in 0..size { | ||
| 143 | + let idx = (yb0 + k) * n_cbs + xb0; | ||
| 144 | + ctx.edge_flags[idx] = val; | ||
| 145 | + ctx.tb_edge[idx] = val; | ||
| 146 | + } | ||
| 147 | + } | ||
| 148 | + EdgeType::Horizontal => { | ||
| 149 | + let val = if yb0 == 0 { ctx.filter_edge_flag } else { true }; | ||
| 150 | + for k in 0..size { | ||
| 151 | + let idx = yb0 * n_cbs + (xb0 + k); | ||
| 152 | + ctx.edge_flags[idx] = val; | ||
| 153 | + ctx.tb_edge[idx] = val; | ||
| 154 | + } | ||
| 155 | + } | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +/// §8.7.2.3 prediction-block-boundary derivation: mark the internal | ||
| 160 | +/// prediction-partition edge of a coding block into `edge_flags` (a | ||
| 161 | +/// prediction edge is *not* a transform-block edge, so `tb_edge` is left | ||
| 162 | +/// untouched). | ||
| 163 | +fn prediction_block_boundary( | ||
| 164 | + part_mode: PartMode, | ||
| 165 | + log2_cb_size: u32, | ||
| 166 | + edge_type: EdgeType, | ||
| 167 | + n_cbs: usize, | ||
| 168 | + edge_flags: &mut [bool], | ||
| 169 | +) { | ||
| 170 | + // The internal partition column (EDGE_VER) / row (EDGE_HOR), if any. | ||
| 171 | + let half = 1usize << (log2_cb_size - 1); | ||
| 172 | + let quarter = 1usize << (log2_cb_size.saturating_sub(2)); | ||
| 173 | + let pos = match (edge_type, part_mode) { | ||
| 174 | + (EdgeType::Vertical, PartMode::PartNx2N | PartMode::PartNxN) => Some(half), | ||
| 175 | + (EdgeType::Vertical, PartMode::PartNLx2N) => Some(quarter), | ||
| 176 | + (EdgeType::Vertical, PartMode::PartNRx2N) => Some(3 * quarter), | ||
| 177 | + (EdgeType::Horizontal, PartMode::Part2NxN | PartMode::PartNxN) => Some(half), | ||
| 178 | + (EdgeType::Horizontal, PartMode::Part2NxnU) => Some(quarter), | ||
| 179 | + (EdgeType::Horizontal, PartMode::Part2NxnD) => Some(3 * quarter), | ||
| 180 | + _ => None, | ||
| 181 | + }; | ||
| 182 | + if let Some(p) = pos { | ||
| 183 | + for k in 0..n_cbs { | ||
| 184 | + let idx = match edge_type { | ||
| 185 | + EdgeType::Vertical => k * n_cbs + p, | ||
| 186 | + EdgeType::Horizontal => p * n_cbs + k, | ||
| 187 | + }; | ||
| 188 | + edge_flags[idx] = true; | ||
| 189 | + } | ||
| 190 | + } | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +/// The §8.7.2.2 / §8.7.2.3 edge-flag grids for one coding block. | ||
| 194 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 195 | +pub struct EdgeFlags { | ||
| 196 | + n_cbs: usize, | ||
| 197 | + /// Row-major `n_cbs²`, `true` where a transform / prediction block | ||
| 198 | + /// boundary falls (the §8.7.2.4 bS input). | ||
| 199 | + edge_flags: Vec<bool>, | ||
| 200 | + /// Row-major `n_cbs²`, `true` where the edge is *also* a | ||
| 201 | + /// transform-block boundary (the §8.7.2.4 second-bullet `cbf` test). | ||
| 202 | + tb_edge: Vec<bool>, | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +impl EdgeFlags { | ||
| 206 | + /// The `edge_flags` grid (row-major, `[y * nCbS + x]`). | ||
| 207 | + #[inline] | ||
| 208 | + #[must_use] | ||
| 209 | + pub fn edge_flags(&self) -> &[bool] { | ||
| 210 | + &self.edge_flags | ||
| 211 | + } | ||
| 212 | + | ||
| 213 | + /// The `tb_edge` grid (row-major, `[y * nCbS + x]`). | ||
| 214 | + #[inline] | ||
| 215 | + #[must_use] | ||
| 216 | + pub fn tb_edge(&self) -> &[bool] { | ||
| 217 | + &self.tb_edge | ||
| 218 | + } | ||
| 219 | + | ||
| 220 | + /// `edge_flags[x][y]`. | ||
| 221 | + #[inline] | ||
| 222 | + #[must_use] | ||
| 223 | + pub fn edge_at(&self, x: usize, y: usize) -> bool { | ||
| 224 | + self.edge_flags[y * self.n_cbs + x] | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + /// `tb_edge[x][y]`. | ||
| 228 | + #[inline] | ||
| 229 | + #[must_use] | ||
| 230 | + pub fn tb_at(&self, x: usize, y: usize) -> bool { | ||
| 231 | + self.tb_edge[y * self.n_cbs + x] | ||
| 232 | + } | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +/// §8.7.2.2 + §8.7.2.3 — derive the `edge_flags` + `tb_edge` grids for one | ||
| 236 | +/// coding block in one edge direction. | ||
| 237 | +/// | ||
| 238 | +/// `transform_split` is the coding block's transform-tree split geometry | ||
| 239 | +/// ([`TransformSplit`]); `part_mode` is the prediction `PartMode`; | ||
| 240 | +/// `log2_cb_size` is the luma coding-block side; `filter_edge_flag` is the | ||
| 241 | +/// §8.7.2.1 `filterLeftCbEdgeFlag` (EDGE_VER) / `filterTopCbEdgeFlag` | ||
| 242 | +/// (EDGE_HOR) gating the coding-block boundary edge. | ||
| 243 | +/// | ||
| 244 | +/// The result feeds [`derive_boundary_strength`] (`edge_flags` + `tb_edge`) | ||
| 245 | +/// and, after bS, the §8.7.2.5.1 / .2 CU edge filtering driver. | ||
| 246 | +#[must_use] | ||
| 247 | +pub fn derive_edge_flags( | ||
| 248 | + transform_split: &TransformSplit, | ||
| 249 | + part_mode: PartMode, | ||
| 250 | + log2_cb_size: u32, | ||
| 251 | + edge_type: EdgeType, | ||
| 252 | + filter_edge_flag: bool, | ||
| 253 | +) -> EdgeFlags { | ||
| 254 | + let n_cbs = 1usize << log2_cb_size; | ||
| 255 | + let mut edge_flags = vec![false; n_cbs * n_cbs]; | ||
| 256 | + let mut tb_edge = vec![false; n_cbs * n_cbs]; | ||
| 257 | + { | ||
| 258 | + let mut ctx = TbBoundaryCtx { | ||
| 259 | + filter_edge_flag, | ||
| 260 | + edge_type, | ||
| 261 | + n_cbs, | ||
| 262 | + edge_flags: &mut edge_flags, | ||
| 263 | + tb_edge: &mut tb_edge, | ||
| 264 | + }; | ||
| 265 | + transform_block_boundary(transform_split, 0, 0, log2_cb_size, &mut ctx); | ||
| 266 | + } | ||
| 267 | + prediction_block_boundary(part_mode, log2_cb_size, edge_type, n_cbs, &mut edge_flags); | ||
| 268 | + EdgeFlags { | ||
| 269 | + n_cbs, | ||
| 270 | + edge_flags, | ||
| 271 | + tb_edge, | ||
| 272 | + } | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +/// The §8.7.2.4 boundary filtering strength for one CU's edges, a | ||
| 276 | +/// `(nCbS)×(nCbS)` grid indexed in luma samples (only the §8.7.2.4 | ||
| 277 | +/// sampled positions `xDi`/`yDj` carry meaningful values; the rest are 0). | ||
| 278 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 279 | +pub struct BoundaryStrength { | ||
| 280 | + n_cbs: usize, | ||
| 281 | + /// Row-major `n_cbs * n_cbs`, `bs[y * n_cbs + x]`. | ||
| 282 | + bs: Vec<u8>, | ||
| 283 | +} | ||
| 284 | + | ||
| 285 | +impl BoundaryStrength { | ||
| 286 | + /// `bS[x][y]` at luma offset `(x, y)` within the coding block. | ||
| 287 | + /// | ||
| 288 | + /// # Panics | ||
| 289 | + /// Panics if `(x, y)` lies outside the `(nCbS)×(nCbS)` block. | ||
| 290 | + #[must_use] | ||
| 291 | + pub fn at(&self, x: usize, y: usize) -> u8 { | ||
| 292 | + self.bs[y * self.n_cbs + x] | ||
| 293 | + } | ||
| 294 | + | ||
| 295 | + /// The coding-block side `nCbS` in luma samples. | ||
| 296 | + #[inline] | ||
| 297 | + #[must_use] | ||
| 298 | + pub fn n_cbs(&self) -> usize { | ||
| 299 | + self.n_cbs | ||
| 300 | + } | ||
| 301 | +} | ||
| 302 | + | ||
| 303 | +/// Whether the §8.7.2.4 "different reference pictures or different number | ||
| 304 | +/// of motion vectors" predicate holds between the p- and q-side blocks. | ||
| 305 | +/// | ||
| 306 | +/// The reference-picture comparison uses the picture identities | ||
| 307 | +/// (`ref_poc_lX`), not the `RefIdxLX` list positions, and is order- and | ||
| 308 | +/// list-independent (spec NOTE 1): block p uses reference-picture set | ||
| 309 | +/// `{ p.l0?, p.l1? }`, block q uses `{ q.l0?, q.l1? }`. | ||
| 310 | +fn different_refs_or_count(p: &crate::motion::MotionCell, q: &crate::motion::MotionCell) -> bool { | ||
| 311 | + let p_count = u8::from(p.pred_flag_l0) + u8::from(p.pred_flag_l1); | ||
| 312 | + let q_count = u8::from(q.pred_flag_l0) + u8::from(q.pred_flag_l1); | ||
| 313 | + if p_count != q_count { | ||
| 314 | + return true; | ||
| 315 | + } | ||
| 316 | + // Compare the *sets* of reference pictures (POCs), list-independent. | ||
| 317 | + let mut p_refs = Vec::new(); | ||
| 318 | + if p.pred_flag_l0 { | ||
| 319 | + p_refs.push(p.ref_poc_l0); | ||
| 320 | + } | ||
| 321 | + if p.pred_flag_l1 { | ||
| 322 | + p_refs.push(p.ref_poc_l1); | ||
| 323 | + } | ||
| 324 | + let mut q_refs = Vec::new(); | ||
| 325 | + if q.pred_flag_l0 { | ||
| 326 | + q_refs.push(q.ref_poc_l0); | ||
| 327 | + } | ||
| 328 | + if q.pred_flag_l1 { | ||
| 329 | + q_refs.push(q.ref_poc_l1); | ||
| 330 | + } | ||
| 331 | + p_refs.sort_unstable(); | ||
| 332 | + q_refs.sort_unstable(); | ||
| 333 | + p_refs != q_refs | ||
| 334 | +} | ||
| 335 | + | ||
| 336 | +/// `|a − b| >= 4` on either component (the §8.7.2.4 quarter-luma-sample | ||
| 337 | +/// MV-difference test). | ||
| 338 | +#[inline] | ||
| 339 | +fn mv_diff_ge4(a: [i32; 2], b: [i32; 2]) -> bool { | ||
| 340 | + (a[0] - b[0]).abs() >= 4 || (a[1] - b[1]).abs() >= 4 | ||
| 341 | +} | ||
| 342 | + | ||
| 343 | +/// §8.7.2.4 motion-only bS test for two inter prediction blocks `p` / `q` | ||
| 344 | +/// (the third bullet onward: same/different references, MV differences). | ||
| 345 | +/// Returns `true` when bS should be 1 on motion grounds. | ||
| 346 | +fn motion_bs_is_one(p: &crate::motion::MotionCell, q: &crate::motion::MotionCell) -> bool { | ||
| 347 | + // Bullet 1: different reference pictures or different number of MVs. | ||
| 348 | + if different_refs_or_count(p, q) { | ||
| 349 | + return true; | ||
| 350 | + } | ||
| 351 | + | ||
| 352 | + let p_count = u8::from(p.pred_flag_l0) + u8::from(p.pred_flag_l1); | ||
| 353 | + | ||
| 354 | + // Bullet 2: one MV each, |Δmv| >= 4. | ||
| 355 | + if p_count == 1 { | ||
| 356 | + let pmv = if p.pred_flag_l0 { p.mv_l0 } else { p.mv_l1 }; | ||
| 357 | + let qmv = if q.pred_flag_l0 { q.mv_l0 } else { q.mv_l1 }; | ||
| 358 | + return mv_diff_ge4(pmv, qmv); | ||
| 359 | + } | ||
| 360 | + | ||
| 361 | + // Two MVs each (p_count == 2). The reference-picture sets are equal | ||
| 362 | + // (different_refs_or_count returned false). | ||
| 363 | + if p.ref_poc_l0 != p.ref_poc_l1 { | ||
| 364 | + // Bullet 3: two different reference pictures. Match each list to | ||
| 365 | + // the q-side list referencing the same picture. | ||
| 366 | + // p.l0 ↔ q.(list with same poc as p.l0), p.l1 ↔ the other. | ||
| 367 | + let (q0, q1) = if q.ref_poc_l0 == p.ref_poc_l0 { | ||
| 368 | + (q.mv_l0, q.mv_l1) | ||
| 369 | + } else { | ||
| 370 | + (q.mv_l1, q.mv_l0) | ||
| 371 | + }; | ||
| 372 | + mv_diff_ge4(p.mv_l0, q0) || mv_diff_ge4(p.mv_l1, q1) | ||
| 373 | + } else { | ||
| 374 | + // Bullet 4: both MVs use the same reference picture. bS = 1 iff | ||
| 375 | + // (|Δl0| or |Δl1| >= 4) AND (|p.l0−q.l1| or |p.l1−q.l0| >= 4). | ||
| 376 | + let straight = mv_diff_ge4(p.mv_l0, q.mv_l0) || mv_diff_ge4(p.mv_l1, q.mv_l1); | ||
| 377 | + let crossed = mv_diff_ge4(p.mv_l0, q.mv_l1) || mv_diff_ge4(p.mv_l1, q.mv_l0); | ||
| 378 | + straight && crossed | ||
| 379 | + } | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +/// §8.7.2.4 — derive the `(nCbS)×(nCbS)` boundary filtering strength grid | ||
| 383 | +/// for one luma coding block. | ||
| 384 | +/// | ||
| 385 | +/// Inputs: | ||
| 386 | +/// * `field` — the picture's per-4×4-block motion / mode store | ||
| 387 | +/// ([`MotionField`]); the p / q sample look-ups read from it. | ||
| 388 | +/// * `(x_cb, y_cb)` — the coding block's luma top-left position. | ||
| 389 | +/// * `log2_cb_size` — the coding-block side `log2CbSize`. | ||
| 390 | +/// * `edge_type` — `EDGE_VER` or `EDGE_HOR`. | ||
| 391 | +/// * `edge_flags` — the §8.7.2.2/§8.7.2.3 `(nCbS)×(nCbS)` edge-flag grid | ||
| 392 | +/// (row-major, `edge_flags[y * nCbS + x]`), `true` where a transform / | ||
| 393 | +/// prediction block boundary falls. | ||
| 394 | +/// * `tb_edge` — `(nCbS)×(nCbS)` grid, `true` where the edge at that | ||
| 395 | +/// position is *also* a transform-block edge (the §8.7.2.4 second | ||
| 396 | +/// bullet `cbf` test only fires on transform-block edges). | ||
| 397 | +/// | ||
| 398 | +/// The bS at every sampled `(xDi, yDj)` is 2 when either neighbouring | ||
| 399 | +/// sample is intra; 1 when the edge is a transform-block edge and either | ||
| 400 | +/// transform block holds a non-zero coefficient; 1 on the §8.7.2.4 | ||
| 401 | +/// motion criteria; otherwise 0. Positions not sampled by §8.7.2.4 are 0. | ||
| 402 | +/// | ||
| 403 | +/// # Panics | ||
| 404 | +/// Panics if `edge_flags` / `tb_edge` are not `(1 << log2_cb_size)`² | ||
| 405 | +/// long, or if a sampled p / q location falls outside `field`. | ||
| 406 | +pub fn derive_boundary_strength( | ||
| 407 | + field: &MotionField, | ||
| 408 | + x_cb: usize, | ||
| 409 | + y_cb: usize, | ||
| 410 | + log2_cb_size: u32, | ||
| 411 | + edge_type: EdgeType, | ||
| 412 | + edge_flags: &[bool], | ||
| 413 | + tb_edge: &[bool], | ||
| 414 | +) -> BoundaryStrength { | ||
| 415 | + let n_cbs = 1usize << log2_cb_size; | ||
| 416 | + assert_eq!(edge_flags.len(), n_cbs * n_cbs, "edge_flags is nCbS^2"); | ||
| 417 | + assert_eq!(tb_edge.len(), n_cbs * n_cbs, "tb_edge is nCbS^2"); | ||
| 418 | + let mut bs = vec![0u8; n_cbs * n_cbs]; | ||
| 419 | + | ||
| 420 | + // §8.7.2.4 sampling grid: EDGE_VER strides 8 in x, 4 in y; EDGE_HOR | ||
| 421 | + // strides 4 in x, 8 in y. | ||
| 422 | + let (step_x, step_y) = match edge_type { | ||
| 423 | + EdgeType::Vertical => (8usize, 4usize), | ||
| 424 | + EdgeType::Horizontal => (4usize, 8usize), | ||
| 425 | + }; | ||
| 426 | + | ||
| 427 | + let mut y_dj = 0; | ||
| 428 | + while y_dj < n_cbs { | ||
| 429 | + let mut x_di = 0; | ||
| 430 | + while x_di < n_cbs { | ||
| 431 | + let idx = y_dj * n_cbs + x_di; | ||
| 432 | + if edge_flags[idx] { | ||
| 433 | + // p0 / q0 sample positions (§8.7.2.4). | ||
| 434 | + let (px, py, qx, qy) = match edge_type { | ||
| 435 | + EdgeType::Vertical => (x_cb + x_di - 1, y_cb + y_dj, x_cb + x_di, y_cb + y_dj), | ||
| 436 | + EdgeType::Horizontal => { | ||
| 437 | + (x_cb + x_di, y_cb + y_dj - 1, x_cb + x_di, y_cb + y_dj) | ||
| 438 | + } | ||
| 439 | + }; | ||
| 440 | + let p = field.cell_at(px, py); | ||
| 441 | + let q = field.cell_at(qx, qy); | ||
| 442 | + | ||
| 443 | + // §8.7.2.4 cascade: intra ⇒ 2; else a coded-coeff | ||
| 444 | + // transform-block edge OR the motion criteria ⇒ 1; else 0. | ||
| 445 | + let coeff_edge = tb_edge[idx] && (p.has_nonzero_coeff || q.has_nonzero_coeff); | ||
| 446 | + let val = if p.is_intra || q.is_intra { | ||
| 447 | + 2 | ||
| 448 | + } else if coeff_edge || motion_bs_is_one(&p, &q) { | ||
| 449 | + 1 | ||
| 450 | + } else { | ||
| 451 | + 0 | ||
| 452 | + }; | ||
| 453 | + bs[idx] = val; | ||
| 454 | + } | ||
| 455 | + x_di += step_x; | ||
| 456 | + } | ||
| 457 | + y_dj += step_y; | ||
| 458 | + } | ||
| 459 | + | ||
| 460 | + BoundaryStrength { n_cbs, bs } | ||
| 461 | +} | ||
| 462 | + | ||
| 463 | +/// Table 8-12 — `β′` as a function of the input variable `Q` (0..=51). | ||
| 464 | +/// | ||
| 465 | +/// The deblocking threshold `β′` is 0 for `Q < 16`, then rises in the | ||
| 466 | +/// pattern documented in Table 8-12. `Q` outside `0..=51` returns the | ||
| 467 | +/// boundary value (the callers clip `Q` to `0..=51` for `β′`, eq. 8-348). | ||
| 468 | +#[must_use] | ||
| 469 | +pub fn beta_prime(q: i32) -> i32 { | ||
| 470 | + const BETA: [i32; 52] = [ | ||
| 471 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Q 0..15 | ||
| 472 | + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, // Q 16..31 | ||
| 473 | + 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, // Q 32..47 | ||
| 474 | + 58, 60, 62, 64, // Q 48..51 | ||
| 475 | + ]; | ||
| 476 | + BETA[q.clamp(0, 51) as usize] | ||
| 477 | +} | ||
| 478 | + | ||
| 479 | +/// Table 8-12 — `tC′` as a function of the input variable `Q` (0..=53). | ||
| 480 | +/// | ||
| 481 | +/// The clipping threshold `tC′` is 0 for `Q <= 17`, `1` at `Q = 18`, | ||
| 482 | +/// then rises per Table 8-12 up to `24` at `Q = 53`. `Q` outside | ||
| 483 | +/// `0..=53` returns the boundary value (callers clip `Q` to `0..=53`, | ||
| 484 | +/// eqs. 8-350 / 8-383). | ||
| 485 | +#[must_use] | ||
| 486 | +pub fn tc_prime(q: i32) -> i32 { | ||
| 487 | + const TC: [i32; 54] = [ | ||
| 488 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, // Q 0..18 | ||
| 489 | + 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, // Q 19..37 | ||
| 490 | + 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, // Q 38..53 | ||
| 491 | + ]; | ||
| 492 | + TC[q.clamp(0, 53) as usize] | ||
| 493 | +} | ||
| 494 | + | ||
| 495 | +/// §8.7.2.5.3 — derive `β` and `tC` for a luma block edge. | ||
| 496 | +/// | ||
| 497 | +/// `qp_q` / `qp_p` are the `QpY` values of the coding units containing | ||
| 498 | +/// the `q0,0` and `p0,0` samples; `bs` is the §8.7.2.4 boundary strength | ||
| 499 | +/// (must be 1 or 2 for a filtered edge); `beta_offset_div2` / | ||
| 500 | +/// `tc_offset_div2` are the per-slice `slice_beta_offset_div2` / | ||
| 501 | +/// `slice_tc_offset_div2` syntax-element values; `bit_depth` is | ||
| 502 | +/// `BitDepthY`. | ||
| 503 | +/// | ||
| 504 | +/// Returns `(β, tC)` per eqs. 8-347..8-351. | ||
| 505 | +#[must_use] | ||
| 506 | +pub fn luma_beta_tc( | ||
| 507 | + qp_q: i32, | ||
| 508 | + qp_p: i32, | ||
| 509 | + bs: u8, | ||
| 510 | + beta_offset_div2: i32, | ||
| 511 | + tc_offset_div2: i32, | ||
| 512 | + bit_depth: u8, | ||
| 513 | +) -> (i32, i32) { | ||
| 514 | + let qp_l = (qp_q + qp_p + 1) >> 1; // eq. 8-347 | ||
| 515 | + let q_beta = (qp_l + (beta_offset_div2 << 1)).clamp(0, 51); // eq. 8-348 | ||
| 516 | + let beta = beta_prime(q_beta) * (1 << (i32::from(bit_depth) - 8)); // eq. 8-349 | ||
| 517 | + let q_tc = (qp_l + 2 * (i32::from(bs) - 1) + (tc_offset_div2 << 1)).clamp(0, 53); // eq. 8-350 | ||
| 518 | + let tc = tc_prime(q_tc) * (1 << (i32::from(bit_depth) - 8)); // eq. 8-351 | ||
| 519 | + (beta, tc) | ||
| 520 | +} | ||
| 521 | + | ||
| 522 | +/// §8.7.2.5.6 — decision process for a luma sample. | ||
| 523 | +/// | ||
| 524 | +/// Returns `dSam`: `true` (1) when the long (strong) filter conditions | ||
| 525 | +/// across `p0`/`p3`/`q0`/`q3` hold, given `dpq`, `β` and `tC`. | ||
| 526 | +#[inline] | ||
| 527 | +#[must_use] | ||
| 528 | +pub fn luma_sample_decision( | ||
| 529 | + p0: i32, | ||
| 530 | + p3: i32, | ||
| 531 | + q0: i32, | ||
| 532 | + q3: i32, | ||
| 533 | + dpq: i32, | ||
| 534 | + beta: i32, | ||
| 535 | + tc: i32, | ||
| 536 | +) -> bool { | ||
| 537 | + dpq < (beta >> 2) | ||
| 538 | + && (p3 - p0).abs() + (q0 - q3).abs() < (beta >> 3) | ||
| 539 | + && (p0 - q0).abs() < (5 * tc + 1) >> 1 | ||
| 540 | +} | ||
| 541 | + | ||
| 542 | +/// Decisions emitted by the §8.7.2.5.3 luma edge decision process for a | ||
| 543 | +/// 4-row edge segment. | ||
| 544 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 545 | +pub struct LumaEdgeDecision { | ||
| 546 | + /// `dE`: 0 = no filtering, 1 = weak (normal), 2 = strong (long). | ||
| 547 | + pub de: u8, | ||
| 548 | + /// `dEp`: when 1, the `p1` sample is also filtered (weak filter). | ||
| 549 | + pub dep: u8, | ||
| 550 | + /// `dEq`: when 1, the `q1` sample is also filtered (weak filter). | ||
| 551 | + pub deq: u8, | ||
| 552 | + /// `β` (eq. 8-349). | ||
| 553 | + pub beta: i32, | ||
| 554 | + /// `tC` (eq. 8-351). | ||
| 555 | + pub tc: i32, | ||
| 556 | +} | ||
| 557 | + | ||
| 558 | +/// The result of §8.7.2.5.7 luma-sample filtering for one boundary row. | ||
| 559 | +/// | ||
| 560 | +/// `p[i]` / `q[i]` are the filtered sample values (`pi'` / `qj'`); only | ||
| 561 | +/// the first `ndp` `p[]` and `ndq` `q[]` entries are valid replacements | ||
| 562 | +/// for the input samples. | ||
| 563 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 564 | +pub struct LumaFilterOut { | ||
| 565 | + /// `nDp` — number of filtered samples on the p side (0..=3). | ||
| 566 | + pub ndp: usize, | ||
| 567 | + /// `nDq` — number of filtered samples on the q side (0..=3). | ||
| 568 | + pub ndq: usize, | ||
| 569 | + /// `p0'`, `p1'`, `p2'` (only `0..ndp` valid). | ||
| 570 | + pub p: [i32; 3], | ||
| 571 | + /// `q0'`, `q1'`, `q2'` (only `0..ndq` valid). | ||
| 572 | + pub q: [i32; 3], | ||
| 573 | +} | ||
| 574 | + | ||
| 575 | +/// §8.7.2.5.7 — filtering process for a luma sample row. | ||
| 576 | +/// | ||
| 577 | +/// `p` / `q` are the four samples each side of the boundary (`p[0]` is | ||
| 578 | +/// `p0`, closest to the edge); `dec` carries `dE` / `dEp` / `dEq` and | ||
| 579 | +/// `tC`; `bit_depth` is `BitDepthY` for the final `Clip1Y`. | ||
| 580 | +/// | ||
| 581 | +/// Strong filtering (`dE == 2`) writes `p0'..p2'` / `q0'..q2'`; weak | ||
| 582 | +/// filtering (`dE == 1`) writes `p0'` (+`p1'` when `dEp`) and `q0'` | ||
| 583 | +/// (+`q1'` when `dEq`). The PCM / transquant-bypass / palette | ||
| 584 | +/// suppressions are applied by the caller (they need per-CU state). | ||
| 585 | +#[must_use] | ||
| 586 | +pub fn filter_luma_sample( | ||
| 587 | + p: [i32; 4], | ||
| 588 | + q: [i32; 4], | ||
| 589 | + de: u8, | ||
| 590 | + dep: u8, | ||
| 591 | + deq: u8, | ||
| 592 | + tc: i32, | ||
| 593 | + bit_depth: u8, | ||
| 594 | +) -> LumaFilterOut { | ||
| 595 | + let [p0, p1, p2, p3] = p; | ||
| 596 | + let [q0, q1, q2, q3] = q; | ||
| 597 | + let clip = |v: i32| crate::picture::clip1(v, bit_depth); | ||
| 598 | + if de == 2 { | ||
| 599 | + // Strong filter (eqs. 8-389..8-394). | ||
| 600 | + let p0p = | ||
| 601 | + (p0 - 2 * tc).max((p0 + 2 * tc).min((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3)); | ||
| 602 | + let p1p = (p1 - 2 * tc).max((p1 + 2 * tc).min((p2 + p1 + p0 + q0 + 2) >> 2)); | ||
| 603 | + let p2p = (p2 - 2 * tc).max((p2 + 2 * tc).min((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3)); | ||
| 604 | + let q0p = | ||
| 605 | + (q0 - 2 * tc).max((q0 + 2 * tc).min((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3)); | ||
| 606 | + let q1p = (q1 - 2 * tc).max((q1 + 2 * tc).min((p0 + q0 + q1 + q2 + 2) >> 2)); | ||
| 607 | + let q2p = (q2 - 2 * tc).max((q2 + 2 * tc).min((p0 + q0 + q1 + 3 * q2 + 2 * q3 + 4) >> 3)); | ||
| 608 | + return LumaFilterOut { | ||
| 609 | + ndp: 3, | ||
| 610 | + ndq: 3, | ||
| 611 | + p: [p0p, p1p, p2p], | ||
| 612 | + q: [q0p, q1p, q2p], | ||
| 613 | + }; | ||
| 614 | + } | ||
| 615 | + // Weak filter (eqs. 8-395..8-402). | ||
| 616 | + let mut out = LumaFilterOut { | ||
| 617 | + ndp: 0, | ||
| 618 | + ndq: 0, | ||
| 619 | + p: [p0, p1, p2], | ||
| 620 | + q: [q0, q1, q2], | ||
| 621 | + }; | ||
| 622 | + let delta = (9 * (q0 - p0) - 3 * (q1 - p1) + 8) >> 4; // eq. 8-395 | ||
| 623 | + if delta.abs() < tc * 10 { | ||
| 624 | + let delta = delta.clamp(-tc, tc); // eq. 8-396 | ||
| 625 | + out.p[0] = clip(p0 + delta); // eq. 8-397 | ||
| 626 | + out.q[0] = clip(q0 - delta); // eq. 8-398 | ||
| 627 | + if dep == 1 { | ||
| 628 | + let dp = ((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1).clamp(-(tc >> 1), tc >> 1); // eq. 8-399 | ||
| 629 | + out.p[1] = clip(p1 + dp); // eq. 8-400 | ||
| 630 | + } | ||
| 631 | + if deq == 1 { | ||
| 632 | + let dq = ((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1).clamp(-(tc >> 1), tc >> 1); // eq. 8-401 | ||
| 633 | + out.q[1] = clip(q1 + dq); // eq. 8-402 | ||
| 634 | + } | ||
| 635 | + out.ndp = (dep + 1) as usize; // eq. 8-403 (nDp = dEp + 1) | ||
| 636 | + out.ndq = (deq + 1) as usize; // (nDq = dEq + 1) | ||
| 637 | + } | ||
| 638 | + out | ||
| 639 | +} | ||
| 640 | + | ||
| 641 | +/// §8.7.2.5.3 — decision process for a luma block edge. | ||
| 642 | +/// | ||
| 643 | +/// `p` / `q` are the `(i=0..3) × (k=0,3)` sample grids on each side of | ||
| 644 | +/// the edge, laid out as `p[i][k_idx]` where `k_idx` selects row 0 or | ||
| 645 | +/// row 3 of the edge segment (`p[i][0]` = `pi,0`, `p[i][1]` = `pi,3`). | ||
| 646 | +/// `beta` / `tc` come from [`luma_beta_tc`]. Returns the | ||
| 647 | +/// [`LumaEdgeDecision`] (`dE`, `dEp`, `dEq`) that drives §8.7.2.5.4. | ||
| 648 | +/// | ||
| 649 | +/// The result's `beta` / `tc` fields echo the inputs so a caller can | ||
| 650 | +/// pass the whole decision straight into [`filter_luma_sample`]. | ||
| 651 | +#[must_use] | ||
| 652 | +pub fn luma_edge_decision( | ||
| 653 | + p: [[i32; 2]; 4], | ||
| 654 | + q: [[i32; 2]; 4], | ||
| 655 | + beta: i32, | ||
| 656 | + tc: i32, | ||
| 657 | +) -> LumaEdgeDecision { | ||
| 658 | + // Row 0 (k_idx 0) and row 3 (k_idx 1) second differences (eqs. | ||
| 659 | + // 8-352..8-360 for EDGE_VER, identical form 8-361..8-369 for HOR). | ||
| 660 | + let dp0 = (p[2][0] - 2 * p[1][0] + p[0][0]).abs(); // eq. 8-352 | ||
| 661 | + let dp3 = (p[2][1] - 2 * p[1][1] + p[0][1]).abs(); // eq. 8-353 | ||
| 662 | + let dq0 = (q[2][0] - 2 * q[1][0] + q[0][0]).abs(); // eq. 8-354 | ||
| 663 | + let dq3 = (q[2][1] - 2 * q[1][1] + q[0][1]).abs(); // eq. 8-355 | ||
| 664 | + let dpq0 = dp0 + dq0; // eq. 8-356 | ||
| 665 | + let dpq3 = dp3 + dq3; // eq. 8-357 | ||
| 666 | + let dp = dp0 + dp3; // eq. 8-358 | ||
| 667 | + let dq = dq0 + dq3; // eq. 8-359 | ||
| 668 | + let d = dpq0 + dpq3; // eq. 8-360 | ||
| 669 | + | ||
| 670 | + let mut dec = LumaEdgeDecision { | ||
| 671 | + de: 0, | ||
| 672 | + dep: 0, | ||
| 673 | + deq: 0, | ||
| 674 | + beta, | ||
| 675 | + tc, | ||
| 676 | + }; | ||
| 677 | + if d < beta { | ||
| 678 | + // Strong/weak split (eqs. 8-360 step 3). | ||
| 679 | + let dsam0 = luma_sample_decision(p[0][0], p[3][0], q[0][0], q[3][0], 2 * dpq0, beta, tc); | ||
| 680 | + let dsam3 = luma_sample_decision(p[0][1], p[3][1], q[0][1], q[3][1], 2 * dpq3, beta, tc); | ||
| 681 | + dec.de = if dsam0 && dsam3 { 2 } else { 1 }; | ||
| 682 | + let thr = (beta + (beta >> 1)) >> 3; | ||
| 683 | + if dp < thr { | ||
| 684 | + dec.dep = 1; // eq. step g | ||
| 685 | + } | ||
| 686 | + if dq < thr { | ||
| 687 | + dec.deq = 1; // eq. step h | ||
| 688 | + } | ||
| 689 | + } | ||
| 690 | + dec | ||
| 691 | +} | ||
| 692 | + | ||
| 693 | +/// Table 8-10 — `ChromaArrayType == 1` chroma-QP mapping `QpC = f(qPi)`. | ||
| 694 | +/// | ||
| 695 | +/// The piecewise mapping is identity below `qPi == 30`, a flat-ish run | ||
| 696 | +/// `29..37` across `qPi 30..43`, then `qPi − 6` for `qPi >= 44`. | ||
| 697 | +#[must_use] | ||
| 698 | +pub fn chroma_qpc_420(qpi: i32) -> i32 { | ||
| 699 | + match qpi { | ||
| 700 | + x if x < 30 => x, | ||
| 701 | + 30 => 29, | ||
| 702 | + 31 => 30, | ||
| 703 | + 32 => 31, | ||
| 704 | + 33 => 32, | ||
| 705 | + 34 => 33, | ||
| 706 | + 35 => 33, | ||
| 707 | + 36 => 34, | ||
| 708 | + 37 => 34, | ||
| 709 | + 38 => 35, | ||
| 710 | + 39 => 35, | ||
| 711 | + 40 => 36, | ||
| 712 | + 41 => 36, | ||
| 713 | + 42 => 37, | ||
| 714 | + 43 => 37, | ||
| 715 | + x => x - 6, | ||
| 716 | + } | ||
| 717 | +} | ||
| 718 | + | ||
| 719 | +/// §8.7.2.5.5 — derive `tC` for a chroma block edge. | ||
| 720 | +/// | ||
| 721 | +/// `qp_q` / `qp_p` are the luma `QpY` values of the CUs containing the | ||
| 722 | +/// `q0,0` / `p0,0` chroma samples; `c_qp_pic_offset` is the picture-level | ||
| 723 | +/// `pps_cb_qp_offset` / `pps_cr_qp_offset` for the filtered component; | ||
| 724 | +/// `chroma_array_type` selects Table 8-10 (`== 1`) vs `Min(qPi, 51)`; | ||
| 725 | +/// `tc_offset_div2` is `slice_tc_offset_div2`; `bit_depth` is | ||
| 726 | +/// `BitDepthC`. | ||
| 727 | +/// | ||
| 728 | +/// Returns `tC` per eqs. 8-382..8-384. | ||
| 729 | +#[must_use] | ||
| 730 | +pub fn chroma_tc( | ||
| 731 | + qp_q: i32, | ||
| 732 | + qp_p: i32, | ||
| 733 | + c_qp_pic_offset: i32, | ||
| 734 | + chroma_array_type: u8, | ||
| 735 | + tc_offset_div2: i32, | ||
| 736 | + bit_depth: u8, | ||
| 737 | +) -> i32 { | ||
| 738 | + let qpi = ((qp_q + qp_p + 1) >> 1) + c_qp_pic_offset; // eq. 8-382 | ||
| 739 | + let qp_c = if chroma_array_type == 1 { | ||
| 740 | + chroma_qpc_420(qpi) | ||
| 741 | + } else { | ||
| 742 | + qpi.min(51) | ||
| 743 | + }; | ||
| 744 | + let q = (qp_c + 2 + (tc_offset_div2 << 1)).clamp(0, 53); // eq. 8-383 | ||
| 745 | + tc_prime(q) * (1 << (i32::from(bit_depth) - 8)) // eq. 8-384 | ||
| 746 | +} | ||
| 747 | + | ||
| 748 | +/// §8.7.2.5.8 — filtering process for a chroma sample. | ||
| 749 | +/// | ||
| 750 | +/// `p` / `q` are the two samples each side of the boundary (`p[0]` is | ||
| 751 | +/// `p0`, closest to the edge); `tc` is from [`chroma_tc`]; `bit_depth` | ||
| 752 | +/// is `BitDepthC` for the final `Clip1C`. Returns `(p0', q0')`. The | ||
| 753 | +/// PCM / transquant-bypass / palette suppressions (which restore the | ||
| 754 | +/// input sample) are applied by the caller. | ||
| 755 | +#[inline] | ||
| 756 | +#[must_use] | ||
| 757 | +pub fn filter_chroma_sample(p: [i32; 2], q: [i32; 2], tc: i32, bit_depth: u8) -> (i32, i32) { | ||
| 758 | + let [p0, p1] = p; | ||
| 759 | + let [q0, q1] = q; | ||
| 760 | + let delta = (((q0 - p0) << 2) + p1 - q1 + 4) >> 3; // eq. 8-403 | ||
| 761 | + let delta = delta.clamp(-tc, tc); | ||
| 762 | + let p0p = crate::picture::clip1(p0 + delta, bit_depth); // eq. 8-404 | ||
| 763 | + let q0p = crate::picture::clip1(q0 - delta, bit_depth); // eq. 8-405 | ||
| 764 | + (p0p, q0p) | ||
| 765 | +} | ||
| 766 | + | ||
| 767 | +/// A mutable sample plane: row-major `samples[y * stride + x]`. | ||
| 768 | +/// | ||
| 769 | +/// The §8.7.2.5.4 / .5 block-edge filtering processes read and write | ||
| 770 | +/// this plane in place. Callers wrap their reconstructed luma / chroma | ||
| 771 | +/// component buffer (as `i32` samples) in a [`SamplePlane`]. | ||
| 772 | +pub struct SamplePlane<'a> { | ||
| 773 | + /// Row-major sample storage, `width * height` long. | ||
| 774 | + pub samples: &'a mut [i32], | ||
| 775 | + /// Plane width in samples. | ||
| 776 | + pub width: usize, | ||
| 777 | + /// Row stride in samples (usually equal to `width`). | ||
| 778 | + pub stride: usize, | ||
| 779 | +} | ||
| 780 | + | ||
| 781 | +impl core::fmt::Debug for SamplePlane<'_> { | ||
| 782 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| 783 | + f.debug_struct("SamplePlane") | ||
| 784 | + .field("len", &self.samples.len()) | ||
| 785 | + .field("width", &self.width) | ||
| 786 | + .field("stride", &self.stride) | ||
| 787 | + .finish() | ||
| 788 | + } | ||
| 789 | +} | ||
| 790 | + | ||
| 791 | +impl SamplePlane<'_> { | ||
| 792 | + #[inline] | ||
| 793 | + fn get(&self, x: usize, y: usize) -> i32 { | ||
| 794 | + self.samples[y * self.stride + x] | ||
| 795 | + } | ||
| 796 | + #[inline] | ||
| 797 | + fn set(&mut self, x: usize, y: usize, v: i32) { | ||
| 798 | + self.samples[y * self.stride + x] = v; | ||
| 799 | + } | ||
| 800 | + /// `(x, y)` plane coordinates for the `i`-th sample on the p (`pi`, | ||
| 801 | + /// negative side) or q (`qi`, positive side) of an edge at `(ex, ey)` | ||
| 802 | + /// for row offset `k` along the edge. | ||
| 803 | + #[inline] | ||
| 804 | + fn edge_xy( | ||
| 805 | + &self, | ||
| 806 | + ex: usize, | ||
| 807 | + ey: usize, | ||
| 808 | + edge: EdgeType, | ||
| 809 | + side_p: bool, | ||
| 810 | + i: usize, | ||
| 811 | + k: usize, | ||
| 812 | + ) -> (usize, usize) { | ||
| 813 | + match (edge, side_p) { | ||
| 814 | + // EDGE_VER: q at x = ex+i, p at x = ex-i-1; both at y = ey+k. | ||
| 815 | + (EdgeType::Vertical, false) => (ex + i, ey + k), | ||
| 816 | + (EdgeType::Vertical, true) => (ex - i - 1, ey + k), | ||
| 817 | + // EDGE_HOR: q at y = ey+i, p at y = ey-i-1; both at x = ex+k. | ||
| 818 | + (EdgeType::Horizontal, false) => (ex + k, ey + i), | ||
| 819 | + (EdgeType::Horizontal, true) => (ex + k, ey - i - 1), | ||
| 820 | + } | ||
| 821 | + } | ||
| 822 | +} | ||
| 823 | + | ||
| 824 | +/// The position + orientation of one 4-row deblocking edge segment. | ||
| 825 | +/// | ||
| 826 | +/// `(ex, ey)` is the plane location of `q0,0`: for `EDGE_VER` the column | ||
| 827 | +/// `ex` is the first q-side column; for `EDGE_HOR` the row `ey` is the | ||
| 828 | +/// first q-side row. | ||
| 829 | +#[derive(Debug, Clone, Copy)] | ||
| 830 | +pub struct EdgePos { | ||
| 831 | + /// `q0,0` x location in the plane. | ||
| 832 | + pub ex: usize, | ||
| 833 | + /// `q0,0` y location in the plane. | ||
| 834 | + pub ey: usize, | ||
| 835 | + /// Edge orientation (`EDGE_VER` / `EDGE_HOR`). | ||
| 836 | + pub edge: EdgeType, | ||
| 837 | +} | ||
| 838 | + | ||
| 839 | +/// The §8.7.2.5.3 / .5 QP + offset context for one block edge. | ||
| 840 | +/// | ||
| 841 | +/// `qp_q` / `qp_p` are the `QpY` values of the CUs containing `q0,0` / | ||
| 842 | +/// `p0,0`; the `*_div2` fields are the per-slice | ||
| 843 | +/// `slice_beta_offset_div2` / `slice_tc_offset_div2`; `bit_depth` is | ||
| 844 | +/// `BitDepthY` (luma) or `BitDepthC` (chroma). | ||
| 845 | +#[derive(Debug, Clone, Copy)] | ||
| 846 | +pub struct EdgeQp { | ||
| 847 | + /// `QpY` of the q-side CU. | ||
| 848 | + pub qp_q: i32, | ||
| 849 | + /// `QpY` of the p-side CU. | ||
| 850 | + pub qp_p: i32, | ||
| 851 | + /// `slice_beta_offset_div2` (luma only; ignored for chroma). | ||
| 852 | + pub beta_offset_div2: i32, | ||
| 853 | + /// `slice_tc_offset_div2`. | ||
| 854 | + pub tc_offset_div2: i32, | ||
| 855 | + /// `BitDepthY` (luma) or `BitDepthC` (chroma). | ||
| 856 | + pub bit_depth: u8, | ||
| 857 | +} | ||
| 858 | + | ||
| 859 | +/// §8.7.2.5.4 — filtering process for a luma block edge. | ||
| 860 | +/// | ||
| 861 | +/// Filters the 4-row edge segment positioned by `pos` (the `q0,0` | ||
| 862 | +/// boundary location). `bs` (1 or 2) and the [`EdgeQp`] context drive | ||
| 863 | +/// [`luma_beta_tc`] / [`luma_edge_decision`] / [`filter_luma_sample`]. | ||
| 864 | +/// | ||
| 865 | +/// Returns the [`LumaEdgeDecision`] that was applied (for inspection / | ||
| 866 | +/// trace); the plane is modified in place. A `bs == 0` edge is a no-op. | ||
| 867 | +/// | ||
| 868 | +/// # Panics | ||
| 869 | +/// Panics if the edge segment reads/writes outside the plane. | ||
| 870 | +pub fn filter_luma_block_edge( | ||
| 871 | + plane: &mut SamplePlane<'_>, | ||
| 872 | + pos: EdgePos, | ||
| 873 | + bs: u8, | ||
| 874 | + qp: EdgeQp, | ||
| 875 | +) -> LumaEdgeDecision { | ||
| 876 | + filter_luma_block_edge_gated(plane, pos, bs, qp, None) | ||
| 877 | +} | ||
| 878 | + | ||
| 879 | +/// [`filter_luma_block_edge`] with the per-CU loop-filter suppression | ||
| 880 | +/// map: a p- / q-side sample whose cell is flagged is left unmodified | ||
| 881 | +/// (the §8.7.2.5.4 `nDp = 0` / `nDq = 0` rule for PCM / | ||
| 882 | +/// transquant-bypass / palette coding units); the filter decision | ||
| 883 | +/// itself still reads both sides. | ||
| 884 | +pub fn filter_luma_block_edge_gated( | ||
| 885 | + plane: &mut SamplePlane<'_>, | ||
| 886 | + pos: EdgePos, | ||
| 887 | + bs: u8, | ||
| 888 | + qp: EdgeQp, | ||
| 889 | + no_filter: Option<&NoFilterMap<'_>>, | ||
| 890 | +) -> LumaEdgeDecision { | ||
| 891 | + let EdgePos { ex, ey, edge } = pos; | ||
| 892 | + let zero = LumaEdgeDecision { | ||
| 893 | + de: 0, | ||
| 894 | + dep: 0, | ||
| 895 | + deq: 0, | ||
| 896 | + beta: 0, | ||
| 897 | + tc: 0, | ||
| 898 | + }; | ||
| 899 | + if bs == 0 { | ||
| 900 | + return zero; | ||
| 901 | + } | ||
| 902 | + let (beta, tc) = luma_beta_tc( | ||
| 903 | + qp.qp_q, | ||
| 904 | + qp.qp_p, | ||
| 905 | + bs, | ||
| 906 | + qp.beta_offset_div2, | ||
| 907 | + qp.tc_offset_div2, | ||
| 908 | + qp.bit_depth, | ||
| 909 | + ); | ||
| 910 | + let bit_depth = qp.bit_depth; | ||
| 911 | + // Gather the decision grid: rows k=0 and k=3, samples i=0..3 each side. | ||
| 912 | + let mut pg = [[0i32; 2]; 4]; | ||
| 913 | + let mut qg = [[0i32; 2]; 4]; | ||
| 914 | + for (k_idx, &k) in [0usize, 3].iter().enumerate() { | ||
| 915 | + for i in 0..4 { | ||
| 916 | + let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k); | ||
| 917 | + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k); | ||
| 918 | + pg[i][k_idx] = plane.get(px, py); | ||
| 919 | + qg[i][k_idx] = plane.get(qx, qy); | ||
| 920 | + } | ||
| 921 | + } | ||
| 922 | + let dec = luma_edge_decision(pg, qg, beta, tc); | ||
| 923 | + if dec.de == 0 { | ||
| 924 | + return dec; | ||
| 925 | + } | ||
| 926 | + // Apply the filter to each of the 4 rows (eq. 8-372/8-373 layout). | ||
| 927 | + for k in 0..4 { | ||
| 928 | + let mut p = [0i32; 4]; | ||
| 929 | + let mut q = [0i32; 4]; | ||
| 930 | + for i in 0..4 { | ||
| 931 | + let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k); | ||
| 932 | + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k); | ||
| 933 | + p[i] = plane.get(px, py); | ||
| 934 | + q[i] = plane.get(qx, qy); | ||
| 935 | + } | ||
| 936 | + let out = filter_luma_sample(p, q, dec.de, dec.dep, dec.deq, tc, bit_depth); | ||
| 937 | + for i in 0..out.ndp { | ||
| 938 | + let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k); | ||
| 939 | + if no_filter.is_some_and(|m| m.at_luma(px, py)) { | ||
| 940 | + continue; // §8.7.2.5.4 nDp = 0 (PCM / bypass / palette) | ||
| 941 | + } | ||
| 942 | + plane.set(px, py, out.p[i]); | ||
| 943 | + } | ||
| 944 | + for j in 0..out.ndq { | ||
| 945 | + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, j, k); | ||
| 946 | + if no_filter.is_some_and(|m| m.at_luma(qx, qy)) { | ||
| 947 | + continue; // §8.7.2.5.4 nDq = 0 | ||
| 948 | + } | ||
| 949 | + plane.set(qx, qy, out.q[j]); | ||
| 950 | + } | ||
| 951 | + } | ||
| 952 | + dec | ||
| 953 | +} | ||
| 954 | + | ||
| 955 | +/// §8.7.2.5.5 — filtering process for a chroma block edge. | ||
| 956 | +/// | ||
| 957 | +/// Filters the 4-row chroma edge segment positioned by `pos` (the `q0,0` | ||
| 958 | +/// chroma location). The [`EdgeQp`] context carries the luma `QpY` | ||
| 959 | +/// values + `slice_tc_offset_div2` + `BitDepthC`; `c_qp_pic_offset` is | ||
| 960 | +/// the picture chroma offset; `chroma_array_type` selects Table 8-10 | ||
| 961 | +/// (`== 1`) vs `Min(qPi, 51)`. Only `p0`/`q0` are modified (eqs. | ||
| 962 | +/// 8-385..8-388). Returns the `tC` that was applied. | ||
| 963 | +/// | ||
| 964 | +/// # Panics | ||
| 965 | +/// Panics if the edge segment reads/writes outside the plane. | ||
| 966 | +pub fn filter_chroma_block_edge( | ||
| 967 | + plane: &mut SamplePlane<'_>, | ||
| 968 | + pos: EdgePos, | ||
| 969 | + qp: EdgeQp, | ||
| 970 | + c_qp_pic_offset: i32, | ||
| 971 | + chroma_array_type: u8, | ||
| 972 | +) -> i32 { | ||
| 973 | + filter_chroma_block_edge_gated(plane, pos, qp, c_qp_pic_offset, chroma_array_type, None) | ||
| 974 | +} | ||
| 975 | + | ||
| 976 | +/// [`filter_chroma_block_edge`] with the per-CU loop-filter | ||
| 977 | +/// suppression map (§8.7.2.5.5: the flagged side's `p0'` / `q0'` is | ||
| 978 | +/// not written). Chroma sample positions map onto the luma cell grid | ||
| 979 | +/// through the `SubWidthC` / `SubHeightC` factors of | ||
| 980 | +/// `chroma_array_type`. | ||
| 981 | +pub fn filter_chroma_block_edge_gated( | ||
| 982 | + plane: &mut SamplePlane<'_>, | ||
| 983 | + pos: EdgePos, | ||
| 984 | + qp: EdgeQp, | ||
| 985 | + c_qp_pic_offset: i32, | ||
| 986 | + chroma_array_type: u8, | ||
| 987 | + no_filter: Option<&NoFilterMap<'_>>, | ||
| 988 | +) -> i32 { | ||
| 989 | + let (sub_w, sub_h) = sub_wh_c(chroma_array_type); | ||
| 990 | + let EdgePos { ex, ey, edge } = pos; | ||
| 991 | + let bit_depth = qp.bit_depth; | ||
| 992 | + let tc = chroma_tc( | ||
| 993 | + qp.qp_q, | ||
| 994 | + qp.qp_p, | ||
| 995 | + c_qp_pic_offset, | ||
| 996 | + chroma_array_type, | ||
| 997 | + qp.tc_offset_div2, | ||
| 998 | + bit_depth, | ||
| 999 | + ); | ||
| 1000 | + for k in 0..4 { | ||
| 1001 | + let mut p = [0i32; 2]; | ||
| 1002 | + let mut q = [0i32; 2]; | ||
| 1003 | + for i in 0..2 { | ||
| 1004 | + let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k); | ||
| 1005 | + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k); | ||
| 1006 | + p[i] = plane.get(px, py); | ||
| 1007 | + q[i] = plane.get(qx, qy); | ||
| 1008 | + } | ||
| 1009 | + let (p0p, q0p) = filter_chroma_sample(p, q, tc, bit_depth); | ||
| 1010 | + let (px, py) = plane.edge_xy(ex, ey, edge, true, 0, k); | ||
| 1011 | + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, 0, k); | ||
| 1012 | + if !no_filter.is_some_and(|m| m.at_luma(px * sub_w, py * sub_h)) { | ||
| 1013 | + plane.set(px, py, p0p); | ||
| 1014 | + } | ||
| 1015 | + if !no_filter.is_some_and(|m| m.at_luma(qx * sub_w, qy * sub_h)) { | ||
| 1016 | + plane.set(qx, qy, q0p); | ||
| 1017 | + } | ||
| 1018 | + } | ||
| 1019 | + tc | ||
| 1020 | +} | ||
| 1021 | + | ||
| 1022 | +/// The §8.7.2.5.1 / .2 per-CU deblocking context: the QP + offset state a | ||
| 1023 | +/// coding unit contributes to its edge filtering. | ||
| 1024 | +/// | ||
| 1025 | +/// `qp_y` is the CU's `QpY`; the `*_offset_div2` are the per-slice | ||
| 1026 | +/// `slice_beta_offset_div2` / `slice_tc_offset_div2`; the `pps_c*_qp_offset` | ||
| 1027 | +/// are the picture chroma QP offsets; the bit depths are `BitDepthY` / | ||
| 1028 | +/// `BitDepthC`. The driver reads neighbour `QpY` from `qp_y_at` so a | ||
| 1029 | +/// boundary edge can use the p-side CU's `QpY` for `qP,p` (eq. 8-347). | ||
| 1030 | +#[derive(Debug, Clone, Copy)] | ||
| 1031 | +pub struct DeblockCuParams { | ||
| 1032 | + /// The CU's `QpY` (the q-side QP at every edge inside the CU). | ||
| 1033 | + pub qp_y: i32, | ||
| 1034 | + /// `slice_beta_offset_div2`. | ||
| 1035 | + pub beta_offset_div2: i32, | ||
| 1036 | + /// `slice_tc_offset_div2`. | ||
| 1037 | + pub tc_offset_div2: i32, | ||
| 1038 | + /// `pps_cb_qp_offset` for the Cb component — the §8.7.2.5.1/.2 | ||
| 1039 | + /// `cQpPicOffset` (slice-level and CU-level chroma QP adjustments | ||
| 1040 | + /// are excluded from chroma deblocking by the invocation text). | ||
| 1041 | + pub cb_qp_offset: i32, | ||
| 1042 | + /// `pps_cr_qp_offset` for the Cr component. | ||
| 1043 | + pub cr_qp_offset: i32, | ||
| 1044 | + /// `BitDepthY`. | ||
| 1045 | + pub bit_depth_luma: u8, | ||
| 1046 | + /// `BitDepthC`. | ||
| 1047 | + pub bit_depth_chroma: u8, | ||
| 1048 | + /// `ChromaArrayType` (selects Table 8-10 / `Min(qPi,51)` + subsampling). | ||
| 1049 | + pub chroma_array_type: u8, | ||
| 1050 | +} | ||
| 1051 | + | ||
| 1052 | +/// The geometry + QP context of one coding unit for the §8.7.2.5.1 / .2 | ||
| 1053 | +/// edge-filtering driver. | ||
| 1054 | +#[derive(Debug, Clone, Copy)] | ||
| 1055 | +pub struct DeblockCu { | ||
| 1056 | + /// The CU's luma top-left x. | ||
| 1057 | + pub x_cb: usize, | ||
| 1058 | + /// The CU's luma top-left y. | ||
| 1059 | + pub y_cb: usize, | ||
| 1060 | + /// `log2CbSize`. | ||
| 1061 | + pub log2_cb_size: u32, | ||
| 1062 | + /// The CU QP / offset / chroma context. | ||
| 1063 | + pub params: DeblockCuParams, | ||
| 1064 | + /// The left-neighbour CU's `QpY` at the vertical coding-block | ||
| 1065 | + /// boundary edge (xDk == 0); interior edges use `params.qp_y` on | ||
| 1066 | + /// both sides. | ||
| 1067 | + pub qp_y_p_left: i32, | ||
| 1068 | + /// The above-neighbour CU's `QpY` at the horizontal coding-block | ||
| 1069 | + /// boundary edge (yDm == 0). | ||
| 1070 | + pub qp_y_p_top: i32, | ||
| 1071 | +} | ||
| 1072 | + | ||
| 1073 | +/// §8.7.2.5.1 / .2 — filter all edges of one coding unit in one direction. | ||
| 1074 | +/// | ||
| 1075 | +/// Applies the §8.7.2.5.4 luma block-edge filter at every `bS > 0` sampled | ||
| 1076 | +/// position, then (when `ChromaArrayType != 0`) the §8.7.2.5.5 chroma | ||
| 1077 | +/// block-edge filter at every `bS == 2`, 8-luma-sample-aligned position. | ||
| 1078 | +/// The luma sampling grid is 8-stride along the edge axis and 4-stride | ||
| 1079 | +/// across; the chroma grid steps `8 / SubWidthC` (vertical) / | ||
| 1080 | +/// `8 / SubHeightC` (horizontal) in the edge axis. | ||
| 1081 | +/// | ||
| 1082 | +/// `cu` carries the CU's geometry + QP context; `bs` is the §8.7.2.4 grid | ||
| 1083 | +/// for `edge_type`. | ||
| 1084 | +/// | ||
| 1085 | +/// # Panics | ||
| 1086 | +/// Panics if a filtered edge segment reads/writes outside a plane. | ||
| 1087 | +pub fn filter_cu_edges( | ||
| 1088 | + pic: &mut Picture, | ||
| 1089 | + cu: &DeblockCu, | ||
| 1090 | + edge_type: EdgeType, | ||
| 1091 | + bs: &BoundaryStrength, | ||
| 1092 | +) { | ||
| 1093 | + filter_cu_edges_with_qp_map(pic, cu, edge_type, bs, None); | ||
| 1094 | +} | ||
| 1095 | + | ||
| 1096 | +/// [`filter_cu_edges`] with the per-position [`QpMap`] (exact `QpQ` / | ||
| 1097 | +/// `QpP` when quantization groups vary inside / around the CU). | ||
| 1098 | +pub fn filter_cu_edges_with_qp_map( | ||
| 1099 | + pic: &mut Picture, | ||
| 1100 | + cu: &DeblockCu, | ||
| 1101 | + edge_type: EdgeType, | ||
| 1102 | + bs: &BoundaryStrength, | ||
| 1103 | + qp_map: Option<QpMap<'_>>, | ||
| 1104 | +) { | ||
| 1105 | + filter_cu_edges_full(pic, cu, edge_type, bs, qp_map, None); | ||
| 1106 | +} | ||
| 1107 | + | ||
| 1108 | +/// [`filter_cu_edges_with_qp_map`] with the per-CU loop-filter | ||
| 1109 | +/// suppression map (§8.7.2.5.4 / §8.7.2.5.5 `nDp` / `nDq` zeroing). | ||
| 1110 | +pub fn filter_cu_edges_full( | ||
| 1111 | + pic: &mut Picture, | ||
| 1112 | + cu: &DeblockCu, | ||
| 1113 | + edge_type: EdgeType, | ||
| 1114 | + bs: &BoundaryStrength, | ||
| 1115 | + qp_map: Option<QpMap<'_>>, | ||
| 1116 | + no_filter: Option<&NoFilterMap<'_>>, | ||
| 1117 | +) { | ||
| 1118 | + let DeblockCu { | ||
| 1119 | + x_cb, | ||
| 1120 | + y_cb, | ||
| 1121 | + log2_cb_size, | ||
| 1122 | + params, | ||
| 1123 | + qp_y_p_left, | ||
| 1124 | + qp_y_p_top, | ||
| 1125 | + } = *cu; | ||
| 1126 | + let n_d = 1usize << (log2_cb_size - 3); | ||
| 1127 | + let (sub_w, sub_h) = sub_wh_c(params.chroma_array_type); | ||
| 1128 | + | ||
| 1129 | + // ----- luma (§8.7.2.5.1 step 2 / §8.7.2.5.2 step 2) ----- | ||
| 1130 | + // EDGE_VER: xDk = k<<3 (k=0..nD-1), yDm = m<<2 (m=0..2nD-1). | ||
| 1131 | + // EDGE_HOR: yDm = m<<3 (m=0..nD-1), xDk = k<<2 (k=0..2nD-1). | ||
| 1132 | + // `edges` indexes the 8-strided axis (nD); `segs` the 4-strided axis. | ||
| 1133 | + let (n_edges, n_segs) = (n_d, n_d * 2); | ||
| 1134 | + for e in 0..n_edges { | ||
| 1135 | + for s_idx in 0..n_segs { | ||
| 1136 | + let (x_dk, y_dm) = match edge_type { | ||
| 1137 | + EdgeType::Vertical => (e << 3, s_idx << 2), | ||
| 1138 | + EdgeType::Horizontal => (s_idx << 2, e << 3), | ||
| 1139 | + }; | ||
| 1140 | + let s = bs.at(x_dk, y_dm); | ||
| 1141 | + if s == 0 { | ||
| 1142 | + continue; | ||
| 1143 | + } | ||
| 1144 | + // p-side QpY: the neighbour CU only at the coding-block | ||
| 1145 | + // boundary edge; interior edges share the CU's QpY. | ||
| 1146 | + let (boundary, qp_y_p) = match edge_type { | ||
| 1147 | + EdgeType::Vertical => (x_dk == 0, qp_y_p_left), | ||
| 1148 | + EdgeType::Horizontal => (y_dm == 0, qp_y_p_top), | ||
| 1149 | + }; | ||
| 1150 | + // §8.7.2.5.3: QpQ / QpP are the QpY of the coding units | ||
| 1151 | + // containing the q0 / p0 samples — per position from the QP | ||
| 1152 | + // map when supplied, else the per-CU scalars. | ||
| 1153 | + let (qp_q, qp_p) = match qp_map { | ||
| 1154 | + Some(m) => { | ||
| 1155 | + let (qx, qy) = (x_cb + x_dk, y_cb + y_dm); | ||
| 1156 | + let (px, py) = match edge_type { | ||
| 1157 | + EdgeType::Vertical => (qx - 1, qy), | ||
| 1158 | + EdgeType::Horizontal => (qx, qy - 1), | ||
| 1159 | + }; | ||
| 1160 | + (m.qp_at(qx, qy), m.qp_at(px, py)) | ||
| 1161 | + } | ||
| 1162 | + None => (params.qp_y, if boundary { qp_y_p } else { params.qp_y }), | ||
| 1163 | + }; | ||
| 1164 | + let qp = EdgeQp { | ||
| 1165 | + qp_q, | ||
| 1166 | + qp_p, | ||
| 1167 | + beta_offset_div2: params.beta_offset_div2, | ||
| 1168 | + tc_offset_div2: params.tc_offset_div2, | ||
| 1169 | + bit_depth: params.bit_depth_luma, | ||
| 1170 | + }; | ||
| 1171 | + let (buf, stride) = pic.plane_mut(Plane::Luma); | ||
| 1172 | + let mut plane = SamplePlane { | ||
| 1173 | + samples: buf, | ||
| 1174 | + width: stride, | ||
| 1175 | + stride, | ||
| 1176 | + }; | ||
| 1177 | + let pos = EdgePos { | ||
| 1178 | + ex: x_cb + x_dk, | ||
| 1179 | + ey: y_cb + y_dm, | ||
| 1180 | + edge: edge_type, | ||
| 1181 | + }; | ||
| 1182 | + filter_luma_block_edge_gated(&mut plane, pos, s, qp, no_filter); | ||
| 1183 | + } | ||
| 1184 | + } | ||
| 1185 | + | ||
| 1186 | + // ----- chroma (§8.7.2.5.1 / .2 chroma steps) ----- | ||
| 1187 | + if params.chroma_array_type == 0 { | ||
| 1188 | + return; | ||
| 1189 | + } | ||
| 1190 | + let (xc_cb, yc_cb) = (x_cb / sub_w, y_cb / sub_h); | ||
| 1191 | + // edgeSpacing / edgeSections per direction. | ||
| 1192 | + let (spacing, sections, n_edges) = match edge_type { | ||
| 1193 | + EdgeType::Vertical => (8 / sub_w, n_d * (2 / sub_h), n_d), | ||
| 1194 | + EdgeType::Horizontal => (8 / sub_h, n_d * (2 / sub_w), n_d), | ||
| 1195 | + }; | ||
| 1196 | + for plane in [Plane::Cb, Plane::Cr] { | ||
| 1197 | + let c_qp_offset = if plane == Plane::Cb { | ||
| 1198 | + params.cb_qp_offset | ||
| 1199 | + } else { | ||
| 1200 | + params.cr_qp_offset | ||
| 1201 | + }; | ||
| 1202 | + // EDGE_VER: xDk = k*spacing (k=0..nD-1), yDm = m<<2 (m=0..sections-1). | ||
| 1203 | + // EDGE_HOR: yDm = m*spacing, xDk = k<<2. | ||
| 1204 | + let (k_max, m_max) = match edge_type { | ||
| 1205 | + EdgeType::Vertical => (n_edges, sections), | ||
| 1206 | + EdgeType::Horizontal => (sections, n_edges), | ||
| 1207 | + }; | ||
| 1208 | + for kk in 0..k_max { | ||
| 1209 | + for mm in 0..m_max { | ||
| 1210 | + let (x_dk, y_dm) = match edge_type { | ||
| 1211 | + EdgeType::Vertical => (kk * spacing, mm << 2), | ||
| 1212 | + EdgeType::Horizontal => (kk << 2, mm * spacing), | ||
| 1213 | + }; | ||
| 1214 | + // bS[xDk*SubWidthC][yDm*SubHeightC] == 2. | ||
| 1215 | + let bx = x_dk * sub_w; | ||
| 1216 | + let by = y_dm * sub_h; | ||
| 1217 | + if bs.at(bx, by) != 2 { | ||
| 1218 | + continue; | ||
| 1219 | + } | ||
| 1220 | + // 8-luma-grid alignment of the chroma edge position. | ||
| 1221 | + let aligned = match edge_type { | ||
| 1222 | + EdgeType::Vertical => ((xc_cb + x_dk) >> 3) << 3 == xc_cb + x_dk, | ||
| 1223 | + EdgeType::Horizontal => ((yc_cb + y_dm) >> 3) << 3 == yc_cb + y_dm, | ||
| 1224 | + }; | ||
| 1225 | + if !aligned { | ||
| 1226 | + continue; | ||
| 1227 | + } | ||
| 1228 | + let (boundary, qp_y_p) = match edge_type { | ||
| 1229 | + EdgeType::Vertical => (bx == 0, qp_y_p_left), | ||
| 1230 | + EdgeType::Horizontal => (by == 0, qp_y_p_top), | ||
| 1231 | + }; | ||
| 1232 | + // §8.7.2.5.5: QpQ / QpP from the coding units containing | ||
| 1233 | + // the chroma edge's q0 / p0 samples (luma positions). | ||
| 1234 | + let (qp_q, qp_p) = match qp_map { | ||
| 1235 | + Some(m) => { | ||
| 1236 | + let (qx, qy) = ((xc_cb + x_dk) * sub_w, (yc_cb + y_dm) * sub_h); | ||
| 1237 | + let (px, py) = match edge_type { | ||
| 1238 | + EdgeType::Vertical => (qx - 1, qy), | ||
| 1239 | + EdgeType::Horizontal => (qx, qy - 1), | ||
| 1240 | + }; | ||
| 1241 | + (m.qp_at(qx, qy), m.qp_at(px, py)) | ||
| 1242 | + } | ||
| 1243 | + None => (params.qp_y, if boundary { qp_y_p } else { params.qp_y }), | ||
| 1244 | + }; | ||
| 1245 | + let qp = EdgeQp { | ||
| 1246 | + qp_q, | ||
| 1247 | + qp_p, | ||
| 1248 | + beta_offset_div2: params.beta_offset_div2, | ||
| 1249 | + tc_offset_div2: params.tc_offset_div2, | ||
| 1250 | + bit_depth: params.bit_depth_chroma, | ||
| 1251 | + }; | ||
| 1252 | + let (buf, stride) = pic.plane_mut(plane); | ||
| 1253 | + let mut cplane = SamplePlane { | ||
| 1254 | + samples: buf, | ||
| 1255 | + width: stride, | ||
| 1256 | + stride, | ||
| 1257 | + }; | ||
| 1258 | + let pos = EdgePos { | ||
| 1259 | + ex: xc_cb + x_dk, | ||
| 1260 | + ey: yc_cb + y_dm, | ||
| 1261 | + edge: edge_type, | ||
| 1262 | + }; | ||
| 1263 | + filter_chroma_block_edge_gated( | ||
| 1264 | + &mut cplane, | ||
| 1265 | + pos, | ||
| 1266 | + qp, | ||
| 1267 | + c_qp_offset, | ||
| 1268 | + params.chroma_array_type, | ||
| 1269 | + no_filter, | ||
| 1270 | + ); | ||
| 1271 | + } | ||
| 1272 | + } | ||
| 1273 | + } | ||
| 1274 | +} | ||
| 1275 | + | ||
| 1276 | +/// One coding unit's full §8.7.2 deblocking description, as the | ||
| 1277 | +/// picture-level driver [`deblock_picture`] consumes it. | ||
| 1278 | +/// | ||
| 1279 | +/// Carries everything the §8.7.2.2 / .3 edge-flag derivation, the §8.7.2.4 | ||
| 1280 | +/// bS derivation and the §8.7.2.5.1 / .2 filtering need for one CU: its | ||
| 1281 | +/// geometry + QP context ([`DeblockCu`]), its transform-tree split | ||
| 1282 | +/// ([`TransformSplit`]) + prediction [`PartMode`], and the §8.7.2.1 | ||
| 1283 | +/// `filterLeftCbEdgeFlag` / `filterTopCbEdgeFlag` the caller computes from | ||
| 1284 | +/// the picture / tile / slice geometry (`false` at a non-filtered | ||
| 1285 | +/// boundary). | ||
| 1286 | +#[derive(Debug, Clone)] | ||
| 1287 | +pub struct DeblockCuDesc { | ||
| 1288 | + /// Geometry + QP context. | ||
| 1289 | + pub cu: DeblockCu, | ||
| 1290 | + /// The CU's transform-tree split structure. | ||
| 1291 | + pub transform_split: TransformSplit, | ||
| 1292 | + /// The CU's prediction partition mode. | ||
| 1293 | + pub part_mode: PartMode, | ||
| 1294 | + /// §8.7.2.1 `filterLeftCbEdgeFlag` (gates the left CB-boundary | ||
| 1295 | + /// vertical edge). | ||
| 1296 | + pub filter_left: bool, | ||
| 1297 | + /// §8.7.2.1 `filterTopCbEdgeFlag` (gates the top CB-boundary | ||
| 1298 | + /// horizontal edge). | ||
| 1299 | + pub filter_top: bool, | ||
| 1300 | +} | ||
| 1301 | + | ||
| 1302 | +/// §8.7.2.1 — the picture-level deblocking filter driver. | ||
| 1303 | +/// | ||
| 1304 | +/// Filters all vertical edges of the picture first, then all horizontal | ||
| 1305 | +/// edges (with the vertically-filtered samples as input), per §8.7.2.1. | ||
| 1306 | +/// Each pass walks `cus` in order and, for each CU: derives the | ||
| 1307 | +/// §8.7.2.2 / .3 edge flags, the §8.7.2.4 boundary strengths from `field`, | ||
| 1308 | +/// then applies the §8.7.2.5.1 / .2 luma + chroma filters via | ||
| 1309 | +/// [`filter_cu_edges`]. | ||
| 1310 | +/// | ||
| 1311 | +/// `cus` must be in coding (z-scan) order; the caller is responsible for | ||
| 1312 | +/// the §8.7.2.1 boundary exclusions (picture / tile / slice edges, and the | ||
| 1313 | +/// `slice_deblocking_filter_disabled_flag` skip) by setting each | ||
| 1314 | +/// descriptor's `filter_left` / `filter_top` (and omitting CUs whose slice | ||
| 1315 | +/// disables deblocking). | ||
| 1316 | +/// | ||
| 1317 | +/// # Panics | ||
| 1318 | +/// Panics if a CU's edges read/write outside a `pic` plane. | ||
| 1319 | +pub fn deblock_picture(pic: &mut Picture, field: &MotionField, cus: &[DeblockCuDesc]) { | ||
| 1320 | + deblock_picture_with_qp_map(pic, field, cus, None); | ||
| 1321 | +} | ||
| 1322 | + | ||
| 1323 | +/// Per-4×4-cell `QpY` map for the §8.7.2.5.3 / §8.7.2.5.5 per-position | ||
| 1324 | +/// `QpQ` / `QpP` reads (row-major over the picture's 4×4 cells). When a | ||
| 1325 | +/// picture carries per-quantization-group `cu_qp_delta` values, the | ||
| 1326 | +/// p-side QP can change along a single coding-block edge, so the | ||
| 1327 | +/// per-CU scalar fallback in [`DeblockCu`] is not exact. | ||
| 1328 | +#[derive(Debug, Clone, Copy)] | ||
| 1329 | +pub struct QpMap<'a> { | ||
| 1330 | + /// Per-cell `QpY`. | ||
| 1331 | + pub cells: &'a [i8], | ||
| 1332 | + /// Cell-grid width (`ceil(pic_width / 4)`). | ||
| 1333 | + pub w_cells: usize, | ||
| 1334 | +} | ||
| 1335 | + | ||
| 1336 | +impl QpMap<'_> { | ||
| 1337 | + fn qp_at(&self, x_luma: usize, y_luma: usize) -> i32 { | ||
| 1338 | + let idx = (y_luma >> 2) * self.w_cells + (x_luma >> 2); | ||
| 1339 | + self.cells.get(idx).copied().map_or(0, i32::from) | ||
| 1340 | + } | ||
| 1341 | +} | ||
| 1342 | + | ||
| 1343 | +/// Per-4×4-luma-cell in-loop-filter suppression map: `true` cells | ||
| 1344 | +/// belong to a coding unit whose reconstructed samples the loop | ||
| 1345 | +/// filters must not modify — a `pcm_flag == 1` CU when | ||
| 1346 | +/// `pcm_loop_filter_disabled_flag == 1` (§7.4.3.2.1), or a | ||
| 1347 | +/// `cu_transquant_bypass_flag == 1` CU (§7.4.9.5). The §8.7.2.5.4 / | ||
| 1348 | +/// §8.7.2.5.5 filters zero `nDp` / `nDq` on the flagged side (the | ||
| 1349 | +/// decision still reads both sides); §8.7.3 SAO skips flagged samples. | ||
| 1350 | +#[derive(Debug, Clone, Copy)] | ||
| 1351 | +pub struct NoFilterMap<'a> { | ||
| 1352 | + /// Per-cell suppression flags, row-major. | ||
| 1353 | + pub cells: &'a [bool], | ||
| 1354 | + /// Cell-grid width (`ceil(pic_width / 4)`). | ||
| 1355 | + pub w_cells: usize, | ||
| 1356 | +} | ||
| 1357 | + | ||
| 1358 | +impl NoFilterMap<'_> { | ||
| 1359 | + /// Suppression flag of the cell covering luma sample | ||
| 1360 | + /// `(x_luma, y_luma)` (out-of-range positions are not suppressed). | ||
| 1361 | + #[must_use] | ||
| 1362 | + pub fn at_luma(&self, x_luma: usize, y_luma: usize) -> bool { | ||
| 1363 | + self.cells | ||
| 1364 | + .get((y_luma >> 2) * self.w_cells + (x_luma >> 2)) | ||
| 1365 | + .copied() | ||
| 1366 | + .unwrap_or(false) | ||
| 1367 | + } | ||
| 1368 | +} | ||
| 1369 | + | ||
| 1370 | +/// [`deblock_picture`] with the per-position QP map. | ||
| 1371 | +pub fn deblock_picture_with_qp_map( | ||
| 1372 | + pic: &mut Picture, | ||
| 1373 | + field: &MotionField, | ||
| 1374 | + cus: &[DeblockCuDesc], | ||
| 1375 | + qp_map: Option<QpMap<'_>>, | ||
| 1376 | +) { | ||
| 1377 | + deblock_picture_full(pic, field, cus, qp_map, None); | ||
| 1378 | +} | ||
| 1379 | + | ||
| 1380 | +/// [`deblock_picture_with_qp_map`] with the per-CU loop-filter | ||
| 1381 | +/// suppression map (§8.7.2.5.4 / §8.7.2.5.5 — PCM with | ||
| 1382 | +/// `pcm_loop_filter_disabled_flag` and transquant-bypass coding units | ||
| 1383 | +/// keep their reconstructed samples). | ||
| 1384 | +pub fn deblock_picture_full( | ||
| 1385 | + pic: &mut Picture, | ||
| 1386 | + field: &MotionField, | ||
| 1387 | + cus: &[DeblockCuDesc], | ||
| 1388 | + qp_map: Option<QpMap<'_>>, | ||
| 1389 | + no_filter: Option<&NoFilterMap<'_>>, | ||
| 1390 | +) { | ||
| 1391 | + // Pass 1: all vertical edges. | ||
| 1392 | + for desc in cus { | ||
| 1393 | + apply_cu_direction(pic, field, desc, EdgeType::Vertical, qp_map, no_filter); | ||
| 1394 | + } | ||
| 1395 | + // Pass 2: all horizontal edges (on the vertically-filtered samples). | ||
| 1396 | + for desc in cus { | ||
| 1397 | + apply_cu_direction(pic, field, desc, EdgeType::Horizontal, qp_map, no_filter); | ||
| 1398 | + } | ||
| 1399 | +} | ||
| 1400 | + | ||
| 1401 | +/// Derive the edge flags + bS for one CU in one direction and filter it. | ||
| 1402 | +fn apply_cu_direction( | ||
| 1403 | + pic: &mut Picture, | ||
| 1404 | + field: &MotionField, | ||
| 1405 | + desc: &DeblockCuDesc, | ||
| 1406 | + edge_type: EdgeType, | ||
| 1407 | + qp_map: Option<QpMap<'_>>, | ||
| 1408 | + no_filter: Option<&NoFilterMap<'_>>, | ||
| 1409 | +) { | ||
| 1410 | + let DeblockCu { | ||
| 1411 | + x_cb, | ||
| 1412 | + y_cb, | ||
| 1413 | + log2_cb_size, | ||
| 1414 | + .. | ||
| 1415 | + } = desc.cu; | ||
| 1416 | + let filter_edge_flag = match edge_type { | ||
| 1417 | + EdgeType::Vertical => desc.filter_left, | ||
| 1418 | + EdgeType::Horizontal => desc.filter_top, | ||
| 1419 | + }; | ||
| 1420 | + let ef = derive_edge_flags( | ||
| 1421 | + &desc.transform_split, | ||
| 1422 | + desc.part_mode, | ||
| 1423 | + log2_cb_size, | ||
| 1424 | + edge_type, | ||
| 1425 | + filter_edge_flag, | ||
| 1426 | + ); | ||
| 1427 | + let bs = derive_boundary_strength( | ||
| 1428 | + field, | ||
| 1429 | + x_cb, | ||
| 1430 | + y_cb, | ||
| 1431 | + log2_cb_size, | ||
| 1432 | + edge_type, | ||
| 1433 | + ef.edge_flags(), | ||
| 1434 | + ef.tb_edge(), | ||
| 1435 | + ); | ||
| 1436 | + filter_cu_edges_full(pic, &desc.cu, edge_type, &bs, qp_map, no_filter); | ||
| 1437 | +} | ||
| 1438 | + | ||
| 1439 | +#[cfg(test)] | ||
| 1440 | +mod tests { | ||
| 1441 | + use super::*; | ||
| 1442 | + use crate::motion::MotionCell; | ||
| 1443 | + | ||
| 1444 | + fn inter_cell(mv0: [i32; 2], poc0: i32) -> MotionCell { | ||
| 1445 | + MotionCell { | ||
| 1446 | + is_intra: false, | ||
| 1447 | + has_nonzero_coeff: false, | ||
| 1448 | + pred_flag_l0: true, | ||
| 1449 | + pred_flag_l1: false, | ||
| 1450 | + ref_poc_l0: poc0, | ||
| 1451 | + ref_poc_l1: i32::MIN, | ||
| 1452 | + mv_l0: mv0, | ||
| 1453 | + mv_l1: [0, 0], | ||
| 1454 | + } | ||
| 1455 | + } | ||
| 1456 | + | ||
| 1457 | + /// A 16×16 CU's internal vertical edge at xDi=8, with the left | ||
| 1458 | + /// (p-side) half intra ⇒ bS == 2 at the sampled positions. | ||
| 1459 | + /// | ||
| 1460 | + /// The §8.7.2.4 vertical-edge x stride is 8, so a 16-wide CU samples | ||
| 1461 | + /// xDi ∈ {0, 8}; the internal edge is at xDi=8. | ||
| 1462 | + #[test] | ||
| 1463 | + fn intra_neighbour_gives_bs2() { | ||
| 1464 | + let mut field = MotionField::new(32, 32); | ||
| 1465 | + // CU at (0,0), 16×16. q-side (right half) inter; p-side (left) | ||
| 1466 | + // stays intra (background). | ||
| 1467 | + field.fill_rect(8, 0, 8, 16, inter_cell([0, 0], 0)); | ||
| 1468 | + let n = 16; | ||
| 1469 | + let mut edge_flags = vec![false; n * n]; | ||
| 1470 | + let tb_edge = vec![false; n * n]; | ||
| 1471 | + // Internal vertical edge at xDi=8, sampled yDj 0,4,8,12. | ||
| 1472 | + for yj in (0..16).step_by(4) { | ||
| 1473 | + edge_flags[yj * n + 8] = true; | ||
| 1474 | + } | ||
| 1475 | + let bs = | ||
| 1476 | + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); | ||
| 1477 | + // p0 = col 7 (intra), q0 = col 8 (inter) ⇒ bS == 2. | ||
| 1478 | + assert_eq!(bs.at(8, 0), 2); | ||
| 1479 | + assert_eq!(bs.at(8, 12), 2); | ||
| 1480 | + // xDi=4 not sampled for EDGE_VER (8-stride). | ||
| 1481 | + assert_eq!(bs.at(4, 0), 0); | ||
| 1482 | + } | ||
| 1483 | + | ||
| 1484 | + /// Transform-block edge with a non-zero coefficient on an inter block | ||
| 1485 | + /// ⇒ bS == 1. | ||
| 1486 | + #[test] | ||
| 1487 | + fn tb_edge_with_coeff_gives_bs1() { | ||
| 1488 | + let mut field = MotionField::new(32, 32); | ||
| 1489 | + let mut p = inter_cell([0, 0], 0); | ||
| 1490 | + p.has_nonzero_coeff = true; | ||
| 1491 | + let q = inter_cell([0, 0], 0); | ||
| 1492 | + field.fill_rect(0, 0, 16, 16, q); | ||
| 1493 | + field.fill_rect(0, 0, 8, 16, p); // left half carries the coeff | ||
| 1494 | + let n = 16; | ||
| 1495 | + let mut edge_flags = vec![false; n * n]; | ||
| 1496 | + let mut tb_edge = vec![false; n * n]; | ||
| 1497 | + // Vertical edge at xDi=8 (a transform-block edge). | ||
| 1498 | + for yj in (0..16).step_by(4) { | ||
| 1499 | + edge_flags[yj * n + 8] = true; | ||
| 1500 | + tb_edge[yj * n + 8] = true; | ||
| 1501 | + } | ||
| 1502 | + let bs = | ||
| 1503 | + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); | ||
| 1504 | + // p0 = col 7 (coeff block), q0 = col 8 ⇒ bS == 1. | ||
| 1505 | + assert_eq!(bs.at(8, 0), 1); | ||
| 1506 | + assert_eq!(bs.at(8, 4), 1); | ||
| 1507 | + } | ||
| 1508 | + | ||
| 1509 | + /// Two inter blocks, same reference, MV difference >= 4 ⇒ bS == 1. | ||
| 1510 | + #[test] | ||
| 1511 | + fn mv_diff_gives_bs1() { | ||
| 1512 | + let mut field = MotionField::new(32, 32); | ||
| 1513 | + field.fill_rect(0, 0, 8, 16, inter_cell([0, 0], 0)); // p side | ||
| 1514 | + field.fill_rect(8, 0, 8, 16, inter_cell([4, 0], 0)); // q side, Δ=4 | ||
| 1515 | + let n = 16; | ||
| 1516 | + let mut edge_flags = vec![false; n * n]; | ||
| 1517 | + let tb_edge = vec![false; n * n]; | ||
| 1518 | + for yj in (0..16).step_by(4) { | ||
| 1519 | + edge_flags[yj * n + 8] = true; | ||
| 1520 | + } | ||
| 1521 | + let bs = | ||
| 1522 | + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); | ||
| 1523 | + assert_eq!(bs.at(8, 0), 1); | ||
| 1524 | + assert_eq!(bs.at(8, 12), 1); | ||
| 1525 | + } | ||
| 1526 | + | ||
| 1527 | + /// Two inter blocks, same reference + same MV ⇒ bS == 0. | ||
| 1528 | + #[test] | ||
| 1529 | + fn same_motion_gives_bs0() { | ||
| 1530 | + let mut field = MotionField::new(32, 32); | ||
| 1531 | + field.fill_rect(0, 0, 16, 16, inter_cell([3, 1], 0)); // identical motion | ||
| 1532 | + let n = 16; | ||
| 1533 | + let mut edge_flags = vec![false; n * n]; | ||
| 1534 | + let tb_edge = vec![false; n * n]; | ||
| 1535 | + for yj in (0..16).step_by(4) { | ||
| 1536 | + edge_flags[yj * n + 8] = true; | ||
| 1537 | + } | ||
| 1538 | + let bs = | ||
| 1539 | + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); | ||
| 1540 | + assert_eq!(bs.at(8, 0), 0); | ||
| 1541 | + } | ||
| 1542 | + | ||
| 1543 | + /// Different reference pictures ⇒ bS == 1 even with identical MVs. | ||
| 1544 | + #[test] | ||
| 1545 | + fn different_ref_gives_bs1() { | ||
| 1546 | + let mut field = MotionField::new(32, 32); | ||
| 1547 | + field.fill_rect(0, 0, 8, 16, inter_cell([2, 2], 0)); // poc 0 | ||
| 1548 | + field.fill_rect(8, 0, 8, 16, inter_cell([2, 2], 8)); // poc 8 | ||
| 1549 | + let n = 16; | ||
| 1550 | + let mut edge_flags = vec![false; n * n]; | ||
| 1551 | + let tb_edge = vec![false; n * n]; | ||
| 1552 | + for yj in (0..16).step_by(4) { | ||
| 1553 | + edge_flags[yj * n + 8] = true; | ||
| 1554 | + } | ||
| 1555 | + let bs = | ||
| 1556 | + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); | ||
| 1557 | + assert_eq!(bs.at(8, 0), 1); | ||
| 1558 | + } | ||
| 1559 | + | ||
| 1560 | + /// Horizontal edges sample 4-stride x, 8-stride y. | ||
| 1561 | + #[test] | ||
| 1562 | + fn horizontal_edge_sampling() { | ||
| 1563 | + let mut field = MotionField::new(32, 32); | ||
| 1564 | + // top half intra (background), bottom half inter; internal | ||
| 1565 | + // horizontal edge at yDj=8. | ||
| 1566 | + field.fill_rect(0, 8, 16, 8, inter_cell([0, 0], 0)); | ||
| 1567 | + let n = 16; | ||
| 1568 | + let mut edge_flags = vec![false; n * n]; | ||
| 1569 | + let tb_edge = vec![false; n * n]; | ||
| 1570 | + for xi in (0..16).step_by(4) { | ||
| 1571 | + edge_flags[8 * n + xi] = true; | ||
| 1572 | + } | ||
| 1573 | + let bs = | ||
| 1574 | + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Horizontal, &edge_flags, &tb_edge); | ||
| 1575 | + // yDj=8: p0 = row 7 (intra), q0 = row 8 (inter) ⇒ bS == 2. | ||
| 1576 | + assert_eq!(bs.at(0, 8), 2); | ||
| 1577 | + assert_eq!(bs.at(12, 8), 2); | ||
| 1578 | + // yDj=4 not sampled for EDGE_HOR. | ||
| 1579 | + assert_eq!(bs.at(0, 4), 0); | ||
| 1580 | + } | ||
| 1581 | + | ||
| 1582 | + /// edgeFlags == 0 ⇒ bS stays 0 regardless of mode. | ||
| 1583 | + #[test] | ||
| 1584 | + fn no_edge_flag_gives_bs0() { | ||
| 1585 | + let field = MotionField::new(16, 16); // intra background | ||
| 1586 | + let n = 8; | ||
| 1587 | + let edge_flags = vec![false; n * n]; | ||
| 1588 | + let tb_edge = vec![false; n * n]; | ||
| 1589 | + let bs = | ||
| 1590 | + derive_boundary_strength(&field, 0, 0, 3, EdgeType::Vertical, &edge_flags, &tb_edge); | ||
| 1591 | + assert_eq!(bs.at(0, 0), 0); | ||
| 1592 | + } | ||
| 1593 | + | ||
| 1594 | + /// Bullet-4 path: two MVs each, same single reference picture on both | ||
| 1595 | + /// sides; bS == 1 only when both the straight and crossed MV-pair | ||
| 1596 | + /// differences reach 4. | ||
| 1597 | + #[test] | ||
| 1598 | + fn bipred_same_ref_bullet4() { | ||
| 1599 | + let mut field = MotionField::new(32, 32); | ||
| 1600 | + let bi = |mv0: [i32; 2], mv1: [i32; 2]| MotionCell { | ||
| 1601 | + is_intra: false, | ||
| 1602 | + has_nonzero_coeff: false, | ||
| 1603 | + pred_flag_l0: true, | ||
| 1604 | + pred_flag_l1: true, | ||
| 1605 | + ref_poc_l0: 0, | ||
| 1606 | + ref_poc_l1: 0, // same reference picture for both lists | ||
| 1607 | + mv_l0: mv0, | ||
| 1608 | + mv_l1: mv1, | ||
| 1609 | + }; | ||
| 1610 | + // p: l0=[0,0] l1=[0,0]; q: l0=[4,0] l1=[4,0]. | ||
| 1611 | + // straight: |Δl0|>=4 ⇒ true. crossed: |p.l0−q.l1|=4 ⇒ true ⇒ bS 1. | ||
| 1612 | + field.fill_rect(0, 0, 8, 16, bi([0, 0], [0, 0])); | ||
| 1613 | + field.fill_rect(8, 0, 8, 16, bi([4, 0], [4, 0])); | ||
| 1614 | + let n = 16; | ||
| 1615 | + let mut edge_flags = vec![false; n * n]; | ||
| 1616 | + let tb_edge = vec![false; n * n]; | ||
| 1617 | + for yj in (0..16).step_by(4) { | ||
| 1618 | + edge_flags[yj * n + 8] = true; | ||
| 1619 | + } | ||
| 1620 | + let bs = | ||
| 1621 | + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); | ||
| 1622 | + assert_eq!(bs.at(8, 0), 1); | ||
| 1623 | + } | ||
| 1624 | + | ||
| 1625 | + // ----- §8.7.2.2 / §8.7.2.3 edge-flag derivation ----- | ||
| 1626 | + | ||
| 1627 | + /// §8.7.2.2: an un-split 16×16 CB marks only its left CB-boundary | ||
| 1628 | + /// column (EDGE_VER), gated by filterEdgeFlag. No internal TB edges. | ||
| 1629 | + #[test] | ||
| 1630 | + fn edge_flags_single_tb_left_boundary() { | ||
| 1631 | + let n = 16; | ||
| 1632 | + // filterEdgeFlag = true ⇒ the CB-left column (x=0) is an edge. | ||
| 1633 | + let ef = derive_edge_flags( | ||
| 1634 | + &TransformSplit::leaf(), | ||
| 1635 | + PartMode::Part2Nx2N, | ||
| 1636 | + 4, | ||
| 1637 | + EdgeType::Vertical, | ||
| 1638 | + true, | ||
| 1639 | + ); | ||
| 1640 | + for y in 0..n { | ||
| 1641 | + assert!(ef.edge_at(0, y), "left CB-boundary column must be set"); | ||
| 1642 | + assert!(ef.tb_at(0, y), "left CB-boundary is a TB edge"); | ||
| 1643 | + } | ||
| 1644 | + // No internal column is set (no split, PART_2Nx2N). | ||
| 1645 | + for x in 1..n { | ||
| 1646 | + for y in 0..n { | ||
| 1647 | + assert!(!ef.edge_at(x, y), "interior ({x},{y}) must be clear"); | ||
| 1648 | + } | ||
| 1649 | + } | ||
| 1650 | + } | ||
| 1651 | + | ||
| 1652 | + /// filterEdgeFlag = false suppresses the CB-boundary edge entirely. | ||
| 1653 | + #[test] | ||
| 1654 | + fn edge_flags_cb_boundary_gated_off() { | ||
| 1655 | + let ef = derive_edge_flags( | ||
| 1656 | + &TransformSplit::leaf(), | ||
| 1657 | + PartMode::Part2Nx2N, | ||
| 1658 | + 4, | ||
| 1659 | + EdgeType::Vertical, | ||
| 1660 | + false, | ||
| 1661 | + ); | ||
| 1662 | + for y in 0..16 { | ||
| 1663 | + assert!(!ef.edge_at(0, y), "gated-off CB boundary stays clear"); | ||
| 1664 | + } | ||
| 1665 | + } | ||
| 1666 | + | ||
| 1667 | + /// §8.7.2.2: a one-level transform split of a 16×16 CB marks the | ||
| 1668 | + /// internal vertical TB edge at column 8 (always 1, not gated), plus | ||
| 1669 | + /// the gated left boundary. | ||
| 1670 | + #[test] | ||
| 1671 | + fn edge_flags_split_marks_internal_tb_edge() { | ||
| 1672 | + let ef = derive_edge_flags( | ||
| 1673 | + &TransformSplit::split_once(), | ||
| 1674 | + PartMode::Part2Nx2N, | ||
| 1675 | + 4, | ||
| 1676 | + EdgeType::Vertical, | ||
| 1677 | + true, | ||
| 1678 | + ); | ||
| 1679 | + for y in 0..16 { | ||
| 1680 | + assert!(ef.edge_at(0, y), "left boundary set"); | ||
| 1681 | + assert!(ef.edge_at(8, y), "internal split column 8 set"); | ||
| 1682 | + assert!(ef.tb_at(8, y), "internal split is a TB edge"); | ||
| 1683 | + } | ||
| 1684 | + } | ||
| 1685 | + | ||
| 1686 | + /// §8.7.2.2 EDGE_HOR: the split marks the internal horizontal TB edge | ||
| 1687 | + /// at row 8. | ||
| 1688 | + #[test] | ||
| 1689 | + fn edge_flags_split_horizontal() { | ||
| 1690 | + let ef = derive_edge_flags( | ||
| 1691 | + &TransformSplit::split_once(), | ||
| 1692 | + PartMode::Part2Nx2N, | ||
| 1693 | + 4, | ||
| 1694 | + EdgeType::Horizontal, | ||
| 1695 | + true, | ||
| 1696 | + ); | ||
| 1697 | + for x in 0..16 { | ||
| 1698 | + assert!(ef.edge_at(x, 0), "top boundary set"); | ||
| 1699 | + assert!(ef.edge_at(x, 8), "internal split row 8 set"); | ||
| 1700 | + assert!(ef.tb_at(x, 8), "internal split is a TB edge"); | ||
| 1701 | + } | ||
| 1702 | + } | ||
| 1703 | + | ||
| 1704 | + /// §8.7.2.3 PART_Nx2N marks the prediction column at nCbS/2 — and it | ||
| 1705 | + /// is NOT a transform-block edge (tb_edge stays clear there). | ||
| 1706 | + #[test] | ||
| 1707 | + fn edge_flags_part_nx2n_prediction_edge() { | ||
| 1708 | + let ef = derive_edge_flags( | ||
| 1709 | + &TransformSplit::leaf(), | ||
| 1710 | + PartMode::PartNx2N, | ||
| 1711 | + 4, | ||
| 1712 | + EdgeType::Vertical, | ||
| 1713 | + true, | ||
| 1714 | + ); | ||
| 1715 | + for y in 0..16 { | ||
| 1716 | + assert!(ef.edge_at(8, y), "PART_Nx2N prediction column 8 set"); | ||
| 1717 | + assert!(!ef.tb_at(8, y), "prediction edge is not a TB edge"); | ||
| 1718 | + } | ||
| 1719 | + } | ||
| 1720 | + | ||
| 1721 | + /// §8.7.2.3 AMP PART_nLx2N marks column nCbS/4; PART_nRx2N marks | ||
| 1722 | + /// 3·nCbS/4. | ||
| 1723 | + #[test] | ||
| 1724 | + fn edge_flags_amp_columns() { | ||
| 1725 | + let l = derive_edge_flags( | ||
| 1726 | + &TransformSplit::leaf(), | ||
| 1727 | + PartMode::PartNLx2N, | ||
| 1728 | + 4, | ||
| 1729 | + EdgeType::Vertical, | ||
| 1730 | + true, | ||
| 1731 | + ); | ||
| 1732 | + assert!(l.edge_at(4, 0), "PART_nLx2N column 4"); | ||
| 1733 | + let r = derive_edge_flags( | ||
| 1734 | + &TransformSplit::leaf(), | ||
| 1735 | + PartMode::PartNRx2N, | ||
| 1736 | + 4, | ||
| 1737 | + EdgeType::Vertical, | ||
| 1738 | + true, | ||
| 1739 | + ); | ||
| 1740 | + assert!(r.edge_at(12, 0), "PART_nRx2N column 12"); | ||
| 1741 | + } | ||
| 1742 | + | ||
| 1743 | + /// §8.7.2.3 horizontal AMP: PART_2NxnU row nCbS/4, PART_2NxnD row | ||
| 1744 | + /// 3·nCbS/4. | ||
| 1745 | + #[test] | ||
| 1746 | + fn edge_flags_amp_rows() { | ||
| 1747 | + let u = derive_edge_flags( | ||
| 1748 | + &TransformSplit::leaf(), | ||
| 1749 | + PartMode::Part2NxnU, | ||
| 1750 | + 4, | ||
| 1751 | + EdgeType::Horizontal, | ||
| 1752 | + true, | ||
| 1753 | + ); | ||
| 1754 | + assert!(u.edge_at(0, 4), "PART_2NxnU row 4"); | ||
| 1755 | + let d = derive_edge_flags( | ||
| 1756 | + &TransformSplit::leaf(), | ||
| 1757 | + PartMode::Part2NxnD, | ||
| 1758 | + 4, | ||
| 1759 | + EdgeType::Horizontal, | ||
| 1760 | + true, | ||
| 1761 | + ); | ||
| 1762 | + assert!(d.edge_at(0, 12), "PART_2NxnD row 12"); | ||
| 1763 | + } | ||
| 1764 | + | ||
| 1765 | + /// A nested split (one quadrant splits again) marks the deeper TB edge | ||
| 1766 | + /// at the 4-sample sub-block column. | ||
| 1767 | + #[test] | ||
| 1768 | + fn edge_flags_nested_split() { | ||
| 1769 | + // 16×16 CB: TL quadrant (8×8) splits into four 4×4; others leaf. | ||
| 1770 | + let nested = TransformSplit::Split(Box::new([ | ||
| 1771 | + TransformSplit::split_once(), // TL 8×8 → 4×4 leaves | ||
| 1772 | + TransformSplit::Leaf, | ||
| 1773 | + TransformSplit::Leaf, | ||
| 1774 | + TransformSplit::Leaf, | ||
| 1775 | + ])); | ||
| 1776 | + let ef = derive_edge_flags(&nested, PartMode::Part2Nx2N, 4, EdgeType::Vertical, true); | ||
| 1777 | + // The TL quadrant's internal vertical edge is at column 4. | ||
| 1778 | + for y in 0..8 { | ||
| 1779 | + assert!(ef.edge_at(4, y), "nested TB edge at column 4, row {y}"); | ||
| 1780 | + assert!(ef.tb_at(4, y)); | ||
| 1781 | + } | ||
| 1782 | + // The CB-internal split at column 8 is still present. | ||
| 1783 | + for y in 0..16 { | ||
| 1784 | + assert!(ef.edge_at(8, y), "CB-level split column 8"); | ||
| 1785 | + } | ||
| 1786 | + // Column 4 below the TL quadrant (y>=8) is not an edge (BL leaf is | ||
| 1787 | + // 8 wide, its only internal edge would be column 8, not 4). | ||
| 1788 | + assert!(!ef.edge_at(4, 8), "column 4 row 8 clear (BL leaf)"); | ||
| 1789 | + } | ||
| 1790 | + | ||
| 1791 | + /// The §8.7.2.4 bS derivation consumes the derived flags: an | ||
| 1792 | + /// intra/inter split CU with a derived internal TB edge yields bS=2 | ||
| 1793 | + /// at the internal column. | ||
| 1794 | + #[test] | ||
| 1795 | + fn edge_flags_feed_boundary_strength() { | ||
| 1796 | + // filterEdgeFlag = false: this CB is at the picture's left edge, so | ||
| 1797 | + // only the internal split column (8) is an edge — the bS sampler | ||
| 1798 | + // never reads a p-sample at x = −1. | ||
| 1799 | + let ef = derive_edge_flags( | ||
| 1800 | + &TransformSplit::split_once(), | ||
| 1801 | + PartMode::Part2Nx2N, | ||
| 1802 | + 4, | ||
| 1803 | + EdgeType::Vertical, | ||
| 1804 | + false, | ||
| 1805 | + ); | ||
| 1806 | + let mut field = MotionField::new(32, 32); | ||
| 1807 | + // Left half intra (background), right half inter. | ||
| 1808 | + field.fill_rect(8, 0, 8, 16, inter_cell([0, 0], 0)); | ||
| 1809 | + let bs = derive_boundary_strength( | ||
| 1810 | + &field, | ||
| 1811 | + 0, | ||
| 1812 | + 0, | ||
| 1813 | + 4, | ||
| 1814 | + EdgeType::Vertical, | ||
| 1815 | + ef.edge_flags(), | ||
| 1816 | + ef.tb_edge(), | ||
| 1817 | + ); | ||
| 1818 | + // Internal column 8: p (col 7, intra) vs q (col 8, inter) ⇒ bS 2. | ||
| 1819 | + assert_eq!(bs.at(8, 0), 2); | ||
| 1820 | + } | ||
| 1821 | + | ||
| 1822 | + // ----- §8.7.2.5.3 / .6 / .7 luma filtering primitives ----- | ||
| 1823 | + | ||
| 1824 | + /// Table 8-12 spot checks: β′ is 0 below Q=16 and tracks the listed | ||
| 1825 | + /// breakpoints; tC′ is 0 up to Q=17 and 1 at Q=18. | ||
| 1826 | + #[test] | ||
| 1827 | + fn table_8_12_breakpoints() { | ||
| 1828 | + assert_eq!(beta_prime(15), 0); | ||
| 1829 | + assert_eq!(beta_prime(16), 6); | ||
| 1830 | + assert_eq!(beta_prime(29), 20); | ||
| 1831 | + assert_eq!(beta_prime(51), 64); | ||
| 1832 | + assert_eq!(tc_prime(17), 0); | ||
| 1833 | + assert_eq!(tc_prime(18), 1); | ||
| 1834 | + assert_eq!(tc_prime(53), 24); | ||
| 1835 | + // Clip behaviour at the table edges. | ||
| 1836 | + assert_eq!(beta_prime(-3), 0); | ||
| 1837 | + assert_eq!(tc_prime(99), 24); | ||
| 1838 | + } | ||
| 1839 | + | ||
| 1840 | + /// §8.7.2.5.3 β/tC at 8-bit: qPL = (QpQ+QpP+1)>>1, no offsets, bS=2. | ||
| 1841 | + /// QpQ=QpP=37 ⇒ qPL=37 ⇒ Q_beta=37 ⇒ β′=36, β=36; Q_tc=37+2=39 ⇒ | ||
| 1842 | + /// tC′=5, tC=5. | ||
| 1843 | + #[test] | ||
| 1844 | + fn luma_beta_tc_no_offset_8bit() { | ||
| 1845 | + let (beta, tc) = luma_beta_tc(37, 37, 2, 0, 0, 8); | ||
| 1846 | + assert_eq!(beta, 36); | ||
| 1847 | + assert_eq!(tc, 5); | ||
| 1848 | + // bS=1 lowers the tC index by 2 (Q_tc=37): tC′=4. | ||
| 1849 | + let (_, tc1) = luma_beta_tc(37, 37, 1, 0, 0, 8); | ||
| 1850 | + assert_eq!(tc1, 4); | ||
| 1851 | + } | ||
| 1852 | + | ||
| 1853 | + /// 10-bit scaling: β and tC are multiplied by 1<<(BitDepthY−8)=4. | ||
| 1854 | + #[test] | ||
| 1855 | + fn luma_beta_tc_10bit_scaled() { | ||
| 1856 | + let (beta, tc) = luma_beta_tc(37, 37, 2, 0, 0, 10); | ||
| 1857 | + assert_eq!(beta, 36 * 4); | ||
| 1858 | + assert_eq!(tc, 5 * 4); | ||
| 1859 | + } | ||
| 1860 | + | ||
| 1861 | + /// §8.7.2.5.6: a flat region (all-equal samples) passes the decision. | ||
| 1862 | + #[test] | ||
| 1863 | + fn luma_sample_decision_flat_passes() { | ||
| 1864 | + // dpq=0 < β>>2; |p3−p0|+|q0−q3|=0 < β>>3; |p0−q0|=0 < (5tC+1)>>1. | ||
| 1865 | + assert!(luma_sample_decision(128, 128, 128, 128, 0, 32, 4)); | ||
| 1866 | + // A large step at the boundary fails the |p0−q0| test. | ||
| 1867 | + assert!(!luma_sample_decision(64, 64, 200, 200, 0, 32, 4)); | ||
| 1868 | + } | ||
| 1869 | + | ||
| 1870 | + /// §8.7.2.5.7 strong filter: a flat block stays flat (idempotent). | ||
| 1871 | + #[test] | ||
| 1872 | + fn strong_filter_flat_is_idempotent() { | ||
| 1873 | + let s = [100; 4]; | ||
| 1874 | + let out = filter_luma_sample(s, s, 2, 0, 0, 6, 8); | ||
| 1875 | + assert_eq!(out.ndp, 3); | ||
| 1876 | + assert_eq!(out.ndq, 3); | ||
| 1877 | + assert_eq!(out.p, [100, 100, 100]); | ||
| 1878 | + assert_eq!(out.q, [100, 100, 100]); | ||
| 1879 | + } | ||
| 1880 | + | ||
| 1881 | + /// §8.7.2.5.7 strong filter clips each output to ±2·tC of the input. | ||
| 1882 | + #[test] | ||
| 1883 | + fn strong_filter_clips_to_two_tc() { | ||
| 1884 | + // A hard step: p side 0, q side 255. tC=2 ⇒ p0' clipped to | ||
| 1885 | + // p0+2·tC = 0+4 = 4; q0' clipped to q0−2·tC = 255−4 = 251. | ||
| 1886 | + let out = filter_luma_sample([0, 0, 0, 0], [255, 255, 255, 255], 2, 0, 0, 2, 8); | ||
| 1887 | + assert_eq!(out.p[0], 4); | ||
| 1888 | + assert_eq!(out.q[0], 251); | ||
| 1889 | + } | ||
| 1890 | + | ||
| 1891 | + /// §8.7.2.5.7 weak filter: small ramp, dEp=dEq=0 filters only p0/q0. | ||
| 1892 | + /// p0=98,q0=102,p1=q1=100 ⇒ δ=(9·4−3·0+8)>>4=2; |δ|<10·tC; clamp to | ||
| 1893 | + /// [−tC,tC]=2 ⇒ p0'=100, q0'=100; nDp=nDq=1. | ||
| 1894 | + #[test] | ||
| 1895 | + fn weak_filter_centres_small_step() { | ||
| 1896 | + let out = filter_luma_sample([98, 100, 100, 100], [102, 100, 100, 100], 1, 0, 0, 5, 8); | ||
| 1897 | + assert_eq!(out.ndp, 1); | ||
| 1898 | + assert_eq!(out.ndq, 1); | ||
| 1899 | + assert_eq!(out.p[0], 100); | ||
| 1900 | + assert_eq!(out.q[0], 100); | ||
| 1901 | + } | ||
| 1902 | + | ||
| 1903 | + /// §8.7.2.5.7 weak filter no-op when |δ| ≥ 10·tC. | ||
| 1904 | + #[test] | ||
| 1905 | + fn weak_filter_skips_large_delta() { | ||
| 1906 | + // Big step with tiny tC ⇒ |δ| ≥ 10·tC ⇒ nDp=nDq=0, no change. | ||
| 1907 | + let out = filter_luma_sample([0, 0, 0, 0], [255, 255, 255, 255], 1, 1, 1, 1, 8); | ||
| 1908 | + assert_eq!(out.ndp, 0); | ||
| 1909 | + assert_eq!(out.ndq, 0); | ||
| 1910 | + assert_eq!(out.p[0], 0); | ||
| 1911 | + assert_eq!(out.q[0], 255); | ||
| 1912 | + } | ||
| 1913 | + | ||
| 1914 | + // ----- §8.7.2.5.3 edge decision + §8.7.2.5.5 / .8 chroma ----- | ||
| 1915 | + | ||
| 1916 | + /// §8.7.2.5.3: a perfectly flat edge (d=0 < β) with no step picks the | ||
| 1917 | + /// strong filter (dE=2) and sets dEp=dEq=1 (dp=dq=0 < threshold). | ||
| 1918 | + #[test] | ||
| 1919 | + fn edge_decision_flat_is_strong() { | ||
| 1920 | + let flat = [[128, 128], [128, 128], [128, 128], [128, 128]]; | ||
| 1921 | + let dec = luma_edge_decision(flat, flat, 32, 6); | ||
| 1922 | + assert_eq!(dec.de, 2); | ||
| 1923 | + assert_eq!(dec.dep, 1); | ||
| 1924 | + assert_eq!(dec.deq, 1); | ||
| 1925 | + } | ||
| 1926 | + | ||
| 1927 | + /// §8.7.2.5.3: a large hard step (d ≥ β) leaves dE=0 (no filtering). | ||
| 1928 | + #[test] | ||
| 1929 | + fn edge_decision_hard_step_no_filter() { | ||
| 1930 | + // p side ramps strongly so the second differences make d ≥ β. | ||
| 1931 | + let p = [[0, 0], [60, 60], [0, 0], [0, 0]]; | ||
| 1932 | + let q = [[255, 255], [255, 255], [255, 255], [255, 255]]; | ||
| 1933 | + let dec = luma_edge_decision(p, q, 8, 2); | ||
| 1934 | + assert_eq!(dec.de, 0); | ||
| 1935 | + assert_eq!(dec.dep, 0); | ||
| 1936 | + assert_eq!(dec.deq, 0); | ||
| 1937 | + } | ||
| 1938 | + | ||
| 1939 | + /// §8.7.2.5.3: a smooth region that passes d<β but fails the strong | ||
| 1940 | + /// per-sample decision (a moderate boundary step) selects the weak | ||
| 1941 | + /// filter (dE=1). | ||
| 1942 | + #[test] | ||
| 1943 | + fn edge_decision_moderate_step_is_weak() { | ||
| 1944 | + // Flat halves with a step at the boundary: second differences are | ||
| 1945 | + // 0 (d=0<β) but |p0−q0| is large ⇒ luma_sample_decision fails. | ||
| 1946 | + let p = [[100, 100], [100, 100], [100, 100], [100, 100]]; | ||
| 1947 | + let q = [[140, 140], [140, 140], [140, 140], [140, 140]]; | ||
| 1948 | + let dec = luma_edge_decision(p, q, 64, 4); | ||
| 1949 | + assert_eq!(dec.de, 1); | ||
| 1950 | + } | ||
| 1951 | + | ||
| 1952 | + /// Table 8-10 (4:2:0) chroma-QP mapping breakpoints. | ||
| 1953 | + #[test] | ||
| 1954 | + fn table_8_10_chroma_qpc() { | ||
| 1955 | + assert_eq!(chroma_qpc_420(29), 29); | ||
| 1956 | + assert_eq!(chroma_qpc_420(30), 29); | ||
| 1957 | + assert_eq!(chroma_qpc_420(35), 33); | ||
| 1958 | + assert_eq!(chroma_qpc_420(43), 37); | ||
| 1959 | + assert_eq!(chroma_qpc_420(44), 38); | ||
| 1960 | + assert_eq!(chroma_qpc_420(51), 45); | ||
| 1961 | + } | ||
| 1962 | + | ||
| 1963 | + /// §8.7.2.5.5 chroma tC: 4:2:0, QpY=37 both sides, no offsets. | ||
| 1964 | + /// qPi=37 ⇒ QpC=34 (Table 8-10) ⇒ Q=34+2=36 ⇒ tC′=4, tC=4 at 8-bit. | ||
| 1965 | + #[test] | ||
| 1966 | + fn chroma_tc_420_8bit() { | ||
| 1967 | + assert_eq!(chroma_tc(37, 37, 0, 1, 0, 8), 4); | ||
| 1968 | + // 4:4:4 (chroma_array_type=3): QpC=Min(qPi,51)=37 ⇒ Q=39 ⇒ tC′=5. | ||
| 1969 | + assert_eq!(chroma_tc(37, 37, 0, 3, 0, 8), 5); | ||
| 1970 | + // 10-bit scales by 1<<(BitDepthC−8)=4. | ||
| 1971 | + assert_eq!(chroma_tc(37, 37, 0, 1, 0, 10), 4 * 4); | ||
| 1972 | + } | ||
| 1973 | + | ||
| 1974 | + /// §8.7.2.5.8 chroma sample filter: a flat edge is unchanged. | ||
| 1975 | + #[test] | ||
| 1976 | + fn chroma_filter_flat_unchanged() { | ||
| 1977 | + let (p0, q0) = filter_chroma_sample([100, 100], [100, 100], 6, 8); | ||
| 1978 | + assert_eq!(p0, 100); | ||
| 1979 | + assert_eq!(q0, 100); | ||
| 1980 | + } | ||
| 1981 | + | ||
| 1982 | + /// §8.7.2.5.8 chroma sample filter centres a small step and clips δ. | ||
| 1983 | + /// p0=98,q0=102,p1=q1=100 ⇒ δ=((4·4)+0+4)>>3 = 20>>3 = 2 ⇒ clamp 2 ⇒ | ||
| 1984 | + /// p0'=100, q0'=100. | ||
| 1985 | + #[test] | ||
| 1986 | + fn chroma_filter_small_step() { | ||
| 1987 | + let (p0, q0) = filter_chroma_sample([98, 100], [102, 100], 6, 8); | ||
| 1988 | + assert_eq!(p0, 100); | ||
| 1989 | + assert_eq!(q0, 100); | ||
| 1990 | + // tC clamp: hard step 0/255, tC=3 ⇒ δ clamped to 3. | ||
| 1991 | + let (p0, q0) = filter_chroma_sample([0, 0], [255, 255], 3, 8); | ||
| 1992 | + assert_eq!(p0, 3); | ||
| 1993 | + assert_eq!(q0, 252); | ||
| 1994 | + } | ||
| 1995 | + | ||
| 1996 | + // ----- §8.7.2.5.4 / .5 plane-level block-edge filtering ----- | ||
| 1997 | + | ||
| 1998 | + /// A vertical edge at plane `(x, y)`. | ||
| 1999 | + fn vpos(x: usize, y: usize) -> EdgePos { | ||
| 2000 | + EdgePos { | ||
| @@ -0,0 +1,349 @@ | |||
| 1 | +//! Picture-sequence decode state machine: the §8.3.1 → §8.3.2 → §8.3.4 → | ||
| 2 | +//! §8.3.5 per-picture chain that ties the [`crate::poc`] POC derivation | ||
| 3 | +//! and the [`crate::dpb`] decoded-picture buffer together. | ||
| 4 | +//! | ||
| 5 | +//! [`PictureSequenceState`] threads the cross-picture state — the | ||
| 6 | +//! [`crate::poc::PocState`] (`prevTid0Pic`) and the [`crate::dpb::Dpb`] — | ||
| 7 | +//! across a coded video sequence. For each coded picture the driver: | ||
| 8 | +//! | ||
| 9 | +//! 1. derives `PicOrderCntVal` (§8.3.1) from the picture's `NalKind`, | ||
| 10 | +//! `TemporalId`, `NoRaslOutputFlag` and `slice_pic_order_cnt_lsb`; | ||
| 11 | +//! 2. builds the five §8.3.2 RPS POC lists and applies the §8.3.2 marking | ||
| 12 | +//! to the DPB, resolving the RPS to concrete DPB entries; | ||
| 13 | +//! 3. for a P / B slice, constructs `RefPicList0` / `RefPicList1` (§8.3.4) | ||
| 14 | +//! and selects the §8.3.5 `ColPic` + `NoBackwardPredFlag` for temporal | ||
| 15 | +//! MV prediction. | ||
| 16 | +//! | ||
| 17 | +//! After the picture's samples + per-PU motion field are reconstructed, | ||
| 18 | +//! [`PictureSequenceState::store_picture`] inserts it into the DPB as a | ||
| 19 | +//! short-term reference, completing the per-picture cycle. | ||
| 20 | + | ||
| 21 | +use crate::dpb::{ | ||
| 22 | + build_rps_poc_lists, no_backward_pred_flag, select_col_pic, Dpb, DpbEntry, LongTermEntry, | ||
| 23 | + Marking, RefPicListParams, RefPicLists, ResolvedRps, | ||
| 24 | +}; | ||
| 25 | +use crate::motion::MotionField; | ||
| 26 | +use crate::picture::Picture; | ||
| 27 | +use crate::poc::{NalKind, PicOrderCnt, PocState}; | ||
| 28 | +use crate::sps::MaterializedShortTermRefPicSet; | ||
| 29 | + | ||
| 30 | +/// The per-picture §8.3 inputs the [`PictureSequenceState`] driver needs, | ||
| 31 | +/// resolved from the picture's NAL header + activated SPS + parsed slice | ||
| 32 | +/// segment header. | ||
| 33 | +#[derive(Debug, Clone)] | ||
| 34 | +pub struct PictureHeaderInfo { | ||
| 35 | + /// The picture's `nal_unit_type` classification. | ||
| 36 | + pub nal_kind: NalKind, | ||
| 37 | + /// `TemporalId`. | ||
| 38 | + pub temporal_id: u8, | ||
| 39 | + /// `nuh_layer_id`. | ||
| 40 | + pub layer_id: u8, | ||
| 41 | + /// `NoRaslOutputFlag`. | ||
| 42 | + pub no_rasl_output: bool, | ||
| 43 | + /// `slice_pic_order_cnt_lsb` (0 for an IDR). | ||
| 44 | + pub poc_lsb: u32, | ||
| 45 | + /// `MaxPicOrderCntLsb` from the active SPS. | ||
| 46 | + pub max_poc_lsb: u32, | ||
| 47 | + /// The current picture's materialized short-term RPS | ||
| 48 | + /// (`DeltaPocS0` / `UsedByCurrPicS0` / …). | ||
| 49 | + pub short_term_rps: MaterializedShortTermRefPicSet, | ||
| 50 | + /// The current picture's long-term RPS entries (§7.4.7.1-resolved). | ||
| 51 | + pub long_term: Vec<LongTermEntry>, | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// The §8.3 per-picture decode outputs the slice / CU decode then uses. | ||
| 55 | +#[derive(Debug, Clone)] | ||
| 56 | +pub struct PictureRefState { | ||
| 57 | + /// The derived `PicOrderCntVal` (§8.3.1). | ||
| 58 | + pub poc: PicOrderCnt, | ||
| 59 | + /// The §8.3.2 RPS resolved to DPB entry indices. | ||
| 60 | + pub rps: ResolvedRps, | ||
| 61 | + /// `RefPicList0` / `RefPicList1` (§8.3.4), `None` for an I slice. | ||
| 62 | + pub ref_pic_lists: Option<RefPicLists>, | ||
| 63 | + /// `ColPic` (§8.3.5) — DPB index of the collocated picture, when | ||
| 64 | + /// `slice_temporal_mvp_enabled_flag` and a P / B slice selected one. | ||
| 65 | + pub col_pic: Option<usize>, | ||
| 66 | + /// `NoBackwardPredFlag` (§8.3.5). | ||
| 67 | + pub no_backward_pred: bool, | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// The per-slice §8.3.4 / §8.3.5 inputs (the reference-list sizing + the | ||
| 71 | +/// collocated-picture selectors from the slice segment header). | ||
| 72 | +#[derive(Debug, Clone, Copy)] | ||
| 73 | +pub struct SliceRefParams { | ||
| 74 | + /// `true` for a P or B slice (builds reference lists). | ||
| 75 | + pub is_inter: bool, | ||
| 76 | + /// `true` for a B slice (builds `RefPicList1`). | ||
| 77 | + pub is_b: bool, | ||
| 78 | + /// `num_ref_idx_l0_active_minus1`. | ||
| 79 | + pub num_ref_idx_l0_active_minus1: u32, | ||
| 80 | + /// `num_ref_idx_l1_active_minus1`. | ||
| 81 | + pub num_ref_idx_l1_active_minus1: u32, | ||
| 82 | + /// `NumPicTotalCurr` (§7.4.7.2). | ||
| 83 | + pub num_pic_total_curr: u32, | ||
| 84 | + /// `slice_temporal_mvp_enabled_flag`. | ||
| 85 | + pub temporal_mvp_enabled: bool, | ||
| 86 | + /// `collocated_from_l0_flag` (inferred 1 for a P slice). | ||
| 87 | + pub collocated_from_l0_flag: bool, | ||
| 88 | + /// `collocated_ref_idx` (inferred 0 when absent). | ||
| 89 | + pub collocated_ref_idx: u32, | ||
| 90 | + /// `pps_curr_pic_ref_enabled_flag` — the §8.3.4 currPic append | ||
| 91 | + /// (intra block copy). | ||
| 92 | + pub curr_pic_ref_enabled: bool, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// The cross-picture decode state for one coded video sequence. | ||
| 96 | +#[derive(Debug, Default)] | ||
| 97 | +pub struct PictureSequenceState { | ||
| 98 | + poc_state: PocState, | ||
| 99 | + dpb: Dpb, | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +impl PictureSequenceState { | ||
| 103 | + /// A fresh state at the start of a coded video sequence. | ||
| 104 | + #[must_use] | ||
| 105 | + pub fn new() -> Self { | ||
| 106 | + Self::default() | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + /// Borrow the decoded-picture buffer (reference-picture inspection). | ||
| 110 | + #[must_use] | ||
| 111 | + pub fn dpb(&self) -> &Dpb { | ||
| 112 | + &self.dpb | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + /// §8.3.1 → §8.3.2 → §8.3.4 → §8.3.5 — run the per-picture reference | ||
| 116 | + /// derivation for a picture about to be decoded. | ||
| 117 | + /// | ||
| 118 | + /// `header` carries the POC + RPS inputs; `slice` carries the | ||
| 119 | + /// reference-list / collocated-picture selectors. The returned | ||
| 120 | + /// [`PictureRefState`] is consumed by the slice / CU decode (its | ||
| 121 | + /// `RefPicList0` / `ColPic` resolve `RefPicListX[ refIdx ]` and the | ||
| 122 | + /// temporal-MV collocated picture). | ||
| 123 | + pub fn begin_picture( | ||
| 124 | + &mut self, | ||
| 125 | + header: &PictureHeaderInfo, | ||
| 126 | + slice: &SliceRefParams, | ||
| 127 | + ) -> PictureRefState { | ||
| 128 | + // Step 1 — §8.3.1 POC. | ||
| 129 | + let poc = self.poc_state.decode_picture_poc( | ||
| 130 | + header.nal_kind, | ||
| 131 | + header.temporal_id, | ||
| 132 | + header.no_rasl_output, | ||
| 133 | + header.poc_lsb, | ||
| 134 | + header.max_poc_lsb, | ||
| 135 | + ); | ||
| 136 | + | ||
| 137 | + // Step 2 — §8.3.2 RPS POC lists + DPB marking. | ||
| 138 | + let lists = build_rps_poc_lists( | ||
| 139 | + header.nal_kind.is_idr(), | ||
| 140 | + poc.val, | ||
| 141 | + header.max_poc_lsb, | ||
| 142 | + &header.short_term_rps, | ||
| 143 | + &header.long_term, | ||
| 144 | + ); | ||
| 145 | + let is_irap_no_rasl = header.nal_kind.is_irap() && header.no_rasl_output; | ||
| 146 | + let rps = self | ||
| 147 | + .dpb | ||
| 148 | + .apply_rps(is_irap_no_rasl, header.layer_id, &lists, header.max_poc_lsb); | ||
| 149 | + | ||
| 150 | + // Step 3 — §8.3.4 reference picture lists (P / B only). | ||
| 151 | + let ref_pic_lists = if slice.is_inter { | ||
| 152 | + Some(self.dpb.build_ref_pic_lists( | ||
| 153 | + &rps, | ||
| 154 | + &RefPicListParams { | ||
| 155 | + num_ref_idx_l0_active_minus1: slice.num_ref_idx_l0_active_minus1, | ||
| 156 | + num_ref_idx_l1_active_minus1: slice.num_ref_idx_l1_active_minus1, | ||
| 157 | + num_pic_total_curr: slice.num_pic_total_curr, | ||
| 158 | + is_b: slice.is_b, | ||
| 159 | + list_entry_l0: None, | ||
| 160 | + list_entry_l1: None, | ||
| 161 | + curr_pic_ref_enabled: slice.curr_pic_ref_enabled, | ||
| 162 | + }, | ||
| 163 | + )) | ||
| 164 | + } else { | ||
| 165 | + None | ||
| 166 | + }; | ||
| 167 | + | ||
| 168 | + // Step 4 — §8.3.5 ColPic + NoBackwardPredFlag. | ||
| 169 | + let (col_pic, no_backward_pred) = match &ref_pic_lists { | ||
| 170 | + Some(rpl) if slice.temporal_mvp_enabled => ( | ||
| 171 | + select_col_pic( | ||
| 172 | + rpl, | ||
| 173 | + slice.is_b, | ||
| 174 | + slice.collocated_from_l0_flag, | ||
| 175 | + slice.collocated_ref_idx, | ||
| 176 | + ), | ||
| 177 | + no_backward_pred_flag(&self.dpb, rpl, poc.val), | ||
| 178 | + ), | ||
| 179 | + Some(rpl) => (None, no_backward_pred_flag(&self.dpb, rpl, poc.val)), | ||
| 180 | + None => (None, true), | ||
| 181 | + }; | ||
| 182 | + | ||
| 183 | + PictureRefState { | ||
| 184 | + poc, | ||
| 185 | + rps, | ||
| 186 | + ref_pic_lists, | ||
| 187 | + col_pic, | ||
| 188 | + no_backward_pred, | ||
| 189 | + } | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + /// Insert a freshly-decoded picture into the DPB as a short-term | ||
| 193 | + /// reference, completing the per-picture cycle. `picture` are the | ||
| 194 | + /// reconstructed (in-loop-filtered) samples; `motion` is the per-PU | ||
| 195 | + /// motion field for the §8.5.3.2.9 collocated-MV derivation of future | ||
| 196 | + /// pictures. | ||
| 197 | + pub fn store_picture( | ||
| 198 | + &mut self, | ||
| 199 | + poc: PicOrderCnt, | ||
| 200 | + layer_id: u8, | ||
| 201 | + picture: Picture, | ||
| 202 | + motion: MotionField, | ||
| 203 | + ) { | ||
| 204 | + self.dpb.insert(DpbEntry { | ||
| 205 | + poc: poc.val, | ||
| 206 | + layer_id, | ||
| 207 | + marking: Marking::ShortTerm, | ||
| 208 | + picture, | ||
| 209 | + motion, | ||
| 210 | + }); | ||
| 211 | + } | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +#[cfg(test)] | ||
| 215 | +mod tests { | ||
| 216 | + use super::*; | ||
| 217 | + | ||
| 218 | + fn empty_rps() -> MaterializedShortTermRefPicSet { | ||
| 219 | + MaterializedShortTermRefPicSet { | ||
| 220 | + delta_poc_s0: vec![], | ||
| 221 | + used_by_curr_pic_s0: vec![], | ||
| 222 | + delta_poc_s1: vec![], | ||
| 223 | + used_by_curr_pic_s1: vec![], | ||
| 224 | + } | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + fn idr_header() -> PictureHeaderInfo { | ||
| 228 | + PictureHeaderInfo { | ||
| 229 | + nal_kind: NalKind::new(NalKind::IDR_N_LP), | ||
| 230 | + temporal_id: 0, | ||
| 231 | + layer_id: 0, | ||
| 232 | + no_rasl_output: true, | ||
| 233 | + poc_lsb: 0, | ||
| 234 | + max_poc_lsb: 256, | ||
| 235 | + short_term_rps: empty_rps(), | ||
| 236 | + long_term: vec![], | ||
| 237 | + } | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + fn i_slice() -> SliceRefParams { | ||
| 241 | + SliceRefParams { | ||
| 242 | + is_inter: false, | ||
| 243 | + is_b: false, | ||
| 244 | + num_ref_idx_l0_active_minus1: 0, | ||
| 245 | + num_ref_idx_l1_active_minus1: 0, | ||
| 246 | + num_pic_total_curr: 0, | ||
| 247 | + temporal_mvp_enabled: false, | ||
| 248 | + collocated_from_l0_flag: true, | ||
| 249 | + collocated_ref_idx: 0, | ||
| 250 | + curr_pic_ref_enabled: false, | ||
| 251 | + } | ||
| 252 | + } | ||
| 253 | + | ||
| 254 | + #[test] | ||
| 255 | + fn idr_then_p_frame_resolves_ref_pic_list() { | ||
| 256 | + let mut st = PictureSequenceState::new(); | ||
| 257 | + // IDR (POC 0), I slice, no references. | ||
| 258 | + let idr = st.begin_picture(&idr_header(), &i_slice()); | ||
| 259 | + assert_eq!(idr.poc.val, 0); | ||
| 260 | + assert!(idr.ref_pic_lists.is_none()); | ||
| 261 | + st.store_picture( | ||
| 262 | + idr.poc, | ||
| 263 | + 0, | ||
| 264 | + Picture::new(16, 16, 1, 8, 8), | ||
| 265 | + MotionField::new(16, 16), | ||
| 266 | + ); | ||
| 267 | + | ||
| 268 | + // P frame (POC 1), one short-term-before ref at POC 0. | ||
| 269 | + let p_header = PictureHeaderInfo { | ||
| 270 | + nal_kind: NalKind::new(NalKind::TRAIL_R), | ||
| 271 | + no_rasl_output: false, | ||
| 272 | + poc_lsb: 1, | ||
| 273 | + short_term_rps: MaterializedShortTermRefPicSet { | ||
| 274 | + delta_poc_s0: vec![-1], | ||
| 275 | + used_by_curr_pic_s0: vec![true], | ||
| 276 | + delta_poc_s1: vec![], | ||
| 277 | + used_by_curr_pic_s1: vec![], | ||
| 278 | + }, | ||
| 279 | + ..idr_header() | ||
| 280 | + }; | ||
| 281 | + let p_slice = SliceRefParams { | ||
| 282 | + is_inter: true, | ||
| 283 | + num_pic_total_curr: 1, | ||
| 284 | + ..i_slice() | ||
| 285 | + }; | ||
| 286 | + let p = st.begin_picture(&p_header, &p_slice); | ||
| 287 | + assert_eq!(p.poc.val, 1); | ||
| 288 | + let rpl = p.ref_pic_lists.expect("P slice builds RefPicList0"); | ||
| 289 | + // RefPicList0[0] points at the IDR (DPB index 0). | ||
| 290 | + assert_eq!(rpl.list0, vec![Some(0)]); | ||
| 291 | + // The IDR stays short-term (it is in the P frame's RPS). | ||
| 292 | + assert_eq!(st.dpb().entries()[0].marking, Marking::ShortTerm); | ||
| 293 | + // NoBackwardPredFlag: the only ref (POC 0) is in the past of POC 1. | ||
| 294 | + assert!(p.no_backward_pred); | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + #[test] | ||
| 298 | + fn temporal_mvp_selects_col_pic() { | ||
| 299 | + let mut st = PictureSequenceState::new(); | ||
| 300 | + let idr = st.begin_picture(&idr_header(), &i_slice()); | ||
| 301 | + st.store_picture( | ||
| 302 | + idr.poc, | ||
| 303 | + 0, | ||
| 304 | + Picture::new(16, 16, 1, 8, 8), | ||
| 305 | + MotionField::new(16, 16), | ||
| 306 | + ); | ||
| 307 | + | ||
| 308 | + let p_header = PictureHeaderInfo { | ||
| 309 | + nal_kind: NalKind::new(NalKind::TRAIL_R), | ||
| 310 | + no_rasl_output: false, | ||
| 311 | + poc_lsb: 1, | ||
| 312 | + short_term_rps: MaterializedShortTermRefPicSet { | ||
| 313 | + delta_poc_s0: vec![-1], | ||
| 314 | + used_by_curr_pic_s0: vec![true], | ||
| 315 | + delta_poc_s1: vec![], | ||
| 316 | + used_by_curr_pic_s1: vec![], | ||
| 317 | + }, | ||
| 318 | + ..idr_header() | ||
| 319 | + }; | ||
| 320 | + let p_slice = SliceRefParams { | ||
| 321 | + is_inter: true, | ||
| 322 | + num_pic_total_curr: 1, | ||
| 323 | + temporal_mvp_enabled: true, | ||
| 324 | + collocated_from_l0_flag: true, | ||
| 325 | + collocated_ref_idx: 0, | ||
| 326 | + curr_pic_ref_enabled: false, | ||
| 327 | + ..i_slice() | ||
| 328 | + }; | ||
| 329 | + let p = st.begin_picture(&p_header, &p_slice); | ||
| 330 | + // ColPic = RefPicList0[0] = the IDR at DPB index 0. | ||
| 331 | + assert_eq!(p.col_pic, Some(0)); | ||
| 332 | + } | ||
| 333 | + | ||
| 334 | + #[test] | ||
| 335 | + fn second_idr_unmarks_prior_references() { | ||
| 336 | + let mut st = PictureSequenceState::new(); | ||
| 337 | + let idr = st.begin_picture(&idr_header(), &i_slice()); | ||
| 338 | + st.store_picture( | ||
| 339 | + idr.poc, | ||
| 340 | + 0, | ||
| 341 | + Picture::new(16, 16, 1, 8, 8), | ||
| 342 | + MotionField::new(16, 16), | ||
| 343 | + ); | ||
| 344 | + // A second IDR with NoRaslOutputFlag == 1 marks the prior IDR | ||
| 345 | + // "unused for reference". | ||
| 346 | + let _ = st.begin_picture(&idr_header(), &i_slice()); | ||
| 347 | + assert_eq!(st.dpb().entries()[0].marking, Marking::Unused); | ||
| 348 | + } | ||
| 349 | +} | ||
| @@ -0,0 +1,214 @@ | |||
| 1 | +//! Registry decoder — the [`oxideav_core::Decoder`] contract over the | ||
| 2 | +//! whole-bitstream [`crate::sequence`] driver. | ||
| 3 | +//! | ||
| 4 | +//! [`make_decoder`] is the direct factory endpoint (the crate's | ||
| 5 | +//! historical direct-API convention); [`crate::register`] wires the | ||
| 6 | +//! same factory into the [`oxideav_core`] codec registry under the | ||
| 7 | +//! `"h265"` / `"hevc"` ids and the common container tags. | ||
| 8 | +//! | ||
| 9 | +//! Packets carry either Annex B byte-stream chunks (start-code | ||
| 10 | +//! delimited NAL units) or, when `CodecParameters::extradata` is an | ||
| 11 | +//! `hvcC` / `HEVCDecoderConfigurationRecord` (ISO/IEC 14496-15 | ||
| 12 | +//! §8.3.3.1), length-prefixed NAL runs as ISO-BMFF samples carry them. | ||
| 13 | +//! Extradata in either form is fed ahead of the first packet so | ||
| 14 | +//! out-of-band parameter sets activate. Output frames come in output | ||
| 15 | +//! (PicOrderCntVal) order, with packet PTS values re-attached in | ||
| 16 | +//! ascending order; an empty packet flushes the reorder queue. | ||
| 17 | + | ||
| 18 | +use std::collections::BinaryHeap; | ||
| 19 | +use std::collections::VecDeque; | ||
| 20 | + | ||
| 21 | +use oxideav_core::{ | ||
| 22 | + CodecId, CodecParameters, Decoder, Error, Frame, Packet, Result, VideoFrame, VideoPlane, | ||
| 23 | +}; | ||
| 24 | + | ||
| 25 | +use crate::hvcc::{extradata_is_hvcc, parse_hvcc, split_length_prefixed}; | ||
| 26 | +use crate::picture::{Picture, Plane}; | ||
| 27 | +use crate::sequence::{DecodedFrame, SequenceDecoder}; | ||
| 28 | + | ||
| 29 | +/// The default reorder depth when no SPS has been activated yet (the | ||
| 30 | +/// §7.4.3.2.1 `sps_max_num_reorder_pics` bound once one has). | ||
| 31 | +const DEFAULT_REORDER: usize = 8; | ||
| 32 | + | ||
| 33 | +/// H.265 / HEVC Annex B streaming decoder. | ||
| 34 | +pub struct H265Decoder { | ||
| 35 | + codec_id: CodecId, | ||
| 36 | + seq: SequenceDecoder, | ||
| 37 | + /// Decoded pictures not yet emitted, sorted on demand by | ||
| 38 | + /// `(cvs_index, poc)`. | ||
| 39 | + reorder: Vec<DecodedFrame>, | ||
| 40 | + /// Frames ready to hand out. | ||
| 41 | + ready: VecDeque<Frame>, | ||
| 42 | + /// Min-heap of packet PTS values, re-attached in output order. | ||
| 43 | + pts_queue: BinaryHeap<std::cmp::Reverse<i64>>, | ||
| 44 | + /// `Some(n)` when the extradata was an `hvcC` record: packets are | ||
| 45 | + /// length-prefixed NAL runs with `n`-byte big-endian sizes | ||
| 46 | + /// (ISO/IEC 14496-15 §8.3.3.1.3 `lengthSizeMinusOne + 1`). | ||
| 47 | + /// `None` for Annex B packets. | ||
| 48 | + nal_length_size: Option<usize>, | ||
| 49 | + flushed: bool, | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +impl std::fmt::Debug for H265Decoder { | ||
| 53 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 54 | + f.debug_struct("H265Decoder") | ||
| 55 | + .field("codec_id", &self.codec_id) | ||
| 56 | + .field("reorder", &self.reorder.len()) | ||
| 57 | + .field("ready", &self.ready.len()) | ||
| 58 | + .finish() | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// Direct factory endpoint: construct the software H.265 decoder. | ||
| 63 | +/// | ||
| 64 | +/// The `extradata` form selects the packet framing: an `hvcC` | ||
| 65 | +/// (`HEVCDecoderConfigurationRecord`) extradata activates its carried | ||
| 66 | +/// parameter sets and switches packets to length-prefixed NAL runs; | ||
| 67 | +/// Annex B extradata (or none) keeps start-code framing. | ||
| 68 | +/// | ||
| 69 | +/// # Errors | ||
| 70 | +/// [`Error::InvalidData`] when the `extradata` fails to parse. | ||
| 71 | +pub fn make_decoder(params: &CodecParameters) -> Result<Box<dyn Decoder>> { | ||
| 72 | + let mut seq = SequenceDecoder::new(); | ||
| 73 | + let mut nal_length_size = None; | ||
| 74 | + if !params.extradata.is_empty() { | ||
| 75 | + if extradata_is_hvcc(¶ms.extradata) { | ||
| 76 | + // hvcC record: out-of-band VPS/SPS/PPS (+ SEI) arrays. | ||
| 77 | + let rec = parse_hvcc(¶ms.extradata) | ||
| 78 | + .map_err(|e| Error::InvalidData(format!("h265 hvcC extradata: {e}")))?; | ||
| 79 | + for unit in rec.nal_units { | ||
| 80 | + seq.push_nal_unit(unit) | ||
| 81 | + .map_err(|e| Error::InvalidData(format!("h265 hvcC extradata: {e}")))?; | ||
| 82 | + } | ||
| 83 | + nal_length_size = Some(rec.length_size); | ||
| 84 | + } else { | ||
| 85 | + // Out-of-band parameter sets in Annex B form. | ||
| 86 | + seq.push_annexb(¶ms.extradata) | ||
| 87 | + .map_err(|e| Error::InvalidData(format!("h265 extradata: {e}")))?; | ||
| 88 | + } | ||
| 89 | + } | ||
| 90 | + Ok(Box::new(H265Decoder { | ||
| 91 | + codec_id: params.codec_id.clone(), | ||
| 92 | + seq, | ||
| 93 | + reorder: Vec::new(), | ||
| 94 | + ready: VecDeque::new(), | ||
| 95 | + pts_queue: BinaryHeap::new(), | ||
| 96 | + nal_length_size, | ||
| 97 | + flushed: false, | ||
| 98 | + })) | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +impl H265Decoder { | ||
| 102 | + /// Move decoded pictures into the reorder buffer and emit every | ||
| 103 | + /// frame that is guaranteed next in output order. | ||
| 104 | + fn drain(&mut self, flush: bool) { | ||
| 105 | + self.reorder.extend(self.seq.take_decoded()); | ||
| 106 | + self.reorder.sort_by_key(|f| (f.cvs_index, f.poc)); | ||
| 107 | + let depth = if flush { | ||
| 108 | + 0 | ||
| 109 | + } else { | ||
| 110 | + self.seq | ||
| 111 | + .max_num_reorder_pics() | ||
| 112 | + .map_or(DEFAULT_REORDER, |n| n as usize) | ||
| 113 | + }; | ||
| 114 | + while self.reorder.len() > depth { | ||
| 115 | + let f = self.reorder.remove(0); | ||
| 116 | + if !f.output { | ||
| 117 | + continue; | ||
| 118 | + } | ||
| 119 | + let pts = self.pts_queue.pop().map(|r| r.0); | ||
| 120 | + self.ready | ||
| 121 | + .push_back(Frame::Video(video_frame(&f.picture, pts))); | ||
| 122 | + } | ||
| 123 | + } | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +impl Decoder for H265Decoder { | ||
| 127 | + fn codec_id(&self) -> &CodecId { | ||
| 128 | + &self.codec_id | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + fn send_packet(&mut self, packet: &Packet) -> Result<()> { | ||
| 132 | + if packet.data.is_empty() { | ||
| 133 | + // An empty packet is treated as a flush signal too. | ||
| 134 | + return self.flush(); | ||
| 135 | + } | ||
| 136 | + if let Some(pts) = packet.pts { | ||
| 137 | + self.pts_queue.push(std::cmp::Reverse(pts)); | ||
| 138 | + } | ||
| 139 | + if let Some(length_size) = self.nal_length_size { | ||
| 140 | + let units = split_length_prefixed(&packet.data, length_size) | ||
| 141 | + .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?; | ||
| 142 | + for unit in units { | ||
| 143 | + self.seq | ||
| 144 | + .push_nal_unit(unit) | ||
| 145 | + .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?; | ||
| 146 | + } | ||
| 147 | + } else { | ||
| 148 | + self.seq | ||
| 149 | + .push_annexb(&packet.data) | ||
| 150 | + .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?; | ||
| 151 | + } | ||
| 152 | + self.drain(false); | ||
| 153 | + Ok(()) | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + fn receive_frame(&mut self) -> Result<Frame> { | ||
| 157 | + if let Some(f) = self.ready.pop_front() { | ||
| 158 | + return Ok(f); | ||
| 159 | + } | ||
| 160 | + if self.flushed { | ||
| 161 | + if !self.reorder.is_empty() { | ||
| 162 | + self.drain(true); | ||
| 163 | + if let Some(f) = self.ready.pop_front() { | ||
| 164 | + return Ok(f); | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | + return Err(Error::Eof); | ||
| 168 | + } | ||
| 169 | + Err(Error::NeedMore) | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + fn flush(&mut self) -> Result<()> { | ||
| 173 | + // Decode any pending picture and release the reorder queue. | ||
| 174 | + self.seq | ||
| 175 | + .flush() | ||
| 176 | + .map_err(|e| Error::InvalidData(format!("h265 flush: {e}")))?; | ||
| 177 | + self.flushed = true; | ||
| 178 | + self.drain(true); | ||
| 179 | + Ok(()) | ||
| 180 | + } | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// Pack a reconstructed [`Picture`] into a [`VideoFrame`] (8-bit planes | ||
| 184 | +/// as one byte per sample; higher bit depths as little-endian 16-bit, | ||
| 185 | +/// the planar `p010le`-family layout). | ||
| 186 | +fn video_frame(pic: &Picture, pts: Option<i64>) -> VideoFrame { | ||
| 187 | + let planes = if pic.chroma_array_type() == 0 { | ||
| 188 | + vec![Plane::Luma] | ||
| 189 | + } else { | ||
| 190 | + vec![Plane::Luma, Plane::Cb, Plane::Cr] | ||
| 191 | + }; | ||
| 192 | + let wide = pic.bit_depth(Plane::Luma) > 8 | ||
| 193 | + || (pic.chroma_array_type() != 0 && pic.bit_depth(Plane::Cb) > 8); | ||
| 194 | + let mut out = Vec::with_capacity(planes.len()); | ||
| 195 | + for plane in planes { | ||
| 196 | + let (w, h) = pic.plane_dims(plane); | ||
| 197 | + let buf = pic.plane(plane); | ||
| 198 | + let mut data; | ||
| 199 | + let stride; | ||
| 200 | + if wide { | ||
| 201 | + stride = w * 2; | ||
| 202 | + data = Vec::with_capacity(w * h * 2); | ||
| 203 | + for &v in buf.iter().take(w * h) { | ||
| 204 | + data.extend_from_slice(&(v as u16).to_le_bytes()); | ||
| 205 | + } | ||
| 206 | + } else { | ||
| 207 | + stride = w; | ||
| 208 | + data = Vec::with_capacity(w * h); | ||
| 209 | + data.extend(buf.iter().take(w * h).map(|&v| v as u8)); | ||
| 210 | + } | ||
| 211 | + out.push(VideoPlane { stride, data }); | ||
| 212 | + } | ||
| 213 | + VideoFrame { pts, planes: out } | ||
| 214 | +} | ||
Diff too large; view file
| @@ -0,0 +1,833 @@ | |||
| 1 | +//! §8.3.2 reference-picture-set marking, §8.3.4 reference-picture-list | ||
| 2 | +//! construction, §8.3.5 collocated-picture selection, and the | ||
| 3 | +//! decoded-picture-buffer (DPB) storage that ties them together. | ||
| 4 | +//! | ||
| 5 | +//! A [`Dpb`] holds the previously-decoded pictures available for | ||
| 6 | +//! inter prediction of the current and future pictures. Each | ||
| 7 | +//! [`DpbEntry`] carries: | ||
| 8 | +//! | ||
| 9 | +//! * the reconstructed [`crate::picture::Picture`] samples | ||
| 10 | +//! (`refPicLXL` / `refPicLXCb` / `refPicLXCr` of §8.5.3.3.2), | ||
| 11 | +//! * its `PicOrderCntVal` (the §8.3.1 identity used to address it), | ||
| 12 | +//! * its short/long-term reference [`Marking`], | ||
| 13 | +//! * its per-PU [`crate::motion::MotionField`] (the `MvLXCol` / | ||
| 14 | +//! `PredFlagLXCol` / `RefIdxLXCol`-equivalent arrays the §8.5.3.2.9 | ||
| 15 | +//! collocated-MV derivation reads). | ||
| 16 | +//! | ||
| 17 | +//! The picture-decode driver, after deriving the current picture's POC | ||
| 18 | +//! (§8.3.1), calls [`Dpb::apply_rps`] to build the five §8.3.2 RPS lists | ||
| 19 | +//! (`RefPicSetStCurrBefore` … `RefPicSetLtFoll`) and mark every DPB | ||
| 20 | +//! picture accordingly. For a P / B slice it then calls | ||
| 21 | +//! [`Dpb::build_ref_pic_lists`] (§8.3.4) to construct `RefPicList0` / | ||
| 22 | +//! `RefPicList1`, and [`select_col_pic`] (§8.3.5) to pick the collocated | ||
| 23 | +//! picture for temporal MV prediction. | ||
| 24 | + | ||
| 25 | +use crate::motion::MotionField; | ||
| 26 | +use crate::picture::Picture; | ||
| 27 | +use crate::poc::diff_pic_order_cnt; | ||
| 28 | +use crate::sps::MaterializedShortTermRefPicSet; | ||
| 29 | + | ||
| 30 | +/// A decoded picture's reference marking (§8.3.2). Exactly one of these | ||
| 31 | +/// applies at any moment. | ||
| 32 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 33 | +pub enum Marking { | ||
| 34 | + /// "unused for reference". | ||
| 35 | + Unused, | ||
| 36 | + /// "used for short-term reference". | ||
| 37 | + ShortTerm, | ||
| 38 | + /// "used for long-term reference". | ||
| 39 | + LongTerm, | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// One decoded picture stored in the [`Dpb`]. | ||
| 43 | +#[derive(Debug)] | ||
| 44 | +pub struct DpbEntry { | ||
| 45 | + /// `PicOrderCntVal` (§8.3.1). | ||
| 46 | + pub poc: i32, | ||
| 47 | + /// `nuh_layer_id` of the picture. | ||
| 48 | + pub layer_id: u8, | ||
| 49 | + /// The current reference [`Marking`]. | ||
| 50 | + pub marking: Marking, | ||
| 51 | + /// The reconstructed sample planes (`SL` / `SCb` / `SCr`). | ||
| 52 | + pub picture: Picture, | ||
| 53 | + /// The per-PU motion field — the §8.5.3.2.9 collocated arrays | ||
| 54 | + /// (`PredFlagLXCol`, `MvLXCol`, the per-cell reference-picture POC | ||
| 55 | + /// identity standing in for `RefIdxLXCol` → `refPicListCol`). | ||
| 56 | + pub motion: MotionField, | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +impl DpbEntry { | ||
| 60 | + /// `( PicOrderCntVal & ( MaxPicOrderCntLsb − 1 ) )` — the LSB-only | ||
| 61 | + /// identity used for the §8.3.2 short-term-vs-long-term lookup of a | ||
| 62 | + /// long-term entry whose `delta_poc_msb_present_flag` is 0. | ||
| 63 | + #[inline] | ||
| 64 | + #[must_use] | ||
| 65 | + fn poc_lsb(&self, max_poc_lsb: u32) -> u32 { | ||
| 66 | + (self.poc as u32) & (max_poc_lsb - 1) | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// The five §8.3.2 RPS POC lists (equation 8-5). | ||
| 71 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | ||
| 72 | +pub struct RpsPocLists { | ||
| 73 | + /// `PocStCurrBefore`. | ||
| 74 | + pub st_curr_before: Vec<i32>, | ||
| 75 | + /// `PocStCurrAfter`. | ||
| 76 | + pub st_curr_after: Vec<i32>, | ||
| 77 | + /// `PocStFoll`. | ||
| 78 | + pub st_foll: Vec<i32>, | ||
| 79 | + /// `PocLtCurr`. | ||
| 80 | + pub lt_curr: Vec<i32>, | ||
| 81 | + /// `PocLtFoll`. | ||
| 82 | + pub lt_foll: Vec<i32>, | ||
| 83 | + /// `CurrDeltaPocMsbPresentFlag[i]` (paired with `lt_curr`). | ||
| 84 | + pub curr_delta_poc_msb_present: Vec<bool>, | ||
| 85 | + /// `FollDeltaPocMsbPresentFlag[i]` (paired with `lt_foll`). | ||
| 86 | + pub foll_delta_poc_msb_present: Vec<bool>, | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// One long-term RPS input entry — the §7.4.7.1 / §8.3.2 long-term | ||
| 90 | +/// reference, already resolved to `PocLsbLt[i]` plus the MSB-cycle block. | ||
| 91 | +#[derive(Debug, Clone, Copy)] | ||
| 92 | +pub struct LongTermEntry { | ||
| 93 | + /// `PocLsbLt[i]`. | ||
| 94 | + pub poc_lsb_lt: u32, | ||
| 95 | + /// `UsedByCurrPicLt[i]`. | ||
| 96 | + pub used_by_curr_pic_lt: bool, | ||
| 97 | + /// `delta_poc_msb_present_flag[i]`. | ||
| 98 | + pub delta_poc_msb_present: bool, | ||
| 99 | + /// `DeltaPocMsbCycleLt[i]` (the §7.4.7.1 accumulated cycle). | ||
| 100 | + pub delta_poc_msb_cycle_lt: u32, | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// Build the five §8.3.2 POC lists (equation 8-5) for the current | ||
| 104 | +/// picture from its current short-term RPS + long-term entries. | ||
| 105 | +/// | ||
| 106 | +/// `is_idr` short-circuits all five lists to empty (the §8.3.2 IDR rule). | ||
| 107 | +/// `poc` is the current `PicOrderCntVal`; `max_poc_lsb` is | ||
| 108 | +/// `MaxPicOrderCntLsb`. | ||
| 109 | +#[must_use] | ||
| 110 | +pub fn build_rps_poc_lists( | ||
| 111 | + is_idr: bool, | ||
| 112 | + poc: i32, | ||
| 113 | + max_poc_lsb: u32, | ||
| 114 | + st_rps: &MaterializedShortTermRefPicSet, | ||
| 115 | + lt_entries: &[LongTermEntry], | ||
| 116 | +) -> RpsPocLists { | ||
| 117 | + let mut out = RpsPocLists::default(); | ||
| 118 | + if is_idr { | ||
| 119 | + return out; | ||
| 120 | + } | ||
| 121 | + // Negative (S0) pics — equation 8-5 first loop. | ||
| 122 | + for (i, &delta) in st_rps.delta_poc_s0.iter().enumerate() { | ||
| 123 | + let p = poc + delta; | ||
| 124 | + if st_rps.used_by_curr_pic_s0[i] { | ||
| 125 | + out.st_curr_before.push(p); | ||
| 126 | + } else { | ||
| 127 | + out.st_foll.push(p); | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + // Positive (S1) pics — equation 8-5 second loop. | ||
| 131 | + for (i, &delta) in st_rps.delta_poc_s1.iter().enumerate() { | ||
| 132 | + let p = poc + delta; | ||
| 133 | + if st_rps.used_by_curr_pic_s1[i] { | ||
| 134 | + out.st_curr_after.push(p); | ||
| 135 | + } else { | ||
| 136 | + out.st_foll.push(p); | ||
| 137 | + } | ||
| 138 | + } | ||
| 139 | + // Long-term — equation 8-5 third loop. | ||
| 140 | + for e in lt_entries { | ||
| 141 | + let mut poc_lt = e.poc_lsb_lt as i32; | ||
| 142 | + if e.delta_poc_msb_present { | ||
| 143 | + poc_lt += poc | ||
| 144 | + - (e.delta_poc_msb_cycle_lt as i32) * (max_poc_lsb as i32) | ||
| 145 | + - (poc & (max_poc_lsb as i32 - 1)); | ||
| 146 | + } | ||
| 147 | + if e.used_by_curr_pic_lt { | ||
| 148 | + out.lt_curr.push(poc_lt); | ||
| 149 | + out.curr_delta_poc_msb_present.push(e.delta_poc_msb_present); | ||
| 150 | + } else { | ||
| 151 | + out.lt_foll.push(poc_lt); | ||
| 152 | + out.foll_delta_poc_msb_present.push(e.delta_poc_msb_present); | ||
| 153 | + } | ||
| 154 | + } | ||
| 155 | + out | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +/// The decoded-picture buffer. | ||
| 159 | +#[derive(Debug, Default)] | ||
| 160 | +pub struct Dpb { | ||
| 161 | + entries: Vec<DpbEntry>, | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +impl Dpb { | ||
| 165 | + /// An empty DPB. | ||
| 166 | + #[must_use] | ||
| 167 | + pub fn new() -> Self { | ||
| 168 | + Self::default() | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + /// Number of pictures currently stored. | ||
| 172 | + #[inline] | ||
| 173 | + #[must_use] | ||
| 174 | + pub fn len(&self) -> usize { | ||
| 175 | + self.entries.len() | ||
| 176 | + } | ||
| 177 | + | ||
| 178 | + /// Whether the DPB holds no pictures. | ||
| 179 | + #[inline] | ||
| 180 | + #[must_use] | ||
| 181 | + pub fn is_empty(&self) -> bool { | ||
| 182 | + self.entries.is_empty() | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + /// Borrow the stored entries (output / bumping inspection). | ||
| 186 | + #[must_use] | ||
| 187 | + pub fn entries(&self) -> &[DpbEntry] { | ||
| 188 | + &self.entries | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + /// Insert a freshly-decoded picture, marked "used for short-term | ||
| 192 | + /// reference" per the §8.3.2 default. The picture-decode driver calls | ||
| 193 | + /// this after reconstruction + in-loop filtering, having already run | ||
| 194 | + /// [`Dpb::apply_rps`] for the picture's own RPS. | ||
| 195 | + pub fn insert(&mut self, entry: DpbEntry) { | ||
| 196 | + self.entries.push(entry); | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + /// Find a stored picture by exact `PicOrderCntVal` and `nuh_layer_id`. | ||
| 200 | + #[must_use] | ||
| 201 | + pub fn find_by_poc(&self, poc: i32, layer_id: u8) -> Option<&DpbEntry> { | ||
| 202 | + self.entries | ||
| 203 | + .iter() | ||
| 204 | + .find(|e| e.poc == poc && e.layer_id == layer_id) | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + /// Find a short-term reference picture by exact POC (§8.3.2 step 3). | ||
| 208 | + fn find_short_term(&self, poc: i32, layer_id: u8) -> Option<usize> { | ||
| 209 | + self.entries | ||
| 210 | + .iter() | ||
| 211 | + .position(|e| e.poc == poc && e.layer_id == layer_id && e.marking == Marking::ShortTerm) | ||
| 212 | + } | ||
| 213 | + | ||
| 214 | + /// Find a long-term candidate by exact POC or by LSB-only POC | ||
| 215 | + /// (§8.3.2 step 1). | ||
| 216 | + fn find_long_term( | ||
| 217 | + &self, | ||
| 218 | + target: i32, | ||
| 219 | + msb_present: bool, | ||
| 220 | + max_poc_lsb: u32, | ||
| 221 | + layer_id: u8, | ||
| 222 | + ) -> Option<usize> { | ||
| 223 | + self.entries.iter().position(|e| { | ||
| 224 | + e.layer_id == layer_id | ||
| 225 | + && if msb_present { | ||
| 226 | + e.poc == target | ||
| 227 | + } else { | ||
| 228 | + e.poc_lsb(max_poc_lsb) == (target as u32) & (max_poc_lsb - 1) | ||
| 229 | + } | ||
| 230 | + }) | ||
| 231 | + } | ||
| 232 | + | ||
| 233 | + /// §8.3.2 — apply the reference-picture-set marking for the current | ||
| 234 | + /// picture. | ||
| 235 | + /// | ||
| 236 | + /// `is_irap_no_rasl` is `true` for an IRAP picture with | ||
| 237 | + /// `NoRaslOutputFlag == 1` (all current references become "unused"); | ||
| 238 | + /// `layer_id` is the current picture's `nuh_layer_id`; `lists` is the | ||
| 239 | + /// output of [`build_rps_poc_lists`]; `max_poc_lsb` is | ||
| 240 | + /// `MaxPicOrderCntLsb`. | ||
| 241 | + /// | ||
| 242 | + /// Returns the five resolved RPS reference-picture lists as index | ||
| 243 | + /// vectors into [`Dpb::entries`]; a `None` entry is the §8.3.2 "no | ||
| 244 | + /// reference picture". After this call every DPB picture carries its | ||
| 245 | + /// updated [`Marking`]. | ||
| 246 | + pub fn apply_rps( | ||
| 247 | + &mut self, | ||
| 248 | + is_irap_no_rasl: bool, | ||
| 249 | + layer_id: u8, | ||
| 250 | + lists: &RpsPocLists, | ||
| 251 | + max_poc_lsb: u32, | ||
| 252 | + ) -> ResolvedRps { | ||
| 253 | + // §8.3.2 — an IRAP with NoRaslOutputFlag == 1 marks every current | ||
| 254 | + // reference of this layer "unused for reference" up front. | ||
| 255 | + if is_irap_no_rasl { | ||
| 256 | + for e in &mut self.entries { | ||
| 257 | + if e.layer_id == layer_id { | ||
| 258 | + e.marking = Marking::Unused; | ||
| 259 | + } | ||
| 260 | + } | ||
| 261 | + } | ||
| 262 | + | ||
| 263 | + let mut resolved = ResolvedRps::default(); | ||
| 264 | + | ||
| 265 | + // Step 1 — resolve the long-term RPS sets (LSB or full POC). | ||
| 266 | + for (i, &poc_lt) in lists.lt_curr.iter().enumerate() { | ||
| 267 | + resolved.lt_curr.push(self.find_long_term( | ||
| 268 | + poc_lt, | ||
| 269 | + lists.curr_delta_poc_msb_present[i], | ||
| 270 | + max_poc_lsb, | ||
| 271 | + layer_id, | ||
| 272 | + )); | ||
| 273 | + } | ||
| 274 | + for (i, &poc_lt) in lists.lt_foll.iter().enumerate() { | ||
| 275 | + resolved.lt_foll.push(self.find_long_term( | ||
| 276 | + poc_lt, | ||
| 277 | + lists.foll_delta_poc_msb_present[i], | ||
| 278 | + max_poc_lsb, | ||
| 279 | + layer_id, | ||
| 280 | + )); | ||
| 281 | + } | ||
| 282 | + | ||
| 283 | + // Step 2 — mark the long-term picks "used for long-term reference". | ||
| 284 | + for idx in resolved | ||
| 285 | + .lt_curr | ||
| 286 | + .iter() | ||
| 287 | + .chain(resolved.lt_foll.iter()) | ||
| 288 | + .flatten() | ||
| 289 | + { | ||
| 290 | + self.entries[*idx].marking = Marking::LongTerm; | ||
| 291 | + } | ||
| 292 | + | ||
| 293 | + // Step 3 — resolve the short-term RPS sets (exact POC). | ||
| 294 | + for &poc in &lists.st_curr_before { | ||
| 295 | + resolved | ||
| 296 | + .st_curr_before | ||
| 297 | + .push(self.find_short_term(poc, layer_id)); | ||
| 298 | + } | ||
| 299 | + for &poc in &lists.st_curr_after { | ||
| 300 | + resolved | ||
| 301 | + .st_curr_after | ||
| 302 | + .push(self.find_short_term(poc, layer_id)); | ||
| 303 | + } | ||
| 304 | + for &poc in &lists.st_foll { | ||
| 305 | + resolved.st_foll.push(self.find_short_term(poc, layer_id)); | ||
| 306 | + } | ||
| 307 | + | ||
| 308 | + // Step 4 — any picture of this layer not in any RPS set is | ||
| 309 | + // "unused for reference". | ||
| 310 | + let mut keep = vec![false; self.entries.len()]; | ||
| 311 | + for idx in resolved | ||
| 312 | + .lt_curr | ||
| 313 | + .iter() | ||
| 314 | + .chain(resolved.lt_foll.iter()) | ||
| 315 | + .chain(resolved.st_curr_before.iter()) | ||
| 316 | + .chain(resolved.st_curr_after.iter()) | ||
| 317 | + .chain(resolved.st_foll.iter()) | ||
| 318 | + .flatten() | ||
| 319 | + { | ||
| 320 | + keep[*idx] = true; | ||
| 321 | + } | ||
| 322 | + for (i, e) in self.entries.iter_mut().enumerate() { | ||
| 323 | + if e.layer_id == layer_id && !keep[i] { | ||
| 324 | + e.marking = Marking::Unused; | ||
| 325 | + } | ||
| 326 | + } | ||
| 327 | + | ||
| 328 | + resolved | ||
| 329 | + } | ||
| 330 | + | ||
| 331 | + /// §8.3.4 — construct `RefPicList0` (and, for a B slice, | ||
| 332 | + /// `RefPicList1`) as index vectors into [`Dpb::entries`]. | ||
| 333 | + /// | ||
| 334 | + /// `rps` is the [`apply_rps`](Dpb::apply_rps) output; `params` carries | ||
| 335 | + /// the §8.3.4 sizing + modification inputs. With | ||
| 336 | + /// `curr_pic_ref_enabled` (`pps_curr_pic_ref_enabled_flag`) the | ||
| 337 | + /// equation 8-8 / 8-10 wrap appends the current picture — the | ||
| 338 | + /// [`CURR_PIC`] sentinel — after `RefPicSetLtCurr` on every pass, | ||
| 339 | + /// and the equation 8-9 closing clause overrides the last active | ||
| 340 | + /// `RefPicList0` slot when the temp list was longer than the | ||
| 341 | + /// active count and no explicit modification was signalled. | ||
| 342 | + #[must_use] | ||
| 343 | + pub fn build_ref_pic_lists( | ||
| 344 | + &self, | ||
| 345 | + rps: &ResolvedRps, | ||
| 346 | + params: &RefPicListParams<'_>, | ||
| 347 | + ) -> RefPicLists { | ||
| 348 | + // RefPicListTemp0 (equation 8-8): StCurrBefore, StCurrAfter, LtCurr, | ||
| 349 | + // (+ currPic with pps_curr_pic_ref_enabled_flag), repeated until | ||
| 350 | + // NumRpsCurrTempList0 entries are produced. | ||
| 351 | + let active0 = (params.num_ref_idx_l0_active_minus1 + 1) as usize; | ||
| 352 | + let num_temp0 = active0.max(params.num_pic_total_curr as usize); | ||
| 353 | + let temp0 = build_temp_list( | ||
| 354 | + num_temp0, | ||
| 355 | + &[&rps.st_curr_before, &rps.st_curr_after, &rps.lt_curr], | ||
| 356 | + params.curr_pic_ref_enabled, | ||
| 357 | + ); | ||
| 358 | + let mut list0 = apply_list_modification(&temp0, active0, params.list_entry_l0); | ||
| 359 | + // Equation 8-9 closing clause. | ||
| 360 | + if params.curr_pic_ref_enabled && params.list_entry_l0.is_none() && num_temp0 > active0 { | ||
| 361 | + if let Some(last) = list0.last_mut() { | ||
| 362 | + *last = Some(CURR_PIC); | ||
| 363 | + } | ||
| 364 | + } | ||
| 365 | + | ||
| 366 | + let list1 = if params.is_b { | ||
| 367 | + // RefPicListTemp1 (equation 8-10): StCurrAfter, StCurrBefore, | ||
| 368 | + // LtCurr (note the swapped first two sets). | ||
| 369 | + let active1 = (params.num_ref_idx_l1_active_minus1 + 1) as usize; | ||
| 370 | + let num_temp1 = active1.max(params.num_pic_total_curr as usize); | ||
| 371 | + let temp1 = build_temp_list( | ||
| 372 | + num_temp1, | ||
| 373 | + &[&rps.st_curr_after, &rps.st_curr_before, &rps.lt_curr], | ||
| 374 | + params.curr_pic_ref_enabled, | ||
| 375 | + ); | ||
| 376 | + Some(apply_list_modification( | ||
| 377 | + &temp1, | ||
| 378 | + active1, | ||
| 379 | + params.list_entry_l1, | ||
| 380 | + )) | ||
| 381 | + } else { | ||
| 382 | + None | ||
| 383 | + }; | ||
| 384 | + | ||
| 385 | + RefPicLists { list0, list1 } | ||
| 386 | + } | ||
| 387 | +} | ||
| 388 | + | ||
| 389 | +/// The [`RefPicLists`] sentinel index standing for the CURRENT decoded | ||
| 390 | +/// picture (before in-loop filtering) — the §8.3.4 `currPic` appended | ||
| 391 | +/// when `pps_curr_pic_ref_enabled_flag` is 1. It is deliberately out of | ||
| 392 | +/// range for every real DPB entry vector; consumers must test for it | ||
| 393 | +/// before indexing. | ||
| 394 | +pub const CURR_PIC: usize = usize::MAX; | ||
| 395 | + | ||
| 396 | +/// §8.3.4 sizing + modification inputs for | ||
| 397 | +/// [`Dpb::build_ref_pic_lists`]. | ||
| 398 | +#[derive(Debug, Clone, Copy, Default)] | ||
| 399 | +pub struct RefPicListParams<'a> { | ||
| 400 | + /// `num_ref_idx_l0_active_minus1`. | ||
| 401 | + pub num_ref_idx_l0_active_minus1: u32, | ||
| 402 | + /// `num_ref_idx_l1_active_minus1`. | ||
| 403 | + pub num_ref_idx_l1_active_minus1: u32, | ||
| 404 | + /// `NumPicTotalCurr` (§7.4.7.2). | ||
| 405 | + pub num_pic_total_curr: u32, | ||
| 406 | + /// `true` for a B slice (builds `RefPicList1`). | ||
| 407 | + pub is_b: bool, | ||
| 408 | + /// `list_entry_l0[]` (§7.3.6.2) — `Some` reorders `RefPicListTemp0`. | ||
| 409 | + pub list_entry_l0: Option<&'a [u32]>, | ||
| 410 | + /// `list_entry_l1[]` (§7.3.6.2) — `Some` reorders `RefPicListTemp1`. | ||
| 411 | + pub list_entry_l1: Option<&'a [u32]>, | ||
| 412 | + /// `pps_curr_pic_ref_enabled_flag` — appends the [`CURR_PIC`] | ||
| 413 | + /// sentinel per equations 8-8 / 8-9 / 8-10. | ||
| 414 | + pub curr_pic_ref_enabled: bool, | ||
| 415 | +} | ||
| 416 | + | ||
| 417 | +/// The §8.3.2 RPS resolved to DPB entry indices. A `None` is the spec's | ||
| 418 | +/// "no reference picture". | ||
| 419 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | ||
| 420 | +pub struct ResolvedRps { | ||
| 421 | + /// `RefPicSetStCurrBefore`. | ||
| 422 | + pub st_curr_before: Vec<Option<usize>>, | ||
| 423 | + /// `RefPicSetStCurrAfter`. | ||
| 424 | + pub st_curr_after: Vec<Option<usize>>, | ||
| 425 | + /// `RefPicSetStFoll`. | ||
| 426 | + pub st_foll: Vec<Option<usize>>, | ||
| 427 | + /// `RefPicSetLtCurr`. | ||
| 428 | + pub lt_curr: Vec<Option<usize>>, | ||
| 429 | + /// `RefPicSetLtFoll`. | ||
| 430 | + pub lt_foll: Vec<Option<usize>>, | ||
| 431 | +} | ||
| 432 | + | ||
| 433 | +/// The §8.3.4 reference picture lists, as DPB entry indices. A `None` | ||
| 434 | +/// entry is a "no reference picture" carried through from the RPS. | ||
| 435 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 436 | +pub struct RefPicLists { | ||
| 437 | + /// `RefPicList0`. | ||
| 438 | + pub list0: Vec<Option<usize>>, | ||
| 439 | + /// `RefPicList1` (only for B slices). | ||
| 440 | + pub list1: Option<Vec<Option<usize>>>, | ||
| 441 | +} | ||
| 442 | + | ||
| 443 | +/// §8.3.5 — select the collocated picture `ColPic` for temporal MV | ||
| 444 | +/// prediction, returning its DPB entry index. | ||
| 445 | +/// | ||
| 446 | +/// `slice_type_is_b` + `collocated_from_l0_flag` choose the list per | ||
| 447 | +/// §8.3.5; `collocated_ref_idx` indexes it. Returns `None` when the | ||
| 448 | +/// chosen entry is "no reference picture" or the index is out of range. | ||
| 449 | +#[must_use] | ||
| 450 | +pub fn select_col_pic( | ||
| 451 | + lists: &RefPicLists, | ||
| 452 | + slice_type_is_b: bool, | ||
| 453 | + collocated_from_l0_flag: bool, | ||
| 454 | + collocated_ref_idx: u32, | ||
| 455 | +) -> Option<usize> { | ||
| 456 | + let idx = collocated_ref_idx as usize; | ||
| 457 | + let picked = if slice_type_is_b && !collocated_from_l0_flag { | ||
| 458 | + lists.list1.as_ref()?.get(idx).copied().flatten() | ||
| 459 | + } else { | ||
| 460 | + lists.list0.get(idx).copied().flatten() | ||
| 461 | + }; | ||
| 462 | + // §7.4.7.1: collocated_ref_idx shall not refer to the current | ||
| 463 | + // picture — treat a malformed selection as "no collocated picture". | ||
| 464 | + picked.filter(|&i| i != CURR_PIC) | ||
| 465 | +} | ||
| 466 | + | ||
| 467 | +/// §8.3.5 — `NoBackwardPredFlag`: true iff every reference picture in | ||
| 468 | +/// `RefPicList0` / `RefPicList1` has `DiffPicOrderCnt( aPic, CurrPic ) | ||
| 469 | +/// <= 0`. `curr_poc` is the current picture's `PicOrderCntVal`; the | ||
| 470 | +/// closure resolves a DPB index to its POC. | ||
| 471 | +#[must_use] | ||
| 472 | +pub fn no_backward_pred_flag(dpb: &Dpb, lists: &RefPicLists, curr_poc: i32) -> bool { | ||
| 473 | + let mut all_le = true; | ||
| 474 | + let check = |idx: &Option<usize>, all_le: &mut bool| { | ||
| 475 | + if let Some(i) = idx { | ||
| 476 | + // The current picture (CURR_PIC) has DiffPicOrderCnt == 0. | ||
| 477 | + if *i != CURR_PIC && diff_pic_order_cnt(dpb.entries[*i].poc, curr_poc) > 0 { | ||
| 478 | + *all_le = false; | ||
| 479 | + } | ||
| 480 | + } | ||
| 481 | + }; | ||
| 482 | + for idx in &lists.list0 { | ||
| 483 | + check(idx, &mut all_le); | ||
| 484 | + } | ||
| 485 | + if let Some(l1) = &lists.list1 { | ||
| 486 | + for idx in l1 { | ||
| 487 | + check(idx, &mut all_le); | ||
| 488 | + } | ||
| 489 | + } | ||
| 490 | + all_le | ||
| 491 | +} | ||
| 492 | + | ||
| 493 | +/// Build a §8.3.4 `RefPicListTempX` by concatenating the given RPS sets | ||
| 494 | +/// in order — appending the [`CURR_PIC`] sentinel after each pass when | ||
| 495 | +/// `curr_pic_ref_enabled` (`pps_curr_pic_ref_enabled_flag`) — and | ||
| 496 | +/// wrapping around until `len` entries are produced (equations | ||
| 497 | +/// 8-8 / 8-10). | ||
| 498 | +fn build_temp_list( | ||
| 499 | + len: usize, | ||
| 500 | + sets: &[&[Option<usize>]], | ||
| 501 | + curr_pic_ref_enabled: bool, | ||
| 502 | +) -> Vec<Option<usize>> { | ||
| 503 | + let mut temp = Vec::with_capacity(len); | ||
| 504 | + if sets.iter().all(|s| s.is_empty()) && !curr_pic_ref_enabled { | ||
| 505 | + return temp; | ||
| 506 | + } | ||
| 507 | + while temp.len() < len { | ||
| 508 | + for set in sets { | ||
| 509 | + for &e in *set { | ||
| 510 | + if temp.len() >= len { | ||
| 511 | + break; | ||
| 512 | + } | ||
| 513 | + temp.push(e); | ||
| 514 | + } | ||
| 515 | + } | ||
| 516 | + if curr_pic_ref_enabled { | ||
| 517 | + // The equation 8-8 / 8-10 currPic append carries no | ||
| 518 | + // `rIdx < NumRpsCurrTempListX` guard — the temp list may | ||
| 519 | + // end one entry longer than `len` (reachable through | ||
| 520 | + // `list_entry_lX`). | ||
| 521 | + temp.push(Some(CURR_PIC)); | ||
| 522 | + } | ||
| 523 | + } | ||
| 524 | + temp | ||
| 525 | +} | ||
| 526 | + | ||
| 527 | +/// Apply the §8.3.4 `RefPicListX` selection (equation 8-9 / 8-11): take | ||
| 528 | +/// the first `active` entries of `temp`, reordered through `list_entry` | ||
| 529 | +/// when present. | ||
| 530 | +fn apply_list_modification( | ||
| 531 | + temp: &[Option<usize>], | ||
| 532 | + active: usize, | ||
| 533 | + list_entry: Option<&[u32]>, | ||
| 534 | +) -> Vec<Option<usize>> { | ||
| 535 | + (0..active) | ||
| 536 | + .map(|r_idx| match list_entry { | ||
| 537 | + Some(le) => temp.get(le[r_idx] as usize).copied().flatten(), | ||
| 538 | + None => temp.get(r_idx).copied().flatten(), | ||
| 539 | + }) | ||
| 540 | + .collect() | ||
| 541 | +} | ||
| 542 | + | ||
| 543 | +#[cfg(test)] | ||
| 544 | +mod tests { | ||
| 545 | + use super::*; | ||
| 546 | + use crate::picture::Picture; | ||
| 547 | + | ||
| 548 | + fn entry(poc: i32, marking: Marking) -> DpbEntry { | ||
| 549 | + DpbEntry { | ||
| 550 | + poc, | ||
| 551 | + layer_id: 0, | ||
| 552 | + marking, | ||
| 553 | + picture: Picture::new(16, 16, 1, 8, 8), | ||
| 554 | + motion: MotionField::new(16, 16), | ||
| 555 | + } | ||
| 556 | + } | ||
| 557 | + | ||
| 558 | + fn empty_st_rps() -> MaterializedShortTermRefPicSet { | ||
| 559 | + MaterializedShortTermRefPicSet { | ||
| 560 | + delta_poc_s0: vec![], | ||
| 561 | + used_by_curr_pic_s0: vec![], | ||
| 562 | + delta_poc_s1: vec![], | ||
| 563 | + used_by_curr_pic_s1: vec![], | ||
| 564 | + } | ||
| 565 | + } | ||
| 566 | + | ||
| 567 | + #[test] | ||
| 568 | + fn idr_rps_lists_are_empty() { | ||
| 569 | + let st = empty_st_rps(); | ||
| 570 | + let lists = build_rps_poc_lists(true, 0, 256, &st, &[]); | ||
| 571 | + assert!(lists.st_curr_before.is_empty()); | ||
| 572 | + assert!(lists.st_curr_after.is_empty()); | ||
| 573 | + assert!(lists.lt_curr.is_empty()); | ||
| 574 | + } | ||
| 575 | + | ||
| 576 | + #[test] | ||
| 577 | + fn p_frame_short_term_before_resolves_idr() { | ||
| 578 | + // One negative pic at delta −1, used by curr ⇒ PocStCurrBefore | ||
| 579 | + // = [poc 1 + (−1)] = [0], which resolves to the IDR in the DPB. | ||
| 580 | + let st = MaterializedShortTermRefPicSet { | ||
| 581 | + delta_poc_s0: vec![-1], | ||
| 582 | + used_by_curr_pic_s0: vec![true], | ||
| 583 | + delta_poc_s1: vec![], | ||
| 584 | + used_by_curr_pic_s1: vec![], | ||
| 585 | + }; | ||
| 586 | + let lists = build_rps_poc_lists(false, 1, 256, &st, &[]); | ||
| 587 | + assert_eq!(lists.st_curr_before, vec![0]); | ||
| 588 | + | ||
| 589 | + let mut dpb = Dpb::new(); | ||
| 590 | + dpb.insert(entry(0, Marking::ShortTerm)); | ||
| 591 | + let rps = dpb.apply_rps(false, 0, &lists, 256); | ||
| 592 | + assert_eq!(rps.st_curr_before, vec![Some(0)]); | ||
| 593 | + // The IDR stays short-term (it is in the RPS). | ||
| 594 | + assert_eq!(dpb.entries[0].marking, Marking::ShortTerm); | ||
| 595 | + } | ||
| 596 | + | ||
| 597 | + #[test] | ||
| 598 | + fn picture_not_in_rps_becomes_unused() { | ||
| 599 | + let st = empty_st_rps(); | ||
| 600 | + let lists = build_rps_poc_lists(false, 5, 256, &st, &[]); | ||
| 601 | + let mut dpb = Dpb::new(); | ||
| 602 | + dpb.insert(entry(0, Marking::ShortTerm)); | ||
| 603 | + dpb.apply_rps(false, 0, &lists, 256); | ||
| 604 | + // poc 0 is in no RPS list ⇒ unused for reference. | ||
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file
Diff too large; view file