Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

8.9 KB
Raw Blame
//! The modular part of JPEG XL, as far as we use it: whole-number images (the low-frequency image, the block
//! metadata, the alpha channel) predicted pixel by pixel, the prediction picked by a small decision tree whose leaves
//! also pick the distribution the residual is coded with.
//!
//! One tree is shared by all the streams of a frame (the "global tree"); it tells them apart through the channel
//! number and the stream number, which are the tree's first two properties.

use crate::ans::{Codes, Token, build_codes};
use crate::bits::BitWriter;

pub const PRED_ZERO: u8 = 0;
pub const PRED_WEST: u8 = 1;
pub const PRED_NORTH: u8 = 2;
pub const PRED_GRADIENT: u8 = 5;

/// A tree as it is built: the left branch is taken when the property is bigger than the value.
pub enum T {
    Leaf(u8),
    Split(u8, i32, Box<T>, Box<T>),
}

#[derive(Clone, Copy, Debug)]
pub enum Node {
    Split { prop: u8, val: i32, left: u32, right: u32 },
    Leaf { pred: u8, id: u32 },
}

/// The tree with its nodes in the order the format stores them: breadth first, a node's two children one after the
/// other.
pub struct Tree {
    pub nodes: Vec<Node>,
    pub num_leaves: usize,
    simple: bool,
}

impl Tree {
    pub fn new(t: T) -> Tree {
        let mut nodes: Vec<Node> = Vec::new();
        let mut queue: std::collections::VecDeque<(T, usize)> = std::collections::VecDeque::new();
        queue.push_back((t, 0));
        nodes.push(Node::Leaf { pred: 0, id: 0 });
        let mut leaves = 0;
        while let Some((t, at)) = queue.pop_front() {
            match t {
                T::Leaf(pred) => {
                    nodes[at] = Node::Leaf { pred, id: leaves };
                    leaves += 1;
                }
                T::Split(prop, val, l, r) => {
                    let left = nodes.len() as u32;
                    nodes.push(Node::Leaf { pred: 0, id: 0 });
                    nodes.push(Node::Leaf { pred: 0, id: 0 });
                    nodes[at] = Node::Split { prop, val, left, right: left + 1 };
                    queue.push_back((*l, left as usize));
                    queue.push_back((*r, left as usize + 1));
                }
            }
        }
        // Without a split on a neighbour's value (properties 3 and up) a row of a channel has one leaf, and the
        // tokens can be made without the work of the properties.
        let simple = !nodes.iter().any(|n| matches!(n, Node::Split { prop, .. } if *prop >= 3));
        Tree { nodes, num_leaves: leaves as usize, simple }
    }

    #[inline]
    fn walk(&self, props: &[i32; 16]) -> (u8, u32) {
        let mut at = 0;
        loop {
            match self.nodes[at] {
                Node::Split { prop, val, left, right } => {
                    at = if props[prop as usize] > val { left as usize } else { right as usize };
                }
                Node::Leaf { pred, id } => return (pred, id),
            }
        }
    }

    /// The predictor and leaf for a channel of a stream, for the leaves that depend on nothing else.
    pub fn leaf_of(&self, stream: u32, channel: u32) -> (u8, u32) {
        let mut props = [0i32; 16];
        props[0] = channel as i32;
        props[1] = stream as i32;
        self.walk(&props)
    }

    /// The tree as the decoder reads it: its own small code, then the nodes as tokens.
    pub fn write(&self, bw: &mut BitWriter) {
        let mut toks = Vec::new();
        for n in &self.nodes {
            match *n {
                Node::Split { prop, val, .. } => {
                    toks.push(Token { ctx: 1, val: prop as u32 + 1 });
                    toks.push(Token { ctx: 0, val: pack_signed(val) });
                }
                Node::Leaf { pred, .. } => {
                    toks.push(Token { ctx: 1, val: 0 });
                    toks.push(Token { ctx: 2, val: pred as u32 });
                    toks.push(Token { ctx: 3, val: 0 }); // offset
                    toks.push(Token { ctx: 4, val: 0 }); // multiplier, log2
                    toks.push(Token { ctx: 5, val: 0 }); // multiplier, bits
                }
            }
        }
        let codes = build_codes(6, &[&toks]);
        codes.write_header(bw);
        codes.write_stream(bw, &toks);
    }
}

#[inline(always)]
pub fn pack_signed(v: i32) -> u32 {
    ((v << 1) ^ (v >> 31)) as u32
}

/// One channel of whole numbers.
pub struct Chan {
    pub w: usize,
    pub h: usize,
    pub data: Vec<i32>,
}

fn clamped_gradient(l: i32, t: i32, tl: i32) -> i32 {
    let (l, t, tl) = (l as i64, t as i64, tl as i64);
    let min = l.min(t);
    let max = l.max(t);
    let g = l + t - tl;
    (if tl < min { max } else if tl > max { min } else { g }) as i32
}

/// Codes the channels of one stream: for each pixel the residual of the tree's prediction, as a token whose context
/// is the leaf. `stream` is the frame's number for the stream (the tree's second property).
pub fn encode_channels(chans: &[Chan], stream: u32, tree: &Tree, out: &mut Vec<Token>) {
    for (ci, ch) in chans.iter().enumerate() {
        let (w, h) = (ch.w, ch.h);
        let mut props = [0i32; 16];
        props[0] = ci as i32;
        props[1] = stream as i32;
        for y in 0..h {
            let row = &ch.data[y * w..(y + 1) * w];
            let top_row = if y > 0 { Some(&ch.data[(y - 1) * w..y * w]) } else { None };
            let toptop_row = if y > 1 { Some(&ch.data[(y - 2) * w..(y - 1) * w]) } else { None };
            if tree.simple {
                props[2] = y as i32;
                let (pred, id) = tree.walk(&props);
                if pred == PRED_GRADIENT {
                    gradient_row(&ch.data, w, y, id, out);
                    continue;
                }
            }
            for x in 0..w {
                // The neighbours the decoder uses, with its rules for the edges.
                let left = if x > 0 {
                    row[x - 1]
                } else if let Some(t) = top_row {
                    t[0]
                } else {
                    0
                };
                let top = top_row.map_or(left, |t| t[x]);
                let topleft = if x > 0 && y > 0 { top_row.unwrap()[x - 1] } else { left };
                let topright = if x + 1 < w && y > 0 { top_row.unwrap()[x + 1] } else { top };
                let leftleft = if x > 1 { row[x - 2] } else { left };
                let toptop = toptop_row.map_or(top, |t| t[x]);
                props[2] = y as i32;
                props[3] = x as i32;
                props[4] = top.wrapping_abs();
                props[5] = left.wrapping_abs();
                props[6] = top;
                props[7] = left;
                props[9] = left.wrapping_add(top).wrapping_sub(topleft);
                props[10] = left.wrapping_sub(topleft);
                props[11] = topleft.wrapping_sub(top);
                props[12] = top.wrapping_sub(topright);
                props[13] = top.wrapping_sub(toptop);
                props[14] = left.wrapping_sub(leftleft);
                let (pred, id) = tree.walk(&props);
                let guess = match pred {
                    PRED_ZERO => 0,
                    PRED_WEST => left,
                    PRED_NORTH => top,
                    PRED_GRADIENT => clamped_gradient(left, top, topleft),
                    _ => panic!("predictor {pred} not implemented"),
                };
                out.push(Token { ctx: id, val: pack_signed(row[x].wrapping_sub(guess)) });
            }
        }
    }
}

/// One channel that is coded with a single leaf of the tree (the gradient predictor, one distribution), without the
/// work of evaluating the tree for every pixel.
pub fn encode_gradient(ch: &Chan, pred: u8, id: u32, out: &mut Vec<Token>) {
    assert_eq!(pred, PRED_GRADIENT);
    let (w, h) = (ch.w, ch.h);
    out.reserve(w * h);
    for y in 0..h {
        gradient_row(&ch.data, w, y, id, out);
    }
}

/// The tokens of row `y` of an image `w` wide, predicted by the clamped gradient, edges as the decoder takes them.
fn gradient_row(data: &[i32], w: usize, y: usize, id: u32, out: &mut Vec<Token>) {
    let row = &data[y * w..(y + 1) * w];
    if y == 0 {
        let mut left = 0;
        for &v in row {
            out.push(Token { ctx: id, val: pack_signed(v.wrapping_sub(left)) });
            left = v;
        }
        return;
    }
    let top = &data[(y - 1) * w..y * w];
    // first pixel: left and top-left are the pixel above
    out.push(Token { ctx: id, val: pack_signed(row[0].wrapping_sub(top[0])) });
    for x in 1..w {
        let guess = clamped_gradient(row[x - 1], top[x], top[x - 1]);
        out.push(Token { ctx: id, val: pack_signed(row[x].wrapping_sub(guess)) });
    }
}

/// The start of every modular stream that uses the global tree: no own tree, default weighted-predictor
/// parameters, no transforms.
pub fn write_stream_header(bw: &mut BitWriter) {
    bw.put(1, 1);
    bw.put(1, 1);
    bw.put(0, 2);
}

/// A complete stream: its header and the tokens.
pub fn write_stream(bw: &mut BitWriter, codes: &Codes, tokens: &[Token]) {
    write_stream_header(bw);
    codes.write_stream(bw, tokens);
}