forge
Explore
Log in

Don't you dare go Hollow

S8: encoder analysis heuristics (mean_gradient, chroma offset, fast knobs, lambda) move to enc/analysis.rs

Browse files at this commit

ad62b2306bba3fa5c544a28f68453a47feacd67dAhmet Kaan GümüşParent: 2a9d5ea
crates/ec-h264/src/enc/analysis.rsadded+141 -0
@@ -0,0 +1,141 @@
1+use super::mb;
2+use super::mb::Source;
3+
4+/// Everything one band worker needs.
5+/// Mean absolute neighbour difference of one plane, horizontal and vertical
6+/// averaged, over the `w` by `h` samples at the top left of `plane`.
7+pub(super) fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 {
8+ let (mut sum, mut n) = (0u64, 0u64);
9+ for y in 0..h {
10+ let row = &plane[y * stride..y * stride + w];
11+ for x in 1..w {
12+ sum += u64::from(row[x].abs_diff(row[x - 1]));
13+ n += 1;
14+ }
15+ if y > 0 {
16+ let prev = &plane[(y - 1) * stride..(y - 1) * stride + w];
17+ for x in 0..w {
18+ sum += u64::from(row[x].abs_diff(prev[x]));
19+ n += 1;
20+ }
21+ }
22+ }
23+ if n == 0 { 0.0 } else { sum as f64 / n as f64 }
24+}
25+
26+/// `chroma_qp_index_offset` for a source, from how textured its chroma is
27+/// relative to its luma.
28+///
29+/// A negative offset spends bits on chroma that luma would otherwise take.
30+/// That pays when the chroma planes are flat — screen capture, phone video,
31+/// anything with large constant-hue areas — because their few edges are what
32+/// the eye reads, and it loses on film, whose chroma carries as much detail as
33+/// its luma and whose luma is the better place for the same bits. The
34+/// separating statistic is the mean absolute sample gradient of the chroma
35+/// planes over that of luma, measured on the first source picture.
36+/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over
37+/// nine clips of the user's library, offset 0 against offset -2:
38+///
39+/// ```text
40+/// chroma/luma gradient 0 -> -2 (dB)
41+/// 0.013 +0.019
42+/// 0.092 +0.181
43+/// 0.094 +0.228
44+/// 0.098 +0.014
45+/// 0.118 +0.081
46+/// 0.122 +0.045
47+/// 0.128 +0.065
48+/// 0.286 +0.011
49+/// 0.911 -0.158
50+/// ```
51+///
52+/// Every clip whose chroma is flatter than its luma gains; the one film clip,
53+/// whose chroma gradient is nearly its luma's, loses. The threshold sits in
54+/// the middle of the gap the data leaves.
55+pub(super) fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 {
56+ let (w, h) = (width as usize, height as usize);
57+ let (cw, ch) = (w / 2, h / 2);
58+ let luma = mean_gradient(&src.y, src.stride, w, h);
59+ if luma <= 0.0 {
60+ return 0;
61+ }
62+ let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch)
63+ + mean_gradient(&src.v, src.c_stride, cw, ch))
64+ / 2.0;
65+ if chroma / luma < CHROMA_FLAT_RATIO {
66+ CHROMA_FLAT_QP_OFFSET
67+ } else {
68+ 0
69+ }
70+}
71+
72+/// Chroma is "flat" below this share of the luma gradient.
73+pub(super) const CHROMA_FLAT_RATIO: f64 = 0.5;
74+
75+/// The offset flat chroma is coded with.
76+pub(super) const CHROMA_FLAT_QP_OFFSET: i32 = -2;
77+
78+/// The Fast-preset speed settings: the defaults, with `EC_H264_INTRA_GATE`
79+/// (a number) and `EC_H264_SKIP_I8` (any value but 0 skips Intra_8x8) as
80+/// sweep overrides. Read once per band, so they cost nothing per macroblock.
81+pub(super) fn fast_knobs() -> mb::FastKnobs {
82+ let mut k = mb::FastKnobs::default();
83+ if let Some(g) = std::env::var("EC_H264_INTRA_GATE")
84+ .ok()
85+ .and_then(|v| v.parse().ok())
86+ {
87+ k.intra_gate = g;
88+ }
89+ if let Ok(v) = std::env::var("EC_H264_SKIP_I8") {
90+ k.skip_i8 = v != "0";
91+ }
92+ if let Some(v) = std::env::var("EC_H264_ME_SUB")
93+ .ok()
94+ .and_then(|v| v.parse().ok())
95+ {
96+ k.me_sub = v;
97+ }
98+ if let Ok(v) = std::env::var("EC_H264_ME_SATD") {
99+ k.me_satd = v != "0";
100+ }
101+ if let Some(v) = std::env::var("EC_H264_INTER_TX")
102+ .ok()
103+ .and_then(|v| v.parse().ok())
104+ {
105+ k.inter_tx = v;
106+ }
107+ if let Ok(v) = std::env::var("EC_H264_LAZY_I16") {
108+ k.lazy_i16 = v != "0";
109+ }
110+ if let Some(v) = std::env::var("EC_H264_EARLY_SKIP")
111+ .ok()
112+ .and_then(|v| v.parse().ok())
113+ {
114+ k.early_skip = v;
115+ }
116+ if let Some(v) = std::env::var("EC_H264_TX8_NZ")
117+ .ok()
118+ .and_then(|v| v.parse().ok())
119+ {
120+ k.tx8_nz_limit = v;
121+ }
122+ if let Ok(v) = std::env::var("EC_H264_P_SKIP_I8") {
123+ k.p_skip_i8 = v != "0";
124+ }
125+ k
126+}
127+
128+/// Standard Lagrangian multiplier in the squared-error domain.
129+pub(crate) fn lambda_ssd(qp: i32) -> f64 {
130+ 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
131+}
132+
133+/// Lagrangian multiplier. Production uses the established byte-stable ladder;
134+/// the ablation feature can select the standard squared-error multiplier.
135+pub(super) fn lambda_for(qp: i32, standard: bool) -> f64 {
136+ if standard {
137+ lambda_ssd(qp)
138+ } else {
139+ (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0)
140+ }
141+}
crates/ec-h264/src/enc/mod.rsmodified+3 -139
@@ -20,6 +20,7 @@
20 //! once over the whole picture, across slice boundaries exactly as a decoder20 //! once over the whole picture, across slice boundaries exactly as a decoder
21 //! runs it. No `unsafe`, no shared mutable state at all.21 //! runs it. No `unsafe`, no shared mutable state at all.
22 22
23+mod analysis;
23 mod cabac_enc;24 mod cabac_enc;
24 mod entropy;25 mod entropy;
25 mod headers;26 mod headers;
@@ -41,6 +42,7 @@ use crate::transform::{LevelScale4x4, LevelScale8x8};
41 42
42 use entropy::EncEntropy;43 use entropy::EncEntropy;
43 use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};44 use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};
45+use analysis::{chroma_qp_offset_for_source, fast_knobs, lambda_for, lambda_ssd};
44 use mb::{MbEnc, Source, encode_mb};46 use mb::{MbEnc, Source, encode_mb};
45 use pool::BandPool;47 use pool::BandPool;
46 use rc::RateControl;48 use rc::RateControl;
@@ -512,80 +514,6 @@ impl Encoder {
512 }514 }
513 }515 }
514 516
515-/// Everything one band worker needs.
516-/// Mean absolute neighbour difference of one plane, horizontal and vertical
517-/// averaged, over the `w` by `h` samples at the top left of `plane`.
518-fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 {
519- let (mut sum, mut n) = (0u64, 0u64);
520- for y in 0..h {
521- let row = &plane[y * stride..y * stride + w];
522- for x in 1..w {
523- sum += u64::from(row[x].abs_diff(row[x - 1]));
524- n += 1;
525- }
526- if y > 0 {
527- let prev = &plane[(y - 1) * stride..(y - 1) * stride + w];
528- for x in 0..w {
529- sum += u64::from(row[x].abs_diff(prev[x]));
530- n += 1;
531- }
532- }
533- }
534- if n == 0 { 0.0 } else { sum as f64 / n as f64 }
535-}
536-
537-/// `chroma_qp_index_offset` for a source, from how textured its chroma is
538-/// relative to its luma.
539-///
540-/// A negative offset spends bits on chroma that luma would otherwise take.
541-/// That pays when the chroma planes are flat — screen capture, phone video,
542-/// anything with large constant-hue areas — because their few edges are what
543-/// the eye reads, and it loses on film, whose chroma carries as much detail as
544-/// its luma and whose luma is the better place for the same bits. The
545-/// separating statistic is the mean absolute sample gradient of the chroma
546-/// planes over that of luma, measured on the first source picture.
547-/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over
548-/// nine clips of the user's library, offset 0 against offset -2:
549-///
550-/// ```text
551-/// chroma/luma gradient 0 -> -2 (dB)
552-/// 0.013 +0.019
553-/// 0.092 +0.181
554-/// 0.094 +0.228
555-/// 0.098 +0.014
556-/// 0.118 +0.081
557-/// 0.122 +0.045
558-/// 0.128 +0.065
559-/// 0.286 +0.011
560-/// 0.911 -0.158
561-/// ```
562-///
563-/// Every clip whose chroma is flatter than its luma gains; the one film clip,
564-/// whose chroma gradient is nearly its luma's, loses. The threshold sits in
565-/// the middle of the gap the data leaves.
566-fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 {
567- let (w, h) = (width as usize, height as usize);
568- let (cw, ch) = (w / 2, h / 2);
569- let luma = mean_gradient(&src.y, src.stride, w, h);
570- if luma <= 0.0 {
571- return 0;
572- }
573- let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch)
574- + mean_gradient(&src.v, src.c_stride, cw, ch))
575- / 2.0;
576- if chroma / luma < CHROMA_FLAT_RATIO {
577- CHROMA_FLAT_QP_OFFSET
578- } else {
579- 0
580- }
581-}
582-
583-/// Chroma is "flat" below this share of the luma gradient.
584-const CHROMA_FLAT_RATIO: f64 = 0.5;
585-
586-/// The offset flat chroma is coded with.
587-const CHROMA_FLAT_QP_OFFSET: i32 = -2;
588-
589 /// What every band of one picture reads. The workers share it through an `Arc`.517 /// What every band of one picture reads. The workers share it through an `Arc`.
590 struct FrameShared {518 struct FrameShared {
591 sps: Sps,519 sps: Sps,
@@ -740,71 +668,6 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
740 w.finish(job.slice_type == SliceType::P)668 w.finish(job.slice_type == SliceType::P)
741 }669 }
742 670
743-/// The Fast-preset speed settings: the defaults, with `EC_H264_INTRA_GATE`
744-/// (a number) and `EC_H264_SKIP_I8` (any value but 0 skips Intra_8x8) as
745-/// sweep overrides. Read once per band, so they cost nothing per macroblock.
746-fn fast_knobs() -> mb::FastKnobs {
747- let mut k = mb::FastKnobs::default();
748- if let Some(g) = std::env::var("EC_H264_INTRA_GATE")
749- .ok()
750- .and_then(|v| v.parse().ok())
751- {
752- k.intra_gate = g;
753- }
754- if let Ok(v) = std::env::var("EC_H264_SKIP_I8") {
755- k.skip_i8 = v != "0";
756- }
757- if let Some(v) = std::env::var("EC_H264_ME_SUB")
758- .ok()
759- .and_then(|v| v.parse().ok())
760- {
761- k.me_sub = v;
762- }
763- if let Ok(v) = std::env::var("EC_H264_ME_SATD") {
764- k.me_satd = v != "0";
765- }
766- if let Some(v) = std::env::var("EC_H264_INTER_TX")
767- .ok()
768- .and_then(|v| v.parse().ok())
769- {
770- k.inter_tx = v;
771- }
772- if let Ok(v) = std::env::var("EC_H264_LAZY_I16") {
773- k.lazy_i16 = v != "0";
774- }
775- if let Some(v) = std::env::var("EC_H264_EARLY_SKIP")
776- .ok()
777- .and_then(|v| v.parse().ok())
778- {
779- k.early_skip = v;
780- }
781- if let Some(v) = std::env::var("EC_H264_TX8_NZ")
782- .ok()
783- .and_then(|v| v.parse().ok())
784- {
785- k.tx8_nz_limit = v;
786- }
787- if let Ok(v) = std::env::var("EC_H264_P_SKIP_I8") {
788- k.p_skip_i8 = v != "0";
789- }
790- k
791-}
792-
793-/// Standard Lagrangian multiplier in the squared-error domain.
794-pub(crate) fn lambda_ssd(qp: i32) -> f64 {
795- 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
796-}
797-
798-/// Lagrangian multiplier. Production uses the established byte-stable ladder;
799-/// the ablation feature can select the standard squared-error multiplier.
800-fn lambda_for(qp: i32, standard: bool) -> f64 {
801- if standard {
802- lambda_ssd(qp)
803- } else {
804- (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0)
805- }
806-}
807-
808 /// Split `mb_h` macroblock rows into at most `n` contiguous bands.671 /// Split `mb_h` macroblock rows into at most `n` contiguous bands.
809 fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> {672 fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> {
810 let n = n.clamp(1, mb_h);673 let n = n.clamp(1, mb_h);
@@ -927,6 +790,7 @@ fn rational_timing(fps: f64) -> (u32, u32) {
927 #[cfg(test)]790 #[cfg(test)]
928 mod tests {791 mod tests {
929 use super::*;792 use super::*;
793+ use super::analysis::CHROMA_FLAT_QP_OFFSET;
930 794
931 #[test]795 #[test]
932 fn bands_cover_every_row_once() {796 fn bands_cover_every_row_once() {