From 006a18d80da1d042dc372b79fc52d8daa1c5cd9b Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Sun, 20 Sep 2026 00:41:44 -0500 Subject: [PATCH] Reach the networked models, and read Elgato's own documentation Two threads, and they belong together because the second corrected what the first was built on. A Stream Deck Studio is not a USB device. It takes Ethernet and PoE and is driven over TCP, and so is the Network Dock, so nothing here could talk to either -- the Studio sat in the tables as a product id nobody could reach. `StreamDeck.device` is now a tagged-union `Transport` over a HID device or a TCP connection, and everything above it is untouched: the same `keys`, `encoders` and `events`, the same `setImage`. That works because the tunnelled payloads are byte-identical HID reports and key images are not re-chunked, which the loopback test in `Tcp.zig` pins by taking the pages apart again and reassembling the image out of them. `framing.zig` is the protocol with the socket removed, fuzzed like the other parsers, because these bytes come off a network rather than out of a USB device. It is a union rather than a vtable so that the `.none` transport the tests use answers rather than jumps. And Elgato publishes HID documentation, which this README had said for its whole life that it did not. The "Rests on" column gains an *Elgato's docs* tier above two references and a *one reference* tier below it, and the References Cited section stops claiming there is no first-party source. It settled two things and found a bug. Elgato says the Mini rotates ninety degrees clockwise and the Plus XL ninety counterclockwise -- opposite directions, where this library turned both the same way. The Plus XL was wrong, which is the question the README had flagged as the two references disagreeing about a flip. And the Mini was wrong too, by a half turn: **every key image on a Mini has been coming out upside down.** That was settled by putting the same figure on four keys under the four corrections a table can be wrong by and looking at which read correctly, with a Neo and a Plus as controls; the Mini family moves from two references to hardware. `getUnitInfo` is the useful discovery. Feature report `0x08` makes a device report its own keypad matrix and its own key and panel pixel sizes, so a table can be checked against hardware instead of against another implementation. A Neo and a Plus answered with exactly what Elgato documents. Pointing it at a Studio would end the argument about that model's key resolution in one call. Note that `rows` and `cols` describe the matrix and not the key count -- a Neo says four by three, twelve positions, where it has eight keys and two touch buttons. `Panel` is the screen behind the keys. The keys are not separate displays; there is one sheet of glass and the keys are windows onto it, which a checkerboard painted across a Neo's panel shows by running continuously from one key to the next and on into the info strip. That is also how Elgato's software's "background" works, and it is the application's feature rather than the device's -- paint the panel, then draw over only the keys that want a foreground, and a key left alone goes on showing the panel. "The background shows where the foreground is transparent" means nothing more than not writing that key. Also from the documentation: `fillKey` and `fillScreen`, the sleep timeout, and the other two firmware versions every device carries besides the one it calls its own -- plus the two more a Studio has for its encoder board. The sleep timeout does not apply before the device answers the next question, so reading it straight back reports the value it held a moment ago; ten milliseconds is enough and nothing here waits on a caller's behalf. The firmware reports carry a checksum this does not verify, and that is a conclusion rather than an omission. Forty-one algorithms over twenty-three derivations of the report and all twenty-four byte orders, required to agree on six observations from two devices: nothing matched. The reason is in the older protocol, where the same four bytes read as a byte count -- 322 KiB of bootloader and two application images of about 3.28 MiB -- so the field describes the firmware image rather than the eight characters beside it, and the newer protocol's checksum is of an image this library never sees. `setBackground` and `showBackground` are implemented from the documentation and marked untested, because nothing has been able to make a stored background appear. An Original V2 took all thirty-two pages, and then Show Background by Index did nothing, Show Logo showed the manufacturer's logo, none of its 256 feature reports changed across the upload, it blanked to darkness rather than to the background when left idle, and six candidate transparency colours all stayed flat. The field order is unvalidated with it: a swapped header and a discarded write look alike from the host. The Corsair Galleon K100 is the first device here that is not Elgato's. Corsair owns Elgato and Elgato's own SDK counts it among the Stream Decks, but it reports Corsair's vendor id, so `Type` can no longer assume one vendor. It rests on a single implementation, has never been run, and is the only model that stops listening if left alone -- it wants `keepAlive` about twice a second, which this library will not do for anyone. `zig-hidapi` moves to c7805bb, which replaced the minor-number scan with a portable enumeration, made `Device` something opened in place and used by pointer, and dropped the three node-name calls the example printed. So `Transport` holds the device by pointer, `StreamDeck.open` takes what an enumeration reported, `StreamDeckIterator` becomes `Enumerator`, and the example prints Elgato's own product strings from the `DeviceInfo` instead. Enumerating no longer needs permission where opening does, so an unprivileged user now gets `error.AccessDenied` rather than an empty list. The README's reason for being Linux-only changes with it: hidapi has four backends now, and the constraint is `z2dimg`. One breaking change worth calling out. `Events.read` returned `null` for a transport failure, which a caller could only read as "nothing happened" -- and the obvious loop around it then spins forever on a deck that has gone away. Over USB that is a device somebody unplugged; over TCP it is a socket that will never recover. It returns the error now. `tools/probe.zig` is how most of the above was established: it asks every attached device what it says about itself, prints the tables beside the answers, and carries the experiments -- the orientation corrections, the report scan, the sleep round trip, the background attempts. Worth keeping, because a Stream Deck accepts writes it does not implement. It answers all 256 feature report ids and takes output reports for commands it has never heard of, without error either way, so nothing about a write being accepted means it did anything. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01WUvf9zwMsPMwUDkUFViFbu --- README.md | 668 +++++++++++++++++-- build.zig | 27 +- build.zig.zon | 4 +- src/Encoders.zig | 3 +- src/Events.zig | 23 +- src/Keys.zig | 6 +- src/Panel.zig | 493 ++++++++++++++ src/StreamDeck.zig | 786 ++++++++++++++++++++-- src/Tcp.zig | 680 +++++++++++++++++++ src/Touchscreen.zig | 19 +- src/Transport.zig | 199 ++++++ src/devices.zig | 2 + src/devices/CorsairGalleonK100.zig | 75 +++ src/devices/ElgatoStreamDeckMini.zig | 21 +- src/devices/ElgatoStreamDeckMiniMK2.zig | 4 +- src/devices/ElgatoStreamDeckPlusXL.zig | 18 +- src/framing.zig | 594 +++++++++++++++++ src/image.zig | 93 +++ src/main.zig | 115 +++- src/root.zig | 134 +++- tests/fuzz.zig | 168 ++++- tools/probe.zig | 850 ++++++++++++++++++++++++ 22 files changed, 4816 insertions(+), 166 deletions(-) create mode 100644 src/Panel.zig create mode 100644 src/Tcp.zig create mode 100644 src/Transport.zig create mode 100644 src/devices/CorsairGalleonK100.zig create mode 100644 src/framing.zig create mode 100644 tools/probe.zig diff --git a/README.md b/README.md index 9b0682c..ee75c6f 100644 --- a/README.md +++ b/README.md @@ -6,14 +6,26 @@ SPDX-License-Identifier: MIT # zig-streamdeck A Zig library for driving [Elgato Stream Deck](https://www.elgato.com/stream-deck) -devices over USB HID: enumerating the decks attached to a machine, setting the -image on each key, changing the brightness, and reading the events the device -sends when a key is pressed, an encoder is turned, or the touchscreen is -touched. +devices: enumerating the decks attached to a machine, setting the image on each +key, changing the brightness, and reading the events the device sends when a +key is pressed, an encoder is turned, or the touchscreen is touched. + +What this library knows about the hardware comes from Elgato's own +[HID documentation](https://docs.elgato.com/streamdeck/hid/intro) where that +covers a model, from two independent reverse-engineered implementations where +it does not, and from running real devices wherever one was to hand. Each row +of the table below says which. + +Most models plug into USB and are driven over HID. The Stream Deck Studio and +the Stream Deck Network Dock do not: they take Ethernet, and are driven over +TCP. Both are the same `StreamDeck` here — the network carries the very same +HID reports, so the key tables, the image paging and the event decoding are +written once and do not know which they are talking to. See +[Networked devices](#networked-devices). It talks to the hardware through [zig-hidapi](https://git.jcollie.dev/jeff/zig-hidapi), -which is pure Zig over the Linux `hidraw` interface, so there is no C `hidapi` -to link against. Every blocking operation takes a `std.Io` and is dispatched +which is pure Zig with backends for Linux, FreeBSD, Windows and macOS, so there +is no C `hidapi` to link against. Every blocking operation takes a `std.Io` and is dispatched through the caller's I/O implementation rather than blocking a thread outright. **This is a work in progress.** The tree builds and its tests pass, and the @@ -41,7 +53,11 @@ been shown to work without. - Zig 0.16 - Linux with the `hidraw` driver (`CONFIG_HIDRAW`), i.e. `/dev/hidraw*` present -Only Linux is supported, because `zig-hidapi` is Linux-only. +Only Linux is supported, and the reason is the image encoder rather than the +HID layer: `z2dimg` builds for Linux only at present. `zig-hidapi` has backends +for FreeBSD, Windows and macOS as well, and nothing in the network transport is +Linux-specific either, so the rest of this would follow whenever the encoder +does. ## Supported devices @@ -54,34 +70,43 @@ id pair it reports. | --- | --- | --- | --- | --- | --- | | Stream Deck Original | `0x0060` | 5 × 3 | 72×72 BMP | — | two references | | Stream Deck Original V2 | `0x006d` | 5 × 3 | 72×72 JPEG | — | **hardware** | -| Stream Deck Mini | `0x0063` | 3 × 2 | 80×80 BMP | — | two references | -| Stream Deck Mini (Discord) | `0x00b3` | 3 × 2 | 80×80 BMP | — | two references | -| Stream Deck Mini MK.2 | `0x0090` | 3 × 2 | 80×80 BMP | — | two references | +| Stream Deck Mini | `0x0063` | 3 × 2 | 80×80 BMP | — | **hardware** | +| Stream Deck Mini (Discord) | `0x00b3` | 3 × 2 | 80×80 BMP | — | **hardware** | +| Stream Deck Mini MK.2 | `0x0090` | 3 × 2 | 80×80 BMP | — | **hardware** | | Stream Deck MK.2 | `0x0080` | 5 × 3 | 72×72 JPEG | — | two references | | Stream Deck MK.2 (Scissor) | `0x00a5` | 5 × 3 | 72×72 JPEG | — | two references | | Stream Deck Neo | `0x009a` | 4 × 2, plus 2 touch keys | 96×96 JPEG | — | **hardware** | | Stream Deck XL | `0x006c` | 8 × 4 | 96×96 JPEG | — | two references | | Stream Deck XL V2 | `0x008f` | 8 × 4 | 96×96 JPEG | — | two references | | Stream Deck Plus | `0x0084` | 4 × 2 | 120×120 JPEG | 4 | **hardware** | -| Stream Deck Plus XL | `0x00c6` | 9 × 4 | 112×112 JPEG | 6 | two references | +| Stream Deck Plus XL | `0x00c6` | 9 × 4 | 112×112 JPEG | 6 | Elgato's docs | | Stream Deck Studio | `0x00aa` | 16 × 2 | 80×120 or 144×112 JPEG | 2 | **they disagree** | | Stream Deck Pedal | `0x0086` | 3 pedals, no displays | — | — | two references | | Stream Deck 6 Module | `0x00b8` | 3 × 2 | 80×80 BMP | — | three references | | Stream Deck 15 Module | `0x00b9` | 5 × 3 | 72×72 JPEG | — | three references | | Stream Deck 32 Module | `0x00ba` | 8 × 4 | 96×96 JPEG | — | three references | +| Corsair Galleon K100 | `0x2b18` | 3 × 4 | 160×160 JPEG | 2 | one reference | "Rests on" is what each row's numbers are actually good for. **Hardware** means -the model was run against a real device and did what this says; *two -references* means python-elgato-streamdeck and node-elgato-stream-deck agree -and nothing has run it; *three* adds the module tables in DDRBoxman/gadgetdeck's -protocol notes, which are attributed to Elgato's own module documentation. The +the model was run against a real device and did what this says; *Elgato's docs* +means its HID documentation states it and nothing has run it; *two references* +means python-elgato-streamdeck and node-elgato-stream-deck agree and nothing +has run it; *three* adds the module tables in DDRBoxman/gadgetdeck's protocol +notes; *one reference* means a single implementation says so and nothing else +mentions it at all, which is the weakest thing here. The distinction is not academic: the Plus was the first device here whose controls are not all the same width, and running it turned up a bug two references had happily agreed through — `Events.decode` gave every parser the body sized for the *largest* control, so a turn of one dial reported nine of them on a device with four. -The vendor id is `0x0fd9` throughout. `Touchscreen` describes the screens: the +The vendor id is `0x0fd9` throughout except for the Galleon, which is a Corsair +keyboard with a Stream Deck panel built into it and reports Corsair's `0x1b1c`. +Corsair owns Elgato and Elgato's own SDK counts it among the Stream Decks, so +it belongs here — but it is the one device whose numbers rest on a single +source, it has never been run, and it is the only model that stops listening if +it is left alone: it wants `keepAlive` about twice a second, which this library +will not do for you. `Touchscreen` describes the screens: the Plus and the Plus XL carry one that reports where it was touched, 800×100 and 1200×100 respectively, and the Neo carries a 248×58 info strip that only displays — its two touch keys report through the key control, as keys 8 and 9. @@ -102,22 +127,28 @@ your own, and the two named editions are ordinary devices with a product id of their own; each is electrically the model it is derived from, so they share its key table rather than repeating it. -Two things in the table are worth flagging as unverified, and Elgato's own -literature settles neither: it publishes no key display resolution for any -model, and its SDK documents only the sizes a plugin should supply its icons in -(72×72, and 144×144 for high DPI), which is about authoring art in the desktop -application rather than what goes over the wire. - -- The **Studio's key resolution** is not known. python-elgato-streamdeck says - 80×120 and node-elgato-stream-deck says 144×112, and no third implementation - has one to break the tie — the others that recognise the product id decline - to drive the device. The table names both rather than a number of its own. - `src/devices/ElgatoStreamDeckStudio.zig` has to pick something to compile and - still carries 96×96, which is a placeholder and is marked as one; it wants - checking against real hardware before it is worth trusting. -- The **Plus XL's** key images are rotated a quarter turn, which both - references agree on, but they disagree about whether a vertical flip goes - with it. +Elgato's HID documentation gives a key image size for six of these families, +and every one of them matches what was already in the table. What it does not +cover is the Studio, the Pedal, the Original and the Galleon. + +- The **Studio's key resolution** is still not known. + python-elgato-streamdeck says 80×120 and node-elgato-stream-deck says + 144×112, no third implementation drives the device, and Elgato documents no + HID protocol for it. The table names both rather than a number of its own, + and `src/devices/ElgatoStreamDeckStudio.zig` carries 96×96 as a placeholder + marked as one. + + There is now a way to settle it without guessing. `getUnitInfo` asks a device + for its own key and panel dimensions, and a Neo and a Plus both answered with + exactly the sizes Elgato documents for them. Pointing it at a Studio would + end the argument in one call — over USB, or over the network transport + described below. +- The **Plus XL's** rotation is settled. Both references agreed on a quarter + turn and disagreed about which way; Elgato's documentation says *90° + counterclockwise*, for the keys, the panel and the touchscreen alike. This + library had it turning the other way, and now does not. No hardware has + confirmed it. +- The **Galleon** rests on one implementation and has never been run. ### What the hardware settled @@ -140,6 +171,38 @@ the `0x02 0x0b` header and shows it the right way up — the one thing byte-leve checking could not reach, since a strip written upside down is written just as successfully, and a seven segment 6 turned over is a convincing 9. +The **Mini** settled its own image transform, which two references had agreed +on and got wrong. Putting the same figure on four keys under the four +corrections a table can be wrong by, and looking at which read correctly, found +that every key image on a Mini had been coming out **upside down** — the table +carried a quarter turn with a top/bottom flip where it wants that turn with a +left/right one. Elgato's documentation says to rotate ninety degrees clockwise +and mentions no flip at all, so the Mini does what the documentation says and +one thing more; the likeliest reason is that `bmp.zig` writes its rows +bottom-up and the documentation does not say which row order these devices +expect. + +The **Neo** also settled what the panel behind the keys actually is. A +checkerboard painted over its whole 480×320 screen appears through every key +*and* through the info strip, with the pattern running continuously from one key +to the next rather than restarting in each. The keys are windows onto one sheet +of glass, which is what `Panel` is built on, and a marker in the image's +top-left corner came out under the top-left key. `fillScreen` and `fillKey` were +confirmed on it too, along with `getUnitInfo`, which answered with exactly the +sizes Elgato documents. + +The **Original V2** came back for a second look and confirmed the panel. It +reports its own LCD as 480 × 272 through `getUnitInfo`, which is exactly what +Elgato documents for the Classic family and what `Panel` had been carrying on +documentation alone. Its grid, key size and all three firmware versions check +out too, and its two application slots report identically as the Plus's do. + +It also settled the background, though not the way it was meant to. The HID +command for storing one did nothing observable, five different ways — but +painting the panel and then drawing over only some of the keys produced exactly +the effect Elgato's software calls a background, on this model and on the Neo +and the Plus. See [Backgrounds](#backgrounds). + The **Plus** exercised the two riskiest repairs from the audit and found a third fault nobody had looked for. Its 800×100 touchscreen takes an image through the `v3` header, which the audit had found wrong three ways at once — a first byte @@ -186,12 +249,13 @@ pub fn main(init: std.process.Init) !void { const io = init.io; const alloc = init.gpa; - var it = try streamdeck.enumerate(); - defer it.deinit(); + var decks: streamdeck.Enumerator = undefined; + try decks.init(io, alloc); + defer decks.deinit(io, alloc); - while (try it.next(io)) |info| { - const sd = info.deck; - defer info.deinit(io); + while (try decks.next(io, alloc)) |found| { + const sd = found.deck; + defer found.deinit(io, alloc); var serial_buf: [32]u8 = undefined; var version_buf: [32]u8 = undefined; @@ -203,7 +267,8 @@ pub fn main(init: std.process.Init) !void { try sd.reset(io); try sd.setBrightness(io, 50); - while (try sd.events.read(io, alloc)) |event| { + while (true) { + const event = try sd.events.read(io, alloc); defer event.deinit(alloc); switch (event) { .keys => |e| std.debug.print("key: {any}\n", .{e.event}), @@ -215,7 +280,15 @@ pub fn main(init: std.process.Init) !void { } ``` -A `StreamDeck` is mostly a handle plus four control groups, each of which finds +An `Enumerator` is initialized in place rather than returned, because it holds +the scratch the enumeration works in and hands back pointers into its own +storage — so it must not move once started. `StreamDeckInfo` carries the open +deck and the `DeviceInfo` the system reported: the serial number, the product +and manufacturer strings, and where the device sits on the bus. Keep it rather +than asking the open device, which answers less — on Linux a device reports no +manufacturer at all. + +A `StreamDeck` is mostly a handle plus five control groups, each of which finds its way back to the device with `@fieldParentPtr` and answers according to the model: @@ -229,13 +302,21 @@ model: Studio (2). - `touchscreen` — the screens: a touchscreen on the Plus and the Plus XL, and the Neo's info strip, which displays without reporting touches. +- `panel` — the single screen behind the keys, which the key images are + cut-outs of, and which can be painted whole. - `events` — decoding of the input reports the device sends when something is pressed, turned or touched. -The library writes nothing to the log. A report it will not parse comes back as -one of `ReportError` — `ShortReport`, `UnknownReportType`, -`UnknownControlType`, `UnknownEventType` — and what to do about that is the -caller's to decide: a daemon may want it logged, a one-shot tool may want to +`events.read` waits for the device to say something and returns what it said. +A report it will not parse is one of `ReportError` — `ShortReport`, +`UnknownReportType`, `UnknownControlType`, `UnknownEventType` — and is worth +carrying on through; anything else means the deck is no longer reachable, which +is the end of that device. The two have to be told apart, because the obvious +loop around `read` spins forever otherwise: over USB on a deck somebody +unplugged, and over TCP on a connection that will never come back. + +The library writes nothing to the log. What to do about a report it will not +parse is the caller's to decide: a daemon may want it logged, a one-shot tool may want to exit, and neither choice belongs to a library. `src/main.zig` logs them and carries on listening, which is the usual answer but not the library's to assume. @@ -245,6 +326,439 @@ part-way through a report, and a model whose tables here are wrong will send control and event types this library does not expect — which is exactly the case where a caller wants to see the error rather than have it swallowed. +## Networked devices + +The Stream Deck Studio and the Stream Deck Network Dock are not USB devices. +They take Ethernet — the Studio is powered over it — and are driven over TCP, +on port 5343. + +```zig +const address = try std.Io.net.IpAddress.parse("192.0.2.10", streamdeck.Tcp.default_port); +const sd = try streamdeck.connect(io, alloc, address); +defer sd.close(io); +``` + +Everything above the socket is the same as for a USB deck. `keys`, `encoders` +and `events` behave identically, `setImage` takes the same surface, and the +image that goes across is byte for byte the one that would have gone over USB — +the same kilobyte reports with the same headers, not re-chunked for the +network. That is what makes one `StreamDeck` able to drive either. + +These devices are not enumerated. `Enumerator` walks the HID devices attached +to this machine and will never find one, because it is somewhere on a network +rather than plugged in. There is no discovery here either, so the address is the caller's +to know; the devices do advertise themselves over mDNS as `_elg._tcp`, which is +a reasonable thing to add later but is a protocol of its own. + +### What a caller has to do + +**Keep reading.** The device pings every few seconds and hangs up on a host +that has not answered within about five. Answering happens inside +`events.read`, and inside any question asked of the device — but nothing runs +on its own, so a program that spends five seconds drawing without reading will +be disconnected. An application that is doing anything with a Stream Deck sits +in `events.read` anyway; one that does not has to say so. + +The alternative was a task owning the socket, with a queue and a lock between +it and the caller. That is a lot of machinery for a library that otherwise has +none, and it would impose a threading model on every caller to fix a problem +most of them do not have. + +### What differs from USB + +Two things, and both are the protocol's doing rather than this library's: + +- **`reset` is refused**, with `error.Unsupported`. No implementation of this + protocol has ever been seen to perform it, and there is nothing to copy — the + reference client refuses it outright rather than sending something. Inventing + an encoding for a command that clears the device would be guessing with the + device's state. `resetKeyStream` and `setBrightness` work normally. +- **The serial number and firmware version come from elsewhere.** Over USB they + are feature reports `0x06` and `0x05`; over the network they are commands + `0x84` and `0x83` in a separate namespace, whose replies declare their length + *big-endian* in a protocol that is little-endian everywhere else. + `getSerialNumber` and `getFirmwareVersion` hide the difference. + +A **Network Dock** connects and identifies itself — it reports a product id of +`0xffff`, which is Elgato's stand-in rather than an id anything was assigned — +and is then refused with `error.NetworkDockUnsupported`. The dock is only a way +in: the decks are behind it, each on a connection of its own, reached through a +table the dock keeps. Driving one is a follow-up rather than something this +does today. + +### How it is put together + +`framing.zig` is the protocol with the socket taken out of it: frames in and +out, the keepalive exchange, the command replies. It touches no socket and no +`std.Io`, which is what lets it be unit tested and fuzzed without hardware — +the same split `Events.decode` and `Keys.encodeImage` already make, and for the +same reason, only more so: these bytes came off a network rather than out of a +USB device. + +`Tcp.zig` is the thin half that owns the socket, and `Transport.zig` is the +tagged union that lets `StreamDeck` hold either a HID device or one of these. It is a union rather than a vtable because most of this library is +decided by which model a device is and can be tested with no device at all — +which the tests do, with a `.none` transport that answers every call with +`error.NoTransport`. A vtable would make that a pointer nobody set. + +### How far to trust it + +Not very far yet, and further than the Studio's key size. + +Elgato publishes nothing about this protocol — not a specification, not a port +number, not an SDK. What is here was read out of three independent +reverse-engineered implementations, which the references below name, and they +agree with each other on the framing, the keepalive exchange and the image +path. By the standard the device table uses that is *three references*. + +But no networked device has ever been run against this code. The device table's +grades are about numbers that have a reference to rest on; this is a whole +transport that nothing has exercised, and "three implementations agree" is +exactly the position that was held about the Plus before running one turned up +a bug all of them had agreed through. The loopback test in `Tcp.zig` plays a +device convincingly enough to prove this library is self-consistent, and proves +nothing whatever about what real hardware answers. + +## 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 cut out of it — which is +visible the moment you paint the whole thing: + +```zig +var surface = (try sd.panel.blankImage(alloc)).?; +defer surface.deinit(alloc); +// ...draw on it... +try sd.panel.setImage(io, alloc, surface); +``` + +A checkerboard written that way on a Neo shows through every key and through +the info strip, with the pattern running continuously from one key to the next +instead of restarting in each. That is what `Panel` is for: a background that +runs behind and between the keys, and one write that repaints everything +instead of a report per key. + +| Model family | Panel | +| --- | --- | +| Classic (Original V2, MK.2, MK.2 Scissor, 15 Module) | 480 × 272 — **confirmed on hardware** | +| XL (XL, XL V2, 32 Module) | 1024 × 600 | +| Neo | 480 × 320 | +| Plus | 800 × 480 | +| Plus XL | 1280 × 800 | + +The sizes are Elgato's, and a device will confirm its own — see `getUnitInfo` +below. The Mini family has a panel too, and Elgato documents its size, but the +only output report those devices accept writes a key's image bank, so there is +no command to send and `getFeature` reports none. The Studio and the Original +have no documented size at all. + +## Backgrounds + +Elgato's software has a feature it calls a background: an image that "sits +behind your key layout", showing wherever your key artwork does not cover it. +It is worth knowing two things about it. The first is that **it is a feature of +the desktop application, not of the device** — and the second is that you can +have the same effect here without it. + +### How to actually do it + +Paint the panel, then draw over only the keys that want a foreground. A key you +leave alone goes on showing the panel: + +```zig +var background = (try sd.panel.blankImage(alloc)).?; +defer background.deinit(alloc); +// ...draw on it... +try sd.panel.setImage(io, alloc, background); + +// Only the keys that need artwork. The rest keep showing the background. +try sd.keys.setImage(io, alloc, 0, icon); +``` + +That is the whole mechanism, and it works because the keys are windows onto one +sheet of glass rather than separate displays. "The background shows where the +foreground is transparent" turns out to mean nothing more than *not writing +that key*. + +Confirmed on a Stream Deck Original V2, a Neo and a Plus: panel painted with +diagonal stripes, key images drawn over the even-numbered keys only, and the +odd-numbered keys show the stripes. + +### Why it is the application's feature and not the device's + +Elgato's own description gives it away three times over. A background is set by +right-clicking a key in the app and applies to a *profile* and a *page* — +concepts the device knows nothing about. A screensaver is shown "when the +Stream Deck app **is running**, and the computer is locked", which a firmware +feature would not require. And the list of models supporting it includes the +**Stream Deck Pedal**, which has no displays at all. + +So the application composites your artwork over its own copy of the background +and sends ordinary, flattened key images. That also explains the transparency: +key images are JPEG, which has no alpha channel, so nothing transparent ever +reaches the wire. + +### The HID command, which is something else + +There is also a real, documented HID command for storing a background in the +device — and it is not how the desktop feature works. + +```zig +try sd.panel.setBackground(io, alloc, 0, surface); // store it +try sd.panel.showBackground(io, 0); // and put it up +``` + +| Family | Store (`0x02 0x0d`) | Show by index (`0x03 0x13`) | +| --- | --- | --- | +| Classic (Original V2, MK.2, MK.2 Scissor, 15 Module) | yes | **no** | +| XL (XL, XL V2, 32 Module) | yes | yes | +| everything else | no | no | + +The asymmetry is Elgato's: the Classic family's page documents Update Background +and its setter table has no `0x13`. `backgrounds()` reports the two capabilities +separately for that reason. + +**It has never been seen to do anything.** A Stream Deck Original V2 — Classic +family, where the command *is* documented — took all thirty-two pages of a +background without complaint, and then: + +- **Show Background by Index** (`0x03 0x13`): accepted, nothing appeared. + Expected; not a command on this family. +- **Show Logo** (`0x03 0x02`): showed the manufacturer's logo, not the stored + image. +- **A differential scan**, all 256 feature reports read before and after the + upload: **none changed**. The device admits to nothing. +- **Left to go idle** with a five second sleep timeout: blanked to darkness. +- **Colour-keyed transparency**: six candidates painted flat over a stored + background — black, white, magenta, green, mid-grey, near-black. All six + stayed flat. + +So the device is either discarding the upload or displaying it by some means +nobody here has found. One consequence worth being explicit about: **the field +order below is unvalidated too**, because a header with its fields the wrong +way round and a write that is simply discarded look identical from this side. + +`setBackground` is in the API because the command is documented and costs +little to offer, and it is marked untested in its own doc comment. An XL would +settle it, being the one family with both halves. + +### Mind the field order + +The background header is the key image header with **the chunk index and the +chunk size the other way round** — page number at `+0x04` and length at `+0x06`, +where a key image has length at `+0x04` and page number at `+0x06`. Elgato's two +tables differ in exactly that and nothing else, which is easy to read past. + +Getting it backwards would not fail loudly. The first page of a small image has +page number zero and a size of about a kilobyte, so a swapped header asks the +device to write page 1016 of nothing, and the device shows no background with +nothing to say why. This library had precisely that bug in the touchscreen +header once, and it looked the same there. `ImageHeaderV6`'s test pins both +layouts side by side so the difference is visible rather than implied. + +### What the gallery count is not + +`getUnitInfo` reports `lcd_gallery`, and it is tempting to read that as the +number of background slots. It is not. + +A Stream Deck Neo reports **four** LCD images in its gallery. It was sent a +background and asked to show it; it accepted both without complaint and +displayed nothing at all. A Stream Deck Plus reports zero and behaves +identically. + +The wider lesson is worth stating because it bit repeatedly while this was +written: **a Stream Deck accepts writes it does not implement.** It answers all +256 feature report ids, and takes output reports for commands it has never +heard of, in both cases without an error. Nothing about a write being accepted +means it did anything. Only looking at the device settles it. + +## Asking a device about itself + +`getUnitInfo` is the newer protocol's `Get Unit Information`, and it is the one +call that checks this library's tables against the hardware rather than against +another implementation: + +```zig +const unit = try sd.getUnitInfo(io); +// unit.key_width, unit.key_height, unit.lcd_width, unit.lcd_height, ... +``` + +A Neo and a Plus both answered with exactly the key and panel sizes Elgato +documents for them. Where a table and a device disagree, the device is right. + +One trap: `rows` and `cols` describe the **keypad matrix**, not the number of +keys. A Neo answers four by three — twelve positions — where it has eight keys +and two touch buttons, the rest of its bottom row being taken up by the info +strip. Pixel sizes it confirms outright; grid shapes take judgement. + +The Mini family has no such report, and `getUnitInfo` returns +`error.Unsupported` there rather than reading the zeroes one of them answers +with. + +## Other whole-device commands + +| Call | What it does | +| --- | --- | +| `fillKey` | Paint one key a solid colour instead of encoding an image for it. The only way to light a Neo's touch keys, and much cheaper than a JPEG for a key that is one colour. | +| `fillScreen` | Paint the whole panel a solid colour in one feature report. | +| `setSleepTimeout` / `getSleepTimeout` | How long the device sits idle before blanking itself; zero disables it. See the note below. | +| `getFirmwareVersionOf` | A device carries firmware in several parts. See below. | +| `getFirmwareReport` | The same, plus the thirty-two bits the device puts in front of the version string. See below. | +| `keepAlive` | Only the Galleon needs it, about twice a second, and this library will not do it for you — there is no timer here. It does nothing on every other model, so it is safe to call on whatever is attached. | + +`fillKey`, `fillScreen` and `getUnitInfo` were confirmed on a Neo and a Plus, +and all three firmware versions read correctly from a Mini, a Neo and a Plus. +Note that `fillScreen` is a fill and not a mode: the next image written over it +covers it, which is easy to mistake for the command not having worked. + +### A device has more than one firmware version + +Elgato documents three getters for the version, and they are three different +programs rather than three ways of asking the same question: + +| Report | `Firmware` | What it is | +| --- | --- | --- | +| `0x05` / `0xa1` | `.ap2` | The primary application firmware. What a user means by "the firmware version", and what `getFirmwareVersion` reads. | +| `0x04` / `0xa0` | `.ld` | The bootloader. | +| `0x07` / `0xa2` | `.ap1` | The backup application firmware. | + +The Mini family numbers them `0xa0`–`0xa2` instead, and all three were read +correctly off a Mini, a Neo and a Plus. They are genuinely independent: a Neo +reports 1.00.013, 1.00.003 and 1.00.011 for the three. A Plus reports its two +application slots identically, which is what both slots holding the same image +looks like. + +The **Studio** has two more, because its encoders are a board of their own with +a bootloader of their own: + +| Report | `Firmware` | What it is | +| --- | --- | --- | +| `0x11` | `.encoder_ap2` | The encoder module's application firmware. | +| `0x13` | `.encoder_ld` | The encoder module's bootloader. | + +Those two rest on node-elgato-stream-deck, whose Studio driver asks for exactly +these where every other model gets the generic three. Elgato publishes no HID +documentation for the Studio at all, so there is nothing to check them against, +and no hardware here has one. `firmwareReportFor` reports them only for the +Studio and `getFirmwareVersionOf` answers `error.Unsupported` elsewhere. + +Not for want of asking, either: **a Stream Deck Plus was asked for `0x11` and +`0x13` and answered with the same empty stub it gives any report it does not +implement**, and Elgato's Plus XL page lists that model's getters as `0x04` +through `0x08` and `0x0a` and nothing more. So having encoders is not what +brings the extra firmware; being a Studio is. + +`Firmware.all` is the lot, for a caller that wants to print them, and +`zig build probe` does. + +### Reports Elgato does not document + +`zig build probe -- --scan` asks a device for all 256 feature reports and +prints the ones that answer with something. It has to work that way round +because **a device answers every report id** rather than refusing the ones it +does not implement — so "it answered" means nothing, and what separates a real +report from a stub is that the stub is identical whatever you ask for. The scan +derives the stub from ids nothing could plausibly use and subtracts it. + +On a Neo and a Plus, nine reports differ from the stub. Six are the documented +ones (`0x04`–`0x08`, `0x0a`). Three are not documented anywhere: + +| Report | Neo | Plus | +| --- | --- | --- | +| `0x09` | `00 00 00 00 69 16` | `01 00 01 00 e7 34` | +| `0x0b` | length 2, then `0x0120` | length 2, then `0x0110` | +| `0x0c` | length 8, then zeroes | length 8, then zeroes | + +All three are stable across repeated reads and across separate runs, which +rules out counters and anything sampled like a temperature. Beyond that this +library does not guess, and does not expose them: three stable numbers of +unknown meaning are a thing to write down, not an API. They are recorded here +so the next person has somewhere to start. + +The Mini answers only `0x03`, `0x04` and `0xa0`–`0xa3`, which is its documented +set plus the undocumented `0x04` that duplicates `0xa1`. + +### The firmware checksum, and why it is not checked + +A firmware report carries four bytes between its length and its version +string. Elgato's documentation labels them **Checksum** on the newer protocol, +and that is all it says — not what they cover, not the algorithm, not even the +endianness. On the Mini family the same four bytes are listed as "N/A". + +`getFirmwareReport` hands them over as a `u32`. It does not verify them, and +that is a conclusion rather than an omission. + +They were attacked with the hardware to hand: three devices, six firmware +reports, and a search over **41 checksum algorithms** — the RevEng catalogue of +32-bit CRCs, eight 16-bit ones, Adler-32, Fletcher-32, FNV-1 and FNV-1a, djb2, +sdbm, byte and word sums, and MD5, SHA-1 and SHA-256 prefixes — crossed with +**23 ways of deriving an input** from the report (the string field, the string +cut at its terminator, with and without the report id and length, the whole +report with the checksum zeroed, the version parsed back into numbers, and so +on) and **all 24 byte orders** of the stored value. A little over twenty-two +thousand combinations, each required to agree on all six observations at once. +None did. + +The reason turns out to be visible in the older protocol. Those same four +bytes, the ones Elgato's Mini page declines to describe, read as a plain byte +count on a Stream Deck Mini: + +| Report | Version | Four bytes, little-endian | +| --- | --- | --- | +| `0xa0` LD (bootloader) | 0.01.002 | 329,560 — 322 KiB | +| `0xa1` AP2 (primary) | 3.00.001 | 3,397,852 — 3.28 MiB | +| `0xa2` AP1 (backup) | 3.00.000 | 3,354,892 — 3.20 MiB | + +A small bootloader and two application images of nearly the same size, +differing by 42,960 bytes. All three are under 2²⁴, which a uniformly random +32-bit checksum would manage about once in sixteen million times. + +So the four bytes in that slot describe the **firmware image**, not the eight +ASCII characters beside them — and the newer protocol's checksum is a checksum +of an image this library never sees. It cannot be verified from the host, and +no further searching over the version string will change that. + +It is still worth reading. The value changes when the firmware changes, so two +reads that disagree mean the device was reflashed underneath you. The observed +values from a Neo and a Plus are kept as a test in `StreamDeck.zig`, so that +anyone who picks this up again starts with real data: + +| Device | Report | Version | Checksum | +| --- | --- | --- | --- | +| Neo | `0x04` LD | 1.00.003 | `0x01c8a81a` | +| Neo | `0x05` AP2 | 1.00.013 | `0xe19327d5` | +| Neo | `0x07` AP1 | 1.00.011 | `0x63aa63e2` | +| Plus | `0x04` LD | 2.0.0.0 | `0x325db0b1` | +| Plus | `0x05` AP2 | 2.0.3.1 | `0x20a0081e` | +| Plus | `0x07` AP1 | 2.0.3.1 | `0x20a0081e` | + +The Plus reports its two application slots byte for byte identically — same +version, same checksum — which is what two slots holding the same image looks +like, and is why one device alone could not have settled this. + +### The sleep timeout lags its own write + +`setSleepTimeout` takes a count of seconds, little-endian, in feature report +`0x03` behind command `0x0d` on the newer protocol and in `0x0b` behind `0xa2` +on the Mini family. Zero disables sleep rather than meaning "immediately". + +**A device does not apply it before answering the next question.** Read it +straight back and you get the value it held a moment ago, which looks exactly +like the write having failed — and looks worse than that, because a run of +writes then produces a run of answers each one step behind, as though the +device were echoing. It is not; it is just slow to commit. + +A Mini, a Neo and a Plus were each given two different values and asked to read +them back. With no gap at all, every answer lagged. With ten milliseconds, all +three were correct every time, on both values, and restored cleanly afterwards. +Elgato recommends a fifty millisecond polling interval elsewhere in its +documentation, and fifty is comfortably enough here. + +Nothing in this library waits on your behalf — there is no timer in it — so a +caller that wants to confirm the write has to leave the gap itself. The +round-trip lives in `zig build probe -- --sleep`, which reads the current +value, writes two others, checks each, and puts the original back. + ## Diagnostic images `diagnostic.keyIndexImage` draws a key's own index as seven segment @@ -284,8 +798,20 @@ zig build fuzz -- --target events-decode --seed 42 The targets are in `tests/fuzz.zig` and cover everything that turns bytes the hardware said into something this library believes: the input report framing in `Events.decode`, the key, encoder and touchscreen -report parsers under it, and the image path from a drawn surface to the -bytes that would go on the wire. Each picks a model first, so the device +report parsers under it, the image path from a drawn surface to the +bytes that would go on the wire, and the network framing in +`framing.zig`. + +That last one matters most. The rest parse what a USB device said, which +is at worst a device this library has the wrong tables for; the framing +parses what came out of a socket, and a header declaring its own payload +length is exactly the shape of thing that reads past the end of a buffer +when it is got wrong. Both of its targets build a well formed prefix — +the magic, or a reply's leading byte — around the generated bytes, +because random input contains the magic about once in four billion and +a target waiting for one would spend the whole run in an early return. +The malformed shapes are in the corpus instead, where they are +deliberate. Each picks a model first, so the device tables are exercised as well as the parsers — a report that is harmless for one model is a different length and a different shape for another. @@ -328,8 +854,12 @@ Two things that loop reports are worth watching: ## Permissions -`/dev/hidraw*` nodes are normally root-only, so enumeration will simply find -nothing as an unprivileged user. Grant access with a udev rule rather than +`/dev/hidraw*` nodes are normally root-only. **Enumerating** them needs no +permission — the device list comes from `/sys/class/hidraw` — but **opening** +one does, so an unprivileged user gets `error.AccessDenied` from +`Enumerator.next` rather than an empty list. That is a better answer than the +silence this used to give, and it is worth knowing which of the two you are +looking at. Grant access with a udev rule rather than running as root — in `/etc/udev/rules.d/70-streamdeck.rules`: ```udev @@ -439,11 +969,24 @@ reuse lint ## References cited -Elgato publishes no protocol documentation, so what this library knows about -the devices comes from reading the two independent implementations below and -checking them against each other. Where they disagree, the README and the +Elgato **does** publish protocol documentation, which this library did not know +for most of its life. It covers six device families and settles several things +the implementations below disagreed about. It does not cover the Studio, the +Pedal, the Original or the Galleon, so for those the two independent +implementations are still all there is; where they disagree, the README and the device modules say so rather than picking a winner quietly. +- Elgato. *Stream Deck HID API*. + . First-party documentation of + the protocol, with a general reference at `/streamdeck/hid/general` and a page + per device family: Classic, XL, Neo, Plus, Plus XL, and Mini, the last + documented as a legacy protocol that differs from the rest. It gives the USB + product ids, key grid dimensions, key and panel pixel sizes, image rotations, + and the feature and output report layouts. It is the source for the panel + sizes in `Panel.zig`, for `Get Unit Information`, for the sleep timeout and + colour fill commands, and for the Plus XL's rotation. It confirmed every key + image size in the table above. It says nothing about the Studio, the Pedal, + the Original or the Galleon. - Camera, Dean. *python-elgato-streamdeck: Python library to control an Elgato Stream Deck*. . The de-facto reference implementation. Its per-model device classes are the @@ -465,6 +1008,31 @@ device modules say so rather than picking a winner quietly. touch keys. It does not give the key resolution, which is why that figure is still unconfirmed here. +The network transport has sources of its own. Elgato publishes nothing at all +about it — no specification, no port number, no SDK — so the three below are +the whole of what is known, and `framing.zig` follows them where they agree and +says so in a comment where they do not. + +- Waller, Julian. *node-elgato-stream-deck*, `packages/tcp`. + . + The primary source, and the most trustworthy: it is what Bitfocus Companion + ships, and it is tested against real Studio and Network Dock hardware. + `socketWrapper.ts` gives the header layout, the two framings and how a device + is classified into one of them; `hid-device/cora.ts` and `legacy.ts` give the + flags, the operation codes and the split between verbatim reports and host + commands; `device2Info.ts` gives the child device table. +- Haukcode. *Haukcode.StreamDeck*. . + A .NET implementation with a packet capture of Elgato's own application + beside it, which is the only source that can say what the official software + does rather than what a reimplementation found sufficient. Corroborates the + header layout, the keepalive exchange and the big-endian reply length, and is + explicit about which of its own claims are untested. +- SKAARHOJ. *go-streamdeck*. , and + the notes at . + An independent Go implementation of the older, headerless framing, which is + the third agreement on the fixed frame sizes and on the image path being + unchanged from USB. + ## License MIT — see [`LICENSES/MIT.txt`](LICENSES/MIT.txt). diff --git a/build.zig b/build.zig index 96ea2fd..ddf1080 100644 --- a/build.zig +++ b/build.zig @@ -73,6 +73,28 @@ pub fn build(b: *std.Build) void { const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); + // A tool for asking attached hardware what it says about itself, + // so that the device tables can be checked against a device rather + // than against another implementation. + const probe = b.addExecutable(.{ + .name = "probe", + .root_module = b.createModule(.{ + .root_source_file = b.path("tools/probe.zig"), + .target = target, + .optimize = optimize, + .imports = &.{ + .{ .name = "streamdeck", .module = streamdeck_mod }, + .{ .name = "z2d", .module = z2d_dep.module("z2d") }, + }, + }), + }); + + const run_probe = b.addRunArtifact(probe); + if (b.args) |args| run_probe.addArgs(args); + run_probe.stdio = .inherit; + const probe_step = b.step("probe", "Ask every attached device what it says about itself"); + probe_step.dependOn(&run_probe.step); + const test_step = b.step("test", "Run unit tests"); // The library's own tests. `root.zig` names every file in the @@ -127,10 +149,13 @@ pub fn build(b: *std.Build) void { fuzz_step.dependOn(&run_fuzz.step); // Nothing else builds the driver, so without this it could stop - // compiling and no test would notice. + // compiling and no test would notice. The same goes for the probe. test_step.dependOn(&b.addRunArtifact( b.addTest(.{ .root_module = fuzz_driver.root_module }), ).step); + test_step.dependOn(&b.addRunArtifact( + b.addTest(.{ .root_module = probe.root_module }), + ).step); } /// Fail the build if a file under `src/` is not named in `root.zig`'s diff --git a/build.zig.zon b/build.zig.zon index 2b5d5da..1c415f9 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -20,8 +20,8 @@ .hash = "z2dimg-0.0.0-N7PaCW-nDwB1bANVVhG50FC7E_1Z9fnrnDDG075F0gGC", }, .hidapi = .{ - .url = "git+https://git.jcollie.dev/jeff/zig-hidapi.git#d72bcf297104707a31c07b447b3f9f5514c9eed8", - .hash = "hidapi-0.0.3-PuroMzzaAAC9GfCUMbujYgxyfvkMW0kIlLN5gAVm9cyg", + .url = "git+https://git.jcollie.dev/jeff/zig-hidapi.git#c7805bb33410e16af6e222222815de8dda62a7d3", + .hash = "hidapi-0.0.3-PuroMzLsBgDX3w2x_YpI2OaqVeQxx0H3twxKjAPRKE6l", }, }, diff --git a/src/Encoders.zig b/src/Encoders.zig index ee8633e..3af0aef 100644 --- a/src/Encoders.zig +++ b/src/Encoders.zig @@ -24,6 +24,7 @@ pub const init: Encoders = .{}; pub fn count(self: *const Encoders) u8 { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("encoders", self)); return switch (sd.type) { + .CorsairGalleonK100 => 2, .ElgatoStreamDeckMini => 0, .ElgatoStreamDeckMiniDiscord => 0, .ElgatoStreamDeckMiniMK2 => 0, @@ -143,7 +144,7 @@ pub const Event = struct { /// 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 = undefined }; + return .{ .type = t, .device = .none }; } test count { diff --git a/src/Events.zig b/src/Events.zig index 09be997..2db6011 100644 --- a/src/Events.zig +++ b/src/Events.zig @@ -90,16 +90,25 @@ pub fn readSize(self: *const Events) usize { return @max(computed, sd.type.inputReportSize() orelse 0); } -pub fn read(self: *const Events, io: std.Io, alloc: std.mem.Allocator) !?Event { +/// 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 = sd.device.read(io, buf) catch |err| switch (err) { - error.HIDError => return null, - error.ConcurrencyUnavailable => unreachable, - }; + const data = try sd.device.read(io, buf); const now: std.Io.Timestamp = .now(io, .real); @@ -178,7 +187,7 @@ fn forControl(body: []const u8, size: usize) []const u8 { /// 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 = undefined }; + return .{ .type = t, .device = .none }; } test headerFormat { @@ -288,7 +297,7 @@ test "decoding a report cleans up after a failed allocation" { }) |report| { try std.testing.checkAllAllocationFailures(std.testing.allocator, struct { fn run(alloc: std.mem.Allocator) !void { - var sd: StreamDeck = .{ .type = .ElgatoStreamDeckPlus, .device = undefined }; + var sd: StreamDeck = .{ .type = .ElgatoStreamDeckPlus, .device = .none }; const event = try sd.events.decode(alloc, .{ .nanoseconds = 0 }, &report); defer event.deinit(alloc); } diff --git a/src/Keys.zig b/src/Keys.zig index e2c306d..63197e7 100644 --- a/src/Keys.zig +++ b/src/Keys.zig @@ -443,7 +443,7 @@ pub fn setTouchKeyColor(self: *const Keys, io: std.Io, key: u8, r: u8, g: u8, b: /// the handle, so they can be tested without one; anything that talks /// to the device cannot, and is only compiled here rather than run. fn testDeck(t: StreamDeck.Type) StreamDeck { - return .{ .type = t, .device = undefined }; + return .{ .type = t, .device = .none }; } test cols { @@ -596,7 +596,7 @@ test "encoding a key image cleans up after a failed allocation" { }) |t| { try std.testing.checkAllAllocationFailures(std.testing.allocator, struct { fn run(alloc: std.mem.Allocator) !void { - var sd: StreamDeck = .{ .type = t, .device = undefined }; + var sd: StreamDeck = .{ .type = t, .device = .none }; const feature = sd.keys.getImageFeature(0).?; var surface = try image.blankImage(alloc, feature.width, feature.height); @@ -612,7 +612,7 @@ test "encoding a key image cleans up after a failed allocation" { test "a diagnostic key image cleans up after a failed allocation" { try std.testing.checkAllAllocationFailures(std.testing.allocator, struct { fn run(alloc: std.mem.Allocator) !void { - var sd: StreamDeck = .{ .type = .ElgatoStreamDeckMK2, .device = undefined }; + var sd: StreamDeck = .{ .type = .ElgatoStreamDeckMK2, .device = .none }; var img = (try sd.keys.indexImage(alloc, 6, .yellow_on_black)).?; defer img.deinit(alloc); } diff --git a/src/Panel.zig b/src/Panel.zig new file mode 100644 index 0000000..776064d --- /dev/null +++ b/src/Panel.zig @@ -0,0 +1,493 @@ +// 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. +//! +//! `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. +//! +//! **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. 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, +}; + +/// 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 +/// Studio and the Original have 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, + }, + + // Its panel is 720x1280, but nothing describes a command to + // write the whole of it, so it is not offered. + .CorsairGalleonK100, + .ElgatoStreamDeckMini, + .ElgatoStreamDeckMiniDiscord, + .ElgatoStreamDeckMiniMK2, + .ElgatoStreamDeckModule6, + .ElgatoStreamDeckOriginal, + .ElgatoStreamDeckPedal, + .ElgatoStreamDeckStudio, + => 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. +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; + } + + 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{ + .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 (std.meta.fields(StreamDeck.Type)) |f| { + var sd = testDeck(@enumFromInt(f.value)); + 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); + + 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 (std.meta.fields(StreamDeck.Type)) |f| { + var sd = testDeck(@enumFromInt(f.value)); + 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()); +} diff --git a/src/StreamDeck.zig b/src/StreamDeck.zig index 7ac5989..33f0631 100644 --- a/src/StreamDeck.zig +++ b/src/StreamDeck.zig @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT -//! A single Stream Deck: the open HID device, the model it is, and the +//! A single Stream Deck: the open device, the model it is, and the //! whole-device operations that do not belong to any one control, such //! as resetting it or reading its serial number. //! @@ -17,8 +17,11 @@ const StreamDeck = @This(); const hidapi = @import("hidapi"); const devices = @import("devices.zig"); +const Tcp = @import("Tcp.zig"); +const Transport = @import("Transport.zig"); const Keys = @import("Keys.zig"); const Touchscreen = @import("Touchscreen.zig"); +const Panel = @import("Panel.zig"); const Encoders = @import("Encoders.zig"); const Events = @import("Events.zig"); @@ -26,6 +29,10 @@ const Events = @import("Events.zig"); /// vendor id in the upper sixteen bits and the product id in the lower /// sixteen, which makes a device easy to identify in one comparison. pub const Type = enum(u32) { + /// The only device here that is not Elgato's: a Corsair keyboard + /// with a Stream Deck panel built into it, reporting Corsair's + /// vendor id. + CorsairGalleonK100 = 0x1b1c2b18, ElgatoStreamDeckMK2 = 0x0fd90080, ElgatoStreamDeckMK2Scissor = 0x0fd900a5, ElgatoStreamDeckMini = 0x0fd90063, @@ -82,6 +89,7 @@ pub const Type = enum(u32) { .ElgatoStreamDeckOriginal, => .gen1, + .CorsairGalleonK100, .ElgatoStreamDeckMK2, .ElgatoStreamDeckMK2Scissor, .ElgatoStreamDeckModule15, @@ -141,6 +149,7 @@ pub const Type = enum(u32) { return switch (self) { .ElgatoStreamDeckOriginal => .{ .size = 8191, .first_page = 1 }, + .CorsairGalleonK100, .ElgatoStreamDeckMK2, .ElgatoStreamDeckMK2Scissor, .ElgatoStreamDeckMini, @@ -179,6 +188,17 @@ pub const Type = enum(u32) { }; } + /// Whether this model answers `Get Unit Information`, the feature + /// report through which a device describes its own geometry. + /// + /// Only the newer protocol has it. Elgato's documentation lists the + /// getter feature reports for the Mini family separately and this + /// is not among them, so asking a Mini would be asking for a report + /// it has never heard of. + pub fn hasUnitInfo(self: Type) bool { + return self.generation() == .gen2; + } + /// The feature report that carries this model's firmware version. pub fn firmwareReport(self: Type) StringReport { return switch (self.generation()) { @@ -200,57 +220,102 @@ test Type { /// Which model this device is. Nearly everything else about the device /// is decided by this. type: Type, -/// The open HID device. Valid until `close`. -device: hidapi.Device, +/// How this device is reached: a HID device, or a TCP connection to a +/// Studio or a Network Dock. Valid until `close`. +device: Transport, /// The keys, and the images shown on them. keys: Keys = .init, /// The touchscreen, on the models that have one. touchscreen: Touchscreen = .init, +/// The whole screen behind the keys, on the models that will let it be +/// written. +panel: Panel = .init, /// The rotary encoders, on the models that have them. encoders: Encoders = .init, /// Decoding of the input reports the device sends when something on it /// is pressed, touched or turned. events: Events = .init, -/// Build a `StreamDeck` from an entry returned by enumeration, taking -/// the device handle from it. Fails with `error.NotAStreamDeck` if the -/// entry is for a device this library does not know. -pub fn initFromDeviceInfo(info: hidapi.DeviceInfo) !StreamDeck { - return .{ - .type = try .init(info.vendor, info.product), - .device = info.device, - }; +/// Open the device an enumeration reported and build a `StreamDeck` +/// around it. +/// +/// `info` is what `Enumerator.next` handed back. Its vendor and product +/// ids say which model this is before the device is opened at all, so a +/// device this library does not know is refused with +/// `error.NotAStreamDeck` without being touched. +/// +/// Opening needs permission where enumerating does not: `/dev/hidraw*` +/// is root-only until a udev rule says otherwise, and until then this +/// answers `error.AccessDenied`. The README has a rule to copy. +/// +/// The caller owns the result and must release it with `close`. +pub fn open(io: std.Io, alloc: std.mem.Allocator, info: *const hidapi.DeviceInfo) !StreamDeck { + const t: Type = try .init(info.vendor_id, info.product_id); + + // The device is held by pointer because `hidapi` opens one in place + // and every operation on it takes a mutable pointer, so it cannot + // be moved once opened. + const device = try alloc.create(hidapi.Device); + errdefer alloc.destroy(device); + + try device.open(io, info.id, .{}); + return .{ .type = t, .device = .fromHid(device) }; } -/// Build a `StreamDeck` around a device that is already open, asking it -/// which model it is. Fails with `error.NotAStreamDeck` if it is not -/// one this library knows. -pub fn initFromDevice(io: std.Io, device: hidapi.Device) !StreamDeck { - const info = try device.getDeviceInfo(io); +/// Open a device by the id an enumeration reported, asking it which +/// model it is once it is open. +/// +/// `open` is the better way round when the `DeviceInfo` is still to +/// hand: it knows the model before it touches the device. This is for a +/// caller that kept only the id, which is the part with no lifetime of +/// its own. +pub fn openId(io: std.Io, alloc: std.mem.Allocator, id: hidapi.DeviceId) !StreamDeck { + const device = try alloc.create(hidapi.Device); + errdefer alloc.destroy(device); + + try device.open(io, id, .{}); + errdefer device.close(io); + + var info: hidapi.DeviceInfo = .empty; + try device.getInfo(io, &info); + return .{ - .type = try .init(info.vendor, info.product), - .device = device, + .type = try .init(info.vendor_id, info.product_id), + .device = .fromHid(device), }; } -/// Open the device with the given minor device number and build a -/// `StreamDeck` around it. The device is closed again if it turns out -/// not to be a Stream Deck. The caller owns the result and must release -/// it with `close`. -pub fn open(io: std.Io, minor: u64) !StreamDeck { - var device = try hidapi.Device.open(io, minor); - errdefer device.close(io); - const info = try device.getDeviceInfo(io); +/// Open a connection to a Stream Deck reached over the network -- a +/// Studio, or a Network Dock -- and build a `StreamDeck` around it. +/// +/// `address` is where the device is; there is no discovery here, and +/// `std.Io.net` has no name resolver, so a caller with a host name has +/// to turn it into an address itself. `Tcp.default_port` is the port +/// these devices listen on. +/// +/// The device is asked what it is as part of connecting, and the +/// connection is closed again if the answer is not a model this library +/// knows. The caller owns the result and must release it with `close`. +/// +/// Note what driving one of these asks of the caller: the device pings +/// every few seconds and hangs up on a host that has not answered +/// within five, and answering happens only while something is reading. +/// See the note at the top of `Tcp.zig`. +pub fn connect(io: std.Io, alloc: std.mem.Allocator, address: std.Io.net.IpAddress) !StreamDeck { + const connection = try Tcp.connect(io, alloc, address); + errdefer connection.close(io); + return .{ - .type = try .init(info.vendor, info.product), - .device = device, + .type = try .init(connection.vendor, connection.product), + .device = .fromTcp(connection), }; } -/// Close the underlying HID device. Nothing else on this `StreamDeck` -/// may be used afterwards. -pub fn close(self: *const StreamDeck, io: std.Io) void { - self.device.close(io); +/// Release the underlying device, closing the HID node or the network +/// connection and freeing what was allocated for it. Nothing else on +/// this `StreamDeck` may be used afterwards. +pub fn close(self: *const StreamDeck, io: std.Io, alloc: std.mem.Allocator) void { + self.device.close(io, alloc); } /// The report size every model but the Original takes, and the size of @@ -279,6 +344,13 @@ pub fn resetKeyStream(self: *const StreamDeck, io: std.Io) !void { /// back to the manufacturer's logo. The older models want a different /// feature report for this than the newer ones. pub fn reset(self: *const StreamDeck, io: std.Io) !void { + // No implementation of the network protocol has ever been seen to + // perform this, and there is nothing to copy: the reference client + // refuses it outright rather than sending something. Inventing an + // encoding for a command that clears the device would be guessing + // with the device's state, so this says so instead. + if (self.device.kind() == .tcp) return error.Unsupported; + var buf: [32]u8 = undefined; var writer = std.Io.Writer.fixed(&buf); switch (self.type.generation()) { @@ -346,6 +418,624 @@ pub fn setBrightness(self: *const StreamDeck, io: std.Io, percent: u8) !void { _ = try self.device.sendFeatureReport(io, writer.buffered()); } +/// What a device says about itself when asked. +/// +/// This is the answer to `Get Unit Information`, feature report `0x08`, +/// and it is worth more than its size suggests: it is the device +/// reporting its own key grid and its own pixel dimensions, rather than +/// this library looking them up in a table somebody wrote down. Where +/// the two disagree, the device is right. +/// +/// Elgato's HID documentation describes the layout; see the README's +/// references. +pub const UnitInfo = struct { + /// Rows in the key grid, as the device counts them. + rows: u8, + /// Columns in the key grid. + cols: u8, + /// The pixel size of one key's display. + key_width: u16, + key_height: u16, + /// The pixel size of the whole panel behind the keys. Every model + /// with displays has one, including the ones with no touchscreen. + lcd_width: u16, + lcd_height: u16, + /// Bits per pixel of the images the device takes. + image_bpp: u8, + /// Which colour scheme those images are in. Elgato documents the + /// field but not its values, so this is passed through as a number. + image_color_scheme: u8, + /// How many key images and screen images the device says it can + /// hold in its own gallery, and how many frames its demo runs for. + /// + /// Do **not** read `lcd_gallery` as the number of background slots. + /// A Stream Deck Neo reports four and does not implement the + /// background commands at all -- it was sent one and asked to show + /// it, accepted both, and displayed nothing. What the gallery + /// actually counts is not documented and has not been worked out. + key_gallery: u8, + lcd_gallery: u8, + demo_frames: u8, + + /// The total number of keys the device says it has. + pub fn count(self: UnitInfo) u16 { + return @as(u16, self.rows) * self.cols; + } +}; + +/// Ask the device to describe itself. +/// +/// Returns `error.Unsupported` on a model whose protocol has no such +/// report -- the Mini family -- and `error.ShortReport` if the device +/// answered with less than the layout requires. +/// +/// This is the one call that can check the device tables against the +/// hardware instead of against another implementation, so it is worth +/// reaching for when a model's numbers are in doubt. +/// +/// Confirmed against a Neo and a Plus, which answered with exactly the +/// key and panel sizes Elgato's documentation gives for them. +/// +/// Note that `rows` and `cols` describe the **keypad matrix** and not +/// the number of keys: a Neo answers four by three, twelve positions, +/// where it has eight keys and two touch buttons and the rest of the +/// bottom row is taken up by its info strip. So this confirms pixel +/// sizes outright and grid shapes only with judgement. +pub fn getUnitInfo(self: *const StreamDeck, io: std.Io) !UnitInfo { + if (!self.type.hasUnitInfo()) return error.Unsupported; + + var buffer = std.mem.zeroes([32]u8); + buffer[0] = 0x08; + const result = try self.device.getFeatureReport(io, &buffer); + + // The fields run from +0x01 to +0x0f, so anything shorter than + // sixteen bytes is an answer this cannot be read out of. + if (result.len < 16) return error.ShortReport; + + return .{ + .rows = result[1], + .cols = result[2], + .key_width = std.mem.readInt(u16, result[3..5], .little), + .key_height = std.mem.readInt(u16, result[5..7], .little), + .lcd_width = std.mem.readInt(u16, result[7..9], .little), + .lcd_height = std.mem.readInt(u16, result[9..11], .little), + .image_bpp = result[11], + .image_color_scheme = result[12], + .key_gallery = result[13], + .lcd_gallery = result[14], + .demo_frames = result[15], + }; +} + +/// Which firmware version to ask a device for. +/// +/// A Stream Deck carries more than one processor and reports a version +/// for each. `ap2` is the one a user means by "the firmware version", +/// and is what `getFirmwareVersion` reads; the others are here because +/// Elgato's documentation names them and because a device that is +/// misbehaving is a device whose other versions are worth seeing. +pub const Firmware = enum { + /// The primary application firmware. + ap2, + /// The bootloader. + ld, + /// The backup application firmware. + ap1, + /// The primary application firmware of the encoder module, on a + /// model whose encoders are a board of their own. + encoder_ap2, + /// That module's bootloader. + encoder_ld, + + /// Every version this library knows how to ask for, for a caller + /// that wants to print the lot. + pub const all = [_]Firmware{ .ap2, .ld, .ap1, .encoder_ap2, .encoder_ld }; +}; + +/// Whether this model's encoders carry firmware of their own. +/// +/// Only the Studio does, as far as anything says. Its encoders are a +/// separate board with a separate bootloader, and Elgato publishes no +/// HID documentation for that model at all -- the two report ids come +/// from node-elgato-stream-deck, whose Studio driver asks for exactly +/// these three versions where every other model gets the generic set. +/// +/// The Plus and the Plus XL have encoders and do **not** have this: a +/// Stream Deck Plus was asked for both reports and answered with the +/// same empty stub it gives any report it does not implement, and +/// Elgato's Plus XL page lists its getters as `0x04` through `0x08` +/// and `0x0a` and nothing else. +pub fn hasEncoderFirmware(t: Type) bool { + return t == .ElgatoStreamDeckStudio; +} + +/// The feature report carrying one of a model's firmware versions, or +/// null if this model does not report that one. +pub fn firmwareReportFor(t: Type, which: Firmware) ?Type.StringReport { + switch (which) { + .encoder_ap2, .encoder_ld => { + if (!hasEncoderFirmware(t)) return null; + // Assumed to be laid out like the other newer-protocol + // firmware reports -- a length, a word, then the string at + // +0x06 -- because that is what the report they sit beside + // does. Nothing has run a Studio to check it. + return .{ + .id = switch (which) { + .encoder_ap2 => 0x11, + .encoder_ld => 0x13, + else => unreachable, + }, + .len = 32, + .offset = 6, + }; + }, + .ap2, .ld, .ap1 => {}, + } + + return switch (t.generation()) { + // The older protocol numbers these quite differently, and the + // report this library has always used for the Mini family -- + // 0x04 -- is not in Elgato's list for them at all. It answers + // anyway, with the same string 0xa1 gives; that was checked + // against a Stream Deck Mini. Both are kept: the documented one + // is what `ap2` asks for, and the other is left working. + .gen1 => switch (which) { + .ld => .{ .id = 0xa0, .len = 17, .offset = 5 }, + .ap2 => .{ .id = 0xa1, .len = 17, .offset = 5 }, + .ap1 => .{ .id = 0xa2, .len = 17, .offset = 5 }, + .encoder_ap2, .encoder_ld => unreachable, + }, + .gen2 => switch (which) { + .ld => .{ .id = 0x04, .len = 32, .offset = 6 }, + .ap2 => .{ .id = 0x05, .len = 32, .offset = 6 }, + .ap1 => .{ .id = 0x07, .len = 32, .offset = 6 }, + .encoder_ap2, .encoder_ld => unreachable, + }, + }; +} + +/// A firmware report in full: the version string, and the thirty-two +/// bits the device puts in front of it. +pub const FirmwareReport = struct { + /// The version string. Points into the buffer it was read into. + version: []const u8, + /// The four bytes between the report's length and its version + /// string, read little-endian. + /// + /// Elgato's documentation calls this a **checksum** on the newer + /// protocol and says nothing else about it: not what it covers, + /// not the algorithm, not the endianness. On the Mini family the + /// same four bytes are listed as "N/A". + /// + /// What it is a checksum *of* is almost certainly the firmware + /// image, which means this library cannot verify it -- see + /// `checksum_is_not_of_the_version_string` for the evidence and + /// for what was ruled out. It is exposed rather than hidden + /// because it is still good for something: it changes when the + /// firmware changes, so two reads that disagree mean the device + /// was reflashed under you, and a value recorded here is evidence + /// for whoever next tries to identify it. + checksum: u32, +}; + +/// Why this library does not check the firmware checksum. +/// +/// Elgato documents the field and not the algorithm, so it was +/// attacked with what hardware was to hand: three devices, six +/// firmware reports, and a search over 41 checksum algorithms -- the +/// RevEng catalogue of 32-bit CRCs, eight 16-bit ones, Adler-32, +/// Fletcher-32, FNV-1 and 1a, djb2, sdbm, byte and word sums, MD5, +/// SHA-1 and SHA-256 prefixes -- crossed with 23 ways of deriving an +/// input from the report and all 24 byte orders of the stored value. +/// That is a little over twenty-two thousand combinations, required to +/// agree on all six observations at once. None did. +/// +/// The reason is visible in the older protocol. Those same four bytes, +/// which Elgato's Mini page declines to describe, read as a byte count +/// on a Stream Deck Mini: 329,560 for the bootloader and 3,397,852 and +/// 3,354,892 for the two application slots, which is a bootloader of +/// 322 KiB and two firmware images of about 3.28 MiB differing by +/// 42,960 bytes. All three are under 2^24, which a random 32-bit +/// checksum would manage about once in sixteen million times. +/// +/// So the four bytes in that slot describe the firmware image rather +/// than the eight ASCII characters beside them, and the newer +/// protocol's checksum is therefore a checksum of an image this +/// library never sees. Checking it from the host is not possible, and +/// no amount of further searching over the version string will help. +/// +/// The observed values are kept as a test below, so that the next +/// person to try has real data to work from. +pub const checksum_is_not_of_the_version_string = {}; + +/// Parse a firmware report: the string, and the word in front of it. +/// +/// Split out from the read so that it can be checked against bytes a +/// real device sent without needing the device, which is what the test +/// below does. +pub fn parseFirmwareReport(report: Type.StringReport, data: []const u8) !FirmwareReport { + // The word sits in the four bytes immediately before the string, + // which is true of both protocols: the older puts the string at + // +0x05 and the word at +0x01, the newer at +0x06 and +0x02. + if (report.offset < 4) return error.ShortReport; + const word_at = report.offset - 4; + if (data.len < report.offset) return error.ShortReport; + + const string = data[report.offset..]; + return .{ + .version = if (std.mem.findScalar(u8, string, 0)) |end| string[0..end] else string, + .checksum = std.mem.readInt(u32, data[word_at..][0..4], .little), + }; +} + +/// Read one of the device's firmware versions in full: the string and +/// the word in front of it. +/// +/// `getFirmwareVersion` is this with the word thrown away, which is +/// what nearly every caller wants. +pub fn getFirmwareReport( + self: *const StreamDeck, + io: std.Io, + which: Firmware, + buffer: []u8, +) !FirmwareReport { + const report = firmwareReportFor(self.type, which) orelse return error.Unsupported; + if (buffer.len < report.len) return error.BufferTooSmall; + + @memset(buffer, 0); + buffer[0] = report.id; + const result = try self.device.getFeatureReport(io, buffer[0..report.len]); + return parseFirmwareReport(report, result); +} + +/// Read one of the device's firmware versions into `buffer`. +/// +/// `getFirmwareVersion` is this with `.ap2`, which is the one worth +/// printing; the others are for telling apart two devices that claim +/// the same primary version. +pub fn getFirmwareVersionOf( + self: *const StreamDeck, + io: std.Io, + which: Firmware, + buffer: []u8, +) ![]const u8 { + const report = firmwareReportFor(self.type, which) orelse return error.Unsupported; + return self.readStringReport(io, buffer, report); +} + +/// Fill one key with a solid colour, instead of sending it an image. +/// +/// This is far cheaper than encoding a JPEG for a key that only needs +/// to be one colour, and it is the only way to light the touch keys on +/// a Neo, which have a backlight rather than a display. Elgato's +/// documentation describes it for every key on the newer protocol, not +/// only those. +/// +/// Returns `error.Unsupported` on the older protocol, which has no such +/// command, and on the Pedal, which has nothing to light. +/// +/// Confirmed against a Neo and a Plus. +pub fn fillKey(self: *const StreamDeck, io: std.Io, key: u8, r: u8, g: u8, b: u8) !void { + if (self.type.generation() != .gen2) return error.Unsupported; + if (self.type == .ElgatoStreamDeckPedal) return error.Unsupported; + + const packet: extern struct { + byte0: u8 = 0x03, + byte1: u8 = 0x06, + key: u8, + r: u8, + g: u8, + b: u8, + } = .{ .key = key, .r = r, .g = g, .b = b }; + std.debug.assert(@sizeOf(@TypeOf(packet)) == 6); + + _ = try self.device.sendFeatureReport(io, std.mem.asBytes(&packet)); +} + +/// Fill the whole panel behind the keys with a solid colour. +/// +/// Every model with displays has one screen behind all of them, which +/// is what the keys are windows onto; this paints the lot in one +/// command. Returns `error.Unsupported` where there is no such screen +/// or no such command. +/// +/// Confirmed against a Neo and a Plus: the keys and, on the Neo, the +/// info strip all take the colour together. Note that it is a fill and +/// not a mode -- the next image written to a key or to the panel +/// covers it, which is easy to mistake for the fill not having worked. +pub fn fillScreen(self: *const StreamDeck, io: std.Io, r: u8, g: u8, b: u8) !void { + if (self.type.generation() != .gen2) return error.Unsupported; + if (self.type == .ElgatoStreamDeckPedal) return error.Unsupported; + + const packet: extern struct { + byte0: u8 = 0x03, + byte1: u8 = 0x05, + r: u8, + g: u8, + b: u8, + } = .{ .r = r, .g = g, .b = b }; + std.debug.assert(@sizeOf(@TypeOf(packet)) == 5); + + _ = try self.device.sendFeatureReport(io, std.mem.asBytes(&packet)); +} + +/// The feature report that sets the sleep timeout, built into `buf`. +/// +/// Split out from `setSleepTimeout` so that the bytes can be checked +/// without a device, which is how everything else here that turns a +/// decision into a packet is arranged. +/// +/// The two protocols disagree about everything but the field: the older +/// one carries it in report `0x0b` behind command `0xa2`, the newer in +/// `0x03` behind `0x0d`. Both take a little-endian signed thirty-two +/// bit count of seconds, and both read zero as "do not sleep". +pub fn sleepTimeoutReport(t: Type, seconds: u31, buf: []u8) ![]const u8 { + var writer = std.Io.Writer.fixed(buf); + + switch (t.generation()) { + .gen1 => { + const packet: extern struct { + byte0: u8 = 0x0b, + byte1: u8 = 0xa2, + seconds: i32 align(1), + } = .{ .seconds = seconds }; + std.debug.assert(@sizeOf(@TypeOf(packet)) == 6); + try writer.writeStruct(packet, .little); + }, + .gen2 => { + const packet: extern struct { + byte0: u8 = 0x03, + byte1: u8 = 0x0d, + seconds: i32 align(1), + } = .{ .seconds = seconds }; + std.debug.assert(@sizeOf(@TypeOf(packet)) == 6); + try writer.writeStruct(packet, .little); + }, + } + + return writer.buffered(); +} + +/// The feature report a model answers its sleep timeout on. +pub fn sleepTimeoutQuery(t: Type) u8 { + return switch (t.generation()) { + .gen1 => 0xa3, + .gen2 => 0x0a, + }; +} + +/// How long the device sits idle before blanking itself, in seconds. +/// Zero disables it, so the device stays lit until told otherwise. +/// +/// **A device does not apply this before it answers the next question.** +/// Reading it straight back reports the value it held a moment ago, +/// which looks exactly like the write having failed. A Mini, a Neo and +/// a Plus all wanted somewhere between nothing and ten milliseconds; +/// none of them needed fifty. Nothing here waits on your behalf -- +/// there is no timer in this library -- so a caller that wants to +/// confirm the write has to leave a gap before `getSleepTimeout`. +/// +/// Confirmed on all three of those devices, which round-tripped two +/// different values and restored the original. +pub fn setSleepTimeout(self: *const StreamDeck, io: std.Io, seconds: u31) !void { + var buf: [32]u8 = undefined; + const report = try sleepTimeoutReport(self.type, seconds, &buf); + _ = try self.device.sendFeatureReport(io, report); +} + +/// How long the device is currently set to wait before blanking, in +/// seconds. Zero means it does not. +/// +/// See `setSleepTimeout` about reading this immediately after writing +/// it: the answer lags the write. +pub fn getSleepTimeout(self: *const StreamDeck, io: std.Io) !u31 { + var buffer = std.mem.zeroes([32]u8); + buffer[0] = sleepTimeoutQuery(self.type); + + const result = try self.device.getFeatureReport(io, &buffer); + // A report id, a length byte, then the duration. Anything shorter + // than the three of them together is not an answer. + if (result.len < 6) return error.ShortReport; + + const seconds = std.mem.readInt(i32, result[2..6], .little); + // A device has no business reporting a negative idle time, and + // narrowing one into a `u31` would be a panic rather than an error. + if (seconds < 0) return error.ShortReport; + return @intCast(seconds); +} + +test hasEncoderFirmware { + // Only the Studio, and the two reports exist only there. + inline for (std.meta.fields(Type)) |f| { + const t: Type = @enumFromInt(f.value); + const expected = t == .ElgatoStreamDeckStudio; + try std.testing.expectEqual(expected, hasEncoderFirmware(t)); + + for ([_]Firmware{ .encoder_ap2, .encoder_ld }) |which| { + const report = firmwareReportFor(t, which); + try std.testing.expectEqual(expected, report != null); + } + + // The three every model answers are always there, whatever the + // protocol. + for ([_]Firmware{ .ap2, .ld, .ap1 }) |which| { + try std.testing.expect(firmwareReportFor(t, which) != null); + } + } + + try std.testing.expectEqual( + @as(u8, 0x11), + firmwareReportFor(.ElgatoStreamDeckStudio, .encoder_ap2).?.id, + ); + try std.testing.expectEqual( + @as(u8, 0x13), + firmwareReportFor(.ElgatoStreamDeckStudio, .encoder_ld).?.id, + ); +} + +test "no two firmware reports on one model share a report id" { + // Asking for the encoder's version and getting the panel's would be + // silent and wrong, so the ids have to be distinct per model -- and + // distinct from the serial number's, which sits in the same range. + inline for (std.meta.fields(Type)) |f| { + const t: Type = @enumFromInt(f.value); + + for (Firmware.all) |a| { + const ra = firmwareReportFor(t, a) orelse continue; + try std.testing.expect(ra.id != t.serialReport().id); + + for (Firmware.all) |b| { + if (a == b) continue; + const rb = firmwareReportFor(t, b) orelse continue; + try std.testing.expect(ra.id != rb.id); + } + } + } +} + +test parseFirmwareReport { + // Bytes a real Stream Deck Neo and a real Stream Deck Plus sent, + // recorded so that the parse is checked against hardware rather + // than against a reading of the documentation -- and so that the + // checksum values survive for whoever next tries to identify them. + const Case = struct { + model: Type, + which: Firmware, + raw: []const u8, + version: []const u8, + checksum: u32, + }; + + for ([_]Case{ + // Stream Deck Neo, firmware 1.00.013. + .{ + .model = .ElgatoStreamDeckNeo, + .which = .ld, + .raw = &.{ 0x04, 0x0c, 0x1a, 0xa8, 0xc8, 0x01, '1', '.', '0', '0', '.', '0', '0', '3' }, + .version = "1.00.003", + .checksum = 0x01c8a81a, + }, + .{ + .model = .ElgatoStreamDeckNeo, + .which = .ap2, + .raw = &.{ 0x05, 0x0c, 0xd5, 0x27, 0x93, 0xe1, '1', '.', '0', '0', '.', '0', '1', '3' }, + .version = "1.00.013", + .checksum = 0xe19327d5, + }, + .{ + .model = .ElgatoStreamDeckNeo, + .which = .ap1, + .raw = &.{ 0x07, 0x0c, 0xe2, 0x63, 0xaa, 0x63, '1', '.', '0', '0', '.', '0', '1', '1' }, + .version = "1.00.011", + .checksum = 0x63aa63e2, + }, + // Stream Deck Plus, firmware 2.0.3.1. Its strings are seven + // characters and a terminator where the Neo's fill the field, + // so this is also the test that the cut is made at the NUL. + .{ + .model = .ElgatoStreamDeckPlus, + .which = .ld, + .raw = &.{ 0x04, 0x0c, 0xb1, 0xb0, 0x5d, 0x32, '2', '.', '0', '.', '0', '.', '0', 0x00 }, + .version = "2.0.0.0", + .checksum = 0x325db0b1, + }, + .{ + .model = .ElgatoStreamDeckPlus, + .which = .ap2, + .raw = &.{ 0x05, 0x0c, 0x1e, 0x08, 0xa0, 0x20, '2', '.', '0', '.', '3', '.', '1', 0x00 }, + .version = "2.0.3.1", + .checksum = 0x20a0081e, + }, + }) |case| { + const report = firmwareReportFor(case.model, case.which).?; + const parsed = try parseFirmwareReport(report, case.raw); + try std.testing.expectEqualStrings(case.version, parsed.version); + try std.testing.expectEqual(case.checksum, parsed.checksum); + } +} + +test "the Plus reports the same firmware in both application slots" { + // Its AP1 and AP2 reports are byte for byte identical -- same + // version, same checksum -- which is what the two slots holding + // the same image looks like, and is why one device alone cannot + // say whether the checksum covers the image or the string. + const ap2 = [_]u8{ 0x05, 0x0c, 0x1e, 0x08, 0xa0, 0x20, '2', '.', '0', '.', '3', '.', '1', 0x00 }; + const ap1 = [_]u8{ 0x07, 0x0c, 0x1e, 0x08, 0xa0, 0x20, '2', '.', '0', '.', '3', '.', '1', 0x00 }; + + const a = try parseFirmwareReport( + firmwareReportFor(.ElgatoStreamDeckPlus, .ap2).?, + &ap2, + ); + const b = try parseFirmwareReport( + firmwareReportFor(.ElgatoStreamDeckPlus, .ap1).?, + &ap1, + ); + try std.testing.expectEqualStrings(a.version, b.version); + try std.testing.expectEqual(a.checksum, b.checksum); +} + +test "a firmware report shorter than its own layout is refused" { + const report = firmwareReportFor(.ElgatoStreamDeckPlus, .ap2).?; + // Nothing at all, and a report cut off inside the checksum. + try std.testing.expectError(error.ShortReport, parseFirmwareReport(report, &.{})); + try std.testing.expectError( + error.ShortReport, + parseFirmwareReport(report, &.{ 0x05, 0x0c, 0x1e, 0x08 }), + ); +} + +test sleepTimeoutReport { + var buf: [32]u8 = undefined; + + // The newer protocol: report 0x03, command 0x0d, then the seconds + // little-endian. 3600 is 0x00000e10. + try std.testing.expectEqualSlices( + u8, + &.{ 0x03, 0x0d, 0x10, 0x0e, 0x00, 0x00 }, + try sleepTimeoutReport(.ElgatoStreamDeckPlus, 3600, &buf), + ); + + // Zero is what disables it, and is not a special encoding. + try std.testing.expectEqualSlices( + u8, + &.{ 0x03, 0x0d, 0x00, 0x00, 0x00, 0x00 }, + try sleepTimeoutReport(.ElgatoStreamDeckNeo, 0, &buf), + ); + + // The older protocol carries the same field behind a different + // report and command. + try std.testing.expectEqualSlices( + u8, + &.{ 0x0b, 0xa2, 0x78, 0x00, 0x00, 0x00 }, + try sleepTimeoutReport(.ElgatoStreamDeckMini, 120, &buf), + ); + + // The largest a `u31` can ask for still fits the field without + // becoming negative, which is what makes the narrowing in + // `getSleepTimeout` safe. + const most = try sleepTimeoutReport(.ElgatoStreamDeckPlus, std.math.maxInt(u31), &buf); + try std.testing.expectEqual( + @as(i32, std.math.maxInt(u31)), + std.mem.readInt(i32, most[2..6], .little), + ); +} + +test sleepTimeoutQuery { + // The two protocols answer on different reports, and the newer + // one's number would be a firmware version on the older. + try std.testing.expectEqual(0x0a, sleepTimeoutQuery(.ElgatoStreamDeckPlus)); + try std.testing.expectEqual(0xa3, sleepTimeoutQuery(.ElgatoStreamDeckMini)); + + inline for (std.meta.fields(Type)) |f| { + const t: Type = @enumFromInt(f.value); + const query = sleepTimeoutQuery(t); + // Whatever it is, it has to be a report this library does not + // use for something else. + try std.testing.expect(query != t.serialReport().id); + try std.testing.expect(query != t.firmwareReport().id); + } +} + /// Read a string-valued feature report into `buffer` and return the /// part of it that holds the string. `buffer` is used for the report /// itself, so it has to be at least `report.len` bytes; anything @@ -372,6 +1062,9 @@ fn readStringReport(self: *const StreamDeck, io: std.Io, buffer: []u8, report: T /// Read the serial number into `buffer` and return the part of it that /// holds the number, under the rules of `readStringReport`. pub fn getSerialNumber(self: *const StreamDeck, io: std.Io, buffer: []u8) ![]const u8 { + if (self.device.tcp()) |connection| { + if (connection.primary) return connection.serialNumber(io, buffer); + } return self.readStringReport(io, buffer, self.type.serialReport()); } @@ -379,12 +1072,15 @@ pub fn getSerialNumber(self: *const StreamDeck, io: std.Io, buffer: []u8) ![]con /// result and must free it with `alloc`. pub fn getSerialNumberAlloc(self: *const StreamDeck, io: std.Io, alloc: std.mem.Allocator) ![]const u8 { var buffer: [32]u8 = undefined; - return try alloc.dupe(u8, try self.readStringReport(io, &buffer, self.type.serialReport())); + return try alloc.dupe(u8, try self.getSerialNumber(io, &buffer)); } /// Read the firmware version into `buffer` and return the part of it /// that holds the version, under the rules of `readStringReport`. pub fn getFirmwareVersion(self: *const StreamDeck, io: std.Io, buffer: []u8) ![]const u8 { + if (self.device.tcp()) |connection| { + if (connection.primary) return connection.firmwareVersion(io, buffer); + } return self.readStringReport(io, buffer, self.type.firmwareReport()); } @@ -392,7 +1088,7 @@ pub fn getFirmwareVersion(self: *const StreamDeck, io: std.Io, buffer: []u8) ![] /// the result and must free it with `alloc`. pub fn getFirmwareVersionAlloc(self: *const StreamDeck, io: std.Io, alloc: std.mem.Allocator) ![]const u8 { var buffer: [32]u8 = undefined; - return try alloc.dupe(u8, try self.readStringReport(io, &buffer, self.type.firmwareReport())); + return try alloc.dupe(u8, try self.getFirmwareVersion(io, &buffer)); } test "the vendor and product ids round-trip through the enum value" { @@ -406,15 +1102,27 @@ test "the vendor and product ids round-trip through the enum value" { } } -test "every model is Elgato's, and no two share a product id" { +test "every model is Elgato's but one, and no two share a product id" { + // Corsair owns Elgato and builds a Stream Deck panel into one of + // its keyboards, which reports Corsair's vendor id. Everything else + // is Elgato's own. inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); - try std.testing.expectEqual(0x0fd9, t.vendor()); + const expected: u16 = switch (t) { + .CorsairGalleonK100 => 0x1b1c, + else => 0x0fd9, + }; + try std.testing.expectEqual(expected, t.vendor()); } // The enum value is the vendor and product together, so Zig has // already rejected a duplicate pair at compile time. This says so // out loud, and checks the product ids alone for good measure. + // + // Every model is compared with every other, so the work here grows + // as the square of the table and the default comptime budget does + // not cover it. + @setEvalBranchQuota(10_000); inline for (std.meta.fields(Type)) |a| { inline for (std.meta.fields(Type)) |b| { if (comptime std.mem.eql(u8, a.name, b.name)) continue; @@ -464,8 +1172,8 @@ test "a module speaks the same protocol as the model it is built from" { try std.testing.expectEqual(base.generation(), module.generation()); try std.testing.expectEqual(base.firmwareReport(), module.firmwareReport()); - var m: StreamDeck = .{ .type = module, .device = undefined }; - var b: StreamDeck = .{ .type = base, .device = undefined }; + var m: StreamDeck = .{ .type = module, .device = .none }; + var b: StreamDeck = .{ .type = base, .device = .none }; try std.testing.expectEqual(b.keys.count(), m.keys.count()); try std.testing.expectEqual(b.keys.getFeature(0), m.keys.getFeature(0)); try std.testing.expectEqual(b.events.readSize(), m.events.readSize()); @@ -524,7 +1232,7 @@ test "only the Original takes an oversized image report" { test "a report leaves room for the header of every key it has" { inline for (std.meta.fields(Type)) |f| { const t: Type = @enumFromInt(f.value); - var sd: StreamDeck = .{ .type = t, .device = undefined }; + var sd: StreamDeck = .{ .type = t, .device = .none }; for (0..sd.keys.count()) |key| { const feature = sd.keys.getImageFeature(@intCast(key)) orelse continue; diff --git a/src/Tcp.zig b/src/Tcp.zig new file mode 100644 index 0000000..a25047f --- /dev/null +++ b/src/Tcp.zig @@ -0,0 +1,680 @@ +// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! A Stream Deck reached over the network rather than over USB: the +//! open socket, which of the two framings it turned out to speak, and +//! the buffer partly-arrived frames accumulate in. +//! +//! This is the half of the TCP transport that touches a socket. +//! Everything that turns bytes into a structure and back is in +//! `framing.zig`, which needs no socket and is tested and fuzzed +//! without one. +//! +//! ## The caller has to keep reading +//! +//! A networked device pings every few seconds and disconnects a host +//! that has not answered within about five. Answering happens here, but +//! only while something is reading: inside `read`, and inside the +//! request half of any host command. Nothing runs on its own -- there +//! is no background task and no thread -- so a caller that neither +//! reads events nor asks the device anything for five seconds will be +//! dropped. +//! +//! That is a real constraint and not an oversight. The alternative is a +//! task owning the socket, with a queue and a lock between it and the +//! caller, which is a great deal of machinery for a library that +//! otherwise has none. An application that is doing anything with a +//! Stream Deck is sitting in `Events.read` anyway, which services the +//! socket; one that spends five seconds drawing without reading has to +//! say so. + +const std = @import("std"); + +const Tcp = @This(); + +const framing = @import("framing.zig"); +const Keys = @import("Keys.zig"); +const StreamDeck = @import("StreamDeck.zig"); + +/// The port a Stream Deck listens on. +pub const default_port: u16 = 5343; + +/// How long without a word from the device before it is presumed gone. +/// +/// The device's own ping interval is not documented and the sources +/// that guess put it between two and a half and four seconds, so five +/// is what the reference implementation waits and five is what this +/// waits. +pub const timeout_ns: u64 = 5 * std.time.ns_per_s; + +/// How much of a partly-arrived frame can be held. +/// +/// A frame is a header and at most `framing.max_payload`, and there can +/// be the tail of one and the head of the next, so this is comfortably +/// more than one of the largest frames either side sends. +const buffer_size = 2 * (framing.header_size + framing.max_payload); + +/// How big an acknowledgement and a host request are made. +/// +/// Implementations send 32 bytes and 1024 bytes for these and both are +/// reported to work, so the device does not care. 32 is the smaller. +const command_size = 32; + +/// What can go wrong that is this transport's own, rather than the +/// socket's. +/// The product id a Stream Deck Network Dock reports over the network. +/// +/// It is not a USB id: the dock is not a USB device and was never +/// assigned one, so this is Elgato's own stand-in. Nothing here can +/// drive a dock yet -- the decks are behind it, on connections of their +/// own -- but recognising the id is what lets one be turned away with +/// an answer rather than with "not a Stream Deck". +pub const network_dock_product: u16 = 0xffff; + +pub const Error = error{ + /// The device sent something that is neither framing. + NotAStreamDeck, + /// A Stream Deck Network Dock answered. It is a real device and + /// this is a real connection to it, but the decks it carries are + /// reached through further connections that this library does not + /// open yet. + NetworkDockUnsupported, + /// The connection was closed, by the device or by the network. + Disconnected, + /// The device did not answer a question it was asked. + NoResponse, + /// The operation has no known encoding on this transport. `reset` + /// is the one: no implementation has ever been seen to perform it + /// over the network, so this library will not invent an encoding + /// for it. + Unsupported, +}; + +alloc: std.mem.Allocator, +stream: std.Io.net.Stream, +/// Which framing the device speaks, once it has said enough for that +/// to be known. Null until then. +framing_mode: ?framing.Framing = null, +/// Bytes received from the socket and not yet consumed by a frame. +buffer: [buffer_size]u8 = undefined, +len: usize = 0, +/// The payload most recently taken off the wire, copied out of +/// `buffer` so that consuming the frame around it cannot disturb it. +payload: [framing.max_payload]u8 = undefined, +/// Whether this connection answers host commands -- a Studio, or a +/// dock itself -- as opposed to being a device behind a dock, which +/// answers ordinary USB feature reports instead. +primary: bool = false, +/// What the device said it is, once `identity` has been asked. +vendor: u16 = 0, +product: u16 = 0, +/// Counts up so that a reply can be matched to its request. The device +/// echoes whatever it is sent, so only distinctness matters. +next_message_id: u32 = 1, + +/// Open a connection to a Stream Deck and bring it up: classify the +/// framing it speaks, answer its first keepalive, and ask it what it +/// is. +/// +/// The caller owns the result and must release it with `close`. +pub fn connect(io: std.Io, alloc: std.mem.Allocator, address: std.Io.net.IpAddress) !*Tcp { + // `ConnectOptions` has a `timeout`, and it would be the right thing + // here -- the usual way to get an address wrong is to give one with + // nothing at it, and waiting for the operating system to give up on + // a silently dropped packet takes minutes. It cannot be used on Zig + // 0.16.0: `Io.Threaded.netConnectIpPosix` answers any timeout but + // `.none` with `@panic("TODO implement netConnectIpPosix with + // timeout")`, so asking for one is a crash rather than a wait. + // + // So this waits as long as the operating system does, and a caller + // that needs to bound it has to bound the whole call. Worth + // revisiting whenever the toolchain moves. + const stream = try address.connect(io, .{ .mode = .stream }); + errdefer stream.close(io); + + const self = try alloc.create(Tcp); + errdefer alloc.destroy(self); + + self.* = .{ .alloc = alloc, .stream = stream }; + self.setNoDelay(); + + // The device speaks first, and what it opens with is what says + // which framing it uses. Until one whole frame has been taken off + // the wire nothing can be sent, because there is no way to know how + // to wrap it. + const first = try self.receive(io); + + // A device opens with a keepalive probe. Answering it is what makes + // the connection live, so it is done here rather than left for + // whenever the caller first reads. + if (framing.isKeepaliveProbe(first)) try self.acknowledge(io, first); + + try self.identify(io); + return self; +} + +/// Ask the device its vendor and product id, and learn from the answer +/// whether this is a connection that speaks host commands at all. +fn identify(self: *Tcp, io: std.Io) !void { + var buf: [command_size]u8 = undefined; + // This is the one question every device reached directly answers, + // and asking it is how a connection turns into a model. + // + // A device reached *through* a dock would not answer it -- those + // take ordinary USB feature reports and know nothing of this + // namespace -- and since there is no read timeout to be had (see + // the note in `connect`), connecting to one waits rather than + // failing. That is a real rough edge, and it is bounded by the fact + // that nothing hands out a child's address: a dock is refused + // below, and its children are reached through a table this library + // does not read yet. + const reply = self.hostCommand(io, .identity, &buf) catch |err| switch (err) { + error.NoResponse => return error.Unsupported, + else => |e| return e, + }; + + const id = framing.parseIdentity(reply) orelse return error.NotAStreamDeck; + + // A dock answers this perfectly well; what it has not got is any + // keys. Saying so beats letting the model lookup below call it "not + // a Stream Deck", which it plainly is. + if (id.product == network_dock_product) return error.NetworkDockUnsupported; + + self.vendor = id.vendor; + self.product = id.product; + self.primary = true; +} + +/// Turn off Nagle's algorithm. +/// +/// Image data goes out as a run of one kilobyte packets, and coalescing +/// them costs a round trip apiece. `std.Io.net` exposes no socket +/// options, so this reaches for the handle directly and shrugs if the +/// platform will not have it -- it is throughput and not correctness. +fn setNoDelay(self: *Tcp) void { + std.posix.setsockopt( + self.stream.socket.handle, + std.posix.IPPROTO.TCP, + std.posix.TCP.NODELAY, + &std.mem.toBytes(@as(c_int, 1)), + ) catch {}; +} + +/// Close the connection and free this `Tcp`. Nothing may be used +/// afterwards. +pub fn close(self: *Tcp, io: std.Io) void { + self.stream.close(io); + self.alloc.destroy(self); +} + +/// Read more bytes from the socket into the buffer. +/// +/// The reader is given the free tail of `buffer` as its own buffer, so +/// what it reads lands where it is wanted with no second copy. +fn fill(self: *Tcp, io: std.Io) !void { + if (self.len >= self.buffer.len) { + // Nothing legitimate is this big -- `framing.max_payload` + // bounds a frame and the buffer holds two of them -- so a full + // buffer means the stream holds something that is not a frame. + return error.NotAStreamDeck; + } + + var reader = self.stream.reader(io, self.buffer[self.len..]); + reader.interface.fill(1) catch return error.Disconnected; + self.len += reader.interface.bufferedLen(); +} + +/// Drop the first `n` bytes of the buffer. +fn drop(self: *Tcp, n: usize) void { + std.debug.assert(n <= self.len); + std.mem.copyForwards(u8, self.buffer[0 .. self.len - n], self.buffer[n..self.len]); + self.len -= n; +} + +/// Take one payload off the wire, whichever framing this device +/// speaks, reading more as it takes to get a whole one. +/// +/// The result points into `payload` and is good only until the next +/// call. +fn receive(self: *Tcp, io: std.Io) ![]const u8 { + while (true) { + if (self.framing_mode) |mode| switch (mode) { + .cora => { + if (try framing.decode(self.buffer[0..self.len])) |frame| { + const n = frame.payload.len; + @memcpy(self.payload[0..n], frame.payload); + self.drop(frame.consumed); + return self.payload[0..n]; + } + }, + .legacy => { + // No header: a frame is however many bytes a frame is, + // and what it means is decided by its first bytes. + if (self.len >= framing.legacy_recv_size) { + const n = framing.legacy_recv_size; + @memcpy(self.payload[0..n], self.buffer[0..n]); + self.drop(n); + return self.payload[0..n]; + } + }, + } else { + // `classify` says null while what has arrived so far is + // still consistent with either framing. + if (try framing.classify(self.buffer[0..self.len])) |mode| { + self.framing_mode = mode; + continue; + } + } + + try self.fill(io); + } +} + +/// Send one payload, wrapped however this device expects. +fn send(self: *Tcp, io: std.Io, flags: u16, op: framing.HidOp, payload: []const u8) !void { + switch (self.framing_mode orelse return error.NotAStreamDeck) { + .cora => { + var buf: [framing.header_size + framing.max_payload]u8 = undefined; + const message_id = self.next_message_id; + self.next_message_id +%= 1; + const bytes = try framing.encode(&buf, flags, op, message_id, payload); + try self.writeAll(io, bytes); + }, + .legacy => { + // No header, and every frame is the same size whatever it + // carries, so a short payload is padded out. + if (payload.len > framing.legacy_send_size) return error.BufferTooSmall; + var buf = std.mem.zeroes([framing.legacy_send_size]u8); + @memcpy(buf[0..payload.len], payload); + try self.writeAll(io, &buf); + }, + } +} + +fn writeAll(self: *Tcp, io: std.Io, bytes: []const u8) !void { + var buf: [64]u8 = undefined; + var writer = self.stream.writer(io, &buf); + writer.interface.writeAll(bytes) catch return error.Disconnected; + writer.interface.flush() catch return error.Disconnected; +} + +/// Answer a keepalive probe, quoting back the connection number it +/// carried. A device serves several clients at once and tells them +/// apart by that number. +fn acknowledge(self: *Tcp, io: std.Io, probe: []const u8) !void { + var buf: [command_size]u8 = undefined; + const ack = try framing.keepaliveAck(&buf, probe); + // `ack_nak` echoes nothing useful in legacy framing, where there is + // no header to carry it, and is ignored there. + try self.send(io, framing.Flags.ack_nak, .write, ack); +} + +/// Take payloads off the wire until one is something the caller wants, +/// answering keepalives and discarding notifications on the way. +/// +/// Without this filter a keepalive would reach `Events.decode`, which +/// would read its `0x01` as an input report and its `0x0a` as a control +/// type it has never heard of, several times a second. +fn pump(self: *Tcp, io: std.Io, want: enum { input, reply }) ![]const u8 { + while (true) { + const payload = try self.receive(io); + + if (framing.isKeepaliveProbe(payload)) { + try self.acknowledge(io, payload); + continue; + } + + // A dock saying something was plugged in or pulled out. Driving + // a device behind a dock is not implemented, so there is + // nothing to do with it yet -- but it must not be mistaken for + // an input report. + if (framing.isChildNotification(payload)) continue; + + switch (want) { + .input => if (framing.isInputReport(payload)) return payload, + // Anything that is not an input report is an answer to + // something that was asked. This is deliberately not "a + // payload beginning 0x03": that is the shape of a host + // command reply, but a verbatim `get_report` -- what a + // device behind a dock answers -- comes back as a raw HID + // feature report whose first byte is the report id. Waiting + // for 0x03 would wait forever for one of those. + .reply => if (payload.len > 0 and !framing.isInputReport(payload)) return payload, + } + } +} + +/// Ask the device a host command and return its reply payload. +/// +/// The reply points into this `Tcp`'s buffer and is good only until the +/// next read. +pub fn hostCommand(self: *Tcp, io: std.Io, command: framing.HostCommand, buf: []u8) ![]const u8 { + const request = try framing.hostRequest(buf, command); + try self.send(io, framing.Flags.none, .get_report, request); + + // A device answers the question it was asked; anything else on the + // wire in the meantime is somebody else's business and is handled + // by `pump`. A reply to a different command means this one went + // unanswered. + const payload = try self.pump(io, .reply); + if (payload.len < 2 or payload[1] != @intFromEnum(command)) return error.NoResponse; + return payload; +} + +/// Read a string-valued host command into `buf` and return the part of +/// it that holds the string. +fn hostString(self: *Tcp, io: std.Io, command: framing.HostCommand, buf: []u8) ![]const u8 { + var request: [command_size]u8 = undefined; + const payload = try self.hostCommand(io, command, &request); + const reply = framing.HostReply.parse(payload) orelse return error.NoResponse; + const string = framing.replyString(reply); + + if (buf.len < string.len) return error.BufferTooSmall; + @memcpy(buf[0..string.len], string); + return buf[0..string.len]; +} + +/// The device's serial number. +/// +/// Over USB this is a feature report; here it is a host command, which +/// is the one place the two transports genuinely disagree about how to +/// ask the same question. +pub fn serialNumber(self: *Tcp, io: std.Io, buf: []u8) ![]const u8 { + return self.hostString(io, .serial, buf); +} + +/// The device's firmware version. +pub fn firmwareVersion(self: *Tcp, io: std.Io, buf: []u8) ![]const u8 { + return self.hostString(io, .firmware, buf); +} + +/// Write an output report: a page of a key image, or a command that +/// takes no answer. +/// +/// The bytes are exactly what would go to a USB device, and they are +/// not re-chunked on the way -- the same kilobyte packets with the same +/// headers cross the network unchanged, which is what lets `Keys` and +/// `Touchscreen` stay entirely unaware of which transport they are +/// driving. +pub fn write(self: *Tcp, io: std.Io, buf: []const u8) !usize { + try self.send(io, framing.Flags.verbatim, .write, buf); + return buf.len; +} + +/// Send a feature report. Verbatim, so brightness and touch key colour +/// go out as the very same bytes a USB device would be sent. +pub fn sendFeatureReport(self: *Tcp, io: std.Io, data: []const u8) !usize { + try self.send(io, framing.Flags.verbatim, .send_report, data); + return data.len; +} + +/// Read a feature report. `buf[0]` names the report wanted, as it does +/// over USB. +/// +/// This is the verbatim path, which is right for a device behind a dock +/// and wrong for one reached directly -- a Studio answers questions +/// about itself through host commands instead. `StreamDeck` is what +/// knows the difference; see `serialNumber` above. +pub fn getFeatureReport(self: *Tcp, io: std.Io, buf: []u8) ![]const u8 { + if (buf.len == 0) return error.BufferTooSmall; + try self.send(io, framing.Flags.verbatim, .get_report, buf[0..1]); + + const payload = try self.pump(io, .reply); + const n = @min(buf.len, payload.len); + @memcpy(buf[0..n], payload[0..n]); + return buf[0..n]; +} + +/// Wait for an input report and copy it into `buf`. +/// +/// Keepalives are answered while waiting, which is what keeps the +/// connection alive at all; see the note at the top of this file about +/// what that asks of the caller. +pub fn read(self: *Tcp, io: std.Io, buf: []u8) ![]const u8 { + const payload = try self.pump(io, .input); + const n = @min(buf.len, payload.len); + @memcpy(buf[0..n], payload[0..n]); + return buf[0..n]; +} + +test { + std.testing.refAllDecls(@This()); +} + +/// A Stream Deck Studio, played by a socket on the loopback interface. +/// +/// This is enough of a device to bring a connection up and take an +/// image: it opens with a keepalive probe as a real one does, answers +/// the two questions `connect` asks, and records every verbatim write +/// it is sent so that the test can check what actually crossed the +/// wire. +const FakeDeck = struct { + server: std.Io.net.Server, + /// What the client wrote, concatenated. Image pages land here. + written: std.ArrayList(u8) = .empty, + /// Whether the keepalive probe was acknowledged, and with the right + /// connection number. + acknowledged: bool = false, + alloc: std.mem.Allocator, + + /// The connection number the probe carries. Quoting back something + /// else would be answering on another client's behalf, so the test + /// checks for this exact value. + const connection: u8 = 0x2a; + + fn address(self: *const FakeDeck) std.Io.net.IpAddress { + return self.server.socket.address; + } + + /// Wrap a payload in a `cora` frame and send it. + fn sendFrame(stream: std.Io.net.Stream, io: std.Io, flags: u16, payload: []const u8) !void { + var frame: [framing.header_size + 256]u8 = undefined; + const bytes = try framing.encode(&frame, flags, .get_report, 1, payload); + + var buf: [64]u8 = undefined; + var writer = stream.writer(io, &buf); + try writer.interface.writeAll(bytes); + try writer.interface.flush(); + } + + /// Take one whole frame off the wire. + fn recv(stream: std.Io.net.Stream, io: std.Io, buf: []u8, len: *usize) !framing.Frame { + while (true) { + if (try framing.decode(buf[0..len.*])) |frame| return frame; + + var reader = stream.reader(io, buf[len.*..]); + try reader.interface.fill(1); + len.* += reader.interface.bufferedLen(); + } + } + + /// Run the device until the client hangs up. + fn run(self: *FakeDeck, io: std.Io) void { + self.serve(io) catch {}; + } + + fn serve(self: *FakeDeck, io: std.Io) !void { + const stream = try self.server.accept(io); + defer stream.close(io); + + // A real device speaks first, and what it opens with is what + // tells the client which framing to use. + var probe = std.mem.zeroes([8]u8); + probe[0] = 0x01; + probe[1] = 0x0a; + probe[5] = connection; + try sendFrame(stream, io, framing.Flags.none, &probe); + + var buf: [4096]u8 = undefined; + var len: usize = 0; + + while (true) { + const frame = recv(stream, io, &buf, &len) catch return; + const payload = frame.payload; + + if (payload.len >= 3 and payload[0] == 0x03 and payload[1] == 0x1a) { + self.acknowledged = payload[2] == connection; + } else if (frame.header.flags & framing.Flags.verbatim != 0) { + if (frame.header.hid_op == @intFromEnum(framing.HidOp.write)) { + try self.written.appendSlice(self.alloc, payload); + } + } else if (payload.len >= 2 and payload[0] == 0x03) { + try self.answer(stream, io, payload[1]); + } + + // `recv` leaves the rest of the buffer behind it. + const rest = buf[frame.consumed..len]; + std.mem.copyForwards(u8, buf[0..rest.len], rest); + len = rest.len; + } + } + + fn answer(self: *FakeDeck, stream: std.Io.net.Stream, io: std.Io, command: u8) !void { + _ = self; + switch (command) { + // Identity: a Studio's vendor and product id, at the fixed + // offsets the reply carries them at. + 0x80 => { + var reply = std.mem.zeroes([16]u8); + reply[0] = 0x03; + reply[1] = 0x80; + std.mem.writeInt(u16, reply[12..14], 0x0fd9, .little); + std.mem.writeInt(u16, reply[14..16], 0x00aa, .little); + try sendFrame(stream, io, framing.Flags.result, &reply); + }, + // Serial number, whose length is big-endian. + 0x84 => { + var reply = std.mem.zeroes([16]u8); + reply[0] = 0x03; + reply[1] = 0x84; + std.mem.writeInt(u16, reply[2..4], 4, .big); + @memcpy(reply[4..8], "CL12"); + try sendFrame(stream, io, framing.Flags.result, &reply); + }, + else => {}, + } + } +}; + +test "a deck is brought up, identified and driven over a socket" { + const alloc = std.testing.allocator; + + // `std.testing.io` does not promise the concurrency this needs -- + // the device and the client both have to be making progress, or + // each waits for the other forever. `Io.Threaded` leaves + // `concurrent_limit` unlimited. + var threaded: std.Io.Threaded = .init(alloc, .{}); + defer threaded.deinit(); + const io = threaded.io(); + + const loopback: std.Io.net.IpAddress = .{ .ip4 = .loopback(0) }; + var deck: FakeDeck = .{ + // Port zero, so the kernel picks one nothing else is using. + .server = try loopback.listen(io, .{ .mode = .stream }), + .alloc = alloc, + }; + defer deck.server.deinit(io); + defer deck.written.deinit(alloc); + + var group: std.Io.Group = .init; + defer group.cancel(io); + try group.concurrent(io, FakeDeck.run, .{ &deck, io }); + + // Connecting classifies the framing, answers the first keepalive + // and asks the device what it is -- so a deck coming back at all + // means the whole handshake worked. + // Closed explicitly further down rather than with a `defer`: + // `close` frees the connection, so closing twice is a use after + // free, and the device has to be let go before what it recorded is + // read. + const sd = try StreamDeck.connect(io, alloc, deck.address()); + + try std.testing.expectEqual(StreamDeck.Type.ElgatoStreamDeckStudio, sd.type); + + // The serial number comes from a host command rather than the USB + // feature report, and its length is the one big-endian field in the + // protocol. + var serial_buf: [32]u8 = undefined; + try std.testing.expectEqualStrings("CL12", try sd.getSerialNumber(io, &serial_buf)); + + // Resetting has no known encoding here, and is refused rather than + // guessed at. + try std.testing.expectError(error.Unsupported, sd.reset(io)); + + // Now the claim this whole design rests on: an image sent over the + // network is byte for byte the one that would have gone over USB. + const key = 0; + var surface = (try sd.keys.blankImage(alloc, key)).?; + defer surface.deinit(alloc); + + // Noise, so that the JPEG of it is too big for one packet and the + // image is actually paged. A blank key encodes to a few hundred + // bytes and would cross in a single write, which would leave the + // paging untested -- and paging is where a transport that + // re-chunked would show itself. + var prng: std.Random.DefaultPrng = .init(0x5715_dec4); + const random = prng.random(); + for (0..@intCast(surface.getHeight())) |y| { + for (0..@intCast(surface.getWidth())) |x| { + surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ + .r = random.int(u8), + .g = random.int(u8), + .b = random.int(u8), + } }); + } + } + + try sd.keys.setImage(io, alloc, key, surface); + + // Let the device finish reading before looking at what it got. + sd.close(io, alloc); + group.await(io) catch {}; + + const feature = sd.keys.getImageFeature(key).?; + const encoded = try Keys.encodeImage(alloc, surface, feature); + defer alloc.free(encoded); + + const report = sd.type.imageReport(); + const max = report.size - feature.header_format.headerSize(); + const pages = (encoded.len + max - 1) / max; + + // Every page is a whole report, padded, exactly as the USB path + // writes them -- not re-chunked to fit the network. A single page + // would make the rest of this vacuous, so check there were several. + try std.testing.expect(pages > 1); + try std.testing.expectEqual(pages * report.size, deck.written.items.len); + + // Take the pages apart again and reassemble the image out of them. + // If anything had been re-chunked, re-headered or dropped on the + // way across, this is what would not come back. + const header_len = feature.header_format.headerSize(); + var rebuilt: std.ArrayList(u8) = .empty; + defer rebuilt.deinit(alloc); + + for (0..pages) |page| { + const packet = deck.written.items[page * report.size ..][0..report.size]; + + // The v2 key image header, with this key's index and this + // page's number on it. + try std.testing.expectEqual(@as(u8, 0x02), packet[0]); + try std.testing.expectEqual(@as(u8, 0x07), packet[1]); + try std.testing.expectEqual(@as(u8, key), packet[2]); + try std.testing.expectEqual( + @as(u16, @intCast(page)), + std.mem.readInt(u16, packet[6..8], .little), + ); + + // Only the last page is marked last. + const last = packet[3] == 1; + try std.testing.expectEqual(page == pages - 1, last); + + const page_len = std.mem.readInt(u16, packet[4..6], .little); + try std.testing.expect(page_len <= max); + try rebuilt.appendSlice(alloc, packet[header_len..][0..page_len]); + } + + try std.testing.expectEqualSlices(u8, encoded, rebuilt.items); + + // The keepalive was answered, quoting the right connection number. + try std.testing.expect(deck.acknowledged); +} diff --git a/src/Touchscreen.zig b/src/Touchscreen.zig index 751a16c..4c37ae5 100644 --- a/src/Touchscreen.zig +++ b/src/Touchscreen.zig @@ -113,6 +113,9 @@ pub const report_size = 10; pub fn readSize(self: *const Touchscreen) usize { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("touchscreen", self)); return switch (sd.type) { + // Its screen takes partial writes the way the Plus's does, so + // it is assumed to report touches the same way. Unverified. + .CorsairGalleonK100 => report_size, .ElgatoStreamDeckMK2 => 0, .ElgatoStreamDeckMK2Scissor => 0, .ElgatoStreamDeckMini => 0, @@ -176,6 +179,18 @@ pub fn getFeature(self: *const Touchscreen) ?TouchScreenFeature { const sd: *const StreamDeck = @alignCast(@fieldParentPtr("touchscreen", self)); return switch (sd.type) { + // 720x384, filling the top of a portrait panel above the keys. + // One source only, and no hardware. + .CorsairGalleonK100 => .{ + .header_format = .v3, + .image_format = .JPEG, + .width = 720, + .height = 384, + .rotation = null, + .flip_left_right = false, + .flip_top_bottom = false, + .touch = true, + }, .ElgatoStreamDeckPlus => .{ .header_format = .v3, .image_format = .JPEG, @@ -332,7 +347,7 @@ fn writeImage(self: *const Touchscreen, io: std.Io, x: u16, y: u16, width: u16, /// 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 = undefined }; + return .{ .type = t, .device = .none }; } test getFeature { @@ -566,7 +581,7 @@ test "encoding a screen image cleans up after a failed allocation" { }) |t| { try std.testing.checkAllAllocationFailures(std.testing.allocator, struct { fn run(alloc: std.mem.Allocator) !void { - var sd: StreamDeck = .{ .type = t, .device = undefined }; + var sd: StreamDeck = .{ .type = t, .device = .none }; const feature = sd.touchscreen.getFeature().?; var surface = (try sd.touchscreen.blankImage(alloc)).?; diff --git a/src/Transport.zig b/src/Transport.zig new file mode 100644 index 0000000..800ea7b --- /dev/null +++ b/src/Transport.zig @@ -0,0 +1,199 @@ +// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! How a `StreamDeck` reaches the device it drives. +//! +//! There are two ways: a HID device, which is every model that plugs +//! into USB, and a TCP connection, which is the Studio and the Network +//! Dock. Both carry the very same HID reports, +//! so everything above this -- the key tables, the image paging, the +//! event decoding -- is written once and does not know which it is +//! talking to. +//! +//! The four verbs below are the whole of what the rest of the library +//! asks of a device. That the list is this short is why a second +//! transport was worth adding at all. +//! +//! ## Why a union and not a vtable +//! +//! Most of this library is decided by which model a device is rather +//! than by what is behind it, and all of that can be tested with no +//! device at all -- which the tests do, by building a `StreamDeck` +//! whose transport is `.none`. A vtable would make that a pointer +//! nobody set, and calling through it a jump into nowhere; a union tag +//! is checked by the switch, and `.none` answers every call with +//! `error.NoTransport`. + +const std = @import("std"); + +const hidapi = @import("hidapi"); + +const Tcp = @import("Tcp.zig"); + +const Transport = @This(); + +/// No device at all. +/// +/// This is what the tests use for the parts of the library that never +/// touch the hardware, and what a `StreamDeck` describing a model +/// rather than driving one carries. Every operation on it fails. +pub const none: Transport = .{ .value = .{ .none = {} } }; + +pub const Kind = enum { none, hid, tcp }; + +value: Value, + +pub const Value = union(Kind) { + none: void, + /// An open HID device: every model that plugs into USB. Held by + /// pointer because `hidapi.Device` is opened in place and every + /// operation on it takes a mutable pointer, so it has to stay put. + /// Owned by this transport and released by `close`. + hid: *hidapi.Device, + /// An open TCP connection: the Studio and the Network Dock. Owned + /// by this transport and released by `close`. + tcp: *Tcp, +}; + +/// Build a transport over an open HID device, taking ownership of it. +pub fn fromHid(device: *hidapi.Device) Transport { + return .{ .value = .{ .hid = device } }; +} + +/// Build a transport over an open TCP connection, taking ownership of +/// it. +pub fn fromTcp(connection: *Tcp) Transport { + return .{ .value = .{ .tcp = connection } }; +} + +/// Which kind of transport this is. `StreamDeck` asks, because a +/// handful of operations genuinely differ between the two -- reading +/// the serial number is one. +pub fn kind(self: Transport) Kind { + return std.meta.activeTag(self.value); +} + +/// The TCP connection behind this transport, or null if it is not one. +pub fn tcp(self: Transport) ?*Tcp { + return switch (self.value) { + .tcp => |t| t, + else => null, + }; +} + +/// The HID device behind this transport, or null if it is not one. +/// +/// This exists for the few things that are meaningful only over USB, +/// which belong to a caller that knows it is driving a local device +/// rather than to this library. +pub fn hid(self: Transport) ?*hidapi.Device { + return switch (self.value) { + .hid => |d| d, + else => null, + }; +} + +/// Write an output report: a page of image data, or a command that +/// takes no answer. The first byte is the report id. +pub fn write(self: Transport, io: std.Io, buf: []const u8) !usize { + return switch (self.value) { + .none => error.NoTransport, + .hid => |d| d.write(io, buf), + .tcp => |t| t.write(io, buf), + }; +} + +/// Wait for an input report and copy it into `buf`. +/// +/// Both transports block until the device says something. Over TCP +/// this is also what answers the device's keepalives, so a caller that +/// stops reading for several seconds will be disconnected; see the note +/// at the top of `Tcp.zig`. +pub fn read(self: Transport, io: std.Io, buf: []u8) ![]const u8 { + return switch (self.value) { + .none => error.NoTransport, + .hid => |d| d.read(io, buf), + .tcp => |t| t.read(io, buf), + }; +} + +/// Wait for an input report, giving up after `timeout`. Null means the +/// time ran out with nothing to report, which is not a failure. +/// +/// Only the HID transport can do this today: `hidapi` grew a timed read +/// and `std.Io.Threaded` has no read timeout to build one on for a +/// socket. The TCP transport answers `error.Unsupported` rather than +/// quietly waiting forever, which would be the worse answer. +pub fn readTimeout( + self: Transport, + io: std.Io, + buf: []u8, + timeout: std.Io.Timeout, +) !?[]const u8 { + return switch (self.value) { + .none => error.NoTransport, + .hid => |d| d.readTimeout(io, buf, timeout), + .tcp => error.Unsupported, + }; +} + +/// Send a feature report. The first byte is the report id. +pub fn sendFeatureReport(self: Transport, io: std.Io, data: []const u8) !usize { + return switch (self.value) { + .none => error.NoTransport, + .hid => |d| d.sendFeatureReport(io, data), + .tcp => |t| t.sendFeatureReport(io, data), + }; +} + +/// Read a feature report. `buf[0]` names the report wanted on the way +/// in, and the report is written over it on the way out. +pub fn getFeatureReport(self: Transport, io: std.Io, buf: []u8) ![]const u8 { + return switch (self.value) { + .none => error.NoTransport, + .hid => |d| d.getFeatureReport(io, buf), + .tcp => |t| t.getFeatureReport(io, buf), + }; +} + +/// Release the device, freeing whatever was allocated to hold it. +/// Nothing on this transport may be used afterwards. +/// +/// `alloc` has to be the one the device was opened with. A TCP +/// connection carries its own and ignores this, because it is reached +/// through a pointer it allocated itself; a HID device does not, so +/// this is where it is freed. +pub fn close(self: Transport, io: std.Io, alloc: std.mem.Allocator) void { + switch (self.value) { + .none => {}, + .hid => |d| { + d.close(io); + alloc.destroy(d); + }, + .tcp => |t| t.close(io), + } +} + +test none { + const io = std.testing.io; + + // A transport with nothing behind it answers rather than crashing, + // which is what makes it safe for the tests that describe a model + // without driving one. + var buf: [8]u8 = undefined; + try std.testing.expectEqual(Kind.none, none.kind()); + try std.testing.expectEqual(null, none.tcp()); + try std.testing.expectEqual(null, none.hid()); + try std.testing.expectError(error.NoTransport, none.write(io, &buf)); + try std.testing.expectError(error.NoTransport, none.read(io, &buf)); + try std.testing.expectError(error.NoTransport, none.sendFeatureReport(io, &buf)); + try std.testing.expectError(error.NoTransport, none.getFeatureReport(io, &buf)); + + // And closing one does nothing rather than dereferencing something + // that was never set. + none.close(io, std.testing.allocator); +} + +test { + std.testing.refAllDecls(@This()); +} diff --git a/src/devices.zig b/src/devices.zig index 51aff90..b43a520 100644 --- a/src/devices.zig +++ b/src/devices.zig @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT +pub const CorsairGalleonK100 = @import("devices/CorsairGalleonK100.zig"); pub const ElgatoStreamDeckMini = @import("devices/ElgatoStreamDeckMini.zig"); pub const ElgatoStreamDeckMiniMK2 = @import("devices/ElgatoStreamDeckMiniMK2.zig"); pub const ElgatoStreamDeckMK2 = @import("devices/ElgatoStreamDeckMK2.zig"); @@ -29,6 +30,7 @@ const StreamDeck = @import("StreamDeck.zig"); /// about all of them at once rather than naming them one at a time and /// silently missing the next one added. pub const all = &[_]type{ + CorsairGalleonK100, ElgatoStreamDeckMini, ElgatoStreamDeckMiniMK2, ElgatoStreamDeckMK2, diff --git a/src/devices/CorsairGalleonK100.zig b/src/devices/CorsairGalleonK100.zig new file mode 100644 index 0000000..fe016fe --- /dev/null +++ b/src/devices/CorsairGalleonK100.zig @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! The Corsair Galleon K100, a keyboard with a Stream Deck built into +//! it: twelve keys in a portrait block with a screen above them and two +//! encoders above that. +//! +//! It is the only device here that is not Elgato's. Corsair owns +//! Elgato, the panel speaks the same protocol as a Stream Deck of the +//! same generation, and Elgato's own SDK lists it among the Stream Deck +//! devices -- but it reports Corsair's USB vendor id, which is why +//! `StreamDeck.Type` can no longer assume one vendor. +//! +//! **It also has to be talked to or it stops listening.** See +//! `StreamDeck.keepAlive`. +//! +//! Nothing here has been run against hardware, and Elgato's HID +//! documentation does not cover this device; the numbers come from +//! node-elgato-stream-deck alone, which is one source where every other +//! model in this library has at least two. Treat it accordingly. +//! +//! `devices.zig` gathers this module together with the one for every +//! other model, so that the control groups can look up the properties +//! of whichever device they are attached to. + +const CorsairGalleonK100 = @This(); + +const KeyFeature = @import("../Keys.zig").KeyFeature; + +/// Corsair's vendor id, not Elgato's. +pub const vendor: u16 = 0x1b1c; +pub const product: u16 = 0x2b18; + +/// What this model's keys look like and what they can do. +pub const keys = struct { + /// The number of columns in the key grid. + pub const cols: u5 = 3; + /// The number of rows in the key grid. + pub const rows: u5 = 4; + /// The number of touch keys beyond the grid. This model has none. + pub const touch: u5 = 0; + /// The total number of keys, the grid and the touch keys together. + pub const count: u8 = @as(u8, cols) * rows + touch; + + /// What the given key is capable of, or null if this model has no + /// such key. Keys are numbered from zero. Every key displays a + /// JPEG image sent with a v2 header. + /// + /// The displays need no rotation and no flip, which is the one + /// thing about this model that a second source agrees on: the + /// driver in node-elgato-stream-deck asks for neither, the same as + /// it does for the Studio. + /// + /// These keys are much larger than any Stream Deck's -- 160 pixels + /// square, where the biggest elsewhere is 120 -- which is worth + /// noticing rather than assuming a typo. + pub fn getFeature(key: u8) ?KeyFeature { + switch (key) { + 0...11 => { + return .{ + .image = .{ + .header_format = .v2, + .image_format = .JPEG, + .width = 160, + .height = 160, + .rotation = null, + .flip_left_right = false, + .flip_top_bottom = false, + }, + }; + }, + else => return null, + } + } +}; diff --git a/src/devices/ElgatoStreamDeckMini.zig b/src/devices/ElgatoStreamDeckMini.zig index 4ac8fc6..bdd4f06 100644 --- a/src/devices/ElgatoStreamDeckMini.zig +++ b/src/devices/ElgatoStreamDeckMini.zig @@ -33,6 +33,23 @@ pub const keys = struct { /// such key. Keys are numbered from zero. Every key here displays a /// BMP image sent with a v1 header, turned a quarter turn first /// because the displays are mounted on their side. + /// + /// **Confirmed against the hardware.** The quarter turn and the + /// left/right flip below were settled by putting the same figure on + /// four keys under the four corrections a table can be wrong by and + /// looking at which one read correctly. What this library carried + /// before -- the same quarter turn with a top/bottom flip instead + /// -- was a half turn out, so every key image on a Mini came out + /// upside down. + /// + /// Elgato's HID documentation says to rotate ninety degrees + /// clockwise and says nothing about a flip, so this does what the + /// documentation says and one thing more. The likeliest reason is + /// that `bmp.zig` writes its rows bottom-up, as a BMP's have been + /// written since 1990, and the documentation does not say which row + /// order these devices expect -- but the two ways of writing this + /// transform are algebraically the same, so that explanation is a + /// reasonable guess rather than something the experiment showed. pub fn getFeature(key: u8) ?KeyFeature { switch (key) { 0...5 => { @@ -43,8 +60,8 @@ pub const keys = struct { .width = 80, .height = 80, .rotation = .@"90", - .flip_left_right = false, - .flip_top_bottom = true, + .flip_left_right = true, + .flip_top_bottom = false, }, }; }, diff --git a/src/devices/ElgatoStreamDeckMiniMK2.zig b/src/devices/ElgatoStreamDeckMiniMK2.zig index 4b81689..2f5337e 100644 --- a/src/devices/ElgatoStreamDeckMiniMK2.zig +++ b/src/devices/ElgatoStreamDeckMiniMK2.zig @@ -43,8 +43,8 @@ pub const keys = struct { .width = 80, .height = 80, .rotation = .@"90", - .flip_left_right = false, - .flip_top_bottom = true, + .flip_left_right = true, + .flip_top_bottom = false, }, }; }, diff --git a/src/devices/ElgatoStreamDeckPlusXL.zig b/src/devices/ElgatoStreamDeckPlusXL.zig index f07a92e..d3841c9 100644 --- a/src/devices/ElgatoStreamDeckPlusXL.zig +++ b/src/devices/ElgatoStreamDeckPlusXL.zig @@ -33,8 +33,20 @@ pub const keys = struct { /// What the given key is capable of, or null if this model has no /// such key. Keys are numbered from zero. Every key here displays - /// a JPEG image sent with a v2 header, and unlike most models the - /// displays need no rotation or flipping first. + /// a JPEG image sent with a v2 header. + /// + /// The displays are mounted a quarter turn round, so an image is + /// rotated ninety degrees **counterclockwise** on its way out -- + /// `.@"270"`, since the rotation here is named clockwise. Elgato's + /// HID documentation says so in as many words, for the keys and for + /// the screen alike, which settles a question the two reverse + /// engineered implementations could not: both agreed on a quarter + /// turn and disagreed about which way, and this library had it + /// turning the other way until the documentation was read. + /// + /// No hardware has confirmed it. The documentation is first-party + /// and unambiguous, which is better than this row had before, and + /// still not a measurement. pub fn getFeature(key: u8) ?KeyFeature { switch (key) { 0...35 => { @@ -44,7 +56,7 @@ pub const keys = struct { .image_format = .JPEG, .width = 112, .height = 112, - .rotation = .@"90", + .rotation = .@"270", .flip_left_right = false, .flip_top_bottom = false, }, diff --git a/src/framing.zig b/src/framing.zig new file mode 100644 index 0000000..e0ee115 --- /dev/null +++ b/src/framing.zig @@ -0,0 +1,594 @@ +// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! The framing a Stream Deck speaks over TCP, with the socket taken out +//! of it. +//! +//! A networked Stream Deck -- the Studio, and the Network Dock -- does +//! not speak a protocol of its own. It carries the very same USB HID +//! reports this library already builds, wrapped in one of two framings, +//! alongside a small set of commands that have no USB equivalent. So +//! what is here is only the wrapping and unwrapping: everything that +//! turns bytes into a structure and back, and nothing that touches a +//! socket. +//! +//! That split is the same one `Events.decode` and `Keys.encodeImage` +//! already make, and for the same reason. These bytes come from a +//! network peer, which is a good deal less trustworthy than a USB +//! device, and no device is needed to test or fuzz any of it. +//! +//! Elgato publishes nothing about this protocol. What follows was read +//! out of three independent reverse-engineered implementations, which +//! the README names; where they disagree, the comments say so. + +const std = @import("std"); + +/// Which of the two framings a device speaks. +/// +/// Which one a given device uses is not a thing that can be known in +/// advance -- it depends on the model and on the firmware, and no +/// source documents the cutover -- so it is decided by looking at the +/// first bytes the device sends. See `classify`. +pub const Framing = enum { + /// A sixteen byte header and a payload of the length it declares. + /// The Network Dock and newer Studio firmware. + cora, + /// No header at all: fixed size frames, a different size in each + /// direction. Original Studio firmware. + legacy, +}; + +/// The four bytes a `cora` frame begins with. +pub const magic = [4]u8{ 0x43, 0x93, 0x8a, 0x41 }; + +/// The size of a `cora` header, and so the smallest a frame can be. +pub const header_size = 16; + +/// How big a frame a device sends in `legacy` framing. The two +/// directions differ, which is the whole reason both constants exist. +pub const legacy_recv_size = 512; + +/// How big a frame a device expects in `legacy` framing. Anything +/// shorter is padded out to this with zeroes. +pub const legacy_send_size = 1024; + +/// The largest payload this library will accept in a `cora` header. +/// +/// The header declares its own payload length, so a peer can ask for +/// any size at all. Nothing legitimate is anywhere near this -- the +/// largest thing either side sends is a 1024 byte image packet -- so +/// this is only here to turn a wild length into an error rather than an +/// enormous read. +pub const max_payload = 4096; + +/// What a `cora` header's flag word can carry. +/// +/// `verbatim` is the one that matters: it says the payload is a USB HID +/// report and nothing else, to be handed to the device as-is. Without +/// it the payload is a command in the host namespace, which has no USB +/// counterpart at all. See `HostCommand`. +pub const Flags = struct { + pub const none: u16 = 0x0000; + /// Set by a device on a reply to a `get_report`. + pub const result: u16 = 0x0100; + /// Set by a device answering something that asked for `req_ack`, + /// and by this library on a keepalive acknowledgement. + pub const ack_nak: u16 = 0x0200; + /// Asks the device to acknowledge. This library never sets it; the + /// reference implementation does not either, which is what says it + /// is optional. + pub const req_ack: u16 = 0x4000; + /// The payload is a USB HID report, byte for byte. + pub const verbatim: u16 = 0x8000; +}; + +/// Which of the three hidapi calls a `cora` frame is carrying. +/// +/// This is the whole of what the framing does: it is a remote procedure +/// call for `hid_write`, `hid_send_feature_report` and +/// `hid_get_feature_report`, which is exactly the set of operations +/// this library already makes of a USB device. +pub const HidOp = enum(u8) { + write = 0x00, + send_report = 0x01, + get_report = 0x02, + _, +}; + +/// A `cora` header, in the order and the widths it goes on the wire. +/// +/// Everything here is little-endian. That is worth saying out loud +/// because the *other* namespace this protocol carries is not: a host +/// command reply declares its length big-endian. See `HostReply`. +pub const Header = extern struct { + magic: [4]u8 = framing_magic, + flags: u16, + hid_op: u8, + /// Always zero. What it is for is not known; no implementation + /// reads it and every one writes zero. + reserved: u8 = 0, + /// Correlates a reply with the request that asked for it. A device + /// echoes whatever it was sent, so the value itself means nothing. + message_id: u32, + payload_len: u32, + + const framing_magic = magic; +}; + +comptime { + std.debug.assert(@sizeOf(Header) == header_size); +} + +/// A whole `cora` frame taken off the front of a stream: the header, +/// the payload it declared, and how many bytes of the stream the two of +/// them occupied. +/// +/// `consumed` is not simply `header_size + payload.len`. A stream can +/// arrive misaligned, and `decode` skips whatever it had to skip to +/// find the magic, so `consumed` counts that too. +pub const Frame = struct { + header: Header, + payload: []const u8, + consumed: usize, +}; + +/// What can be wrong with a frame a device sent. +/// +/// As with `ReportError` in `root.zig`, these are errors rather than a +/// null with a log line beside it: a caller knows whether it is running +/// a daemon or a one-shot tool, and a library does not. +pub const FramingError = error{ + /// The header declared a payload larger than `max_payload`. The + /// peer is confused, or this is not a Stream Deck. + PayloadTooLarge, + /// The buffer handed in cannot hold the frame being built. + BufferTooSmall, + /// The first bytes a device sent match neither framing. + UnknownFraming, +}; + +/// Which framing these bytes are the start of, or null if there are not +/// yet enough of them to tell. +/// +/// The device speaks first -- there is no client hello -- so this runs +/// on whatever it opens with. A `cora` device opens with the magic; a +/// `legacy` one opens with a keepalive probe, which begins `01 0a`. +/// +/// Note that this insists the magic be at offset zero. A device that +/// sent anything at all before its first frame would be classified as +/// `legacy` if those bytes happened to begin `01 0a` and refused +/// otherwise. One implementation reports hardware emitting a few zero +/// bytes on connection setup, which would be refused here; it is the +/// only source that mentions it, and inventing a tolerance for +/// something only one source has seen would be guessing. +pub fn classify(data: []const u8) FramingError!?Framing { + if (data.len >= magic.len and std.mem.eql(u8, data[0..magic.len], &magic)) return .cora; + + // Two bytes is enough to recognise a keepalive probe, and one is + // not enough to rule the magic out. + if (data.len < magic.len) { + if (data.len >= 2 and data[0] == 0x01 and data[1] == 0x0a) return .legacy; + // Still consistent with the magic, so wait for more. + if (std.mem.startsWith(u8, &magic, data)) return null; + if (data.len < 2) return null; + return error.UnknownFraming; + } + + if (data[0] == 0x01 and data[1] == 0x0a) return .legacy; + return error.UnknownFraming; +} + +/// Where the `cora` magic starts in `data`, or null if it is not there. +/// +/// The decoder resynchronises rather than trusting that a stream is +/// aligned. Every implementation read does the same, which says they +/// all meet misaligned streams in practice. +pub fn findMagic(data: []const u8) ?usize { + return std.mem.find(u8, data, &magic); +} + +/// Take one whole `cora` frame off the front of `data`, or null if +/// `data` does not yet hold one. +/// +/// The returned payload points into `data` and is good only until +/// `data` is next written to. +pub fn decode(data: []const u8) FramingError!?Frame { + const start = findMagic(data) orelse return null; + const rest = data[start..]; + if (rest.len < header_size) return null; + + const flags = std.mem.readInt(u16, rest[4..6], .little); + const hid_op = rest[6]; + const reserved = rest[7]; + const message_id = std.mem.readInt(u32, rest[8..12], .little); + const payload_len = std.mem.readInt(u32, rest[12..16], .little); + + if (payload_len > max_payload) return error.PayloadTooLarge; + + const total = header_size + payload_len; + if (rest.len < total) return null; + + return .{ + .header = .{ + .flags = flags, + .hid_op = hid_op, + .reserved = reserved, + .message_id = message_id, + .payload_len = payload_len, + }, + .payload = rest[header_size..total], + .consumed = start + total, + }; +} + +/// Build a `cora` frame into `buf` and return the part of it written. +/// +/// `buf` has to hold the header and the payload together; anything +/// smaller is `error.BufferTooSmall`. +pub fn encode( + buf: []u8, + flags: u16, + hid_op: HidOp, + message_id: u32, + payload: []const u8, +) FramingError![]const u8 { + if (payload.len > max_payload) return error.PayloadTooLarge; + const total = header_size + payload.len; + if (buf.len < total) return error.BufferTooSmall; + + var writer = std.Io.Writer.fixed(buf[0..header_size]); + writer.writeStruct(Header{ + .flags = flags, + .hid_op = @intFromEnum(hid_op), + .message_id = message_id, + .payload_len = @intCast(payload.len), + }, .little) catch unreachable; + + @memcpy(buf[header_size..total], payload); + return buf[0..total]; +} + +/// Whether this payload is the keepalive a device sends unprompted. +/// +/// The device pings and the host answers; there is no ping in the other +/// direction. A host that does not answer is disconnected after about +/// five seconds. +pub fn isKeepaliveProbe(payload: []const u8) bool { + return payload.len > 5 and payload[0] == 0x01 and payload[1] == 0x0a; +} + +/// Whether this payload is the notification a dock sends when +/// something is plugged into or pulled out of it. +/// +/// Nothing is done with these yet -- driving a device behind a dock is +/// not implemented -- but they have to be recognised so that they are +/// not mistaken for an input report, which is what anything else +/// beginning `0x01` is. +pub fn isChildNotification(payload: []const u8) bool { + return payload.len > 1 and payload[0] == 0x01 and payload[1] == 0x0b; +} + +/// Whether this payload is an input report: a key pressed, an encoder +/// turned, a screen touched. +/// +/// This is what `Events.decode` parses, and it is byte for byte the +/// report the same device would send over USB, leading report id and +/// all. +pub fn isInputReport(payload: []const u8) bool { + return payload.len > 0 and payload[0] == 0x01 and + !isKeepaliveProbe(payload) and !isChildNotification(payload); +} + +/// The connection number a keepalive probe carries, which its +/// acknowledgement has to quote back. +/// +/// A device accepts several clients at once and tells them apart by +/// this, so answering with the wrong one is answering on somebody +/// else's behalf. +pub fn keepaliveConnection(probe: []const u8) u8 { + std.debug.assert(isKeepaliveProbe(probe)); + return probe[5]; +} + +/// Build the payload acknowledging a keepalive probe. +/// +/// `buf` is zeroed and the whole of it is returned, because its length +/// is the acknowledgement's length. What that length should be is not +/// settled: implementations send 32 bytes and 1024 bytes and both are +/// reported to work, so the device evidently does not care. The caller +/// picks by the size of the buffer it passes. +pub fn keepaliveAck(buf: []u8, probe: []const u8) FramingError![]const u8 { + if (buf.len < 3) return error.BufferTooSmall; + @memset(buf, 0); + buf[0] = 0x03; + buf[1] = 0x1a; + buf[2] = keepaliveConnection(probe); + return buf; +} + +/// The commands that have no USB equivalent. +/// +/// These are the other half of what a `cora` frame can carry, selected +/// by *not* setting `Flags.verbatim`. A device reached directly -- a +/// Studio, or a dock itself -- answers questions about itself here +/// rather than through the feature reports its USB counterpart uses. A +/// device reached through a dock does not: everything to one of those +/// is verbatim, and the USB report ids apply unchanged. +pub const HostCommand = enum(u8) { + /// Vendor and product id. The reply is the only way to learn what + /// model is on the other end of a socket. + identity = 0x80, + /// The AP2 firmware version, which is what stands in for the + /// firmware version a USB device reports through feature report + /// `0x05`. + firmware = 0x83, + /// The serial number, standing in for USB feature report `0x06`. + serial = 0x84, + _, +}; + +/// Build the payload asking a device a host command. +pub fn hostRequest(buf: []u8, command: HostCommand) FramingError![]const u8 { + if (buf.len < 2) return error.BufferTooSmall; + @memset(buf, 0); + buf[0] = 0x03; + buf[1] = @intFromEnum(command); + return buf; +} + +/// A device's answer to a host command: which command it is answering, +/// and the body it carried. +pub const HostReply = struct { + command: u8, + /// The bytes after the length field. Points into the payload it was + /// parsed from. + body: []const u8, + + /// Parse a host command reply, or null if this payload is not one. + /// + /// The shape is `03 `, and **the length is + /// big-endian** -- in a protocol that is little-endian everywhere + /// else, including the header this payload arrived in. Two + /// independent implementations read it that way and a third reads + /// only its low byte, which agrees for every length either has ever + /// seen. It is the single most likely thing here to be got wrong. + /// + /// A length reaching past what the device actually sent is clamped + /// rather than refused: the body is whatever really arrived. A + /// device that lies about its length cannot make this read past the + /// end of the payload. + pub fn parse(payload: []const u8) ?HostReply { + if (payload.len < 4) return null; + if (payload[0] != 0x03) return null; + + const declared = std.mem.readInt(u16, payload[2..4], .big); + const available = payload.len - 4; + const len = @min(@as(usize, declared), available); + + return .{ + .command = payload[1], + .body = payload[4 .. 4 + len], + }; + } +}; + +/// The vendor and product id out of an `identity` reply, or null if the +/// reply is too short to carry them. +/// +/// These sit at a fixed offset in the payload rather than in the body, +/// so this takes the whole payload. Both are little-endian, unlike the +/// length field above them. +pub fn parseIdentity(payload: []const u8) ?struct { vendor: u16, product: u16 } { + if (payload.len < 16) return null; + return .{ + .vendor = std.mem.readInt(u16, payload[12..14], .little), + .product = std.mem.readInt(u16, payload[14..16], .little), + }; +} + +/// The string in a host command reply: its body, cut at the first NUL. +/// +/// A device pads with zeroes, and the declared length does not always +/// exclude the padding, so the terminator is what actually ends the +/// string. +pub fn replyString(reply: HostReply) []const u8 { + if (std.mem.findScalar(u8, reply.body, 0)) |end| return reply.body[0..end]; + return reply.body; +} + +test classify { + // Not yet enough to tell. + try std.testing.expectEqual(null, try classify(&.{})); + try std.testing.expectEqual(null, try classify(&.{0x43})); + try std.testing.expectEqual(null, try classify(&.{ 0x43, 0x93 })); + + try std.testing.expectEqual(Framing.cora, (try classify(&magic)).?); + try std.testing.expectEqual(Framing.cora, (try classify(&(magic ++ [_]u8{ 0, 0 }))).?); + try std.testing.expectEqual(Framing.legacy, (try classify(&.{ 0x01, 0x0a })).?); + try std.testing.expectEqual( + Framing.legacy, + (try classify(&.{ 0x01, 0x0a, 0x00, 0x00, 0x00, 0x07 })).?, + ); + + // A device that is not a Stream Deck. + try std.testing.expectError(error.UnknownFraming, classify(&.{ 0xde, 0xad })); + try std.testing.expectError(error.UnknownFraming, classify(&.{ 0xde, 0xad, 0xbe, 0xef })); + // One byte that cannot be the start of the magic, and is not enough + // to be a probe either. + try std.testing.expectEqual(null, try classify(&.{0xff})); +} + +test "a frame round-trips through encode and decode" { + var buf: [64]u8 = undefined; + const payload = [_]u8{ 0x02, 0x07, 0x00, 0x01, 0x10, 0x00, 0x00, 0x00 }; + + const bytes = try encode(&buf, Flags.verbatim, .write, 0x11223344, &payload); + try std.testing.expectEqual(header_size + payload.len, bytes.len); + + // The header goes out exactly as it is described, little-endian. + try std.testing.expectEqualSlices(u8, &magic, bytes[0..4]); + try std.testing.expectEqualSlices(u8, &.{ 0x00, 0x80 }, bytes[4..6]); + try std.testing.expectEqual(@as(u8, 0x00), bytes[6]); + try std.testing.expectEqual(@as(u8, 0x00), bytes[7]); + try std.testing.expectEqualSlices(u8, &.{ 0x44, 0x33, 0x22, 0x11 }, bytes[8..12]); + try std.testing.expectEqualSlices(u8, &.{ 0x08, 0x00, 0x00, 0x00 }, bytes[12..16]); + + const frame = (try decode(bytes)).?; + try std.testing.expectEqual(Flags.verbatim, frame.header.flags); + try std.testing.expectEqual(HidOp.write, @as(HidOp, @enumFromInt(frame.header.hid_op))); + try std.testing.expectEqual(@as(u32, 0x11223344), frame.header.message_id); + try std.testing.expectEqualSlices(u8, &payload, frame.payload); + try std.testing.expectEqual(bytes.len, frame.consumed); +} + +test "a frame split across two reads is not returned until it is whole" { + var buf: [64]u8 = undefined; + const payload = [_]u8{ 1, 2, 3, 4 }; + const bytes = try encode(&buf, Flags.none, .get_report, 1, &payload); + + // Every prefix short of the whole thing has to say "not yet". + for (0..bytes.len) |n| { + try std.testing.expectEqual(null, try decode(bytes[0..n])); + } + try std.testing.expect(try decode(bytes) != null); +} + +test "the decoder resynchronises on the magic" { + var buf: [64]u8 = undefined; + const payload = [_]u8{ 0xaa, 0xbb }; + const bytes = try encode(&buf, Flags.none, .write, 7, &payload); + + var stream: [80]u8 = undefined; + const junk = [_]u8{ 0x00, 0x00, 0xde, 0xad, 0xbe }; + @memcpy(stream[0..junk.len], &junk); + @memcpy(stream[junk.len..][0..bytes.len], bytes); + + const frame = (try decode(stream[0 .. junk.len + bytes.len])).?; + try std.testing.expectEqualSlices(u8, &payload, frame.payload); + // `consumed` counts the junk that was skipped, or the caller would + // leave it in the buffer and find it again forever. + try std.testing.expectEqual(junk.len + bytes.len, frame.consumed); +} + +test "a header claiming an enormous payload is refused" { + var bytes: [header_size]u8 = undefined; + @memcpy(bytes[0..4], &magic); + @memset(bytes[4..12], 0); + std.mem.writeInt(u32, bytes[12..16], max_payload + 1, .little); + + try std.testing.expectError(error.PayloadTooLarge, decode(&bytes)); + + // And the largest allowed length is accepted, not off by one -- + // though the frame is not complete, so it reads as "not yet". + std.mem.writeInt(u32, bytes[12..16], max_payload, .little); + try std.testing.expectEqual(null, try decode(&bytes)); +} + +test "a buffer too small for the frame is refused rather than truncated" { + var buf: [8]u8 = undefined; + try std.testing.expectError( + error.BufferTooSmall, + encode(&buf, Flags.none, .write, 0, &.{ 1, 2, 3, 4 }), + ); +} + +test isKeepaliveProbe { + const probe = [_]u8{ 0x01, 0x0a, 0x00, 0x00, 0x00, 0x05 }; + try std.testing.expect(isKeepaliveProbe(&probe)); + try std.testing.expectEqual(@as(u8, 5), keepaliveConnection(&probe)); + + // An input report begins with the same byte and is not a probe. + try std.testing.expect(!isKeepaliveProbe(&.{ 0x01, 0x00, 0x00, 0x00 })); + try std.testing.expect(isInputReport(&.{ 0x01, 0x00, 0x00, 0x00 })); + try std.testing.expect(!isInputReport(&probe)); + + // Nor is a hotplug notification. + const hotplug = [_]u8{ 0x01, 0x0b, 0x7c, 0x00, 0x02 }; + try std.testing.expect(isChildNotification(&hotplug)); + try std.testing.expect(!isInputReport(&hotplug)); + try std.testing.expect(!isKeepaliveProbe(&hotplug)); + + // Too short to be anything. + try std.testing.expect(!isKeepaliveProbe(&.{0x01})); + try std.testing.expect(!isChildNotification(&.{0x01})); + try std.testing.expect(!isInputReport(&.{})); +} + +test keepaliveAck { + const probe = [_]u8{ 0x01, 0x0a, 0x00, 0x00, 0x00, 0x2a }; + + var buf: [32]u8 = undefined; + const ack = try keepaliveAck(&buf, &probe); + try std.testing.expectEqual(32, ack.len); + try std.testing.expectEqual(@as(u8, 0x03), ack[0]); + try std.testing.expectEqual(@as(u8, 0x1a), ack[1]); + try std.testing.expectEqual(@as(u8, 0x2a), ack[2]); + // Everything after the connection number is zero. + for (ack[3..]) |b| try std.testing.expectEqual(@as(u8, 0), b); + + var tiny: [2]u8 = undefined; + try std.testing.expectError(error.BufferTooSmall, keepaliveAck(&tiny, &probe)); +} + +test "a host reply declares its length big-endian" { + // This is the one field in the whole protocol that is not + // little-endian, so it gets a test of its own. `0x0004` read the + // wrong way round is `0x0400`, which would run off the end. + const payload = [_]u8{ 0x03, 0x84, 0x00, 0x04, 'A', 'B', '1', '2', 0x00, 0x00 }; + + const reply = HostReply.parse(&payload).?; + try std.testing.expectEqual(@as(u8, 0x84), reply.command); + try std.testing.expectEqualStrings("AB12", reply.body); + try std.testing.expectEqualStrings("AB12", replyString(reply)); +} + +test "a host reply claiming more than it carries is clamped" { + // A device that lies about its length must not make this read past + // the end of what actually arrived. + const payload = [_]u8{ 0x03, 0x84, 0xff, 0xff, 'x', 'y' }; + const reply = HostReply.parse(&payload).?; + try std.testing.expectEqualStrings("xy", reply.body); + + // And something that is not a host reply at all. + try std.testing.expectEqual(null, HostReply.parse(&.{ 0x01, 0x00, 0x00, 0x00 })); + try std.testing.expectEqual(null, HostReply.parse(&.{ 0x03, 0x84 })); +} + +test "a string reply is cut at its terminator" { + const payload = [_]u8{ 0x03, 0x84, 0x00, 0x08, 'C', 'L', '1', '2', 0x00, 0x00, 0x00, 0x00 }; + const reply = HostReply.parse(&payload).?; + // The device declared eight bytes and four of them are padding. + try std.testing.expectEqual(8, reply.body.len); + try std.testing.expectEqualStrings("CL12", replyString(reply)); +} + +test parseIdentity { + var payload = std.mem.zeroes([16]u8); + payload[0] = 0x03; + payload[1] = 0x80; + std.mem.writeInt(u16, payload[12..14], 0x0fd9, .little); + std.mem.writeInt(u16, payload[14..16], 0x00aa, .little); + + const id = parseIdentity(&payload).?; + try std.testing.expectEqual(@as(u16, 0x0fd9), id.vendor); + try std.testing.expectEqual(@as(u16, 0x00aa), id.product); + + // Too short to carry them. + try std.testing.expectEqual(null, parseIdentity(payload[0..15])); +} + +test hostRequest { + var buf: [32]u8 = undefined; + const req = try hostRequest(&buf, .serial); + try std.testing.expectEqual(32, req.len); + try std.testing.expectEqual(@as(u8, 0x03), req[0]); + try std.testing.expectEqual(@as(u8, 0x84), req[1]); + for (req[2..]) |b| try std.testing.expectEqual(@as(u8, 0), b); + + var tiny: [1]u8 = undefined; + try std.testing.expectError(error.BufferTooSmall, hostRequest(&tiny, .serial)); +} + +test { + std.testing.refAllDecls(@This()); +} diff --git a/src/image.zig b/src/image.zig index 6c3e3e4..bd8f251 100644 --- a/src/image.zig +++ b/src/image.zig @@ -48,6 +48,99 @@ pub const ImageHeaderV4 = extern struct { page_number: u16, }; +/// The header on each page of an image sent to the whole panel behind +/// the keys. It is the shape of `ImageHeaderV4` with a command byte of +/// its own; there is only one such screen per device, so it carries no +/// index, and it is always written whole, so it carries no rectangle. +pub const ImageHeaderV5 = extern struct { + byte0: u8 = 0x02, + byte1: u8 = 0x08, + byte2: u8 = 0x00, + last: bool align(1), + length: u16, + page_number: u16, +}; + +/// The header on each page of a **background** image. +/// +/// It is the same eight bytes as `ImageHeaderV2` in every respect but +/// one, and that one is a trap: the chunk index and the chunk size are +/// **the other way round**. A key image carries its size at `+0x04` +/// and its page number at `+0x06`; a background carries its page +/// number at `+0x04` and its size at `+0x06`. Elgato's Update +/// Background and Update Key Image tables differ in exactly that, +/// which is easy to read past. +/// +/// Getting it backwards would not fail loudly. The first page of a +/// small image has page number zero and a size of about a kilobyte, so +/// a swapped header asks the device to write page 1016 of nothing -- +/// and the device simply shows no background, with nothing to say why. +/// This library once had the same fault in the touchscreen header, and +/// that is what it looked like there too. +pub const ImageHeaderV6 = extern struct { + byte0: u8 = 0x02, + byte1: u8 = 0x0d, + /// Which background slot is being written. + index: u8, + last: bool align(1), + /// At `+0x04`, where a key image keeps its length. + page_number: u16, + /// At `+0x06`, where a key image keeps its page number. + length: u16, +}; + +test ImageHeaderV6 { + try std.testing.expectEqual(8, @sizeOf(ImageHeaderV6)); + + var buf: [16]u8 = undefined; + var writer = std.Io.Writer.fixed(&buf); + try writer.writeStruct(ImageHeaderV6{ + .index = 2, + .last = true, + .page_number = 0x0304, + .length = 0x0102, + }, .little); + + // The whole point of this header is the field order, so it is + // pinned byte by byte: page number first, then length. + try std.testing.expectEqualSlices(u8, &.{ + 0x02, 0x0d, 0x02, 0x01, 0x04, 0x03, 0x02, 0x01, + }, writer.buffered()); + + // And said the other way about: a key image with the same numbers + // puts them in the opposite order, which is what makes mixing the + // two silent rather than obvious. + var key_buf: [16]u8 = undefined; + var key_writer = std.Io.Writer.fixed(&key_buf); + try key_writer.writeStruct(ImageHeaderV2{ + .key = 2, + .last = true, + .length = 0x0102, + .page_number = 0x0304, + }, .little); + try std.testing.expectEqualSlices(u8, &.{ + 0x02, 0x07, 0x02, 0x01, 0x02, 0x01, 0x04, 0x03, + }, key_writer.buffered()); +} + +test ImageHeaderV5 { + try std.testing.expectEqual(8, @sizeOf(ImageHeaderV5)); + + var buf: [16]u8 = undefined; + var writer = std.Io.Writer.fixed(&buf); + try writer.writeStruct(ImageHeaderV5{ + .last = true, + .length = 0x0102, + .page_number = 0x0304, + }, .little); + + // The command byte is what separates this from the strip header, + // so it is worth pinning rather than assuming. + try std.testing.expectEqualSlices(u8, &.{ + 0x02, 0x08, 0x00, 0x01, 0x02, 0x01, 0x04, 0x03, + }, writer.buffered()); +} + test ImageHeaderV4 { try std.testing.expectEqual(8, @sizeOf(ImageHeaderV4)); diff --git a/src/main.zig b/src/main.zig index d4d9234..19df410 100644 --- a/src/main.zig +++ b/src/main.zig @@ -14,16 +14,64 @@ pub fn main(init: std.process.Init) !void { defer streamdeck.deinit(); var group: std.Io.Group = .init; + defer group.cancel(io); + + // Any addresses on the command line are networked decks -- a + // Studio, or a Network Dock -- which enumeration will never find, + // because they are somewhere on a network rather than plugged into + // this machine. Written `1.2.3.4:5343`, or with the port left off + // to take the default. + var args = init.minimal.args.iterate(); + // The first argument is this program's own name. + _ = args.next(); + + while (args.next()) |arg| { + const address = parseAddress(arg) catch |err| { + log.warn("{s}: not an address: {t}", .{ arg, err }); + continue; + }; + + const deck = streamdeck.connect(io, alloc, address) catch |err| { + log.warn("{s}: {t}", .{ arg, err }); + continue; + }; + + // A networked deck was not enumerated, so nothing described it + // beforehand; the empty info says so rather than inventing one. + try group.concurrent(io, sd_handler, .{ + io, alloc, streamdeck.StreamDeckInfo{ .deck = deck, .info = .empty }, + }); + } - var it = try streamdeck.enumerate(); + var decks: streamdeck.Enumerator = undefined; + try decks.init(io, alloc); + defer decks.deinit(io, alloc); - while (try it.next(io)) |info| { - try group.concurrent(io, sd_handler, .{ io, alloc, info }); + while (try decks.next(io, alloc)) |found| { + try group.concurrent(io, sd_handler, .{ io, alloc, found }); } try group.await(io); } +/// An address with an optional port, defaulting to the one these +/// devices listen on. `std.Io.net` parses a literal with a port and a +/// literal without one, but not either, so this tries both. +fn parseAddress(text: []const u8) !std.Io.net.IpAddress { + if (std.Io.net.IpAddress.parseLiteral(text)) |address| { + const port = switch (address) { + .ip4 => |a| a.port, + .ip6 => |a| a.port, + }; + // A literal with no port parses with a port of zero, which is + // not something to connect to; fall through and supply the + // default instead. + if (port != 0) return address; + } else |_| {} + + return std.Io.net.IpAddress.parse(text, streamdeck.Tcp.default_port); +} + pub fn sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.StreamDeckInfo) error{Canceled}!void { _sd_handler(io, alloc, info) catch |err| { log.warn("error: {t}", .{err}); @@ -31,7 +79,7 @@ pub fn sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.StreamD } pub fn _sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.StreamDeckInfo) !void { - defer info.deinit(io); + defer info.deinit(io, alloc); const sd = info.deck; @@ -44,15 +92,24 @@ pub fn _sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.Stream // The library no longer prints any of this itself, so what a // caller wants to know about a device it asks for and prints. - var name_buf: [64]u8 = undefined; try stderr.print("model : {t}\n", .{sd.type}); - try stderr.print("name : {?s}\n", .{try sd.device.getRawName(io, &name_buf)}); - - var uniq_buf: [64]u8 = undefined; - try stderr.print("uniq : {?s}\n", .{try sd.device.getRawUniq(io, &uniq_buf)}); - - var where_buf: [256]u8 = undefined; - try stderr.print("location : {?s}\n", .{try sd.device.getPhysicalLocation(io, &where_buf)}); + try stderr.print("transport : {t}\n", .{sd.device.kind()}); + + // What the system said about the device when it was found. + // This comes from the enumeration rather than from the open + // device, which answers less: on Linux the device does not + // report a manufacturer at all. A deck reached over the network + // was never enumerated and has none of it. + if (info.info.product.slice()) |product| { + try stderr.print("product : {s}\n", .{product}); + } + if (info.info.manufacturer.slice()) |manufacturer| { + try stderr.print("manufacturer : {s}\n", .{manufacturer}); + } + if (info.info.physical_location.slice()) |where| { + try stderr.print("location : {s}\n", .{where}); + } + try stderr.print("bus : {t}\n", .{info.info.bus_type}); var serial_buffer: [32]u8 = undefined; const serial = try sd.getSerialNumber(io, &serial_buffer); @@ -61,13 +118,31 @@ pub fn _sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.Stream var version_buffer: [32]u8 = undefined; const version = try sd.getFirmwareVersion(io, &version_buffer); try stderr.print("firmware version: {s}\n", .{version}); + + // Zero means the device never blanks itself, which is what a + // program driving the keys usually wants -- so say what it is + // rather than changing it behind the user's back. + if (sd.getSleepTimeout(io)) |seconds| { + if (seconds == 0) { + try stderr.print("sleep timeout : disabled\n", .{}); + } else { + try stderr.print("sleep timeout : {d}s\n", .{seconds}); + } + } else |err| { + try stderr.print("sleep timeout : {t}\n", .{err}); + } } { var serial_buffer: [32]u8 = undefined; const serial = try sd.getSerialNumber(io, &serial_buffer); - try sd.reset(io); + // Resetting has no known encoding over the network, so a + // networked deck is left as it is rather than refusing to run. + sd.reset(io) catch |err| switch (err) { + error.Unsupported => {}, + else => return err, + }; try sd.resetKeyStream(io); try sd.setBrightness(io, 50); @@ -96,7 +171,7 @@ pub fn _sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.Stream // listening. Deciding that is the application's job, which // is why the library reports these rather than logging them // itself. - const maybe_event = sd.events.read(io, alloc) catch |err| switch (err) { + const event = sd.events.read(io, alloc) catch |err| switch (err) { error.ShortReport, error.UnknownReportType, error.UnknownControlType, @@ -105,10 +180,16 @@ pub fn _sd_handler(io: std.Io, alloc: std.mem.Allocator, info: streamdeck.Stream log.warn("{s} ignoring report: {t}", .{ serial, err }); continue; }, - else => return err, + // Anything else means the deck is no longer reachable + // -- unplugged, or a connection that has dropped -- + // which is the end of this device rather than a report + // to skip. Before `read` reported these, the loop spun + // here forever. + else => { + log.warn("{s} disconnected: {t}", .{ serial, err }); + return; + }, }; - - const event = maybe_event orelse continue; defer event.deinit(alloc); switch (event) { diff --git a/src/root.zig b/src/root.zig index 84aa7c5..84adef9 100644 --- a/src/root.zig +++ b/src/root.zig @@ -16,9 +16,19 @@ pub const Keys = @import("Keys.zig"); pub const Touchscreen = @import("Touchscreen.zig"); /// The rotary encoders, on the models that have them. pub const Encoders = @import("Encoders.zig"); +/// The single screen behind the keys, which the key images are cut-outs +/// of, and which can be painted whole. +pub const Panel = @import("Panel.zig"); /// Decoding of the input reports a device sends when something on it is /// pressed, touched or turned. pub const Events = @import("Events.zig"); +/// How a device is reached: a HID device, or a network connection. +pub const Transport = @import("Transport.zig"); +/// A Stream Deck reached over the network: the Studio and the Network +/// Dock. +pub const Tcp = @import("Tcp.zig"); +/// The framing those devices speak, with the socket taken out of it. +pub const framing = @import("framing.zig"); pub fn init() !void {} @@ -74,14 +84,19 @@ pub const Command = enum(u8) { reset_key_stream = 0x02, }; -/// One Stream Deck found by `enumerate`. The device is already open by -/// the time it is reported, so `deck` is ready to use; the caller owns -/// it and must release it with `deinit`. +/// One Stream Deck found by an `Enumerator`: the open device, and +/// everything the system said about it without being asked. +/// +/// `info` is worth keeping. It carries the serial number, the product +/// string and where the device sits on the bus, all of which the +/// enumeration already knew -- asking the open device for them again +/// answers less, because that asks the device rather than the system. pub const StreamDeckInfo = struct { deck: StreamDeck, + info: hidapi.DeviceInfo, - pub fn deinit(self: *const StreamDeckInfo, io: std.Io) void { - self.deck.close(io); + pub fn deinit(self: *const StreamDeckInfo, io: std.Io, alloc: std.mem.Allocator) void { + self.deck.close(io, alloc); } }; @@ -125,56 +140,99 @@ test KeyIterator { }, seen.items); } -pub const StreamDeckIterator = struct { - devices: hidapi.DeviceInfoIterator = .init, +/// Walks the Stream Decks attached to the system. +/// +/// Initialized in place rather than returned, because it holds the +/// scratch the enumeration works in and a `DeviceInfo` that the +/// underlying iterator hands back pointers into -- so it must not move +/// once started: +/// +/// ``` +/// var decks: streamdeck.Enumerator = undefined; +/// try decks.init(io, alloc); +/// defer decks.deinit(io); +/// +/// while (try decks.next(io, alloc)) |found| { +/// defer found.deinit(io, alloc); +/// // ... +/// } +/// ``` +/// +/// Enumerating needs no special permission. Opening does, and `next` +/// opens each deck it finds, so a process without access to +/// `/dev/hidraw*` gets `error.AccessDenied` from `next` rather than an +/// empty list -- which is a better answer than the silence it used to +/// give. See the README. +pub const Enumerator = struct { + devices: hidapi.Enumerator, + scratch: []u8, + + /// Begin enumerating. `alloc` is used for the enumeration's own + /// scratch and is released by `deinit`. + pub fn init(self: *Enumerator, io: std.Io, alloc: std.mem.Allocator) !void { + self.scratch = try alloc.alloc(u8, hidapi.Enumerator.recommended_scratch); + errdefer alloc.free(self.scratch); + + // Usage pages cost a report descriptor read per device on + // Linux and say nothing this library uses -- a Stream Deck is + // identified by its vendor and product ids. The strings are + // worth having, since `StreamDeckInfo` hands them on. + try self.devices.init(io, self.scratch, .{ .usages = false, .strings = true }); + } - pub const init: StreamDeckIterator = .{}; + /// Release the enumeration. `alloc` has to be the one `init` was + /// given. + pub fn deinit(self: *Enumerator, io: std.Io, alloc: std.mem.Allocator) void { + self.devices.deinit(io); + alloc.free(self.scratch); + } - pub fn next(self: *StreamDeckIterator, io: std.Io) !?StreamDeckInfo { + /// The next Stream Deck, already open, or null when there are no + /// more. Devices that are not Stream Decks are skipped without + /// being opened. + pub fn next(self: *Enumerator, io: std.Io, alloc: std.mem.Allocator) !?StreamDeckInfo { while (try self.devices.next(io)) |info| { - var deck: StreamDeck = StreamDeck.initFromDeviceInfo(info) catch |err| switch (err) { + // The model is decided from the ids the enumeration already + // reported, so something that is not a Stream Deck is + // passed over without being opened -- which matters, + // because opening is the part that needs permission. + _ = StreamDeck.Type.init(info.vendor_id, info.product_id) catch |err| switch (err) { error.NotAStreamDeck => continue, - else => |e| return e, }; - errdefer deck.close(io); - return .{ - .deck = deck, - }; + const deck = try StreamDeck.open(io, alloc, info); + return .{ .deck = deck, .info = info.* }; } return null; } - - /// Release the iterator. It holds nothing that needs releasing -- - /// `hidapi.DeviceInfoIterator` is a device number and nothing else - /// -- so this does nothing today. It exists so that callers can - /// write the `defer` they would write for any other iterator, and - /// so that giving this one something to release later is not a - /// breaking change. - pub fn deinit(self: *StreamDeckIterator) void { - _ = self; - } }; -/// Enumerate all of the Stream Decks that are attached to the system -pub fn enumerate() !StreamDeckIterator { - return .init; +/// Open a Stream Deck reached over the network -- a Studio, or a +/// Network Dock -- at the given address. +/// +/// These devices are not enumerated: they are somewhere on a network +/// rather than plugged into this machine, and `enumerate` will never +/// find one. There is no discovery here either, so the address is the +/// caller's to know; `Tcp.default_port` is the port they listen on. +/// +/// The caller owns the result and must release it with `close`. +pub fn connect( + io: std.Io, + alloc: std.mem.Allocator, + address: std.Io.net.IpAddress, +) !StreamDeck { + return StreamDeck.connect(io, alloc, address); } -// pub fn openSerial(io: std.Io, serial: []const u8) !StreamDeck { -// return try StreamDeck.open(product, serial); -// } - test StreamDeckInfo { - // The iterator hands back a deck that is already open, so the info - // is just a wrapper over it; there is nothing to construct here - // without a device, but this keeps `deinit` compiled. + // Everything here needs a device, so this only keeps `deinit` + // compiled. std.testing.refAllDecls(StreamDeckInfo); } test { std.testing.refAllDecls(@This()); - std.testing.refAllDecls(StreamDeckIterator); + std.testing.refAllDecls(Enumerator); std.testing.refAllDecls(KeyIterator(3, 2)); // Naming each file here is what makes its tests part of the @@ -185,9 +243,13 @@ test { _ = @import("diagnostic.zig"); _ = @import("Encoders.zig"); _ = @import("Events.zig"); + _ = @import("framing.zig"); _ = @import("image.zig"); _ = @import("jpeg.zig"); _ = @import("Keys.zig"); + _ = @import("Panel.zig"); _ = @import("StreamDeck.zig"); + _ = @import("Tcp.zig"); + _ = @import("Transport.zig"); _ = @import("Touchscreen.zig"); } diff --git a/tests/fuzz.zig b/tests/fuzz.zig index 8a66156..ebd332d 100644 --- a/tests/fuzz.zig +++ b/tests/fuzz.zig @@ -47,7 +47,7 @@ pub var accepted: usize = 0; /// split `Events.decode` out of `Events.read` -- so a fuzz target needs /// no device. fn deck(t: streamdeck.StreamDeck.Type) streamdeck.StreamDeck { - return .{ .type = t, .device = undefined }; + return .{ .type = t, .device = .none }; } /// Whether an error is one a malformed report is *supposed* to produce. @@ -221,6 +221,106 @@ fn imageEncode(smith: *Smith) anyerror!void { } } +/// The framing a networked deck speaks, fed whatever bytes. +/// +/// This is the most hostile input anything in this library takes. The +/// rest of these targets parse what a USB device said, which is at +/// worst a device with the wrong tables; this parses what came out of a +/// socket, and a header that declares its own payload length is exactly +/// the shape of thing that reads past the end of a buffer when it is +/// got wrong. +fn framingDecode(smith: *Smith) anyerror!void { + // The magic is put in front rather than hoped for. Random bytes + // contain it about once in four billion, so a target that waited + // for one would spend the whole run in the early return and never + // reach the length arithmetic below it -- which is the part worth + // fuzzing. The shapes that have no magic, or have it late, are in + // the corpus instead, where they are deliberate. + var buf: [max_report]u8 = undefined; + const magic = streamdeck.framing.magic; + @memcpy(buf[0..magic.len], &magic); + + var rest: [max_report]u8 = undefined; + const n = @min(smith.slice(&rest), buf.len - magic.len); + @memcpy(buf[magic.len..][0..n], rest[0..n]); + const data = buf[0 .. magic.len + n]; + + const frame = streamdeck.framing.decode(data) catch |err| { + if (refusedFraming(err)) return; + return err; + } orelse return; + accepted += 1; + + // A frame that came back has to describe itself honestly: the + // payload is the length the header declared, and the whole of it + // lies inside what was handed in. + std.debug.assert(frame.payload.len == frame.header.payload_len); + std.debug.assert(frame.consumed <= data.len); + std.debug.assert(frame.payload.len + streamdeck.framing.header_size <= frame.consumed); + + // And it has to be exactly the tail of what was consumed, which is + // what says the decoder counted the bytes it skipped resynchronising. + const start = frame.consumed - frame.payload.len; + std.debug.assert(frame.payload.ptr == data[start..].ptr); + + // Classifying the payload is a total function: every payload is one + // of these or none of them, and never two at once. + const probe = streamdeck.framing.isKeepaliveProbe(frame.payload); + const child = streamdeck.framing.isChildNotification(frame.payload); + const input = streamdeck.framing.isInputReport(frame.payload); + std.debug.assert(@as(u8, @intFromBool(probe)) + @intFromBool(child) + @intFromBool(input) <= 1); + + if (probe) { + // A probe always has a connection number to quote back, and an + // acknowledgement can always be built for it. + var ack_buf: [32]u8 = undefined; + const ack = try streamdeck.framing.keepaliveAck(&ack_buf, frame.payload); + std.debug.assert(ack[2] == streamdeck.framing.keepaliveConnection(frame.payload)); + } +} + +/// A host command reply, which is where the protocol's one big-endian +/// length lives. A device that lies about that length must not make the +/// parser read past what actually arrived. +fn framingHostReply(smith: *Smith) anyerror!void { + var buf: [max_report]u8 = undefined; + const n = smith.slice(&buf); + if (n < 4) return; + + // As with the magic above: a reply begins `0x03`, and waiting for + // random bytes to do that tests the early return and nothing else. + // What is worth reaching is the declared length -- the one + // big-endian field in the protocol -- and whether a body can be cut + // out of the payload that outlives it. + buf[0] = 0x03; + const data = buf[0..n]; + + const reply = streamdeck.framing.HostReply.parse(data) orelse return; + accepted += 1; + + // The body lies inside the payload, whatever length was declared. + std.debug.assert(reply.body.len + 4 <= data.len); + std.debug.assert(reply.body.ptr == data[4..].ptr); + + // And the string is a prefix of the body with no terminator in it. + const string = streamdeck.framing.replyString(reply); + std.debug.assert(string.len <= reply.body.len); + std.debug.assert(std.mem.findScalar(u8, string, 0) == null); +} + +/// Whether a framing error is one malformed bytes are supposed to +/// produce. As with `refused` above, these are listed rather than +/// swallowed wholesale. +fn refusedFraming(err: anyerror) bool { + return switch (err) { + error.PayloadTooLarge, + error.BufferTooSmall, + error.UnknownFraming, + => true, + else => false, + }; +} + /// The largest report any target reads into. `Smith.slice` hands back /// an *empty* slice for a length larger than the buffer rather than /// reducing it into range, so a generator has to know this number or @@ -248,8 +348,39 @@ pub const targets = [_]Target{ .{ .name = "touchscreen-event", .leading_values = 0, .takes_payload = true, .run = touchscreenEvent }, .{ .name = "diagnostic-image", .leading_values = 4, .takes_payload = false, .run = diagnosticImage }, .{ .name = "image-encode", .leading_values = 4, .takes_payload = false, .run = imageEncode }, + .{ .name = "framing-decode", .leading_values = 0, .takes_payload = true, .run = framingDecode }, + .{ .name = "framing-host-reply", .leading_values = 0, .takes_payload = true, .run = framingHostReply }, }; +/// A corpus entry carrying `payload` as the slice a target reads. +/// +/// `Smith.slice` reads four bytes of little-endian length before the +/// content, so an entry written as bare bytes is read as a length and +/// then whatever follows -- which is usually nothing. This writes the +/// length, so that an entry means what it looks like it means. +fn payload(comptime bytes: []const u8) []const u8 { + const length: [4]u8 = .{ + @intCast(bytes.len & 0xff), + @intCast((bytes.len >> 8) & 0xff), + 0, + 0, + }; + return &(length ++ bytes[0..bytes.len].*); +} + +/// A whole `cora` frame: the header this library writes, and `body` +/// behind it. +fn coraFrame(comptime flags: u16, comptime op: u8, comptime body: []const u8) []const u8 { + return &(streamdeck.framing.magic ++ [_]u8{ + @intCast(flags & 0xff), @intCast(flags >> 8), + op, 0, + 1, 0, + 0, 0, + @intCast(body.len & 0xff), @intCast((body.len >> 8) & 0xff), + 0, 0, + } ++ body[0..body.len].*); +} + /// Inputs worth keeping: the shapes a real device produces, and the /// edges around them. `zig build test` runs every target over every one /// of these, and the driver mutates them. @@ -278,6 +409,41 @@ pub const corpus = [_][]const u8{ &.{0x01}, &.{ 0x01, 0x00 }, &.{ 0x01, 0x00, 0x0f }, + + // A keepalive probe in a `cora` frame, which is the first thing a + // networked device ever sends. + payload(coraFrame(0x0200, 0x00, &.{ 0x01, 0x0a, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00 })), + // An input report in one: a key went down on a gen2 device. + payload(coraFrame(0x8000, 0x00, &.{ 0x01, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00 })), + // A dock saying something was plugged in. + payload(coraFrame(0x0000, 0x00, &.{ 0x01, 0x0b, 0x7c, 0x00, 0x02, 0x00 })), + // A frame behind junk, which the decoder has to resynchronise past. + payload(&([_]u8{ 0x00, 0x00, 0xde, 0xad } ++ + coraFrame(0x8000, 0x00, &.{ 0x01, 0x00, 0x00, 0x00 })[0..20].*)), + // The magic and nothing else, and then a header cut short. + payload(&streamdeck.framing.magic), + payload(&(streamdeck.framing.magic ++ [_]u8{ 0, 0, 0, 0, 0, 0 })), + // A header declaring a payload far larger than anything real. + payload(&(streamdeck.framing.magic ++ [_]u8{ + 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, + })), + // A header declaring a payload it does not carry. + payload(&(streamdeck.framing.magic ++ [_]u8{ + 0, 0, 0, 0, 0, 0, 0, 0, 0x20, 0, 0, 0, 1, 2, 3, + })), + + // A host command reply: the serial number, whose length is the one + // big-endian field in the protocol. + payload(&.{ 0x03, 0x84, 0x00, 0x04, 'A', 'B', '1', '2' }), + // One claiming far more than it carries. + payload(&.{ 0x03, 0x84, 0xff, 0xff, 'x', 'y' }), + // One whose declared length runs into its own padding. + payload(&.{ 0x03, 0x84, 0x00, 0x08, 'C', 'L', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }), + // An identity reply. + payload(&.{ + 0x03, 0x80, 0x00, 0x0c, 0, 0, 0, 0, + 0, 0, 0, 0, 0xd9, 0x0f, 0xaa, 0x00, + }), }; test "every target survives every corpus entry" { diff --git a/tools/probe.zig b/tools/probe.zig new file mode 100644 index 0000000..a8df49b --- /dev/null +++ b/tools/probe.zig @@ -0,0 +1,850 @@ +// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! Ask every attached Stream Deck what it says about itself, and print +//! the raw bytes of the answers beside what they were decoded as. +//! +//! This exists to check the device tables against hardware rather than +//! against another implementation. Reading it is the point: a table +//! that disagrees with what the device says here is wrong. + +const std = @import("std"); +const streamdeck = @import("streamdeck"); +const z2d = @import("z2d"); + +pub fn main(init: std.process.Init) !void { + const io = init.io; + const alloc = init.gpa; + + var buf: [4096]u8 = undefined; + const locked = std.debug.lockStderr(&buf); + defer std.debug.unlockStderr(); + const out = &locked.file_writer.interface; + + // `--orient` puts the same figure on the first four keys of every + // deck, each under a different correction, so that one look says + // which correction a model's table is missing. The figure is "12" + // with a rule under it: asymmetric every way round, so a mirror and + // a half turn cannot be confused for each other the way a lone + // digit can. + var orient = false; + var paint = false; + var fill = false; + var sleep = false; + var scan = false; + var background = false; + var logo = false; + var diff = false; + var idle = false; + var wake = false; + var transparent = false; + var composite = false; + var args = init.minimal.args.iterate(); + _ = args.next(); + while (args.next()) |arg| { + if (std.mem.eql(u8, arg, "--orient")) orient = true; + if (std.mem.eql(u8, arg, "--paint")) paint = true; + if (std.mem.eql(u8, arg, "--fill")) fill = true; + if (std.mem.eql(u8, arg, "--sleep")) sleep = true; + if (std.mem.eql(u8, arg, "--scan")) scan = true; + if (std.mem.eql(u8, arg, "--background")) background = true; + if (std.mem.eql(u8, arg, "--logo")) logo = true; + if (std.mem.eql(u8, arg, "--diff")) diff = true; + if (std.mem.eql(u8, arg, "--idle")) idle = true; + if (std.mem.eql(u8, arg, "--wake")) wake = true; + if (std.mem.eql(u8, arg, "--transparent")) transparent = true; + if (std.mem.eql(u8, arg, "--composite")) composite = true; + } + + var decks: streamdeck.Enumerator = undefined; + try decks.init(io, alloc); + defer decks.deinit(io, alloc); + + while (try decks.next(io, alloc)) |found| { + defer found.deinit(io, alloc); + const sd = found.deck; + + try out.print("\n=== {t} ===\n", .{sd.type}); + + // What Elgato's application calls a background, done with the + // commands this library already has: paint the panel, then draw + // key images over only the keys that want one. A key left alone + // goes on showing the panel, which is exactly "the background + // shows where the foreground is transparent" -- with the + // transparency being the absence of a write rather than a + // property of the image. + if (composite) { + try tryComposite(io, alloc, &sd, out); + continue; + } + + // Store a background, then put flat colours on the first few + // keys. If a background shows where the foreground is + // "transparent", and the key images are JPEG -- which has no + // alpha channel at all -- then transparency has to mean some + // particular colour being treated as see-through. This tries + // the likely candidates one key at a time. + if (transparent) { + try tryTransparency(io, alloc, &sd, out); + continue; + } + + // Put back what `--idle` changed. + if (wake) { + sd.setSleepTimeout(io, 0) catch {}; + sd.setBrightness(io, 50) catch {}; + try out.print(" sleep disabled, brightness restored\n", .{}); + continue; + } + + // Store a background and then let the device go idle. If a + // "background" is simply what a device shows when it has + // nothing else to show, that would explain why the Classic + // family has a command to store one and none to display it. + if (idle) { + try tryBackgroundQuiet(io, alloc, &sd); + if (sd.setSleepTimeout(io, 5)) { + try out.print(" background stored, sleep timeout set to 5s\n", .{}); + } else |err| { + try out.print(" sleep timeout : {t}\n", .{err}); + } + continue; + } + + // Snapshot every feature report, store a background, and + // snapshot again. If storing one changes anything the device + // will admit to, it shows up here -- which distinguishes "it + // stored it and nothing displays it" from "it accepted the + // write and threw it away", without anyone having to look at + // the hardware. + if (diff) { + try diffAcrossBackground(io, alloc, &sd, out); + continue; + } + + // Show Logo, on its own. If Update Background replaces what a + // device shows when it has nothing else to show, then this is + // the command that puts a stored background up -- which would + // explain how the Classic family uses a background it has no + // Show Background command for. + if (logo) { + if (sd.reset(io)) { + try out.print(" show logo (0x03 0x02) : sent\n", .{}); + } else |err| { + try out.print(" show logo (0x03 0x02) : {t}\n", .{err}); + } + continue; + } + + if (background) { + try tryBackground(io, alloc, &sd, out); + continue; + } + + // Ask every possible feature report id and print the ones that + // answer with something. Reading a feature report is a + // Get_Report control request and changes nothing, so this is + // safe to point at whatever is attached -- and it finds the + // reports Elgato has not documented as well as the ones it has. + if (scan) { + try scanReports(io, &sd, out); + try out.print(" -- stability over 5 reads --\n", .{}); + try checkStability(io, &sd, out); + continue; + } + + // Round-trip the sleep timeout: read what it is, write + // something else, read it back, and put the original value + // returned. Reading alone proves nothing about the write, which + // is the half that had never been exercised. + if (sleep) { + try roundTripSleep(io, &sd, out); + continue; + } + + // `--paint` writes an image over the fill a moment later, which + // makes the fill impossible to see. This does the fill and + // nothing else, and leaves it up. + if (fill) { + try sd.setBrightness(io, 70); + if (sd.fillScreen(io, 0, 90, 0)) { + try out.print(" fillScreen green : ok -- left up\n", .{}); + } else |err| { + try out.print(" fillScreen green : {t}\n", .{err}); + } + continue; + } + + if (paint) { + try paintPanel(io, alloc, &sd, out); + continue; + } + + if (orient) { + try out.print(" key 0 = as the table has it key 1 = + flip left/right\n", .{}); + try out.print(" key 2 = + flip top/bottom key 3 = + half turn\n", .{}); + try showCorrections(io, alloc, &sd); + continue; + } + + var serial: [32]u8 = undefined; + try out.print("serial : {s}\n", .{sd.getSerialNumber(io, &serial) catch "?"}); + if (found.info.serial_number.slice()) |from_system| { + // The device and the system should agree about this. Where + // they do not, the device is the one that matters and the + // difference is worth seeing. + if (!std.mem.eql(u8, from_system, sd.getSerialNumber(io, &serial) catch "")) { + try out.print("serial (system) : {s}\n", .{from_system}); + } + } + inline for (streamdeck.StreamDeck.Firmware.all) |which| { + var version: [32]u8 = undefined; + if (sd.getFirmwareReport(io, which, &version)) |fw| { + // The word in front of the string: a checksum on the + // newer protocol, and what looks like an image byte + // count on the older. Printed both ways because which + // it is depends on the model. + try out.print("firmware {s:<11}: {s:<12} word=0x{x:0>8} ({d})\n", .{ + @tagName(which), fw.version, fw.checksum, fw.checksum, + }); + } else |err| switch (err) { + // A model without an encoder board has no such report, + // which is not worth a line of output. + error.Unsupported => {}, + else => try out.print("firmware {s:<11}: {t}\n", .{ @tagName(which), err }), + } + } + + if (sd.getSleepTimeout(io)) |seconds| { + try out.print("sleep timeout : {d}s\n", .{seconds}); + } else |err| { + try out.print("sleep timeout : {t}\n", .{err}); + } + + // What this library believes, out of its tables. + try out.print("table grid : {d} x {d} ({d} keys)\n", .{ + sd.keys.cols(), sd.keys.rows(), sd.keys.count(), + }); + if (sd.keys.getImageFeature(0)) |f| { + try out.print("table key image : {d}x{d} {t}, rotation {?t}, flip lr={} tb={}\n", .{ + f.width, f.height, f.image_format, f.rotation, f.flip_left_right, f.flip_top_bottom, + }); + } + + // What the device says, if it answers at all. + if (sd.getUnitInfo(io)) |unit| { + try out.print("device grid : {d} x {d} ({d} keys)\n", .{ + unit.cols, unit.rows, unit.count(), + }); + try out.print("device key image : {d}x{d}\n", .{ unit.key_width, unit.key_height }); + try out.print("device lcd : {d}x{d}\n", .{ unit.lcd_width, unit.lcd_height }); + try out.print("device bpp/scheme : {d} / {d}\n", .{ unit.image_bpp, unit.image_color_scheme }); + try out.print("device gallery : {d} key, {d} lcd, {d} demo frames\n", .{ + unit.key_gallery, unit.lcd_gallery, unit.demo_frames, + }); + } else |err| { + try out.print("device unit info : {t}\n", .{err}); + } + + // And the raw bytes of every getter, so that a layout this + // library has wrong is visible rather than merely wrong. + for ([_]u8{ 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0a, 0xa0, 0xa1, 0xa2, 0xa3 }) |report| { + var raw = std.mem.zeroes([32]u8); + raw[0] = report; + const answer = sd.device.getFeatureReport(io, &raw) catch continue; + if (answer.len == 0) continue; + + // `printable` writes into its scratch, so that scratch must + // not be the buffer `answer` points into -- the arguments + // are all evaluated before any of them is formatted, so + // sharing one buffer prints the dotted copy twice. + var text: [32]u8 = undefined; + try out.print(" report 0x{x:0>2} [{d:>2}] : {x} |{s}|\n", .{ + report, answer.len, answer, printable(answer, &text), + }); + } + } + + try out.flush(); +} + +/// Paint the panel, then draw over every other key. +fn tryComposite( + io: std.Io, + alloc: std.mem.Allocator, + sd: *const streamdeck.StreamDeck, + out: *std.Io.Writer, +) !void { + const feature = sd.panel.getFeature() orelse { + try out.print(" no writable panel\n", .{}); + return; + }; + + try sd.setBrightness(io, 70); + + var surface = (try sd.panel.blankImage(alloc)).?; + defer surface.deinit(alloc); + for (0..feature.height) |y| { + for (0..feature.width) |x| { + const on = ((x + y) / 24) % 2 == 0; + surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ + .r = if (on) 180 else 0, + .g = 0, + .b = if (on) 0 else 180, + } }); + } + } + + sd.panel.setImage(io, alloc, surface) catch |err| { + try out.print(" panel : {t}\n", .{err}); + return; + }; + try out.print(" panel : {d}x{d} diagonal stripes\n", .{ feature.width, feature.height }); + + // Now a foreground over the even keys only. + var drawn: usize = 0; + for (0..sd.keys.count()) |i| { + if (i % 2 == 1) continue; + const key: u8 = @intCast(i); + var figure = (try sd.keys.indexImage(alloc, key, .yellow_on_black)) orelse continue; + defer figure.deinit(alloc); + sd.keys.setImage(io, alloc, key, figure) catch continue; + drawn += 1; + } + try out.print(" foreground : {d} key(s) drawn; the odd-numbered keys left alone\n", .{drawn}); +} + +/// The colours worth trying as a transparency key, one per key. +const Candidate = struct { + name: []const u8, + r: u8, + g: u8, + b: u8, +}; + +const candidates = [_]Candidate{ + .{ .name = "black 0,0,0", .r = 0, .g = 0, .b = 0 }, + .{ .name = "white 255,255,255", .r = 255, .g = 255, .b = 255 }, + .{ .name = "magenta 255,0,255", .r = 255, .g = 0, .b = 255 }, + .{ .name = "green 0,255,0", .r = 0, .g = 255, .b = 0 }, + .{ .name = "grey 128,128,128", .r = 128, .g = 128, .b = 128 }, + .{ .name = "near-black 1,1,1", .r = 1, .g = 1, .b = 1 }, +}; + +/// Store a background and then paint each of the first few keys a flat +/// candidate colour, so that one look says which colour -- if any -- +/// lets the background through. +fn tryTransparency( + io: std.Io, + alloc: std.mem.Allocator, + sd: *const streamdeck.StreamDeck, + out: *std.Io.Writer, +) !void { + try sd.setBrightness(io, 70); + try tryBackgroundQuiet(io, alloc, sd); + + const feature = sd.keys.getImageFeature(0) orelse { + try out.print(" no key displays\n", .{}); + return; + }; + + for (candidates, 0..) |candidate, i| { + const key: u8 = @intCast(i); + if (sd.keys.getImageFeature(key) == null) break; + + var surface = try image_blank(alloc, feature.width, feature.height); + defer surface.deinit(alloc); + + // A flat fill, except for a thin marker stripe down the right + // edge in a colour nothing else uses, so that a key which went + // fully transparent can still be told from one that failed to + // draw at all. + for (0..feature.height) |y| { + for (0..feature.width) |x| { + const marker = x >= feature.width - 6; + surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ + .r = if (marker) 255 else candidate.r, + .g = if (marker) 200 else candidate.g, + .b = if (marker) 0 else candidate.b, + } }); + } + } + + sd.keys.setImage(io, alloc, key, surface) catch |err| { + try out.print(" key {d} {s:<20}: {t}\n", .{ key, candidate.name, err }); + continue; + }; + try out.print(" key {d} {s:<20}: drawn (amber stripe on its right edge)\n", .{ + key, candidate.name, + }); + } +} + +/// A black surface of the given size. `image.blankImage` is not public, +/// so this is the same thing through the public surface type. +fn image_blank(alloc: std.mem.Allocator, width: usize, height: usize) !z2d.Surface { + return try z2d.Surface.init(.image_surface_rgb, alloc, @intCast(width), @intCast(height)); +} + +/// Read all 256 feature reports into `into`. +fn snapshot(io: std.Io, sd: *const streamdeck.StreamDeck, into: *[256][32]u8) void { + for (0..256) |id| { + var raw = std.mem.zeroes([32]u8); + raw[0] = @intCast(id); + const answer = sd.device.getFeatureReport(io, &raw) catch { + into[id] = std.mem.zeroes([32]u8); + continue; + }; + into[id] = std.mem.zeroes([32]u8); + @memcpy(into[id][0..answer.len], answer); + } +} + +fn diffAcrossBackground( + io: std.Io, + alloc: std.mem.Allocator, + sd: *const streamdeck.StreamDeck, + out: *std.Io.Writer, +) !void { + if (sd.panel.getFeature() == null) { + try out.print(" no panel -- nothing to store\n", .{}); + return; + } + + var before = try alloc.create([256][32]u8); + defer alloc.destroy(before); + var after = try alloc.create([256][32]u8); + defer alloc.destroy(after); + + snapshot(io, sd, before); + try tryBackgroundQuiet(io, alloc, sd); + snapshot(io, sd, after); + + var changed: usize = 0; + for (0..256) |id| { + if (std.mem.eql(u8, &before[id], &after[id])) continue; + changed += 1; + try out.print(" 0x{x:0>2} before : {x}\n", .{ id, before[id] }); + try out.print(" after : {x}\n", .{after[id]}); + } + try out.print(" {d} report(s) changed across the upload\n", .{changed}); +} + +/// The upload half of `tryBackground`, without the printing, so that +/// the differential scan can run it between snapshots. +fn tryBackgroundQuiet( + io: std.Io, + alloc: std.mem.Allocator, + sd: *const streamdeck.StreamDeck, +) !void { + const feature = sd.panel.getFeature() orelse return; + + var surface = (try sd.panel.blankImage(alloc)).?; + defer surface.deinit(alloc); + for (0..feature.height) |y| { + for (0..feature.width) |x| { + const on = ((x + y) / 30) % 2 == 0; + surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ + .r = if (on) 200 else 0, + .g = 0, + .b = if (on) 0 else 200, + } }); + } + } + + const data = streamdeck.Panel.encodeImage(alloc, surface, feature) catch return; + defer alloc.free(data); + + const header = 8; + const max = 1024 - header; + 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([1024]u8); + packet[0] = 0x02; + packet[1] = 0x0d; + packet[2] = 0; + packet[3] = if (page.len < max) 1 else 0; + std.mem.writeInt(u16, packet[4..6], page_number, .little); + std.mem.writeInt(u16, packet[6..8], @intCast(page.len), .little); + @memcpy(packet[header..][0..page.len], page); + _ = sd.device.write(io, &packet) catch return; + } +} + +/// Try the background commands **whether or not** the tables say this +/// model has them. +/// +/// Elgato documents Update Background for the Classic and XL families +/// only, but `Get Unit Information` reports a gallery of LCD images on +/// a Neo, which is what a background slot is. The two cannot both be +/// right, and the device is the one worth asking -- so this writes the +/// packets itself rather than going through `Panel`, which would +/// refuse. +fn tryBackground( + io: std.Io, + alloc: std.mem.Allocator, + sd: *const streamdeck.StreamDeck, + out: *std.Io.Writer, +) !void { + const caps = sd.panel.backgrounds(); + try out.print(" table says : store={} show={}\n", .{ caps.can_store, caps.can_show }); + + if (sd.getUnitInfo(io)) |unit| { + try out.print(" device gallery : {d} key image(s), {d} lcd image(s)\n", .{ + unit.key_gallery, unit.lcd_gallery, + }); + } else |_| { + try out.print(" device gallery : not reported\n", .{}); + } + + const feature = sd.panel.getFeature() orelse { + try out.print(" no panel -- nothing to store\n", .{}); + return; + }; + + // Broad diagonal stripes, which no ordinary key image resembles, so + // that a background actually appearing is unmistakable. + var surface = (try sd.panel.blankImage(alloc)).?; + defer surface.deinit(alloc); + for (0..feature.height) |y| { + for (0..feature.width) |x| { + const on = ((x + y) / 30) % 2 == 0; + surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ + .r = if (on) 200 else 0, + .g = 0, + .b = if (on) 0 else 200, + } }); + } + } + + const data = streamdeck.Panel.encodeImage(alloc, surface, feature) catch |err| { + try out.print(" encode : {t}\n", .{err}); + return; + }; + defer alloc.free(data); + + // The background header, written here rather than by the library so + // that a model the library refuses can still be tried. + const header = 8; + const max = 1024 - header; + var iter = std.mem.window(u8, data, max, max); + var page_number: u16 = 0; + var wrote: usize = 0; + var failed: ?anyerror = null; + while (iter.next()) |page| : (page_number += 1) { + var packet = std.mem.zeroes([1024]u8); + packet[0] = 0x02; + packet[1] = 0x0d; + packet[2] = 0; // slot 0 + packet[3] = if (page.len < max) 1 else 0; + std.mem.writeInt(u16, packet[4..6], page_number, .little); // page, then + std.mem.writeInt(u16, packet[6..8], @intCast(page.len), .little); // length + @memcpy(packet[header..][0..page.len], page); + + _ = sd.device.write(io, &packet) catch |err| { + failed = err; + break; + }; + wrote += 1; + } + + if (failed) |err| { + try out.print(" upload slot 0 : refused after {d} page(s): {t}\n", .{ wrote, err }); + } else { + try out.print(" upload slot 0 : {d} page(s) accepted\n", .{wrote}); + } + + // And ask for it to be shown, again bypassing the table. + const show: extern struct { + byte0: u8 = 0x03, + byte1: u8 = 0x13, + index: u8 = 0, + } = .{}; + if (sd.device.sendFeatureReport(io, std.mem.asBytes(&show))) |_| { + try out.print(" show slot 0 : accepted\n", .{}); + } else |err| { + try out.print(" show slot 0 : {t}\n", .{err}); + } +} + +/// Try every feature report id and report the ones that answer with +/// something the device does not say to everything. +/// +/// A device answers *every* id rather than refusing the ones it does +/// not implement, so "it answered" means nothing on its own. What +/// separates a real report from a stub is that the stub is the same +/// whatever you ask for, so this works out the stub from ids nothing +/// could plausibly use and reports only what differs from it. +fn scanReports(io: std.Io, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { + // Derive the stub from a few high ids. If they disagree with each + // other there is no stub to subtract and everything gets printed. + var stub = std.mem.zeroes([32]u8); + var have_stub = false; + for ([_]u8{ 0xf0, 0xf7, 0xfe }) |id| { + var raw = std.mem.zeroes([32]u8); + raw[0] = id; + const answer = sd.device.getFeatureReport(io, &raw) catch continue; + if (answer.len < 32) continue; + if (!have_stub) { + @memcpy(&stub, answer[0..32]); + have_stub = true; + } else if (!std.mem.eql(u8, stub[1..], answer[1..32])) { + have_stub = false; + break; + } + } + if (have_stub) { + var text: [32]u8 = undefined; + try out.print(" stub (0xf0/f7/fe) : {x} |{s}|\n", .{ + stub[1..], printable(stub[1..], &text), + }); + } else { + try out.print(" no consistent stub -- printing everything\n", .{}); + } + + var found: usize = 0; + for (0..256) |id| { + var raw = std.mem.zeroes([32]u8); + raw[0] = @intCast(id); + const answer = sd.device.getFeatureReport(io, &raw) catch continue; + if (answer.len == 0) continue; + + // Everything past the echoed id, compared with the stub. + if (have_stub and answer.len == 32 and std.mem.eql(u8, stub[1..], answer[1..32])) continue; + + var content = false; + for (answer[1..]) |b| if (b != 0) { + content = true; + break; + }; + if (!content) continue; + + found += 1; + var text: [32]u8 = undefined; + try out.print(" 0x{x:0>2} [{d:>2}] : {x} |{s}|\n", .{ + id, answer.len, answer, printable(answer, &text), + }); + } + + try out.print(" {d} report(s) differ from the stub\n", .{found}); +} + +/// Read the firmware reports several times over and say whether the +/// word in front of the version string holds still. +/// +/// This matters because a value that drifts between reads is not a +/// checksum of anything, and one read cannot tell the difference. +fn checkStability(io: std.Io, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { + const ids = [_]u8{ 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0b, 0x0c, 0x11, 0x13, 0xa0, 0xa1, 0xa2 }; + const passes = 5; + + for (ids) |id| { + var words: [passes]u32 = undefined; + var strings: [passes][8]u8 = undefined; + var ok = true; + + for (0..passes) |pass| { + var raw = std.mem.zeroes([32]u8); + raw[0] = id; + const answer = sd.device.getFeatureReport(io, &raw) catch { + ok = false; + break; + }; + if (answer.len < 16) { + ok = false; + break; + } + words[pass] = std.mem.readInt(u32, answer[1..5], .little); + @memcpy(&strings[pass], answer[5..13]); + } + if (!ok) continue; + + var stable = true; + for (words[1..]) |w| if (w != words[0]) { + stable = false; + }; + var text_stable = true; + for (strings[1..]) |t| if (!std.mem.eql(u8, &strings[0], &t)) { + text_stable = false; + }; + + // Only worth printing for ids that said something at all. + if (words[0] == 0 and strings[0][0] == 0) continue; + + try out.print(" 0x{x:0>2} word[1..5]", .{id}); + for (words) |w| try out.print(" {x:0>8}", .{w}); + try out.print(" {s}{s}\n", .{ + if (stable) "STABLE" else "DRIFTS", + if (text_stable) "" else " (string drifts too!)", + }); + } +} + +/// Set the sleep timeout to something, read it back/// Set the sleep timeout to something, read it back, and restore +/// whatever it was. +fn roundTripSleep(io: std.Io, sd: *const streamdeck.StreamDeck, out: *std.Io.Writer) !void { + const before = sd.getSleepTimeout(io) catch |err| { + try out.print(" sleep: cannot read: {t}\n", .{err}); + return; + }; + try out.print(" sleep before : {d}s\n", .{before}); + + // Two values, so that a device that merely echoes the last thing + // written cannot pass by accident, and one of them is not the + // value it already had. + for ([_]u31{ 120, 3600 }) |wanted| { + sd.setSleepTimeout(io, wanted) catch |err| { + try out.print(" sleep set {d:<6} : {t}\n", .{ wanted, err }); + continue; + }; + + // The device does not apply the setting before it answers the + // next question: read straight back and it reports the value it + // held a moment ago. This waits instead of reporting a lag as + // a mismatch. + try io.sleep(.{ .nanoseconds = 1050 * std.time.ns_per_ms }, .awake); + + const got = sd.getSleepTimeout(io) catch |err| { + try out.print(" sleep set {d:<6} : wrote, cannot read back: {t}\n", .{ wanted, err }); + continue; + }; + try out.print(" sleep set {d:<6} : read back {d}s {s}\n", .{ + wanted, got, if (got == wanted) "OK" else "MISMATCH", + }); + } + + sd.setSleepTimeout(io, before) catch |err| { + try out.print(" sleep restore : {t}\n", .{err}); + return; + }; + try io.sleep(.{ .nanoseconds = 1050 * std.time.ns_per_ms }, .awake); + const after = sd.getSleepTimeout(io) catch 0; + try out.print(" sleep after : {d}s {s}\n", .{ + after, if (after == before) "(restored)" else "(NOT restored)", + }); +} + +/// Exercise the commands that came out of Elgato's own documentation +/// and had nothing in this library before: painting the whole screen +/// behind the keys, and filling a key with a colour instead of sending +/// it an image. +fn paintPanel( + io: std.Io, + alloc: std.mem.Allocator, + sd: *const streamdeck.StreamDeck, + out: *std.Io.Writer, +) !void { + try sd.setBrightness(io, 70); + + // A solid fill of the whole panel, which takes one feature report + // rather than an image. + if (sd.fillScreen(io, 0, 0, 80)) { + try out.print(" fillScreen : ok (dark blue)\n", .{}); + } else |err| { + try out.print(" fillScreen : {t}\n", .{err}); + } + + // Then an actual image over the whole panel: a coarse checkerboard, + // so that a panel written in the wrong order or the wrong place is + // obvious rather than plausible. + if (sd.panel.getFeature()) |feature| { + var surface = (try sd.panel.blankImage(alloc)).?; + defer surface.deinit(alloc); + + for (0..feature.height) |y| { + for (0..feature.width) |x| { + const on = ((x / 40) + (y / 40)) % 2 == 0; + // One corner is marked, so that a panel written + // upside down cannot look like one written correctly. + const corner = x < 80 and y < 80; + surface.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ + .r = if (corner) 255 else if (on) 90 else 0, + .g = if (corner) 0 else if (on) 90 else 0, + .b = if (corner) 0 else if (on) 90 else 0, + } }); + } + } + + if (sd.panel.setImage(io, alloc, surface)) { + try out.print(" panel image : ok ({d}x{d}, red square at top-left)\n", .{ + feature.width, feature.height, + }); + } else |err| { + try out.print(" panel image : {t}\n", .{err}); + } + } else { + try out.print(" panel image : no writable panel\n", .{}); + } + + // And one key filled with a colour rather than an image. + if (sd.fillKey(io, 0, 255, 200, 0)) { + try out.print(" fillKey 0 : ok (amber)\n", .{}); + } else |err| { + try out.print(" fillKey 0 : {t}\n", .{err}); + } +} + +/// One of the four corrections that a table can be wrong by, once the +/// rotation itself is right. Each is its own inverse, which is why +/// trying all four settles the matter rather than narrowing it. +const Correction = enum { none, flip_left_right, flip_top_bottom, half_turn }; + +/// Draw the same figure on the first four keys, each corrected +/// differently. Whichever key reads correctly names the correction the +/// model's table is missing. +fn showCorrections(io: std.Io, alloc: std.mem.Allocator, sd: *const streamdeck.StreamDeck) !void { + try sd.reset(io); + try sd.resetKeyStream(io); + try sd.setBrightness(io, 60); + + for ([_]Correction{ .none, .flip_left_right, .flip_top_bottom, .half_turn }, 0..) |correction, key| { + const feature = sd.keys.getImageFeature(@intCast(key)) orelse continue; + + var figure = try streamdeck.diagnostic.keyIndexImage( + alloc, + feature.width, + feature.height, + 12, + .yellow_on_black, + ); + defer figure.deinit(alloc); + + var corrected = try apply(alloc, figure, correction); + defer corrected.deinit(alloc); + + try sd.keys.setImage(io, alloc, @intCast(key), corrected); + } +} + +/// A copy of `surface` with `correction` applied. +fn apply(alloc: std.mem.Allocator, surface: z2d.Surface, correction: Correction) !z2d.Surface { + const width: usize = @intCast(surface.getWidth()); + const height: usize = @intCast(surface.getHeight()); + + var out: z2d.Surface = try .init(.image_surface_rgb, alloc, @intCast(width), @intCast(height)); + errdefer out.deinit(alloc); + + for (0..height) |y| { + for (0..width) |x| { + const sx = switch (correction) { + .none, .flip_top_bottom => x, + .flip_left_right, .half_turn => width - 1 - x, + }; + const sy = switch (correction) { + .none, .flip_left_right => y, + .flip_top_bottom, .half_turn => height - 1 - y, + }; + out.putPixel(@intCast(x), @intCast(y), surface.getPixel(@intCast(sx), @intCast(sy)).?); + } + } + + return out; +} + +/// The report with anything unprintable replaced by a dot, so that a +/// string inside it can be seen at a glance. +fn printable(data: []const u8, scratch: []u8) []const u8 { + for (data, 0..) |c, i| scratch[i] = if (c >= 0x20 and c < 0x7f) c else '.'; + return scratch[0..data.len]; +} -- knotmirror 0.0.1