mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
storytold main 83cb1133dd (291 commits) into the integration head bab1a99b85; 47 conflicted files.
- Domain test files (metafile, prepress, pdf plates, settings store, heif, media-testkit, atomic): tests next cut stay cut; tests new on main are kept, as trials where the crate's test target runs trials.
- atomic: main's group-bits test and Faulty::set_group go to src/tests.rs. audio: main's GSM and SBC oracles join tests/main.rs. cms constructors, pdf knockout_backdrop and testing_pdf join their crates' one test binary; timeline's preflight tests become src/preflight_tests.rs trials.
- update: main's changes to detect, install (linux, macos) and the tests land in next's split modules. The app's own offer is inspected on a thread of its own, picked up by tick's polling; settle_for_tests settles offers too. Later on a ready update drops the close it asked for. updater_pin_tests.rs stays deleted; its new pin test is in tests/it/update.rs.
- craft-color: main added a different crate at crates/color (the colour tags of compositor and display frames); it is next's craft-color module `tags`, re-exported at the root.
- Old crates/ui (combo, docking, testing, README) and keymap's ui/view.rs stay deleted; main's new crates/ui/src/testing files are dropped with them.
- New crates in the craft facade: ai, control, dds, frame, ipc, media-source, palette, press-print, score, ssip. testkit and xtask are listed outside it.
- Cargo.lock: the union of both locks, resolved by cargo metadata. Workflow: main's nextest Windows leg, with next's --keep-going clippy.
394 lines
13 KiB
Rust
394 lines
13 KiB
Rust
//! One-dimensional tone curves (ICC `curv` and `para` tag types) and their inverses.
|
||
|
||
/// A tone reproduction curve.
|
||
///
|
||
/// Gamma and parametric curves are evaluated analytically, including outside `[0, 1]` (negative
|
||
/// inputs mirror, values above 1 extend the formula), so unbounded float transforms keep HDR
|
||
/// values. Sampled tables clamp their input to `[0, 1]`.
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub enum Curve {
|
||
#[allow(missing_docs)]
|
||
Identity,
|
||
/// `y = x^g`.
|
||
Gamma(f64),
|
||
/// ICC `parametricCurveType` function `kind` (0–4) with parameters `[g, a, b, c, d, e, f]`
|
||
/// (unused ones are 0).
|
||
Parametric {
|
||
/// ICC parametric function type, 0 to 4 (see [`Curve::param_count`]).
|
||
kind: u16,
|
||
/// Parameters `[g, a, b, c, d, e, f]`; those the function type does not use are 0.
|
||
p: [f64; 7],
|
||
},
|
||
/// Samples at evenly spaced inputs over `[0, 1]`, normalised outputs.
|
||
Table(Vec<f32>),
|
||
}
|
||
|
||
/// The sRGB transfer function (IEC 61966-2.1) as ICC parametric type 3.
|
||
pub fn srgb_trc() -> Curve {
|
||
Curve::Parametric { kind: 3, p: [2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045, 0.0, 0.0] }
|
||
}
|
||
|
||
impl Curve {
|
||
/// Creates a gamma curve `y = x^g`. Returns `Identity` if `g == 1.0` (within 1e-6).
|
||
pub fn gamma(g: f64) -> Result<Self, crate::CmsError> {
|
||
if !crate::math::fits_s15f16(g) || crate::math::s15f16_round(g) <= 0.0 {
|
||
return Err(crate::CmsError::InvalidArgument("gamma must remain positive and representable in ICC fixed point".into()));
|
||
}
|
||
if (g - 1.0).abs() < 1e-6 { Ok(Curve::Identity) } else { Ok(Curve::Gamma(g)) }
|
||
}
|
||
|
||
/// Creates an ICC parametric curve (types 0 to 4).
|
||
pub fn parametric(kind: u16, p: [f64; 7]) -> Result<Self, crate::CmsError> {
|
||
if kind > 4 {
|
||
return Err(crate::CmsError::InvalidArgument(format!("parametric curve kind {kind} must be <= 4")));
|
||
}
|
||
let count = Self::param_count(kind);
|
||
if !p.iter().take(count).all(|&v| crate::math::fits_s15f16(v)) {
|
||
return Err(crate::CmsError::InvalidArgument("parametric curve parameters must be representable in ICC fixed point".into()));
|
||
}
|
||
Ok(Curve::Parametric { kind, p })
|
||
}
|
||
|
||
/// Creates a sampled lookup table curve over evenly spaced inputs in `[0, 1]`.
|
||
pub fn from_table(samples: Vec<f32>) -> Result<Self, crate::CmsError> {
|
||
if samples.len() < 2 {
|
||
return Err(crate::CmsError::InvalidArgument("sampled curve must contain at least 2 entries".into()));
|
||
}
|
||
if !samples.iter().all(|s| s.is_finite() && (0.0..=1.0).contains(s)) {
|
||
return Err(crate::CmsError::InvalidArgument("sampled curve values must be finite and within [0, 1]".into()));
|
||
}
|
||
Ok(Curve::Table(samples))
|
||
}
|
||
|
||
/// Validate public enum variants before a profile stores them in ICC tags.
|
||
pub(crate) fn validate_icc(&self) -> Result<(), crate::CmsError> {
|
||
match self {
|
||
Self::Identity => Ok(()),
|
||
Self::Gamma(g) => Self::gamma(*g).map(|_| ()),
|
||
Self::Parametric { kind, p } => Self::parametric(*kind, *p).map(|_| ()),
|
||
Self::Table(t) if t.len() >= 2 && u32::try_from(t.len()).is_ok() && t.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) => Ok(()),
|
||
Self::Table(_) => Err(crate::CmsError::InvalidArgument("sampled curve must contain representable finite normalized samples".into())),
|
||
}
|
||
}
|
||
/// Number of parameters stored for a parametric function type.
|
||
pub fn param_count(kind: u16) -> usize {
|
||
match kind {
|
||
0 => 1,
|
||
1 => 3,
|
||
2 => 4,
|
||
3 => 5,
|
||
_ => 7,
|
||
}
|
||
}
|
||
|
||
/// `true` when the curve maps every input to itself (within 1e-9 for formulas, 1/65535 for tables).
|
||
pub fn is_identity(&self) -> bool {
|
||
match self {
|
||
Curve::Identity => true,
|
||
Curve::Gamma(g) => (*g - 1.0).abs() < 1e-9,
|
||
Curve::Parametric { kind: 0, p } => (p[0] - 1.0).abs() < 1e-9,
|
||
Curve::Table(t) => {
|
||
let n = t.len();
|
||
n < 2 || t.iter().enumerate().all(|(i, v)| (*v as f64 - i as f64 / (n - 1) as f64).abs() < 1.0 / 65535.0)
|
||
}
|
||
_ => false,
|
||
}
|
||
}
|
||
|
||
/// Evaluates the curve at `x` (f64 reference path).
|
||
pub fn eval64(&self, x: f64) -> f64 {
|
||
match self {
|
||
Curve::Identity => x,
|
||
Curve::Gamma(g) => mirror(x, |v| v.powf(*g)),
|
||
Curve::Parametric { kind, p } => para(*kind, p, x),
|
||
Curve::Table(t) => table(t, x as f32) as f64,
|
||
}
|
||
}
|
||
|
||
/// Evaluates the curve at `x` in `f32`, the fast path for pixel loops.
|
||
#[inline]
|
||
pub fn eval(&self, x: f32) -> f32 {
|
||
match self {
|
||
Curve::Identity => x,
|
||
Curve::Table(t) => table(t, x),
|
||
_ => self.eval64(x as f64) as f32,
|
||
}
|
||
}
|
||
|
||
/// Evaluates the inverse curve at `y`.
|
||
pub fn eval_inverse64(&self, y: f64) -> f64 {
|
||
match self {
|
||
Curve::Identity => y,
|
||
Curve::Gamma(g) => {
|
||
if g.abs() < 1e-12 {
|
||
y
|
||
} else {
|
||
mirror(y, |v| v.powf(1.0 / g))
|
||
}
|
||
}
|
||
Curve::Parametric { kind, p } => para_inverse(*kind, p, y).unwrap_or_else(|| numeric_inverse(|x| para(*kind, p, x), y)),
|
||
Curve::Table(t) => table_inverse(t, y as f32) as f64,
|
||
}
|
||
}
|
||
|
||
/// [`eval_inverse64`](Self::eval_inverse64) for many values. A table's flat ends are found
|
||
/// once here instead of on every call, so building an output table from a long, flat table
|
||
/// costs one scan of it, not one per entry.
|
||
pub fn inverse64_many(&self) -> impl Fn(f64) -> f64 + '_ {
|
||
let edges = self.inverse_edges();
|
||
move |y| match (self, edges) {
|
||
(Curve::Table(_), Some(_)) => self.eval_inverse_with(y as f32, edges) as f64,
|
||
_ => self.eval_inverse64(y),
|
||
}
|
||
}
|
||
|
||
/// Evaluates the inverse curve at `y` in `f32`, the fast path for pixel loops.
|
||
#[inline]
|
||
pub fn eval_inverse(&self, y: f32) -> f32 {
|
||
match self {
|
||
Curve::Identity => y,
|
||
Curve::Table(t) => table_inverse(t, y),
|
||
_ => self.eval_inverse64(y as f64) as f32,
|
||
}
|
||
}
|
||
|
||
/// The ends of a sampled curve's flat runs, as [`eval_inverse_with`](Self::eval_inverse_with)
|
||
/// takes them; `None` for other curves. Finding them scans the table, so a caller that
|
||
/// inverts the same curve many times finds them once.
|
||
pub(crate) fn inverse_edges(&self) -> Option<(f32, f32)> {
|
||
match self {
|
||
Curve::Table(t) if t.len() >= 2 => Some((edge_index(t, true), edge_index(t, false))),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// [`eval_inverse`](Self::eval_inverse) with the flat-run ends from
|
||
/// [`inverse_edges`](Self::inverse_edges) of this curve.
|
||
#[inline]
|
||
pub(crate) fn eval_inverse_with(&self, y: f32, edges: Option<(f32, f32)>) -> f32 {
|
||
match (self, edges) {
|
||
(Curve::Table(t), Some((first, last))) => table_inverse_with(t, y, |start| if start { first } else { last }),
|
||
_ => self.eval_inverse(y),
|
||
}
|
||
}
|
||
|
||
/// Samples `n` evenly spaced points over `[0, 1]` (one sample is the value at 0).
|
||
pub fn sample(&self, n: usize) -> Vec<f32> {
|
||
let step = n.saturating_sub(1).max(1) as f64;
|
||
(0..n).map(|i| self.eval64(i as f64 / step) as f32).collect()
|
||
}
|
||
|
||
/// `true` when the curve never decreases over `[0, 1]`.
|
||
pub fn is_monotonic(&self) -> bool {
|
||
let s = self.sample(1024);
|
||
s.windows(2).all(|w| w[1] >= w[0] - 1e-6) || s.windows(2).all(|w| w[1] <= w[0] + 1e-6)
|
||
}
|
||
}
|
||
|
||
#[inline]
|
||
fn mirror(x: f64, f: impl Fn(f64) -> f64) -> f64 {
|
||
if x < 0.0 { -f(-x) } else { f(x) }
|
||
}
|
||
|
||
fn pw(base: f64, g: f64) -> f64 {
|
||
if base <= 0.0 { 0.0 } else { base.powf(g) }
|
||
}
|
||
|
||
fn para(kind: u16, p: &[f64; 7], x: f64) -> f64 {
|
||
let [g, a, b, c, d, e, f] = *p;
|
||
match kind {
|
||
0 => mirror(x, |v| v.powf(g)),
|
||
1 => {
|
||
if a != 0.0 && x >= -b / a {
|
||
pw(a * x + b, g)
|
||
} else {
|
||
0.0
|
||
}
|
||
}
|
||
2 => {
|
||
if a != 0.0 && x >= -b / a {
|
||
pw(a * x + b, g) + c
|
||
} else {
|
||
c
|
||
}
|
||
}
|
||
3 => {
|
||
if x < 0.0 && b == 0.0 && d == 0.0 {
|
||
// Pure gamma written as type 3: mirror negatives.
|
||
-para(kind, p, -x)
|
||
} else if x >= d {
|
||
pw(a * x + b, g)
|
||
} else {
|
||
c * x
|
||
}
|
||
}
|
||
_ => {
|
||
if x >= d {
|
||
pw(a * x + b, g) + e
|
||
} else {
|
||
c * x + f
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
fn para_inverse(kind: u16, p: &[f64; 7], y: f64) -> Option<f64> {
|
||
let [g, a, b, c, d, e, f] = *p;
|
||
if g.abs() < 1e-12 {
|
||
return None;
|
||
}
|
||
let root = |v: f64| if v <= 0.0 { 0.0 } else { v.powf(1.0 / g) };
|
||
Some(match kind {
|
||
0 => mirror(y, |v| v.powf(1.0 / g)),
|
||
1 => {
|
||
if a == 0.0 {
|
||
return None;
|
||
}
|
||
if y <= 0.0 { -b / a } else { (root(y) - b) / a }
|
||
}
|
||
2 => {
|
||
if a == 0.0 {
|
||
return None;
|
||
}
|
||
if y <= c { -b / a } else { (root(y - c) - b) / a }
|
||
}
|
||
3 => {
|
||
if a == 0.0 {
|
||
return None;
|
||
}
|
||
if y < 0.0 && b == 0.0 && d == 0.0 {
|
||
return para_inverse(kind, p, -y).map(|v| -v);
|
||
}
|
||
let yd = pw(a * d + b, g);
|
||
if y >= yd {
|
||
(root(y) - b) / a
|
||
} else if c != 0.0 {
|
||
y / c
|
||
} else {
|
||
0.0
|
||
}
|
||
}
|
||
_ => {
|
||
if a == 0.0 {
|
||
return None;
|
||
}
|
||
let yd = pw(a * d + b, g) + e;
|
||
if y >= yd {
|
||
(root(y - e) - b) / a
|
||
} else if c != 0.0 {
|
||
(y - f) / c
|
||
} else {
|
||
0.0
|
||
}
|
||
}
|
||
})
|
||
}
|
||
|
||
/// Bisection inverse of an increasing function on `[0, 1]`.
|
||
fn numeric_inverse(f: impl Fn(f64) -> f64, y: f64) -> f64 {
|
||
let (f0, f1) = (f(0.0), f(1.0));
|
||
let increasing = f1 >= f0;
|
||
let (mut lo, mut hi) = (0.0f64, 1.0f64);
|
||
for _ in 0..60 {
|
||
let mid = 0.5 * (lo + hi);
|
||
let v = f(mid);
|
||
if (v < y) == increasing {
|
||
lo = mid;
|
||
} else {
|
||
hi = mid;
|
||
}
|
||
}
|
||
0.5 * (lo + hi)
|
||
}
|
||
|
||
#[inline]
|
||
fn table(t: &[f32], x: f32) -> f32 {
|
||
let n = t.len();
|
||
match n {
|
||
0 => x,
|
||
1 => t[0],
|
||
_ => {
|
||
let pos = x.clamp(0.0, 1.0) * (n - 1) as f32;
|
||
let i = (pos as usize).min(n - 2);
|
||
let f = pos - i as f32;
|
||
t[i] + (t[i + 1] - t[i]) * f
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Exact inverse of a piecewise-linear table (binary search), for increasing or decreasing tables.
|
||
fn table_inverse(t: &[f32], y: f32) -> f32 {
|
||
table_inverse_with(t, y, |start| edge_index(t, start))
|
||
}
|
||
|
||
/// [`table_inverse`] with the flat-run ends from `edge` (see [`edge_index`]).
|
||
fn table_inverse_with(t: &[f32], y: f32, edge: impl Fn(bool) -> f32) -> f32 {
|
||
let n = t.len();
|
||
if n < 2 {
|
||
return y;
|
||
}
|
||
let increasing = t[n - 1] >= t[0];
|
||
let (lo_v, hi_v) = if increasing { (t[0], t[n - 1]) } else { (t[n - 1], t[0]) };
|
||
if y <= lo_v {
|
||
// Flat start: choose the last index still at the lowest value.
|
||
return edge(increasing);
|
||
}
|
||
if y >= hi_v {
|
||
return edge(!increasing);
|
||
}
|
||
let (mut lo, mut hi) = (0usize, n - 1);
|
||
while hi - lo > 1 {
|
||
let mid = (lo + hi) / 2;
|
||
if (t[mid] < y) == increasing {
|
||
lo = mid;
|
||
} else {
|
||
hi = mid;
|
||
}
|
||
}
|
||
let (a, b) = (t[lo], t[hi]);
|
||
let f = if (b - a).abs() > 1e-12 { (y - a) / (b - a) } else { 0.5 };
|
||
(lo as f32 + f) / (n - 1) as f32
|
||
}
|
||
|
||
/// For a flat run at the table start (`start = true`) the last index of the run, or for a flat
|
||
/// run at the end the first index of it, as a normalised input.
|
||
///
|
||
/// A table that is inverted is monotonic, so the run is found by bisection, not by a scan: a long
|
||
/// constant table is inverted once per pixel, and scanning it each time made the cost the curve's
|
||
/// length times the image's.
|
||
fn edge_index(t: &[f32], start: bool) -> f32 {
|
||
let n = t.len();
|
||
if start {
|
||
let v = t[0];
|
||
// The first value that differs, given they do so from there on.
|
||
let first_other = t.partition_point(|x| (*x - v).abs() <= 1e-7);
|
||
let i = if first_other >= n { n - 1 } else { first_other.saturating_sub(1) };
|
||
i as f32 / (n - 1) as f32
|
||
} else {
|
||
let v = t[n - 1];
|
||
// The start of the trailing run equal to the last value.
|
||
let i = t.partition_point(|x| (*x - v).abs() > 1e-7);
|
||
i as f32 / (n - 1) as f32
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn inverting_a_long_flat_table_does_not_rescan_it_for_every_pixel() {
|
||
// Four million zeros and a one: a scan per call would be 8·10¹¹ steps for these calls.
|
||
let mut t = vec![0.0f32; 4_000_000];
|
||
t.push(1.0);
|
||
let c = Curve::Table(t);
|
||
let started = std::time::Instant::now();
|
||
let mut last = 0.0;
|
||
for _ in 0..200_000 {
|
||
last = c.eval_inverse(0.0);
|
||
}
|
||
assert!(last > 0.99, "the flat start ends at the last zero: {last}");
|
||
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
|
||
}
|
||
}
|