// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! JPEG encoding of images destined for a Stream Deck. Devices that //! expect `ImageFormat.JPEG` key or touchscreen data are fed the bytes //! produced here. const std = @import("std"); const z2d = @import("z2d"); const z2dimg = @import("z2dimg"); /// The quality and table choices the encoder takes. pub const Options = z2dimg.jpeg.EncodeOptions; /// 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(); z2dimg.encode(alloc, &surface, &out.writer, .{ .jpeg = options }) catch |err| switch (err) { // An allocating writer has exactly one way to fail, and it is // running out of memory -- but it has to report that as // `WriteFailed`, because that is the only failure a `Writer` // has. Put the real reason back, so that a caller is not told // a write failed when there was no writer to fail. error.WriteFailed => return error.OutOfMemory, else => |e| return e, }; return try out.toOwnedSlice(); } test encode { const alloc = std.testing.allocator; 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, surface, .{}); defer alloc.free(data); // 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, }, data[0..11]); }