Skip to main content

kallo_core/
halation.rs

1//! Halation: the light that comes back.
2//!
3//! Light entering the emulsion does not all stop there. Some of it reaches the
4//! base, scatters, and reflects off the back surface — the film base, a glass
5//! carrier, the pressure plate — and returns into the emulsion to expose it a
6//! second time. Because the returning light is out of focus and has already
7//! crossed the layers once, the result is a **red-orange glow around bright
8//! highlights**, not a white one.
9//!
10//! Two components are modelled, both as energy-preserving kernels:
11//!
12//! - **scatter**, micrometres wide, roughly colour-neutral: a short-range
13//!   diffusion inside the emulsion;
14//! - **reflection**, tens of micrometres wide, strongly red: the light that went
15//!   all the way down and came back through the yellow filter layer and the
16//!   silver halide again.
17//!
18//! Each Gaussian kernel sums to one, so the blur moves light rather than
19//! creating it. The only place energy is added is `strength`: the fraction of
20//! the blurred exposure that returns to each layer. That energy is real — it is
21//! light that would otherwise have left the film through the back.
22//!
23//! Halation is applied to the **exposure**, before development, because that is
24//! where it happens: it is light exposing the emulsion, not a property of the
25//! developed image. That is why it runs before grain rather than after it.
26//!
27//! ## What is not modelled, and how it would be
28//!
29//! The **strengths** and the **scatter width** are placeholders. The red bias
30//! has the right *shape* — a double pass through the yellow filter layer cannot
31//! leave blue intact — but the numbers describe a modern colour negative in
32//! general, not this film.
33//!
34//! The reflection width is not a placeholder any more: it is the geometry of a
35//! 135 µm base and the aperture's cone, and [`Halation::reflection_radius_um`]
36//! computes it. At f/1.4 the halo reaches 62 µm across the film, at f/4 22 µm,
37//! at f/16 5.6 µm. The old fixed 30 µm was the wide-open case — not wrong,
38//! just always at f/1.4.
39//!
40//! There is no data sheet for this. It is a property of the film *in a camera* —
41//! base, anti-halation backing, pressure plate — and the only way to have it is
42//! to expose film to a controlled highlight and read the halo's falloff.
43//!
44//! One published measurement does exist, and it brackets these numbers. The ENS
45//! Louis Lumière mémoire (*Study of Film Texture*, 2023) measured halation from
46//! an edge-spread function and reports its "halation ratio" — the halo's level
47//! at 3–10 pixels from an edge, relative to the illuminated side — as
48//! **0.12–0.13 red, 0.066 green, 0.037 blue**. The placeholders here total
49//! 0.110 / 0.048 / 0.027, so they are 10–35 % low and in the right colour order.
50//! The two are not the same quantity — a ratio at a position is not a fraction of
51//! the source's energy — so that paper brackets these numbers rather than
52//! replacing them; what it does establish is that they are the right size.
53//!
54//! The experiment is designed in `docs/0011-halation-experiment.md`, with the two
55//! scripts that carry it out: `scripts/halo_profile.py` turns a scan into a
56//! radial profile, and `scripts/fit_halation.py` fits these eight numbers to it.
57//!
58//! Both have self-tests that run without a camera, and those already say what
59//! the measurement has to achieve. The fit separates the lens from the emulsion
60//! only if the lens's own point-spread function is measured to a few tenths of a
61//! micrometre — a 0.6 µm error doubles the reflection strength. And the blue
62//! layer's reflection, at 1.2 % of the highlight, is invisible at a single
63//! frame's scan noise: it needs a profile averaged to about 1e-3 of density.
64//!
65//! ## And the model is much sharper than a film
66//!
67//! Checking whether the data sheet's modulation-transfer curve could replace
68//! that experiment turned up something else: it cannot, because at these
69//! strengths halation only puts a floor under the response at 90 %, 95 % and
70//! 97 %, while the sheet draws 35 %, 28 % and 20 % at 90 cycles/mm. **Fifty to
71//! eighty points of that loss is the emulsion's own blur**, and there is no term
72//! here for it — a pixel rendered by this model is as sharp as the arithmetic
73//! that made it, where a real negative would already be soft. Halation is the
74//! only spatial effect the model has, and it is the smaller of the two.
75
76/// One halation component: how far the light spreads and how much returns.
77#[derive(Debug, Clone, Copy)]
78pub struct Halo {
79    /// Standard deviation of the spread on the film, in micrometres.
80    pub sigma_um: f64,
81    /// Fraction of the blurred exposure added back, per layer (R, G, B).
82    pub strength: [f64; 3],
83}
84
85/// Both halation components for one image, with its scale on the film.
86#[derive(Debug, Clone, Copy)]
87pub struct Halation {
88    /// Size of one pixel on the film, in micrometres across.
89    pub pixel_um: f64,
90    /// Diffusion inside the emulsion: short, and almost colour-neutral.
91    pub scatter: Halo,
92    /// Reflection off the base: long, and red by the time it returns.
93    pub reflection: Halo,
94}
95
96impl Halation {
97    /// Thickness of the film base, in millimetres.
98    ///
99    /// The halo's size follows from it and from nothing else that varies: a
100    /// photographic base is 0.125–0.135 mm across every manufacturer's sheet,
101    /// and 0.135 is the thick end.
102    pub const BASE_THICKNESS_MM: f64 = 0.135;
103
104    /// Refractive index of the base, which is what bends the returning cone.
105    pub const FILM_INDEX: f64 = 1.5;
106
107    /// How far the reflection halo reaches on the film, at a given aperture.
108    ///
109    /// The light that comes back travelled down through the base and up again,
110    /// so its cone is the lens's, refracted into the base and stretched over
111    /// twice 135 µm. The marginal ray outside is `atan(1/2N)`; inside it is
112    /// `asin(sin(θ)/n)`; the radius at the emulsion is `2B·tan` of that.
113    ///
114    /// There is no free parameter here, which is the point: the sigma was the
115    /// one number in this file that could be derived instead of guessed.
116    #[must_use]
117    pub fn reflection_radius_um(f_number: f64) -> f64 {
118        let outside = (1.0 / (2.0 * f_number.max(1e-3))).atan();
119        let inside = (outside.sin() / Self::FILM_INDEX).asin();
120        2.0 * Self::BASE_THICKNESS_MM * 1000.0 * inside.tan()
121    }
122
123    /// Both components for an exposure made at a particular aperture.
124    ///
125    /// `pixel_um` is the film-plane size of one pixel, so the kernels are
126    /// expressed in micrometres and do not change when the scan resolution does.
127    ///
128    /// The reflection halo's **width** now comes from the geometry; its
129    /// **strength**, and both of the scatter term's numbers, are still
130    /// placeholders — see the module documentation. A Gaussian of
131    /// `radius / 2` carries the same second moment as a disc of that radius,
132    /// which is as much as a geometry can say about the shape.
133    #[must_use]
134    pub fn for_aperture(pixel_um: f64, f_number: f64) -> Self {
135        Self {
136            pixel_um,
137            scatter: Halo {
138                sigma_um: 6.0,
139                strength: [0.020, 0.018, 0.015],
140            },
141            reflection: Halo {
142                sigma_um: 0.5 * Self::reflection_radius_um(f_number),
143                strength: [0.090, 0.030, 0.012],
144            },
145        }
146    }
147
148    /// The same, at a normal shooting aperture.
149    ///
150    /// f/4 rather than f/1.4: the old fixed 30 µm was the wide-open case for a
151    /// 135 µm base, which is where a lens that vignettes its corners stops
152    /// being a lens. The placeholder was not wrong so much as always wide open.
153    #[must_use]
154    pub fn typical(pixel_um: f64) -> Self {
155        Self::for_aperture(pixel_um, 4.0)
156    }
157
158    /// Whether either component would change anything.
159    #[must_use]
160    pub fn is_noop(&self) -> bool {
161        let inert =
162            |halo: &Halo| halo.sigma_um <= 0.0 || halo.strength.iter().all(|&value| value <= 0.0);
163        inert(&self.scatter) && inert(&self.reflection)
164    }
165
166    /// Apply halation to a buffer of log10 exposures, in place.
167    ///
168    /// `width * height` is read from the buffer; a buffer that is shorter than
169    /// the declared rectangle is processed only as far as it goes.
170    pub fn apply(&self, log_e: &mut [[f64; 3]], width: usize, height: usize) {
171        if self.is_noop() || width == 0 || height == 0 {
172            return;
173        }
174        let pixels = (width * height).min(log_e.len());
175        let height = pixels / width;
176        if height == 0 {
177            return;
178        }
179
180        // The light that reaches the base is what the scene threw at the film,
181        // not the density it produced, so the halo source is the incident
182        // exposure averaged over the layers.
183        let mut source = Vec::with_capacity(pixels);
184        for pixel in &log_e[..pixels] {
185            let sum: f64 = pixel.iter().map(|&value| 10.0_f64.powf(value)).sum();
186            source.push(sum / 3.0);
187        }
188
189        let scatter = self.halo_plane(&source, width, height, &self.scatter);
190        let reflection = self.halo_plane(&source, width, height, &self.reflection);
191
192        for (index, pixel) in log_e.iter_mut().enumerate().take(pixels) {
193            for (channel, value) in pixel.iter_mut().enumerate() {
194                let exposure = 10.0_f64.powf(*value).max(1e-10);
195                let added = self.scatter.strength[channel] * scatter[index]
196                    + self.reflection.strength[channel] * reflection[index];
197                // The halo is light, so it adds to the exposure and then goes
198                // back through the logarithm: a black area next to a highlight
199                // really does get exposed.
200                *value = (exposure + added).log10();
201            }
202        }
203    }
204
205    /// One component's blurred source plane, or zeros when inert.
206    fn halo_plane(&self, source: &[f64], width: usize, height: usize, halo: &Halo) -> Vec<f64> {
207        if halo.sigma_um <= 0.0 || halo.strength.iter().all(|&value| value <= 0.0) {
208            return vec![0.0; source.len()];
209        }
210        let sigma_px = halo.sigma_um / self.pixel_um.max(1e-9);
211        crate::psf::gaussian_blur(source, width, height, sigma_px)
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use crate::psf::gaussian_blur as blur;
219    use crate::psf::gaussian_kernel;
220
221    const W: usize = 64;
222    const H: usize = 64;
223
224    /// A black frame with one bright pixel in the middle.
225    fn highlight(log_e: f64) -> Vec<[f64; 3]> {
226        let mut buffer = vec![[-6.0; 3]; W * H];
227        buffer[(H / 2) * W + W / 2] = [log_e; 3];
228        buffer
229    }
230
231    /// The kernel moves light; it does not create it. A flat plane has to come
232    /// out flat and equal, or the blur is not normalised.
233    #[test]
234    fn the_blur_preserves_a_flat_plane() {
235        let plane = vec![0.25; W * H];
236        let blurred = blur(&plane, W, H, 3.0);
237        for value in blurred {
238            assert!((value - 0.25).abs() < 1e-12, "{value}");
239        }
240    }
241
242    /// Halation *does* add light — that is the whole point, the reflection
243    /// returns exposure that would otherwise have left the film. On a uniform
244    /// field the gain is exactly the sum of the strengths, everywhere.
245    #[test]
246    fn a_flat_frame_gains_exactly_the_strengths() {
247        let mut buffer = vec![[0.2, 0.2, 0.2]; W * H];
248        let halation = Halation::typical(6.0);
249        halation.apply(&mut buffer, W, H);
250        let gain = 1.0 + halation.scatter.strength[0] + halation.reflection.strength[0];
251        let expected = 0.2 + gain.log10();
252        for pixel in &buffer {
253            assert!(
254                (pixel[0] - expected).abs() < 1e-9,
255                "{:?} vs {expected}",
256                pixel[0]
257            );
258        }
259    }
260
261    /// The halo has to be red: the same returned light, weighted by how much of
262    /// each layer survives the double pass.
263    /// The reflection halo's size is geometry: the lens's cone, refracted into
264    /// a 135 µm base and stretched over the two trips through it. These numbers
265    /// are the whole reason this width is no longer a placeholder.
266    #[test]
267    fn the_reflection_halo_is_the_size_the_base_allows() {
268        assert!((Halation::reflection_radius_um(5.6) - 16.0).abs() < 0.5);
269        assert!((Halation::reflection_radius_um(1.4) - 62.1).abs() < 1.0);
270        assert!((Halation::reflection_radius_um(16.0) - 5.6).abs() < 0.3);
271
272        // A wider aperture throws a wider cone, and the halo with it.
273        let mut previous = f64::INFINITY;
274        for aperture in [1.4, 2.0, 2.8, 4.0, 5.6, 8.0, 11.0, 16.0] {
275            let radius = Halation::reflection_radius_um(aperture);
276            assert!(
277                radius < previous,
278                "f/{aperture} is not narrower than the last"
279            );
280            previous = radius;
281        }
282
283        // And the base's own refraction is a third of the effect: in air the
284        // cone would reach 2B·tan(atan(1/2N)), which at f/4 is 33.8 µm.
285        let straight = 2.0 * Halation::BASE_THICKNESS_MM * 1000.0 * (1.0_f64 / 8.0).atan().tan();
286        let ratio = Halation::reflection_radius_um(4.0) / straight;
287        assert!(
288            (0.6..0.75).contains(&ratio),
289            "the index of the base is not bending the cone the way it should: {ratio}"
290        );
291
292        // `typical` is f/4, and the scatter term does not move with the lens.
293        let typical = Halation::typical(6.0);
294        assert!(
295            (typical.reflection.sigma_um - 0.5 * Halation::reflection_radius_um(4.0)).abs() < 1e-9
296        );
297        assert!((typical.scatter.sigma_um - 6.0).abs() < 1e-9);
298    }
299
300    #[test]
301    fn the_glow_is_red() {
302        let mut buffer = highlight(3.0);
303        Halation::typical(6.0).apply(&mut buffer, W, H);
304        let near = (H / 2) * W + W / 2 + 3;
305        let pixel = buffer[near];
306        assert!(pixel[0] > pixel[1], "red {pixel:?}");
307        assert!(pixel[1] > pixel[2], "green over blue {pixel:?}");
308    }
309
310    #[test]
311    fn the_halo_falls_off_with_distance() {
312        let mut buffer = highlight(3.0);
313        Halation::typical(6.0).apply(&mut buffer, W, H);
314        let at = |offset: usize| buffer[(H / 2) * W + W / 2 + offset][0];
315        assert!(at(1) > at(5), "near {} vs far {}", at(1), at(5));
316        assert!(at(5) > at(20), "near {} vs far {}", at(5), at(20));
317    }
318
319    /// The kernels are in micrometres, so the scan resolution must not change how
320    /// much light comes back — only how many pixels it is spread over.
321    #[test]
322    fn the_returned_energy_does_not_depend_on_the_scan() {
323        let energy = |pixel_um: f64| {
324            let mut buffer = highlight(3.0);
325            let before: f64 = buffer.iter().map(|p| 10.0_f64.powf(p[0])).sum();
326            Halation::typical(pixel_um).apply(&mut buffer, W, H);
327            let after: f64 = buffer.iter().map(|p| 10.0_f64.powf(p[0])).sum();
328            after - before
329        };
330        let fine = energy(3.0);
331        let coarse = energy(12.0);
332        let relative = (fine - coarse).abs() / fine;
333        assert!(relative < 0.01, "fine {fine} vs coarse {coarse}");
334    }
335
336    /// And the halo really is larger in pixels when the pixels are smaller.
337    #[test]
338    fn the_halo_widens_when_the_pixels_shrink() {
339        let reach = |pixel_um: f64| {
340            let mut buffer = highlight(3.0);
341            Halation::typical(pixel_um).apply(&mut buffer, W, H);
342            // A thousand times the unexposed level: inside the halo core, and
343            // well outside it once the glow has fallen away.
344            let row = &buffer[(H / 2) * W..(H / 2 + 1) * W];
345            row.iter().filter(|pixel| pixel[0] > -2.0).count()
346        };
347        let fine = reach(3.0);
348        let coarse = reach(12.0);
349        assert!(fine > coarse, "fine {fine} px vs coarse {coarse} px");
350    }
351
352    #[test]
353    fn a_zero_strength_is_a_no_op() {
354        let mut halation = Halation::typical(6.0);
355        halation.reflection.strength = [0.0; 3];
356        halation.scatter.strength = [0.0; 3];
357        assert!(halation.is_noop());
358        let mut buffer = highlight(4.0);
359        let before = buffer.clone();
360        halation.apply(&mut buffer, W, H);
361        assert_eq!(buffer, before);
362    }
363
364    /// The kernel sums to one, so a uniform field stays put even at the edges,
365    /// where clamping would otherwise lose or invent light.
366    #[test]
367    fn the_kernel_is_normalised() {
368        let kernel = gaussian_kernel(2.5);
369        let sum: f64 = kernel.iter().sum();
370        assert!((sum - 1.0).abs() < 1e-12, "sum {sum}");
371    }
372}