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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! PCX, in every shape the format has.//!//! The fixtures are written by Pillow and ImageMagick and the expected pixels//! read back out of Pillow --- except for the two shapes no reader here//! supports, four bits packed and a version 3 file, where the expectation is//! the builder's. See `tools/gen_pcx_fixtures.py`.//!//! What makes PCX worth this many cases is that `bits_per_pixel` is per//! *plane*, so the same two small numbers describe seven different memory//! layouts, and the planar ones are not historical curiosities: ImageMagick//! writes one for any image of sixteen colours or fewer, today.
const std = @import("std");const Io = std.Io;const mem = std.mem;const testing = std.testing;const Allocator = mem.Allocator;
const z2d = @import("z2d");const z2dimg = @import("z2dimg");
const fixtures = @import("pcx_fixtures.zig");const Rgba8 = z2dimg.pixels.Rgba8;
fn decodeBytes(gpa: Allocator, bytes: []const u8) !z2d.Surface { var r: Io.Reader = .fixed(bytes); return z2dimg.decode(gpa, &r, .{});}
fn at(sfc: z2d.Surface, x: i32, y: i32) Rgba8 { return Rgba8.fromZ2d(sfc.getPixel(x, y).?);}
fn expectPixels(sfc: z2d.Surface, expected: []const Rgba8) !void { try testing.expectEqual(@as(i32, fixtures.width), sfc.getWidth()); try testing.expectEqual(@as(i32, fixtures.height), sfc.getHeight()); for (expected, 0..) |want, i| { const x: i32 = @intCast(i % fixtures.width); const y: i32 = @intCast(i / fixtures.width); const got = at(sfc, x, y); testing.expectEqual(want, got) catch |err| { std.debug.print("at ({d},{d}): want {any}, got {any}\n", .{ x, y, want, got }); return err; }; }}
test "every shape the format has decodes to what a reader says is in it" { const gpa = testing.allocator; const cases = [_]struct { []const u8, []const Rgba8, []const u8 }{ .{ &fixtures.rgb, &fixtures.rgb_pixels, "eight bits in three planes" }, .{ &fixtures.grey, &fixtures.grey_pixels, "eight bits in one plane, greyscale palette" }, .{ &fixtures.paletted, &fixtures.paletted_pixels, "eight bits in one plane, colour palette" }, .{ &fixtures.mono, &fixtures.mono_pixels, "one bit in one plane" }, .{ &fixtures.ega, &fixtures.ega_pixels, "one bit in each of four planes" }, .{ &fixtures.packed_4, &fixtures.packed_4_pixels, "four bits in one plane" }, .{ &fixtures.version_3, &fixtures.version_3_pixels, "version 3, no palette" }, }; for (cases) |case| { const bytes, const want, const what = case; var sfc = decodeBytes(gpa, bytes) catch |err| { std.debug.print("{s}: {t}\n", .{ what, err }); return err; }; defer sfc.deinit(gpa); expectPixels(sfc, want) catch |err| { std.debug.print("in the case of {s}\n", .{what}); return err; }; }}
test "a monochrome file whose palette says nothing is black and white" { // Pillow writes a one-bit PCX with sixteen palette entries of zero and // renders the set bit white itself. Believing that palette would make the // image one flat black rectangle --- a palette whose two entries are the // same colour cannot tell the two values apart, so it is not a palette. // // Scoped to one bit in one plane. A four-plane file names real colours // and is believed, which the `ega` case above is the evidence for. const gpa = testing.allocator; var sfc = try decodeBytes(gpa, &fixtures.mono); defer sfc.deinit(gpa);
var saw_black = false; var saw_white = false; for (0..fixtures.height) |y| for (0..fixtures.width) |x| { const px = at(sfc, @intCast(x), @intCast(y)); if (px.r == 0) saw_black = true; if (px.r == 255) saw_white = true; }; try testing.expect(saw_black); try testing.expect(saw_white);}
test "what is detected as a PCX, and what is not" { // One magic byte is not a signature, so detection reads five fields. A // file passing all five and not being a PCX would have to be trying. for ([_][]const u8{ "\x0a" ++ @as([200]u8, @splat('\x00')), // planes of zero, stride of zero "\x0aZ" ++ @as([200]u8, @splat('\x00')), // a version that does not exist "\x0a\x05\x09" ++ @as([200]u8, @splat('\x00')), // an encoding that does not exist "\n#include <stdio.h>\nint main(void) { return 0; }\n" ++ @as([100]u8, @splat(' ')), "not an image at all, just a sentence about one" ++ @as([100]u8, @splat(' ')), }) |bytes| { try testing.expectEqual(@as(?z2dimg.Format, null), z2dimg.detect(bytes)); } try testing.expectEqual(@as(?z2dimg.Format, .pcx), z2dimg.detect(&fixtures.rgb)); try testing.expectEqual(@as(?z2dimg.Format, .pcx), z2dimg.detect(&fixtures.ega));}
test "probe and decode agree" { const gpa = testing.allocator; for ([_][]const u8{ &fixtures.rgb, &fixtures.grey, &fixtures.paletted, &fixtures.mono, &fixtures.ega, &fixtures.packed_4, &fixtures.version_3, }) |bytes| { var r: Io.Reader = .fixed(bytes); const info = try z2dimg.probe(&r, .{}); var sfc = try decodeBytes(gpa, bytes); defer sfc.deinit(gpa); try testing.expectEqual(@as(i32, @intCast(info.width)), sfc.getWidth()); try testing.expectEqual(@as(i32, @intCast(info.height)), sfc.getHeight()); try testing.expectEqual(z2dimg.Format.pcx, info.format); }}
test "headers that describe nothing are refused" { // The window is a pair of inclusive corners, so a maximum below a minimum // is a negative size; the rest are fields with no valid value. for ([_][]const u8{ "\x0a\x05\x01\x08" ++ "\x05\x00\x00\x00\x00\x00\x00\x00" ++ @as([200]u8, @splat('\x00')), "\x0a\x05\x01\x03" ++ @as([200]u8, @splat('\x00')), // three bits a pixel "\x0a\x05\x02\x08" ++ @as([200]u8, @splat('\x00')), // an encoding of two }) |bytes| { var r: Io.Reader = .fixed(bytes); try testing.expectError(error.UnknownFormat, z2dimg.probe(&r, .{})); }
// A row too short to hold the pixels it claims is a file that contradicts // itself, and is told apart from one this cannot read. var narrow: [200]u8 = @splat(0); narrow[0] = 0x0a; narrow[1] = 5; narrow[2] = 1; narrow[3] = 8; mem.writeInt(u16, narrow[8..10], 99, .little); // xmax: a hundred wide mem.writeInt(u16, narrow[10..12], 0, .little); narrow[65] = 1; mem.writeInt(u16, narrow[66..68], 4, .little); // four bytes a row var r: Io.Reader = .fixed(&narrow); try testing.expectError(error.InvalidData, z2dimg.probe(&r, .{}));}
test "a truncated file keeps what arrived" { // Every prefix of a PCX is a prefix of an image. What was not reached is // the palette's first colour, which is what the surface already holds. const gpa = testing.allocator; var n: usize = 128; while (n < fixtures.rgb.len) : (n += 7) { var sfc = decodeBytes(gpa, fixtures.rgb[0..n]) catch |err| switch (err) { error.InvalidData, error.Unsupported, error.EndOfStream => continue, else => return err, }; defer sfc.deinit(gpa); try testing.expectEqual(@as(i32, fixtures.width), sfc.getWidth()); }}
test "what is written comes back" { const gpa = testing.allocator; var source = try decodeBytes(gpa, &fixtures.rgb); defer source.deinit(gpa);
for ([_]bool{ true, false }) |encoded| { var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try z2dimg.encode(gpa, &source, &w.writer, .{ .pcx = .{ .encoded = encoded } });
try testing.expectEqual(@as(?z2dimg.Format, .pcx), z2dimg.detect(w.written())); var back = try decodeBytes(gpa, w.written()); defer back.deinit(gpa); try expectPixels(back, &fixtures.rgb_pixels); }}
test "a run of a byte that looks like a count is still written as a run" { // A byte with its top two bits set is a count, so a literal that happens // to look like one costs two bytes to say. An encoder that wrote it plain // would produce a file that decodes as a run of something else entirely. const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_rgb, gpa, 4, 1); defer sfc.deinit(gpa); // 0xC1 in every channel: a value that is also a run marker. for (0..4) |x| sfc.putPixel(@intCast(x), 0, .{ .rgb = .{ .r = 0xc1, .g = 0xc1, .b = 0xc1 } });
var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try z2dimg.encode(gpa, &sfc, &w.writer, .{ .pcx = .{} });
var back = try decodeBytes(gpa, w.written()); defer back.deinit(gpa); for (0..4) |x| { try testing.expectEqual(Rgba8.rgb(0xc1, 0xc1, 0xc1), at(back, @intCast(x), 0)); }}
test "alpha is flattened onto white" { // Every shape but `.rgba` has no alpha, and the default is one of them. // `.rgba` keeps it, and is tested below. const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_rgba, gpa, 3, 1); defer sfc.deinit(gpa); z2dimg.pixels.writeRow(&sfc, 0, &[_]Rgba8{ .{ .r = 0, .g = 0, .b = 0, .a = 255 }, .{ .r = 0, .g = 0, .b = 0, .a = 0 }, .{ .r = 0, .g = 0, .b = 0, .a = 128 }, });
var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try z2dimg.encode(gpa, &sfc, &w.writer, .{ .pcx = .{} });
var back = try decodeBytes(gpa, w.written()); defer back.deinit(gpa); try testing.expectEqual(Rgba8.rgb(0, 0, 0), at(back, 0, 0)); try testing.expectEqual(Rgba8.rgb(255, 255, 255), at(back, 1, 0)); try testing.expectEqual(Rgba8.rgb(127, 127, 127), at(back, 2, 0));}
/// A surface of `width`×`height` using exactly `colors` distinct opaque/// colors, spread so that neighbouring pixels differ and every color is/// used at least once when the image has room for it.fn surfaceOfColors(gpa: Allocator, width: i32, height: i32, colors: u32) !z2d.Surface { var sfc: z2d.Surface = try .init(.image_surface_rgb, gpa, width, height); errdefer sfc.deinit(gpa); const w: u32 = @intCast(width); for (0..@intCast(height)) |y| for (0..w) |x| { const i: u32 = @intCast((y * w + x) % colors); // Distinct for every `i` under 4096, and far from grey so that a // palette entry read from the wrong place shows. sfc.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = @intCast((i * 37) % 256), .g = @intCast((i / 7 * 53 + 11) % 256), .b = @intCast(255 - (i % 256)), } }); }; return sfc;}
fn encodePcx(gpa: Allocator, sfc: *const z2d.Surface, opts: z2dimg.pcx.EncodeOptions) ![]u8 { var list: std.ArrayList(u8) = .empty; errdefer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); errdefer list = w.toArrayList(); try z2dimg.encode(gpa, sfc, &w.writer, .{ .pcx = opts }); list = w.toArrayList(); return list.toOwnedSlice(gpa);}
fn expectSame(a: z2d.Surface, b: z2d.Surface) !void { try testing.expectEqual(a.getWidth(), b.getWidth()); try testing.expectEqual(a.getHeight(), b.getHeight()); for (0..@intCast(a.getHeight())) |y| for (0..@intCast(a.getWidth())) |x| { const want = at(a, @intCast(x), @intCast(y)); const got = at(b, @intCast(x), @intCast(y)); testing.expectEqual(want, got) catch |err| { std.debug.print("at ({d},{d}): want {any}, got {any}\n", .{ x, y, want, got }); return err; }; };}
test "every shape that is written comes back, at every width a byte can end on" { // The bit-packed shapes put several pixels in a byte and pad each plane's // row to an even length, so the widths that matter are the ones either // side of every byte boundary. Seventeen covers all of them for depths of // one, two and four bits. const gpa = testing.allocator; const shapes = [_]struct { z2dimg.pcx.Shape, u32 }{ .{ .packed_4, 4 }, .{ .packed_16, 16 }, .{ .planar_16, 16 }, .{ .indexed_256, 256 }, .{ .rgb, 1000 }, .{ .rgba, 1000 }, }; for (shapes) |case| { const shape, const colors = case; for (1..18) |width| { var sfc = try surfaceOfColors(gpa, @intCast(width), 17, colors); defer sfc.deinit(gpa); for ([_]bool{ true, false }) |encoded| { const bytes = try encodePcx(gpa, &sfc, .{ .shape = shape, .encoded = encoded }); defer gpa.free(bytes); try testing.expectEqual(@as(?z2dimg.Format, .pcx), z2dimg.detect(bytes)); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); expectSame(sfc, back) catch |err| { std.debug.print("{t}, {d} wide, encoded {}\n", .{ shape, width, encoded }); return err; }; } } }}
test "a paletted shape refuses one color more than it holds" { // Nothing here quantises, so an image that does not fit is refused rather // than written wrong. const gpa = testing.allocator; for ([_]struct { z2dimg.pcx.Shape, u32 }{ .{ .packed_4, 4 }, .{ .packed_16, 16 }, .{ .planar_16, 16 }, .{ .indexed_256, 256 }, }) |case| { const shape, const holds = case; var fits = try surfaceOfColors(gpa, 32, 16, holds); defer fits.deinit(gpa); const bytes = try encodePcx(gpa, &fits, .{ .shape = shape }); gpa.free(bytes);
var over = try surfaceOfColors(gpa, 32, 16, holds + 1); defer over.deinit(gpa); try testing.expectError(error.Unsupported, encodePcx(gpa, &over, .{ .shape = shape })); }}
test "auto writes the shallowest shape every reader reads" { const gpa = testing.allocator; for ([_]struct { u32, u8, u8 }{ // colors, bits per plane, planes .{ 2, 1, 4 }, .{ 16, 1, 4 }, .{ 17, 8, 1 }, .{ 256, 8, 1 }, .{ 257, 8, 3 }, }) |case| { const colors, const bits, const planes = case; var sfc = try surfaceOfColors(gpa, 32, 16, colors); defer sfc.deinit(gpa); const bytes = try encodePcx(gpa, &sfc, .{ .shape = .auto }); defer gpa.free(bytes); testing.expectEqual(bits, bytes[3]) catch |err| { std.debug.print("{d} colors\n", .{colors}); return err; }; try testing.expectEqual(planes, bytes[65]); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try expectSame(sfc, back); }}
test "the four-plane shape keeps alpha" { // Straight alpha in the fourth plane, where every other shape flattens // onto white. const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_rgba, gpa, 3, 1); defer sfc.deinit(gpa); z2dimg.pixels.writeRow(&sfc, 0, &[_]Rgba8{ .{ .r = 10, .g = 20, .b = 30, .a = 255 }, .{ .r = 0, .g = 0, .b = 0, .a = 0 }, .{ .r = 255, .g = 0, .b = 0, .a = 128 }, });
const bytes = try encodePcx(gpa, &sfc, .{ .shape = .rgba }); defer gpa.free(bytes); var r: Io.Reader = .fixed(bytes); try testing.expect((try z2dimg.probe(&r, .{})).has_alpha);
var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(Rgba8{ .r = 10, .g = 20, .b = 30, .a = 255 }, at(back, 0, 0)); try testing.expectEqual(@as(u8, 0), at(back, 1, 0).a); // Half-transparent red survives within what premultiplying it in an // 8-bit surface can keep. const half = at(back, 2, 0); try testing.expectEqual(@as(u8, 128), half.a); try testing.expect(half.r >= 254 and half.g == 0 and half.b == 0);}