Skip to main content

kallo_core/
meter.rs

1//! Metering: where a frame's exposure is, and how far it is from where the film
2//! expects it.
3//!
4//! The input is a linear-light image on the scale "1.0 is white". That scale is
5//! enough for a frame that is already exposed the way the model assumes — 18 %
6//! grey is at `log10(0.18)` by definition — but not for one whose scale is
7//! unknown, which is most inputs: a camera RAW developed to a float TIFF is
8//! normalised to its own white point, and how much light that white point
9//! corresponds to is not in the file.
10//!
11//! The oldest rule in photography recovers the missing scale from the frame
12//! itself: the average scene reflects 18 % of the light falling on it. An
13//! averaging exposure meter and a laboratory's average printer both rest on
14//! that assumption; this module is the same rule, solved in closed form
15//! instead of by a test strip.
16//!
17//! # What it does not do
18//!
19//! It is an *averaging* meter, not an evaluative one. A frame whose average is
20//! not 18 % — a night street, a snowfield, a snowfield at night — is metered to
21//! 18 % anyway, exactly as the hardware would. That is a property of the rule,
22//! not a defect to be tuned away: pass a fixed `--ev` when the scene's key
23//! differs from the average, which is what a photographer's exposure
24//! compensation dial is for.
25
26use crate::pipeline::mid_grey_log_e;
27
28/// The luminance weights of Rec. 709, which is the space the input is in.
29///
30/// The channels are *not* averaged equally: pure red is 21 % of white's
31/// luminance, not 33 %, and a frame of redness is not a bright frame.
32const LUMA: [f64; 3] = [0.2126, 0.7152, 0.0722];
33
34/// What an averaging meter reads of a frame, and the offset that follows.
35#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct Metering {
37    /// Mean luminance of the frame, in linear light.
38    ///
39    /// Zero for a frame with no light at all, and for an empty one.
40    pub key: f64,
41    /// Exposure offset in stops that puts `key` on mid grey.
42    ///
43    /// Zero when the frame is already mid grey, and zero when it carries no
44    /// light to meter: a black frame has no exposure to recover, so the meter
45    /// says nothing rather than everything.
46    pub ev: f64,
47}
48
49impl Metering {
50    /// Meter a row-major frame.
51    ///
52    /// The mean is taken over every pixel and weighed by luminance. It is
53    /// arithmetic in linear light, not in log: the average printer integrates
54    /// transmittance, and a frame that is half black and half white integrates
55    /// to 0.5, not to the geometric mean.
56    #[must_use]
57    pub fn of(pixels: &[[f64; 3]]) -> Self {
58        if pixels.is_empty() {
59            return Self { key: 0.0, ev: 0.0 };
60        }
61
62        let mut sum = 0.0;
63        for pixel in pixels {
64            // A decoded image should not be negative or NaN, but a meter is the
65            // wrong place to discover it: `max` clamps the first and turns the
66            // second into black, and the finite check keeps an infinity out.
67            let value = LUMA[0] * pixel[0].max(0.0)
68                + LUMA[1] * pixel[1].max(0.0)
69                + LUMA[2] * pixel[2].max(0.0);
70            if value.is_finite() {
71                sum += value;
72            }
73        }
74        let key = sum / pixels.len() as f64;
75
76        Self {
77            key,
78            ev: offset_for(key),
79        }
80    }
81}
82
83/// The offset in stops from a frame's key to the film's mid-grey exposure.
84///
85/// Defined as the solve `key · 2^ev = 0.18`, written in the module's own
86/// currency of decades instead of duplicating the constant.
87#[must_use]
88pub fn offset_for(key: f64) -> f64 {
89    if !key.is_finite() || key <= 0.0 {
90        return 0.0;
91    }
92    (mid_grey_log_e() - key.log10()) / 2.0_f64.log10()
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn a_frame_of_mid_grey_needs_no_offset() {
101        let metered = Metering::of(&[[0.18; 3]; 64]);
102        assert!((metered.key - 0.18).abs() < 1e-12, "{}", metered.key);
103        assert!(metered.ev.abs() < 1e-9, "{}", metered.ev);
104    }
105
106    #[test]
107    fn a_frame_two_stops_dark_is_lifted_by_two() {
108        // A quarter of 18 % is two stops down.
109        let metered = Metering::of(&[[0.045; 3]; 64]);
110        assert!((metered.ev - 2.0).abs() < 1e-9, "{}", metered.ev);
111    }
112
113    #[test]
114    fn a_frame_with_no_light_gets_no_offset() {
115        // Nothing to meter: an infinite offset would be a claim about a frame
116        // that carries no information.
117        let metered = Metering::of(&[[0.0; 3]; 16]);
118        assert_eq!(metered.key, 0.0);
119        assert_eq!(metered.ev, 0.0);
120    }
121
122    #[test]
123    fn an_empty_frame_is_not_a_division_by_zero() {
124        assert_eq!(Metering::of(&[]), Metering { key: 0.0, ev: 0.0 });
125    }
126
127    #[test]
128    fn the_meter_weighs_the_channels_as_luminance() {
129        // Pure red is 21 % of white to the eye. A meter that averaged the three
130        // channels would call it 33 % and expose it two-thirds of a stop down.
131        let metered = Metering::of(&[[1.0, 0.0, 0.0]]);
132        assert!((metered.key - LUMA[0]).abs() < 1e-12, "{}", metered.key);
133    }
134
135    #[test]
136    fn the_offset_lands_the_key_on_mid_grey() {
137        // The definition of the solve, over the range a frame can occupy.
138        for key in [1e-3, 0.02, 0.18, 0.9] {
139            let metered = Metering::of(&[[key; 3]]);
140            let landed = key * 2.0_f64.powf(metered.ev);
141            assert!((landed - 0.18).abs() < 1e-9, "{key} landed at {landed}");
142        }
143    }
144
145    #[test]
146    fn the_mean_is_arithmetic_not_geometric() {
147        // Half black and half white: the average printer integrates light, so
148        // this frame's key is 0.5 — two stops above mid grey — not the
149        // geometric mean of nothing.
150        let mut pixels = vec![[0.0; 3]; 8];
151        pixels.extend(std::iter::repeat_n([1.0; 3], 8));
152        let metered = Metering::of(&pixels);
153        assert!((metered.key - 0.5).abs() < 1e-12, "{}", metered.key);
154        assert!((metered.ev + 1.4739).abs() < 1e-3, "{}", metered.ev);
155    }
156
157    #[test]
158    fn negatives_and_nonsense_do_not_poison_the_mean() {
159        let mut pixels = vec![[0.18; 3]; 4];
160        pixels.push([-1.0, -1.0, -1.0]);
161        pixels.push([f64::NAN, f64::NAN, f64::NAN]);
162        let metered = Metering::of(&pixels);
163        // The negative clamps to black and the NaN is dropped, so the mean is
164        // four mid-grey pixels over six: the meter does not invent light.
165        assert!((metered.key - 0.12).abs() < 1e-12, "{}", metered.key);
166    }
167}