From 126b10d6ce690d78703e199edf7a31b8b4584cd9 Mon Sep 17 00:00:00 2001 From: Eric Dahl Date: Mon, 16 Nov 2026 00:33:09 -0500 Subject: [PATCH] tools/lc6000-display: the jog-display research tools from #121 (Part of #165) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit jogbuild.py (encoder: 180° rotation, byte-sum 0E, plan writer, selftest), jogseq.swift (guarded sender), sysex_decode.py and mmon_list.py (capture readers), and two test images of our own. No third-party images or captures. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VCgWWsoPKWUFiYf5pcC5B5 --- tools/lc6000-display/README.md | 65 ++++++ tools/lc6000-display/images/deck-ring.png | Bin 0 -> 17924 bytes tools/lc6000-display/images/f-test.png | Bin 0 -> 2139 bytes tools/lc6000-display/jogbuild.py | 194 ++++++++++++++++++ tools/lc6000-display/jogseq.swift | 183 +++++++++++++++++ tools/lc6000-display/mmon_list.py | 12 ++ tools/lc6000-display/sysex_decode.py | 238 ++++++++++++++++++++++ 7 files changed, 692 insertions(+) create mode 100644 tools/lc6000-display/README.md create mode 100644 tools/lc6000-display/images/deck-ring.png create mode 100644 tools/lc6000-display/images/f-test.png create mode 100644 tools/lc6000-display/jogbuild.py create mode 100644 tools/lc6000-display/jogseq.swift create mode 100644 tools/lc6000-display/mmon_list.py create mode 100644 tools/lc6000-display/sysex_decode.py diff --git a/tools/lc6000-display/README.md b/tools/lc6000-display/README.md new file mode 100644 index 0000000..59efb96 --- /dev/null +++ b/tools/lc6000-display/README.md @@ -0,0 +1,65 @@ +# LC6000 jog display tools + +Research tools for the LC6000 PRIME's jog-wheel display, which is driven over its "WD" MIDI port (#121). They're +the groundwork for showing the active deck on the jog (#165). They're not part of the app, and none of them run in +CI. + +The protocol, with what each message does and what the unit answers, is written up on #121 (see its recipe comment). +In short: + +1. **Host hello** to the Controller port: `F0 00 02 0B 7F 10 60 00 04 04 01 01 00 F7`, then `F0 00 20 7F 01 F7`. + Without it, the unit refuses uploads (ack `06`). +2. **Upload** to WD: + - `90 01 00` + - `0A 01 00 06 0D` + - `0C`: the PNG's size + - `0D`: chunks of a 21-bit offset plus the data as an MSB-first 7-bit bitstream + - `0E`: slot `01`, then the PNG's 32-bit byte-sum as 8 nibbles +3. **Commit:** wait for the `01 10 0F 00 01 00` acks, then send `7E 00 06 01` and `10`. +4. **Show:** `0A 01 00 01 0D`, which displays image index 01. + +The display shows uploads **rotated 180°**, so images are sent pre-rotated. Uploads move about 3.1 KB/s, so they're +for what changes rarely, not real-time readouts. + +## Files + +| File | What it does | +|---|---| +| `jogbuild.py` | PNG in, upload out. `png` re-encodes a 198×198 PNG for the unit (rotated 180°, in the layout the unit has accepted). `plan` writes a `jogseq` plan. `selftest` runs round trips with no device. | +| `jogseq.swift` | Sends a plan to the unit once, listening on both ports. `dry` checks a plan and prints it. | +| `sysex_decode.py` | Reads a MIDI Monitor capture (`.mmon`, text export or `.syx`), groups the SysEx, and rebuilds image uploads as PNG files (`--dump DIR`). | +| `mmon_list.py` | Lists every message in a `.mmon`, with timing and "To"/"From" endpoints. | +| `images/deck-ring.png` | Our app icon at 198×198, as a source image, not rotated. | +| `images/f-test.png` | An upright F with a red square top-right. The orientation test: the unit shows it upside down with the square lower-left. | + +## Use + +```sh +cd tools/lc6000-display +python3 -I jogbuild.py selftest +python3 -I jogbuild.py plan images/deck-ring.png /tmp/deck-ring.plan +swiftc -O -swift-version 5 jogseq.swift -o /tmp/jogseq +/tmp/jogseq dry /tmp/deck-ring.plan # checks and prints; sends nothing +/tmp/jogseq send /tmp/deck-ring.plan # sends once: see the rules below +``` + +A plan is one message per line: ` WD|CTL `, or ` ACKS `, which +waits for that many accepted acks and stops the run on a refusal. Lines starting with `#` are comments. + +`jogseq` sends only what the protocol needs: +- **WD:** the `00 02 0B 7F 10` messages, the identity request, and `90 01 00`. +- **Controller:** Serato SysEx, the `cmd 60` host message, LED note-ons, and the identity request. + +It also refuses to send if the port names are ambiguous. + +## Rules + +- **Get an OK before sending to the hardware.** A stray note on WD resets the display (#143), and the host hello + changes the unit's mode. +- **No third-party data in this folder:** no other app's images, and no capture files. Test images are our own. +- **What was verified, and what's still a guess:** + - Verified: these exact images were uploaded and shown on hardware. Uploads were accepted (acks `00`), with the + hello first. + - Not yet tested: `plan` writes the protocol's minimal sequence. The verified runs also replayed a DJ app's LED + paint and identity requests on the Controller port, and four `0A` messages before the last. + - Trimming those is the bisect planned in #165. diff --git a/tools/lc6000-display/images/deck-ring.png b/tools/lc6000-display/images/deck-ring.png new file mode 100644 index 0000000000000000000000000000000000000000..57dd4b006166a453491f1098102a0c17569ed9d7 GIT binary patch literal 17924 zcmbSzXIK+m)NL9GC83wldsC2(pp*oVBE4IWOLPwDDSj2Ajyjuzh5)}RxNeP$3i(GLXs?-a%+#MnR}2nF(g zkMvNW|8M`lH%$|r96=xq$if7B@g{hEqyg1|;e=rl&9kw;ms|-xXG2wR%ojmwEZmy? zZz1yOgBB+Xo2J)Qbs#WiP6-SV1pfcs*@g9l>P_TX2K?gYdPQC~8`^sDV;qPwxwn)C z|9bPqw*e35-?_JbT`357{_*ADw|fWTEHyu)70L^o?|Eee1i3Zz40LQ}H&jjE_23zM zm5^X+xPw9hoeiz+gkxK)HdRo>X7{kezt3p=RZts{TkN*udbg zi_dFn+y@2*{^gPL-fOFC@58OO+ipZe0I~HiU$S4TDKCF`xhVaf`;tX-?8Tj~7O)Gd zDl)xV%u`%jzy2n;J0l}w<1)VBy}H(`sq21zJYIf&Rgedhws`}bs#;p(FY8~{s%t^( zUC${pcdBk9#X1!)D$$WE*~{X%G$;`hIP?w4zyS_4$Jw$i{UH3C-e@;}p4rlKd5mV$d@|X9iT#*AUR_mn(fpLO z@zlV8)6~pp7$hWn^=WGDH{S}hk*vOAa*<>6nKRMU&z;+6>nZC@k;Cz(rl&Alvcrp` z%gg)$sD~*4r*KGiawLPp?fjKlHx$3;3XQcdJn8Yt-$zQMz+sU3s>3VE&D~; z2@W64H~#l&r~Lbwq4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0lbBzLrOW+UP zC1t4sJW48wv*Wf+&k(hZu9UR1DK5#FySn&%zvaE1O*=pQ^U{2~y@Wqx{nGdA|61I; zms=h6M{>Dl_KVpM=CC!t)9&wiw&j|P=|1H;-jmmBuG+qi*&O)Ty6T)|<@M`3(&zp* z{LwcrST6F@LibvWZSzkX*ennK`}~zc?!_0o^33-ht3C2r`RoG6t_ojc^L{n0SB8=2 zE3e+3!TFd&Xn8AH@)D=^cx`wvLE-o$ym$K?SaLYW?V-ju$~fGu;co*Yt;!kIkPO! zT(-`<$ISOsN>WO4Z9r%+dw%Cpv4+J-hu5<)>S_ZI9FTvI@w6!6^}z{SLX4e4n%kZ< zsM|eZG`GAvVS4xv{##C7YtJ}j8TW>KRVbgds{Pulmk-s79K(mA9xAf7;7=XWa^ps4$)wrUG9_$B+A2HoWEJ@(B_a+UKEsRVV1`y%kWm=?5AZnb~+G3=+s=JTMUWYVbc-?C9~Qpwn19UHx3vIVCg!00B_ahyVZp literal 0 HcmV?d00001 diff --git a/tools/lc6000-display/images/f-test.png b/tools/lc6000-display/images/f-test.png new file mode 100644 index 0000000000000000000000000000000000000000..521e278e50712396af16ccc0e63ed10cbb099fa2 GIT binary patch literal 2139 zcmc&#Yfw|y7Cs^L@H#+1h8|HdTnYpQ$w@RtD{=!g5ao@n=5~rnNPu1WGzTCa^_^>cw z1DcxynEcNGQ)3AlPG|stNsY-Hq@xD=HaA|<@)>&pz^tDhMBSZ^nHfSXbBVw^QMRW8 z(+yU%Xv>(6D_1UuH2hYf65fa7wo&Br%A?)*r_>qN$#wv77_fv%S0wb)*n=y-`d|enpCw^hHG8_6+@@aq+B`^I(+S?J>RiZq@IHKcY<{Z zNvJG&`kuI?4Y!E)@b9X`g}KBPo;94qiq}3kK!P7RGXdJgRd=eL@3dxQQTByv@2C^T zx}v^G&V0(dxjXH`7vY;X`VOQGjA~LVDsSj#&QR?YM04!CaK&&j3-H^FS!0npuZ%|; z=sunm2?u-)BhPXZh_wYCew`H|pnm+)*OEMveoY#wcRXcuJ3uaecmS`fx3lZ;lGUw&NmeIMgy9mUwjI`VXV!HKg~TOullG?hvBv*L^Pmpx$) zs>qskW_7-vC0xy5CI2Dwg~TB{llKeL7q$`bpLw33ZciTQEmFx|7TIaTFNTV_F`wJe zHh^E~+%w!4rCJO+7_$!7V%{ZYRV@`?G zJ~xV@p42(!meJWLIGw!5iXr~{kh*uJY6(wpvPNud4c|A?D2+;?WS9R1H7Ip~f)wr!oZ z+EMD|el;KA_9c{T=iJNhPmZu+IIbF2l#?c#>CU8SMdA+^^1O~0%(6mP&uQMXt(a%E z3=af|+m#E%^UzCPalZN`@xkn8F5PVQ5jY0SqNoDnv*6i5?D;9idfE*?Zw@1rXB*d5)BFEu$LhwxQ@0~=Ce%6m>xPd?u#-E@ zOlF5|;K`MboY;+<>lI}`(|dM`x)!F~R*QFOgiUvAZ1x@V*t!wfFx*ha*}IAB+Odtje3r52 zal^?+hgJ+>LaHd?6AC@iI4!KP%EX=Y2bog!ir9`1Z=xvxjnWp zj)&%+9tK}NC^=(l{;kMv4L~cE&SgsVGiDHzNaF!;RAJfgvYF`5dfvSLO?B+T hqI8$+jo4qX_T`yXFM0P`35`RZ{$Y5~r2yu!KL7)|vi|@8 literal 0 HcmV?d00001 diff --git a/tools/lc6000-display/jogbuild.py b/tools/lc6000-display/jogbuild.py new file mode 100644 index 0000000..e1a18b0 --- /dev/null +++ b/tools/lc6000-display/jogbuild.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Builds the LC6000 jog-display upload (#121, #165): a 198x198 PNG in, a jogseq plan out. + + python3 -I jogbuild.py png re-encode for the unit: rotated 180°, the PNG layout it accepts + python3 -I jogbuild.py plan the full host + upload + commit + show plan for jogseq + python3 -I jogbuild.py selftest encoder round trips, no device + +The recipe, as verified on hardware (see #121's recipe comment): + CTL F0 00 02 0B 7F 10 60 00 04 04 01 01 00 F7, then F0 00 20 7F 01 F7 host hello (without it: ack 06) + WD 90 01 00, 0A 01 00 06 0D, 0C , 0D …, 0E + WD wait for the 01 10 0F 00 01 00 acks (06 = refused), then 7E 00 06 01, 10 (commit; unit answers 01 10 10) + WD 0A … 01 00 01 0D show image index 01 +Frame: F0 00 02 0B 10 F7. +""" +import struct +import sys +import zlib + +HEAD = [0x00, 0x02, 0x0B, 0x7F, 0x10] +SIZE = 198 +CHUNK = 14332 # the most image bytes whose 7-bit form (n*8//7 + 1) plus a 3-byte offset fits a 14-bit length + +HOST_HELLO = [ + [0xF0, 0x00, 0x02, 0x0B, 0x7F, 0x10, 0x60, 0x00, 0x04, 0x04, 0x01, 0x01, 0x00, 0xF7], + [0xF0, 0x00, 0x20, 0x7F, 0x01, 0xF7], +] +HOST_GOODBYE = [0xF0, 0x00, 0x20, 0x7F, 0x02, 0xF7] +SHOW_BLANK = [0x01, 0x00, 0x06, 0x0D] # 0A before an upload: image index 06 +SHOW_INDEX_1 = [0x01, 0x00, 0x01, 0x0D] # 0A after the commit: image index 01, the upload + + +def frame(cmd, payload): + n = len(payload) + return [0xF0, *HEAD, cmd, n >> 7, n & 0x7F, *payload, 0xF7] + + +def u21(value): + return [(value >> 14) & 0x7F, (value >> 7) & 0x7F, value & 0x7F] + + +def bits7(data): + """MSB-first bitstream into 7-bit bytes, zero-padded: len(data)*8//7 + 1 bytes.""" + out, acc, nbits = [], 0, 0 + for byte in data: + acc, nbits = (acc << 8) | byte, nbits + 8 + while nbits >= 7: + nbits -= 7 + out.append((acc >> nbits) & 0x7F) + out.append((acc << (7 - nbits)) & 0x7F if nbits else 0) + return out + + +def commit_0e(png, slot=1): + """0E: the slot, then the PNG's 32-bit byte-sum as 8 nibbles, most significant first.""" + total = sum(png) & 0xFFFFFFFF + return [slot] + [(total >> shift) & 0x0F for shift in range(28, -4, -4)] + + +def upload(png, slot=1): + """0A (index 06), 0C size, 0D chunks, 0E checksum, 10 commit.""" + msgs = [frame(0x0A, SHOW_BLANK), frame(0x0C, u21(len(png)))] + for offset in range(0, len(png), CHUNK): + msgs.append(frame(0x0D, u21(offset) + bits7(png[offset:offset + CHUNK]))) + msgs += [frame(0x0E, commit_0e(png, slot)), frame(0x10, [])] + return msgs + + +# PNG in and out. Only 8-bit RGB and RGBA, not interlaced: what this tool makes and reads. + +def chunks(png): + pos = 8 + while pos < len(png): + n, kind = struct.unpack('>I4s', png[pos:pos + 8]) + yield kind, png[pos + 8:pos + 8 + n] + pos += 12 + n + + +def decode_rgba(png): + """Rows of RGBA bytes from an 8-bit RGB or RGBA PNG.""" + header = dict(chunks(png))[b'IHDR'] + width, height, depth, kind, _, _, interlace = struct.unpack('>IIBBBBB', header) + if depth != 8 or kind not in (2, 6) or interlace: + raise SystemExit(f"need an 8-bit RGB or RGBA PNG, not interlaced (got depth {depth}, type {kind})") + bpp = 4 if kind == 6 else 3 + raw = zlib.decompress(b''.join(body for k, body in chunks(png) if k == b'IDAT')) + stride, rows, prev = width * bpp, [], bytearray(width * bpp) + for y in range(height): + kind_ = raw[y * (stride + 1)] + line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)]) + for i in range(stride): + a = line[i - bpp] if i >= bpp else 0 + b = prev[i] + c = prev[i - bpp] if i >= bpp else 0 + if kind_ == 1: + line[i] = (line[i] + a) & 255 + elif kind_ == 2: + line[i] = (line[i] + b) & 255 + elif kind_ == 3: + line[i] = (line[i] + ((a + b) >> 1)) & 255 + elif kind_ == 4: + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255 + prev = line + rows.append(bytes(line) if bpp == 4 else b''.join(bytes(line[i:i + 3]) + b'\xff' for i in range(0, stride, 3))) + return width, height, rows + + +def rotate180(rows): + """The unit shows uploads rotated 180° (#121's F test), so they're sent pre-rotated.""" + return [b''.join(row[i:i + 4] for i in range(len(row) - 4, -4, -4)) for row in reversed(rows)] + + +def _chunk(kind, body): + return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body)) + + +def exif_dimensions(width, height): + """A minimal eXIf: a big-endian TIFF header, an Exif IFD pointer, and PixelX/YDimension (as on the tested files).""" + tiff = b'MM\x00\x2a' + struct.pack('>I', 8) + ifd0 = struct.pack('>H', 1) + struct.pack('>HHII', 0x8769, 4, 1, 26) + struct.pack('>I', 0) + exif = struct.pack('>H', 2) + struct.pack('>HHII', 0xA002, 4, 1, width) + struct.pack('>HHII', 0xA003, 4, 1, height) + return tiff + ifd0 + exif + struct.pack('>I', 0) + + +def encode(width, height, rows): + """RGBA PNG laid out as the unit has accepted: IHDR, sRGB, eXIf, IDAT in 16384-byte pieces of a + several-block zlib stream (level 1), IEND. Row filter 0.""" + raw = b''.join(b'\x00' + row for row in rows) + compressor = zlib.compressobj(1, zlib.DEFLATED, 15, 1) + data = compressor.compress(raw) + compressor.flush() + png = b'\x89PNG\r\n\x1a\n' + _chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0)) + png += _chunk(b'sRGB', b'\x00') + _chunk(b'eXIf', exif_dimensions(width, height)) + for i in range(0, len(data), 16384): + png += _chunk(b'IDAT', data[i:i + 16384]) + return png + _chunk(b'IEND', b'') + + +def for_unit(png): + width, height, rows = decode_rgba(png) + if (width, height) != (SIZE, SIZE): + raise SystemExit(f"the jog display takes {SIZE}x{SIZE}, not {width}x{height}") + return encode(width, height, rotate180(rows)) + + +def hexs(msg): + return ' '.join(f'{b:02X}' for b in msg) + + +def plan(png): + """A jogseq plan: hello, upload, wait for the acks, commit, show index 01.""" + msgs = upload(png) + body, commit = msgs[:-1], msgs[-1] + lines = ["# LC6000 jog upload (#121): host hello, upload, acks, commit, show index 01"] + lines += [f"0 CTL {hexs(m)}" for m in HOST_HELLO] + lines.append("0 WD 90 01 00") + lines += [f"{8 if i == 1 else 0} WD {hexs(m)}" for i, m in enumerate(body)] + # Each upload message but one is acked: the count seen on hardware. + lines.append(f"0 ACKS {len(body) - 1} 20000") + lines.append(f"0 WD {hexs([0xF0, 0x7E, 0x00, 0x06, 0x01, 0xF7])}") + lines.append(f"10 WD {hexs(commit)}") + lines.append(f"500 WD {hexs(frame(0x0A, SHOW_INDEX_1))}") + return '\n'.join(lines) + '\n' + + +def selftest(): + import os + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + import sysex_decode + rows = [b''.join(bytes([x, y, (x * y) & 255, 255]) for x in range(SIZE)) for y in range(SIZE)] + png = encode(SIZE, SIZE, rows) + assert decode_rgba(png)[2] == rows, "PNG round trip" + assert rotate180(rotate180(rows)) == rows, "two half turns are none" + assert rotate180(rows)[0][:4] == rows[-1][-4:], "the last pixel comes first" + assert sysex_decode.unbits(bits7(png))[:len(png)] == png, "7-bit bitstream round trip" + messages = [("?", m) for m in upload(png)] + assert sysex_decode.lc6000_images(messages) == [png], "upload rebuilds to the same PNG" + assert commit_0e(bytes([1, 2, 3])) == [1, 0, 0, 0, 0, 0, 0, 0, 6], "byte-sum as nibbles" + assert commit_0e(bytes([0xFF] * 0x3AEE))[1:] == [(0x3AEE * 0xFF >> s) & 0xF for s in range(28, -4, -4)] + print("selftest ok:", len(png), "byte PNG,", len(messages), "messages") + + +if __name__ == '__main__': + if len(sys.argv) == 2 and sys.argv[1] == 'selftest': + selftest() + elif len(sys.argv) == 4 and sys.argv[1] in ('png', 'plan'): + source = open(sys.argv[2], 'rb').read() + if sys.argv[1] == 'png': + open(sys.argv[3], 'wb').write(for_unit(source)) + else: + open(sys.argv[3], 'w').write(plan(for_unit(source))) + else: + print(__doc__) + sys.exit(2) diff --git a/tools/lc6000-display/jogseq.swift b/tools/lc6000-display/jogseq.swift new file mode 100644 index 0000000..e116ef6 --- /dev/null +++ b/tools/lc6000-display/jogseq.swift @@ -0,0 +1,183 @@ +import CoreMIDI +import Foundation + +// Sends a jog-display plan to the LC6000 (#121, #165), listening on both of its ports. Plan lines: +// WD send to "Denon DJ LC6000 PRIME WD" +// CTL send to the Controller (Serato SysEx 00 20 7F only) +// ACKS wait until n `01 10 0F` acks have arrived on WD since the last ACKS +// # comment +// `dry ` checks and prints the plan, sends nothing. `send ` sends it once, listening on both sources. +let wdName = "Denon DJ LC6000 PRIME WD" +let ctlName = "Denon DJ LC6000 PRIME LC6000 PRIME Controller" + +func name(_ e: MIDIEndpointRef) -> String { + var s: Unmanaged? + MIDIObjectGetStringProperty(e, kMIDIPropertyDisplayName, &s) + return (s?.takeRetainedValue() as String?) ?? "?" +} +func hex(_ b: [UInt8], _ n: Int = 12) -> String { + b.prefix(n).map { String(format: "%02X", $0) }.joined(separator: " ") + (b.count > n ? " … (\(b.count) B)" : "") +} + +enum Step { case send(port: String, bytes: [UInt8]); case acks(count: Int, timeoutMs: Int) } +let args = CommandLine.arguments +guard args.count == 3, ["dry", "send"].contains(args[1]) else { print("usage: dry|send "); exit(2) } +var plan: [(delay: Int, step: Step)] = [] +for (n, raw) in try String(contentsOfFile: args[2], encoding: .utf8).split(separator: "\n").enumerated() { + let line = raw.trimmingCharacters(in: .whitespaces) + if line.isEmpty || line.hasPrefix("#") { continue } + let p = line.split(separator: " ").map(String.init) + func fail(_ why: String) -> Never { print("ABORT line \(n + 1): \(why): \(line)"); exit(1) } + guard p.count >= 3, let delay = Int(p[0]) else { fail("bad line") } + switch p[1] { + case "ACKS": + guard let c = Int(p[2]), p.count == 4, let t = Int(p[3]) else { fail("ACKS ") } + plan.append((delay, .acks(count: c, timeoutMs: t))) + case "WD", "CTL": + let bytes = p.dropFirst(2).map { UInt8($0, radix: 16) } + guard bytes.allSatisfy({ $0 != nil }) else { fail("not hex (placeholder still in the plan?)") } + let b = bytes.map { $0! } + let sysexOK = b.first == 0xF0 && b.last == 0xF7 && b.dropFirst().dropLast().allSatisfy { $0 < 0x80 } + if p[1] == "CTL" { + // Serato SysEx, or the Denon host message a DJ app sends at launch (cmd 60). + let hostHello: [UInt8] = [0xF0, 0x00, 0x02, 0x0B, 0x7F, 0x10, 0x60, 0x00, 0x04, 0x04, 0x01, 0x01, 0x00, 0xF7] + // A host's launch also sends LED note-ons on ch1-4 and identity requests to the Controller. + let ledNote = b.count == 3 && (0x90...0x93).contains(b[0]) && b[1] < 0x80 && b[2] < 0x80 + let identity = b == [0xF0, 0x7E, 0x00, 0x06, 0x01, 0xF7] + guard ledNote || identity || (sysexOK && (Array(b[1...3]) == [0x00, 0x20, 0x7F] || b == hostHello)) else { + fail("Controller takes only Serato SysEx, the cmd 60 host hello, LED note-ons or an identity request") + } + } else { + let denon = sysexOK && Array(b[1...5]) == [0x00, 0x02, 0x0B, 0x7F, 0x10] + let identity = b == [0xF0, 0x7E, 0x00, 0x06, 0x01, 0xF7] + guard denon || identity || b == [0x90, 0x01, 0x00] else { fail("WD takes 00 02 0B 7F 10 SysEx, identity request, or 90 01 00") } + } + plan.append((delay, .send(port: p[1], bytes: b))) + default: fail("port must be WD, CTL or ACKS") + } +} +for (i, s) in plan.enumerated() { + switch s.step { + case .send(let port, let b): print("plan #\(i) +\(s.delay) ms \(port): \(hex(b))") + case .acks(let c, let t): print("plan #\(i) +\(s.delay) ms wait for \(c) acks (max \(t) ms)") + } +} +if args[1] == "dry" { exit(0) } + +let dests = (0.. MIDIEndpointRef { + let m = list.filter { name($0) == n } + guard m.count == 1 else { print("ABORT: \(m.count) endpoints named \(n)"); exit(1) } + return m[0] +} +let dest = ["WD": one(dests, wdName), "CTL": one(dests, ctlName)] +let wdSource = one(sources, wdName), ctlSource = one(sources, ctlName) + +var client = MIDIClientRef() +guard MIDIClientCreateWithBlock("jog-seq" as CFString, &client, nil) == noErr else { print("ABORT: client"); exit(1) } +var outPort = MIDIPortRef() +guard MIDIOutputPortCreate(client, "out" as CFString, &outPort) == noErr else { print("ABORT: out port"); exit(1) } + +final class Acks: @unchecked Sendable { + let lock = NSLock(); var count = 0; var refused = false + func add() { lock.withLock { count += 1 } } + func refuse() { lock.withLock { refused = true } } + var anyRefused: Bool { lock.withLock { refused } } + func take() -> Int { lock.withLock { defer { count = 0 }; return count } } +} +let acks = Acks() +let t0 = Date() +func since() -> String { String(format: "+%8.3f s", Date().timeIntervalSince(t0)) } + +/// Rebuilds SysEx from UMP SysEx7 packets, per source; logs every complete message and voice message. +final class Reassembler: @unchecked Sendable { + let label: String; var buf: [UInt8] = [] + init(_ label: String) { self.label = label } + func feed(_ words: [UInt32]) { + var i = 0 + while i < words.count { + let w0 = words[i], type = w0 >> 28 + if type == 3, i + 1 < words.count { + let w1 = words[i + 1], status = (w0 >> 20) & 0xF, n = Int((w0 >> 16) & 0xF) + let bytes = [UInt8((w0 >> 8) & 0xFF), UInt8(w0 & 0xFF), UInt8(w1 >> 24), UInt8((w1 >> 16) & 0xFF), + UInt8((w1 >> 8) & 0xFF), UInt8(w1 & 0xFF)].prefix(n) + if status == 0 || status == 1 { buf = [] } + buf += bytes + if status == 0 || status == 3 { + let msg = [0xF0] + buf + [0xF7] + // An ack is 01 10 0F 00 01 : 00 accepted; anything else (06 seen) is a refusal. + if Array(buf.prefix(6)) == [0x00, 0x02, 0x0B, 0x01, 0x10, 0x0F] { + if buf.last == 0x00 { acks.add() } else { acks.refuse() } + } + print("\(since()) RECV \(label): \(hex(msg, 40))") + } + i += 2 + } else if type == 2 { + let b = [UInt8((w0 >> 16) & 0xFF), UInt8((w0 >> 8) & 0xFF), UInt8(w0 & 0xFF)] + // The heartbeat (note 52 every 300 ms) would drown the log. + if !(b[0] & 0xF0 == 0x90 && b[1] == 0x34) { print("\(since()) RECV \(label): \(hex(b))") } + i += 1 + } else { i += [1, 1, 1, 2, 2, 4, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4][Int(type)] } + } + } +} +let wdIn = Reassembler("WD"), ctlIn = Reassembler("CTL") +var inPort = MIDIPortRef() +guard MIDIInputPortCreateWithProtocol(client, "in" as CFString, ._1_0, &inPort, { list, ref in + let r = Unmanaged.fromOpaque(ref!).takeUnretainedValue() + for packet in list.unsafeSequence() { r.feed(Array(packet.words())) } +}) == noErr, + MIDIPortConnectSource(inPort, wdSource, Unmanaged.passUnretained(wdIn).toOpaque()) == noErr, + MIDIPortConnectSource(inPort, ctlSource, Unmanaged.passUnretained(ctlIn).toOpaque()) == noErr +else { print("ABORT: listen"); exit(1) } + +final class Done: @unchecked Sendable { var flag = false } +func send(_ bytes: [UInt8], to d: MIDIEndpointRef) -> Bool { + if bytes.first != 0xF0 { + var list = MIDIEventList() + let packet = MIDIEventListInit(&list, ._1_0) + let word = 0x2000_0000 | UInt32(bytes[0]) << 16 | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) + _ = MIDIEventListAdd(&list, MemoryLayout.size, packet, 0, 1, [word]) + return MIDISendEventList(outPort, d, &list) == noErr + } + let buffer = UnsafeMutablePointer.allocate(capacity: bytes.count) + buffer.initialize(from: bytes, count: bytes.count) + defer { buffer.deallocate() } + let done = Done() + let req = UnsafeMutablePointer.allocate(capacity: 1) + defer { req.deallocate() } + req.initialize(to: MIDISysexSendRequest(destination: d, data: UnsafePointer(buffer), bytesToSend: UInt32(bytes.count), + complete: false, reserved: (0, 0, 0), completionProc: { r in + Unmanaged.fromOpaque(r.pointee.completionRefCon!).takeUnretainedValue().flag = true + }, completionRefCon: Unmanaged.passUnretained(done).toOpaque())) + guard MIDISendSysex(req) == noErr else { return false } + let deadline = Date().addingTimeInterval(15) + while !done.flag && Date() < deadline { RunLoop.current.run(until: Date().addingTimeInterval(0.005)) } + return done.flag && req.pointee.bytesToSend == 0 +} + +print("\(since()) listening on WD and CTL") +var acked = 0 +for (i, s) in plan.enumerated() { + RunLoop.current.run(until: Date().addingTimeInterval(Double(s.delay) / 1000)) + switch s.step { + case .send(let port, let b): + let ok = send(b, to: dest[port]!) + print("\(since()) SENT #\(i) \(port): \(hex(b)) \(ok ? "ok" : "FAILED")") + if !ok { print("STOP: send failed; the rest not sent"); exit(1) } + case .acks(let c, let t): + let deadline = Date().addingTimeInterval(Double(t) / 1000) + while acked < c && Date() < deadline && !acks.anyRefused { + acked += acks.take() + RunLoop.current.run(until: Date().addingTimeInterval(0.01)) + } + acked += acks.take() + print("\(since()) ACKS \(acked)/\(c)") + if acks.anyRefused { print("STOP: the unit refused (ack status not 00); the rest not sent"); exit(1) } + if acked < c { print("STOP: acks missing; the rest not sent"); exit(1) } + acked = 0 + } +} +RunLoop.current.run(until: Date().addingTimeInterval(3)) +print("\(since()) done") diff --git a/tools/lc6000-display/mmon_list.py b/tools/lc6000-display/mmon_list.py new file mode 100644 index 0000000..b9b0b26 --- /dev/null +++ b/tools/lc6000-display/mmon_list.py @@ -0,0 +1,12 @@ +"""Lists every message in a MIDI Monitor .mmon: index, ms since start, endpoint ("To X"/"From X"), hex.""" +import plistlib, sys +p = plistlib.load(open(sys.argv[1], 'rb')); a = plistlib.loads(p['messageData']); O = a['$objects'] +d = lambda u: O[u.data] if isinstance(u, plistlib.UID) else u +msgs = [d(u) for u in d(a['$top']['root'])['NS.objects']] +t0 = msgs[0]['timeStampInNanos'] +for i, m in enumerate(msgs): + ep = d(m.get('originatingEndpoint')); ep = ep if isinstance(ep, str) else '?' + status = m.get('statusByte'); data = d(m.get('data', m.get('dataBytes', b''))) + raw = bytes([status]) + data if status != 0xF0 else b'\xf0' + data + b'\xf7' + h = raw.hex(' ').upper() + print(f"{i:4} {(m['timeStampInNanos'] - t0) / 1e6:10.1f} ms {ep:40} {len(raw):6} B {h[:66]}{'…' if len(h) > 66 else ''}") diff --git a/tools/lc6000-display/sysex_decode.py b/tools/lc6000-display/sysex_decode.py new file mode 100644 index 0000000..61e4780 --- /dev/null +++ b/tools/lc6000-display/sysex_decode.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Decoder for LC6000 jog-display SysEx (#121): splits a MIDI Monitor capture into messages and rebuilds image uploads. + +Input: a MIDI Monitor text export (File > Export, or copy-paste of the event list with +"Show SysEx data as hex"), or a raw .syx dump (MIDI Monitor > Save SysEx). Any text whose +lines carry hex byte pairs works: SysEx spanning several lines is joined until F7. + + python3 -I sysex-decode.py capture.txt # summary + python3 -I sysex-decode.py capture.syx --dump out # also write payload bursts, decoded + +What it prints: + 1. Each SysEx split out, grouped by header. Denon/inMusic (00 02 0B) is parsed as the Prime 4 + layout (github.com/whanake-music/denon-prime-4-analysis): + F0 00 02 0B F7 + with len a 14-bit count of payload bytes; a mismatch is flagged. + 2. Bursts: runs of the same (target, class, cmd) back to back, with their total payload. + 3. Image guesses: each burst's payload size against WxH x bytes-per-pixel under the + packings a 7-bit SysEx stream can use (nibbles, 7-in-8, raw 7-bit). +No device I/O: this only reads a file. +""" +import re +import sys +from collections import OrderedDict, defaultdict +from pathlib import Path + +DENON = (0x00, 0x02, 0x0B) +SIZES = [(320, 320), (240, 240), (480, 480), (360, 360), (128, 128), (320, 240), (240, 320)] +FORMATS = [("RGB565", 2), ("RGB888", 3), ("ARGB8888", 4), ("gray8", 1), ("gray4", 0.5), ("mono1", 0.125)] +# Bytes on the wire per byte of image data, for each 7-bit packing. +PACKINGS = [("nibbles (2 wire B per B)", 2.0), ("7-in-8 (8 per 7)", 8 / 7), ("raw 7-bit", 1.0)] + +HEX = re.compile(r"\b[0-9A-Fa-f]{2}\b") + + +def read_mmon(data): + """A MIDI Monitor document: a plist whose messageData is a keyed archive of SMMessages.""" + import plistlib + archive = plistlib.loads(plistlib.loads(data)["messageData"]) + objects = archive["$objects"] + deref = lambda u: objects[u.data] if isinstance(u, plistlib.UID) else u + chunks = [] + for u in deref(archive["$top"]["root"])["NS.objects"]: + m = deref(u) + if deref(m["$class"])["$classname"] == "SMSystemExclusiveMessage": + chunks.append(("?", [0xF0, *deref(m.get("data", b"")), 0xF7])) + return chunks + + +def read_bytes(path): + """Returns [(direction, bytes)] chunks. Binary .syx is one chunk; text is one per line.""" + data = Path(path).read_bytes() + if data.startswith(b"bplist00"): + return read_mmon(data) + if data[:1] == b"\xF0": + return [("?", list(data))] + chunks = [] + for line in data.decode("utf-8", "replace").splitlines(): + lower = line.lower() + direction = "to" if re.search(r"\bto\b", lower) else "from" if re.search(r"\bfrom\b", lower) else "?" + # Only the hex run that holds SysEx bytes: drop timestamps like 12:34:56.789. + tokens = [int(t, 16) for t in HEX.findall(re.sub(r"\d+:\d+:\d+(\.\d+)?", " ", line))] + if tokens: + chunks.append((direction, tokens)) + return chunks + + +def split_sysex(chunks): + """Yields (direction, message) for each F0…F7, joining messages that span chunks.""" + current, direction = None, "?" + for d, data in chunks: + for b in data: + if b == 0xF0: + current, direction = [b], d + elif current is not None: + current.append(b) + if b == 0xF7: + yield direction, current + current = None + if current: + yield direction, current + ["(unterminated)"] + + +def parse(msg): + body = [b for b in msg[1:] if isinstance(b, int) and b != 0xF7] + if not body: + return {"maker": "empty"} + if body[0] == 0x00 and len(body) >= 3: + maker, rest = tuple(body[:3]), body[3:] + else: + maker, rest = (body[0],), body[1:] + info = {"maker": " ".join(f"{b:02X}" for b in maker), "rest": rest} + if maker == DENON and len(rest) >= 5: + target, cls, cmd, hi, lo = rest[:5] + payload = rest[5:] + declared = (hi << 7) | lo + info.update(key=(target, cls, cmd), payload=payload, declared=declared, ok=declared == len(payload)) + elif maker == (0x7E,) or maker == (0x7F,): + info.update(key=("universal", *rest[:3]), payload=rest) + else: + info.update(key=tuple(rest[:3]), payload=rest) + return info + + +def hexs(bs, limit=24): + s = " ".join(f"{b:02X}" for b in bs[:limit]) + return s + (f" … (+{len(bs) - limit})" if len(bs) > limit else "") + + +def image_guesses(n): + out = [] + for (w, h) in SIZES: + for fmt, bpp in FORMATS: + raw = w * h * bpp + for pack, factor in PACKINGS: + wire = raw * factor + if wire and abs(n - wire) / wire < 0.02: + out.append((abs(n - int(wire)), f"{w}x{h} {fmt}, {pack}: expect {int(wire)} B ({n - int(wire):+d})")) + return [text for _, text in sorted(out, key=lambda t: t[0])] + + +def unnibble(p): + return bytes(((p[i] & 0x0F) << 4) | (p[i + 1] & 0x0F) for i in range(0, len(p) - 1, 2)) + + +def unpack78(p): + """MSB-first 7-in-8: a header byte holds bit 7 of the next seven bytes (Roland/Elektron style).""" + out = bytearray() + for i in range(0, len(p), 8): + group = p[i:i + 8] + if not group: + break + msbs = group[0] + for j, b in enumerate(group[1:]): + out.append(b | (((msbs >> (6 - j)) & 1) << 7)) + return bytes(out) + + +def unbits(seven): + """MSB-first bitstream: 7 bits from each byte, back to back, read as 8-bit bytes (#121).""" + acc = nbits = 0 + out = bytearray() + for b in seven: + acc, nbits = (acc << 7) | (b & 0x7F), nbits + 7 + if nbits >= 8: + nbits -= 8 + out.append((acc >> nbits) & 0xFF) + return bytes(out) + + +def lc6000_images(messages): + """The LC6000 jog image upload (#121): 0C <21-bit size>, then 0D chunks of + <21-bit offset into the image> + MSB-first 7-bit bitstream. The image is a PNG.""" + images, size, image = [], None, bytearray() + for _, m in messages: + info = parse(m) + key, p = info.get("key"), info.get("payload", []) + if info["maker"] != "00 02 0B" or not key or len(p) < 3: + continue + value = (p[0] << 14) | (p[1] << 7) | p[2] + if key[2] == 0x0C: + size, image = value, bytearray() + elif key[2] == 0x0D and size is not None: + if value != len(image): + print(f" chunk offset {value} != {len(image)} so far: gap or reorder") + image += unbits(p[3:]) + if len(image) >= size: + images.append(bytes(image[:size])) + size = None + return images + + +def main(argv): + if len(argv) < 2: + print(__doc__) + return 2 + dump = Path(argv[argv.index("--dump") + 1]) if "--dump" in argv else None + messages = list(split_sysex(read_bytes(argv[1]))) + print(f"{len(messages)} SysEx messages\n") + + groups = OrderedDict() + for d, m in messages: + info = parse(m) + k = (d, info["maker"], info.get("key")) + g = groups.setdefault(k, {"n": 0, "sizes": defaultdict(int), "first": m, "bad": 0}) + g["n"] += 1 + g["sizes"][len(m)] += 1 + g["bad"] += 0 if info.get("ok", True) else 1 + + print("== Groups (direction, maker, key = target/class/cmd for Denon) ==") + for (d, maker, key), g in groups.items(): + k = " ".join(f"{x:02X}" if isinstance(x, int) else str(x) for x in (key or ())) + sizes = ", ".join(f"{s} B x{c}" for s, c in sorted(g["sizes"].items())[:6]) + flag = f" LEN MISMATCH x{g['bad']}" if g["bad"] else "" + print(f"{d:>4} {maker:8} [{k}] x{g['n']} sizes: {sizes}{flag}") + print(f" first: {hexs(g['first'])}") + + print("\n== Bursts (same key back to back) ==") + bursts = [] + for d, m in messages: + info = parse(m) + k = (d, info["maker"], info.get("key")) + if bursts and bursts[-1]["k"] == k: + bursts[-1]["msgs"] += 1 + bursts[-1]["payload"] += info.get("payload", []) + else: + bursts.append({"k": k, "msgs": 1, "payload": list(info.get("payload", []))}) + for i, b in enumerate(bursts): + d, maker, key = b["k"] + k = " ".join(f"{x:02X}" if isinstance(x, int) else str(x) for x in (key or ())) + n = len(b["payload"]) + line = f"#{i:<3} {d:>4} {maker} [{k}] {b['msgs']} msgs, {n} payload B" + print(line) + for guess in image_guesses(n) if n > 1000 else []: + print(f" image? {guess}") + if dump and n > 1000: + dump.mkdir(parents=True, exist_ok=True) + base = dump / f"burst{i:03d}" + Path(f"{base}.raw").write_bytes(bytes(b["payload"])) + Path(f"{base}.nib").write_bytes(unnibble(b["payload"])) + Path(f"{base}.78").write_bytes(unpack78(b["payload"])) + images = lc6000_images(messages) + if images: + print("\n== LC6000 jog image uploads (0C size, 0D offset + 7-bit bitstream) ==") + for i, image in enumerate(images): + kind = "PNG" if image[:8] == b"\x89PNG\r\n\x1a\n" else "unknown" + dims = f" {int.from_bytes(image[16:20], 'big')}x{int.from_bytes(image[20:24], 'big')}" if kind == "PNG" else "" + print(f"image {i}: {len(image)} B, {kind}{dims}, head {image[:8].hex()}") + if dump: + dump.mkdir(parents=True, exist_ok=True) + (dump / f"image{i}.{'png' if kind == 'PNG' else 'bin'}").write_bytes(image) + if dump: + print(f"\nPayloads in {dump}/: .raw as sent, .nib nibble-joined, .78 7-in-8 unpacked.") + print("View one: ffmpeg -f rawvideo -pixel_format rgb565le -video_size 320x320 -i burst000.nib out.png") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv))