// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The JPEG decoder, against libjpeg. //! //! `jpeg_fixtures.zig` holds fifteen files written by Pillow with the options //! each one's note names — baseline and progressive, 4:4:4, 4:2:2 and 4:2:0, //! greyscale, restart markers, optimised Huffman tables, and dimensions that //! do not divide by the MCU size — together with the pixels libjpeg decodes //! them back to. //! //! ## Why the comparison has a tolerance //! //! JPEG does not define an exact inverse DCT. ITU-T T.83 defines accuracy //! *requirements* instead, deliberately, so that the fast approximations //! everybody wanted to use would stay conforming — and nothing about chroma //! upsampling is normative at all. Two conforming decoders are therefore //! entitled to disagree, and this one and libjpeg do, by very little: the //! transform here is computed in `f32` from the definition where libjpeg uses //! a 13-bit fixed-point factorisation, and the interpolation weights round //! differently in the last bit. //! //! Measured across all fifteen fixtures, the worst single channel of any pixel //! is **3** and the worst mean over an image is **0.14**. The bounds below are //! set just above that, which makes them a real test: anything that actually //! went wrong — a dropped refinement scan, a misread sampling factor, chroma //! off by half a block — moves those numbers by tens, not by one. //! //! It was worth chasing. An earlier version upsampled chroma by replication //! rather than interpolating, which is legal and much simpler, and it put the //! worst case at 55. 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("jpeg_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, .{}); } /// No single channel of any pixel may be further from libjpeg than this, when /// both implementations are upsampling chroma the same way. const max_difference: u16 = 3; /// And the average over a whole image must be under this. const max_mean_difference: f64 = 0.25; /// What to allow when they are not. libjpeg has an interpolating upsampler for /// a ratio of exactly two in each direction and nothing else, so a file with a /// coarser ratio is replicated there and interpolated here, and a pixel-exact /// comparison stops being a statement about correctness. What still is one is /// that the image is substantially right, which is what the mean says. const max_difference_replicated: u16 = 64; const max_mean_replicated: f64 = 8.0; /// Whether libjpeg would have used its interpolating chroma upsampler on this /// file, which is to say whether every sampling factor in it is one or two. /// /// Read out of the frame header rather than hard-coded against fixture names, /// so that adding a fixture cannot quietly pick the wrong bound. /// /// Proved rather than assumed. For the fixtures with a factor of three or /// four, `djpeg` and `djpeg -nosmooth` --- which is libjpeg with fancy /// upsampling switched off --- produce byte-identical output, so it was never /// interpolating; for a 4:2:0 file the two differ. fn libjpegInterpolates(jpeg: []const u8) bool { var o: usize = 2; while (o + 4 <= jpeg.len) { if (jpeg[o] != 0xff) { o += 1; continue; } const marker = jpeg[o + 1]; switch (marker) { // A frame header: precision, height, width, component count, then // three bytes for each component of which the second is the // sampling factors, four bits each way. 0xc0, 0xc1, 0xc2 => { const n = jpeg[o + 9]; for (0..n) |i| { const sampling = jpeg[o + 10 + i * 3 + 1]; const h = sampling >> 4; const v = sampling & 0x0f; if (h > 2 or v > 2) return false; } return true; }, 0xd8, 0xd9 => o += 2, 0xd0...0xd7, 0x01 => o += 2, else => { const len = (@as(usize, jpeg[o + 2]) << 8) | jpeg[o + 3]; o += 2 + len; }, } } return true; } test "every fixture decodes to what libjpeg decodes it to" { const gpa = testing.allocator; for (fixtures.all) |f| { var sfc = decodeBytes(gpa, f.jpeg) catch |err| { std.debug.print("\n{s} ({s}): {t}\n", .{ f.name, f.note, err }); return err; }; defer sfc.deinit(gpa); if (sfc.getWidth() != @as(i32, @intCast(f.width)) or sfc.getHeight() != @as(i32, @intCast(f.height))) { std.debug.print("\n{s}: {d}x{d}, expected {d}x{d}\n", .{ f.name, sfc.getWidth(), sfc.getHeight(), f.width, f.height, }); return error.WrongSize; } var worst: u16 = 0; var total: u64 = 0; var worst_at: [2]u32 = .{ 0, 0 }; for (f.expected, 0..) |want, i| { const x: u32 = @intCast(i % f.width); const y: u32 = @intCast(i / f.width); const got = Rgba8.fromZ2d(sfc.getPixel(@intCast(x), @intCast(y)).?); // A JPEG never carries transparency, whatever else it carries. try testing.expectEqual(@as(u8, 255), got.a); inline for (.{ "r", "g", "b" }, 0..) |ch, k| { const a = @field(got, ch); const b = want[k]; const diff: u16 = if (a > b) a - b else b - a; total += diff; if (diff > worst) { worst = diff; worst_at = .{ x, y }; } } } const mean = @as(f64, @floatFromInt(total)) / @as(f64, @floatFromInt(f.expected.len * 3)); const interpolates = libjpegInterpolates(f.jpeg); const allowed_max = if (interpolates) max_difference else max_difference_replicated; const allowed_mean = if (interpolates) max_mean_difference else max_mean_replicated; if (worst > allowed_max or mean > allowed_mean) { std.debug.print( "\n{s} ({s}): worst {d} at ({d},{d}), mean {d:.3}; allowed max {d}, mean {d:.2}\n", .{ f.name, f.note, worst, worst_at[0], worst_at[1], mean, allowed_max, allowed_mean }, ); return error.TooFarFromLibjpeg; } } } test "probe agrees with what the fixtures decode to" { for (fixtures.all) |f| { var r: Io.Reader = .fixed(f.jpeg); const info = try z2dimg.probe(&r, .{}); try testing.expectEqual(z2dimg.Format.jpeg, info.format); try testing.expectEqual(f.width, info.width); try testing.expectEqual(f.height, info.height); // No mode of JPEG carries an alpha channel. try testing.expectEqual(false, info.has_alpha); try testing.expectEqual( z2d.surface.SurfaceType.image_surface_rgb, info.surface_type, ); } } test "progressive and baseline of the same image agree with each other" { const gpa = testing.allocator; const base = find("baseline_444"); const prog = find("progressive_444"); var a = try decodeBytes(gpa, base.jpeg); defer a.deinit(gpa); var b = try decodeBytes(gpa, prog.jpeg); defer b.deinit(gpa); // The same picture at the same quality, coded two ways. They are not // required to be identical --- the coefficients are quantised // independently --- but they must be close, and a progressive decoder that // has dropped a refinement scan is not. var worst: u16 = 0; var y: i32 = 0; while (y < a.getHeight()) : (y += 1) { var x: i32 = 0; while (x < a.getWidth()) : (x += 1) { const pa = a.getPixel(x, y).?.rgb; const pb = b.getPixel(x, y).?.rgb; inline for (.{ "r", "g", "b" }) |ch| { const u = @field(pa, ch); const v = @field(pb, ch); const d: u16 = if (u > v) u - v else v - u; worst = @max(worst, d); } } } if (worst > 8) { std.debug.print("\nbaseline and progressive differ by {d}\n", .{worst}); return error.ProgressiveDisagrees; } } fn find(name: []const u8) fixtures.Fixture { for (fixtures.all) |f| { if (mem.eql(u8, f.name, name)) return f; } unreachable; } // -- what must be refused ---------------------------------------------------- test "two bytes of a JPEG signature are not a JPEG" { const gpa = testing.allocator; // The signature is three bytes: SOI and then the 0xFF that begins whatever // marker follows. Two of them and some text is not a JPEG and not anything // else either. var r: Io.Reader = .fixed("\xff\xd8not really"); try testing.expectError(error.UnknownFormat, z2dimg.decode(gpa, &r, .{})); } test "a JPEG signature with nothing usable behind it" { const gpa = testing.allocator; var r: Io.Reader = .fixed("\xff\xd8\xff\xe0\x00\x04ab\xff\xd9"); try testing.expectError(error.InvalidData, z2dimg.decode(gpa, &r, .{})); } test "arithmetic coding says it is unsupported rather than corrupt" { const gpa = testing.allocator; // SOI, then SOF9: arithmetic-coded sequential, which is legal, was // patented until 2003, and is implemented by almost nothing. var r: Io.Reader = .fixed("\xff\xd8\xff\xc9\x00\x0b\x08\x00\x10\x00\x10\x01\x01\x11\x00"); try testing.expectError(error.Unsupported, z2dimg.decode(gpa, &r, .{})); } test "twelve-bit samples say they are unsupported" { const gpa = testing.allocator; // A baseline frame header claiming twelve bits per sample. var r: Io.Reader = .fixed("\xff\xd8\xff\xc0\x00\x0b\x0c\x00\x10\x00\x10\x01\x01\x11\x00"); try testing.expectError(error.Unsupported, z2dimg.decode(gpa, &r, .{})); } test "limits are applied before the scans are read" { const gpa = testing.allocator; const f = find("baseline_444"); var r: Io.Reader = .fixed(f.jpeg); try testing.expectError(error.ImageTooLarge, z2dimg.decode(gpa, &r, .{ .limits = .{ .max_pixels = 16 }, })); } test "a truncated file keeps what it decoded" { const gpa = testing.allocator; const f = find("baseline_444"); // Cut short well inside the entropy-coded data. A JPEG that stops there is // what a part-downloaded image is, and every decoder shows the part that // arrived rather than nothing. const cut = f.jpeg.len - 40; var sfc = try decodeBytes(gpa, f.jpeg[0..cut]); defer sfc.deinit(gpa); try testing.expectEqual(@as(i32, @intCast(f.width)), sfc.getWidth()); // The top-left corner arrived, so it must match; what did not arrive is // grey rather than whatever was in memory. const got = Rgba8.fromZ2d(sfc.getPixel(0, 0).?); const want = f.expected[0]; try testing.expect(@abs(@as(i32, got.r) - @as(i32, want[0])) <= 4); } test "a file truncated at every length either decodes or fails cleanly" { const gpa = testing.allocator; const f = find("baseline_420"); var len: usize = 2; while (len < f.jpeg.len) : (len += 11) { const result = decodeBytes(gpa, f.jpeg[0..len]); if (result) |sfc| { var s = sfc; s.deinit(gpa); } else |err| switch (err) { error.EndOfStream, error.InvalidData, error.Unsupported, error.UnknownFormat => {}, else => { std.debug.print("\ntruncated to {d}: {t}\n", .{ len, err }); return err; }, } } } test "a requested surface type overrides the natural one" { const gpa = testing.allocator; const f = find("greyscale"); var r: Io.Reader = .fixed(f.jpeg); var sfc = try z2dimg.decode(gpa, &r, .{ .surface_type = .image_surface_rgba }); defer sfc.deinit(gpa); try testing.expectEqual(z2d.pixel.Format.rgba, sfc.getFormat()); // Opaque, since a JPEG has no transparency to carry. var row: [24]Rgba8 = undefined; z2dimg.pixels.readRow(&row, &sfc, 0); for (row[0..@intCast(sfc.getWidth())]) |px| { try testing.expectEqual(@as(u8, 255), px.a); } } test "a DHT segment shorter than its own counts is refused" { const gpa = testing.allocator; // A `DHT` whose declared length leaves no room for the sixteen code-length // counts, let alone any symbols. The bookkeeping subtracts those sixteen // from a `usize`, so before this was checked the subtraction wrapped to // about eighteen quintillion and the loop went on reading. // // Found by the fuzzer within a minute of the JPEG target existing. var r: Io.Reader = .fixed( "\xff\xd8" ++ // SOI "\xff\xc4\x00\x05\x00\x01\x02" ++ // DHT, length 5, and not enough behind it "\xff\xd9", ); try testing.expectError(error.InvalidData, z2dimg.decode(gpa, &r, .{})); } test "a DQT segment shorter than a table is refused" { const gpa = testing.allocator; var r: Io.Reader = .fixed( "\xff\xd8" ++ "\xff\xdb\x00\x05\x00\x01\x02" ++ // DQT with three bytes of a 64-entry table "\xff\xd9", ); try testing.expectError(error.InvalidData, z2dimg.decode(gpa, &r, .{})); } // -- writing ----------------------------------------------------------------- fn encodeJpeg(gpa: Allocator, sfc: *const z2d.Surface, opts: z2dimg.jpeg.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, .{ .jpeg = opts }); list = w.toArrayList(); return list.toOwnedSlice(gpa); } /// A smooth gradient, which is what JPEG is for and what a round trip can be /// held to a tight bound on. A wrapping pattern would be the adversarial case /// and says nothing about whether the encoder is right. fn gradient(gpa: Allocator, t: z2d.surface.SurfaceType, w: i32, h: i32) !z2d.Surface { var sfc: z2d.Surface = try .init(t, gpa, w, h); errdefer sfc.deinit(gpa); var row: [128]Rgba8 = undefined; var y: i32 = 0; while (y < h) : (y += 1) { const uw: usize = @intCast(w); for (row[0..uw], 0..) |*px, i| { const fx = @as(u32, @intCast(i)) * 200 / @max(1, @as(u32, @intCast(w)) - 1); const fy = @as(u32, @intCast(y)) * 200 / @max(1, @as(u32, @intCast(h)) - 1); px.* = .{ .r = @intCast(30 + fx), .g = @intCast(30 + fy), .b = @intCast(30 + (fx + fy) / 2), .a = 255, }; } z2dimg.pixels.writeRow(&sfc, y, row[0..uw]); } return sfc; } test "what is written begins with SOI and ends with EOI" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 8, 8); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{}); defer gpa.free(bytes); try testing.expectEqualSlices(u8, &.{ 0xff, 0xd8 }, bytes[0..2]); try testing.expectEqualSlices(u8, &.{ 0xff, 0xd9 }, bytes[bytes.len - 2 ..]); // And a JFIF segment right after the signature, which is what says the // three components are YCbCr. try testing.expectEqualSlices(u8, "JFIF\x00", bytes[6..11]); } test "a smooth image survives a round trip at high quality" { const gpa = testing.allocator; for ([_]z2dimg.jpeg.Chroma{ .full, .horizontal, .vertical, .half }) |chroma| { var sfc = try gradient(gpa, .image_surface_rgb, 32, 24); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{ .quality = 95, .chroma = chroma }); defer gpa.free(bytes); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 32), back.getWidth()); try testing.expectEqual(@as(i32, 24), back.getHeight()); var worst: u16 = 0; var y: i32 = 0; while (y < 24) : (y += 1) { var x: i32 = 0; while (x < 32) : (x += 1) { const a = sfc.getPixel(x, y).?.rgb; const b = back.getPixel(x, y).?.rgb; inline for (.{ "r", "g", "b" }) |ch| { const u = @field(a, ch); const v = @field(b, ch); worst = @max(worst, if (u > v) u - v else v - u); } } } // Lossy, but not by much on a gradient at quality 95. 4:2:0 is allowed // more because it is throwing away three quarters of the colour // resolution before the quantiser has touched anything, and a gradient // is exactly where that shows. // Each halving throws away three quarters — or half — of the colour // resolution before the quantiser has touched anything, and a gradient // is exactly where that shows. const allowed: u16 = switch (chroma) { .full => 6, .horizontal, .vertical => 9, .half => 10, .factors => unreachable, }; if (worst > allowed) { std.debug.print("\n{t} chroma: worst {d} after a round trip\n", .{ chroma, worst }); return error.RoundTripTooLossy; } } } test "quality trades size against fidelity, monotonically" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 64, 64); defer sfc.deinit(gpa); var last_size: usize = 0; for ([_]u7{ 20, 50, 80, 95 }) |q| { const bytes = try encodeJpeg(gpa, &sfc, .{ .quality = q }); defer gpa.free(bytes); try testing.expect(bytes.len > last_size); last_size = bytes.len; // And every one of them still decodes to the right size. var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 64), back.getWidth()); } } test "4:2:0 is smaller than 4:4:4 and still the same picture" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 64, 64); defer sfc.deinit(gpa); const full = try encodeJpeg(gpa, &sfc, .{ .chroma = .full }); defer gpa.free(full); const half = try encodeJpeg(gpa, &sfc, .{ .chroma = .half }); defer gpa.free(half); try testing.expect(half.len < full.len); var a = try decodeBytes(gpa, full); defer a.deinit(gpa); var b = try decodeBytes(gpa, half); defer b.deinit(gpa); // Subsampling costs colour resolution, not colour. const pa = a.getPixel(32, 32).?.rgb; const pb = b.getPixel(32, 32).?.rgb; try testing.expect(@abs(@as(i32, pa.r) - @as(i32, pb.r)) <= 8); } test "dimensions that do not divide by the MCU size" { const gpa = testing.allocator; // Thirteen by seven at 4:2:0 means a sixteen-by-sixteen MCU hanging off // two edges, which is where an encoder that pads with zeroes rather than // repeating the edge shows a dark fringe. for ([_]z2dimg.jpeg.Chroma{ .full, .horizontal, .vertical, .half }) |chroma| { var sfc = try gradient(gpa, .image_surface_rgb, 13, 7); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{ .quality = 95, .chroma = chroma }); defer gpa.free(bytes); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 13), back.getWidth()); try testing.expectEqual(@as(i32, 7), back.getHeight()); // The bottom-right pixel, which is the one the padding would spoil. // What this is looking for is a dark fringe — an encoder that filled // the padding with zeroes rather than repeating the edge puts one // there, and it is worth tens of counts, not single figures. The // subsampled ratios are allowed more because a chroma sample in that // corner is an average that legitimately includes the repeated row or // column: measured, `vertical` lands nine out on this image. const allowed: i32 = switch (chroma) { .full => 6, else => 14, }; const a = sfc.getPixel(12, 6).?.rgb; const b = back.getPixel(12, 6).?.rgb; try testing.expect(@abs(@as(i32, a.r) - @as(i32, b.r)) <= allowed); } } test "a single pixel" { const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_rgb, gpa, 1, 1); defer sfc.deinit(gpa); sfc.putPixel(0, 0, .{ .rgb = .{ .r = 200, .g = 100, .b = 50 } }); const bytes = try encodeJpeg(gpa, &sfc, .{ .quality = 95 }); defer gpa.free(bytes); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); const px = back.getPixel(0, 0).?.rgb; try testing.expect(@abs(@as(i32, px.r) - 200) <= 6); try testing.expect(@abs(@as(i32, px.g) - 100) <= 6); try testing.expect(@abs(@as(i32, px.b) - 50) <= 6); } test "an alpha-only surface becomes a greyscale JPEG carrying the alpha" { const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_alpha8, gpa, 16, 8); defer sfc.deinit(gpa); var y: i32 = 0; while (y < 8) : (y += 1) { var x: i32 = 0; while (x < 16) : (x += 1) { sfc.putPixel(x, y, .{ .alpha8 = .{ .a = @intCast(x * 16) } }); } } const bytes = try encodeJpeg(gpa, &sfc, .{ .quality = 95 }); defer gpa.free(bytes); // One component: SOF0's component count is the byte after the two // dimensions, and the frame header is easy enough to walk to. const sof = mem.indexOf(u8, bytes, &.{ 0xff, 0xc0 }).?; try testing.expectEqual(@as(u8, 1), bytes[sof + 9]); // And the alpha comes back as brightness. This is the one place JPEG // differs from what `bmp` and `png` do with the same surface: they can // keep the coverage in an alpha channel and so write transparent black, // and JPEG has no alpha channel to keep it in — so the choice is between // the one channel the file has and a black rectangle. var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); const dark = back.getPixel(0, 4).?.rgb; const bright = back.getPixel(15, 4).?.rgb; try testing.expect(dark.r < 20); try testing.expect(bright.r > 220); } test "transparency is composited onto the background" { const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_rgba, gpa, 16, 8); defer sfc.deinit(gpa); var y: i32 = 0; while (y < 8) : (y += 1) { var row: [16]Rgba8 = @splat(.{ .r = 255, .g = 0, .b = 0, .a = 0 }); z2dimg.pixels.writeRow(&sfc, y, &row); } // Fully transparent everywhere, so the output is entirely the background. for ([_]Rgba8{ .rgb(0, 0, 0), .rgb(255, 255, 255), .rgb(0, 0, 255) }) |bg| { const bytes = try encodeJpeg(gpa, &sfc, .{ .quality = 95, .background = bg }); defer gpa.free(bytes); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); const px = back.getPixel(8, 4).?.rgb; try testing.expect(@abs(@as(i32, px.r) - @as(i32, bg.r)) <= 6); try testing.expect(@abs(@as(i32, px.g) - @as(i32, bg.g)) <= 6); try testing.expect(@abs(@as(i32, px.b) - @as(i32, bg.b)) <= 6); } } test "the quantisation tables scale with quality and never reach zero" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 8, 8); defer sfc.deinit(gpa); // Quality 100 drives every divisor towards one; a divisor of zero would be // a division by zero in the encoder and a nonsense table in the file. for ([_]u7{ 1, 50, 100 }) |q| { const bytes = try encodeJpeg(gpa, &sfc, .{ .quality = q }); defer gpa.free(bytes); const dqt = mem.indexOf(u8, bytes, &.{ 0xff, 0xdb }).?; // Length, then the identifier byte, then sixty-four entries. for (bytes[dqt + 5 ..][0..64]) |entry| { try testing.expect(entry >= 1); } var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 8), back.getWidth()); } } test "the upsampling bound is chosen from the file, not from its name" { // The two-tier tolerance above is only honest if the tier is decided by // what the file actually contains. Every fixture with a sampling factor of // three or four must take the loose bound, and every other must take the // tight one — and the tight one must be what almost all of them take. var tight: usize = 0; var loose: usize = 0; for (fixtures.all) |f| { if (libjpegInterpolates(f.jpeg)) tight += 1 else loose += 1; } try testing.expect(tight > loose * 2); // The sampling fixtures built with cjpeg are the only loose ones. try testing.expect(loose >= 4); // And a 4:4:4 file is certainly on the tight side. try testing.expect(libjpegInterpolates(find("baseline_444").jpeg)); try testing.expect(libjpegInterpolates(find("baseline_420").jpeg)); try testing.expect(!libjpegInterpolates(find("sampling_411").jpeg)); try testing.expect(!libjpegInterpolates(find("sampling_3x1").jpeg)); } test "every chroma ratio writes the sampling factors it says it does" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 32, 32); defer sfc.deinit(gpa); const cases = [_]struct { c: z2dimg.jpeg.Chroma, h: u8, v: u8 }{ .{ .c = .full, .h = 1, .v = 1 }, .{ .c = .horizontal, .h = 2, .v = 1 }, .{ .c = .vertical, .h = 1, .v = 2 }, .{ .c = .half, .h = 2, .v = 2 }, }; for (cases) |k| { const bytes = try encodeJpeg(gpa, &sfc, .{ .chroma = k.c }); defer gpa.free(bytes); // The luma component's sampling byte, in SOF0: the header is at the // marker, and the first component's three bytes follow the count. const sof = mem.indexOf(u8, bytes, &.{ 0xff, 0xc0 }).?; const sampling = bytes[sof + 11]; try testing.expectEqual(k.h, sampling >> 4); try testing.expectEqual(k.v, sampling & 0x0f); // And chroma is always one by one, which is where JPEG puts the // reciprocal. try testing.expectEqual(@as(u8, 0x11), bytes[sof + 14]); try testing.expectEqual(@as(u8, 0x11), bytes[sof + 17]); // Our own decoder agrees about the size, and so does the round trip. var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 32), back.getWidth()); } } test "subsampling costs bytes in the direction it is applied" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 64, 64); defer sfc.deinit(gpa); var size: [4]usize = undefined; for ([_]z2dimg.jpeg.Chroma{ .full, .horizontal, .vertical, .half }, 0..) |c, i| { const bytes = try encodeJpeg(gpa, &sfc, .{ .chroma = c }); defer gpa.free(bytes); size[i] = bytes.len; } // Halving one way is smaller than halving neither, and halving both is // smaller again. Not a law, but on an image with this much colour in it // anything else would mean the chroma planes are not being subsampled. try testing.expect(size[1] < size[0]); try testing.expect(size[2] < size[0]); try testing.expect(size[3] < size[1]); try testing.expect(size[3] < size[2]); } // -- restart intervals ------------------------------------------------------- test "a restart interval puts markers in the scan and DRI in the header" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 64, 64); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{ .chroma = .half, .restart_interval = 2 }); defer gpa.free(bytes); // The DRI segment, with the interval in it. const dri = mem.indexOf(u8, bytes, &.{ 0xff, 0xdd }).?; try testing.expectEqual(@as(u16, 4), mem.readInt(u16, bytes[dri + 2 ..][0..2], .big)); try testing.expectEqual(@as(u16, 2), mem.readInt(u16, bytes[dri + 4 ..][0..2], .big)); // And the markers themselves, after the scan header, cycling 0 through 7. const sos = mem.indexOf(u8, bytes, &.{ 0xff, 0xda }).?; var found: usize = 0; var expect_next: u8 = 0xd0; var i = sos; while (i + 1 < bytes.len) : (i += 1) { if (bytes[i] != 0xff) continue; const m = bytes[i + 1]; if (m < 0xd0 or m > 0xd7) continue; try testing.expectEqual(expect_next, m); expect_next = if (m == 0xd7) 0xd0 else m + 1; found += 1; } // A 64x64 image at 4:2:0 is 4x4 MCUs, so sixteen of them, and a marker // after every two but not after the last. try testing.expectEqual(@as(usize, 7), found); } test "an image with restart markers decodes to the same picture as one without" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 48, 40); defer sfc.deinit(gpa); const plain = try encodeJpeg(gpa, &sfc, .{ .quality = 90 }); defer gpa.free(plain); var want = try decodeBytes(gpa, plain); defer want.deinit(gpa); // Several intervals, including one that does not divide the MCU count. for ([_]u16{ 1, 2, 3, 5, 100 }) |interval| { const bytes = try encodeJpeg(gpa, &sfc, .{ .quality = 90, .restart_interval = interval }); defer gpa.free(bytes); var got = try decodeBytes(gpa, bytes); defer got.deinit(gpa); var y: i32 = 0; while (y < 40) : (y += 1) { var x: i32 = 0; while (x < 48) : (x += 1) { testing.expectEqual(want.getPixel(x, y).?.rgb, got.getPixel(x, y).?.rgb) catch { std.debug.print("\ninterval {d} differs at ({d},{d})\n", .{ interval, x, y }); return error.RestartChangedTheImage; }; } } } } test "restart intervals work with every chroma ratio and with greyscale" { const gpa = testing.allocator; for ([_]z2dimg.jpeg.Chroma{ .full, .horizontal, .vertical, .half }) |chroma| { var sfc = try gradient(gpa, .image_surface_rgb, 33, 25); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{ .chroma = chroma, .restart_interval = 3 }); defer gpa.free(bytes); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 33), back.getWidth()); try testing.expectEqual(@as(i32, 25), back.getHeight()); } var grey: z2d.Surface = try .init(.image_surface_alpha8, gpa, 20, 20); defer grey.deinit(gpa); const bytes = try encodeJpeg(gpa, &grey, .{ .restart_interval = 2 }); defer gpa.free(bytes); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 20), back.getWidth()); } // -- optimised Huffman tables ------------------------------------------------ /// A surface holding a fixture's decoded pixels, which is a more realistic /// thing to measure a table against than a gradient: it has the run lengths /// and the coefficient distribution of an image that has already been through /// a JPEG encoder once. fn fromFixture(gpa: Allocator, name: []const u8) !z2d.Surface { const f = find(name); var sfc: z2d.Surface = try .init(.image_surface_rgb, gpa, @intCast(f.width), @intCast(f.height)); errdefer sfc.deinit(gpa); for (0..f.height) |y| { for (0..f.width) |x| { const px = f.expected[y * f.width + x]; sfc.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ .r = px[0], .g = px[1], .b = px[2], } }); } } return sfc; } test "optimised tables are smaller than the Annex K ones" { const gpa = testing.allocator; for ([_][]const u8{ "baseline_444", "baseline_420", "greyscale" }) |name| { var sfc = try fromFixture(gpa, name); defer sfc.deinit(gpa); for ([_]u7{ 25, 85, 100 }) |q| { const fixed = try encodeJpeg(gpa, &sfc, .{ .quality = q, .tables = .annex_k }); defer gpa.free(fixed); const optimal = try encodeJpeg(gpa, &sfc, .{ .quality = q, .tables = .optimal }); defer gpa.free(optimal); if (optimal.len >= fixed.len) { std.debug.print("\n{s} q{d}: optimal {d} is not smaller than Annex K {d}\n", .{ name, q, optimal.len, fixed.len }); return error.OptimalTablesAreNotSmaller; } } } } test "both kinds of table decode to the same picture" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 64, 64); defer sfc.deinit(gpa); // The tables change how the coefficients are spelled and not what they // are, so the two files must decode identically --- not nearly, exactly. const fixed = try encodeJpeg(gpa, &sfc, .{ .tables = .annex_k }); defer gpa.free(fixed); const optimal = try encodeJpeg(gpa, &sfc, .{ .tables = .optimal }); defer gpa.free(optimal); var a = try decodeBytes(gpa, fixed); defer a.deinit(gpa); var b = try decodeBytes(gpa, optimal); defer b.deinit(gpa); var y: i32 = 0; while (y < 64) : (y += 1) { var x: i32 = 0; while (x < 64) : (x += 1) { try testing.expectEqual(a.getPixel(x, y).?.rgb, b.getPixel(x, y).?.rgb); } } } test "an optimised table is written for every component that uses one" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 32, 32); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{ .tables = .optimal }); defer gpa.free(bytes); // Four DHT segments, one per class and identifier the scan header names, // and none of them the Annex K table it replaced. var seen: [4]bool = @splat(false); var i: usize = 2; while (i + 4 <= bytes.len and bytes[i] == 0xff) { const marker = bytes[i + 1]; const length = mem.readInt(u16, bytes[i + 2 ..][0..2], .big); if (marker == 0xda) break; // SOS, and the scan is not segments. if (marker == 0xc4) { const class_and_id = bytes[i + 4]; const slot: usize = switch (class_and_id) { 0x00 => 0, 0x10 => 1, 0x01 => 2, 0x11 => 3, else => unreachable, }; try testing.expect(!seen[slot]); seen[slot] = true; // The counts of an Annex K table sum to 12, 162, 12 and 162 // respectively; a table measured from a 32x32 gradient uses far // fewer symbols than that, which is the whole point. var total: usize = 0; for (bytes[i + 5 ..][0..16]) |n| total += n; try testing.expectEqual(@as(usize, length) - 3 - 16, total); try testing.expect(total < 162); } i += 2 + length; } try testing.expectEqualSlices(bool, &.{ true, true, true, true }, &seen); } test "greyscale writes two tables and not four" { const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_alpha8, gpa, 24, 24); defer sfc.deinit(gpa); for (0..24) |y| for (0..24) |x| { sfc.putPixel(@intCast(x), @intCast(y), .{ .alpha8 = .{ .a = @intCast((x * 10 + y * 3) % 256) } }); }; for ([_]z2dimg.jpeg.Tables{ .annex_k, .optimal }) |t| { const bytes = try encodeJpeg(gpa, &sfc, .{ .tables = t }); defer gpa.free(bytes); var count: usize = 0; var i: usize = 2; while (i + 4 <= bytes.len and bytes[i] == 0xff) { const marker = bytes[i + 1]; const length = mem.readInt(u16, bytes[i + 2 ..][0..2], .big); if (marker == 0xda) break; if (marker == 0xc4) count += 1; i += 2 + length; } try testing.expectEqual(@as(usize, 2), count); } } // -- progressive ------------------------------------------------------------- test "a progressive file says SOF2 and carries the scans the script asks for" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 48, 40); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{ .mode = .progressive }); defer gpa.free(bytes); try testing.expect(mem.indexOf(u8, bytes, &.{ 0xff, 0xc2 }) != null); try testing.expect(mem.indexOf(u8, bytes, &.{ 0xff, 0xc0 }) == null); // Ten scans, and every one of them a band the script names. Walking the // segments rather than counting marker bytes, since the entropy-coded data // between them can hold anything. var script: std.ArrayList([4]u8) = .empty; defer script.deinit(gpa); var i: usize = 2; while (i + 4 <= bytes.len) { if (bytes[i] != 0xff) return error.NotAtASegment; const marker = bytes[i + 1]; if (marker == 0xd9) break; const length = mem.readInt(u16, bytes[i + 2 ..][0..2], .big); if (marker == 0xda) { const n = bytes[i + 4]; const at = i + 5 + @as(usize, n) * 2; try script.append(gpa, .{ n, bytes[at], bytes[at + 1], bytes[at + 2] }); // Skip the entropy-coded segment, which is everything up to the // next marker that is not a stuffed byte or a restart. i += 2 + length; while (i + 1 < bytes.len) : (i += 1) { if (bytes[i] != 0xff) continue; if (bytes[i + 1] == 0x00) continue; if (bytes[i + 1] >= 0xd0 and bytes[i + 1] <= 0xd7) continue; break; } continue; } i += 2 + length; } try testing.expectEqualSlices([4]u8, &.{ .{ 3, 0, 0, 0x01 }, .{ 1, 1, 5, 0x02 }, .{ 1, 1, 63, 0x01 }, .{ 1, 1, 63, 0x01 }, .{ 1, 6, 63, 0x02 }, .{ 1, 1, 63, 0x21 }, .{ 3, 0, 0, 0x10 }, .{ 1, 1, 63, 0x10 }, .{ 1, 1, 63, 0x10 }, .{ 1, 1, 63, 0x10 }, }, script.items); } test "a greyscale progressive file uses the shorter script" { const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_alpha8, gpa, 24, 24); defer sfc.deinit(gpa); for (0..24) |y| for (0..24) |x| { sfc.putPixel(@intCast(x), @intCast(y), .{ .alpha8 = .{ .a = @intCast((x * 9 + y * 5) % 256) } }); }; const bytes = try encodeJpeg(gpa, &sfc, .{ .mode = .progressive }); defer gpa.free(bytes); var scans: usize = 0; var i: usize = 2; while (i + 4 <= bytes.len) { if (bytes[i] != 0xff) break; const marker = bytes[i + 1]; if (marker == 0xd9) break; const length = mem.readInt(u16, bytes[i + 2 ..][0..2], .big); i += 2 + length; if (marker == 0xda) { scans += 1; while (i + 1 < bytes.len) : (i += 1) { if (bytes[i] != 0xff) continue; if (bytes[i + 1] == 0x00) continue; if (bytes[i + 1] >= 0xd0 and bytes[i + 1] <= 0xd7) continue; break; } } } try testing.expectEqual(@as(usize, 6), scans); } test "progressive and baseline are the same picture" { const gpa = testing.allocator; for ([_]z2dimg.jpeg.Chroma{ .full, .horizontal, .vertical, .half }) |c| { for ([_][2]i32{ .{ 48, 40 }, .{ 33, 17 }, .{ 7, 3 }, .{ 1, 1 } }) |size| { var sfc = try gradient(gpa, .image_surface_rgb, size[0], size[1]); defer sfc.deinit(gpa); const base = try encodeJpeg(gpa, &sfc, .{ .chroma = c }); defer gpa.free(base); const prog = try encodeJpeg(gpa, &sfc, .{ .chroma = c, .mode = .progressive }); defer gpa.free(prog); // The two carry exactly the same coefficients, spelled differently, // so the decoded images must be identical and not merely close. var a = try decodeBytes(gpa, base); defer a.deinit(gpa); var b = try decodeBytes(gpa, prog); defer b.deinit(gpa); var y: i32 = 0; while (y < size[1]) : (y += 1) { var x: i32 = 0; while (x < size[0]) : (x += 1) { const pa = a.getPixel(x, y).?.rgb; const pb = b.getPixel(x, y).?.rgb; if (!std.meta.eql(pa, pb)) { std.debug.print("\n{t} {d}x{d} at ({d},{d}): baseline {any} progressive {any}\n", .{ c, size[0], size[1], x, y, pa, pb }); return error.ProgressiveDiffers; } } } } } } test "progressive with restart intervals is still the same picture" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 48, 40); defer sfc.deinit(gpa); const base = try encodeJpeg(gpa, &sfc, .{ .chroma = .half }); defer gpa.free(base); var a = try decodeBytes(gpa, base); defer a.deinit(gpa); for ([_]u16{ 1, 2, 5, 17 }) |interval| { const prog = try encodeJpeg(gpa, &sfc, .{ .chroma = .half, .mode = .progressive, .restart_interval = interval, }); defer gpa.free(prog); var b = try decodeBytes(gpa, prog); defer b.deinit(gpa); var y: i32 = 0; while (y < 40) : (y += 1) { var x: i32 = 0; while (x < 48) : (x += 1) { try testing.expectEqual(a.getPixel(x, y).?.rgb, b.getPixel(x, y).?.rgb); } } } } test "every combination of options, against surfaces chosen to be awkward" { // The encoder has five options that interact, and the combinations that // break something are not the ones a hand-written test reaches for. Two // thousand of them, from a fixed seed so that a failure can be got back: // the point is not coverage of the pixels — a gradient covers those — but // coverage of the *paths*, and the three styles below are chosen for the // three that are hard to reach otherwise. Noise makes every coefficient // large and every run of zeroes short; black and white blocks are where a // DC difference is at its largest; and a flat image makes every AC // coefficient zero, which in a progressive file is an end-of-block run // covering the whole image and in a refinement scan is a correction bit // for every coefficient and nothing else. const gpa = testing.allocator; var prng: std.Random.DefaultPrng = .init(0xc0ffee); const rand = prng.random(); var n: usize = 0; while (n < 2000) : (n += 1) { const w: i32 = @intCast(rand.intRangeAtMost(u32, 1, 17)); const h: i32 = @intCast(rand.intRangeAtMost(u32, 1, 17)); const alpha = rand.boolean(); var sfc: z2d.Surface = try .init( if (alpha) .image_surface_rgba else .image_surface_rgb, gpa, w, h, ); defer sfc.deinit(gpa); const style = rand.intRangeAtMost(u8, 0, 2); var y: i32 = 0; while (y < h) : (y += 1) { var x: i32 = 0; while (x < w) : (x += 1) { const px: [3]u8 = switch (style) { 0 => .{ rand.int(u8), rand.int(u8), rand.int(u8) }, 1 => blk: { const v: u8 = if (rand.boolean()) 0 else 255; break :blk .{ v, v, v }; }, else => .{ 128, 128, 128 }, }; if (alpha) { // A surface with alpha holds it premultiplied, so the // colour channels have to be scaled or the conversion on // the way in would reject them. const a = rand.int(u8); sfc.putPixel(x, y, .{ .rgba = .{ .r = @intCast(@as(u16, px[0]) * a / 255), .g = @intCast(@as(u16, px[1]) * a / 255), .b = @intCast(@as(u16, px[2]) * a / 255), .a = a, } }); } else { sfc.putPixel(x, y, .{ .rgb = .{ .r = px[0], .g = px[1], .b = px[2] } }); } } } const opts: z2dimg.jpeg.EncodeOptions = .{ .quality = rand.intRangeAtMost(u7, 1, 100), .chroma = switch (rand.intRangeAtMost(u8, 0, 3)) { 0 => .full, 1 => .horizontal, 2 => .vertical, else => .half, }, .tables = if (rand.boolean()) .annex_k else .optimal, .mode = if (rand.boolean()) .baseline else .progressive, .restart_interval = rand.intRangeAtMost(u16, 0, 4), }; const bytes = encodeJpeg(gpa, &sfc, opts) catch |err| { std.debug.print("\ncase {d}: {d}x{d} style {d} alpha {}: {t}\n", .{ n, w, h, style, alpha, err }); return err; }; defer gpa.free(bytes); // And what came out is a JPEG, which is the whole claim: the encoder // cannot write something its own decoder refuses. var back = decodeBytes(gpa, bytes) catch |err| { std.debug.print("\ncase {d}: {d}x{d} style {d} alpha {} did not decode: {t}\n", .{ n, w, h, style, alpha, err }); return err; }; defer back.deinit(gpa); try testing.expectEqual(w, back.getWidth()); try testing.expectEqual(h, back.getHeight()); } } // -- how many components, and what they mean --------------------------------- /// How many components `SOF0` or `SOF2` says the file has. fn componentCount(bytes: []const u8) u8 { const sof = mem.indexOf(u8, bytes, &.{ 0xff, 0xc0 }) orelse mem.indexOf(u8, bytes, &.{ 0xff, 0xc2 }).?; return bytes[sof + 9]; } test "a colour surface can be written as greyscale" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 32, 24); defer sfc.deinit(gpa); const colour = try encodeJpeg(gpa, &sfc, .{ .colour = .ycbcr }); defer gpa.free(colour); const grey = try encodeJpeg(gpa, &sfc, .{ .colour = .greyscale }); defer gpa.free(grey); try testing.expectEqual(@as(u8, 3), componentCount(colour)); try testing.expectEqual(@as(u8, 1), componentCount(grey)); // Two tables fewer and two components fewer. try testing.expect(grey.len < colour.len); // And what comes back is the luma of what went in: grey, and close to the // ITU-R BT.601 weighting the three-component file would have used for Y. var back = try decodeBytes(gpa, grey); defer back.deinit(gpa); var worst: u16 = 0; var y: i32 = 0; while (y < 24) : (y += 1) { var x: i32 = 0; while (x < 32) : (x += 1) { const got = back.getPixel(x, y).?.rgb; try testing.expectEqual(got.r, got.g); try testing.expectEqual(got.g, got.b); const src = sfc.getPixel(x, y).?.rgb; const want: i32 = @intCast((19595 * @as(u32, src.r) + 38470 * @as(u32, src.g) + 7471 * @as(u32, src.b)) >> 16); const d: u16 = @intCast(@abs(@as(i32, got.r) - want)); worst = @max(worst, d); } } // Lossy, but only by what the quantisation costs. try testing.expect(worst <= 4); } test "an alpha-only surface can be written in three components" { const gpa = testing.allocator; var sfc: z2d.Surface = try .init(.image_surface_alpha8, gpa, 24, 16); defer sfc.deinit(gpa); for (0..16) |y| for (0..24) |x| { sfc.putPixel(@intCast(x), @intCast(y), .{ .alpha8 = .{ .a = @intCast((x * 9 + y * 5) % 256) } }); }; const one = try encodeJpeg(gpa, &sfc, .{ .colour = .auto }); defer gpa.free(one); const three = try encodeJpeg(gpa, &sfc, .{ .colour = .ycbcr }); defer gpa.free(three); try testing.expectEqual(@as(u8, 1), componentCount(one)); try testing.expectEqual(@as(u8, 3), componentCount(three)); // Three components carrying what one did: larger, and no better. try testing.expect(three.len > one.len); // Both decode to the same grey image, the alpha channel as brightness. var a = try decodeBytes(gpa, one); defer a.deinit(gpa); var b = try decodeBytes(gpa, three); defer b.deinit(gpa); var y: i32 = 0; while (y < 16) : (y += 1) { var x: i32 = 0; while (x < 24) : (x += 1) { const pa = a.getPixel(x, y).?.rgb; const pb = b.getPixel(x, y).?.rgb; try testing.expectEqual(pa.r, pb.r); try testing.expectEqual(pb.r, pb.g); try testing.expectEqual(pb.g, pb.b); } } } test "auto is what the surface would have got before there was a choice" { const gpa = testing.allocator; // Colour surfaces go to three components and alpha-only ones to one, // which is what the encoder did when it had no say in the matter. var colour = try gradient(gpa, .image_surface_rgba, 16, 16); defer colour.deinit(gpa); const a = try encodeJpeg(gpa, &colour, .{}); defer gpa.free(a); try testing.expectEqual(@as(u8, 3), componentCount(a)); var alpha: z2d.Surface = try .init(.image_surface_alpha8, gpa, 16, 16); defer alpha.deinit(gpa); const b = try encodeJpeg(gpa, &alpha, .{}); defer gpa.free(b); try testing.expectEqual(@as(u8, 1), componentCount(b)); } test "greyscale and progressive together use the shorter script" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 32, 24); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{ .colour = .greyscale, .mode = .progressive }); defer gpa.free(bytes); try testing.expectEqual(@as(u8, 1), componentCount(bytes)); var scans: usize = 0; var i: usize = 2; while (i + 4 <= bytes.len and bytes[i] == 0xff) { const marker = bytes[i + 1]; if (marker == 0xd9) break; const length = mem.readInt(u16, bytes[i + 2 ..][0..2], .big); i += 2 + length; if (marker == 0xda) { scans += 1; while (i + 1 < bytes.len) : (i += 1) { if (bytes[i] != 0xff) continue; if (bytes[i + 1] == 0x00) continue; if (bytes[i + 1] >= 0xd0 and bytes[i + 1] <= 0xd7) continue; break; } } } try testing.expectEqual(@as(usize, 6), scans); } // -- quantisation tables ----------------------------------------------------- test "quantisation tables given by the caller are the ones written" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 32, 24); defer sfc.deinit(gpa); var q: z2dimg.jpeg.Quant = .{ .luma = undefined, .chroma = undefined }; for (&q.luma, 0..) |*v, i| v.* = @intCast(1 + i % 64); for (&q.chroma, 0..) |*v, i| v.* = @intCast(2 + (i * 3) % 200); const bytes = try encodeJpeg(gpa, &sfc, .{ .quant = q }); defer gpa.free(bytes); // Two DQT segments, each carrying its table in zig-zag order — which is // the whole of what "raster order" on the option means: the encoder // reorders, the caller does not. const zigzag = [_]u8{ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, }; var at: usize = 2; var found: usize = 0; while (at + 4 <= bytes.len and bytes[at] == 0xff) { const marker = bytes[at + 1]; if (marker == 0xda or marker == 0xd9) break; const length = mem.readInt(u16, bytes[at + 2 ..][0..2], .big); if (marker == 0xdb) { const id = bytes[at + 4]; const table = if (id == 0) q.luma else q.chroma; for (zigzag, 0..) |raster, k| { try testing.expectEqual(@as(u8, @intCast(table[raster])), bytes[at + 5 + k]); } found += 1; } at += 2 + length; } try testing.expectEqual(@as(usize, 2), found); // And the file decodes, which says the tables were used as well as written. var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 32), back.getWidth()); } test "the quality scale is a line through the space the tables span" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 32, 32); defer sfc.deinit(gpa); // The top of the scale is exactly a table of ones — quality 100 scales // every Annex K entry down to one — so asking for that table by hand // writes the same file byte for byte. Worth pinning: it says the option // reaches the end of the scale rather than somewhere near it. const ones: z2dimg.jpeg.Quant = .{ .luma = @splat(1), .chroma = @splat(1) }; const by_table = try encodeJpeg(gpa, &sfc, .{ .quant = ones, .chroma = .full }); defer gpa.free(by_table); const by_quality = try encodeJpeg(gpa, &sfc, .{ .quality = 100, .chroma = .full }); defer gpa.free(by_quality); try testing.expectEqualSlices(u8, by_quality, by_table); // And what the scale cannot reach: it moves both tables together, so // there is no quality that keeps every bit of the luma while throwing // most of the chroma away. That is the reason the option exists. const lopsided: z2dimg.jpeg.Quant = .{ .luma = @splat(1), .chroma = @splat(64) }; const uneven = try encodeJpeg(gpa, &sfc, .{ .quant = lopsided, .chroma = .full }); defer gpa.free(uneven); try testing.expect(uneven.len < by_table.len); var back = try decodeBytes(gpa, uneven); defer back.deinit(gpa); // Luma divided by one is the most a JPEG can keep, so the brightness // comes back very close; the colour does not, and that asymmetry is the // whole of what was asked for. var worst_luma: u16 = 0; var worst_chroma: u16 = 0; var y: i32 = 0; while (y < 32) : (y += 1) { var x: i32 = 0; while (x < 32) : (x += 1) { const src = sfc.getPixel(x, y).?.rgb; const got = back.getPixel(x, y).?.rgb; const luma = struct { fn f(p: z2d.pixel.RGB) i32 { return @intCast((19595 * @as(u32, p.r) + 38470 * @as(u32, p.g) + 7471 * @as(u32, p.b)) >> 16); } }.f; worst_luma = @max(worst_luma, @as(u16, @intCast(@abs(luma(got) - luma(src))))); // Cb, which is the channel a coarse chroma table loses. const cb = struct { fn f(p: z2d.pixel.RGB) i32 { return @as(i32, p.b) - @as(i32, p.g); } }.f; worst_chroma = @max(worst_chroma, @as(u16, @intCast(@abs(cb(got) - cb(src))))); } } try testing.expect(worst_luma <= 3); try testing.expect(worst_chroma > worst_luma); } test "a quantisation table that cannot be written is refused" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 16, 16); defer sfc.deinit(gpa); // Zero would be divided by; 256 does not fit the eight-bit DQT this // encoder writes. Both are refused rather than clamped, because a table // silently changed is a file that does not say what the caller asked for. var q: z2dimg.jpeg.Quant = .{ .luma = @splat(16), .chroma = @splat(16) }; try testing.expect(q.valid()); q.luma[0] = 0; try testing.expect(!q.valid()); try testing.expectError(error.Unsupported, encodeJpeg(gpa, &sfc, .{ .quant = q })); q.luma[0] = 16; q.chroma[63] = 256; try testing.expect(!q.valid()); try testing.expectError(error.Unsupported, encodeJpeg(gpa, &sfc, .{ .quant = q })); } // -- sampling factors given outright ----------------------------------------- /// The sampling byte of each component, out of `SOF0` or `SOF2`. fn samplingBytes(bytes: []const u8, out: []u8) void { const sof = mem.indexOf(u8, bytes, &.{ 0xff, 0xc0 }) orelse mem.indexOf(u8, bytes, &.{ 0xff, 0xc2 }).?; for (out, 0..) |*b, i| b.* = bytes[sof + 11 + i * 3]; } test "factors given outright reproduce the named ratios exactly" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 48, 40); defer sfc.deinit(gpa); const named = [_]z2dimg.jpeg.Chroma{ .full, .horizontal, .vertical, .half }; const spelled = [_]z2dimg.jpeg.Chroma{ .{ .factors = .{ .luma = .{ .h = 1, .v = 1 } } }, .{ .factors = .{ .luma = .{ .h = 2, .v = 1 } } }, .{ .factors = .{ .luma = .{ .h = 1, .v = 2 } } }, .{ .factors = .{ .luma = .{ .h = 2, .v = 2 } } }, }; // The general path and the named one are the same path, which is the only // way the four names stay trustworthy now that they are shorthand. for (named, spelled) |a, b| { const by_name = try encodeJpeg(gpa, &sfc, .{ .chroma = a }); defer gpa.free(by_name); const by_factors = try encodeJpeg(gpa, &sfc, .{ .chroma = b }); defer gpa.free(by_factors); try testing.expectEqualSlices(u8, by_name, by_factors); } } test "the ratios the names do not cover" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 64, 48); defer sfc.deinit(gpa); const cases = [_]struct { note: []const u8, chroma: z2dimg.jpeg.Chroma, want: [3]u8, }{ // 4:1:1, which DV and some older camcorders use. .{ .note = "411", .chroma = .{ .factors = .{ .luma = .{ .h = 4, .v = 1 } } }, .want = .{ 0x41, 0x11, 0x11 }, }, // Chroma by three across, which nothing much writes and the decoder // here reads because cjpeg will produce it. .{ .note = "3x1", .chroma = .{ .factors = .{ .luma = .{ .h = 3, .v = 1 } } }, .want = .{ 0x31, 0x11, 0x11 }, }, // Four by two, which is ten blocks to an MCU: the specification's // limit exactly, and worth having a case at. .{ .note = "4x2", .chroma = .{ .factors = .{ .luma = .{ .h = 4, .v = 2 } } }, .want = .{ 0x42, 0x11, 0x11 }, }, // And the two chroma components sampled differently from each other, // which no named ratio can say at all. .{ .note = "mixed", .chroma = .{ .factors = .{ .luma = .{ .h = 2, .v = 2 }, .cb = .{ .h = 2, .v = 1 }, .cr = .{ .h = 1, .v = 1 }, } }, .want = .{ 0x22, 0x21, 0x11 }, }, }; for (cases) |k| { for ([_]z2dimg.jpeg.Mode{ .baseline, .progressive }) |mode| { const bytes = try encodeJpeg(gpa, &sfc, .{ .chroma = k.chroma, .mode = mode }); defer gpa.free(bytes); var got: [3]u8 = undefined; samplingBytes(bytes, &got); if (!mem.eql(u8, &k.want, &got)) { std.debug.print("\n{s} {t}: SOF says {x:0>2} {x:0>2} {x:0>2}\n", .{ k.note, mode, got[0], got[1], got[2] }); return error.WrongSamplingFactors; } var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 64), back.getWidth()); try testing.expectEqual(@as(i32, 48), back.getHeight()); // A gradient survives even the coarsest of these, which is the // claim worth making: the factors reached the planes as well as // the header. var worst: u16 = 0; var y: i32 = 0; while (y < 48) : (y += 1) { var x: i32 = 0; while (x < 64) : (x += 1) { const src = sfc.getPixel(x, y).?.rgb; const out = back.getPixel(x, y).?.rgb; inline for (.{ "r", "g", "b" }) |ch| { const d: u16 = @intCast(@abs(@as(i32, @field(out, ch)) - @as(i32, @field(src, ch)))); worst = @max(worst, d); } } } if (worst > 14) { std.debug.print("\n{s} {t}: worst {d} after a round trip\n", .{ k.note, mode, worst }); return error.RoundTripTooLossy; } } } } test "factors this encoder will not write" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 16, 16); defer sfc.deinit(gpa); const refused = [_]struct { note: []const u8, chroma: z2dimg.jpeg.Chroma }{ .{ .note = "zero", .chroma = .{ .factors = .{ .luma = .{ .h = 0, .v = 1 } } } }, .{ .note = "five", .chroma = .{ .factors = .{ .luma = .{ .h = 5, .v = 1 } } } }, // Chroma sampled more finely than luma: legal in the format, and bits // spent on the channel the eye is least sensitive to. .{ .note = "chroma finer", .chroma = .{ .factors = .{ .luma = .{ .h = 1, .v = 1 }, .cb = .{ .h = 2, .v = 1 }, } } }, // A ratio of three against two, where a chroma sample would cover one // and a half luma samples. .{ .note = "fractional", .chroma = .{ .factors = .{ .luma = .{ .h = 3, .v = 1 }, .cb = .{ .h = 2, .v = 1 }, } } }, // Eleven blocks to an MCU, one past what the specification allows. .{ .note = "too many blocks", .chroma = .{ .factors = .{ .luma = .{ .h = 3, .v = 3 }, .cb = .{ .h = 1, .v = 1 }, .cr = .{ .h = 1, .v = 1 }, } } }, }; for (refused) |k| { if (k.chroma.valid()) { std.debug.print("\n{s}: accepted and should not be\n", .{k.note}); return error.ShouldBeRefused; } try testing.expectError(error.Unsupported, encodeJpeg(gpa, &sfc, .{ .chroma = k.chroma })); } // And the four named ratios are all valid, which is what says the rules // above are rules about factors rather than about this encoder. for ([_]z2dimg.jpeg.Chroma{ .full, .horizontal, .vertical, .half }) |c| { try testing.expect(c.valid()); } } test "greyscale ignores whatever sampling factors were asked for" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 32, 24); defer sfc.deinit(gpa); // One component has nothing to subsample against, so even factors that // would be refused for a colour file are simply not used. const bytes = try encodeJpeg(gpa, &sfc, .{ .colour = .greyscale, .chroma = .{ .factors = .{ .luma = .{ .h = 9, .v = 9 } } }, }); defer gpa.free(bytes); var got: [1]u8 = undefined; samplingBytes(bytes, &got); try testing.expectEqual(@as(u8, 0x11), got[0]); } // -- scan scripts ------------------------------------------------------------ const Scan = z2dimg.jpeg.Scan; /// The simplest progressive script there is: everything in one pass, with no /// successive approximation at all. Four scans rather than ten, and a decoder /// gets the whole image from the first three-component scan onwards at one /// eighth scale. const plain_script = [_]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 }, }; /// Two bits of successive approximation on the DC coefficient where the /// default script uses one, and the AC spectrum cut into three bands. const fine_script = [_]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 }, }; test "a script of the caller's own carries the same image" { const gpa = testing.allocator; for ([_][]const Scan{ &plain_script, &fine_script }) |script| { for ([_]z2dimg.jpeg.Chroma{ .full, .half }) |chroma| { for ([_][2]i32{ .{ 48, 40 }, .{ 33, 17 }, .{ 1, 1 } }) |size| { var sfc = try gradient(gpa, .image_surface_rgb, size[0], size[1]); defer sfc.deinit(gpa); const base = try encodeJpeg(gpa, &sfc, .{ .chroma = chroma }); defer gpa.free(base); const prog = try encodeJpeg(gpa, &sfc, .{ .chroma = chroma, .mode = .progressive, .script = script, }); defer gpa.free(prog); // Every complete script carries the same coefficients however // it cuts them up, so the decoded images must be identical. var a = try decodeBytes(gpa, base); defer a.deinit(gpa); var b = try decodeBytes(gpa, prog); defer b.deinit(gpa); var y: i32 = 0; while (y < size[1]) : (y += 1) { var x: i32 = 0; while (x < size[0]) : (x += 1) { const pa = a.getPixel(x, y).?.rgb; const pb = b.getPixel(x, y).?.rgb; if (!std.meta.eql(pa, pb)) { std.debug.print("\n{d} scans, {t}, {d}x{d} at ({d},{d}): {any} against {any}\n", .{ script.len, chroma, size[0], size[1], x, y, pa, pb }); return error.ScriptDiffers; } } } } } } } test "the script that was asked for is the script that was written" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 32, 24); defer sfc.deinit(gpa); const bytes = try encodeJpeg(gpa, &sfc, .{ .mode = .progressive, .script = &fine_script }); defer gpa.free(bytes); var i: usize = 2; var at: usize = 0; while (i + 4 <= bytes.len and bytes[i] == 0xff) { const marker = bytes[i + 1]; if (marker == 0xd9) break; const length = mem.readInt(u16, bytes[i + 2 ..][0..2], .big); if (marker == 0xda) { const want = fine_script[at]; const n = bytes[i + 4]; try testing.expectEqual(@as(u8, @intCast(want.components.len)), n); for (want.components, 0..) |ci, k| { // Component identifiers are one-based in the file. try testing.expectEqual(ci + 1, bytes[i + 5 + k * 2]); } const spectral = i + 5 + @as(usize, n) * 2; try testing.expectEqual(want.ss, bytes[spectral]); try testing.expectEqual(want.se, bytes[spectral + 1]); try testing.expectEqual( (@as(u8, want.ah) << 4) | want.al, bytes[spectral + 2], ); at += 1; i += 2 + length; while (i + 1 < bytes.len) : (i += 1) { if (bytes[i] != 0xff) continue; if (bytes[i + 1] == 0x00) continue; if (bytes[i + 1] >= 0xd0 and bytes[i + 1] <= 0xd7) continue; break; } continue; } i += 2 + length; } try testing.expectEqual(fine_script.len, at); } test "every way a script can be wrong is named" { const Problem = z2dimg.jpeg.ScriptProblem; const check = z2dimg.jpeg.checkScript; // The default scripts are the reference: whatever the rules are, these // have to satisfy them. try testing.expectEqual(@as(?Problem, null), check(&z2dimg.jpeg.progressive_colour, 3)); try testing.expectEqual(@as(?Problem, null), check(&z2dimg.jpeg.progressive_grey, 1)); try testing.expectEqual(@as(?Problem, null), check(&plain_script, 3)); try testing.expectEqual(@as(?Problem, null), check(&fine_script, 3)); // The greyscale script names only component 0, so for a colour image it // is well formed and simply leaves the chroma unsent. try testing.expectEqual(@as(?Problem, .incomplete), check(&z2dimg.jpeg.progressive_grey, 3)); // And the colour one asks a one-component image for three. try testing.expectEqual(@as(?Problem, .bad_component_count), check(&z2dimg.jpeg.progressive_colour, 1)); const cases = [_]struct { want: Problem, components: usize = 3, script: []const Scan, }{ .{ .want = .empty, .script = &.{} }, .{ .want = .bad_component_count, .script = &.{ .{ .components = &.{}, .ss = 0, .se = 0, .ah = 0, .al = 0 }, } }, .{ .want = .bad_component_count, .script = &.{ .{ .components = &.{ 0, 1, 2, 3 }, .ss = 0, .se = 0, .ah = 0, .al = 0 }, } }, // A count the image could have, naming a component it has not. .{ .want = .no_such_component, .script = &.{ .{ .components = &.{5}, .ss = 0, .se = 0, .ah = 0, .al = 0 }, } }, .{ .want = .components_out_of_order, .script = &.{ .{ .components = &.{ 1, 0 }, .ss = 0, .se = 0, .ah = 0, .al = 0 }, } }, .{ .want = .components_out_of_order, .script = &.{ .{ .components = &.{ 0, 0 }, .ss = 0, .se = 0, .ah = 0, .al = 0 }, } }, .{ .want = .bad_band, .script = &.{ .{ .components = &.{0}, .ss = 1, .se = 64, .ah = 0, .al = 0 }, } }, .{ .want = .bad_band, .script = &.{ .{ .components = &.{0}, .ss = 20, .se = 5, .ah = 0, .al = 0 }, } }, .{ .want = .dc_and_ac_together, .script = &.{ .{ .components = &.{0}, .ss = 0, .se = 5, .ah = 0, .al = 0 }, } }, .{ .want = .interleaved_ac, .script = &.{ .{ .components = &.{ 0, 1 }, .ss = 1, .se = 63, .ah = 0, .al = 0 }, } }, .{ .want = .bad_point_transform, .script = &.{ .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 0, .al = 14 }, } }, // A first scan claiming to refine something. .{ .want = .bad_succession, .script = &.{ .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 1, .al = 0 }, } }, // A refinement that does not continue from where the last scan of // that coefficient stopped. .{ .want = .bad_succession, .script = &.{ .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 0, .al = 2 }, .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 1, .al = 0 }, } }, // And one that skips a bit on the way down. .{ .want = .bad_succession, .script = &.{ .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 0, .al = 3 }, .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 3, .al = 1 }, } }, // The DC coefficient sent and the AC spectrum never. .{ .want = .incomplete, .components = 1, .script = &.{ .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 0, .al = 0 }, } }, // Everything sent, and the bottom bit never reached. .{ .want = .incomplete, .components = 1, .script = &.{ .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 0, .al = 1 }, .{ .components = &.{0}, .ss = 1, .se = 63, .ah = 0, .al = 1 }, } }, }; for (cases, 0..) |k, i| { const got = check(k.script, k.components); if (got != k.want) { std.debug.print("\ncase {d}: wanted {t}, got {s}\n", .{ i, k.want, if (got) |g| @tagName(g) else "nothing", }); return error.WrongProblem; } } } test "a script that cannot be written is refused rather than written badly" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 16, 16); defer sfc.deinit(gpa); // Incomplete: the AC spectrum is never sent, so the file would decode to // a block-averaged smear rather than the image. const truncated = [_]Scan{ .{ .components = &.{ 0, 1, 2 }, .ss = 0, .se = 0, .ah = 0, .al = 0 }, }; try testing.expectError(error.Unsupported, encodeJpeg(gpa, &sfc, .{ .mode = .progressive, .script = &truncated, })); // And a script is only checked for the mode that uses one: baseline has // a single scan and no choice, so the same script is simply ignored. const bytes = try encodeJpeg(gpa, &sfc, .{ .mode = .baseline, .script = &truncated }); defer gpa.free(bytes); try testing.expect(mem.indexOf(u8, bytes, &.{ 0xff, 0xc0 }) != null); } test "a greyscale image takes a script that names only the component it has" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 24, 16); defer sfc.deinit(gpa); // The default colour script names components a one-component file has // not got. try testing.expectError(error.Unsupported, encodeJpeg(gpa, &sfc, .{ .colour = .greyscale, .mode = .progressive, .script = &z2dimg.jpeg.progressive_colour, })); // The greyscale one is fine, and so is a script of the caller's own. const single = [_]Scan{ .{ .components = &.{0}, .ss = 0, .se = 0, .ah = 0, .al = 0 }, .{ .components = &.{0}, .ss = 1, .se = 63, .ah = 0, .al = 0 }, }; for ([_][]const Scan{ &z2dimg.jpeg.progressive_grey, &single }) |script| { const bytes = try encodeJpeg(gpa, &sfc, .{ .colour = .greyscale, .mode = .progressive, .script = script, }); defer gpa.free(bytes); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 24), back.getWidth()); } } // -- trellis quantisation ---------------------------------------------------- test "the search makes a smaller file that is still the picture" { const gpa = testing.allocator; for ([_]z2dimg.jpeg.Chroma{ .full, .half }) |chroma| { for ([_]u7{ 40, 75, 95 }) |q| { var sfc = try gradient(gpa, .image_surface_rgb, 64, 48); defer sfc.deinit(gpa); const plain = try encodeJpeg(gpa, &sfc, .{ .quality = q, .chroma = chroma }); defer gpa.free(plain); const searched = try encodeJpeg(gpa, &sfc, .{ .quality = q, .chroma = chroma, .trellis = true, }); defer gpa.free(searched); if (searched.len >= plain.len) { std.debug.print("\n{t} q{d}: {d} bytes searched against {d} plain\n", .{ chroma, q, searched.len, plain.len }); return error.SearchDidNotHelp; } // Still an ordinary JPEG --- nothing about the format changes, only // the numbers in it --- and still the same picture. var back = try decodeBytes(gpa, searched); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 64), back.getWidth()); try testing.expectEqual(@as(i32, 48), back.getHeight()); var worst: u16 = 0; var y: i32 = 0; while (y < 48) : (y += 1) { var x: i32 = 0; while (x < 64) : (x += 1) { const src = sfc.getPixel(x, y).?.rgb; const out = back.getPixel(x, y).?.rgb; inline for (.{ "r", "g", "b" }) |ch| { const d: u16 = @intCast(@abs(@as(i32, @field(out, ch)) - @as(i32, @field(src, ch)))); worst = @max(worst, d); } } } if (worst > 24) { std.debug.print("\n{t} q{d}: worst {d} after a searched round trip\n", .{ chroma, q, worst }); return error.SearchLostTooMuch; } } } } test "a price of zero is plain rounding" { // The search's own degenerate case, checked through the encoder: when bits // are free the cheapest block is the nearest one, so the file has to come // out byte for byte the same as one written without searching at all. const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 48, 40); defer sfc.deinit(gpa); for ([_]z2dimg.jpeg.Mode{ .baseline, .progressive }) |mode| { const plain = try encodeJpeg(gpa, &sfc, .{ .mode = mode }); defer gpa.free(plain); const free = try encodeJpeg(gpa, &sfc, .{ .mode = mode, .trellis = true, .trellis_strength = 0, }); defer gpa.free(free); try testing.expectEqualSlices(u8, plain, free); } } test "the search works with everything else the encoder does" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 48, 40); defer sfc.deinit(gpa); // The coefficients it chooses are just coefficients, so every other option // has to go on working over them unchanged. const cases = [_]z2dimg.jpeg.EncodeOptions{ .{ .trellis = true, .mode = .progressive }, .{ .trellis = true, .tables = .annex_k }, .{ .trellis = true, .restart_interval = 3 }, .{ .trellis = true, .colour = .greyscale }, .{ .trellis = true, .chroma = .{ .factors = .{ .luma = .{ .h = 4, .v = 1 } } } }, .{ .trellis = true, .quant = .{ .luma = @splat(8), .chroma = @splat(24) } }, }; for (cases, 0..) |opts, i| { const bytes = encodeJpeg(gpa, &sfc, opts) catch |err| { std.debug.print("\ncase {d}: {t}\n", .{ i, err }); return err; }; defer gpa.free(bytes); var back = try decodeBytes(gpa, bytes); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 48), back.getWidth()); } } test "a price that is not a number is refused" { const gpa = testing.allocator; var sfc = try gradient(gpa, .image_surface_rgb, 16, 16); defer sfc.deinit(gpa); for ([_]f32{ -1.0, -0.0001, std.math.nan(f32), std.math.inf(f32) }) |bad| { try testing.expectError(error.Unsupported, encodeJpeg(gpa, &sfc, .{ .trellis = true, .trellis_strength = bad, })); } // And the setting is only consulted when the search is on, so nonsense // beside a search that is not happening is not an error. const bytes = try encodeJpeg(gpa, &sfc, .{ .trellis_strength = -5 }); defer gpa.free(bytes); try testing.expect(bytes.len > 0); }