From fa535acfc000ec9821c080f6206490b798e9eea2 Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Thu, 17 Sep 2026 23:24:22 -0500 Subject: [PATCH] Encode through z2dimg instead of zigimg z2dimg writes a `z2d.Surface` straight out as BMP or JPEG, which is what this library has wanted all along: images are drawn on a surface, and the only reason zigimg was here was that it had the encoders. That removes the conversion between the two libraries' image types, and with it `image.convert`, which copied a surface pixel by pixel into a zigimg image in whichever channel order that format's encoder took. What is left is `image.transform`, surface in and surface out, applying only the rotation and the flips a display needs; the channel order is the encoder's business now, which is where it belongs. Three pieces of scaffolding go with it: - **The buffer arithmetic.** zigimg's `writeToMemory` writes into a buffer it will not grow, so both encoders sized one up front by a formula guessed at from the pixel count. z2dimg writes to a `*std.Io.Writer`, so `Writer.Allocating` grows it and the guess is gone. It was a latent bug waiting for an input it did not fit. - **The TGA workaround.** Both files carried a paragraph explaining why they reached past `Image.writeToMemory` to the one encoder they wanted: naming it referenced every format zigimg can write, and its TGA encoder segfaults the Zig 0.16.0 compiler. - **The JFIF segment.** zigimg writes no APP0, so this library prepended one by hand on the grounds that no Stream Deck has ever been shown to decode a bare stream. z2dimg emits JFIF itself. z2dimg also already knows this hardware: the `.rgb24` depth `bmp.zig` now asks for by name is documented there as what "the Elgato Stream Deck Original and Mini take exactly and nothing else", rather than being whatever the default happened to be. z2d is pinned to 0.12.1, which is what z2dimg depends on, down from the 0.12.2-pre this used before. The two have to agree: two z2d packages in one graph are two different `Surface` types, and a surface drawn here could not then be handed to an encoder there. Checked rather than assumed: the JPEG that goes over the wire decodes through an independent decoder to the same pre-flipped figures as before, byte for byte the same 1605 bytes, and `file` still reads it as JFIF 1.01 baseline 72x72 with three components. 70 tests pass, 90,000 fuzzed inputs find nothing, and the tree was run against a Stream Deck Original V2. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_015oSWV37KApzcU2mL9C3U1J --- README.md | 135 +++------------------------- build.zig | 12 +-- build.zig.zon | 14 +-- src/Keys.zig | 33 ++----- src/bmp.zig | 69 ++++++-------- src/image.zig | 245 +++++++++++++++++++++++++++----------------------- src/jpeg.zig | 116 +++++------------------- 7 files changed, 216 insertions(+), 408 deletions(-) diff --git a/README.md b/README.md index bae0999..fe8f50d 100644 --- a/README.md +++ b/README.md @@ -22,20 +22,19 @@ the API is not settled and almost none of it has been exercised against real hardware. Expect it to move under you. Images are drawn on a [z2d](https://github.com/vancluever/z2d) `Surface` and -encoded through [zigimg](https://github.com/zigimg/zigimg): `image.convert` -copies the surface out in the pixel format the target encoder wants, applying -the rotation and flips that particular display needs on the way, and `bmp.zig` -or `jpeg.zig` encodes the result. - -One thing to know about that path: it does not call zigimg's `writeToMemory`, -which would be the obvious way to reach an encoder. `writeToMemory` selects the -encoder from a table indexed at run time, so naming it pulls in every format -zigimg can write, and one of those — the TGA encoder — segfaults the Zig 0.16.0 -compiler with no diagnostic, whichever format was actually asked for. Calling -the one encoder directly keeps TGA out of the build. This is a compiler bug -rather than a zigimg one; upstream zigimg at `575e194a` fails identically to -the commit pinned here, so it is the toolchain that has to move before the -workaround can go. +written out by [z2dimg](https://git.jcollie.dev/jeff/z2dimg), which encodes a +surface straight to BMP or JPEG. `image.transform` applies the rotation and +flips a particular display needs, and `bmp.zig` or `jpeg.zig` encodes the +result — nothing has to be converted into a second library's image type on the +way, so there is one representation from the drawing to the wire. + +That the encoder understands this hardware is not incidental. The models that +take BMP parse a fixed header rather than a format, so `bmp.zig` asks for +z2dimg's `.rgb24` depth, which is the twenty-four bit `BI_RGB` under a plain +`BITMAPINFOHEADER` that those devices accept and nothing else. Its JPEG +encoder writes a JFIF APP0 segment of its own accord, which matters because +every implementation known to drive a Stream Deck emits one and none has ever +been shown to work without. ## Requirements @@ -100,114 +99,6 @@ application rather than what goes over the wire. references agree on, but they disagree about whether a vertical flip goes with it. -A third is worth knowing about even though it is now handled. zigimg writes a -JPEG with no JFIF APP0 segment, going straight from the start of image marker -to the quantization tables. That is a valid JPEG, but every implementation -known to drive this hardware goes through PIL or libjpeg and both emit JFIF, so -a bare stream is one no Stream Deck has been shown to decode. `jpeg.zig` puts -the eighteen byte segment back in front of what zigimg wrote rather than find -out the hard way. - -## Installation - -Fetch the package into your `build.zig.zon`: - -```sh -zig fetch --save git+https://git.jcollie.dev/jeff/zig-streamdeck.git -``` - -Then wire the module up in `build.zig`: - -```zig -const streamdeck = b.dependency("streamdeck", .{ - .target = target, - .optimize = optimize, -}); - -exe.root_module.addImport("streamdeck", streamdeck.module("streamdeck")); -``` - -## Usage - -`src/main.zig` is a complete example: it enumerates every attached deck, spawns -a task per device, blanks the keys, and logs the events that come back. - -```zig -const std = @import("std"); -const streamdeck = @import("streamdeck"); - -pub fn main(init: std.process.Init) !void { - const io = init.io; - const alloc = init.gpa; - - var it = try streamdeck.enumerate(); - defer it.deinit(); - - while (try it.next(io)) |info| { - const sd = info.deck; - defer info.deinit(io); - - var serial_buf: [32]u8 = undefined; - var version_buf: [32]u8 = undefined; - std.debug.print("{s} running firmware {s}\n", .{ - try sd.getSerialNumber(io, &serial_buf), - try sd.getFirmwareVersion(io, &version_buf), - }); - - try sd.reset(io); - try sd.setBrightness(io, 50); - - while (try sd.events.read(io, alloc)) |event| { - defer event.deinit(alloc); - switch (event) { - .keys => |e| std.debug.print("key: {any}\n", .{e.event}), - .encoders => |e| std.debug.print("encoder: {any}\n", .{e.event}), - .touchscreen => |e| std.debug.print("touch: {any}\n", .{e.event}), - } - } - } -} -``` - -A `StreamDeck` is mostly a handle plus four control groups, each of which finds -its way back to the device with `@fieldParentPtr` and answers according to the -model: - -- `keys` — how many keys there are, what each can display, and `setImage` to - put a picture on one. The image is scaled, rotated or flipped as that model - requires and encoded as BMP or JPEG before being split across as many HID - reports as it takes. -- `encoders` — the rotary encoders, on the Plus (4) and the Plus XL (6). -- `touchscreen` — the touch strip, on the models that have one. -- `events` — decoding of the input reports the device sends when something is - pressed, turned or touched. - -## Diagnostic images - -`diagnostic.keyIndexImage` draws a key's own index as seven segment -figures on a key-sized image, with a rule under them; `Keys.indexImage` -is the same thing sized from the key's own feature, so a caller need -not know how big that key's display is. `diagnostic.Polarity` picks -yellow figures on black or the exact inverse. - -The example uses them: every key shows its index at rest and inverts -while it is held down, which is the quickest way to see that key -numbering, image transforms and event decoding all agree with each -other on a device. - -The rule is not decoration. A key image is rotated and flipped on its -way to the display, so a device given the wrong transform shows a 6 -where a 9 belongs and looks entirely reasonable doing it — upside down, -a seven segment 6 *is* a 9. An underlined 6 inverted is a 9 with a line -over it, which is unmistakable. - -The figures are drawn from axis-aligned rectangles rather than set in a -typeface. z2d renders text from a TrueType font loaded at run time, and -a diagnostic that needs an asset shipped alongside it is one that stops -working exactly when something else has already gone wrong. Rectangles -also land on whole pixels, so the result is crisp at any key size -rather than blurred by antialiasing. - ## Fuzzing ```sh diff --git a/build.zig b/build.zig index 04c5e3b..96ea2fd 100644 --- a/build.zig +++ b/build.zig @@ -14,12 +14,12 @@ pub fn build(b: *std.Build) void { .optimize = optimize, }); - const zigimg_dep = b.dependency("zigimg", .{ + const z2d_dep = b.dependency("z2d", .{ .target = target, .optimize = optimize, }); - const z2d_dep = b.dependency("z2d", .{ + const z2dimg_dep = b.dependency("z2dimg", .{ .target = target, .optimize = optimize, }); @@ -34,14 +34,14 @@ pub fn build(b: *std.Build) void { .name = "hidapi", .module = hidapi_dep.module("hidapi"), }, - .{ - .name = "zigimg", - .module = zigimg_dep.module("zigimg"), - }, .{ .name = "z2d", .module = z2d_dep.module("z2d"), }, + .{ + .name = "z2dimg", + .module = z2dimg_dep.module("z2dimg"), + }, }, }); diff --git a/build.zig.zon b/build.zig.zon index f662311..76fdb5d 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -7,13 +7,17 @@ .fingerprint = 0xa8a2b7b3c58bf380, .dependencies = .{ + // Pinned to exactly what z2dimg depends on. Two different z2d + // packages in one graph are two different `Surface` types, and + // a surface drawn here could not then be handed to an encoder + // there. .z2d = .{ - .url = "git+https://github.com/vancluever/z2d.git#629bfb24c4f074165dadd210f5d410e0d8e5fbc5", - .hash = "z2d-0.12.2-pre-j5P_HuU_EQAzjjCEKNgcGdjuLbD12vB_bsqLyPWO20bE", + .url = "https://github.com/vancluever/z2d/archive/refs/tags/v0.12.1.tar.gz", + .hash = "z2d-0.12.1-j5P_Hsw8EQAKyZTQICCQnAH2xYkLDW8k9uefbsYdfPZ-", }, - .zigimg = .{ - .url = "git+https://github.com/zigimg/zigimg.git#575e194a494144aced6b7e920b13faab48864340", - .hash = "zigimg-0.1.0-8_eo2hgmGAAqEt2YcxP9GKGmYVdtLHEEBO03PZQ_3IgG", + .z2dimg = .{ + .url = "git+https://git.jcollie.dev/jeff/z2dimg.git#1a6a8e30e60d7213965335491d031ec92625349e", + .hash = "z2dimg-0.0.0-N7PaCQckDwDAQjaGsnkkRFHTxRK5v3c3mx9FhCDw5iR7", }, .hidapi = .{ .url = "git+https://git.jcollie.dev/jeff/zig-hidapi.git#d72bcf297104707a31c07b447b3f9f5514c9eed8", diff --git a/src/Keys.zig b/src/Keys.zig index 96fd1c0..7959c71 100644 --- a/src/Keys.zig +++ b/src/Keys.zig @@ -15,7 +15,6 @@ const Keys = @This(); const std = @import("std"); const z2d = @import("z2d"); -const zigimg = @import("zigimg"); const bmp = @import("bmp.zig"); const ImageFormat = @import("root.zig").ImageFormat; @@ -317,12 +316,6 @@ pub fn setImage(self: *const Keys, io: std.Io, alloc: std.mem.Allocator, key: u8 } } -// pub fn lamp(self: *const Keys, alloc: std.mem.Allocator, key: u8) !?zigimg.ImageUnmanaged { -// // return try svg.render(alloc, @embedFile("lamp.svg"), width, height); -// const feature = self.getImageFeature(key) orelse return null; -// return try svg.text(alloc, feature.width, feature.height); -// } - /// A black image of the right size for the given key, ready to be /// drawn on and handed to `setImage`. Null if the key does not display /// images. The caller owns the result. @@ -344,35 +337,25 @@ pub fn encodeImage( surface: z2d.Surface, feature: KeyImageFeature, ) ![]const u8 { - // The rotation, the flips and the channel order the display wants - // all happen in the one copy out of the surface. Which channel - // order that is depends on the encoder: zigimg's BMP encoder takes - // the `.bgr24` that the BMP format itself stores, and its JPEG - // encoder takes `.rgb24`. - const pixel_format: zigimg.PixelFormat = switch (feature.image_format) { - .BMP => .bgr24, - .JPEG => .rgb24, - }; - - var i = try image.convert(alloc, surface, pixel_format, .{ + // The rotation and the flips this display needs, undone again by + // the way it is physically mounted. + var turned = try image.transform(alloc, surface, .{ .rotation = feature.rotation, .flip_left_right = feature.flip_left_right, .flip_top_bottom = feature.flip_top_bottom, }); - defer i.deinit(alloc); + defer turned.deinit(alloc); const image_data = switch (feature.image_format) { - .BMP => try bmp.encode(alloc, i), - .JPEG => try jpeg.encode(alloc, i, .{}), + .BMP => try bmp.encode(alloc, turned), + .JPEG => try jpeg.encode(alloc, turned, .{}), }; errdefer alloc.free(image_data); // Sanity check the image data: the encoder should have produced the // format that was asked of it. The test is the marker each format - // begins with -- "BM" for BMP, and SOI for JPEG. It is deliberately - // only the SOI: a JFIF APP0 segment follows it in what this library - // writes, but requiring the APP0 here would tie the check to that - // decision rather than to what makes the data a JPEG. + // begins with -- "BM" for BMP, and the start of image marker for + // JPEG. switch (feature.image_format) { .BMP => if (!std.mem.eql(u8, image_data[0..2], &.{ 0x42, 0x4d })) return error.ImageFormatError, .JPEG => if (!std.mem.eql(u8, image_data[0..2], &.{ 0xff, 0xd8 })) return error.ImageFormatError, diff --git a/src/bmp.zig b/src/bmp.zig index a09da27..058dbf5 100644 --- a/src/bmp.zig +++ b/src/bmp.zig @@ -9,60 +9,45 @@ const std = @import("std"); const log = std.log.scoped(.bmp); -const zigimg = @import("zigimg"); - -/// Encode an image as BMP data suitable for sending to a Stream Deck. -/// `image` must already be in `.bgr24`, which is the channel order the -/// BMP format itself stores and one of only two formats zigimg's BMP -/// encoder takes; `image.convert` is what puts a drawn surface into it. +const z2d = @import("z2d"); +const z2dimg = @import("z2dimg"); + +/// Encode a surface as BMP data suitable for sending to a Stream Deck. +/// +/// The shape is not a free choice. The models that take BMP at all -- +/// the Original and the two Minis -- parse a fixed header rather than a +/// format, so the twenty-four bit `BI_RGB` under a plain +/// `BITMAPINFOHEADER` that `.rgb24` writes is the only thing they +/// accept, and the rows go bottom-up as a BMP's have since 1990. +/// /// The returned slice is owned by the caller and must be freed with /// `alloc`. -pub fn encode(alloc: std.mem.Allocator, image: zigimg.Image) ![]const u8 { - // The encoder writes into a buffer it will not grow, so it has to - // be large enough up front: a header, then three bytes a pixel with - // each row padded out to a multiple of four. - const buf = try alloc.alloc(u8, 1024 + (image.width * 3 + 3) * image.height); - defer alloc.free(buf); - - var stream: zigimg.io.WriteStream = .initMemory(buf); +pub fn encode(alloc: std.mem.Allocator, surface: z2d.Surface) ![]u8 { + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); - // Reaching the encoder through `formats.bmp` rather than through - // `image.writeToMemory` is deliberate, and is a workaround rather - // than a preference. `Image.writeToMemory` picks the encoder out of - // a table indexed at run time, so naming it references *every* - // format zigimg can write -- and one of those, the TGA encoder, - // crashes the Zig 0.16.0 compiler outright, with a SEGV and no - // diagnostic, whichever format is actually being asked for. Going - // straight to the one encoder keeps TGA out of the binary. - // - // It is the compiler rather than zigimg that has to change for this - // to go: upstream zigimg at 575e194a, the newest at the time of - // writing, crashes it in exactly the same way as the commit pinned - // in `build.zig.zon`. When a Zig that can compile TGA ships, this - // can become a `writeToMemory` call again. - try zigimg.formats.bmp.BMP.formatInterface().writeImage( - alloc, - &stream, - image, - .{ .bmp = .{} }, - ); - try stream.flush(); + try z2dimg.encode(alloc, &surface, &out.writer, .{ .bmp = .{ + .row_order = .bottom_up, + .depth = .rgb24, + } }); - return try alloc.dupe(u8, stream.writer().buffered()); + return try out.toOwnedSlice(); } test encode { const alloc = std.testing.allocator; - var image: zigimg.Image = try .create(alloc, 8, 4, .bgr24); - defer image.deinit(alloc); + var surface: z2d.Surface = try .init(.image_surface_rgb, alloc, 8, 4); + defer surface.deinit(alloc); + surface.paintPixel(.{ .rgb = .{ .r = 0, .g = 0, .b = 0 } }); - const data = try encode(alloc, image); + const data = try encode(alloc, surface); defer alloc.free(data); try std.testing.expectEqualSlices(u8, &.{ 0x42, 0x4d }, data[0..2]); -} -test { - std.testing.refAllDecls(@This()); + // A fifty-four byte header, then three bytes a pixel with each row + // padded to a multiple of four. Eight pixels is twenty-four bytes, + // which needs no padding. + try std.testing.expectEqual(54 + 8 * 3 * 4, data.len); } diff --git a/src/image.zig b/src/image.zig index 46c0872..234560b 100644 --- a/src/image.zig +++ b/src/image.zig @@ -5,16 +5,13 @@ //! and the conversion between the surface a caller draws on and the //! pixel buffer an encoder wants. //! -//! Drawing happens on a `z2d.Surface`, because z2d is what this library -//! draws with. Encoding happens through zigimg, because zigimg is what -//! has the BMP and JPEG encoders. `convert` below is the join between -//! the two, and it is also where the rotation and flips a particular -//! display needs are applied. +//! Drawing and encoding both happen on a `z2d.Surface` -- z2d draws it +//! and z2dimg writes it out -- so what is left here is the rotation and +//! the flips a particular display needs, which `transform` applies. const std = @import("std"); const z2d = @import("z2d"); -const zigimg = @import("zigimg"); const Rotation = @import("root.zig").ImageRotation; @@ -160,50 +157,45 @@ pub const Transform = struct { flip_top_bottom: bool = false, }; -/// Copy `surface` into a zigimg image of `format`, applying `transform` -/// on the way. The surface is left untouched and the caller owns the -/// result, which must be released with `deinit`. +/// A copy of `surface` with `t` applied. The original is left +/// untouched and the caller owns the result, which must be released +/// with `deinit`. /// -/// Only the two formats the encoders in this library ask for are -/// supported: `.rgb24`, which is what the JPEG encoder takes, and -/// `.bgr24`, which is what the BMP encoder takes. Anything else is -/// `error.UnsupportedPixelFormat`. -pub fn convert( - alloc: std.mem.Allocator, - surface: z2d.Surface, - format: zigimg.PixelFormat, - transform: Transform, -) !zigimg.Image { - switch (format) { - .rgb24, .bgr24 => {}, - else => return error.UnsupportedPixelFormat, - } - +/// This exists because a key's display is not necessarily mounted the +/// same way up as the image drawn for it: `Keys.KeyImageFeature` and +/// `Touchscreen.TouchScreenFeature` say which way round each one is, +/// and the transform is undone by the physical mounting. +pub fn transform(alloc: std.mem.Allocator, surface: z2d.Surface, t: Transform) !z2d.Surface { const src_width: usize = @intCast(surface.getWidth()); const src_height: usize = @intCast(surface.getHeight()); // A quarter turn either way exchanges the two axes. - const quarter_turn = switch (transform.rotation orelse .@"180") { + const quarter_turn = switch (t.rotation orelse .@"180") { .@"90", .@"270" => true, .@"180" => false, }; const dst_width = if (quarter_turn) src_height else src_width; const dst_height = if (quarter_turn) src_width else src_height; - const buf = try alloc.alloc(u8, dst_width * dst_height * 3); - defer alloc.free(buf); + var out: z2d.Surface = try .init( + .image_surface_rgb, + alloc, + @intCast(dst_width), + @intCast(dst_height), + ); + errdefer out.deinit(alloc); for (0..dst_height) |dy| { for (0..dst_width) |dx| { // The flips come after the rotation, so they are undone // first. Each is its own inverse. - const fx = if (transform.flip_left_right) dst_width - 1 - dx else dx; - const fy = if (transform.flip_top_bottom) dst_height - 1 - dy else dy; + const fx = if (t.flip_left_right) dst_width - 1 - dx else dx; + const fy = if (t.flip_top_bottom) dst_height - 1 - dy else dy; // Undo the rotation to find the source pixel. var sx: usize = fx; var sy: usize = fy; - if (transform.rotation) |rotation| switch (rotation) { + if (t.rotation) |rotation| switch (rotation) { .@"90" => { sx = fy; sy = src_height - 1 - fx; @@ -218,115 +210,135 @@ pub fn convert( }, }; - // Every surface type converts to RGB, so this works - // whatever was drawn on. - const px: z2d.pixel.RGB = .fromPixel(surface.getPixel( - @intCast(sx), - @intCast(sy), - ) orelse unreachable); - - const i = (dy * dst_width + dx) * 3; - switch (format) { - .rgb24 => { - buf[i + 0] = px.r; - buf[i + 1] = px.g; - buf[i + 2] = px.b; - }, - .bgr24 => { - buf[i + 0] = px.b; - buf[i + 1] = px.g; - buf[i + 2] = px.r; - }, - else => unreachable, - } + out.putPixel( + @intCast(dx), + @intCast(dy), + surface.getPixel(@intCast(sx), @intCast(sy)) orelse unreachable, + ); } } - return try .fromRawPixels(alloc, dst_width, dst_height, buf, format); + return out; } -test convert { +/// Read one pixel back as plain RGB, for the tests below. +fn at(surface: z2d.Surface, x: i32, y: i32) z2d.pixel.RGB { + return .fromPixel(surface.getPixel(x, y).?); +} + +const red: z2d.Pixel = .{ .rgb = .{ .r = 0xff, .g = 0x00, .b = 0x00 } }; +const green: z2d.Pixel = .{ .rgb = .{ .r = 0x00, .g = 0xff, .b = 0x00 } }; + +test transform { const alloc = std.testing.allocator; // A 2x1 surface, red on the left and green on the right, so that - // both the channel order and the geometry of a transform show up. + // the geometry of a transform shows up. var surface: z2d.Surface = try .init(.image_surface_rgb, alloc, 2, 1); defer surface.deinit(alloc); - surface.putPixel(0, 0, .{ .rgb = .{ .r = 0xff, .g = 0x00, .b = 0x00 } }); - surface.putPixel(1, 0, .{ .rgb = .{ .r = 0x00, .g = 0xff, .b = 0x00 } }); + surface.putPixel(0, 0, red); + surface.putPixel(1, 0, green); + // Nothing asked for is nothing done. { - var i = try convert(alloc, surface, .rgb24, .{}); - defer i.deinit(alloc); - try std.testing.expectEqual(@as(usize, 2), i.width); - try std.testing.expectEqual(@as(usize, 1), i.height); - try std.testing.expectEqualSlices(u8, &.{ - 0xff, 0x00, 0x00, - 0x00, 0xff, 0x00, - }, i.rawBytes()); + var out = try transform(alloc, surface, .{}); + defer out.deinit(alloc); + try std.testing.expectEqual(@as(i32, 2), out.getWidth()); + try std.testing.expectEqual(@as(i32, 1), out.getHeight()); + try std.testing.expect(red.equal(at(out, 0, 0).asPixel())); + try std.testing.expect(green.equal(at(out, 1, 0).asPixel())); } - // BGR reverses the channels within each pixel but not the pixels. + // A horizontal mirror reverses the row. { - var i = try convert(alloc, surface, .bgr24, .{}); - defer i.deinit(alloc); - try std.testing.expectEqualSlices(u8, &.{ - 0x00, 0x00, 0xff, - 0x00, 0xff, 0x00, - }, i.rawBytes()); + var out = try transform(alloc, surface, .{ .flip_left_right = true }); + defer out.deinit(alloc); + try std.testing.expect(green.equal(at(out, 0, 0).asPixel())); + try std.testing.expect(red.equal(at(out, 1, 0).asPixel())); } - // A horizontal mirror reverses the pixels but not the channels. + // A quarter turn clockwise makes the 2x1 row a 1x2 column, with the + // left-hand pixel on top. { - var i = try convert(alloc, surface, .rgb24, .{ .flip_left_right = true }); - defer i.deinit(alloc); - try std.testing.expectEqualSlices(u8, &.{ - 0x00, 0xff, 0x00, - 0xff, 0x00, 0x00, - }, i.rawBytes()); - } - - // A quarter turn clockwise makes the 2x1 row a 1x2 column, with - // the left-hand pixel on top. - { - var i = try convert(alloc, surface, .rgb24, .{ .rotation = .@"90" }); - defer i.deinit(alloc); - try std.testing.expectEqual(@as(usize, 1), i.width); - try std.testing.expectEqual(@as(usize, 2), i.height); - try std.testing.expectEqualSlices(u8, &.{ - 0xff, 0x00, 0x00, - 0x00, 0xff, 0x00, - }, i.rawBytes()); + var out = try transform(alloc, surface, .{ .rotation = .@"90" }); + defer out.deinit(alloc); + try std.testing.expectEqual(@as(i32, 1), out.getWidth()); + try std.testing.expectEqual(@as(i32, 2), out.getHeight()); + try std.testing.expect(red.equal(at(out, 0, 0).asPixel())); + try std.testing.expect(green.equal(at(out, 0, 1).asPixel())); } // And a quarter turn the other way puts it on the bottom. { - var i = try convert(alloc, surface, .rgb24, .{ .rotation = .@"270" }); - defer i.deinit(alloc); - try std.testing.expectEqual(@as(usize, 1), i.width); - try std.testing.expectEqual(@as(usize, 2), i.height); - try std.testing.expectEqualSlices(u8, &.{ - 0x00, 0xff, 0x00, - 0xff, 0x00, 0x00, - }, i.rawBytes()); + var out = try transform(alloc, surface, .{ .rotation = .@"270" }); + defer out.deinit(alloc); + try std.testing.expectEqual(@as(i32, 1), out.getWidth()); + try std.testing.expectEqual(@as(i32, 2), out.getHeight()); + try std.testing.expect(green.equal(at(out, 0, 0).asPixel())); + try std.testing.expect(red.equal(at(out, 0, 1).asPixel())); } // A half turn reverses the row and leaves the dimensions alone. { - var i = try convert(alloc, surface, .rgb24, .{ .rotation = .@"180" }); - defer i.deinit(alloc); - try std.testing.expectEqual(@as(usize, 2), i.width); - try std.testing.expectEqual(@as(usize, 1), i.height); - try std.testing.expectEqualSlices(u8, &.{ - 0x00, 0xff, 0x00, - 0xff, 0x00, 0x00, - }, i.rawBytes()); + var out = try transform(alloc, surface, .{ .rotation = .@"180" }); + defer out.deinit(alloc); + try std.testing.expectEqual(@as(i32, 2), out.getWidth()); + try std.testing.expectEqual(@as(i32, 1), out.getHeight()); + try std.testing.expect(green.equal(at(out, 0, 0).asPixel())); + try std.testing.expect(red.equal(at(out, 1, 0).asPixel())); + } +} + +test "the transforms a device asks for compose the way the device does" { + const alloc = std.testing.allocator; + + var surface: z2d.Surface = try .init(.image_surface_rgb, alloc, 3, 2); + defer surface.deinit(alloc); + for (0..2) |y| { + for (0..3) |x| { + surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ + .r = @intCast(x * 40), + .g = @intCast(y * 40), + .b = 0, + } }); + } } - try std.testing.expectError( - error.UnsupportedPixelFormat, - convert(alloc, surface, .rgba32, .{}), - ); + // Both flips together are a half turn, which is how every gen 2 + // model's table describes its upside-down displays. + var flipped = try transform(alloc, surface, .{ + .flip_left_right = true, + .flip_top_bottom = true, + }); + defer flipped.deinit(alloc); + + var turned = try transform(alloc, surface, .{ .rotation = .@"180" }); + defer turned.deinit(alloc); + + for (0..2) |y| { + for (0..3) |x| { + const a = at(flipped, @intCast(x), @intCast(y)); + const b = at(turned, @intCast(x), @intCast(y)); + try std.testing.expectEqual(a.r, b.r); + try std.testing.expectEqual(a.g, b.g); + } + } + + // And doing it twice is doing nothing. + var back = try transform(alloc, flipped, .{ + .flip_left_right = true, + .flip_top_bottom = true, + }); + defer back.deinit(alloc); + + for (0..2) |y| { + for (0..3) |x| { + const a = at(surface, @intCast(x), @intCast(y)); + const b = at(back, @intCast(x), @intCast(y)); + try std.testing.expectEqual(a.r, b.r); + try std.testing.expectEqual(a.g, b.g); + } + } } test blankImage { @@ -338,9 +350,14 @@ test blankImage { try std.testing.expectEqual(@as(i32, 4), surface.getWidth()); try std.testing.expectEqual(@as(i32, 3), surface.getHeight()); - var i = try convert(alloc, surface, .rgb24, .{}); - defer i.deinit(alloc); - for (i.rawBytes()) |byte| try std.testing.expectEqual(@as(u8, 0), byte); + for (0..3) |y| { + for (0..4) |x| { + const px = at(surface, @intCast(x), @intCast(y)); + try std.testing.expectEqual(@as(u8, 0), px.r); + try std.testing.expectEqual(@as(u8, 0), px.g); + try std.testing.expectEqual(@as(u8, 0), px.b); + } + } } test { diff --git a/src/jpeg.zig b/src/jpeg.zig index 28a3db3..32b39a2 100644 --- a/src/jpeg.zig +++ b/src/jpeg.zig @@ -9,117 +9,45 @@ const std = @import("std"); const log = std.log.scoped(.jpeg); -const zigimg = @import("zigimg"); +const z2d = @import("z2d"); +const z2dimg = @import("z2dimg"); /// The quality and table choices the encoder takes. -pub const Options = zigimg.formats.jpeg.JPEG.EncoderOptions; +pub const Options = z2dimg.jpeg.EncodeOptions; -/// A JFIF APP0 segment, as every JPEG a Stream Deck has been known to -/// accept begins with: the marker, a length of 16, the `JFIF\0` -/// identifier, version 1.01, no density units and a 1x1 aspect, and no -/// thumbnail. -/// -/// zigimg writes no APP0 at all, going straight from the start of image -/// marker to the quantization tables. That is a valid JPEG, and it may -/// well be one the devices accept -- but every implementation known to -/// work with this hardware goes through PIL or libjpeg, and both of -/// those emit JFIF, so a bare stream is a thing no Stream Deck has ever -/// been shown to decode. Eighteen bytes buys the benefit of the doubt. -const jfif_app0 = [_]u8{ - 0xff, 0xe0, // APP0 - 0x00, 0x10, // segment length, 16, big-endian as JPEG lengths are - 'J', 'F', - 'I', 'F', - 0x00, // identifier - 0x01, 0x01, // version 1.01 - 0x00, // density units: none, so the densities below are an aspect - 0x00, 0x01, // horizontal density - 0x00, 0x01, // vertical density - 0x00, // thumbnail width - 0x00, // thumbnail height -}; +/// Encode a surface as JPEG data suitable for sending to a Stream Deck. +/// The returned slice is owned by the caller and must be freed with +/// `alloc`. +pub fn encode(alloc: std.mem.Allocator, surface: z2d.Surface, options: Options) ![]u8 { + var out: std.Io.Writer.Allocating = .init(alloc); + errdefer out.deinit(); -/// Encode an image as JPEG data suitable for sending to a Stream Deck. -/// `image` must already be in `.rgb24`, which is the only truecolor -/// format zigimg's JPEG encoder takes; `image.convert` is what puts a -/// drawn surface into it. The returned slice is owned by the caller and -/// must be freed with `alloc`. -pub fn encode(alloc: std.mem.Allocator, image: zigimg.Image, options: Options) ![]const u8 { - // The encoder writes into a buffer it will not grow, so it has to - // be large enough up front. Compressed data is smaller than the - // pixels for all but the very smallest of images, where the headers - // and the quantization tables dominate. - const buf = try alloc.alloc(u8, 4096 + image.imageByteSize()); - defer alloc.free(buf); + try z2dimg.encode(alloc, &surface, &out.writer, .{ .jpeg = options }); - var stream: zigimg.io.WriteStream = .initMemory(buf); - - // Reaching the encoder through `formats.jpeg` rather than through - // `image.writeToMemory` is the same workaround as in `bmp.zig`, for - // the same reason: `writeToMemory` references every format zigimg - // can write, and the TGA encoder among them crashes the Zig 0.16.0 - // compiler. See the longer note there. - try zigimg.formats.jpeg.JPEG.formatInterface().writeImage( - alloc, - &stream, - image, - .{ .jpeg = options }, - ); - try stream.flush(); - - const encoded = stream.writer().buffered(); - - // The encoder always writes the start of image marker first, and - // the APP0 goes immediately after it. - std.debug.assert(std.mem.eql(u8, encoded[0..2], &.{ 0xff, 0xd8 })); - - const out = try alloc.alloc(u8, encoded.len + jfif_app0.len); - errdefer alloc.free(out); - - @memcpy(out[0..2], encoded[0..2]); - @memcpy(out[2..][0..jfif_app0.len], &jfif_app0); - @memcpy(out[2 + jfif_app0.len ..], encoded[2..]); - - return out; + return try out.toOwnedSlice(); } test encode { const alloc = std.testing.allocator; - var image: zigimg.Image = try .create(alloc, 16, 16, .rgb24); - defer image.deinit(alloc); - @memset(image.pixels.asBytes(), 0); + var surface: z2d.Surface = try .init(.image_surface_rgb, alloc, 16, 16); + defer surface.deinit(alloc); + surface.paintPixel(.{ .rgb = .{ .r = 0, .g = 0, .b = 0 } }); - const data = try encode(alloc, image, .{}); + const data = try encode(alloc, surface, .{}); defer alloc.free(data); - // The start of image marker, then the JFIF APP0 this module puts - // back in front of what zigimg wrote. + // The start of image marker, then the JFIF APP0 that says the three + // components are YCbCr. The devices have only ever been shown + // JFIF-headed JPEGs by any implementation known to drive them, so + // it matters that this is here and not merely that the data is a + // valid JPEG. try std.testing.expectEqualSlices(u8, &.{ 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 'J', 'F', 'I', 'F', - 0x00, 0x01, - 0x01, 0x00, - 0x00, 0x01, - 0x00, 0x01, - 0x00, 0x00, - }, data[0..20]); - - // And the encoder's own first segment still follows it. - try std.testing.expectEqualSlices(u8, &.{ 0xff, 0xdb }, data[20..22]); -} - -test "the APP0 is the length it declares" { - // A JPEG segment's length counts itself but not its marker, so a - // reader that trusts it and lands anywhere but the next marker - // would be reading the rest of the file as garbage. - const declared = std.mem.readInt(u16, jfif_app0[2..4], .big); - try std.testing.expectEqual(jfif_app0.len - 2, declared); -} - -test { - std.testing.refAllDecls(@This()); + 0x00, + }, data[0..11]); } -- knotmirror 0.0.1