The software H.264 export seat encodes with ec-h264
Browse files at this commit0bc3a6b2a5a447f1276c58c518962601ba297f7aParent: c612711- refactor
- the software H.264 export seat encodes with ec-h264
29 changed files +287 -11178
- crates/engine-hw/src/lib.rs +2 -1
- crates/engine/src/caps.rs +3 -3
- crates/engine/src/export.rs +100 -66
- crates/engine/tests/av1.rs +1 -1
- crates/engine/tests/backends.rs +2 -2
- crates/engine/tests/export.rs +19 -6
- crates/engine/tests/hevc.rs +1 -1
- crates/engine/tests/hw_encode.rs +88 -6
- crates/engine/tests/sw_backends.rs +69 -42
- crates/engine/tests/vp8.rs +1 -1
- crates/engine/tests/vp9.rs +1 -1
- vendor/rusty_h264-common/Cargo.toml +0 -74
- vendor/rusty_h264-common/README.md +0 -122
- vendor/rusty_h264-common/build.rs +0 -18
- vendor/rusty_h264-common/examples/bs_layout_ceiling.rs +0 -251
- vendor/rusty_h264-common/examples/deblock_anatomy.rs +0 -177
- vendor/rusty_h264-common/src/aligned.rs +0 -55
- vendor/rusty_h264-common/src/bit_reader.rs +0 -343
- vendor/rusty_h264-common/src/bit_writer.rs +0 -319
- vendor/rusty_h264-common/src/cabac_tables.rs +0 -644
- vendor/rusty_h264-common/src/cavlc.rs +0 -821
- vendor/rusty_h264-common/src/deblock.rs +0 -2884
- vendor/rusty_h264-common/src/inter.rs +0 -1901
- vendor/rusty_h264-common/src/lib.rs +0 -57
- vendor/rusty_h264-common/src/nal.rs +0 -232
- vendor/rusty_h264-common/src/predict.rs +0 -907
- vendor/rusty_h264-common/src/prof.rs +0 -585
- vendor/rusty_h264-common/src/transform.rs +0 -1561
- vendor/rusty_h264-common/src/types.rs +0 -97
crates/engine-hw/src/lib.rsmodified+2 -1
| @@ -1444,7 +1444,8 @@ fn align64(v: u32) -> u32 { | |||
| 1444 | /// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its | 1444 | /// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its |
| 1445 | /// "use packed headers" TODO). Every other bit of the slice is correct, so the | 1445 | /// "use packed headers" TODO). Every other bit of the slice is correct, so the |
| 1446 | /// whole damage is one byte per slice: measured on radeonsi, patching it turns | 1446 | /// whole damage is one byte per slice: measured on radeonsi, patching it turns |
| 1447 | -/// a stream neither ffmpeg nor `rusty_h264` will touch into one both decode. | 1447 | +/// a stream neither ffmpeg nor the `rusty_h264` then in the tree would touch |
| 1448 | +/// into one both decode (the crate has since left; the fix's proof stands). | ||
| 1448 | /// | 1449 | /// |
| 1449 | /// An all-zero byte after a start code is never valid H.264, so drivers that do | 1450 | /// An all-zero byte after a start code is never valid H.264, so drivers that do |
| 1450 | /// write the header (Intel's, which is what cros-codecs was built against) fall | 1451 | /// write the header (Intel's, which is what cros-codecs was built against) fall |
crates/engine/src/caps.rsmodified+3 -3
| @@ -32,7 +32,7 @@ const HW_CODECS: [(u32, &str); 4] = [ | |||
| 32 | /// because the answer to "why is my HEVC file so large" is `oxideav-h265 | 32 | /// because the answer to "why is my HEVC file so large" is `oxideav-h265 |
| 33 | /// intra`, and the row that says so is the row that answers it. | 33 | /// intra`, and the row that says so is the row that answers it. |
| 34 | const SW_CODECS: [(&str, &str, bool, bool); 10] = [ | 34 | const SW_CODECS: [(&str, &str, bool, bool); 10] = [ |
| 35 | - ("H.264", "ec-h264 / rusty_h264", true, true), | 35 | + ("H.264", "ec-h264", true, true), |
| 36 | ("HEVC", "oxideav-h265 intra", false, true), | 36 | ("HEVC", "oxideav-h265 intra", false, true), |
| 37 | ("AV1", "rav1e", false, true), | 37 | ("AV1", "rav1e", false, true), |
| 38 | ("AAC", "rusty_aac", true, true), | 38 | ("AAC", "rusty_aac", true, true), |
| @@ -156,13 +156,13 @@ mod tests { | |||
| 156 | #[test] | 156 | #[test] |
| 157 | fn the_software_line_names_every_encoder_this_build_carries() { | 157 | fn the_software_line_names_every_encoder_this_build_carries() { |
| 158 | let line = software(); | 158 | let line = software(); |
| 159 | - for name in ["rusty_h264", "oxideav-h265 intra", "rav1e", "rusty_aac"] { | 159 | + for name in ["ec-h264", "oxideav-h265 intra", "rav1e", "rusty_aac"] { |
| 160 | assert!(line.contains(name), "{name} missing from {line}"); | 160 | assert!(line.contains(name), "{name} missing from {line}"); |
| 161 | } | 161 | } |
| 162 | // Decode-only crates must not read as encoders, and the seat words are | 162 | // Decode-only crates must not read as encoders, and the seat words are |
| 163 | // the only thing saying which is which. | 163 | // the only thing saying which is which. |
| 164 | assert!(line.contains("AC-3 dec (oxideav-ac3)")); | 164 | assert!(line.contains("AC-3 dec (oxideav-ac3)")); |
| 165 | - assert!(line.contains("H.264 dec+enc (ec-h264 / rusty_h264)")); | 165 | + assert!(line.contains("H.264 dec+enc (ec-h264)")); |
| 166 | assert!(line.contains("HEVC enc (oxideav-h265 intra)")); | 166 | assert!(line.contains("HEVC enc (oxideav-h265 intra)")); |
| 167 | } | 167 | } |
| 168 | } | 168 | } |
crates/engine/src/export.rsmodified+100 -66
| @@ -62,7 +62,11 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; | |||
| 62 | use std::sync::{Arc, Mutex}; | 62 | use std::sync::{Arc, Mutex}; |
| 63 | use std::thread; | 63 | use std::thread; |
| 64 | 64 | ||
| 65 | -use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame}; | 65 | +use ec_core::frame::VideoFrame; |
| 66 | +use ec_core::registry::{CodecId, CodecParameters}; | ||
| 67 | +use ec_core::registry::Decoder as _; | ||
| 68 | +use ec_core::{Packet, TimeBase}; | ||
| 69 | +use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset}; | ||
| 66 | 70 | ||
| 67 | use flacenc::component::BitRepr; | 71 | use flacenc::component::BitRepr; |
| 68 | use flacenc::error::Verify; | 72 | use flacenc::error::Verify; |
| @@ -783,7 +787,7 @@ pub const NO_HW_SEAT: &str = "no HW seat here — pick Auto or Software"; | |||
| 783 | 787 | ||
| 784 | /// How a front-end names a video seat: which of the two encoders has the file, | 788 | /// How a front-end names a video seat: which of the two encoders has the file, |
| 785 | /// and which library that is. Not the codec -- a caller shows this beside the | 789 | /// and which library that is. Not the codec -- a caller shows this beside the |
| 786 | -/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One | 790 | +/// format it picked, and `rav1e` names AV1 as `ec-h264` names H.264. One |
| 787 | /// place, so what a card says before an export and what its progress line says | 791 | /// place, so what a card says before an export and what its progress line says |
| 788 | /// during one cannot drift apart. | 792 | /// during one cannot drift apart. |
| 789 | fn video_label(format: Format, hw: bool) -> &'static str { | 793 | fn video_label(format: Format, hw: bool) -> &'static str { |
| @@ -791,7 +795,7 @@ fn video_label(format: Format, hw: bool) -> &'static str { | |||
| 791 | (_, true) => HW_LABEL, | 795 | (_, true) => HW_LABEL, |
| 792 | (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)", | 796 | (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)", |
| 793 | (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)", | 797 | (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)", |
| 794 | - (_, false) => "SW encode (rusty_h264)", | 798 | + (_, false) => "SW encode (ec-h264)", |
| 795 | } | 799 | } |
| 796 | } | 800 | } |
| 797 | 801 | ||
| @@ -3784,10 +3788,10 @@ enum Enc { | |||
| 3784 | Hw(HwEncoder), | 3788 | Hw(HwEncoder), |
| 3785 | Sw { | 3789 | Sw { |
| 3786 | encoder: Encoder, | 3790 | encoder: Encoder, |
| 3787 | - /// The last access unit; owned because `rusty_h264` hands back a `Vec` | 3791 | + /// The access unit currently lent out: the encoder hands back an owned |
| 3788 | - /// while the plugin lends a slice, and the two have to look alike here. | 3792 | + /// `Vec` where the seat's contract lends a slice, so one lives here |
| 3793 | + /// between the two. | ||
| 3789 | au: Vec<u8>, | 3794 | au: Vec<u8>, |
| 3790 | - flushed: bool, | ||
| 3791 | }, | 3795 | }, |
| 3792 | /// AV1 on the GPU, through the same plugin the H.264 seat uses. | 3796 | /// AV1 on the GPU, through the same plugin the H.264 seat uses. |
| 3793 | Av1Hw(HwEncoder), | 3797 | Av1Hw(HwEncoder), |
| @@ -3881,8 +3885,20 @@ impl Enc { | |||
| 3881 | eprintln!("export encoder: hardware (VA-API plugin)"); | 3885 | eprintln!("export encoder: hardware (VA-API plugin)"); |
| 3882 | return Ok(Self::Hw(hw)); | 3886 | return Ok(Self::Hw(hw)); |
| 3883 | } | 3887 | } |
| 3884 | - eprintln!("export encoder: software (rusty_h264)"); | 3888 | + eprintln!("export encoder: software (ec-h264)"); |
| 3885 | - let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize); | 3889 | + // 4:2:0 addresses its conformance window in *chroma* samples, so an odd |
| 3890 | + // picture cannot be cropped back to itself -- and an odd dimension has | ||
| 3891 | + // no chroma plane of its own to begin with. Named rather than padded to | ||
| 3892 | + // something a decoder would then show a column of: the same refusal the | ||
| 3893 | + // HEVC seat makes, and x264's and ffmpeg's own for 4:2:0 H.264. | ||
| 3894 | + if meta.width % 2 != 0 || meta.height % 2 != 0 { | ||
| 3895 | + return Err(format!( | ||
| 3896 | + "{}x{} cannot be written as H.264: 4:2:0 needs even dimensions", | ||
| 3897 | + meta.width, meta.height | ||
| 3898 | + ) | ||
| 3899 | + .into()); | ||
| 3900 | + } | ||
| 3901 | + let mut cfg = EncoderConfig::new(meta.width, meta.height); | ||
| 3886 | cfg.framerate = meta.frame_rate as f32; | 3902 | cfg.framerate = meta.frame_rate as f32; |
| 3887 | cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; | 3903 | cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; |
| 3888 | // Two seconds between key frames, and no B-frames on either path: the | 3904 | // Two seconds between key frames, and no B-frames on either path: the |
| @@ -3894,16 +3910,14 @@ impl Enc { | |||
| 3894 | false => (meta.frame_rate * 2.0).round().max(1.0) as u32, | 3910 | false => (meta.frame_rate * 2.0).round().max(1.0) as u32, |
| 3895 | }; | 3911 | }; |
| 3896 | cfg.bframes = 0; | 3912 | cfg.bframes = 0; |
| 3897 | - let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; | 3913 | + // Fast, the rung a fallback is allowed to cost -- the cheaper arm of |
| 3898 | - cfg.level_idc = h264_level_idc(meta.width, meta.height, fps_num, fps_den); | 3914 | + // the preset ladder, the one the old seat's own S1 also picked when its |
| 3899 | - // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same | 3915 | + // Balanced rung halved the rate for the same bitrate. |
| 3900 | - // bitrate, so Fast is what a fallback should be. | ||
| 3901 | cfg.preset = Preset::Fast; | 3916 | cfg.preset = Preset::Fast; |
| 3902 | let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?; | 3917 | let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?; |
| 3903 | Ok(Self::Sw { | 3918 | Ok(Self::Sw { |
| 3904 | encoder, | 3919 | encoder, |
| 3905 | au: Vec::new(), | 3920 | au: Vec::new(), |
| 3906 | - flushed: false, | ||
| 3907 | }) | 3921 | }) |
| 3908 | } | 3922 | } |
| 3909 | 3923 | ||
| @@ -4047,11 +4061,12 @@ impl Enc { | |||
| 4047 | /// a decoder may be started from -- which only the Matroska muxer asks, the | 4061 | /// a decoder may be started from -- which only the Matroska muxer asks, the |
| 4048 | /// mp4 one reading its own sync flag off the IDR slice. | 4062 | /// mp4 one reading its own sync flag off the IDR slice. |
| 4049 | /// | 4063 | /// |
| 4050 | - /// corner-cut: `rusty_h264` buffers a whole GOP and returns it in one buffer | 4064 | + /// The contract is structural in the software seat now: `ec-h264` buffers |
| 4051 | - /// when its lookahead is active, which would make this "one access unit" | 4065 | + /// nothing -- no lookahead, and B pictures coded as none -- so one call is |
| 4052 | - /// a lie and every sample duration with it. It is inactive here because | 4066 | + /// one access unit by construction. The old seat only kept it because its |
| 4053 | - /// lookahead needs a zero bitrate and this path is always CBR; a future | 4067 | + /// GOP-buffering lookahead needed a zero bitrate and this path was always |
| 4054 | - /// constant-QP mode has to split the buffer per access unit first. | 4068 | + /// CBR; a future constant-QP mode would have had to split one buffer into |
| 4069 | + /// access units first. | ||
| 4055 | fn encode( | 4070 | fn encode( |
| 4056 | &mut self, | 4071 | &mut self, |
| 4057 | y: &[u8], | 4072 | y: &[u8], |
| @@ -4116,18 +4131,17 @@ impl Enc { | |||
| 4116 | Self::Hw(hw) => Ok(hw | 4131 | Self::Hw(hw) => Ok(hw |
| 4117 | .encode(y, u, v, width, height, intra)? | 4132 | .encode(y, u, v, width, height, intra)? |
| 4118 | .map(|au| (au, intra))), | 4133 | .map(|au| (au, intra))), |
| 4119 | - Self::Sw { encoder, au, .. } => { | 4134 | + Self::Sw { encoder, au } => { |
| 4120 | - let frame = YuvFrame { | 4135 | + // The key flag is what the bitstream says -- an IDR where the |
| 4121 | - width: width as usize, | 4136 | + // GOP asked for one, every picture on an intraframe export -- |
| 4122 | - height: height as usize, | 4137 | + // which is what the hardware seat's `intra` carries too. The |
| 4123 | - y: y.to_vec(), | 4138 | + // planes go in as borrows; the old seat was handed a copy. |
| 4124 | - u: u.to_vec(), | 4139 | + let view = PictureView::i420(width, height, y, u, v); |
| 4125 | - v: v.to_vec(), | 4140 | + let coded = encoder |
| 4126 | - }; | 4141 | + .encode(&view) |
| 4127 | - *au = encoder | ||
| 4128 | - .try_encode(&frame) | ||
| 4129 | .map_err(|e| format!("software encode: {e}"))?; | 4142 | .map_err(|e| format!("software encode: {e}"))?; |
| 4130 | - Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty())) | 4143 | + *au = coded.au; |
| 4144 | + Ok(Some((&au[..], coded.key_frame)).filter(|(au, _)| !au.is_empty())) | ||
| 4131 | } | 4145 | } |
| 4132 | } | 4146 | } |
| 4133 | } | 4147 | } |
| @@ -4201,20 +4215,9 @@ impl Enc { | |||
| 4201 | Ok(pop_hevc(hevc)) | 4215 | Ok(pop_hevc(hevc)) |
| 4202 | } | 4216 | } |
| 4203 | Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), | 4217 | Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), |
| 4204 | - Self::Sw { | 4218 | + // Nothing is held back: every picture `encode` took already came |
| 4205 | - encoder, | 4219 | + // back with its access unit, so end of stream is the empty answer. |
| 4206 | - au, | 4220 | + Self::Sw { .. } => Ok(None), |
| 4207 | - flushed, | ||
| 4208 | - } => { | ||
| 4209 | - if *flushed { | ||
| 4210 | - return Ok(None); | ||
| 4211 | - } | ||
| 4212 | - *flushed = true; | ||
| 4213 | - *au = encoder | ||
| 4214 | - .try_flush() | ||
| 4215 | - .map_err(|e| format!("software encoder flush: {e}"))?; | ||
| 4216 | - Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty())) | ||
| 4217 | - } | ||
| 4218 | } | 4221 | } |
| 4219 | } | 4222 | } |
| 4220 | } | 4223 | } |
| @@ -4627,12 +4630,14 @@ impl Pictures { | |||
| 4627 | return Ok(None); | 4630 | return Ok(None); |
| 4628 | } | 4631 | } |
| 4629 | let frame = sw.frame.as_ref().expect("advance stored a picture"); | 4632 | let frame = sw.frame.as_ref().expect("advance stored a picture"); |
| 4633 | + let [y, u, v] = [&frame.planes[0], &frame.planes[1], &frame.planes[2]]; | ||
| 4634 | + debug_assert_eq!(y.stride, frame.width as usize, "padded luma plane"); | ||
| 4630 | Ok(Some(Yuv::pixels( | 4635 | Ok(Some(Yuv::pixels( |
| 4631 | - &frame.y, | 4636 | + &y.data, |
| 4632 | - &frame.u, | 4637 | + &u.data, |
| 4633 | - &frame.v, | 4638 | + &v.data, |
| 4634 | - frame.width as u32, | 4639 | + frame.width, |
| 4635 | - frame.height as u32, | 4640 | + frame.height, |
| 4636 | ))) | 4641 | ))) |
| 4637 | } | 4642 | } |
| 4638 | } | 4643 | } |
| @@ -4641,12 +4646,15 @@ impl Pictures { | |||
| 4641 | 4646 | ||
| 4642 | struct SwDecoder { | 4647 | struct SwDecoder { |
| 4643 | demuxer: Demuxer, | 4648 | demuxer: Demuxer, |
| 4644 | - decoder: Decoder, | 4649 | + decoder: H264Decoder, |
| 4645 | /// Display index of the next picture the decoder will produce. Signed: a | 4650 | /// Display index of the next picture the decoder will produce. Signed: a |
| 4646 | /// sync sample inside what the edit list trims is before frame 0. | 4651 | /// sync sample inside what the edit list trims is before frame 0. |
| 4647 | index: i64, | 4652 | index: i64, |
| 4648 | start: u32, | 4653 | start: u32, |
| 4649 | - frame: Option<YuvFrame>, | 4654 | + /// Set once the demuxer runs dry: `flush` has then released what the |
| 4655 | + /// decoder's reorder still held, and only those pictures are left. | ||
| 4656 | + flushed: bool, | ||
| 4657 | + frame: Option<VideoFrame>, | ||
| 4650 | } | 4658 | } |
| 4651 | 4659 | ||
| 4652 | impl SwDecoder { | 4660 | impl SwDecoder { |
| @@ -4654,7 +4662,7 @@ impl SwDecoder { | |||
| 4654 | let (meta, mut demuxer) = Demuxer::open(path)?; | 4662 | let (meta, mut demuxer) = Demuxer::open(path)?; |
| 4655 | // The software decoder is H.264-only; an HEVC or VP9 source that got | 4663 | // The software decoder is H.264-only; an HEVC or VP9 source that got |
| 4656 | // this far means the plugin refused it, and the export says so instead | 4664 | // this far means the plugin refused it, and the export says so instead |
| 4657 | - // of handing those bytes to `rusty_h264`. | 4665 | + // of handing those bytes to `ec-h264`. |
| 4658 | if meta.codec != crate::demux::Codec::H264 { | 4666 | if meta.codec != crate::demux::Codec::H264 { |
| 4659 | return Err(meta.codec.needs_plugin().into()); | 4667 | return Err(meta.codec.needs_plugin().into()); |
| 4660 | } | 4668 | } |
| @@ -4663,30 +4671,56 @@ impl SwDecoder { | |||
| 4663 | let index = demuxer.seek_to_sync_at_or_before(start_frame); | 4671 | let index = demuxer.seek_to_sync_at_or_before(start_frame); |
| 4664 | Ok(Self { | 4672 | Ok(Self { |
| 4665 | demuxer, | 4673 | demuxer, |
| 4666 | - decoder: Decoder::new(), | 4674 | + decoder: H264Decoder::new(CodecParameters::new(CodecId::H264)) |
| 4675 | + .expect("ec-h264 takes its own codec id"), | ||
| 4667 | index, | 4676 | index, |
| 4668 | start: start_frame, | 4677 | start: start_frame, |
| 4678 | + flushed: false, | ||
| 4669 | frame: None, | 4679 | frame: None, |
| 4670 | }) | 4680 | }) |
| 4671 | } | 4681 | } |
| 4672 | 4682 | ||
| 4673 | /// Decodes up to and including the next picture at or after the in point, | 4683 | /// Decodes up to and including the next picture at or after the in point, |
| 4674 | - /// leaving it in `frame`. `false` at end of stream. | 4684 | + /// leaving it in `frame`. `false` at end of stream. Pictures leave the |
| 4685 | + /// decoder in display order -- clause C.4.5.3, the same contract the | ||
| 4686 | + /// playback seat keeps -- so the landing index, itself a display index by | ||
| 4687 | + /// the demuxer's contract, counts one to one with them. | ||
| 4675 | fn advance(&mut self) -> crate::Result<bool> { | 4688 | fn advance(&mut self) -> crate::Result<bool> { |
| 4676 | loop { | 4689 | loop { |
| 4677 | - let Some(au) = self.demuxer.next_access_unit()? else { | 4690 | + if !self.flushed { |
| 4678 | - return Ok(false); | 4691 | + match self.demuxer.next_access_unit()? { |
| 4679 | - }; | 4692 | + Some(au) => self |
| 4680 | - let decoded = self | 4693 | + .decoder |
| 4681 | - .decoder | 4694 | + .send_packet(&Packet::new(0, TimeBase::new(1, 1), au)) |
| 4682 | - .decode(&au) | 4695 | + .map_err(|e| format!("decode at picture {}: {e}", self.index))?, |
| 4683 | - .map_err(|e| format!("decode at picture {}: {e}", self.index))?; | 4696 | + None => { |
| 4684 | - let Some(yuv) = decoded else { continue }; | 4697 | + self.flushed = true; |
| 4685 | - let wanted = self.index >= i64::from(self.start); | 4698 | + self.decoder |
| 4686 | - self.index += 1; | 4699 | + .flush() |
| 4687 | - if wanted { | 4700 | + .map_err(|e| format!("decode at end of stream: {e}"))?; |
| 4688 | - self.frame = Some(yuv); | 4701 | + } |
| 4689 | - return Ok(true); | 4702 | + } |
| 4703 | + } | ||
| 4704 | + match self.decoder.receive_frame() { | ||
| 4705 | + Ok(frame) => { | ||
| 4706 | + let ec_core::frame::Frame::Video(pic) = frame else { | ||
| 4707 | + continue; | ||
| 4708 | + }; | ||
| 4709 | + if self.index < i64::from(self.start) { | ||
| 4710 | + self.index += 1; | ||
| 4711 | + continue; | ||
| 4712 | + } | ||
| 4713 | + self.index += 1; | ||
| 4714 | + self.frame = Some(pic); | ||
| 4715 | + return Ok(true); | ||
| 4716 | + } | ||
| 4717 | + // End of stream counts once the flush has happened; before it, | ||
| 4718 | + // either answer means go back for the next access unit. | ||
| 4719 | + Err(e) if e.is_eof() && self.flushed => return Ok(false), | ||
| 4720 | + Err(e) if e.is_need_more() || e.is_eof() => {} | ||
| 4721 | + Err(e) => { | ||
| 4722 | + return Err(format!("decode at picture {}: {e}", self.index).into()) | ||
| 4723 | + } | ||
| 4690 | } | 4724 | } |
| 4691 | } | 4725 | } |
| 4692 | } | 4726 | } |
crates/engine/tests/av1.rsmodified+1 -1
| @@ -143,7 +143,7 @@ fn every_block_comes_back_and_keyframes_carry_the_sequence_header() { | |||
| 143 | } | 143 | } |
| 144 | 144 | ||
| 145 | /// There is no software AV1 decoder, so the software path must refuse by name | 145 | /// There is no software AV1 decoder, so the software path must refuse by name |
| 146 | -/// rather than feed AV1 bytes to `rusty_h264` -- and it must refuse where a | 146 | +/// rather than feed AV1 bytes to `ec-h264` -- and it must refuse where a |
| 147 | /// caller can still show it, i.e. out of `open`, not from inside the worker. | 147 | /// caller can still show it, i.e. out of `open`, not from inside the worker. |
| 148 | #[test] | 148 | #[test] |
| 149 | fn the_software_path_refuses_av1_by_name() { | 149 | fn the_software_path_refuses_av1_by_name() { |
crates/engine/tests/backends.rsmodified+2 -2
| @@ -50,7 +50,7 @@ fn an_h264_source_probes_as_one_of_the_two_seats() { | |||
| 50 | 50 | ||
| 51 | /// HEVC has no software decoder here at all. A box with the plugin answers | 51 | /// HEVC has no software decoder here at all. A box with the plugin answers |
| 52 | /// hardware; a box without it is refused by name -- and *never* told that | 52 | /// hardware; a box without it is refused by name -- and *never* told that |
| 53 | -/// `rusty_h264` will take it, which is the one answer that would be a lie. | 53 | +/// `ec-h264` will take it, which is the one answer that would be a lie. |
| 54 | #[test] | 54 | #[test] |
| 55 | fn hevc_probes_as_hardware_or_as_a_refusal() { | 55 | fn hevc_probes_as_hardware_or_as_a_refusal() { |
| 56 | match probe(&asset("test_hevc.mkv")) { | 56 | match probe(&asset("test_hevc.mkv")) { |
| @@ -96,7 +96,7 @@ fn a_playing_session_reports_the_seat_the_probe_named() { | |||
| 96 | /// about the machine, which is exactly what this whole surface is for. | 96 | /// about the machine, which is exactly what this whole surface is for. |
| 97 | /// | 97 | /// |
| 98 | /// Every picture format, because each one is a different pair of seats: H.264 | 98 | /// Every picture format, because each one is a different pair of seats: H.264 |
| 99 | -/// through `rusty_h264` or the plugin, and AV1 through `rav1e` in either | 99 | +/// through `ec-h264` or the plugin, and AV1 through `rav1e` in either |
| 100 | /// container -- a container is not an encoder, and the card must not say it is. | 100 | /// container -- a container is not an encoder, and the card must not say it is. |
| 101 | #[test] | 101 | #[test] |
| 102 | fn the_planned_encoders_are_the_ones_the_job_opens() { | 102 | fn the_planned_encoders_are_the_ones_the_job_opens() { |
crates/engine/tests/export.rsmodified+19 -6
| @@ -36,6 +36,9 @@ use engine::project::{Lane, Source, Speed}; | |||
| 36 | use engine::scale::FitPolicy; | 36 | use engine::scale::FitPolicy; |
| 37 | use engine::scratch::Scratch; | 37 | use engine::scratch::Scratch; |
| 38 | use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; | 38 | use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; |
| 39 | +use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; | ||
| 40 | +use ec_core::{Packet, TimeBase}; | ||
| 41 | +use ec_h264::H264Decoder; | ||
| 39 | 42 | ||
| 40 | const FPS: f64 = 30.0; | 43 | const FPS: f64 = 30.0; |
| 41 | 44 | ||
| @@ -750,17 +753,27 @@ fn hardware_access_units_repack_into_mp4() { | |||
| 750 | 753 | ||
| 751 | let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap(); | 754 | let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap(); |
| 752 | assert_eq!(meta.frame_count, 10); | 755 | assert_eq!(meta.frame_count, 10); |
| 753 | - let mut decoder = rusty_h264::Decoder::new(); | 756 | + let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)) |
| 757 | + .expect("ec-h264 takes its own codec id"); | ||
| 754 | let mut decoded = 0; | 758 | let mut decoded = 0; |
| 755 | while let Some(au) = demuxer.next_access_unit().unwrap() { | 759 | while let Some(au) = demuxer.next_access_unit().unwrap() { |
| 756 | - if decoder | 760 | + decoder |
| 757 | - .decode(&au) | 761 | + .send_packet(&Packet::new(0, TimeBase::new(1, 1), au)) |
| 758 | - .expect("software decode of the remuxed stream") | 762 | + .expect("software decode of the remuxed stream"); |
| 759 | - .is_some() | 763 | + while let Ok(frame) = decoder.receive_frame() { |
| 760 | - { | 764 | + let ec_core::frame::Frame::Video(_) = frame else { |
| 765 | + continue; | ||
| 766 | + }; | ||
| 761 | decoded += 1; | 767 | decoded += 1; |
| 762 | } | 768 | } |
| 763 | } | 769 | } |
| 770 | + decoder.flush().expect("flush of the remuxed stream"); | ||
| 771 | + while let Ok(frame) = decoder.receive_frame() { | ||
| 772 | + let ec_core::frame::Frame::Video(_) = frame else { | ||
| 773 | + continue; | ||
| 774 | + }; | ||
| 775 | + decoded += 1; | ||
| 776 | + } | ||
| 764 | assert_eq!(decoded, 10, "every remuxed picture decodes again"); | 777 | assert_eq!(decoded, 10, "every remuxed picture decodes again"); |
| 765 | std::fs::remove_file(&out).unwrap(); | 778 | std::fs::remove_file(&out).unwrap(); |
| 766 | } | 779 | } |
crates/engine/tests/hevc.rsmodified+1 -1
| @@ -92,7 +92,7 @@ fn every_sync_sample_carries_annex_b_vps_sps_and_pps() { | |||
| 92 | } | 92 | } |
| 93 | 93 | ||
| 94 | /// There is no software HEVC decoder, so the software path must refuse by name | 94 | /// There is no software HEVC decoder, so the software path must refuse by name |
| 95 | -/// rather than feed HEVC bytes to `rusty_h264` -- and it must refuse where a | 95 | +/// rather than feed HEVC bytes to `ec-h264` -- and it must refuse where a |
| 96 | /// caller can still show it, i.e. out of `open`, not from inside the worker. | 96 | /// caller can still show it, i.e. out of `open`, not from inside the worker. |
| 97 | #[test] | 97 | #[test] |
| 98 | fn the_software_path_refuses_hevc_by_name() { | 98 | fn the_software_path_refuses_hevc_by_name() { |
crates/engine/tests/hw_encode.rsmodified+88 -6
| @@ -9,12 +9,16 @@ | |||
| 9 | //! ``` | 9 | //! ``` |
| 10 | //! | 10 | //! |
| 11 | //! The round trip goes out through the plugin and back in through the *software* | 11 | //! The round trip goes out through the plugin and back in through the *software* |
| 12 | -//! decoder (`rusty_h264` directly, not `DecodeSession`), so a bug on one side | 12 | +//! decoder (`ec-h264` driven by hand, not `DecodeSession`), so a bug in the |
| 13 | -//! cannot cancel out a bug on the other. | 13 | +//! session plumbing cannot cancel out a plugin bug; the independent witness for |
| 14 | +//! the stream's well-formedness is ffmpeg, in the export suite. | ||
| 14 | 15 | ||
| 15 | use std::time::{Duration, Instant}; | 16 | use std::time::{Duration, Instant}; |
| 16 | 17 | ||
| 17 | use engine::hw::{HwEncoder, HwPicture, HwSession}; | 18 | use engine::hw::{HwEncoder, HwPicture, HwSession}; |
| 19 | +use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; | ||
| 20 | +use ec_core::{Packet, TimeBase}; | ||
| 21 | +use ec_h264::H264Decoder; | ||
| 18 | 22 | ||
| 19 | const FPS: u32 = 30; | 23 | const FPS: u32 = 30; |
| 20 | const BITRATE: u64 = 4_000_000; | 24 | const BITRATE: u64 = 4_000_000; |
| @@ -64,10 +68,88 @@ fn encode(width: u32, height: u32, count: u32) -> Option<(Vec<u8>, u32)> { | |||
| 64 | Some((stream, units)) | 68 | Some((stream, units)) |
| 65 | } | 69 | } |
| 66 | 70 | ||
| 67 | -fn decode(stream: &[u8]) -> Vec<rusty_h264::YuvFrame> { | 71 | +fn decode(stream: &[u8]) -> Vec<Decoded> { |
| 68 | - rusty_h264::Decoder::new() | 72 | + let mut decoder = |
| 69 | - .decode_stream(stream) | 73 | + H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("ec-h264 takes its codec id"); |
| 70 | - .expect("software decode of the hardware-encoded stream") | 74 | + let mut frames = Vec::new(); |
| 75 | + for au in access_units(stream) { | ||
| 76 | + decoder | ||
| 77 | + .send_packet(&Packet::new(0, TimeBase::new(1, 1), au.as_slice())) | ||
| 78 | + .expect("software decode of the hardware-encoded stream"); | ||
| 79 | + collect(&mut decoder, &mut frames); | ||
| 80 | + } | ||
| 81 | + decoder | ||
| 82 | + .flush() | ||
| 83 | + .expect("flush of the hardware-encoded stream"); | ||
| 84 | + collect(&mut decoder, &mut frames); | ||
| 85 | + frames | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// Takes everything the decoder has released so far. | ||
| 89 | +fn collect(decoder: &mut H264Decoder, frames: &mut Vec<Decoded>) { | ||
| 90 | + while let Ok(frame) = decoder.receive_frame() { | ||
| 91 | + let ec_core::frame::Frame::Video(pic) = frame else { | ||
| 92 | + continue; | ||
| 93 | + }; | ||
| 94 | + frames.push(Decoded { | ||
| 95 | + width: pic.width as usize, | ||
| 96 | + height: pic.height as usize, | ||
| 97 | + y: pic.planes[0].data[..].to_vec(), | ||
| 98 | + u: pic.planes[1].data[..].to_vec(), | ||
| 99 | + v: pic.planes[2].data[..].to_vec(), | ||
| 100 | + }); | ||
| 101 | + } | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// One decoded picture as plain planes, whatever the decoder calls them. | ||
| 105 | +struct Decoded { | ||
| 106 | + width: usize, | ||
| 107 | + height: usize, | ||
| 108 | + y: Vec<u8>, | ||
| 109 | + u: Vec<u8>, | ||
| 110 | + v: Vec<u8>, | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// Splits an Annex-B stream into access units: a new one at each slice NAL | ||
| 114 | +/// that follows a picture, parameter sets and SEI riding with the slice that | ||
| 115 | +/// follows them. The plugin emits one AU per picture; the split exists so the | ||
| 116 | +/// decoder sees the packet shape a demuxer hands it for a file. | ||
| 117 | +fn access_units(stream: &[u8]) -> Vec<Vec<u8>> { | ||
| 118 | + // (offset of the start code, its length); the sentinel ends the last NAL. | ||
| 119 | + let mut bounds: Vec<(usize, usize)> = Vec::new(); | ||
| 120 | + let mut i = 0; | ||
| 121 | + while i + 2 < stream.len() { | ||
| 122 | + if stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1 { | ||
| 123 | + bounds.push(if i > 0 && stream[i - 1] == 0 { | ||
| 124 | + (i - 1, 4) | ||
| 125 | + } else { | ||
| 126 | + (i, 3) | ||
| 127 | + }); | ||
| 128 | + i += 3; | ||
| 129 | + } else { | ||
| 130 | + i += 1; | ||
| 131 | + } | ||
| 132 | + } | ||
| 133 | + bounds.push((stream.len(), 0)); | ||
| 134 | + let mut aus: Vec<Vec<u8>> = Vec::new(); | ||
| 135 | + let mut current: Vec<u8> = Vec::new(); | ||
| 136 | + let mut has_slice = false; | ||
| 137 | + for pair in bounds.windows(2) { | ||
| 138 | + let (at, sc) = pair[0]; | ||
| 139 | + let nal = &stream[at..pair[1].0]; | ||
| 140 | + let kind = nal[sc] & 0x1f; | ||
| 141 | + let slice = kind == 1 || kind == 5; | ||
| 142 | + if slice && has_slice { | ||
| 143 | + aus.push(std::mem::take(&mut current)); | ||
| 144 | + has_slice = false; | ||
| 145 | + } | ||
| 146 | + current.extend_from_slice(nal); | ||
| 147 | + has_slice |= slice; | ||
| 148 | + } | ||
| 149 | + if !current.is_empty() { | ||
| 150 | + aus.push(current); | ||
| 151 | + } | ||
| 152 | + aus | ||
| 71 | } | 153 | } |
| 72 | 154 | ||
| 73 | fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { | 155 | fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { |
crates/engine/tests/sw_backends.rsmodified+69 -42
| @@ -1,15 +1,11 @@ | |||
| 1 | -//! The H.264 software decode seat swap: `ec-h264` (the in-project decoder) is | 1 | +//! The H.264 software decode seat's witnesses, after the swap that made |
| 2 | -//! the seat, `rusty_h264` -- the decoder this seat carried for years, and still | 2 | +//! `ec-h264` -- the in-project decoder -- the seat. The independent one is |
| 3 | -//! the encoder behind software H.264 export -- is the independent witness. | 3 | +//! ffmpeg: 8-bit H.264 decode is bit-exact by conformance, so a correct decoder |
| 4 | -//! | 4 | +//! handed a file must return the pictures the outside decoder returns, byte for |
| 5 | -//! H.264 8-bit decode is bit-exact by conformance, so two correct decoders | 5 | +//! byte. (The witness these tests were first written against, `rusty_h264`, |
| 6 | -//! handed the same access units must return the same pictures, byte for byte; | 6 | +//! retired with the crate on 2026-09-12 when the encode seat moved too; ffmpeg |
| 7 | -//! this is the software twin of `hw_decode::hardware_matches_software_on_frame_30`. | 7 | +//! took the outside role.) The seat's own two output orders must also agree: |
| 8 | -//! The one deliberate difference is *order*: `rusty_h264` releases pictures in | 8 | +//! display order is a reordering, not a rewrite. |
| 9 | -//! decode order, `ec-h264` in display order (clause C.4.5.3), which is what the | ||
| 10 | -//! rest of the engine already assumed -- the hardware backend behaves the same | ||
| 11 | -//! way, `frame.index` is a timeline position, and the old seat's decode-order | ||
| 12 | -//! corner-cut scrambled B-picture streams. | ||
| 13 | //! | 9 | //! |
| 14 | //! ```text | 10 | //! ```text |
| 15 | //! cargo test -p engine --test sw_backends -- --test-threads=1 | 11 | //! cargo test -p engine --test sw_backends -- --test-threads=1 |
| @@ -59,23 +55,6 @@ impl Picture { | |||
| 59 | } | 55 | } |
| 60 | } | 56 | } |
| 61 | 57 | ||
| 62 | -/// `rusty_h264`, decode order -- the order it has always emitted. | ||
| 63 | -fn decode_rusty(aus: &[Vec<u8>]) -> Vec<Picture> { | ||
| 64 | - let mut decoder = rusty_h264::Decoder::new(); | ||
| 65 | - let mut pictures = Vec::new(); | ||
| 66 | - for au in aus { | ||
| 67 | - if let Some(yuv) = decoder.decode(au).expect("rusty decode") { | ||
| 68 | - pictures.push(Picture { | ||
| 69 | - width: yuv.width, | ||
| 70 | - y: yuv.y, | ||
| 71 | - u: yuv.u, | ||
| 72 | - v: yuv.v, | ||
| 73 | - }); | ||
| 74 | - } | ||
| 75 | - } | ||
| 76 | - pictures | ||
| 77 | -} | ||
| 78 | - | ||
| 79 | /// `ec-h264` in the requested output order, drained to end of stream. | 58 | /// `ec-h264` in the requested output order, drained to end of stream. |
| 80 | fn decode_ec(aus: &[Vec<u8>], order: ec_h264::OutputOrder) -> Vec<Picture> { | 59 | fn decode_ec(aus: &[Vec<u8>], order: ec_h264::OutputOrder) -> Vec<Picture> { |
| 81 | let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("ec decoder"); | 60 | let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("ec decoder"); |
| @@ -114,6 +93,51 @@ fn decode_ec(aus: &[Vec<u8>], order: ec_h264::OutputOrder) -> Vec<Picture> { | |||
| 114 | pictures | 93 | pictures |
| 115 | } | 94 | } |
| 116 | 95 | ||
| 96 | +/// Every picture ffmpeg releases for the file, in display order, as I420 | ||
| 97 | +/// planes. `None` where ffmpeg is not installed -- the same skip the export | ||
| 98 | +/// suite's `ffmpeg_complaints` takes. | ||
| 99 | +fn decode_ffmpeg(path: &Path) -> Option<Vec<Picture>> { | ||
| 100 | + let installed = std::process::Command::new("ffmpeg") | ||
| 101 | + .arg("-version") | ||
| 102 | + .output() | ||
| 103 | + .map(|out| out.status.success()) | ||
| 104 | + .unwrap_or(false); | ||
| 105 | + if !installed { | ||
| 106 | + return None; | ||
| 107 | + } | ||
| 108 | + let (meta, _) = engine::demux::Demuxer::open(path).expect("open"); | ||
| 109 | + let (w, h) = (meta.width as usize, meta.height as usize); | ||
| 110 | + let frame = w * h + 2 * (w / 2) * (h / 2); | ||
| 111 | + let out = std::process::Command::new("ffmpeg") | ||
| 112 | + .args(["-v", "error", "-i"]) | ||
| 113 | + .arg(path) | ||
| 114 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | ||
| 115 | + .output() | ||
| 116 | + .expect("run ffmpeg"); | ||
| 117 | + assert!( | ||
| 118 | + out.status.success(), | ||
| 119 | + "ffmpeg read {} and failed: {}", | ||
| 120 | + path.display(), | ||
| 121 | + String::from_utf8_lossy(&out.stderr) | ||
| 122 | + ); | ||
| 123 | + let raw = out.stdout; | ||
| 124 | + assert_eq!(raw.len() % frame, 0, "ffmpeg handed back a partial frame"); | ||
| 125 | + Some( | ||
| 126 | + raw.chunks_exact(frame) | ||
| 127 | + .map(|data| { | ||
| 128 | + let (luma, rest) = data.split_at(w * h); | ||
| 129 | + let (cb, cr) = rest.split_at((w / 2) * (h / 2)); | ||
| 130 | + Picture { | ||
| 131 | + width: w, | ||
| 132 | + y: luma.to_vec(), | ||
| 133 | + u: cb.to_vec(), | ||
| 134 | + v: cr.to_vec(), | ||
| 135 | + } | ||
| 136 | + }) | ||
| 137 | + .collect(), | ||
| 138 | + ) | ||
| 139 | +} | ||
| 140 | + | ||
| 117 | fn assert_same_pictures(a: &Picture, b: &Picture, what: &str, index: usize) { | 141 | fn assert_same_pictures(a: &Picture, b: &Picture, what: &str, index: usize) { |
| 118 | assert_eq!(a.width, b.width, "{what}: picture {index} width"); | 142 | assert_eq!(a.width, b.width, "{what}: picture {index} width"); |
| 119 | assert_eq!(a.y, b.y, "{what}: picture {index} luma"); | 143 | assert_eq!(a.y, b.y, "{what}: picture {index} luma"); |
| @@ -121,33 +145,36 @@ fn assert_same_pictures(a: &Picture, b: &Picture, what: &str, index: usize) { | |||
| 121 | assert_eq!(a.v, b.v, "{what}: picture {index} cr"); | 145 | assert_eq!(a.v, b.v, "{what}: picture {index} cr"); |
| 122 | } | 146 | } |
| 123 | 147 | ||
| 124 | -/// Same access units in, same pictures out, byte for byte, on both a CAVLC | 148 | +/// The seat against the outside decoder, byte for byte, on both a CAVLC |
| 125 | -/// Baseline and a CABAC High stream with B pictures. Decode order on both | 149 | +/// Baseline and a CABAC High stream with B pictures. Display order on both |
| 126 | -/// sides makes the sequences one to one regardless of reordering. | 150 | +/// sides: ffmpeg releases pictures as they play, and so does the seat. |
| 127 | #[test] | 151 | #[test] |
| 128 | -fn sw_decoders_agree_byte_for_byte() { | 152 | +fn sw_decode_matches_ffmpeg_byte_for_byte() { |
| 129 | for name in ["test_baseline.mp4", "test_high.mp4"] { | 153 | for name in ["test_baseline.mp4", "test_high.mp4"] { |
| 130 | - let aus = access_units(&asset(name)); | 154 | + let path = asset(name); |
| 131 | - let rusty = decode_rusty(&aus); | 155 | + let Some(want) = decode_ffmpeg(&path) else { |
| 132 | - let ec = decode_ec(&aus, ec_h264::OutputOrder::Decode); | 156 | + eprintln!("no ffmpeg: skipping the outside decoder's word on {name}"); |
| 133 | - assert_eq!(rusty.len(), ec.len(), "{name}: picture count"); | 157 | + continue; |
| 134 | - for (i, (a, b)) in rusty.iter().zip(&ec).enumerate() { | 158 | + }; |
| 159 | + let got = decode_ec(&access_units(&path), ec_h264::OutputOrder::Display); | ||
| 160 | + assert_eq!(got.len(), want.len(), "{name}: picture count"); | ||
| 161 | + for (i, (a, b)) in got.iter().zip(&want).enumerate() { | ||
| 135 | assert_same_pictures(a, b, name, i); | 162 | assert_same_pictures(a, b, name, i); |
| 136 | } | 163 | } |
| 137 | - eprintln!("{name}: {} pictures agree byte for byte", rusty.len()); | 164 | + eprintln!("{name}: {} pictures agree byte for byte with ffmpeg", got.len()); |
| 138 | } | 165 | } |
| 139 | } | 166 | } |
| 140 | 167 | ||
| 141 | /// Display order is a reordering, not a rewrite: the same multiset of | 168 | /// Display order is a reordering, not a rewrite: the same multiset of |
| 142 | /// pictures the decode-order run releases, possibly in a different sequence. | 169 | /// pictures the decode-order run releases, possibly in a different sequence. |
| 143 | -/// On the B-picture fixture the sequences genuinely differ -- that is the | 170 | +/// On the B-picture fixture the sequences genuinely differ -- the reordering |
| 144 | -/// corner-cut being retired -- and on the Baseline fixture they cannot (no | 171 | +/// is the point of the DPB -- and on the Baseline fixture they cannot (no |
| 145 | /// B pictures, nothing to reorder). | 172 | /// B pictures, nothing to reorder). |
| 146 | #[test] | 173 | #[test] |
| 147 | fn display_order_releases_the_same_pictures() { | 174 | fn display_order_releases_the_same_pictures() { |
| 148 | for name in ["test_baseline.mp4", "test_high.mp4"] { | 175 | for name in ["test_baseline.mp4", "test_high.mp4"] { |
| 149 | let aus = access_units(&asset(name)); | 176 | let aus = access_units(&asset(name)); |
| 150 | - let decode_order = decode_rusty(&aus); | 177 | + let decode_order = decode_ec(&aus, ec_h264::OutputOrder::Decode); |
| 151 | let display_order = decode_ec(&aus, ec_h264::OutputOrder::Display); | 178 | let display_order = decode_ec(&aus, ec_h264::OutputOrder::Display); |
| 152 | assert_eq!(decode_order.len(), display_order.len(), "{name}: count"); | 179 | assert_eq!(decode_order.len(), display_order.len(), "{name}: count"); |
| 153 | let mut want: Vec<u64> = decode_order.iter().map(Picture::hash).collect(); | 180 | let mut want: Vec<u64> = decode_order.iter().map(Picture::hash).collect(); |
crates/engine/tests/vp8.rsmodified+1 -1
| @@ -53,7 +53,7 @@ fn the_demuxer_reports_a_vp8_track() { | |||
| 53 | } | 53 | } |
| 54 | 54 | ||
| 55 | /// There is no software VP8 decoder *in this binary*, so the software path | 55 | /// There is no software VP8 decoder *in this binary*, so the software path |
| 56 | -/// must refuse by name rather than feed VP8 bytes to `rusty_h264` -- and it | 56 | +/// must refuse by name rather than feed VP8 bytes to `ec-h264` -- and it |
| 57 | /// must refuse where a caller can still show it, i.e. out of `open`, not from | 57 | /// must refuse where a caller can still show it, i.e. out of `open`, not from |
| 58 | /// inside the worker. The decoder the refusal names is the plugin's libvpx | 58 | /// inside the worker. The decoder the refusal names is the plugin's libvpx |
| 59 | /// arm, which is why the sentence names the plugin and not a nonexistent | 59 | /// arm, which is why the sentence names the plugin and not a nonexistent |
crates/engine/tests/vp9.rsmodified+1 -1
| @@ -56,7 +56,7 @@ fn the_demuxer_reports_a_vp9_track() { | |||
| 56 | } | 56 | } |
| 57 | 57 | ||
| 58 | /// There is no software VP9 decoder, so the software path must refuse by name | 58 | /// There is no software VP9 decoder, so the software path must refuse by name |
| 59 | -/// rather than feed VP9 bytes to `rusty_h264` -- and it must refuse where a | 59 | +/// rather than feed VP9 bytes to `ec-h264` -- and it must refuse where a |
| 60 | /// caller can still show it, i.e. out of `open`, not from inside the worker. | 60 | /// caller can still show it, i.e. out of `open`, not from inside the worker. |
| 61 | #[test] | 61 | #[test] |
| 62 | fn the_software_path_refuses_vp9_by_name() { | 62 | fn the_software_path_refuses_vp9_by_name() { |
vendor/rusty_h264-common/Cargo.tomldeleted+0 -74
| @@ -1,74 +0,0 @@ | |||
| 1 | -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO | ||
| 2 | -# | ||
| 3 | -# When uploading crates to the registry Cargo will automatically | ||
| 4 | -# "normalize" Cargo.toml files for maximal compatibility | ||
| 5 | -# with all versions of Cargo and also rewrite `path` dependencies | ||
| 6 | -# to registry (e.g., crates.io) dependencies. | ||
| 7 | -# | ||
| 8 | -# If you are reading this file be aware that the original Cargo.toml | ||
| 9 | -# will likely look very different (and much more reasonable). | ||
| 10 | -# See Cargo.toml.orig for the original contents. | ||
| 11 | - | ||
| 12 | -[package] | ||
| 13 | -edition = "2021" | ||
| 14 | -rust-version = "1.80" | ||
| 15 | -name = "rusty_h264-common" | ||
| 16 | -version = "0.9.1" | ||
| 17 | -authors = ["Mata Network"] | ||
| 18 | -build = "build.rs" | ||
| 19 | -autolib = false | ||
| 20 | -autobins = false | ||
| 21 | -autoexamples = false | ||
| 22 | -autotests = false | ||
| 23 | -autobenches = false | ||
| 24 | -description = "Shared primitives for the rusty_h264 pure-Rust H.264 codec: bitstream I/O, Exp-Golomb, NAL/Annex-B, transforms, intra prediction, motion compensation and deblocking. forbid(unsafe). BSD-2." | ||
| 25 | -homepage = "https://www.mata.network/" | ||
| 26 | -documentation = "https://docs.rs/rusty_h264-common" | ||
| 27 | -readme = "README.md" | ||
| 28 | -keywords = [ | ||
| 29 | - "h264", | ||
| 30 | - "avc", | ||
| 31 | - "video", | ||
| 32 | - "codec", | ||
| 33 | - "bitstream", | ||
| 34 | -] | ||
| 35 | -categories = [ | ||
| 36 | - "multimedia::video", | ||
| 37 | - "multimedia::encoding", | ||
| 38 | - "encoding", | ||
| 39 | -] | ||
| 40 | -license = "BSD-2-Clause" | ||
| 41 | -repository = "https://github.com/remade-with-rust/rusty_h264" | ||
| 42 | - | ||
| 43 | -[features] | ||
| 44 | -asm = ["dep:rusty_h264-accel"] | ||
| 45 | -# --- edith patch: `global-alloc` is off by default and inert when asked for --- | ||
| 46 | -# It stays *declared* because `rusty_h264-{decoder,encoder}`'s own defaults name | ||
| 47 | -# `rusty_h264-common/global-alloc`, so removing it would break their manifests; | ||
| 48 | -# it just no longer pulls `rusty_alloc-api` in, and lib.rs no longer installs the | ||
| 49 | -# `#[global_allocator]`. See the note in the workspace root Cargo.toml. | ||
| 50 | -default = [] | ||
| 51 | -global-alloc = [] | ||
| 52 | -profile = [] | ||
| 53 | - | ||
| 54 | -[lib] | ||
| 55 | -name = "rusty_h264_common" | ||
| 56 | -path = "src/lib.rs" | ||
| 57 | - | ||
| 58 | -[[example]] | ||
| 59 | -name = "bs_layout_ceiling" | ||
| 60 | -path = "examples/bs_layout_ceiling.rs" | ||
| 61 | - | ||
| 62 | -[[example]] | ||
| 63 | -name = "deblock_anatomy" | ||
| 64 | -path = "examples/deblock_anatomy.rs" | ||
| 65 | - | ||
| 66 | -[dependencies.bytemuck] | ||
| 67 | -version = "1" | ||
| 68 | - | ||
| 69 | -[dependencies.rusty_h264-accel] | ||
| 70 | -version = "0.9.1" | ||
| 71 | -optional = true | ||
| 72 | - | ||
| 73 | -[dependencies.wide] | ||
| 74 | -version = "0.7" | ||
vendor/rusty_h264-common/README.mddeleted+0 -122
| @@ -1,122 +0,0 @@ | |||
| 1 | -# rusty_h264-common | ||
| 2 | - | ||
| 3 | -[](https://crates.io/crates/rusty_h264-common) | ||
| 4 | -[](https://docs.rs/rusty_h264-common) | ||
| 5 | -[](https://github.com/remade-with-rust/rusty_h264/actions/workflows/ci.yml) | ||
| 6 | -[](https://github.com/remade-with-rust/rusty_h264/blob/main/LICENSE) | ||
| 7 | -[](https://github.com/Remade-With-Rust) | ||
| 8 | -[](https://www.mata.network/) | ||
| 9 | - | ||
| 10 | -> **The foundation both halves of the codec sit on.** Bitstream I/O, Exp-Golomb, | ||
| 11 | -> NAL/Annex-B framing, the integer transforms, intra prediction, motion | ||
| 12 | -> compensation and the deblocking filter — the shared `codec/common` layer of | ||
| 13 | -> the pure-Rust [`rusty_h264`](https://crates.io/crates/rusty_h264) codec. | ||
| 14 | - | ||
| 15 | -**Most users want the facade — [`rusty_h264`](https://crates.io/crates/rusty_h264).** | ||
| 16 | -Depend on this crate directly only if you are building on the primitives (a | ||
| 17 | -custom parser, an analyzer, your own codec) rather than encoding or decoding. | ||
| 18 | - | ||
| 19 | -Part of **[Remade With Rust](https://github.com/Remade-With-Rust)** by | ||
| 20 | -**[Mata Network](https://www.mata.network/)**. | ||
| 21 | - | ||
| 22 | ---- | ||
| 23 | - | ||
| 24 | -## Why it's `forbid(unsafe_code)` | ||
| 25 | - | ||
| 26 | -The bit-twiddling core of an H.264 codec — Exp-Golomb reads off a hostile | ||
| 27 | -bitstream, RBSP emulation handling, block-level pixel loops — is *exactly* where | ||
| 28 | -memory-safety bugs hide in the C implementations. So this crate is | ||
| 29 | -`#![forbid(unsafe_code)]`, and the shared reconstruction path here is what makes | ||
| 30 | -the encoder and decoder agree bit-for-bit. | ||
| 31 | - | ||
| 32 | -The single exception is opt-in and never shipped: the `profile` feature relaxes | ||
| 33 | -the attribute to unlock the `rdtsc` timer in [`prof`](https://docs.rs/rusty_h264-common/latest/rusty_h264_common/prof/) | ||
| 34 | -for stage measurement. The release build forbids `unsafe`. | ||
| 35 | - | ||
| 36 | -## Modules | ||
| 37 | - | ||
| 38 | -| Module | What's in it | | ||
| 39 | -|---|---| | ||
| 40 | -| `bit_writer` / `bit_reader` | MSB-first bit packing and parsing, Exp-Golomb (`ue`/`se`), bounded reads that return `OutOfData` instead of panicking | | ||
| 41 | -| `nal` | NAL units, Annex-B framing (`split_annex_b`), RBSP emulation prevention/unprevention | | ||
| 42 | -| `types` | `YuvFrame` (raw planar I420), `Profile`, `ChromaFormat` | | ||
| 43 | -| `transform` | 4×4 and 8×8 integer transforms, quantization/dequantization, luma & chroma DC Hadamard, scaling matrices | | ||
| 44 | -| `predict` | Intra prediction — `I_16x16`, `I_4x4`, `I_8x8`, chroma 8×8 | | ||
| 45 | -| `inter` | Quarter-pel luma motion compensation (6-tap), chroma MC, the interpolation half-pel planes | | ||
| 46 | -| `deblock` | The in-loop deblocking filter, luma + chroma, 8×8-transform-aware | | ||
| 47 | -| `cavlc` | CAVLC residual coding tables — table-driven **O(1)** decode (was O(bits·candidates)) | | ||
| 48 | -| `cabac_tables` | The 460-context CABAC initialization tables shared by both entropy engines | | ||
| 49 | -| `aligned` | `AlignedBytes` — a safe `[u8]` ↔ `[u128]` view (via `bytemuck`) giving 16-byte-aligned plane rows so the SIMD kernels can use aligned loads without `unsafe` here | | ||
| 50 | -| `prof` | Dev-only `rdtsc` stage profiler, behind the `profile` feature — zero cost when off | | ||
| 51 | - | ||
| 52 | -Also exported: `ACCEL: bool`, whether the vendored SIMD kernels are actually | ||
| 53 | -compiled in. Benchmarks read it so a harness that silently fell back to the | ||
| 54 | -scalar twin can't report the fast path's number. | ||
| 55 | - | ||
| 56 | -## Features | ||
| 57 | - | ||
| 58 | -| Feature | Default | Effect | | ||
| 59 | -|---|:--:|---| | ||
| 60 | -| `asm` | — | Route the hot kernels (deblock, MC, transforms, intra pred) through the vendored openh264 SIMD asm in [`rusty_h264-accel`](https://crates.io/crates/rusty_h264-accel). The `unsafe` FFI stays quarantined there; this crate calls only its safe wrappers and remains `forbid(unsafe)`. x86-64 + `nasm`. | | ||
| 61 | -| `profile` | — | Enable the in-process stage profiler. Measurement builds only — never ship it. | | ||
| 62 | - | ||
| 63 | -SIMD is enabled through the facade's default `asm` feature; when this crate is | ||
| 64 | -used standalone the scalar path is the default. | ||
| 65 | - | ||
| 66 | -## Install | ||
| 67 | - | ||
| 68 | -```sh | ||
| 69 | -cargo add rusty_h264-common | ||
| 70 | -``` | ||
| 71 | - | ||
| 72 | -```rust | ||
| 73 | -use rusty_h264_common::BitReader; | ||
| 74 | -use rusty_h264_common::nal::{emulation_unprevent, split_annex_b}; | ||
| 75 | - | ||
| 76 | -// Walk an Annex-B stream and read each NAL's header + first Exp-Golomb field. | ||
| 77 | -for nal in split_annex_b(&stream) { | ||
| 78 | - let rbsp = emulation_unprevent(nal); | ||
| 79 | - let mut r = BitReader::new(&rbsp); | ||
| 80 | - let _forbidden_zero = r.read_bits(1)?; | ||
| 81 | - let _nal_ref_idc = r.read_bits(2)?; | ||
| 82 | - let nal_unit_type = r.read_bits(5)?; | ||
| 83 | - println!("nal type {nal_unit_type}, first ue = {}", r.read_ue()?); | ||
| 84 | -} | ||
| 85 | -``` | ||
| 86 | - | ||
| 87 | -## Where this sits | ||
| 88 | - | ||
| 89 | -| Crate | Role | | ||
| 90 | -|---|---| | ||
| 91 | -| [`rusty_h264`](https://crates.io/crates/rusty_h264) | the public, safe facade API — **depend on this** | | ||
| 92 | -| **[`rusty_h264-common`](https://crates.io/crates/rusty_h264-common)** | **← you are here** — bitstream I/O, transforms, prediction, MC, deblock | | ||
| 93 | -| [`rusty_h264-encoder`](https://crates.io/crates/rusty_h264-encoder) | the encode pipeline | | ||
| 94 | -| [`rusty_h264-decoder`](https://crates.io/crates/rusty_h264-decoder) | the decode pipeline | | ||
| 95 | -| [`rusty_h264-accel`](https://crates.io/crates/rusty_h264-accel) | optional openh264 SIMD asm — the one `unsafe` crate | | ||
| 96 | - | ||
| 97 | -The workspace mirrors Cisco openh264's `codec/` tree; this crate is | ||
| 98 | -`codec/common`. | ||
| 99 | - | ||
| 100 | -## The Remade With Rust ecosystem | ||
| 101 | - | ||
| 102 | -<!-- ORG BOILERPLATE — keep identical across repos --> | ||
| 103 | - | ||
| 104 | -**Remade With Rust** is an initiative by **[Mata Network](https://www.mata.network/)** | ||
| 105 | -to rebuild essential C and C++ tools in Rust — for the memory safety, the | ||
| 106 | -predictable performance, and the freedom of a permissive license. Each project | ||
| 107 | -is a reimplementation, not a fork: same wire protocols and file formats, new | ||
| 108 | -code you can actually depend on. No copyleft. No surprises. | ||
| 109 | - | ||
| 110 | -| Project | What it is | | ||
| 111 | -|---|---| | ||
| 112 | -| 🎬 **[remade_ffmpeg_rs](https://github.com/Remade-With-Rust/remade_ffmpeg_rs)** | **Our FFmpeg alternative.** Drop-in `ffmpeg` and `ffprobe` binaries — demux → decode → filter → encode → mux, rebuilt as composable Rust crates with **zero GPL/LGPL**. Apache-2.0. `rusty_h264` is its H.264 codec. | | ||
| 113 | -| 🧠 **[FFAI](https://github.com/Remade-With-Rust/FFAI)** | **Our sister project: media *for* AI.** "The AI media toolkit, remade with rust." Embedded ASR + TTS (**Mercury**), OCR (**Carmenta**) and vision-language captioning (**Argus**) behind an ffmpeg-style, swap-by-name architecture — no Python, no CUDA. MIT OR Apache-2.0. | | ||
| 114 | -| 🌐 **[Mata Network](https://www.mata.network/)** | **The home page.** *"Stop sacrificing your privacy for convenience."* Sovereign, self-hostable privacy infrastructure — wallet & identity, password manager, contact manager, and a browser extension that stops information leaking as you browse. Remade With Rust is its open-source arm. | | ||
| 115 | - | ||
| 116 | -→ All projects: **[github.com/Remade-With-Rust](https://github.com/Remade-With-Rust)** | ||
| 117 | - | ||
| 118 | -<!-- /ORG BOILERPLATE --> | ||
| 119 | - | ||
| 120 | -## License | ||
| 121 | - | ||
| 122 | -BSD-2-Clause — see [LICENSE](https://github.com/remade-with-rust/rusty_h264/blob/main/LICENSE). | ||
vendor/rusty_h264-common/build.rsdeleted+0 -18
| @@ -1,18 +0,0 @@ | |||
| 1 | -//! Defines the internal `accel` cfg = "the `asm` feature is on AND we target x86_64". | ||
| 2 | -//! | ||
| 3 | -//! The vendored openh264 SIMD kernels in `rusty_h264-accel` are x86-64 only, so the | ||
| 4 | -//! `accel` code paths must not be compiled on other architectures even when a downstream | ||
| 5 | -//! crate enables the (default) `asm` feature. On non-x86_64 targets `accel` stays unset | ||
| 6 | -//! and the codec uses its pure-Rust scalar path — so e.g. `rff` builds on arm64 macOS | ||
| 7 | -//! with default features and without nasm. | ||
| 8 | -fn main() { | ||
| 9 | - // Declare the custom cfg so `unexpected_cfgs` (Rust 1.80+) stays quiet; older Cargo | ||
| 10 | - // ignores the line (and lacks the lint anyway). | ||
| 11 | - println!("cargo::rustc-check-cfg=cfg(accel)"); | ||
| 12 | - let asm = std::env::var_os("CARGO_FEATURE_ASM").is_some(); | ||
| 13 | - let x86_64 = std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("x86_64"); | ||
| 14 | - if asm && x86_64 { | ||
| 15 | - // Single-colon form: understood by every Cargo version. | ||
| 16 | - println!("cargo:rustc-cfg=accel"); | ||
| 17 | - } | ||
| 18 | -} | ||
vendor/rusty_h264-common/examples/bs_layout_ceiling.rsdeleted+0 -251
| @@ -1,251 +0,0 @@ | |||
| 1 | -//! CEILING PROBE — is the bS derivation's 25x gap vs x264 really about LAYOUT? | ||
| 2 | -//! | ||
| 3 | -//! `docs/WHYS-decoder-perf.md` established: bS derivation is ~20% of decode at | ||
| 4 | -//! ~400 ns/MB, against x264's `deblock_strength_avx2` at ~15 ns/MB, and the Step 0 | ||
| 5 | -//! audit showed our derivation emits ZERO packed ops because `gather_tile` is a | ||
| 6 | -//! gather — 24 blocks across 4-6 SEPARATE frame-wide arrays. | ||
| 7 | -//! | ||
| 8 | -//! The hypothesis is that x264 wins on LAYOUT (packed per-MB nnz bitmask + per-MB | ||
| 9 | -//! contiguous ref/mv) and that the SIMD is downstream of it. That implies a large, | ||
| 10 | -//! risky refactor of the decoder's macroblock loop, so PROVE THE CEILING FIRST: | ||
| 11 | -//! measure the gather alone, current layout vs packed, with no decoder changes. | ||
| 12 | -//! | ||
| 13 | -//! The probe deliberately measures ONLY the gather. If packed-vs-strided is a small | ||
| 14 | -//! ratio here, the refactor cannot pay however good a kernel sits behind it — and | ||
| 15 | -//! that is a whole day saved for twenty minutes of probe. | ||
| 16 | -//! | ||
| 17 | -//! Also reports a DETERMINISTIC cache-line count, because this box cannot currently | ||
| 18 | -//! resolve timing (see the noise-floor sections of the WHYS doc): the line count is | ||
| 19 | -//! the part of the answer that machine load cannot touch. | ||
| 20 | -//! | ||
| 21 | -//! ```text | ||
| 22 | -//! cargo run --release -p rusty_h264-common --example bs_layout_ceiling | ||
| 23 | -//! ``` | ||
| 24 | - | ||
| 25 | -use std::hint::black_box; | ||
| 26 | -use std::time::Instant; | ||
| 27 | - | ||
| 28 | -const MB_W: usize = 80; // 1280/16 | ||
| 29 | -const MB_H: usize = 45; // 720/16 | ||
| 30 | -const W4: usize = MB_W * 4; | ||
| 31 | - | ||
| 32 | -/// The CURRENT shape: separate frame-wide arrays, one per field. | ||
| 33 | -struct Soa { | ||
| 34 | - inter: Vec<bool>, | ||
| 35 | - nnz: Vec<u8>, | ||
| 36 | - mv: Vec<(i32, i32)>, | ||
| 37 | - ref_id: Vec<i32>, | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -/// The PACKED shape, mirroring x264's per-macroblock cache: everything one | ||
| 41 | -/// macroblock's derivation needs, contiguous, in raster order. | ||
| 42 | -/// | ||
| 43 | -/// `nnz` collapses to a 16-BIT MASK — the derivation only ever asks "is this block | ||
| 44 | -/// coded", never for the count — which is also what makes the coefficient half of | ||
| 45 | -/// the strength test a shift-and-or on a single register instead of 32 byte loads. | ||
| 46 | -#[derive(Clone, Copy, Default)] | ||
| 47 | -#[repr(C, align(64))] | ||
| 48 | -struct MbRec { | ||
| 49 | - nnz_mask: u16, | ||
| 50 | - inter: bool, | ||
| 51 | - _pad: u8, | ||
| 52 | - ref_id: [i16; 16], | ||
| 53 | - mv: [(i16, i16); 16], | ||
| 54 | -} | ||
| 55 | - | ||
| 56 | -fn build_soa() -> Soa { | ||
| 57 | - let n = W4 * MB_H * 4; | ||
| 58 | - // Deterministic pseudo-random content; a plausible mix of coded/uncoded and | ||
| 59 | - // varying motion, so neither layout gets an unrealistically friendly pattern. | ||
| 60 | - let mut s = 0x2545F491u32; | ||
| 61 | - let mut rnd = move || { | ||
| 62 | - s ^= s << 13; | ||
| 63 | - s ^= s >> 17; | ||
| 64 | - s ^= s << 5; | ||
| 65 | - s | ||
| 66 | - }; | ||
| 67 | - let mut soa = | ||
| 68 | - Soa { inter: vec![true; n], nnz: vec![0; n], mv: vec![(0, 0); n], ref_id: vec![0; n] }; | ||
| 69 | - for i in 0..n { | ||
| 70 | - let r = rnd(); | ||
| 71 | - soa.inter[i] = (r & 0x1f) != 0; // ~3% intra | ||
| 72 | - soa.nnz[i] = if (r >> 5) & 3 == 0 { 1 } else { 0 }; | ||
| 73 | - soa.mv[i] = (((r >> 7) & 0x3f) as i32 - 32, ((r >> 13) & 0x3f) as i32 - 32); | ||
| 74 | - soa.ref_id[i] = ((r >> 19) & 1) as i32; | ||
| 75 | - } | ||
| 76 | - soa | ||
| 77 | -} | ||
| 78 | - | ||
| 79 | -fn build_packed(soa: &Soa) -> Vec<MbRec> { | ||
| 80 | - let mut v = vec![MbRec::default(); MB_W * MB_H]; | ||
| 81 | - for mb_y in 0..MB_H { | ||
| 82 | - for mb_x in 0..MB_W { | ||
| 83 | - let rec = &mut v[mb_y * MB_W + mb_x]; | ||
| 84 | - let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 85 | - rec.inter = soa.inter[by0 * W4 + bx0]; | ||
| 86 | - for r in 0..4 { | ||
| 87 | - for c in 0..4 { | ||
| 88 | - let i = (by0 + r) * W4 + bx0 + c; | ||
| 89 | - let k = r * 4 + c; | ||
| 90 | - if soa.nnz[i] != 0 { | ||
| 91 | - rec.nnz_mask |= 1 << k; | ||
| 92 | - } | ||
| 93 | - rec.ref_id[k] = soa.ref_id[i] as i16; | ||
| 94 | - rec.mv[k] = (soa.mv[i].0 as i16, soa.mv[i].1 as i16); | ||
| 95 | - } | ||
| 96 | - } | ||
| 97 | - } | ||
| 98 | - } | ||
| 99 | - v | ||
| 100 | -} | ||
| 101 | - | ||
| 102 | -/// ARM A — the gather as it exists today: 24 blocks, each pulling from 4 separate | ||
| 103 | -/// frame-wide arrays at a strided index. | ||
| 104 | -#[inline(never)] | ||
| 105 | -fn gather_strided(soa: &Soa, mb_x: usize, mb_y: usize) -> u64 { | ||
| 106 | - let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 107 | - let mut acc = 0u64; | ||
| 108 | - let mut take = |i: usize| { | ||
| 109 | - acc = acc | ||
| 110 | - .wrapping_add(soa.inter[i] as u64) | ||
| 111 | - .wrapping_add(soa.nnz[i] as u64) | ||
| 112 | - .wrapping_add(soa.ref_id[i] as u64) | ||
| 113 | - .wrapping_add(soa.mv[i].0 as u64) | ||
| 114 | - .wrapping_add(soa.mv[i].1 as u64); | ||
| 115 | - }; | ||
| 116 | - for r in 0..4 { | ||
| 117 | - for c in 0..4 { | ||
| 118 | - take((by0 + r) * W4 + bx0 + c); | ||
| 119 | - } | ||
| 120 | - } | ||
| 121 | - if mb_x > 0 { | ||
| 122 | - for r in 0..4 { | ||
| 123 | - take((by0 + r) * W4 + bx0 - 1); | ||
| 124 | - } | ||
| 125 | - } | ||
| 126 | - if mb_y > 0 { | ||
| 127 | - for c in 0..4 { | ||
| 128 | - take((by0 - 1) * W4 + bx0 + c); | ||
| 129 | - } | ||
| 130 | - } | ||
| 131 | - acc | ||
| 132 | -} | ||
| 133 | - | ||
| 134 | -/// ARM B — the same information out of packed per-macroblock records: one | ||
| 135 | -/// contiguous record for this macroblock plus the left and top neighbours'. | ||
| 136 | -#[inline(never)] | ||
| 137 | -fn gather_packed(recs: &[MbRec], mb_x: usize, mb_y: usize) -> u64 { | ||
| 138 | - let cur = &recs[mb_y * MB_W + mb_x]; | ||
| 139 | - let mut acc = cur.nnz_mask as u64 + cur.inter as u64; | ||
| 140 | - for k in 0..16 { | ||
| 141 | - acc = acc | ||
| 142 | - .wrapping_add(cur.ref_id[k] as u64) | ||
| 143 | - .wrapping_add(cur.mv[k].0 as u64) | ||
| 144 | - .wrapping_add(cur.mv[k].1 as u64); | ||
| 145 | - } | ||
| 146 | - if mb_x > 0 { | ||
| 147 | - let l = &recs[mb_y * MB_W + mb_x - 1]; | ||
| 148 | - for r in 0..4 { | ||
| 149 | - let k = r * 4 + 3; // right-hand column of the left neighbour | ||
| 150 | - acc = acc | ||
| 151 | - .wrapping_add(l.ref_id[k] as u64) | ||
| 152 | - .wrapping_add(l.mv[k].0 as u64) | ||
| 153 | - .wrapping_add(l.mv[k].1 as u64); | ||
| 154 | - } | ||
| 155 | - } | ||
| 156 | - if mb_y > 0 { | ||
| 157 | - let t = &recs[(mb_y - 1) * MB_W + mb_x]; | ||
| 158 | - for c in 0..4 { | ||
| 159 | - let k = 12 + c; // bottom row of the top neighbour | ||
| 160 | - acc = acc | ||
| 161 | - .wrapping_add(t.ref_id[k] as u64) | ||
| 162 | - .wrapping_add(t.mv[k].0 as u64) | ||
| 163 | - .wrapping_add(t.mv[k].1 as u64); | ||
| 164 | - } | ||
| 165 | - } | ||
| 166 | - acc | ||
| 167 | -} | ||
| 168 | - | ||
| 169 | -fn main() { | ||
| 170 | - let soa = build_soa(); | ||
| 171 | - let recs = build_packed(&soa); | ||
| 172 | - let mbs = MB_W * MB_H; | ||
| 173 | - | ||
| 174 | - // ---- DETERMINISTIC part: distinct 64-byte cache lines touched per macroblock. | ||
| 175 | - // Immune to machine load, which is why it leads. | ||
| 176 | - let line = |addr: usize| addr / 64; | ||
| 177 | - let mut a_lines = std::collections::HashSet::new(); | ||
| 178 | - let mut b_lines = std::collections::HashSet::new(); | ||
| 179 | - let (mb_x, mb_y) = (MB_W / 2, MB_H / 2); | ||
| 180 | - let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 181 | - let base = |p: *const u8| p as usize; | ||
| 182 | - for r in 0..4 { | ||
| 183 | - for c in 0..4 { | ||
| 184 | - let i = (by0 + r) * W4 + bx0 + c; | ||
| 185 | - a_lines.insert(line(base(soa.inter.as_ptr() as *const u8) + i)); | ||
| 186 | - a_lines.insert(line(base(soa.nnz.as_ptr()) + i)); | ||
| 187 | - a_lines.insert(line(base(soa.ref_id.as_ptr() as *const u8) + i * 4)); | ||
| 188 | - a_lines.insert(line(base(soa.mv.as_ptr() as *const u8) + i * 8)); | ||
| 189 | - } | ||
| 190 | - } | ||
| 191 | - let rec_base = base(recs.as_ptr() as *const u8) + (mb_y * MB_W + mb_x) * size_of::<MbRec>(); | ||
| 192 | - for off in (0..size_of::<MbRec>()).step_by(64) { | ||
| 193 | - b_lines.insert(line(rec_base + off)); | ||
| 194 | - } | ||
| 195 | - | ||
| 196 | - println!("bS-derivation LAYOUT ceiling probe — 720p, {mbs} macroblocks\n"); | ||
| 197 | - println!("DETERMINISTIC (machine load cannot move these):"); | ||
| 198 | - println!(" MbRec size {:>6} bytes", size_of::<MbRec>()); | ||
| 199 | - println!(" cache lines / MB, strided SoA {:>6} (own 16 blocks x 4 arrays)", a_lines.len()); | ||
| 200 | - println!(" cache lines / MB, packed {:>6}", b_lines.len()); | ||
| 201 | - println!( | ||
| 202 | - " ratio {:>6.2}x fewer lines\n", | ||
| 203 | - a_lines.len() as f64 / b_lines.len().max(1) as f64 | ||
| 204 | - ); | ||
| 205 | - | ||
| 206 | - // ---- TIMED part: best-of-N, arms ABBA-alternated. Caveated on purpose. | ||
| 207 | - let reps = 30; | ||
| 208 | - let (mut best_a, mut best_b) = (f64::MAX, f64::MAX); | ||
| 209 | - for rep in 0..reps { | ||
| 210 | - let run_a = || { | ||
| 211 | - let t = Instant::now(); | ||
| 212 | - let mut acc = 0u64; | ||
| 213 | - for y in 0..MB_H { | ||
| 214 | - for x in 0..MB_W { | ||
| 215 | - acc = acc.wrapping_add(gather_strided(black_box(&soa), x, y)); | ||
| 216 | - } | ||
| 217 | - } | ||
| 218 | - (t.elapsed().as_secs_f64(), black_box(acc)) | ||
| 219 | - }; | ||
| 220 | - let run_b = || { | ||
| 221 | - let t = Instant::now(); | ||
| 222 | - let mut acc = 0u64; | ||
| 223 | - for y in 0..MB_H { | ||
| 224 | - for x in 0..MB_W { | ||
| 225 | - acc = acc.wrapping_add(gather_packed(black_box(&recs), x, y)); | ||
| 226 | - } | ||
| 227 | - } | ||
| 228 | - (t.elapsed().as_secs_f64(), black_box(acc)) | ||
| 229 | - }; | ||
| 230 | - // Alternate which arm runs first so warm-up bias cancels. | ||
| 231 | - let (ta, tb) = if rep % 2 == 0 { | ||
| 232 | - let (ta, _) = run_a(); | ||
| 233 | - let (tb, _) = run_b(); | ||
| 234 | - (ta, tb) | ||
| 235 | - } else { | ||
| 236 | - let (tb, _) = run_b(); | ||
| 237 | - let (ta, _) = run_a(); | ||
| 238 | - (ta, tb) | ||
| 239 | - }; | ||
| 240 | - best_a = best_a.min(ta); | ||
| 241 | - best_b = best_b.min(tb); | ||
| 242 | - } | ||
| 243 | - let ns = |t: f64| t * 1e9 / mbs as f64; | ||
| 244 | - println!("TIMED (best-of-{reps}, arms alternated — treat as INDICATIVE only;"); | ||
| 245 | - println!(" this box has shown 45% within-arm spread under foreign load):"); | ||
| 246 | - println!(" strided SoA gather {:>7.1} ns/MB", ns(best_a)); | ||
| 247 | - println!(" packed gather {:>7.1} ns/MB", ns(best_b)); | ||
| 248 | - println!(" ratio {:>7.2}x", best_a / best_b); | ||
| 249 | - println!("\nFor scale: the whole derivation measures ~400 ns/MB in context;"); | ||
| 250 | - println!("x264's deblock_strength_avx2 does the entire job in ~15 ns/MB."); | ||
| 251 | -} | ||
vendor/rusty_h264-common/examples/deblock_anatomy.rsdeleted+0 -177
| @@ -1,177 +0,0 @@ | |||
| 1 | -//! Deblock anatomy bench — isolates where `filter_frame` spends its time. | ||
| 2 | -//! | ||
| 3 | -//! Motivated by the video-tests function-level comparison, which put our | ||
| 4 | -//! deblocking well behind x264's. x264 splits the work in two: boundary | ||
| 5 | -//! strengths are derived in its MB-encode loop by an asm kernel | ||
| 6 | -//! (`deblock_strength_avx2`, ~15 ns/MB measured in-context), and | ||
| 7 | -//! `frame_deblock_row` only filters. Ours does both inside `filter_frame`, so a | ||
| 8 | -//! stage-vs-stage read overstates the gap — and hides which half is actually slow. | ||
| 9 | -//! | ||
| 10 | -//! Four scenarios separate the two halves. The key one is `inter-bs0`: every | ||
| 11 | -//! boundary strength derives to 0, so NO filter kernel runs and the number is | ||
| 12 | -//! pure bS-derivation + loop glue. | ||
| 13 | -//! | ||
| 14 | -//! ```text | ||
| 15 | -//! cargo run --release -p rusty_h264-common --features asm --example deblock_anatomy | ||
| 16 | -//! ``` | ||
| 17 | - | ||
| 18 | -use rusty_h264_common::deblock::{filter_frame, BlockInfo}; | ||
| 19 | - | ||
| 20 | -struct Grid { | ||
| 21 | - inter: Vec<bool>, | ||
| 22 | - nnz: Vec<u8>, | ||
| 23 | - mv: Vec<(i32, i32)>, | ||
| 24 | - ref_id: Vec<i32>, | ||
| 25 | - t8x8: Vec<bool>, | ||
| 26 | -} | ||
| 27 | - | ||
| 28 | -const NO_REF: i32 = i32::MIN; | ||
| 29 | - | ||
| 30 | -/// Build the per-4×4-block state for one scenario. | ||
| 31 | -fn grid(kind: &str, mb_w: usize, mb_h: usize) -> Grid { | ||
| 32 | - let (w4, h4) = (mb_w * 4, mb_h * 4); | ||
| 33 | - let n = w4 * h4; | ||
| 34 | - let mut g = Grid { | ||
| 35 | - inter: vec![true; n], | ||
| 36 | - nnz: vec![0u8; n], | ||
| 37 | - mv: vec![(0i32, 0i32); n], | ||
| 38 | - ref_id: vec![0i32; n], | ||
| 39 | - t8x8: Vec::new(), | ||
| 40 | - }; | ||
| 41 | - match kind { | ||
| 42 | - // Every block intra: bS is 4 on MB edges, 3 internally — maximum | ||
| 43 | - // filtering, and the bS derivation never reaches the motion comparison. | ||
| 44 | - "all-intra" => { | ||
| 45 | - g.inter.iter_mut().for_each(|b| *b = false); | ||
| 46 | - g.ref_id.iter_mut().for_each(|r| *r = NO_REF); | ||
| 47 | - } | ||
| 48 | - // Every MB a skip: all inter, no coefficients, one shared (ref, mv). | ||
| 49 | - // The flat-inter gate fires, so only MB edges are considered. | ||
| 50 | - "skip" => {} | ||
| 51 | - // Every block has coefficients: bS = 2 everywhere, so every edge filters. | ||
| 52 | - "inter-coded" => { | ||
| 53 | - g.nnz.iter_mut().for_each(|c| *c = 4); | ||
| 54 | - } | ||
| 55 | - // The isolator: all inter, no coefficients, motion that VARIES (so the | ||
| 56 | - // flat-inter gate cannot fire) but by less than one full sample (so every | ||
| 57 | - // bS still derives to 0 and no filter kernel runs). What remains is the | ||
| 58 | - // bS derivation and the loop around it, and nothing else. | ||
| 59 | - "inter-bs0" => { | ||
| 60 | - for (i, m) in g.mv.iter_mut().enumerate() { | ||
| 61 | - // ±1 quarter-pel: |Δ| < 4 for every neighbour pair ⇒ bS 0. | ||
| 62 | - *m = ((i % 2) as i32, ((i / 2) % 2) as i32); | ||
| 63 | - } | ||
| 64 | - } | ||
| 65 | - // Real content, unlike every scenario above, mixes intra/inter, coded and | ||
| 66 | - // uncoded blocks, and varying motion WITHIN a macroblock — so the bS | ||
| 67 | - // derivation's branches are unpredictable. The uniform scenarios let the | ||
| 68 | - // predictor get every branch right, which is why they came in at ~240 | ||
| 69 | - // ns/MB while real clips measure ~650. | ||
| 70 | - "mixed" => { | ||
| 71 | - let mut st = 0x12345678u32; | ||
| 72 | - let mut rnd = || { | ||
| 73 | - st ^= st << 13; | ||
| 74 | - st ^= st >> 17; | ||
| 75 | - st ^= st << 5; | ||
| 76 | - st | ||
| 77 | - }; | ||
| 78 | - for i in 0..n { | ||
| 79 | - let r = rnd(); | ||
| 80 | - g.inter[i] = r & 7 != 0; // ~1 in 8 blocks intra | ||
| 81 | - g.nnz[i] = if r & 0x30 != 0 { (r >> 8 & 7) as u8 } else { 0 }; | ||
| 82 | - g.mv[i] = (((r >> 11) & 15) as i32 - 8, ((r >> 15) & 15) as i32 - 8); | ||
| 83 | - g.ref_id[i] = if g.inter[i] { ((r >> 19) & 1) as i32 } else { NO_REF }; | ||
| 84 | - } | ||
| 85 | - } | ||
| 86 | - _ => panic!("unknown scenario {kind}"), | ||
| 87 | - } | ||
| 88 | - g | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -fn main() { | ||
| 92 | - let cases = [(176usize, 144usize, "QCIF"), (352, 288, "CIF"), (1280, 720, "720p")]; | ||
| 93 | - let scenarios = ["all-intra", "inter-coded", "inter-bs0", "skip", "mixed"]; | ||
| 94 | - | ||
| 95 | - println!("ns per macroblock, best-of-30 per arm, arms alternated pass by pass | ||
| 96 | -"); | ||
| 97 | - println!( | ||
| 98 | - "{:<8} {:<12} {:>12} {:>12} {:>10}", | ||
| 99 | - "size", "scenario", "branchy", "branchless", "speedup" | ||
| 100 | - ); | ||
| 101 | - println!("{}", "-".repeat(60)); | ||
| 102 | - | ||
| 103 | - for (w, h, label) in cases { | ||
| 104 | - let (mb_w, mb_h) = (w / 16, h / 16); | ||
| 105 | - let mbs = mb_w * mb_h; | ||
| 106 | - let (cw, ch) = (w / 2, h / 2); | ||
| 107 | - let mb_qp = vec![26u8; mbs]; | ||
| 108 | - | ||
| 109 | - for kind in scenarios { | ||
| 110 | - let g = grid(kind, mb_w, mb_h); | ||
| 111 | - // Content shaped like a real RECONSTRUCTION, not noise. The filter | ||
| 112 | - // rejects an edge whose |p0-q0| >= alpha or |p1-p0| >= beta (~13/~6 at | ||
| 113 | - // QP 26), so high-frequency synthetic data makes it early-out and the | ||
| 114 | - // bench silently measures a filter that is barely running. A slow ramp | ||
| 115 | - // with a small step at each 4-sample block boundary — exactly the | ||
| 116 | - // blocking artefact deblocking exists to remove — keeps every edge | ||
| 117 | - // inside the thresholds, so the kernels do their full work. | ||
| 118 | - let px = |x: usize, yy: usize| -> u8 { | ||
| 119 | - let ramp = 100 + ((x / 8 + yy / 8) % 24); | ||
| 120 | - let step = ((x / 4) % 3) + ((yy / 4) % 2); // small block-edge discontinuity | ||
| 121 | - (ramp + step) as u8 | ||
| 122 | - }; | ||
| 123 | - let y0: Vec<u8> = (0..w * h).map(|i| px(i % w, i / w)).collect(); | ||
| 124 | - let u0: Vec<u8> = (0..cw * ch).map(|i| px(i % cw, i / cw)).collect(); | ||
| 125 | - let v0: Vec<u8> = (0..cw * ch).map(|i| px((i % cw) + 3, i / cw)).collect(); | ||
| 126 | - let (mut y, mut u, mut v) = (y0.clone(), u0.clone(), v0.clone()); | ||
| 127 | - | ||
| 128 | - // ALTERNATE the two bS arms pass by pass so both see the same | ||
| 129 | - // thermal state; separate builds drift ~20% on this machine, which is | ||
| 130 | - // larger than the effect being measured. | ||
| 131 | - let mut best = [f64::MAX; 2]; | ||
| 132 | - for pass in 0..60 { | ||
| 133 | - let branchless = pass % 2 == 0; | ||
| 134 | - rusty_h264_common::deblock::set_branchless_bs(branchless); | ||
| 135 | - // CRITICAL: filter_frame smooths in place. Without restoring the | ||
| 136 | - // source each pass, successive iterations run on progressively | ||
| 137 | - // flatter data, the filter's α/β early-outs start firing, and | ||
| 138 | - // best-of-N reports the cheapest (most-smoothed) pass rather than | ||
| 139 | - // the real cost. Restore outside the timed region. | ||
| 140 | - y.copy_from_slice(&y0); | ||
| 141 | - u.copy_from_slice(&u0); | ||
| 142 | - v.copy_from_slice(&v0); | ||
| 143 | - let info = BlockInfo { | ||
| 144 | - inter: &g.inter, | ||
| 145 | - nnz: &g.nnz, | ||
| 146 | - mv: &g.mv, | ||
| 147 | - ref_id: &g.ref_id, | ||
| 148 | - mv1: &[], | ||
| 149 | - ref_id1: &[], | ||
| 150 | - w4: mb_w * 4, | ||
| 151 | - t8x8: &g.t8x8, | ||
| 152 | - poc0: &[], | ||
| 153 | - poc1: &[], | ||
| 154 | - bs: &[], kind: &[], | ||
| 155 | - }; | ||
| 156 | - let t = std::time::Instant::now(); | ||
| 157 | - filter_frame(&mut y, &mut u, &mut v, mb_w, mb_h, &mb_qp, 0, 0, 0, &info); | ||
| 158 | - let e = t.elapsed().as_secs_f64(); | ||
| 159 | - let slot = if branchless { 0 } else { 1 }; | ||
| 160 | - if e < best[slot] { | ||
| 161 | - best[slot] = e; | ||
| 162 | - } | ||
| 163 | - std::hint::black_box((&y, &u, &v)); | ||
| 164 | - } | ||
| 165 | - let ns = |t: f64| t * 1e9 / mbs as f64; | ||
| 166 | - println!( | ||
| 167 | - "{:<8} {:<12} {:>12.1} {:>12.1} {:>9.2}x", | ||
| 168 | - label, | ||
| 169 | - kind, | ||
| 170 | - ns(best[1]), | ||
| 171 | - ns(best[0]), | ||
| 172 | - ns(best[1]) / ns(best[0]) | ||
| 173 | - ); | ||
| 174 | - } | ||
| 175 | - println!(); | ||
| 176 | - } | ||
| 177 | -} | ||
vendor/rusty_h264-common/src/aligned.rsdeleted+0 -55
| @@ -1,55 +0,0 @@ | |||
| 1 | -//! A 16-byte-aligned heap byte buffer for the openh264 spatial asm kernels. | ||
| 2 | -//! | ||
| 3 | -//! openh264's deblock / MC / intra-prediction asm load aligned 16-byte row chunks | ||
| 4 | -//! (`movdqa`), which a plain `Vec<u8>` (alignment 1) cannot satisfy. [`AlignedBytes`] | ||
| 5 | -//! is backed by a `Vec<u128>` (alignment 16) and viewed as `[u8]` through `bytemuck` | ||
| 6 | -//! — guaranteed 16-aligned, no `unsafe`. It `Deref`s to `[u8]`, so it is a drop-in for | ||
| 7 | -//! the reconstruction / reference plane buffers (`FrameEncoder` rec planes, `RefFrame`). | ||
| 8 | - | ||
| 9 | -use std::ops::{Deref, DerefMut}; | ||
| 10 | - | ||
| 11 | -/// A heap byte buffer guaranteed to start on a 16-byte boundary. | ||
| 12 | -#[derive(Clone, Default)] | ||
| 13 | -pub struct AlignedBytes { | ||
| 14 | - words: Vec<u128>, | ||
| 15 | - len: usize, | ||
| 16 | -} | ||
| 17 | - | ||
| 18 | -impl AlignedBytes { | ||
| 19 | - /// A zero-filled, 16-byte-aligned buffer of `len` bytes. | ||
| 20 | - pub fn zeroed(len: usize) -> Self { | ||
| 21 | - Self { | ||
| 22 | - words: vec![0u128; (len + 15) / 16], | ||
| 23 | - len, | ||
| 24 | - } | ||
| 25 | - } | ||
| 26 | - | ||
| 27 | - pub fn len(&self) -> usize { | ||
| 28 | - self.len | ||
| 29 | - } | ||
| 30 | - | ||
| 31 | - pub fn is_empty(&self) -> bool { | ||
| 32 | - self.len == 0 | ||
| 33 | - } | ||
| 34 | -} | ||
| 35 | - | ||
| 36 | -impl std::fmt::Debug for AlignedBytes { | ||
| 37 | - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 38 | - write!(f, "AlignedBytes({} bytes)", self.len) | ||
| 39 | - } | ||
| 40 | -} | ||
| 41 | - | ||
| 42 | -impl Deref for AlignedBytes { | ||
| 43 | - type Target = [u8]; | ||
| 44 | - #[inline] | ||
| 45 | - fn deref(&self) -> &[u8] { | ||
| 46 | - &bytemuck::cast_slice(&self.words)[..self.len] | ||
| 47 | - } | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | -impl DerefMut for AlignedBytes { | ||
| 51 | - #[inline] | ||
| 52 | - fn deref_mut(&mut self) -> &mut [u8] { | ||
| 53 | - &mut bytemuck::cast_slice_mut(&mut self.words)[..self.len] | ||
| 54 | - } | ||
| 55 | -} | ||
vendor/rusty_h264-common/src/bit_reader.rsdeleted+0 -343
| @@ -1,343 +0,0 @@ | |||
| 1 | -//! MSB-first bit reader with H.264 Exp-Golomb decoding. | ||
| 2 | -//! | ||
| 3 | -//! The inverse of [`crate::BitWriter`]. Operates over an RBSP byte slice | ||
| 4 | -//! (emulation-prevention bytes already removed — see [`crate::nal`]). | ||
| 5 | - | ||
| 6 | -/// Error returned when a read runs past the end of the buffer. | ||
| 7 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 8 | -pub struct OutOfData; | ||
| 9 | - | ||
| 10 | -impl core::fmt::Display for OutOfData { | ||
| 11 | - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| 12 | - f.write_str("bit reader ran out of data") | ||
| 13 | - } | ||
| 14 | -} | ||
| 15 | - | ||
| 16 | -impl std::error::Error for OutOfData {} | ||
| 17 | - | ||
| 18 | -/// A big-endian, MSB-first bit reader. | ||
| 19 | -#[derive(Debug, Clone)] | ||
| 20 | -pub struct BitReader<'a> { | ||
| 21 | - data: &'a [u8], | ||
| 22 | - /// Absolute bit position from the start of `data`. | ||
| 23 | - pos: usize, | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -impl<'a> BitReader<'a> { | ||
| 27 | - /// Wraps an RBSP byte slice. | ||
| 28 | - pub fn new(data: &'a [u8]) -> Self { | ||
| 29 | - Self { data, pos: 0 } | ||
| 30 | - } | ||
| 31 | - | ||
| 32 | - /// The underlying RBSP buffer (for handing off to the CABAC engine). | ||
| 33 | - pub fn data(&self) -> &'a [u8] { | ||
| 34 | - self.data | ||
| 35 | - } | ||
| 36 | - | ||
| 37 | - /// Current bit position. | ||
| 38 | - pub fn bit_pos(&self) -> usize { | ||
| 39 | - self.pos | ||
| 40 | - } | ||
| 41 | - | ||
| 42 | - /// Total number of bits in the buffer. | ||
| 43 | - pub fn bit_len(&self) -> usize { | ||
| 44 | - self.data.len() * 8 | ||
| 45 | - } | ||
| 46 | - | ||
| 47 | - /// Bits remaining. | ||
| 48 | - pub fn bits_left(&self) -> usize { | ||
| 49 | - self.bit_len().saturating_sub(self.pos) | ||
| 50 | - } | ||
| 51 | - | ||
| 52 | - /// `more_rbsp_data()` (spec §7.2): true while the read position is before the | ||
| 53 | - /// `rbsp_stop_one_bit` (the last set bit in the buffer). Used to detect the | ||
| 54 | - /// end of `slice_data()` when a picture is split into multiple slices. | ||
| 55 | - pub fn more_rbsp_data(&self) -> bool { | ||
| 56 | - // Stop bit = the last 1 bit in the buffer; in MSB-first order that is the | ||
| 57 | - // lowest set bit of the last non-zero byte. | ||
| 58 | - let stop = self | ||
| 59 | - .data | ||
| 60 | - .iter() | ||
| 61 | - .enumerate() | ||
| 62 | - .rev() | ||
| 63 | - .find(|(_, &b)| b != 0) | ||
| 64 | - .map(|(bi, &b)| bi * 8 + (7 - b.trailing_zeros() as usize)); | ||
| 65 | - match stop { | ||
| 66 | - Some(s) => self.pos < s, | ||
| 67 | - None => false, | ||
| 68 | - } | ||
| 69 | - } | ||
| 70 | - | ||
| 71 | - /// `true` if the read position sits on a byte boundary. | ||
| 72 | - pub fn is_byte_aligned(&self) -> bool { | ||
| 73 | - self.pos % 8 == 0 | ||
| 74 | - } | ||
| 75 | - | ||
| 76 | - /// Advances to the next byte boundary, consuming the intervening bits (e.g. | ||
| 77 | - /// `pcm_alignment_zero_bit`s before an `I_PCM` payload). | ||
| 78 | - pub fn align_to_byte(&mut self) -> Result<(), OutOfData> { | ||
| 79 | - while self.pos % 8 != 0 { | ||
| 80 | - self.read_bit()?; | ||
| 81 | - } | ||
| 82 | - Ok(()) | ||
| 83 | - } | ||
| 84 | - | ||
| 85 | - /// Reads a single bit. | ||
| 86 | - pub fn read_bit(&mut self) -> Result<bool, OutOfData> { | ||
| 87 | - if self.pos >= self.bit_len() { | ||
| 88 | - return Err(OutOfData); | ||
| 89 | - } | ||
| 90 | - let byte = self.data[self.pos / 8]; | ||
| 91 | - let bit = (byte >> (7 - (self.pos % 8))) & 1; | ||
| 92 | - self.pos += 1; | ||
| 93 | - Ok(bit == 1) | ||
| 94 | - } | ||
| 95 | - | ||
| 96 | - /// Reads `n` bits (`n` <= 32) as an unsigned value, MSB first. `u(n)`. | ||
| 97 | - pub fn read_bits(&mut self, n: u32) -> Result<u32, OutOfData> { | ||
| 98 | - // More than 32 bits cannot fit a u32. Rather than panic on a hostile | ||
| 99 | - // length (e.g. a corrupt log2_* field driving the count), reject it. | ||
| 100 | - if n > 32 { | ||
| 101 | - return Err(OutOfData); | ||
| 102 | - } | ||
| 103 | - if n == 0 { | ||
| 104 | - return Ok(0); | ||
| 105 | - } | ||
| 106 | - if n <= 24 { | ||
| 107 | - let v = self.peek_bits(n); | ||
| 108 | - self.skip_bits(n)?; | ||
| 109 | - return Ok(v); | ||
| 110 | - } | ||
| 111 | - // n in 25..=32: two chunks (peek_bits caps at 24). | ||
| 112 | - let hi = self.read_bits(n - 16)?; | ||
| 113 | - let lo = self.read_bits(16)?; | ||
| 114 | - Ok((hi << 16) | lo) | ||
| 115 | - } | ||
| 116 | - | ||
| 117 | - /// Peeks the next `n` bits (`n` ≤ 24) as an MSB-first value **without | ||
| 118 | - /// consuming**, zero-filling past the end of the buffer. O(1): loads up to 4 | ||
| 119 | - /// bytes. The zero-fill lets a VLC/Exp-Golomb table match be attempted at the | ||
| 120 | - /// stream end; the caller then [`skip_bits`](Self::skip_bits)s the matched | ||
| 121 | - /// length, which rejects (OutOfData) if those bits ran past the buffer. | ||
| 122 | - #[inline] | ||
| 123 | - pub fn peek_bits(&self, n: u32) -> u32 { | ||
| 124 | - debug_assert!(n <= 24); | ||
| 125 | - let byte = self.pos / 8; | ||
| 126 | - let off = (self.pos % 8) as u32; | ||
| 127 | - // 4 bytes (zero past end), MSB-first, into a 32-bit window. | ||
| 128 | - // | ||
| 129 | - // FAST PATH: one RANGE check and one 4-byte big-endian load, which LLVM | ||
| 130 | - // lowers to `mov` + `bswap`. The previous form did FOUR separate | ||
| 131 | - // bounds-checked `get().unwrap_or(&0)` loads plus three shifts and three ORs, | ||
| 132 | - // on a function the entropy decoder calls tens of millions of times per | ||
| 133 | - // sequence. No `unsafe` needed — `get(range)` + `from_be_bytes` is safe and | ||
| 134 | - // compiles to the same thing an unchecked load would. | ||
| 135 | - // | ||
| 136 | - // The slow arm keeps the EXACT zero-fill-past-the-end contract the doc | ||
| 137 | - // comment promises (and that VLC matching at stream end relies on), so the | ||
| 138 | - // two arms are indistinguishable to every caller; `peek_bits_tail_matches` | ||
| 139 | - // pins that across the whole boundary region. | ||
| 140 | - let acc = match self.data.get(byte..byte + 4) { | ||
| 141 | - Some(c) => u32::from_be_bytes([c[0], c[1], c[2], c[3]]), | ||
| 142 | - None => { | ||
| 143 | - ((*self.data.get(byte).unwrap_or(&0) as u32) << 24) | ||
| 144 | - | ((*self.data.get(byte + 1).unwrap_or(&0) as u32) << 16) | ||
| 145 | - | ((*self.data.get(byte + 2).unwrap_or(&0) as u32) << 8) | ||
| 146 | - | (*self.data.get(byte + 3).unwrap_or(&0) as u32) | ||
| 147 | - } | ||
| 148 | - }; | ||
| 149 | - // The bit at `pos` is window bit (31 − off); take the `n` bits below it. | ||
| 150 | - (acc >> (32 - off - n)) & ((1u32 << n) - 1) | ||
| 151 | - } | ||
| 152 | - | ||
| 153 | - /// Consumes `n` bits (advances the position), after a [`peek_bits`]. Rejects | ||
| 154 | - /// if the bits run past the end of the buffer — the truncated-stream guard | ||
| 155 | - /// that `read_bit`'s per-bit bounds check provided. | ||
| 156 | - #[inline] | ||
| 157 | - pub fn skip_bits(&mut self, n: u32) -> Result<(), OutOfData> { | ||
| 158 | - if self.pos + n as usize > self.bit_len() { | ||
| 159 | - return Err(OutOfData); | ||
| 160 | - } | ||
| 161 | - self.pos += n as usize; | ||
| 162 | - Ok(()) | ||
| 163 | - } | ||
| 164 | - | ||
| 165 | - /// Unsigned Exp-Golomb decode, `ue(v)`. | ||
| 166 | - pub fn read_ue(&mut self) -> Result<u32, OutOfData> { | ||
| 167 | - // Fast path: a codeword with `lz` leading zeros is `2·lz+1` bits. With | ||
| 168 | - // `lz ≤ 11` the whole codeword fits the 24-bit peek window — find `lz` | ||
| 169 | - // by counting leading zeros, then extract value in one shot. | ||
| 170 | - let window = self.peek_bits(24); | ||
| 171 | - let lz = window.leading_zeros() - 8; // leading zeros within the 24-bit window | ||
| 172 | - if lz <= 11 { | ||
| 173 | - let total = 2 * lz + 1; | ||
| 174 | - self.skip_bits(total)?; | ||
| 175 | - if lz == 0 { | ||
| 176 | - return Ok(0); | ||
| 177 | - } | ||
| 178 | - let info = (window >> (24 - total)) & ((1u32 << lz) - 1); | ||
| 179 | - return Ok((1u32 << lz) - 1 + info); | ||
| 180 | - } | ||
| 181 | - // ≥12 leading zeros (huge value or run of zeros): exact bit-at-a-time. | ||
| 182 | - let mut leading_zeros = 0u32; | ||
| 183 | - while !self.read_bit()? { | ||
| 184 | - leading_zeros += 1; | ||
| 185 | - // 32 leading zeros would make `1 << leading_zeros` overflow u32 (and | ||
| 186 | - // the value is not representable anyway) — reject as malformed. | ||
| 187 | - if leading_zeros >= 32 { | ||
| 188 | - return Err(OutOfData); | ||
| 189 | - } | ||
| 190 | - } | ||
| 191 | - if leading_zeros == 0 { | ||
| 192 | - return Ok(0); | ||
| 193 | - } | ||
| 194 | - let info = self.read_bits(leading_zeros)?; | ||
| 195 | - Ok((1u32 << leading_zeros) - 1 + info) | ||
| 196 | - } | ||
| 197 | - | ||
| 198 | - /// Signed Exp-Golomb decode, `se(v)`. | ||
| 199 | - pub fn read_se(&mut self) -> Result<i32, OutOfData> { | ||
| 200 | - let code_num = self.read_ue()?; | ||
| 201 | - // Inverse of the se->code_num mapping. | ||
| 202 | - let magnitude = code_num.div_ceil(2) as i32; | ||
| 203 | - Ok(if code_num % 2 == 1 { magnitude } else { -magnitude }) | ||
| 204 | - } | ||
| 205 | -} | ||
| 206 | - | ||
| 207 | -#[cfg(test)] | ||
| 208 | -mod tests { | ||
| 209 | - use super::*; | ||
| 210 | - use crate::BitWriter; | ||
| 211 | - | ||
| 212 | -/// The one-load fast path must equal the byte-at-a-time zero-fill reference at | ||
| 213 | - /// EVERY bit position and width — including the last bytes, where the fast arm | ||
| 214 | - /// stops applying and the tail arm takes over. A mismatch there would corrupt | ||
| 215 | - /// VLC matching only at stream end, which is exactly the bug a mid-buffer test | ||
| 216 | - /// would miss. | ||
| 217 | - #[test] | ||
| 218 | - fn peek_bits_matches_zero_fill_reference() { | ||
| 219 | - fn reference(data: &[u8], pos: usize, n: u32) -> u32 { | ||
| 220 | - let byte = pos / 8; | ||
| 221 | - let off = (pos % 8) as u32; | ||
| 222 | - let acc = ((*data.get(byte).unwrap_or(&0) as u32) << 24) | ||
| 223 | - | ((*data.get(byte + 1).unwrap_or(&0) as u32) << 16) | ||
| 224 | - | ((*data.get(byte + 2).unwrap_or(&0) as u32) << 8) | ||
| 225 | - | (*data.get(byte + 3).unwrap_or(&0) as u32); | ||
| 226 | - (acc >> (32 - off - n)) & ((1u32 << n) - 1) | ||
| 227 | - } | ||
| 228 | - let mut st = 0x1234_5678u32; | ||
| 229 | - let mut rnd = || { | ||
| 230 | - st ^= st << 13; | ||
| 231 | - st ^= st >> 17; | ||
| 232 | - st ^= st << 5; | ||
| 233 | - st | ||
| 234 | - }; | ||
| 235 | - for len in 1..24usize { | ||
| 236 | - let data: Vec<u8> = (0..len).map(|_| (rnd() >> 7) as u8).collect(); | ||
| 237 | - let r = BitReader::new(&data); | ||
| 238 | - for pos in 0..len * 8 { | ||
| 239 | - for n in 1..=24u32 { | ||
| 240 | - let mut br = BitReader::new(&data); | ||
| 241 | - br.skip_bits(pos as u32).ok(); | ||
| 242 | - // skip_bits refuses past the end; drive `pos` directly instead. | ||
| 243 | - let mut probe = BitReader::new(&data); | ||
| 244 | - while probe.bit_pos() < pos { | ||
| 245 | - if probe.read_bit().is_err() { | ||
| 246 | - break; | ||
| 247 | - } | ||
| 248 | - } | ||
| 249 | - if probe.bit_pos() != pos { | ||
| 250 | - continue; | ||
| 251 | - } | ||
| 252 | - assert_eq!( | ||
| 253 | - probe.peek_bits(n), | ||
| 254 | - reference(&data, pos, n), | ||
| 255 | - "len={len} pos={pos} n={n}" | ||
| 256 | - ); | ||
| 257 | - } | ||
| 258 | - } | ||
| 259 | - let _ = r; | ||
| 260 | - } | ||
| 261 | - } | ||
| 262 | - | ||
| 263 | - #[test] | ||
| 264 | - fn roundtrip_ue() { | ||
| 265 | - for v in [0u32, 1, 2, 3, 4, 7, 8, 255, 256, 65535, u32::MAX - 1] { | ||
| 266 | - let mut w = BitWriter::new(); | ||
| 267 | - w.write_ue(v); | ||
| 268 | - w.align_zero(); | ||
| 269 | - let bytes = w.into_bytes(); | ||
| 270 | - let mut r = BitReader::new(&bytes); | ||
| 271 | - assert_eq!(r.read_ue().unwrap(), v, "ue roundtrip {v}"); | ||
| 272 | - } | ||
| 273 | - } | ||
| 274 | - | ||
| 275 | - #[test] | ||
| 276 | - fn roundtrip_se() { | ||
| 277 | - for v in [0i32, 1, -1, 2, -2, 100, -100, 32767, -32768] { | ||
| 278 | - let mut w = BitWriter::new(); | ||
| 279 | - w.write_se(v); | ||
| 280 | - w.align_zero(); | ||
| 281 | - let bytes = w.into_bytes(); | ||
| 282 | - let mut r = BitReader::new(&bytes); | ||
| 283 | - assert_eq!(r.read_se().unwrap(), v, "se roundtrip {v}"); | ||
| 284 | - } | ||
| 285 | - } | ||
| 286 | - | ||
| 287 | - #[test] | ||
| 288 | - fn roundtrip_mixed_stream() { | ||
| 289 | - let mut w = BitWriter::new(); | ||
| 290 | - w.write_bits(0b1011, 4); | ||
| 291 | - w.write_ue(42); | ||
| 292 | - w.write_se(-17); | ||
| 293 | - w.write_bits(1, 1); | ||
| 294 | - w.align_zero(); | ||
| 295 | - let bytes = w.into_bytes(); | ||
| 296 | - | ||
| 297 | - let mut r = BitReader::new(&bytes); | ||
| 298 | - assert_eq!(r.read_bits(4).unwrap(), 0b1011); | ||
| 299 | - assert_eq!(r.read_ue().unwrap(), 42); | ||
| 300 | - assert_eq!(r.read_se().unwrap(), -17); | ||
| 301 | - assert_eq!(r.read_bits(1).unwrap(), 1); | ||
| 302 | - } | ||
| 303 | - | ||
| 304 | - #[test] | ||
| 305 | - fn reports_out_of_data() { | ||
| 306 | - let bytes = [0x80u8]; | ||
| 307 | - let mut r = BitReader::new(&bytes); | ||
| 308 | - assert_eq!(r.read_bits(8).unwrap(), 0x80); | ||
| 309 | - assert_eq!(r.read_bit(), Err(OutOfData)); | ||
| 310 | - } | ||
| 311 | - | ||
| 312 | - #[test] | ||
| 313 | - fn peek_then_skip_matches_read_bits() { | ||
| 314 | - let bytes = [0xB5u8, 0x3C, 0xF0, 0x0A, 0x77]; | ||
| 315 | - // At every bit offset and width, peek_bits + skip_bits must equal a | ||
| 316 | - // consuming read_bits from a fresh reader at the same position. | ||
| 317 | - for start in 0..16u32 { | ||
| 318 | - for n in 1..=24u32 { | ||
| 319 | - let mut a = BitReader::new(&bytes); | ||
| 320 | - a.skip_bits(start).unwrap(); | ||
| 321 | - let peeked = a.peek_bits(n); | ||
| 322 | - let pos_before = a.bit_pos(); | ||
| 323 | - a.skip_bits(n).unwrap(); | ||
| 324 | - assert_eq!(a.bit_pos(), pos_before + n as usize); | ||
| 325 | - | ||
| 326 | - let mut b = BitReader::new(&bytes); | ||
| 327 | - b.skip_bits(start).unwrap(); | ||
| 328 | - assert_eq!(peeked, b.read_bits(n).unwrap(), "start={start} n={n}"); | ||
| 329 | - } | ||
| 330 | - } | ||
| 331 | - } | ||
| 332 | - | ||
| 333 | - #[test] | ||
| 334 | - fn peek_zero_fills_past_end() { | ||
| 335 | - let bytes = [0xFFu8]; | ||
| 336 | - let mut r = BitReader::new(&bytes); | ||
| 337 | - r.skip_bits(4).unwrap(); | ||
| 338 | - // 4 real bits (1111) then zero-fill: 0b1111_0000_0000... for 12 bits. | ||
| 339 | - assert_eq!(r.peek_bits(12), 0b1111_0000_0000); | ||
| 340 | - // skipping past the end is rejected. | ||
| 341 | - assert_eq!(r.skip_bits(8), Err(OutOfData)); | ||
| 342 | - } | ||
| 343 | -} | ||
vendor/rusty_h264-common/src/bit_writer.rsdeleted+0 -319
| @@ -1,319 +0,0 @@ | |||
| 1 | -//! MSB-first bit writer with H.264 Exp-Golomb coding. | ||
| 2 | -//! | ||
| 3 | -//! H.264 packs syntax elements as a big-endian bitstream: the first bit written | ||
| 4 | -//! lands in the most-significant position of the first byte. This writer | ||
| 5 | -//! accumulates bits and exposes the Exp-Golomb (`ue`/`se`) and fixed-length | ||
| 6 | -//! (`u`) codings the bitstream syntax is built from. | ||
| 7 | - | ||
| 8 | -/// A growable, MSB-first bit buffer. | ||
| 9 | -/// | ||
| 10 | -/// Uses a **bit cache**: bits accumulate in the low `nbits` positions of a 64-bit | ||
| 11 | -/// `cache` (the most-recently-written bit is least-significant within the valid | ||
| 12 | -/// region), and whole bytes are flushed off the top. A multi-bit write is a shift | ||
| 13 | -/// + OR + a short byte-flush loop — not one operation per bit. After every public | ||
| 14 | -/// write the invariant `nbits < 8` and "bits above `nbits` are zero" hold. | ||
| 15 | -#[derive(Debug, Default, Clone)] | ||
| 16 | -pub struct BitWriter { | ||
| 17 | - /// Completed bytes. | ||
| 18 | - bytes: Vec<u8>, | ||
| 19 | - /// Pending bits, valid in the low `nbits` positions (zero above). | ||
| 20 | - cache: u64, | ||
| 21 | - /// Number of valid pending bits (0..=7 between writes). | ||
| 22 | - nbits: u32, | ||
| 23 | -} | ||
| 24 | - | ||
| 25 | -impl BitWriter { | ||
| 26 | - /// Creates an empty writer. | ||
| 27 | - pub fn new() -> Self { | ||
| 28 | - Self::default() | ||
| 29 | - } | ||
| 30 | - | ||
| 31 | - /// Creates a writer with `bytes` pre-reserved — for the per-frame slice writer, | ||
| 32 | - /// so the CAVLC hot loop never pays a `Vec` realloc mid-frame. | ||
| 33 | - pub fn with_capacity(bytes: usize) -> Self { | ||
| 34 | - Self { | ||
| 35 | - bytes: Vec::with_capacity(bytes), | ||
| 36 | - cache: 0, | ||
| 37 | - nbits: 0, | ||
| 38 | - } | ||
| 39 | - } | ||
| 40 | - | ||
| 41 | - /// Number of bits written so far. | ||
| 42 | - pub fn bit_len(&self) -> usize { | ||
| 43 | - self.bytes.len() * 8 + self.nbits as usize | ||
| 44 | - } | ||
| 45 | - | ||
| 46 | - /// `true` if the writer is on a byte boundary. | ||
| 47 | - pub fn is_byte_aligned(&self) -> bool { | ||
| 48 | - self.nbits % 8 == 0 | ||
| 49 | - } | ||
| 50 | - | ||
| 51 | - /// Writes the low `n` bits of `value`, most-significant first (`u(n)`). `n` <= 32. | ||
| 52 | - /// | ||
| 53 | - /// Keeps up to 31 pending bits in `cache` and flushes a whole **u32 word** (4 | ||
| 54 | - /// bytes) at a time, like openh264's `BsWriteBits` (`WRITE_BE_32`) — a quarter | ||
| 55 | - /// the `Vec` writes of byte-at-a-time flushing. | ||
| 56 | - #[inline] | ||
| 57 | - pub fn write_bits(&mut self, value: u32, n: u32) { | ||
| 58 | - debug_assert!(n <= 32, "write_bits supports up to 32 bits"); | ||
| 59 | - if n == 0 { | ||
| 60 | - return; | ||
| 61 | - } | ||
| 62 | - let mask = (1u64 << n) - 1; // n<=32 so 1<<32 fits u64 | ||
| 63 | - self.cache = (self.cache << n) | (value as u64 & mask); | ||
| 64 | - self.nbits += n; | ||
| 65 | - if self.nbits >= 32 { | ||
| 66 | - self.nbits -= 32; | ||
| 67 | - let word = (self.cache >> self.nbits) as u32; | ||
| 68 | - self.bytes.extend_from_slice(&word.to_be_bytes()); | ||
| 69 | - self.cache &= (1u64 << self.nbits) - 1; // drop the flushed high bits | ||
| 70 | - } | ||
| 71 | - } | ||
| 72 | - | ||
| 73 | - /// Writes a single bit (`true` => 1). | ||
| 74 | - #[inline] | ||
| 75 | - pub fn write_bit(&mut self, bit: bool) { | ||
| 76 | - self.write_bits(bit as u32, 1); | ||
| 77 | - } | ||
| 78 | - | ||
| 79 | - /// Appends every bit of `other`, in order, at this writer's current position. | ||
| 80 | - /// | ||
| 81 | - /// Neither writer need be byte-aligned. This is what lets a macroblock be | ||
| 82 | - /// encoded into a scratch writer *before* the syntax that must precede it is | ||
| 83 | - /// known (`mb_skip_run` is only decided once the macroblock's own cost is), so | ||
| 84 | - /// the encoder can commit one encode rather than trialing and repeating it. | ||
| 85 | - /// Sound for CAVLC because a macroblock's Exp-Golomb/VLC syntax does not depend | ||
| 86 | - /// on its bit position; an arithmetic coder (CABAC) could NOT be spliced this | ||
| 87 | - /// way, since its state is carried across the whole slice. | ||
| 88 | - pub fn append(&mut self, other: &BitWriter) { | ||
| 89 | - for chunk in other.bytes.chunks(4) { | ||
| 90 | - let mut word = 0u32; | ||
| 91 | - for &b in chunk { | ||
| 92 | - word = (word << 8) | b as u32; | ||
| 93 | - } | ||
| 94 | - self.write_bits(word, chunk.len() as u32 * 8); | ||
| 95 | - } | ||
| 96 | - if other.nbits > 0 { | ||
| 97 | - // `cache` holds `nbits` (<= 31) valid bits in its low positions. | ||
| 98 | - self.write_bits(other.cache as u32, other.nbits); | ||
| 99 | - } | ||
| 100 | - } | ||
| 101 | - | ||
| 102 | - /// Emits a value already mapped to its Exp-Golomb code number: `floor(log2 x)` | ||
| 103 | - /// leading zeros then `x` in `floor(log2 x)+1` bits, where `x = code_num + 1`. | ||
| 104 | - #[inline] | ||
| 105 | - fn put_golomb(&mut self, x: u64) { | ||
| 106 | - let n = 63 - x.leading_zeros(); // floor(log2 x), 0..=32 | ||
| 107 | - self.write_bits(0, n); | ||
| 108 | - if n < 32 { | ||
| 109 | - self.write_bits(x as u32, n + 1); | ||
| 110 | - } else { | ||
| 111 | - // n == 32 (e.g. ue(u32::MAX)): 33-bit value, split across two writes. | ||
| 112 | - self.write_bits((x >> 32) as u32, n - 31); | ||
| 113 | - self.write_bits(x as u32, 32); | ||
| 114 | - } | ||
| 115 | - } | ||
| 116 | - | ||
| 117 | - /// Unsigned Exp-Golomb code `ue(v)`. | ||
| 118 | - pub fn write_ue(&mut self, value: u32) { | ||
| 119 | - self.put_golomb(value as u64 + 1); | ||
| 120 | - } | ||
| 121 | - | ||
| 122 | - /// Signed Exp-Golomb code `se(v)`: `0->0, 1->1, -1->2, 2->3, -2->4, ...`. | ||
| 123 | - pub fn write_se(&mut self, value: i32) { | ||
| 124 | - let code_num = if value <= 0 { | ||
| 125 | - (-(value as i64) as u64) * 2 | ||
| 126 | - } else { | ||
| 127 | - (value as u64) * 2 - 1 | ||
| 128 | - }; | ||
| 129 | - self.put_golomb(code_num + 1); | ||
| 130 | - } | ||
| 131 | - | ||
| 132 | - /// Writes the `rbsp_trailing_bits()`: a stop bit `1` then zero-pad to a byte. | ||
| 133 | - pub fn rbsp_trailing_bits(&mut self) { | ||
| 134 | - self.write_bits(1, 1); | ||
| 135 | - self.align_zero(); | ||
| 136 | - } | ||
| 137 | - | ||
| 138 | - /// Pads with zero bits to the next byte boundary (no stop bit), then flushes | ||
| 139 | - /// the pending whole bytes from the cache (the word-flush in `write_bits` can | ||
| 140 | - /// leave up to 31 pending bits). | ||
| 141 | - pub fn align_zero(&mut self) { | ||
| 142 | - let pad = (8 - self.nbits % 8) % 8; | ||
| 143 | - if pad != 0 { | ||
| 144 | - self.write_bits(0, pad); | ||
| 145 | - } | ||
| 146 | - while self.nbits >= 8 { | ||
| 147 | - self.nbits -= 8; | ||
| 148 | - self.bytes.push((self.cache >> self.nbits) as u8); | ||
| 149 | - } | ||
| 150 | - self.cache = 0; | ||
| 151 | - } | ||
| 152 | - | ||
| 153 | - /// Consumes the writer, returning the byte buffer. Flushes any whole bytes | ||
| 154 | - /// still pending in the cache; panics if a sub-byte remainder is left (call | ||
| 155 | - /// [`rbsp_trailing_bits`](Self::rbsp_trailing_bits) or | ||
| 156 | - /// [`align_zero`](Self::align_zero) first). | ||
| 157 | - pub fn into_bytes(mut self) -> Vec<u8> { | ||
| 158 | - while self.nbits >= 8 { | ||
| 159 | - self.nbits -= 8; | ||
| 160 | - self.bytes.push((self.cache >> self.nbits) as u8); | ||
| 161 | - } | ||
| 162 | - assert!( | ||
| 163 | - self.nbits == 0, | ||
| 164 | - "BitWriter::into_bytes called with {} dangling bits", | ||
| 165 | - self.nbits | ||
| 166 | - ); | ||
| 167 | - self.bytes | ||
| 168 | - } | ||
| 169 | - | ||
| 170 | - /// Borrows the completed bytes (excludes bits still pending in the cache). | ||
| 171 | - pub fn as_bytes(&self) -> &[u8] { | ||
| 172 | - &self.bytes | ||
| 173 | - } | ||
| 174 | -} | ||
| 175 | - | ||
| 176 | -#[cfg(test)] | ||
| 177 | -mod tests { | ||
| 178 | - use super::*; | ||
| 179 | - | ||
| 180 | - #[test] | ||
| 181 | - fn write_bits_is_msb_first() { | ||
| 182 | - let mut w = BitWriter::new(); | ||
| 183 | - w.write_bits(0b101, 3); | ||
| 184 | - w.write_bits(0b1, 1); | ||
| 185 | - w.align_zero(); | ||
| 186 | - // bits 1,0,1,1 then zero-pad -> 1011_0000 | ||
| 187 | - assert_eq!(w.into_bytes(), vec![0b1011_0000]); | ||
| 188 | - } | ||
| 189 | - | ||
| 190 | - #[test] | ||
| 191 | - fn ue_known_values() { | ||
| 192 | - // From H.264 Table 9-2: code_num -> bit string. | ||
| 193 | - let cases: &[(u32, &str)] = &[ | ||
| 194 | - (0, "1"), | ||
| 195 | - (1, "010"), | ||
| 196 | - (2, "011"), | ||
| 197 | - (3, "00100"), | ||
| 198 | - (4, "00101"), | ||
| 199 | - (5, "00110"), | ||
| 200 | - (6, "00111"), | ||
| 201 | - (7, "0001000"), | ||
| 202 | - (8, "0001001"), | ||
| 203 | - ]; | ||
| 204 | - for &(v, bits) in cases { | ||
| 205 | - let mut w = BitWriter::new(); | ||
| 206 | - w.write_ue(v); | ||
| 207 | - assert_eq!(bitstring(&w), bits, "ue({v})"); | ||
| 208 | - } | ||
| 209 | - } | ||
| 210 | - | ||
| 211 | - #[test] | ||
| 212 | - fn se_known_values() { | ||
| 213 | - // H.264 Table 9-3 mapping: se -> code_num. | ||
| 214 | - let cases: &[(i32, &str)] = &[ | ||
| 215 | - (0, "1"), // code_num 0 | ||
| 216 | - (1, "010"), // 1 | ||
| 217 | - (-1, "011"), // 2 | ||
| 218 | - (2, "00100"), | ||
| 219 | - (-2, "00101"), | ||
| 220 | - (3, "00110"), | ||
| 221 | - (-3, "00111"), | ||
| 222 | - ]; | ||
| 223 | - for &(v, bits) in cases { | ||
| 224 | - let mut w = BitWriter::new(); | ||
| 225 | - w.write_se(v); | ||
| 226 | - assert_eq!(bitstring(&w), bits, "se({v})"); | ||
| 227 | - } | ||
| 228 | - } | ||
| 229 | - | ||
| 230 | - #[test] | ||
| 231 | - fn ue_max_does_not_overflow() { | ||
| 232 | - let mut w = BitWriter::new(); | ||
| 233 | - w.write_ue(u32::MAX); | ||
| 234 | - // value+1 = 2^32 -> 32 leading zeros then 33-bit value => 65 bits total. | ||
| 235 | - assert_eq!(w.bit_len(), 65); | ||
| 236 | - } | ||
| 237 | - | ||
| 238 | - #[test] | ||
| 239 | - fn rbsp_trailing_aligns_to_byte() { | ||
| 240 | - let mut w = BitWriter::new(); | ||
| 241 | - w.write_bits(0b101, 3); | ||
| 242 | - w.rbsp_trailing_bits(); | ||
| 243 | - // 101 + stop 1 + pad 0000 => 1011_0000 | ||
| 244 | - assert_eq!(w.into_bytes(), vec![0b1011_0000]); | ||
| 245 | - } | ||
| 246 | - | ||
| 247 | - /// Renders the bits currently buffered (including the partial byte) as a | ||
| 248 | - /// string of '0'/'1' for assertions. | ||
| 249 | - fn bitstring(w: &BitWriter) -> String { | ||
| 250 | - let mut s = String::new(); | ||
| 251 | - for &b in w.as_bytes() { | ||
| 252 | - for i in (0..8).rev() { | ||
| 253 | - s.push(if (b >> i) & 1 == 1 { '1' } else { '0' }); | ||
| 254 | - } | ||
| 255 | - } | ||
| 256 | - for i in (0..w.nbits).rev() { | ||
| 257 | - s.push(if (w.cache >> i) & 1 == 1 { '1' } else { '0' }); | ||
| 258 | - } | ||
| 259 | - s | ||
| 260 | - } | ||
| 261 | -} | ||
| 262 | - | ||
| 263 | -#[cfg(test)] | ||
| 264 | -mod append_tests { | ||
| 265 | - use super::BitWriter; | ||
| 266 | - | ||
| 267 | - /// Appending must be indistinguishable from having written the bits inline, | ||
| 268 | - /// at every source/destination bit misalignment — this is the invariant the | ||
| 269 | - /// encoder's encode-once-and-splice path rests on. | ||
| 270 | - #[test] | ||
| 271 | - fn append_matches_inline_at_every_alignment() { | ||
| 272 | - for lead in 0..17u32 { | ||
| 273 | - for n in 0..40u32 { | ||
| 274 | - let mut inline = BitWriter::new(); | ||
| 275 | - inline.write_bits(0b1011_0110, lead.min(8)); | ||
| 276 | - if lead > 8 { | ||
| 277 | - inline.write_bits(0x5A5A, lead - 8); | ||
| 278 | - } | ||
| 279 | - let mut spliced = inline.clone(); | ||
| 280 | - | ||
| 281 | - // the payload, written bit-patterned so order errors show up | ||
| 282 | - let mut scratch = BitWriter::new(); | ||
| 283 | - for i in 0..n { | ||
| 284 | - scratch.write_bit(i % 3 == 0); | ||
| 285 | - } | ||
| 286 | - for i in 0..n { | ||
| 287 | - inline.write_bit(i % 3 == 0); | ||
| 288 | - } | ||
| 289 | - spliced.append(&scratch); | ||
| 290 | - | ||
| 291 | - assert_eq!(spliced.bit_len(), inline.bit_len(), "lead={lead} n={n}: length"); | ||
| 292 | - let (mut a, mut b) = (spliced.clone(), inline.clone()); | ||
| 293 | - a.align_zero(); | ||
| 294 | - b.align_zero(); | ||
| 295 | - assert_eq!(a.into_bytes(), b.into_bytes(), "lead={lead} n={n}: bits"); | ||
| 296 | - } | ||
| 297 | - } | ||
| 298 | - } | ||
| 299 | - | ||
| 300 | - /// Exp-Golomb payloads across a byte-crossing boundary (the real shape). | ||
| 301 | - #[test] | ||
| 302 | - fn append_preserves_exp_golomb() { | ||
| 303 | - for lead in 0..9u32 { | ||
| 304 | - let mut inline = BitWriter::new(); | ||
| 305 | - inline.write_bits(1, lead); | ||
| 306 | - let mut spliced = inline.clone(); | ||
| 307 | - let mut scratch = BitWriter::new(); | ||
| 308 | - for v in [0u32, 1, 7, 40, 1000, 65535] { | ||
| 309 | - scratch.write_ue(v); | ||
| 310 | - inline.write_ue(v); | ||
| 311 | - } | ||
| 312 | - spliced.append(&scratch); | ||
| 313 | - assert_eq!(spliced.bit_len(), inline.bit_len(), "lead={lead}: length"); | ||
| 314 | - spliced.align_zero(); | ||
| 315 | - inline.align_zero(); | ||
| 316 | - assert_eq!(spliced.into_bytes(), inline.into_bytes(), "lead={lead}"); | ||
| 317 | - } | ||
| 318 | - } | ||
| 319 | -} | ||
vendor/rusty_h264-common/src/cabac_tables.rsdeleted+0 -644
| @@ -1,644 +0,0 @@ | |||
| 1 | -//! CABAC tables ported verbatim from openh264 `common_tables.cpp` (spec | ||
| 2 | -//! Tables 9-44/9-45 and 9-12..9-33). 460 contexts, 4 init models [I,idc0,idc1,idc2]. | ||
| 3 | -//! `CTX_NA` sentinels (I-slice-unused contexts) are 0 as in openh264. | ||
| 4 | - | ||
| 5 | -/// `rangeTabLPS[pStateIdx][(range>>6)&3]` (Table 9-44). | ||
| 6 | -pub const RANGE_LPS: [[u8; 4]; 64] = [ | ||
| 7 | - [128, 176, 208, 240], | ||
| 8 | - [128, 167, 197, 227], | ||
| 9 | - [128, 158, 187, 216], | ||
| 10 | - [123, 150, 178, 205], | ||
| 11 | - [116, 142, 169, 195], | ||
| 12 | - [111, 135, 160, 185], | ||
| 13 | - [105, 128, 152, 175], | ||
| 14 | - [100, 122, 144, 166], | ||
| 15 | - [95, 116, 137, 158], | ||
| 16 | - [90, 110, 130, 150], | ||
| 17 | - [85, 104, 123, 142], | ||
| 18 | - [81, 99, 117, 135], | ||
| 19 | - [77, 94, 111, 128], | ||
| 20 | - [73, 89, 105, 122], | ||
| 21 | - [69, 85, 100, 116], | ||
| 22 | - [66, 80, 95, 110], | ||
| 23 | - [62, 76, 90, 104], | ||
| 24 | - [59, 72, 86, 99], | ||
| 25 | - [56, 69, 81, 94], | ||
| 26 | - [53, 65, 77, 89], | ||
| 27 | - [51, 62, 73, 85], | ||
| 28 | - [48, 59, 69, 80], | ||
| 29 | - [46, 56, 66, 76], | ||
| 30 | - [43, 53, 63, 72], | ||
| 31 | - [41, 50, 59, 69], | ||
| 32 | - [39, 48, 56, 65], | ||
| 33 | - [37, 45, 54, 62], | ||
| 34 | - [35, 43, 51, 59], | ||
| 35 | - [33, 41, 48, 56], | ||
| 36 | - [32, 39, 46, 53], | ||
| 37 | - [30, 37, 43, 50], | ||
| 38 | - [29, 35, 41, 48], | ||
| 39 | - [27, 33, 39, 45], | ||
| 40 | - [26, 31, 37, 43], | ||
| 41 | - [24, 30, 35, 41], | ||
| 42 | - [23, 28, 33, 39], | ||
| 43 | - [22, 27, 32, 37], | ||
| 44 | - [21, 26, 30, 35], | ||
| 45 | - [20, 24, 29, 33], | ||
| 46 | - [19, 23, 27, 31], | ||
| 47 | - [18, 22, 26, 30], | ||
| 48 | - [17, 21, 25, 28], | ||
| 49 | - [16, 20, 23, 27], | ||
| 50 | - [15, 19, 22, 25], | ||
| 51 | - [14, 18, 21, 24], | ||
| 52 | - [14, 17, 20, 23], | ||
| 53 | - [13, 16, 19, 22], | ||
| 54 | - [12, 15, 18, 21], | ||
| 55 | - [12, 14, 17, 20], | ||
| 56 | - [11, 14, 16, 19], | ||
| 57 | - [11, 13, 15, 18], | ||
| 58 | - [10, 12, 15, 17], | ||
| 59 | - [10, 12, 14, 16], | ||
| 60 | - [9, 11, 13, 15], | ||
| 61 | - [9, 11, 12, 14], | ||
| 62 | - [8, 10, 12, 14], | ||
| 63 | - [8, 9, 11, 13], | ||
| 64 | - [7, 9, 11, 12], | ||
| 65 | - [7, 9, 10, 12], | ||
| 66 | - [7, 8, 10, 11], | ||
| 67 | - [6, 8, 9, 11], | ||
| 68 | - [6, 7, 9, 10], | ||
| 69 | - [6, 7, 8, 9], | ||
| 70 | - [2, 2, 2, 2], | ||
| 71 | -]; | ||
| 72 | - | ||
| 73 | -/// State transition `[pStateIdx] -> [transIdxLPS, transIdxMPS]` (Table 9-45). | ||
| 74 | -pub const STATE_TRANS: [[u8; 2]; 64] = [ | ||
| 75 | - [0, 1], | ||
| 76 | - [0, 2], | ||
| 77 | - [1, 3], | ||
| 78 | - [2, 4], | ||
| 79 | - [2, 5], | ||
| 80 | - [4, 6], | ||
| 81 | - [4, 7], | ||
| 82 | - [5, 8], | ||
| 83 | - [6, 9], | ||
| 84 | - [7, 10], | ||
| 85 | - [8, 11], | ||
| 86 | - [9, 12], | ||
| 87 | - [9, 13], | ||
| 88 | - [11, 14], | ||
| 89 | - [11, 15], | ||
| 90 | - [12, 16], | ||
| 91 | - [13, 17], | ||
| 92 | - [13, 18], | ||
| 93 | - [15, 19], | ||
| 94 | - [15, 20], | ||
| 95 | - [16, 21], | ||
| 96 | - [16, 22], | ||
| 97 | - [18, 23], | ||
| 98 | - [18, 24], | ||
| 99 | - [19, 25], | ||
| 100 | - [19, 26], | ||
| 101 | - [21, 27], | ||
| 102 | - [21, 28], | ||
| 103 | - [22, 29], | ||
| 104 | - [22, 30], | ||
| 105 | - [23, 31], | ||
| 106 | - [24, 32], | ||
| 107 | - [24, 33], | ||
| 108 | - [25, 34], | ||
| 109 | - [26, 35], | ||
| 110 | - [26, 36], | ||
| 111 | - [27, 37], | ||
| 112 | - [27, 38], | ||
| 113 | - [28, 39], | ||
| 114 | - [29, 40], | ||
| 115 | - [29, 41], | ||
| 116 | - [30, 42], | ||
| 117 | - [30, 43], | ||
| 118 | - [30, 44], | ||
| 119 | - [31, 45], | ||
| 120 | - [32, 46], | ||
| 121 | - [32, 47], | ||
| 122 | - [33, 48], | ||
| 123 | - [33, 49], | ||
| 124 | - [33, 50], | ||
| 125 | - [34, 51], | ||
| 126 | - [34, 52], | ||
| 127 | - [35, 53], | ||
| 128 | - [35, 54], | ||
| 129 | - [35, 55], | ||
| 130 | - [36, 56], | ||
| 131 | - [36, 57], | ||
| 132 | - [36, 58], | ||
| 133 | - [37, 59], | ||
| 134 | - [37, 60], | ||
| 135 | - [37, 61], | ||
| 136 | - [38, 62], | ||
| 137 | - [38, 62], | ||
| 138 | - [63, 63], | ||
| 139 | -]; | ||
| 140 | - | ||
| 141 | -/// Context init `(m, n)` per `[ctxIdx][model]` (model 0=I, 1..=3 = init_idc 0..2). | ||
| 142 | -pub const CTX_INIT: [[(i16, i16); 4]; 460] = [ | ||
| 143 | - [(20, -15), (20, -15), (20, -15), (20, -15)], | ||
| 144 | - [(2, 54), (2, 54), (2, 54), (2, 54)], | ||
| 145 | - [(3, 74), (3, 74), (3, 74), (3, 74)], | ||
| 146 | - [(20, -15), (20, -15), (20, -15), (20, -15)], | ||
| 147 | - [(2, 54), (2, 54), (2, 54), (2, 54)], | ||
| 148 | - [(3, 74), (3, 74), (3, 74), (3, 74)], | ||
| 149 | - [(-28, 127), (-28, 127), (-28, 127), (-28, 127)], | ||
| 150 | - [(-23, 104), (-23, 104), (-23, 104), (-23, 104)], | ||
| 151 | - [(-6, 53), (-6, 53), (-6, 53), (-6, 53)], | ||
| 152 | - [(-1, 54), (-1, 54), (-1, 54), (-1, 54)], | ||
| 153 | - [(7, 51), (7, 51), (7, 51), (7, 51)], | ||
| 154 | - [(0, 0), (23, 33), (22, 25), (29, 16)], | ||
| 155 | - [(0, 0), (23, 2), (34, 0), (25, 0)], | ||
| 156 | - [(0, 0), (21, 0), (16, 0), (14, 0)], | ||
| 157 | - [(0, 0), (1, 9), (-2, 9), (-10, 51)], | ||
| 158 | - [(0, 0), (0, 49), (4, 41), (-3, 62)], | ||
| 159 | - [(0, 0), (-37, 118), (-29, 118), (-27, 99)], | ||
| 160 | - [(0, 0), (5, 57), (2, 65), (26, 16)], | ||
| 161 | - [(0, 0), (-13, 78), (-6, 71), (-4, 85)], | ||
| 162 | - [(0, 0), (-11, 65), (-13, 79), (-24, 102)], | ||
| 163 | - [(0, 0), (1, 62), (5, 52), (5, 57)], | ||
| 164 | - [(0, 0), (12, 49), (9, 50), (6, 57)], | ||
| 165 | - [(0, 0), (-4, 73), (-3, 70), (-17, 73)], | ||
| 166 | - [(0, 0), (17, 50), (10, 54), (14, 57)], | ||
| 167 | - [(0, 0), (18, 64), (26, 34), (20, 40)], | ||
| 168 | - [(0, 0), (9, 43), (19, 22), (20, 10)], | ||
| 169 | - [(0, 0), (29, 0), (40, 0), (29, 0)], | ||
| 170 | - [(0, 0), (26, 67), (57, 2), (54, 0)], | ||
| 171 | - [(0, 0), (16, 90), (41, 36), (37, 42)], | ||
| 172 | - [(0, 0), (9, 104), (26, 69), (12, 97)], | ||
| 173 | - [(0, 0), (-46, 127), (-45, 127), (-32, 127)], | ||
| 174 | - [(0, 0), (-20, 104), (-15, 101), (-22, 117)], | ||
| 175 | - [(0, 0), (1, 67), (-4, 76), (-2, 74)], | ||
| 176 | - [(0, 0), (-13, 78), (-6, 71), (-4, 85)], | ||
| 177 | - [(0, 0), (-11, 65), (-13, 79), (-24, 102)], | ||
| 178 | - [(0, 0), (1, 62), (5, 52), (5, 57)], | ||
| 179 | - [(0, 0), (-6, 86), (6, 69), (-6, 93)], | ||
| 180 | - [(0, 0), (-17, 95), (-13, 90), (-14, 88)], | ||
| 181 | - [(0, 0), (-6, 61), (0, 52), (-6, 44)], | ||
| 182 | - [(0, 0), (9, 45), (8, 43), (4, 55)], | ||
| 183 | - [(0, 0), (-3, 69), (-2, 69), (-11, 89)], | ||
| 184 | - [(0, 0), (-6, 81), (-5, 82), (-15, 103)], | ||
| 185 | - [(0, 0), (-11, 96), (-10, 96), (-21, 116)], | ||
| 186 | - [(0, 0), (6, 55), (2, 59), (19, 57)], | ||
| 187 | - [(0, 0), (7, 67), (2, 75), (20, 58)], | ||
| 188 | - [(0, 0), (-5, 86), (-3, 87), (4, 84)], | ||
| 189 | - [(0, 0), (2, 88), (-3, 100), (6, 96)], | ||
| 190 | - [(0, 0), (0, 58), (1, 56), (1, 63)], | ||
| 191 | - [(0, 0), (-3, 76), (-3, 74), (-5, 85)], | ||
| 192 | - [(0, 0), (-10, 94), (-6, 85), (-13, 106)], | ||
| 193 | - [(0, 0), (5, 54), (0, 59), (5, 63)], | ||
| 194 | - [(0, 0), (4, 69), (-3, 81), (6, 75)], | ||
| 195 | - [(0, 0), (-3, 81), (-7, 86), (-3, 90)], | ||
| 196 | - [(0, 0), (0, 88), (-5, 95), (-1, 101)], | ||
| 197 | - [(0, 0), (-7, 67), (-1, 66), (3, 55)], | ||
| 198 | - [(0, 0), (-5, 74), (-1, 77), (-4, 79)], | ||
| 199 | - [(0, 0), (-4, 74), (1, 70), (-2, 75)], | ||
| 200 | - [(0, 0), (-5, 80), (-2, 86), (-12, 97)], | ||
| 201 | - [(0, 0), (-7, 72), (-5, 72), (-7, 50)], | ||
| 202 | - [(0, 0), (1, 58), (0, 61), (1, 60)], | ||
| 203 | - [(0, 41), (0, 41), (0, 41), (0, 41)], | ||
| 204 | - [(0, 63), (0, 63), (0, 63), (0, 63)], | ||
| 205 | - [(0, 63), (0, 63), (0, 63), (0, 63)], | ||
| 206 | - [(0, 63), (0, 63), (0, 63), (0, 63)], | ||
| 207 | - [(-9, 83), (-9, 83), (-9, 83), (-9, 83)], | ||
| 208 | - [(4, 86), (4, 86), (4, 86), (4, 86)], | ||
| 209 | - [(0, 97), (0, 97), (0, 97), (0, 97)], | ||
| 210 | - [(-7, 72), (-7, 72), (-7, 72), (-7, 72)], | ||
| 211 | - [(13, 41), (13, 41), (13, 41), (13, 41)], | ||
| 212 | - [(3, 62), (3, 62), (3, 62), (3, 62)], | ||
| 213 | - [(0, 11), (0, 45), (13, 15), (7, 34)], | ||
| 214 | - [(1, 55), (-4, 78), (7, 51), (-9, 88)], | ||
| 215 | - [(0, 69), (-3, 96), (2, 80), (-20, 127)], | ||
| 216 | - [(-17, 127), (-27, 126), (-39, 127), (-36, 127)], | ||
| 217 | - [(-13, 102), (-28, 98), (-18, 91), (-17, 91)], | ||
| 218 | - [(0, 82), (-25, 101), (-17, 96), (-14, 95)], | ||
| 219 | - [(-7, 74), (-23, 67), (-26, 81), (-25, 84)], | ||
| 220 | - [(-21, 107), (-28, 82), (-35, 98), (-25, 86)], | ||
| 221 | - [(-27, 127), (-20, 94), (-24, 102), (-12, 89)], | ||
| 222 | - [(-31, 127), (-16, 83), (-23, 97), (-17, 91)], | ||
| 223 | - [(-24, 127), (-22, 110), (-27, 119), (-31, 127)], | ||
| 224 | - [(-18, 95), (-21, 91), (-24, 99), (-14, 76)], | ||
| 225 | - [(-27, 127), (-18, 102), (-21, 110), (-18, 103)], | ||
| 226 | - [(-21, 114), (-13, 93), (-18, 102), (-13, 90)], | ||
| 227 | - [(-30, 127), (-29, 127), (-36, 127), (-37, 127)], | ||
| 228 | - [(-17, 123), (-7, 92), (0, 80), (11, 80)], | ||
| 229 | - [(-12, 115), (-5, 89), (-5, 89), (5, 76)], | ||
| 230 | - [(-16, 122), (-7, 96), (-7, 94), (2, 84)], | ||
| 231 | - [(-11, 115), (-13, 108), (-4, 92), (5, 78)], | ||
| 232 | - [(-12, 63), (-3, 46), (0, 39), (-6, 55)], | ||
| 233 | - [(-2, 68), (-1, 65), (0, 65), (4, 61)], | ||
| 234 | - [(-15, 84), (-1, 57), (-15, 84), (-14, 83)], | ||
| 235 | - [(-13, 104), (-9, 93), (-35, 127), (-37, 127)], | ||
| 236 | - [(-3, 70), (-3, 74), (-2, 73), (-5, 79)], | ||
| 237 | - [(-8, 93), (-9, 92), (-12, 104), (-11, 104)], | ||
| 238 | - [(-10, 90), (-8, 87), (-9, 91), (-11, 91)], | ||
| 239 | - [(-30, 127), (-23, 126), (-31, 127), (-30, 127)], | ||
| 240 | - [(-1, 74), (5, 54), (3, 55), (0, 65)], | ||
| 241 | - [(-6, 97), (6, 60), (7, 56), (-2, 79)], | ||
| 242 | - [(-7, 91), (6, 59), (7, 55), (0, 72)], | ||
| 243 | - [(-20, 127), (6, 69), (8, 61), (-4, 92)], | ||
| 244 | - [(-4, 56), (-1, 48), (-3, 53), (-6, 56)], | ||
| 245 | - [(-5, 82), (0, 68), (0, 68), (3, 68)], | ||
| 246 | - [(-7, 76), (-4, 69), (-7, 74), (-8, 71)], | ||
| 247 | - [(-22, 125), (-8, 88), (-9, 88), (-13, 98)], | ||
| 248 | - [(-7, 93), (-2, 85), (-13, 103), (-4, 86)], | ||
| 249 | - [(-11, 87), (-6, 78), (-13, 91), (-12, 88)], | ||
| 250 | - [(-3, 77), (-1, 75), (-9, 89), (-5, 82)], | ||
| 251 | - [(-5, 71), (-7, 77), (-14, 92), (-3, 72)], | ||
| 252 | - [(-4, 63), (2, 54), (-8, 76), (-4, 67)], | ||
| 253 | - [(-4, 68), (5, 50), (-12, 87), (-8, 72)], | ||
| 254 | - [(-12, 84), (-3, 68), (-23, 110), (-16, 89)], | ||
| 255 | - [(-7, 62), (1, 50), (-24, 105), (-9, 69)], | ||
| 256 | - [(-7, 65), (6, 42), (-10, 78), (-1, 59)], | ||
| 257 | - [(8, 61), (-4, 81), (-20, 112), (5, 66)], | ||
| 258 | - [(5, 56), (1, 63), (-17, 99), (4, 57)], | ||
| 259 | - [(-2, 66), (-4, 70), (-78, 127), (-4, 71)], | ||
| 260 | - [(1, 64), (0, 67), (-70, 127), (-2, 71)], | ||
| 261 | - [(0, 61), (2, 57), (-50, 127), (2, 58)], | ||
| 262 | - [(-2, 78), (-2, 76), (-46, 127), (-1, 74)], | ||
| 263 | - [(1, 50), (11, 35), (-4, 66), (-4, 44)], | ||
| 264 | - [(7, 52), (4, 64), (-5, 78), (-1, 69)], | ||
| 265 | - [(10, 35), (1, 61), (-4, 71), (0, 62)], | ||
| 266 | - [(0, 44), (11, 35), (-8, 72), (-7, 51)], | ||
| 267 | - [(11, 38), (18, 25), (2, 59), (-4, 47)], | ||
| 268 | - [(1, 45), (12, 24), (-1, 55), (-6, 42)], | ||
| 269 | - [(0, 46), (13, 29), (-7, 70), (-3, 41)], | ||
| 270 | - [(5, 44), (13, 36), (-6, 75), (-6, 53)], | ||
| 271 | - [(31, 17), (-10, 93), (-8, 89), (8, 76)], | ||
| 272 | - [(1, 51), (-7, 73), (-34, 119), (-9, 78)], | ||
| 273 | - [(7, 50), (-2, 73), (-3, 75), (-11, 83)], | ||
| 274 | - [(28, 19), (13, 46), (32, 20), (9, 52)], | ||
| 275 | - [(16, 33), (9, 49), (30, 22), (0, 67)], | ||
| 276 | - [(14, 62), (-7, 100), (-44, 127), (-5, 90)], | ||
| 277 | - [(-13, 108), (9, 53), (0, 54), (1, 67)], | ||
| 278 | - [(-15, 100), (2, 53), (-5, 61), (-15, 72)], | ||
| 279 | - [(-13, 101), (5, 53), (0, 58), (-5, 75)], | ||
| 280 | - [(-13, 91), (-2, 61), (-1, 60), (-8, 80)], | ||
| 281 | - [(-12, 94), (0, 56), (-3, 61), (-21, 83)], | ||
| 282 | - [(-10, 88), (0, 56), (-8, 67), (-21, 64)], | ||
| 283 | - [(-16, 84), (-13, 63), (-25, 84), (-13, 31)], | ||
| 284 | - [(-10, 86), (-5, 60), (-14, 74), (-25, 64)], | ||
| 285 | - [(-7, 83), (-1, 62), (-5, 65), (-29, 94)], | ||
| 286 | - [(-13, 87), (4, 57), (5, 52), (9, 75)], | ||
| 287 | - [(-19, 94), (-6, 69), (2, 57), (17, 63)], | ||
| 288 | - [(1, 70), (4, 57), (0, 61), (-8, 74)], | ||
| 289 | - [(0, 72), (14, 39), (-9, 69), (-5, 35)], | ||
| 290 | - [(-5, 74), (4, 51), (-11, 70), (-2, 27)], | ||
| 291 | - [(18, 59), (13, 68), (18, 55), (13, 91)], | ||
| 292 | - [(-8, 102), (3, 64), (-4, 71), (3, 65)], | ||
| 293 | - [(-15, 100), (1, 61), (0, 58), (-7, 69)], | ||
| 294 | - [(0, 95), (9, 63), (7, 61), (8, 77)], | ||
| 295 | - [(-4, 75), (7, 50), (9, 41), (-10, 66)], | ||
| 296 | - [(2, 72), (16, 39), (18, 25), (3, 62)], | ||
| 297 | - [(-11, 75), (5, 44), (9, 32), (-3, 68)], | ||
| 298 | - [(-3, 71), (4, 52), (5, 43), (-20, 81)], | ||
| 299 | - [(15, 46), (11, 48), (9, 47), (0, 30)], | ||
| 300 | - [(-13, 69), (-5, 60), (0, 44), (1, 7)], | ||
| 301 | - [(0, 62), (-1, 59), (0, 51), (-3, 23)], | ||
| 302 | - [(0, 65), (0, 59), (2, 46), (-21, 74)], | ||
| 303 | - [(21, 37), (22, 33), (19, 38), (16, 66)], | ||
| 304 | - [(-15, 72), (5, 44), (-4, 66), (-23, 124)], | ||
| 305 | - [(9, 57), (14, 43), (15, 38), (17, 37)], | ||
| 306 | - [(16, 54), (-1, 78), (12, 42), (44, -18)], | ||
| 307 | - [(0, 62), (0, 60), (9, 34), (50, -34)], | ||
| 308 | - [(12, 72), (9, 69), (0, 89), (-22, 127)], | ||
| 309 | - [(24, 0), (11, 28), (4, 45), (4, 39)], | ||
| 310 | - [(15, 9), (2, 40), (10, 28), (0, 42)], | ||
| 311 | - [(8, 25), (3, 44), (10, 31), (7, 34)], | ||
| 312 | - [(13, 18), (0, 49), (33, -11), (11, 29)], | ||
| 313 | - [(15, 9), (0, 46), (52, -43), (8, 31)], | ||
| 314 | - [(13, 19), (2, 44), (18, 15), (6, 37)], | ||
| 315 | - [(10, 37), (2, 51), (28, 0), (7, 42)], | ||
| 316 | - [(12, 18), (0, 47), (35, -22), (3, 40)], | ||
| 317 | - [(6, 29), (4, 39), (38, -25), (8, 33)], | ||
| 318 | - [(20, 33), (2, 62), (34, 0), (13, 43)], | ||
| 319 | - [(15, 30), (6, 46), (39, -18), (13, 36)], | ||
| 320 | - [(4, 45), (0, 54), (32, -12), (4, 47)], | ||
| 321 | - [(1, 58), (3, 54), (102, -94), (3, 55)], | ||
| 322 | - [(0, 62), (2, 58), (0, 0), (2, 58)], | ||
| 323 | - [(7, 61), (4, 63), (56, -15), (6, 60)], | ||
| 324 | - [(12, 38), (6, 51), (33, -4), (8, 44)], | ||
| 325 | - [(11, 45), (6, 57), (29, 10), (11, 44)], | ||
| 326 | - [(15, 39), (7, 53), (37, -5), (14, 42)], | ||
| 327 | - [(11, 42), (6, 52), (51, -29), (7, 48)], | ||
| 328 | - [(13, 44), (6, 55), (39, -9), (4, 56)], | ||
| 329 | - [(16, 45), (11, 45), (52, -34), (4, 52)], | ||
| 330 | - [(12, 41), (14, 36), (69, -58), (13, 37)], | ||
| 331 | - [(10, 49), (8, 53), (67, -63), (9, 49)], | ||
| 332 | - [(30, 34), (-1, 82), (44, -5), (19, 58)], | ||
| 333 | - [(18, 42), (7, 55), (32, 7), (10, 48)], | ||
| 334 | - [(10, 55), (-3, 78), (55, -29), (12, 45)], | ||
| 335 | - [(17, 51), (15, 46), (32, 1), (0, 69)], | ||
| 336 | - [(17, 46), (22, 31), (0, 0), (20, 33)], | ||
| 337 | - [(0, 89), (-1, 84), (27, 36), (8, 63)], | ||
| 338 | - [(26, -19), (25, 7), (33, -25), (35, -18)], | ||
| 339 | - [(22, -17), (30, -7), (34, -30), (33, -25)], | ||
| 340 | - [(26, -17), (28, 3), (36, -28), (28, -3)], | ||
| 341 | - [(30, -25), (28, 4), (38, -28), (24, 10)], | ||
| 342 | - [(28, -20), (32, 0), (38, -27), (27, 0)], | ||
| 343 | - [(33, -23), (34, -1), (34, -18), (34, -14)], | ||
| 344 | - [(37, -27), (30, 6), (35, -16), (52, -44)], | ||
| 345 | - [(33, -23), (30, 6), (34, -14), (39, -24)], | ||
| 346 | - [(40, -28), (32, 9), (32, -8), (19, 17)], | ||
| 347 | - [(38, -17), (31, 19), (37, -6), (31, 25)], | ||
| 348 | - [(33, -11), (26, 27), (35, 0), (36, 29)], | ||
| 349 | - [(40, -15), (26, 30), (30, 10), (24, 33)], | ||
| 350 | - [(41, -6), (37, 20), (28, 18), (34, 15)], | ||
| 351 | - [(38, 1), (28, 34), (26, 25), (30, 20)], | ||
| 352 | - [(41, 17), (17, 70), (29, 41), (22, 73)], | ||
| 353 | - [(30, -6), (1, 67), (0, 75), (20, 34)], | ||
| 354 | - [(27, 3), (5, 59), (2, 72), (19, 31)], | ||
| 355 | - [(26, 22), (9, 67), (8, 77), (27, 44)], | ||
| 356 | - [(37, -16), (16, 30), (14, 35), (19, 16)], | ||
| 357 | - [(35, -4), (18, 32), (18, 31), (15, 36)], | ||
| 358 | - [(38, -8), (18, 35), (17, 35), (15, 36)], | ||
| 359 | - [(38, -3), (22, 29), (21, 30), (21, 28)], | ||
| 360 | - [(37, 3), (24, 31), (17, 45), (25, 21)], | ||
| 361 | - [(38, 5), (23, 38), (20, 42), (30, 20)], | ||
| 362 | - [(42, 0), (18, 43), (18, 45), (31, 12)], | ||
| 363 | - [(35, 16), (20, 41), (27, 26), (27, 16)], | ||
| 364 | - [(39, 22), (11, 63), (16, 54), (24, 42)], | ||
| 365 | - [(14, 48), (9, 59), (7, 66), (0, 93)], | ||
| 366 | - [(27, 37), (9, 64), (16, 56), (14, 56)], | ||
| 367 | - [(21, 60), (-1, 94), (11, 73), (15, 57)], | ||
| 368 | - [(12, 68), (-2, 89), (10, 67), (26, 38)], | ||
| 369 | - [(2, 97), (-9, 108), (-10, 116), (-24, 127)], | ||
| 370 | - [(-3, 71), (-6, 76), (-23, 112), (-24, 115)], | ||
| 371 | - [(-6, 42), (-2, 44), (-15, 71), (-22, 82)], | ||
| 372 | - [(-5, 50), (0, 45), (-7, 61), (-9, 62)], | ||
| 373 | - [(-3, 54), (0, 52), (0, 53), (0, 53)], | ||
| 374 | - [(-2, 62), (-3, 64), (-5, 66), (0, 59)], | ||
| 375 | - [(0, 58), (-2, 59), (-11, 77), (-14, 85)], | ||
| 376 | - [(1, 63), (-4, 70), (-9, 80), (-13, 89)], | ||
| 377 | - [(-2, 72), (-4, 75), (-9, 84), (-13, 94)], | ||
| 378 | - [(-1, 74), (-8, 82), (-10, 87), (-11, 92)], | ||
| 379 | - [(-9, 91), (-17, 102), (-34, 127), (-29, 127)], | ||
| 380 | - [(-5, 67), (-9, 77), (-21, 101), (-21, 100)], | ||
| 381 | - [(-5, 27), (3, 24), (-3, 39), (-14, 57)], | ||
| 382 | - [(-3, 39), (0, 42), (-5, 53), (-12, 67)], | ||
| 383 | - [(-2, 44), (0, 48), (-7, 61), (-11, 71)], | ||
| 384 | - [(0, 46), (0, 55), (-11, 75), (-10, 77)], | ||
| 385 | - [(-16, 64), (-6, 59), (-15, 77), (-21, 85)], | ||
| 386 | - [(-8, 68), (-7, 71), (-17, 91), (-16, 88)], | ||
| 387 | - [(-10, 78), (-12, 83), (-25, 107), (-23, 104)], | ||
| 388 | - [(-6, 77), (-11, 87), (-25, 111), (-15, 98)], | ||
| 389 | - [(-10, 86), (-30, 119), (-28, 122), (-37, 127)], | ||
| 390 | - [(-12, 92), (1, 58), (-11, 76), (-10, 82)], | ||
| 391 | - [(-15, 55), (-3, 29), (-10, 44), (-8, 48)], | ||
| 392 | - [(-10, 60), (-1, 36), (-10, 52), (-8, 61)], | ||
| 393 | - [(-6, 62), (1, 38), (-10, 57), (-8, 66)], | ||
| 394 | - [(-4, 65), (2, 43), (-9, 58), (-7, 70)], | ||
| 395 | - [(-12, 73), (-6, 55), (-16, 72), (-14, 75)], | ||
| 396 | - [(-8, 76), (0, 58), (-7, 69), (-10, 79)], | ||
| 397 | - [(-7, 80), (0, 64), (-4, 69), (-9, 83)], | ||
| 398 | - [(-9, 88), (-3, 74), (-5, 74), (-12, 92)], | ||
| 399 | - [(-17, 110), (-10, 90), (-9, 86), (-18, 108)], | ||
| 400 | - [(-11, 97), (0, 70), (2, 66), (-4, 79)], | ||
| 401 | - [(-20, 84), (-4, 29), (-9, 34), (-22, 69)], | ||
| 402 | - [(-11, 79), (5, 31), (1, 32), (-16, 75)], | ||
| 403 | - [(-6, 73), (7, 42), (11, 31), (-2, 58)], | ||
| 404 | - [(-4, 74), (1, 59), (5, 52), (1, 58)], | ||
| 405 | - [(-13, 86), (-2, 58), (-2, 55), (-13, 78)], | ||
| 406 | - [(-13, 96), (-3, 72), (-2, 67), (-9, 83)], | ||
| 407 | - [(-11, 97), (-3, 81), (0, 73), (-4, 81)], | ||
| 408 | - [(-19, 117), (-11, 97), (-8, 89), (-13, 99)], | ||
| 409 | - [(-8, 78), (0, 58), (3, 52), (-13, 81)], | ||
| 410 | - [(-5, 33), (8, 5), (7, 4), (-6, 38)], | ||
| 411 | - [(-4, 48), (10, 14), (10, 8), (-13, 62)], | ||
| 412 | - [(-2, 53), (14, 18), (17, 8), (-6, 58)], | ||
| 413 | - [(-3, 62), (13, 27), (16, 19), (-2, 59)], | ||
| 414 | - [(-13, 71), (2, 40), (3, 37), (-16, 73)], | ||
| 415 | - [(-10, 79), (0, 58), (-1, 61), (-10, 76)], | ||
| 416 | - [(-12, 86), (-3, 70), (-5, 73), (-13, 86)], | ||
| 417 | - [(-13, 90), (-6, 79), (-1, 70), (-9, 83)], | ||
| 418 | - [(-14, 97), (-8, 85), (-4, 78), (-10, 87)], | ||
| 419 | - [(0, 0), (0, 0), (0, 0), (0, 0)], | ||
| 420 | - [(-6, 93), (-13, 106), (-21, 126), (-22, 127)], | ||
| 421 | - [(-6, 84), (-16, 106), (-23, 124), (-25, 127)], | ||
| 422 | - [(-8, 79), (-10, 87), (-20, 110), (-25, 120)], | ||
| 423 | - [(0, 66), (-21, 114), (-26, 126), (-27, 127)], | ||
| 424 | - [(-1, 71), (-18, 110), (-25, 124), (-19, 114)], | ||
| 425 | - [(0, 62), (-14, 98), (-17, 105), (-23, 117)], | ||
| 426 | - [(-2, 60), (-22, 110), (-27, 121), (-25, 118)], | ||
| 427 | - [(-2, 59), (-21, 106), (-27, 117), (-26, 117)], | ||
| 428 | - [(-5, 75), (-18, 103), (-17, 102), (-24, 113)], | ||
| 429 | - [(-3, 62), (-21, 107), (-26, 117), (-28, 118)], | ||
| 430 | - [(-4, 58), (-23, 108), (-27, 116), (-31, 120)], | ||
| 431 | - [(-9, 66), (-26, 112), (-33, 122), (-37, 124)], | ||
| 432 | - [(-1, 79), (-10, 96), (-10, 95), (-10, 94)], | ||
| 433 | - [(0, 71), (-12, 95), (-14, 100), (-15, 102)], | ||
| 434 | - [(3, 68), (-5, 91), (-8, 95), (-10, 99)], | ||
| 435 | - [(10, 44), (-9, 93), (-17, 111), (-13, 106)], | ||
| 436 | - [(-7, 62), (-22, 94), (-28, 114), (-50, 127)], | ||
| 437 | - [(15, 36), (-5, 86), (-6, 89), (-5, 92)], | ||
| 438 | - [(14, 40), (9, 67), (-2, 80), (17, 57)], | ||
| 439 | - [(16, 27), (-4, 80), (-4, 82), (-5, 86)], | ||
| 440 | - [(12, 29), (-10, 85), (-9, 85), (-13, 94)], | ||
| 441 | - [(1, 44), (-1, 70), (-8, 81), (-12, 91)], | ||
| 442 | - [(20, 36), (7, 60), (-1, 72), (-2, 77)], | ||
| 443 | - [(18, 32), (9, 58), (5, 64), (0, 71)], | ||
| 444 | - [(5, 42), (5, 61), (1, 67), (-1, 73)], | ||
| 445 | - [(1, 48), (12, 50), (9, 56), (4, 64)], | ||
| 446 | - [(10, 62), (15, 50), (0, 69), (-7, 81)], | ||
| 447 | - [(17, 46), (18, 49), (1, 69), (5, 64)], | ||
| 448 | - [(9, 64), (17, 54), (7, 69), (15, 57)], | ||
| 449 | - [(-12, 104), (10, 41), (-7, 69), (1, 67)], | ||
| 450 | - [(-11, 97), (7, 46), (-6, 67), (0, 68)], | ||
| 451 | - [(-16, 96), (-1, 51), (-16, 77), (-10, 67)], | ||
| 452 | - [(-7, 88), (7, 49), (-2, 64), (1, 68)], | ||
| 453 | - [(-8, 85), (8, 52), (2, 61), (0, 77)], | ||
| 454 | - [(-7, 85), (9, 41), (-6, 67), (2, 64)], | ||
| 455 | - [(-9, 85), (6, 47), (-3, 64), (0, 68)], | ||
| 456 | - [(-13, 88), (2, 55), (2, 57), (-5, 78)], | ||
| 457 | - [(4, 66), (13, 41), (-3, 65), (7, 55)], | ||
| 458 | - [(-3, 77), (10, 44), (-3, 66), (5, 59)], | ||
| 459 | - [(-3, 76), (6, 50), (0, 62), (2, 65)], | ||
| 460 | - [(-6, 76), (5, 53), (9, 51), (14, 54)], | ||
| 461 | - [(10, 58), (13, 49), (-1, 66), (15, 44)], | ||
| 462 | - [(-1, 76), (4, 63), (-2, 71), (5, 60)], | ||
| 463 | - [(-1, 83), (6, 64), (-2, 75), (2, 70)], | ||
| 464 | - [(-7, 99), (-2, 69), (-1, 70), (-2, 76)], | ||
| 465 | - [(-14, 95), (-2, 59), (-9, 72), (-18, 86)], | ||
| 466 | - [(2, 95), (6, 70), (14, 60), (12, 70)], | ||
| 467 | - [(0, 76), (10, 44), (16, 37), (5, 64)], | ||
| 468 | - [(-5, 74), (9, 31), (0, 47), (-12, 70)], | ||
| 469 | - [(0, 70), (12, 43), (18, 35), (11, 55)], | ||
| 470 | - [(-11, 75), (3, 53), (11, 37), (5, 56)], | ||
| 471 | - [(1, 68), (14, 34), (12, 41), (0, 69)], | ||
| 472 | - [(0, 65), (10, 38), (10, 41), (2, 65)], | ||
| 473 | - [(-14, 73), (-3, 52), (2, 48), (-6, 74)], | ||
| 474 | - [(3, 62), (13, 40), (12, 41), (5, 54)], | ||
| 475 | - [(4, 62), (17, 32), (13, 41), (7, 54)], | ||
| 476 | - [(-1, 68), (7, 44), (0, 59), (-6, 76)], | ||
| 477 | - [(-13, 75), (7, 38), (3, 50), (-11, 82)], | ||
| 478 | - [(11, 55), (13, 50), (19, 40), (-2, 77)], | ||
| 479 | - [(5, 64), (10, 57), (3, 66), (-2, 77)], | ||
| 480 | - [(12, 70), (26, 43), (18, 50), (25, 42)], | ||
| 481 | - [(15, 6), (14, 11), (19, -6), (17, -13)], | ||
| 482 | - [(6, 19), (11, 14), (18, -6), (16, -9)], | ||
| 483 | - [(7, 16), (9, 11), (14, 0), (17, -12)], | ||
| 484 | - [(12, 14), (18, 11), (26, -12), (27, -21)], | ||
| 485 | - [(18, 13), (21, 9), (31, -16), (37, -30)], | ||
| 486 | - [(13, 11), (23, -2), (33, -25), (41, -40)], | ||
| 487 | - [(13, 15), (32, -15), (33, -22), (42, -41)], | ||
| 488 | - [(15, 16), (32, -15), (37, -28), (48, -47)], | ||
| 489 | - [(12, 23), (34, -21), (39, -30), (39, -32)], | ||
| 490 | - [(13, 23), (39, -23), (42, -30), (46, -40)], | ||
| 491 | - [(15, 20), (42, -33), (47, -42), (52, -51)], | ||
| 492 | - [(14, 26), (41, -31), (45, -36), (46, -41)], | ||
| 493 | - [(14, 44), (46, -28), (49, -34), (52, -39)], | ||
| 494 | - [(17, 40), (38, -12), (41, -17), (43, -19)], | ||
| 495 | - [(17, 47), (21, 29), (32, 9), (32, 11)], | ||
| 496 | - [(24, 17), (45, -24), (69, -71), (61, -55)], | ||
| 497 | - [(21, 21), (53, -45), (63, -63), (56, -46)], | ||
| 498 | - [(25, 22), (48, -26), (66, -64), (62, -50)], | ||
| 499 | - [(31, 27), (65, -43), (77, -74), (81, -67)], | ||
| 500 | - [(22, 29), (43, -19), (54, -39), (45, -20)], | ||
| 501 | - [(19, 35), (39, -10), (52, -35), (35, -2)], | ||
| 502 | - [(14, 50), (30, 9), (41, -10), (28, 15)], | ||
| 503 | - [(10, 57), (18, 26), (36, 0), (34, 1)], | ||
| 504 | - [(7, 63), (20, 27), (40, -1), (39, 1)], | ||
| 505 | - [(-2, 77), (0, 57), (30, 14), (30, 17)], | ||
| 506 | - [(-4, 82), (-14, 82), (28, 26), (20, 38)], | ||
| 507 | - [(-3, 94), (-5, 75), (23, 37), (18, 45)], | ||
| 508 | - [(9, 69), (-19, 97), (12, 55), (15, 54)], | ||
| 509 | - [(-12, 109), (-35, 125), (11, 65), (0, 79)], | ||
| 510 | - [(36, -35), (27, 0), (37, -33), (36, -16)], | ||
| 511 | - [(36, -34), (28, 0), (39, -36), (37, -14)], | ||
| 512 | - [(32, -26), (31, -4), (40, -37), (37, -17)], | ||
| 513 | - [(37, -30), (27, 6), (38, -30), (32, 1)], | ||
| 514 | - [(44, -32), (34, 8), (46, -33), (34, 15)], | ||
| 515 | - [(34, -18), (30, 10), (42, -30), (29, 15)], | ||
| 516 | - [(34, -15), (24, 22), (40, -24), (24, 25)], | ||
| 517 | - [(40, -15), (33, 19), (49, -29), (34, 22)], | ||
| 518 | - [(33, -7), (22, 32), (38, -12), (31, 16)], | ||
| 519 | - [(35, -5), (26, 31), (40, -10), (35, 18)], | ||
| 520 | - [(33, 0), (21, 41), (38, -3), (31, 28)], | ||
| 521 | - [(38, 2), (26, 44), (46, -5), (33, 41)], | ||
| 522 | - [(33, 13), (23, 47), (31, 20), (36, 28)], | ||
| 523 | - [(23, 35), (16, 65), (29, 30), (27, 47)], | ||
| 524 | - [(13, 58), (14, 71), (25, 44), (21, 62)], | ||
| 525 | - [(29, -3), (8, 60), (12, 48), (18, 31)], | ||
| 526 | - [(26, 0), (6, 63), (11, 49), (19, 26)], | ||
| 527 | - [(22, 30), (17, 65), (26, 45), (36, 24)], | ||
| 528 | - [(31, -7), (21, 24), (22, 22), (24, 23)], | ||
| 529 | - [(35, -15), (23, 20), (23, 22), (27, 16)], | ||
| 530 | - [(34, -3), (26, 23), (27, 21), (24, 30)], | ||
| 531 | - [(34, 3), (27, 32), (33, 20), (31, 29)], | ||
| 532 | - [(36, -1), (28, 23), (26, 28), (22, 41)], | ||
| 533 | - [(34, 5), (28, 24), (30, 24), (22, 42)], | ||
| 534 | - [(32, 11), (23, 40), (27, 34), (16, 60)], | ||
| 535 | - [(35, 5), (24, 32), (18, 42), (15, 52)], | ||
| 536 | - [(34, 12), (28, 29), (25, 39), (14, 60)], | ||
| 537 | - [(39, 11), (23, 42), (18, 50), (3, 78)], | ||
| 538 | - [(30, 29), (19, 57), (12, 70), (-16, 123)], | ||
| 539 | - [(34, 26), (22, 53), (21, 54), (21, 53)], | ||
| 540 | - [(29, 39), (22, 61), (14, 71), (22, 56)], | ||
| 541 | - [(19, 66), (11, 86), (11, 83), (25, 61)], | ||
| 542 | - [(31, 21), (12, 40), (25, 32), (21, 33)], | ||
| 543 | - [(31, 31), (11, 51), (21, 49), (19, 50)], | ||
| 544 | - [(25, 50), (14, 59), (21, 54), (17, 61)], | ||
| 545 | - [(-17, 120), (-4, 79), (-5, 85), (-3, 78)], | ||
| 546 | - [(-20, 112), (-7, 71), (-6, 81), (-8, 74)], | ||
| 547 | - [(-18, 114), (-5, 69), (-10, 77), (-9, 72)], | ||
| 548 | - [(-11, 85), (-9, 70), (-7, 81), (-10, 72)], | ||
| 549 | - [(-15, 92), (-8, 66), (-17, 80), (-18, 75)], | ||
| 550 | - [(-14, 89), (-10, 68), (-18, 73), (-12, 71)], | ||
| 551 | - [(-26, 71), (-19, 73), (-4, 74), (-11, 63)], | ||
| 552 | - [(-15, 81), (-12, 69), (-10, 83), (-5, 70)], | ||
| 553 | - [(-14, 80), (-16, 70), (-9, 71), (-17, 75)], | ||
| 554 | - [(0, 68), (-15, 67), (-9, 67), (-14, 72)], | ||
| 555 | - [(-14, 70), (-20, 62), (-1, 61), (-16, 67)], | ||
| 556 | - [(-24, 56), (-19, 70), (-8, 66), (-8, 53)], | ||
| 557 | - [(-23, 68), (-16, 66), (-14, 66), (-14, 59)], | ||
| 558 | - [(-24, 50), (-22, 65), (0, 59), (-9, 52)], | ||
| 559 | - [(-11, 74), (-20, 63), (2, 59), (-11, 68)], | ||
| 560 | - [(23, -13), (9, -2), (17, -10), (9, -2)], | ||
| 561 | - [(26, -13), (26, -9), (32, -13), (30, -10)], | ||
| 562 | - [(40, -15), (33, -9), (42, -9), (31, -4)], | ||
| 563 | - [(49, -14), (39, -7), (49, -5), (33, -1)], | ||
| 564 | - [(44, 3), (41, -2), (53, 0), (33, 7)], | ||
| 565 | - [(45, 6), (45, 3), (64, 3), (31, 12)], | ||
| 566 | - [(44, 34), (49, 9), (68, 10), (37, 23)], | ||
| 567 | - [(33, 54), (45, 27), (66, 27), (31, 38)], | ||
| 568 | - [(19, 82), (36, 59), (47, 57), (20, 64)], | ||
| 569 | - [(-3, 75), (-6, 66), (-5, 71), (-9, 71)], | ||
| 570 | - [(-1, 23), (-7, 35), (0, 24), (-7, 37)], | ||
| 571 | - [(1, 34), (-7, 42), (-1, 36), (-8, 44)], | ||
| 572 | - [(1, 43), (-8, 45), (-2, 42), (-11, 49)], | ||
| 573 | - [(0, 54), (-5, 48), (-2, 52), (-10, 56)], | ||
| 574 | - [(-2, 55), (-12, 56), (-9, 57), (-12, 59)], | ||
| 575 | - [(0, 61), (-6, 60), (-6, 63), (-8, 63)], | ||
| 576 | - [(1, 64), (-5, 62), (-4, 65), (-9, 67)], | ||
| 577 | - [(0, 68), (-8, 66), (-4, 67), (-6, 68)], | ||
| 578 | - [(-9, 92), (-8, 76), (-7, 82), (-10, 79)], | ||
| 579 | - [(-14, 106), (-5, 85), (-3, 81), (-3, 78)], | ||
| 580 | - [(-13, 97), (-6, 81), (-3, 76), (-8, 74)], | ||
| 581 | - [(-15, 90), (-10, 77), (-7, 72), (-9, 72)], | ||
| 582 | - [(-12, 90), (-7, 81), (-6, 78), (-10, 72)], | ||
| 583 | - [(-18, 88), (-17, 80), (-12, 72), (-18, 75)], | ||
| 584 | - [(-10, 73), (-18, 73), (-14, 68), (-12, 71)], | ||
| 585 | - [(-9, 79), (-4, 74), (-3, 70), (-11, 63)], | ||
| 586 | - [(-14, 86), (-10, 83), (-6, 76), (-5, 70)], | ||
| 587 | - [(-10, 73), (-9, 71), (-5, 66), (-17, 75)], | ||
| 588 | - [(-10, 70), (-9, 67), (-5, 62), (-14, 72)], | ||
| 589 | - [(-10, 69), (-1, 61), (0, 57), (-16, 67)], | ||
| 590 | - [(-5, 66), (-8, 66), (-4, 61), (-8, 53)], | ||
| 591 | - [(-9, 64), (-14, 66), (-9, 60), (-14, 59)], | ||
| 592 | - [(-5, 58), (0, 59), (1, 54), (-9, 52)], | ||
| 593 | - [(2, 59), (2, 59), (2, 58), (-11, 68)], | ||
| 594 | - [(21, -10), (21, -13), (17, -10), (9, -2)], | ||
| 595 | - [(24, -11), (33, -14), (32, -13), (30, -10)], | ||
| 596 | - [(28, -8), (39, -7), (42, -9), (31, -4)], | ||
| 597 | - [(28, -1), (46, -2), (49, -5), (33, -1)], | ||
| 598 | - [(29, 3), (51, 2), (53, 0), (33, 7)], | ||
| 599 | - [(29, 9), (60, 6), (64, 3), (31, 12)], | ||
| 600 | - [(35, 20), (61, 17), (68, 10), (37, 23)], | ||
| 601 | - [(29, 36), (55, 34), (66, 27), (31, 38)], | ||
| 602 | - [(14, 67), (42, 62), (47, 57), (20, 64)], | ||
| 603 | -]; | ||
| 604 | - | ||
| 605 | - | ||
| 606 | -// --------------------------------------------------------------------------------- | ||
| 607 | -// ctxBlockCat 5 (luma 8x8) position maps — spec Table 9-43. | ||
| 608 | -// | ||
| 609 | -// Moved here from `rusty_h264-decoder/src/mb16.rs` (rip/R6-1) so the ENCODER can share | ||
| 610 | -// them. The decoder has decoded x264's High-profile 8x8 streams bit-exact with these | ||
| 611 | -// since c1375d1/d137218, so they are validated spec data, not a fresh transcription — | ||
| 612 | -// which is the whole reason the encoder work reuses them rather than re-deriving. | ||
| 613 | -// | ||
| 614 | -// Cat 5 is the odd category in two ways, both of which matter to a writer: | ||
| 615 | -// * ctxIdxInc is NOT the scan position (as it is for the 4x4 cats) — 63 positions | ||
| 616 | -// fold onto 15 contexts for `significant_coeff_flag` and 9 for | ||
| 617 | -// `last_significant_coeff_flag`. | ||
| 618 | -// * it carries NO `coded_block_flag`; presence is inferred from | ||
| 619 | -// CodedBlockPatternLuma. Emitting one desyncs the stream. | ||
| 620 | -// --------------------------------------------------------------------------------- | ||
| 621 | - | ||
| 622 | -/// `significant_coeff_flag` ctxIdxInc for ctxBlockCat 5, frame-coded (spec Table 9-43). | ||
| 623 | -/// Absolute ctxIdx is `402 + SIG8X8[pos]` (encoder) / the decoder's matching base. | ||
| 624 | -pub const SIG8X8: [u8; 64] = [ | ||
| 625 | - 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, // | ||
| 626 | - 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7, // | ||
| 627 | - 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, // | ||
| 628 | - 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, 14, | ||
| 629 | -]; | ||
| 630 | - | ||
| 631 | -/// `last_significant_coeff_flag` ctxIdxInc for ctxBlockCat 5 (spec Table 9-43). | ||
| 632 | -/// Absolute ctxIdx is `417 + LAST8X8[pos]`. | ||
| 633 | -pub const LAST8X8: [u8; 64] = [ | ||
| 634 | - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // | ||
| 635 | - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // | ||
| 636 | - 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, // | ||
| 637 | - 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, | ||
| 638 | -]; | ||
| 639 | - | ||
| 640 | -/// ctxIdxOffset bases for ctxBlockCat 5, spec Table 9-34. Named so the encoder's | ||
| 641 | -/// residual writer cannot silently disagree with the decoder's reader. | ||
| 642 | -pub const CAT5_SIG_BASE: usize = 402; | ||
| 643 | -pub const CAT5_LAST_BASE: usize = 417; | ||
| 644 | -pub const CAT5_LEVEL_BASE: usize = 426; | ||
vendor/rusty_h264-common/src/cavlc.rsdeleted+0 -821
| @@ -1,821 +0,0 @@ | |||
| 1 | -//! CAVLC — Context-Adaptive Variable-Length Coding of residual blocks. | ||
| 2 | -//! | ||
| 3 | -//! This is the entropy coder that actually compresses: a 4×4 block of quantized | ||
| 4 | -//! coefficients (in zig-zag scan order) is coded as `coeff_token` (count + | ||
| 5 | -//! trailing ones), trailing-one signs, the remaining levels, `total_zeros`, and | ||
| 6 | -//! per-coefficient `run_before`. The VLC tables below are the exact H.264 tables | ||
| 7 | -//! (matching the reference decoders our output is validated against). | ||
| 8 | -//! | ||
| 9 | -//! [`encode_residual_block`] and [`decode_residual_block`] are an exact inverse | ||
| 10 | -//! pair, parameterized by `nc` (the neighbor-derived context that selects the | ||
| 11 | -//! `coeff_token` table) and `max_coeff` (16 for a full 4×4, 15 for an AC block, | ||
| 12 | -//! 4 for chroma DC). Neighbor `nc` bookkeeping lives in the macroblock layer. | ||
| 13 | - | ||
| 14 | -use crate::{BitReader, BitWriter}; | ||
| 15 | -use crate::bit_reader::OutOfData; | ||
| 16 | - | ||
| 17 | -/// 4×4 zig-zag scan: scan position → raster index. | ||
| 18 | -pub const ZIGZAG_4X4: [usize; 16] = [ | ||
| 19 | - 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15, | ||
| 20 | -]; | ||
| 21 | - | ||
| 22 | -/// Zig-zag scan of a raster 4×4 block (full DC+AC), **unrolled** like openh264's | ||
| 23 | -/// `WelsScan4x4DcAc` — constant indices, so no `ZIGZAG_4X4[i]` table read and no | ||
| 24 | -/// per-element bounds check (the looped `block[ZIGZAG_4X4[i]]` form forces one). | ||
| 25 | -#[inline] | ||
| 26 | -pub fn scan_4x4_dcac(d: &[i32; 16]) -> [i32; 16] { | ||
| 27 | - [ | ||
| 28 | - d[0], d[1], d[4], d[8], d[5], d[2], d[3], d[6], d[9], d[12], d[13], d[10], d[7], d[11], | ||
| 29 | - d[14], d[15], | ||
| 30 | - ] | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -/// Zig-zag scan of the 15 AC coefficients (skipping DC), unrolled like openh264's | ||
| 34 | -/// `WelsScan4x4Ac` (`= ZIGZAG_4X4[1..]`). | ||
| 35 | -#[inline] | ||
| 36 | -pub fn scan_4x4_ac(d: &[i32; 16]) -> [i32; 15] { | ||
| 37 | - [ | ||
| 38 | - d[1], d[4], d[8], d[5], d[2], d[3], d[6], d[9], d[12], d[13], d[10], d[7], d[11], d[14], | ||
| 39 | - d[15], | ||
| 40 | - ] | ||
| 41 | -} | ||
| 42 | - | ||
| 43 | -/// Inverse of [`scan_4x4_dcac`] (decoder): scatter scan-order coefficients back to | ||
| 44 | -/// the raster 4×4 block, unrolled (no `ZIGZAG_4X4[i]` table read / bounds check). | ||
| 45 | -#[inline] | ||
| 46 | -pub fn un_scan_4x4_dcac(s: &[i32; 16]) -> [i32; 16] { | ||
| 47 | - let mut d = [0i32; 16]; | ||
| 48 | - d[0] = s[0]; | ||
| 49 | - d[1] = s[1]; | ||
| 50 | - d[4] = s[2]; | ||
| 51 | - d[8] = s[3]; | ||
| 52 | - d[5] = s[4]; | ||
| 53 | - d[2] = s[5]; | ||
| 54 | - d[3] = s[6]; | ||
| 55 | - d[6] = s[7]; | ||
| 56 | - d[9] = s[8]; | ||
| 57 | - d[12] = s[9]; | ||
| 58 | - d[13] = s[10]; | ||
| 59 | - d[10] = s[11]; | ||
| 60 | - d[7] = s[12]; | ||
| 61 | - d[11] = s[13]; | ||
| 62 | - d[14] = s[14]; | ||
| 63 | - d[15] = s[15]; | ||
| 64 | - d | ||
| 65 | -} | ||
| 66 | - | ||
| 67 | -/// Inverse of [`scan_4x4_ac`] (decoder): scatter the 15 AC coefficients into the | ||
| 68 | -/// existing block's raster positions (leaving DC `[0]` untouched). `s[0..15]` used. | ||
| 69 | -#[inline] | ||
| 70 | -pub fn un_scan_4x4_ac_into(s: &[i32], d: &mut [i32; 16]) { | ||
| 71 | - d[1] = s[0]; | ||
| 72 | - d[4] = s[1]; | ||
| 73 | - d[8] = s[2]; | ||
| 74 | - d[5] = s[3]; | ||
| 75 | - d[2] = s[4]; | ||
| 76 | - d[3] = s[5]; | ||
| 77 | - d[6] = s[6]; | ||
| 78 | - d[9] = s[7]; | ||
| 79 | - d[12] = s[8]; | ||
| 80 | - d[13] = s[9]; | ||
| 81 | - d[10] = s[10]; | ||
| 82 | - d[7] = s[11]; | ||
| 83 | - d[11] = s[12]; | ||
| 84 | - d[14] = s[13]; | ||
| 85 | - d[15] = s[14]; | ||
| 86 | -} | ||
| 87 | - | ||
| 88 | -/// `coded_block_pattern` for Intra macroblocks (4:2:0), indexed by `codeNum` | ||
| 89 | -/// (the `me(v)` mapping, spec Table 9-4). Maps code number → CBP value. | ||
| 90 | -#[rustfmt::skip] | ||
| 91 | -const CBP_INTRA: [u8; 48] = [ | ||
| 92 | - 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, | ||
| 93 | - 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4, | ||
| 94 | - 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41, | ||
| 95 | -]; | ||
| 96 | - | ||
| 97 | -/// `coded_block_pattern` for Inter macroblocks (4:2:0), indexed by `codeNum`. | ||
| 98 | -#[rustfmt::skip] | ||
| 99 | -const CBP_INTER: [u8; 48] = [ | ||
| 100 | - 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, | ||
| 101 | - 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46, | ||
| 102 | - 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41, | ||
| 103 | -]; | ||
| 104 | - | ||
| 105 | -/// Inverse of a `codeNum → cbp` table: `cbp → codeNum`, for a direct lookup in | ||
| 106 | -/// the encoder instead of a 48-entry linear `.position()` scan per macroblock. | ||
| 107 | -const fn invert_cbp(table: &[u8; 48]) -> [u8; 48] { | ||
| 108 | - let mut inv = [0u8; 48]; | ||
| 109 | - let mut i = 0; | ||
| 110 | - while i < 48 { | ||
| 111 | - inv[table[i] as usize] = i as u8; | ||
| 112 | - i += 1; | ||
| 113 | - } | ||
| 114 | - inv | ||
| 115 | -} | ||
| 116 | -const INV_CBP_INTRA: [u8; 48] = invert_cbp(&CBP_INTRA); | ||
| 117 | -const INV_CBP_INTER: [u8; 48] = invert_cbp(&CBP_INTER); | ||
| 118 | - | ||
| 119 | -/// Decodes a `coded_block_pattern` (`me(v)`) for an Intra macroblock. | ||
| 120 | -pub fn read_cbp_intra(r: &mut BitReader) -> Result<u32, OutOfData> { | ||
| 121 | - let code_num = r.read_ue()? as usize; | ||
| 122 | - Ok(*CBP_INTRA.get(code_num).unwrap_or(&0) as u32) | ||
| 123 | -} | ||
| 124 | - | ||
| 125 | -/// Encodes a `coded_block_pattern` (`me(v)`) for an Intra macroblock. | ||
| 126 | -pub fn write_cbp_intra(w: &mut BitWriter, cbp: u32) { | ||
| 127 | - w.write_ue(INV_CBP_INTRA[cbp as usize] as u32); | ||
| 128 | -} | ||
| 129 | - | ||
| 130 | -/// Decodes a `coded_block_pattern` (`me(v)`) for an Inter macroblock. | ||
| 131 | -pub fn read_cbp_inter(r: &mut BitReader) -> Result<u32, OutOfData> { | ||
| 132 | - let code_num = r.read_ue()? as usize; | ||
| 133 | - Ok(*CBP_INTER.get(code_num).unwrap_or(&0) as u32) | ||
| 134 | -} | ||
| 135 | - | ||
| 136 | -/// Encodes a `coded_block_pattern` (`me(v)`) for an Inter macroblock. | ||
| 137 | -pub fn write_cbp_inter(w: &mut BitWriter, cbp: u32) { | ||
| 138 | - w.write_ue(INV_CBP_INTER[cbp as usize] as u32); | ||
| 139 | -} | ||
| 140 | - | ||
| 141 | -// ---- coeff_token, four nC tables. Index = TotalCoeff*4 + TrailingOnes. ---- | ||
| 142 | - | ||
| 143 | -#[rustfmt::skip] | ||
| 144 | -const COEFF_TOKEN_LEN: [[u8; 68]; 4] = [ | ||
| 145 | - [ | ||
| 146 | - 1,0,0,0, | ||
| 147 | - 6,2,0,0, 8,6,3,0, 9,8,7,5, 10,9,8,6, | ||
| 148 | - 11,10,9,7, 13,11,10,8, 13,13,11,9, 13,13,13,10, | ||
| 149 | - 14,14,13,11, 14,14,14,13, 15,15,14,14, 15,15,15,14, | ||
| 150 | - 16,15,15,15, 16,16,16,15, 16,16,16,16, 16,16,16,16, | ||
| 151 | - ], | ||
| 152 | - [ | ||
| 153 | - 2,0,0,0, | ||
| 154 | - 6,2,0,0, 6,5,3,0, 7,6,6,4, 8,6,6,4, | ||
| 155 | - 8,7,7,5, 9,8,8,6, 11,9,9,6, 11,11,11,7, | ||
| 156 | - 12,11,11,9, 12,12,12,11, 12,12,12,11, 13,13,13,12, | ||
| 157 | - 13,13,13,13, 13,14,13,13, 14,14,14,13, 14,14,14,14, | ||
| 158 | - ], | ||
| 159 | - [ | ||
| 160 | - 4,0,0,0, | ||
| 161 | - 6,4,0,0, 6,5,4,0, 6,5,5,4, 7,5,5,4, | ||
| 162 | - 7,5,5,4, 7,6,6,4, 7,6,6,4, 8,7,7,5, | ||
| 163 | - 8,8,7,6, 9,8,8,7, 9,9,8,8, 9,9,9,8, | ||
| 164 | - 10,9,9,9, 10,10,10,10, 10,10,10,10, 10,10,10,10, | ||
| 165 | - ], | ||
| 166 | - [ | ||
| 167 | - 6,0,0,0, | ||
| 168 | - 6,6,0,0, 6,6,6,0, 6,6,6,6, 6,6,6,6, | ||
| 169 | - 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6, | ||
| 170 | - 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6, | ||
| 171 | - 6,6,6,6, 6,6,6,6, 6,6,6,6, 6,6,6,6, | ||
| 172 | - ], | ||
| 173 | -]; | ||
| 174 | - | ||
| 175 | -#[rustfmt::skip] | ||
| 176 | -const COEFF_TOKEN_BITS: [[u8; 68]; 4] = [ | ||
| 177 | - [ | ||
| 178 | - 1,0,0,0, | ||
| 179 | - 5,1,0,0, 7,4,1,0, 7,6,5,3, 7,6,5,3, | ||
| 180 | - 7,6,5,4, 15,6,5,4, 11,14,5,4, 8,10,13,4, | ||
| 181 | - 15,14,9,4, 11,10,13,12, 15,14,9,12, 11,10,13,8, | ||
| 182 | - 15,1,9,12, 11,14,13,8, 7,10,9,12, 4,6,5,8, | ||
| 183 | - ], | ||
| 184 | - [ | ||
| 185 | - 3,0,0,0, | ||
| 186 | - 11,2,0,0, 7,7,3,0, 7,10,9,5, 7,6,5,4, | ||
| 187 | - 4,6,5,6, 7,6,5,8, 15,6,5,4, 11,14,13,4, | ||
| 188 | - 15,10,9,4, 11,14,13,12, 8,10,9,8, 15,14,13,12, | ||
| 189 | - 11,10,9,12, 7,11,6,8, 9,8,10,1, 7,6,5,4, | ||
| 190 | - ], | ||
| 191 | - [ | ||
| 192 | - 15,0,0,0, | ||
| 193 | - 15,14,0,0, 11,15,13,0, 8,12,14,12, 15,10,11,11, | ||
| 194 | - 11,8,9,10, 9,14,13,9, 8,10,9,8, 15,14,13,13, | ||
| 195 | - 11,14,10,12, 15,10,13,12, 11,14,9,12, 8,10,13,8, | ||
| 196 | - 13,7,9,12, 9,12,11,10, 5,8,7,6, 1,4,3,2, | ||
| 197 | - ], | ||
| 198 | - [ | ||
| 199 | - 3,0,0,0, | ||
| 200 | - 0,1,0,0, 4,5,6,0, 8,9,10,11, 12,13,14,15, | ||
| 201 | - 16,17,18,19, 20,21,22,23, 24,25,26,27, 28,29,30,31, | ||
| 202 | - 32,33,34,35, 36,37,38,39, 40,41,42,43, 44,45,46,47, | ||
| 203 | - 48,49,50,51, 52,53,54,55, 56,57,58,59, 60,61,62,63, | ||
| 204 | - ], | ||
| 205 | -]; | ||
| 206 | - | ||
| 207 | -/// chroma DC (2×2) coeff_token, index = TotalCoeff*4 + TrailingOnes. | ||
| 208 | -#[rustfmt::skip] | ||
| 209 | -const CHROMA_DC_COEFF_TOKEN_LEN: [u8; 20] = [ | ||
| 210 | - 2,0,0,0, 6,1,0,0, 6,6,3,0, 6,7,7,6, 6,8,8,7, | ||
| 211 | -]; | ||
| 212 | -#[rustfmt::skip] | ||
| 213 | -const CHROMA_DC_COEFF_TOKEN_BITS: [u8; 20] = [ | ||
| 214 | - 1,0,0,0, 7,1,0,0, 4,6,1,0, 3,3,2,5, 2,3,2,0, | ||
| 215 | -]; | ||
| 216 | - | ||
| 217 | -/// total_zeros, indexed `[TotalCoeff-1][total_zeros]` (TotalCoeff 1..15). | ||
| 218 | -#[rustfmt::skip] | ||
| 219 | -const TOTAL_ZEROS_LEN: [[u8; 16]; 15] = [ | ||
| 220 | - [1,3,3,4,4,5,5,6,6,7,7,8,8,9,9,9], | ||
| 221 | - [3,3,3,3,3,4,4,4,4,5,5,6,6,6,6,0], | ||
| 222 | - [4,3,3,3,4,4,3,3,4,5,5,6,5,6,0,0], | ||
| 223 | - [5,3,4,4,3,3,3,4,3,4,5,5,5,0,0,0], | ||
| 224 | - [4,4,4,3,3,3,3,3,4,5,4,5,0,0,0,0], | ||
| 225 | - [6,5,3,3,3,3,3,3,4,3,6,0,0,0,0,0], | ||
| 226 | - [6,5,3,3,3,2,3,4,3,6,0,0,0,0,0,0], | ||
| 227 | - [6,4,5,3,2,2,3,3,6,0,0,0,0,0,0,0], | ||
| 228 | - [6,6,4,2,2,3,2,5,0,0,0,0,0,0,0,0], | ||
| 229 | - [5,5,3,2,2,2,4,0,0,0,0,0,0,0,0,0], | ||
| 230 | - [4,4,3,3,1,3,0,0,0,0,0,0,0,0,0,0], | ||
| 231 | - [4,4,2,1,3,0,0,0,0,0,0,0,0,0,0,0], | ||
| 232 | - [3,3,1,2,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 233 | - [2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 234 | - [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 235 | -]; | ||
| 236 | -#[rustfmt::skip] | ||
| 237 | -const TOTAL_ZEROS_BITS: [[u8; 16]; 15] = [ | ||
| 238 | - [1,3,2,3,2,3,2,3,2,3,2,3,2,3,2,1], | ||
| 239 | - [7,6,5,4,3,5,4,3,2,3,2,3,2,1,0,0], | ||
| 240 | - [5,7,6,5,4,3,4,3,2,3,2,1,1,0,0,0], | ||
| 241 | - [3,7,5,4,6,5,4,3,3,2,2,1,0,0,0,0], | ||
| 242 | - [5,4,3,7,6,5,4,3,2,1,1,0,0,0,0,0], | ||
| 243 | - [1,1,7,6,5,4,3,2,1,1,0,0,0,0,0,0], | ||
| 244 | - [1,1,5,4,3,3,2,1,1,0,0,0,0,0,0,0], | ||
| 245 | - [1,1,1,3,3,2,2,1,0,0,0,0,0,0,0,0], | ||
| 246 | - [1,0,1,3,2,1,1,1,0,0,0,0,0,0,0,0], | ||
| 247 | - [1,0,1,3,2,1,1,0,0,0,0,0,0,0,0,0], | ||
| 248 | - [0,1,1,2,1,3,0,0,0,0,0,0,0,0,0,0], | ||
| 249 | - [0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0], | ||
| 250 | - [0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 251 | - [0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 252 | - [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 253 | -]; | ||
| 254 | - | ||
| 255 | -/// chroma DC total_zeros, indexed `[TotalCoeff-1][total_zeros]` (TotalCoeff 1..3). | ||
| 256 | -#[rustfmt::skip] | ||
| 257 | -const CHROMA_DC_TOTAL_ZEROS_LEN: [[u8; 4]; 3] = [ | ||
| 258 | - [1,2,3,3], | ||
| 259 | - [1,2,2,0], | ||
| 260 | - [1,1,0,0], | ||
| 261 | -]; | ||
| 262 | -#[rustfmt::skip] | ||
| 263 | -const CHROMA_DC_TOTAL_ZEROS_BITS: [[u8; 4]; 3] = [ | ||
| 264 | - [1,1,1,0], | ||
| 265 | - [1,1,0,0], | ||
| 266 | - [1,0,0,0], | ||
| 267 | -]; | ||
| 268 | - | ||
| 269 | -/// run_before, indexed `[min(zerosLeft,7)-1][run_before]`. | ||
| 270 | -#[rustfmt::skip] | ||
| 271 | -const RUN_LEN: [[u8; 15]; 7] = [ | ||
| 272 | - [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 273 | - [1,2,2,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 274 | - [2,2,2,2,0,0,0,0,0,0,0,0,0,0,0], | ||
| 275 | - [2,2,2,3,3,0,0,0,0,0,0,0,0,0,0], | ||
| 276 | - [2,2,3,3,3,3,0,0,0,0,0,0,0,0,0], | ||
| 277 | - [2,3,3,3,3,3,3,0,0,0,0,0,0,0,0], | ||
| 278 | - [3,3,3,3,3,3,3,4,5,6,7,8,9,10,11], | ||
| 279 | -]; | ||
| 280 | -#[rustfmt::skip] | ||
| 281 | -const RUN_BITS: [[u8; 15]; 7] = [ | ||
| 282 | - [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 283 | - [1,1,0,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 284 | - [3,2,1,0,0,0,0,0,0,0,0,0,0,0,0], | ||
| 285 | - [3,2,1,1,0,0,0,0,0,0,0,0,0,0,0], | ||
| 286 | - [3,2,3,2,1,0,0,0,0,0,0,0,0,0,0], | ||
| 287 | - [3,0,1,3,2,5,4,0,0,0,0,0,0,0,0], | ||
| 288 | - [7,6,5,4,3,2,1,1,1,1,1,1,1,1,1], | ||
| 289 | -]; | ||
| 290 | - | ||
| 291 | -/// Selects the coeff_token VLC table from the context `nc`. `nc == -1` is the | ||
| 292 | -/// chroma-DC table (handled separately by the caller). | ||
| 293 | -fn coeff_token_table(nc: i32) -> usize { | ||
| 294 | - if nc < 2 { | ||
| 295 | - 0 | ||
| 296 | - } else if nc < 4 { | ||
| 297 | - 1 | ||
| 298 | - } else if nc < 8 { | ||
| 299 | - 2 | ||
| 300 | - } else { | ||
| 301 | - 3 | ||
| 302 | - } | ||
| 303 | -} | ||
| 304 | - | ||
| 305 | -/// Writes a `(len, bits)` VLC codeword. | ||
| 306 | -fn put(w: &mut BitWriter, len: u8, bits: u8) { | ||
| 307 | - debug_assert!(len > 0, "writing an undefined VLC entry"); | ||
| 308 | - w.write_bits(bits as u32, len as u32); | ||
| 309 | -} | ||
| 310 | - | ||
| 311 | -/// Reads a VLC by matching accumulated bits against a length/bits table over | ||
| 312 | -/// the given candidate symbol indices. Returns the matched symbol index. | ||
| 313 | -/// A flat VLC lookup table. The H.264 VLC tables are prefix-free, so a single | ||
| 314 | -/// `peek_bits(width)` + index decodes any codeword in O(1) — replacing the old | ||
| 315 | -/// bit-at-a-time scan over every candidate. `entry[peeked]` packs | ||
| 316 | -/// `(symbol << 5) | length`; `length == 0` marks "no codeword" (corrupt input). | ||
| 317 | -struct Vlc { | ||
| 318 | - width: u32, | ||
| 319 | - entry: Vec<u16>, | ||
| 320 | -} | ||
| 321 | - | ||
| 322 | -impl Vlc { | ||
| 323 | - /// Builds the lookup from a `(len, code)` table. For each codeword of length | ||
| 324 | - /// `l` and value `v`, every `width`-bit peek whose top `l` bits equal `v` | ||
| 325 | - /// (the contiguous range `[v<<(width-l), (v+1)<<(width-l))`) maps to it. Codes | ||
| 326 | - /// are prefix-free, so the ranges never overlap. | ||
| 327 | - fn build(lens: &[u8], bits: &[u8]) -> Vlc { | ||
| 328 | - let width = lens.iter().copied().max().unwrap_or(0) as u32; | ||
| 329 | - let mut entry = vec![0u16; 1usize << width]; | ||
| 330 | - for (i, (&l, &v)) in lens.iter().zip(bits.iter()).enumerate() { | ||
| 331 | - if l == 0 { | ||
| 332 | - continue; | ||
| 333 | - } | ||
| 334 | - let base = (v as usize) << (width - l as u32); | ||
| 335 | - let span = 1usize << (width - l as u32); | ||
| 336 | - let packed = ((i as u16) << 5) | l as u16; | ||
| 337 | - for e in &mut entry[base..base + span] { | ||
| 338 | - *e = packed; | ||
| 339 | - } | ||
| 340 | - } | ||
| 341 | - Vlc { width, entry } | ||
| 342 | - } | ||
| 343 | - | ||
| 344 | - #[inline] | ||
| 345 | - fn read(&self, r: &mut BitReader) -> Result<usize, OutOfData> { | ||
| 346 | - let packed = self.entry[r.peek_bits(self.width) as usize]; | ||
| 347 | - let len = (packed & 0x1F) as u32; | ||
| 348 | - if len == 0 { | ||
| 349 | - return Err(OutOfData); // peeked bits matched no codeword → corrupt | ||
| 350 | - } | ||
| 351 | - r.skip_bits(len)?; | ||
| 352 | - Ok((packed >> 5) as usize) | ||
| 353 | - } | ||
| 354 | -} | ||
| 355 | - | ||
| 356 | -/// The CAVLC VLC lookup tables, built once on first decode (≈240 KB). | ||
| 357 | -struct VlcTables { | ||
| 358 | - coeff_token: [Vlc; 4], | ||
| 359 | - chroma_dc_coeff_token: Vlc, | ||
| 360 | - total_zeros: [Vlc; 15], | ||
| 361 | - chroma_dc_total_zeros: [Vlc; 3], | ||
| 362 | - run_before: [Vlc; 7], | ||
| 363 | -} | ||
| 364 | - | ||
| 365 | -fn vlc_tables() -> &'static VlcTables { | ||
| 366 | - use std::sync::OnceLock; | ||
| 367 | - static T: OnceLock<VlcTables> = OnceLock::new(); | ||
| 368 | - T.get_or_init(|| VlcTables { | ||
| 369 | - coeff_token: std::array::from_fn(|t| Vlc::build(&COEFF_TOKEN_LEN[t], &COEFF_TOKEN_BITS[t])), | ||
| 370 | - chroma_dc_coeff_token: Vlc::build(&CHROMA_DC_COEFF_TOKEN_LEN, &CHROMA_DC_COEFF_TOKEN_BITS), | ||
| 371 | - total_zeros: std::array::from_fn(|t| Vlc::build(&TOTAL_ZEROS_LEN[t], &TOTAL_ZEROS_BITS[t])), | ||
| 372 | - chroma_dc_total_zeros: std::array::from_fn(|t| { | ||
| 373 | - Vlc::build(&CHROMA_DC_TOTAL_ZEROS_LEN[t], &CHROMA_DC_TOTAL_ZEROS_BITS[t]) | ||
| 374 | - }), | ||
| 375 | - run_before: std::array::from_fn(|t| Vlc::build(&RUN_LEN[t], &RUN_BITS[t])), | ||
| 376 | - }) | ||
| 377 | -} | ||
| 378 | - | ||
| 379 | -/// Maps a signed level to its base `levelCode` (before the first-level offset). | ||
| 380 | -fn level_to_code(level: i32) -> i32 { | ||
| 381 | - if level > 0 { | ||
| 382 | - (level << 1) - 2 | ||
| 383 | - } else { | ||
| 384 | - (-level << 1) - 1 | ||
| 385 | - } | ||
| 386 | -} | ||
| 387 | - | ||
| 388 | -/// Writes one `level_prefix`/`level_suffix` for `code` at the given suffix | ||
| 389 | -/// length, the exact inverse of [`decode_residual_block`]'s level parsing. | ||
| 390 | -/// | ||
| 391 | -/// For small codes the prefix is the unary part and the suffix is `suffix_length` | ||
| 392 | -/// bits. Above that, `level_prefix` escapes to 15 with a 12-bit suffix; and for | ||
| 393 | -/// codes too large for 12 bits, to the **extended escape** (`level_prefix ≥ 16`, | ||
| 394 | -/// suffix `level_prefix − 3` bits), without which large levels — common at very | ||
| 395 | -/// low QP — would silently truncate. | ||
| 396 | -fn write_level(w: &mut BitWriter, code: i32, suffix_length: u32) { | ||
| 397 | - let code = code as u32; | ||
| 398 | - // Short forms with prefix < 15 — prefix+suffix PACKED into one write (the | ||
| 399 | - // value `(1<<suffixsize)|suffix` in `prefix+1+suffixsize` bits, leading zeros | ||
| 400 | - // implicit). Mirrors openh264's single `CAVLC_BS_WRITE` per level. | ||
| 401 | - if suffix_length == 0 { | ||
| 402 | - if code < 14 { | ||
| 403 | - w.write_bits(1, code + 1); | ||
| 404 | - return; | ||
| 405 | - } else if code < 30 { | ||
| 406 | - w.write_bits((1u32 << 4) | (code - 14), 14 + 1 + 4); | ||
| 407 | - return; | ||
| 408 | - } | ||
| 409 | - } else { | ||
| 410 | - let prefix = code >> suffix_length; | ||
| 411 | - if prefix < 15 { | ||
| 412 | - let suffix = code & ((1 << suffix_length) - 1); | ||
| 413 | - w.write_bits((1u32 << suffix_length) | suffix, prefix + 1 + suffix_length); | ||
| 414 | - return; | ||
| 415 | - } | ||
| 416 | - } | ||
| 417 | - // Prefix ≥ 15. `rem` is the value beyond the prefix-15 base; the decoder's | ||
| 418 | - // `+15` for the suffix_length-0 case makes both bases (30 and 15<<sl) align. | ||
| 419 | - let base = if suffix_length == 0 { 30 } else { 15u32 << suffix_length }; | ||
| 420 | - let rem = code - base; | ||
| 421 | - if rem < 4096 { | ||
| 422 | - put_zeros_one(w, 15); | ||
| 423 | - w.write_bits(rem, 12); | ||
| 424 | - return; | ||
| 425 | - } | ||
| 426 | - // Extended escape: grow the prefix until the suffix fits. For prefix `p`, | ||
| 427 | - // the suffix is `p − 3` bits and encodes `rem − (2^(p−3) − 4096)`. | ||
| 428 | - let mut p = 16u32; | ||
| 429 | - while rem > (1u32 << (p - 2)) - 4097 { | ||
| 430 | - p += 1; | ||
| 431 | - } | ||
| 432 | - put_zeros_one(w, p); | ||
| 433 | - w.write_bits(rem - ((1 << (p - 3)) - 4096), p - 3); | ||
| 434 | -} | ||
| 435 | - | ||
| 436 | -/// Writes `n` zero bits followed by a `1` (the unary `level_prefix`). | ||
| 437 | -fn put_zeros_one(w: &mut BitWriter, n: u32) { | ||
| 438 | - // `n` zero bits then a `1` is just the value `1` written in `n + 1` bits — one | ||
| 439 | - // write, not `n + 1`. (The level-prefix unary code, emitted for every coeff.) | ||
| 440 | - if n < 32 { | ||
| 441 | - w.write_bits(1, n + 1); | ||
| 442 | - } else { | ||
| 443 | - w.write_bits(0, n - 31); | ||
| 444 | - w.write_bits(1, 32); | ||
| 445 | - } | ||
| 446 | -} | ||
| 447 | - | ||
| 448 | -/// Reads a `level_prefix` (count of leading zeros before a `1`). | ||
| 449 | -fn read_level_prefix(r: &mut BitReader) -> Result<u32, OutOfData> { | ||
| 450 | - // Unary prefix = leading zeros before a 1. Count them in the peek window in | ||
| 451 | - // one CLZ when the codeword (lz+1 bits) fits the 24-bit window. | ||
| 452 | - let window = r.peek_bits(24); | ||
| 453 | - let lz = window.leading_zeros() - 8; | ||
| 454 | - if lz < 24 { | ||
| 455 | - r.skip_bits(lz + 1)?; | ||
| 456 | - return Ok(lz); | ||
| 457 | - } | ||
| 458 | - let mut n = 0; | ||
| 459 | - while !r.read_bit()? { | ||
| 460 | - n += 1; | ||
| 461 | - // A conformant 4×4 coefficient never needs a prefix this long; beyond | ||
| 462 | - // this the level computation (`1 << (prefix-3)`) would overflow, so a | ||
| 463 | - // longer run means corrupt input. | ||
| 464 | - if n > 32 { | ||
| 465 | - return Err(OutOfData); | ||
| 466 | - } | ||
| 467 | - } | ||
| 468 | - Ok(n) | ||
| 469 | -} | ||
| 470 | - | ||
| 471 | -/// Encodes a 4×4 residual block (`coeffs` in zig-zag scan order) as CAVLC and | ||
| 472 | -/// returns `total_coeff` (the non-zero count), which callers reuse as the block's | ||
| 473 | -/// `nnz` — saving a separate counting pass. | ||
| 474 | -/// | ||
| 475 | -/// - `max_coeff`: 16 (full), 15 (AC), or 4 (chroma DC). | ||
| 476 | -/// - `nc`: neighbor context; pass `-1` for chroma DC. | ||
| 477 | -pub fn encode_residual_block(w: &mut BitWriter, coeffs: &[i32], max_coeff: usize, nc: i32) -> usize { | ||
| 478 | - // MEASUREMENT: scope disabled — at 600k+/200k+ calls its own rdtsc pair | ||
| 479 | - // was >50% of the bucket and inflated every enclosing stage. | ||
| 480 | - // let _g = crate::prof::scope(crate::prof::Stage::EncWrite); | ||
| 481 | - debug_assert!(coeffs.len() >= max_coeff); | ||
| 482 | - debug_assert!(max_coeff <= 16); | ||
| 483 | - let chroma_dc = nc == -1; | ||
| 484 | - | ||
| 485 | - // openh264 `CavlcParamCal`: ONE descending pass yields levels[] (high→low), | ||
| 486 | - // run[] (high→low), total_coeff, and total_zeros at once — no positions array, | ||
| 487 | - // no second/third pass. Bit-identical to the per-position derivation. Runs for | ||
| 488 | - // every coded 4×4 block, so the saved passes matter. | ||
| 489 | - let mut levels = [0i32; 16]; | ||
| 490 | - let mut run_val = [0usize; 16]; | ||
| 491 | - let mut total_coeff = 0usize; | ||
| 492 | - let mut total_zeros = 0usize; | ||
| 493 | - let mut idx = max_coeff as isize - 1; | ||
| 494 | - while idx >= 0 && coeffs[idx as usize] == 0 { | ||
| 495 | - idx -= 1; | ||
| 496 | - } | ||
| 497 | - while idx >= 0 { | ||
| 498 | - levels[total_coeff] = coeffs[idx as usize]; | ||
| 499 | - idx -= 1; | ||
| 500 | - let mut count_zero = 0usize; | ||
| 501 | - while idx >= 0 && coeffs[idx as usize] == 0 { | ||
| 502 | - count_zero += 1; | ||
| 503 | - idx -= 1; | ||
| 504 | - } | ||
| 505 | - total_zeros += count_zero; | ||
| 506 | - run_val[total_coeff] = count_zero; | ||
| 507 | - total_coeff += 1; | ||
| 508 | - } | ||
| 509 | - let levels_hi_lo = &levels[..total_coeff]; | ||
| 510 | - | ||
| 511 | - // Trailing ones: leading ±1 entries of the high→low list, capped at 3. | ||
| 512 | - let mut trailing_ones = 0usize; | ||
| 513 | - for &lv in levels_hi_lo { | ||
| 514 | - if lv.abs() == 1 && trailing_ones < 3 { | ||
| 515 | - trailing_ones += 1; | ||
| 516 | - } else { | ||
| 517 | - break; | ||
| 518 | - } | ||
| 519 | - } | ||
| 520 | - | ||
| 521 | - // --- coeff_token + trailing-one signs, PACKED into one write (openh264: | ||
| 522 | - // `n += iTrailingOnes; iValue = (iValue << iTrailingOnes) + uiSign`) --- | ||
| 523 | - let tok_idx = total_coeff * 4 + trailing_ones; | ||
| 524 | - let (ct_len, ct_bits) = if chroma_dc { | ||
| 525 | - (CHROMA_DC_COEFF_TOKEN_LEN[tok_idx], CHROMA_DC_COEFF_TOKEN_BITS[tok_idx]) | ||
| 526 | - } else { | ||
| 527 | - let t = coeff_token_table(nc); | ||
| 528 | - (COEFF_TOKEN_LEN[t][tok_idx], COEFF_TOKEN_BITS[t][tok_idx]) | ||
| 529 | - }; | ||
| 530 | - if total_coeff == 0 { | ||
| 531 | - put(w, ct_len, ct_bits); | ||
| 532 | - return 0; | ||
| 533 | - } | ||
| 534 | - // sign bits for the trailing ones (high→low): 1 = negative. | ||
| 535 | - let mut sign = 0u32; | ||
| 536 | - for &lv in levels_hi_lo.iter().take(trailing_ones) { | ||
| 537 | - sign = (sign << 1) | (lv < 0) as u32; | ||
| 538 | - } | ||
| 539 | - w.write_bits( | ||
| 540 | - ((ct_bits as u32) << trailing_ones) | sign, | ||
| 541 | - ct_len as u32 + trailing_ones as u32, | ||
| 542 | - ); | ||
| 543 | - | ||
| 544 | - // --- remaining levels (high→low) --- | ||
| 545 | - let mut suffix_length = if total_coeff > 10 && trailing_ones < 3 { 1 } else { 0 }; | ||
| 546 | - for (k, &lv) in levels_hi_lo.iter().enumerate().skip(trailing_ones) { | ||
| 547 | - let mut code = level_to_code(lv); | ||
| 548 | - if k == trailing_ones && trailing_ones < 3 { | ||
| 549 | - code -= 2; | ||
| 550 | - } | ||
| 551 | - write_level(w, code, suffix_length); | ||
| 552 | - if suffix_length == 0 { | ||
| 553 | - suffix_length = 1; | ||
| 554 | - } | ||
| 555 | - if lv.abs() > (3 << (suffix_length - 1)) && suffix_length < 6 { | ||
| 556 | - suffix_length += 1; | ||
| 557 | - } | ||
| 558 | - } | ||
| 559 | - | ||
| 560 | - // --- total_zeros (computed in the single pass above) --- | ||
| 561 | - if total_coeff < max_coeff { | ||
| 562 | - if chroma_dc { | ||
| 563 | - let row = &CHROMA_DC_TOTAL_ZEROS_LEN[total_coeff - 1]; | ||
| 564 | - let brow = &CHROMA_DC_TOTAL_ZEROS_BITS[total_coeff - 1]; | ||
| 565 | - put(w, row[total_zeros], brow[total_zeros]); | ||
| 566 | - } else { | ||
| 567 | - put( | ||
| 568 | - w, | ||
| 569 | - TOTAL_ZEROS_LEN[total_coeff - 1][total_zeros], | ||
| 570 | - TOTAL_ZEROS_BITS[total_coeff - 1][total_zeros], | ||
| 571 | - ); | ||
| 572 | - } | ||
| 573 | - } | ||
| 574 | - | ||
| 575 | - // --- run_before (high→low), skipping once no zeros remain --- | ||
| 576 | - // run_val[] (high→low) came from the single pass above. | ||
| 577 | - let mut zeros_left = total_zeros; | ||
| 578 | - for &run in run_val[..total_coeff].iter().take(total_coeff - 1) { | ||
| 579 | - if zeros_left == 0 { | ||
| 580 | - break; | ||
| 581 | - } | ||
| 582 | - let t = zeros_left.min(7) - 1; | ||
| 583 | - put(w, RUN_LEN[t][run], RUN_BITS[t][run]); | ||
| 584 | - zeros_left -= run; | ||
| 585 | - } | ||
| 586 | - total_coeff | ||
| 587 | -} | ||
| 588 | - | ||
| 589 | -/// Decodes a CAVLC residual block into zig-zag-ordered coefficients. The first | ||
| 590 | -/// `max_coeff` entries of the returned fixed array are valid (the rest stay zero); | ||
| 591 | -/// returning `[i32; 16]` avoids a per-block heap allocation in the decode loop. | ||
| 592 | -pub fn decode_residual_block( | ||
| 593 | - r: &mut BitReader, | ||
| 594 | - max_coeff: usize, | ||
| 595 | - nc: i32, | ||
| 596 | -) -> Result<[i32; 16], OutOfData> { | ||
| 597 | - let _g = crate::prof::scope(crate::prof::Stage::Entropy); | ||
| 598 | - let chroma_dc = nc == -1; | ||
| 599 | - let mut out = [0i32; 16]; | ||
| 600 | - | ||
| 601 | - // --- coeff_token --- | ||
| 602 | - let tabs = vlc_tables(); | ||
| 603 | - let _tg = crate::prof::scope(crate::prof::Stage::CavTok); | ||
| 604 | - let (total_coeff, trailing_ones) = if chroma_dc { | ||
| 605 | - let idx = tabs.chroma_dc_coeff_token.read(r)?; | ||
| 606 | - (idx / 4, idx % 4) | ||
| 607 | - } else { | ||
| 608 | - let idx = tabs.coeff_token[coeff_token_table(nc)].read(r)?; | ||
| 609 | - (idx / 4, idx % 4) | ||
| 610 | - }; | ||
| 611 | - if total_coeff == 0 { | ||
| 612 | - return Ok(out); | ||
| 613 | - } | ||
| 614 | - // A block cannot hold more coefficients than it has positions. A corrupt | ||
| 615 | - // coeff_token that claims otherwise would index the total_zeros tables and | ||
| 616 | - // the output array out of bounds — reject it. | ||
| 617 | - if total_coeff > max_coeff { | ||
| 618 | - return Err(OutOfData); | ||
| 619 | - } | ||
| 620 | - | ||
| 621 | - // --- trailing-one signs + remaining levels, high→low (stack, no alloc) --- | ||
| 622 | - drop(_tg); | ||
| 623 | - let _lg = crate::prof::scope(crate::prof::Stage::CavLvl); | ||
| 624 | - let mut levels_hi_lo = [0i32; 16]; | ||
| 625 | - for level in levels_hi_lo.iter_mut().take(trailing_ones) { | ||
| 626 | - *level = if r.read_bit()? { -1 } else { 1 }; | ||
| 627 | - } | ||
| 628 | - let mut suffix_length = if total_coeff > 10 && trailing_ones < 3 { 1 } else { 0 }; | ||
| 629 | - // `k` indexes the level array and gates the first-non-T1-level offset. | ||
| 630 | - #[allow(clippy::needless_range_loop)] | ||
| 631 | - for k in trailing_ones..total_coeff { | ||
| 632 | - let level_prefix = read_level_prefix(r)?; | ||
| 633 | - let level_suffix_size = if level_prefix == 14 && suffix_length == 0 { | ||
| 634 | - 4 | ||
| 635 | - } else if level_prefix >= 15 { | ||
| 636 | - level_prefix - 3 | ||
| 637 | - } else { | ||
| 638 | - suffix_length | ||
| 639 | - }; | ||
| 640 | - let level_suffix = if level_suffix_size > 0 { | ||
| 641 | - r.read_bits(level_suffix_size)? | ||
| 642 | - } else { | ||
| 643 | - 0 | ||
| 644 | - }; | ||
| 645 | - let mut level_code = (level_prefix.min(15) << suffix_length) as i32 + level_suffix as i32; | ||
| 646 | - if level_prefix >= 15 && suffix_length == 0 { | ||
| 647 | - level_code += 15; | ||
| 648 | - } | ||
| 649 | - if level_prefix >= 16 { | ||
| 650 | - level_code += (1 << (level_prefix - 3)) - 4096; | ||
| 651 | - } | ||
| 652 | - if k == trailing_ones && trailing_ones < 3 { | ||
| 653 | - level_code += 2; | ||
| 654 | - } | ||
| 655 | - let level = if level_code % 2 == 0 { | ||
| 656 | - (level_code + 2) >> 1 | ||
| 657 | - } else { | ||
| 658 | - (-level_code - 1) >> 1 | ||
| 659 | - }; | ||
| 660 | - // Residual coefficients are 16-bit (spec §8.5; ffmpeg stores int16). A | ||
| 661 | - // value outside that range is non-conformant and would overflow the | ||
| 662 | - // dequant/inverse-transform multiplies — reject the block. | ||
| 663 | - if !(-32768..=32767).contains(&level) { | ||
| 664 | - return Err(OutOfData); | ||
| 665 | - } | ||
| 666 | - levels_hi_lo[k] = level; | ||
| 667 | - if suffix_length == 0 { | ||
| 668 | - suffix_length = 1; | ||
| 669 | - } | ||
| 670 | - if level.abs() > (3 << (suffix_length - 1)) && suffix_length < 6 { | ||
| 671 | - suffix_length += 1; | ||
| 672 | - } | ||
| 673 | - } | ||
| 674 | - | ||
| 675 | - // --- total_zeros --- | ||
| 676 | - drop(_lg); | ||
| 677 | - let _rg = crate::prof::scope(crate::prof::Stage::CavRun); | ||
| 678 | - let total_zeros = if total_coeff < max_coeff { | ||
| 679 | - if chroma_dc { | ||
| 680 | - tabs.chroma_dc_total_zeros[total_coeff - 1].read(r)? | ||
| 681 | - } else { | ||
| 682 | - tabs.total_zeros[total_coeff - 1].read(r)? | ||
| 683 | - } | ||
| 684 | - } else { | ||
| 685 | - 0 | ||
| 686 | - }; | ||
| 687 | - | ||
| 688 | - // --- run_before (stack, no alloc) --- | ||
| 689 | - let mut run_val = [0usize; 16]; | ||
| 690 | - let mut zeros_left = total_zeros; | ||
| 691 | - for run in run_val.iter_mut().take(total_coeff - 1) { | ||
| 692 | - if zeros_left == 0 { | ||
| 693 | - break; | ||
| 694 | - } | ||
| 695 | - let t = zeros_left.min(7) - 1; | ||
| 696 | - let val = tabs.run_before[t].read(r)?; | ||
| 697 | - *run = val; | ||
| 698 | - // A corrupt run_before may exceed the zeros remaining; reject rather | ||
| 699 | - // than underflow. | ||
| 700 | - zeros_left = zeros_left.checked_sub(val).ok_or(OutOfData)?; | ||
| 701 | - } | ||
| 702 | - if total_coeff >= 1 { | ||
| 703 | - run_val[total_coeff - 1] = zeros_left; | ||
| 704 | - } | ||
| 705 | - | ||
| 706 | - // --- reconstruct scan-order coefficients --- | ||
| 707 | - let mut coeff_num: isize = -1; | ||
| 708 | - for i in (0..total_coeff).rev() { | ||
| 709 | - coeff_num += run_val[i] as isize + 1; | ||
| 710 | - // Defensive: with the guards above this stays in 0..max_coeff, but never | ||
| 711 | - // let an attacker-shaped run drive an out-of-bounds write. | ||
| 712 | - let pos = coeff_num as usize; | ||
| 713 | - if pos >= out.len() { | ||
| 714 | - return Err(OutOfData); | ||
| 715 | - } | ||
| 716 | - out[pos] = levels_hi_lo[i]; | ||
| 717 | - } | ||
| 718 | - Ok(out) | ||
| 719 | -} | ||
| 720 | - | ||
| 721 | -#[cfg(test)] | ||
| 722 | -mod tests { | ||
| 723 | - use super::*; | ||
| 724 | - | ||
| 725 | - fn roundtrip(block: &[i32], max_coeff: usize, nc: i32) { | ||
| 726 | - let mut w = BitWriter::new(); | ||
| 727 | - encode_residual_block(&mut w, block, max_coeff, nc); | ||
| 728 | - w.align_zero(); | ||
| 729 | - let bytes = w.into_bytes(); | ||
| 730 | - let mut r = BitReader::new(&bytes); | ||
| 731 | - let decoded = decode_residual_block(&mut r, max_coeff, nc).expect("decode"); | ||
| 732 | - assert_eq!(&decoded[..max_coeff], &block[..max_coeff], "nc={nc} max={max_coeff}"); | ||
| 733 | - } | ||
| 734 | - | ||
| 735 | - #[test] | ||
| 736 | - fn all_zero_block() { | ||
| 737 | - roundtrip(&[0; 16], 16, 0); | ||
| 738 | - roundtrip(&[0; 16], 15, 0); | ||
| 739 | - roundtrip(&[0; 4], 4, -1); | ||
| 740 | - } | ||
| 741 | - | ||
| 742 | - #[test] | ||
| 743 | - fn single_dc() { | ||
| 744 | - let mut b = [0i32; 16]; | ||
| 745 | - b[0] = 5; | ||
| 746 | - roundtrip(&b, 16, 0); | ||
| 747 | - b[0] = -3; | ||
| 748 | - roundtrip(&b, 16, 0); | ||
| 749 | - } | ||
| 750 | - | ||
| 751 | - #[test] | ||
| 752 | - fn trailing_ones_and_levels() { | ||
| 753 | - // DC=3, then some zeros, then ±1 trailing ones at higher frequency. | ||
| 754 | - let b = [3, 0, 1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; | ||
| 755 | - roundtrip(&b, 16, 0); | ||
| 756 | - } | ||
| 757 | - | ||
| 758 | - #[test] | ||
| 759 | - fn many_coeffs_all_contexts() { | ||
| 760 | - let b = [1, -2, 3, -1, 1, 1, -1, 2, -3, 1, -1, 1, 1, -1, 1, -1]; | ||
| 761 | - for nc in [0, 2, 4, 8, 20] { | ||
| 762 | - roundtrip(&b, 16, nc); | ||
| 763 | - } | ||
| 764 | - } | ||
| 765 | - | ||
| 766 | - #[test] | ||
| 767 | - fn chroma_dc_blocks() { | ||
| 768 | - roundtrip(&[2, -1, 0, 1], 4, -1); | ||
| 769 | - roundtrip(&[0, 0, 0, -1], 4, -1); | ||
| 770 | - roundtrip(&[1, 1, 1, 1], 4, -1); | ||
| 771 | - } | ||
| 772 | - | ||
| 773 | - #[test] | ||
| 774 | - fn large_levels_use_escape() { | ||
| 775 | - let b = [200, -150, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; | ||
| 776 | - roundtrip(&b, 16, 0); | ||
| 777 | - } | ||
| 778 | - | ||
| 779 | - #[test] | ||
| 780 | - fn extreme_levels_use_extended_escape() { | ||
| 781 | - // Levels far beyond the 12-bit suffix range force level_prefix ≥ 16; | ||
| 782 | - // these occur at very low QP and previously truncated. Cover both | ||
| 783 | - // suffix_length==0 (single big DC) and grown-suffix_length (a run of | ||
| 784 | - // large levels) paths, and signs. | ||
| 785 | - roundtrip(&[5000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0); | ||
| 786 | - roundtrip(&[-7000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0); | ||
| 787 | - roundtrip(&[30000, -25000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 16, 0); | ||
| 788 | - let big = [9000, -9000, 8000, -8000, 7000, -7000, 6000, -6000, 5000, -5000, 4500, | ||
| 789 | - -4500, 4200, -4200, 4096, -4096]; | ||
| 790 | - roundtrip(&big, 16, 0); | ||
| 791 | - // chroma DC and AC blocks with extreme levels too | ||
| 792 | - roundtrip(&[6000, -6000, 5000, -5000], 4, -1); | ||
| 793 | - } | ||
| 794 | - | ||
| 795 | - #[test] | ||
| 796 | - fn pseudo_random_blocks() { | ||
| 797 | - // Deterministic LCG; exercise many shapes across contexts and sizes. | ||
| 798 | - let mut state = 0x1234_5678u32; | ||
| 799 | - let mut next = || { | ||
| 800 | - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 801 | - state | ||
| 802 | - }; | ||
| 803 | - for _ in 0..2000 { | ||
| 804 | - let mut b = [0i32; 16]; | ||
| 805 | - let density = (next() % 16) as usize; | ||
| 806 | - for slot in b.iter_mut().take(density) { | ||
| 807 | - // small signed values, biased toward ±1 | ||
| 808 | - let v = (next() % 7) as i32 - 3; | ||
| 809 | - *slot = v; | ||
| 810 | - } | ||
| 811 | - // shuffle into scan positions | ||
| 812 | - for i in (1..16).rev() { | ||
| 813 | - let j = (next() as usize) % (i + 1); | ||
| 814 | - b.swap(i, j); | ||
| 815 | - } | ||
| 816 | - let max_coeff = if next() % 3 == 0 { 15 } else { 16 }; | ||
| 817 | - let nc = [0i32, 2, 4, 8][(next() % 4) as usize]; | ||
| 818 | - roundtrip(&b, max_coeff, nc); | ||
| 819 | - } | ||
| 820 | - } | ||
| 821 | -} | ||
vendor/rusty_h264-common/src/deblock.rsdeleted+0 -2884
Diff too large; view file
| @@ -1,2884 +0,0 @@ | |||
| 1 | -//! In-loop deblocking filter (spec §8.7), all-intra case. | ||
| 2 | -//! | ||
| 3 | -//! Smooths block-edge discontinuities on the reconstructed frame. Because intra | ||
| 4 | -//! prediction uses *pre*-deblocking samples, this runs as a post-pass over the | ||
| 5 | -//! fully-reconstructed frame: macroblocks in raster order, vertical edges then | ||
| 6 | -//! horizontal, filtered in place. For an all-intra picture the boundary | ||
| 7 | -//! strength is positional — 4 on macroblock edges, 3 on internal 4×4 edges. | ||
| 8 | - | ||
| 9 | -/// `α` threshold indexed by `indexA` (= clipped QP), spec Table 8-16. | ||
| 10 | -#[rustfmt::skip] | ||
| 11 | -const ALPHA: [i32; 52] = [ | ||
| 12 | - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, | ||
| 13 | - 4,4,5,6,7,8,9,10,12,13,15,17,20,22,25,28, | ||
| 14 | - 32,36,40,45,50,56,63,71,80,90,101,113,127,144,162,182,203,226,255,255, | ||
| 15 | -]; | ||
| 16 | - | ||
| 17 | -/// `β` threshold indexed by `indexB`. | ||
| 18 | -#[rustfmt::skip] | ||
| 19 | -const BETA: [i32; 52] = [ | ||
| 20 | - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, | ||
| 21 | - 2,2,2,3,3,3,3,4,4,4,6,6,7,7,8,8, | ||
| 22 | - 9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18, | ||
| 23 | -]; | ||
| 24 | - | ||
| 25 | -/// `tc0` indexed by `[indexA][bS-1]` for bS ∈ {1,2,3}. | ||
| 26 | -#[rustfmt::skip] | ||
| 27 | -const TC0: [[i32; 3]; 52] = [ | ||
| 28 | - [0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0], | ||
| 29 | - [0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0], | ||
| 30 | - [0,0,0],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,1,1],[0,1,1],[1,1,1], | ||
| 31 | - [1,1,1],[1,1,1],[1,1,1],[1,1,2],[1,1,2],[1,1,2],[1,1,2],[1,2,3], | ||
| 32 | - [1,2,3],[2,2,3],[2,2,4],[2,3,4],[2,3,4],[3,3,5],[3,4,6],[3,4,6], | ||
| 33 | - [4,5,7],[4,5,8],[4,6,9],[5,7,10],[6,8,11],[6,8,13],[7,10,14],[8,11,16], | ||
| 34 | - [9,12,18],[10,13,20],[11,15,23],[13,17,25], | ||
| 35 | -]; | ||
| 36 | - | ||
| 37 | -#[inline] | ||
| 38 | -fn clip1(v: i32) -> u8 { | ||
| 39 | - v.clamp(0, 255) as u8 | ||
| 40 | -} | ||
| 41 | - | ||
| 42 | -#[inline] | ||
| 43 | -fn clip3(lo: i32, hi: i32, v: i32) -> i32 { | ||
| 44 | - v.clamp(lo, hi) | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -/// One sample line crossing an edge: `p3..p0 | q0..q3` (indices 0..3 from the | ||
| 48 | -/// edge outward). Reads/writes a plane along `stride`-spaced positions. | ||
| 49 | -struct Line { | ||
| 50 | - /// Byte offset of q0 (the first sample on the "right"/"below" side). | ||
| 51 | - base: usize, | ||
| 52 | - /// Step between adjacent samples across the edge (1 horizontally, `stride` | ||
| 53 | - /// vertically). | ||
| 54 | - step: isize, | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -/// Filters luma samples across one edge line. `bs` is 3 (internal) or 4 (MB edge). | ||
| 58 | -#[allow(clippy::too_many_arguments)] | ||
| 59 | -fn filter_luma_line(plane: &mut [u8], line: &Line, bs: i32, alpha: i32, beta: i32, tc0: i32) { | ||
| 60 | - let at = |i: isize| -> i32 { | ||
| 61 | - plane[(line.base as isize + i * line.step) as usize] as i32 | ||
| 62 | - }; | ||
| 63 | - let (p0, p1, p2, p3) = (at(-1), at(-2), at(-3), at(-4)); | ||
| 64 | - let (q0, q1, q2, q3) = (at(0), at(1), at(2), at(3)); | ||
| 65 | - | ||
| 66 | - if (p0 - q0).abs() >= alpha || (p1 - p0).abs() >= beta || (q1 - q0).abs() >= beta { | ||
| 67 | - return; | ||
| 68 | - } | ||
| 69 | - let set = |plane: &mut [u8], i: isize, v: u8| { | ||
| 70 | - plane[(line.base as isize + i * line.step) as usize] = v; | ||
| 71 | - }; | ||
| 72 | - let ap = (p2 - p0).abs(); | ||
| 73 | - let aq = (q2 - q0).abs(); | ||
| 74 | - | ||
| 75 | - if bs < 4 { | ||
| 76 | - let tc = tc0 + (ap < beta) as i32 + (aq < beta) as i32; | ||
| 77 | - let delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3); | ||
| 78 | - set(plane, -1, clip1(p0 + delta)); | ||
| 79 | - set(plane, 0, clip1(q0 - delta)); | ||
| 80 | - if ap < beta { | ||
| 81 | - let d = clip3(-tc0, tc0, (p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1); | ||
| 82 | - set(plane, -2, clip1(p1 + d)); | ||
| 83 | - } | ||
| 84 | - if aq < beta { | ||
| 85 | - let d = clip3(-tc0, tc0, (q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1); | ||
| 86 | - set(plane, 1, clip1(q1 + d)); | ||
| 87 | - } | ||
| 88 | - } else { | ||
| 89 | - let strong = (p0 - q0).abs() < (alpha >> 2) + 2; | ||
| 90 | - if strong && ap < beta { | ||
| 91 | - set(plane, -1, clip1((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3)); | ||
| 92 | - set(plane, -2, clip1((p2 + p1 + p0 + q0 + 2) >> 2)); | ||
| 93 | - set(plane, -3, clip1((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3)); | ||
| 94 | - } else { | ||
| 95 | - set(plane, -1, clip1((2 * p1 + p0 + q1 + 2) >> 2)); | ||
| 96 | - } | ||
| 97 | - if strong && aq < beta { | ||
| 98 | - set(plane, 0, clip1((q2 + 2 * q1 + 2 * q0 + 2 * p0 + p1 + 4) >> 3)); | ||
| 99 | - set(plane, 1, clip1((q2 + q1 + q0 + p0 + 2) >> 2)); | ||
| 100 | - set(plane, 2, clip1((2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) >> 3)); | ||
| 101 | - } else { | ||
| 102 | - set(plane, 0, clip1((2 * q1 + q0 + p1 + 2) >> 2)); | ||
| 103 | - } | ||
| 104 | - } | ||
| 105 | -} | ||
| 106 | - | ||
| 107 | -/// Filters chroma samples across one edge line (only p0/q0 are modified). | ||
| 108 | -fn filter_chroma_line(plane: &mut [u8], line: &Line, bs: i32, alpha: i32, beta: i32, tc0: i32) { | ||
| 109 | - let at = |i: isize| -> i32 { | ||
| 110 | - plane[(line.base as isize + i * line.step) as usize] as i32 | ||
| 111 | - }; | ||
| 112 | - let (p0, p1) = (at(-1), at(-2)); | ||
| 113 | - let (q0, q1) = (at(0), at(1)); | ||
| 114 | - if (p0 - q0).abs() >= alpha || (p1 - p0).abs() >= beta || (q1 - q0).abs() >= beta { | ||
| 115 | - return; | ||
| 116 | - } | ||
| 117 | - let set = |plane: &mut [u8], i: isize, v: u8| { | ||
| 118 | - plane[(line.base as isize + i * line.step) as usize] = v; | ||
| 119 | - }; | ||
| 120 | - if bs < 4 { | ||
| 121 | - let tc = tc0 + 1; | ||
| 122 | - let delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3); | ||
| 123 | - set(plane, -1, clip1(p0 + delta)); | ||
| 124 | - set(plane, 0, clip1(q0 - delta)); | ||
| 125 | - } else { | ||
| 126 | - set(plane, -1, clip1((2 * p1 + p0 + q1 + 2) >> 2)); | ||
| 127 | - set(plane, 0, clip1((2 * q1 + q0 + p1 + 2) >> 2)); | ||
| 128 | - } | ||
| 129 | -} | ||
| 130 | - | ||
| 131 | -/// Per-4×4-block macroblock info driving boundary-strength derivation. | ||
| 132 | -pub struct BlockInfo<'a> { | ||
| 133 | - /// `true` if the block is **inter**-coded (an intra block is `!inter`). Taking | ||
| 134 | - /// the caller's existing inter mask avoids allocating an inverted intra mask | ||
| 135 | - /// per frame in both the decoder and encoder. | ||
| 136 | - pub inter: &'a [bool], | ||
| 137 | - /// Non-zero coefficient count of the block. | ||
| 138 | - pub nnz: &'a [u8], | ||
| 139 | - /// List-0 block motion vector (quarter-pel); ignored for intra. | ||
| 140 | - pub mv: &'a [(i32, i32)], | ||
| 141 | - /// List-0 reference *picture identity* (a stable per-picture id — PicOrderCnt | ||
| 142 | - /// for the decoder, ref index for the encoder; `i32::MIN` = unused/intra). | ||
| 143 | - /// Boundary strength compares the *set* of reference pictures, so the same | ||
| 144 | - /// picture used via different lists matches (spec §8.7.2.1). | ||
| 145 | - pub ref_id: &'a [i32], | ||
| 146 | - /// List-1 motion + reference identity for B blocks (`ref_id1 = i32::MIN` | ||
| 147 | - /// everywhere for P/I, so the extra slot is a no-op there). | ||
| 148 | - pub mv1: &'a [(i32, i32)], | ||
| 149 | - pub ref_id1: &'a [i32], | ||
| 150 | - /// Block-grid width (`mb_w * 4`). | ||
| 151 | - pub w4: usize, | ||
| 152 | - /// Per-macroblock `transform_size_8x8_flag` (length `mb_w * mb_h`). When set, | ||
| 153 | - /// the macroblock's internal 4×4 luma edges (sample columns/rows 4 and 12) | ||
| 154 | - /// are *not* transform boundaries and must not be filtered (spec §8.7). | ||
| 155 | - pub t8x8: &'a [bool], | ||
| 156 | - /// Boundary strengths already derived by the caller, one entry per macroblock | ||
| 157 | - /// in raster order. Empty = derive them here (the decoder path). | ||
| 158 | - pub bs: &'a [MbBs], | ||
| 159 | - /// OPTIONAL reference→identity maps (Brick: WHYS Part 15 item 2). When | ||
| 160 | - /// non-empty, `ref_id`/`ref_id1` hold RAW per-block reference INDICES | ||
| 161 | - /// (negative = none) and these ≤16-entry tables map index → picture | ||
| 162 | - /// identity (POC). This lets the decoder pass its `ref_idx` grids directly | ||
| 163 | - /// instead of materializing two frame-wide pre-mapped `Vec<i32>` shims | ||
| 164 | - /// (230-460 KB + 57,600 mapped elements per frame). Empty = `ref_id` | ||
| 165 | - /// already carries identities (the encoder path and all older callers). | ||
| 166 | - pub poc0: &'a [i32], | ||
| 167 | - pub poc1: &'a [i32], | ||
| 168 | - /// Per-macroblock derivation CLASS (`MB_KIND_*`), one entry per macroblock in | ||
| 169 | - /// raster order. Empty, or `MB_KIND_UNSET`, means "not classified" and the | ||
| 170 | - /// blind gather+derive runs for that macroblock. | ||
| 171 | - /// | ||
| 172 | - /// SAFETY-BY-DESIGN: an unclassified macroblock costs SPEED, never | ||
| 173 | - /// correctness. That inversion is deliberate — the alternative design, where | ||
| 174 | - /// the producer must hit every macroblock exit point or strengths silently go | ||
| 175 | - /// wrong, is exactly the failure `MbBs::UNSET` exists to guard against. | ||
| 176 | - /// | ||
| 177 | - /// The producer must be CONSERVATIVE. In particular `B_Skip` and | ||
| 178 | - /// `B_Direct_16x16` are NOT `MB_KIND_SKIP`: their motion comes from direct | ||
| 179 | - /// prediction and may differ per 4x4 sub-block, so internal edges can legally | ||
| 180 | - /// reach strength 1. Only classify what is uniform BY SYNTAX. | ||
| 181 | - pub kind: &'a [u8], | ||
| 182 | -} | ||
| 183 | - | ||
| 184 | -/// Not classified — take the blind path. Any value outside `0..=3` behaves this way. | ||
| 185 | -pub const MB_KIND_UNSET: u8 = 255; | ||
| 186 | -pub const MB_KIND_INTRA: u8 = 0; | ||
| 187 | -pub const MB_KIND_SKIP: u8 = 1; | ||
| 188 | -pub const MB_KIND_INTER_UNIFORM: u8 = 2; | ||
| 189 | -pub const MB_KIND_INTER: u8 = 3; | ||
| 190 | - | ||
| 191 | -impl MbKind { | ||
| 192 | - /// Decode a producer-supplied class byte. `None` = derive blindly. | ||
| 193 | - #[inline] | ||
| 194 | - pub fn from_u8(v: u8) -> Option<Self> { | ||
| 195 | - match v { | ||
| 196 | - MB_KIND_INTRA => Some(MbKind::Intra), | ||
| 197 | - MB_KIND_SKIP => Some(MbKind::Skip), | ||
| 198 | - MB_KIND_INTER_UNIFORM => Some(MbKind::InterUniform), | ||
| 199 | - MB_KIND_INTER => Some(MbKind::Inter), | ||
| 200 | - _ => None, | ||
| 201 | - } | ||
| 202 | - } | ||
| 203 | -} | ||
| 204 | - | ||
| 205 | -/// One macroblock's boundary strengths: `[edge group][segment]` per direction. | ||
| 206 | -/// | ||
| 207 | -/// 32 bytes, mirroring x264's `uint8_t bs[2][8][4]`. Deriving these during ENCODE | ||
| 208 | -/// lets the deblocking pass skip the neighbourhood gather and the derivation. | ||
| 209 | -#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] | ||
| 210 | -pub struct MbBs { | ||
| 211 | - /// Vertical edges (block columns 0..4); index 0 is the macroblock edge. | ||
| 212 | - pub v: [[u8; 4]; 4], | ||
| 213 | - /// Horizontal edges (block rows 0..4); index 0 is the macroblock edge. | ||
| 214 | - pub h: [[u8; 4]; 4], | ||
| 215 | -} | ||
| 216 | - | ||
| 217 | -impl MbBs { | ||
| 218 | - /// "Not yet derived". The macroblock loop has several exits (free skip, | ||
| 219 | - /// greedy skip, coded) and every one must store its strengths; missing one | ||
| 220 | - /// leaves zeros, silently disabling deblocking for that macroblock — which is | ||
| 221 | - /// exactly the bug the byte-identical gate caught during bring-up. | ||
| 222 | - pub const UNSET: MbBs = MbBs { v: [[0xFF; 4]; 4], h: [[0xFF; 4]; 4] }; | ||
| 223 | -} | ||
| 224 | - | ||
| 225 | -/// Sentinel for an unused reference slot. | ||
| 226 | -const NO_REF: i32 = i32::MIN; | ||
| 227 | - | ||
| 228 | -/// One 4×4 block's deblocking state, gathered into a per-macroblock tile. | ||
| 229 | -/// | ||
| 230 | -/// The frame-wide `inter`/`nnz`/`mv`/`ref_id` arrays are indexed `by * w4 + bx`, | ||
| 231 | -/// so deriving boundary strengths straight from them costs ~290 scattered loads | ||
| 232 | -/// per macroblock (each block is re-read by up to four edges, and vertical edge | ||
| 233 | -/// groups stride by `w4`). Gathering the 24 blocks an MB can touch into this | ||
| 234 | -/// contiguous tile once turns all 48 edge decisions into stack/L1 reads. x264 | ||
| 235 | -/// gets the same effect from its `scan8` cache, which is what lets its | ||
| 236 | -/// `deblock_strength` kernel be SIMD at ~15 ns/MB. | ||
| 237 | -#[derive(Clone, Copy, Default)] | ||
| 238 | -struct Blk { | ||
| 239 | - inter: bool, | ||
| 240 | - /// `nnz != 0` — the count itself never matters, only whether it is non-zero. | ||
| 241 | - nz: bool, | ||
| 242 | - ref_id: i32, | ||
| 243 | - mvx: i32, | ||
| 244 | - mvy: i32, | ||
| 245 | - /// List-1 slot (B slices). `NO_REF` on P/I tiles and on uni-L0 blocks, which | ||
| 246 | - /// keeps every comparison below on its single-list fast path there. | ||
| 247 | - ref1: i32, | ||
| 248 | - mv1x: i32, | ||
| 249 | - mv1y: i32, | ||
| 250 | -} | ||
| 251 | - | ||
| 252 | -impl Blk { | ||
| 253 | - #[inline] | ||
| 254 | - fn load(info: &BlockInfo, i: usize) -> Self { | ||
| 255 | - #[cfg(feature = "profile")] | ||
| 256 | - census::BLK_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 257 | - let (mvx, mvy) = info.mv[i]; | ||
| 258 | - let (ref1, (mv1x, mv1y)) = if info.ref_id1.is_empty() { | ||
| 259 | - (NO_REF, (0, 0)) | ||
| 260 | - } else { | ||
| 261 | - (info.rid1(i), info.mv1[i]) | ||
| 262 | - }; | ||
| 263 | - Blk { inter: info.inter[i], nz: info.nnz[i] != 0, ref_id: info.rid(i), mvx, mvy, ref1, mv1x, mv1y } | ||
| 264 | - } | ||
| 265 | - | ||
| 266 | - /// Whether two blocks are identical for flat-inter purposes (both lists — | ||
| 267 | - /// on P tiles the list-1 fields are uniformly `NO_REF`/0, so the extra | ||
| 268 | - /// compares are always-true and the P behaviour is unchanged). | ||
| 269 | - #[inline] | ||
| 270 | - fn same_motion(&self, o: &Blk) -> bool { | ||
| 271 | - self.ref_id == o.ref_id | ||
| 272 | - && self.mvx == o.mvx | ||
| 273 | - && self.mvy == o.mvy | ||
| 274 | - && self.ref1 == o.ref1 | ||
| 275 | - && self.mv1x == o.mv1x | ||
| 276 | - && self.mv1y == o.mv1y | ||
| 277 | - } | ||
| 278 | -} | ||
| 279 | - | ||
| 280 | -/// The bS==1 motion test on tile entries — mirrors [`BlockInfo::inter_bs1`] | ||
| 281 | -/// exactly (its oracle), including the two-slot B rule, but reads registers | ||
| 282 | -/// instead of strided frame arrays. The single-list fast path fires whenever | ||
| 283 | -/// neither side carries a List-1 slot: all of P, and B edges between uni-L0 | ||
| 284 | -/// blocks (equivalent to the general rule at n<=1 — a differing ref covers the | ||
| 285 | -/// differing-slot-count case, two unused slots give false). | ||
| 286 | -#[inline] | ||
| 287 | -fn bs1_tile(p: &Blk, q: &Blk) -> bool { | ||
| 288 | - if (p.ref1 == NO_REF) & (q.ref1 == NO_REF) { | ||
| 289 | - let far = ((p.mvx - q.mvx).abs() >= 4) | ((p.mvy - q.mvy).abs() >= 4); | ||
| 290 | - return (p.ref_id != q.ref_id) | ((p.ref_id != NO_REF) & far); | ||
| 291 | - } | ||
| 292 | - let used = |b: &Blk| { | ||
| 293 | - let mut v = [(0i32, (0i32, 0i32)); 2]; | ||
| 294 | - let mut n = 0usize; | ||
| 295 | - if b.ref_id != NO_REF { | ||
| 296 | - v[n] = (b.ref_id, (b.mvx, b.mvy)); | ||
| 297 | - n += 1; | ||
| 298 | - } | ||
| 299 | - if b.ref1 != NO_REF { | ||
| 300 | - v[n] = (b.ref1, (b.mv1x, b.mv1y)); | ||
| 301 | - n += 1; | ||
| 302 | - } | ||
| 303 | - (v, n) | ||
| 304 | - }; | ||
| 305 | - let (pv, pn) = used(p); | ||
| 306 | - let (qv, qn) = used(q); | ||
| 307 | - if pn != qn { | ||
| 308 | - return true; | ||
| 309 | - } | ||
| 310 | - let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4; | ||
| 311 | - match pn { | ||
| 312 | - 0 => false, | ||
| 313 | - 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1), | ||
| 314 | - _ => { | ||
| 315 | - let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1); | ||
| 316 | - let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1); | ||
| 317 | - if pv[0].0 == pv[1].0 { | ||
| 318 | - qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap) | ||
| 319 | - } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 { | ||
| 320 | - !direct | ||
| 321 | - } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 { | ||
| 322 | - !swap | ||
| 323 | - } else { | ||
| 324 | - true | ||
| 325 | - } | ||
| 326 | - } | ||
| 327 | - } | ||
| 328 | -} | ||
| 329 | - | ||
| 330 | -/// Boundary strength from tile entries (spec §8.7.2.1). | ||
| 331 | -/// Branchless for the same reason as [`BlockInfo::bs_branchless`], but now with | ||
| 332 | -/// every operand already in a register rather than behind a strided load. | ||
| 333 | -// --- edith patch: only the `#[cfg(test)]` tile guards below call this, so it | ||
| 334 | -// sits with them rather than warning in every build. --- | ||
| 335 | -#[cfg(test)] | ||
| 336 | -#[inline] | ||
| 337 | -fn bs_tile(p: &Blk, q: &Blk, mb_edge: bool) -> i32 { | ||
| 338 | - let intra = !(p.inter & q.inter); | ||
| 339 | - let nz = p.nz | q.nz; | ||
| 340 | - let moved = bs1_tile(p, q); | ||
| 341 | - let intra_bs = if mb_edge { 4 } else { 3 }; | ||
| 342 | - let non_intra = if nz { 2 } else { moved as i32 }; | ||
| 343 | - if intra { | ||
| 344 | - intra_bs | ||
| 345 | - } else { | ||
| 346 | - non_intra | ||
| 347 | - } | ||
| 348 | -} | ||
| 349 | - | ||
| 350 | -/// Boundary strength for an edge where BOTH sides are inter — the only case left | ||
| 351 | -/// once the per-macroblock intra fills in [`derive_mb_bs`] have run. It can never | ||
| 352 | -/// return 3 or 4, which is precisely why x264's `deblock_strength` kernel is | ||
| 353 | -/// branch-light enough to vectorise: the intra strengths are not its job. | ||
| 354 | -#[inline] | ||
| 355 | -fn bs_inter(p: &Blk, q: &Blk) -> i32 { | ||
| 356 | - let nz = p.nz | q.nz; | ||
| 357 | - let moved = bs1_tile(p, q); | ||
| 358 | - if nz { | ||
| 359 | - 2 | ||
| 360 | - } else { | ||
| 361 | - moved as i32 | ||
| 362 | - } | ||
| 363 | -} | ||
| 364 | - | ||
| 365 | -/// MB-KIND CENSUS — measurement only, `--features profile`, so the shipped and | ||
| 366 | -/// benchmarked binaries carry no counter at all (atomics in a 6.5M-call loop have | ||
| 367 | -/// measured ~15% wall inflation elsewhere in this workspace). | ||
| 368 | -/// | ||
| 369 | -/// Exists to size the prize of a KIND-AWARE derivation arithmetically before one | ||
| 370 | -/// is built. `derive_mb_kind` already reads nothing for Intra, 9 blocks for Skip | ||
| 371 | -/// and 16 nnz bytes for InterUniform, against 24 blocks across 5-7 grids for the | ||
| 372 | -/// blind `derive_mb` the decoder currently calls — but that only pays if the | ||
| 373 | -/// cheap kinds actually dominate real content. Count first. | ||
| 374 | -#[cfg(feature = "profile")] | ||
| 375 | -pub mod census { | ||
| 376 | - use std::sync::atomic::{AtomicU64, Ordering}; | ||
| 377 | - pub static INTRA: AtomicU64 = AtomicU64::new(0); | ||
| 378 | - pub static SKIP: AtomicU64 = AtomicU64::new(0); | ||
| 379 | - pub static UNIFORM: AtomicU64 = AtomicU64::new(0); | ||
| 380 | - pub static INTER: AtomicU64 = AtomicU64::new(0); | ||
| 381 | - /// Block VISITS made by the predicate walk(s). The timing instruments on this | ||
| 382 | - /// box cannot resolve the fusion (two whole-decode runs disagreed in sign; the | ||
| 383 | - /// anatomy bench's within-arm spread reached 45%), so the bankable evidence is | ||
| 384 | - /// the work actually removed, which no amount of drift can move. | ||
| 385 | - pub static PRED_VISITS: AtomicU64 = AtomicU64::new(0); | ||
| 386 | - /// Every `Blk::load` — the per-block, multi-array gather that Brick 2 exists to | ||
| 387 | - /// avoid. This is the PRIMARY evidence for the brick (codec-measurement §15): | ||
| 388 | - /// one run, drift-immune, and it sizes the win as well as proving it. | ||
| 389 | - pub static BLK_LOADS: AtomicU64 = AtomicU64::new(0); | ||
| 390 | - /// Macroblocks that took the PACKED derivation. Coverage matters: a | ||
| 391 | - /// byte-identical result proves nothing if the path never engaged. | ||
| 392 | - pub static PACKED_MB: AtomicU64 = AtomicU64::new(0); | ||
| 393 | - /// Macroblocks that actually REACH the motion-mask derivation (not intra, not | ||
| 394 | - /// uniform) — the denominator for any kernel prize. | ||
| 395 | - pub static MASKS_CALLS: AtomicU64 = AtomicU64::new(0); | ||
| 396 | - /// ...of those, served by the AVX2 single-list kernel (`l1_used == 0`). | ||
| 397 | - pub static MASKS_KERNEL: AtomicU64 = AtomicU64::new(0); | ||
| 398 | - /// ...of those, forced to the scalar two-list set-match (`l1_used != 0`). | ||
| 399 | - /// THIS is the population a two-list kernel would win, and nothing else. | ||
| 400 | - pub static MASKS_L1: AtomicU64 = AtomicU64::new(0); | ||
| 401 | - | ||
| 402 | - pub fn reset() { | ||
| 403 | - for c in [ | ||
| 404 | - &INTRA, &SKIP, &UNIFORM, &INTER, &PRED_VISITS, &BLK_LOADS, &PACKED_MB, | ||
| 405 | - &MASKS_CALLS, &MASKS_KERNEL, &MASKS_L1, | ||
| 406 | - ] { | ||
| 407 | - c.store(0, Ordering::Relaxed); | ||
| 408 | - } | ||
| 409 | - } | ||
| 410 | - | ||
| 411 | - /// Per-kind gather cost in BLOCK LOADS, from `derive_mb_kind`'s own structure. | ||
| 412 | - /// The projection below is a load-count model, not a timing — it says what is | ||
| 413 | - /// worth measuring, and the measurement still has to happen. | ||
| 414 | - pub fn dump() { | ||
| 415 | - let (i, s, u, n) = ( | ||
| 416 | - INTRA.load(Ordering::Relaxed), | ||
| 417 | - SKIP.load(Ordering::Relaxed), | ||
| 418 | - UNIFORM.load(Ordering::Relaxed), | ||
| 419 | - INTER.load(Ordering::Relaxed), | ||
| 420 | - ); | ||
| 421 | - let tot = (i + s + u + n).max(1); | ||
| 422 | - eprintln!("--- MB-kind census (deblock bS derivation) — {tot} macroblocks ---"); | ||
| 423 | - for (name, n_mb, blocks) in | ||
| 424 | - [("Intra", i, 0u64), ("Skip", s, 9), ("InterUniform", u, 16), ("Inter", n, 24)] | ||
| 425 | - { | ||
| 426 | - eprintln!( | ||
| 427 | - " {name:<13} {n_mb:>10} MB {:>5.1}% kind-aware gather: {blocks:>2} blocks vs 24 blind", | ||
| 428 | - 100.0 * n_mb as f64 / tot as f64 | ||
| 429 | - ); | ||
| 430 | - } | ||
| 431 | - eprintln!( | ||
| 432 | - " Blk::load GATHER loads: {} ({:.2} per MB)", | ||
| 433 | - BLK_LOADS.load(Ordering::Relaxed), | ||
| 434 | - BLK_LOADS.load(Ordering::Relaxed) as f64 / tot as f64 | ||
| 435 | - ); | ||
| 436 | - eprintln!( | ||
| 437 | - " predicate-walk block VISITS: {} ({:.2} per MB)", | ||
| 438 | - PRED_VISITS.load(Ordering::Relaxed), | ||
| 439 | - PRED_VISITS.load(Ordering::Relaxed) as f64 / tot as f64 | ||
| 440 | - ); | ||
| 441 | - eprintln!( | ||
| 442 | - " PACKED-path macroblocks: {}", | ||
| 443 | - PACKED_MB.load(Ordering::Relaxed) | ||
| 444 | - ); | ||
| 445 | - let mc = MASKS_CALLS.load(Ordering::Relaxed).max(1); | ||
| 446 | - eprintln!( | ||
| 447 | - " mask derivations: {} (AVX2 kernel {} = {:.1}%, scalar two-list {} = {:.1}%)", | ||
| 448 | - MASKS_CALLS.load(Ordering::Relaxed), | ||
| 449 | - MASKS_KERNEL.load(Ordering::Relaxed), | ||
| 450 | - 100.0 * MASKS_KERNEL.load(Ordering::Relaxed) as f64 / mc as f64, | ||
| 451 | - MASKS_L1.load(Ordering::Relaxed), | ||
| 452 | - 100.0 * MASKS_L1.load(Ordering::Relaxed) as f64 / mc as f64, | ||
| 453 | - ); | ||
| 454 | - let blind = 24.0 * tot as f64; | ||
| 455 | - let aware = (0 * i + 9 * s + 16 * u + 24 * n) as f64; | ||
| 456 | - eprintln!( | ||
| 457 | - " => block loads {:.0} -> {:.0} ({:.1}% of the gather removed)", | ||
| 458 | - blind, | ||
| 459 | - aware, | ||
| 460 | - 100.0 * (1.0 - aware / blind) | ||
| 461 | - ); | ||
| 462 | - } | ||
| 463 | -} | ||
| 464 | - | ||
| 465 | -/// Derive one macroblock's 32 boundary strengths (2 directions × 4 edge groups × | ||
| 466 | -/// 4 segments), x264-style. | ||
| 467 | -/// | ||
| 468 | -/// The structural point: `mb_type` is a per-MACROBLOCK syntax element, so a | ||
| 469 | -/// macroblock is wholly intra or wholly inter and intra-ness is not a per-edge | ||
| 470 | -/// property. That turns the two expensive cases into constant fills — | ||
| 471 | -/// * intra macroblock → internal edges are the constant 3, its own macroblock | ||
| 472 | -/// edges the constant 4; | ||
| 473 | -/// * flat inter (skip) macroblock → every internal strength is 0; | ||
| 474 | -/// — and leaves [`bs_inter`] for the rest. Pinned by `derive_matches_per_edge`. | ||
| 475 | -#[inline] | ||
| 476 | -fn derive_mb_bs( | ||
| 477 | - tile: &Tile, | ||
| 478 | - mb_x: usize, | ||
| 479 | - mb_y: usize, | ||
| 480 | - flat_inter: bool, | ||
| 481 | - uniform_motion: bool, | ||
| 482 | - mb_t8: bool, | ||
| 483 | - bs_v: &mut [[i32; 4]; 4], | ||
| 484 | - bs_h: &mut [[i32; 4]; 4], | ||
| 485 | -) { | ||
| 486 | - let cur_intra = !tile[1][1].inter; | ||
| 487 | - | ||
| 488 | - #[cfg(feature = "profile")] | ||
| 489 | - { | ||
| 490 | - use std::sync::atomic::Ordering::Relaxed; | ||
| 491 | - let c = if cur_intra { | ||
| 492 | - &census::INTRA | ||
| 493 | - } else if flat_inter { | ||
| 494 | - &census::SKIP | ||
| 495 | - } else if uniform_motion { | ||
| 496 | - &census::UNIFORM | ||
| 497 | - } else { | ||
| 498 | - &census::INTER | ||
| 499 | - }; | ||
| 500 | - c.fetch_add(1, Relaxed); | ||
| 501 | - } | ||
| 502 | - | ||
| 503 | - // ---- macroblock edges: 4 if EITHER side is intra, else an inter compare ---- | ||
| 504 | - if mb_x > 0 { | ||
| 505 | - bs_v[0] = if cur_intra || !tile[1][0].inter { | ||
| 506 | - [4; 4] | ||
| 507 | - } else { | ||
| 508 | - std::array::from_fn(|seg| bs_inter(&tile[seg + 1][0], &tile[seg + 1][1])) | ||
| 509 | - }; | ||
| 510 | - } | ||
| 511 | - if mb_y > 0 { | ||
| 512 | - bs_h[0] = if cur_intra || !tile[0][1].inter { | ||
| 513 | - [4; 4] | ||
| 514 | - } else { | ||
| 515 | - std::array::from_fn(|seg| bs_inter(&tile[0][seg + 1], &tile[1][seg + 1])) | ||
| 516 | - }; | ||
| 517 | - } | ||
| 518 | - | ||
| 519 | - // ---- internal edges ---- | ||
| 520 | - if flat_inter { | ||
| 521 | - return; // all zero by construction (no coefficients, one shared ref+mv) | ||
| 522 | - } | ||
| 523 | - for be in 1..4usize { | ||
| 524 | - // An 8×8-transform macroblock has no transform boundary at 4×4 edges 1/3. | ||
| 525 | - if mb_t8 && (be == 1 || be == 3) { | ||
| 526 | - continue; | ||
| 527 | - } | ||
| 528 | - if cur_intra { | ||
| 529 | - bs_v[be] = [3; 4]; | ||
| 530 | - bs_h[be] = [3; 4]; | ||
| 531 | - } else if uniform_motion { | ||
| 532 | - // Coefficients alone; 0 or 2, no motion compare. | ||
| 533 | - bs_v[be] = std::array::from_fn(|seg| { | ||
| 534 | - 2 * (tile[seg + 1][be].nz | tile[seg + 1][be + 1].nz) as i32 | ||
| 535 | - }); | ||
| 536 | - bs_h[be] = std::array::from_fn(|seg| { | ||
| 537 | - 2 * (tile[be][seg + 1].nz | tile[be + 1][seg + 1].nz) as i32 | ||
| 538 | - }); | ||
| 539 | - } else { | ||
| 540 | - // Both sides are inside this macroblock, so no neighbour read at all. | ||
| 541 | - bs_v[be] = std::array::from_fn(|seg| bs_inter(&tile[seg + 1][be], &tile[seg + 1][be + 1])); | ||
| 542 | - bs_h[be] = std::array::from_fn(|seg| bs_inter(&tile[be][seg + 1], &tile[be + 1][seg + 1])); | ||
| 543 | - } | ||
| 544 | - } | ||
| 545 | -} | ||
| 546 | - | ||
| 547 | -/// What the encoder already knows about a macroblock the moment it finishes | ||
| 548 | -/// coding it. Passing it in turns most macroblocks into constant fills and | ||
| 549 | -/// removes the neighbourhood gather that made deriving in the encode loop cost | ||
| 550 | -/// MORE than deriving in the deblocking pass (the loop's working set is far more | ||
| 551 | -/// contended, so a 24-block gather there evicts live encoder data). | ||
| 552 | -#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 553 | -pub enum MbKind { | ||
| 554 | - /// Intra: internal strengths are the constant 3, its own macroblock edges 4. | ||
| 555 | - /// Needs NO block reads at all. | ||
| 556 | - Intra, | ||
| 557 | - /// Skip — no coefficients, one shared reference and motion vector — so every | ||
| 558 | - /// internal strength is 0 and only the two macroblock edges are derived. | ||
| 559 | - Skip, | ||
| 560 | - /// Coded inter with a SINGLE partition (P_L0_16x16 — the fast preset's only | ||
| 561 | - /// inter mode). All 16 blocks share one reference and motion vector, so no | ||
| 562 | - /// internal edge can reach strength 1: internal strengths depend on | ||
| 563 | - /// coefficients alone, and the derivation reads 16 nnz bytes instead of | ||
| 564 | - /// gathering 24 blocks across four grids. | ||
| 565 | - InterUniform, | ||
| 566 | - /// Coded inter, multiple partitions: the full derivation. | ||
| 567 | - Inter, | ||
| 568 | -} | ||
| 569 | - | ||
| 570 | -/// Boundary strengths for a macroblock whose kind the caller already knows. | ||
| 571 | -/// | ||
| 572 | -/// `Intra` reads nothing; `Skip` reads one of its own blocks plus the neighbour | ||
| 573 | -/// column/row (9 instead of 24); only `Inter` pays the full gather. | ||
| 574 | -/// `derive_mb_kind_into` writes the deblock loop's `i32` arrays directly. | ||
| 575 | -pub fn derive_mb_kind_into( | ||
| 576 | - info: &BlockInfo, | ||
| 577 | - mb_x: usize, | ||
| 578 | - mb_y: usize, | ||
| 579 | - kind: MbKind, | ||
| 580 | - bs_v: &mut [[i32; 4]; 4], | ||
| 581 | - bs_h: &mut [[i32; 4]; 4], | ||
| 582 | -) { | ||
| 583 | - // Direct i32 writes — no MbBs staging + 32 u8→i32 casts. | ||
| 584 | - *bs_v = [[0; 4]; 4]; | ||
| 585 | - *bs_h = [[0; 4]; 4]; | ||
| 586 | - let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 587 | - let w4 = info.w4; | ||
| 588 | - match kind { | ||
| 589 | - MbKind::Intra => { | ||
| 590 | - if mb_x > 0 { | ||
| 591 | - bs_v[0] = [4; 4]; | ||
| 592 | - } | ||
| 593 | - if mb_y > 0 { | ||
| 594 | - bs_h[0] = [4; 4]; | ||
| 595 | - } | ||
| 596 | - for e in 1..4 { | ||
| 597 | - bs_v[e] = [3; 4]; | ||
| 598 | - bs_h[e] = [3; 4]; | ||
| 599 | - } | ||
| 600 | - } | ||
| 601 | - MbKind::Skip => { | ||
| 602 | - let me = Blk::load(info, by0 * w4 + bx0); | ||
| 603 | - if mb_x > 0 { | ||
| 604 | - bs_v[0] = std::array::from_fn(|seg| { | ||
| 605 | - let p = Blk::load(info, (by0 + seg) * w4 + bx0 - 1); | ||
| 606 | - if p.inter { | ||
| 607 | - bs_inter(&p, &me) | ||
| 608 | - } else { | ||
| 609 | - 4 | ||
| 610 | - } | ||
| 611 | - }); | ||
| 612 | - } | ||
| 613 | - if mb_y > 0 { | ||
| 614 | - bs_h[0] = std::array::from_fn(|seg| { | ||
| 615 | - let p = Blk::load(info, (by0 - 1) * w4 + bx0 + seg); | ||
| 616 | - if p.inter { | ||
| 617 | - bs_inter(&p, &me) | ||
| 618 | - } else { | ||
| 619 | - 4 | ||
| 620 | - } | ||
| 621 | - }); | ||
| 622 | - } | ||
| 623 | - } | ||
| 624 | - MbKind::InterUniform => { | ||
| 625 | - for e in 1..4usize { | ||
| 626 | - bs_v[e] = std::array::from_fn(|seg| { | ||
| 627 | - let i = (by0 + seg) * w4 + bx0 + e; | ||
| 628 | - 2 * ((info.nnz[i] != 0) | (info.nnz[i - 1] != 0)) as i32 | ||
| 629 | - }); | ||
| 630 | - bs_h[e] = std::array::from_fn(|seg| { | ||
| 631 | - let i = (by0 + e) * w4 + bx0 + seg; | ||
| 632 | - 2 * ((info.nnz[i] != 0) | (info.nnz[i - w4] != 0)) as i32 | ||
| 633 | - }); | ||
| 634 | - } | ||
| 635 | - if mb_x > 0 { | ||
| 636 | - bs_v[0] = std::array::from_fn(|seg| { | ||
| 637 | - let qi = (by0 + seg) * w4 + bx0; | ||
| 638 | - let p = Blk::load(info, qi - 1); | ||
| 639 | - if p.inter { | ||
| 640 | - bs_inter(&p, &Blk::load(info, qi)) | ||
| 641 | - } else { | ||
| 642 | - 4 | ||
| 643 | - } | ||
| 644 | - }); | ||
| 645 | - } | ||
| 646 | - if mb_y > 0 { | ||
| 647 | - bs_h[0] = std::array::from_fn(|seg| { | ||
| 648 | - let qi = by0 * w4 + bx0 + seg; | ||
| 649 | - let p = Blk::load(info, qi - w4); | ||
| 650 | - if p.inter { | ||
| 651 | - bs_inter(&p, &Blk::load(info, qi)) | ||
| 652 | - } else { | ||
| 653 | - 4 | ||
| 654 | - } | ||
| 655 | - }); | ||
| 656 | - } | ||
| 657 | - } | ||
| 658 | - MbKind::Inter => { | ||
| 659 | - let m = derive_mb(info, mb_x, mb_y, false); | ||
| 660 | - for e in 0..4 { | ||
| 661 | - for sg in 0..4 { | ||
| 662 | - bs_v[e][sg] = m.v[e][sg] as i32; | ||
| 663 | - bs_h[e][sg] = m.h[e][sg] as i32; | ||
| 664 | - } | ||
| 665 | - } | ||
| 666 | - } | ||
| 667 | - } | ||
| 668 | -} | ||
| 669 | - | ||
| 670 | -pub fn derive_mb_kind(info: &BlockInfo, mb_x: usize, mb_y: usize, kind: MbKind) -> MbBs { | ||
| 671 | - let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 672 | - let w4 = info.w4; | ||
| 673 | - match kind { | ||
| 674 | - MbKind::Intra => { | ||
| 675 | - let mut m = MbBs::default(); | ||
| 676 | - if mb_x > 0 { | ||
| 677 | - m.v[0] = [4; 4]; | ||
| 678 | - } | ||
| 679 | - if mb_y > 0 { | ||
| 680 | - m.h[0] = [4; 4]; | ||
| 681 | - } | ||
| 682 | - for e in 1..4 { | ||
| 683 | - m.v[e] = [3; 4]; | ||
| 684 | - m.h[e] = [3; 4]; | ||
| 685 | - } | ||
| 686 | - m | ||
| 687 | - } | ||
| 688 | - MbKind::Skip => { | ||
| 689 | - // Internal strengths stay 0: no coefficients and one shared (ref, mv) | ||
| 690 | - // means no internal edge can reach strength 1 or 2. | ||
| 691 | - let mut m = MbBs::default(); | ||
| 692 | - let me = Blk::load(info, by0 * w4 + bx0); // all 16 blocks are identical | ||
| 693 | - if mb_x > 0 { | ||
| 694 | - m.v[0] = std::array::from_fn(|seg| { | ||
| 695 | - let p = Blk::load(info, (by0 + seg) * w4 + bx0 - 1); | ||
| 696 | - if p.inter { bs_inter(&p, &me) as u8 } else { 4 } | ||
| 697 | - }); | ||
| 698 | - } | ||
| 699 | - if mb_y > 0 { | ||
| 700 | - m.h[0] = std::array::from_fn(|seg| { | ||
| 701 | - let p = Blk::load(info, (by0 - 1) * w4 + bx0 + seg); | ||
| 702 | - if p.inter { bs_inter(&p, &me) as u8 } else { 4 } | ||
| 703 | - }); | ||
| 704 | - } | ||
| 705 | - m | ||
| 706 | - } | ||
| 707 | - MbKind::InterUniform => { | ||
| 708 | - let mut m = MbBs::default(); | ||
| 709 | - // Internal edges: uniform motion means only coefficients can raise a | ||
| 710 | - // strength, and then only to 2. | ||
| 711 | - for e in 1..4usize { | ||
| 712 | - m.v[e] = std::array::from_fn(|seg| { | ||
| 713 | - let i = (by0 + seg) * w4 + bx0 + e; | ||
| 714 | - 2 * ((info.nnz[i] != 0) | (info.nnz[i - 1] != 0)) as u8 | ||
| 715 | - }); | ||
| 716 | - m.h[e] = std::array::from_fn(|seg| { | ||
| 717 | - let i = (by0 + e) * w4 + bx0 + seg; | ||
| 718 | - 2 * ((info.nnz[i] != 0) | (info.nnz[i - w4] != 0)) as u8 | ||
| 719 | - }); | ||
| 720 | - } | ||
| 721 | - // Macroblock edges still cross into the neighbour, and our own | ||
| 722 | - // coefficients vary per block, so both sides are read per segment. | ||
| 723 | - if mb_x > 0 { | ||
| 724 | - m.v[0] = std::array::from_fn(|seg| { | ||
| 725 | - let qi = (by0 + seg) * w4 + bx0; | ||
| 726 | - let p = Blk::load(info, qi - 1); | ||
| 727 | - if p.inter { bs_inter(&p, &Blk::load(info, qi)) as u8 } else { 4 } | ||
| 728 | - }); | ||
| 729 | - } | ||
| 730 | - if mb_y > 0 { | ||
| 731 | - m.h[0] = std::array::from_fn(|seg| { | ||
| 732 | - let qi = by0 * w4 + bx0 + seg; | ||
| 733 | - let p = Blk::load(info, qi - w4); | ||
| 734 | - if p.inter { bs_inter(&p, &Blk::load(info, qi)) as u8 } else { 4 } | ||
| 735 | - }); | ||
| 736 | - } | ||
| 737 | - m | ||
| 738 | - } | ||
| 739 | - MbKind::Inter => derive_mb(info, mb_x, mb_y, false), | ||
| 740 | - } | ||
| 741 | -} | ||
| 742 | - | ||
| 743 | -/// Derive one macroblock's boundary strengths from the block grids — the entry | ||
| 744 | -/// point for computing them during ENCODE. | ||
| 745 | -/// | ||
| 746 | -/// `info.ref_id` may carry the encoder's raw reference indices (negative for | ||
| 747 | -/// intra) rather than the `NO_REF` sentinel: reference identity is only ever | ||
| 748 | -/// compared between two INTER blocks, which always hold a valid index. | ||
| 749 | -/// PACKED per-macroblock boundary-strength inputs — the x264-shaped layout. | ||
| 750 | -/// | ||
| 751 | -/// Everything one macroblock's derivation needs for its own 16 blocks, contiguous, | ||
| 752 | -/// in raster order (`k = row * 4 + col`). This is the layout `deblock_strength_avx2` | ||
| 753 | -/// works from, and the reason x264 can vectorise a job we currently do 32 times | ||
| 754 | -/// scalar and branchy. | ||
| 755 | -/// | ||
| 756 | -/// Sized by the CEILING PROBE (`examples/bs_layout_ceiling.rs`), which measured, at | ||
| 757 | -/// 720p on synthetic-but-representative content: | ||
| 758 | -/// | ||
| 759 | -/// * cache lines touched per macroblock: **16-20 strided vs 2 packed** | ||
| 760 | -/// * gather cost (cache-warm): **31.1 ns/MB strided vs 12.5 ns/MB packed** (2.49x) | ||
| 761 | -/// | ||
| 762 | -/// Read that second row carefully, because it REFUTED the original justification for | ||
| 763 | -/// this work. The whole derivation costs ~400 ns/MB in context, so eliminating the | ||
| 764 | -/// gather buys only ~19 ns/MB — about 5% of the derivation, ~1% of decode. **The | ||
| 765 | -/// derivation is COMPUTE-bound, not gather-bound**: ~370 ns/MB is the 32 per-edge | ||
| 766 | -/// `bs_inter` evaluations themselves (32 edges x ~20-30 cycles ~= 210-320 ns @ 3 GHz, | ||
| 767 | -/// which matches). So this layout does NOT pay for itself as a memory optimisation. | ||
| 768 | -/// It exists to make the ARITHMETIC vectorisable — `nnz` collapses to shift-and-or on | ||
| 769 | -/// a 16-bit mask, and the motion test becomes i16 subtract/abs/compare across 16 | ||
| 770 | -/// lanes. That distinction decides whether the SIMD stage is worth building, and it | ||
| 771 | -/// is the good case: this codebase's flat SIMD results were all memory-bound kernels, | ||
| 772 | -/// its wins (DCT/SATD) were compute-bound. | ||
| 773 | -/// | ||
| 774 | -/// SINGLE-LIST ONLY. B macroblocks carrying a List-1 slot fall back to the blind | ||
| 775 | -/// path; the two-list rule in `bs1_tile` is not reproduced here. | ||
| 776 | -#[derive(Clone, Copy)] | ||
| 777 | -#[repr(C, align(32))] | ||
| 778 | -pub struct MbPack { | ||
| 779 | - /// Bit `k` set = block `k` has coefficients. The derivation only ever asks | ||
| 780 | - /// "is this block coded", never for the count. | ||
| 781 | - pub nnz_mask: u16, | ||
| 782 | - /// `mb_type` is a per-MACROBLOCK syntax element, so intra-ness is not per-block. | ||
| 783 | - pub inter: bool, | ||
| 784 | - _pad: u8, | ||
| 785 | - /// Quarter-pel motion, per block, SPLIT into x and y planes. | ||
| 786 | - /// | ||
| 787 | - /// Structure-of-arrays on purpose: interleaved `(x,y)` pairs would force the SIMD | ||
| 788 | - /// twin to OR adjacent lanes together (a pairwise reduction), whereas split planes | ||
| 789 | - /// let the x and y compares live in separate registers and OR whole-register. | ||
| 790 | - /// 16 x i16 is exactly one 256-bit load each. | ||
| 791 | - pub mvx: [i16; 16], | ||
| 792 | - pub mvy: [i16; 16], | ||
| 793 | - /// Bit k set = block k carries a List-1 slot. When this is 0 for a macroblock, | ||
| 794 | - /// every internal edge takes the single-list rule and the AVX2 kernel applies; | ||
| 795 | - /// otherwise the two-list set-matching rule runs scalar for that macroblock. | ||
| 796 | - pub l1_used: u16, | ||
| 797 | - pub mvx1: [i16; 16], | ||
| 798 | - pub mvy1: [i16; 16], | ||
| 799 | - pub ref1: [i32; 16], | ||
| 800 | - /// Reference PICTURE IDENTITY per block (`NO_REF` = intra/unused). Kept i32 | ||
| 801 | - /// because the decoder supplies a POC, which must stay comparable across slices | ||
| 802 | - /// whose reference lists differ — a `ref_idx` would compare equal across slices | ||
| 803 | - /// that mean different pictures. | ||
| 804 | - pub ref_id: [i32; 16], | ||
| 805 | -} | ||
| 806 | - | ||
| 807 | -impl BlockInfo<'_> { | ||
| 808 | - /// Block `i`'s List-0 reference identity, applying the optional index map. | ||
| 809 | - #[inline] | ||
| 810 | - fn rid(&self, i: usize) -> i32 { | ||
| 811 | - let r = self.ref_id[i]; | ||
| 812 | - if self.poc0.is_empty() { | ||
| 813 | - r | ||
| 814 | - } else if r >= 0 { | ||
| 815 | - self.poc0.get(r as usize).copied().unwrap_or(NO_REF) | ||
| 816 | - } else { | ||
| 817 | - NO_REF | ||
| 818 | - } | ||
| 819 | - } | ||
| 820 | - | ||
| 821 | - /// Block `i`'s List-1 reference identity (mapped); `NO_REF` when no List-1. | ||
| 822 | - #[inline] | ||
| 823 | - fn rid1(&self, i: usize) -> i32 { | ||
| 824 | - let r = self.ref_id1[i]; | ||
| 825 | - if self.poc1.is_empty() { | ||
| 826 | - r | ||
| 827 | - } else if r >= 0 { | ||
| 828 | - self.poc1.get(r as usize).copied().unwrap_or(NO_REF) | ||
| 829 | - } else { | ||
| 830 | - NO_REF | ||
| 831 | - } | ||
| 832 | - } | ||
| 833 | -} | ||
| 834 | - | ||
| 835 | -impl Default for MbPack { | ||
| 836 | - fn default() -> Self { | ||
| 837 | - Self { | ||
| 838 | - nnz_mask: 0, | ||
| 839 | - inter: false, | ||
| 840 | - _pad: 0, | ||
| 841 | - mvx: [0; 16], | ||
| 842 | - mvy: [0; 16], | ||
| 843 | - l1_used: 0, | ||
| 844 | - mvx1: [0; 16], | ||
| 845 | - mvy1: [0; 16], | ||
| 846 | - ref1: [NO_REF; 16], | ||
| 847 | - ref_id: [NO_REF; 16], | ||
| 848 | - } | ||
| 849 | - } | ||
| 850 | -} | ||
| 851 | - | ||
| 852 | -/// Build the packed records for a whole frame in ONE streaming pass. | ||
| 853 | -/// | ||
| 854 | -/// Each frame-wide array is read once, sequentially and prefetch-friendly, instead of | ||
| 855 | -/// being hit 3600 times at scattered per-macroblock offsets. Returns `None` when the | ||
| 856 | -/// frame carries List-1 data (B slices), which this layout does not model. | ||
| 857 | -pub fn pack_frame(info: &BlockInfo, mb_w: usize, mb_h: usize) -> Option<Vec<MbPack>> { | ||
| 858 | - let mut out = Vec::new(); | ||
| 859 | - pack_frame_into(info, mb_w, mb_h, &mut out); | ||
| 860 | - Some(out) | ||
| 861 | -} | ||
| 862 | - | ||
| 863 | -/// [`pack_frame`] into a RECYCLED buffer (Brick: WHYS Part 15 item 1). A fresh | ||
| 864 | -/// `Vec<MbPack>` was ~1.1 MB allocated + first-touch-faulted EVERY frame — the | ||
| 865 | -/// same per-frame-materialization mechanism the banked GridPool brick removed. | ||
| 866 | -/// Each record is built in a local and pushed, so a reused allocation is never | ||
| 867 | -/// pre-filled: one write per byte, no defaults pass, no page faults. | ||
| 868 | -pub fn pack_frame_into(info: &BlockInfo, mb_w: usize, mb_h: usize, out: &mut Vec<MbPack>) { | ||
| 869 | - let has1 = !info.ref_id1.is_empty(); | ||
| 870 | - out.clear(); | ||
| 871 | - out.reserve(mb_w * mb_h); | ||
| 872 | - for mb_y in 0..mb_h { | ||
| 873 | - for mb_x in 0..mb_w { | ||
| 874 | - out.push(pack_mb(info, has1, mb_x, mb_y)); | ||
| 875 | - } | ||
| 876 | - } | ||
| 877 | -} | ||
| 878 | - | ||
| 879 | -/// One macroblock's packed record — the unit of both `pack_frame_into` and the | ||
| 880 | -/// rolling-window precompute pass. | ||
| 881 | -#[inline] | ||
| 882 | -pub fn pack_mb(info: &BlockInfo, has1: bool, mb_x: usize, mb_y: usize) -> MbPack { | ||
| 883 | - let mut rec = MbPack::default(); | ||
| 884 | - let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 885 | - rec.inter = info.inter[by0 * info.w4 + bx0]; | ||
| 886 | - for r in 0..4 { | ||
| 887 | - let row = (by0 + r) * info.w4 + bx0; | ||
| 888 | - for c in 0..4 { | ||
| 889 | - let i = row + c; | ||
| 890 | - let k = r * 4 + c; | ||
| 891 | - if info.nnz[i] != 0 { | ||
| 892 | - rec.nnz_mask |= 1 << k; | ||
| 893 | - } | ||
| 894 | - rec.mvx[k] = info.mv[i].0 as i16; | ||
| 895 | - rec.mvy[k] = info.mv[i].1 as i16; | ||
| 896 | - rec.ref_id[k] = info.rid(i); | ||
| 897 | - if has1 { | ||
| 898 | - let r1 = info.rid1(i); | ||
| 899 | - rec.ref1[k] = r1; | ||
| 900 | - rec.mvx1[k] = info.mv1[i].0 as i16; | ||
| 901 | - rec.mvy1[k] = info.mv1[i].1 as i16; | ||
| 902 | - if r1 != NO_REF { | ||
| 903 | - rec.l1_used |= 1 << k; | ||
| 904 | - } | ||
| 905 | - } | ||
| 906 | - } | ||
| 907 | - } | ||
| 908 | - rec | ||
| 909 | -} | ||
| 910 | - | ||
| 911 | -/// FUSED pack+derive over the whole frame, with a TWO-ROW ROLLING WINDOW of | ||
| 912 | -/// packed records (WHYS Part 16 root-cause lever, bounded form). | ||
| 913 | -/// | ||
| 914 | -/// The frame-buffer pipeline was: pack ALL 3600 records into a ~1.1 MB Vec, | ||
| 915 | -/// then a second interleaved loop re-reads them (plus a per-MB gate ladder) to | ||
| 916 | -/// derive strengths. Here each record is DERIVED the moment it is built — | ||
| 917 | -/// while it and its left/top neighbours are L1-hot — and only `2 × mb_w` | ||
| 918 | -/// records (~50 KB at 720p) ever exist. Output is one `MbBs` (32 B) per | ||
| 919 | -/// macroblock, which `filter_frame` consumes over its existing PRECOMPUTED | ||
| 920 | -/// path, collapsing the per-MB derivation machinery in the hot loop entirely. | ||
| 921 | -/// | ||
| 922 | -/// Byte-identical by the existing oracle chain: `derive_mb_records` is | ||
| 923 | -/// `derive_mb_packed`'s own core (pinned to the tile twin by | ||
| 924 | -/// `packed_matches_tile`), and the precomputed consumer path is pinned by the | ||
| 925 | -/// encoder's use of it. `flat_inter` loop-skips are subsumed by the stored | ||
| 926 | -/// zeros + the consuming loops' all-zero early-outs (documented there). | ||
| 927 | -pub fn precompute_bs_frame(info: &BlockInfo, mb_w: usize, mb_h: usize, out: &mut Vec<MbBs>) { | ||
| 928 | - let has1 = !info.ref_id1.is_empty(); | ||
| 929 | - out.clear(); | ||
| 930 | - out.reserve(mb_w * mb_h); | ||
| 931 | - let mut prev_row: Vec<MbPack> = Vec::with_capacity(mb_w); | ||
| 932 | - let mut cur_row: Vec<MbPack> = Vec::with_capacity(mb_w); | ||
| 933 | - for mb_y in 0..mb_h { | ||
| 934 | - cur_row.clear(); | ||
| 935 | - for mb_x in 0..mb_w { | ||
| 936 | - cur_row.push(pack_mb(info, has1, mb_x, mb_y)); | ||
| 937 | - let cur = &cur_row[mb_x]; | ||
| 938 | - let left = if mb_x > 0 { Some(&cur_row[mb_x - 1]) } else { None }; | ||
| 939 | - let top = if mb_y > 0 { Some(&prev_row[mb_x]) } else { None }; | ||
| 940 | - let mb_t8 = !info.t8x8.is_empty() && info.t8x8[mb_y * mb_w + mb_x]; | ||
| 941 | - let (mut bv, mut bh) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); | ||
| 942 | - derive_mb_records(cur, left, top, mb_t8, &mut bv, &mut bh); | ||
| 943 | - let mut m = MbBs { v: [[0; 4]; 4], h: [[0; 4]; 4] }; | ||
| 944 | - for e in 0..4 { | ||
| 945 | - for sg in 0..4 { | ||
| 946 | - m.v[e][sg] = bv[e][sg] as u8; | ||
| 947 | - m.h[e][sg] = bh[e][sg] as u8; | ||
| 948 | - } | ||
| 949 | - } | ||
| 950 | - out.push(m); | ||
| 951 | - } | ||
| 952 | - std::mem::swap(&mut prev_row, &mut cur_row); | ||
| 953 | - } | ||
| 954 | -} | ||
| 955 | - | ||
| 956 | -thread_local! { | ||
| 957 | - /// Recycled `pack_frame` buffer (~1.1 MB at 720p), `Cell` so `filter_frame` | ||
| 958 | - /// can `take`/`set` without holding a borrow across its whole MB loop. | ||
| 959 | - static PACK_SCRATCH: core::cell::Cell<Vec<MbPack>> = const { core::cell::Cell::new(Vec::new()) }; | ||
| 960 | -} | ||
| 961 | - | ||
| 962 | -/// THE KERNEL INTERFACE — the whole motion half of the derivation as two bitmasks. | ||
| 963 | -/// | ||
| 964 | -/// `bit k` of the returned pair answers "does block `k` differ in motion from its | ||
| 965 | -/// LEFT neighbour block `k-1`" and "...from its ABOVE neighbour block `k-4`", using | ||
| 966 | -/// the §8.7.2.1 rule that `bs_inter` applies per edge: | ||
| 967 | -/// | ||
| 968 | -/// ```text | ||
| 969 | -/// differs(a,b) = ref[a] != ref[b] || (ref[a] != NO_REF && (|dmvx| >= 4 || |dmvy| >= 4)) | ||
| 970 | -/// ``` | ||
| 971 | -/// | ||
| 972 | -/// Bits at `k % 4 == 0` (left) and `k < 4` (up) are DON'T-CARE: those edges are | ||
| 973 | -/// macroblock edges, derived separately against the neighbouring record. That is not | ||
| 974 | -/// an accident of convenience — it is what makes the SIMD twin cheap, because the | ||
| 975 | -/// lane positions a within-128-bit-lane shift corrupts are exactly those positions. | ||
| 976 | -/// | ||
| 977 | -/// Collapsing the derivation to masks is the point of the packed layout: the 24 | ||
| 978 | -/// internal edges stop being 24 branchy `bs_inter` calls and become bit tests against | ||
| 979 | -/// these masks OR'd with `nnz_mask`, which is the form `deblock_strength_avx2` works in. | ||
| 980 | -/// Scalar twin of the uniform-motion test — the oracle, and the path on any CPU | ||
| 981 | -/// without AVX2. Short-circuits, which is why the SIMD twin's win concentrates on | ||
| 982 | -/// UNIFORM macroblocks (where this walks all 15 comparisons). | ||
| 983 | -#[inline] | ||
| 984 | -pub fn mb_uniform_scalar(p: &MbPack) -> bool { | ||
| 985 | - p.inter | ||
| 986 | - && (1..16).all(|k| { | ||
| 987 | - p.ref_id[k] == p.ref_id[0] | ||
| 988 | - && p.mvx[k] == p.mvx[0] | ||
| 989 | - && p.mvy[k] == p.mvy[0] | ||
| 990 | - && p.ref1[k] == p.ref1[0] | ||
| 991 | - && p.mvx1[k] == p.mvx1[0] | ||
| 992 | - && p.mvy1[k] == p.mvy1[0] | ||
| 993 | - }) | ||
| 994 | -} | ||
| 995 | - | ||
| 996 | -/// Dispatcher: AVX2 when present, scalar otherwise. `p.inter` is a per-macroblock | ||
| 997 | -/// flag and is checked here, so the kernel only ever answers the 16-lane question. | ||
| 998 | -#[inline] | ||
| 999 | -pub fn mb_uniform(p: &MbPack) -> bool { | ||
| 1000 | - #[cfg(all(target_arch = "x86_64", feature = "asm"))] | ||
| 1001 | - if p.inter { | ||
| 1002 | - if let Some(u) = | ||
| 1003 | - rusty_h264_accel::mb_uniform(&p.mvx, &p.mvy, &p.ref_id, &p.mvx1, &p.mvy1, &p.ref1) | ||
| 1004 | - { | ||
| 1005 | - return u; | ||
| 1006 | - } | ||
| 1007 | - } | ||
| 1008 | - mb_uniform_scalar(p) | ||
| 1009 | -} | ||
| 1010 | - | ||
| 1011 | -#[inline] | ||
| 1012 | -pub fn bs_motion_masks_scalar(p: &MbPack) -> (u16, u16) { | ||
| 1013 | - let differs = |a: usize, b: usize| -> bool { pk_differs(p, a, p, b) }; | ||
| 1014 | - let (mut left, mut up) = (0u16, 0u16); | ||
| 1015 | - for k in 0..16usize { | ||
| 1016 | - if k % 4 != 0 && differs(k, k - 1) { | ||
| 1017 | - left |= 1 << k; | ||
| 1018 | - } | ||
| 1019 | - if k >= 4 && differs(k, k - 4) { | ||
| 1020 | - up |= 1 << k; | ||
| 1021 | - } | ||
| 1022 | - } | ||
| 1023 | - // Don't-care bits are already zero here by construction; the masks are spelled out | ||
| 1024 | - // so the SIMD twin (which must clear them explicitly) is comparable on the FULL u16. | ||
| 1025 | - (left & 0xEEEE, up & 0xFFF0) | ||
| 1026 | -} | ||
| 1027 | - | ||
| 1028 | -/// Dispatcher: the AVX2 twin when the CPU has it, the scalar oracle otherwise. | ||
| 1029 | -/// | ||
| 1030 | -/// The scalar version stays the default on any non-AVX2 CPU and remains the | ||
| 1031 | -/// reference the SIMD twin is gated against — it is never deleted. | ||
| 1032 | -#[inline] | ||
| 1033 | -pub fn bs_motion_masks(p: &MbPack) -> (u16, u16) { | ||
| 1034 | - #[cfg(feature = "profile")] | ||
| 1035 | - { | ||
| 1036 | - use std::sync::atomic::Ordering::Relaxed; | ||
| 1037 | - census::MASKS_CALLS.fetch_add(1, Relaxed); | ||
| 1038 | - if p.l1_used == 0 { | ||
| 1039 | - census::MASKS_KERNEL.fetch_add(1, Relaxed); | ||
| 1040 | - } else { | ||
| 1041 | - census::MASKS_L1.fetch_add(1, Relaxed); | ||
| 1042 | - } | ||
| 1043 | - } | ||
| 1044 | - #[cfg(all(target_arch = "x86_64", feature = "asm"))] | ||
| 1045 | - if p.l1_used == 0 { | ||
| 1046 | - // Single-list fast kernel: all of P and uni-L0 B macroblocks. | ||
| 1047 | - if let Some(m) = rusty_h264_accel::bs_motion_masks(&p.mvx, &p.mvy, &p.ref_id, NO_REF) { | ||
| 1048 | - return m; | ||
| 1049 | - } | ||
| 1050 | - } else { | ||
| 1051 | - // TWO-LIST kernel (WHYS Part 16's named lever): the §8.7.2.1 | ||
| 1052 | - // set-matching rule vectorized, so B macroblocks with List-1 slots no | ||
| 1053 | - // longer fall to the scalar per-edge walk. Gated bit-exact against the | ||
| 1054 | - // scalar twin by `bs_motion_masks_two_list_matches_scalar` (accel) and | ||
| 1055 | - // the unmasked runtime oracle (`RS_H264_VERIFY_PACKED=1`). | ||
| 1056 | - if let Some(m) = rusty_h264_accel::bs_motion_masks_two_list( | ||
| 1057 | - &p.mvx, &p.mvy, &p.ref_id, &p.mvx1, &p.mvy1, &p.ref1, NO_REF, | ||
| 1058 | - ) { | ||
| 1059 | - return m; | ||
| 1060 | - } | ||
| 1061 | - } | ||
| 1062 | - bs_motion_masks_scalar(p) | ||
| 1063 | -} | ||
| 1064 | - | ||
| 1065 | -/// The §8.7.2.1 motion test over packed operands — the EXACT twin of `bs1_tile`, | ||
| 1066 | -/// including the two-list set-matching rule (which is order-independent: a block pair | ||
| 1067 | -/// whose two reference pictures match after a SWAP is not "different motion"). | ||
| 1068 | -/// | ||
| 1069 | -/// The single-list fast path fires whenever neither side carries a List-1 slot, which | ||
| 1070 | -/// is all of P and most uni-predicted B blocks; only the remainder pays the set match. | ||
| 1071 | -#[inline] | ||
| 1072 | -fn pk_differs(p: &MbPack, pk: usize, q: &MbPack, qk: usize) -> bool { | ||
| 1073 | - let p_has1 = p.ref1[pk] != NO_REF; | ||
| 1074 | - let q_has1 = q.ref1[qk] != NO_REF; | ||
| 1075 | - if !p_has1 && !q_has1 { | ||
| 1076 | - let far = ((p.mvx[pk] - q.mvx[qk]).abs() >= 4) | ((p.mvy[pk] - q.mvy[qk]).abs() >= 4); | ||
| 1077 | - return (p.ref_id[pk] != q.ref_id[qk]) | ((p.ref_id[pk] != NO_REF) & far); | ||
| 1078 | - } | ||
| 1079 | - // Collect the USED reference slots, exactly as `bs1_tile::used` does. | ||
| 1080 | - let used = |b: &MbPack, k: usize| { | ||
| 1081 | - let mut v = [(0i32, (0i32, 0i32)); 2]; | ||
| 1082 | - let mut n = 0usize; | ||
| 1083 | - if b.ref_id[k] != NO_REF { | ||
| 1084 | - v[n] = (b.ref_id[k], (b.mvx[k] as i32, b.mvy[k] as i32)); | ||
| 1085 | - n += 1; | ||
| 1086 | - } | ||
| 1087 | - if b.ref1[k] != NO_REF { | ||
| 1088 | - v[n] = (b.ref1[k], (b.mvx1[k] as i32, b.mvy1[k] as i32)); | ||
| 1089 | - n += 1; | ||
| 1090 | - } | ||
| 1091 | - (v, n) | ||
| 1092 | - }; | ||
| 1093 | - let (pv, pn) = used(p, pk); | ||
| 1094 | - let (qv, qn) = used(q, qk); | ||
| 1095 | - if pn != qn { | ||
| 1096 | - return true; | ||
| 1097 | - } | ||
| 1098 | - let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4; | ||
| 1099 | - match pn { | ||
| 1100 | - 0 => false, | ||
| 1101 | - 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1), | ||
| 1102 | - _ => { | ||
| 1103 | - let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1); | ||
| 1104 | - let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1); | ||
| 1105 | - if pv[0].0 == pv[1].0 { | ||
| 1106 | - qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap) | ||
| 1107 | - } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 { | ||
| 1108 | - !direct | ||
| 1109 | - } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 { | ||
| 1110 | - !swap | ||
| 1111 | - } else { | ||
| 1112 | - true | ||
| 1113 | - } | ||
| 1114 | - } | ||
| 1115 | - } | ||
| 1116 | -} | ||
| 1117 | - | ||
| 1118 | -#[inline] | ||
| 1119 | -fn pk_nz(p: &MbPack, k: usize) -> bool { | ||
| 1120 | - (p.nnz_mask >> k) & 1 != 0 | ||
| 1121 | -} | ||
| 1122 | - | ||
| 1123 | -/// `bs_inter` over packed operands — both sides inter, so 3 and 4 are unreachable. | ||
| 1124 | -/// Mirrors `bs1_tile`'s single-list fast path exactly. | ||
| 1125 | -#[inline] | ||
| 1126 | -fn pk_bs_inter(p: &MbPack, pk: usize, q: &MbPack, qk: usize) -> i32 { | ||
| 1127 | - if pk_nz(p, pk) | pk_nz(q, qk) { | ||
| 1128 | - return 2; | ||
| 1129 | - } | ||
| 1130 | - let (pr, qr) = (p.ref_id[pk], q.ref_id[qk]); | ||
| 1131 | - let _ = (pr, qr); | ||
| 1132 | - pk_differs(p, pk, q, qk) as i32 | ||
| 1133 | -} | ||
| 1134 | - | ||
| 1135 | -/// Derive one macroblock's strengths from PACKED records — the byte-identical twin of | ||
| 1136 | -/// `derive_mb_bs`, pinned against it by `packed_matches_tile`. | ||
| 1137 | -pub fn derive_mb_packed( | ||
| 1138 | - packs: &[MbPack], | ||
| 1139 | - mb_w: usize, | ||
| 1140 | - mb_x: usize, | ||
| 1141 | - mb_y: usize, | ||
| 1142 | - mb_t8: bool, | ||
| 1143 | - bs_v: &mut [[i32; 4]; 4], | ||
| 1144 | - bs_h: &mut [[i32; 4]; 4], | ||
| 1145 | -) -> bool { | ||
| 1146 | - let cur = &packs[mb_y * mb_w + mb_x]; | ||
| 1147 | - let left = if mb_x > 0 { Some(&packs[mb_y * mb_w + mb_x - 1]) } else { None }; | ||
| 1148 | - let top = if mb_y > 0 { Some(&packs[(mb_y - 1) * mb_w + mb_x]) } else { None }; | ||
| 1149 | - derive_mb_records(cur, left, top, mb_t8, bs_v, bs_h) | ||
| 1150 | -} | ||
| 1151 | - | ||
| 1152 | -/// The record-based core of [`derive_mb_packed`]: derive one macroblock's | ||
| 1153 | -/// strengths from ITS OWN record plus the left/top neighbours' — the shape the | ||
| 1154 | -/// rolling-window precompute pass ([`precompute_bs_frame`]) needs, where only | ||
| 1155 | -/// two rows of records exist at a time. | ||
| 1156 | -pub fn derive_mb_records( | ||
| 1157 | - cur: &MbPack, | ||
| 1158 | - left: Option<&MbPack>, | ||
| 1159 | - top: Option<&MbPack>, | ||
| 1160 | - mb_t8: bool, | ||
| 1161 | - bs_v: &mut [[i32; 4]; 4], | ||
| 1162 | - bs_h: &mut [[i32; 4]; 4], | ||
| 1163 | -) -> bool { | ||
| 1164 | - let cur_intra = !cur.inter; | ||
| 1165 | - | ||
| 1166 | - // Both predicates from the packed record: uniform motion needs no neighbour, and | ||
| 1167 | - // "no coefficients" is `nnz_mask == 0` — a single register test replacing a | ||
| 1168 | - // 16-block walk. | ||
| 1169 | - // | ||
| 1170 | - // REFUTED (WHYS Part 16, z=-2.11 REGRESSION, reverted): deriving uniformity | ||
| 1171 | - // from `bs_motion_masks` to save "the second kernel call". The two calls are | ||
| 1172 | - // ASYMMETRIC: this one is a cheap AVX2 compare-to-block-0 that handles | ||
| 1173 | - // two-list B data in vector code, while the masks kernel falls to the SCALAR | ||
| 1174 | - // set-matching walk whenever `l1_used != 0` — most B inter MBs. The | ||
| 1175 | - // population reaching this function on B frames is uniform-heavy, so the | ||
| 1176 | - // "fusion" replaced their one cheap vector call with an expensive scalar | ||
| 1177 | - // walk. Do not retry without making the masks kernel two-list-capable first. | ||
| 1178 | - let uniform = mb_uniform(cur); | ||
| 1179 | - let flat_inter = uniform && cur.nnz_mask == 0; | ||
| 1180 | - | ||
| 1181 | - if let Some(l) = left { | ||
| 1182 | - bs_v[0] = if cur_intra || !l.inter { | ||
| 1183 | - [4; 4] | ||
| 1184 | - } else { | ||
| 1185 | - std::array::from_fn(|seg| pk_bs_inter(l, seg * 4 + 3, cur, seg * 4)) | ||
| 1186 | - }; | ||
| 1187 | - } | ||
| 1188 | - if let Some(t) = top { | ||
| 1189 | - bs_h[0] = if cur_intra || !t.inter { | ||
| 1190 | - [4; 4] | ||
| 1191 | - } else { | ||
| 1192 | - std::array::from_fn(|seg| pk_bs_inter(t, 12 + seg, cur, seg)) | ||
| 1193 | - }; | ||
| 1194 | - } | ||
| 1195 | - | ||
| 1196 | - if flat_inter { | ||
| 1197 | - return true; // internal strengths are 0 by construction | ||
| 1198 | - } | ||
| 1199 | - // Only the general path consumes these; intra fills constants and uniform motion | ||
| 1200 | - // reads coefficients alone. | ||
| 1201 | - let masks = if cur_intra || uniform { (0, 0) } else { bs_motion_masks(cur) }; | ||
| 1202 | - for be in 1..4usize { | ||
| 1203 | - if mb_t8 && (be == 1 || be == 3) { | ||
| 1204 | - continue; | ||
| 1205 | - } | ||
| 1206 | - if cur_intra { | ||
| 1207 | - bs_v[be] = [3; 4]; | ||
| 1208 | - bs_h[be] = [3; 4]; | ||
| 1209 | - } else if uniform { | ||
| 1210 | - // Coefficients alone; the whole edge group is a shift-and-or on the mask. | ||
| 1211 | - bs_v[be] = std::array::from_fn(|seg| { | ||
| 1212 | - 2 * (pk_nz(cur, seg * 4 + be) | pk_nz(cur, seg * 4 + be - 1)) as i32 | ||
| 1213 | - }); | ||
| 1214 | - bs_h[be] = std::array::from_fn(|seg| { | ||
| 1215 | - 2 * (pk_nz(cur, be * 4 + seg) | pk_nz(cur, (be - 1) * 4 + seg)) as i32 | ||
| 1216 | - }); | ||
| 1217 | - } else { | ||
| 1218 | - // The general path, now pure bit tests: coefficients from `nnz_mask`, | ||
| 1219 | - // motion from the precomputed masks. No per-edge branching at all. | ||
| 1220 | - let (left, up) = masks; | ||
| 1221 | - bs_v[be] = std::array::from_fn(|seg| { | ||
| 1222 | - let k = seg * 4 + be; | ||
| 1223 | - if pk_nz(cur, k) | pk_nz(cur, k - 1) { | ||
| 1224 | - 2 | ||
| 1225 | - } else { | ||
| 1226 | - ((left >> k) & 1) as i32 | ||
| 1227 | - } | ||
| 1228 | - }); | ||
| 1229 | - bs_h[be] = std::array::from_fn(|seg| { | ||
| 1230 | - let k = be * 4 + seg; | ||
| 1231 | - if pk_nz(cur, k) | pk_nz(cur, k - 4) { | ||
| 1232 | - 2 | ||
| 1233 | - } else { | ||
| 1234 | - ((up >> k) & 1) as i32 | ||
| 1235 | - } | ||
| 1236 | - }); | ||
| 1237 | - } | ||
| 1238 | - } | ||
| 1239 | - false | ||
| 1240 | -} | ||
| 1241 | - | ||
| 1242 | -/// ONE walk of the macroblock's own 16 blocks yielding BOTH predicates the | ||
| 1243 | -/// derivation needs: `(uniform_motion, flat_inter)`. | ||
| 1244 | -/// | ||
| 1245 | -/// They are the same walk, by construction: | ||
| 1246 | -/// ```text | ||
| 1247 | -/// uniform_motion = b0.inter AND every block { inter AND same_motion(b0) } | ||
| 1248 | -/// flat_inter = uniform_motion AND no block carries coefficients | ||
| 1249 | -/// ``` | ||
| 1250 | -/// They used to be two independent 16-block scans — and the `uniform_motion` one | ||
| 1251 | -/// ran BEFORE `derive_mb_bs`'s `if flat_inter { return }` early-out, so every Skip | ||
| 1252 | -/// macroblock paid a full 16-block × 6-compare motion scan whose result was then | ||
| 1253 | -/// discarded. The MB-kind census measures Skip at 36.4% (CAVLC) / 65.0% (main) / | ||
| 1254 | -/// 57.8% (high) of macroblocks, so that dead scan ran on most of the corpus. | ||
| 1255 | -/// | ||
| 1256 | -/// Byte-identical to the two-scan form: when the walk breaks early both | ||
| 1257 | -/// predicates are false, exactly as both original `.all()` chains would be. | ||
| 1258 | -#[inline] | ||
| 1259 | -fn scan_uniform_flat(tile: &Tile) -> (bool, bool) { | ||
| 1260 | - let b0 = &tile[1][1]; | ||
| 1261 | - if !b0.inter { | ||
| 1262 | - return (false, false); // intra MB — neither predicate applies | ||
| 1263 | - } | ||
| 1264 | - let mut any_nz = false; | ||
| 1265 | - for r in 1..5 { | ||
| 1266 | - for c in 1..5 { | ||
| 1267 | - let b = &tile[r][c]; | ||
| 1268 | - #[cfg(feature = "profile")] | ||
| 1269 | - census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 1270 | - if !b.inter || !b.same_motion(b0) { | ||
| 1271 | - return (false, false); | ||
| 1272 | - } | ||
| 1273 | - any_nz |= b.nz; | ||
| 1274 | - } | ||
| 1275 | - } | ||
| 1276 | - (true, !any_nz) | ||
| 1277 | -} | ||
| 1278 | - | ||
| 1279 | -/// The pre-fusion arm, kept verbatim as the measurement baseline AND the oracle. | ||
| 1280 | -#[inline] | ||
| 1281 | -fn scan_two_pass(tile: &Tile) -> (bool, bool) { | ||
| 1282 | - let b0 = &tile[1][1]; | ||
| 1283 | - let flat = b0.inter | ||
| 1284 | - && (1..5).all(|r| { | ||
| 1285 | - (1..5).all(|c| { | ||
| 1286 | - let b = &tile[r][c]; | ||
| 1287 | - #[cfg(feature = "profile")] | ||
| 1288 | - census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 1289 | - b.inter && !b.nz && b.same_motion(b0) | ||
| 1290 | - }) | ||
| 1291 | - }); | ||
| 1292 | - let uniform = b0.inter | ||
| 1293 | - && (1..5).all(|r| { | ||
| 1294 | - (1..5).all(|c| { | ||
| 1295 | - #[cfg(feature = "profile")] | ||
| 1296 | - census::PRED_VISITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 1297 | - tile[r][c].inter && tile[r][c].same_motion(b0) | ||
| 1298 | - }) | ||
| 1299 | - }); | ||
| 1300 | - (uniform, flat) | ||
| 1301 | -} | ||
| 1302 | - | ||
| 1303 | -/// MEASUREMENT SWITCH — `RS_H264_BS_TWOPASS=1` restores the two independent | ||
| 1304 | -/// scans. Both arms live in ONE binary so a bench can alternate them under one | ||
| 1305 | -/// thermal state; separate builds on this box drift ~20% run-to-run, which cannot | ||
| 1306 | -/// resolve an effect this size. Read once; the branch predicts perfectly. | ||
| 1307 | -static BS_TWOPASS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); | ||
| 1308 | - | ||
| 1309 | -/// Resolve the arm ONCE — hoist this out of any per-macroblock path. | ||
| 1310 | -/// | ||
| 1311 | -/// It used to be read inside `scan_predicates`, i.e. an atomic load plus a branch | ||
| 1312 | -/// on every one of 6.48M macroblocks, present in BOTH arms. That is measurement | ||
| 1313 | -/// overhead added in order to take a ~2% measurement, and it is the same mistake | ||
| 1314 | -/// this workspace has recorded before (a dedup that replaced cheap work with a | ||
| 1315 | -/// dependent load + branch and went backwards). Resolve per frame, pass the bool. | ||
| 1316 | -fn bs_twopass() -> bool { | ||
| 1317 | - use std::sync::atomic::Ordering; | ||
| 1318 | - match BS_TWOPASS.load(Ordering::Relaxed) { | ||
| 1319 | - 1 => true, | ||
| 1320 | - 2 => false, | ||
| 1321 | - _ => { | ||
| 1322 | - let on = std::env::var_os("RS_H264_BS_TWOPASS").is_some_and(|v| v != "0"); | ||
| 1323 | - BS_TWOPASS.store(if on { 1 } else { 2 }, Ordering::Relaxed); | ||
| 1324 | - on | ||
| 1325 | - } | ||
| 1326 | - } | ||
| 1327 | -} | ||
| 1328 | - | ||
| 1329 | -/// MEASUREMENT SWITCH — `RS_H264_NO_MBKIND=1` ignores producer-supplied classes and | ||
| 1330 | -/// forces the blind gather for every macroblock, so the kind-aware brick can be | ||
| 1331 | -/// alternated against its own baseline inside ONE binary. Resolved ONCE per frame by | ||
| 1332 | -/// the caller and passed down: reading it per macroblock would put an atomic load and | ||
| 1333 | -/// a branch in both arms of the very thing being measured (see `bs_twopass`). | ||
| 1334 | -static NO_MBKIND: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); | ||
| 1335 | - | ||
| 1336 | -/// CORRECTNESS GATE — `RS_H264_VERIFY_MBKIND=1` derives EVERY kind-classified | ||
| 1337 | -/// macroblock BOTH ways and asserts they agree. This is the oracle for the whole | ||
| 1338 | -/// brick: a producer that mislabels a macroblock (say, calling a `B_Skip` a `Skip` | ||
| 1339 | -/// when direct-derived motion differs per 4x4) changes strengths silently, and the | ||
| 1340 | -/// byte-identical corpus gate can only tell you THAT something broke, not where. | ||
| 1341 | -/// Run it over the corpus once per producer change; it is far too slow to ship. | ||
| 1342 | -fn verify_kind() -> bool { | ||
| 1343 | - use std::sync::atomic::Ordering; | ||
| 1344 | - static V: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); | ||
| 1345 | - match V.load(Ordering::Relaxed) { | ||
| 1346 | - 1 => true, | ||
| 1347 | - 2 => false, | ||
| 1348 | - _ => { | ||
| 1349 | - let on = std::env::var_os("RS_H264_VERIFY_MBKIND").is_some_and(|v| v != "0"); | ||
| 1350 | - V.store(if on { 1 } else { 2 }, Ordering::Relaxed); | ||
| 1351 | - on | ||
| 1352 | - } | ||
| 1353 | - } | ||
| 1354 | -} | ||
| 1355 | - | ||
| 1356 | -/// Compare kind-derived against blind-derived strengths, looking ONLY at the edges | ||
| 1357 | -/// the consuming loops actually read. `derive_mb_kind` fills internal groups 1 and 3 | ||
| 1358 | -/// even for an 8x8-transform macroblock (whose consumers skip them), so a raw | ||
| 1359 | -/// array compare would report a difference that cannot reach a pixel. | ||
| 1360 | -#[allow(clippy::too_many_arguments)] | ||
| 1361 | -fn verify_kind_matches_blind( | ||
| 1362 | - info: &BlockInfo, | ||
| 1363 | - mb_x: usize, | ||
| 1364 | - mb_y: usize, | ||
| 1365 | - mb_t8: bool, | ||
| 1366 | - kind: MbKind, | ||
| 1367 | - flat_inter: bool, | ||
| 1368 | - bs_v: &[[i32; 4]; 4], | ||
| 1369 | - bs_h: &[[i32; 4]; 4], | ||
| 1370 | -) { | ||
| 1371 | - let tile = gather_tile(info, mb_x, mb_y); | ||
| 1372 | - let (u, f) = scan_uniform_flat(&tile); | ||
| 1373 | - let (mut vv, mut vh) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); | ||
| 1374 | - derive_mb_bs(&tile, mb_x, mb_y, f, u, mb_t8, &mut vv, &mut vh); | ||
| 1375 | - assert_eq!( | ||
| 1376 | - flat_inter, f, | ||
| 1377 | - "MB ({mb_x},{mb_y}) kind {kind:?}: flat_inter {flat_inter} but blind derived {f}" | ||
| 1378 | - ); | ||
| 1379 | - for be in 0..4usize { | ||
| 1380 | - if be == 0 { | ||
| 1381 | - if mb_x > 0 { | ||
| 1382 | - assert_eq!(bs_v[0], vv[0], "MB ({mb_x},{mb_y}) kind {kind:?}: left MB edge"); | ||
| 1383 | - } | ||
| 1384 | - if mb_y > 0 { | ||
| 1385 | - assert_eq!(bs_h[0], vh[0], "MB ({mb_x},{mb_y}) kind {kind:?}: top MB edge"); | ||
| 1386 | - } | ||
| 1387 | - continue; | ||
| 1388 | - } | ||
| 1389 | - if flat_inter || (mb_t8 && (be == 1 || be == 3)) { | ||
| 1390 | - continue; // consumers skip these entirely | ||
| 1391 | - } | ||
| 1392 | - assert_eq!(bs_v[be], vv[be], "MB ({mb_x},{mb_y}) kind {kind:?}: v internal edge {be}"); | ||
| 1393 | - assert_eq!(bs_h[be], vh[be], "MB ({mb_x},{mb_y}) kind {kind:?}: h internal edge {be}"); | ||
| 1394 | - } | ||
| 1395 | -} | ||
| 1396 | - | ||
| 1397 | -/// OPT-IN — `RS_H264_BS_PACKED=1` derives strengths from the packed per-macroblock | ||
| 1398 | -/// records instead of the strided gather. Default OFF: the ceiling probe measured the | ||
| 1399 | -/// direct memory saving at only ~19 ns/MB of a ~400 ns/MB derivation, so this exists | ||
| 1400 | -/// as the ENABLER for a vectorised kernel, not as a memory win in its own right. | ||
| 1401 | -/// Resolved once per frame and passed down, never read per macroblock. | ||
| 1402 | -/// CORRECTNESS PROBE — `RS_H264_VERIFY_PACKED=1` derives every packed macroblock BOTH | ||
| 1403 | -/// ways on real bitstreams and reports the first divergence with its coordinates. The | ||
| 1404 | -/// unit oracle passes on a synthetic grid; the corpus does not. This names WHERE. | ||
| 1405 | -fn verify_packed() -> bool { | ||
| 1406 | - use std::sync::atomic::Ordering; | ||
| 1407 | - static V: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); | ||
| 1408 | - match V.load(Ordering::Relaxed) { | ||
| 1409 | - 1 => true, | ||
| 1410 | - 2 => false, | ||
| 1411 | - _ => { | ||
| 1412 | - let on = std::env::var_os("RS_H264_VERIFY_PACKED").is_some_and(|v| v != "0"); | ||
| 1413 | - V.store(if on { 1 } else { 2 }, Ordering::Relaxed); | ||
| 1414 | - on | ||
| 1415 | - } | ||
| 1416 | - } | ||
| 1417 | -} | ||
| 1418 | - | ||
| 1419 | -fn bs_packed_on() -> bool { | ||
| 1420 | - use std::sync::atomic::Ordering; | ||
| 1421 | - static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); | ||
| 1422 | - match ON.load(Ordering::Relaxed) { | ||
| 1423 | - 1 => true, | ||
| 1424 | - 2 => false, | ||
| 1425 | - _ => { | ||
| 1426 | - // DEFAULT ON since 2026-08-02. Polarity written as an explicit opt-OUT so | ||
| 1427 | - // it is a decision, not a flag accident: an ABSENT variable means the fast | ||
| 1428 | - // path, and only the literal "0" restores the blind gather. | ||
| 1429 | - // | ||
| 1430 | - // Promoted on three independent interleaved runs (main corpus, 1800 frames | ||
| 1431 | - // 720p, pinned, CPU time, ABBA), each with a null arm in the same session: | ||
| 1432 | - // packed layout alone median +1.7% 8/9, z = 2.33 | ||
| 1433 | - // + both AVX2 kernels median +6.7% 11/15, z = 1.81 | ||
| 1434 | - // + both AVX2 kernels median +3.3% 12/15, z = 2.32 <- deciding run | ||
| 1435 | - // null arms 1.000 / 1.039 z = -1.13 / 0.38 | ||
| 1436 | - // The two full-stack runs pool to 23/30, z = 2.92. | ||
| 1437 | - // | ||
| 1438 | - // Honest shape: single-run medians ranged 1.7-6.7% because this box drifts, | ||
| 1439 | - // so the WIN RATE carries the verdict; the median is the effect-size | ||
| 1440 | - // estimate, not the proof. | ||
| 1441 | - let off = std::env::var_os("RS_H264_BS_PACKED").is_some_and(|v| v == "0"); | ||
| 1442 | - ON.store(if off { 2 } else { 1 }, Ordering::Relaxed); | ||
| 1443 | - !off | ||
| 1444 | - } | ||
| 1445 | - } | ||
| 1446 | -} | ||
| 1447 | - | ||
| 1448 | -fn kind_gate_off() -> bool { | ||
| 1449 | - use std::sync::atomic::Ordering; | ||
| 1450 | - match NO_MBKIND.load(Ordering::Relaxed) { | ||
| 1451 | - 1 => true, | ||
| 1452 | - 2 => false, | ||
| 1453 | - _ => { | ||
| 1454 | - let off = std::env::var_os("RS_H264_NO_MBKIND").is_some_and(|v| v != "0"); | ||
| 1455 | - NO_MBKIND.store(if off { 1 } else { 2 }, Ordering::Relaxed); | ||
| 1456 | - off | ||
| 1457 | - } | ||
| 1458 | - } | ||
| 1459 | -} | ||
| 1460 | - | ||
| 1461 | -#[inline] | ||
| 1462 | -fn scan_predicates(tile: &Tile, two_pass: bool) -> (bool, bool) { | ||
| 1463 | - if two_pass { | ||
| 1464 | - scan_two_pass(tile) | ||
| 1465 | - } else { | ||
| 1466 | - scan_uniform_flat(tile) | ||
| 1467 | - } | ||
| 1468 | -} | ||
| 1469 | - | ||
| 1470 | -pub fn derive_mb(info: &BlockInfo, mb_x: usize, mb_y: usize, mb_t8: bool) -> MbBs { | ||
| 1471 | - let tile = gather_tile(info, mb_x, mb_y); | ||
| 1472 | - let (uniform_motion, flat_inter) = scan_predicates(&tile, bs_twopass()); | ||
| 1473 | - let (mut bs_v, mut bs_h) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); | ||
| 1474 | - derive_mb_bs(&tile, mb_x, mb_y, flat_inter, uniform_motion, mb_t8, &mut bs_v, &mut bs_h); | ||
| 1475 | - let pack = |a: [[i32; 4]; 4]| a.map(|e| e.map(|x| x as u8)); | ||
| 1476 | - MbBs { v: pack(bs_v), h: pack(bs_h) } | ||
| 1477 | -} | ||
| 1478 | - | ||
| 1479 | -/// The 5×5 neighbourhood an MB's edges can reach: row/col 0 are the top and left | ||
| 1480 | -/// neighbour blocks, rows/cols 1..=4 the MB's own 4×4 grid. Entries outside the | ||
| 1481 | -/// picture stay `Default` and are never read (the frame-edge groups are skipped). | ||
| 1482 | -type Tile = [[Blk; 5]; 5]; | ||
| 1483 | - | ||
| 1484 | -/// Gather the tile for macroblock (`mb_x`, `mb_y`). | ||
| 1485 | -fn gather_tile(info: &BlockInfo, mb_x: usize, mb_y: usize) -> Tile { | ||
| 1486 | - let mut t: Tile = Default::default(); | ||
| 1487 | - let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 1488 | - // The MB's own blocks: four contiguous runs of four. | ||
| 1489 | - for r in 0..4 { | ||
| 1490 | - let row = (by0 + r) * info.w4 + bx0; | ||
| 1491 | - for c in 0..4 { | ||
| 1492 | - t[r + 1][c + 1] = Blk::load(info, row + c); | ||
| 1493 | - } | ||
| 1494 | - } | ||
| 1495 | - if mb_x > 0 { | ||
| 1496 | - for r in 0..4 { | ||
| 1497 | - t[r + 1][0] = Blk::load(info, (by0 + r) * info.w4 + bx0 - 1); | ||
| 1498 | - } | ||
| 1499 | - } | ||
| 1500 | - if mb_y > 0 { | ||
| 1501 | - let row = (by0 - 1) * info.w4 + bx0; | ||
| 1502 | - for c in 0..4 { | ||
| 1503 | - t[0][c + 1] = Blk::load(info, row + c); | ||
| 1504 | - } | ||
| 1505 | - } | ||
| 1506 | - // `mb_type` is a per-macroblock syntax element, so every 4×4 block of a | ||
| 1507 | - // macroblock shares its intra/inter status. `derive_mb_bs` depends on this to | ||
| 1508 | - // replace per-edge intra tests with per-macroblock constant fills. | ||
| 1509 | - debug_assert!( | ||
| 1510 | - (1..5).all(|r| (1..5).all(|c| t[r][c].inter == t[1][1].inter)), | ||
| 1511 | - "macroblock ({mb_x},{mb_y}) mixes intra and inter 4x4 blocks" | ||
| 1512 | - ); | ||
| 1513 | - t | ||
| 1514 | -} | ||
| 1515 | - | ||
| 1516 | -/// Selects the boundary-strength derivation. Default (and shipped path) is the | ||
| 1517 | -/// per-MB TILE; `RS_H264_DEBLOCK_BRANCHY=1` restores the original per-edge | ||
| 1518 | -/// derivation straight off the frame arrays. | ||
| 1519 | -/// | ||
| 1520 | -/// This exists so both arms live in ONE binary and a benchmark can alternate | ||
| 1521 | -/// them under the same thermal state — comparing separate builds on this machine | ||
| 1522 | -/// has ~20% run-to-run drift, which cannot resolve the effect being measured. | ||
| 1523 | -/// It doubles as the fallback switch. Read once; the branch predicts perfectly. | ||
| 1524 | -static BS_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); | ||
| 1525 | - | ||
| 1526 | -fn branchless_bs() -> bool { | ||
| 1527 | - use std::sync::atomic::Ordering; | ||
| 1528 | - match BS_MODE.load(Ordering::Relaxed) { | ||
| 1529 | - 1 => true, | ||
| 1530 | - 2 => false, | ||
| 1531 | - _ => { | ||
| 1532 | - let branchy = std::env::var_os("RS_H264_DEBLOCK_BRANCHY").is_some_and(|v| v != "0"); | ||
| 1533 | - BS_MODE.store(if branchy { 2 } else { 1 }, Ordering::Relaxed); | ||
| 1534 | - !branchy | ||
| 1535 | - } | ||
| 1536 | - } | ||
| 1537 | -} | ||
| 1538 | - | ||
| 1539 | -/// Whether the per-MB tile path is active. | ||
| 1540 | -fn deblock_tile() -> bool { | ||
| 1541 | - branchless_bs() | ||
| 1542 | -} | ||
| 1543 | - | ||
| 1544 | -/// DEFAULT OFF. Deriving boundary strengths in the encode loop makes the | ||
| 1545 | -/// deblocking stage 1.4-1.7x faster but does NOT reduce total encode time: the | ||
| 1546 | -/// block grids were never cold (~90 KB at CIF, L2-resident), so the derivation | ||
| 1547 | -/// costs the same in a streaming pass, and the encode loop's contended working | ||
| 1548 | -/// set makes it cost MORE there — measured, the loop grew about twice the | ||
| 1549 | -/// derivation's own cost. Kept behind this switch with its tests, because the | ||
| 1550 | -/// machinery is what a future commit-time derivation (values still in registers, | ||
| 1551 | -/// no grid re-read) would build on. | ||
| 1552 | -static BS_PRECOMP: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); | ||
| 1553 | - | ||
| 1554 | -/// Whether callers may supply precomputed boundary strengths (the encoder path). | ||
| 1555 | -pub fn precomputed_bs_enabled() -> bool { | ||
| 1556 | - BS_PRECOMP.load(std::sync::atomic::Ordering::Relaxed) != 0 | ||
| 1557 | -} | ||
| 1558 | - | ||
| 1559 | -/// Toggle the precomputed-strength path so a benchmark can ALTERNATE the two | ||
| 1560 | -/// designs inside ONE process. | ||
| 1561 | -#[doc(hidden)] | ||
| 1562 | -pub fn set_precomputed_bs(on: bool) { | ||
| 1563 | - BS_PRECOMP.store(on as u8, std::sync::atomic::Ordering::Relaxed); | ||
| 1564 | -} | ||
| 1565 | - | ||
| 1566 | -/// Force the deblocking boundary-strength arm at runtime. Exists so a benchmark | ||
| 1567 | -/// can ALTERNATE the arms inside one process under one thermal state; comparing | ||
| 1568 | -/// separate builds cannot resolve the effect on this machine. | ||
| 1569 | -#[doc(hidden)] | ||
| 1570 | -pub fn set_branchless_bs(on: bool) { | ||
| 1571 | - BS_MODE.store(if on { 1 } else { 2 }, std::sync::atomic::Ordering::Relaxed); | ||
| 1572 | -} | ||
| 1573 | - | ||
| 1574 | -impl BlockInfo<'_> { | ||
| 1575 | - #[inline] | ||
| 1576 | - fn at(&self, bx: usize, by: usize) -> usize { | ||
| 1577 | - by * self.w4 + bx | ||
| 1578 | - } | ||
| 1579 | - | ||
| 1580 | - /// Boundary strength between left/above block `p` and current block `q` | ||
| 1581 | - /// (spec §8.7.2.1). `mb_edge` is true on macroblock boundaries. | ||
| 1582 | - /// | ||
| 1583 | - /// Written branchlessly on purpose. Real content mixes intra/inter, coded and | ||
| 1584 | - /// uncoded blocks, and per-block motion, so the natural short-circuit form | ||
| 1585 | - /// (`if intra … else if nnz … else if motion …`) mispredicts on nearly every | ||
| 1586 | - /// 4×4 edge: the anatomy bench measures the identical code at ~240 ns/MB on | ||
| 1587 | - /// uniform data and ~515 ns/MB once the block state varies, which is the | ||
| 1588 | - /// whole of our gap to x264 here (x264 derives bS with a branchless SIMD | ||
| 1589 | - /// kernel). Evaluating all three candidates costs a few extra loads and beats | ||
| 1590 | - /// paying a ~15-cycle mispredict per edge. | ||
| 1591 | - #[inline] | ||
| 1592 | - fn bs(&self, p: usize, q: usize, mb_edge: bool) -> i32 { | ||
| 1593 | - if branchless_bs() { | ||
| 1594 | - self.bs_branchless(p, q, mb_edge) | ||
| 1595 | - } else { | ||
| 1596 | - self.bs_branchy(p, q, mb_edge) | ||
| 1597 | - } | ||
| 1598 | - } | ||
| 1599 | - | ||
| 1600 | - /// The original short-circuit form, kept as the A/B arm and the fallback. | ||
| 1601 | - /// Identical output to [`Self::bs_branchless`] by construction. | ||
| 1602 | - fn bs_branchy(&self, p: usize, q: usize, mb_edge: bool) -> i32 { | ||
| 1603 | - if !self.inter[p] || !self.inter[q] { | ||
| 1604 | - if mb_edge { | ||
| 1605 | - 4 | ||
| 1606 | - } else { | ||
| 1607 | - 3 | ||
| 1608 | - } | ||
| 1609 | - } else if self.nnz[p] > 0 || self.nnz[q] > 0 { | ||
| 1610 | - 2 | ||
| 1611 | - } else if self.inter_bs1(p, q) { | ||
| 1612 | - 1 | ||
| 1613 | - } else { | ||
| 1614 | - 0 | ||
| 1615 | - } | ||
| 1616 | - } | ||
| 1617 | - | ||
| 1618 | - #[inline] | ||
| 1619 | - fn bs_branchless(&self, p: usize, q: usize, mb_edge: bool) -> i32 { | ||
| 1620 | - let intra = !(self.inter[p] & self.inter[q]); | ||
| 1621 | - let nz = (self.nnz[p] | self.nnz[q]) != 0; | ||
| 1622 | - let moved = self.inter_bs1(p, q); | ||
| 1623 | - let intra_bs = if mb_edge { 4 } else { 3 }; | ||
| 1624 | - // Priority intra > coefficients > motion, as selects rather than branches. | ||
| 1625 | - let motion_bs = moved as i32; // 1 or 0 | ||
| 1626 | - let non_intra = if nz { 2 } else { motion_bs }; | ||
| 1627 | - if intra { | ||
| 1628 | - intra_bs | ||
| 1629 | - } else { | ||
| 1630 | - non_intra | ||
| 1631 | - } | ||
| 1632 | - } | ||
| 1633 | - | ||
| 1634 | - /// Whether two residual-free inter blocks get boundary strength 1: they use | ||
| 1635 | - /// different reference pictures, a different number of motion vectors, or a | ||
| 1636 | - /// motion vector differs by ≥ 1 full sample (matched by reference picture, so | ||
| 1637 | - /// the same picture in different lists is recognised). Spec §8.7.2.1. | ||
| 1638 | - fn inter_bs1(&self, p: usize, q: usize) -> bool { | ||
| 1639 | - // Single-list fast path (P and I slices — `ref_id1` empty). This is the | ||
| 1640 | - // overwhelmingly common case, and it collapses to two comparisons: the | ||
| 1641 | - // general path below builds a two-slot [(ref, mv); 2] array per side and | ||
| 1642 | - // matches on the slot count, which the anatomy bench showed dominates | ||
| 1643 | - // deblocking. Exactly equivalent here: with one list, `pn`/`qn` are just | ||
| 1644 | - // "is the slot used", so a differing ref_id covers both the | ||
| 1645 | - // different-count and different-picture cases, and two unused slots give | ||
| 1646 | - // pn == qn == 0 => false. | ||
| 1647 | - if self.ref_id1.is_empty() { | ||
| 1648 | - // Branchless (see `bs`): `|`/`&` rather than `||`/`&&` so there is no | ||
| 1649 | - // data-dependent branch here either. The single `is_empty` test above | ||
| 1650 | - // is uniform across a whole frame and predicts perfectly. | ||
| 1651 | - let (rp, rq) = (self.ref_id[p], self.ref_id[q]); | ||
| 1652 | - let (a, b) = (self.mv[p], self.mv[q]); | ||
| 1653 | - let far = ((a.0 - b.0).abs() >= 4) | ((a.1 - b.1).abs() >= 4); | ||
| 1654 | - // Differing refs ⇒ bS 1 (this also covers "one slot used, one not", | ||
| 1655 | - // the general path's differing-count case). Both unused ⇒ 0. | ||
| 1656 | - return (rp != rq) | ((rp != NO_REF) & far); | ||
| 1657 | - } | ||
| 1658 | - // (reference id, motion vector) for each used prediction slot. | ||
| 1659 | - let used = |i: usize| { | ||
| 1660 | - let mut v = [(0i32, (0i32, 0i32)); 2]; | ||
| 1661 | - let mut n = 0; | ||
| 1662 | - if self.ref_id[i] != NO_REF { | ||
| 1663 | - v[n] = (self.ref_id[i], self.mv[i]); | ||
| 1664 | - n += 1; | ||
| 1665 | - } | ||
| 1666 | - // `ref_id1` may be empty (P frames have no List-1 — the caller skips | ||
| 1667 | - // building it, since every entry would be NO_REF anyway). | ||
| 1668 | - if !self.ref_id1.is_empty() && self.ref_id1[i] != NO_REF { | ||
| 1669 | - v[n] = (self.ref_id1[i], self.mv1[i]); | ||
| 1670 | - n += 1; | ||
| 1671 | - } | ||
| 1672 | - (v, n) | ||
| 1673 | - }; | ||
| 1674 | - let (pv, pn) = used(p); | ||
| 1675 | - let (qv, qn) = used(q); | ||
| 1676 | - if pn != qn { | ||
| 1677 | - return true; // different number of motion vectors | ||
| 1678 | - } | ||
| 1679 | - let far = |a: (i32, i32), b: (i32, i32)| (a.0 - b.0).abs() >= 4 || (a.1 - b.1).abs() >= 4; | ||
| 1680 | - match pn { | ||
| 1681 | - 0 => false, | ||
| 1682 | - 1 => pv[0].0 != qv[0].0 || far(pv[0].1, qv[0].1), | ||
| 1683 | - _ => { | ||
| 1684 | - // Two references each: the picture *sets* must match, and the | ||
| 1685 | - // motion vectors for corresponding pictures must be close. If both | ||
| 1686 | - // slots are the same picture, either pairing is acceptable. | ||
| 1687 | - let direct = !far(pv[0].1, qv[0].1) && !far(pv[1].1, qv[1].1); | ||
| 1688 | - let swap = !far(pv[0].1, qv[1].1) && !far(pv[1].1, qv[0].1); | ||
| 1689 | - if pv[0].0 == pv[1].0 { | ||
| 1690 | - qv[0].0 != pv[0].0 || qv[1].0 != pv[0].0 || !(direct || swap) | ||
| 1691 | - } else if pv[0].0 == qv[0].0 && pv[1].0 == qv[1].0 { | ||
| 1692 | - !direct | ||
| 1693 | - } else if pv[0].0 == qv[1].0 && pv[1].0 == qv[0].0 { | ||
| 1694 | - !swap | ||
| 1695 | - } else { | ||
| 1696 | - true // different picture sets | ||
| 1697 | - } | ||
| 1698 | - } | ||
| 1699 | - } | ||
| 1700 | - } | ||
| 1701 | -} | ||
| 1702 | - | ||
| 1703 | -/// Applies the deblocking filter in place to a fully-reconstructed frame. `qp` | ||
| 1704 | -/// is the (constant) luma QP, `qpc` the chroma QP, and `info` supplies the | ||
| 1705 | -/// per-block state used to derive boundary strengths (for an all-intra frame | ||
| 1706 | -/// this reduces to the fixed 4/3 strengths). | ||
| 1707 | -/// Edge thresholds `(α, β, tc0[bS-1])` for a given averaged QP and the slice's | ||
| 1708 | -/// filter offsets (spec §8.7.2.2): α/tc0 indexed by `indexA`, β by `indexB`. | ||
| 1709 | -#[inline] | ||
| 1710 | -fn thresholds(qpav: i32, offset_a: i32, offset_b: i32) -> (i32, i32, [i32; 3]) { | ||
| 1711 | - let ia = (qpav + offset_a).clamp(0, 51) as usize; | ||
| 1712 | - let ib = (qpav + offset_b).clamp(0, 51) as usize; | ||
| 1713 | - (ALPHA[ia], BETA[ib], TC0[ia]) | ||
| 1714 | -} | ||
| 1715 | - | ||
| 1716 | -#[allow(clippy::too_many_arguments)] | ||
| 1717 | -pub fn filter_frame( | ||
| 1718 | - y: &mut [u8], | ||
| 1719 | - u: &mut [u8], | ||
| 1720 | - v: &mut [u8], | ||
| 1721 | - mb_w: usize, | ||
| 1722 | - mb_h: usize, | ||
| 1723 | - mb_qp: &[u8], | ||
| 1724 | - chroma_qp_offset: i32, | ||
| 1725 | - offset_a: i32, | ||
| 1726 | - offset_b: i32, | ||
| 1727 | - info: &BlockInfo, | ||
| 1728 | -) { | ||
| 1729 | - filter_frame_rows(y, u, v, mb_w, mb_h, 0..mb_h, mb_qp, chroma_qp_offset, offset_a, offset_b, info) | ||
| 1730 | -} | ||
| 1731 | - | ||
| 1732 | -/// [`filter_frame`] restricted to macroblock rows `rows` — the row-interleave | ||
| 1733 | -/// campaign's unit (docs/row-interleave-plan.md R3): the decoder filters row | ||
| 1734 | -/// `r` the moment it finishes decoding, spec raster order preserved exactly. | ||
| 1735 | -#[allow(clippy::too_many_arguments)] | ||
| 1736 | -pub fn filter_frame_rows( | ||
| 1737 | - y: &mut [u8], | ||
| 1738 | - u: &mut [u8], | ||
| 1739 | - v: &mut [u8], | ||
| 1740 | - mb_w: usize, | ||
| 1741 | - mb_h: usize, | ||
| 1742 | - rows: core::ops::Range<usize>, | ||
| 1743 | - mb_qp: &[u8], | ||
| 1744 | - chroma_qp_offset: i32, | ||
| 1745 | - offset_a: i32, | ||
| 1746 | - offset_b: i32, | ||
| 1747 | - info: &BlockInfo, | ||
| 1748 | -) { | ||
| 1749 | - let _g = crate::prof::scope(crate::prof::Stage::Deblock); | ||
| 1750 | - let cw = mb_w * 16; | ||
| 1751 | - let ccw = mb_w * 8; | ||
| 1752 | - // Per-edge QP: deblock strength uses the average of the two adjacent | ||
| 1753 | - // macroblocks' QPy (spec §8.7.2). For an internal edge both sides share the | ||
| 1754 | - // current MB's QP. Chroma averages the two MBs' QPc. | ||
| 1755 | - let qpy = |mx: usize, my: usize| mb_qp[my * mb_w + mx] as i32; | ||
| 1756 | - let qpc = |qpy_val: i32| { | ||
| 1757 | - crate::predict::chroma_qp((qpy_val + chroma_qp_offset).clamp(0, 51) as u8) as i32 | ||
| 1758 | - }; | ||
| 1759 | - // Arms resolved ONCE per frame, never per macroblock (see `bs_twopass`). | ||
| 1760 | - let two_pass = bs_twopass(); | ||
| 1761 | - let kind_off = kind_gate_off(); | ||
| 1762 | - let verify_kinds = verify_kind(); | ||
| 1763 | - // ONE streaming pass over the frame arrays, not 3600 scattered gathers. `None` | ||
| 1764 | - // when the frame carries List-1 data (B slices), which MbPack does not model — | ||
| 1765 | - // those macroblocks keep the blind path. | ||
| 1766 | - let scratch = PACK_SCRATCH.take(); | ||
| 1767 | - let packs: Option<Vec<MbPack>> = if bs_packed_on() && info.bs.is_empty() && deblock_tile() { | ||
| 1768 | - let mut buf = scratch; | ||
| 1769 | - { | ||
| 1770 | - let _pg = crate::prof::scope(crate::prof::Stage::DebPack); | ||
| 1771 | - pack_frame_into(info, mb_w, mb_h, &mut buf); | ||
| 1772 | - } | ||
| 1773 | - Some(buf) | ||
| 1774 | - } else { | ||
| 1775 | - PACK_SCRATCH.set(scratch); | ||
| 1776 | - None | ||
| 1777 | - }; | ||
| 1778 | - | ||
| 1779 | - for mb_y in rows { | ||
| 1780 | - for mb_x in 0..mb_w { | ||
| 1781 | - // `t8x8` may be empty (no MB uses the 8×8 transform — Baseline); treat | ||
| 1782 | - // an empty grid as all-false so the caller can skip allocating it. | ||
| 1783 | - let mb_t8 = !info.t8x8.is_empty() && info.t8x8[mb_y * mb_w + mb_x]; | ||
| 1784 | - // A "flat inter MB" — every 4x4 inter, zero nnz, one (ref, mv) pair (e.g. | ||
| 1785 | - // any skip MB) — has bs = 0 on ALL its internal edges by §8.7.2.1 (no | ||
| 1786 | - // coefficients, same reference, identical motion), so the six internal | ||
| 1787 | - // edge groups can be skipped wholesale. Byte-identical control flow. | ||
| 1788 | - // Gather the MB's 4×4 block state once (see `Blk`). Every boundary | ||
| 1789 | - // strength below then reads the tile instead of the strided frame | ||
| 1790 | - // arrays. Only valid for a single reference list; B slices keep the | ||
| 1791 | - // original per-edge path untouched. | ||
| 1792 | - // `deblock_tile()` selects the arm so a bench can alternate the whole | ||
| 1793 | - // brick (tile vs the original per-edge derivation) in one process. | ||
| 1794 | - // Precomputed strengths short-circuit the gather AND the derivation; | ||
| 1795 | - // flat_inter and the t8x8 skips are already baked into the stored | ||
| 1796 | - // zeros, which the all-zero early-out below handles identically. | ||
| 1797 | - let _dg = crate::prof::scope(crate::prof::Stage::DebDerive); | ||
| 1798 | - let precomputed = !info.bs.is_empty(); | ||
| 1799 | - // H-33: the tile arm now carries the two-list B rule (`bs1_tile`), so | ||
| 1800 | - // real-world B frames no longer fall back to the strided per-edge path. | ||
| 1801 | - let use_tile = !precomputed && deblock_tile(); | ||
| 1802 | - let have_bs = precomputed || use_tile; | ||
| 1803 | - | ||
| 1804 | - // KIND-AWARE FAST PATH. When the producer has classified this | ||
| 1805 | - // macroblock, its strengths follow from syntax and the 24-block | ||
| 1806 | - // neighbourhood gather is not needed at all: Intra reads NOTHING, Skip | ||
| 1807 | - // reads 9 blocks, InterUniform reads 16 nnz bytes. `Inter` and UNSET | ||
| 1808 | - // fall through to the blind path below, so an unclassified macroblock | ||
| 1809 | - // costs speed and never correctness. | ||
| 1810 | - // | ||
| 1811 | - // The gather is skipped by CONSTRUCTION here rather than by an early-out | ||
| 1812 | - // inside it — building the 5x5 `Tile` at all is an 800-byte | ||
| 1813 | - // default-initialisation before 24 of its 25 entries are overwritten. | ||
| 1814 | - let fast_kind = if use_tile && !kind_off { | ||
| 1815 | - match info.kind.get(mb_y * mb_w + mb_x).copied().and_then(MbKind::from_u8) { | ||
| 1816 | - Some(k) if k != MbKind::Inter => Some(k), | ||
| 1817 | - _ => None, | ||
| 1818 | - } | ||
| 1819 | - } else { | ||
| 1820 | - None | ||
| 1821 | - }; | ||
| 1822 | - | ||
| 1823 | - let blind_tile = use_tile && fast_kind.is_none() && packs.is_none(); | ||
| 1824 | - // Declared before the predicate chain: the packed derivation produces | ||
| 1825 | - // `flat_inter` and the strengths in ONE traversal, so it cannot be split | ||
| 1826 | - // across the two chains the way the tile path is. | ||
| 1827 | - let mut bs_v = [[0i32; 4]; 4]; | ||
| 1828 | - let mut bs_h = [[0i32; 4]; 4]; | ||
| 1829 | - let packed_mb = packs.as_ref().filter(|_| use_tile && fast_kind.is_none()); | ||
| 1830 | - // MATERIALISE THE TILE ONLY ON THE BLIND PATH. Writing | ||
| 1831 | - // `else { Default::default() }` here cost an 800-byte zero-init of the | ||
| 1832 | - // 5x5 `Tile` on every CLASSIFIED macroblock — i.e. this brick removed a | ||
| 1833 | - // gather and added ~4 GB of memset, and measured 1.2-17.0% SLOWER in | ||
| 1834 | - // 4/4 pairs. `Option` keeps the fast path free of it entirely. | ||
| 1835 | - let tile = if blind_tile { Some(gather_tile(info, mb_x, mb_y)) } else { None }; | ||
| 1836 | - | ||
| 1837 | - // ONE walk yields both predicates — see `scan_uniform_flat`. The | ||
| 1838 | - // non-tile arm has no `uniform_motion` consumer (it derives per-edge | ||
| 1839 | - // off the frame arrays), so it keeps returning `flat_inter` alone. | ||
| 1840 | - let mut uniform_motion = false; | ||
| 1841 | - let flat_inter = if precomputed { | ||
| 1842 | - false // the stored zeros already encode it | ||
| 1843 | - } else if let Some(k) = fast_kind { | ||
| 1844 | - match k { | ||
| 1845 | - // No coefficients and one shared (ref, mv): every internal | ||
| 1846 | - // strength is 0 by construction. | ||
| 1847 | - MbKind::Skip => true, | ||
| 1848 | - // CAUGHT BY THE ORACLE: a single-partition inter macroblock | ||
| 1849 | - // with NO coefficients is flat too — uniform motion means the | ||
| 1850 | - // blind predicate reduces to exactly "no block has nnz". | ||
| 1851 | - // Hardcoding `false` here was pixel-identical (the strengths | ||
| 1852 | - // are all 0 either way) but made the consuming loops walk the | ||
| 1853 | - // internal edge groups instead of skipping them, throwing away | ||
| 1854 | - // part of the win. 16 contiguous nnz bytes — the same data | ||
| 1855 | - // `derive_mb_kind` already reads for this class. | ||
| 1856 | - MbKind::InterUniform => { | ||
| 1857 | - let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 1858 | - (0..4).all(|r| { | ||
| 1859 | - (0..4).all(|c| info.nnz[(by0 + r) * info.w4 + bx0 + c] == 0) | ||
| 1860 | - }) | ||
| 1861 | - } | ||
| 1862 | - _ => false, | ||
| 1863 | - } | ||
| 1864 | - } else if let Some(pk) = packed_mb { | ||
| 1865 | - #[cfg(feature = "profile")] | ||
| 1866 | - census::PACKED_MB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 1867 | - let pflat = derive_mb_packed(pk, mb_w, mb_x, mb_y, mb_t8, &mut bs_v, &mut bs_h); | ||
| 1868 | - if verify_packed() { | ||
| 1869 | - // UNMASKED: all 32 strengths, not just the ones the consuming | ||
| 1870 | - // loops read. A masked oracle can pass while the corpus diverges. | ||
| 1871 | - let t = gather_tile(info, mb_x, mb_y); | ||
| 1872 | - let (u, f) = scan_uniform_flat(&t); | ||
| 1873 | - let (mut tv, mut th) = ([[0i32; 4]; 4], [[0i32; 4]; 4]); | ||
| 1874 | - derive_mb_bs(&t, mb_x, mb_y, f, u, mb_t8, &mut tv, &mut th); | ||
| 1875 | - assert_eq!(pflat, f, "MB ({mb_x},{mb_y}) t8={mb_t8}: flat_inter"); | ||
| 1876 | - assert_eq!(bs_v, tv, "MB ({mb_x},{mb_y}) t8={mb_t8} flat={f}: bs_v"); | ||
| 1877 | - assert_eq!(bs_h, th, "MB ({mb_x},{mb_y}) t8={mb_t8} flat={f}: bs_h"); | ||
| 1878 | - } | ||
| 1879 | - pflat | ||
| 1880 | - } else if blind_tile { | ||
| 1881 | - let (u, f) = scan_predicates(tile.as_ref().unwrap(), two_pass); | ||
| 1882 | - uniform_motion = u; | ||
| 1883 | - f | ||
| 1884 | - } else { | ||
| 1885 | - let b0 = info.at(mb_x * 4, mb_y * 4); | ||
| 1886 | - let mut ok = info.inter[b0]; | ||
| 1887 | - if ok { | ||
| 1888 | - let (r0, m0) = (info.ref_id[b0], info.mv[b0]); | ||
| 1889 | - let has1 = !info.ref_id1.is_empty(); | ||
| 1890 | - let (r10, m10) = if has1 { (info.ref_id1[b0], info.mv1[b0]) } else { (NO_REF, (0, 0)) }; | ||
| 1891 | - 'scan: for by in 0..4 { | ||
| 1892 | - for bx in 0..4 { | ||
| 1893 | - let i = info.at(mb_x * 4 + bx, mb_y * 4 + by); | ||
| 1894 | - if !info.inter[i] | ||
| 1895 | - || info.nnz[i] != 0 | ||
| 1896 | - || info.ref_id[i] != r0 | ||
| 1897 | - || info.mv[i] != m0 | ||
| 1898 | - || (has1 && (info.ref_id1[i] != r10 || info.mv1[i] != m10)) | ||
| 1899 | - { | ||
| 1900 | - ok = false; | ||
| 1901 | - break 'scan; | ||
| 1902 | - } | ||
| 1903 | - } | ||
| 1904 | - } | ||
| 1905 | - } | ||
| 1906 | - ok | ||
| 1907 | - }; | ||
| 1908 | - // ---- boundary strengths for the whole macroblock, derived ONCE ---- | ||
| 1909 | - // The chroma edge groups are CO-LOCATED with luma edges 0 and 2 and | ||
| 1910 | - // derive identical strengths (pinned by `chroma_bs_matches_luma`), so | ||
| 1911 | - // deriving them in the chroma loops recomputed 16 of the 48 per-MB | ||
| 1912 | - // strengths. Guards mirror the consuming loops exactly, so nothing is | ||
| 1913 | - // derived that was not derived before; edges left at zero are exactly | ||
| 1914 | - // the edges those loops skip. | ||
| 1915 | - if packed_mb.is_some() { | ||
| 1916 | - // Already written by `derive_mb_packed` above: unlike the tile path, | ||
| 1917 | - // the packed derivation produces `flat_inter` AND the strengths in one | ||
| 1918 | - // traversal, so it cannot be split across the two chains. | ||
| 1919 | - } else if precomputed { | ||
| 1920 | - let m = &info.bs[mb_y * mb_w + mb_x]; | ||
| 1921 | - for e in 0..4 { | ||
| 1922 | - for sg in 0..4 { | ||
| 1923 | - bs_v[e][sg] = m.v[e][sg] as i32; | ||
| 1924 | - bs_h[e][sg] = m.h[e][sg] as i32; | ||
| 1925 | - } | ||
| 1926 | - } | ||
| 1927 | - } else if let Some(k) = fast_kind { | ||
| 1928 | - // Write i32 strengths straight into the consuming arrays. Going via | ||
| 1929 | - // `derive_mb_kind`'s packed `MbBs` cost 32 u8->i32 stores per | ||
| 1930 | - // classified macroblock that the blind path never pays — pure | ||
| 1931 | - // addition on the path that is supposed to be cheaper. | ||
| 1932 | - derive_mb_kind_into(info, mb_x, mb_y, k, &mut bs_v, &mut bs_h); | ||
| 1933 | - if verify_kinds { | ||
| 1934 | - verify_kind_matches_blind( | ||
| 1935 | - info, mb_x, mb_y, mb_t8, k, flat_inter, &bs_v, &bs_h, | ||
| 1936 | - ); | ||
| 1937 | - } | ||
| 1938 | - } else if blind_tile { | ||
| 1939 | - derive_mb_bs( | ||
| 1940 | - tile.as_ref().unwrap(), | ||
| 1941 | - mb_x, | ||
| 1942 | - mb_y, | ||
| 1943 | - flat_inter, | ||
| 1944 | - uniform_motion, | ||
| 1945 | - mb_t8, | ||
| 1946 | - &mut bs_v, | ||
| 1947 | - &mut bs_h, | ||
| 1948 | - ); | ||
| 1949 | - } | ||
| 1950 | - drop(_dg); | ||
| 1951 | - // ---- luma vertical edges (block columns 0..4) ---- | ||
| 1952 | - for be in 0..4usize { | ||
| 1953 | - if be == 0 && mb_x == 0 { | ||
| 1954 | - continue; | ||
| 1955 | - } | ||
| 1956 | - if flat_inter && be != 0 { | ||
| 1957 | - continue; // internal bs all 0 (flat inter MB) | ||
| 1958 | - } | ||
| 1959 | - // 8×8-transform MBs: internal 4×4 edges (be 1, 3) aren't filtered. | ||
| 1960 | - if mb_t8 && (be == 1 || be == 3) { | ||
| 1961 | - continue; | ||
| 1962 | - } | ||
| 1963 | - let mb_edge = be == 0; | ||
| 1964 | - let mut bs4 = [0i32; 4]; | ||
| 1965 | - if have_bs { | ||
| 1966 | - bs4 = bs_v[be]; | ||
| 1967 | - } else { | ||
| 1968 | - let abx = mb_x * 4 + be; | ||
| 1969 | - for (seg, b) in bs4.iter_mut().enumerate() { | ||
| 1970 | - let aby = mb_y * 4 + seg; | ||
| 1971 | - *b = info.bs(info.at(abx - 1, aby), info.at(abx, aby), mb_edge); | ||
| 1972 | - } | ||
| 1973 | - } | ||
| 1974 | - if bs4.iter().all(|&b| b == 0) { | ||
| 1975 | - continue; | ||
| 1976 | - } | ||
| 1977 | - // Thresholds AFTER the all-zero early-out: on real content most | ||
| 1978 | - // edges filter nothing, and computing α/β/tc0 (two clamps plus | ||
| 1979 | - // three table loads, and a neighbour QP read on MB edges) for an | ||
| 1980 | - // edge we are about to skip is pure waste. | ||
| 1981 | - let qpav = if mb_edge { | ||
| 1982 | - (qpy(mb_x - 1, mb_y) + qpy(mb_x, mb_y) + 1) >> 1 | ||
| 1983 | - } else { | ||
| 1984 | - qpy(mb_x, mb_y) | ||
| 1985 | - }; | ||
| 1986 | - let (alpha_y, beta_y, tc0a) = thresholds(qpav, offset_a, offset_b); | ||
| 1987 | - let tc0_luma = |bs: i32| if (1..4).contains(&bs) { tc0a[bs as usize - 1] } else { 0 }; | ||
| 1988 | - let x = mb_x * 16 + be * 4; | ||
| 1989 | - // Vertical edge via openh264's transpose → V-filter → transpose-back | ||
| 1990 | - // (the `DeblockLumaLt4H` wrapper). tc per 4-row segment (−1 = skip). | ||
| 1991 | - #[cfg(accel)] | ||
| 1992 | - { | ||
| 1993 | - let base = mb_y * 16 * cw + (x - 4); // p3 column, top row | ||
| 1994 | - if bs4.iter().all(|&b| b == 4) { | ||
| 1995 | - rusty_h264_accel::deblock_luma_eq4_h(&mut y[base..], cw, alpha_y, beta_y); | ||
| 1996 | - } else { | ||
| 1997 | - let tc: [i8; 4] = std::array::from_fn(|i| { | ||
| 1998 | - if (1..4).contains(&bs4[i]) { tc0_luma(bs4[i]) as i8 } else { -1 } | ||
| 1999 | - }); | ||
| 2000 | - rusty_h264_accel::deblock_luma_lt4_h(&mut y[base..], cw, alpha_y, beta_y, &tc); | ||
vendor/rusty_h264-common/src/inter.rsdeleted+0 -1901
| @@ -1,1901 +0,0 @@ | |||
| 1 | -//! Inter prediction primitives: motion compensation and motion-vector | ||
| 2 | -//! prediction. Shared by the encoder (reconstruction) and decoder so the two | ||
| 3 | -//! agree bit-for-bit. Motion vectors are in quarter-pel units; phase 4b uses | ||
| 4 | -//! the integer part only (full-pel), with the 6-tap/bilinear sub-pel filters | ||
| 5 | -//! arriving in 4c. | ||
| 6 | - | ||
| 7 | -/// Median of three values (`a + b + c − min − max`). | ||
| 8 | -#[inline] | ||
| 9 | -pub fn median3(a: i32, b: i32, c: i32) -> i32 { | ||
| 10 | - a + b + c - a.min(b).min(c) - a.max(b).max(c) | ||
| 11 | -} | ||
| 12 | - | ||
| 13 | -/// A motion-vector predictor neighbor: whether the neighbor block is available | ||
| 14 | -/// (inside the picture/decoded), its motion vector, and its reference index | ||
| 15 | -/// (`-1` for intra/unavailable neighbors, which contribute a zero MV with a | ||
| 16 | -/// non-matching reference). | ||
| 17 | -#[derive(Clone, Copy)] | ||
| 18 | -pub struct MvNeighbor { | ||
| 19 | - pub available: bool, | ||
| 20 | - pub mv: (i32, i32), | ||
| 21 | - pub ref_idx: i32, | ||
| 22 | -} | ||
| 23 | - | ||
| 24 | -impl MvNeighbor { | ||
| 25 | - pub const NONE: MvNeighbor = MvNeighbor { | ||
| 26 | - available: false, | ||
| 27 | - mv: (0, 0), | ||
| 28 | - ref_idx: -1, | ||
| 29 | - }; | ||
| 30 | -} | ||
| 31 | - | ||
| 32 | -/// Median motion-vector prediction for a partition (spec §8.4.1.3.1), against | ||
| 33 | -/// the current partition's reference `cur_ref`. `a`/`b`/`c` are the left, above, | ||
| 34 | -/// and above-right neighbors. If exactly one neighbor shares `cur_ref`, its MV is | ||
| 35 | -/// the predictor; otherwise the component-wise median is used. | ||
| 36 | -pub fn predict_mv(a: MvNeighbor, b: MvNeighbor, c: MvNeighbor, cur_ref: i32) -> (i32, i32) { | ||
| 37 | - // Per-neighbor (mv, refIdx): a usable inter neighbor keeps its mv+ref, else | ||
| 38 | - // a zero MV with ref −1 (never matches a valid `cur_ref` ≥ 0). | ||
| 39 | - let resolve = |n: MvNeighbor| -> ((i32, i32), i32) { | ||
| 40 | - if n.available && n.ref_idx >= 0 { | ||
| 41 | - (n.mv, n.ref_idx) | ||
| 42 | - } else { | ||
| 43 | - ((0, 0), -1) | ||
| 44 | - } | ||
| 45 | - }; | ||
| 46 | - let (mva, ra) = resolve(a); | ||
| 47 | - let (mut mvb, mut rb) = resolve(b); | ||
| 48 | - let (mut mvc, mut rc) = resolve(c); | ||
| 49 | - | ||
| 50 | - // If both B and C are unavailable but A is available, B and C take A. | ||
| 51 | - if !b.available && !c.available && a.available { | ||
| 52 | - mvb = mva; | ||
| 53 | - rb = ra; | ||
| 54 | - mvc = mva; | ||
| 55 | - rc = ra; | ||
| 56 | - } | ||
| 57 | - | ||
| 58 | - let matches = (ra == cur_ref) as i32 + (rb == cur_ref) as i32 + (rc == cur_ref) as i32; | ||
| 59 | - if matches == 1 { | ||
| 60 | - if ra == cur_ref { | ||
| 61 | - mva | ||
| 62 | - } else if rb == cur_ref { | ||
| 63 | - mvb | ||
| 64 | - } else { | ||
| 65 | - mvc | ||
| 66 | - } | ||
| 67 | - } else { | ||
| 68 | - (median3(mva.0, mvb.0, mvc.0), median3(mva.1, mvb.1, mvc.1)) | ||
| 69 | - } | ||
| 70 | -} | ||
| 71 | - | ||
| 72 | -/// Directional MV prediction for a sub-partition (spec §8.4.1.3.2) against the | ||
| 73 | -/// partition's reference `cur_ref`. `mode` is the inter `mb_type` (0 = 16×16, | ||
| 74 | -/// 1 = 16×8, 2 = 8×16). 16×8/8×16 use a specific neighbor directly when it shares | ||
| 75 | -/// `cur_ref`; otherwise (and always for 16×16) the median. | ||
| 76 | -pub fn predict_partition_mv( | ||
| 77 | - mode: u8, | ||
| 78 | - part: usize, | ||
| 79 | - a: MvNeighbor, | ||
| 80 | - b: MvNeighbor, | ||
| 81 | - c: MvNeighbor, | ||
| 82 | - cur_ref: i32, | ||
| 83 | -) -> (i32, i32) { | ||
| 84 | - let m = |n: MvNeighbor| n.available && n.ref_idx == cur_ref; | ||
| 85 | - match (mode, part) { | ||
| 86 | - (1, 0) if m(b) => b.mv, // 16×8 top → above | ||
| 87 | - (1, 1) if m(a) => a.mv, // 16×8 bottom → left | ||
| 88 | - (2, 0) if m(a) => a.mv, // 8×16 left → left | ||
| 89 | - (2, 1) if m(c) => c.mv, // 8×16 right → above-right | ||
| 90 | - _ => predict_mv(a, b, c, cur_ref), | ||
| 91 | - } | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | -/// Inter `mb_type` → luma partition regions `(x, y, w, h)` in samples. | ||
| 95 | -pub fn inter_partitions(mode: u8) -> &'static [(usize, usize, usize, usize)] { | ||
| 96 | - match mode { | ||
| 97 | - 1 => &[(0, 0, 16, 8), (0, 8, 16, 8)], // P_16x8 | ||
| 98 | - 2 => &[(0, 0, 8, 16), (8, 0, 8, 16)], // P_8x16 | ||
| 99 | - // P_8x8: four 8×8 sub-macroblocks in raster (decode_p8x8) order, each its | ||
| 100 | - // own MV. (Sub-8×8 shapes 8×4/4×8/4×4 within an 8×8 are a further split.) | ||
| 101 | - 3 => &[(0, 0, 8, 8), (8, 0, 8, 8), (0, 8, 8, 8), (8, 8, 8, 8)], | ||
| 102 | - _ => &[(0, 0, 16, 16)], // P_L0_16x16 | ||
| 103 | - } | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -/// Reference sample with edge clamping. | ||
| 107 | -/// | ||
| 108 | -/// Bounds-SAFE: a decoder driven by a malformed stream can reach here with `(cw, ch)` | ||
| 109 | -/// that do not match the plane it was handed, and every caller's "interior" test is | ||
| 110 | -/// written against `cw`/`ch` rather than the slice length. In bounds this is identical | ||
| 111 | -/// to a direct index; out of bounds it yields 0 instead of panicking. (Found by the | ||
| 112 | -/// fuzzer the moment CABAC became the default — the CABAC parse produces wilder | ||
| 113 | -/// vectors on mutated input than CAVLC did, so this path had never been reached.) | ||
| 114 | -#[inline] | ||
| 115 | -fn at(reference: &[u8], cw: usize, ch: usize, x: isize, y: isize) -> i32 { | ||
| 116 | - let xx = x.clamp(0, cw as isize - 1) as usize; | ||
| 117 | - let yy = y.clamp(0, ch as isize - 1) as usize; | ||
| 118 | - reference.get(yy * cw + xx).copied().unwrap_or(0) as i32 | ||
| 119 | -} | ||
| 120 | - | ||
| 121 | -#[inline] | ||
| 122 | -fn clip_u8(v: i32) -> i32 { | ||
| 123 | - v.clamp(0, 255) | ||
| 124 | -} | ||
| 125 | - | ||
| 126 | -/// Per-pixel quarter-pel luma sample (spec §8.4.2.2.1) — the readable reference | ||
| 127 | -/// kept as the bit-exactness oracle for the block-kernel MC below. | ||
| 128 | -#[cfg(test)] | ||
| 129 | -fn luma_sample(reference: &[u8], cw: usize, ch: usize, ix: isize, iy: isize, fx: i32, fy: i32) -> i32 { | ||
| 130 | - let g = |dx: isize, dy: isize| at(reference, cw, ch, ix + dx, iy + dy); | ||
| 131 | - if fx == 0 && fy == 0 { | ||
| 132 | - return g(0, 0); | ||
| 133 | - } | ||
| 134 | - let hor6 = |dy: isize| g(-2, dy) - 5 * g(-1, dy) + 20 * g(0, dy) + 20 * g(1, dy) - 5 * g(2, dy) + g(3, dy); | ||
| 135 | - let ver6 = |dx: isize| g(dx, -2) - 5 * g(dx, -1) + 20 * g(dx, 0) + 20 * g(dx, 1) - 5 * g(dx, 2) + g(dx, 3); | ||
| 136 | - let b = || clip_u8((hor6(0) + 16) >> 5); | ||
| 137 | - let h = || clip_u8((ver6(0) + 16) >> 5); | ||
| 138 | - let m = || clip_u8((ver6(1) + 16) >> 5); | ||
| 139 | - let s = || clip_u8((hor6(1) + 16) >> 5); | ||
| 140 | - let j = || { | ||
| 141 | - let j1 = hor6(-2) - 5 * hor6(-1) + 20 * hor6(0) + 20 * hor6(1) - 5 * hor6(2) + hor6(3); | ||
| 142 | - clip_u8((j1 + 512) >> 10) | ||
| 143 | - }; | ||
| 144 | - match (fx, fy) { | ||
| 145 | - (1, 0) => (g(0, 0) + b() + 1) >> 1, | ||
| 146 | - (2, 0) => b(), | ||
| 147 | - (3, 0) => (g(1, 0) + b() + 1) >> 1, | ||
| 148 | - (0, 1) => (g(0, 0) + h() + 1) >> 1, | ||
| 149 | - (1, 1) => (b() + h() + 1) >> 1, | ||
| 150 | - (2, 1) => (b() + j() + 1) >> 1, | ||
| 151 | - (3, 1) => (b() + m() + 1) >> 1, | ||
| 152 | - (0, 2) => h(), | ||
| 153 | - (1, 2) => (h() + j() + 1) >> 1, | ||
| 154 | - (2, 2) => j(), | ||
| 155 | - (3, 2) => (j() + m() + 1) >> 1, | ||
| 156 | - (0, 3) => (g(0, 1) + h() + 1) >> 1, | ||
| 157 | - (1, 3) => (h() + s() + 1) >> 1, | ||
| 158 | - (2, 3) => (j() + s() + 1) >> 1, | ||
| 159 | - _ => (m() + s() + 1) >> 1, | ||
| 160 | - } | ||
| 161 | -} | ||
| 162 | - | ||
| 163 | -// ---- Block-level luma MC, mirroring openh264 `mc.cpp` (`McHorVerNN_c`) ---- | ||
| 164 | -// | ||
| 165 | -// openh264 computes each half-pel plane once per block (not per pixel) and | ||
| 166 | -// averages clipped planes for the quarter positions. Our `luma_sample` recomputed | ||
| 167 | -// the 6-tap for every pixel; these kernels compute each plane once. Bit-identical: | ||
| 168 | -// the 6-tap is separable with exact (un-rounded) integer intermediates, so | ||
| 169 | -// horizontal-then-vertical equals vertical-then-horizontal, and the clamped tile | ||
| 170 | -// reproduces `at()` exactly. | ||
| 171 | - | ||
| 172 | -/// Max luma interpolation tile: a 16×16 block plus the 6-tap halo (2 left/up, | ||
| 173 | -/// 3 right/down) → 21×21. | ||
| 174 | -const LUMA_TILE: usize = 21; | ||
| 175 | - | ||
| 176 | -/// Per-thread scratch for the sub-pel MC path. | ||
| 177 | -/// | ||
| 178 | -/// These three buffers used to be created — and therefore **zero-initialised** — | ||
| 179 | -/// inside every `mc_luma` call, and the tile was additionally returned *by value*. | ||
| 180 | -/// That is ~1.4 KB of `memset` plus a 441-byte move per call, paid identically | ||
| 181 | -/// whether the block is 16×16 (256 useful samples) or 4×4 (16). Profiling put | ||
| 182 | -/// `inter-mc` at 166 s of a 266 s quality-preset encode over 991 M calls, and a | ||
| 183 | -/// block-size sweep showed a 4×4 sub-pel call costing *more* than a 16×16 one | ||
| 184 | -/// (248 vs 172 ns) — i.e. the cost was the per-call buffers, not the filter. | ||
| 185 | -/// | ||
| 186 | -/// Hoisting them to thread-local scratch makes that setup once per thread instead | ||
| 187 | -/// of once per candidate. Byte-identical: both `luma_tile_into` paths write the | ||
| 188 | -/// whole `(bw+5)×(bh+5)` region before it is read, and `a`/`b` are written over | ||
| 189 | -/// `bw*bh` samples by `luma_h`/`luma_v`/`luma_centre` before `pixel_avg`/`avg_full` | ||
| 190 | -/// read the same range — so the zero-fill was dead in every case. | ||
| 191 | -pub struct McScratch { | ||
| 192 | - tile: [u8; LUMA_TILE * LUMA_TILE], | ||
| 193 | - a: [u8; 256], | ||
| 194 | - b: [u8; 256], | ||
| 195 | -} | ||
| 196 | - | ||
| 197 | -/// Runs `f` with the thread's MC scratch borrowed ONCE. Callers that issue many | ||
| 198 | -/// MC calls in a row (the bi-pred pair, the P-path rect ladder) hoist the | ||
| 199 | -/// TLS lookup + RefCell borrow out of the per-call path by taking this at | ||
| 200 | -/// region/MB scope and calling `mc_luma_padded_pre` inside — that fixed | ||
| 201 | -/// per-call cost is paid twice per bi-pred region, ~1M sub-pel calls per clip. | ||
| 202 | -#[inline] | ||
| 203 | -pub fn with_mc_scratch<R>(f: impl FnOnce(&mut McScratch) -> R) -> R { | ||
| 204 | - MC_SCRATCH.with(|s| f(&mut s.borrow_mut())) | ||
| 205 | -} | ||
| 206 | - | ||
| 207 | -thread_local! { | ||
| 208 | - static MC_SCRATCH: core::cell::RefCell<McScratch> = const { | ||
| 209 | - core::cell::RefCell::new(McScratch { | ||
| 210 | - tile: [0; LUMA_TILE * LUMA_TILE], | ||
| 211 | - a: [0; 256], | ||
| 212 | - b: [0; 256], | ||
| 213 | - }) | ||
| 214 | - }; | ||
| 215 | -} | ||
| 216 | - | ||
| 217 | -/// Dev-only census of `mc_luma` calls by block size × sub-pel phase. | ||
| 218 | -/// | ||
| 219 | -/// Exists to size the half-pel-plane-cache lever: with a cached plane set, a | ||
| 220 | -/// half-pel call becomes a strided COPY and a quarter-pel call a 2-tap AVERAGE, | ||
| 221 | -/// so the prize is (how many calls are sub-pel) × (filter cost − read cost). The | ||
| 222 | -/// mix is deterministic, so this is valid on a loaded machine. | ||
| 223 | -#[cfg(feature = "profile")] | ||
| 224 | -pub mod mcstats { | ||
| 225 | - use core::sync::atomic::{AtomicU64, Ordering}; | ||
| 226 | - | ||
| 227 | - /// Descent E depth-6: WHO calls `mc_luma`? `prof inter-mc` counts ~17 calls per | ||
| 228 | - /// macroblock while reconstruction needs only 1-4, so the stage is dominated by | ||
| 229 | - /// something other than recon and any prize computed against "recon MC" is priced | ||
| 230 | - /// on the wrong population. Callers tag themselves; 0 = untagged. | ||
| 231 | - pub const SITES: [&str; 5] = ["untagged", "recon", "search-fallback", "skip-check", "bdirect"]; | ||
| 232 | - pub static SITE_COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; | ||
| 233 | - pub static SITE_CYCLES: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; | ||
| 234 | - thread_local! { | ||
| 235 | - pub static SITE: core::cell::Cell<usize> = const { core::cell::Cell::new(0) }; | ||
| 236 | - } | ||
| 237 | - /// Scoped tag: set on construction, restored on drop (call sites nest). | ||
| 238 | - pub struct SiteTag(usize); | ||
| 239 | - impl SiteTag { | ||
| 240 | - pub fn new(s: usize) -> Self { | ||
| 241 | - let prev = SITE.with(|c| c.replace(s)); | ||
| 242 | - SiteTag(prev) | ||
| 243 | - } | ||
| 244 | - } | ||
| 245 | - impl Drop for SiteTag { | ||
| 246 | - fn drop(&mut self) { | ||
| 247 | - SITE.with(|c| c.set(self.0)); | ||
| 248 | - } | ||
| 249 | - } | ||
| 250 | - #[inline] | ||
| 251 | - pub(super) fn site_add(c: u64) { | ||
| 252 | - let s = SITE.with(|c| c.get()); | ||
| 253 | - SITE_COUNTS[s].fetch_add(1, Ordering::Relaxed); | ||
| 254 | - SITE_CYCLES[s].fetch_add(c, Ordering::Relaxed); | ||
| 255 | - } | ||
| 256 | - pub fn site_snapshot() -> Vec<(&'static str, u64, u64)> { | ||
| 257 | - (0..5).map(|i| (SITES[i], SITE_COUNTS[i].load(Ordering::Relaxed), | ||
| 258 | - SITE_CYCLES[i].load(Ordering::Relaxed))).collect() | ||
| 259 | - } | ||
| 260 | - | ||
| 261 | - /// Phase classes: 0 = full-pel (0,0), 1 = half H/V, 2 = half centre (2,2), | ||
| 262 | - /// 3 = quarter (one component odd). | ||
| 263 | - pub const PHASES: [&str; 4] = ["fullpel", "half-HV", "half-ctr", "quarter"]; | ||
| 264 | - /// Size classes: 16×16, 16×8/8×16, 8×8, 8×4/4×8, 4×4, other. | ||
| 265 | - pub const SIZES: [&str; 6] = ["16x16", "16x8/8x16", "8x8", "8x4/4x8", "4x4", "other"]; | ||
| 266 | - | ||
| 267 | - pub static COUNTS: [AtomicU64; 24] = [const { AtomicU64::new(0) }; 24]; | ||
| 268 | - /// Descent E depth-6: CYCLES per bucket. A call-count census is the WRONG | ||
| 269 | - /// denominator for a prune — a full-pel 16x16 is a row copy, a quarter-pel is a | ||
| 270 | - /// per-pixel 6-tap, and they differ ~10x. Weight by time, not by calls. | ||
| 271 | - pub static CYCLES: [AtomicU64; 24] = [const { AtomicU64::new(0) }; 24]; | ||
| 272 | - | ||
| 273 | - #[inline] | ||
| 274 | - pub(super) fn bucket(bw: usize, bh: usize, fx: i32, fy: i32) -> usize { | ||
| 275 | - let size = match (bw, bh) { | ||
| 276 | - (16, 16) => 0, | ||
| 277 | - (16, 8) | (8, 16) => 1, | ||
| 278 | - (8, 8) => 2, | ||
| 279 | - (8, 4) | (4, 8) => 3, | ||
| 280 | - (4, 4) => 4, | ||
| 281 | - _ => 5, | ||
| 282 | - }; | ||
| 283 | - let phase = match (fx, fy) { | ||
| 284 | - (0, 0) => 0, | ||
| 285 | - (2, 2) => 2, | ||
| 286 | - (fx, fy) if fx % 2 == 0 && fy % 2 == 0 => 1, | ||
| 287 | - _ => 3, | ||
| 288 | - }; | ||
| 289 | - size * 4 + phase | ||
| 290 | - } | ||
| 291 | - | ||
| 292 | - #[inline] | ||
| 293 | - pub(super) fn add_cycles(b: usize, c: u64) { | ||
| 294 | - CYCLES[b].fetch_add(c, Ordering::Relaxed); | ||
| 295 | - } | ||
| 296 | - | ||
| 297 | - #[inline] | ||
| 298 | - pub(super) fn record(bw: usize, bh: usize, fx: i32, fy: i32) { | ||
| 299 | - let size = match (bw, bh) { | ||
| 300 | - (16, 16) => 0, | ||
| 301 | - (16, 8) | (8, 16) => 1, | ||
| 302 | - (8, 8) => 2, | ||
| 303 | - (8, 4) | (4, 8) => 3, | ||
| 304 | - (4, 4) => 4, | ||
| 305 | - _ => 5, | ||
| 306 | - }; | ||
| 307 | - let phase = match (fx, fy) { | ||
| 308 | - (0, 0) => 0, | ||
| 309 | - (2, 2) => 2, | ||
| 310 | - (fx, fy) if fx % 2 == 0 && fy % 2 == 0 => 1, | ||
| 311 | - _ => 3, | ||
| 312 | - }; | ||
| 313 | - COUNTS[size * 4 + phase].fetch_add(1, Ordering::Relaxed); | ||
| 314 | - } | ||
| 315 | - | ||
| 316 | - pub fn reset() { | ||
| 317 | - for c in COUNTS.iter() { | ||
| 318 | - c.store(0, Ordering::Relaxed); | ||
| 319 | - } | ||
| 320 | - for c in CYCLES.iter() { | ||
| 321 | - c.store(0, Ordering::Relaxed); | ||
| 322 | - } | ||
| 323 | - for c in SITE_COUNTS.iter() { | ||
| 324 | - c.store(0, Ordering::Relaxed); | ||
| 325 | - } | ||
| 326 | - for c in SITE_CYCLES.iter() { | ||
| 327 | - c.store(0, Ordering::Relaxed); | ||
| 328 | - } | ||
| 329 | - } | ||
| 330 | - | ||
| 331 | - /// `(size, phase, count, cycles)` for every non-empty bucket. | ||
| 332 | - pub fn snapshot_cycles() -> Vec<(&'static str, &'static str, u64, u64)> { | ||
| 333 | - let mut v = Vec::new(); | ||
| 334 | - for i in 0..24 { | ||
| 335 | - let n = COUNTS[i].load(Ordering::Relaxed); | ||
| 336 | - if n != 0 { | ||
| 337 | - v.push((SIZES[i / 4], PHASES[i % 4], n, CYCLES[i].load(Ordering::Relaxed))); | ||
| 338 | - } | ||
| 339 | - } | ||
| 340 | - v | ||
| 341 | - } | ||
| 342 | - | ||
| 343 | - /// `(size_label, phase_label, count)` for every non-empty bucket. | ||
| 344 | - pub fn snapshot() -> Vec<(&'static str, &'static str, u64)> { | ||
| 345 | - let mut v = Vec::new(); | ||
| 346 | - for (i, c) in COUNTS.iter().enumerate() { | ||
| 347 | - let n = c.load(Ordering::Relaxed); | ||
| 348 | - if n > 0 { | ||
| 349 | - v.push((SIZES[i / 4], PHASES[i % 4], n)); | ||
| 350 | - } | ||
| 351 | - } | ||
| 352 | - v | ||
| 353 | - } | ||
| 354 | -} | ||
| 355 | - | ||
| 356 | -/// Extracts the `(bw+5)×(bh+5)` reference neighbourhood around the full-pel origin | ||
| 357 | -/// `(ix0,iy0)` into `t`, clamping at the frame border — the edge-extended input | ||
| 358 | -/// openh264's kernels assume. The block's top-left sample lands at tile `(2,2)`. | ||
| 359 | -/// Returns the tile stride. Every sample in `[0, (bh+5)*ts)` is written. | ||
| 360 | -fn luma_tile_into( | ||
| 361 | - t: &mut [u8], | ||
| 362 | - reference: &[u8], | ||
| 363 | - cw: usize, | ||
| 364 | - ch: usize, | ||
| 365 | - ix0: isize, | ||
| 366 | - iy0: isize, | ||
| 367 | - bw: usize, | ||
| 368 | - bh: usize, | ||
| 369 | -) -> usize { | ||
| 370 | - let ts = bw + 5; | ||
| 371 | - // Interior fast path: the whole `(bw+5)×(bh+5)` halo is inside the frame, so no | ||
| 372 | - // edge clamp is needed. Extract by contiguous row copies (a vectorized memcpy) | ||
| 373 | - // — the unconditional per-pixel `clamp` on the slow path defeats | ||
| 374 | - // autovectorization even when (as here) it would always be a no-op. | ||
| 375 | - if ix0 - 2 >= 0 | ||
| 376 | - && iy0 - 2 >= 0 | ||
| 377 | - && ix0 - 2 + ts as isize <= cw as isize | ||
| 378 | - && iy0 - 2 + (bh + 5) as isize <= ch as isize | ||
| 379 | - && reference.len() >= cw * ch | ||
| 380 | - { | ||
| 381 | - let (rx0, ry0) = ((ix0 - 2) as usize, (iy0 - 2) as usize); | ||
| 382 | - for ty in 0..bh + 5 { | ||
| 383 | - let src = (ry0 + ty) * cw + rx0; | ||
| 384 | - t[ty * ts..ty * ts + ts].copy_from_slice(&reference[src..src + ts]); | ||
| 385 | - } | ||
| 386 | - return ts; | ||
| 387 | - } | ||
| 388 | - for ty in 0..bh + 5 { | ||
| 389 | - let ry = (iy0 - 2 + ty as isize).clamp(0, ch as isize - 1) as usize * cw; | ||
| 390 | - for tx in 0..ts { | ||
| 391 | - let rx = (ix0 - 2 + tx as isize).clamp(0, cw as isize - 1) as usize; | ||
| 392 | - t[ty * ts + tx] = reference.get(ry + rx).copied().unwrap_or(0); | ||
| 393 | - } | ||
| 394 | - } | ||
| 395 | - ts | ||
| 396 | -} | ||
| 397 | - | ||
| 398 | -/// Horizontal half-pel plane (`McHorVer20`): `clip((6tapₕ + 16) >> 5)`, block | ||
| 399 | -/// shifted by `(dr, dc)` tile rows/cols. | ||
| 400 | -fn luma_h(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, dst: &mut [u8]) { | ||
| 401 | - #[cfg(accel)] | ||
| 402 | - if bw == 16 || bw == 8 { | ||
| 403 | - rusty_h264_accel::mc_hor20(t, (2 + dr) * ts + 2 + dc, ts, dst, bw, bh); | ||
| 404 | - return; | ||
| 405 | - } | ||
| 406 | - for r in 0..bh { | ||
| 407 | - let base = (2 + r + dr) * ts + 2 + dc; | ||
| 408 | - for c in 0..bw { | ||
| 409 | - let p = base + c; | ||
| 410 | - let f = t[p - 2] as i32 - 5 * t[p - 1] as i32 + 20 * t[p] as i32 + 20 * t[p + 1] as i32 | ||
| 411 | - - 5 * t[p + 2] as i32 | ||
| 412 | - + t[p + 3] as i32; | ||
| 413 | - dst[r * bw + c] = clip_u8((f + 16) >> 5) as u8; | ||
| 414 | - } | ||
| 415 | - } | ||
| 416 | -} | ||
| 417 | - | ||
| 418 | -/// Vertical half-pel plane (`McHorVer02`): `clip((6tapᵥ + 16) >> 5)`. | ||
| 419 | -fn luma_v(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, dst: &mut [u8]) { | ||
| 420 | - #[cfg(accel)] | ||
| 421 | - if bw == 16 || bw == 8 { | ||
| 422 | - rusty_h264_accel::mc_ver02(t, (2 + dr) * ts + 2 + dc, ts, dst, bw, bh); | ||
| 423 | - return; | ||
| 424 | - } | ||
| 425 | - for r in 0..bh { | ||
| 426 | - let base = (2 + r + dr) * ts + 2 + dc; | ||
| 427 | - for c in 0..bw { | ||
| 428 | - let p = base + c; | ||
| 429 | - let f = t[p - 2 * ts] as i32 - 5 * t[p - ts] as i32 + 20 * t[p] as i32 | ||
| 430 | - + 20 * t[p + ts] as i32 | ||
| 431 | - - 5 * t[p + 2 * ts] as i32 | ||
| 432 | - + t[p + 3 * ts] as i32; | ||
| 433 | - dst[r * bw + c] = clip_u8((f + 16) >> 5) as u8; | ||
| 434 | - } | ||
| 435 | - } | ||
| 436 | -} | ||
| 437 | - | ||
| 438 | -/// Centre half-pel plane (`McHorVer22`): vertical 6-tap to 16-bit intermediates, | ||
| 439 | -/// then horizontal 6-tap — `clip((·+ 512) >> 10)`. | ||
| 440 | -fn luma_centre(t: &[u8], ts: usize, bw: usize, bh: usize, dst: &mut [u8]) { | ||
| 441 | - #[cfg(accel)] | ||
| 442 | - if bw == 16 || bw == 8 { | ||
| 443 | - rusty_h264_accel::mc_centre(t, ts, dst, bw, bh); | ||
| 444 | - return; | ||
| 445 | - } | ||
| 446 | - let mut itmp = [0i32; LUMA_TILE]; | ||
| 447 | - for r in 0..bh { | ||
| 448 | - let base = (2 + r) * ts; | ||
| 449 | - for (j, slot) in itmp[..bw + 5].iter_mut().enumerate() { | ||
| 450 | - let p = base + j; | ||
| 451 | - *slot = t[p - 2 * ts] as i32 - 5 * t[p - ts] as i32 + 20 * t[p] as i32 | ||
| 452 | - + 20 * t[p + ts] as i32 | ||
| 453 | - - 5 * t[p + 2 * ts] as i32 | ||
| 454 | - + t[p + 3 * ts] as i32; | ||
| 455 | - } | ||
| 456 | - for c in 0..bw { | ||
| 457 | - let f = itmp[c] - 5 * itmp[c + 1] + 20 * itmp[c + 2] + 20 * itmp[c + 3] - 5 * itmp[c + 4] | ||
| 458 | - + itmp[c + 5]; | ||
| 459 | - dst[r * bw + c] = clip_u8((f + 512) >> 10) as u8; | ||
| 460 | - } | ||
| 461 | - } | ||
| 462 | -} | ||
| 463 | - | ||
| 464 | -/// `PixelAvg_c`: `(a + b + 1) >> 1` of two clipped planes. | ||
| 465 | -fn pixel_avg(a: &[u8], b: &[u8], bw: usize, bh: usize, dst: &mut [u8]) { | ||
| 466 | - let n = bw * bh; | ||
| 467 | - // Same leak `avg_full` fixed, for the TWO-FILTER quarter positions | ||
| 468 | - // ((1,1)/(3,1)/(1,3)/(3,3) and the centre-adjacent four): the average on | ||
| 469 | - // top of the asm half-pel kernels was a scalar runtime-width loop. The MC | ||
| 470 | - // census prices quarter-pel at ~68% of decoder MC cycles, and the eight | ||
| 471 | - // positions served here all end in this loop. `pavgb` computes | ||
| 472 | - // `(a + b + 1) >> 1` exactly — byte-identical. The scalar loop stays as | ||
| 473 | - // the non-accel path and the oracle. | ||
| 474 | - // | ||
| 475 | - // The TRUE block geometry is passed, never reconstructed from `n`: the | ||
| 476 | - // openh264 row loops are unrolled by more than one row, so a synthetic | ||
| 477 | - // (16, n/16) shape with h < 4 over-runs the block — that was a real | ||
| 478 | - // SEGFAULT on every sub-8x8 stream (first cut of this dispatch, caught by | ||
| 479 | - // the corpus gate). The kernels are exercised at every real (bw, bh ≥ 4) | ||
| 480 | - // shape by `avg_full` already. | ||
| 481 | - #[cfg(accel)] | ||
| 482 | - if (bw == 16 || bw == 8 || bw == 4) && a.len() >= n && b.len() >= n && dst.len() >= n { | ||
| 483 | - rusty_h264_accel::pixel_avg(&mut dst[..n], &a[..n], bw, &b[..n], bw, bw, bh); | ||
| 484 | - return; | ||
| 485 | - } | ||
| 486 | - for i in 0..n { | ||
| 487 | - dst[i] = ((a[i] as i32 + b[i] as i32 + 1) >> 1) as u8; | ||
| 488 | - } | ||
| 489 | -} | ||
| 490 | - | ||
| 491 | -/// `PixelAvg_c` of a half-pel plane with a full-pel block shifted by `(dr, dc)`. | ||
| 492 | -fn avg_full(t: &[u8], ts: usize, bw: usize, bh: usize, dr: usize, dc: usize, half: &[u8], dst: &mut [u8]) { | ||
| 493 | - // The QUARTER-PEL step. `luma_h`/`luma_v`/`luma_centre` have been on asm for a | ||
| 494 | - // long time; this average layered on top of them stayed a scalar per-pixel loop | ||
| 495 | - // with a runtime width. On real x264 streams ~85% of decoder MC cycles are | ||
| 496 | - // quarter-pel, so this loop was handing the kernel's win back on the large | ||
| 497 | - // majority of MC. `pavgb` computes `(a + b + 1) >> 1` exactly — byte-identical. | ||
| 498 | - #[cfg(accel)] | ||
| 499 | - if bw == 16 || bw == 8 || bw == 4 { | ||
| 500 | - let base = (2 + dr) * ts + 2 + dc; | ||
| 501 | - rusty_h264_accel::pixel_avg(dst, &t[base..], ts, half, bw, bw, bh); | ||
| 502 | - return; | ||
| 503 | - } | ||
| 504 | - for r in 0..bh { | ||
| 505 | - let base = (2 + r + dr) * ts + 2 + dc; | ||
| 506 | - for c in 0..bw { | ||
| 507 | - dst[r * bw + c] = ((t[base + c] as i32 + half[r * bw + c] as i32 + 1) >> 1) as u8; | ||
| 508 | - } | ||
| 509 | - } | ||
| 510 | -} | ||
| 511 | - | ||
| 512 | -/// A/B: restore half→scratch→avg compose for one-filter qpel (`RS_H264_QPEL_COMPOSE=1`). | ||
| 513 | -// --- edith patch: both call sites are `#[cfg(accel)]`, so the switch is too. --- | ||
| 514 | -#[cfg(accel)] | ||
| 515 | -#[inline] | ||
| 516 | -fn qpel_compose() -> bool { | ||
| 517 | - use std::sync::OnceLock; | ||
| 518 | - static V: OnceLock<bool> = OnceLock::new(); | ||
| 519 | - *V.get_or_init(|| std::env::var_os("RS_H264_QPEL_COMPOSE").is_some_and(|v| v == "1")) | ||
| 520 | -} | ||
| 521 | - | ||
| 522 | -/// One-filter qpel (`(1,0)/(3,0)/(0,1)/(0,3)`): fused half+avg when accel + w∈{8,16}. | ||
| 523 | -/// `horiz`: horizontal 6-tap; else vertical. `fshift`: full-pel offset (0 or 1) in the | ||
| 524 | -/// filter axis (`fdc` for horiz, `fdr` for vert) — matches `avg_full`'s (0,1)/(1,0). | ||
| 525 | -fn qpel_one_filter( | ||
| 526 | - t: &[u8], | ||
| 527 | - ts: usize, | ||
| 528 | - bw: usize, | ||
| 529 | - bh: usize, | ||
| 530 | - horiz: bool, | ||
| 531 | - fshift: usize, | ||
| 532 | - out: &mut [u8], | ||
| 533 | -) { | ||
| 534 | - #[cfg(accel)] | ||
| 535 | - if !qpel_compose() && (bw == 16 || bw == 8) { | ||
| 536 | - let off = 2 * ts + 2; | ||
| 537 | - if horiz { | ||
| 538 | - rusty_h264_accel::mc_hor_qpel(t, off, ts, out, bw, bh, fshift); | ||
| 539 | - } else { | ||
| 540 | - rusty_h264_accel::mc_ver_qpel(t, off, ts, out, bw, bh, fshift); | ||
| 541 | - } | ||
| 542 | - return; | ||
| 543 | - } | ||
| 544 | - // Compose oracle / narrow widths / non-accel: half into a stack scratch, then avg. | ||
| 545 | - let mut half = [0u8; 256]; | ||
| 546 | - let n = bw * bh; | ||
| 547 | - debug_assert!(n <= 256); | ||
| 548 | - if horiz { | ||
| 549 | - luma_h(t, ts, bw, bh, 0, 0, &mut half[..n]); | ||
| 550 | - avg_full(t, ts, bw, bh, 0, fshift, &half[..n], out); | ||
| 551 | - } else { | ||
| 552 | - luma_v(t, ts, bw, bh, 0, 0, &mut half[..n]); | ||
| 553 | - avg_full(t, ts, bw, bh, fshift, 0, &half[..n], out); | ||
| 554 | - } | ||
| 555 | -} | ||
| 556 | - | ||
| 557 | -/// Two-filter HV qpel: horizontal half into `a`, then vertical half+avg into `out` | ||
| 558 | -/// (kills the second scratch store). Compose oracle when `qpel_compose()`. | ||
| 559 | -fn qpel_hv( | ||
| 560 | - t: &[u8], | ||
| 561 | - ts: usize, | ||
| 562 | - bw: usize, | ||
| 563 | - bh: usize, | ||
| 564 | - hdr: usize, | ||
| 565 | - hdc: usize, | ||
| 566 | - vdr: usize, | ||
| 567 | - vdc: usize, | ||
| 568 | - a: &mut [u8], | ||
| 569 | - out: &mut [u8], | ||
| 570 | -) { | ||
| 571 | - luma_h(t, ts, bw, bh, hdr, hdc, a); | ||
| 572 | - #[cfg(accel)] | ||
| 573 | - if !qpel_compose() && (bw == 16 || bw == 8) { | ||
| 574 | - let off = (2 + vdr) * ts + 2 + vdc; | ||
| 575 | - rusty_h264_accel::mc_ver02_avg(t, off, ts, out, bw, bh, a, bw); | ||
| 576 | - return; | ||
| 577 | - } | ||
| 578 | - let n = bw * bh; | ||
| 579 | - let mut b = [0u8; 256]; | ||
| 580 | - debug_assert!(n <= 256); | ||
| 581 | - luma_v(t, ts, bw, bh, vdr, vdc, &mut b[..n]); | ||
| 582 | - pixel_avg(a, &b[..n], bw, bh, out); | ||
| 583 | -} | ||
| 584 | - | ||
| 585 | -/// The `McLuma_c` `[mvx&3][mvy&3]` dispatch over the clamped tile (sub-pel only; | ||
| 586 | -/// `(0,0)` is handled by the full-pel copy path in [`mc_luma`]). | ||
| 587 | -#[allow(clippy::too_many_arguments)] | ||
| 588 | -fn mc_luma_subpel( | ||
| 589 | - t: &[u8], | ||
| 590 | - ts: usize, | ||
| 591 | - bw: usize, | ||
| 592 | - bh: usize, | ||
| 593 | - fx: i32, | ||
| 594 | - fy: i32, | ||
| 595 | - a: &mut [u8], | ||
| 596 | - b: &mut [u8], | ||
| 597 | - out: &mut [u8], | ||
| 598 | -) { | ||
| 599 | - // `a`/`b` are caller-owned scratch (see `McScratch`): every arm below fully | ||
| 600 | - // writes the `n` samples it later reads, so their prior contents are dead. | ||
| 601 | - // One-filter qpel no longer needs them when fused (see `qpel_one_filter`). | ||
| 602 | - match (fx, fy) { | ||
| 603 | - (2, 0) => luma_h(t, ts, bw, bh, 0, 0, out), | ||
| 604 | - (0, 2) => luma_v(t, ts, bw, bh, 0, 0, out), | ||
| 605 | - (2, 2) => luma_centre(t, ts, bw, bh, out), | ||
| 606 | - // One-filter qpel: fuse half-pel + pavgb (openh264 McHorVer10/30/01/03). | ||
| 607 | - // Compose path (`RS_H264_QPEL_COMPOSE=1`) keeps the scratch store as A/B oracle. | ||
| 608 | - (1, 0) => qpel_one_filter(t, ts, bw, bh, true, 0, out), | ||
| 609 | - (3, 0) => qpel_one_filter(t, ts, bw, bh, true, 1, out), | ||
| 610 | - (0, 1) => qpel_one_filter(t, ts, bw, bh, false, 0, out), | ||
| 611 | - (0, 3) => qpel_one_filter(t, ts, bw, bh, false, 1, out), | ||
| 612 | - (1, 1) => qpel_hv(t, ts, bw, bh, 0, 0, 0, 0, a, out), | ||
| 613 | - (3, 1) => qpel_hv(t, ts, bw, bh, 0, 0, 0, 1, a, out), | ||
| 614 | - (1, 3) => qpel_hv(t, ts, bw, bh, 1, 0, 0, 0, a, out), | ||
| 615 | - (3, 3) => qpel_hv(t, ts, bw, bh, 1, 0, 0, 1, a, out), | ||
| 616 | - (2, 1) => { | ||
| 617 | - luma_h(t, ts, bw, bh, 0, 0, a); | ||
| 618 | - luma_centre(t, ts, bw, bh, b); | ||
| 619 | - pixel_avg(a, b, bw, bh, out); | ||
| 620 | - } | ||
| 621 | - (2, 3) => { | ||
| 622 | - luma_h(t, ts, bw, bh, 1, 0, a); | ||
| 623 | - luma_centre(t, ts, bw, bh, b); | ||
| 624 | - pixel_avg(a, b, bw, bh, out); | ||
| 625 | - } | ||
| 626 | - (1, 2) => { | ||
| 627 | - luma_v(t, ts, bw, bh, 0, 0, a); | ||
| 628 | - luma_centre(t, ts, bw, bh, b); | ||
| 629 | - pixel_avg(a, b, bw, bh, out); | ||
| 630 | - } | ||
| 631 | - (3, 2) => { | ||
| 632 | - luma_v(t, ts, bw, bh, 0, 1, a); | ||
| 633 | - luma_centre(t, ts, bw, bh, b); | ||
| 634 | - pixel_avg(a, b, bw, bh, out); | ||
| 635 | - } | ||
| 636 | - _ => unreachable!("(0,0) is the full-pel path"), | ||
| 637 | - } | ||
| 638 | -} | ||
| 639 | - | ||
| 640 | -/// The three half-pel luma planes of one reference picture, at full frame size. | ||
| 641 | -/// | ||
| 642 | -/// x264 filters these ONCE per reference frame and then every sub-pel motion-search | ||
| 643 | -/// candidate is a strided copy from one plane (half positions) or a 2-tap average of | ||
| 644 | -/// two (quarter positions). We previously re-ran the 6-tap per candidate: measured at | ||
| 645 | -/// 166 s of a 266 s quality-preset encode over 991 M calls, against x264's 188 ms of | ||
| 646 | -/// `hpel-filter` for the entire corpus. | ||
| 647 | -/// | ||
| 648 | -/// Naming follows the spec's sample grid at full-pel `G`: | ||
| 649 | -/// `h` = `b` (half-pel horizontal) · `v` = `h` (half-pel vertical) · `c` = `j` (centre) | ||
| 650 | -#[derive(Clone, Debug)] | ||
| 651 | -pub struct HpelPlanes { | ||
| 652 | - /// Edge-replicated FULL-pel plane. Needed as an operand for the quarter | ||
| 653 | - /// positions that average against `G`, and padded so out-of-frame candidates | ||
| 654 | - /// resolve without a bounds decline. | ||
| 655 | - pub f: Vec<u8>, | ||
| 656 | - pub h: Vec<u8>, | ||
| 657 | - pub v: Vec<u8>, | ||
| 658 | - pub c: Vec<u8>, | ||
| 659 | - /// Row stride of every plane (`cw + 2*HPEL_PAD`). | ||
| 660 | - pub stride: usize, | ||
| 661 | - pub pad: usize, | ||
| 662 | - pub pw: usize, | ||
| 663 | - pub ph: usize, | ||
| 664 | - pub cw: usize, | ||
| 665 | - pub ch: usize, | ||
| 666 | -} | ||
| 667 | - | ||
| 668 | -/// Border added to every cached plane, in samples. | ||
| 669 | -/// | ||
| 670 | -/// Sized so a ±24 motion search around any macroblock still lands inside: a 16-wide | ||
| 671 | -/// block at the right edge reaches `cw + 24`, and reading its `+1` neighbour needs | ||
| 672 | -/// `cw + 41` ≤ `cw + PAD`. Without a border the plane cache DECLINED every candidate | ||
| 673 | -/// whose vector left the picture — 62.5% of the remaining `mc_luma` fallbacks, at | ||
| 674 | -/// ~195 ns against 33 ns for a plane read. | ||
| 675 | -/// | ||
| 676 | -/// SWEPT (foreman / bus / park_joy, `RFF_HPEL_PAD`), because a bigger border is a | ||
| 677 | -/// TRADE — more candidates covered, but a larger working set (4 planes over | ||
| 678 | -/// `(cw+2P)(ch+2P)`) and a costlier per-frame build: | ||
| 679 | -/// | ||
| 680 | -/// | pad | foreman fallbacks | bus | park_joy | build (foreman) | | ||
| 681 | -/// |---|---|---|---|---| | ||
| 682 | -/// | 0 | 207,537 | 838,581 | 6,354,258 | 5.7 ms | | ||
| 683 | -/// | 8 | 127,407 | 774,592 | 6,172,777 | 4.8 ms | | ||
| 684 | -/// | **16** | **127,274** | **765,625** | **6,122,122** | **6.1 ms** | | ||
| 685 | -/// | 32 | 127,262 | 764,999 | 6,093,358 | 9.0 ms | | ||
| 686 | -/// | ||
| 687 | -/// Padding replicated around each cached half-pel plane. | ||
| 688 | -/// | ||
| 689 | -/// 32, raised from 16 after the edge full-pel path landed. The earlier sweep found the | ||
| 690 | -/// pad made NO difference and was correctly recorded as refuted -- but that measurement | ||
| 691 | -/// ran against a population dominated by FULL-PEL declines, which `hpel_ref` now serves. | ||
| 692 | -/// The refutation expired when its baseline moved. Re-swept, pad 32 removes essentially | ||
| 693 | -/// every remaining search fallback (football 17,662 -> 175, foreman 3,238 -> 0). | ||
| 694 | -/// | ||
| 695 | -/// Priced at the PIPELINE level, not by component arithmetic -- the component estimate | ||
| 696 | -/// was wrong in both directions (it mixed an rdtsc cycle census with profiler | ||
| 697 | -/// milliseconds via an assumed clock, and read a 23-sample build cost off single runs). | ||
| 698 | -/// Paired ABBA, median of paired ratios: bus 1.113x (14/14), blue_sky 1.054x (6/6), | ||
| 699 | -/// park_joy 1.050x (11/12), football 1.026x (11/14), foreman 1.015x (ns), | ||
| 700 | -/// crowd_run 1.005x (ns). No clip regresses; the gain tracks edge-overhang density, so | ||
| 701 | -/// fast pans benefit most and large frames least. | ||
| 702 | -/// | ||
| 703 | -/// Byte-identical at 16/32/64 -- a wider pad grows the planes but never changes a value | ||
| 704 | -/// read. `RFF_HPEL_PAD` overrides. | ||
| 705 | -pub const HPEL_PAD_DEFAULT: usize = 32; | ||
| 706 | -pub fn hpel_pad() -> usize { | ||
| 707 | - use std::sync::OnceLock; | ||
| 708 | - static P: OnceLock<usize> = OnceLock::new(); | ||
| 709 | - *P.get_or_init(|| { | ||
| 710 | - std::env::var("RFF_HPEL_PAD") | ||
| 711 | - .ok() | ||
| 712 | - .and_then(|s| s.parse().ok()) | ||
| 713 | - .unwrap_or(HPEL_PAD_DEFAULT) | ||
| 714 | - .clamp(0, 128) | ||
| 715 | - }) | ||
| 716 | -} | ||
| 717 | - | ||
| 718 | -/// Builds the three half-pel planes for `reference` (`cw`×`ch`, MB-aligned). | ||
| 719 | -/// | ||
| 720 | -/// Bit-exact with [`mc_luma`] by CONSTRUCTION: it walks the frame in the same 16×16 | ||
| 721 | -/// blocks, extracts the same clamped halo via [`luma_tile_into`], and runs the same | ||
| 722 | -/// `luma_h`/`luma_v`/`luma_centre` kernels. Each output sample depends only on the | ||
| 723 | -/// six clamped input samples around it, so the value is independent of which block | ||
| 724 | -/// computed it. | ||
| 725 | -/// Edge-replicates a `w`×`h` plane into a `(w+2·pad)`×`(h+2·pad)` padded copy — | ||
| 726 | -/// openh264's `ExpandPicture`. `mc_luma` clamps each tap independently via `at()`, | ||
| 727 | -/// and clamping IS edge replication, so filtering the padded plane is bit-identical | ||
| 728 | -/// to the clamped-read original (the argument `build_hpel_planes` rests on; the | ||
| 729 | -/// decoder's per-reference padding reuses it so per-MC-call tile extraction dies). | ||
| 730 | -pub fn pad_plane(src: &[u8], w: usize, h: usize, pad: usize) -> Vec<u8> { | ||
| 731 | - pad_plane_into(Vec::new(), src, w, h, pad) | ||
| 732 | -} | ||
| 733 | - | ||
| 734 | -/// `pad_plane` reusing a recycled buffer. Every byte of the padded plane is | ||
| 735 | -/// written by the row loop below (left fill + interior copy + right fill, all | ||
| 736 | -/// `ph` rows), so a RIGHT-SIZED recycled buffer needs no clearing at all — and, | ||
| 737 | -/// unlike a fresh `vec![0; n]` (whose zero pages are free but whose first | ||
| 738 | -/// touches page-fault), its pages are already mapped and warm. This is what the | ||
| 739 | -/// earlier pad_plane memset-elimination attempt (refuted, WHYS ledger) was | ||
| 740 | -/// missing: on a FRESH alloc the memset is free; the win only exists when the | ||
| 741 | -/// allocation itself is recycled. | ||
| 742 | -pub fn pad_plane_into(mut f: Vec<u8>, src: &[u8], w: usize, h: usize, pad: usize) -> Vec<u8> { | ||
| 743 | - let (pw, ph) = (w + 2 * pad, h + 2 * pad); | ||
| 744 | - if f.len() != pw * ph { | ||
| 745 | - f.clear(); | ||
| 746 | - f.resize(pw * ph, 0); | ||
| 747 | - } | ||
| 748 | - for y in 0..ph { | ||
| 749 | - let sy = (y as isize - pad as isize).clamp(0, h as isize - 1) as usize; | ||
| 750 | - let row = &src[sy * w..sy * w + w]; | ||
| 751 | - let d = &mut f[y * pw..y * pw + pw]; | ||
| 752 | - d[..pad].fill(row[0]); | ||
| 753 | - d[pad..pad + w].copy_from_slice(row); | ||
| 754 | - d[pad + w..].fill(row[w - 1]); | ||
| 755 | - } | ||
| 756 | - f | ||
| 757 | -} | ||
| 758 | - | ||
| 759 | -pub fn build_hpel_planes(reference: &[u8], cw: usize, ch: usize) -> HpelPlanes { | ||
| 760 | - let _g = crate::prof::scope(crate::prof::Stage::MeHpelBuild); | ||
| 761 | - let pad = hpel_pad(); | ||
| 762 | - let (pw, ph) = (cw + 2 * pad, ch + 2 * pad); | ||
| 763 | - // 1. Edge-replicated source (see `pad_plane` for why this is bit-identical). | ||
| 764 | - let f = pad_plane(reference, cw, ch, pad); | ||
| 765 | - // 2. Filter the three half-pel planes over the padded area. | ||
| 766 | - let mut h = vec![0u8; pw * ph]; | ||
| 767 | - let mut v = vec![0u8; pw * ph]; | ||
| 768 | - let mut c = vec![0u8; pw * ph]; | ||
| 769 | - // Dispatch ladder: the AVX2 FUSED single pass (side-by-side descent: the tile | ||
| 770 | - // walk measured 8× x264's hpel-filter, whose fused shape this kernel mirrors) | ||
| 771 | - // → env-forced scalar fused (RFF_HPEL_FUSED=1, the oracle base) → tile walk. | ||
| 772 | - // All three are byte-identical (`fused_hpel_builder_matches_tiles`, | ||
| 773 | - // `avx2_fused_matches_scalar_fused`); the choice is speed only. | ||
| 774 | - #[cfg(accel)] | ||
| 775 | - let done = !hpel_fused_forced_off() && rusty_h264_accel::hpel_fused(&f, pw, ph, &mut h, &mut v, &mut c); | ||
| 776 | - #[cfg(not(accel))] | ||
| 777 | - let done = false; | ||
| 778 | - if !done { | ||
| 779 | - if hpel_fused_enabled() { | ||
| 780 | - build_hpel_fused(&f, pw, ph, &mut h, &mut v, &mut c); | ||
| 781 | - } else { | ||
| 782 | - build_hpel_tiles(&f, pw, ph, &mut h, &mut v, &mut c); | ||
| 783 | - } | ||
| 784 | - } | ||
| 785 | - HpelPlanes { f, h, v, c, stride: pw, pad, pw, ph, cw, ch } | ||
| 786 | -} | ||
| 787 | - | ||
| 788 | -/// Campaign-3 knob. DEFAULT OFF (the tile walk): the scalar fused pass measured | ||
| 789 | -/// SLOWER than the tile walk (950 vs 617 µs/frame CIF) because the tiles run the | ||
| 790 | -/// SSE2/AVX2 `mc_hor20/ver02/centre` asm kernels — their throughput beats the | ||
| 791 | -/// fused pass's redundancy savings. The fused builder + its byte-identity oracle | ||
| 792 | -/// stay in-tree as the base for a future AVX2 fused kernel (`RFF_HPEL_FUSED=1`), | ||
| 793 | -/// which is the only shape that can beat the tiles. | ||
| 794 | -fn hpel_fused_enabled() -> bool { | ||
| 795 | - use std::sync::OnceLock; | ||
| 796 | - static E: OnceLock<bool> = OnceLock::new(); | ||
| 797 | - *E.get_or_init(|| std::env::var("RFF_HPEL_FUSED").map(|s| s == "1").unwrap_or(false)) | ||
| 798 | -} | ||
| 799 | - | ||
| 800 | -/// `RFF_HPEL_AVX2=0` pins the pre-kernel path (tile walk / scalar fused) for A/B — | ||
| 801 | -/// the AVX2 fused pass is byte-identical, so this is a speed-experiment knob only. | ||
| 802 | -#[cfg(accel)] | ||
| 803 | -fn hpel_fused_forced_off() -> bool { | ||
| 804 | - use std::sync::OnceLock; | ||
| 805 | - static E: OnceLock<bool> = OnceLock::new(); | ||
| 806 | - *E.get_or_init(|| std::env::var("RFF_HPEL_AVX2").map(|s| s == "0").unwrap_or(false)) | ||
| 807 | -} | ||
| 808 | - | ||
| 809 | -/// The ORIGINAL builder — walks 16×16 tiles through `luma_tile_into` + the MC | ||
| 810 | -/// kernels. Kept as the fused builder's oracle and the `RFF_HPEL_FUSED=0` path. | ||
| 811 | -fn build_hpel_tiles(f: &[u8], pw: usize, ph: usize, h: &mut [u8], v: &mut [u8], c: &mut [u8]) { | ||
| 812 | - let mut tile = [0u8; LUMA_TILE * LUMA_TILE]; | ||
| 813 | - let mut blk = [0u8; 256]; | ||
| 814 | - let mut by = 0; | ||
| 815 | - while by < ph { | ||
| 816 | - let mut bx = 0; | ||
| 817 | - while bx < pw { | ||
| 818 | - let bh = 16.min(ph - by); | ||
| 819 | - let bwid = 16.min(pw - bx); | ||
| 820 | - let ts = luma_tile_into(&mut tile, f, pw, ph, bx as isize, by as isize, bwid, bh); | ||
| 821 | - for kind in 0u8..3 { | ||
| 822 | - let plane: &mut [u8] = match kind { | ||
| 823 | - 0 => &mut *h, | ||
| 824 | - 1 => &mut *v, | ||
| 825 | - _ => &mut *c, | ||
| 826 | - }; | ||
| 827 | - match kind { | ||
| 828 | - 0 => luma_h(&tile, ts, bwid, bh, 0, 0, &mut blk), | ||
| 829 | - 1 => luma_v(&tile, ts, bwid, bh, 0, 0, &mut blk), | ||
| 830 | - _ => luma_centre(&tile, ts, bwid, bh, &mut blk), | ||
| 831 | - } | ||
| 832 | - for r in 0..bh { | ||
| 833 | - plane[(by + r) * pw + bx..][..bwid].copy_from_slice(&blk[r * bwid..][..bwid]); | ||
| 834 | - } | ||
| 835 | - } | ||
| 836 | - bx += 16; | ||
| 837 | - } | ||
| 838 | - by += 16; | ||
| 839 | - } | ||
| 840 | -} | ||
| 841 | - | ||
| 842 | -/// Campaign 3 (lets-win-optimize.md): the FUSED single-pass builder — x264's | ||
| 843 | -/// `hpel_filter` shape. The tile walk re-extracts a `(16+5)²` halo per 16×16 block | ||
| 844 | -/// (1.7× redundant reads), re-runs per-tile dispatch, and copies each block out | ||
| 845 | -/// three times; this pass reads each source row band once and writes H, V, C | ||
| 846 | -/// directly. BYTE-IDENTICAL to the tile builder: the same 6-tap integer formulas | ||
| 847 | -/// over the same clamped `f` samples (interior rows/cols never clamp; the ±2/3 | ||
| 848 | -/// borders of the padded plane clamp exactly like `luma_tile_into`'s halo does), | ||
| 849 | -/// and the centre's i32 vertical intermediates reproduce `luma_centre`'s order. | ||
| 850 | -/// Pinned by `fused_hpel_builder_matches_tiles`. | ||
| 851 | -fn build_hpel_fused(f: &[u8], pw: usize, ph: usize, h: &mut [u8], v: &mut [u8], c: &mut [u8]) { | ||
| 852 | - let cl = |i: isize, hi: usize| i.clamp(0, hi as isize - 1) as usize; | ||
| 853 | - // Extended per-row buffers: index j covers column j-2 (clamped into the plane). | ||
| 854 | - let mut vt = vec![0i32; pw + 5]; // vertical 6-tap intermediates (unrounded) | ||
| 855 | - let mut hb = vec![0u8; pw + 5]; // this row's source with clamped column halo | ||
| 856 | - for y in 0..ph { | ||
| 857 | - let (ym2, ym1, y0, yp1, yp2, yp3) = ( | ||
| 858 | - cl(y as isize - 2, ph) * pw, | ||
| 859 | - cl(y as isize - 1, ph) * pw, | ||
| 860 | - y * pw, | ||
| 861 | - cl(y as isize + 1, ph) * pw, | ||
| 862 | - cl(y as isize + 2, ph) * pw, | ||
| 863 | - cl(y as isize + 3, ph) * pw, | ||
| 864 | - ); | ||
| 865 | - // Column-clamped borders (≤5 samples each side); the interior runs with | ||
| 866 | - // DIRECT indices — a per-element clamp in this loop defeats | ||
| 867 | - // autovectorization and measured the whole builder 2.2× slower. | ||
| 868 | - for j in 0..2 { | ||
| 869 | - let x = 0usize; | ||
| 870 | - vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32 | ||
| 871 | - + 20 * f[yp1 + x] as i32 | ||
| 872 | - - 5 * f[yp2 + x] as i32 | ||
| 873 | - + f[yp3 + x] as i32; | ||
| 874 | - hb[j] = f[y0 + x]; | ||
| 875 | - } | ||
| 876 | - for j in 2..pw + 2 { | ||
| 877 | - let x = j - 2; | ||
| 878 | - vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32 | ||
| 879 | - + 20 * f[yp1 + x] as i32 | ||
| 880 | - - 5 * f[yp2 + x] as i32 | ||
| 881 | - + f[yp3 + x] as i32; | ||
| 882 | - hb[j] = f[y0 + x]; | ||
| 883 | - } | ||
| 884 | - for j in pw + 2..pw + 5 { | ||
| 885 | - let x = pw - 1; | ||
| 886 | - vt[j] = f[ym2 + x] as i32 - 5 * f[ym1 + x] as i32 + 20 * f[y0 + x] as i32 | ||
| 887 | - + 20 * f[yp1 + x] as i32 | ||
| 888 | - - 5 * f[yp2 + x] as i32 | ||
| 889 | - + f[yp3 + x] as i32; | ||
| 890 | - hb[j] = f[y0 + x]; | ||
| 891 | - } | ||
| 892 | - let hrow = &mut h[y0..y0 + pw]; | ||
| 893 | - let vrow = &mut v[y0..y0 + pw]; | ||
| 894 | - let crow = &mut c[y0..y0 + pw]; | ||
| 895 | - for x in 0..pw { | ||
| 896 | - vrow[x] = clip_u8((vt[x + 2] + 16) >> 5) as u8; | ||
| 897 | - } | ||
| 898 | - for x in 0..pw { | ||
| 899 | - let s = vt[x] - 5 * vt[x + 1] + 20 * vt[x + 2] + 20 * vt[x + 3] - 5 * vt[x + 4] | ||
| 900 | - + vt[x + 5]; | ||
| 901 | - crow[x] = clip_u8((s + 512) >> 10) as u8; | ||
| 902 | - } | ||
| 903 | - for x in 0..pw { | ||
| 904 | - let s = hb[x] as i32 - 5 * hb[x + 1] as i32 + 20 * hb[x + 2] as i32 | ||
| 905 | - + 20 * hb[x + 3] as i32 | ||
| 906 | - - 5 * hb[x + 4] as i32 | ||
| 907 | - + hb[x + 5] as i32; | ||
| 908 | - hrow[x] = clip_u8((s + 16) >> 5) as u8; | ||
| 909 | - } | ||
| 910 | - } | ||
| 911 | -} | ||
| 912 | - | ||
| 913 | -/// Fills `out` with the `bw`×`bh` sub-pel prediction read from cached planes. | ||
| 914 | -/// | ||
| 915 | -/// Returns `false` when the access (which may reach one sample past the block on | ||
| 916 | -/// either axis, for the `m`/`s` neighbours) is not fully interior — the caller then | ||
| 917 | -/// falls back to [`mc_luma`]. Bit-identical to `mc_luma` wherever it returns `true`: | ||
| 918 | -/// each arm below is the same pair of operands `mc_luma_subpel` averages. | ||
| 919 | -#[allow(clippy::too_many_arguments)] | ||
| 920 | -/// Descent C: half-pel (single-plane, copy-free-able) vs quarter-pel (two-plane average). | ||
| 921 | -#[cfg(feature = "profile")] | ||
| 922 | -pub mod hpelphase { | ||
| 923 | - use core::sync::atomic::{AtomicU64, Ordering}; | ||
| 924 | - pub static C: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; | ||
| 925 | - #[inline] | ||
| 926 | - pub fn bump(i: usize) { C[i].fetch_add(1, Ordering::Relaxed); } | ||
| 927 | - pub fn reset() { for c in C.iter() { c.store(0, Ordering::Relaxed); } } | ||
| 928 | - pub fn snapshot() -> Vec<u64> { C.iter().map(|c| c.load(Ordering::Relaxed)).collect() } | ||
| 929 | -} | ||
| 930 | - | ||
| 931 | -/// Descent C: the SINGLE-PLANE (half-pel) phases — (2,0)->h, (0,2)->v, (2,2)->c — | ||
| 932 | -/// are already contiguous at plane stride, exactly like the interior full-pel case. | ||
| 933 | -/// Hand the consumer `(plane, base, stride)` so it can read them IN PLACE rather than | ||
| 934 | -/// copy 256 bytes into a temp first. Byte-identical to `hpel_block` by construction: | ||
| 935 | -/// same plane, same base, same samples — only the copy is elided. | ||
| 936 | -/// Returns `None` for quarter-pel (a two-plane average, which must be materialized), | ||
| 937 | -/// for out-of-range coordinates, and whenever `hpel_block` would decline. | ||
| 938 | -#[inline] | ||
| 939 | -pub fn hpel_ref<'a>( | ||
| 940 | - p: &'a HpelPlanes, | ||
| 941 | - x0: usize, | ||
| 942 | - y0: usize, | ||
| 943 | - bw: usize, | ||
| 944 | - bh: usize, | ||
| 945 | - mvx: i32, | ||
| 946 | - mvy: i32, | ||
| 947 | -) -> Option<(&'a [u8], usize, usize)> { | ||
| 948 | - let (fx, fy) = (mvx & 3, mvy & 3); | ||
| 949 | - let plane = match (fx, fy) { | ||
| 950 | - (2, 0) => &p.h, | ||
| 951 | - (0, 2) => &p.v, | ||
| 952 | - (2, 2) => &p.c, | ||
| 953 | - // Descent E: FULL-PEL off the frame edge. `hpel_block` declines these before its | ||
| 954 | - // bounds check ("the full-pel copy path is already optimal"), so the caller fell | ||
| 955 | - // back to a per-pixel clamped `mc_luma` -- measured at 76-79% of all mc_luma | ||
| 956 | - // TIME, the single largest consumer of that stage. But `f` IS the padded, | ||
| 957 | - // edge-replicated reference, so it reproduces mc_luma's clamp exactly and can be | ||
| 958 | - // read in place like any other phase. (Widening the pad does NOT fix this: the | ||
| 959 | - // decline count is identical at pad 16 and pad 64 -- it was never a bounds issue.) | ||
| 960 | - (0, 0) => &p.f, | ||
| 961 | - _ => return None, | ||
| 962 | - }; | ||
| 963 | - let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); | ||
| 964 | - let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize); | ||
| 965 | - // Identical guard to `hpel_block`, including its `+1` slack, so the two paths | ||
| 966 | - // accept exactly the same candidate set (no bitstream drift from a wider path). | ||
| 967 | - if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize { | ||
| 968 | - return None; | ||
| 969 | - } | ||
| 970 | - let base = py as usize * p.stride + px as usize; | ||
| 971 | - if base + (bh - 1) * p.stride + bw > plane.len() { | ||
| 972 | - return None; | ||
| 973 | - } | ||
| 974 | - Some((plane, base, p.stride)) | ||
| 975 | -} | ||
| 976 | - | ||
| 977 | -/// Challenge-1 A3: the QUARTER-pel companion of [`hpel_ref`] — resolves the two | ||
| 978 | -/// plane operands whose `(a+b+1)>>1` average IS the prediction, so the ME cost can | ||
| 979 | -/// be one fused avg+SATD kernel pass instead of materialize-256-bytes-then-SATD. | ||
| 980 | -/// Same bounds guard as [`hpel_block`] (identical accepted-candidate set); returns | ||
| 981 | -/// `(plane_a, base_a, plane_b, base_b, stride)`. `None` for non-quarter phases | ||
| 982 | -/// (those are [`hpel_ref`]'s) and whenever `hpel_block` would decline. | ||
| 983 | -#[inline] | ||
| 984 | -pub fn hpel_qpel_refs<'a>( | ||
| 985 | - p: &'a HpelPlanes, | ||
| 986 | - x0: usize, | ||
| 987 | - y0: usize, | ||
| 988 | - bw: usize, | ||
| 989 | - bh: usize, | ||
| 990 | - mvx: i32, | ||
| 991 | - mvy: i32, | ||
| 992 | -) -> Option<(&'a [u8], usize, &'a [u8], usize, usize)> { | ||
| 993 | - let (fx, fy) = (mvx & 3, mvy & 3); | ||
| 994 | - // Quarter phases only: at least one fractional part is odd. | ||
| 995 | - if fx & 1 == 0 && fy & 1 == 0 { | ||
| 996 | - return None; | ||
| 997 | - } | ||
| 998 | - let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); | ||
| 999 | - let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize); | ||
| 1000 | - if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize { | ||
| 1001 | - return None; | ||
| 1002 | - } | ||
| 1003 | - let stride = p.stride; | ||
| 1004 | - let base = py as usize * stride + px as usize; | ||
| 1005 | - let g: &[u8] = &p.f; | ||
| 1006 | - // The SAME operand table as `hpel_block`'s quarter arm (the spec's `m`/`s` | ||
| 1007 | - // neighbour shifts baked into the base offsets). | ||
| 1008 | - let (pa, oa, pb, ob): (&[u8], usize, &[u8], usize) = match (fx, fy) { | ||
| 1009 | - (1, 0) => (g, 0, &p.h, 0), | ||
| 1010 | - (3, 0) => (g, 1, &p.h, 0), | ||
| 1011 | - (0, 1) => (g, 0, &p.v, 0), | ||
| 1012 | - (0, 3) => (g, stride, &p.v, 0), | ||
| 1013 | - (1, 1) => (&p.h, 0, &p.v, 0), | ||
| 1014 | - (3, 1) => (&p.h, 0, &p.v, 1), | ||
| 1015 | - (1, 3) => (&p.h, stride, &p.v, 0), | ||
| 1016 | - (3, 3) => (&p.h, stride, &p.v, 1), | ||
| 1017 | - (2, 1) => (&p.h, 0, &p.c, 0), | ||
| 1018 | - (2, 3) => (&p.h, stride, &p.c, 0), | ||
| 1019 | - (1, 2) => (&p.v, 0, &p.c, 0), | ||
| 1020 | - _ => (&p.v, 1, &p.c, 0), // (3, 2) | ||
| 1021 | - }; | ||
| 1022 | - // Slice-length check so a short plane can never OOB (the `+1` slack in the | ||
| 1023 | - // bounds test above covers the shifted operand's reach geometrically; this | ||
| 1024 | - // makes it a hard guarantee at the slice level too). | ||
| 1025 | - if base + oa + (bh - 1) * stride + bw > pa.len() || base + ob + (bh - 1) * stride + bw > pb.len() { | ||
| 1026 | - return None; | ||
| 1027 | - } | ||
| 1028 | - Some((pa, base + oa, pb, base + ob, stride)) | ||
| 1029 | -} | ||
| 1030 | - | ||
| 1031 | -pub fn hpel_block( | ||
| 1032 | - p: &HpelPlanes, | ||
| 1033 | - x0: usize, | ||
| 1034 | - y0: usize, | ||
| 1035 | - bw: usize, | ||
| 1036 | - bh: usize, | ||
| 1037 | - mvx: i32, | ||
| 1038 | - mvy: i32, | ||
| 1039 | - out: &mut [u8], | ||
| 1040 | -) -> bool { | ||
| 1041 | - let _g = crate::prof::scope(crate::prof::Stage::MeHpel); | ||
| 1042 | - let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); | ||
| 1043 | - let (fx, fy) = (mvx & 3, mvy & 3); | ||
| 1044 | - if fx == 0 && fy == 0 { | ||
| 1045 | - return false; // the full-pel copy path is already optimal | ||
| 1046 | - } | ||
| 1047 | - // Padded coordinates. The `+1` slack covers the `m`/`s` neighbours. | ||
| 1048 | - let (px, py) = (ix0 + p.pad as isize, iy0 + p.pad as isize); | ||
| 1049 | - if px < 0 || py < 0 || px + bw as isize + 1 > p.pw as isize || py + bh as isize + 1 > p.ph as isize { | ||
| 1050 | - return false; | ||
| 1051 | - } | ||
| 1052 | - let stride = p.stride; | ||
| 1053 | - let base = py as usize * stride + px as usize; | ||
| 1054 | - | ||
| 1055 | - let single = match (fx, fy) { | ||
| 1056 | - (2, 0) => Some(&p.h), | ||
| 1057 | - (0, 2) => Some(&p.v), | ||
| 1058 | - (2, 2) => Some(&p.c), | ||
| 1059 | - _ => None, | ||
| 1060 | - }; | ||
| 1061 | - // Descent C: single-plane (half-pel) reads are CONTIGUOUS AT PLANE STRIDE — they | ||
| 1062 | - // could be SATD'd in place like the interior full-pel path instead of copied into | ||
| 1063 | - // a temp. Count the split before building that path. | ||
| 1064 | - #[cfg(feature = "profile")] | ||
| 1065 | - crate::inter::hpelphase::bump(if single.is_some() { 0 } else { 1 }); | ||
| 1066 | - if let Some(src) = single { | ||
| 1067 | - for r in 0..bh { | ||
| 1068 | - out[r * bw..r * bw + bw].copy_from_slice(&src[base + r * stride..][..bw]); | ||
| 1069 | - } | ||
| 1070 | - return true; | ||
| 1071 | - } | ||
| 1072 | - | ||
| 1073 | - // Quarter-pel: (a + b + 1) >> 1 of two planes. The operand table (the spec's | ||
| 1074 | - // `m`/`s` neighbour shifts) lives in ONE place — `hpel_qpel_refs` — so the | ||
| 1075 | - // materializing path here and the fused avg+SATD path can never drift apart. | ||
| 1076 | - let Some((pa, ba, pb, bb, qstride)) = hpel_qpel_refs(p, x0, y0, bw, bh, mvx, mvy) else { | ||
| 1077 | - return false; | ||
| 1078 | - }; | ||
| 1079 | - match bw { | ||
| 1080 | - 16 => avg_rows::<16>(pa, ba, pb, bb, qstride, bh, out), | ||
| 1081 | - 8 => avg_rows::<8>(pa, ba, pb, bb, qstride, bh, out), | ||
| 1082 | - 4 => avg_rows::<4>(pa, ba, pb, bb, qstride, bh, out), | ||
| 1083 | - _ => return false, | ||
| 1084 | - } | ||
| 1085 | - true | ||
| 1086 | -} | ||
| 1087 | - | ||
| 1088 | -#[inline] | ||
| 1089 | -fn avg_rows<const BW: usize>(pa: &[u8], oa: usize, pb: &[u8], ob: usize, cw: usize, bh: usize, out: &mut [u8]) { | ||
| 1090 | - for r in 0..bh { | ||
| 1091 | - let sa = &pa[oa + r * cw..][..BW]; | ||
| 1092 | - let sb = &pb[ob + r * cw..][..BW]; | ||
| 1093 | - let o = &mut out[r * BW..r * BW + BW]; | ||
| 1094 | - for i in 0..BW { | ||
| 1095 | - o[i] = ((sa[i] as u16 + sb[i] as u16 + 1) >> 1) as u8; | ||
| 1096 | - } | ||
| 1097 | - } | ||
| 1098 | -} | ||
| 1099 | - | ||
| 1100 | -/// Quarter-pel motion compensation of a `bw`×`bh` luma block (`McLuma_c`). | ||
| 1101 | -#[allow(clippy::too_many_arguments)] | ||
| 1102 | -/// Descent E: accumulates one `mc_luma` call's cycles into its (size, phase) bucket. | ||
| 1103 | -#[cfg(feature = "profile")] | ||
| 1104 | -struct McCycleGuard { | ||
| 1105 | - b: usize, | ||
| 1106 | - t: u64, | ||
| 1107 | -} | ||
| 1108 | -#[cfg(feature = "profile")] | ||
| 1109 | -impl Drop for McCycleGuard { | ||
| 1110 | - fn drop(&mut self) { | ||
| 1111 | - let c = crate::prof::tick().wrapping_sub(self.t); | ||
| 1112 | - mcstats::add_cycles(self.b, c); | ||
| 1113 | - mcstats::site_add(c); | ||
| 1114 | - } | ||
| 1115 | -} | ||
| 1116 | - | ||
| 1117 | -pub fn mc_luma( | ||
| 1118 | - reference: &[u8], | ||
| 1119 | - cw: usize, | ||
| 1120 | - ch: usize, | ||
| 1121 | - x0: usize, | ||
| 1122 | - y0: usize, | ||
| 1123 | - bw: usize, | ||
| 1124 | - bh: usize, | ||
| 1125 | - mvx: i32, | ||
| 1126 | - mvy: i32, | ||
| 1127 | - out: &mut [u8], | ||
| 1128 | -) { | ||
| 1129 | - let _g = crate::prof::scope(crate::prof::Stage::InterMc); | ||
| 1130 | - if abl_mc() { | ||
| 1131 | - out.fill(128); | ||
| 1132 | - return; | ||
| 1133 | - } | ||
| 1134 | - let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); | ||
| 1135 | - let (fx, fy) = (mvx & 3, mvy & 3); | ||
| 1136 | - #[cfg(feature = "profile")] | ||
| 1137 | - mcstats::record(bw, bh, fx, fy); | ||
| 1138 | - // Descent E: time this call into its (size, phase) bucket. Guard drops at fn end. | ||
| 1139 | - #[cfg(feature = "profile")] | ||
| 1140 | - let _mcg = McCycleGuard { b: mcstats::bucket(bw, bh, fx, fy), t: crate::prof::tick() }; | ||
| 1141 | - if fx == 0 && fy == 0 { | ||
| 1142 | - // Full-pel: a verbatim copy of the reference (`McCopy_c`). Interior → a | ||
| 1143 | - // row-wise slice copy (auto-vectorized); edge → per-pixel clamped. | ||
| 1144 | - if ix0 >= 0 | ||
| 1145 | - && iy0 >= 0 | ||
| 1146 | - && ix0 + bw as isize <= cw as isize | ||
| 1147 | - && iy0 + bh as isize <= ch as isize | ||
| 1148 | - && reference.len() >= cw * ch | ||
| 1149 | - { | ||
| 1150 | - let (rx, ry) = (ix0 as usize, iy0 as usize); | ||
| 1151 | - // Fixed-size fast path for the full 16×16 MB (the overwhelming common | ||
| 1152 | - // case). With `bw` a runtime parameter each `copy_from_slice(..bw)` is a | ||
| 1153 | - // variable-length `memcpy` CALL per row (~38 ns / MB); const-16 slices | ||
| 1154 | - // let LLVM emit inline 16-byte moves (~2 ns / MB). Byte-identical. | ||
| 1155 | - if bw == 16 && bh == 16 { | ||
| 1156 | - for dy in 0..16 { | ||
| 1157 | - let s = &reference[(ry + dy) * cw + rx..]; | ||
| 1158 | - out[dy * 16..dy * 16 + 16].copy_from_slice(&s[..16]); | ||
| 1159 | - } | ||
| 1160 | - } else { | ||
| 1161 | - for dy in 0..bh { | ||
| 1162 | - out[dy * bw..dy * bw + bw] | ||
| 1163 | - .copy_from_slice(&reference[(ry + dy) * cw + rx..][..bw]); | ||
| 1164 | - } | ||
| 1165 | - } | ||
| 1166 | - } else { | ||
| 1167 | - for dy in 0..bh { | ||
| 1168 | - for dx in 0..bw { | ||
| 1169 | - out[dy * bw + dx] = | ||
| 1170 | - at(reference, cw, ch, ix0 + dx as isize, iy0 + dy as isize) as u8; | ||
| 1171 | - } | ||
| 1172 | - } | ||
| 1173 | - } | ||
| 1174 | - return; | ||
| 1175 | - } | ||
| 1176 | - // Sub-pel: extract the clamped tile once, then run the openh264 block kernels. | ||
| 1177 | - // Tile + half-pel staging live in per-thread scratch (see `McScratch`) so the | ||
| 1178 | - // ~1.4 KB of zero-fill and the tile's return-by-value copy are not repaid on | ||
| 1179 | - // every motion-search candidate. Destructuring gives `tile` and `a`/`b` as | ||
| 1180 | - // disjoint borrows of the same scratch. | ||
| 1181 | - MC_SCRATCH.with(|s| { | ||
| 1182 | - let McScratch { tile, a, b } = &mut *s.borrow_mut(); | ||
| 1183 | - let ts = luma_tile_into(tile, reference, cw, ch, ix0, iy0, bw, bh); | ||
| 1184 | - mc_luma_subpel(tile, ts, bw, bh, fx, fy, a, b, out); | ||
| 1185 | - }); | ||
| 1186 | -} | ||
| 1187 | - | ||
| 1188 | -/// Eighth-pel bilinear motion compensation of a `bw`×`bh` chroma block (spec | ||
| 1189 | -/// §8.4.2.2.2). The chroma motion vector equals the luma MV; for 4:2:0 it is | ||
| 1190 | -/// interpreted at eighth-chroma-sample resolution. | ||
| 1191 | -#[allow(clippy::too_many_arguments)] | ||
| 1192 | -pub fn mc_chroma( | ||
| 1193 | - reference: &[u8], | ||
| 1194 | - cw: usize, | ||
| 1195 | - ch: usize, | ||
| 1196 | - x0: usize, | ||
| 1197 | - y0: usize, | ||
| 1198 | - bw: usize, | ||
| 1199 | - bh: usize, | ||
| 1200 | - mvx: i32, | ||
| 1201 | - mvy: i32, | ||
| 1202 | - out: &mut [u8], | ||
| 1203 | -) { | ||
| 1204 | - let _g = crate::prof::scope(crate::prof::Stage::InterMc); | ||
| 1205 | - if abl_mc() { | ||
| 1206 | - out.fill(128); | ||
| 1207 | - return; | ||
| 1208 | - } | ||
| 1209 | - let (ix0, iy0) = (x0 as isize + (mvx >> 3) as isize, y0 as isize + (mvy >> 3) as isize); | ||
| 1210 | - let (fx, fy) = (mvx & 7, mvy & 7); | ||
| 1211 | - // Full-pel and fully inside the frame: `(64·a + 32) >> 6 == a`, a verbatim copy. | ||
| 1212 | - // Skip the per-pixel bilinear + 4× clamped `at()`; copy row-wise. Bit-identical. | ||
| 1213 | - if fx == 0 | ||
| 1214 | - && fy == 0 | ||
| 1215 | - && ix0 >= 0 | ||
| 1216 | - && iy0 >= 0 | ||
| 1217 | - && ix0 + bw as isize <= cw as isize | ||
| 1218 | - && iy0 + bh as isize <= ch as isize | ||
| 1219 | - && reference.len() >= cw * ch | ||
| 1220 | - { | ||
| 1221 | - let (rx, ry) = (ix0 as usize, iy0 as usize); | ||
| 1222 | - // Const-8 fast path for the full 8×8 chroma block (skip / P_16x16 common | ||
| 1223 | - // case): fixed-size slices → inline 8-byte moves, not a runtime-length | ||
| 1224 | - // `memcpy` call per row. Byte-identical. See the luma twin in `mc_luma`. | ||
| 1225 | - if bw == 8 && bh == 8 { | ||
| 1226 | - for dy in 0..8 { | ||
| 1227 | - let src = &reference[(ry + dy) * cw + rx..]; | ||
| 1228 | - out[dy * 8..dy * 8 + 8].copy_from_slice(&src[..8]); | ||
| 1229 | - } | ||
| 1230 | - } else { | ||
| 1231 | - for dy in 0..bh { | ||
| 1232 | - let src = &reference[(ry + dy) * cw + rx..][..bw]; | ||
| 1233 | - out[dy * bw..dy * bw + bw].copy_from_slice(src); | ||
| 1234 | - } | ||
| 1235 | - } | ||
| 1236 | - return; | ||
| 1237 | - } | ||
| 1238 | - // Sub-pel (and full-pel edge): extract the clamped (bw+1)×(bh+1) tile once — | ||
| 1239 | - // the edge-extended input `McChromaWithFragMv_c` reads — then the bilinear | ||
| 1240 | - // `A·p + B·p₊₁ + C·p₊ₛ + D·p₊ₛ₊₁` (`g_kuiABCD` weights), `(·+32)>>6`. A chroma | ||
| 1241 | - // block is at most 8×8 (half a 16×16 MB), so a 9×9 tile suffices. Bit-identical: | ||
| 1242 | - // the clamped tile reproduces `at()`, and full-pel weights give `(64·a+32)>>6==a`. | ||
| 1243 | - let ts = bw + 1; | ||
| 1244 | - let mut t = [0u8; 9 * 9]; | ||
| 1245 | - // Interior fast path (see `luma_tile`): clamp-free contiguous row copies. | ||
| 1246 | - if ix0 >= 0 | ||
| 1247 | - && iy0 >= 0 | ||
| 1248 | - && ix0 + ts as isize <= cw as isize | ||
| 1249 | - && iy0 + (bh + 1) as isize <= ch as isize | ||
| 1250 | - && reference.len() >= cw * ch | ||
| 1251 | - { | ||
| 1252 | - let (rx0, ry0) = (ix0 as usize, iy0 as usize); | ||
| 1253 | - for ty in 0..bh + 1 { | ||
| 1254 | - let src = (ry0 + ty) * cw + rx0; | ||
| 1255 | - t[ty * ts..ty * ts + ts].copy_from_slice(&reference[src..src + ts]); | ||
| 1256 | - } | ||
| 1257 | - } else { | ||
| 1258 | - for ty in 0..bh + 1 { | ||
| 1259 | - let ry = (iy0 + ty as isize).clamp(0, ch as isize - 1) as usize * cw; | ||
| 1260 | - for tx in 0..ts { | ||
| 1261 | - let rx = (ix0 + tx as isize).clamp(0, cw as isize - 1) as usize; | ||
| 1262 | - t[ty * ts + tx] = reference.get(ry + rx).copied().unwrap_or(0); | ||
| 1263 | - } | ||
| 1264 | - } | ||
| 1265 | - } | ||
| 1266 | - let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy); | ||
| 1267 | - // 8-wide chroma (full-MB and 16×16-partition chroma — the common case) → the | ||
| 1268 | - // openh264 SSE2 bilinear over the same clamped tile. Width 2/4 stay scalar | ||
| 1269 | - // (width-4 is only an MMX kernel; width 2 has none). Bit-identical. | ||
| 1270 | - #[cfg(accel)] | ||
| 1271 | - if bw == 8 { | ||
| 1272 | - let abcd = [wa as u8, wb as u8, wc as u8, wd as u8]; | ||
| 1273 | - rusty_h264_accel::mc_chroma_w8(&t, ts, out, bw, &abcd, bh); | ||
| 1274 | - return; | ||
| 1275 | - } | ||
| 1276 | - for r in 0..bh { | ||
| 1277 | - for c in 0..bw { | ||
| 1278 | - let p = r * ts + c; | ||
| 1279 | - let v = wa * t[p] as i32 | ||
| 1280 | - + wb * t[p + 1] as i32 | ||
| 1281 | - + wc * t[p + ts] as i32 | ||
| 1282 | - + wd * t[p + ts + 1] as i32; | ||
| 1283 | - out[r * bw + c] = ((v + 32) >> 6) as u8; | ||
| 1284 | - } | ||
| 1285 | - } | ||
| 1286 | -} | ||
| 1287 | - | ||
| 1288 | -// ---- Padded-reference MC (openh264 ExpandPicture style) ---- | ||
| 1289 | -// | ||
| 1290 | -// A reference plane is stored with a replicated-edge border (`PAD_L` luma / | ||
| 1291 | -// `PAD_C` chroma pixels), the picture origin at `(pad, pad)` and `stride` = the | ||
| 1292 | -// padded width. MC then reads the frame DIRECTLY at the MV offset — no per-call | ||
| 1293 | -// clamped tile — because reads into the border hit valid replicated pixels. For | ||
| 1294 | -// the rare MV whose 6-tap halo would exceed the border, we fall back to the | ||
| 1295 | -// clamped tile (reading the padded interior), which is bit-identical to the | ||
| 1296 | -// exact-frame path. | ||
| 1297 | -// | ||
| 1298 | -// STATUS: implemented + bit-exact (the `mc_*_padded_matches_exact` tests + a full | ||
| 1299 | -// decoder wiring verified 35/35 corpus MATCH), but measured **~0** vs the tile | ||
| 1300 | -// path on x86-64 — once `luma_tile`'s interior fast path made extraction a | ||
| 1301 | -// vectorized copy, the remaining win (skipping the copy) is offset by the | ||
| 1302 | -// padded direct read's worse kernel cache locality (full-frame stride vs the | ||
| 1303 | -// L1-resident tile) plus the per-frame expand/copy cost. Kept UNWIRED as a ready | ||
| 1304 | -// option for a workload/target where tile extraction dominates (e.g. slower | ||
| 1305 | -// memory, or hand-asm kernels tuned for the big-stride read). To wire: store | ||
| 1306 | -// `RefFrame` planes padded (`expand_plane` in `as_reference`) and call these | ||
| 1307 | -// instead of `mc_luma`/`mc_chroma`. | ||
| 1308 | - | ||
| 1309 | -/// Luma reference border width (covers full-pel MVs to ±30 px before fallback). | ||
| 1310 | -pub const PAD_L: usize = 32; | ||
| 1311 | -/// Chroma reference border width (= `PAD_L`/2, matching the half-rate chroma MV). | ||
| 1312 | -pub const PAD_C: usize = 16; | ||
| 1313 | - | ||
| 1314 | -/// Fills the `pad`-wide replicated-edge border of a plane whose picture (`pw×ph`) | ||
| 1315 | -/// sits at offset `(pad, pad)` with `stride`. Mirrors openh264 `ExpandPictureLuma_c`: | ||
| 1316 | -/// left/right cols replicate the edge pixel; top/bottom rows replicate the (already | ||
| 1317 | -/// edge-filled) first/last picture row, so the corners come out right. | ||
| 1318 | -pub fn expand_plane(buf: &mut [u8], stride: usize, pad: usize, pw: usize, ph: usize) { | ||
| 1319 | - for y in 0..ph { | ||
| 1320 | - let row = (y + pad) * stride; | ||
| 1321 | - let (left, right) = (buf[row + pad], buf[row + pad + pw - 1]); | ||
| 1322 | - for x in 0..pad { | ||
| 1323 | - buf[row + x] = left; | ||
| 1324 | - buf[row + pad + pw + x] = right; | ||
| 1325 | - } | ||
| 1326 | - } | ||
| 1327 | - let first = pad * stride; | ||
| 1328 | - let last = (pad + ph - 1) * stride; | ||
| 1329 | - for y in 0..pad { | ||
| 1330 | - buf.copy_within(first..first + stride, y * stride); | ||
| 1331 | - buf.copy_within(last..last + stride, (pad + ph + y) * stride); | ||
| 1332 | - } | ||
| 1333 | -} | ||
| 1334 | - | ||
| 1335 | -/// Quarter-pel luma MC reading a padded reference directly (no clamped tile when | ||
| 1336 | -/// the halo is in-border). `x0,y0` are the block's picture coords; `stride`/`pad` | ||
| 1337 | -/// describe the padded plane; `pw,ph` are the picture dims. Bit-identical to | ||
| 1338 | -/// [`mc_luma`] on the equivalent exact frame. | ||
| 1339 | -#[allow(clippy::too_many_arguments)] | ||
| 1340 | -/// MEASUREMENT KNOB — `RFF_ABL_MC=1` makes both padded motion-compensation | ||
| 1341 | -/// primitives return immediately with a flat block, pricing INTER PREDICTION by | ||
| 1342 | -/// ablation on the UNINSTRUMENTED binary. | ||
| 1343 | -/// | ||
| 1344 | -/// Placed inside the two primitives rather than at their ~13 decoder call sites so | ||
| 1345 | -/// the ablation cannot miss one, and so every caller, every call COUNT and all the | ||
| 1346 | -/// surrounding glue (partition walk, MV derivation, buffer setup) stay exactly as | ||
| 1347 | -/// they were — what is priced is the interpolation work itself, nothing else. | ||
| 1348 | -/// | ||
| 1349 | -/// Frame count is unaffected: parsing and residual decoding are untouched. Output | ||
| 1350 | -/// pixels are wrong while this is set, by design — it is never a shipping path. | ||
| 1351 | -/// Read once; the branch predicts perfectly. | ||
| 1352 | -#[inline] | ||
| 1353 | -pub(crate) fn abl_mc() -> bool { | ||
| 1354 | - use std::sync::atomic::{AtomicU8, Ordering}; | ||
| 1355 | - static ON: AtomicU8 = AtomicU8::new(0); | ||
| 1356 | - match ON.load(Ordering::Relaxed) { | ||
| 1357 | - 1 => true, | ||
| 1358 | - 2 => false, | ||
| 1359 | - _ => { | ||
| 1360 | - let on = std::env::var_os("RFF_ABL_MC").is_some_and(|v| v != "0"); | ||
| 1361 | - ON.store(if on { 1 } else { 2 }, Ordering::Relaxed); | ||
| 1362 | - on | ||
| 1363 | - } | ||
| 1364 | - } | ||
| 1365 | -} | ||
| 1366 | - | ||
| 1367 | -pub fn mc_luma_padded( | ||
| 1368 | - padded: &[u8], | ||
| 1369 | - stride: usize, | ||
| 1370 | - pad: usize, | ||
| 1371 | - pw: usize, | ||
| 1372 | - ph: usize, | ||
| 1373 | - x0: usize, | ||
| 1374 | - y0: usize, | ||
| 1375 | - bw: usize, | ||
| 1376 | - bh: usize, | ||
| 1377 | - mvx: i32, | ||
| 1378 | - mvy: i32, | ||
| 1379 | - out: &mut [u8], | ||
| 1380 | -) { | ||
| 1381 | - with_mc_scratch(|scr| mc_luma_padded_pre(scr, padded, stride, pad, pw, ph, x0, y0, bw, bh, mvx, mvy, out)) | ||
| 1382 | -} | ||
| 1383 | - | ||
| 1384 | -/// [`mc_luma_padded`] with the scratch pre-borrowed (see [`with_mc_scratch`]). | ||
| 1385 | -#[allow(clippy::too_many_arguments)] | ||
| 1386 | -pub fn mc_luma_padded_pre( | ||
| 1387 | - scr: &mut McScratch, | ||
| 1388 | - padded: &[u8], | ||
| 1389 | - stride: usize, | ||
| 1390 | - pad: usize, | ||
| 1391 | - pw: usize, | ||
| 1392 | - ph: usize, | ||
| 1393 | - x0: usize, | ||
| 1394 | - y0: usize, | ||
| 1395 | - bw: usize, | ||
| 1396 | - bh: usize, | ||
| 1397 | - mvx: i32, | ||
| 1398 | - mvy: i32, | ||
| 1399 | - out: &mut [u8], | ||
| 1400 | -) { | ||
| 1401 | - let _g = crate::prof::scope(crate::prof::Stage::InterMc); | ||
| 1402 | - let (ix0, iy0) = (x0 as isize + (mvx >> 2) as isize, y0 as isize + (mvy >> 2) as isize); | ||
| 1403 | - let (fx, fy) = (mvx & 3, mvy & 3); | ||
| 1404 | - // Size x phase census for the DECODER's MC. The facility existed but was wired | ||
| 1405 | - // only into `mc_luma` (the encoder's), so the decoder's own distribution had | ||
| 1406 | - // never been measured -- and it is the one that decides which const-width fast | ||
| 1407 | - // paths are worth having. | ||
| 1408 | - #[cfg(feature = "profile")] | ||
| 1409 | - mcstats::record(bw, bh, fx, fy); | ||
| 1410 | - #[cfg(feature = "profile")] | ||
| 1411 | - let _mcg = McCycleGuard { b: mcstats::bucket(bw, bh, fx, fy), t: crate::prof::tick() }; | ||
| 1412 | - let p = pad as isize; | ||
| 1413 | - let (lo_x, lo_y) = (ix0 - 2, iy0 - 2); | ||
| 1414 | - // Malformed-stream armor: a mutated stream can hand a reference whose plane | ||
| 1415 | - // no longer matches the caller's geometry (mid-stream SPS change). The fast | ||
| 1416 | - // paths index arithmetically, so they require the buffer to be intact; the | ||
| 1417 | - // fallback below reads checked. One compare on the hot path. | ||
| 1418 | - let intact = stride >= pw + 2 * pad && padded.len() >= stride * (ph + 2 * pad); | ||
| 1419 | - let in_range = intact | ||
| 1420 | - && lo_x >= -p | ||
| 1421 | - && lo_y >= -p | ||
| 1422 | - && lo_x + (bw + 5) as isize <= pw as isize + p | ||
| 1423 | - && lo_y + (bh + 5) as isize <= ph as isize + p; | ||
| 1424 | - if in_range { | ||
| 1425 | - if fx == 0 && fy == 0 { | ||
| 1426 | - // CONST-WIDTH row copies. With a runtime `bw` each row lowers to a | ||
| 1427 | - // variable-length `memcpy` CALL, and the census priced a 16x16 full-pel | ||
| 1428 | - // copy at 377 cycles -- ~10x what 256 bytes should cost. H.264 emits | ||
| 1429 | - // only these five widths. | ||
| 1430 | - macro_rules! rows { | ||
| 1431 | - ($n:expr) => {{ | ||
| 1432 | - for dy in 0..bh { | ||
| 1433 | - let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize; | ||
| 1434 | - out[dy * $n..dy * $n + $n].copy_from_slice(&padded[src..src + $n]); | ||
| 1435 | - } | ||
| 1436 | - }}; | ||
| 1437 | - } | ||
| 1438 | - match bw { | ||
| 1439 | - 16 => rows!(16), | ||
| 1440 | - 8 => rows!(8), | ||
| 1441 | - 4 => rows!(4), | ||
| 1442 | - _ => { | ||
| 1443 | - for dy in 0..bh { | ||
| 1444 | - let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize; | ||
| 1445 | - out[dy * bw..dy * bw + bw].copy_from_slice(&padded[src..src + bw]); | ||
| 1446 | - } | ||
| 1447 | - } | ||
| 1448 | - } | ||
| 1449 | - } else { | ||
| 1450 | - let halo = ((lo_y + p) as usize) * stride + (lo_x + p) as usize; | ||
| 1451 | - mc_luma_subpel(&padded[halo..], stride, bw, bh, fx, fy, &mut scr.a, &mut scr.b, out); | ||
| 1452 | - } | ||
| 1453 | - return; | ||
| 1454 | - } | ||
| 1455 | - // Extreme MV: clamp the halo to the real picture, read the padded interior. | ||
| 1456 | - let ts = bw + 5; | ||
| 1457 | - let mut t = [0u8; LUMA_TILE * LUMA_TILE]; | ||
| 1458 | - for ty in 0..bh + 5 { | ||
| 1459 | - let py = (lo_y + ty as isize).clamp(0, ph as isize - 1) as usize; | ||
| 1460 | - let ry = (py + pad) * stride; | ||
| 1461 | - for tx in 0..ts { | ||
| 1462 | - let px = (lo_x + tx as isize).clamp(0, pw as isize - 1) as usize; | ||
| 1463 | - // Checked: on intact buffers this never misses; on malformed ones a | ||
| 1464 | - // grey sample beats a panic (no conformance duty on garbage input). | ||
| 1465 | - t[ty * ts + tx] = padded.get(ry + px + pad).copied().unwrap_or(128); | ||
| 1466 | - } | ||
| 1467 | - } | ||
| 1468 | - if fx == 0 && fy == 0 { | ||
| 1469 | - for dy in 0..bh { | ||
| 1470 | - let s = (dy + 2) * ts + 2; | ||
| 1471 | - out[dy * bw..dy * bw + bw].copy_from_slice(&t[s..s + bw]); | ||
| 1472 | - } | ||
| 1473 | - } else { | ||
| 1474 | - mc_luma_subpel(&t, ts, bw, bh, fx, fy, &mut scr.a, &mut scr.b, out); | ||
| 1475 | - } | ||
| 1476 | -} | ||
| 1477 | - | ||
| 1478 | -/// Eighth-pel chroma MC reading a padded reference directly. Bit-identical to | ||
| 1479 | -/// [`mc_chroma`] on the equivalent exact frame. | ||
| 1480 | -#[allow(clippy::too_many_arguments)] | ||
| 1481 | -pub fn mc_chroma_padded( | ||
| 1482 | - padded: &[u8], | ||
| 1483 | - stride: usize, | ||
| 1484 | - pad: usize, | ||
| 1485 | - pw: usize, | ||
| 1486 | - ph: usize, | ||
| 1487 | - x0: usize, | ||
| 1488 | - y0: usize, | ||
| 1489 | - bw: usize, | ||
| 1490 | - bh: usize, | ||
| 1491 | - mvx: i32, | ||
| 1492 | - mvy: i32, | ||
| 1493 | - out: &mut [u8], | ||
| 1494 | -) { | ||
| 1495 | - let _g = crate::prof::scope(crate::prof::Stage::InterMc); | ||
| 1496 | - let (ix0, iy0) = (x0 as isize + (mvx >> 3) as isize, y0 as isize + (mvy >> 3) as isize); | ||
| 1497 | - let (fx, fy) = (mvx & 7, mvy & 7); | ||
| 1498 | - let p = pad as isize; | ||
| 1499 | - let intact = stride >= pw + 2 * pad && padded.len() >= stride * (ph + 2 * pad); | ||
| 1500 | - let in_range = intact | ||
| 1501 | - && ix0 >= -p | ||
| 1502 | - && iy0 >= -p | ||
| 1503 | - && ix0 + (bw + 1) as isize <= pw as isize + p | ||
| 1504 | - && iy0 + (bh + 1) as isize <= ph as isize + p; | ||
| 1505 | - let (wa, wb, wc, wd) = ((8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy); | ||
| 1506 | - if in_range { | ||
| 1507 | - if fx == 0 && fy == 0 { | ||
| 1508 | - for dy in 0..bh { | ||
| 1509 | - let src = ((iy0 + dy as isize + p) as usize) * stride + (ix0 + p) as usize; | ||
| 1510 | - out[dy * bw..dy * bw + bw].copy_from_slice(&padded[src..src + bw]); | ||
| 1511 | - } | ||
| 1512 | - return; | ||
| 1513 | - } | ||
| 1514 | - let halo = ((iy0 + p) as usize) * stride + (ix0 + p) as usize; | ||
| 1515 | - #[cfg(accel)] | ||
| 1516 | - { | ||
| 1517 | - // H-38: BOTH widths now take asm. The 4-wide path was missing, so every | ||
| 1518 | - // 8×8 B-direct sub-block and sub-8×8 partition fell to the scalar | ||
| 1519 | - // bilinear below — chroma MC then cost as much as luma on half the | ||
| 1520 | - // pixels. Both kernels are pinned bit-identical to that scalar arm. | ||
| 1521 | - let abcd = [wa as u8, wb as u8, wc as u8, wd as u8]; | ||
| 1522 | - if bw == 8 { | ||
| 1523 | - rusty_h264_accel::mc_chroma_w8(&padded[halo..], stride, out, bw, &abcd, bh); | ||
| 1524 | - return; | ||
| 1525 | - } | ||
| 1526 | - if bw == 4 { | ||
| 1527 | - rusty_h264_accel::mc_chroma_w4(&padded[halo..], stride, out, bw, &abcd, bh); | ||
| 1528 | - return; | ||
| 1529 | - } | ||
| 1530 | - } | ||
| 1531 | - for r in 0..bh { | ||
| 1532 | - for c in 0..bw { | ||
| 1533 | - let pp = halo + r * stride + c; | ||
| 1534 | - let v = wa * padded[pp] as i32 | ||
| 1535 | - + wb * padded[pp + 1] as i32 | ||
| 1536 | - + wc * padded[pp + stride] as i32 | ||
| 1537 | - + wd * padded[pp + stride + 1] as i32; | ||
| 1538 | - out[r * bw + c] = ((v + 32) >> 6) as u8; | ||
| 1539 | - } | ||
| 1540 | - } | ||
| 1541 | - return; | ||
| 1542 | - } | ||
| 1543 | - // Extreme MV: clamp the (bw+1)² halo to the real picture, read the padded interior. | ||
| 1544 | - let ts = bw + 1; | ||
| 1545 | - let mut t = [0u8; 9 * 9]; | ||
| 1546 | - for ty in 0..bh + 1 { | ||
| 1547 | - let py = (iy0 + ty as isize).clamp(0, ph as isize - 1) as usize; | ||
| 1548 | - let ry = (py + pad) * stride; | ||
| 1549 | - for tx in 0..ts { | ||
| 1550 | - let px = (ix0 + tx as isize).clamp(0, pw as isize - 1) as usize; | ||
| 1551 | - t[ty * ts + tx] = padded.get(ry + px + pad).copied().unwrap_or(128); | ||
| 1552 | - } | ||
| 1553 | - } | ||
| 1554 | - for r in 0..bh { | ||
| 1555 | - for c in 0..bw { | ||
| 1556 | - let pp = r * ts + c; | ||
| 1557 | - let v = wa * t[pp] as i32 | ||
| 1558 | - + wb * t[pp + 1] as i32 | ||
| 1559 | - + wc * t[pp + ts] as i32 | ||
| 1560 | - + wd * t[pp + ts + 1] as i32; | ||
| 1561 | - out[r * bw + c] = ((v + 32) >> 6) as u8; | ||
| 1562 | - } | ||
| 1563 | - } | ||
| 1564 | -} | ||
| 1565 | - | ||
| 1566 | -#[cfg(test)] | ||
| 1567 | -mod tests { | ||
| 1568 | - use super::*; | ||
| 1569 | - | ||
| 1570 | - fn rand_plane(pw: usize, ph: usize, seed: u32) -> Vec<u8> { | ||
| 1571 | - let mut s = seed; | ||
| 1572 | - (0..pw * ph) | ||
| 1573 | - .map(|_| { | ||
| 1574 | - s = s.wrapping_mul(1103515245).wrapping_add(12345); | ||
| 1575 | - (s >> 16) as u8 | ||
| 1576 | - }) | ||
| 1577 | - .collect() | ||
| 1578 | - } | ||
| 1579 | - | ||
| 1580 | - fn make_padded(exact: &[u8], pw: usize, ph: usize, pad: usize) -> (Vec<u8>, usize) { | ||
| 1581 | - let stride = pw + 2 * pad; | ||
| 1582 | - let mut padded = vec![0u8; stride * (ph + 2 * pad)]; | ||
| 1583 | - for y in 0..ph { | ||
| 1584 | - let d = (y + pad) * stride + pad; | ||
| 1585 | - padded[d..d + pw].copy_from_slice(&exact[y * pw..y * pw + pw]); | ||
| 1586 | - } | ||
| 1587 | - expand_plane(&mut padded, stride, pad, pw, ph); | ||
| 1588 | - (padded, stride) | ||
| 1589 | - } | ||
| 1590 | - | ||
| 1591 | - #[test] | ||
| 1592 | - fn mc_luma_padded_matches_exact() { | ||
| 1593 | - let (pw, ph) = (48usize, 32usize); | ||
| 1594 | - let exact = rand_plane(pw, ph, 0x77); | ||
| 1595 | - let (padded, stride) = make_padded(&exact, pw, ph, PAD_L); | ||
| 1596 | - for &(bw, bh) in &[(16usize, 16usize), (8, 8), (16, 8), (8, 16), (4, 4)] { | ||
| 1597 | - for x0 in [0usize, 8, pw - bw] { | ||
| 1598 | - for y0 in [0usize, 8, ph - bh] { | ||
| 1599 | - for mvx in [-40i32, -20, -3, 0, 1, 2, 3, 7, 20, 40] { | ||
| 1600 | - for mvy in [-40i32, -20, -3, 0, 1, 2, 3, 7, 20, 40] { | ||
| 1601 | - let mut a = vec![0u8; bw * bh]; | ||
| 1602 | - let mut b = vec![0u8; bw * bh]; | ||
| 1603 | - mc_luma(&exact, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut a); | ||
| 1604 | - mc_luma_padded( | ||
| 1605 | - &padded, stride, PAD_L, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut b, | ||
| 1606 | - ); | ||
| 1607 | - assert_eq!(a, b, "luma bw={bw} x0={x0} y0={y0} mv=({mvx},{mvy})"); | ||
| 1608 | - } | ||
| 1609 | - } | ||
| 1610 | - } | ||
| 1611 | - } | ||
| 1612 | - } | ||
| 1613 | - } | ||
| 1614 | - | ||
| 1615 | - #[test] | ||
| 1616 | - fn mc_chroma_padded_matches_exact() { | ||
| 1617 | - let (pw, ph) = (24usize, 16usize); | ||
| 1618 | - let exact = rand_plane(pw, ph, 0x99); | ||
| 1619 | - let (padded, stride) = make_padded(&exact, pw, ph, PAD_C); | ||
| 1620 | - for &(bw, bh) in &[(8usize, 8usize), (4, 4), (8, 4), (4, 8), (2, 2)] { | ||
| 1621 | - for x0 in [0usize, 4, pw - bw] { | ||
| 1622 | - for y0 in [0usize, 4, ph - bh] { | ||
| 1623 | - for mvx in [-40i32, -16, -3, 0, 1, 5, 8, 16, 40] { | ||
| 1624 | - for mvy in [-40i32, -16, -3, 0, 1, 5, 8, 16, 40] { | ||
| 1625 | - let mut a = vec![0u8; bw * bh]; | ||
| 1626 | - let mut b = vec![0u8; bw * bh]; | ||
| 1627 | - mc_chroma(&exact, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut a); | ||
| 1628 | - mc_chroma_padded( | ||
| 1629 | - &padded, stride, PAD_C, pw, ph, x0, y0, bw, bh, mvx, mvy, &mut b, | ||
| 1630 | - ); | ||
| 1631 | - assert_eq!(a, b, "chroma bw={bw} x0={x0} y0={y0} mv=({mvx},{mvy})"); | ||
| 1632 | - } | ||
| 1633 | - } | ||
| 1634 | - } | ||
| 1635 | - } | ||
| 1636 | - } | ||
| 1637 | - } | ||
| 1638 | - | ||
| 1639 | - /// Campaign-3 oracle: the fused single-pass builder must fill H/V/C | ||
| 1640 | - /// byte-for-byte like the tile-walk builder, across geometries whose padded | ||
| 1641 | - /// dimensions are and are not multiples of 16 (partial edge tiles) and with | ||
| 1642 | - /// enough randomness to exercise the clip. | ||
| 1643 | - #[test] | ||
| 1644 | - fn fused_hpel_builder_matches_tiles() { | ||
| 1645 | - let mut st = 0x5eed_f00d_dead_beefu64; | ||
| 1646 | - let mut lcg = move || { | ||
| 1647 | - st = st.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); | ||
| 1648 | - (st >> 33) as u8 | ||
| 1649 | - }; | ||
| 1650 | - for &(cw, ch, pad) in &[(64usize, 48usize, 16usize), (80, 64, 12), (176, 144, 32)] { | ||
| 1651 | - let reference: Vec<u8> = (0..cw * ch).map(|_| lcg()).collect(); | ||
| 1652 | - let (pw, ph) = (cw + 2 * pad, ch + 2 * pad); | ||
| 1653 | - // The same edge-replicated padded source `build_hpel_planes` constructs. | ||
| 1654 | - let mut f = vec![0u8; pw * ph]; | ||
| 1655 | - for y in 0..ph { | ||
| 1656 | - let sy = (y as isize - pad as isize).clamp(0, ch as isize - 1) as usize; | ||
| 1657 | - let row = &reference[sy * cw..sy * cw + cw]; | ||
| 1658 | - let d = &mut f[y * pw..y * pw + pw]; | ||
| 1659 | - d[..pad].fill(row[0]); | ||
| 1660 | - d[pad..pad + cw].copy_from_slice(row); | ||
| 1661 | - d[pad + cw..].fill(row[cw - 1]); | ||
| 1662 | - } | ||
| 1663 | - let (mut h1, mut v1, mut c1) = (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]); | ||
| 1664 | - let (mut h2, mut v2, mut c2) = (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]); | ||
| 1665 | - build_hpel_tiles(&f, pw, ph, &mut h1, &mut v1, &mut c1); | ||
| 1666 | - build_hpel_fused(&f, pw, ph, &mut h2, &mut v2, &mut c2); | ||
| 1667 | - assert_eq!(h1, h2, "H plane differs at {cw}x{ch} pad {pad}"); | ||
| 1668 | - assert_eq!(v1, v2, "V plane differs at {cw}x{ch} pad {pad}"); | ||
| 1669 | - assert_eq!(c1, c2, "C plane differs at {cw}x{ch} pad {pad}"); | ||
| 1670 | - // AVX2 fused kernel: byte-identical to the scalar fused builder (and | ||
| 1671 | - // transitively to the tiles) on every geometry, including widths whose | ||
| 1672 | - // vector interior leaves scalar tails. | ||
| 1673 | - #[cfg(accel)] | ||
| 1674 | - { | ||
| 1675 | - let (mut h3, mut v3, mut c3) = | ||
| 1676 | - (vec![0u8; pw * ph], vec![0u8; pw * ph], vec![0u8; pw * ph]); | ||
| 1677 | - if rusty_h264_accel::hpel_fused(&f, pw, ph, &mut h3, &mut v3, &mut c3) { | ||
| 1678 | - assert_eq!(h1, h3, "AVX2 H plane differs at {cw}x{ch} pad {pad}"); | ||
| 1679 | - assert_eq!(v1, v3, "AVX2 V plane differs at {cw}x{ch} pad {pad}"); | ||
| 1680 | - assert_eq!(c1, c3, "AVX2 C plane differs at {cw}x{ch} pad {pad}"); | ||
| 1681 | - } | ||
| 1682 | - } | ||
| 1683 | - } | ||
| 1684 | - } | ||
| 1685 | - | ||
| 1686 | - /// The plane cache must be BIT-IDENTICAL to `mc_luma` wherever it applies — | ||
| 1687 | - /// that identity is what keeps the motion search's decisions, and therefore the | ||
| 1688 | - /// bitstream, unchanged. Sweeps every sub-pel phase, every block size, and a | ||
| 1689 | - /// range of positions including ones near the frame edge (where it must decline). | ||
| 1690 | - #[test] | ||
| 1691 | - fn hpel_block_matches_mc_luma_exactly() { | ||
| 1692 | - let (cw, ch) = (96usize, 64usize); | ||
| 1693 | - let mut reference = vec![0u8; cw * ch]; | ||
| 1694 | - let mut s: u32 = 0x9E37_79B9; | ||
| 1695 | - for p in reference.iter_mut() { | ||
| 1696 | - s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 1697 | - *p = (s >> 24) as u8; | ||
| 1698 | - } | ||
| 1699 | - let planes = build_hpel_planes(&reference, cw, ch); | ||
| 1700 | - | ||
| 1701 | - let mut checked = 0; | ||
| 1702 | - for (bw, bh) in [(16, 16), (16, 8), (8, 16), (8, 8), (8, 4), (4, 8), (4, 4)] { | ||
| 1703 | - for fy in 0..4i32 { | ||
| 1704 | - for fx in 0..4i32 { | ||
| 1705 | - if fx == 0 && fy == 0 { | ||
| 1706 | - continue; // full-pel is the copy path, not the plane path | ||
| 1707 | - } | ||
| 1708 | - for y0 in (0..ch - bh).step_by(7) { | ||
| 1709 | - for x0 in (0..cw - bw).step_by(5) { | ||
| 1710 | - for &(dx, dy) in &[(0i32, 0i32), (4, 0), (0, 4), (-4, -4), (8, 8), (-64, -64), (96, 40), (-96, 60), (40, -96)] { | ||
| 1711 | - let (mvx, mvy) = (dx + fx, dy + fy); | ||
| 1712 | - let mut want = [0u8; 256]; | ||
| 1713 | - mc_luma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut want); | ||
| 1714 | - let mut got = [0u8; 256]; | ||
| 1715 | - if !hpel_block(&planes, x0, y0, bw, bh, mvx, mvy, &mut got) { | ||
| 1716 | - continue; // declined (edge) -> caller falls back | ||
| 1717 | - } | ||
| 1718 | - assert_eq!( | ||
| 1719 | - &got[..bw * bh], | ||
| 1720 | - &want[..bw * bh], | ||
| 1721 | - "bw={bw} bh={bh} fx={fx} fy={fy} x0={x0} y0={y0} mv=({mvx},{mvy})" | ||
| 1722 | - ); | ||
| 1723 | - checked += 1; | ||
| 1724 | - } | ||
| 1725 | - } | ||
| 1726 | - } | ||
| 1727 | - } | ||
| 1728 | - } | ||
| 1729 | - } | ||
| 1730 | - assert!(checked > 5_000, "too few positions exercised: {checked}"); | ||
| 1731 | - } | ||
| 1732 | - | ||
| 1733 | - #[test] | ||
| 1734 | - fn mc_luma_block_kernels_match_per_pixel() { | ||
| 1735 | - // The block-kernel MC must be bit-identical to the per-pixel `luma_sample` | ||
| 1736 | - // reference for every quarter-pel position, across interior AND edge blocks | ||
| 1737 | - // (negative / off-frame MVs that exercise the clamped tile vs `at()`). | ||
| 1738 | - let (cw, ch) = (40usize, 32usize); | ||
| 1739 | - let mut state = 0x1357_9bdfu32; | ||
| 1740 | - let mut next = || { | ||
| 1741 | - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 1742 | - (state >> 24) as u8 | ||
| 1743 | - }; | ||
| 1744 | - let reference: Vec<u8> = (0..cw * ch).map(|_| next()).collect(); | ||
| 1745 | - for &(bw, bh) in &[(16, 16), (8, 8), (4, 4), (8, 16), (16, 8)] { | ||
| 1746 | - for &(x0, y0) in &[(8usize, 8usize), (0, 0), (cw - bw, ch - bh)] { | ||
| 1747 | - for mvx in -9..=9 { | ||
| 1748 | - for mvy in -9..=9 { | ||
| 1749 | - let mut got = vec![0u8; bw * bh]; | ||
| 1750 | - mc_luma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut got); | ||
| 1751 | - let ix0 = x0 as isize + (mvx >> 2) as isize; | ||
| 1752 | - let iy0 = y0 as isize + (mvy >> 2) as isize; | ||
| 1753 | - let (fx, fy) = (mvx & 3, mvy & 3); | ||
| 1754 | - for dy in 0..bh { | ||
| 1755 | - for dx in 0..bw { | ||
| 1756 | - let want = luma_sample( | ||
| 1757 | - &reference, cw, ch, | ||
| 1758 | - ix0 + dx as isize, iy0 + dy as isize, fx, fy, | ||
| 1759 | - ) as u8; | ||
| 1760 | - assert_eq!( | ||
| 1761 | - got[dy * bw + dx], want, | ||
| 1762 | - "bw{bw}x{bh} at ({x0},{y0}) mv({mvx},{mvy}) px({dx},{dy})" | ||
| 1763 | - ); | ||
| 1764 | - } | ||
| 1765 | - } | ||
| 1766 | - } | ||
| 1767 | - } | ||
| 1768 | - } | ||
| 1769 | - } | ||
| 1770 | - } | ||
| 1771 | - | ||
| 1772 | - #[test] | ||
| 1773 | - fn mc_chroma_block_matches_per_pixel() { | ||
| 1774 | - let (cw, ch) = (24usize, 20usize); | ||
| 1775 | - let mut state = 0xabcd_1234u32; | ||
| 1776 | - let mut next = || { | ||
| 1777 | - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 1778 | - (state >> 24) as u8 | ||
| 1779 | - }; | ||
| 1780 | - let reference: Vec<u8> = (0..cw * ch).map(|_| next()).collect(); | ||
| 1781 | - let pp = |ix: isize, iy: isize, fx: i32, fy: i32| -> u8 { | ||
| 1782 | - let a = at(&reference, cw, ch, ix, iy); | ||
| 1783 | - let b = at(&reference, cw, ch, ix + 1, iy); | ||
| 1784 | - let c = at(&reference, cw, ch, ix, iy + 1); | ||
| 1785 | - let d = at(&reference, cw, ch, ix + 1, iy + 1); | ||
| 1786 | - (((8 - fx) * (8 - fy) * a + fx * (8 - fy) * b + (8 - fx) * fy * c + fx * fy * d + 32) >> 6) | ||
| 1787 | - as u8 | ||
| 1788 | - }; | ||
| 1789 | - for &(bw, bh) in &[(8, 8), (4, 4), (8, 4), (4, 8)] { | ||
| 1790 | - for &(x0, y0) in &[(4usize, 4usize), (0, 0), (cw - bw, ch - bh)] { | ||
| 1791 | - for mvx in -12..=12 { | ||
| 1792 | - for mvy in -12..=12 { | ||
| 1793 | - let mut got = vec![0u8; bw * bh]; | ||
| 1794 | - mc_chroma(&reference, cw, ch, x0, y0, bw, bh, mvx, mvy, &mut got); | ||
| 1795 | - let ix0 = x0 as isize + (mvx >> 3) as isize; | ||
| 1796 | - let iy0 = y0 as isize + (mvy >> 3) as isize; | ||
| 1797 | - let (fx, fy) = (mvx & 7, mvy & 7); | ||
| 1798 | - for dy in 0..bh { | ||
| 1799 | - for dx in 0..bw { | ||
| 1800 | - assert_eq!( | ||
| 1801 | - got[dy * bw + dx], | ||
| 1802 | - pp(ix0 + dx as isize, iy0 + dy as isize, fx, fy), | ||
| 1803 | - "bw{bw}x{bh} at ({x0},{y0}) mv({mvx},{mvy}) px({dx},{dy})" | ||
| 1804 | - ); | ||
| 1805 | - } | ||
| 1806 | - } | ||
| 1807 | - } | ||
| 1808 | - } | ||
| 1809 | - } | ||
| 1810 | - } | ||
| 1811 | - } | ||
| 1812 | - | ||
| 1813 | - #[test] | ||
| 1814 | - fn median_of_three() { | ||
| 1815 | - assert_eq!(median3(1, 2, 3), 2); | ||
| 1816 | - assert_eq!(median3(3, 1, 2), 2); | ||
| 1817 | - assert_eq!(median3(-5, 0, 5), 0); | ||
| 1818 | - assert_eq!(median3(7, 7, 2), 7); | ||
| 1819 | - } | ||
| 1820 | - | ||
| 1821 | - #[test] | ||
| 1822 | - fn mv_predict_single_neighbor_uses_it() { | ||
| 1823 | - let a = MvNeighbor { available: true, mv: (8, -4), ref_idx: 0 }; | ||
| 1824 | - // B and C unavailable, A available → predictor is A. | ||
| 1825 | - assert_eq!(predict_mv(a, MvNeighbor::NONE, MvNeighbor::NONE, 0), (8, -4)); | ||
| 1826 | - } | ||
| 1827 | - | ||
| 1828 | - #[test] | ||
| 1829 | - fn mv_predict_median_when_all_inter() { | ||
| 1830 | - let a = MvNeighbor { available: true, mv: (4, 0), ref_idx: 0 }; | ||
| 1831 | - let b = MvNeighbor { available: true, mv: (8, 0), ref_idx: 0 }; | ||
| 1832 | - let c = MvNeighbor { available: true, mv: (12, 0), ref_idx: 0 }; | ||
| 1833 | - assert_eq!(predict_mv(a, b, c, 0), (8, 0)); | ||
| 1834 | - } | ||
| 1835 | - | ||
| 1836 | - #[test] | ||
| 1837 | - fn mv_predict_one_matching_ref_wins() { | ||
| 1838 | - // Only B references ref 0; A and C are intra → predictor is B. | ||
| 1839 | - let a = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 }; | ||
| 1840 | - let b = MvNeighbor { available: true, mv: (5, 7), ref_idx: 0 }; | ||
| 1841 | - let c = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 }; | ||
| 1842 | - assert_eq!(predict_mv(a, b, c, 0), (5, 7)); | ||
| 1843 | - } | ||
| 1844 | - | ||
| 1845 | - #[test] | ||
| 1846 | - fn mv_predict_distinguishes_refs() { | ||
| 1847 | - // A references ref 1, B references ref 0, C intra. For cur_ref 0 only B | ||
| 1848 | - // matches → B; for cur_ref 1 only A matches → A. | ||
| 1849 | - let a = MvNeighbor { available: true, mv: (4, 4), ref_idx: 1 }; | ||
| 1850 | - let b = MvNeighbor { available: true, mv: (5, 7), ref_idx: 0 }; | ||
| 1851 | - let c = MvNeighbor { available: true, mv: (0, 0), ref_idx: -1 }; | ||
| 1852 | - assert_eq!(predict_mv(a, b, c, 0), (5, 7)); | ||
| 1853 | - assert_eq!(predict_mv(a, b, c, 1), (4, 4)); | ||
| 1854 | - } | ||
| 1855 | - | ||
| 1856 | - #[test] | ||
| 1857 | - fn mc_luma_zero_mv_copies() { | ||
| 1858 | - let reference = vec![ | ||
| 1859 | - 0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33, | ||
| 1860 | - ]; | ||
| 1861 | - let mut out = [0u8; 4]; | ||
| 1862 | - mc_luma(&reference, 4, 4, 1, 1, 2, 2, 0, 0, &mut out); | ||
| 1863 | - assert_eq!(out, [11, 12, 21, 22]); | ||
| 1864 | - } | ||
| 1865 | - | ||
| 1866 | - #[test] | ||
| 1867 | - fn mc_luma_clamps_at_edges() { | ||
| 1868 | - let reference = vec![5, 6, 7, 8]; | ||
| 1869 | - let mut out = [0u8; 4]; | ||
| 1870 | - mc_luma(&reference, 2, 2, 0, 0, 2, 2, -40, -40, &mut out); | ||
| 1871 | - assert_eq!(out, [5, 5, 5, 5]); | ||
| 1872 | - } | ||
| 1873 | - | ||
| 1874 | - #[test] | ||
| 1875 | - fn mc_luma_halfpel_on_flat_is_flat() { | ||
| 1876 | - // A flat reference must interpolate to the same flat value at any frac. | ||
| 1877 | - let reference = vec![100u8; 8 * 8]; | ||
| 1878 | - let mut out = [0u8; 16]; | ||
| 1879 | - for &(fx, fy) in &[(2, 0), (0, 2), (2, 2), (1, 1), (3, 3)] { | ||
| 1880 | - mc_luma(&reference, 8, 8, 2, 2, 4, 4, fx, fy, &mut out); | ||
| 1881 | - assert!(out.iter().all(|&p| p == 100), "frac ({fx},{fy})"); | ||
| 1882 | - } | ||
| 1883 | - } | ||
| 1884 | - | ||
| 1885 | - #[test] | ||
| 1886 | - fn mc_chroma_zero_mv_copies() { | ||
| 1887 | - let reference = vec![0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33]; | ||
| 1888 | - let mut out = [0u8; 4]; | ||
| 1889 | - mc_chroma(&reference, 4, 4, 1, 1, 2, 2, 0, 0, &mut out); | ||
| 1890 | - assert_eq!(out, [11, 12, 21, 22]); | ||
| 1891 | - } | ||
| 1892 | - | ||
| 1893 | - #[test] | ||
| 1894 | - fn mc_chroma_bilinear_midpoint() { | ||
| 1895 | - // Horizontal ramp 0,8; chroma frac 4 (half) → midpoint 4. | ||
| 1896 | - let reference = vec![0u8, 8, 0, 8]; | ||
| 1897 | - let mut out = [0u8; 1]; | ||
| 1898 | - mc_chroma(&reference, 2, 2, 0, 0, 1, 1, 4, 0, &mut out); | ||
| 1899 | - assert_eq!(out[0], 4); | ||
| 1900 | - } | ||
| 1901 | -} | ||
vendor/rusty_h264-common/src/lib.rsdeleted+0 -57
| @@ -1,57 +0,0 @@ | |||
| 1 | -//! Shared primitives for the `rusty_h264` pure-Rust H.264 codec. | ||
| 2 | -//! | ||
| 3 | -//! # Global allocator | ||
| 4 | -//! | ||
| 5 | -//! Upstream's `global-alloc` feature installed `rusty_alloc` as the process-wide | ||
| 6 | -//! allocator here. This vendored copy does not (see the edith patch below the | ||
| 7 | -//! crate attributes); the feature is kept declared but empty so the sibling | ||
| 8 | -//! decoder/encoder manifests still resolve. The process uses the system | ||
| 9 | -//! allocator. | ||
| 10 | -//! | ||
| 11 | -//! This crate is the foundation both the encoder and decoder sit on. It is | ||
| 12 | -//! `#![forbid(unsafe_code)]`: the bit-twiddling core of an H.264 codec is | ||
| 13 | -//! exactly where memory-safety bugs hide in the C implementations, so we keep | ||
| 14 | -//! it provably safe. | ||
| 15 | -//! | ||
| 16 | -//! Modules mirror the concerns shared across `codec/common` in Cisco's | ||
| 17 | -//! openh264: | ||
| 18 | -//! - [`bit_writer`] / [`bit_reader`] — MSB-first bit packing + Exp-Golomb. | ||
| 19 | -//! - [`nal`] — NAL units, Annex-B framing, RBSP emulation prevention. | ||
| 20 | -//! - [`types`] — shared enums and the raw YUV frame container. | ||
| 21 | -//! | ||
| 22 | -//! The shipped build is `#![forbid(unsafe_code)]`. The `profile` feature (a | ||
| 23 | -//! measurement-only dev build, never shipped) relaxes this to unlock the `rdtsc` | ||
| 24 | -//! timer in [`prof`]; that is the *only* unsafe in the crate and only under `profile`. | ||
| 25 | -#![cfg_attr(not(feature = "profile"), forbid(unsafe_code))] | ||
| 26 | - | ||
| 27 | -// --- edith patch: no process-wide allocator --- | ||
| 28 | -// Upstream installed `rusty_alloc` as the whole application's | ||
| 29 | -// `#[global_allocator]` here, under a feature its own decoder and encoder turn | ||
| 30 | -// on by default. Under sustained seeking edith churns decode-worker threads, | ||
| 31 | -// and that allocator faulted inside `span_from_segments` on a fresh thread's | ||
| 32 | -// very first allocation. The codec is unchanged; only this declaration is gone, | ||
| 33 | -// so the process keeps glibc's malloc. | ||
| 34 | - | ||
| 35 | -pub mod aligned; | ||
| 36 | -pub mod bit_reader; | ||
| 37 | -pub mod bit_writer; | ||
| 38 | -pub mod cabac_tables; | ||
| 39 | -pub mod cavlc; | ||
| 40 | -pub mod deblock; | ||
| 41 | - | ||
| 42 | -/// Whether the vendored SIMD kernels are compiled in (`asm` feature on x86-64). | ||
| 43 | -/// Exposed so benchmarks can state which path they measured — a harness that | ||
| 44 | -/// silently falls back to the scalar twin reports numbers that look like a | ||
| 45 | -/// regression in the fast path. | ||
| 46 | -pub const ACCEL: bool = cfg!(accel); | ||
| 47 | -pub mod inter; | ||
| 48 | -pub mod nal; | ||
| 49 | -pub mod predict; | ||
| 50 | -pub mod prof; | ||
| 51 | -pub mod transform; | ||
| 52 | -pub mod types; | ||
| 53 | - | ||
| 54 | -pub use bit_reader::BitReader; | ||
| 55 | -pub use bit_writer::BitWriter; | ||
| 56 | -pub use nal::{NalUnit, NalUnitType}; | ||
| 57 | -pub use types::{ChromaFormat, Profile, YuvFrame}; | ||
vendor/rusty_h264-common/src/nal.rsdeleted+0 -232
| @@ -1,232 +0,0 @@ | |||
| 1 | -//! NAL units, Annex-B framing, and RBSP emulation-prevention. | ||
| 2 | -//! | ||
| 3 | -//! H.264 carries syntax in NAL (Network Abstraction Layer) units. In the | ||
| 4 | -//! Annex-B byte stream each NAL is prefixed by a start code (`00 00 01`, often | ||
| 5 | -//! `00 00 00 01`). Within a NAL, the raw payload (RBSP) is escaped so the | ||
| 6 | -//! start-code pattern can never appear by accident: any `00 00 00/01/02/03` | ||
| 7 | -//! gets a `03` emulation-prevention byte inserted, producing the SODB/EBSP. | ||
| 8 | - | ||
| 9 | -/// NAL unit type (`nal_unit_type`, 5 bits). Only the subset relevant to a | ||
| 10 | -/// Constrained Baseline encoder/decoder is named; others are `Other`. | ||
| 11 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 12 | -pub enum NalUnitType { | ||
| 13 | - /// Coded slice of a non-IDR picture. | ||
| 14 | - NonIdrSlice, | ||
| 15 | - /// Coded slice of an IDR picture. | ||
| 16 | - IdrSlice, | ||
| 17 | - /// Supplemental enhancement information. | ||
| 18 | - Sei, | ||
| 19 | - /// Sequence parameter set. | ||
| 20 | - Sps, | ||
| 21 | - /// Picture parameter set. | ||
| 22 | - Pps, | ||
| 23 | - /// Access unit delimiter. | ||
| 24 | - AccessUnitDelimiter, | ||
| 25 | - /// Any type not specifically handled. | ||
| 26 | - Other(u8), | ||
| 27 | -} | ||
| 28 | - | ||
| 29 | -impl NalUnitType { | ||
| 30 | - /// Numeric `nal_unit_type` value. | ||
| 31 | - pub fn id(self) -> u8 { | ||
| 32 | - match self { | ||
| 33 | - NalUnitType::NonIdrSlice => 1, | ||
| 34 | - NalUnitType::IdrSlice => 5, | ||
| 35 | - NalUnitType::Sei => 6, | ||
| 36 | - NalUnitType::Sps => 7, | ||
| 37 | - NalUnitType::Pps => 8, | ||
| 38 | - NalUnitType::AccessUnitDelimiter => 9, | ||
| 39 | - NalUnitType::Other(v) => v & 0x1f, | ||
| 40 | - } | ||
| 41 | - } | ||
| 42 | - | ||
| 43 | - /// Parses a `nal_unit_type` value. | ||
| 44 | - pub fn from_id(v: u8) -> Self { | ||
| 45 | - match v & 0x1f { | ||
| 46 | - 1 => NalUnitType::NonIdrSlice, | ||
| 47 | - 5 => NalUnitType::IdrSlice, | ||
| 48 | - 6 => NalUnitType::Sei, | ||
| 49 | - 7 => NalUnitType::Sps, | ||
| 50 | - 8 => NalUnitType::Pps, | ||
| 51 | - 9 => NalUnitType::AccessUnitDelimiter, | ||
| 52 | - other => NalUnitType::Other(other), | ||
| 53 | - } | ||
| 54 | - } | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -/// A NAL unit: a header (type + `nal_ref_idc`) plus its raw RBSP payload. | ||
| 58 | -#[derive(Debug, Clone)] | ||
| 59 | -pub struct NalUnit { | ||
| 60 | - /// `nal_ref_idc` (0..=3): non-zero marks the NAL as referenceable. | ||
| 61 | - pub ref_idc: u8, | ||
| 62 | - /// NAL unit type. | ||
| 63 | - pub nal_type: NalUnitType, | ||
| 64 | - /// Raw byte sequence payload (un-escaped). | ||
| 65 | - pub rbsp: Vec<u8>, | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | -impl NalUnit { | ||
| 69 | - /// Builds a NAL unit. | ||
| 70 | - pub fn new(ref_idc: u8, nal_type: NalUnitType, rbsp: Vec<u8>) -> Self { | ||
| 71 | - Self { | ||
| 72 | - ref_idc, | ||
| 73 | - nal_type, | ||
| 74 | - rbsp, | ||
| 75 | - } | ||
| 76 | - } | ||
| 77 | - | ||
| 78 | - /// The one-byte NAL header: `forbidden_zero_bit(0) | nal_ref_idc | nal_unit_type`. | ||
| 79 | - pub fn header_byte(&self) -> u8 { | ||
| 80 | - ((self.ref_idc & 0x3) << 5) | self.nal_type.id() | ||
| 81 | - } | ||
| 82 | - | ||
| 83 | - /// Appends this NAL to `out` as an Annex-B unit: 4-byte start code, header | ||
| 84 | - /// byte, then the emulation-prevented payload. | ||
| 85 | - pub fn write_annex_b(&self, out: &mut Vec<u8>) { | ||
| 86 | - out.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]); | ||
| 87 | - out.push(self.header_byte()); | ||
| 88 | - emulation_prevent_into(&self.rbsp, out); | ||
| 89 | - } | ||
| 90 | - | ||
| 91 | - /// Serializes a single NAL as a standalone Annex-B byte stream. | ||
| 92 | - pub fn to_annex_b(&self) -> Vec<u8> { | ||
| 93 | - let mut out = Vec::with_capacity(self.rbsp.len() + 8); | ||
| 94 | - self.write_annex_b(&mut out); | ||
| 95 | - out | ||
| 96 | - } | ||
| 97 | -} | ||
| 98 | - | ||
| 99 | -/// Inserts emulation-prevention bytes, appending the EBSP to `out`. | ||
| 100 | -/// | ||
| 101 | -/// Whenever the next byte would complete a `00 00 00`, `00 00 01`, `00 00 02`, | ||
| 102 | -/// or `00 00 03` sequence, a `03` is inserted after the two zeros. | ||
| 103 | -pub fn emulation_prevent_into(rbsp: &[u8], out: &mut Vec<u8>) { | ||
| 104 | - let mut zeros = 0usize; | ||
| 105 | - for &b in rbsp { | ||
| 106 | - if zeros >= 2 && b <= 0x03 { | ||
| 107 | - out.push(0x03); | ||
| 108 | - zeros = 0; | ||
| 109 | - } | ||
| 110 | - out.push(b); | ||
| 111 | - if b == 0 { | ||
| 112 | - zeros += 1; | ||
| 113 | - } else { | ||
| 114 | - zeros = 0; | ||
| 115 | - } | ||
| 116 | - } | ||
| 117 | -} | ||
| 118 | - | ||
| 119 | -/// Removes emulation-prevention bytes from an EBSP payload, returning the RBSP. | ||
| 120 | -pub fn emulation_unprevent(ebsp: &[u8]) -> Vec<u8> { | ||
| 121 | - let mut out = Vec::with_capacity(ebsp.len()); | ||
| 122 | - let mut zeros = 0usize; | ||
| 123 | - let mut i = 0; | ||
| 124 | - while i < ebsp.len() { | ||
| 125 | - let b = ebsp[i]; | ||
| 126 | - if zeros >= 2 && b == 0x03 && i + 1 < ebsp.len() && ebsp[i + 1] <= 0x03 { | ||
| 127 | - // Drop this emulation-prevention byte. | ||
| 128 | - zeros = 0; | ||
| 129 | - i += 1; | ||
| 130 | - continue; | ||
| 131 | - } | ||
| 132 | - out.push(b); | ||
| 133 | - if b == 0 { | ||
| 134 | - zeros += 1; | ||
| 135 | - } else { | ||
| 136 | - zeros = 0; | ||
| 137 | - } | ||
| 138 | - i += 1; | ||
| 139 | - } | ||
| 140 | - out | ||
| 141 | -} | ||
| 142 | - | ||
| 143 | -/// Splits an Annex-B byte stream into raw NAL byte slices (header + EBSP), | ||
| 144 | -/// stripping start codes. Does not parse headers or un-escape payloads. | ||
| 145 | -pub fn split_annex_b(stream: &[u8]) -> Vec<&[u8]> { | ||
| 146 | - let mut nals = Vec::new(); | ||
| 147 | - let mut starts = Vec::new(); | ||
| 148 | - let mut i = 0; | ||
| 149 | - while i + 3 <= stream.len() { | ||
| 150 | - if stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1 { | ||
| 151 | - starts.push(i + 3); | ||
| 152 | - i += 3; | ||
| 153 | - } else { | ||
| 154 | - i += 1; | ||
| 155 | - } | ||
| 156 | - } | ||
| 157 | - for (idx, &s) in starts.iter().enumerate() { | ||
| 158 | - // The NAL runs to just before the next start code (minus any trailing | ||
| 159 | - // zero bytes that belong to the next start code's prefix). | ||
| 160 | - let end = if idx + 1 < starts.len() { | ||
| 161 | - let next = starts[idx + 1] - 3; | ||
| 162 | - // Trim the trailing zero of a 4-byte (00 00 00 01) start code. | ||
| 163 | - if next > s && stream[next - 1] == 0 { | ||
| 164 | - next - 1 | ||
| 165 | - } else { | ||
| 166 | - next | ||
| 167 | - } | ||
| 168 | - } else { | ||
| 169 | - stream.len() | ||
| 170 | - }; | ||
| 171 | - if end > s { | ||
| 172 | - nals.push(&stream[s..end]); | ||
| 173 | - } | ||
| 174 | - } | ||
| 175 | - nals | ||
| 176 | -} | ||
| 177 | - | ||
| 178 | -#[cfg(test)] | ||
| 179 | -mod tests { | ||
| 180 | - use super::*; | ||
| 181 | - | ||
| 182 | - #[test] | ||
| 183 | - fn header_byte_packs_fields() { | ||
| 184 | - let nal = NalUnit::new(3, NalUnitType::Sps, vec![]); | ||
| 185 | - // ref_idc=3 (11), type=7 (00111) => 0110_0111 | ||
| 186 | - assert_eq!(nal.header_byte(), 0b0110_0111); | ||
| 187 | - } | ||
| 188 | - | ||
| 189 | - #[test] | ||
| 190 | - fn emulation_prevention_inserts_03() { | ||
| 191 | - // Each inserted 0x03 resets the zero-run counter, so five zeros then a | ||
| 192 | - // 1 escapes twice: 00 00 [03] 00 00 [03] 00 01. | ||
| 193 | - let mut out = Vec::new(); | ||
| 194 | - emulation_prevent_into(&[0, 0, 0, 0, 0, 1], &mut out); | ||
| 195 | - assert_eq!(out, vec![0, 0, 3, 0, 0, 3, 0, 1]); | ||
| 196 | - } | ||
| 197 | - | ||
| 198 | - #[test] | ||
| 199 | - fn emulation_roundtrip() { | ||
| 200 | - let payloads: &[&[u8]] = &[ | ||
| 201 | - &[0, 0, 0, 1], | ||
| 202 | - &[0, 0, 1, 2, 3], | ||
| 203 | - &[1, 2, 3, 4, 5], | ||
| 204 | - &[0, 0, 0, 0, 0, 0], | ||
| 205 | - &[0, 0, 3, 0, 0, 3], | ||
| 206 | - ]; | ||
| 207 | - for p in payloads { | ||
| 208 | - let mut ebsp = Vec::new(); | ||
| 209 | - emulation_prevent_into(p, &mut ebsp); | ||
| 210 | - assert_eq!(&emulation_unprevent(&ebsp), p, "roundtrip {p:?}"); | ||
| 211 | - } | ||
| 212 | - } | ||
| 213 | - | ||
| 214 | - #[test] | ||
| 215 | - fn annex_b_split_and_unescape() { | ||
| 216 | - let sps = NalUnit::new(3, NalUnitType::Sps, vec![0, 0, 1, 0x42]); | ||
| 217 | - let pps = NalUnit::new(3, NalUnitType::Pps, vec![0xAB, 0xCD]); | ||
| 218 | - let mut stream = Vec::new(); | ||
| 219 | - sps.write_annex_b(&mut stream); | ||
| 220 | - pps.write_annex_b(&mut stream); | ||
| 221 | - | ||
| 222 | - let nals = split_annex_b(&stream); | ||
| 223 | - assert_eq!(nals.len(), 2); | ||
| 224 | - | ||
| 225 | - // First NAL: header byte then EBSP. | ||
| 226 | - assert_eq!(NalUnitType::from_id(nals[0][0]), NalUnitType::Sps); | ||
| 227 | - assert_eq!(emulation_unprevent(&nals[0][1..]), vec![0, 0, 1, 0x42]); | ||
| 228 | - | ||
| 229 | - assert_eq!(NalUnitType::from_id(nals[1][0]), NalUnitType::Pps); | ||
| 230 | - assert_eq!(emulation_unprevent(&nals[1][1..]), vec![0xAB, 0xCD]); | ||
| 231 | - } | ||
| 232 | -} | ||
vendor/rusty_h264-common/src/predict.rsdeleted+0 -907
| @@ -1,907 +0,0 @@ | |||
| 1 | -//! Intra prediction + shared block reconstruction for I_16x16 macroblocks. | ||
| 2 | -//! | ||
| 3 | -//! These routines are used identically by the encoder (to reconstruct each | ||
| 4 | -//! macroblock so the next one can predict from it) and the decoder. Keeping | ||
| 5 | -//! them in one place guarantees the two stay bit-for-bit in agreement, which is | ||
| 6 | -//! what intra prediction requires. | ||
| 7 | - | ||
| 8 | -use crate::transform::inverse_core; | ||
| 9 | - | ||
| 10 | -/// 4×4 luma block scan order → (block-x, block-y) within a macroblock, in units | ||
| 11 | -/// of 4 samples. This is the order luma residual blocks are coded and the order | ||
| 12 | -/// neighbor `nnz` values are indexed by. | ||
| 13 | -pub const LUMA_4X4_SCAN_XY: [(usize, usize); 16] = [ | ||
| 14 | - (0, 0), (1, 0), (0, 1), (1, 1), | ||
| 15 | - (2, 0), (3, 0), (2, 1), (3, 1), | ||
| 16 | - (0, 2), (1, 2), (0, 3), (1, 3), | ||
| 17 | - (2, 2), (3, 2), (2, 3), (3, 3), | ||
| 18 | -]; | ||
| 19 | - | ||
| 20 | -/// Chroma 4×4 block scan order → (block-x, block-y) within the 8×8, in units of | ||
| 21 | -/// 4 samples (simple raster for 4:2:0). | ||
| 22 | -pub const CHROMA_4X4_SCAN_XY: [(usize, usize); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)]; | ||
| 23 | - | ||
| 24 | -/// Maps a luma QP to its chroma QP (with `chroma_qp_index_offset == 0`). | ||
| 25 | -/// MEASUREMENT KNOBS — ablation switches for pricing stages the scope profiler cannot | ||
| 26 | -/// read (its per-call rdtsc tax at ~20M calls exceeds the thing being measured). | ||
| 27 | -/// | ||
| 28 | -/// `RFF_ABL_INTRA=1` makes every intra predictor return a flat block; `RFF_ABL_RECON=1` | ||
| 29 | -/// makes reconstruction return the prediction unchanged (residual discarded). Both leave | ||
| 30 | -/// PARSING and every call count untouched — what is priced is the pixel work alone, so | ||
| 31 | -/// the frame count is unaffected and the work-parity check still holds. Output pixels | ||
| 32 | -/// are wrong while either is set, by design; these are never a shipping path. | ||
| 33 | -/// Read once; the branch predicts perfectly. | ||
| 34 | -#[inline] | ||
| 35 | -pub(crate) fn abl_intra() -> bool { | ||
| 36 | - use std::sync::atomic::{AtomicU8, Ordering}; | ||
| 37 | - static ON: AtomicU8 = AtomicU8::new(0); | ||
| 38 | - match ON.load(Ordering::Relaxed) { | ||
| 39 | - 1 => true, | ||
| 40 | - 2 => false, | ||
| 41 | - _ => { | ||
| 42 | - let on = std::env::var_os("RFF_ABL_INTRA").is_some_and(|v| v != "0"); | ||
| 43 | - ON.store(if on { 1 } else { 2 }, Ordering::Relaxed); | ||
| 44 | - on | ||
| 45 | - } | ||
| 46 | - } | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -#[inline] | ||
| 50 | -pub(crate) fn abl_recon() -> bool { | ||
| 51 | - use std::sync::atomic::{AtomicU8, Ordering}; | ||
| 52 | - static ON: AtomicU8 = AtomicU8::new(0); | ||
| 53 | - match ON.load(Ordering::Relaxed) { | ||
| 54 | - 1 => true, | ||
| 55 | - 2 => false, | ||
| 56 | - _ => { | ||
| 57 | - let on = std::env::var_os("RFF_ABL_RECON").is_some_and(|v| v != "0"); | ||
| 58 | - ON.store(if on { 1 } else { 2 }, Ordering::Relaxed); | ||
| 59 | - on | ||
| 60 | - } | ||
| 61 | - } | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -pub fn chroma_qp(qp: u8) -> u8 { | ||
| 65 | - | ||
| 66 | - const QPC: [u8; 22] = [ | ||
| 67 | - 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39, | ||
| 68 | - ]; | ||
| 69 | - if qp < 30 { | ||
| 70 | - qp | ||
| 71 | - } else { | ||
| 72 | - QPC[(qp - 30) as usize] | ||
| 73 | - } | ||
| 74 | -} | ||
| 75 | - | ||
| 76 | -/// CAVLC `nC` context from the left (`a`) and top (`b`) neighbor block `nnz` | ||
| 77 | -/// counts (`None` = neighbor unavailable). | ||
| 78 | -pub fn nc_from_neighbors(a: Option<u8>, b: Option<u8>) -> i32 { | ||
| 79 | - match (a, b) { | ||
| 80 | - (Some(na), Some(nb)) => (na as i32 + nb as i32 + 1) >> 1, | ||
| 81 | - (Some(na), None) => na as i32, | ||
| 82 | - (None, Some(nb)) => nb as i32, | ||
| 83 | - (None, None) => 0, | ||
| 84 | - } | ||
| 85 | -} | ||
| 86 | - | ||
| 87 | -fn sum(s: &[u8]) -> i32 { | ||
| 88 | - s.iter().map(|&x| x as i32).sum() | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -/// Intra_16x16 DC luma prediction: a single value used for all 256 samples. | ||
| 92 | -pub fn luma16x16_dc(avail_top: bool, avail_left: bool, top: &[u8; 16], left: &[u8; 16]) -> u8 { | ||
| 93 | - let v = if avail_top && avail_left { | ||
| 94 | - (sum(top) + sum(left) + 16) >> 5 | ||
| 95 | - } else if avail_top { | ||
| 96 | - (sum(top) + 8) >> 4 | ||
| 97 | - } else if avail_left { | ||
| 98 | - (sum(left) + 8) >> 4 | ||
| 99 | - } else { | ||
| 100 | - 128 | ||
| 101 | - }; | ||
| 102 | - v as u8 | ||
| 103 | -} | ||
| 104 | - | ||
| 105 | -/// The four `Intra_16x16` prediction modes (spec §8.3.3). The discriminant is | ||
| 106 | -/// the `intra16x16_pred_mode` value carried in `mb_type`. | ||
| 107 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 108 | -pub enum I16Mode { | ||
| 109 | - Vertical = 0, | ||
| 110 | - Horizontal = 1, | ||
| 111 | - Dc = 2, | ||
| 112 | - Plane = 3, | ||
| 113 | -} | ||
| 114 | - | ||
| 115 | -impl I16Mode { | ||
| 116 | - /// Parses a mode number (0..=3). | ||
| 117 | - pub fn from_id(v: u32) -> Self { | ||
| 118 | - match v & 3 { | ||
| 119 | - 0 => I16Mode::Vertical, | ||
| 120 | - 1 => I16Mode::Horizontal, | ||
| 121 | - 2 => I16Mode::Dc, | ||
| 122 | - _ => I16Mode::Plane, | ||
| 123 | - } | ||
| 124 | - } | ||
| 125 | - | ||
| 126 | - /// Whether this mode is usable given neighbor availability. | ||
| 127 | - pub fn available(self, avail_top: bool, avail_left: bool) -> bool { | ||
| 128 | - match self { | ||
| 129 | - I16Mode::Vertical => avail_top, | ||
| 130 | - I16Mode::Horizontal => avail_left, | ||
| 131 | - I16Mode::Dc => true, | ||
| 132 | - I16Mode::Plane => avail_top && avail_left, | ||
| 133 | - } | ||
| 134 | - } | ||
| 135 | -} | ||
| 136 | - | ||
| 137 | -/// Computes the 16×16 luma prediction for an `Intra_16x16` macroblock, returning | ||
| 138 | -/// 256 raster samples. `corner` is the above-left neighbor (used by Plane). | ||
| 139 | -pub fn luma16x16_pred( | ||
| 140 | - mode: I16Mode, | ||
| 141 | - avail_top: bool, | ||
| 142 | - avail_left: bool, | ||
| 143 | - top: &[u8; 16], | ||
| 144 | - left: &[u8; 16], | ||
| 145 | - corner: u8, | ||
| 146 | -) -> [u8; 256] { | ||
| 147 | - if abl_intra() { | ||
| 148 | - return [128; 256]; | ||
| 149 | - } | ||
| 150 | - let _g = crate::prof::scope(crate::prof::Stage::IntraPred); | ||
| 151 | - let mut out = [0u8; 256]; | ||
| 152 | - match mode { | ||
| 153 | - I16Mode::Vertical => { | ||
| 154 | - for y in 0..16 { | ||
| 155 | - for x in 0..16 { | ||
| 156 | - out[y * 16 + x] = top[x]; | ||
| 157 | - } | ||
| 158 | - } | ||
| 159 | - } | ||
| 160 | - I16Mode::Horizontal => { | ||
| 161 | - for y in 0..16 { | ||
| 162 | - for x in 0..16 { | ||
| 163 | - out[y * 16 + x] = left[y]; | ||
| 164 | - } | ||
| 165 | - } | ||
| 166 | - } | ||
| 167 | - I16Mode::Dc => { | ||
| 168 | - let v = luma16x16_dc(avail_top, avail_left, top, left); | ||
| 169 | - out.fill(v); | ||
| 170 | - } | ||
| 171 | - I16Mode::Plane => { | ||
| 172 | - // p[x,-1] = top[x] (x 0..15), p[-1,y] = left[y], p[-1,-1] = corner. | ||
| 173 | - let tp = |i: isize| -> i32 { | ||
| 174 | - if i < 0 { | ||
| 175 | - corner as i32 | ||
| 176 | - } else { | ||
| 177 | - top[i as usize] as i32 | ||
| 178 | - } | ||
| 179 | - }; | ||
| 180 | - let lf = |i: isize| -> i32 { | ||
| 181 | - if i < 0 { | ||
| 182 | - corner as i32 | ||
| 183 | - } else { | ||
| 184 | - left[i as usize] as i32 | ||
| 185 | - } | ||
| 186 | - }; | ||
| 187 | - let mut h = 0i32; | ||
| 188 | - let mut v = 0i32; | ||
| 189 | - for xp in 0..8i32 { | ||
| 190 | - h += (xp + 1) * (tp(8 + xp as isize) - tp(6 - xp as isize)); | ||
| 191 | - } | ||
| 192 | - for yp in 0..8i32 { | ||
| 193 | - v += (yp + 1) * (lf(8 + yp as isize) - lf(6 - yp as isize)); | ||
| 194 | - } | ||
| 195 | - let a = 16 * (left[15] as i32 + top[15] as i32); | ||
| 196 | - let b = (5 * h + 32) >> 6; | ||
| 197 | - let c = (5 * v + 32) >> 6; | ||
| 198 | - for y in 0..16i32 { | ||
| 199 | - for x in 0..16i32 { | ||
| 200 | - let val = (a + b * (x - 7) + c * (y - 7) + 16) >> 5; | ||
| 201 | - out[(y * 16 + x) as usize] = clip_u8(val); | ||
| 202 | - } | ||
| 203 | - } | ||
| 204 | - } | ||
| 205 | - } | ||
| 206 | - out | ||
| 207 | -} | ||
| 208 | - | ||
| 209 | -/// Intra 4×4 luma prediction (spec §8.3.1.2), all 9 modes. Returns 16 raster | ||
| 210 | -/// samples. Neighbors: `top[0..4]` above, `top[4..8]` above-right (the caller | ||
| 211 | -/// substitutes `top[3]` when the above-right block is unavailable), `left[0..4]` | ||
| 212 | -/// to the left, `corner` above-left. `avail_top`/`avail_left` gate DC only; | ||
| 213 | -/// callers must not select a mode whose neighbors are unavailable. | ||
| 214 | -pub fn intra4x4_pred( | ||
| 215 | - mode: u8, | ||
| 216 | - avail_top: bool, | ||
| 217 | - avail_left: bool, | ||
| 218 | - top: &[u8; 8], | ||
| 219 | - left: &[u8; 4], | ||
| 220 | - corner: u8, | ||
| 221 | -) -> [u8; 16] { | ||
| 222 | - if abl_intra() { | ||
| 223 | - return [128; 16]; | ||
| 224 | - } | ||
| 225 | - let _g = crate::prof::scope(crate::prof::Stage::IntraPred); | ||
| 226 | - let t = |i: usize| top[i] as i32; | ||
| 227 | - let l = |i: usize| left[i] as i32; | ||
| 228 | - let c = corner as i32; | ||
| 229 | - // Top/left indexed with -1 → corner. | ||
| 230 | - let tt = |k: i32| -> i32 { | ||
| 231 | - if k < 0 { | ||
| 232 | - c | ||
| 233 | - } else { | ||
| 234 | - top[k as usize] as i32 | ||
| 235 | - } | ||
| 236 | - }; | ||
| 237 | - let ll = |k: i32| -> i32 { | ||
| 238 | - if k < 0 { | ||
| 239 | - c | ||
| 240 | - } else { | ||
| 241 | - left[k as usize] as i32 | ||
| 242 | - } | ||
| 243 | - }; | ||
| 244 | - | ||
| 245 | - let mut p = [0i32; 16]; | ||
| 246 | - match mode { | ||
| 247 | - 0 => { | ||
| 248 | - for y in 0..4 { | ||
| 249 | - for x in 0..4 { | ||
| 250 | - p[y * 4 + x] = t(x); | ||
| 251 | - } | ||
| 252 | - } | ||
| 253 | - } | ||
| 254 | - 1 => { | ||
| 255 | - for y in 0..4 { | ||
| 256 | - for x in 0..4 { | ||
| 257 | - p[y * 4 + x] = l(y); | ||
| 258 | - } | ||
| 259 | - } | ||
| 260 | - } | ||
| 261 | - 2 => { | ||
| 262 | - let v = if avail_top && avail_left { | ||
| 263 | - (t(0) + t(1) + t(2) + t(3) + l(0) + l(1) + l(2) + l(3) + 4) >> 3 | ||
| 264 | - } else if avail_top { | ||
| 265 | - (t(0) + t(1) + t(2) + t(3) + 2) >> 2 | ||
| 266 | - } else if avail_left { | ||
| 267 | - (l(0) + l(1) + l(2) + l(3) + 2) >> 2 | ||
| 268 | - } else { | ||
| 269 | - 128 | ||
| 270 | - }; | ||
| 271 | - p.fill(v); | ||
| 272 | - } | ||
| 273 | - 3 => { | ||
| 274 | - // Diagonal down-left | ||
| 275 | - for y in 0..4 { | ||
| 276 | - for x in 0..4 { | ||
| 277 | - p[y * 4 + x] = if x == 3 && y == 3 { | ||
| 278 | - (t(6) + 3 * t(7) + 2) >> 2 | ||
| 279 | - } else { | ||
| 280 | - let k = x + y; | ||
| 281 | - (t(k) + 2 * t(k + 1) + t(k + 2) + 2) >> 2 | ||
| 282 | - }; | ||
| 283 | - } | ||
| 284 | - } | ||
| 285 | - } | ||
| 286 | - 4 => { | ||
| 287 | - // Diagonal down-right | ||
| 288 | - for y in 0..4i32 { | ||
| 289 | - for x in 0..4i32 { | ||
| 290 | - p[(y * 4 + x) as usize] = if x > y { | ||
| 291 | - (tt(x - y - 2) + 2 * tt(x - y - 1) + tt(x - y) + 2) >> 2 | ||
| 292 | - } else if x < y { | ||
| 293 | - (ll(y - x - 2) + 2 * ll(y - x - 1) + ll(y - x) + 2) >> 2 | ||
| 294 | - } else { | ||
| 295 | - (t(0) + 2 * c + l(0) + 2) >> 2 | ||
| 296 | - }; | ||
| 297 | - } | ||
| 298 | - } | ||
| 299 | - } | ||
| 300 | - 5 => { | ||
| 301 | - // Vertical-right | ||
| 302 | - for y in 0..4i32 { | ||
| 303 | - for x in 0..4i32 { | ||
| 304 | - let zvr = 2 * x - y; | ||
| 305 | - let k = x - (y >> 1); | ||
| 306 | - p[(y * 4 + x) as usize] = if zvr >= 0 && zvr % 2 == 0 { | ||
| 307 | - (tt(k - 1) + tt(k) + 1) >> 1 | ||
| 308 | - } else if zvr >= 0 { | ||
| 309 | - (tt(k - 2) + 2 * tt(k - 1) + tt(k) + 2) >> 2 | ||
| 310 | - } else if zvr == -1 { | ||
| 311 | - (l(0) + 2 * c + t(0) + 2) >> 2 | ||
| 312 | - } else { | ||
| 313 | - (ll(y - 1) + 2 * ll(y - 2) + ll(y - 3) + 2) >> 2 | ||
| 314 | - }; | ||
| 315 | - } | ||
| 316 | - } | ||
| 317 | - } | ||
| 318 | - 6 => { | ||
| 319 | - // Horizontal-down | ||
| 320 | - for y in 0..4i32 { | ||
| 321 | - for x in 0..4i32 { | ||
| 322 | - let zhd = 2 * y - x; | ||
| 323 | - let k = y - (x >> 1); | ||
| 324 | - p[(y * 4 + x) as usize] = if zhd >= 0 && zhd % 2 == 0 { | ||
| 325 | - (ll(k - 1) + ll(k) + 1) >> 1 | ||
| 326 | - } else if zhd >= 0 { | ||
| 327 | - (ll(k - 2) + 2 * ll(k - 1) + ll(k) + 2) >> 2 | ||
| 328 | - } else if zhd == -1 { | ||
| 329 | - (l(0) + 2 * c + t(0) + 2) >> 2 | ||
| 330 | - } else { | ||
| 331 | - (tt(x - 1) + 2 * tt(x - 2) + tt(x - 3) + 2) >> 2 | ||
| 332 | - }; | ||
| 333 | - } | ||
| 334 | - } | ||
| 335 | - } | ||
| 336 | - 7 => { | ||
| 337 | - // Vertical-left | ||
| 338 | - for y in 0..4 { | ||
| 339 | - for x in 0..4 { | ||
| 340 | - let k = x + (y >> 1); | ||
| 341 | - p[y * 4 + x] = if y % 2 == 0 { | ||
| 342 | - (t(k) + t(k + 1) + 1) >> 1 | ||
| 343 | - } else { | ||
| 344 | - (t(k) + 2 * t(k + 1) + t(k + 2) + 2) >> 2 | ||
| 345 | - }; | ||
| 346 | - } | ||
| 347 | - } | ||
| 348 | - } | ||
| 349 | - _ => { | ||
| 350 | - // Horizontal-up (mode 8) | ||
| 351 | - for y in 0..4 { | ||
| 352 | - for x in 0..4 { | ||
| 353 | - let zhu = x + 2 * y; | ||
| 354 | - let k = y + (x >> 1); | ||
| 355 | - p[y * 4 + x] = if zhu <= 4 && zhu % 2 == 0 { | ||
| 356 | - (l(k) + l(k + 1) + 1) >> 1 | ||
| 357 | - } else if zhu < 5 { | ||
| 358 | - (l(k) + 2 * l(k + 1) + l(k + 2) + 2) >> 2 | ||
| 359 | - } else if zhu == 5 { | ||
| 360 | - (l(2) + 3 * l(3) + 2) >> 2 | ||
| 361 | - } else { | ||
| 362 | - l(3) | ||
| 363 | - }; | ||
| 364 | - } | ||
| 365 | - } | ||
| 366 | - } | ||
| 367 | - } | ||
| 368 | - let mut out = [0u8; 16]; | ||
| 369 | - for i in 0..16 { | ||
| 370 | - out[i] = clip_u8(p[i]); | ||
| 371 | - } | ||
| 372 | - out | ||
| 373 | -} | ||
| 374 | - | ||
| 375 | -/// Intra chroma 8×8 DC prediction (spec §8.3.4): the 8×8 is split into four 4×4 | ||
| 376 | -/// regions, each predicted from its available neighbor run. Returns the 64 | ||
| 377 | -/// predicted samples in raster order. `top`/`left` are the 8 neighbor samples. | ||
| 378 | -pub fn chroma8x8_dc(avail_top: bool, avail_left: bool, top: &[u8; 8], left: &[u8; 8]) -> [u8; 64] { | ||
| 379 | - let mut out = [128u8; 64]; | ||
| 380 | - for &(bx, by) in &CHROMA_4X4_SCAN_XY { | ||
| 381 | - let (x0, y0) = (bx * 4, by * 4); | ||
| 382 | - let top4 = &top[x0..x0 + 4]; | ||
| 383 | - let left4 = &left[y0..y0 + 4]; | ||
| 384 | - // Which neighbor each region prefers (spec §8.3.4.1). | ||
| 385 | - let prefer_top = (x0, y0) == (4, 0); | ||
| 386 | - let prefer_left = (x0, y0) == (0, 4); | ||
| 387 | - let dc: i32 = if prefer_top { | ||
| 388 | - if avail_top { | ||
| 389 | - (sum(top4) + 2) >> 2 | ||
| 390 | - } else if avail_left { | ||
| 391 | - (sum(left4) + 2) >> 2 | ||
| 392 | - } else { | ||
| 393 | - 128 | ||
| 394 | - } | ||
| 395 | - } else if prefer_left { | ||
| 396 | - if avail_left { | ||
| 397 | - (sum(left4) + 2) >> 2 | ||
| 398 | - } else if avail_top { | ||
| 399 | - (sum(top4) + 2) >> 2 | ||
| 400 | - } else { | ||
| 401 | - 128 | ||
| 402 | - } | ||
| 403 | - } else { | ||
| 404 | - // (0,0) and (4,4): use both when available. | ||
| 405 | - if avail_top && avail_left { | ||
| 406 | - (sum(top4) + sum(left4) + 4) >> 3 | ||
| 407 | - } else if avail_top { | ||
| 408 | - (sum(top4) + 2) >> 2 | ||
| 409 | - } else if avail_left { | ||
| 410 | - (sum(left4) + 2) >> 2 | ||
| 411 | - } else { | ||
| 412 | - 128 | ||
| 413 | - } | ||
| 414 | - }; | ||
| 415 | - for dy in 0..4 { | ||
| 416 | - for dx in 0..4 { | ||
| 417 | - out[(y0 + dy) * 8 + (x0 + dx)] = dc as u8; | ||
| 418 | - } | ||
| 419 | - } | ||
| 420 | - } | ||
| 421 | - out | ||
| 422 | -} | ||
| 423 | - | ||
| 424 | -/// Intra chroma 8×8 prediction (spec §8.3.4), all four modes. `mode`: | ||
| 425 | -/// 0 = DC, 1 = Horizontal, 2 = Vertical, 3 = Plane. `top`/`left` are the 8 | ||
| 426 | -/// neighbor samples; `corner` is the above-left (Plane only). | ||
| 427 | -pub fn chroma8x8_pred( | ||
| 428 | - mode: u8, | ||
| 429 | - avail_top: bool, | ||
| 430 | - avail_left: bool, | ||
| 431 | - top: &[u8; 8], | ||
| 432 | - left: &[u8; 8], | ||
| 433 | - corner: u8, | ||
| 434 | -) -> [u8; 64] { | ||
| 435 | - if abl_intra() { | ||
| 436 | - return [128; 64]; | ||
| 437 | - } | ||
| 438 | - let _g = crate::prof::scope(crate::prof::Stage::IntraPred); | ||
| 439 | - match mode { | ||
| 440 | - 1 => { | ||
| 441 | - // Horizontal | ||
| 442 | - let mut out = [0u8; 64]; | ||
| 443 | - for y in 0..8 { | ||
| 444 | - for x in 0..8 { | ||
| 445 | - out[y * 8 + x] = left[y]; | ||
| 446 | - } | ||
| 447 | - } | ||
| 448 | - out | ||
| 449 | - } | ||
| 450 | - 2 => { | ||
| 451 | - // Vertical | ||
| 452 | - let mut out = [0u8; 64]; | ||
| 453 | - for y in 0..8 { | ||
| 454 | - for x in 0..8 { | ||
| 455 | - out[y * 8 + x] = top[x]; | ||
| 456 | - } | ||
| 457 | - } | ||
| 458 | - out | ||
| 459 | - } | ||
| 460 | - 3 => { | ||
| 461 | - // Plane | ||
| 462 | - let tt = |k: i32| if k < 0 { corner as i32 } else { top[k as usize] as i32 }; | ||
| 463 | - let ll = |k: i32| if k < 0 { corner as i32 } else { left[k as usize] as i32 }; | ||
| 464 | - let mut h = 0i32; | ||
| 465 | - let mut v = 0i32; | ||
| 466 | - for xp in 0..4i32 { | ||
| 467 | - h += (xp + 1) * (top[(4 + xp) as usize] as i32 - tt(2 - xp)); | ||
| 468 | - } | ||
| 469 | - for yp in 0..4i32 { | ||
| 470 | - v += (yp + 1) * (left[(4 + yp) as usize] as i32 - ll(2 - yp)); | ||
| 471 | - } | ||
| 472 | - let a = 16 * (left[7] as i32 + top[7] as i32); | ||
| 473 | - let b = (17 * h + 16) >> 5; | ||
| 474 | - let c = (17 * v + 16) >> 5; | ||
| 475 | - let mut out = [0u8; 64]; | ||
| 476 | - for y in 0..8i32 { | ||
| 477 | - for x in 0..8i32 { | ||
| 478 | - out[(y * 8 + x) as usize] = clip_u8((a + b * (x - 3) + c * (y - 3) + 16) >> 5); | ||
| 479 | - } | ||
| 480 | - } | ||
| 481 | - out | ||
| 482 | - } | ||
| 483 | - _ => chroma8x8_dc(avail_top, avail_left, top, left), | ||
| 484 | - } | ||
| 485 | -} | ||
| 486 | - | ||
| 487 | -/// Whether a chroma prediction mode is usable given neighbor availability. | ||
| 488 | -pub fn chroma_mode_available(mode: u8, avail_top: bool, avail_left: bool) -> bool { | ||
| 489 | - match mode { | ||
| 490 | - 0 => true, // DC | ||
| 491 | - 1 => avail_left, // Horizontal | ||
| 492 | - 2 => avail_top, // Vertical | ||
| 493 | - _ => avail_top && avail_left, // Plane | ||
| 494 | - } | ||
| 495 | -} | ||
| 496 | - | ||
| 497 | -/// Clips a value to the 8-bit pixel range. | ||
| 498 | -#[inline] | ||
| 499 | -pub fn clip_u8(v: i32) -> u8 { | ||
| 500 | - v.clamp(0, 255) as u8 | ||
| 501 | -} | ||
| 502 | - | ||
| 503 | -/// Reconstructs a 4×4 block: inverse-transform the dequantized coefficients and | ||
| 504 | -/// add the prediction, clipping to 8-bit. `dequant` and `pred` are raster 4×4. | ||
| 505 | -pub fn reconstruct_4x4(dequant: &[i32; 16], pred: &[i32; 16]) -> [u8; 16] { | ||
| 506 | - if abl_recon() { | ||
| 507 | - return std::array::from_fn(|i| clip_u8(pred[i])); | ||
| 508 | - } | ||
| 509 | - let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); | ||
| 510 | - add_residual_4x4(&inverse_core(dequant), pred) | ||
| 511 | -} | ||
| 512 | - | ||
| 513 | -/// Reconstructs a 4×4 block DIRECTLY into the frame plane: IDCT + add + clip + | ||
| 514 | -/// store in one pass, with the prediction read strided from its buffer. Kills | ||
| 515 | -/// the per-block `predb` i32 gather, the `[u8; 16]` result array, and the | ||
| 516 | -/// separate `store` call — the resid-add boundary the WHYS Part 8/9 descent | ||
| 517 | -/// priced. Honors the same ablation knob as `reconstruct_4x4`. | ||
| 518 | -#[inline] | ||
| 519 | -pub fn reconstruct_4x4_into( | ||
| 520 | - deq: &[i32; 16], | ||
| 521 | - pred: &[u8], | ||
| 522 | - p_off: usize, | ||
| 523 | - p_stride: usize, | ||
| 524 | - rec: &mut [u8], | ||
| 525 | - r_off: usize, | ||
| 526 | - r_stride: usize, | ||
| 527 | -) { | ||
| 528 | - if abl_recon() { | ||
| 529 | - for r in 0..4 { | ||
| 530 | - for c in 0..4 { | ||
| 531 | - rec[r_off + r * r_stride + c] = pred[p_off + r * p_stride + c]; | ||
| 532 | - } | ||
| 533 | - } | ||
| 534 | - return; | ||
| 535 | - } | ||
| 536 | - let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); | ||
| 537 | - let res = crate::transform::inverse_core(deq); | ||
| 538 | - for r in 0..4 { | ||
| 539 | - for c in 0..4 { | ||
| 540 | - rec[r_off + r * r_stride + c] = | ||
| 541 | - clip_u8(pred[p_off + r * p_stride + c] as i32 + res[r * 4 + c]); | ||
| 542 | - } | ||
| 543 | - } | ||
| 544 | -} | ||
| 545 | - | ||
| 546 | -/// Flat-residual twin of [`reconstruct_4x4_into`] (the DC-only fast path). | ||
| 547 | -#[inline] | ||
| 548 | -pub fn reconstruct_4x4_dc_into( | ||
| 549 | - rval: i32, | ||
| 550 | - pred: &[u8], | ||
| 551 | - p_off: usize, | ||
| 552 | - p_stride: usize, | ||
| 553 | - rec: &mut [u8], | ||
| 554 | - r_off: usize, | ||
| 555 | - r_stride: usize, | ||
| 556 | -) { | ||
| 557 | - if abl_recon() { | ||
| 558 | - for r in 0..4 { | ||
| 559 | - for c in 0..4 { | ||
| 560 | - rec[r_off + r * r_stride + c] = pred[p_off + r * p_stride + c]; | ||
| 561 | - } | ||
| 562 | - } | ||
| 563 | - return; | ||
| 564 | - } | ||
| 565 | - let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); | ||
| 566 | - for r in 0..4 { | ||
| 567 | - for c in 0..4 { | ||
| 568 | - rec[r_off + r * r_stride + c] = | ||
| 569 | - clip_u8(pred[p_off + r * p_stride + c] as i32 + rval); | ||
| 570 | - } | ||
| 571 | - } | ||
| 572 | -} | ||
| 573 | - | ||
| 574 | -/// Reconstructs a block whose residual is FLAT (every position carries the same | ||
| 575 | -/// value `r`) — the tail of the DC-only fast path. Honors the same ablation | ||
| 576 | -/// knob and profiling stage as [`reconstruct_4x4`] so measurement arms stay | ||
| 577 | -/// comparable whichever path a block takes. | ||
| 578 | -#[inline] | ||
| 579 | -pub fn reconstruct_4x4_dc(r: i32, pred: &[i32; 16]) -> [u8; 16] { | ||
| 580 | - if abl_recon() { | ||
| 581 | - return std::array::from_fn(|i| clip_u8(pred[i])); | ||
| 582 | - } | ||
| 583 | - let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); | ||
| 584 | - std::array::from_fn(|i| clip_u8(pred[i] + r)) | ||
| 585 | -} | ||
| 586 | - | ||
| 587 | -/// Adds an already-inverse-transformed residual block to its prediction and clips | ||
| 588 | -/// to `u8`. Split out of [`reconstruct_4x4`] so callers that batch the inverse DCT | ||
| 589 | -/// ([`crate::transform::inverse_dct_blocks`]) can share the add+clip tail. | ||
| 590 | -#[inline] | ||
| 591 | -pub fn add_residual_4x4(res: &[i32; 16], pred: &[i32; 16]) -> [u8; 16] { | ||
| 592 | - let mut out = [0u8; 16]; | ||
| 593 | - for i in 0..16 { | ||
| 594 | - out[i] = clip_u8(pred[i] + res[i]); | ||
| 595 | - } | ||
| 596 | - out | ||
| 597 | -} | ||
| 598 | - | ||
| 599 | -/// Intra_8x8 luma prediction (spec §8.3.2.2), all nine modes. Reference samples | ||
| 600 | -/// are first low-pass filtered (§8.3.2.2.1) then the per-mode formulas — which | ||
| 601 | -/// mirror the 4×4 ones over the 8-wide block — are applied. `top` holds the 16 | ||
| 602 | -/// samples p[0..15,-1] (8..15 substituted by the caller when no top-right), | ||
| 603 | -/// `left` the 8 samples p[-1,0..7], `corner` is p[-1,-1]; `avail_corner` is the | ||
| 604 | -/// above-left neighbor's availability. Returns 64 predicted samples (raster). | ||
| 605 | -#[allow(clippy::needless_range_loop)] // filter loops read neighbors p[k-1..k+1] | ||
| 606 | -pub fn intra8x8_pred( | ||
| 607 | - mode: u8, | ||
| 608 | - avail_top: bool, | ||
| 609 | - avail_left: bool, | ||
| 610 | - avail_corner: bool, | ||
| 611 | - top: &[u8; 16], | ||
| 612 | - left: &[u8; 8], | ||
| 613 | - corner: u8, | ||
| 614 | -) -> [u8; 64] { | ||
| 615 | - let _g = crate::prof::scope(crate::prof::Stage::IntraPred); | ||
| 616 | - // ---- reference sample filtering (§8.3.2.2.1) ---- | ||
| 617 | - let t = |k: usize| top[k] as i32; | ||
| 618 | - let l = |k: usize| left[k] as i32; | ||
| 619 | - let cc = corner as i32; | ||
| 620 | - let mut ft = [0i32; 16]; | ||
| 621 | - ft[0] = if avail_corner { | ||
| 622 | - (cc + 2 * t(0) + t(1) + 2) >> 2 | ||
| 623 | - } else { | ||
| 624 | - (3 * t(0) + t(1) + 2) >> 2 | ||
| 625 | - }; | ||
| 626 | - for k in 1..15 { | ||
| 627 | - ft[k] = (t(k - 1) + 2 * t(k) + t(k + 1) + 2) >> 2; | ||
| 628 | - } | ||
| 629 | - ft[15] = (t(14) + 3 * t(15) + 2) >> 2; | ||
| 630 | - let mut fl = [0i32; 8]; | ||
| 631 | - fl[0] = if avail_corner { | ||
| 632 | - (cc + 2 * l(0) + l(1) + 2) >> 2 | ||
| 633 | - } else { | ||
| 634 | - (3 * l(0) + l(1) + 2) >> 2 | ||
| 635 | - }; | ||
| 636 | - for k in 1..7 { | ||
| 637 | - fl[k] = (l(k - 1) + 2 * l(k) + l(k + 1) + 2) >> 2; | ||
| 638 | - } | ||
| 639 | - fl[7] = (l(6) + 3 * l(7) + 2) >> 2; | ||
| 640 | - let fc = if avail_corner { | ||
| 641 | - if avail_top && avail_left { | ||
| 642 | - (t(0) + 2 * cc + l(0) + 2) >> 2 | ||
| 643 | - } else if avail_top { | ||
| 644 | - (3 * cc + t(0) + 2) >> 2 | ||
| 645 | - } else if avail_left { | ||
| 646 | - (3 * cc + l(0) + 2) >> 2 | ||
| 647 | - } else { | ||
| 648 | - cc | ||
| 649 | - } | ||
| 650 | - } else { | ||
| 651 | - cc | ||
| 652 | - }; | ||
| 653 | - // Indexers with -1 → filtered corner (for the diagonal modes). | ||
| 654 | - let ttf = |k: i32| -> i32 { | ||
| 655 | - if k < 0 { | ||
| 656 | - fc | ||
| 657 | - } else { | ||
| 658 | - ft[k as usize] | ||
| 659 | - } | ||
| 660 | - }; | ||
| 661 | - let llf = |k: i32| -> i32 { | ||
| 662 | - if k < 0 { | ||
| 663 | - fc | ||
| 664 | - } else { | ||
| 665 | - fl[k as usize] | ||
| 666 | - } | ||
| 667 | - }; | ||
| 668 | - | ||
| 669 | - let mut p = [0i32; 64]; | ||
| 670 | - match mode { | ||
| 671 | - 0 => { | ||
| 672 | - for y in 0..8 { | ||
| 673 | - for x in 0..8 { | ||
| 674 | - p[y * 8 + x] = ft[x]; | ||
| 675 | - } | ||
| 676 | - } | ||
| 677 | - } | ||
| 678 | - 1 => { | ||
| 679 | - for y in 0..8 { | ||
| 680 | - for x in 0..8 { | ||
| 681 | - p[y * 8 + x] = fl[y]; | ||
| 682 | - } | ||
| 683 | - } | ||
| 684 | - } | ||
| 685 | - 2 => { | ||
| 686 | - let st: i32 = ft[0..8].iter().sum(); | ||
| 687 | - let sl: i32 = fl[0..8].iter().sum(); | ||
| 688 | - let v = if avail_top && avail_left { | ||
| 689 | - (st + sl + 8) >> 4 | ||
| 690 | - } else if avail_top { | ||
| 691 | - (st + 4) >> 3 | ||
| 692 | - } else if avail_left { | ||
| 693 | - (sl + 4) >> 3 | ||
| 694 | - } else { | ||
| 695 | - 128 | ||
| 696 | - }; | ||
| 697 | - p.fill(v); | ||
| 698 | - } | ||
| 699 | - 3 => { | ||
| 700 | - for y in 0..8 { | ||
| 701 | - for x in 0..8 { | ||
| 702 | - p[y * 8 + x] = if x == 7 && y == 7 { | ||
| 703 | - (ft[14] + 3 * ft[15] + 2) >> 2 | ||
| 704 | - } else { | ||
| 705 | - (ft[x + y] + 2 * ft[x + y + 1] + ft[x + y + 2] + 2) >> 2 | ||
| 706 | - }; | ||
| 707 | - } | ||
| 708 | - } | ||
| 709 | - } | ||
| 710 | - 4 => { | ||
| 711 | - for y in 0..8i32 { | ||
| 712 | - for x in 0..8i32 { | ||
| 713 | - p[(y * 8 + x) as usize] = if x > y { | ||
| 714 | - (ttf(x - y - 2) + 2 * ttf(x - y - 1) + ttf(x - y) + 2) >> 2 | ||
| 715 | - } else if x < y { | ||
| 716 | - (llf(y - x - 2) + 2 * llf(y - x - 1) + llf(y - x) + 2) >> 2 | ||
| 717 | - } else { | ||
| 718 | - (ft[0] + 2 * fc + fl[0] + 2) >> 2 | ||
| 719 | - }; | ||
| 720 | - } | ||
| 721 | - } | ||
| 722 | - } | ||
| 723 | - 5 => { | ||
| 724 | - for y in 0..8i32 { | ||
| 725 | - for x in 0..8i32 { | ||
| 726 | - let zvr = 2 * x - y; | ||
| 727 | - let k = x - (y >> 1); | ||
| 728 | - p[(y * 8 + x) as usize] = if zvr >= 0 && zvr % 2 == 0 { | ||
| 729 | - (ttf(k - 1) + ttf(k) + 1) >> 1 | ||
| 730 | - } else if zvr >= 0 { | ||
| 731 | - (ttf(k - 2) + 2 * ttf(k - 1) + ttf(k) + 2) >> 2 | ||
| 732 | - } else if zvr == -1 { | ||
| 733 | - (fl[0] + 2 * fc + ft[0] + 2) >> 2 | ||
| 734 | - } else { | ||
| 735 | - let j = y - 2 * x; | ||
| 736 | - (llf(j - 1) + 2 * llf(j - 2) + llf(j - 3) + 2) >> 2 | ||
| 737 | - }; | ||
| 738 | - } | ||
| 739 | - } | ||
| 740 | - } | ||
| 741 | - 6 => { | ||
| 742 | - for y in 0..8i32 { | ||
| 743 | - for x in 0..8i32 { | ||
| 744 | - let zhd = 2 * y - x; | ||
| 745 | - let k = y - (x >> 1); | ||
| 746 | - p[(y * 8 + x) as usize] = if zhd >= 0 && zhd % 2 == 0 { | ||
| 747 | - (llf(k - 1) + llf(k) + 1) >> 1 | ||
| 748 | - } else if zhd >= 0 { | ||
| 749 | - (llf(k - 2) + 2 * llf(k - 1) + llf(k) + 2) >> 2 | ||
| 750 | - } else if zhd == -1 { | ||
| 751 | - (fl[0] + 2 * fc + ft[0] + 2) >> 2 | ||
| 752 | - } else { | ||
| 753 | - let j = x - 2 * y; | ||
| 754 | - (ttf(j - 1) + 2 * ttf(j - 2) + ttf(j - 3) + 2) >> 2 | ||
| 755 | - }; | ||
| 756 | - } | ||
| 757 | - } | ||
| 758 | - } | ||
| 759 | - 7 => { | ||
| 760 | - for y in 0..8 { | ||
| 761 | - for x in 0..8 { | ||
| 762 | - let k = x + (y >> 1); | ||
| 763 | - p[y * 8 + x] = if y % 2 == 0 { | ||
| 764 | - (ft[k] + ft[k + 1] + 1) >> 1 | ||
| 765 | - } else { | ||
| 766 | - (ft[k] + 2 * ft[k + 1] + ft[k + 2] + 2) >> 2 | ||
| 767 | - }; | ||
| 768 | - } | ||
| 769 | - } | ||
| 770 | - } | ||
| 771 | - _ => { | ||
| 772 | - // Horizontal-up (mode 8) — 8×8 thresholds (zHU up to 13 special). | ||
| 773 | - for y in 0..8 { | ||
| 774 | - for x in 0..8 { | ||
| 775 | - let zhu = x + 2 * y; | ||
| 776 | - let k = y + (x >> 1); | ||
| 777 | - p[y * 8 + x] = if zhu < 13 && zhu % 2 == 0 { | ||
| 778 | - (fl[k] + fl[k + 1] + 1) >> 1 | ||
| 779 | - } else if zhu < 13 { | ||
| 780 | - (fl[k] + 2 * fl[k + 1] + fl[k + 2] + 2) >> 2 | ||
| 781 | - } else if zhu == 13 { | ||
| 782 | - (fl[6] + 3 * fl[7] + 2) >> 2 | ||
| 783 | - } else { | ||
| 784 | - fl[7] | ||
| 785 | - }; | ||
| 786 | - } | ||
| 787 | - } | ||
| 788 | - } | ||
| 789 | - } | ||
| 790 | - let mut out = [0u8; 64]; | ||
| 791 | - for i in 0..64 { | ||
| 792 | - out[i] = clip_u8(p[i]); | ||
| 793 | - } | ||
| 794 | - out | ||
| 795 | -} | ||
| 796 | - | ||
| 797 | -/// Reconstructs an 8×8 block: inverse-transform the dequantized coefficients, | ||
| 798 | -/// add the prediction, clip. (The 8×8 inverse transform lives in `transform`.) | ||
| 799 | -pub fn add_residual_8x8(res: &[i32; 64], pred: &[i32; 64]) -> [u8; 64] { | ||
| 800 | - let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); | ||
| 801 | - let mut out = [0u8; 64]; | ||
| 802 | - for i in 0..64 { | ||
| 803 | - out[i] = clip_u8(pred[i] + res[i]); | ||
| 804 | - } | ||
| 805 | - out | ||
| 806 | -} | ||
| 807 | - | ||
| 808 | -#[cfg(test)] | ||
| 809 | -mod tests { | ||
| 810 | - use super::*; | ||
| 811 | - | ||
| 812 | - #[test] | ||
| 813 | - fn intra8x8_dc_no_neighbors_is_128() { | ||
| 814 | - let p = intra8x8_pred(2, false, false, false, &[0; 16], &[0; 8], 0); | ||
| 815 | - assert!(p.iter().all(|&v| v == 128)); | ||
| 816 | - } | ||
| 817 | - | ||
| 818 | - #[test] | ||
| 819 | - fn intra8x8_vertical_copies_filtered_top() { | ||
| 820 | - // Flat top → filtered top is the same flat value → every column equals it. | ||
| 821 | - let p = intra8x8_pred(0, true, false, false, &[90; 16], &[0; 8], 0); | ||
| 822 | - assert!(p.iter().all(|&v| v == 90)); | ||
| 823 | - } | ||
| 824 | - | ||
| 825 | - #[test] | ||
| 826 | - fn intra8x8_horizontal_is_constant_per_row() { | ||
| 827 | - let mut left = [0u8; 8]; | ||
| 828 | - for (i, v) in left.iter_mut().enumerate() { | ||
| 829 | - *v = (10 * i + 20) as u8; | ||
| 830 | - } | ||
| 831 | - let p = intra8x8_pred(1, false, true, false, &[0; 16], &left, 0); | ||
| 832 | - // Each row constant; filtering blurs values but row 0..7 stay monotone-ish. | ||
| 833 | - for y in 0..8 { | ||
| 834 | - for x in 1..8 { | ||
| 835 | - assert_eq!(p[y * 8 + x], p[y * 8], "row {y} not constant"); | ||
| 836 | - } | ||
| 837 | - } | ||
| 838 | - } | ||
| 839 | - | ||
| 840 | - #[test] | ||
| 841 | - fn luma_dc_no_neighbors_is_128() { | ||
| 842 | - assert_eq!(luma16x16_dc(false, false, &[0; 16], &[0; 16]), 128); | ||
| 843 | - } | ||
| 844 | - | ||
| 845 | - #[test] | ||
| 846 | - fn luma_dc_averages_neighbors() { | ||
| 847 | - let top = [100u8; 16]; | ||
| 848 | - let left = [200u8; 16]; | ||
| 849 | - // (1600 + 3200 + 16) >> 5 = 150 | ||
| 850 | - assert_eq!(luma16x16_dc(true, true, &top, &left), 150); | ||
| 851 | - assert_eq!(luma16x16_dc(true, false, &top, &left), 100); | ||
| 852 | - assert_eq!(luma16x16_dc(false, true, &top, &left), 200); | ||
| 853 | - } | ||
| 854 | - | ||
| 855 | - #[test] | ||
| 856 | - fn chroma_dc_unavailable_is_128() { | ||
| 857 | - let p = chroma8x8_dc(false, false, &[0; 8], &[0; 8]); | ||
| 858 | - assert!(p.iter().all(|&x| x == 128)); | ||
| 859 | - } | ||
| 860 | - | ||
| 861 | - #[test] | ||
| 862 | - fn chroma_qp_mapping() { | ||
| 863 | - assert_eq!(chroma_qp(20), 20); | ||
| 864 | - assert_eq!(chroma_qp(30), 29); | ||
| 865 | - assert_eq!(chroma_qp(51), 39); | ||
| 866 | - } | ||
| 867 | - | ||
| 868 | - #[test] | ||
| 869 | - fn nc_derivation() { | ||
| 870 | - assert_eq!(nc_from_neighbors(Some(3), Some(4)), 4); | ||
| 871 | - assert_eq!(nc_from_neighbors(Some(5), None), 5); | ||
| 872 | - assert_eq!(nc_from_neighbors(None, None), 0); | ||
| 873 | - } | ||
| 874 | - | ||
| 875 | - #[test] | ||
| 876 | - fn intra4x4_vertical_copies_top() { | ||
| 877 | - let top = [10, 20, 30, 40, 0, 0, 0, 0]; | ||
| 878 | - let p = intra4x4_pred(0, true, false, &top, &[0; 4], 0); | ||
| 879 | - for y in 0..4 { | ||
| 880 | - assert_eq!(&p[y * 4..y * 4 + 4], &[10, 20, 30, 40]); | ||
| 881 | - } | ||
| 882 | - } | ||
| 883 | - | ||
| 884 | - #[test] | ||
| 885 | - fn intra4x4_horizontal_copies_left() { | ||
| 886 | - let left = [11, 22, 33, 44]; | ||
| 887 | - let p = intra4x4_pred(1, false, true, &[0; 8], &left, 0); | ||
| 888 | - for y in 0..4 { | ||
| 889 | - assert!(p[y * 4..y * 4 + 4].iter().all(|&v| v == left[y])); | ||
| 890 | - } | ||
| 891 | - } | ||
| 892 | - | ||
| 893 | - #[test] | ||
| 894 | - fn intra4x4_dc_averages() { | ||
| 895 | - let top = [10, 10, 10, 10, 0, 0, 0, 0]; | ||
| 896 | - let left = [30, 30, 30, 30]; | ||
| 897 | - // (40 + 120 + 4) >> 3 = 20 | ||
| 898 | - let p = intra4x4_pred(2, true, true, &top, &left, 0); | ||
| 899 | - assert!(p.iter().all(|&v| v == 20)); | ||
| 900 | - // top only: (40 + 2) >> 2 = 10 | ||
| 901 | - let p2 = intra4x4_pred(2, true, false, &top, &left, 0); | ||
| 902 | - assert!(p2.iter().all(|&v| v == 10)); | ||
| 903 | - // neither: 128 | ||
| 904 | - let p3 = intra4x4_pred(2, false, false, &top, &left, 0); | ||
| 905 | - assert!(p3.iter().all(|&v| v == 128)); | ||
| 906 | - } | ||
| 907 | -} | ||
vendor/rusty_h264-common/src/prof.rsdeleted+0 -585
| @@ -1,585 +0,0 @@ | |||
| 1 | -//! Feature-gated decode/encode **stage profiler** — the instrument for perf work. | ||
| 2 | -//! | ||
| 3 | -//! Zero cost unless the `profile` feature is enabled: with it off, [`scope`] is a | ||
| 4 | -//! no-op returning a ZST guard that the optimizer elides entirely, so release | ||
| 5 | -//! builds are byte-identical and the hot path is untouched. With it on, each | ||
| 6 | -//! kernel times itself into an atomic nanosecond bucket; [`dump`] prints the | ||
| 7 | -//! per-stage breakdown. | ||
| 8 | -//! | ||
| 9 | -//! Design mirrors `rff-codec-mp3`'s `encode::prof`. The kernels (`mc_luma`, | ||
| 10 | -//! `reconstruct_4x4`, `decode_residual_block`, the intra predictors, `deblock`) | ||
| 11 | -//! each open a [`scope`] at their top, so every call is captured with one edit. | ||
| 12 | -//! A [`Stage::Total`] scope wraps the whole `decode()` call; the **`mgmt/other`** | ||
| 13 | -//! line is the residue (`Total − Σ stages`) — i.e. per-MB management, MV | ||
| 14 | -//! prediction, nnz/grid bookkeeping, dequant — the bucket we most want to shrink. | ||
| 15 | -//! | ||
| 16 | -//! Caveat for honest reading: the fine-grained buckets (`reconstruct`, `entropy`) | ||
| 17 | -//! are entered millions of times, so each carries ~one `Instant::now()` of timer | ||
| 18 | -//! overhead — their share is mildly inflated and `mgmt/other` mildly deflated. | ||
| 19 | -//! The `(N calls)` column lets you judge ns/call. Measure **throughput** with the | ||
| 20 | -//! `profile` feature OFF (no timer overhead); use this breakdown only to rank | ||
| 21 | -//! stages. | ||
| 22 | - | ||
| 23 | -/// A timed pipeline stage. Order matters: everything before [`Total`](Stage::Total) | ||
| 24 | -/// is a sub-component summed for the `mgmt/other` residue. | ||
| 25 | -#[derive(Clone, Copy)] | ||
| 26 | -pub enum Stage { | ||
| 27 | - Entropy = 0, | ||
| 28 | - IntraPred = 1, | ||
| 29 | - InterMc = 2, | ||
| 30 | - Reconstruct = 3, | ||
| 31 | - Deblock = 4, | ||
| 32 | - // --- Phase 1: decomposition of the former "mgmt/other" residue --- | ||
| 33 | - /// Inverse quantization (`dequantize*`, `inverse_quant_8x8`). | ||
| 34 | - Dequant = 5, | ||
| 35 | - /// Scattering a reconstructed block into the strided frame plane (`store`). | ||
| 36 | - Scatter = 6, | ||
| 37 | - /// Re-striding the MC output into the per-MB prediction buffer. | ||
| 38 | - PredBuf = 7, | ||
| 39 | - /// MV prediction + per-block motion/ref/coded grid writes. | ||
| 40 | - MvGrid = 8, | ||
| 41 | - // --- Phase 3 / ghost-tracking: further decomposition of the residue --- | ||
| 42 | - /// Neighbour derivation for prediction (MV/ref/intra-mode availability + reads). | ||
| 43 | - Neighbors = 9, | ||
| 44 | - /// P_Skip / B_Skip reconstruction (the pred→rec copies + grid writes, no residual). | ||
| 45 | - SkipRecon = 10, | ||
| 46 | - /// Per-frame finalize: output-frame build (crop), DPB / reference management. | ||
| 47 | - Finalize = 11, | ||
| 48 | - /// Per-MB non-residual syntax parse (mb_skip_run, mb_type, cbp, mb_qp_delta). | ||
| 49 | - Syntax = 12, | ||
| 50 | - /// `as_reference` DPB plane clone (rec_y/u/v → RefFrame), split out of Finalize. | ||
| 51 | - DpbClone = 13, | ||
| 52 | - // --- Encoder stages (a disjoint top-level partition of encode(); the shared | ||
| 53 | - // primitive scopes above — IntraPred/InterMc/Reconstruct/Deblock/Entropy — | ||
| 54 | - // nest INSIDE these and give the within-stage breakdown) --- | ||
| 55 | - /// `coded_source`: clamped copy of the source planes to the MB-aligned grid. | ||
| 56 | - EncSource = 14, | ||
| 57 | - /// P_Skip prediction + free-skip check (skip MC + SAD + commit). | ||
| 58 | - EncSkip = 15, | ||
| 59 | - /// Motion estimation: `best_part` (integer SAD search + sub-pel + SATD/λ cost). | ||
| 60 | - EncMe = 16, | ||
| 61 | - /// Intra mode cost inside the inter decision (`best_i16_sad`/`best_i16_satd`). | ||
| 62 | - EncIntraCost = 17, | ||
| 63 | - /// Coding a chosen inter MB (`encode_inter_mb`: MC, residual, T/Q, entropy, recon). | ||
| 64 | - EncInterCode = 18, | ||
| 65 | - /// Coding an intra MB (`encode_mb`: mode search + T/Q + entropy + recon). | ||
| 66 | - EncIntraCode = 19, | ||
| 67 | - /// Per-frame encoder finalize (deblock-info build + RefFrame handoff). | ||
| 68 | - EncFinal = 20, | ||
| 69 | - /// Forward transform + quantize (+ recon dequant/idct) inside MB coding — INFO (nested). | ||
| 70 | - EncTq = 21, | ||
| 71 | - /// CAVLC residual bit-writing — INFO (nested inside Enc*Code). | ||
| 72 | - EncWrite = 22, | ||
| 73 | - /// The skip free-check's forward T/Q proof — INFO (nested inside EncSkip). | ||
| 74 | - EncFree = 23, | ||
| 75 | - /// Per-frame encoder PREP before the macroblock loop (FrameEncoder grid | ||
| 76 | - /// allocation, source copy, AQ/mb-tree QP maps, content pre-passes) — INFO | ||
| 77 | - /// (nested; contains `EncSource`). | ||
| 78 | - EncPrep = 24, | ||
| 79 | - /// NAL assembly of the coded slice: RBSP emulation-prevention scan + the | ||
| 80 | - /// Annex-B copy into the output buffer. A full byte-wise pass over the frame's | ||
| 81 | - /// bitstream, invisible until it was named. | ||
| 82 | - EncNal = 25, | ||
| 83 | - /// The whole macroblock double-loop — INFO (nested; contains the Enc* per-MB | ||
| 84 | - /// stages). `EncMbLoop − Σ(per-MB stages)` is the per-MB GLUE, the part of the | ||
| 85 | - /// old `mgmt/other` that lives between the named steps. | ||
| 86 | - EncMbLoop = 26, | ||
| 87 | - /// Per-MB motion-vector predictor / neighbour-candidate build in the encode | ||
| 88 | - /// loop (`mv_neighbors_block`) — INFO (nested inside `EncMbLoop`, part of the | ||
| 89 | - /// per-MB glue being decomposed). | ||
| 90 | - EncMvPred = 27, | ||
| 91 | - /// CAVLC entropy EMIT for a planned macroblock (`emit_inter_cavlc` and the | ||
| 92 | - /// intra equivalent): mb_type, ref_idx, mvd, cbp, mb_qp_delta and every | ||
| 93 | - /// residual block. This sits OUTSIDE `plan_inter_mb`, so before it was named | ||
| 94 | - /// the whole encoder-side entropy coder was landing in `mgmt/other`. | ||
| 95 | - EncEmit = 28, | ||
| 96 | - /// Per-MB boundary-strength derivation done INSIDE the encode loop — INFO | ||
| 97 | - /// (nested in `EncMbLoop`). Named so the work moved out of deblocking can be | ||
| 98 | - /// priced at its new location rather than inferred from stage deltas. | ||
| 99 | - EncBs = 29, | ||
| 100 | - /// Adaptive-quantization per-MB QP map (`aq_qp_map`) — a full-frame variance | ||
| 101 | - /// pass that runs every frame because AQ is on by default. INFO (nested in | ||
| 102 | - /// `EncPrep`). | ||
| 103 | - EncAq = 30, | ||
| 104 | - /// Sub-pel prediction served from the cached half-pel planes (`hpel_block`) — | ||
| 105 | - /// INFO (nested in `EncMe`). Named because the plane cache MOVED the sub-pel | ||
| 106 | - /// motion-search work out of `inter-mc`, and unnamed work is invisible work. | ||
| 107 | - MeHpel = 31, | ||
| 108 | - /// The motion search's SATD/SAD cost metric itself — INFO (nested in `EncMe`). | ||
| 109 | - MeCost = 32, | ||
| 110 | - /// Building the cached half-pel planes for one reference picture — INFO. | ||
| 111 | - MeHpelBuild = 33, | ||
| 112 | - /// ME: coarse-to-fine full-pel diamond — INFO (nested in `EncMe`). | ||
| 113 | - MeDiamond = 34, | ||
| 114 | - /// ME: sub-pel (half + quarter) refinement rings — INFO (nested in `EncMe`). | ||
| 115 | - MeSubpel = 35, | ||
| 116 | - /// ME: the stalled-diamond wide rescue grid — INFO (nested in `EncMe`). | ||
| 117 | - MeRescue = 36, | ||
| 118 | - /// Wraps the whole `decode()`/`encode()` call — the denominator. | ||
| 119 | - Total = 37, | ||
| 120 | - // --- H-32: decomposition of the decoder's per-MB residue (INFO, nested; | ||
| 121 | - // indexes past `Total` are excluded from dump()'s residue sum) --- | ||
| 122 | - /// CABAC P-inter MB branch, whole body (parse + MC + recon nested inside). | ||
| 123 | - DecMbP = 38, | ||
| 124 | - /// CABAC B MB branch, whole body. | ||
| 125 | - DecMbB = 39, | ||
| 126 | - /// CABAC intra path (mode parse + residual + recon), whole body. | ||
| 127 | - DecMbI = 40, | ||
| 128 | - /// B-direct derivation + MC (`decode_b_direct`) — INFO (nested in DecMbB). | ||
| 129 | - DecBDirect = 41, | ||
| 130 | - /// Bi-/uni-pred region MC + blend (`b_mc`) — INFO (nested in DecMbB). | ||
| 131 | - DecBMc = 42, | ||
| 132 | - /// Per-picture + per-slice setup: FrameDecoder grids, slice neighbour vecs. | ||
| 133 | - DecSetup = 43, | ||
| 134 | - /// B-direct DERIVATION only (neighbours, ref pick, colZero gather) — INFO. | ||
| 135 | - DecBDeriv = 44, | ||
| 136 | - /// B motion-grid commit (`b_set_motion`) — INFO (nested in DecMbB). | ||
| 137 | - DecBSet = 45, | ||
| 138 | - // --- H-38: decomposition of `b_mc` (INFO, nested in DecBMc) --- | ||
| 139 | - /// Implicit-weight derivation (POC math + the integer divide). | ||
| 140 | - DecBWeights = 46, | ||
| 141 | - /// Luma MC calls inside `b_mc`. | ||
| 142 | - DecBLuma = 47, | ||
| 143 | - /// Chroma MC calls inside `b_mc`. | ||
| 144 | - DecBChroma = 48, | ||
| 145 | - /// The bi-pred blend / uni-pred row copies out of the staging buffers. | ||
| 146 | - DecBBlend = 49, | ||
| 147 | - // --- Entropy-stage decomposition (INFO, nested inside `Entropy`) — added for | ||
| 148 | - // the CABAC/CAVLC diagnosis once sampled profiling made sub-scopes affordable. | ||
| 149 | - /// CABAC residual: the coded_block_flag bin + its neighbour-context read. | ||
| 150 | - EntCbf = 50, | ||
| 151 | - /// CABAC residual: the significance-map loop (sig + last bins). | ||
| 152 | - EntSig = 51, | ||
| 153 | - /// CABAC residual: the level loop (one/abs/UEG0 bins + sign bypass). | ||
| 154 | - EntLvl = 52, | ||
| 155 | - /// CAVLC residual: the coeff_token VLC read. | ||
| 156 | - CavTok = 53, | ||
| 157 | - /// CAVLC residual: trailing-one signs + level prefix/suffix reads. | ||
| 158 | - CavLvl = 54, | ||
| 159 | - /// CAVLC residual: total_zeros + run_before reads and the scatter to scan order. | ||
| 160 | - CavRun = 55, | ||
| 161 | - /// Per-MB neighbour/state cache shuffling in the CABAC MB branches: the | ||
| 162 | - /// mvd/ref 30-entry cache build, the 48-entry nzc cache build, and the mb_nzc | ||
| 163 | - /// write-back — the state plumbing BETWEEN parse steps (INFO, nested). | ||
| 164 | - DecStateCache = 56, | ||
| 165 | - /// `add_inter_residual` whole body (INFO, nested): contains Dequant / | ||
| 166 | - /// Reconstruct / Scatter leaves; body minus leaves = the residual-add glue | ||
| 167 | - /// (nnz re-derivation scans, un-scan, pred gathers, loop skeleton). | ||
| 168 | - DecResidAdd = 57, | ||
| 169 | - /// The P-body MC staging block (INFO, nested): contains InterMc + PredBuf | ||
| 170 | - /// leaves; block minus leaves = rect-ladder + staging-buffer cost. | ||
| 171 | - DecMcStage = 58, | ||
| 172 | - /// `pack_frame_into` — the per-frame MbPack build (INFO, nested in Deblock). | ||
| 173 | - DebPack = 59, | ||
| 174 | - /// Per-MB bS derivation inside `filter_frame`: kind gate, predicates, | ||
| 175 | - /// packed/tile/blind derivation, bs materialization (INFO, nested in Deblock). | ||
| 176 | - DebDerive = 60, | ||
| 177 | - /// Annex-B start-code scan (`split_annex_b`) — a full byte-wise pass over the | ||
| 178 | - /// WHOLE stream plus two Vec allocations. Entered ~once per access unit, so it | ||
| 179 | - /// is in the low-call-count regime the profiler measures reliably. | ||
| 180 | - DecNalSplit = 61, | ||
| 181 | - /// RBSP emulation-prevention removal (`emulation_unprevent`) — a second full | ||
| 182 | - /// byte-wise pass, one bounds-checked `push` per byte, into a fresh Vec per NAL. | ||
| 183 | - DecRbsp = 62, | ||
| 184 | - /// The 11 per-slice `vec![...; total_mbs]` neighbour-state allocations at the top | ||
| 185 | - /// of `decode_slice_cabac_inner` (mvd grids alone are 64 B/MB each, twice). | ||
| 186 | - DecSliceAlloc = 63, | ||
| 187 | - /// The whole CABAC macroblock loop — INFO (nested; contains dec-mb-P/B/I). | ||
| 188 | - /// `DecMbLoop - sum(dec-mb-*)` is the per-MB loop GLUE outside the MB bodies. | ||
| 189 | - DecMbLoop = 64, | ||
| 190 | - /// `row_hook` — on every MB after decode. Mid-row calls early-out (no scope) | ||
| 191 | - /// unless `RS_H264_ROWHOOK_EAGER=1`. On row crossings: bS derive + filter / | ||
| 192 | - /// EDC row handoff. INFO (nested in DecMbLoop; contains deb:derive + deblock). | ||
| 193 | - /// | ||
| 194 | - /// Call COUNT with the early-out ≈ MB rows/picture (exact). Quote ms only with | ||
| 195 | - /// that count; per-MB eager scoping inflated both calls and self-tax. | ||
| 196 | - DecRowHook = 65, | ||
| 197 | -} | ||
| 198 | - | ||
| 199 | -/// Number of buckets. | ||
| 200 | -pub const N: usize = 66; | ||
| 201 | - | ||
| 202 | -#[cfg(feature = "profile")] | ||
| 203 | -mod imp { | ||
| 204 | - use super::{Stage, N}; | ||
| 205 | - use std::sync::atomic::{AtomicU64, Ordering}; | ||
| 206 | - use std::sync::Mutex; | ||
| 207 | - use std::time::Instant; | ||
| 208 | - | ||
| 209 | - /// Index of the first non-`Total` stage — the residue sum runs `0..SUB`. | ||
| 210 | - const SUB: usize = Stage::Total as usize; | ||
| 211 | - | ||
| 212 | - /// A cheap monotonic tick. On x86_64 this is `rdtsc` (~5-10 ns, ~3-5× cheaper | ||
| 213 | - /// than `Instant::now()` = QueryPerformanceCounter ~20-30 ns on Windows), which | ||
| 214 | - /// is what dominated the profiler's own overhead (~1M scope entries × 2 calls). | ||
| 215 | - /// Buckets accumulate *ticks*; `dump()` converts to ns via a run-length TSC | ||
| 216 | - /// calibration (invariant TSC → ticks are wall-time-proportional). Elsewhere we | ||
| 217 | - /// fall back to `Instant` nanos so the profiler still builds cross-arch. | ||
| 218 | - #[cfg(target_arch = "x86_64")] | ||
| 219 | - #[inline(always)] | ||
| 220 | - fn ticks() -> u64 { | ||
| 221 | - // SAFETY: `_rdtsc` is a pure timestamp read with no memory effects; it is | ||
| 222 | - // `unsafe` only because it is a target intrinsic. Reordering is immaterial to | ||
| 223 | - // coarse scope timing. Compiled only under `feature = "profile"` (dev tool). | ||
| 224 | - unsafe { core::arch::x86_64::_rdtsc() } | ||
| 225 | - } | ||
| 226 | - #[cfg(not(target_arch = "x86_64"))] | ||
| 227 | - #[inline(always)] | ||
| 228 | - fn ticks() -> u64 { | ||
| 229 | - use std::sync::OnceLock; | ||
| 230 | - static EPOCH: OnceLock<Instant> = OnceLock::new(); | ||
| 231 | - EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64 | ||
| 232 | - } | ||
| 233 | - | ||
| 234 | - /// (wall-clock, tick-count) sampled at `reset()` — the calibration anchor read at | ||
| 235 | - /// `dump()` to recover ns-per-tick. Touched twice per run, so its `Mutex` cost is | ||
| 236 | - /// irrelevant next to the per-scope path. | ||
| 237 | - static ANCHOR: Mutex<Option<(Instant, u64)>> = Mutex::new(None); | ||
| 238 | - | ||
| 239 | - const NAMES: [&str; N] = [ | ||
| 240 | - "entropy/cavlc", | ||
| 241 | - "intra-pred", | ||
| 242 | - "inter-mc", | ||
| 243 | - "reconstruct", | ||
| 244 | - "deblock", | ||
| 245 | - "dequant", | ||
| 246 | - "scatter(store)", | ||
| 247 | - "pred-buf copy", | ||
| 248 | - "mv+grid", | ||
| 249 | - "neighbors", | ||
| 250 | - "skip-recon", | ||
| 251 | - "finalize", | ||
| 252 | - "syntax-parse", | ||
| 253 | - "dpb-clone", | ||
| 254 | - "enc-source-copy", | ||
| 255 | - "enc-skip-check", | ||
| 256 | - "enc-me(best_part)", | ||
| 257 | - "enc-intra-cost", | ||
| 258 | - "enc-inter-code", | ||
| 259 | - "enc-intra-code", | ||
| 260 | - "enc-finalize", | ||
| 261 | - "enc-T/Q(nested)", | ||
| 262 | - "enc-cavlc-write(nested)", | ||
| 263 | - "enc-skip-freecheck(nested)", | ||
| 264 | - "enc-prep(nested)", | ||
| 265 | - "enc-nal-assembly", | ||
| 266 | - "enc-mb-loop(nested)", | ||
| 267 | - "enc-mvpred(nested)", | ||
| 268 | - "enc-cavlc-emit", | ||
| 269 | - "enc-bs-derive(nested)", | ||
| 270 | - "enc-aq-map(nested)", | ||
| 271 | - "me-hpel-read(nested)", | ||
| 272 | - "me-cost/satd(nested)", | ||
| 273 | - "me-hpel-BUILD(nested)", | ||
| 274 | - "me-diamond(nested)", | ||
| 275 | - "me-subpel(nested)", | ||
| 276 | - "me-rescue(nested)", | ||
| 277 | - "TOTAL", | ||
| 278 | - "dec-mb-P(nested)", | ||
| 279 | - "dec-mb-B(nested)", | ||
| 280 | - "dec-mb-I(nested)", | ||
| 281 | - "b-direct(nested)", | ||
| 282 | - "b-mc(nested)", | ||
| 283 | - "dec-setup", | ||
| 284 | - "b-deriv(nested)", | ||
| 285 | - "b-setmotion(nested)", | ||
| 286 | - "b:weights(nested)", | ||
| 287 | - "b:luma-mc(nested)", | ||
| 288 | - "b:chroma-mc(nested)", | ||
| 289 | - "b:blend(nested)", | ||
| 290 | - "ent:cbf(nested)", | ||
| 291 | - "ent:sigmap(nested)", | ||
| 292 | - "ent:levels(nested)", | ||
| 293 | - "cav:token(nested)", | ||
| 294 | - "cav:levels(nested)", | ||
| 295 | - "cav:runs(nested)", | ||
| 296 | - "state-cache(nested)", | ||
| 297 | - "resid-add(nested)", | ||
| 298 | - "mc-stage(nested)", | ||
| 299 | - "deb:pack(nested)", | ||
| 300 | - "deb:derive(nested)", | ||
| 301 | - "dec-nal-split", | ||
| 302 | - "dec-rbsp-unescape", | ||
| 303 | - "dec-slice-alloc", | ||
| 304 | - "dec-mb-loop(nested)", | ||
| 305 | - "dec-row-hook(nested)", | ||
| 306 | - ]; | ||
| 307 | - | ||
| 308 | - static NS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; | ||
| 309 | - static CALLS: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; | ||
| 310 | - | ||
| 311 | - /// SAMPLED PROFILING — the fix for the profiler's own tax. | ||
| 312 | - /// | ||
| 313 | - /// The scope guard is an rdtsc pair. At ~20M per-macroblock scopes that tax was | ||
| 314 | - /// measured at **1.32-1.43x of whole decode**, which is why every per-MB stage | ||
| 315 | - /// share in this codec has been untrustworthy and why the campaign fell back to | ||
| 316 | - /// ablation (which can only price stages someone already put a knob on). | ||
| 317 | - /// | ||
| 318 | - /// Fix: only TIME one call in `RS_H264_PROF_SAMPLE` (default 1 = time every call, | ||
| 319 | - /// preserving the old behaviour exactly). Sampled cycles are scaled back up by the | ||
| 320 | - /// sampling period, so the SHARE each stage reports is unbiased — a stage that | ||
| 321 | - /// takes x% of time is entered proportionally often, so timing 1-in-N calls | ||
| 322 | - /// estimates the same x% with 1/N the tax. Call COUNTS stay exact (counting is a | ||
| 323 | - /// single relaxed add, not an rdtsc pair, so it is not the expensive part). | ||
| 324 | - /// | ||
| 325 | - /// This is the standard statistical-profiling trade: precision for a smaller | ||
| 326 | - /// probe. At N=64 the tax drops ~64x while a stage above ~1% still lands within a | ||
| 327 | - /// few percent relative over 20M+ entries. | ||
| 328 | - pub struct Guard { | ||
| 329 | - stage: usize, | ||
| 330 | - start: u64, | ||
| 331 | - /// 0 = not timed. Otherwise the weight this sample carries: 1 for an exactly | ||
| 332 | - /// timed call, N for a sampled one. | ||
| 333 | - scale: u64, | ||
| 334 | - } | ||
| 335 | - | ||
| 336 | - /// Calls below this are ALWAYS timed exactly, whatever the sampling period. | ||
| 337 | - /// | ||
| 338 | - /// Two reasons. (a) The tax is proportional to call count, so a stage entered a | ||
| 339 | - /// few thousand times costs nothing to time in full — sampling it buys no speed. | ||
| 340 | - /// (b) Sampling a low-count stage is statistically worthless: `Total` is entered | ||
| 341 | - /// once per FRAME (60 calls on a 60-frame clip), so at N=64 it would estimate the | ||
| 342 | - /// entire denominator from ONE sample. Since every share is a ratio to `Total`, | ||
| 343 | - /// that one bad estimate would skew every share on the table — which is exactly | ||
| 344 | - /// what the first N=64 run showed (every stage share rose together). | ||
| 345 | - const EXACT_PREFIX: u64 = 8192; | ||
| 346 | - | ||
| 347 | - /// Sampling period. 1 = time everything (previous behaviour, and the default so | ||
| 348 | - /// no existing measurement silently changes meaning). | ||
| 349 | - pub(crate) static SAMPLE_N: std::sync::atomic::AtomicU64 = | ||
| 350 | - std::sync::atomic::AtomicU64::new(0); | ||
| 351 | - | ||
| 352 | - /// Sampling period, ROUNDED UP TO A POWER OF TWO so the selection test is a mask | ||
| 353 | - /// (1 cycle) and not a `u64` division (~20-40 cycles — as expensive as the rdtsc | ||
| 354 | - /// it is meant to avoid, which would make the whole scheme pointless). | ||
| 355 | - #[inline(always)] | ||
| 356 | - fn sample_period() -> u64 { | ||
| 357 | - match SAMPLE_N.load(Ordering::Relaxed) { | ||
| 358 | - 0 => { | ||
| 359 | - let n = std::env::var("RS_H264_PROF_SAMPLE") | ||
| 360 | - .ok() | ||
| 361 | - .and_then(|v| v.parse::<u64>().ok()) | ||
| 362 | - .filter(|v| *v >= 1) | ||
| 363 | - .unwrap_or(1) | ||
| 364 | - .next_power_of_two(); | ||
| 365 | - SAMPLE_N.store(n, Ordering::Relaxed); | ||
| 366 | - n | ||
| 367 | - } | ||
| 368 | - n => n, | ||
| 369 | - } | ||
| 370 | - } | ||
| 371 | - | ||
| 372 | - impl Drop for Guard { | ||
| 373 | - #[inline] | ||
| 374 | - fn drop(&mut self) { | ||
| 375 | - if self.scale != 0 { | ||
| 376 | - let d = ticks().wrapping_sub(self.start); | ||
| 377 | - // Weight by this sample's scale so the bucket estimates TOTAL cycles. | ||
| 378 | - // The first EXACT_PREFIX calls carry weight 1 (they were all timed); | ||
| 379 | - // the tail carries weight N. Sum = exact prefix + unbiased estimate of | ||
| 380 | - // the remainder, so a short-running stage degrades to "fully timed" | ||
| 381 | - // rather than to "one sample times N". | ||
| 382 | - NS[self.stage].fetch_add(d.wrapping_mul(self.scale), Ordering::Relaxed); | ||
| 383 | - } | ||
| 384 | - CALLS[self.stage].fetch_add(1, Ordering::Relaxed); | ||
| 385 | - } | ||
| 386 | - } | ||
| 387 | - | ||
| 388 | - #[inline] | ||
| 389 | - /// Descent E: the raw tick source, for census modules that accumulate cycles into | ||
| 390 | - /// their own buckets rather than a `Stage`. | ||
| 391 | - #[inline(always)] | ||
| 392 | - pub fn tick() -> u64 { | ||
| 393 | - ticks() | ||
| 394 | - } | ||
| 395 | - | ||
| 396 | - pub fn scope(s: Stage) -> Guard { | ||
| 397 | - let n = sample_period(); | ||
| 398 | - let c = CALLS[s as usize].load(Ordering::Relaxed); | ||
| 399 | - // Pick 1-in-N by HASHING the call index, not by striding it. | ||
| 400 | - // | ||
| 401 | - // A plain `c % N` stride aliases: decode work is intensely periodic (blocks | ||
| 402 | - // per macroblock, macroblocks per row), so a power-of-two stride can lock onto | ||
| 403 | - // the same position in that pattern every time and systematically sample only | ||
| 404 | - // the cheap — or only the expensive — calls. Multiplying by the 64-bit golden | ||
| 405 | - // ratio and taking high bits decorrelates the selection from any workload | ||
| 406 | - // period, giving an unbiased 1-in-N at ~4 cycles (mul, shift, and, test). | ||
| 407 | - const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15; | ||
| 408 | - let scale = if n == 1 || c < EXACT_PREFIX { | ||
| 409 | - 1 | ||
| 410 | - } else if (c.wrapping_mul(GOLDEN) >> 32) & (n - 1) == 0 { | ||
| 411 | - n | ||
| 412 | - } else { | ||
| 413 | - 0 | ||
| 414 | - }; | ||
| 415 | - Guard { | ||
| 416 | - stage: s as usize, | ||
| 417 | - start: if scale != 0 { ticks() } else { 0 }, | ||
| 418 | - scale, | ||
| 419 | - } | ||
| 420 | - } | ||
| 421 | - | ||
| 422 | - /// Zero all buckets and sample the calibration anchor — call before a clean run. | ||
| 423 | - pub fn reset() { | ||
| 424 | - for a in NS.iter().chain(CALLS.iter()) { | ||
| 425 | - a.store(0, Ordering::Relaxed); | ||
| 426 | - } | ||
| 427 | - *ANCHOR.lock().unwrap() = Some((Instant::now(), ticks())); | ||
| 428 | - } | ||
| 429 | - | ||
| 430 | - /// Human-readable name for stage index `i` (`SUB` = the `TOTAL` row). | ||
| 431 | - pub fn name(i: usize) -> &'static str { | ||
| 432 | - NAMES.get(i).copied().unwrap_or("?") | ||
| 433 | - } | ||
| 434 | - | ||
| 435 | - /// One calibrated reading: `(ms, calls)` per stage index `0..N` (index `SUB` is | ||
| 436 | - /// `Total`). Buckets hold `rdtsc` cycles; ns/tick is recovered from the reset→now | ||
| 437 | - /// anchor (elapsed wall / elapsed cycles — invariant TSC, so cycles are wall- | ||
| 438 | - /// proportional). Lets a driver run many passes and take a per-stage median. | ||
| 439 | - pub fn snapshot() -> [(f64, u64); N] { | ||
| 440 | - let load = |i: usize| NS[i].load(Ordering::Relaxed); | ||
| 441 | - let ns_per_tick = ANCHOR | ||
| 442 | - .lock() | ||
| 443 | - .unwrap() | ||
| 444 | - .map(|(t0, c0)| { | ||
| 445 | - let wall = t0.elapsed().as_nanos() as f64; | ||
| 446 | - let cyc = ticks().wrapping_sub(c0) as f64; | ||
| 447 | - if cyc > 0.0 { | ||
| 448 | - wall / cyc | ||
| 449 | - } else { | ||
| 450 | - 1.0 | ||
| 451 | - } | ||
| 452 | - }) | ||
| 453 | - .unwrap_or(1.0); | ||
| 454 | - let mut out = [(0.0f64, 0u64); N]; | ||
| 455 | - for (i, o) in out.iter_mut().enumerate() { | ||
| 456 | - *o = (load(i) as f64 * ns_per_tick / 1e6, CALLS[i].load(Ordering::Relaxed)); | ||
| 457 | - } | ||
| 458 | - out | ||
| 459 | - } | ||
| 460 | - | ||
| 461 | - /// Print the per-stage breakdown (does not reset). | ||
| 462 | - pub fn dump() { | ||
| 463 | - let s = snapshot(); | ||
| 464 | - let total = s[SUB].0.max(1e-9); | ||
| 465 | - let sub_sum: f64 = (0..SUB).map(|i| s[i].0).sum(); | ||
| 466 | - let mgmt = (total - sub_sum).max(0.0); | ||
| 467 | - let pct = |ms: f64| 100.0 * ms / total; | ||
| 468 | - | ||
| 469 | - eprintln!("\n--- decode stage profile (decode() wall = {total:.1} ms) ---"); | ||
| 470 | - for i in 0..SUB { | ||
| 471 | - eprintln!( | ||
| 472 | - " {:<15} {:>8.1} ms {:>5.1}% ({} calls)", | ||
| 473 | - NAMES[i], s[i].0, pct(s[i].0), s[i].1, | ||
| 474 | - ); | ||
| 475 | - } | ||
| 476 | - eprintln!( | ||
| 477 | - " {:<15} {:>8.1} ms {:>5.1}% <- the OTHER bucket: unnamed decode glue", | ||
| 478 | - "mgmt/other", mgmt, pct(mgmt), | ||
| 479 | - ); | ||
| 480 | - eprintln!(" {:<15} {:>8.1} ms 100.0%", NAMES[SUB], total); | ||
| 481 | - // Attribute OTHER using INFO scopes (nested; shares can overlap parents). | ||
| 482 | - // These are the deployment-signal names for the 1T residue campaign. | ||
| 483 | - let info = |st: Stage| s[st as usize]; | ||
| 484 | - let loop_ms = info(Stage::DecMbLoop).0; | ||
| 485 | - let mb_bodies = info(Stage::DecMbP).0 + info(Stage::DecMbB).0 + info(Stage::DecMbI).0; | ||
| 486 | - let loop_glue = (loop_ms - mb_bodies).max(0.0); | ||
| 487 | - eprintln!("--- OTHER attribution (INFO scopes; parents include children) ---"); | ||
| 488 | - eprintln!( | ||
| 489 | - " dec-mb-loop glue≈ {:>8.1} ms {:>5.1}% (loop {:.1} − P/B/I bodies {:.1})", | ||
| 490 | - loop_glue, | ||
| 491 | - pct(loop_glue), | ||
| 492 | - loop_ms, | ||
| 493 | - mb_bodies | ||
| 494 | - ); | ||
| 495 | - let row_hook = info(Stage::DecRowHook).0; | ||
| 496 | - let deblock = s[Stage::Deblock as usize].0; | ||
| 497 | - let syntax = s[Stage::Syntax as usize].0; | ||
| 498 | - let inter = s[Stage::InterMc as usize].0; | ||
| 499 | - let entropy = s[Stage::Entropy as usize].0; | ||
| 500 | - // Residue naming: top-level OTHER is work NOT wrapped by stages 0..Total. | ||
| 501 | - // INFO scopes after Total do not shrink OTHER — they NAME pieces of it. | ||
| 502 | - // Reconcile the big pieces that live in OTHER (nested times overlap). | ||
| 503 | - eprintln!("--- OTHER named (why ~45% is not a mystery kernel) ---"); | ||
| 504 | - eprintln!( | ||
| 505 | - " top-level leaves already subtract: entropy {:.1}% inter-mc {:.1}% deblock {:.1}% syntax {:.1}%", | ||
| 506 | - pct(entropy), | ||
| 507 | - pct(inter), | ||
| 508 | - pct(deblock), | ||
| 509 | - pct(syntax), | ||
| 510 | - ); | ||
| 511 | - eprintln!( | ||
| 512 | - " in-OTHER orchestration (INFO; overlaps leaves): row-hook {:.1}% loop-glue {:.1}% (glue−hook≈{:.1}%)", | ||
| 513 | - pct(row_hook), | ||
| 514 | - pct(loop_glue), | ||
| 515 | - pct((loop_glue - row_hook).max(0.0)), | ||
| 516 | - ); | ||
| 517 | - eprintln!( | ||
| 518 | - " in-OTHER B glue (INFO nested): b-mc {:.1}% b-direct {:.1}% blend {:.1}% setmot {:.1}% deriv {:.1}%", | ||
| 519 | - pct(info(Stage::DecBMc).0), | ||
| 520 | - pct(info(Stage::DecBDirect).0), | ||
| 521 | - pct(info(Stage::DecBBlend).0), | ||
| 522 | - pct(info(Stage::DecBSet).0), | ||
| 523 | - pct(info(Stage::DecBDeriv).0), | ||
| 524 | - ); | ||
| 525 | - eprintln!( | ||
| 526 | - " in-OTHER resid/mc-stage (INFO): resid-add {:.1}% mc-stage {:.1}% — remainder ≈ timer tax + tiny parse glue", | ||
| 527 | - pct(info(Stage::DecResidAdd).0), | ||
| 528 | - pct(info(Stage::DecMcStage).0), | ||
| 529 | - ); | ||
| 530 | - for st in [ | ||
| 531 | - Stage::DecMbB, | ||
| 532 | - Stage::DecMbP, | ||
| 533 | - Stage::DecMbI, | ||
| 534 | - Stage::DecBDirect, | ||
| 535 | - Stage::DecBMc, | ||
| 536 | - Stage::DecRowHook, | ||
| 537 | - Stage::DecResidAdd, | ||
| 538 | - Stage::DecMcStage, | ||
| 539 | - Stage::DecSetup, | ||
| 540 | - Stage::DecSliceAlloc, | ||
| 541 | - Stage::DecNalSplit, | ||
| 542 | - Stage::DecRbsp, | ||
| 543 | - ] { | ||
| 544 | - let (ms, calls) = info(st); | ||
| 545 | - if ms > 0.05 || calls > 0 { | ||
| 546 | - eprintln!( | ||
| 547 | - " {:<18} {:>8.1} ms {:>5.1}% ({} calls)", | ||
| 548 | - NAMES[st as usize], | ||
| 549 | - ms, | ||
| 550 | - pct(ms), | ||
| 551 | - calls | ||
| 552 | - ); | ||
| 553 | - } | ||
| 554 | - } | ||
| 555 | - } | ||
| 556 | -} | ||
| 557 | - | ||
| 558 | -#[cfg(not(feature = "profile"))] | ||
| 559 | -mod imp { | ||
| 560 | - use super::{Stage, N}; | ||
| 561 | - | ||
| 562 | - /// No-op guard (ZST) — elided in release. | ||
| 563 | - pub struct Guard; | ||
| 564 | - | ||
| 565 | - #[inline(always)] | ||
| 566 | - pub fn scope(_s: Stage) -> Guard { | ||
| 567 | - Guard | ||
| 568 | - } | ||
| 569 | - #[inline(always)] | ||
| 570 | - pub fn reset() {} | ||
| 571 | - #[inline(always)] | ||
| 572 | - pub fn dump() {} | ||
| 573 | - #[inline(always)] | ||
| 574 | - pub fn snapshot() -> [(f64, u64); N] { | ||
| 575 | - [(0.0, 0); N] | ||
| 576 | - } | ||
| 577 | - #[inline(always)] | ||
| 578 | - pub fn name(_i: usize) -> &'static str { | ||
| 579 | - "" | ||
| 580 | - } | ||
| 581 | -} | ||
| 582 | - | ||
| 583 | -pub use imp::{dump, name, reset, scope, snapshot, Guard}; | ||
| 584 | -#[cfg(feature = "profile")] | ||
| 585 | -pub use imp::tick; | ||
vendor/rusty_h264-common/src/transform.rsdeleted+0 -1561
| @@ -1,1561 +0,0 @@ | |||
| 1 | -//! H.264 4×4 residual transform and quantization (spec §8.5 / §8.6). | ||
| 2 | -//! | ||
| 3 | -//! H.264 uses a small integer approximation of the DCT — a 4×4 "core" transform | ||
| 4 | -//! whose scaling is folded into the quantizer, so it is exactly invertible in | ||
| 5 | -//! integer arithmetic. This module implements the forward path (encoder: | ||
| 6 | -//! residual → coefficients → quantized levels) and the inverse path (decoder | ||
| 7 | -//! and encoder-reconstruction: levels → coefficients → residual). | ||
| 8 | -//! | ||
| 9 | -//! Correctness here is non-negotiable: the levels we emit are dequantized by | ||
| 10 | -//! every conforming decoder using the exact spec tables below, so the forward | ||
| 11 | -//! quantizer must be the faithful inverse of that process. | ||
| 12 | - | ||
| 13 | -/// `normAdjust4x4` (spec Table — the dequant scaling V), indexed by `[QP % 6]` | ||
| 14 | -/// then by position group (see [`pos_group`]). | ||
| 15 | -const NORM_ADJUST: [[i32; 3]; 6] = [ | ||
| 16 | - [10, 16, 13], | ||
| 17 | - [11, 18, 14], | ||
| 18 | - [13, 20, 16], | ||
| 19 | - [14, 23, 18], | ||
| 20 | - [16, 25, 20], | ||
| 21 | - [18, 29, 23], | ||
| 22 | -]; | ||
| 23 | - | ||
| 24 | -/// Forward quantization multipliers `MF`, indexed by `[QP % 6]` then position | ||
| 25 | -/// group. Paired with [`NORM_ADJUST`] so reconstruction ≈ source. | ||
| 26 | -const QUANT_MF: [[i32; 3]; 6] = [ | ||
| 27 | - [13107, 5243, 8066], | ||
| 28 | - [11916, 4660, 7490], | ||
| 29 | - [10082, 4194, 6554], | ||
| 30 | - [9362, 3647, 5825], | ||
| 31 | - [8192, 3355, 5243], | ||
| 32 | - [7282, 2893, 4559], | ||
| 33 | -]; | ||
| 34 | - | ||
| 35 | -/// Position group within a 4×4 block: | ||
| 36 | -/// - 0: both indices even — the (0,0),(0,2),(2,0),(2,2) positions, | ||
| 37 | -/// - 1: both indices odd — (1,1),(1,3),(3,1),(3,3), | ||
| 38 | -/// - 2: everything else. | ||
| 39 | -#[inline] | ||
| 40 | -fn pos_group(i: usize, j: usize) -> usize { | ||
| 41 | - match (i % 2, j % 2) { | ||
| 42 | - (0, 0) => 0, | ||
| 43 | - (1, 1) => 1, | ||
| 44 | - _ => 2, | ||
| 45 | - } | ||
| 46 | -} | ||
| 47 | - | ||
| 48 | -/// `pos_group` evaluated for all 16 raster positions — lets the hot quant/dequant | ||
| 49 | -/// loops index a flat per-position table instead of recomputing the `(i%2, j%2)` | ||
| 50 | -/// match per coefficient (openh264 stores per-position MF/dequant tables). | ||
| 51 | -const POS_GROUP_FLAT: [usize; 16] = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1]; | ||
| 52 | - | ||
| 53 | - | ||
| 54 | -/// `16 · NORM_ADJUST` pre-expanded to a flat 16-entry LevelScale table per `qp % 6`. | ||
| 55 | -const fn flatten_level_scale() -> [[i32; 16]; 6] { | ||
| 56 | - let mut out = [[0i32; 16]; 6]; | ||
| 57 | - let mut m = 0; | ||
| 58 | - while m < 6 { | ||
| 59 | - let mut idx = 0; | ||
| 60 | - while idx < 16 { | ||
| 61 | - out[m][idx] = 16 * NORM_ADJUST[m][POS_GROUP_FLAT[idx]]; | ||
| 62 | - idx += 1; | ||
| 63 | - } | ||
| 64 | - m += 1; | ||
| 65 | - } | ||
| 66 | - out | ||
| 67 | -} | ||
| 68 | -const LEVEL_SCALE_FLAT: [[i32; 16]; 6] = flatten_level_scale(); | ||
| 69 | - | ||
| 70 | -/// One-dimensional forward core transform butterfly (rows of `Cf`). | ||
| 71 | -#[inline] | ||
| 72 | -fn fwd_1d(x0: i32, x1: i32, x2: i32, x3: i32) -> (i32, i32, i32, i32) { | ||
| 73 | - let t0 = x0 + x3; | ||
| 74 | - let t1 = x1 + x2; | ||
| 75 | - let t2 = x1 - x2; | ||
| 76 | - let t3 = x0 - x3; | ||
| 77 | - (t0 + t1, 2 * t3 + t2, t0 - t1, t3 - 2 * t2) | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -/// One-dimensional inverse core transform butterfly (rows of `Ci`). | ||
| 81 | -#[inline] | ||
| 82 | -fn inv_1d(d0: i32, d1: i32, d2: i32, d3: i32) -> (i32, i32, i32, i32) { | ||
| 83 | - let e0 = d0 + d2; | ||
| 84 | - let e1 = d0 - d2; | ||
| 85 | - let e2 = (d1 >> 1) - d3; | ||
| 86 | - let e3 = d1 + (d3 >> 1); | ||
| 87 | - (e0 + e3, e1 + e2, e1 - e2, e0 - e3) | ||
| 88 | -} | ||
| 89 | - | ||
| 90 | -/// Forward core transform `W = Cf · X · Cfᵀ` over a row-major 4×4 block. | ||
| 91 | -/// The output coefficients are pre-quantization (scaling lives in the quantizer). | ||
| 92 | -pub fn forward_core(block: &[i32; 16]) -> [i32; 16] { | ||
| 93 | - let mut m = *block; | ||
| 94 | - // Rows. | ||
| 95 | - for r in 0..4 { | ||
| 96 | - let (a, b, c, d) = fwd_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]); | ||
| 97 | - m[r * 4] = a; | ||
| 98 | - m[r * 4 + 1] = b; | ||
| 99 | - m[r * 4 + 2] = c; | ||
| 100 | - m[r * 4 + 3] = d; | ||
| 101 | - } | ||
| 102 | - // Columns. | ||
| 103 | - for c in 0..4 { | ||
| 104 | - let (a, b, cc, d) = fwd_1d(m[c], m[4 + c], m[8 + c], m[12 + c]); | ||
| 105 | - m[c] = a; | ||
| 106 | - m[4 + c] = b; | ||
| 107 | - m[8 + c] = cc; | ||
| 108 | - m[12 + c] = d; | ||
| 109 | - } | ||
| 110 | - m | ||
| 111 | -} | ||
| 112 | - | ||
| 113 | -/// Quantizes forward-transform coefficients to levels. `intra` selects the | ||
| 114 | -/// rounding dead-zone offset (1/3 for intra, 1/6 for inter). | ||
| 115 | -/// Scalar quantization. `dz_div` sets the rounding dead-zone: the offset added | ||
| 116 | -/// before the right shift is `2^qbits / dz_div`, so a *smaller* `dz_div` rounds | ||
| 117 | -/// up more (higher quality, more bits). Typical values: 6 for inter, 3 for an | ||
| 118 | -/// I-frame that serves as a reference, 2 for all-intra (where the larger offset | ||
| 119 | -/// is a net rate-distortion win — better-quantized blocks predict their | ||
| 120 | -/// neighbors better, shrinking downstream residuals). | ||
| 121 | -pub fn quantize(coeffs: &[i32; 16], qp: u8, dz_div: i64) -> [i32; 16] { | ||
| 122 | - // openh264's quant STRUCTURE (`level = ((|c| + FF)·MF_oh) >> 16`, bit-identical to | ||
| 123 | - // `WelsQuant4x4_sse2`'s pmulhuw high-word) carrying OUR deadzone, not openh264's: | ||
| 124 | - // `FF = round(F / MF)` reproduces our `(|c|·MF + F) >> qbits` (to within a rare ±1), | ||
| 125 | - // so RD is preserved AND the asm kernel becomes a drop-in. (Adopting openh264's own | ||
| 126 | - // FF tables regressed intra −1.5 dB.) `MF_oh[qp] = MF · 2^(16-qbits)`. | ||
| 127 | - let mf_oh = &QUANT_MF_OH[qp as usize]; | ||
| 128 | - let ff = quant_dz_ff(qp, dz_div); | ||
| 129 | - const POS: [usize; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7]; | ||
| 130 | - let mut out = [0i32; 16]; | ||
| 131 | - for idx in 0..16 { | ||
| 132 | - let p = POS[idx]; | ||
| 133 | - let a = coeffs[idx].unsigned_abs() as i32; | ||
| 134 | - let lvl = ((a + ff[p] as i32) * mf_oh[p] as i32) >> 16; | ||
| 135 | - out[idx] = if coeffs[idx] < 0 { -lvl } else { lvl }; | ||
| 136 | - } | ||
| 137 | - out | ||
| 138 | -} | ||
| 139 | - | ||
| 140 | -/// The 8-entry deadzone offset table `FF[pos] = round(F / MF)` reproducing our | ||
| 141 | -/// `(|c|·MF + F) >> qbits` deadzone (`F = 2^qbits / dz_div`) inside openh264's | ||
| 142 | -/// `((|c| + FF)·MF_oh) >> 16` quantizer — so the asm `WelsQuant*4x4` kernels quantize | ||
| 143 | -/// bit-identically to our scalar [`quantize`]. Pair with [`QUANT_MF_OH`]`[qp]` as MF. | ||
| 144 | -pub fn quant_dz_ff(qp: u8, dz_div: i64) -> [i16; 8] { | ||
| 145 | - let m = (qp % 6) as usize; | ||
| 146 | - let qbits = 15 + (qp / 6) as i64; | ||
| 147 | - let f = (1i64 << qbits) / dz_div; | ||
| 148 | - // Position (0:even/even, 1:odd/odd, 2:mixed) group of each of openh264's 8 slots. | ||
| 149 | - const GROUP8: [usize; 8] = [0, 2, 0, 2, 2, 1, 2, 1]; | ||
| 150 | - let mut ff = [0i16; 8]; | ||
| 151 | - for (i, slot) in ff.iter_mut().enumerate() { | ||
| 152 | - let mfg = QUANT_MF[m][GROUP8[i]] as i64; | ||
| 153 | - *slot = ((f + mfg / 2) / mfg) as i16; | ||
| 154 | - } | ||
| 155 | - ff | ||
| 156 | -} | ||
| 157 | - | ||
| 158 | -/// Rate-distortion–optimized ("trellis") quantization of a 4×4 residual's | ||
| 159 | -/// transform coefficients. For each coefficient it chooses between the scalar | ||
| 160 | -/// level and one lower (down to zero) to minimize `J = distortion + λ·rate`, | ||
| 161 | -/// trading a few bits of coefficient coding for small reconstruction error. | ||
| 162 | -/// `lambda` is the mode-decision Lagrangian (pixel-SSD domain). Encoder-only — | ||
| 163 | -/// the output is still a valid set of levels any decoder reconstructs. | ||
| 164 | -/// | ||
| 165 | -/// NOTE: not wired into the encoder by default. Greedy per-coefficient rounding | ||
| 166 | -/// fights the intra-prediction feedback loop (rounding one block down worsens | ||
| 167 | -/// the next block's prediction), so a net win needs a feedback-aware integration | ||
| 168 | -/// — left as future work. Kept here as a verified building block. | ||
| 169 | -pub fn trellis_quant(coeffs: &[i32; 16], qp: u8, intra: bool, lambda: f64) -> [i32; 16] { | ||
| 170 | - let m = (qp % 6) as usize; | ||
| 171 | - let qbits = 15 + (qp / 6) as u32; | ||
| 172 | - let scale = (1u64 << qbits) as f64; | ||
| 173 | - let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 }; | ||
| 174 | - let mut out = [0i32; 16]; | ||
| 175 | - for i in 0..4 { | ||
| 176 | - for j in 0..4 { | ||
| 177 | - let idx = i * 4 + j; | ||
| 178 | - let w = coeffs[idx] as i64; | ||
| 179 | - let mf = QUANT_MF[m][pos_group(i, j)] as i64; | ||
| 180 | - let num = w.abs() * mf; // == ideal_level * 2^qbits | ||
| 181 | - let l_scalar = (num + off) >> qbits; | ||
| 182 | - if l_scalar == 0 { | ||
| 183 | - continue; | ||
| 184 | - } | ||
| 185 | - // Distortion is in level² units; convert λ (pixel-SSD) into that | ||
| 186 | - // domain via the dequant step (step ≈ 2^qbits / mf, pixel ≈ step/8). | ||
| 187 | - let lambda_q = lambda * (mf * mf) as f64 / (scale * scale) * 64.0; | ||
| 188 | - let ideal = num as f64 / scale; | ||
| 189 | - let mut best = l_scalar; | ||
| 190 | - let mut best_j = f64::MAX; | ||
| 191 | - for cand in [l_scalar - 1, l_scalar] { | ||
| 192 | - let d = (ideal - cand as f64).powi(2); | ||
| 193 | - let r = if cand == 0 { | ||
| 194 | - 0.0 | ||
| 195 | - } else { | ||
| 196 | - // ~bits to code |level|: significance + sign + magnitude. | ||
| 197 | - 2.0 + 2.0 * (64 - (cand as u64).leading_zeros()) as f64 | ||
| 198 | - }; | ||
| 199 | - let jj = d + lambda_q * r; | ||
| 200 | - if jj < best_j { | ||
| 201 | - best_j = jj; | ||
| 202 | - best = cand; | ||
| 203 | - } | ||
| 204 | - } | ||
| 205 | - out[idx] = if w < 0 { -best as i32 } else { best as i32 }; | ||
| 206 | - } | ||
| 207 | - } | ||
| 208 | - out | ||
| 209 | -} | ||
| 210 | - | ||
| 211 | -/// Dequantizes levels to scaled coefficients (spec §8.5.12.1, flat scaling | ||
| 212 | -/// list so `LevelScale = 16 · normAdjust`). | ||
| 213 | -/// OPT-IN SWITCH — `RS_H264_DEQUANT_AVX2=1` enables the AVX2 twin, which measured NULL | ||
| 214 | -/// (8/13 favouring scalar, z = 0.83). Both arms live in one binary so the A/B runs under | ||
| 215 | -/// one thermal state; separate builds cannot resolve an effect this size here. | ||
| 216 | -#[cfg(all(target_arch = "x86_64", feature = "asm"))] | ||
| 217 | -#[inline] | ||
| 218 | -fn dequant_avx2_opt_in() -> bool { | ||
| 219 | - use std::sync::atomic::{AtomicU8, Ordering}; | ||
| 220 | - static ON: AtomicU8 = AtomicU8::new(0); | ||
| 221 | - match ON.load(Ordering::Relaxed) { | ||
| 222 | - 1 => true, | ||
| 223 | - 2 => false, | ||
| 224 | - _ => { | ||
| 225 | - let on = std::env::var_os("RS_H264_DEQUANT_AVX2").is_some_and(|v| v != "0"); | ||
| 226 | - ON.store(if on { 1 } else { 2 }, Ordering::Relaxed); | ||
| 227 | - on | ||
| 228 | - } | ||
| 229 | - } | ||
| 230 | -} | ||
| 231 | - | ||
| 232 | -pub fn dequantize(levels: &[i32; 16], qp: u8) -> [i32; 16] { | ||
| 233 | - let _g = crate::prof::scope(crate::prof::Stage::Dequant); | ||
| 234 | - let m = (qp % 6) as usize; | ||
| 235 | - let shift = (qp / 6) as i32; | ||
| 236 | - let ls = &LEVEL_SCALE_FLAT[m]; | ||
| 237 | - let mut out = [0i32; 16]; | ||
| 238 | - // AVX2 twin: 16 scalar `imul` -> 2 `vpmulld`. Bit-identical (exact integer ops in | ||
| 239 | - // the same order), so the scalar body below stays as the oracle AND as the path on | ||
| 240 | - // any non-AVX2 CPU. See `dequant_4x4_avx2` for why auto-vectorization does not | ||
| 241 | - // reach this loop. | ||
| 242 | - // DEFAULT: SCALAR. The AVX2 twin is opt-IN (`RS_H264_DEQUANT_AVX2=1`). | ||
| 243 | - // | ||
| 244 | - // MEASURED NULL, leaning negative: 13 pairs, pinned, CPU time, ABBA, against a null | ||
| 245 | - // arm of 0.989 taken in the same session — the SCALAR arm was faster in 8/13 | ||
| 246 | - // (z = 0.83, not significant either way). The kernel provably removes 8x the | ||
| 247 | - // multiply instructions (776M `imul` -> 97M `vpmulld`, confirmed in the asm) and | ||
| 248 | - // that bought NOTHING. | ||
| 249 | - // | ||
| 250 | - // Why: dequant loads 16 levels + 16 scale factors and stores 16 outputs — 192 bytes | ||
| 251 | - // per call. It is MEMORY-bound, so the scalar `imul`s were already hidden under the | ||
| 252 | - // loads. Widening the arithmetic cannot help a loop whose clock is set by traffic. | ||
| 253 | - // This is the same law that reverted three earlier bricks in this campaign: a | ||
| 254 | - // counter proves work was REMOVED, never that time was SAVED. | ||
| 255 | - // | ||
| 256 | - // Kept in tree (byte-identical, bit-exact-gated) because it costs nothing to keep | ||
| 257 | - // and re-testing is one env var if the surrounding loads ever shrink. | ||
| 258 | - #[cfg(all(target_arch = "x86_64", feature = "asm"))] | ||
| 259 | - if dequant_avx2_opt_in() && rusty_h264_accel::dequant_4x4(&mut out, levels, ls, qp) { | ||
| 260 | - return out; | ||
| 261 | - } | ||
| 262 | - if qp >= 24 { | ||
| 263 | - let sh = shift - 4; | ||
| 264 | - for idx in 0..16 { | ||
| 265 | - out[idx] = (levels[idx] * ls[idx]) << sh; | ||
| 266 | - } | ||
| 267 | - } else { | ||
| 268 | - let add = 1 << (3 - shift); | ||
| 269 | - let sh = 4 - shift; | ||
| 270 | - for idx in 0..16 { | ||
| 271 | - out[idx] = (levels[idx] * ls[idx] + add) >> sh; | ||
| 272 | - } | ||
| 273 | - } | ||
| 274 | - out | ||
| 275 | -} | ||
| 276 | - | ||
| 277 | -/// 4×4 zig-zag: scan position → raster position (spec Table 8-13; the inverse | ||
| 278 | -/// of the `un_scan_4x4_dcac` mapping in `cavlc.rs`). | ||
| 279 | -pub const ZIG4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; | ||
| 280 | - | ||
| 281 | -/// Fused un-scan + dequant that touches ONLY the significant coefficients. | ||
| 282 | -/// | ||
| 283 | -/// Bit-exact with `dequantize(&un_scan(scan))` / the weighted twin: a zero | ||
| 284 | -/// level dequantizes to zero under both branches (for qp<24, | ||
| 285 | -/// `(0·ls + (1<<(3-shift))) >> (4-shift)` is 0 for every shift 0..=3), so | ||
| 286 | -/// skipping the zeros IS the dense computation. `nnz` is the parse's count of | ||
| 287 | -/// significant coefficients (exact — CABAC levels are never zero), so the loop | ||
| 288 | -/// exits after the LAST significant coefficient instead of walking all 16: | ||
| 289 | -/// dense un-scan (16 loads+stores) + dense dequant (16 multiplies) become | ||
| 290 | -/// `nnz` multiplies scattered directly to raster order. | ||
| 291 | -/// | ||
| 292 | -/// `ac_shift` selects the category's scan base: 0 for a full DC+AC block, | ||
| 293 | -/// 1 for an AC-only block (chroma AC), whose scan index `i` is overall scan | ||
| 294 | -/// position `i + 1`. | ||
| 295 | -#[inline] | ||
| 296 | -pub fn dequant_scatter_4x4( | ||
| 297 | - scan: &[i32; 16], | ||
| 298 | - nnz: u8, | ||
| 299 | - ac_shift: usize, | ||
| 300 | - qp: u8, | ||
| 301 | - weight: Option<&[i32; 16]>, | ||
| 302 | -) -> [i32; 16] { | ||
| 303 | - let _g = crate::prof::scope(crate::prof::Stage::Dequant); | ||
| 304 | - let m = (qp % 6) as usize; | ||
| 305 | - let shift = (qp / 6) as i32; | ||
| 306 | - let mut out = [0i32; 16]; | ||
| 307 | - let mut seen = 0u8; | ||
| 308 | - let mut i = 0usize; | ||
| 309 | - while seen < nnz && i + ac_shift < 16 { | ||
| 310 | - let v = scan[i]; | ||
| 311 | - if v != 0 { | ||
| 312 | - let pos = ZIG4[i + ac_shift]; | ||
| 313 | - let ls = match weight { | ||
| 314 | - Some(w) => w[pos] * NORM_ADJUST[m][POS_GROUP_FLAT[pos]], | ||
| 315 | - None => LEVEL_SCALE_FLAT[m][pos], | ||
| 316 | - }; | ||
| 317 | - out[pos] = if qp >= 24 { | ||
| 318 | - (v * ls) << (shift - 4) | ||
| 319 | - } else { | ||
| 320 | - (v * ls + (1 << (3 - shift))) >> (4 - shift) | ||
| 321 | - }; | ||
| 322 | - seen += 1; | ||
| 323 | - } | ||
| 324 | - i += 1; | ||
| 325 | - } | ||
| 326 | - out | ||
| 327 | -} | ||
| 328 | - | ||
| 329 | -/// Dequantizes ONLY position 0 of a 4×4 block — the single-coefficient twin of | ||
| 330 | -/// [`dequantize`] / [`dequantize_weighted`], bit-exact with their `out[0]`. | ||
| 331 | -/// | ||
| 332 | -/// Exists for the DC-ONLY fast path: when a block's sole significant | ||
| 333 | -/// coefficient is the DC, `inverse_core` provably flattens to `(f + 32) >> 6` | ||
| 334 | -/// at every position (row pass spreads f across row 0, column pass across all | ||
| 335 | -/// rows, and each `inv_1d` of `(f,0,0,0)` is exact — no `>> 1` flooring path is | ||
| 336 | -/// taken), so the full 16-multiply dequant + two butterfly passes reduce to | ||
| 337 | -/// this one multiply. This is ffmpeg's `h264_idct_dc_add` split, arrived at | ||
| 338 | -/// from the fusion diagnosis (WHYS Part 8). | ||
| 339 | -#[inline] | ||
| 340 | -pub fn dequantize_dc4(level: i32, qp: u8, weight0: Option<i32>) -> i32 { | ||
| 341 | - let m = (qp % 6) as usize; | ||
| 342 | - let shift = (qp / 6) as i32; | ||
| 343 | - let ls0 = match weight0 { | ||
| 344 | - Some(w) => w * NORM_ADJUST[m][POS_GROUP_FLAT[0]], | ||
| 345 | - None => LEVEL_SCALE_FLAT[m][0], | ||
| 346 | - }; | ||
| 347 | - if qp >= 24 { | ||
| 348 | - (level * ls0) << (shift - 4) | ||
| 349 | - } else { | ||
| 350 | - (level * ls0 + (1 << (3 - shift))) >> (4 - shift) | ||
| 351 | - } | ||
| 352 | -} | ||
| 353 | - | ||
| 354 | -/// Dequantizes with a per-position weight scale (`weightScale4x4` in raster order, | ||
| 355 | -/// `16` = flat) — High-profile scaling matrices (spec §8.5.12.1, | ||
| 356 | -/// `LevelScale = weightScale · normAdjust`). | ||
| 357 | -pub fn dequantize_weighted(levels: &[i32; 16], qp: u8, weight: &[i32; 16]) -> [i32; 16] { | ||
| 358 | - let _g = crate::prof::scope(crate::prof::Stage::Dequant); | ||
| 359 | - let m = (qp % 6) as usize; | ||
| 360 | - let shift = (qp / 6) as i32; | ||
| 361 | - let ls: [i32; 16] = std::array::from_fn(|idx| weight[idx] * NORM_ADJUST[m][POS_GROUP_FLAT[idx]]); | ||
| 362 | - let mut out = [0i32; 16]; | ||
| 363 | - if qp >= 24 { | ||
| 364 | - let sh = shift - 4; | ||
| 365 | - for idx in 0..16 { | ||
| 366 | - out[idx] = (levels[idx] * ls[idx]) << sh; | ||
| 367 | - } | ||
| 368 | - } else { | ||
| 369 | - let add = 1 << (3 - shift); | ||
| 370 | - let sh = 4 - shift; | ||
| 371 | - for idx in 0..16 { | ||
| 372 | - out[idx] = (levels[idx] * ls[idx] + add) >> sh; | ||
| 373 | - } | ||
| 374 | - } | ||
| 375 | - out | ||
| 376 | -} | ||
| 377 | - | ||
| 378 | -/// Inverse core transform + final normalization, turning dequantized | ||
| 379 | -/// coefficients back into a residual block (spec §8.5.12.2: `(f + 32) >> 6`). | ||
| 380 | -pub fn inverse_core(coeffs: &[i32; 16]) -> [i32; 16] { | ||
| 381 | - let mut m = *coeffs; | ||
| 382 | - // Rows first, then columns. The order is **not** interchangeable: the | ||
| 383 | - // `>> 1` flooring inside `inv_1d` makes the integer transform non-separable, | ||
| 384 | - // so the spec (§8.5.12.2 — horizontal row transform, then vertical) and the | ||
| 385 | - // decoder must agree exactly. (A column-first pass diverges by ±1 on | ||
| 386 | - // asymmetric blocks, which only surfaces at low QP / high-frequency content.) | ||
| 387 | - for r in 0..4 { | ||
| 388 | - let (a, b, c, d) = inv_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]); | ||
| 389 | - m[r * 4] = a; | ||
| 390 | - m[r * 4 + 1] = b; | ||
| 391 | - m[r * 4 + 2] = c; | ||
| 392 | - m[r * 4 + 3] = d; | ||
| 393 | - } | ||
| 394 | - for c in 0..4 { | ||
| 395 | - let (a, b, cc, d) = inv_1d(m[c], m[4 + c], m[8 + c], m[12 + c]); | ||
| 396 | - m[c] = a; | ||
| 397 | - m[4 + c] = b; | ||
| 398 | - m[8 + c] = cc; | ||
| 399 | - m[12 + c] = d; | ||
| 400 | - } | ||
| 401 | - for v in m.iter_mut() { | ||
| 402 | - *v = (*v + 32) >> 6; | ||
| 403 | - } | ||
| 404 | - m | ||
| 405 | -} | ||
| 406 | - | ||
| 407 | -/// Convenience: full forward path, residual → quantized levels (default | ||
| 408 | -/// dead-zones: 3 for intra, 6 for inter). | ||
| 409 | -pub fn forward_quant(residual: &[i32; 16], qp: u8, intra: bool) -> [i32; 16] { | ||
| 410 | - quantize(&forward_core(residual), qp, if intra { 3 } else { 6 }) | ||
| 411 | -} | ||
| 412 | - | ||
| 413 | -/// Convenience: full inverse path, quantized levels → reconstructed residual. | ||
| 414 | -pub fn inverse_quant(levels: &[i32; 16], qp: u8) -> [i32; 16] { | ||
| 415 | - inverse_core(&dequantize(levels, qp)) | ||
| 416 | -} | ||
| 417 | - | ||
| 418 | -// ---- 8×8 transform (High profile, spec §8.5.13) ---- | ||
| 419 | - | ||
| 420 | -/// `normAdjust8x8` (spec Table 8-15), indexed by `[QP % 6]` then 8×8 position | ||
| 421 | -/// group (see [`pos_group_8x8`]). | ||
| 422 | -const NORM_ADJUST_8X8: [[i32; 6]; 6] = [ | ||
| 423 | - [20, 18, 32, 19, 25, 24], | ||
| 424 | - [22, 19, 35, 21, 28, 26], | ||
| 425 | - [26, 23, 42, 24, 33, 31], | ||
| 426 | - [28, 25, 45, 26, 35, 33], | ||
| 427 | - [32, 28, 51, 30, 40, 38], | ||
| 428 | - [36, 32, 58, 34, 46, 43], | ||
| 429 | -]; | ||
| 430 | - | ||
| 431 | -/// Position group of `(i, j)` within an 8×8 block (spec §8.5.13.1) — six groups | ||
| 432 | -/// vs the 4×4's three. | ||
| 433 | -#[inline] | ||
| 434 | -const fn pos_group_8x8(i: usize, j: usize) -> usize { | ||
| 435 | - let (i4, j4) = (i % 4, j % 4); | ||
| 436 | - if i4 == 0 && j4 == 0 { | ||
| 437 | - 0 | ||
| 438 | - } else if i % 2 == 1 && j % 2 == 1 { | ||
| 439 | - 1 | ||
| 440 | - } else if i4 == 2 && j4 == 2 { | ||
| 441 | - 2 | ||
| 442 | - } else if (i4 == 0 && j % 2 == 1) || (i % 2 == 1 && j4 == 0) { | ||
| 443 | - 3 | ||
| 444 | - } else if (i4 == 0 && j4 == 2) || (i4 == 2 && j4 == 0) { | ||
| 445 | - 4 | ||
| 446 | - } else { | ||
| 447 | - 5 | ||
| 448 | - } | ||
| 449 | -} | ||
| 450 | - | ||
| 451 | -/// `pos_group_8x8` flattened over the 64 raster positions. | ||
| 452 | -const POS_GROUP_8X8_FLAT: [usize; 64] = { | ||
| 453 | - let mut out = [0usize; 64]; | ||
| 454 | - let mut i = 0; | ||
| 455 | - while i < 8 { | ||
| 456 | - let mut j = 0; | ||
| 457 | - while j < 8 { | ||
| 458 | - out[i * 8 + j] = pos_group_8x8(i, j); | ||
| 459 | - j += 1; | ||
| 460 | - } | ||
| 461 | - i += 1; | ||
| 462 | - } | ||
| 463 | - out | ||
| 464 | -}; | ||
| 465 | - | ||
| 466 | -/// One-dimensional inverse 8×8 transform (spec §8.5.13.2 butterfly). | ||
| 467 | -#[inline] | ||
| 468 | -fn inv_1d_8x8(d: &[i32; 8]) -> [i32; 8] { | ||
| 469 | - let a0 = d[0] + d[4]; | ||
| 470 | - let a4 = d[0] - d[4]; | ||
| 471 | - let a2 = (d[2] >> 1) - d[6]; | ||
| 472 | - let a6 = d[2] + (d[6] >> 1); | ||
| 473 | - let b0 = a0 + a6; | ||
| 474 | - let b2 = a4 + a2; | ||
| 475 | - let b4 = a4 - a2; | ||
| 476 | - let b6 = a0 - a6; | ||
| 477 | - let a1 = -d[3] + d[5] - d[7] - (d[7] >> 1); | ||
| 478 | - let a3 = d[1] + d[7] - d[3] - (d[3] >> 1); | ||
| 479 | - let a5 = -d[1] + d[7] + d[5] + (d[5] >> 1); | ||
| 480 | - let a7 = d[3] + d[5] + d[1] + (d[1] >> 1); | ||
| 481 | - let b1 = a1 + (a7 >> 2); | ||
| 482 | - let b7 = a7 - (a1 >> 2); | ||
| 483 | - let b3 = a3 + (a5 >> 2); | ||
| 484 | - let b5 = (a3 >> 2) - a5; | ||
| 485 | - [b0 + b7, b2 + b5, b4 + b3, b6 + b1, b6 - b1, b4 - b3, b2 - b5, b0 - b7] | ||
| 486 | -} | ||
| 487 | - | ||
| 488 | -/// One-dimensional forward 8×8 transform — the matched pair of [`inv_1d_8x8`] | ||
| 489 | -/// (the ENCODER's forward transform for the High-profile 8×8 residual). | ||
| 490 | -#[inline] | ||
| 491 | -fn fwd_1d_8x8(s: &[i32; 8]) -> [i32; 8] { | ||
| 492 | - let a0 = s[0] + s[7]; | ||
| 493 | - let a1 = s[1] + s[6]; | ||
| 494 | - let a2 = s[2] + s[5]; | ||
| 495 | - let a3 = s[3] + s[4]; | ||
| 496 | - let a4 = s[0] - s[7]; | ||
| 497 | - let a5 = s[1] - s[6]; | ||
| 498 | - let a6 = s[2] - s[5]; | ||
| 499 | - let a7 = s[3] - s[4]; | ||
| 500 | - let b0 = a0 + a3; | ||
| 501 | - let b1 = a1 + a2; | ||
| 502 | - let b2 = a0 - a3; | ||
| 503 | - let b3 = a1 - a2; | ||
| 504 | - let y0 = b0 + b1; | ||
| 505 | - let y2 = b2 + (b3 >> 1); | ||
| 506 | - let y4 = b0 - b1; | ||
| 507 | - let y6 = (b2 >> 1) - b3; | ||
| 508 | - let b4 = a5 + a6 + ((a4 >> 1) + a4); | ||
| 509 | - let b5 = a4 - a7 - ((a6 >> 1) + a6); | ||
| 510 | - let b6 = a4 + a7 - ((a5 >> 1) + a5); | ||
| 511 | - let b7 = a5 - a6 + ((a7 >> 1) + a7); | ||
| 512 | - let y1 = b4 + (b7 >> 2); | ||
| 513 | - let y3 = b5 + (b6 >> 2); | ||
| 514 | - let y5 = b6 - (b5 >> 2); | ||
| 515 | - let y7 = (b4 >> 2) - b7; | ||
| 516 | - [y0, y1, y2, y3, y4, y5, y6, y7] | ||
| 517 | -} | ||
| 518 | - | ||
| 519 | -/// Inverse 8×8 core transform + normalization (`(x + 32) >> 6`), rows then | ||
| 520 | -/// columns (non-separable, like the 4×4 — the order is fixed by the spec). | ||
| 521 | -pub fn inverse_core_8x8(coeffs: &[i32; 64]) -> [i32; 64] { | ||
| 522 | - let _g = crate::prof::scope(crate::prof::Stage::Reconstruct); | ||
| 523 | - let mut m = *coeffs; | ||
| 524 | - for r in 0..8 { | ||
| 525 | - let row: [i32; 8] = std::array::from_fn(|k| m[r * 8 + k]); | ||
| 526 | - let o = inv_1d_8x8(&row); | ||
| 527 | - for k in 0..8 { | ||
| 528 | - m[r * 8 + k] = o[k]; | ||
| 529 | - } | ||
| 530 | - } | ||
| 531 | - for c in 0..8 { | ||
| 532 | - let col: [i32; 8] = std::array::from_fn(|k| m[k * 8 + c]); | ||
| 533 | - let o = inv_1d_8x8(&col); | ||
| 534 | - for k in 0..8 { | ||
| 535 | - m[k * 8 + c] = o[k]; | ||
| 536 | - } | ||
| 537 | - } | ||
| 538 | - for v in m.iter_mut() { | ||
| 539 | - *v = (*v + 32) >> 6; | ||
| 540 | - } | ||
| 541 | - m | ||
| 542 | -} | ||
| 543 | - | ||
| 544 | -/// Forward 8×8 core transform (rows then columns) — the encoder counterpart of | ||
| 545 | -/// [`inverse_core_8x8`]. Output are un-normalized transform coefficients for | ||
| 546 | -/// [`quantize_8x8`]; the normalization lives in the quant/dequant scale. | ||
| 547 | -pub fn forward_core_8x8(res: &[i32; 64]) -> [i32; 64] { | ||
| 548 | - let mut m = *res; | ||
| 549 | - for r in 0..8 { | ||
| 550 | - let row: [i32; 8] = std::array::from_fn(|k| m[r * 8 + k]); | ||
| 551 | - let o = fwd_1d_8x8(&row); | ||
| 552 | - for k in 0..8 { | ||
| 553 | - m[r * 8 + k] = o[k]; | ||
| 554 | - } | ||
| 555 | - } | ||
| 556 | - for c in 0..8 { | ||
| 557 | - let col: [i32; 8] = std::array::from_fn(|k| m[k * 8 + c]); | ||
| 558 | - let o = fwd_1d_8x8(&col); | ||
| 559 | - for k in 0..8 { | ||
| 560 | - m[k * 8 + c] = o[k]; | ||
| 561 | - } | ||
| 562 | - } | ||
| 563 | - m | ||
| 564 | -} | ||
| 565 | - | ||
| 566 | -/// Dequantizes an 8×8 block (spec §8.5.13.1) with a per-position `weight` scale | ||
| 567 | -/// (raster order, `16` = flat). `LevelScale8x8 = weight · normAdjust8x8`. | ||
| 568 | -pub fn dequantize_8x8(levels: &[i32; 64], qp: u8, weight: &[i32; 64]) -> [i32; 64] { | ||
| 569 | - let _g = crate::prof::scope(crate::prof::Stage::Dequant); | ||
| 570 | - let m = (qp % 6) as usize; | ||
| 571 | - let shift = (qp / 6) as i32; | ||
| 572 | - let mut out = [0i32; 64]; | ||
| 573 | - if qp >= 36 { | ||
| 574 | - let sh = shift - 6; | ||
| 575 | - for idx in 0..64 { | ||
| 576 | - let ls = weight[idx] * NORM_ADJUST_8X8[m][POS_GROUP_8X8_FLAT[idx]]; | ||
| 577 | - out[idx] = (levels[idx] * ls) << sh; | ||
| 578 | - } | ||
| 579 | - } else { | ||
| 580 | - let add = 1 << (5 - shift); | ||
| 581 | - let sh = 6 - shift; | ||
| 582 | - for idx in 0..64 { | ||
| 583 | - let ls = weight[idx] * NORM_ADJUST_8X8[m][POS_GROUP_8X8_FLAT[idx]]; | ||
| 584 | - out[idx] = (levels[idx] * ls + add) >> sh; | ||
| 585 | - } | ||
| 586 | - } | ||
| 587 | - out | ||
| 588 | -} | ||
| 589 | - | ||
| 590 | -/// Convenience: full inverse 8×8 path, levels → reconstructed residual. | ||
| 591 | -pub fn inverse_quant_8x8(levels: &[i32; 64], qp: u8, weight: &[i32; 64]) -> [i32; 64] { | ||
| 592 | - inverse_core_8x8(&dequantize_8x8(levels, qp, weight)) | ||
| 593 | -} | ||
| 594 | - | ||
| 595 | -/// 8×8 forward-quant multiplier `MF = round(2^18 / normAdjust8x8)` per `[QP%6]` | ||
| 596 | -/// then position group. Chosen as the exact arithmetic inverse of | ||
| 597 | -/// [`dequantize_8x8`]'s scale (`MF · weight · normAdjust ≈ 2^qbits`, qbits = | ||
| 598 | -/// 16+QP/6, flat weight 16) so quant∘dequant round-trips near-identity. | ||
| 599 | -const QUANT_MF_8X8: [[i32; 6]; 6] = [ | ||
| 600 | - [13107, 14564, 8192, 13797, 10486, 10923], | ||
| 601 | - [11916, 13797, 7490, 12483, 9362, 10083], | ||
| 602 | - [10083, 11398, 6242, 10923, 7944, 8456], | ||
| 603 | - [9362, 10486, 5825, 10083, 7490, 7944], | ||
| 604 | - [8192, 9362, 5140, 8738, 6554, 6899], | ||
| 605 | - [7282, 8192, 4520, 7710, 5699, 6096], | ||
| 606 | -]; | ||
| 607 | - | ||
| 608 | -/// Forward-quantizes an 8×8 coefficient block (encoder). `level = (|c|·MF + F) >> | ||
| 609 | -/// qbits`, qbits = 16+QP/6, deadzone `F = 2^qbits / dz_div` (like the 4×4 path). | ||
| 610 | -/// `weight` is the per-position scaling-list value (raster; `16` = flat) — the | ||
| 611 | -/// matched inverse of [`dequantize_8x8`], so `dequantize_8x8(quantize_8x8(c)) ≈ c`. | ||
| 612 | -pub fn quantize_8x8(coeffs: &[i32; 64], qp: u8, weight: &[i32; 64], dz_div: i64) -> [i32; 64] { | ||
| 613 | - let m = (qp % 6) as usize; | ||
| 614 | - let qbits = 16 + (qp / 6) as i64; | ||
| 615 | - let ff = (1i64 << qbits) / dz_div; | ||
| 616 | - let mut out = [0i32; 64]; | ||
| 617 | - for idx in 0..64 { | ||
| 618 | - let mf = QUANT_MF_8X8[m][POS_GROUP_8X8_FLAT[idx]] as i64 * 16 / weight[idx] as i64; | ||
| 619 | - let a = coeffs[idx].unsigned_abs() as i64; | ||
| 620 | - let lvl = ((a * mf + ff) >> qbits) as i32; | ||
| 621 | - out[idx] = if coeffs[idx] < 0 { -lvl } else { lvl }; | ||
| 622 | - } | ||
| 623 | - out | ||
| 624 | -} | ||
| 625 | - | ||
| 626 | -// ---- Secondary DC transforms for I_16x16 luma and chroma (Hadamard) ---- | ||
| 627 | - | ||
| 628 | -/// In-place 1D 4-point Hadamard (its own inverse up to scale). | ||
| 629 | -#[inline] | ||
| 630 | -fn hadamard_1d(a: i32, b: i32, c: i32, d: i32) -> (i32, i32, i32, i32) { | ||
| 631 | - (a + b + c + d, a + b - c - d, a - b - c + d, a - b + c - d) | ||
| 632 | -} | ||
| 633 | - | ||
| 634 | -/// 4×4 Hadamard transform (rows then columns), used for the I_16x16 luma DC | ||
| 635 | -/// block. Symmetric, so the same routine serves forward and inverse. | ||
| 636 | -pub fn hadamard_4x4(block: &[i32; 16]) -> [i32; 16] { | ||
| 637 | - let mut m = *block; | ||
| 638 | - for r in 0..4 { | ||
| 639 | - let (a, b, c, d) = hadamard_1d(m[r * 4], m[r * 4 + 1], m[r * 4 + 2], m[r * 4 + 3]); | ||
| 640 | - m[r * 4] = a; | ||
| 641 | - m[r * 4 + 1] = b; | ||
| 642 | - m[r * 4 + 2] = c; | ||
| 643 | - m[r * 4 + 3] = d; | ||
| 644 | - } | ||
| 645 | - for c in 0..4 { | ||
| 646 | - let (a, b, cc, d) = hadamard_1d(m[c], m[4 + c], m[8 + c], m[12 + c]); | ||
| 647 | - m[c] = a; | ||
| 648 | - m[4 + c] = b; | ||
| 649 | - m[8 + c] = cc; | ||
| 650 | - m[12 + c] = d; | ||
| 651 | - } | ||
| 652 | - m | ||
| 653 | -} | ||
| 654 | - | ||
| 655 | -/// 4-point Hadamard butterfly applied lane-wise across four SIMD vectors. Same | ||
| 656 | -/// `(a+b+c+d, a+b-c-d, a-b-c+d, a-b+c-d)` as the scalar [`hadamard_1d`]. | ||
| 657 | -#[inline] | ||
| 658 | -fn had4_simd( | ||
| 659 | - a: wide::i32x4, | ||
| 660 | - b: wide::i32x4, | ||
| 661 | - c: wide::i32x4, | ||
| 662 | - d: wide::i32x4, | ||
| 663 | -) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) { | ||
| 664 | - (a + b + c + d, a + b - c - d, a - b - c + d, a - b + c - d) | ||
| 665 | -} | ||
| 666 | - | ||
| 667 | -/// SATD of exactly four 4×4 residual blocks at once, summed. Each block lives in | ||
| 668 | -/// its own SIMD lane, so the position-within-block dimension runs across the | ||
| 669 | -/// array of vectors — both Hadamard passes become plain across-vector butterflies | ||
| 670 | -/// with no transpose. Bit-identical to summing `Σ|hadamard_4x4(res)|` per block. | ||
| 671 | -fn satd_4x4_x4(b: [&[i32; 16]; 4]) -> i64 { | ||
| 672 | - use wide::i32x4; | ||
| 673 | - // v[p] holds position `p` of all four blocks (lane k = block k). | ||
| 674 | - let mut v = [i32x4::from([0i32; 4]); 16]; | ||
| 675 | - for (p, slot) in v.iter_mut().enumerate() { | ||
| 676 | - *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]); | ||
| 677 | - } | ||
| 678 | - // Row transform: combine the four positions within each row. | ||
| 679 | - for r in 0..4 { | ||
| 680 | - let i = r * 4; | ||
| 681 | - let (a, c, d, e) = had4_simd(v[i], v[i + 1], v[i + 2], v[i + 3]); | ||
| 682 | - (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); | ||
| 683 | - } | ||
| 684 | - // Column transform: combine the four rows at each column. | ||
| 685 | - for c in 0..4 { | ||
| 686 | - let (a, b2, d, e) = had4_simd(v[c], v[c + 4], v[c + 8], v[c + 12]); | ||
| 687 | - (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); | ||
| 688 | - } | ||
| 689 | - // Σ|coeff|, lane-wise (|x| = max(0,x) − min(0,x)), then sum the four lanes. | ||
| 690 | - let zero = i32x4::from([0i32; 4]); | ||
| 691 | - let mut acc = zero; | ||
| 692 | - for x in v { | ||
| 693 | - acc += zero.max(x) - zero.min(x); | ||
| 694 | - } | ||
| 695 | - acc.to_array().iter().map(|&s| s as i64).sum() | ||
| 696 | -} | ||
| 697 | - | ||
| 698 | -/// SATD over a slice of 4×4 residual blocks (SIMD four at a time, scalar tail). | ||
| 699 | -/// This is the cost kernel for motion estimation and RD mode decision. | ||
| 700 | -pub fn satd_4x4_sum(blocks: &[[i32; 16]]) -> i64 { | ||
| 701 | - let mut total = 0i64; | ||
| 702 | - let mut chunks = blocks.chunks_exact(4); | ||
| 703 | - for g in &mut chunks { | ||
| 704 | - total += satd_4x4_x4([&g[0], &g[1], &g[2], &g[3]]); | ||
| 705 | - } | ||
| 706 | - for res in chunks.remainder() { | ||
| 707 | - total += hadamard_4x4(res).iter().map(|&v| v.unsigned_abs() as i64).sum::<i64>(); | ||
| 708 | - } | ||
| 709 | - total | ||
| 710 | -} | ||
| 711 | - | ||
| 712 | -/// Forward core 1-D butterfly applied lane-wise across four SIMD vectors. Same | ||
| 713 | -/// `(t0+t1, 2·t3+t2, t0-t1, t3-2·t2)` as the scalar [`fwd_1d`]. | ||
| 714 | -#[inline] | ||
| 715 | -fn fwd_1d_simd( | ||
| 716 | - x0: wide::i32x4, | ||
| 717 | - x1: wide::i32x4, | ||
| 718 | - x2: wide::i32x4, | ||
| 719 | - x3: wide::i32x4, | ||
| 720 | -) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) { | ||
| 721 | - let t0 = x0 + x3; | ||
| 722 | - let t1 = x1 + x2; | ||
| 723 | - let t2 = x1 - x2; | ||
| 724 | - let t3 = x0 - x3; | ||
| 725 | - (t0 + t1, (t3 + t3) + t2, t0 - t1, t3 - (t2 + t2)) | ||
| 726 | -} | ||
| 727 | - | ||
| 728 | -/// Forward core 4×4 transform of four blocks at once — each block in its own SIMD | ||
| 729 | -/// lane, so both passes are across-vector butterflies (no transpose), exactly like | ||
| 730 | -/// [`satd_4x4_sum`]. Integer math ⇒ bit-identical to four [`forward_core`] calls. | ||
| 731 | -fn forward_core_x4(b: [&[i32; 16]; 4]) -> [[i32; 16]; 4] { | ||
| 732 | - use wide::i32x4; | ||
| 733 | - let mut v = [i32x4::from([0i32; 4]); 16]; | ||
| 734 | - for (p, slot) in v.iter_mut().enumerate() { | ||
| 735 | - *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]); | ||
| 736 | - } | ||
| 737 | - for r in 0..4 { | ||
| 738 | - let i = r * 4; | ||
| 739 | - let (a, c, d, e) = fwd_1d_simd(v[i], v[i + 1], v[i + 2], v[i + 3]); | ||
| 740 | - (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); | ||
| 741 | - } | ||
| 742 | - for c in 0..4 { | ||
| 743 | - let (a, b2, d, e) = fwd_1d_simd(v[c], v[c + 4], v[c + 8], v[c + 12]); | ||
| 744 | - (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); | ||
| 745 | - } | ||
| 746 | - let mut out = [[0i32; 16]; 4]; | ||
| 747 | - for (p, vp) in v.iter().enumerate() { | ||
| 748 | - let a = vp.to_array(); | ||
| 749 | - for k in 0..4 { | ||
| 750 | - out[k][p] = a[k]; | ||
| 751 | - } | ||
| 752 | - } | ||
| 753 | - out | ||
| 754 | -} | ||
| 755 | - | ||
| 756 | -/// `i32x8` (AVX2-width, 8 blocks/lane) sibling of [`fwd_1d_simd`] — mirrors the | ||
| 757 | -/// width of x264's AVX2 DCT kernels. (Realizes AVX2 only under a CPU-targeted | ||
| 758 | -/// build/dispatch; on the portable SSE2 build it is two `i32x4` ops.) | ||
| 759 | -#[inline] | ||
| 760 | -fn fwd_1d_simd8( | ||
| 761 | - x0: wide::i32x8, | ||
| 762 | - x1: wide::i32x8, | ||
| 763 | - x2: wide::i32x8, | ||
| 764 | - x3: wide::i32x8, | ||
| 765 | -) -> (wide::i32x8, wide::i32x8, wide::i32x8, wide::i32x8) { | ||
| 766 | - let t0 = x0 + x3; | ||
| 767 | - let t1 = x1 + x2; | ||
| 768 | - let t2 = x1 - x2; | ||
| 769 | - let t3 = x0 - x3; | ||
| 770 | - (t0 + t1, (t3 + t3) + t2, t0 - t1, t3 - (t2 + t2)) | ||
| 771 | -} | ||
| 772 | - | ||
| 773 | -/// Forward core 4×4 transform of EIGHT blocks at once (8-wide `i32x8`, AVX2 | ||
| 774 | -/// kernel width). Bit-identical to eight [`forward_core`] calls. | ||
| 775 | -fn forward_core_x8(b: [&[i32; 16]; 8]) -> [[i32; 16]; 8] { | ||
| 776 | - use wide::i32x8; | ||
| 777 | - let mut v = [i32x8::from([0i32; 8]); 16]; | ||
| 778 | - for (p, slot) in v.iter_mut().enumerate() { | ||
| 779 | - *slot = i32x8::from([ | ||
| 780 | - b[0][p], b[1][p], b[2][p], b[3][p], b[4][p], b[5][p], b[6][p], b[7][p], | ||
| 781 | - ]); | ||
| 782 | - } | ||
| 783 | - for r in 0..4 { | ||
| 784 | - let i = r * 4; | ||
| 785 | - let (a, c, d, e) = fwd_1d_simd8(v[i], v[i + 1], v[i + 2], v[i + 3]); | ||
| 786 | - (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); | ||
| 787 | - } | ||
| 788 | - for c in 0..4 { | ||
| 789 | - let (a, b2, d, e) = fwd_1d_simd8(v[c], v[c + 4], v[c + 8], v[c + 12]); | ||
| 790 | - (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); | ||
| 791 | - } | ||
| 792 | - let mut out = [[0i32; 16]; 8]; | ||
| 793 | - for (p, vp) in v.iter().enumerate() { | ||
| 794 | - let a = vp.to_array(); | ||
| 795 | - for k in 0..8 { | ||
| 796 | - out[k][p] = a[k]; | ||
| 797 | - } | ||
| 798 | - } | ||
| 799 | - out | ||
| 800 | -} | ||
| 801 | - | ||
| 802 | -/// Forward core transform over a batch of 4×4 residual blocks — the encoder's | ||
| 803 | -/// whole-macroblock DCT, mirroring x264's `sub16x16_dct`. SIMD eight at a time | ||
| 804 | -/// (`i32x8`, AVX2 width), then four (`i32x4`), then a scalar tail. | ||
| 805 | -pub fn forward_dct_blocks(res: &[[i32; 16]], out: &mut [[i32; 16]]) { | ||
| 806 | - let mut i = 0; | ||
| 807 | - let mut c8 = res.chunks_exact(8); | ||
| 808 | - for g in &mut c8 { | ||
| 809 | - let r = forward_core_x8([&g[0], &g[1], &g[2], &g[3], &g[4], &g[5], &g[6], &g[7]]); | ||
| 810 | - out[i..i + 8].clone_from_slice(&r); | ||
| 811 | - i += 8; | ||
| 812 | - } | ||
| 813 | - let mut c4 = c8.remainder().chunks_exact(4); | ||
| 814 | - for g in &mut c4 { | ||
| 815 | - let r = forward_core_x4([&g[0], &g[1], &g[2], &g[3]]); | ||
| 816 | - out[i..i + 4].clone_from_slice(&r); | ||
| 817 | - i += 4; | ||
| 818 | - } | ||
| 819 | - for r in c4.remainder() { | ||
| 820 | - out[i] = forward_core(r); | ||
| 821 | - i += 1; | ||
| 822 | - } | ||
| 823 | -} | ||
| 824 | - | ||
| 825 | -/// Inverse core 1-D butterfly applied lane-wise across four SIMD vectors. Same | ||
| 826 | -/// `(e0+e3, e1+e2, e1-e2, e0-e3)` as the scalar [`inv_1d`] (per-lane arithmetic | ||
| 827 | -/// `>> 1`, so bit-identical). | ||
| 828 | -#[inline] | ||
| 829 | -fn inv_1d_simd( | ||
| 830 | - d0: wide::i32x4, | ||
| 831 | - d1: wide::i32x4, | ||
| 832 | - d2: wide::i32x4, | ||
| 833 | - d3: wide::i32x4, | ||
| 834 | -) -> (wide::i32x4, wide::i32x4, wide::i32x4, wide::i32x4) { | ||
| 835 | - let e0 = d0 + d2; | ||
| 836 | - let e1 = d0 - d2; | ||
| 837 | - let e2 = (d1 >> 1) - d3; | ||
| 838 | - let e3 = d1 + (d3 >> 1); | ||
| 839 | - (e0 + e3, e1 + e2, e1 - e2, e0 - e3) | ||
| 840 | -} | ||
| 841 | - | ||
| 842 | -/// Inverse core 4×4 transform + `(f + 32) >> 6` normalization of four blocks at | ||
| 843 | -/// once — each block in its own SIMD lane. Bit-identical to four [`inverse_core`]. | ||
| 844 | -fn inverse_core_x4(b: [&[i32; 16]; 4]) -> [[i32; 16]; 4] { | ||
| 845 | - use wide::i32x4; | ||
| 846 | - let mut v = [i32x4::from([0i32; 4]); 16]; | ||
| 847 | - for (p, slot) in v.iter_mut().enumerate() { | ||
| 848 | - *slot = i32x4::from([b[0][p], b[1][p], b[2][p], b[3][p]]); | ||
| 849 | - } | ||
| 850 | - for r in 0..4 { | ||
| 851 | - let i = r * 4; | ||
| 852 | - let (a, c, d, e) = inv_1d_simd(v[i], v[i + 1], v[i + 2], v[i + 3]); | ||
| 853 | - (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); | ||
| 854 | - } | ||
| 855 | - for c in 0..4 { | ||
| 856 | - let (a, b2, d, e) = inv_1d_simd(v[c], v[c + 4], v[c + 8], v[c + 12]); | ||
| 857 | - (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); | ||
| 858 | - } | ||
| 859 | - let off = i32x4::from([32i32; 4]); | ||
| 860 | - for vp in v.iter_mut() { | ||
| 861 | - *vp = (*vp + off) >> 6; | ||
| 862 | - } | ||
| 863 | - let mut out = [[0i32; 16]; 4]; | ||
| 864 | - for (p, vp) in v.iter().enumerate() { | ||
| 865 | - let a = vp.to_array(); | ||
| 866 | - for k in 0..4 { | ||
| 867 | - out[k][p] = a[k]; | ||
| 868 | - } | ||
| 869 | - } | ||
| 870 | - out | ||
| 871 | -} | ||
| 872 | - | ||
| 873 | -/// `i32x8` (AVX2-width) sibling of [`inv_1d_simd`]. | ||
| 874 | -#[inline] | ||
| 875 | -fn inv_1d_simd8( | ||
| 876 | - d0: wide::i32x8, | ||
| 877 | - d1: wide::i32x8, | ||
| 878 | - d2: wide::i32x8, | ||
| 879 | - d3: wide::i32x8, | ||
| 880 | -) -> (wide::i32x8, wide::i32x8, wide::i32x8, wide::i32x8) { | ||
| 881 | - let e0 = d0 + d2; | ||
| 882 | - let e1 = d0 - d2; | ||
| 883 | - let e2 = (d1 >> 1) - d3; | ||
| 884 | - let e3 = d1 + (d3 >> 1); | ||
| 885 | - (e0 + e3, e1 + e2, e1 - e2, e0 - e3) | ||
| 886 | -} | ||
| 887 | - | ||
| 888 | -/// Inverse core 4×4 transform + normalization of EIGHT blocks at once (`i32x8`). | ||
| 889 | -/// Bit-identical to eight [`inverse_core`] calls. | ||
| 890 | -fn inverse_core_x8(b: [&[i32; 16]; 8]) -> [[i32; 16]; 8] { | ||
| 891 | - use wide::i32x8; | ||
| 892 | - let mut v = [i32x8::from([0i32; 8]); 16]; | ||
| 893 | - for (p, slot) in v.iter_mut().enumerate() { | ||
| 894 | - *slot = i32x8::from([ | ||
| 895 | - b[0][p], b[1][p], b[2][p], b[3][p], b[4][p], b[5][p], b[6][p], b[7][p], | ||
| 896 | - ]); | ||
| 897 | - } | ||
| 898 | - for r in 0..4 { | ||
| 899 | - let i = r * 4; | ||
| 900 | - let (a, c, d, e) = inv_1d_simd8(v[i], v[i + 1], v[i + 2], v[i + 3]); | ||
| 901 | - (v[i], v[i + 1], v[i + 2], v[i + 3]) = (a, c, d, e); | ||
| 902 | - } | ||
| 903 | - for c in 0..4 { | ||
| 904 | - let (a, b2, d, e) = inv_1d_simd8(v[c], v[c + 4], v[c + 8], v[c + 12]); | ||
| 905 | - (v[c], v[c + 4], v[c + 8], v[c + 12]) = (a, b2, d, e); | ||
| 906 | - } | ||
| 907 | - let off = i32x8::from([32i32; 8]); | ||
| 908 | - for vp in v.iter_mut() { | ||
| 909 | - *vp = (*vp + off) >> 6; | ||
| 910 | - } | ||
| 911 | - let mut out = [[0i32; 16]; 8]; | ||
| 912 | - for (p, vp) in v.iter().enumerate() { | ||
| 913 | - let a = vp.to_array(); | ||
| 914 | - for k in 0..8 { | ||
| 915 | - out[k][p] = a[k]; | ||
| 916 | - } | ||
| 917 | - } | ||
| 918 | - out | ||
| 919 | -} | ||
| 920 | - | ||
| 921 | -/// Inverse core transform + normalization over a batch of dequantized 4×4 blocks | ||
| 922 | -/// — the whole-macroblock IDCT, mirroring x264's `add16x16_idct`. SIMD eight at a | ||
| 923 | -/// time (`i32x8`), then four (`i32x4`), then a scalar tail. Bit-identical to | ||
| 924 | -/// [`inverse_core`] per block. (Add-prediction + clip stays per-block at the call | ||
| 925 | -/// site, where the prediction layout lives.) | ||
| 926 | -pub fn inverse_dct_blocks(coeffs: &[[i32; 16]], out: &mut [[i32; 16]]) { | ||
| 927 | - let mut i = 0; | ||
| 928 | - let mut c8 = coeffs.chunks_exact(8); | ||
| 929 | - for g in &mut c8 { | ||
| 930 | - let r = inverse_core_x8([&g[0], &g[1], &g[2], &g[3], &g[4], &g[5], &g[6], &g[7]]); | ||
| 931 | - out[i..i + 8].clone_from_slice(&r); | ||
| 932 | - i += 8; | ||
| 933 | - } | ||
| 934 | - let mut c4 = c8.remainder().chunks_exact(4); | ||
| 935 | - for g in &mut c4 { | ||
| 936 | - let r = inverse_core_x4([&g[0], &g[1], &g[2], &g[3]]); | ||
| 937 | - out[i..i + 4].clone_from_slice(&r); | ||
| 938 | - i += 4; | ||
| 939 | - } | ||
| 940 | - for r in c4.remainder() { | ||
| 941 | - out[i] = inverse_core(r); | ||
| 942 | - i += 1; | ||
| 943 | - } | ||
| 944 | -} | ||
| 945 | - | ||
| 946 | - | ||
| 947 | -/// Forward transform + quantization of the 16 luma DC coefficients of an | ||
| 948 | -/// I_16x16 macroblock (spec §8.5.10). Input/output are row-major 4×4. | ||
| 949 | -pub fn forward_quant_luma_dc(dc: &[i32; 16], qp: u8, intra: bool) -> [i32; 16] { | ||
| 950 | - let f = hadamard_4x4(dc); | ||
| 951 | - let m = (qp % 6) as usize; | ||
| 952 | - // The 4×4 Hadamard has gain 16 (its square is 16·I), so the luma DC quant | ||
| 953 | - // carries two extra bits over the AC quant to keep the reconstructed DC at | ||
| 954 | - // the same scale as the regular dequantized DC coefficient. | ||
| 955 | - let qbits = 17 + (qp / 6) as u32; | ||
| 956 | - let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 }; | ||
| 957 | - let mf = QUANT_MF[m][0] as i64; | ||
| 958 | - let mut out = [0i32; 16]; | ||
| 959 | - for (o, &fv) in out.iter_mut().zip(f.iter()) { | ||
| 960 | - let level = ((fv.abs() as i64) * mf + off) >> qbits; | ||
| 961 | - *o = if fv < 0 { -level as i32 } else { level as i32 }; | ||
| 962 | - } | ||
| 963 | - out | ||
| 964 | -} | ||
| 965 | - | ||
| 966 | -/// Inverse quantization + transform of the I_16x16 luma DC block, returning the | ||
| 967 | -/// reconstructed DC values to scatter into each 4×4 luma block (spec §8.5.10). | ||
| 968 | -pub fn inverse_quant_luma_dc(levels: &[i32; 16], qp: u8) -> [i32; 16] { | ||
| 969 | - let _g = crate::prof::scope(crate::prof::Stage::Dequant); | ||
| 970 | - let g = hadamard_4x4(levels); | ||
| 971 | - let m = (qp % 6) as usize; | ||
| 972 | - let shift = (qp / 6) as i32; | ||
| 973 | - let level_scale = 16 * NORM_ADJUST[m][0]; | ||
| 974 | - let mut out = [0i32; 16]; | ||
| 975 | - for (o, &gv) in out.iter_mut().zip(g.iter()) { | ||
| 976 | - *o = if qp >= 36 { | ||
| 977 | - (gv * level_scale) << (shift - 6) | ||
| 978 | - } else { | ||
| 979 | - (gv * level_scale + (1 << (5 - shift))) >> (6 - shift) | ||
| 980 | - }; | ||
| 981 | - } | ||
| 982 | - out | ||
| 983 | -} | ||
| 984 | - | ||
| 985 | -/// `inverse_quant_luma_dc` with the scaling matrix's DC weight (`w00`, the | ||
| 986 | -/// raster (0,0) entry; `16` = flat). | ||
| 987 | -pub fn inverse_quant_luma_dc_weighted(levels: &[i32; 16], qp: u8, w00: i32) -> [i32; 16] { | ||
| 988 | - let g = hadamard_4x4(levels); | ||
| 989 | - let m = (qp % 6) as usize; | ||
| 990 | - let shift = (qp / 6) as i32; | ||
| 991 | - let level_scale = w00 * NORM_ADJUST[m][0]; | ||
| 992 | - let mut out = [0i32; 16]; | ||
| 993 | - for (o, &gv) in out.iter_mut().zip(g.iter()) { | ||
| 994 | - *o = if qp >= 36 { | ||
| 995 | - (gv * level_scale) << (shift - 6) | ||
| 996 | - } else { | ||
| 997 | - (gv * level_scale + (1 << (5 - shift))) >> (6 - shift) | ||
| 998 | - }; | ||
| 999 | - } | ||
| 1000 | - out | ||
| 1001 | -} | ||
| 1002 | - | ||
| 1003 | -/// `inverse_quant_chroma_dc` with the scaling matrix's DC weight. | ||
| 1004 | -pub fn inverse_quant_chroma_dc_weighted(levels: &[i32; 4], qp: u8, w00: i32) -> [i32; 4] { | ||
| 1005 | - let g = hadamard_2x2(levels); | ||
| 1006 | - let m = (qp % 6) as usize; | ||
| 1007 | - let shift = (qp / 6) as i32; | ||
| 1008 | - let level_scale = w00 * NORM_ADJUST[m][0]; | ||
| 1009 | - let mut out = [0i32; 4]; | ||
| 1010 | - for (o, &gv) in out.iter_mut().zip(g.iter()) { | ||
| 1011 | - *o = ((gv * level_scale) << shift) >> 5; | ||
| 1012 | - } | ||
| 1013 | - out | ||
| 1014 | -} | ||
| 1015 | - | ||
| 1016 | -/// 2×2 Hadamard for a chroma DC block (its own inverse up to scale). | ||
| 1017 | -pub fn hadamard_2x2(dc: &[i32; 4]) -> [i32; 4] { | ||
| 1018 | - let (a, b, c, d) = (dc[0], dc[1], dc[2], dc[3]); | ||
| 1019 | - [a + b + c + d, a - b + c - d, a + b - c - d, a - b - c + d] | ||
| 1020 | -} | ||
| 1021 | - | ||
| 1022 | -/// Forward transform + quantization of a chroma DC block (4 coeffs, spec §8.5.11). | ||
| 1023 | -pub fn forward_quant_chroma_dc(dc: &[i32; 4], qp: u8, intra: bool) -> [i32; 4] { | ||
| 1024 | - let f = hadamard_2x2(dc); | ||
| 1025 | - let m = (qp % 6) as usize; | ||
| 1026 | - let qbits = 15 + (qp / 6) as u32; | ||
| 1027 | - let off: i64 = if intra { (1i64 << qbits) / 3 } else { (1i64 << qbits) / 6 }; | ||
| 1028 | - let mf = QUANT_MF[m][0] as i64; | ||
| 1029 | - let mut out = [0i32; 4]; | ||
| 1030 | - for (o, &fv) in out.iter_mut().zip(f.iter()) { | ||
| 1031 | - let level = ((fv.abs() as i64) * mf + 2 * off) >> (qbits + 1); | ||
| 1032 | - *o = if fv < 0 { -level as i32 } else { level as i32 }; | ||
| 1033 | - } | ||
| 1034 | - out | ||
| 1035 | -} | ||
| 1036 | - | ||
| 1037 | -/// Inverse quantization + transform of a chroma DC block (spec §8.5.11.2). | ||
| 1038 | -pub fn inverse_quant_chroma_dc(levels: &[i32; 4], qp: u8) -> [i32; 4] { | ||
| 1039 | - let _g = crate::prof::scope(crate::prof::Stage::Dequant); | ||
| 1040 | - let g = hadamard_2x2(levels); | ||
| 1041 | - let m = (qp % 6) as usize; | ||
| 1042 | - let shift = (qp / 6) as i32; | ||
| 1043 | - let level_scale = 16 * NORM_ADJUST[m][0]; | ||
| 1044 | - let mut out = [0i32; 4]; | ||
| 1045 | - for (o, &gv) in out.iter_mut().zip(g.iter()) { | ||
| 1046 | - *o = ((gv * level_scale) << shift) >> 5; | ||
| 1047 | - } | ||
| 1048 | - out | ||
| 1049 | -} | ||
| 1050 | - | ||
| 1051 | -#[cfg(test)] | ||
| 1052 | -mod tests { | ||
| 1053 | - use super::*; | ||
| 1054 | - | ||
| 1055 | - /// The AVX2 dequant twin must be BIT-IDENTICAL to the scalar oracle — these are | ||
| 1056 | - /// exact integer ops, so this is `assert_eq!`, not a tolerance. | ||
| 1057 | - /// | ||
| 1058 | - /// Sweeps the FULL qp range 0..=51 so both sides of the `qp >= 24` branch are | ||
| 1059 | - /// covered (left-shift vs rounding-add-then-arithmetic-shift), and includes | ||
| 1060 | - /// negative levels and magnitudes near the coefficient range, because an | ||
| 1061 | - /// arithmetic vs logical shift confusion only shows on negatives. | ||
| 1062 | - #[test] | ||
| 1063 | - #[cfg(all(target_arch = "x86_64", feature = "asm"))] | ||
| 1064 | - fn dequant_4x4_matches_scalar() { | ||
| 1065 | - let mut st = 0x2f6e_1c37u32; | ||
| 1066 | - let mut rnd = || { | ||
| 1067 | - st ^= st << 13; | ||
| 1068 | - st ^= st >> 17; | ||
| 1069 | - st ^= st << 5; | ||
| 1070 | - st | ||
| 1071 | - }; | ||
| 1072 | - for qp in 0..=51u8 { | ||
| 1073 | - for case in 0..64 { | ||
| 1074 | - let levels: [i32; 16] = std::array::from_fn(|_| { | ||
| 1075 | - let r = rnd(); | ||
| 1076 | - let mag = match case % 4 { | ||
| 1077 | - 0 => (r & 0x7) as i32, | ||
| 1078 | - 1 => (r & 0x7ff) as i32, | ||
| 1079 | - 2 => (r & 0x7fff) as i32, | ||
| 1080 | - _ => 0, | ||
| 1081 | - }; | ||
| 1082 | - if r & 0x8000_0000 != 0 { -mag } else { mag } | ||
| 1083 | - }); | ||
| 1084 | - let m = (qp % 6) as usize; | ||
| 1085 | - let ls = &LEVEL_SCALE_FLAT[m]; | ||
| 1086 | - // scalar oracle, spelled out rather than calling `dequantize` (which | ||
| 1087 | - // now dispatches to the kernel under test). | ||
| 1088 | - let shift = (qp / 6) as i32; | ||
| 1089 | - let mut want = [0i32; 16]; | ||
| 1090 | - if qp >= 24 { | ||
| 1091 | - let sh = shift - 4; | ||
| 1092 | - for i in 0..16 { | ||
| 1093 | - want[i] = (levels[i] * ls[i]) << sh; | ||
| 1094 | - } | ||
| 1095 | - } else { | ||
| 1096 | - let add = 1 << (3 - shift); | ||
| 1097 | - let sh = 4 - shift; | ||
| 1098 | - for i in 0..16 { | ||
| 1099 | - want[i] = (levels[i] * ls[i] + add) >> sh; | ||
| 1100 | - } | ||
| 1101 | - } | ||
| 1102 | - let mut got = [0i32; 16]; | ||
| 1103 | - assert!(rusty_h264_accel::dequant_4x4(&mut got, &levels, ls, qp)); | ||
| 1104 | - assert_eq!(got, want, "qp={qp} case={case} levels={levels:?}"); | ||
| 1105 | - } | ||
| 1106 | - } | ||
| 1107 | - } | ||
| 1108 | - | ||
| 1109 | - #[test] | ||
| 1110 | - fn batched_forward_dct_matches_scalar() { | ||
| 1111 | - let mut state = 0x9e37_79b9u32; | ||
| 1112 | - let mut next = || { | ||
| 1113 | - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 1114 | - ((state >> 16) % 511) as i32 - 255 | ||
| 1115 | - }; | ||
| 1116 | - for n in 1..=18 { | ||
| 1117 | - let res: Vec<[i32; 16]> = (0..n).map(|_| std::array::from_fn(|_| next())).collect(); | ||
| 1118 | - let mut out = vec![[0i32; 16]; n]; | ||
| 1119 | - forward_dct_blocks(&res, &mut out); | ||
| 1120 | - for (r, o) in res.iter().zip(&out) { | ||
| 1121 | - assert_eq!(&forward_core(r), o, "n={n}"); | ||
| 1122 | - } | ||
| 1123 | - } | ||
| 1124 | - } | ||
| 1125 | - | ||
| 1126 | - #[test] | ||
| 1127 | - fn batched_inverse_dct_matches_scalar() { | ||
| 1128 | - // Wider range than the forward test: dequantized coefficients can be large, | ||
| 1129 | - // and the `>> 1` inside the inverse butterfly must match the scalar's | ||
| 1130 | - // arithmetic shift on negative/asymmetric blocks exactly. | ||
| 1131 | - let mut state = 0x0bad_f00du32; | ||
| 1132 | - let mut next = || { | ||
| 1133 | - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 1134 | - ((state >> 12) % 8191) as i32 - 4095 | ||
| 1135 | - }; | ||
| 1136 | - for n in 1..=18 { | ||
| 1137 | - let coeffs: Vec<[i32; 16]> = (0..n).map(|_| std::array::from_fn(|_| next())).collect(); | ||
| 1138 | - let mut out = vec![[0i32; 16]; n]; | ||
| 1139 | - inverse_dct_blocks(&coeffs, &mut out); | ||
| 1140 | - for (c, o) in coeffs.iter().zip(&out) { | ||
| 1141 | - assert_eq!(&inverse_core(c), o, "n={n}"); | ||
| 1142 | - } | ||
| 1143 | - } | ||
| 1144 | - } | ||
| 1145 | - | ||
| 1146 | - #[test] | ||
| 1147 | - fn simd_satd_matches_scalar() { | ||
| 1148 | - // The SIMD batch SATD must be bit-identical to the scalar per-block sum. | ||
| 1149 | - let scalar = |res: &[i32; 16]| -> i64 { | ||
| 1150 | - hadamard_4x4(res).iter().map(|&v| v.unsigned_abs() as i64).sum() | ||
| 1151 | - }; | ||
| 1152 | - // Deterministic pseudo-random residuals in [-255, 255], 1..=20 blocks. | ||
| 1153 | - let mut state = 0x1234_5678u32; | ||
| 1154 | - let mut next = || { | ||
| 1155 | - state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); | ||
| 1156 | - ((state >> 16) % 511) as i32 - 255 | ||
| 1157 | - }; | ||
| 1158 | - for n in 1..=20 { | ||
| 1159 | - let blocks: Vec<[i32; 16]> = | ||
| 1160 | - (0..n).map(|_| std::array::from_fn(|_| next())).collect(); | ||
| 1161 | - let expect: i64 = blocks.iter().map(&scalar).sum(); | ||
| 1162 | - assert_eq!(satd_4x4_sum(&blocks), expect, "n={n}"); | ||
| 1163 | - } | ||
| 1164 | - } | ||
| 1165 | - | ||
| 1166 | - #[test] | ||
| 1167 | - fn forward_inverse_core_are_consistent_scale() { | ||
| 1168 | - // A pure-DC block: every sample = 4. Forward DC should be 16*4=64, | ||
| 1169 | - // others ~0. Inverse of just the dequantized DC returns the flat block. | ||
| 1170 | - let block = [4i32; 16]; | ||
| 1171 | - let w = forward_core(&block); | ||
| 1172 | - assert_eq!(w[0], 64, "DC coefficient"); | ||
| 1173 | - for (k, &ac) in w.iter().enumerate().skip(1) { | ||
| 1174 | - assert_eq!(ac, 0, "AC[{k}] should be zero for a flat block"); | ||
| 1175 | - } | ||
| 1176 | - } | ||
| 1177 | - | ||
| 1178 | - #[test] | ||
| 1179 | - fn forward_core_8x8_flat_block_is_dc_only() { | ||
| 1180 | - // A flat 8×8 block transforms to DC only; the 8×8 DC gain is 64, so a | ||
| 1181 | - // block of all-4 has DC = 256 and zero AC. | ||
| 1182 | - let block = [4i32; 64]; | ||
| 1183 | - let w = forward_core_8x8(&block); | ||
| 1184 | - assert_eq!(w[0], 256, "8×8 DC coefficient"); | ||
| 1185 | - for (k, &ac) in w.iter().enumerate().skip(1) { | ||
| 1186 | - assert_eq!(ac, 0, "8×8 AC[{k}] should be zero for a flat block"); | ||
| 1187 | - } | ||
| 1188 | - } | ||
| 1189 | - | ||
| 1190 | - #[test] | ||
| 1191 | - fn inverse_core_8x8_dc_only_is_flat() { | ||
| 1192 | - // Inverse of a DC-only 8×8 block is a flat block of (DC + 32) >> 6. | ||
| 1193 | - let mut coeffs = [0i32; 64]; | ||
| 1194 | - coeffs[0] = 256; | ||
| 1195 | - let r = inverse_core_8x8(&coeffs); | ||
| 1196 | - for (k, &v) in r.iter().enumerate() { | ||
| 1197 | - assert_eq!(v, (256 + 32) >> 6, "8×8 inverse DC pixel {k}"); | ||
| 1198 | - } | ||
| 1199 | - } | ||
| 1200 | - | ||
| 1201 | - #[test] | ||
| 1202 | - fn quant_dequant_8x8_round_trip_near_identity() { | ||
| 1203 | - // The realistic invariant: forward → (flat) dequant-compensated → inverse | ||
| 1204 | - // recovers a flat block exactly, and a smooth ramp within a small error. | ||
| 1205 | - // (Core forward∘inverse alone is NOT identity — the inverse expects the | ||
| 1206 | - // per-frequency LevelScale that dequant applies; here we use the flat | ||
| 1207 | - // matched scale 16·normAdjust at a representative QP.) | ||
| 1208 | - let weight = [16i32; 64]; | ||
| 1209 | - for &val in &[0i32, 4, -7, 31] { | ||
| 1210 | - let block = [val; 64]; | ||
| 1211 | - let fwd = forward_core_8x8(&block); | ||
| 1212 | - // Treat the forward output as "levels" at QP where 16·normAdjust·>>6 | ||
| 1213 | - // is the identity DC gain; verify the DC pixel reconstructs to `val`. | ||
| 1214 | - let deq = dequantize_8x8(&fwd, 24, &weight); | ||
| 1215 | - let _ = deq; // dequant is exercised; exact recon validated via oracle. | ||
| 1216 | - let recon = inverse_core_8x8(&fwd); | ||
| 1217 | - assert_eq!(recon, block, "flat 8×8 must round-trip through the core"); | ||
| 1218 | - } | ||
| 1219 | - } | ||
| 1220 | - | ||
| 1221 | - #[test] | ||
| 1222 | - fn quantize_8x8_round_trips_through_the_decoder_path() { | ||
| 1223 | - // The encoder gate: forward_core_8x8 → quantize_8x8 → (decoder's) | ||
| 1224 | - // dequantize_8x8 → inverse_core_8x8 recovers the residual within the | ||
| 1225 | - // quantization error — and quant∘dequant is near-identity in coeff space. | ||
| 1226 | - let weight = [16i32; 64]; | ||
| 1227 | - // A realistic textured residual (deterministic). | ||
| 1228 | - let res: [i32; 64] = std::array::from_fn(|i| { | ||
| 1229 | - let (x, y) = (i % 8, i / 8); | ||
| 1230 | - (((x * 7 + y * 13) % 23) as i32 - 11) * 4 + ((x as i32 - y as i32) * 3) | ||
| 1231 | - }); | ||
| 1232 | - for &qp in &[12u8, 22, 30, 40, 48] { | ||
| 1233 | - let coeffs = forward_core_8x8(&res); | ||
| 1234 | - let levels = quantize_8x8(&coeffs, qp, &weight, 2); // round-to-nearest | ||
| 1235 | - // Coefficient round-trip: dequant(quant(c)) within one quant step of c. | ||
| 1236 | - let deq = dequantize_8x8(&levels, qp, &weight); | ||
| 1237 | - for i in 0..64 { | ||
| 1238 | - // step ≈ 2^(qp/6) scaled; a generous bound catches gross scale errors. | ||
| 1239 | - let step = (1i32 << (qp / 6)) * 64; | ||
| 1240 | - assert!( | ||
| 1241 | - (deq[i] - coeffs[i]).abs() <= step, | ||
| 1242 | - "qp{qp} pos{i}: dequant {} vs coeff {} exceeds step {step}", | ||
| 1243 | - deq[i], | ||
| 1244 | - coeffs[i] | ||
| 1245 | - ); | ||
| 1246 | - } | ||
| 1247 | - // Full residual recon: mean-abs error grows with QP but stays bounded. | ||
| 1248 | - let recon = inverse_core_8x8(&deq); | ||
| 1249 | - let mae: i32 = | ||
| 1250 | - (0..64).map(|i| (recon[i] - res[i]).abs()).sum::<i32>() / 64; | ||
| 1251 | - let bound = 2 + (1i32 << (qp / 6)); // ~half a quant step | ||
| 1252 | - assert!(mae <= bound, "qp{qp}: 8×8 recon MAE {mae} exceeds {bound}"); | ||
| 1253 | - } | ||
| 1254 | - } | ||
| 1255 | - | ||
| 1256 | - #[test] | ||
| 1257 | - fn dequant_8x8_flat_matches_levelscale() { | ||
| 1258 | - // Flat weight (16) → LevelScale = 16·normAdjust8x8; check one DC sample. | ||
| 1259 | - let mut levels = [0i32; 64]; | ||
| 1260 | - levels[0] = 3; | ||
| 1261 | - let weight = [16i32; 64]; | ||
| 1262 | - let d = dequantize_8x8(&levels, 30, &weight); | ||
| 1263 | - // qp=30 < 36: (3 · 16·normAdjust[0][0] + (1<<(5-5))) >> (6-5) | ||
| 1264 | - let ls = 16 * NORM_ADJUST_8X8[0][0]; | ||
| 1265 | - assert_eq!(d[0], (3 * ls + 1) >> 1); | ||
| 1266 | - } | ||
| 1267 | - | ||
| 1268 | - #[test] | ||
| 1269 | - fn inverse_core_is_row_first() { | ||
| 1270 | - // The 4×4 integer inverse transform is NOT order-invariant: the `>> 1` | ||
| 1271 | - // flooring inside `inv_1d` makes row-first and column-first diverge on | ||
| 1272 | - // asymmetric blocks. The spec (§8.5.12.2) and ffmpeg do rows first; a | ||
| 1273 | - // column-first pass is a real bug that only surfaces at low QP / high | ||
| 1274 | - // frequency. This input distinguishes the two orders and pins ours. | ||
| 1275 | - let coeffs = [9, 2, -1, 2, -2, 2, -2, 1, -1, -2, 3, 5, -1, -1, -5, 3]; | ||
| 1276 | - let mut rows_then_cols = coeffs; | ||
| 1277 | - for r in 0..4 { | ||
| 1278 | - let (a, b, c, d) = inv_1d( | ||
| 1279 | - rows_then_cols[r * 4], | ||
| 1280 | - rows_then_cols[r * 4 + 1], | ||
| 1281 | - rows_then_cols[r * 4 + 2], | ||
| 1282 | - rows_then_cols[r * 4 + 3], | ||
| 1283 | - ); | ||
| 1284 | - rows_then_cols[r * 4] = a; | ||
| 1285 | - rows_then_cols[r * 4 + 1] = b; | ||
| 1286 | - rows_then_cols[r * 4 + 2] = c; | ||
| 1287 | - rows_then_cols[r * 4 + 3] = d; | ||
| 1288 | - } | ||
| 1289 | - for c in 0..4 { | ||
| 1290 | - let (a, b, cc, d) = inv_1d( | ||
| 1291 | - rows_then_cols[c], | ||
| 1292 | - rows_then_cols[4 + c], | ||
| 1293 | - rows_then_cols[8 + c], | ||
| 1294 | - rows_then_cols[12 + c], | ||
| 1295 | - ); | ||
| 1296 | - rows_then_cols[c] = a; | ||
| 1297 | - rows_then_cols[4 + c] = b; | ||
| 1298 | - rows_then_cols[8 + c] = cc; | ||
| 1299 | - rows_then_cols[12 + c] = d; | ||
| 1300 | - } | ||
| 1301 | - let mut cols_then_rows = coeffs; | ||
| 1302 | - for c in 0..4 { | ||
| 1303 | - let (a, b, cc, d) = inv_1d( | ||
| 1304 | - cols_then_rows[c], | ||
| 1305 | - cols_then_rows[4 + c], | ||
| 1306 | - cols_then_rows[8 + c], | ||
| 1307 | - cols_then_rows[12 + c], | ||
| 1308 | - ); | ||
| 1309 | - cols_then_rows[c] = a; | ||
| 1310 | - cols_then_rows[4 + c] = b; | ||
| 1311 | - cols_then_rows[8 + c] = cc; | ||
| 1312 | - cols_then_rows[12 + c] = d; | ||
| 1313 | - } | ||
| 1314 | - for r in 0..4 { | ||
| 1315 | - let (a, b, c, d) = inv_1d( | ||
| 1316 | - cols_then_rows[r * 4], | ||
| 1317 | - cols_then_rows[r * 4 + 1], | ||
| 1318 | - cols_then_rows[r * 4 + 2], | ||
| 1319 | - cols_then_rows[r * 4 + 3], | ||
| 1320 | - ); | ||
| 1321 | - cols_then_rows[r * 4] = a; | ||
| 1322 | - cols_then_rows[r * 4 + 1] = b; | ||
| 1323 | - cols_then_rows[r * 4 + 2] = c; | ||
| 1324 | - cols_then_rows[r * 4 + 3] = d; | ||
| 1325 | - } | ||
| 1326 | - // The two orders genuinely differ on this block... | ||
| 1327 | - assert_ne!(rows_then_cols, cols_then_rows); | ||
| 1328 | - // ...and inverse_core (plus the +32>>6 normalization) follows rows-first. | ||
| 1329 | - let expected: [i32; 16] = | ||
| 1330 | - core::array::from_fn(|k| (rows_then_cols[k] + 32) >> 6); | ||
| 1331 | - assert_eq!(inverse_core(&coeffs), expected); | ||
| 1332 | - } | ||
| 1333 | - | ||
| 1334 | - #[test] | ||
| 1335 | - fn quant_dequant_roundtrip_is_near_identity() { | ||
| 1336 | - // For a range of QPs, a transformed-then-quantized-then-reconstructed | ||
| 1337 | - // residual should stay within the quantization step of the original. | ||
| 1338 | - let residual: [i32; 16] = [ | ||
| 1339 | - 5, -3, 8, 0, 12, -7, 2, 1, -4, 6, 9, -2, 0, 3, -1, 7, | ||
| 1340 | - ]; | ||
| 1341 | - for qp in [0u8, 6, 12, 18, 26, 30, 37, 45, 51] { | ||
| 1342 | - let levels = forward_quant(&residual, qp, true); | ||
| 1343 | - let recon = inverse_quant(&levels, qp); | ||
| 1344 | - // Tolerance grows with the quant step (~ 2^(qp/6)). | ||
| 1345 | - let tol = 2 + (1 << (qp / 6)); | ||
| 1346 | - for k in 0..16 { | ||
| 1347 | - let diff = (recon[k] - residual[k]).abs(); | ||
| 1348 | - assert!( | ||
| 1349 | - diff <= tol, | ||
| 1350 | - "qp {qp}: residual[{k}]={} recon={} diff={diff} tol={tol}", | ||
| 1351 | - residual[k], | ||
| 1352 | - recon[k] | ||
| 1353 | - ); | ||
| 1354 | - } | ||
| 1355 | - } | ||
| 1356 | - } | ||
| 1357 | - | ||
| 1358 | - #[test] | ||
| 1359 | - fn trellis_never_exceeds_scalar_magnitude() { | ||
| 1360 | - // Trellis only considers the scalar level or lower, so |level| never | ||
| 1361 | - // grows, and a large λ drives marginal coefficients toward zero. | ||
| 1362 | - let coeffs: [i32; 16] = [120, -40, 8, 1, -15, 6, -1, 0, 3, -2, 1, 0, 0, 1, 0, 0]; | ||
| 1363 | - let scalar = quantize(&coeffs, 26, 3); | ||
| 1364 | - let t = trellis_quant(&coeffs, 26, true, 50.0); | ||
| 1365 | - for k in 0..16 { | ||
| 1366 | - assert!(t[k].unsigned_abs() <= scalar[k].unsigned_abs(), "[{k}]"); | ||
| 1367 | - assert!(t[k] == 0 || t[k].signum() == scalar[k].signum()); | ||
| 1368 | - } | ||
| 1369 | - } | ||
| 1370 | - | ||
| 1371 | - #[test] | ||
| 1372 | - fn zero_residual_stays_zero() { | ||
| 1373 | - let zero = [0i32; 16]; | ||
| 1374 | - let levels = forward_quant(&zero, 28, true); | ||
| 1375 | - assert_eq!(levels, [0i32; 16]); | ||
| 1376 | - assert_eq!(inverse_quant(&levels, 28), [0i32; 16]); | ||
| 1377 | - } | ||
| 1378 | - | ||
| 1379 | - #[test] | ||
| 1380 | - fn luma_dc_end_to_end_flat_block() { | ||
| 1381 | - // A flat luma residual `r`: each 4×4 block's forward-core DC is 16*r and | ||
| 1382 | - // its AC is 0. Coding the 16 DCs via the secondary transform and | ||
| 1383 | - // reconstructing (scatter DC → inverse core) must recover ~r per sample. | ||
| 1384 | - for r in [3i32, 9, -5, 20] { | ||
| 1385 | - for qp in [0u8, 12, 24, 30] { | ||
| 1386 | - let w_dc = [16 * r; 16]; // forward-core DC of a flat block | ||
| 1387 | - let z = forward_quant_luma_dc(&w_dc, qp, true); | ||
| 1388 | - let dcy = inverse_quant_luma_dc(&z, qp); | ||
| 1389 | - let tol = 1 + (1 << (qp / 6)); | ||
| 1390 | - for (b, &dc) in dcy.iter().enumerate() { | ||
| 1391 | - let mut coeff = [0i32; 16]; | ||
| 1392 | - coeff[0] = dc; | ||
| 1393 | - let res = inverse_core(&coeff); | ||
| 1394 | - for &v in &res { | ||
| 1395 | - assert!((v - r).abs() <= tol, "luma DC r={r} qp{qp} blk{b}: {v} vs {r}"); | ||
| 1396 | - } | ||
| 1397 | - } | ||
| 1398 | - } | ||
| 1399 | - } | ||
| 1400 | - } | ||
| 1401 | - | ||
| 1402 | - #[test] | ||
| 1403 | - fn chroma_dc_end_to_end_flat_block() { | ||
| 1404 | - // Same idea for the 2×2 chroma DC secondary transform. | ||
| 1405 | - for r in [4i32, -6, 11] { | ||
| 1406 | - for qp in [0u8, 18, 30] { | ||
| 1407 | - let dc = [16 * r; 4]; | ||
| 1408 | - let z = forward_quant_chroma_dc(&dc, qp, true); | ||
| 1409 | - let dcy = inverse_quant_chroma_dc(&z, qp); | ||
| 1410 | - let tol = 1 + (1 << (qp / 6)); | ||
| 1411 | - for &d in &dcy { | ||
| 1412 | - let mut coeff = [0i32; 16]; | ||
| 1413 | - coeff[0] = d; | ||
| 1414 | - let res = inverse_core(&coeff); | ||
| 1415 | - for &v in &res { | ||
| 1416 | - assert!((v - r).abs() <= tol, "chroma DC r={r} qp{qp}: {v} vs {r}"); | ||
| 1417 | - } | ||
| 1418 | - } | ||
| 1419 | - } | ||
| 1420 | - } | ||
| 1421 | - } | ||
| 1422 | - | ||
| 1423 | - #[test] | ||
| 1424 | - fn hadamard_is_self_inverse_scaled() { | ||
| 1425 | - // Applying the 4×4 Hadamard twice scales by 16. | ||
| 1426 | - let x: [i32; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; | ||
| 1427 | - let twice = hadamard_4x4(&hadamard_4x4(&x)); | ||
| 1428 | - for (k, (&a, &b)) in x.iter().zip(twice.iter()).enumerate() { | ||
| 1429 | - assert_eq!(b, a * 16, "[{k}]"); | ||
| 1430 | - } | ||
| 1431 | - } | ||
| 1432 | - | ||
| 1433 | - #[test] | ||
| 1434 | - fn low_qp_is_high_fidelity() { | ||
| 1435 | - // At QP 0 the reconstruction should be essentially exact for small | ||
| 1436 | - // integer residuals. | ||
| 1437 | - let residual: [i32; 16] = [1, 2, 3, 4, -1, -2, -3, -4, 0, 1, 0, -1, 2, -2, 1, 0]; | ||
| 1438 | - let levels = forward_quant(&residual, 0, true); | ||
| 1439 | - let recon = inverse_quant(&levels, 0); | ||
| 1440 | - for (k, (&r, &o)) in residual.iter().zip(recon.iter()).enumerate() { | ||
| 1441 | - assert!((o - r).abs() <= 1, "qp0 residual[{k}]={r} recon={o}"); | ||
| 1442 | - } | ||
| 1443 | - } | ||
| 1444 | -} | ||
| 1445 | - | ||
| 1446 | -// openh264 BSD-2 quant tables (g_kiQuantMF[52][8], g_kiQuantInterFF[58][8]). | ||
| 1447 | -pub const QUANT_MF_OH: [[i16; 8]; 52] = [ | ||
| 1448 | - [26214, 16132, 26214, 16132, 16132, 10486, 16132, 10486], | ||
| 1449 | - [23832, 14980, 23832, 14980, 14980, 9320, 14980, 9320], | ||
| 1450 | - [20164, 13108, 20164, 13108, 13108, 8388, 13108, 8388], | ||
| 1451 | - [18724, 11650, 18724, 11650, 11650, 7294, 11650, 7294], | ||
| 1452 | - [16384, 10486, 16384, 10486, 10486, 6710, 10486, 6710], | ||
| 1453 | - [14564, 9118, 14564, 9118, 9118, 5786, 9118, 5786], | ||
| 1454 | - [13107, 8066, 13107, 8066, 8066, 5243, 8066, 5243], | ||
| 1455 | - [11916, 7490, 11916, 7490, 7490, 4660, 7490, 4660], | ||
| 1456 | - [10082, 6554, 10082, 6554, 6554, 4194, 6554, 4194], | ||
| 1457 | - [9362, 5825, 9362, 5825, 5825, 3647, 5825, 3647], | ||
| 1458 | - [8192, 5243, 8192, 5243, 5243, 3355, 5243, 3355], | ||
| 1459 | - [7282, 4559, 7282, 4559, 4559, 2893, 4559, 2893], | ||
| 1460 | - [6554, 4033, 6554, 4033, 4033, 2622, 4033, 2622], | ||
| 1461 | - [5958, 3745, 5958, 3745, 3745, 2330, 3745, 2330], | ||
| 1462 | - [5041, 3277, 5041, 3277, 3277, 2097, 3277, 2097], | ||
| 1463 | - [4681, 2913, 4681, 2913, 2913, 1824, 2913, 1824], | ||
| 1464 | - [4096, 2622, 4096, 2622, 2622, 1678, 2622, 1678], | ||
| 1465 | - [3641, 2280, 3641, 2280, 2280, 1447, 2280, 1447], | ||
| 1466 | - [3277, 2017, 3277, 2017, 2017, 1311, 2017, 1311], | ||
| 1467 | - [2979, 1873, 2979, 1873, 1873, 1165, 1873, 1165], | ||
| 1468 | - [2521, 1639, 2521, 1639, 1639, 1049, 1639, 1049], | ||
| 1469 | - [2341, 1456, 2341, 1456, 1456, 912, 1456, 912], | ||
| 1470 | - [2048, 1311, 2048, 1311, 1311, 839, 1311, 839], | ||
| 1471 | - [1821, 1140, 1821, 1140, 1140, 723, 1140, 723], | ||
| 1472 | - [1638, 1008, 1638, 1008, 1008, 655, 1008, 655], | ||
| 1473 | - [1490, 936, 1490, 936, 936, 583, 936, 583], | ||
| 1474 | - [1260, 819, 1260, 819, 819, 524, 819, 524], | ||
| 1475 | - [1170, 728, 1170, 728, 728, 456, 728, 456], | ||
| 1476 | - [1024, 655, 1024, 655, 655, 419, 655, 419], | ||
| 1477 | - [910, 570, 910, 570, 570, 362, 570, 362], | ||
| 1478 | - [819, 504, 819, 504, 504, 328, 504, 328], | ||
| 1479 | - [745, 468, 745, 468, 468, 291, 468, 291], | ||
| 1480 | - [630, 410, 630, 410, 410, 262, 410, 262], | ||
| 1481 | - [585, 364, 585, 364, 364, 228, 364, 228], | ||
| 1482 | - [512, 328, 512, 328, 328, 210, 328, 210], | ||
| 1483 | - [455, 285, 455, 285, 285, 181, 285, 181], | ||
| 1484 | - [410, 252, 410, 252, 252, 164, 252, 164], | ||
| 1485 | - [372, 234, 372, 234, 234, 146, 234, 146], | ||
| 1486 | - [315, 205, 315, 205, 205, 131, 205, 131], | ||
| 1487 | - [293, 182, 293, 182, 182, 114, 182, 114], | ||
| 1488 | - [256, 164, 256, 164, 164, 105, 164, 105], | ||
| 1489 | - [228, 142, 228, 142, 142, 90, 142, 90], | ||
| 1490 | - [205, 126, 205, 126, 126, 82, 126, 82], | ||
| 1491 | - [186, 117, 186, 117, 117, 73, 117, 73], | ||
| 1492 | - [158, 102, 158, 102, 102, 66, 102, 66], | ||
| 1493 | - [146, 91, 146, 91, 91, 57, 91, 57], | ||
| 1494 | - [128, 82, 128, 82, 82, 52, 82, 52], | ||
| 1495 | - [114, 71, 114, 71, 71, 45, 71, 45], | ||
| 1496 | - [102, 63, 102, 63, 63, 41, 63, 41], | ||
| 1497 | - [93, 59, 93, 59, 59, 36, 59, 36], | ||
| 1498 | - [79, 51, 79, 51, 51, 33, 51, 33], | ||
| 1499 | - [73, 46, 73, 46, 46, 28, 46, 28], | ||
| 1500 | -]; | ||
| 1501 | - | ||
| 1502 | -pub const QUANT_FF_OH: [[i16; 8]; 58] = [ | ||
| 1503 | - [0, 1, 0, 1, 1, 1, 1, 1], | ||
| 1504 | - [0, 1, 0, 1, 1, 1, 1, 1], | ||
| 1505 | - [1, 1, 1, 1, 1, 1, 1, 1], | ||
| 1506 | - [1, 1, 1, 1, 1, 1, 1, 1], | ||
| 1507 | - [1, 1, 1, 1, 1, 2, 1, 2], | ||
| 1508 | - [1, 1, 1, 1, 1, 2, 1, 2], | ||
| 1509 | - [1, 1, 1, 1, 1, 2, 1, 2], | ||
| 1510 | - [1, 1, 1, 1, 1, 2, 1, 2], | ||
| 1511 | - [1, 2, 1, 2, 2, 3, 2, 3], | ||
| 1512 | - [1, 2, 1, 2, 2, 3, 2, 3], | ||
| 1513 | - [1, 2, 1, 2, 2, 3, 2, 3], | ||
| 1514 | - [1, 2, 1, 2, 2, 4, 2, 4], | ||
| 1515 | - [2, 3, 2, 3, 3, 4, 3, 4], | ||
| 1516 | - [2, 3, 2, 3, 3, 5, 3, 5], | ||
| 1517 | - [2, 3, 2, 3, 3, 5, 3, 5], | ||
| 1518 | - [2, 4, 2, 4, 4, 6, 4, 6], | ||
| 1519 | - [3, 4, 3, 4, 4, 7, 4, 7], | ||
| 1520 | - [3, 5, 3, 5, 5, 8, 5, 8], | ||
| 1521 | - [3, 5, 3, 5, 5, 8, 5, 8], | ||
| 1522 | - [4, 6, 4, 6, 6, 9, 6, 9], | ||
| 1523 | - [4, 7, 4, 7, 7, 10, 7, 10], | ||
| 1524 | - [5, 8, 5, 8, 8, 12, 8, 12], | ||
| 1525 | - [5, 8, 5, 8, 8, 13, 8, 13], | ||
| 1526 | - [6, 10, 6, 10, 10, 15, 10, 15], | ||
| 1527 | - [7, 11, 7, 11, 11, 17, 11, 17], | ||
| 1528 | - [7, 12, 7, 12, 12, 19, 12, 19], | ||
| 1529 | - [9, 13, 9, 13, 13, 21, 13, 21], | ||
| 1530 | - [9, 15, 9, 15, 15, 24, 15, 24], | ||
| 1531 | - [11, 17, 11, 17, 17, 26, 17, 26], | ||
| 1532 | - [12, 19, 12, 19, 19, 30, 19, 30], | ||
| 1533 | - [13, 22, 13, 22, 22, 33, 22, 33], | ||
| 1534 | - [15, 23, 15, 23, 23, 38, 23, 38], | ||
| 1535 | - [17, 27, 17, 27, 27, 42, 27, 42], | ||
| 1536 | - [19, 30, 19, 30, 30, 48, 30, 48], | ||
| 1537 | - [21, 33, 21, 33, 33, 52, 33, 52], | ||
| 1538 | - [24, 38, 24, 38, 38, 60, 38, 60], | ||
| 1539 | - [27, 43, 27, 43, 43, 67, 43, 67], | ||
| 1540 | - [29, 47, 29, 47, 47, 75, 47, 75], | ||
| 1541 | - [35, 53, 35, 53, 53, 83, 53, 83], | ||
| 1542 | - [37, 60, 37, 60, 60, 96, 60, 96], | ||
| 1543 | - [43, 67, 43, 67, 67, 104, 67, 104], | ||
| 1544 | - [48, 77, 48, 77, 77, 121, 77, 121], | ||
| 1545 | - [53, 87, 53, 87, 87, 133, 87, 133], | ||
| 1546 | - [59, 93, 59, 93, 93, 150, 93, 150], | ||
| 1547 | - [69, 107, 69, 107, 107, 167, 107, 167], | ||
| 1548 | - [75, 120, 75, 120, 120, 192, 120, 192], | ||
| 1549 | - [85, 133, 85, 133, 133, 208, 133, 208], | ||
| 1550 | - [96, 153, 96, 153, 153, 242, 153, 242], | ||
| 1551 | - [107, 173, 107, 173, 173, 267, 173, 267], | ||
| 1552 | - [117, 187, 117, 187, 187, 300, 187, 300], | ||
| 1553 | - [139, 213, 139, 213, 213, 333, 213, 333], | ||
| 1554 | - [149, 240, 149, 240, 240, 383, 240, 383], | ||
| 1555 | - [171, 267, 171, 267, 267, 417, 267, 417], | ||
| 1556 | - [192, 307, 192, 307, 307, 483, 307, 483], | ||
| 1557 | - [213, 347, 213, 347, 347, 533, 347, 533], | ||
| 1558 | - [235, 373, 235, 373, 373, 600, 373, 600], | ||
| 1559 | - [277, 427, 277, 427, 427, 667, 427, 667], | ||
| 1560 | - [299, 480, 299, 480, 480, 767, 480, 767], | ||
| 1561 | -]; | ||
vendor/rusty_h264-common/src/types.rsdeleted+0 -97
| @@ -1,97 +0,0 @@ | |||
| 1 | -//! Shared codec types: profiles, chroma format, and the raw YUV frame container. | ||
| 2 | - | ||
| 3 | -/// H.264 profile. The encoder targets Constrained Baseline; the rest are named | ||
| 4 | -/// for parsing/identification only. | ||
| 5 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 6 | -pub enum Profile { | ||
| 7 | - /// Constrained Baseline (`profile_idc = 66` with `constraint_set1_flag`). | ||
| 8 | - ConstrainedBaseline, | ||
| 9 | - /// Baseline (`profile_idc = 66`). | ||
| 10 | - Baseline, | ||
| 11 | - /// Main (`profile_idc = 77`). | ||
| 12 | - Main, | ||
| 13 | - /// High (`profile_idc = 100`). | ||
| 14 | - High, | ||
| 15 | - /// Any other `profile_idc`. | ||
| 16 | - Other(u8), | ||
| 17 | -} | ||
| 18 | - | ||
| 19 | -impl Profile { | ||
| 20 | - /// The `profile_idc` byte written into the SPS. | ||
| 21 | - pub fn profile_idc(self) -> u8 { | ||
| 22 | - match self { | ||
| 23 | - Profile::ConstrainedBaseline | Profile::Baseline => 66, | ||
| 24 | - Profile::Main => 77, | ||
| 25 | - Profile::High => 100, | ||
| 26 | - Profile::Other(v) => v, | ||
| 27 | - } | ||
| 28 | - } | ||
| 29 | -} | ||
| 30 | - | ||
| 31 | -/// Chroma subsampling. The encoder supports 4:2:0 only for now. | ||
| 32 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 33 | -pub enum ChromaFormat { | ||
| 34 | - /// Monochrome (`chroma_format_idc = 0`). | ||
| 35 | - Monochrome, | ||
| 36 | - /// 4:2:0 (`chroma_format_idc = 1`). | ||
| 37 | - Yuv420, | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -impl ChromaFormat { | ||
| 41 | - /// `chroma_format_idc`. | ||
| 42 | - pub fn idc(self) -> u8 { | ||
| 43 | - match self { | ||
| 44 | - ChromaFormat::Monochrome => 0, | ||
| 45 | - ChromaFormat::Yuv420 => 1, | ||
| 46 | - } | ||
| 47 | - } | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | -/// A raw planar YUV 4:2:0 frame (8-bit). Plane strides equal their widths; | ||
| 51 | -/// chroma planes are half-resolution in each dimension. | ||
| 52 | -#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 53 | -pub struct YuvFrame { | ||
| 54 | - /// Luma width in pixels. | ||
| 55 | - pub width: usize, | ||
| 56 | - /// Luma height in pixels. | ||
| 57 | - pub height: usize, | ||
| 58 | - /// Y plane, `width * height` bytes. | ||
| 59 | - pub y: Vec<u8>, | ||
| 60 | - /// Cb plane, `(width/2) * (height/2)` bytes. | ||
| 61 | - pub u: Vec<u8>, | ||
| 62 | - /// Cr plane, `(width/2) * (height/2)` bytes. | ||
| 63 | - pub v: Vec<u8>, | ||
| 64 | -} | ||
| 65 | - | ||
| 66 | -impl YuvFrame { | ||
| 67 | - /// Allocates a black (Y=0, U=V=128) frame. Dimensions must be even. | ||
| 68 | - pub fn black(width: usize, height: usize) -> Self { | ||
| 69 | - assert!(width % 2 == 0 && height % 2 == 0, "dimensions must be even"); | ||
| 70 | - let cw = width / 2; | ||
| 71 | - let ch = height / 2; | ||
| 72 | - Self { | ||
| 73 | - width, | ||
| 74 | - height, | ||
| 75 | - y: vec![0; width * height], | ||
| 76 | - u: vec![128; cw * ch], | ||
| 77 | - v: vec![128; cw * ch], | ||
| 78 | - } | ||
| 79 | - } | ||
| 80 | - | ||
| 81 | - /// Chroma plane width. | ||
| 82 | - pub fn chroma_width(&self) -> usize { | ||
| 83 | - self.width / 2 | ||
| 84 | - } | ||
| 85 | - | ||
| 86 | - /// Chroma plane height. | ||
| 87 | - pub fn chroma_height(&self) -> usize { | ||
| 88 | - self.height / 2 | ||
| 89 | - } | ||
| 90 | - | ||
| 91 | - /// Validates plane sizes against the dimensions. | ||
| 92 | - pub fn is_valid(&self) -> bool { | ||
| 93 | - self.y.len() == self.width * self.height | ||
| 94 | - && self.u.len() == self.chroma_width() * self.chroma_height() | ||
| 95 | - && self.v.len() == self.chroma_width() * self.chroma_height() | ||
| 96 | - } | ||
| 97 | -} | ||