Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

32.3 KB
Raw Blame
//! Lottie stickers (Discord's built-in Wumpus stickers are Lottie JSON):
//! enough of the format to play them, drawn with tiny-skia into frames the
//! animation player (`video`) shows like a GIF's.
//!
//! Covered (what Discord's sticker packs use, surveyed 2026-11-23): shape,
//! precomp, null and solid layers; parenting and time stretch; groups, paths,
//! rectangles, ellipses; fills, strokes, linear / radial gradient fills; trim
//! paths; alpha / luma track mattes; additive masks; keyframes with bezier
//! easing, hold keys and spatial (curved) motion. Not covered: expressions,
//! effects, text, blend modes, merge paths (drawn as plain shapes).

use serde_json::Value;
use tiny_skia::{
    Color, FillRule, GradientStop, LineCap, LineJoin, LinearGradient, Mask, MaskType, Paint, Path, PathBuilder, Pixmap, PixmapPaint, Point,
    RadialGradient, Shader, SpreadMode, Stroke, Transform,
};

/// A parsed animation: its frame rate, frame range, size and layers.
pub struct Animation {
    root: Value,
    pub fr: f64,
    pub ip: f64,
    pub op: f64,
    pub w: f64,
    pub h: f64,
}

impl Animation {
    pub fn parse(bytes: &[u8]) -> Result<Self, String> {
        let root: Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
        let num = |k: &str| root[k].as_f64();
        let (fr, ip, op, w, h) = (num("fr").unwrap_or(60.0), num("ip").unwrap_or(0.0), num("op").unwrap_or(60.0), num("w").unwrap_or(512.0), num("h").unwrap_or(512.0));
        if !(fr > 0.0 && op > ip && w > 0.0 && h > 0.0) || !root["layers"].is_array() {
            return Err("not a Lottie animation".into());
        }
        Ok(Animation { root, fr, ip, op, w, h })
    }

    /// Draw frame `frame` into a `size` × `size` picture (premultiplied RGBA).
    pub fn render(&self, frame: f64, size: u32) -> Option<Pixmap> {
        let mut px = Pixmap::new(size, size)?;
        let k = (size as f64 / self.w.max(self.h)) as f32;
        let tf = Transform::from_scale(k, k);
        render_layers(&self.root, self.root["layers"].as_array()?, frame, tf, 1.0, &mut px, 0);
        Some(px)
    }
}

// ---- values ----------------------------------------------------------------

fn nums(v: &Value) -> Vec<f64> {
    match v {
        Value::Number(n) => vec![n.as_f64().unwrap_or(0.0)],
        Value::Array(a) => a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(),
        _ => Vec::new(),
    }
}

/// Solve a CSS-style cubic bezier easing (0,0)-(x1,y1)-(x2,y2)-(1,1) for x.
fn ease(x1: f64, y1: f64, x2: f64, y2: f64, x: f64) -> f64 {
    if x <= 0.0 {
        return 0.0;
    }
    if x >= 1.0 {
        return 1.0;
    }
    let bez = |t: f64, a: f64, b: f64| 3.0 * (1.0 - t) * (1.0 - t) * t * a + 3.0 * (1.0 - t) * t * t * b + t * t * t;
    let (mut lo, mut hi) = (0.0, 1.0);
    let mut t = x;
    for _ in 0..30 {
        let cx = bez(t, x1, x2);
        if (cx - x).abs() < 1e-5 {
            break;
        }
        if cx < x {
            lo = t;
        } else {
            hi = t;
        }
        t = (lo + hi) / 2.0;
    }
    bez(t, y1, y2)
}

/// A keyframe's easing for dimension `d` (Lottie stores it per dimension or once).
fn key_ease(k: &Value, d: usize, x: f64) -> f64 {
    let pick = |v: &Value| {
        let a = nums(v);
        a.get(d).or(a.first()).copied().unwrap_or(0.0)
    };
    let (ox, oy, ix, iy) = (pick(&k["o"]["x"]), pick(&k["o"]["y"]), pick(&k["i"]["x"]), pick(&k["i"]["y"]));
    if k["o"].is_null() || k["i"].is_null() {
        return x;
    }
    ease(ox, oy, ix, iy, x)
}

/// The keyframes around `t`: (from, to, progress 0..1 per dimension), or a
/// fixed value.
enum At<'a> {
    Fixed(&'a Value),
    Between(&'a Value, &'a Value, &'a Value, f64),
}

fn at<'a>(prop: &'a Value, t: f64) -> Option<At<'a>> {
    let k = &prop["k"];
    let animated = prop["a"].as_i64() == Some(1) || (k.is_array() && k.as_array().is_some_and(|a| a.first().is_some_and(|f| f.get("t").is_some())));
    if !animated {
        return Some(At::Fixed(k));
    }
    let keys = k.as_array()?;
    if keys.is_empty() {
        return None;
    }
    let first = &keys[0];
    if t <= first["t"].as_f64().unwrap_or(0.0) || keys.len() == 1 {
        return Some(At::Fixed(&first["s"]));
    }
    for w in keys.windows(2) {
        let (a, b) = (&w[0], &w[1]);
        let (ta, tb) = (a["t"].as_f64().unwrap_or(0.0), b["t"].as_f64().unwrap_or(0.0));
        if t < tb {
            if a["h"].as_i64() == Some(1) || tb <= ta {
                return Some(At::Fixed(&a["s"]));
            }
            // Old files give the end value on the key itself ("e").
            let end = if a.get("e").is_some_and(|e| !e.is_null()) { &a["e"] } else { &b["s"] };
            return Some(At::Between(&a["s"], end, a, (t - ta) / (tb - ta)));
        }
    }
    let last = keys.last()?;
    // The last key may carry only "t" (old files): its value is the previous "e".
    if last.get("s").is_none() {
        let prev = &keys[keys.len() - 2];
        return Some(At::Fixed(if prev.get("e").is_some() { &prev["e"] } else { &prev["s"] }));
    }
    Some(At::Fixed(&last["s"]))
}

/// An animated number list (position, scale, colour…) at time `t`.
fn value(prop: &Value, t: f64) -> Vec<f64> {
    match at(prop, t) {
        None => Vec::new(),
        Some(At::Fixed(v)) => nums(v),
        Some(At::Between(a, b, key, x)) => {
            let (a, b) = (nums(a), nums(b));
            // Curved motion (spatial tangents) for 2D positions.
            if a.len() >= 2 && b.len() >= 2 && (key.get("to").is_some() || key.get("ti").is_some()) {
                let to = nums(&key["to"]);
                let ti = nums(&key["ti"]);
                if to.len() >= 2 && ti.len() >= 2 && (to[0] != 0.0 || to[1] != 0.0 || ti[0] != 0.0 || ti[1] != 0.0) {
                    let p = key_ease(key, 0, x);
                    let c1 = (a[0] + to[0], a[1] + to[1]);
                    let c2 = (b[0] + ti[0], b[1] + ti[1]);
                    let q = 1.0 - p;
                    let bx = q * q * q * a[0] + 3.0 * q * q * p * c1.0 + 3.0 * q * p * p * c2.0 + p * p * p * b[0];
                    let by = q * q * q * a[1] + 3.0 * q * q * p * c1.1 + 3.0 * q * p * p * c2.1 + p * p * p * b[1];
                    return vec![bx, by];
                }
            }
            a.iter().enumerate().map(|(d, va)| {
                let vb = b.get(d).copied().unwrap_or(*va);
                va + (vb - va) * key_ease(key, d, x)
            }).collect()
        }
    }
}

fn scalar(prop: &Value, t: f64, default: f64) -> f64 {
    if prop.is_null() {
        return default;
    }
    value(prop, t).first().copied().unwrap_or(default)
}

fn point(prop: &Value, t: f64, default: (f64, f64)) -> (f64, f64) {
    if prop.is_null() {
        return default;
    }
    // Split position: x and y animated separately.
    if prop["s"].as_bool() == Some(true) || prop.get("x").is_some_and(|x| x.is_object()) && prop.get("k").is_none() {
        return (scalar(&prop["x"], t, default.0), scalar(&prop["y"], t, default.1));
    }
    let v = value(prop, t);
    (v.first().copied().unwrap_or(default.0), v.get(1).copied().unwrap_or(default.1))
}

/// A bezier shape ({c, v, i, o}) at time `t`, interpolating vertex by vertex.
fn shape(prop: &Value, t: f64) -> Option<(bool, Vec<[f64; 6]>)> {
    let one = |v: &Value| -> Option<(bool, Vec<[f64; 6]>)> {
        let v = if v.is_array() { v.get(0)? } else { v };
        let closed = v["c"].as_bool().unwrap_or(false);
        let (vs, is, os) = (v["v"].as_array()?, v["i"].as_array()?, v["o"].as_array()?);
        let pts = vs
            .iter()
            .zip(is)
            .zip(os)
            .map(|((p, i), o)| {
                let (p, i, o) = (nums(p), nums(i), nums(o));
                let g = |a: &Vec<f64>, n: usize| a.get(n).copied().unwrap_or(0.0);
                [g(&p, 0), g(&p, 1), g(&i, 0), g(&i, 1), g(&o, 0), g(&o, 1)]
            })
            .collect();
        Some((closed, pts))
    };
    match at(prop, t)? {
        At::Fixed(v) => one(v),
        At::Between(a, b, key, x) => {
            let (ca, pa) = one(a)?;
            let (_, pb) = one(b)?;
            let p = key_ease(key, 0, x);
            let pts = pa.iter().zip(pb.iter().chain(std::iter::repeat(pa.last()?))).map(|(u, v)| {
                let mut out = [0.0; 6];
                for k in 0..6 {
                    out[k] = u[k] + (v[k] - u[k]) * p;
                }
                out
            }).collect();
            Some((ca, pts))
        }
    }
}

// ---- transforms ------------------------------------------------------------

/// Lottie's transform (anchor, position, scale %, rotation °, skew) at `t`,
/// and its opacity (0..1).
fn transform(ks: &Value, t: f64) -> (Transform, f32) {
    if ks.is_null() {
        return (Transform::identity(), 1.0);
    }
    let (ax, ay) = point(&ks["a"], t, (0.0, 0.0));
    let (px, py) = point(&ks["p"], t, (0.0, 0.0));
    let s = if ks["s"].is_null() { vec![100.0, 100.0] } else { value(&ks["s"], t) };
    let (sx, sy) = (s.first().copied().unwrap_or(100.0) / 100.0, s.get(1).copied().unwrap_or(100.0) / 100.0);
    let r = if !ks["r"].is_null() { scalar(&ks["r"], t, 0.0) } else { scalar(&ks["rz"], t, 0.0) };
    let o = scalar(&ks["o"], t, 100.0) / 100.0;
    let sk = scalar(&ks["sk"], t, 0.0);
    let sa = scalar(&ks["sa"], t, 0.0);
    let mut m = Transform::from_translate(px as f32, py as f32);
    m = m.pre_rotate(r as f32);
    if sk != 0.0 {
        // Skew along the axis at `sa` degrees.
        let sa_r = (sa as f32).to_radians();
        let k = (-(sk as f32).to_radians()).tan();
        m = m.pre_rotate(-sa as f32);
        m = m.pre_concat(Transform::from_row(1.0, 0.0, k, 1.0, 0.0, 0.0));
        m = m.pre_rotate(sa_r.to_degrees());
    }
    m = m.pre_scale(sx as f32, sy as f32);
    m = m.pre_translate(-ax as f32, -ay as f32);
    (m, o.clamp(0.0, 1.0) as f32)
}

fn layer_by_ind<'a>(layers: &'a [Value], ind: i64) -> Option<&'a Value> {
    layers.iter().find(|l| l["ind"].as_i64() == Some(ind))
}

/// A layer's transform in its composition, its parents' included.
fn world(layers: &[Value], l: &Value, t: f64, depth: usize) -> Transform {
    let (local, _) = transform(&l["ks"], t);
    match l["parent"].as_i64().and_then(|p| layer_by_ind(layers, p)) {
        Some(p) if depth < 32 => world(layers, p, t, depth + 1).pre_concat(local),
        _ => local,
    }
}

// ---- geometry ---------------------------------------------------------------

/// Flattened outline points of a bezier shape (for trim paths).
fn flatten(closed: bool, pts: &[[f64; 6]]) -> Vec<(f64, f64)> {
    let mut out = Vec::new();
    let n = pts.len();
    if n == 0 {
        return out;
    }
    out.push((pts[0][0], pts[0][1]));
    let segs = if closed { n } else { n - 1 };
    for k in 0..segs {
        let a = pts[k];
        let b = pts[(k + 1) % n];
        let (p0, c1, c2, p3) = ((a[0], a[1]), (a[0] + a[4], a[1] + a[5]), (b[0] + b[2], b[1] + b[3]), (b[0], b[1]));
        for s in 1..=16 {
            let t = s as f64 / 16.0;
            let q = 1.0 - t;
            out.push((
                q * q * q * p0.0 + 3.0 * q * q * t * c1.0 + 3.0 * q * t * t * c2.0 + t * t * t * p3.0,
                q * q * q * p0.1 + 3.0 * q * q * t * c1.1 + 3.0 * q * t * t * c2.1 + t * t * t * p3.1,
            ));
        }
    }
    out
}

/// One piece of geometry: its outline (closed?, points) or a polyline after trimming.
#[derive(Clone)]
enum Geom {
    Bezier(bool, Vec<[f64; 6]>),
    Poly(Vec<(f64, f64)>),
}

impl Geom {
    fn path(&self, tf: Transform) -> Option<Path> {
        let mut pb = PathBuilder::new();
        match self {
            Geom::Bezier(closed, pts) => {
                let n = pts.len();
                if n == 0 {
                    return None;
                }
                pb.move_to(pts[0][0] as f32, pts[0][1] as f32);
                let segs = if *closed { n } else { n - 1 };
                for k in 0..segs {
                    let a = pts[k];
                    let b = pts[(k + 1) % n];
                    pb.cubic_to((a[0] + a[4]) as f32, (a[1] + a[5]) as f32, (b[0] + b[2]) as f32, (b[1] + b[3]) as f32, b[0] as f32, b[1] as f32);
                }
                if *closed {
                    pb.close();
                }
            }
            Geom::Poly(p) => {
                let first = p.first()?;
                pb.move_to(first.0 as f32, first.1 as f32);
                for q in &p[1..] {
                    pb.line_to(q.0 as f32, q.1 as f32);
                }
            }
        }
        pb.finish()?.transform(tf)
    }

    fn poly(&self) -> Vec<(f64, f64)> {
        match self {
            Geom::Bezier(c, p) => flatten(*c, p),
            Geom::Poly(p) => p.clone(),
        }
    }
}

/// Keep the part of `g` from `start` to `end` (0..1 of its length).
fn trim(g: &Geom, start: f64, end: f64) -> Option<Geom> {
    let pts = g.poly();
    if pts.len() < 2 {
        return None;
    }
    let mut cum = vec![0.0];
    for w in pts.windows(2) {
        let d = ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt();
        cum.push(cum.last().unwrap_or(&0.0) + d);
    }
    let total = *cum.last()?;
    if total <= 0.0 {
        return None;
    }
    let (a, b) = (start * total, end * total);
    let mut out = Vec::new();
    let lerp = |i: usize, at: f64| {
        let (l0, l1) = (cum[i], cum[i + 1]);
        let f = if l1 > l0 { (at - l0) / (l1 - l0) } else { 0.0 };
        (pts[i].0 + (pts[i + 1].0 - pts[i].0) * f, pts[i].1 + (pts[i + 1].1 - pts[i].1) * f)
    };
    for i in 0..pts.len() - 1 {
        let (l0, l1) = (cum[i], cum[i + 1]);
        if l1 < a || l0 > b {
            continue;
        }
        if out.is_empty() {
            out.push(if l0 < a { lerp(i, a) } else { pts[i] });
        }
        out.push(if l1 > b { lerp(i, b) } else { pts[i + 1] });
    }
    (out.len() >= 2).then_some(Geom::Poly(out))
}

/// Geometry of a group's items (in the group's own space) and the paint
/// work, gathered in Lottie's order.
fn item_geom(item: &Value, t: f64) -> Vec<Geom> {
    match item["ty"].as_str().unwrap_or("") {
        "sh" => shape(&item["ks"], t).map(|(c, p)| vec![Geom::Bezier(c, p)]).unwrap_or_default(),
        "rc" => {
            let (cx, cy) = point(&item["p"], t, (0.0, 0.0));
            let s = value(&item["s"], t);
            let (w, h) = (s.first().copied().unwrap_or(0.0), s.get(1).copied().unwrap_or(0.0));
            let r = scalar(&item["r"], t, 0.0).min(w / 2.0).min(h / 2.0).max(0.0);
            let (x0, y0, x1, y1) = (cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0);
            if r <= 0.0 {
                return vec![Geom::Bezier(true, vec![[x1, y0, 0.0, 0.0, 0.0, 0.0], [x1, y1, 0.0, 0.0, 0.0, 0.0], [x0, y1, 0.0, 0.0, 0.0, 0.0], [x0, y0, 0.0, 0.0, 0.0, 0.0]])];
            }
            let k = r * 0.5523;
            vec![Geom::Bezier(true, vec![
                [x1 - r, y0, -k, 0.0, k, 0.0],
                [x1, y0 + r, 0.0, -k, 0.0, k],
                [x1, y1 - r, 0.0, -k, 0.0, k],
                [x1 - r, y1, k, 0.0, -k, 0.0],
                [x0 + r, y1, k, 0.0, -k, 0.0],
                [x0, y1 - r, 0.0, k, 0.0, -k],
                [x0, y0 + r, 0.0, k, 0.0, -k],
                [x0 + r, y0, -k, 0.0, k, 0.0],
            ])]
        }
        "el" => {
            let (cx, cy) = point(&item["p"], t, (0.0, 0.0));
            let s = value(&item["s"], t);
            let (rx, ry) = (s.first().copied().unwrap_or(0.0) / 2.0, s.get(1).copied().unwrap_or(0.0) / 2.0);
            let (kx, ky) = (rx * 0.5523, ry * 0.5523);
            vec![Geom::Bezier(true, vec![
                [cx, cy - ry, -kx, 0.0, kx, 0.0],
                [cx + rx, cy, 0.0, -ky, 0.0, ky],
                [cx, cy + ry, kx, 0.0, -kx, 0.0],
                [cx - rx, cy, 0.0, ky, 0.0, -ky],
            ])]
        }
        _ => Vec::new(),
    }
}

fn color(prop: &Value, t: f64, opacity: f32) -> Color {
    let c = value(prop, t);
    let g = |i: usize| c.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0) as f32;
    let a = if c.len() > 3 { g(3) } else { 1.0 };
    Color::from_rgba(g(0), g(1), g(2), (a * opacity).clamp(0.0, 1.0)).unwrap_or(Color::BLACK)
}

fn gradient(item: &Value, t: f64, opacity: f32, tf: Transform) -> Option<Shader<'static>> {
    let n = item["g"]["p"].as_u64().unwrap_or(0) as usize;
    let raw = value(&item["g"]["k"], t);
    if n == 0 || raw.len() < n * 4 {
        return None;
    }
    // Colour stops, then (optionally) alpha stops.
    let alpha_at = |off: f64| -> f64 {
        let a = &raw[n * 4..];
        if a.len() < 4 {
            return 1.0;
        }
        let pairs: Vec<(f64, f64)> = a.chunks(2).filter(|c| c.len() == 2).map(|c| (c[0], c[1])).collect();
        if off <= pairs[0].0 {
            return pairs[0].1;
        }
        for w in pairs.windows(2) {
            if off <= w[1].0 {
                let f = if w[1].0 > w[0].0 { (off - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 };
                return w[0].1 + (w[1].1 - w[0].1) * f;
            }
        }
        pairs.last().map_or(1.0, |p| p.1)
    };
    let stops: Vec<GradientStop> = (0..n)
        .map(|i| {
            let off = raw[i * 4];
            let a = (alpha_at(off) as f32 * opacity).clamp(0.0, 1.0);
            let col = Color::from_rgba(raw[i * 4 + 1] as f32, raw[i * 4 + 2] as f32, raw[i * 4 + 3] as f32, a).unwrap_or(Color::BLACK);
            GradientStop::new(off as f32, col)
        })
        .collect();
    let (sx, sy) = point(&item["s"], t, (0.0, 0.0));
    let (ex, ey) = point(&item["e"], t, (0.0, 0.0));
    if item["t"].as_i64() == Some(2) {
        let r = ((ex - sx).powi(2) + (ey - sy).powi(2)).sqrt() as f32;
        RadialGradient::new(Point::from_xy(sx as f32, sy as f32), Point::from_xy(sx as f32, sy as f32), r.max(0.01), stops, SpreadMode::Pad, tf)
    } else {
        LinearGradient::new(Point::from_xy(sx as f32, sy as f32), Point::from_xy(ex as f32, ey as f32), stops, SpreadMode::Pad, tf)
    }
}

/// Draw a shape group's items. Returns the group's geometry (with transforms)
/// for styles further out. `trim` is a trim-paths range applying from outside.
fn draw_items(items: &[Value], t: f64, tf: Transform, opacity: f32, px: &mut Pixmap, mask: Option<&Mask>, outer_trim: Option<(f64, f64)>) {
    // The group's own transform ("tr", last).
    let (local, o) = items.iter().find(|i| i["ty"] == "tr").map_or((Transform::identity(), 1.0), |tr| transform(tr, t));
    let tf = tf.pre_concat(local);
    let opacity = opacity * o;
    // Trim paths inside this group apply to the shapes before them.
    let trim_here = items.iter().filter(|i| i["ty"] == "tm" && i["hd"].as_bool() != Some(true)).map(|tm| {
        let s = scalar(&tm["s"], t, 0.0) / 100.0;
        let e = scalar(&tm["e"], t, 100.0) / 100.0;
        let off = scalar(&tm["o"], t, 0.0) / 360.0;
        let mut a = s.min(e) + off;
        a -= a.floor();
        let b = a + (s.max(e) - s.min(e));
        (a, b.min(a + 1.0))
    }).next().or(outer_trim);
    let apply_trim = |g: Geom| -> Vec<Geom> {
        match trim_here {
            None => vec![g],
            Some((a, b)) if b - a >= 0.999 => vec![g],
            Some((a, b)) if b <= 1.0 => trim(&g, a, b).into_iter().collect(),
            Some((a, b)) => trim(&g, a, 1.0).into_iter().chain(trim(&g, 0.0, b - 1.0)).collect(),
        }
    };
    // Geometry of each item, in order (nested groups contribute theirs).
    let mut per_item: Vec<Vec<(Geom, Transform)>> = Vec::with_capacity(items.len());
    let mut groups: Vec<Option<usize>> = Vec::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        if item["hd"].as_bool() == Some(true) {
            per_item.push(Vec::new());
            groups.push(None);
            continue;
        }
        match item["ty"].as_str().unwrap_or("") {
            "gr" => {
                per_item.push(Vec::new());
                groups.push(Some(i));
            }
            _ => {
                per_item.push(item_geom(item, t).into_iter().flat_map(apply_trim).map(|g| (g, tf)).collect());
                groups.push(None);
            }
        }
    }
    // Paint from the last item to the first: later styles are underneath.
    // A style paints everything listed before it; a group paints itself.
    let mut collected: Vec<Option<Vec<(Geom, Transform)>>> = vec![None; items.len()];
    let geometry_before = |idx: usize, per_item: &Vec<Vec<(Geom, Transform)>>, collected: &Vec<Option<Vec<(Geom, Transform)>>>| -> Vec<(Geom, Transform)> {
        let mut out = Vec::new();
        for j in 0..idx {
            out.extend(per_item[j].iter().cloned());
            if let Some(g) = &collected[j] {
                out.extend(g.iter().cloned());
            }
        }
        out
    };
    // Groups' geometry is needed by the styles after them: gather it first
    // (drawn later, in order) by drawing nothing (a scratch pixmap is avoided:
    // geometry only).
    for (j, g) in groups.iter().enumerate() {
        if let Some(gi) = g {
            let sub = items[*gi]["it"].as_array().cloned().unwrap_or_default();
            collected[j] = Some(group_geometry(&sub, t, tf, trim_here));
        }
    }
    for idx in (0..items.len()).rev() {
        let item = &items[idx];
        if item["hd"].as_bool() == Some(true) {
            continue;
        }
        match item["ty"].as_str().unwrap_or("") {
            "gr" => {
                let sub = item["it"].as_array().cloned().unwrap_or_default();
                draw_items(&sub, t, tf, opacity, px, mask, trim_here);
            }
            "fl" | "st" | "gf" | "gs" => {
                let geom = geometry_before(idx, &per_item, &collected);
                if geom.is_empty() {
                    continue;
                }
                let o = scalar(&item["o"], t, 100.0) as f32 / 100.0 * opacity;
                if o <= 0.0 {
                    continue;
                }
                let mut paint = Paint { anti_alias: true, ..Paint::default() };
                let ty = item["ty"].as_str().unwrap_or("");
                match ty {
                    "fl" | "st" => paint.shader = Shader::SolidColor(color(&item["c"], t, o)),
                    _ => match gradient(item, t, o, tf) {
                        Some(s) => paint.shader = s,
                        None => continue,
                    },
                }
                if ty == "fl" || ty == "gf" {
                    let rule = if item["r"].as_i64() == Some(2) { FillRule::EvenOdd } else { FillRule::Winding };
                    let mut pb = PathBuilder::new();
                    for (g, gtf) in &geom {
                        if let Some(p) = g.path(*gtf) {
                            pb.push_path(&p);
                        }
                    }
                    if let Some(p) = pb.finish() {
                        px.fill_path(&p, &paint, rule, Transform::identity(), mask);
                    }
                } else {
                    let w = scalar(&item["w"], t, 1.0);
                    for (g, gtf) in &geom {
                        let scale = (gtf.sx * gtf.sy - gtf.kx * gtf.ky).abs().sqrt();
                        let stroke = Stroke {
                            width: (w as f32 * scale).max(0.01),
                            line_cap: match item["lc"].as_i64() {
                                Some(2) => LineCap::Round,
                                Some(3) => LineCap::Square,
                                _ => LineCap::Butt,
                            },
                            line_join: match item["lj"].as_i64() {
                                Some(2) => LineJoin::Round,
                                Some(3) => LineJoin::Bevel,
                                _ => LineJoin::Miter,
                            },
                            miter_limit: item["ml"].as_f64().unwrap_or(4.0) as f32,
                            dash: None,
                        };
                        if let Some(p) = g.path(*gtf) {
                            px.stroke_path(&p, &paint, &stroke, Transform::identity(), mask);
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

/// A group's geometry (no drawing), for the styles of the group around it.
fn group_geometry(items: &[Value], t: f64, tf: Transform, outer_trim: Option<(f64, f64)>) -> Vec<(Geom, Transform)> {
    let (local, _) = items.iter().find(|i| i["ty"] == "tr").map_or((Transform::identity(), 1.0), |tr| transform(tr, t));
    let tf = tf.pre_concat(local);
    let mut out = Vec::new();
    for item in items {
        if item["hd"].as_bool() == Some(true) {
            continue;
        }
        match item["ty"].as_str().unwrap_or("") {
            "gr" => out.extend(group_geometry(item["it"].as_array().map(|v| v.as_slice()).unwrap_or(&[]), t, tf, outer_trim)),
            _ => out.extend(item_geom(item, t).into_iter().map(|g| (g, tf))),
        }
    }
    out
}

// ---- layers ------------------------------------------------------------------

fn visible(l: &Value, frame: f64) -> bool {
    let ip = l["ip"].as_f64().unwrap_or(f64::MIN);
    let op = l["op"].as_f64().unwrap_or(f64::MAX);
    l["hd"].as_bool() != Some(true) && frame >= ip && frame < op
}

/// A layer's own time (its start offset and stretch).
fn local_time(l: &Value, frame: f64) -> f64 {
    let st = l["st"].as_f64().unwrap_or(0.0);
    let sr = l["sr"].as_f64().filter(|s| *s > 0.0).unwrap_or(1.0);
    (frame - st) / sr
}

/// Draw one layer (no matte) into `px`.
fn draw_layer(root: &Value, layers: &[Value], l: &Value, frame: f64, tf: Transform, opacity: f32, px: &mut Pixmap, depth: usize) {
    let t = local_time(l, frame);
    let tfl = tf.pre_concat(world(layers, l, t, 0));
    let (_, o) = transform(&l["ks"], t);
    let opacity = opacity * o;
    if opacity <= 0.0 {
        return;
    }
    // Additive masks clip the layer.
    let mask = masks(l, t, tfl, px.width(), px.height());
    match l["ty"].as_i64().unwrap_or(-1) {
        4 => {
            let items = l["shapes"].as_array().map(|v| v.as_slice()).unwrap_or(&[]);
            draw_items(items, t, tfl, opacity, px, mask.as_ref(), None);
        }
        0 if depth < 8 => {
            let id = l["refId"].as_str().unwrap_or("");
            let asset = root["assets"].as_array().and_then(|a| a.iter().find(|x| x["id"].as_str() == Some(id)));
            if let Some(sub) = asset.and_then(|a| a["layers"].as_array()) {
                // Time remap, if any, gives the inner time in seconds.
                let inner = if l["tm"].is_null() { t } else { scalar(&l["tm"], t, 0.0) * root["fr"].as_f64().unwrap_or(60.0) };
                match &mask {
                    None => render_layers(root, sub, inner, tfl, opacity, px, depth + 1),
                    Some(m) => {
                        if let Some(mut tmp) = Pixmap::new(px.width(), px.height()) {
                            render_layers(root, sub, inner, tfl, opacity, &mut tmp, depth + 1);
                            px.draw_pixmap(0, 0, tmp.as_ref(), &PixmapPaint::default(), Transform::identity(), Some(m));
                        }
                    }
                }
            }
        }
        1 => {
            let (w, h) = (l["sw"].as_f64().unwrap_or(0.0) as f32, l["sh"].as_f64().unwrap_or(0.0) as f32);
            let hex = l["sc"].as_str().unwrap_or("#000000").trim_start_matches('#');
            let c = u32::from_str_radix(hex, 16).unwrap_or(0);
            let mut paint = Paint { anti_alias: true, ..Paint::default() };
            paint.set_color(Color::from_rgba8((c >> 16) as u8, (c >> 8) as u8, c as u8, (opacity * 255.0) as u8));
            if let Some(r) = tiny_skia::Rect::from_xywh(0.0, 0.0, w, h) {
                let p = PathBuilder::from_rect(r);
                px.fill_path(&p, &paint, FillRule::Winding, tfl, mask.as_ref());
            }
        }
        _ => {}
    }
}

/// A layer's masks (mode "a", add) as one clip, if it has any.
fn masks(l: &Value, t: f64, tf: Transform, w: u32, h: u32) -> Option<Mask> {
    let list = l["masksProperties"].as_array()?;
    let mut mask = Mask::new(w, h)?;
    let mut any = false;
    for m in list {
        if m["mode"].as_str().unwrap_or("a") != "a" {
            continue;
        }
        if let Some((c, pts)) = shape(&m["pt"], t) {
            if let Some(p) = Geom::Bezier(c, pts).path(tf) {
                mask.fill_path(&p, FillRule::Winding, true, Transform::identity());
                any = true;
            }
        }
    }
    any.then_some(mask)
}

/// Draw a composition's layers (bottom one first), with track mattes.
fn render_layers(root: &Value, layers: &[Value], frame: f64, tf: Transform, opacity: f32, px: &mut Pixmap, depth: usize) {
    for i in (0..layers.len()).rev() {
        let l = &layers[i];
        // Matte sources are only drawn as the next layer's matte.
        if l["td"].as_i64().unwrap_or(0) != 0 || !visible(l, frame) {
            continue;
        }
        let tt = l["tt"].as_i64().unwrap_or(0);
        if tt != 0 && i > 0 {
            let matte_layer = &layers[i - 1];
            let (Some(mut matte), Some(mut content)) = (Pixmap::new(px.width(), px.height()), Pixmap::new(px.width(), px.height())) else { continue };
            if visible(matte_layer, frame) {
                draw_layer(root, layers, matte_layer, frame, tf, 1.0, &mut matte, depth);
            }
            draw_layer(root, layers, l, frame, tf, opacity, &mut content, depth);
            let kind = if tt == 3 || tt == 4 { MaskType::Luminance } else { MaskType::Alpha };
            let mut mask = Mask::from_pixmap(matte.as_ref(), kind);
            if tt == 2 || tt == 4 {
                mask.invert();
            }
            px.draw_pixmap(0, 0, content.as_ref(), &PixmapPaint::default(), Transform::identity(), Some(&mask));
        } else {
            draw_layer(root, layers, l, frame, tf, opacity, px, depth);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn draws_a_moving_red_circle() {
        let json = br#"{"v":"5.7.0","fr":30,"ip":0,"op":30,"w":100,"h":100,"layers":[
            {"ty":4,"ind":1,"ip":0,"op":30,"st":0,
             "ks":{"o":{"a":0,"k":100},"r":{"a":0,"k":0},"p":{"a":1,"k":[{"t":0,"s":[25,50],"i":{"x":[0.5],"y":[0.5]},"o":{"x":[0.5],"y":[0.5]}},{"t":29,"s":[75,50]}]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]}},
             "shapes":[{"ty":"gr","it":[
                {"ty":"el","p":{"a":0,"k":[0,0]},"s":{"a":0,"k":[20,20]}},
                {"ty":"fl","c":{"a":0,"k":[1,0,0,1]},"o":{"a":0,"k":100}},
                {"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100}}]}]}]}"#;
        let a = Animation::parse(json).unwrap();
        let first = a.render(0.0, 100).unwrap();
        let last = a.render(29.0, 100).unwrap();
        let red = |p: &Pixmap, x: u32, y: u32| p.pixel(x, y).map_or(0, |c| c.red());
        assert!(red(&first, 25, 50) > 200 && red(&first, 75, 50) == 0);
        assert!(red(&last, 75, 50) > 200 && red(&last, 25, 50) == 0);
    }

    /// `LOTTIE_DIR=<folder of .json> cargo test -p rustcord render_files -- --ignored`:
    /// a contact sheet of six frames per file, next to it.
    #[test]
    #[ignore]
    fn render_files() {
        let dir = std::env::var("LOTTIE_DIR").expect("LOTTIE_DIR");
        for e in std::fs::read_dir(&dir).unwrap().flatten() {
            let path = e.path();
            if path.extension().and_then(|x| x.to_str()) != Some("json") {
                continue;
            }
            let Ok(a) = Animation::parse(&std::fs::read(&path).unwrap()) else { continue };
            let size = 160u32;
            let mut sheet = image::RgbaImage::from_pixel(size * 6, size, image::Rgba([49, 51, 56, 255]));
            let t0 = std::time::Instant::now();
            for k in 0..6u32 {
                let f = a.ip + (a.op - a.ip) * k as f64 / 6.0;
                let px = a.render(f, size).unwrap();
                for y in 0..size {
                    for x in 0..size {
                        let c = px.pixel(x, y).unwrap().demultiply();
                        let bg = sheet.get_pixel(k * size + x, y).0;
                        let al = c.alpha() as u32;
                        let mix = |s: u8, d: u8| ((s as u32 * al + d as u32 * (255 - al)) / 255) as u8;
                        sheet.put_pixel(k * size + x, y, image::Rgba([mix(c.red(), bg[0]), mix(c.green(), bg[1]), mix(c.blue(), bg[2]), 255]));
                    }
                }
            }
            eprintln!("{}: {:?} for 6 frames", path.display(), t0.elapsed());
            sheet.save(path.with_extension("png")).unwrap();
        }
    }

    #[test]
    fn easing_ends() {
        assert!((ease(0.42, 0.0, 0.58, 1.0, 0.5) - 0.5).abs() < 0.01);
        assert_eq!(ease(0.3, 0.1, 0.7, 0.9, 0.0), 0.0);
    }
}