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.

26.4 KB
Raw Blame
//! A small JPEG XL encoder of our own, made for the thumbnail cache: pictures from a few pixels to about two thousand
//! on a side, 8-bit RGB or RGBA, written once and read many times.
//!
//! Lossy pictures are coded the way the format's VarDCT mode does it: the picture in the XYB colour space, 8x8 DCT
//! blocks, quantized, the coefficients coded with context-modelled ANS. An alpha channel is coded without loss as a
//! modular channel. The decoder is the reference for every detail; this crate only writes what such a decoder reads
//! back (the tests check it against jxl-rs and jxl-oxide).

mod ans;
mod bits;
mod modular;
mod par;
mod vardct;
mod xyb;

use bits::{BitWriter, U32Form, ceil_log2, put_u32};
use modular::{Chan, T, Tree};

/// The biggest picture side the format can say.
pub const MAX_SIDE: u32 = 1 << 30;

/// Blocks per low-frequency group side (2048 pixels).
const LF_BLOCKS: usize = 256;

/// The decoder's default parameters of its edge-preserving filter's strength: the factor on the quantization step, the
/// scale of the first and the last pass, the border weight.
const EPF_SIGMA_DEFAULT: [f32; 4] = [0.46, 0.9, 6.5, 2.0 / 3.0];

/// Pixels per group side.
const GROUP: usize = 256;

/// Settings for experiments; `encode` uses the defaults.
#[derive(Clone, Debug)]
pub struct Tuning {
    /// Butteraugli-like distance: 1.0 is "visually the same", bigger is smaller and worse.
    pub distance: f32,
    /// Quantization strength at distance 1 (the product of global scale and block quant over 65536).
    pub strength: f32,
    /// The low-frequency image's step relative to the finest high-frequency one.
    pub dc_mult: f32,
    /// Below this fraction of a step a coefficient becomes zero (0.5 is plain rounding).
    pub round_threshold: f32,
    /// Smoothing the decoder applies (0 to 3 passes of its edge-preserving filter).
    pub epf_iters: u32,
    /// The decoder's 3x3 smoothing; only worth it when the encoder sharpens before the transform, which it does not.
    pub gaborish: bool,
    pub epf_sharpness: u8,
    /// How strongly the filter works (see `EPF_SIGMA_DEFAULT`).
    pub epf_sigma: [f32; 4],
    /// Print where the bytes go (for the measuring tools).
    pub verbose: bool,
    /// How much coarser X and B are quantized than the weights say (1.25 per step above 2).
    pub x_qm_scale: u32,
    pub b_qm_scale: u32,
    /// Multipliers of the low-frequency steps of X, Y and B (1 keeps the format's defaults).
    pub dc_scale: [f32; 3],
    /// Changes to the default weights of the 8x8 DCT's frequency bands (see `vardct::DCT8_BANDS`): the first of each
    /// channel scales the weights, the others move the steps between bands.
    pub band_delta: [[f32; 6]; 3],
    /// Fit how much of Y is taken off X and B to the picture (else the format's defaults: none off X, all off B).
    pub cfl: bool,
    /// And per 64x64 pixel tile.
    pub cfl_tiles: bool,
    /// Threads to encode with: 0 picks one for small pictures and all cores for big ones. The output is the same bytes
    /// whatever the number.
    pub threads: usize,
    /// Use 16x16 blocks where the picture is smooth: when the four 8x8 blocks have at most `big_max_nonzero` nonzero
    /// coefficients, and the big block costs less than the small ones (its price times `big_bias`).
    pub big_blocks: bool,
    pub big_max_nonzero: usize,
    pub big_bias: f32,
    /// Smaller pictures than this many pixels keep to 8x8 blocks: they are too detailed for 16x16 ones to pay, and
    /// finding out costs time.
    pub big_min_pixels: usize,
    /// Tell the decoder not to smooth the low-frequency image.
    pub skip_lf_smoothing: bool,
}

impl Tuning {
    /// The mapping from the 0..=100 quality scale (90 is about distance 1) used by libjxl.
    pub fn from_quality(quality: f32) -> Tuning {
        let q = quality.clamp(0.0, 100.0);
        let distance = if q >= 100.0 {
            0.01
        } else if q >= 30.0 {
            0.1 + (100.0 - q) * 0.09
        } else {
            6.4 + 2.5f32.powf((30.0 - q) / 5.0) * 0.1 - 0.1
        };
        Tuning {
            distance,
            strength: 1.0,
            dc_mult: 0.45,
            round_threshold: 0.5,
            epf_iters: 1,
            gaborish: false,
            epf_sharpness: 7,
            epf_sigma: [0.7, 0.9, 6.5, 2.0 / 3.0],
            verbose: false,
            x_qm_scale: 2,
            b_qm_scale: 2,
            dc_scale: [1.0; 3],
            band_delta: [[0.0; 6]; 3],
            cfl: true,
            cfl_tiles: true,
            threads: 0,
            big_blocks: true,
            big_max_nonzero: 120,
            big_bias: 0.9,
            big_min_pixels: 300_000,
            skip_lf_smoothing: true,
        }
    }

    /// For the measuring tools: one setting by its name; false when there is none of that name.
    pub fn set(&mut self, key: &str, v: f32) -> bool {
        match key {
            "q" => *self = Tuning::from_quality(v),
            "strength" => self.strength = v,
            "dc" => self.dc_mult = v,
            "round" => self.round_threshold = v,
            "epf" => self.epf_iters = v as u32,
            "gab" => self.gaborish = v > 0.0,
            "sharp" => self.epf_sharpness = v as u8,
            "verbose" => self.verbose = v > 0.0,
            "eq" => self.epf_sigma[0] = v,
            "e0" => self.epf_sigma[1] = v,
            "e2" => self.epf_sigma[2] = v,
            "eb" => self.epf_sigma[3] = v,
            "xqm" => self.x_qm_scale = v as u32,
            "bqm" => self.b_qm_scale = v as u32,
            "cfl" => self.cfl = v > 0.0,
            "tiles" => self.cfl_tiles = v > 0.0,
            "threads" => self.threads = v as usize,
            "big" => self.big_blocks = v > 0.0,
            "bigmax" => self.big_max_nonzero = v as usize,
            "bigbias" => self.big_bias = v,
            "bigmin" => self.big_min_pixels = v as usize,
            "lfsmooth" => self.skip_lf_smoothing = v == 0.0,
            "dcx" => self.dc_scale[0] = v,
            "dcy" => self.dc_scale[1] = v,
            "dcb" => self.dc_scale[2] = v,
            k if k.len() == 3 && k.starts_with('w') => {
                // wy2 = 0.2: the band step 2 of Y moved by 0.2
                let c = match &k[1..2] {
                    "x" => 0,
                    "y" => 1,
                    "b" => 2,
                    _ => return false,
                };
                let i: usize = k[2..3].parse().unwrap_or(9);
                if i > 5 {
                    return false;
                }
                self.band_delta[c][i] = v;
            }
            _ => return false,
        }
        true
    }
}

/// Why a picture could not be encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// A side of zero pixels.
    EmptyPicture,
    /// The buffer holds fewer than `width * height * 4` bytes.
    BufferTooShort { needed: usize, got: usize },
    /// A side beyond what the format can say (2^30), or a picture that does not fit in memory.
    TooLarge,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::EmptyPicture => write!(f, "the picture has no pixels"),
            Error::BufferTooShort { needed, got } => write!(f, "the pixel buffer holds {got} bytes, {needed} are needed"),
            Error::TooLarge => write!(f, "the picture is too big for JPEG XL"),
        }
    }
}

impl std::error::Error for Error {}

/// Encodes 8-bit RGBA pixels (4 bytes each, row after row; the alpha byte is used only when `has_alpha`) as a bare JPEG
/// XL codestream. `quality` is 0..=100 like libjxl's, about 90 being "visually lossless" (81 is about as good as JPEG
/// quality 85). Alpha is kept exactly. Big pictures use all the cores; see `Tuning::threads`.
pub fn encode(width: u32, height: u32, rgba: &[u8], has_alpha: bool, quality: f32) -> Result<Vec<u8>, Error> {
    encode_tuned(width, height, rgba, has_alpha, &Tuning::from_quality(quality))
}

pub fn encode_tuned(width: u32, height: u32, rgba: &[u8], has_alpha: bool, tuning: &Tuning) -> Result<Vec<u8>, Error> {
    if width == 0 || height == 0 {
        return Err(Error::EmptyPicture);
    }
    if width > MAX_SIDE || height > MAX_SIDE {
        return Err(Error::TooLarge);
    }
    let (w, h) = (width as usize, height as usize);
    let needed = w.checked_mul(h).and_then(|p| p.checked_mul(4)).ok_or(Error::TooLarge)?;
    if rgba.len() < needed {
        return Err(Error::BufferTooShort { needed, got: rgba.len() });
    }
    let threads = par::thread_count(tuning.threads, w * h);
    let started = std::time::Instant::now();
    let lap =|what: &str| {
        if tuning.verbose {
            eprintln!("  {what:<12} {:>8.3} ms", started.elapsed().as_secs_f64() * 1000.0);
        }
    };
    let (bw, bh) = (w.div_ceil(8), h.div_ceil(8));
    let planes = if has_alpha {
        xyb::to_xyb(&fill_transparent(rgba, w, h), w, h, bw * 8, bh * 8, threads)
    } else {
        xyb::to_xyb(rgba, w, h, bw * 8, bh * 8, threads)
    };
    lap("colour");

    // Quantization: blocks get a quant around 16, the global scale makes up the strength.
    let strength = tuning.strength / tuning.distance.max(0.01);
    let raw_quant = 16u32;
    let global_scale = ((strength * 65536.0 / raw_quant as f32).round() as u32).clamp(1, 8193 + 65535);
    let quant_lf = ((raw_quant as f32 * 1.09 / tuning.dc_mult).round() as u32).clamp(1, 65536);
    // the low-frequency factors, as the decoder will read them back from 16-bit floats (factor * 128)
    let custom_lf = tuning.dc_scale != [1.0; 3];
    let lf_bits: [u16; 3] = std::array::from_fn(|c| bits::f16_bits(vardct::LF_QUANT[c] * tuning.dc_scale[c] * 128.0));
    let lf_quant: [f32; 3] = if custom_lf {
        std::array::from_fn(|c| bits::f16_value(lf_bits[c]) / 128.0)
    } else {
        vardct::LF_QUANT
    };
    // the weights of the 8x8 DCT's coefficients, from parameters that go through 16-bit floats
    let custom_bands = tuning.band_delta != [[0.0; 6]; 3];
    let band_bits: [[u16; 6]; 3] = std::array::from_fn(|c| {
        std::array::from_fn(|i| {
            let d = vardct::DCT8_BANDS[c][i];
            // the first value is stored divided by 64, and scaled by the delta as a factor
            if i == 0 { bits::f16_bits(d / 64.0 * (1.0 + tuning.band_delta[c][0])) } else { bits::f16_bits(d + tuning.band_delta[c][i]) }
        })
    });
    let bands: [[f32; 6]; 3] = std::array::from_fn(|c| {
        std::array::from_fn(|i| {
            let v = bits::f16_value(band_bits[c][i]);
            if i == 0 { v * 64.0 } else { v }
        })
    });
    let weight = vardct::dct8_weights(&if custom_bands { bands } else { vardct::DCT8_BANDS });
    let coefs = vardct::analyze(&planes, bw, bh, threads);
    lap("dct");
    // How much of Y the decoder adds back to X and B: the format's defaults (nothing, all) or a fit to this picture,
    // in the form the header stores it (two 16-bit floats and, for the low frequencies, an offset in 84ths).
    let fit = if tuning.cfl { vardct::fit_cfl(&coefs) } else { [0.0, 1.0, 0.0, 1.0] };
    let small = |v: f32| if v.abs() < 1e-3 { 0.0 } else { v };
    let base_bits = [bits::f16_bits(small(fit[0])), bits::f16_bits(small(fit[1]))];
    let base = [bits::f16_value(base_bits[0]), bits::f16_value(base_bits[1])];
    let lf_off: [i32; 2] = [((fit[2] - base[0]) * 84.0).round().clamp(-128.0, 127.0) as i32, ((fit[3] - base[1]) * 84.0).round().clamp(-128.0, 127.0) as i32];
    let cfl = [base[0], base[1], base[0] + lf_off[0] as f32 / 84.0, base[1] + lf_off[1] as f32 / 84.0];
    let q = vardct::Quant {
        global_scale,
        quant_lf,
        lf_quant,
        weight,
        cfl,
        round_offset: tuning.round_threshold,
        x_qm_scale: tuning.x_qm_scale,
        b_qm_scale: tuning.b_qm_scale,
    };
    // every block gets the same quant (an activity-based map was tried, and cost more than it saved)
    let quant_map = vec![raw_quant as u16; bw * bh];
    let tiles = (bw.div_ceil(8), bh.div_ceil(8));
    let tile_cfl = if tuning.cfl_tiles { vardct::fit_cfl_tiles(&coefs, bw, bh, [cfl[0], cfl[1]]) } else { vec![[0, 0]; tiles.0 * tiles.1] };
    let big = (tuning.big_blocks && w * h >= tuning.big_min_pixels).then_some(vardct::BigParams { max_nonzero: tuning.big_max_nonzero, bias: tuning.big_bias });
    let blocks = vardct::quantize(&planes, &coefs, bw, bh, &quant_map, &tile_cfl, &q, big.as_ref(), threads);
    drop((planes, coefs));
    lap("quantize");

    // Low-frequency groups (256 x 256 blocks = 2048 pixels) and groups (32 x 32 blocks = 256 pixels).
    let (lfw, lfh) = (bw.div_ceil(LF_BLOCKS), bh.div_ceil(LF_BLOCKS));
    let n_lf = lfw * lfh;
    let (gw, gh) = (w.div_ceil(GROUP), h.div_ceil(GROUP));
    let n_groups = gw * gh;
    // The streams of modular data share one tree. Which leaf a value uses depends on the stream (the tree's second
    // property: 0 the global one, 1.. the low-frequency groups', then the block metadata's from 2n + 1, and the groups'
    // own alpha from 3n + 18) and the channel in it (the first property).
    let n = n_lf as i32;
    let tree = Tree::new(T::Split(
        1,
        3 * n + 17,
        grad(), // alpha of a group
        Box::new(T::Split(
            1,
            2 * n,
            // the block metadata: channels ytox, ytob, (type, quant), epf
            Box::new(T::Split(
                0,
                2,
                grad(),
                Box::new(T::Split(0, 1, Box::new(T::Split(2, 0, grad(), grad())), grad())),
            )),
            Box::new(T::Split(
                1,
                0,
                // the low-frequency image: channels Y, X, B
                Box::new(T::Split(0, 1, grad(), Box::new(T::Split(0, 0, grad(), grad())))),
                grad(), // alpha of the whole picture
            )),
        )),
    ));
    let lf_rect = |lg: usize| {
        let (x0, y0) = (lg % lfw * LF_BLOCKS, lg / lfw * LF_BLOCKS);
        (x0, y0, (x0 + LF_BLOCKS).min(bw), (y0 + LF_BLOCKS).min(bh))
    };
    // per low-frequency group: the tokens of its low-frequency image and of its block metadata
    let lf_tokens: Vec<(Vec<ans::Token>, Vec<ans::Token>, usize)> = par::par_map(n_lf, threads, |lg| {
        let (x0, y0, x1, y1) = lf_rect(lg);
        let mut dc_tokens = Vec::new();
        modular::encode_channels(&vardct::dc_channels(&blocks, x0, y0, x1, y1), 1 + lg as u32, &tree, &mut dc_tokens);
        let (lw, lh) = (x1 - x0, y1 - y0);
        let nb = lw * lh;
        let (tw, th) = (lw.div_ceil(8), lh.div_ceil(8));
        let mut tile = [Vec::with_capacity(tw * th), Vec::with_capacity(tw * th)];
        for ty in 0..th {
            for tx in 0..tw {
                let t = tile_cfl[(y0 / 8 + ty) * tiles.0 + x0 / 8 + tx];
                tile[0].push(t[0]);
                tile[1].push(t[1]);
            }
        }
        let [t0, t1] = tile;
        // one entry per block that starts here: its transform, then its quant
        let (mut qdata, quants) = blocks.meta(x0, y0, x1, y1);
        let count = qdata.len();
        qdata.extend(quants);
        let meta = [
            Chan { w: tw, h: th, data: t0 },
            Chan { w: tw, h: th, data: t1 },
            Chan { w: count, h: 2, data: qdata },
            Chan { w: lw, h: lh, data: vec![tuning.epf_sharpness as i32; nb] },
        ];
        let mut meta_tokens = Vec::new();
        modular::encode_channels(&meta, 1 + 2 * n_lf as u32 + lg as u32, &tree, &mut meta_tokens);
        (dc_tokens, meta_tokens, count)
    });

    // The alpha channel: in the global section when it is one group big, else in a stream of each group.
    let mut alpha_global: Vec<ans::Token> = Vec::new();
    let mut alpha_groups: Vec<Vec<ans::Token>> = Vec::new();
    if has_alpha {
        if n_groups == 1 {
            let alpha: Vec<i32> = rgba.chunks_exact(4).take(w * h).map(|p| p[3] as i32).collect();
            let (pred, id) = tree.leaf_of(0, 0);
            modular::encode_gradient(&Chan { w, h, data: alpha }, pred, id, &mut alpha_global);
        } else {
            alpha_groups = par::par_map(n_groups, threads, |g| {
                let (x0, y0) = (g % gw * GROUP, g / gw * GROUP);
                let (x1, y1) = ((x0 + GROUP).min(w), (y0 + GROUP).min(h));
                let mut data = Vec::with_capacity((x1 - x0) * (y1 - y0));
                for y in y0..y1 {
                    data.extend(rgba[(y * w + x0) * 4..(y * w + x1) * 4].chunks_exact(4).map(|p| p[3] as i32));
                }
                let (pred, id) = tree.leaf_of(3 * n_lf as u32 + 18 + g as u32, 0);
                let mut t = Vec::new();
                modular::encode_gradient(&Chan { w: x1 - x0, h: y1 - y0, data }, pred, id, &mut t);
                t
            });
        }
    }
    let mut leaf_streams: Vec<&[ans::Token]> = vec![&alpha_global];
    for (a, b, _) in &lf_tokens {
        leaf_streams.push(a);
        leaf_streams.push(b);
    }
    leaf_streams.extend(alpha_groups.iter().map(|t| t.as_slice()));
    let leaf_codes = ans::build_codes(tree.num_leaves, &leaf_streams);
    lap("lf+alpha");

    // The coefficients of each group.
    let group_tokens: Vec<Vec<ans::Token>> = par::par_map(n_groups, threads, |g| {
        let mut t = Vec::new();
        vardct::group_tokens(&blocks, g % gw, g / gw, &mut t);
        t
    });
    lap("tokens");
    let ac_codes = ans::build_codes(vardct::NUM_AC_CONTEXTS, &group_tokens.iter().map(|t| t.as_slice()).collect::<Vec<_>>());
    lap("clusters");

    // --- the sections
    let mut lf_global = BitWriter::new();
    if custom_lf {
        lf_global.put(0, 1);
        for b in lf_bits {
            lf_global.put(b as u64, 16);
        }
    } else {
        lf_global.put(1, 1); // default LF quantization factors
    }
    put_global_scale(&mut lf_global, global_scale);
    put_quant_lf(&mut lf_global, quant_lf);
    // the block context map: Y has its own contexts, X and B share theirs
    lf_global.put(0, 1);
    lf_global.put(0, 12); // no thresholds on the LF values
    lf_global.put(0, 4); // none on the quantization
    // (the map has a row of 13 block shapes for each of Y, X and B; the 16x16 DCT is shape 2)
    let ctx_map: Vec<u8> = (0..3 * 13).map(|i| (i / 13).min(1) as u8 + 2 * (i % 13 == 2) as u8).collect();
    ans::write_context_map(&mut lf_global, &ctx_map, 4);
    if tuning.cfl {
        lf_global.put(0, 1);
        lf_global.put(0, 2); // colour factor 84
        lf_global.put(base_bits[0] as u64, 16);
        lf_global.put(base_bits[1] as u64, 16);
        lf_global.put((lf_off[0] + 128) as u64, 8);
        lf_global.put((lf_off[1] + 128) as u64, 8);
    } else {
        lf_global.put(1, 1); // default colour correlation
    }
    lf_global.put(1, 1); // a global tree
    tree.write(&mut lf_global);
    leaf_codes.write_header(&mut lf_global);
    if has_alpha {
        // the global modular stream: its header, and the alpha channel when it is small enough to be in it
        modular::write_stream_header(&mut lf_global);
        if n_groups == 1 {
            leaf_codes.write_stream(&mut lf_global, &alpha_global);
        } else {
            // Nothing of the channels is in this section. jxl-rs (like libjxl) reads nothing more; jxl-oxide starts
            // an entropy decoder anyway and reads its state, so the section ends with an empty stream (the state is
            // what a decoder ends with, 0x130000).
            leaf_codes.write_stream(&mut lf_global, &[]);
        }
    }

    let lf_groups: Vec<BitWriter> = par::par_map(n_lf, threads, |lg| {
        let (x0, y0, x1, y1) = lf_rect(lg);
        let nb = (x1 - x0) * (y1 - y0);
        let mut b = BitWriter::new();
        b.put(0, 2); // extra precision
        modular::write_stream(&mut b, &leaf_codes, &lf_tokens[lg].0);
        b.put((lf_tokens[lg].2 - 1) as u64, ceil_log2(nb)); // how many blocks start here, minus one
        modular::write_stream(&mut b, &leaf_codes, &lf_tokens[lg].1);
        b
    });

    let mut hf_global = BitWriter::new();
    if custom_bands {
        hf_global.put(0, 1);
        hf_global.put(6, 3); // the 8x8 DCT: a table made from distance bands
        hf_global.put(5, 4); // six bands
        for c in 0..3 {
            for i in 0..6 {
                hf_global.put(band_bits[c][i] as u64, 16);
            }
        }
        for _ in 1..17 {
            hf_global.put(0, 3); // every other transform keeps the library's table
        }
    } else {
        hf_global.put(1, 1); // default dequantization matrices
    }
    hf_global.put(0, ceil_log2(n_groups)); // one set of histograms
    hf_global.put(2, 2); // the coefficient order is the natural one
    ac_codes.write_header(&mut hf_global);

    let hf_groups: Vec<BitWriter> = par::par_map(n_groups, threads, |g| {
        let mut b = BitWriter::new();
        ac_codes.write_stream(&mut b, &group_tokens[g]);
        if has_alpha && n_groups > 1 {
            modular::write_stream(&mut b, &leaf_codes, &alpha_groups[g]);
        }
        b
    });
    lap("streams");

    if tuning.verbose {
        eprintln!(
            "lf_global {} B, lf groups {} B, hf_global {} B, ac {} B in {} tokens",
            lf_global.bit_len() / 8,
            lf_groups.iter().map(|g| g.bit_len() / 8).sum::<usize>(),
            hf_global.bit_len() / 8,
            hf_groups.iter().map(|g| g.bit_len() / 8).sum::<usize>(),
            group_tokens.iter().map(|g| g.len()).sum::<usize>()
        );
    }

    // --- the file
    let mut out = BitWriter::new();
    out.put(0xff, 8);
    out.put(0x0a, 8);
    out.put(0, 1); // not "small"
    put_u32(&mut out, height - 1, [U32Form::Bits(9), U32Form::Bits(13), U32Form::Bits(18), U32Form::Bits(30)]);
    out.put(0, 3); // the width is given
    put_u32(&mut out, width - 1, [U32Form::Bits(9), U32Form::Bits(13), U32Form::Bits(18), U32Form::Bits(30)]);
    if has_alpha {
        // not all default: 8-bit, one extra channel (alpha, all default), XYB, sRGB
        out.put(0, 1);
        out.put(0, 1); // no extra fields
        out.put(0, 1); // integer samples
        out.put(0, 2); // 8 bits
        out.put(1, 1); // 16 bits are enough for modular
        out.put(1, 2); // one extra channel
        out.put(1, 1); // alpha with the defaults
        out.put(1, 1); // XYB
        out.put(1, 1); // sRGB
        out.put(0, 2); // no extensions
    } else {
        out.put(1, 1);
    }
    out.put(1, 1); // default transform data
    out.align();

    // frame header
    out.put(0, 1); // not all default
    out.put(0, 2); // regular frame
    out.put(0, 1); // VarDCT
    if tuning.skip_lf_smoothing {
        out.put(2, 2); // flags: 128 = skip the decoder's smoothing of the low-frequency image
        out.put(128 - 17, 8);
    } else {
        out.put(0, 2); // no flags
    }
    out.put(0, 2); // no upsampling
    if has_alpha {
        out.put(0, 2);
    }
    out.put(q.x_qm_scale as u64, 3);
    out.put(q.b_qm_scale as u64, 3);
    out.put(0, 2); // one pass
    out.put(0, 1); // no crop
    out.put(0, 2); // blending: replace
    if has_alpha {
        out.put(0, 2);
    }
    out.put(1, 1); // last frame
    out.put(0, 2); // no name
    // restoration filter
    out.put(0, 1);
    out.put(tuning.gaborish as u64, 1);
    if tuning.gaborish {
        out.put(0, 1);
    }
    out.put(tuning.epf_iters as u64, 2);
    if tuning.epf_iters > 0 {
        out.put(0, 1); // sharpness table
        out.put(0, 1); // weights
        if tuning.epf_sigma == EPF_SIGMA_DEFAULT {
            out.put(0, 1);
        } else {
            out.put(1, 1);
            for v in tuning.epf_sigma {
                out.put(bits::f16_bits(v) as u64, 16);
            }
        }
    }
    out.put(0, 2); // no extensions
    out.put(0, 2); // frame header extensions

    // table of contents
    out.put(0, 1); // not permuted
    out.align();
    let mut sections: Vec<Vec<u8>> = Vec::new();
    if n_lf == 1 && n_groups == 1 {
        let mut all = lf_global;
        all.append(&lf_groups[0]);
        all.append(&hf_global);
        all.append(&hf_groups[0]);
        sections.push(all.finish());
    } else {
        sections.push(lf_global.finish());
        for g in lf_groups {
            sections.push(g.finish());
        }
        sections.push(hf_global.finish());
        for g in hf_groups {
            sections.push(g.finish());
        }
    }
    for s in &sections {
        put_u32(
            &mut out,
            s.len() as u32,
            [U32Form::Bits(10), U32Form::BitsOffset(14, 1024), U32Form::BitsOffset(22, 17408), U32Form::BitsOffset(30, 4211712)],
        );
    }
    out.align();
    let mut bytes = out.finish();
    bytes.reserve(sections.iter().map(|s| s.len()).sum());
    for s in sections {
        bytes.extend_from_slice(&s);
    }
    lap("done");
    Ok(bytes)
}

fn grad() -> Box<T> {
    Box::new(T::Leaf(modular::PRED_GRADIENT))
}

/// The picture with the colour of fully transparent pixels made like their neighbours' (they are never seen, and an
/// edge between them and the visible colours would cost bits).
fn fill_transparent(rgba: &[u8], w: usize, h: usize) -> std::borrow::Cow<'_, [u8]> {
    if !rgba.chunks_exact(4).take(w * h).any(|p| p[3] == 0) {
        return std::borrow::Cow::Borrowed(rgba);
    }
    let mut px = rgba[..w * h * 4].to_vec();
    for y in 0..h {
        // the colour to the left, else the one above, else the first visible one in the row
        let first_visible = (0..w).find(|&x| px[(y * w + x) * 4 + 3] != 0);
        for x in 0..w {
            let i = (y * w + x) * 4;
            if px[i + 3] == 0 {
                let from = if x > 0 {
                    Some(i - 4)
                } else if y > 0 {
                    Some(i - w * 4)
                } else {
                    first_visible.map(|f| (y * w + f) * 4)
                };
                if let Some(f) = from {
                    px.copy_within(f..f + 3, i);
                }
            }
        }
    }
    std::borrow::Cow::Owned(px)
}

fn put_global_scale(bw: &mut BitWriter, v: u32) {
    match v {
        1..=2048 => {
            bw.put(0, 2);
            bw.put((v - 1) as u64, 11);
        }
        2049..=4096 => {
            bw.put(1, 2);
            bw.put((v - 2049) as u64, 11);
        }
        4097..=8192 => {
            bw.put(2, 2);
            bw.put((v - 4097) as u64, 12);
        }
        _ => {
            bw.put(3, 2);
            bw.put((v - 8193) as u64, 16);
        }
    }
}

fn put_quant_lf(bw: &mut BitWriter, v: u32) {
    match v {
        16 => bw.put(0, 2),
        1..=32 => {
            bw.put(1, 2);
            bw.put((v - 1) as u64, 5);
        }
        33..=256 => {
            bw.put(2, 2);
            bw.put((v - 1) as u64, 8);
        }
        _ => {
            bw.put(3, 2);
            bw.put((v - 1) as u64, 16);
        }
    }
}