// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The screen behind the keys. //! //! A Stream Deck's keys are not separate displays. Every model that //! shows images has **one** LCD panel, and the keys are windows onto //! it; the key images this library sends are cut-outs written into //! their own rectangles of that panel. The panel can also be written //! whole, which is what this does. //! //! That is worth having for two things a key-at-a-time interface //! cannot do: a background that runs behind and between the keys, and //! a single write that repaints everything instead of one report per //! key. //! //! **This is how a background is done.** Elgato's desktop software has //! a feature it calls one -- an image behind the key layout, showing //! wherever the key artwork does not cover it -- and that feature is //! the application's rather than the device's: it composites host-side //! and sends ordinary key images. The same effect is `setImage` here, //! followed by drawing over only the keys that want a foreground. A key //! left alone goes on showing the panel, so "the background shows where //! the foreground is transparent" means nothing more than not writing //! that key. Confirmed on an Original V2, a Neo and a Plus. //! //! ## A painted panel frames every key //! //! A key cap shows slightly more of the panel than the key image //! covers. Paint the panel green and write a flat black image to every //! key, and every key keeps a green border -- confirmed on an Original //! V2, a Neo and a Plus, all three. //! //! That is the physical cap rather than anything this library does. //! The image occupies its documented size exactly, and the caps are //! wider than it, so they also show some of the gap around it: a //! Classic panel is 480x272 carrying fifteen keys of 72x72, which //! leaves a hundred and twenty pixels across and fifty-six down for //! margins and gaps, and node-elgato-stream-deck puts twenty-five pixel //! gaps between the keys and eleven before the first column. Neither it //! nor Elgato's documentation mentions that any of that is visible. //! //! It is worth knowing rather than worth fixing, and it is probably //! what a background is supposed to look like: whatever is on the panel //! becomes a border around every key, so artwork drawn key by key sits //! in a frame of it rather than against black. //! //! `setBackground` further down is a different thing that happens to //! share the name: a real HID command for storing an image *in* the //! device, which nothing here has ever been able to make visible. //! //! A `Panel` lives as the `panel` field of a `StreamDeck` and carries //! no state of its own, recovering the device it belongs to with //! `@fieldParentPtr`. //! //! The sizes below come from Elgato's own HID documentation, which //! gives one per device family. They can be checked against the device //! itself: `StreamDeck.getUnitInfo` asks it, and it answers with the //! same numbers -- a Neo and a Plus were asked, and did. The Galleon's //! is the exception and the other way round: Elgato documents nothing //! for it, so its 720x1280 was taken from what the device said about //! itself. //! //! **Confirmed against the hardware.** A checkerboard painted over a //! Neo's whole panel appears through every key *and* through the info //! strip, and the pattern runs continuously from one key to the next //! rather than restarting in each. It reaches the **two small indicator //! bars** flanking that strip as well: an image with a different colour //! in each corner put its bottom-right one on the right-hand bar. A Neo //! background paints eleven things, not eight. That is the premise of this file //! shown rather than assumed: there is one screen, the keys are //! windows onto it, and what lands under a key is whatever part of the //! image that window happens to cover. A marker in the image's //! top-left corner came out under the top-left key, which is what says //! the transform is the right way round. const std = @import("std"); const z2d = @import("z2d"); const Panel = @This(); const image = @import("image.zig"); const ImageHeaderV5 = image.ImageHeaderV5; const ImageHeaderV6 = image.ImageHeaderV6; const ImageFormat = @import("root.zig").ImageFormat; const ImageRotation = @import("root.zig").ImageRotation; const StreamDeck = @import("StreamDeck.zig"); const jpeg = @import("jpeg.zig"); /// The value to initialize the `panel` field of a `StreamDeck` with. pub const init: Panel = .{}; /// Everything needed to put an image on the panel: how large it is, and /// the rotation and flips it needs first, which are the same ones that /// model's keys need because it is the same glass. pub const PanelFeature = struct { width: u16, height: u16, image_format: ImageFormat, rotation: ?ImageRotation, flip_left_right: bool, flip_top_bottom: bool, /// How many screens the panel is made of, side by side. One on /// every model but the Studio, whose panel is two: the left eight /// columns of keys are on screen 0 and the right eight on screen 1, /// each written and filled separately. `width` is the whole panel, /// all the screens together, so a surface for `setImage` is drawn /// as one picture and split here; each screen is `width / screens` /// across, and that is the size the device reports about itself. screens: u8 = 1, }; /// The panel this model has, or null if it has none that can be written /// whole. /// /// The older protocol is the reason for most of the nulls: the Mini /// family has a panel, and Elgato documents its size, but the only /// output report those devices take writes a key's image bank, so there /// is no command to send. The Pedal has no display at all, and the /// Original has no documentation to take a size from. pub fn getFeature(self: *const Panel) ?PanelFeature { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("panel", self)); return switch (sd.type) { // The Classic family: one 480x272 panel behind fifteen keys. .ElgatoStreamDeckOriginalV2, .ElgatoStreamDeckMK2, .ElgatoStreamDeckMK2Scissor, .ElgatoStreamDeckModule15, => .{ .width = 480, .height = 272, .image_format = .JPEG, .rotation = null, .flip_left_right = true, .flip_top_bottom = true, }, // The XL family. .ElgatoStreamDeckXL, .ElgatoStreamDeckXLV2, .ElgatoStreamDeckModule32, => .{ .width = 1024, .height = 600, .image_format = .JPEG, .rotation = null, .flip_left_right = true, .flip_top_bottom = true, }, // The Neo's panel carries its eight keys and its info strip. .ElgatoStreamDeckNeo => .{ .width = 480, .height = 320, .image_format = .JPEG, .rotation = null, .flip_left_right = true, .flip_top_bottom = true, }, // The Plus, whose touchscreen is the bottom strip of this. .ElgatoStreamDeckPlus => .{ .width = 800, .height = 480, .image_format = .JPEG, .rotation = null, .flip_left_right = false, .flip_top_bottom = false, }, // The Plus XL, a quarter turn round like its keys. .ElgatoStreamDeckPlusXL => .{ .width = 1280, .height = 800, .image_format = .JPEG, .rotation = .@"270", .flip_left_right = false, .flip_top_bottom = false, }, // The Galleon: the only panel here in portrait, and the only // one whose size was not read out of documentation. The device // was asked and answered 720x1280, which is firmer ground than // the other entries stand on -- but it is gen2, so the command // to write it is the same one every entry above uses, and // whether it accepts that command has not been seen. The // transform follows its keys, as every other entry's does, // and its keys' transform is itself unconfirmed. .CorsairGalleonK100 => .{ .width = 720, .height = 1280, .image_format = .JPEG, .rotation = null, .flip_left_right = false, .flip_top_bottom = false, }, // The Studio: two screens of 1424x280, side by side, each behind // eight columns of keys. Elgato documents none of it. The device // reports 1424x280 about itself, which is one screen; // node-elgato-stream-deck gives it two, and filling and writing // each by its index put them on the left and right halves, the // right way up. .ElgatoStreamDeckStudio => .{ .width = 2 * 1424, .height = 280, .image_format = .JPEG, .rotation = null, .flip_left_right = false, .flip_top_bottom = false, .screens = 2, }, .ElgatoStreamDeckMini, .ElgatoStreamDeckMiniDiscord, .ElgatoStreamDeckMiniMK2, .ElgatoStreamDeckModule6, .ElgatoStreamDeckOriginal, .ElgatoStreamDeckPedal, => null, }; } /// A black surface the size of this device's panel, ready to be drawn /// on and handed to `setImage`. Null if the device has no writable /// panel. The caller owns the result. pub fn blankImage(self: *const Panel, alloc: std.mem.Allocator) !?z2d.Surface { const feature = self.getFeature() orelse return null; return try image.blankImage(alloc, feature.width, feature.height); } /// Encode a surface the way the panel wants it: rotated and flipped as /// the glass is mounted, then as the bytes that go on the wire. /// /// This is the half of `setImage` that does not touch the device, split /// out so that it can be tested without one. The caller owns the /// result. pub fn encodeImage( alloc: std.mem.Allocator, surface: z2d.Surface, feature: PanelFeature, ) ![]const u8 { 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 turned.deinit(alloc); const data = switch (feature.image_format) { .JPEG => try jpeg.encode(alloc, turned, .{}), // Nothing takes a BMP panel image; the models that want BMP at // all have no command to send one. .BMP => return error.ImageFormatError, }; errdefer alloc.free(data); if (!std.mem.eql(u8, data[0..2], &.{ 0xff, 0xd8 })) return error.ImageFormatError; return data; } /// Paint the whole panel behind the keys. /// /// `surface` has to be exactly the size `getFeature` reports; anything /// else is `error.WrongImageSize`, because nothing here scales. Does /// nothing on a device with no writable panel. /// /// **Do not call `StreamDeck.reset` before this.** It leaves an Original /// V2 able to accept only a short panel image -- two packets arrive and /// display, six come out as a flat wash of the image's average colour -- /// and this function cannot tell, because every write it makes is /// accepted. See `reset` and the README. pub fn setImage(self: *const Panel, io: std.Io, alloc: std.mem.Allocator, surface: z2d.Surface) !void { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("panel", self)); const feature = self.getFeature() orelse return; if (surface.getWidth() != feature.width or surface.getHeight() != feature.height) { return error.WrongImageSize; } if (feature.screens == 1) return writeScreen(sd, io, alloc, surface, feature, 0); // A panel of several screens is written a screen at a time, each // one its own strip of the surface. const strip_width = feature.width / feature.screens; for (0..feature.screens) |screen| { var strip = try image.blankImage(alloc, strip_width, feature.height); defer strip.deinit(alloc); const left = screen * strip_width; for (0..feature.height) |y| { for (0..strip_width) |x| { const px = surface.getPixel(@intCast(left + x), @intCast(y)).?; strip.putPixel(@intCast(x), @intCast(y), px); } } try writeScreen(sd, io, alloc, strip, feature, @intCast(screen)); } } /// Encode one screen's image and send it, a kilobyte page at a time. fn writeScreen( sd: *const StreamDeck, io: std.Io, alloc: std.mem.Allocator, surface: z2d.Surface, feature: PanelFeature, screen: u8, ) !void { const data = try encodeImage(alloc, surface, feature); defer alloc.free(data); const max = StreamDeck.MAX_PACKET_SIZE - @sizeOf(ImageHeaderV5); var iter = std.mem.window(u8, data, max, max); var page_number: u16 = 0; while (iter.next()) |page| : (page_number += 1) { var packet = std.mem.zeroes([StreamDeck.MAX_PACKET_SIZE]u8); var writer = std.Io.Writer.fixed(&packet); try writer.writeStruct(ImageHeaderV5{ .screen = screen, .last = page.len < max, .length = @intCast(page.len), .page_number = page_number, }, .little); try writer.writeAll(page); _ = try sd.device.write(io, &packet); } } /// How many background images a model can hold, and whether it can be /// told to show one. /// /// A background is a whole-panel image kept **in the device**, so that /// switching to it costs one short feature report rather than /// re-sending the picture. Elgato documents the upload for the Classic /// and XL families and the show-by-index for the XL family alone -- /// so a Classic can be given a background and, as far as anything /// says, cannot then be told to display one. /// /// How many slots there are is documented nowhere, and **is not what /// `getUnitInfo`'s `lcd_gallery` reports**, however much it sounds like /// it. A Stream Deck Neo says four LCD images in its gallery and does /// not implement these commands at all: it was sent a background and /// asked to show it, accepted both without complaint, and displayed /// nothing. A Stream Deck Plus says zero and behaves the same way. /// /// **Nor has storing one ever been seen to do anything, on a model /// Elgato documents it for.** A Stream Deck Original V2 -- Classic /// family, where Update Background is documented -- took all /// thirty-two pages of a background without complaint and then: /// showed nothing for Show Background by Index, which is not a command /// on this family; showed the manufacturer's logo, not the stored /// image, for Show Logo; changed none of its 256 feature reports /// across the upload; and blanked to nothing rather than to the /// background when left to go idle. So the upload is either discarded /// or displayed by something nobody here has found. /// /// Elgato describes the feature as the background showing through /// wherever the foreground is transparent. Key images are JPEG, which /// has no alpha channel, so that would have to mean a colour treated /// as see-through -- and six candidates painted flat over a stored /// background (black, white, magenta, green, mid-grey, near-black) all /// stayed flat. The likeliest reading is that the compositing happens /// in Elgato's application, which sends an ordinary flattened key /// image, and never on the wire at all. /// /// What follows therefore describes what Elgato documents rather than /// what has been demonstrated, and the field order in `ImageHeaderV6` /// is unvalidated with it -- a wrong order and a discarded write look /// exactly alike from the host. Treat `setBackground` as untested. pub const Backgrounds = struct { /// Whether `setBackground` has a command to send on this model. can_store: bool, /// Whether `showBackground` does. The Classic family can be given /// a background and, as far as anything documents, cannot then be /// told to display one -- which is odd, and is what the /// documentation says. can_show: bool, }; /// What this model can do with stored backgrounds. pub fn backgrounds(self: *const Panel) Backgrounds { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("panel", self)); return switch (sd.type) { // Elgato documents Update Background for this family and no // Show Background by Index. .ElgatoStreamDeckOriginalV2, .ElgatoStreamDeckMK2, .ElgatoStreamDeckMK2Scissor, .ElgatoStreamDeckModule15, => .{ .can_store = true, .can_show = false }, // The XL family documents both. .ElgatoStreamDeckXL, .ElgatoStreamDeckXLV2, .ElgatoStreamDeckModule32, => .{ .can_store = true, .can_show = true }, // Everything else, including the Neo and the Plus, which were // both tried anyway and displayed nothing. else => .{ .can_store = false, .can_show = false }, }; } /// Store a whole-panel image in one of the device's background slots. /// /// `surface` has to be exactly the size `getFeature` reports, as for /// `setImage`. `index` names the slot, and nothing here checks it /// against a count, because no source gives one and the device's own /// gallery figure turned out not to be it. /// /// Returns `error.Unsupported` on a model with no such command. pub fn setBackground( self: *const Panel, io: std.Io, alloc: std.mem.Allocator, index: u8, surface: z2d.Surface, ) !void { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("panel", self)); if (!self.backgrounds().can_store) return error.Unsupported; const feature = self.getFeature() orelse return error.Unsupported; if (surface.getWidth() != feature.width or surface.getHeight() != feature.height) { return error.WrongImageSize; } const data = try encodeImage(alloc, surface, feature); defer alloc.free(data); const max = StreamDeck.MAX_PACKET_SIZE - @sizeOf(ImageHeaderV6); var iter = std.mem.window(u8, data, max, max); var page_number: u16 = 0; while (iter.next()) |page| : (page_number += 1) { var packet = std.mem.zeroes([StreamDeck.MAX_PACKET_SIZE]u8); var writer = std.Io.Writer.fixed(&packet); // Mind the field order here; see `ImageHeaderV6`. try writer.writeStruct(ImageHeaderV6{ .index = index, .last = page.len < max, .page_number = page_number, .length = @intCast(page.len), }, .little); try writer.writeAll(page); _ = try sd.device.write(io, &packet); } } /// Show the background in the given slot. /// /// This is the cheap half: one feature report, no image data, so /// swapping between stored backgrounds costs almost nothing. Returns /// `error.Unsupported` on a model that cannot be told to do it. pub fn showBackground(self: *const Panel, io: std.Io, index: u8) !void { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("panel", self)); if (!self.backgrounds().can_show) return error.Unsupported; const packet: extern struct { byte0: u8 = 0x03, byte1: u8 = 0x13, index: u8, } = .{ .index = index }; std.debug.assert(@sizeOf(@TypeOf(packet)) == 3); _ = try sd.device.sendFeatureReport(io, std.mem.asBytes(&packet)); } test backgrounds { // The two families Elgato documents this for, and the asymmetry // between them. var xl = testDeck(.ElgatoStreamDeckXL); try std.testing.expectEqual(Backgrounds{ .can_store = true, .can_show = true }, xl.panel.backgrounds()); var mk2 = testDeck(.ElgatoStreamDeckMK2); try std.testing.expectEqual(Backgrounds{ .can_store = true, .can_show = false }, mk2.panel.backgrounds()); // And a model with no such command at all. var plus = testDeck(.ElgatoStreamDeckPlus); try std.testing.expectEqual(Backgrounds{ .can_store = false, .can_show = false }, plus.panel.backgrounds()); } test "a model that stores backgrounds has a panel to store them of" { // A background is a whole-panel image, so claiming one without a // panel size would be a table contradicting itself. inline for (comptime std.enums.values(StreamDeck.Type)) |t| { var sd = testDeck(t); if (sd.panel.backgrounds().can_store) { try std.testing.expect(sd.panel.getFeature() != null); } // And nothing can be told to show what it cannot store. if (sd.panel.backgrounds().can_show) { try std.testing.expect(sd.panel.backgrounds().can_store); } } } test "storing a background is refused where there is no command for it" { const alloc = std.testing.allocator; const io = std.testing.io; var plus = testDeck(.ElgatoStreamDeckPlus); var surface = (try plus.panel.blankImage(alloc)).?; defer surface.deinit(alloc); try std.testing.expectError(error.Unsupported, plus.panel.setBackground(io, alloc, 0, surface)); try std.testing.expectError(error.Unsupported, plus.panel.showBackground(io, 0)); // The Classic family can store one and cannot be told to show it. var mk2 = testDeck(.ElgatoStreamDeckMK2); try std.testing.expectError(error.Unsupported, mk2.panel.showBackground(io, 0)); } /// A `StreamDeck` of the given model with nothing behind it; see the /// note on `Keys.testDeck`. fn testDeck(t: StreamDeck.Type) StreamDeck { return .{ .type = t, .device = .none }; } test getFeature { // The families Elgato documents a panel size for, and one that has // none to document. var plus = testDeck(.ElgatoStreamDeckPlus); const p = plus.panel.getFeature().?; try std.testing.expectEqual(@as(u16, 800), p.width); try std.testing.expectEqual(@as(u16, 480), p.height); var xl = testDeck(.ElgatoStreamDeckXL); const x = xl.panel.getFeature().?; try std.testing.expectEqual(@as(u16, 1024), x.width); try std.testing.expectEqual(@as(u16, 600), x.height); // The Studio's is two screens, and the size is both of them. var studio = testDeck(.ElgatoStreamDeckStudio); const st = studio.panel.getFeature().?; try std.testing.expectEqual(@as(u16, 2848), st.width); try std.testing.expectEqual(@as(u16, 280), st.height); try std.testing.expectEqual(@as(u8, 2), st.screens); try std.testing.expectEqual(@as(u8, 1), p.screens); var pedal = testDeck(.ElgatoStreamDeckPedal); try std.testing.expectEqual(null, pedal.panel.getFeature()); var mini = testDeck(.ElgatoStreamDeckMini); try std.testing.expectEqual(null, mini.panel.getFeature()); } test "a panel is at least as large as the keys it carries" { // The keys are windows onto this glass, so a grid that could not // fit on the panel would be a table contradicting itself. // // Either way round counts. Elgato describes a panel in the // orientation its glass is mounted, and on the Plus XL that is a // quarter turn from the way the key grid is numbered -- so which of // the two dimensions is "across" depends on the model, and pinning // that per model would be asserting something no source states. inline for (comptime std.enums.values(StreamDeck.Type)) |t| { var sd = testDeck(t); if (sd.panel.getFeature()) |panel| { if (sd.keys.getImageFeature(0)) |key| { const across = @as(usize, sd.keys.cols()) * key.width; const down = @as(usize, sd.keys.rows()) * key.height; const w: usize = panel.width; const h: usize = panel.height; const fits = (across <= w and down <= h) or (across <= h and down <= w); try std.testing.expect(fits); } } } } test "a panel image is refused unless it is exactly the right size" { const alloc = std.testing.allocator; const io = std.testing.io; var sd = testDeck(.ElgatoStreamDeckPlus); var wrong = try image.blankImage(alloc, 100, 100); defer wrong.deinit(alloc); try std.testing.expectError(error.WrongImageSize, sd.panel.setImage(io, alloc, wrong)); } test blankImage { const alloc = std.testing.allocator; var sd = testDeck(.ElgatoStreamDeckNeo); var surface = (try sd.panel.blankImage(alloc)).?; defer surface.deinit(alloc); try std.testing.expectEqual(480, surface.getWidth()); try std.testing.expectEqual(320, surface.getHeight()); var pedal = testDeck(.ElgatoStreamDeckPedal); try std.testing.expectEqual(null, try pedal.panel.blankImage(alloc)); } test { std.testing.refAllDecls(@This()); }