// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT const Events = @This(); const std = @import("std"); const Keys = @import("Keys.zig"); const Touchscreen = @import("Touchscreen.zig"); const Encoders = @import("Encoders.zig"); const StreamDeck = @import("StreamDeck.zig"); pub const init: Events = .{}; pub const ReportType = enum(u8) { input = 1, }; pub const ControlType = enum(u8) { keys = 0, touchscreen = 2, encoders = 3, }; pub const Event = union(ControlType) { keys: *Keys.Event, touchscreen: Touchscreen.Event, encoders: *Encoders.Event, pub fn deinit(self: *const Event, alloc: std.mem.Allocator) void { switch (self.*) { inline else => |v| v.deinit(alloc), } } }; pub const HeaderFormat = enum { v1, v2, pub fn readSize(self: HeaderFormat) usize { return switch (self) { .v1 => 1, .v2 => 4, }; } }; /// Which header an input report from this device carries. It follows /// the generation of the model exactly, so that is what decides it: /// the older models prefix a report with a single byte and everything /// since carries four. /// /// Note that this puts the Pedal on the newer header. It reads and /// writes the newer feature reports too, and /// node-elgato-stream-deck's model table gives it the same key data /// offset as the rest of them. pub fn headerFormat(self: *const Events) HeaderFormat { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("events", self)); return switch (sd.type.generation()) { .gen1 => .v1, .gen2 => .v2, }; } pub fn headerSize(self: *const Events) usize { return self.headerFormat().readSize(); } pub fn bodySize(self: *const Events) usize { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("events", self)); return @max( sd.keys.readSize(), sd.encoders.readSize(), sd.touchscreen.readSize(), ); } /// How much to read for one input report: the header and the largest /// body any of the controls can produce, or the model's own fixed /// report length when that is larger. /// /// The two have to be reconciled rather than just added, because a /// device hands back a whole report or nothing: asking for less than it /// sends truncates, and the Plus XL sends 64 bytes where its controls /// only account for 40. pub fn readSize(self: *const Events) usize { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("events", self)); const computed = self.headerFormat().readSize() + self.bodySize(); return @max(computed, sd.type.inputReportSize() orelse 0); } /// Wait for the device to say something and decode it. /// /// A failure to read is reported rather than swallowed. It used to come /// back as `null`, which a caller could only treat as "nothing /// happened" -- and the obvious loop around this function then spins /// forever on a device that has gone away. Over USB that is a device /// somebody unplugged; over TCP it is a connection that will never /// recover and a caller that never learns the deck has gone. The two /// cases a caller genuinely has to tell apart are "the device said /// something I could not parse", which is a `ReportError` and is worth /// carrying on through, and "the device is no longer there", which is /// not. pub fn read(self: *const Events, io: std.Io, alloc: std.mem.Allocator) !Event { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("events", self)); const buf = try alloc.alloc(u8, self.readSize()); defer alloc.free(buf); const data = try sd.device.read(io, buf); const now: std.Io.Timestamp = .now(io, .real); return try self.decode(alloc, now, data); } /// Wait for the device to say something, giving up after `timeout`. /// /// Null means the time ran out with nothing to report, which is not a /// failure -- it is what a caller wanting to do something else between /// reports is asking for. The Galleon is why this exists: it leaves /// Stream Deck mode about two seconds after the last write, so a /// program driving one has to get a `StreamDeck.keepAlive` in edgeways, /// and it cannot do that while parked in a blocking read. A timeout /// comfortably under two seconds turns the loop into "listen a while, /// say hello, listen again". /// /// Only the HID transport can do this; the TCP one answers /// `error.Unsupported` rather than quietly waiting forever. That is no /// loss, since the models reached over TCP are not the ones that need /// holding open. pub fn readTimeout( self: *const Events, io: std.Io, alloc: std.mem.Allocator, timeout: std.Io.Timeout, ) !?Event { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("events", self)); const buf = try alloc.alloc(u8, self.readSize()); defer alloc.free(buf); const data = try sd.device.readTimeout(io, buf, timeout) orelse return null; const now: std.Io.Timestamp = .now(io, .real); return try self.decode(alloc, now, data); } /// Decode one input report. This is `read` with the device taken out of /// it: everything that turns bytes into an `Event` is here, and `read` /// is the part that gets the bytes and stamps the time. /// /// Splitting the two is what lets this be tested and fuzzed, which /// matters because `data` is whatever the hardware said and nothing /// else has checked it. pub fn decode(self: *const Events, alloc: std.mem.Allocator, now: std.Io.Timestamp, data: []const u8) !Event { const start = self.headerSize(); // Everything below indexes into the header without looking first, // and a short read is a thing a device can hand back, so this is // the one place to check it. if (data.len < start) return error.ShortReport; // The body is whatever follows the header, up to the largest any // of the controls can produce. Each control then gets only as much // of it as that control actually occupies: the body is sized for // the *largest* of them, so handing all of it to a smaller one // reports state the device never sent. A Stream Deck Plus makes a // ten byte body -- its touchscreen is the largest -- and giving // that to the key parser describes ten keys on an eight key device. const end = @min(data.len, start + self.bodySize()); const body = data[start..end]; const sd: *const StreamDeck = @alignCast(@fieldParentPtr("events", self)); switch (self.headerFormat()) { // The older models say nothing about what the report is: one // byte of header, and the rest is always keys. .v1 => return .{ .keys = try Keys.Event.init(alloc, now, forControl(body, sd.keys.readSize())) }, .v2 => { const report_type = std.enums.fromInt(ReportType, data[0]) orelse return error.UnknownReportType; switch (report_type) { .input => { const control_type = std.enums.fromInt(ControlType, data[1]) orelse return error.UnknownControlType; // `data[2..4]` is the length the device claims for // the body. It is not trusted: `end` above is what // bounds the slice, so a report claiming more than // it carries cannot reach past what was read. return switch (control_type) { .keys => .{ .keys = try Keys.Event.init(alloc, now, forControl(body, sd.keys.readSize())), }, .encoders => .{ .encoders = try Encoders.Event.init(alloc, now, forControl(body, sd.encoders.readSize())), }, .touchscreen => .{ .touchscreen = try Touchscreen.Event.init(now, forControl(body, sd.touchscreen.readSize())), }, }; }, } }, } } /// As much of `body` as one control occupies, or all of it if the /// device sent less than that control claims. Short is the parsers' /// business to refuse; long is this function's to prevent. fn forControl(body: []const u8, size: usize) []const u8 { return body[0..@min(body.len, size)]; } /// 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 headerFormat { // The three oldest models and the Pedal prefix an input report // with a single byte; everything since carries a four byte header. var original = testDeck(.ElgatoStreamDeckOriginal); try std.testing.expectEqual(HeaderFormat.v1, original.events.headerFormat()); try std.testing.expectEqual(1, original.events.headerSize()); var mk2 = testDeck(.ElgatoStreamDeckMK2); try std.testing.expectEqual(HeaderFormat.v2, mk2.events.headerFormat()); try std.testing.expectEqual(4, mk2.events.headerSize()); } test bodySize { // The body has to hold the largest of the three controls, because // one buffer is read into whichever control the report turns out // to describe. inline for (std.meta.fields(StreamDeck.Type)) |f| { var sd = testDeck(@enumFromInt(f.value)); const body = sd.events.bodySize(); try std.testing.expectEqual(@max( sd.keys.readSize(), @max(sd.encoders.readSize(), sd.touchscreen.readSize()), ), body); try std.testing.expect(body >= sd.keys.readSize()); try std.testing.expect(body >= sd.encoders.readSize()); try std.testing.expect(body >= sd.touchscreen.readSize()); try std.testing.expect(sd.events.readSize() >= sd.events.headerSize() + body); // Where the model declares a report length, that is what is // read; otherwise the controls decide. if (f.value == @intFromEnum(StreamDeck.Type.ElgatoStreamDeckPlusXL)) { try std.testing.expectEqual(64, sd.events.readSize()); } else { try std.testing.expectEqual(sd.events.headerSize() + body, sd.events.readSize()); } // The whole report has to fit in a packet. try std.testing.expect(sd.events.readSize() <= StreamDeck.MAX_PACKET_SIZE); } } test "the Plus sizes its body for the touchscreen rather than its keys" { // The Plus has eight keys and four encoders but a ten byte // touchscreen report, so the touchscreen is what decides how big // the body has to be. Getting this wrong is invisible until a // touchscreen event arrives and is quietly refused for being // shorter than `Touchscreen.Event.init` will accept. var plus = testDeck(.ElgatoStreamDeckPlus); try std.testing.expectEqual(8, plus.keys.readSize()); try std.testing.expectEqual(5, plus.encoders.readSize()); try std.testing.expectEqual(Touchscreen.report_size, plus.touchscreen.readSize()); try std.testing.expectEqual(Touchscreen.report_size, plus.events.bodySize()); } test "each control is given only the bytes it occupies" { // The body is sized for the largest control, so a smaller one must // not be handed all of it. On a Plus the touchscreen's ten bytes // set the size, and the eight keys and four dials are both // narrower -- which is how a turn of one dial came back describing // nine of them. const alloc = std.testing.allocator; var sd = testDeck(.ElgatoStreamDeckPlus); try std.testing.expectEqual(10, sd.events.bodySize()); { const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &.{ 0x01, 0x00, 0x08, 0x00, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, }); defer event.deinit(alloc); try std.testing.expectEqual(8, event.keys.event.push.states.len); try std.testing.expectEqual(Keys.State.down, event.keys.event.push.states[3]); } { const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &.{ 0x01, 0x03, 0x05, 0x00, 1, 0, 0, 0xfe, 0, 0, 0, 0, 0, 0, }); defer event.deinit(alloc); try std.testing.expectEqual(4, event.encoders.event.turn.states.len); try std.testing.expectEqual(-2, event.encoders.event.turn.states[2]); } } test "a Galleon's own reports, captured from the hardware" { // Taken from `probe --events` pointed at a Corsair Galleon K100 and // trimmed of the trailing zeros of its 512 byte reports. Nothing // about this model's input had ever been seen when its tables were // written, and they turn out to be ordinary gen2 reports: the // header's length field says `0x0c` for the keys and `0x03` for the // encoders, which is exactly twelve keys and an event type plus two // encoders, and exactly what the control tables here claim. // // Note what had to be true before any of this could be captured. // The device leaves Stream Deck mode about two seconds after the // last write and its reports then stop being Stream Deck reports at // all, so these arrived only because `keepAlive` was being sent // around every read. See `StreamDeck.keepAlive`. const alloc = std.testing.allocator; var sd = testDeck(.CorsairGalleonK100); try std.testing.expectEqual(12, sd.events.bodySize()); { // 01 00 0c 00 | 01 -- key 0 pressed. const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &.{ 0x01, 0x00, 0x0c, 0x00, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }); defer event.deinit(alloc); try std.testing.expectEqual(12, event.keys.event.push.states.len); try std.testing.expectEqual(Keys.State.down, event.keys.event.push.states[0]); } { // 01 00 0c 00 | 00 00 00 00 00 01 -- key 5, the furthest along // that was captured, and proof the body really is twelve wide. const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &.{ 0x01, 0x00, 0x0c, 0x00, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, }); defer event.deinit(alloc); try std.testing.expectEqual(Keys.State.down, event.keys.event.push.states[5]); try std.testing.expectEqual(Keys.State.up, event.keys.event.push.states[0]); } { // 01 03 03 00 | 01 02 -- the left encoder turned two detents // clockwise, the right one not at all. const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &.{ 0x01, 0x03, 0x03, 0x00, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }); defer event.deinit(alloc); try std.testing.expectEqual(2, event.encoders.event.turn.states.len); try std.testing.expectEqual(2, event.encoders.event.turn.states[0]); try std.testing.expectEqual(0, event.encoders.event.turn.states[1]); } { // 01 03 03 00 | 01 00 fd -- the right encoder three detents // anticlockwise. Both directions and both encoders were seen. const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &.{ 0x01, 0x03, 0x03, 0x00, 1, 0, 0xfd, 0, 0, 0, 0, 0, 0, 0, 0, 0, }); defer event.deinit(alloc); try std.testing.expectEqual(0, event.encoders.event.turn.states[0]); try std.testing.expectEqual(-3, event.encoders.event.turn.states[1]); } { // 01 03 03 00 | 00 00 01 -- the right encoder pressed in. They // are pressable, which nothing had said. const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &.{ 0x01, 0x03, 0x03, 0x00, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, }); defer event.deinit(alloc); try std.testing.expectEqual(2, event.encoders.event.push.states.len); try std.testing.expectEqual(Encoders.State.up, event.encoders.event.push.states[0]); try std.testing.expectEqual(Encoders.State.down, event.encoders.event.push.states[1]); } { // 01 03 03 00 -- and released, which is a push event with // nothing down rather than a separate kind of report. const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &.{ 0x01, 0x03, 0x03, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }); defer event.deinit(alloc); try std.testing.expectEqual(Encoders.State.up, event.encoders.event.push.states[0]); try std.testing.expectEqual(Encoders.State.up, event.encoders.event.push.states[1]); } } test "a Plus XL's own reports, captured from the hardware" { // From `probe --events` pointed at a Stream Deck + XL, padded out // to the 64 bytes this model always sends. It has more encoders // than anything else here, which is the case worth having: the // Plus's four are what turned up the bug where a turn of one dial // reported nine of them, because every parser was handed the body // sized for the largest control. const alloc = std.testing.allocator; var sd = testDeck(.ElgatoStreamDeckPlusXL); try std.testing.expectEqual(36, sd.events.bodySize()); try std.testing.expectEqual(64, sd.events.readSize()); // The device declares its own body length in the header, and for // the encoders it says seven: an event type and one byte per // encoder, exactly what `Encoders.readSize` works out. { var raw = [_]u8{0} ** 64; @memcpy(raw[0..11], &[_]u8{ 0x01, 0x03, 0x07, 0x00, 1, 0, 0, 2, 0, 0, 1 }); const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); // Six, not nine, and not thirty-six. try std.testing.expectEqual(6, event.encoders.event.turn.states.len); try std.testing.expectEqual(2, event.encoders.event.turn.states[2]); try std.testing.expectEqual(1, event.encoders.event.turn.states[5]); try std.testing.expectEqual(0, event.encoders.event.turn.states[0]); } { // The sixth dial pressed in, which is the far end of the row. var raw = [_]u8{0} ** 64; @memcpy(raw[0..11], &[_]u8{ 0x01, 0x03, 0x07, 0x00, 0, 0, 0, 0, 0, 0, 1 }); const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); try std.testing.expectEqual(6, event.encoders.event.push.states.len); try std.testing.expectEqual(Encoders.State.down, event.encoders.event.push.states[5]); try std.testing.expectEqual(Encoders.State.up, event.encoders.event.push.states[4]); } { // A drag across the touchscreen. The device declares fourteen // bytes here where `Touchscreen.report_size` reserves ten -- // the four beyond the second position are zero in every report // seen, and ten is what the positions need, so the extra is // room this library does not use rather than something it is // missing. var raw = [_]u8{0} ** 64; @memcpy(raw[0..13], &[_]u8{ 0x01, 0x02, 0x0e, 0x00, 3, 0, 0xcb, 0x03, 0x38, 0x00, 0x8e, 0x03, 0x32, }); const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); // **In the size the screen is looked at, not the size the // device reports it as.** This model's glass is mounted a // quarter turn round, its `getUnitInfo` answers 100x1200, and // an image handed to `setImage` is rotated on the way out -- // but a touch arrives already in the 1200x100 the user sees, // so coordinates want no correction at all. Every drag // captured had x within 0..1199 and y within 0..99. try std.testing.expectEqual(971, event.touchscreen.event.drag.in.x); try std.testing.expectEqual(56, event.touchscreen.event.drag.in.y); try std.testing.expectEqual(910, event.touchscreen.event.drag.out.x); try std.testing.expectEqual(50, event.touchscreen.event.drag.out.y); } } test "a Studio's own reports, captured from the hardware" { // From `probe --events` pointed at a Stream Deck Studio over the // network. The device sends every report as a whole 512 byte legacy // frame, and these are the leading bytes of some of them. const alloc = std.testing.allocator; var sd = testDeck(.ElgatoStreamDeckStudio); { // Key 15 down: the last key of the top row, sixteen across. var raw = [_]u8{0} ** 512; @memcpy(raw[0..4], &[_]u8{ 0x01, 0x00, 0x20, 0x00 }); raw[4 + 15] = 1; const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); try std.testing.expectEqual(32, event.keys.event.push.states.len); try std.testing.expectEqual(Keys.State.down, event.keys.event.push.states[15]); try std.testing.expectEqual(Keys.State.up, event.keys.event.push.states[16]); } { // Key 31 down: the bottom right, the last byte the report holds. var raw = [_]u8{0} ** 512; @memcpy(raw[0..4], &[_]u8{ 0x01, 0x00, 0x20, 0x00 }); raw[4 + 31] = 1; const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); try std.testing.expectEqual(Keys.State.down, event.keys.event.push.states[31]); } { // The left knob turned back a click and the right one left // alone. The device declares a body of three: an event type // and one byte per encoder. var raw = [_]u8{0} ** 512; @memcpy(raw[0..7], &[_]u8{ 0x01, 0x03, 0x03, 0x00, 0x01, 0xff, 0x00 }); const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); try std.testing.expectEqual(2, event.encoders.event.turn.states.len); try std.testing.expectEqual(-1, event.encoders.event.turn.states[0]); try std.testing.expectEqual(0, event.encoders.event.turn.states[1]); } { // The left knob pressed in, which is encoder 0: event type 0, // a push, rather than 1, a turn. var raw = [_]u8{0} ** 512; @memcpy(raw[0..7], &[_]u8{ 0x01, 0x03, 0x03, 0x00, 0x00, 0x01, 0x00 }); const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); try std.testing.expectEqual(2, event.encoders.event.push.states.len); try std.testing.expectEqual(Encoders.State.down, event.encoders.event.push.states[0]); try std.testing.expectEqual(Encoders.State.up, event.encoders.event.push.states[1]); } { // The right knob pressed in, which is encoder 1. var raw = [_]u8{0} ** 512; @memcpy(raw[0..7], &[_]u8{ 0x01, 0x03, 0x03, 0x00, 0x00, 0x00, 0x01 }); const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); try std.testing.expectEqual(Encoders.State.up, event.encoders.event.push.states[0]); try std.testing.expectEqual(Encoders.State.down, event.encoders.event.push.states[1]); } { // The right knob turned forward a click. var raw = [_]u8{0} ** 512; @memcpy(raw[0..7], &[_]u8{ 0x01, 0x03, 0x03, 0x00, 0x01, 0x00, 0x01 }); const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &raw); defer event.deinit(alloc); try std.testing.expectEqual(0, event.encoders.event.turn.states[0]); try std.testing.expectEqual(1, event.encoders.event.turn.states[1]); } } test "a report too short to hold its header is refused" { // `read` cannot be called without a device, but what it guards // against is worth stating: the v2 models carry a four byte header // and every one of the models below indexes into it. inline for (std.meta.fields(StreamDeck.Type)) |f| { var sd = testDeck(@enumFromInt(f.value)); try std.testing.expect(sd.events.readSize() > sd.events.headerSize()); } } test "decoding a report cleans up after a failed allocation" { // `decode` allocates through whichever parser the control type // names, so each of the three is tried. inline for (.{ [_]u8{ 0x01, 0x00, 0x08, 0x00, 0, 1, 0, 0, 0, 0, 0, 0 }, [_]u8{ 0x01, 0x03, 0x05, 0x00, 1, 1, 0xff, 0, 0, 0, 0, 0 }, [_]u8{ 0x01, 0x02, 0x0a, 0x00, 1, 0, 0x20, 0x01, 0x30, 0x00, 0, 0, 0, 0 }, }) |report| { try std.testing.checkAllAllocationFailures(std.testing.allocator, struct { fn run(alloc: std.mem.Allocator) !void { var sd: StreamDeck = .{ .type = .ElgatoStreamDeckPlus, .device = .none }; const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &report); defer event.deinit(alloc); } }.run, .{}); } } test { // `read` needs a device to read from, so it cannot be run here. std.testing.refAllDecls(@This()); std.testing.refAllDecls(Event); }