Something went wrong. Try again.
Sans-I/O image codecs for z2d surfaces: BMP, PNG, JPEG, GIF, TGA, XBM, XPM, Netpbm, PCX, ICO and WebP, with an optional sandbox for decoders
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Writes the encoder's output to a directory, for `tools/check_samples.py`//! to hold against libjpeg.//!//! The test suite can check this library's encoder against this library's//! decoder, and does; what it cannot do is check it against anybody else's,//! since a Zig test cannot run Pillow. So the claim that matters most about//! the progressive encoder — that libjpeg decodes a progressive file to the//! *same bytes* as the baseline file written from the same surface — is made//! here instead, in two pieces: this tool writes the pair, and the script//! beside it decodes both and compares them.//!//! ```console//! $ zig build samples//! $ python3 tools/check_samples.py zig-out/samples//! ```//!//! Exactness is the point. The two files carry identical coefficients and//! differ only in how they are spelled, so anything but equality is a bug in//! one of the two coders, and a tolerance would hide it.
const std = @import("std");const Io = std.Io;
const z2d = @import("z2d");const z2dimg = @import("z2dimg");
const Rgba8 = z2dimg.pixels.Rgba8;
/// One image to write, and what makes it worth writing.const Case = struct { name: []const u8, width: i32, height: i32, chroma: z2dimg.jpeg.Chroma, restart_interval: u16 = 0, quality: u7 = 85, greyscale: bool = false, colour: z2dimg.jpeg.Colour = .auto, /// A scan script for the progressive file, or null for the default. script: ?[]const z2dimg.jpeg.Scan = null, /// A flat divisor for both tables, or zero to scale the Annex K ones by /// `quality` as usual. flat_quant: u16 = 0, /// Choose coefficients by what they cost rather than by what is nearest. trellis: bool = false,};
/// Everything in one pass, with no successive approximation: the shortest/// complete progressive script there is, and the one furthest from the/// default.const plain_script = [_]z2dimg.jpeg.Scan{ .{ .components = &.{ 0, 1, 2 }, .ss = 0, .se = 0, .ah = 0, .al = 0 }, .{ .components = &.{0}, .ss = 1, .se = 63, .ah = 0, .al = 0 }, .{ .components = &.{1}, .ss = 1, .se = 63, .ah = 0, .al = 0 }, .{ .components = &.{2}, .ss = 1, .se = 63, .ah = 0, .al = 0 },};
/// Three bits of successive approximation on the DC coefficient where the/// default uses one, and the AC spectrum in three bands.const fine_script = [_]z2dimg.jpeg.Scan{ .{ .components = &.{ 0, 1, 2 }, .ss = 0, .se = 0, .ah = 0, .al = 2 }, .{ .components = &.{ 0, 1, 2 }, .ss = 0, .se = 0, .ah = 2, .al = 1 }, .{ .components = &.{ 0, 1, 2 }, .ss = 0, .se = 0, .ah = 1, .al = 0 }, .{ .components = &.{0}, .ss = 1, .se = 2, .ah = 0, .al = 0 }, .{ .components = &.{0}, .ss = 3, .se = 20, .ah = 0, .al = 0 }, .{ .components = &.{0}, .ss = 21, .se = 63, .ah = 0, .al = 1 }, .{ .components = &.{0}, .ss = 21, .se = 63, .ah = 1, .al = 0 }, .{ .components = &.{1}, .ss = 1, .se = 63, .ah = 0, .al = 0 }, .{ .components = &.{2}, .ss = 1, .se = 63, .ah = 0, .al = 0 },};
const cases = [_]Case{ // Every chroma ratio at a size that fills its MCUs exactly. .{ .name = "444", .width = 64, .height = 48, .chroma = .full }, .{ .name = "422", .width = 64, .height = 48, .chroma = .horizontal }, .{ .name = "440", .width = 64, .height = 48, .chroma = .vertical }, .{ .name = "420", .width = 64, .height = 48, .chroma = .half }, // And sizes that do not, which is where a scan of one component stops // short of the padding an interleaved one walks. .{ .name = "ragged-444", .width = 33, .height = 17, .chroma = .full }, .{ .name = "ragged-420", .width = 33, .height = 17, .chroma = .half }, .{ .name = "tiny", .width = 7, .height = 3, .chroma = .half }, .{ .name = "one-pixel", .width = 1, .height = 1, .chroma = .half }, // Restart markers, which break an end-of-block run. .{ .name = "restarts", .width = 64, .height = 48, .chroma = .half, .restart_interval = 3 }, .{ .name = "restarts-444", .width = 64, .height = 48, .chroma = .full, .restart_interval = 1 }, // The quality extremes, where the coefficients are almost all zero and // almost none of them are. .{ .name = "q10", .width = 64, .height = 48, .chroma = .half, .quality = 10 }, .{ .name = "q100", .width = 64, .height = 48, .chroma = .full, .quality = 100 }, // And one component, which uses the shorter scan script. .{ .name = "greyscale", .width = 40, .height = 24, .chroma = .full, .greyscale = true }, // A colour surface written as one component, which is the same scan // script reached a different way and a different luma: computed from // three channels rather than read from one. .{ .name = "grey-from-colour", .width = 40, .height = 24, .chroma = .full, .colour = .greyscale }, // And an alpha-only surface written as three, which is a grey image with // both chroma components flat all the way through. .{ .name = "colour-from-grey", .width = 40, .height = 24, .chroma = .half, .greyscale = true, .colour = .ycbcr }, // Quantisation tables the quality scale cannot produce: flat, where the // Annex K ones rise steeply towards the high frequencies. .{ .name = "flat-quant-1", .width = 64, .height = 48, .chroma = .full, .flat_quant = 1 }, .{ .name = "flat-quant-40", .width = 64, .height = 48, .chroma = .half, .flat_quant = 40 }, // Sampling factors no named ratio covers. libjpeg upsamples a ratio of // anything but two by replication where this library interpolates, so the // two decoders disagree about the pixels --- but the check here is that // the baseline and progressive files agree with *each other*, which is a // claim about this encoder and is unaffected. .{ .name = "411", .width = 64, .height = 48, .chroma = .{ .factors = .{ .luma = .{ .h = 4, .v = 1 } } } }, .{ .name = "3x1", .width = 64, .height = 48, .chroma = .{ .factors = .{ .luma = .{ .h = 3, .v = 1 } } } }, .{ .name = "4x2", .width = 64, .height = 48, .chroma = .{ .factors = .{ .luma = .{ .h = 4, .v = 2 } } } }, .{ .name = "mixed", .width = 64, .height = 48, .chroma = .{ .factors = .{ .luma = .{ .h = 2, .v = 2 }, .cb = .{ .h = 2, .v = 1 }, .cr = .{ .h = 1, .v = 1 }, } } }, // And one that does not divide by its MCU, since a scan of one component // walks fewer blocks than an interleaved one and the factors decide how // many fewer. .{ .name = "411-ragged", .width = 37, .height = 19, .chroma = .{ .factors = .{ .luma = .{ .h = 4, .v = 1 } } } }, // Scan scripts other than the default. Whatever a script does to the // order, a complete one carries the same coefficients, so libjpeg must // still decode it to the baseline file's bytes. .{ .name = "script-plain", .width = 64, .height = 48, .chroma = .half, .script = &plain_script }, .{ .name = "script-fine", .width = 64, .height = 48, .chroma = .half, .script = &fine_script }, .{ .name = "script-fine-444", .width = 33, .height = 17, .chroma = .full, .script = &fine_script }, // Coefficients chosen by cost. Nothing about the file changes --- it is // an ordinary JPEG with different numbers in it --- so the baseline and // progressive files still have to agree with each other exactly. .{ .name = "trellis", .width = 64, .height = 48, .chroma = .half, .trellis = true }, .{ .name = "trellis-444", .width = 64, .height = 48, .chroma = .full, .trellis = true }, .{ .name = "trellis-q40", .width = 64, .height = 48, .chroma = .half, .quality = 40, .trellis = true },};
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator());
var stderr_buffer: [512]u8 = undefined; var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buffer); const stderr = &stderr_writer.interface;
if (args.len != 2) { try stderr.writeAll("usage: samples <directory>\n"); try stderr.flush(); std.process.exit(2); }
var dir = try Io.Dir.cwd().createDirPathOpen(io, args[1], .{}); defer dir.close(io);
// Which way up, in every value the tag has, written into all three // shapes the encoders can put it in. The `.ori` sidecar is the value, for // the script to hold Pillow's reading against. for (1..9) |value| { const o: z2dimg.exif.Orientation = @fromBackingInt(@intCast(value)); var sfc = try pattern(gpa, .{ .name = "o", .width = 20, .height = 12, .chroma = .half }); defer sfc.deinit(gpa);
var stem_buf: [64]u8 = undefined; const stem = try std.fmt.bufPrint(&stem_buf, "ori-{d}", .{value});
var digit: [1]u8 = .{@intCast('0' + value)}; var buf: [64]u8 = undefined; try write(io, dir, try std.fmt.bufPrint(&buf, "{s}.ori", .{stem}), &digit);
for ([_]z2dimg.jpeg.Mode{ .baseline, .progressive }) |mode| { var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); try z2dimg.encode(gpa, &sfc, &out.writer, .{ .jpeg = .{ .chroma = .half, .mode = mode, .orientation = o, } }); try write(io, dir, try std.fmt.bufPrint(&buf, "{s}-{t}.jpg", .{ stem, mode }), out.written()); }
var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); try z2dimg.encode(gpa, &sfc, &out.writer, .{ .png = .{ .orientation = o } }); try write(io, dir, try std.fmt.bufPrint(&buf, "{s}.png", .{stem}), out.written()); }
// A profile-shaped block, in two sizes: one that fits in a single `APP2` // segment and one that has to be split across three. What is in it is // arbitrary --- nothing reads a profile --- but it has the header that // makes it one, and a pattern behind that so a profile which came back // subtly wrong is not mistaken for one that came back right. for ([_]usize{ 3000, 140_000 }) |len| { const profile = try gpa.alloc(u8, len); defer gpa.free(profile); for (profile, 0..) |*b, i| b.* = @truncate(i *% 97 +% 13); std.mem.writeInt(u32, profile[0..4], @intCast(len), .big); @memcpy(profile[36..40], "acsp");
var sfc = try pattern(gpa, .{ .name = "icc", .width = 32, .height = 24, .chroma = .half }); defer sfc.deinit(gpa);
var name_buf: [64]u8 = undefined; const stem = try std.fmt.bufPrint(&name_buf, "icc-{d}", .{len});
// The profile itself, for the script to compare against. try write(io, dir, try std.fmt.bufPrint(name_buf[stem.len..], "{s}.icc", .{stem}), profile);
for ([_]z2dimg.jpeg.Mode{ .baseline, .progressive }) |mode| { var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); try z2dimg.encode(gpa, &sfc, &out.writer, .{ .jpeg = .{ .chroma = .half, .mode = mode, .icc = profile, } }); var buf: [64]u8 = undefined; try write(io, dir, try std.fmt.bufPrint(&buf, "{s}-{t}.jpg", .{ stem, mode }), out.written()); }
var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); try z2dimg.encode(gpa, &sfc, &out.writer, .{ .png = .{ .icc = profile } }); var buf: [64]u8 = undefined; try write(io, dir, try std.fmt.bufPrint(&buf, "{s}.png", .{stem}), out.written()); }
// Every PCX shape the encoder writes, beside the pixels it was written // from. The script decodes each with Pillow and with ImageMagick, and // holds them to the `.rgba` sidecar exactly: a paletted shape loses // nothing, so a reader that disagrees is reading the palette, the planes // or the packing differently from how this wrote them. for ([_]struct { z2dimg.pcx.Shape, u32 }{ .{ .packed_4, 4 }, .{ .packed_16, 16 }, .{ .planar_16, 16 }, .{ .planar_16, 2 }, .{ .indexed_256, 256 }, .{ .rgb, 0 }, .{ .rgba, 0 }, }) |shape_case| { const shape, const colors = shape_case; // Thirteen wide, so that every plane's row ends partway through a // byte and is padded to an even length. var sfc = try pcxPattern(gpa, 13, 21, colors, shape == .rgba); defer sfc.deinit(gpa);
var name_buf: [64]u8 = undefined; const stem = try std.fmt.bufPrint(&name_buf, "pcx-{t}-{d}", .{ shape, colors });
const expected = try gpa.alloc(u8, 13 * 21 * 4); defer gpa.free(expected); var row: [13]Rgba8 = undefined; for (0..21) |y| { z2dimg.pixels.readRow(&row, &sfc, @intCast(y)); for (row, 0..) |px, x| { @memcpy(expected[(y * 13 + x) * 4 ..][0..4], &[4]u8{ px.r, px.g, px.b, px.a }); } } var buf: [64]u8 = undefined; try write(io, dir, try std.fmt.bufPrint(&buf, "{s}.rgba", .{stem}), expected);
var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); try z2dimg.encode(gpa, &sfc, &out.writer, .{ .pcx = .{ .shape = shape } }); try write(io, dir, try std.fmt.bufPrint(&buf, "{s}.pcx", .{stem}), out.written()); }
var written: usize = 0; for (cases) |case| { var sfc = try pattern(gpa, case); defer sfc.deinit(gpa);
for ([_]z2dimg.jpeg.Mode{ .baseline, .progressive }) |mode| { var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); try z2dimg.encode(gpa, &sfc, &out.writer, .{ .jpeg = .{ .quality = case.quality, .chroma = case.chroma, .restart_interval = case.restart_interval, .mode = mode, .colour = case.colour, .script = case.script, .trellis = case.trellis, .quant = if (case.flat_quant == 0) null else .{ .luma = @splat(case.flat_quant), .chroma = @splat(case.flat_quant), }, } });
var name_buf: [64]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "{s}-{t}.jpg", .{ case.name, mode }); try write(io, dir, name, out.written()); written += 1; } }
try stderr.print("wrote {d} files to {s}\n", .{ written, args[1] }); try stderr.flush();}
/// One file into the directory.fn write(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8) !void { var file = try dir.createFile(io, name, .{}); defer file.close(io); var buf: [4096]u8 = undefined; var writer = file.writer(io, &buf); try writer.interface.writeAll(bytes); try writer.interface.flush();}
/// A PCX test image: exactly `colors` distinct colors, or a gradient when/// that is zero, with a column of graded transparency when `alpha` is set.fn pcxPattern(gpa: std.mem.Allocator, width: i32, height: i32, colors: u32, alpha: bool) !z2d.Surface { var sfc: z2d.Surface = try .init(.image_surface_rgba, gpa, width, height); errdefer sfc.deinit(gpa); const w: u32 = @intCast(width); const row = try gpa.alloc(Rgba8, w); defer gpa.free(row); for (0..@intCast(height)) |y| { for (row, 0..) |*px, x| { const i: u32 = @intCast(y * w + x); px.* = if (colors == 0) .{ .r = @intCast((x * 19 + y * 3) % 256), .g = @intCast((y * 12 + 7) % 256), .b = @intCast((x * y * 5 + 40) % 256), .a = 255, } else blk: { const c = i % colors; break :blk .{ .r = @intCast((c * 37) % 256), .g = @intCast((c / 7 * 53 + 11) % 256), .b = @intCast(255 - c), .a = 255, }; }; // Alpha only where every value of it survives premultiplication // exactly: fully opaque, fully clear, or on a color of 255s. if (alpha and x == 0) px.* = .{ .r = 255, .g = 255, .b = 255, .a = @intCast(y * 12) }; if (alpha and x == 1 and y % 3 == 0) px.* = .{ .r = 0, .g = 0, .b = 0, .a = 0 }; } z2dimg.pixels.writeRow(&sfc, @intCast(y), row); } return sfc;}
/// Something with enough structure in it to exercise the coder: a gradient for/// the low frequencies, and a check pattern on top for the high ones. A flat/// image would leave every AC coefficient zero and every scan after the first/// an end-of-block run.fn pattern(gpa: std.mem.Allocator, case: Case) !z2d.Surface { var sfc: z2d.Surface = try .init( if (case.greyscale) .image_surface_alpha8 else .image_surface_rgb, gpa, case.width, case.height, ); errdefer sfc.deinit(gpa);
const w: u32 = @intCast(case.width); const h: u32 = @intCast(case.height); var y: u32 = 0; while (y < h) : (y += 1) { var x: u32 = 0; while (x < w) : (x += 1) { const checks: u32 = if ((x / 3 + y / 5) % 2 == 0) 40 else 0; const r: u32 = 20 + x * 180 / @max(1, w - 1) + checks; const g: u32 = 30 + y * 180 / @max(1, h - 1) + checks; const b: u32 = 40 + (x + y) * 90 / @max(1, w + h - 2) + checks; if (case.greyscale) { sfc.putPixel(@intCast(x), @intCast(y), .{ .alpha8 = .{ .a = @intCast(@min(255, r)) }, }); } else { sfc.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = @intCast(@min(255, r)), .g = @intCast(@min(255, g)), .b = @intCast(@min(255, b)), } }); } } } return sfc;}