// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Writes one compressed meta-block from its commands: chooses how each of //! its three streams of symbols is coded — block types, context modeling, //! prefix codes — and writes the header and the data that follows it. //! //! The streams are the literals, one insert-and-copy symbol per command, //! and one distance symbol per command that writes its distance out. With //! block splitting each stream is divided into blocks, each coded with the //! prefix codes of its block type; the decompressor is told where blocks //! switch by commands interleaved with the data. Literals also go through a //! context map, which with context modeling sends literals to codes by the //! two bytes before them as well as by block type. const std = @import("std"); const Allocator = std.mem.Allocator; const BitWriter = @import("BitWriter.zig"); const block_split = @import("block_split.zig"); const context = @import("context.zig"); const format = @import("format.zig"); const histogram = @import("histogram.zig"); const literal_contexts = @import("literal_contexts.zig"); const store = @import("store.zig"); const MetaBlockEncoder = @This(); /// One insert-and-copy command of a meta-block. pub const Command = struct { insert_len: u32, /// Zero for the last command of a meta-block, which only inserts. For a /// dictionary word, the length of the base word. copy_len: u32, /// How many bytes of input the copy covers: `copy_len`, except for a /// dictionary word whose transform changes its length. output_len: u32, symbol: u16, /// Whether a distance code follows, and if so which. has_distance: bool, distance: format.DistanceCode, }; pub const Options = struct { /// The most literal codes context modeling may use; 1 for none. literal_trees: u16, /// Divide the streams into blocks of different types. split: bool, }; /// How block splitting divides each stream. const literal_split: block_split.Options = .{ .chunk = 1024, .max_types = 8, .switch_cost = 28.1 }; const command_split: block_split.Options = .{ .chunk = 256, .max_types = 8, .switch_cost = 13.5 }; const distance_split: block_split.Options = .{ .chunk = 256, .max_types = 8, .switch_cost = 14.6 }; /// The block structure of one stream and the codes for its switches. const Category = struct { types: u16 = 1, blocks: std.ArrayList(block_split.Block) = .empty, type_code: store.Code = undefined, count_code: store.Code = undefined, fn deinit(cat: *Category, gpa: Allocator) void { cat.blocks.deinit(gpa); } /// Builds the codes for the block switches. fn buildCodes(cat: *Category) void { if (cat.types < 2) return; var type_counts: [format.max_block_types + 2]u32 = @splat(0); var count_counts: [format.num_block_count_symbols]u32 = @splat(0); var state: SwitchState = .{}; for (cat.blocks.items, 0..) |b, i| { if (i > 0) type_counts[state.symbol(b.type, cat.types)] += 1; count_counts[format.blockLengthCode(b.len)] += 1; } cat.type_code.init(type_counts[0 .. cat.types + 2], format.max_code_length); cat.count_code.init(&count_counts, format.max_code_length); } /// NBLTYPES, and if there is more than one type, the switch codes and /// the first block's length. fn writeHeader(cat: *const Category, bw: *BitWriter, gpa: Allocator) Allocator.Error!void { try store.varLenUint8(bw, gpa, @intCast(cat.types - 1)); if (cat.types < 2) return; try store.prefixCode(bw, gpa, &cat.type_code); try store.prefixCode(bw, gpa, &cat.count_code); try writeCount(bw, gpa, &cat.count_code, cat.blocks.items[0].len); } }; fn writeCount(bw: *BitWriter, gpa: Allocator, code: *const store.Code, len: u32) Allocator.Error!void { const c = format.blockLengthCode(len); const lc = format.block_length_codes[c]; try code.write(bw, gpa, c); try bw.writeBits(gpa, lc.extra_bits, len - lc.base); } /// The previous and current block type, kept as the decompressor keeps /// them, to know which symbol stands for a switch. const SwitchState = struct { previous: u16 = 1, current: u16 = 0, fn symbol(s: *SwitchState, next: u16, types: u16) u16 { const sym: u16 = if (next == s.previous) 0 else if (next == (s.current + 1) % types) 1 else next + 2; s.previous = s.current; s.current = next; return sym; } }; /// Where the writer is in one stream's blocks. const Cursor = struct { cat: *const Category, block: usize = 0, remaining: u32, state: SwitchState = .{}, fn init(cat: *const Category) Cursor { return .{ .cat = cat, .remaining = if (cat.types < 2) std.math.maxInt(u32) else cat.blocks.items[0].len }; } /// The block type of the next symbol, writing a block switch first if /// one is due. fn next(cur: *Cursor, bw: *BitWriter, gpa: Allocator) Allocator.Error!u16 { if (cur.remaining == 0) { cur.block += 1; const b = cur.cat.blocks.items[cur.block]; try cur.cat.type_code.write(bw, gpa, cur.state.symbol(b.type, cur.cat.types)); try writeCount(bw, gpa, &cur.cat.count_code, b.len); cur.remaining = b.len; } cur.remaining -= 1; return cur.state.current; } }; gpa: Allocator, /// Where each literal of the meta-block is, in the data. literal_positions: std.ArrayList(u32) = .empty, literal_symbols: std.ArrayList(u16) = .empty, command_symbols: std.ArrayList(u16) = .empty, distance_symbols: std.ArrayList(u16) = .empty, literals: Category = .{}, commands: Category = .{}, distances: Category = .{}, /// Literal coding: the context mode of each literal block type, how many /// literal codes, and which code each block type and context uses. modes: [format.max_block_types]context.Mode = undefined, literal_trees: u16 = 1, /// What the literals cost under the current literal codes, in bits. literal_data_bits: u64 = 0, literal_map: std.ArrayList(u8) = .empty, literal_codes: std.ArrayList(store.Code) = .empty, command_codes: std.ArrayList(store.Code) = .empty, distance_codes: std.ArrayList(store.Code) = .empty, scratch: ?*literal_contexts.Scratch = null, /// Somewhere to write a header to see how big it is. probe: BitWriter = .{}, pub fn init(gpa: Allocator) MetaBlockEncoder { return .{ .gpa = gpa }; } pub fn deinit(e: *MetaBlockEncoder) void { const gpa = e.gpa; e.literal_positions.deinit(gpa); e.literal_symbols.deinit(gpa); e.command_symbols.deinit(gpa); e.distance_symbols.deinit(gpa); e.literals.deinit(gpa); e.commands.deinit(gpa); e.distances.deinit(gpa); e.literal_map.deinit(gpa); e.literal_codes.deinit(gpa); e.command_codes.deinit(gpa); e.distance_codes.deinit(gpa); if (e.scratch) |s| gpa.destroy(s); e.probe.deinit(gpa); e.* = undefined; } /// Writes the meta-block holding `data[start..end]`, made of `commands`, to /// `bw`. `base` is the position in the stream of `data[0]`. pub fn encode(e: *MetaBlockEncoder, bw: *BitWriter, data: []const u8, base: u64, start: usize, end: usize, commands: []const Command, options: Options) Allocator.Error!void { const gpa = e.gpa; try e.gather(data, start, commands); // Block types for each stream. if (options.split) { e.literals.types = @intCast(try block_split.split(gpa, e.literal_symbols.items, format.num_literal_symbols, literal_split, &e.literals.blocks)); e.commands.types = @intCast(try block_split.split(gpa, e.command_symbols.items, format.num_command_symbols, command_split, &e.commands.blocks)); e.distances.types = @intCast(try block_split.split(gpa, e.distance_symbols.items, format.distanceAlphabetSize(0, 0), distance_split, &e.distances.blocks)); } else { for ([_]*Category{ &e.literals, &e.commands, &e.distances }) |cat| { cat.types = 1; cat.blocks.clearRetainingCapacity(); } } e.literals.buildCodes(); e.commands.buildCodes(); e.distances.buildCodes(); try e.buildSymbolCodes(&e.commands, e.command_symbols.items, format.num_command_symbols, &e.command_codes); try e.buildSymbolCodes(&e.distances, e.distance_symbols.items, format.distanceAlphabetSize(0, 0), &e.distance_codes); try e.chooseLiteralCoding(data, base, options.literal_trees); // The header. try store.metaBlockLength(bw, gpa, @intCast(end - start)); try bw.writeBits(gpa, 1, 0); // ISUNCOMPRESSED try e.literals.writeHeader(bw, gpa); try e.commands.writeHeader(bw, gpa); try e.distances.writeHeader(bw, gpa); try bw.writeBits(gpa, 2 + 4, 0); // NPOSTFIX, NDIRECT for (e.modes[0..e.literals.types]) |m| try bw.writeBits(gpa, 2, @backingInt(m)); try e.writeLiteralMap(bw); // A distance code per distance block type, whatever the copy length. try store.varLenUint8(bw, gpa, @intCast(e.distances.types - 1)); if (e.distances.types > 1) { var map: [format.distance_contexts * format.max_block_types]u8 = undefined; for (0..e.distances.types) |t| @memset(map[t * 4 ..][0..4], @intCast(t)); try store.contextMap(bw, gpa, map[0 .. 4 * @as(usize, e.distances.types)], e.distances.types); } try e.writeLiteralCodes(bw); for (e.command_codes.items) |*code| try store.prefixCode(bw, gpa, code); for (e.distance_codes.items) |*code| try store.prefixCode(bw, gpa, code); // The data. var lit: Cursor = .init(&e.literals); var cmd: Cursor = .init(&e.commands); var dist: Cursor = .init(&e.distances); var pos = start; for (commands) |command| { const ct = try cmd.next(bw, gpa); try e.command_codes.items[ct].write(bw, gpa, command.symbol); const parts = format.command(command.symbol); const ins = format.insert_length_codes[parts.insert_code]; const cpy = format.copy_length_codes[parts.copy_code]; try bw.writeBits(gpa, ins.extra_bits, command.insert_len - ins.base); // The last command's copy length means nothing, but its extra bits // are read all the same. try bw.writeBits(gpa, cpy.extra_bits, if (command.copy_len == 0) 0 else command.copy_len - cpy.base); if (e.literals.types == 1 and e.literal_trees == 1) { // No block types and no context modeling: one code for all. for (data[pos..][0..command.insert_len]) |b| try e.literal_codes.items[0].write(bw, gpa, b); } else for (pos..pos + command.insert_len) |k| { const lt = try lit.next(bw, gpa); const p1 = previous(data, base, k, 1); const p2 = previous(data, base, k, 2); const ctx = context.id(e.modes[lt], p1, p2); const tree = e.literal_map.items[@as(usize, lt) * format.literal_contexts + ctx]; try e.literal_codes.items[tree].write(bw, gpa, data[k]); } if (command.has_distance) { const dt = try dist.next(bw, gpa); try e.distance_codes.items[dt].write(bw, gpa, command.distance.code); try bw.writeBits(gpa, command.distance.extra_bits, command.distance.extra); } pos += command.insert_len + command.output_len; } std.debug.assert(pos == end); } fn previous(data: []const u8, base: u64, k: usize, back: usize) u8 { return if (base + k < back) 0 else data[k - back]; } /// The three streams of symbols, in order. fn gather(e: *MetaBlockEncoder, data: []const u8, start: usize, commands: []const Command) Allocator.Error!void { const gpa = e.gpa; e.literal_positions.clearRetainingCapacity(); e.literal_symbols.clearRetainingCapacity(); e.command_symbols.clearRetainingCapacity(); e.distance_symbols.clearRetainingCapacity(); var pos = start; for (commands) |command| { for (pos..pos + command.insert_len) |k| { try e.literal_positions.append(gpa, @intCast(k)); try e.literal_symbols.append(gpa, data[k]); } try e.command_symbols.append(gpa, command.symbol); if (command.has_distance) try e.distance_symbols.append(gpa, command.distance.code); pos += command.insert_len + command.output_len; } } /// A code per block type, from the symbols that type's blocks hold. fn buildSymbolCodes(e: *MetaBlockEncoder, cat: *const Category, symbols: []const u16, alphabet: usize, codes: *std.ArrayList(store.Code)) Allocator.Error!void { const gpa = e.gpa; const counts = try gpa.alloc(u32, @as(usize, cat.types) * alphabet); defer gpa.free(counts); @memset(counts, 0); if (cat.types < 2) { for (symbols) |s| counts[s] += 1; } else { var i: usize = 0; for (cat.blocks.items) |b| { for (symbols[i..][0..b.len]) |s| counts[@as(usize, b.type) * alphabet + s] += 1; i += b.len; } } try codes.resize(gpa, cat.types); for (codes.items, 0..) |*code, t| code.init(counts[t * alphabet ..][0..alphabet], format.max_code_length); } /// The block type of each literal, written to `types`. fn literalTypes(e: *const MetaBlockEncoder, types: []u8) void { if (e.literals.types < 2) { @memset(types, 0); return; } var i: usize = 0; for (e.literals.blocks.items) |b| { @memset(types[i..][0..b.len], b.type); i += b.len; } } /// Decides how the literals are coded: a code per block type, or context /// modeling with up to `max_trees` codes shared among every block type and /// context. Context modeling is used only where it comes out smaller, /// header and all. fn chooseLiteralCoding(e: *MetaBlockEncoder, data: []const u8, base: u64, max_trees: u16) Allocator.Error!void { const gpa = e.gpa; const types = e.literals.types; const n = e.literal_symbols.items.len; const per_type = try gpa.alloc(u8, n); defer gpa.free(per_type); e.literalTypes(per_type); // A code per type, each used for every context. const simple_counts = try gpa.alloc(u32, @as(usize, types) * format.num_literal_symbols); defer gpa.free(simple_counts); @memset(simple_counts, 0); for (e.literal_symbols.items, per_type) |s, t| simple_counts[@as(usize, t) * format.num_literal_symbols + s] += 1; try e.useLiteralCoding(@splat(.lsb6), types, null, simple_counts); if (max_trees < 2 or n < 1024) return; // The context mode that suits these literals best, if any does. if (e.scratch == null) e.scratch = try gpa.create(literal_contexts.Scratch); const scratch = e.scratch.?; var runs: std.ArrayList(literal_contexts.Run) = .empty; defer runs.deinit(gpa); try literalRuns(gpa, e.literal_positions.items, &runs); const plan = try literal_contexts.plan(gpa, scratch, data, base, runs.items, max_trees); if (plan.trees < 2) return; // Histograms by block type and context, merged into codes. const contexts = @as(usize, types) * format.literal_contexts; const counts = try gpa.alloc(u32, contexts * format.num_literal_symbols); defer gpa.free(counts); @memset(counts, 0); for (e.literal_positions.items, per_type) |k, t| { const ctx = context.id(plan.mode, previous(data, base, k, 1), previous(data, base, k, 2)); counts[(@as(usize, t) * format.literal_contexts + ctx) * format.num_literal_symbols + data[k]] += 1; } const map = try gpa.alloc(u8, contexts); defer gpa.free(map); const trees = try clusterLiteralContexts(gpa, counts, types, map, max_trees); if (trees < 2 and types < 2) return; // Measure both, and keep the smaller. const simple_bits = try e.literalBits(); try e.useLiteralCoding(@splat(plan.mode), trees, map, counts[0 .. @as(usize, trees) * format.num_literal_symbols]); const modeled_bits = try e.literalBits(); if (modeled_bits >= simple_bits) try e.useLiteralCoding(@splat(.lsb6), types, null, simple_counts); } /// Sets the literal coding: a mode for every block type, `trees` codes /// built from the histograms in `counts`, and the map from block type and /// context to code, or with `map` null, one code per block type. fn useLiteralCoding(e: *MetaBlockEncoder, modes: [format.max_block_types]context.Mode, trees: u16, map: ?[]const u8, counts: []const u32) Allocator.Error!void { const gpa = e.gpa; e.modes = modes; e.literal_trees = trees; const contexts = @as(usize, e.literals.types) * format.literal_contexts; try e.literal_map.resize(gpa, contexts); if (map) |m| { @memcpy(e.literal_map.items, m); } else { for (0..e.literals.types) |t| @memset(e.literal_map.items[t * format.literal_contexts ..][0..format.literal_contexts], @intCast(t)); } try e.literal_codes.resize(gpa, trees); e.literal_data_bits = 0; for (e.literal_codes.items, 0..) |*code, t| { const h = counts[t * format.num_literal_symbols ..][0..format.num_literal_symbols]; code.init(h, format.max_code_length); // Each code's histogram is exactly the literals sent to it. e.literal_data_bits += code.cost(h); } } /// The literals' positions as runs of consecutive ones. fn literalRuns(gpa: Allocator, positions: []const u32, runs: *std.ArrayList(literal_contexts.Run)) Allocator.Error!void { for (positions) |k| { if (runs.items.len > 0) { const last = &runs.items[runs.items.len - 1]; if (last.start + last.len == k) { last.len += 1; continue; } } try runs.append(gpa, .{ .start = k, .len = 1 }); } } /// Merges the literal histograms of every block type and context in /// `counts` into at most `max_trees` codes, writing which code each uses to /// `map` and the codes' histograms to the front of `counts`. Each block /// type's 64 contexts are clustered first, then the clusters of all the /// types together, which keeps the work small. A context with no literals /// shares the code of the context before it, which makes the map cheaper to /// write. Returns how many codes there are. fn clusterLiteralContexts(gpa: Allocator, counts: []u32, types: u16, map: []u8, max_trees: u16) Allocator.Error!u16 { const alphabet = format.num_literal_symbols; const per_type = format.literal_contexts * alphabet; var first: [format.max_block_types][format.literal_contexts]u16 = undefined; var offset: [format.max_block_types + 1]usize = undefined; offset[0] = 0; for (0..types) |t| { const slice = counts[t * per_type ..][0..per_type]; const k = try histogram.cluster(gpa, slice, alphabet, &first[t], max_trees); offset[t + 1] = offset[t] + k; } const total = offset[types]; if (total == 0) { @memset(map, 0); return 1; } // Gather every type's clusters together and cluster them again. const gathered = try gpa.alloc(u32, total * alphabet); defer gpa.free(gathered); for (0..types) |t| { const k = offset[t + 1] - offset[t]; @memcpy(gathered[offset[t] * alphabet ..][0 .. k * alphabet], counts[t * per_type ..][0 .. k * alphabet]); } const second = try gpa.alloc(u16, total); defer gpa.free(second); const trees = try histogram.cluster(gpa, gathered, alphabet, second, max_trees); @memcpy(counts[0 .. trees * alphabet], gathered[0 .. trees * alphabet]); for (0..types) |t| { var previous_tree: u8 = 0; for (0..format.literal_contexts) |ctx| { const c = first[t][ctx]; if (c != histogram.unassigned) previous_tree = @intCast(second[offset[t] + c]); map[t * format.literal_contexts + ctx] = previous_tree; } } return @intCast(trees); } /// What the current literal coding costs: its header and its data. fn literalBits(e: *MetaBlockEncoder) Allocator.Error!u64 { e.probe.restore(.{ .len = 0, .acc = 0, .count = 0 }); try e.writeLiteralMap(&e.probe); try e.writeLiteralCodes(&e.probe); return e.probe.bitLength() + e.literal_data_bits; } /// NTREESL, and the literal context map if there is more than one code. fn writeLiteralMap(e: *MetaBlockEncoder, bw: *BitWriter) Allocator.Error!void { try store.varLenUint8(bw, e.gpa, @intCast(e.literal_trees - 1)); if (e.literal_trees > 1) try store.contextMap(bw, e.gpa, e.literal_map.items, e.literal_trees); } /// The literal codes, which come later in the header than the map. fn writeLiteralCodes(e: *MetaBlockEncoder, bw: *BitWriter) Allocator.Error!void { for (e.literal_codes.items) |*code| try store.prefixCode(bw, e.gpa, code); }