diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..2af2843 --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,8 @@ +{ + "version": "0.0.1", + "configurations": [ + {"name": "sim-204", "runtimeExecutable": "python", "runtimeArgs": ["sim.py", "--model", "204", "--port", "9761"], "port": 9761}, + {"name": "sim-408", "runtimeExecutable": "python", "runtimeArgs": ["sim.py", "--model", "408", "--port", "9762"], "port": 9762}, + {"name": "webui", "runtimeExecutable": "python", "runtimeArgs": ["server.py", "--port", "8080"], "port": 8080} + ] +} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8588454 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +* text=auto eol=lf +*.bat text eol=crlf +*.png binary +*.ico binary +*.icns binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea596dc --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +# local data – contains the PIN hash, logins and personal presets +config.json +backups/ +Sicherungen/ + +# build output and tools +.venv/ +build/ +dist/ +__pycache__/ +*.pyc +.DS_Store + +# personal Claude Code settings +.claude/settings.local.json diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..44ca17c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,89 @@ +# CLAUDE.md – guide for AI coding assistants + +BetterDSPControl controls t.racks DSP 204 / DSP 408 loudspeaker processors. Read `README.md` (features, usage) and +`PROTOCOL.md` (wire protocol) first. This file explains how the code is built and what to watch out for. + +## Architecture + +``` +browser / phone ──HTTP + SSE──► server.py (asyncio, stdlib only) ──► dsp/device.py ──TCP 9761 or USB HID──► DSP + ▲ +desktop.py (pywebview window, logs in with a one-time token, no PIN) +pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a systemd service on a Raspberry Pi) +``` + +* **`server.py`** – own HTTP server on `asyncio.start_server` (no framework). JSON API under `/api/…`, live updates as + server-sent events on `/api/events` (`App.broadcast`). `App` holds devices, auth, limiter data, remote access, + backups. Config is one JSON file (`config.json`, gitignored) – `load()` / `apply_config()` / `save()`. +* **Auth** – 4-digit PIN, PBKDF2 hash in `config.json`, session cookie `dspsess` (30 days), lockout after 5 failures. + The desktop app logs in via `/app-login?t=`; app sessions live in memory only, skip the PIN and may + toggle remote access (`/api/remote`) and the lock (`/api/lock`, server answers 423 while locked). Remote clients + always need the PIN. +* **`dsp/device.py`** – one `Device` per DSP: connect (TCP or `usbhid.open_stream`), handshake, config dump + (50-byte chunks), command queue (one request in flight), meter polling (also keepalive), auto-reconnect. + Mirrors changes within link groups locally and re-reads the config ~1.5 s after the last change (resync). +* **`dsp/protocol.py`** – frames, checksum, value scales, model layouts (`MODELS["204"|"408"]`), memory image ↔ state + dict (`parse_state` / `build_state_buffer`), parameter → command (`param_command`), link masks, meter/limiter decoding. + State values are **raw device values**; conversion to dB/Hz/ms happens in the UI (`SPEC` in `app.js`). +* **`dsp/preset.py`** – preset files (`dsp-control-preset` JSON with state + raw image), validation, and the minimal + command sequence for an import. Undo backups go to `backups/` next to `config.json` (last 20 per device). +* **`dsp/usbhid.py`** – HID via ctypes only: Windows `hid.dll`/SetupAPI, macOS IOKit, Linux `/dev/hidraw*`. + `HidStream` adapts a blocking reader thread to the asyncio stream interface `device.py` expects. +* **`static/`** – single-page app in vanilla JS. `h()` builds DOM, `S` is the global state, `render()` redraws the + current view (`mixer`, `channel`, `routing`, `link`, `limiter`, `settings`). Live widgets register in `live` and are + updated without a full redraw. **All UI text goes through `t("English text", {vars})`**; German lives in + `static/i18n.js` (`DE`, plus `DE_PATTERNS` for server messages with variables, applied by `trMsg()`). +* **`sim.py`** – simulated DSP 204/408 speaking the same protocol (meters, limiter flags, links). Use it for all tests. +* **`desktop.py`** – starts `server.App` on 127.0.0.1 with a random port in a thread and opens a pywebview window. + `Api` exposes native file dialogs to the page (`window.pywebview.api.save_file/open_file`). Single instance via a + named mutex (Windows) or lock file (macOS). Data in `%APPDATA%\DSP Control` / `~/Library/Application Support/DSP Control`. +* **`pi_writer.py` / `pi_image.py` / `win_disk.py`** – Windows-only tkinter tool that downloads Raspberry Pi OS Lite + (official image list), writes it raw to an SD card (`\\.\PhysicalDriveN`, verify by SHA-256) and adds cloud-init + files (`user-data`, `network-config`, `meta-data`) plus an `install.sh` that installs the app on first boot. + +## Conventions + +* **Server and `dsp/` use the Python standard library only.** pywebview/PyInstaller/Pillow are only for the desktop + builds. No build step for the web UI. +* Source texts are English. Every new `t("…")` string needs a German entry in `static/i18n.js`; server error messages + that reach the UI need one too (exact text in `DE`, or a regex in `DE_PATTERNS`). Technical terms (Gain, Threshold, + Mixer, Routing, Link, Limiter) stay English in German too. +* Native/desktop apps never ask for the PIN; the web UI and remote access always do. +* Channel names: max 8 printable ASCII characters (umlauts are transliterated), and they must fit the mixer strip. +* Keep comments sparse and factual, match the surrounding style. +* `README.md` and `PROTOCOL.md` are English. The Pi Writer UI is still German. + +## Testing + +```bash +python tests/test_protocol.py +python sim.py --model 204 --port 9761 +python sim.py --model 408 --port 9762 +python server.py --port 8080 --config .json +``` + +Log in with PIN `1234`, add devices `127.0.0.1:9761` / `:9762`. Check both languages after UI changes (⚙ → +Language / Sprache). For the desktop app run `python desktop.py` (needs `pywebview`). + +**Never change values on a real DSP permanently while testing.** Export a preset file first (File… → Export) and +restore it afterwards; prefer the simulator. The DSP accepts only one connection – close other control software. + +## Verified vs. unverified + +Verified on a real DSP 204 (firmware V0104P, USB on macOS): connect/dump/meters, set commands, link command `0x3B` +and the DSP's own mirroring inside groups, limiter-active bit mask, preset import writing only differences. + +Not verified yet – ask for a log (`python server.py -v`) from real hardware before changing protocol code here: + +* **DSP 408 on real hardware** (layout and frames match published captures, limiter bits for Out 5–8 assumed) +* USB on Windows and Linux against a real DSP (only tested against a fake HID device) +* Where the PEQ bypass flag lives in the memory image; format of the set-command acknowledgement; payload of the + preset-count answer (`0x2C`) +* Limiter calculator reference level (assumes limiter 0 dB = 0 dBu at the output; adjustable per device) +* Pi Writer: raw write to a real SD card and first boot on a real Pi (only tested with an image file) + +## Legal notes for contributors + +Do not add code, binaries, firmware, screenshots, manuals or internal symbol names/addresses from the manufacturer's +software. Document protocol facts only as observed behaviour. Use "t.racks"/"Thomann" only to name the supported +devices and keep the "not affiliated" notice in the README. diff --git a/PROTOCOL.md b/PROTOCOL.md new file mode 100644 index 0000000..b74e40a --- /dev/null +++ b/PROTOCOL.md @@ -0,0 +1,163 @@ +# t.racks DSP 204 / DSP 408 – control protocol + +Documented for interoperability by observing the communication between the devices and their control software +and by testing on real devices. Both models speak the same protocol; only the number of channels and the size +of the memory image differ. Implementation: [`dsp/protocol.py`](dsp/protocol.py). + +Status: the network transport and all commands below are implemented and tested against the simulator; links, +the limiter status bits and USB were verified on a real DSP 204 (firmware V0104P). Points marked *assumed* are +not verified yet. + +## Transport + +* **Network:** TCP, port **9761**. Factory default IP `192.168.1.101`. +* **USB:** HID class device, no driver needed, **VID 0x0168 / PID 0x0821** (both models). See [USB](#usb-hid). +* Request/response: send one command and wait for its answer before sending the next. +* The DSP accepts only **one** connection at a time. + +## Frame + +``` +10 02 SRC DST LEN CMD PAYLOAD… 10 03 CHK +``` + +| Field | Meaning | +|-------|---------| +| SRC/DST | PC→DSP: `00 01`, DSP→PC: `01 00` (`01` = device ID) | +| LEN | `1 + len(PAYLOAD)` (includes CMD) | +| CHK | XOR from `02` to `03`, i.e. `0x01 ^ SRC ^ DST ^ LEN ^ CMD ^ PAYLOAD…` | + +There is **no byte stuffing** – a payload may contain `10 03`, so always parse by LEN. +All 16-bit words are little endian. + +## Read / system commands + +| CMD | Direction | Payload | Meaning | +|-----|-----------|---------|---------| +| `10` | → | – | Handshake | +| `13` | → / ← | – / ASCII | Device info, answer starts with `DSP204` or `DSP408` | +| `2C` | → / ← | – / `[?][count]` | Number of presets (payload meaning partly *assumed*) | +| `22`, `14` | → | – | Init queries (sent during connect, content unknown) | +| `29` | → / ← | `[idx]` / `[idx][name…]` | Preset name (idx 0-based) | +| `20` | → | `[idx+1]` | Recall preset | +| `26` | → | `name[14]` | Set name for the next store | +| `21` | → | `[idx+1]` | Store current state into preset | +| `27` | → | `[chunk]` | Request config chunk | +| `24` | ← | `[chunk][50 bytes]` | Config chunk; 204: chunks 0…14, 408: 0…28 | +| `12` | → | – | Status (sent after the dump) | +| `40` | → / ← | – / meters | Read levels (also serves as keepalive) | + +### Meter answer + +12 entries × 3 bytes `b0 b1 b2`, followed by 2 status bytes. + +* Level = float32 from the bytes `00 b2 b0 b1` (little endian) → linear, dB = 20·log10. +* Positions: 0–3 = In A–D, 4–11 = Out 1–8. The 204 uses 0, 1 and 4–7. +* The level is measured before mute. +* **Limiter active**: the status bytes are a bit mask of the outputs (bit 0 = Out 1). Measured on a DSP 204: + `00 03` while Out 1+2 limit, `00 0C` for Out 3+4. That Out 5–8 of the 408 continue in the same 16-bit value + is *assumed*. + +## Channel numbers + +| Device | Inputs | Outputs | +|--------|--------|---------| +| DSP 204 | In A=0, In B=1 | Out 1–4 = 2–5 | +| DSP 408 | In A–D = 0–3 | Out 1–8 = 4–11 | + +## Set commands + +| CMD | Parameter | Payload | +|-----|-----------|---------| +| `34` | Gain | `[ch][u16 gain]` | +| `35` | Mute | `[ch][0/1]` | +| `36` | Polarity | `[ch][0/1]` | +| `38` | Delay | `[ch][u16 delay]` | +| `32` | High pass (low cut) | `[ch][u16 freq][slope]` | +| `31` | Low pass (high cut) | `[ch][u16 freq][slope]` | +| `33` | PEQ band | `[ch][band][u16 gain][u16 freq][q][type][bypass]` | +| `48` | GEQ band (inputs) | `[ch][band 0–30][u16 gain]` | +| `3E` | Gate (inputs) | `[ch][attack][release][hold][threshold]` (u16 each) | +| `30` | Compressor (outputs) | `[ch][ratio][attack][release][knee][threshold]` | +| `3F` | Limiter (outputs) | `[ch][attack][release][knee][threshold]` | +| `3A` | Routing matrix (outputs) | `[ch][bit mask of inputs]` | +| `41` | Mix level (outputs) | `[ch][input][u16 level]` | +| `3D` | Channel name | `[ch][name 8]` (printable ASCII) | +| `3B` | Link | `[ch][u16 link mask]` (see [Channel links](#channel-links)) | +| `15` | Delay unit | `[unit]` (display only) | + +The format of the acknowledgement the DSP sends after a set command is not fully understood yet. + +## Value encoding + +| Parameter | Raw | Conversion | +|-----------|-----|------------| +| Gain / mix level | 0–400 (mix 0–280) | `r<80: r/2−60 dB`, else `(r−280)/10 dB` → −60…+12 dB | +| Frequency (PEQ, HP, LP) | 0–300 | `1000 · 2^((r−170)/30)` Hz → 19.7 Hz…20.16 kHz (1/30 octave) | +| PEQ/GEQ gain | 0–240 | `(r−120)/10` dB → ±12 dB | +| Q | 0–100 | table 0.4…128 (see `protocol.py`) | +| PEQ type | 0–8 | Peak, Low shelf, High shelf, HPF −6, HPF −12, LPF −6, LPF −12, Allpass 1, Allpass 2 | +| Slope | 0–20 | 0 = bypass, 1–20 = BW−6, BL−6, BW−12, BL−12, LK−12, … LK−48 | +| Delay | 0–65280 | `r/96` ms (max 680 ms) | +| Threshold (gate/comp/limit) | 0–220 | `(r−180)/2` dB (gate max 0 dB, comp/limit max +20 dB) | +| Attack | 0–998 | `r+1` ms | +| Release | 9–2999 | `r+1` ms | +| Hold | 9–998 | `r+1` ms | +| Ratio | 0–15 | 1.0, 1.1, 1.3, 1.5, 1.7, 2.0, 2.5, 3.0, 3.5, 4.0, 5.0, 6.0, 8.0, 10, 20, Limit | +| Knee | 0–12 | dB | + +The absolute output level that corresponds to 0 dB limiter threshold is not published; the app assumes 0 dBu. + +## Channel links + +Measured on a DSP 204 (firmware V0104P). Every channel has a u16 mask (bit = channel index within the inputs +or within the outputs): + +| Channel | Mask | +|---------|------| +| not linked | its own bit only (Out 3 = `04`) | +| first channel of a group | bits of all members (Out 3+4 = `0C`) | +| further members | `00` | + +* Set with `3B [ch][mask]` – for every channel of the group (first channel first). +* When a group is formed, the DSP copies the settings of the first channel to the others. +* The DSP itself applies every change on a member to the whole group (gain, delay, polarity, HP/LP, PEQ, GEQ, + gate, compressor, limiter, mute) – but **not** channel name, routing matrix and mix levels. +* A member with mask `00` that is not part of a group ignores changes: when unlinking, give every channel its own + bit again. + +## Config dump = memory image + +Chunk `n` carries bytes `n·50 … n·50+49` of the device memory image. + +``` +0x00 u8[2] ? +0x02 char[14] preset name +0x10 Input[nIn] 140 bytes each + +0 name[8] + +8 gate: attack, release, hold, threshold (4×u16) + +16 geq[31] u16 + +78 peq[8] {u16 gain, u16 freq, u8 q, u8 type} + +126 u16 hp_freq, u16 lp_freq, u8 hp_slope, u8 lp_slope + +132 u16 gain, u16 polarity, u16 delay, u16 link mask + Output[nOut] 96 + 2·nIn bytes each + +0 name[8] + +8 u16 matrix bit mask + +10 u16 mix[nIn] + … u16 hp_freq, u16 lp_freq, u8 hp_slope, u8 lp_slope + … peq[9] {u16 gain, u16 freq, u8 q, u8 type} + … comp: ratio, attack, release, knee, threshold (5×u16) + … limit: attack, release, knee, threshold (4×u16) + … u16 gain, u16 polarity, u16 delay, u16 link mask + u16 input mute bit mask, u16 output mute bit mask, then unknown fields +``` + +Total size: DSP 204 = 724 bytes (15 chunks), DSP 408 = 1448 bytes (29 chunks). +Where the PEQ bypass flag is stored in the image is not known yet. + +## USB (HID) + +* Both models: **VID 0x0168, PID 0x0821**, HID class, no driver. +* Send: report ID `00` + one complete frame (`10 02 … 10 03 CHK`), zero-padded to the output report length. +* Receive: every input report holds exactly one frame starting at byte 0, length = `LEN + 8`, then padding. +* The frames are identical to TCP; the longest (config chunk, 50 data bytes) is 60 bytes and fits a 64-byte report. diff --git a/README.md b/README.md index 9269623..f899762 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,216 @@ # BetterDSPControl +**A modern, phone-friendly control app for the t.racks DSP 204 and DSP 408 loudspeaker processors.** +Control both devices at the same time from your phone, tablet or computer – over the network or USB. + +> **Unofficial project.** BetterDSPControl is an independent open-source project. It is not affiliated with, +> endorsed by or supported by Musikhaus Thomann or the t.racks brand. "Thomann" and "t.racks" are trademarks of +> their respective owner and are used here only to name the devices this software works with. +> Use at your own risk – see [Disclaimer](#disclaimer). + +* Pure Python 3.10+ standard library on the server side – no packages to install +* Vanilla HTML/CSS/JavaScript web UI – no build tools +* Runs on Windows, macOS, Linux and a Raspberry Pi +* English and German user interface + +## Features + +* **Several devices at once** – switch with the tabs at the top; the model is detected automatically +* **Mixer** – faders, mute and live meters for all inputs and outputs, limiter LED on every output (status read + from the DSP) +* **Channel** – name, gain, delay, polarity, high/low pass, 8/9-band PEQ with a draggable curve +* **Inputs** – noise gate, 31-band GEQ · **Outputs** – compressor, limiter, input routing with mix levels +* **Routing matrix**, recall and store presets +* **Channel links** – link channels into groups; the DSP mirrors changes within the group, the app shows them live +* **Preset files** – export the current DSP state to a file and import it again. An import only changes the active + state (stored presets stay untouched), writes only what actually differs and makes an automatic backup first + ("Undo import") +* **Limiter calculator** – enter your amplifiers' datasheet values (power at 8/4/2 Ω, sensitivity or gain), assign + outputs, and see the resulting power when the limiter engages, the clipping headroom and the speaker load. + "Limit to … W" calculates the threshold. Attack/release presets per band (infra, sub, kick, mid, high) +* **Settings backup** – devices, amplifier data, PIN and remote access in one file +* **Many phones at once** – every change is pushed live to all connected clients +* Tap a value to type it in (`-3.5`, `1.2k`, delay in metres `2.5m`); faders snap at 0 dB, double-tap = 0 dB + +## Supported hardware + +| Device | Network | USB | Tested on real hardware | +|--------|---------|-----|-------------------------| +| t.racks DSP 204 | ✓ | ✓ | yes (firmware V0104P, USB on macOS) | +| t.racks DSP 408 | ✓ | ✓ | not yet – frames match published captures | + +The DSPs accept only **one** connection at a time – close any other control software first. + +## Quick start (web UI) + +```bash +git clone https://git.thiemoo.at/Givou/BetterDSPControl.git +``` + +```bash +cd BetterDSPControl +``` + +```bash +python server.py +``` + +Open `http://:8080` in a browser (from a phone: same Wi-Fi/LAN). + +1. Log in with the default PIN **`1234`**. +2. Open ⚙ (settings), enter the IP addresses of your DSPs (or choose *USB cable*) and press *Connect*. +3. **Change the PIN** under ⚙ → Security. +4. Switch the language under ⚙ → *Language / Sprache* (English is the default). + +`config.json` is created on the first start. Options: `--port 8080`, `--host 0.0.0.0`, `--config path/to/config.json`, +`-v` (debug log). On Windows you can also double-click `start.bat`. + +**Forgot the PIN?** Stop the server, delete the `auth` entry from `config.json` and start again – the PIN is `1234` +again. + +### Security + +The PIN protects against accidental access in your own network, nothing more: it has 4 digits, a logged-in device +stays logged in for 30 days, and after 5 wrong attempts the login is blocked (30 s, growing up to 15 min). The server speaks +plain HTTP. **Do not expose it to the internet** (no port forwarding) – use a VPN if you need remote access. + +## Desktop apps (Windows, macOS) + +The desktop app runs the server and the UI in its own window – **no PIN needed** in the app window. +Under ⚙ → *Remote access* you can turn on a web server for phones and tablets (port selectable); other devices +then log in with the PIN. The lock icon (top right) locks the app window (view only); unlock with the PIN. + +Build it yourself (pre-built binaries are not part of the repository): + +```bash +python -m pip install pyinstaller pywebview pillow +``` + +```bash +python packaging/build.py +``` + +* **Windows** → `dist/DSP Control.exe` and `dist/DSP Control Pi Writer.exe`. Data: `%APPDATA%\DSP Control`. +* **macOS** → `dist/DSP Control.app` and `dist/DSP Control.dmg` (use a venv with Python 3.10+, e.g. from Homebrew). + The app is not signed: on the first start right-click → *Open*. Data: `~/Library/Application Support/DSP Control`. + +## Raspberry Pi (always-on web UI) + +`DSP Control Pi Writer.exe` (Windows, user interface currently German only) prepares an SD card for a Raspberry Pi +(Pi 1/2/3/4/5, Zero, Zero 2 W) that serves the web UI permanently: + +* downloads the current Raspberry Pi OS Lite from the official Raspberry Pi servers (with checksum, cached) +* writes and verifies the card, then configures it via cloud-init: hostname, Wi-Fi, user/SSH, web UI PIN, DSP IPs +* installs BetterDSPControl from the card (the Pi needs no internet), as a systemd service on port 80 + +After 2–5 minutes open `http://.local`. Needs administrator rights; only USB/SD drives that are not the +system or boot disk are offered. If Windows then asks to format the Linux partition, click **Cancel**. + +On any other Linux machine: `python3 server.py --port 8080`. For USB access as a normal user add a udev rule for +`hidraw` devices with VID `0168` / PID `0821` (see `INSTALL_SH` in `pi_image.py`). + +## USB + +Choose *USB cable* for a device under ⚙. The DSPs are USB HID devices (VID 0168 / PID 0821) – no driver needed – and +speak the same frames as over the network. Works on Windows (hid.dll), macOS (IOKit) and Linux (hidraw). With two +DSPs on USB, pick the right one in the drop-down. + +## Testing without hardware + +A simulator emulates both models: + +```bash +python sim.py --model 204 --port 9761 +``` + +```bash +python sim.py --model 408 --port 9762 +``` + +```bash +python server.py +``` + +Then add devices with IP `127.0.0.1` and ports 9761 / 9762 in the web UI. Protocol self-test: + +```bash +python tests/test_protocol.py +``` + +## Project layout + +| Path | Contents | +|------|----------| +| `server.py` | Web server (HTTP + server-sent events), device management, auth, backups | +| `dsp/protocol.py` | Frame format, commands, value scales, memory-image parser | +| `dsp/device.py` | Client per DSP (TCP or USB): connect, command queue, meters, auto-reconnect, links | +| `dsp/preset.py` | Preset files: export/import, validation, import command sequence | +| `dsp/usbhid.py` | USB HID without extra packages (Windows hid.dll, macOS IOKit, Linux hidraw) | +| `sim.py` | Simulated DSP 204/408 | +| `desktop.py` | Desktop app (Windows/macOS): server + own window (pywebview) | +| `pi_writer.py`, `pi_image.py`, `win_disk.py` | Raspberry Pi SD card writer: GUI, OS image + cloud-init, raw disk writes | +| `static/` | Web UI (`app.js`, `style.css`, `index.html`), translations in `static/i18n.js` | +| `packaging/` | Build script and icons | +| `tests/` | Protocol tests | +| `PROTOCOL.md` | Protocol documentation | +| `CLAUDE.md` | Guide for AI coding assistants (architecture, conventions, open points) | + +## How to import into your Claude + +This project was built with [Claude Code](https://claude.com/claude-code) and is documented so you can continue +working on it in your own Claude session. `CLAUDE.md` is read automatically by Claude Code and explains the +architecture, conventions and what is still unverified. + +1. Clone the repository (see [Quick start](#quick-start-web-ui)). +2. Open the folder in Claude Code – either the **Claude desktop app** (tab *Code* → choose the folder) or in a + terminal: + + ```bash + cd BetterDSPControl && claude + ``` + +3. Paste this prompt as your first message: + +```text +This is BetterDSPControl, a control app for the t.racks DSP 204 / DSP 408 (Python stdlib server + vanilla JS web UI, +desktop app via pywebview, Raspberry Pi SD card writer). + +Please get familiar with the project first: +1. Read CLAUDE.md, README.md and PROTOCOL.md completely. +2. Look at server.py, dsp/protocol.py, dsp/device.py and static/app.js to understand the structure. +3. Run the tests (python tests/test_protocol.py) and start the simulator test from the README + (sim.py for both models + server.py) to see the app working. +4. Summarise briefly how it is built and which points are still unverified on real hardware. + +Rules: never change values on a real DSP permanently while testing (export a preset file first, use the simulator +whenever possible), keep the server free of third-party packages, and keep English and German texts in sync +(static/i18n.js). Ask me before pushing anything. + +My devices: . +What I want to do: . +``` + +## Contributing + +Issues and pull requests are welcome – especially captures and test results from a real **DSP 408** and anything +listed as unverified in `CLAUDE.md`. Please test with the simulator first and run `python tests/test_protocol.py`. + +## Disclaimer + +This software talks to your audio hardware. Wrong settings (e.g. limiter thresholds, gain, crossover filters) can +damage loudspeakers or amplifiers. The limiter calculator is a planning aid based on datasheet values and an assumed +reference level – verify with a measurement before relying on it. The software is provided "as is", without +warranty of any kind, see [LICENSE](LICENSE). + +The protocol was documented for interoperability purposes only, by observing the communication of the devices and +testing on real hardware. This repository contains no code, binaries, firmware, images or documentation from the +manufacturer. Frame examples in the tests also match the DSP 408 captures published by +[dsp-408-ui](https://github.com/Aeternitaas/dsp-408-ui); no code from that project is used. + +## License + +[MIT](LICENSE) © 2026 Givou + +The desktop builds bundle third-party components under their own licenses (Python – PSF License, pywebview – BSD, +pythonnet – MIT, PyInstaller bootloader – GPL with exception allowing distribution). If you distribute built +binaries, include their license notices. diff --git a/desktop.py b/desktop.py new file mode 100644 index 0000000..864bfe4 --- /dev/null +++ b/desktop.py @@ -0,0 +1,172 @@ +"""DSP Control desktop app: the web server runs inside the app and the UI opens in its own window. + +The window logs in with a one-time token (no PIN). Other devices only get access when +"Fernzugriff" is switched on in the settings - and then they need the PIN. + +Runs on Windows and macOS. Build: python packaging/build.py +""" + +import asyncio +import base64 +import ctypes +import json +import logging +import os +import secrets +import subprocess +import sys +import threading +from pathlib import Path + +import webview + +import server + +APP_NAME = "DSP Control" + + +def data_dir() -> Path: + if sys.platform == "darwin": + d = Path.home() / "Library" / "Application Support" / APP_NAME + else: + d = Path(os.environ.get("APPDATA") or Path.home()) / APP_NAME + d.mkdir(parents=True, exist_ok=True) + return d + + +# texts of this file and pywebview's own (menus, file dialogs); the page itself is translated in static/i18n.js +TEXTS = { + "en": {"running": "DSP Control is already running.", "failed": "DSP Control could not start:\n{error}", + "timeout": "timeout"}, + "de": {"running": "DSP Control läuft bereits.", "failed": "DSP Control konnte nicht starten:\n{error}", + "timeout": "Zeitüberschreitung"}, +} +WEBVIEW_DE = { + "global.quitConfirmation": "Wirklich beenden?", "global.ok": "OK", "global.quit": "Beenden", "global.cancel": "Abbrechen", + "global.saveFile": "Datei speichern", "cocoa.menu.about": "Über", "cocoa.menu.services": "Dienste", + "cocoa.menu.view": "Darstellung", "cocoa.menu.edit": "Bearbeiten", "cocoa.menu.hide": "Ausblenden", + "cocoa.menu.hideOthers": "Andere ausblenden", "cocoa.menu.showAll": "Alle einblenden", "cocoa.menu.quit": "Beenden", + "cocoa.menu.fullscreen": "Vollbild", "cocoa.menu.cut": "Ausschneiden", "cocoa.menu.copy": "Kopieren", + "cocoa.menu.paste": "Einsetzen", "cocoa.menu.selectAll": "Alles auswählen", "windows.fileFilter.allFiles": "Alle Dateien", + "windows.fileFilter.otherFiles": "Andere Dateitypen", +} + + +def ui_lang() -> str: + """Language chosen in the app (kept in config.json by the server), English by default.""" + try: + lang = json.loads((data_dir() / "config.json").read_text(encoding="utf-8")).get("lang") + except (OSError, ValueError, AttributeError): + lang = None + return lang if lang in TEXTS else "en" + + +def text(key: str, **kw) -> str: + return TEXTS[ui_lang()][key].format(**kw) + + +_lock = None + + +def single_instance() -> bool: + """False if the app is already running (Windows named mutex, elsewhere a locked file).""" + global _lock + if sys.platform == "win32": + ctypes.windll.kernel32.CreateMutexW(None, False, "Local\\DSPControlDesktop") + return ctypes.windll.kernel32.GetLastError() != 183 # ERROR_ALREADY_EXISTS + import fcntl + _lock = open(data_dir() / ".lock", "w") # held until the process ends + try: + fcntl.flock(_lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return False + return True + + +def message(text: str): + if sys.platform == "win32": + ctypes.windll.user32.MessageBoxW(None, text, APP_NAME, 0x40) + elif sys.platform == "darwin": + subprocess.run(["osascript", "-e", "on run argv", "-e", + f'display dialog (item 1 of argv) with title "{APP_NAME}" buttons {{"OK"}} default button 1', + "-e", "end run", text], check=False) + else: + print(text) + + +class Api: + """Called from the page (window.pywebview.api): native save/open dialogs for backups and presets.""" + + def __init__(self): + self._window = None # underscore: not exposed to JavaScript + + def save_file(self, name: str, text: str) -> bool: + res = self._window.create_file_dialog(webview.FileDialog.SAVE, save_filename=name) + path = res[0] if isinstance(res, (list, tuple)) else res + if not path: + return False + Path(path).write_text(text, encoding="utf-8") + return True + + def open_file(self) -> dict | None: + res = self._window.create_file_dialog(webview.FileDialog.OPEN) + if not res: + return None + path = Path(res[0] if isinstance(res, (list, tuple)) else res) + if path.stat().st_size > 5_000_000: + raise ValueError("File is too large") + return {"name": path.name, "data": base64.b64encode(path.read_bytes()).decode()} + + +def main(): + if not single_instance(): + message(text("running")) + return + d = data_dir() + logging.basicConfig(filename=d / "dsp-control.log", level=logging.INFO, encoding="utf-8", + format="%(asctime)s %(name)s %(levelname)s %(message)s") + app = server.App(d / "config.json") + app.app_token = secrets.token_urlsafe(24) + + loop = asyncio.new_event_loop() + started = threading.Event() + state: dict = {} + + async def start(): + app.load() + srv = await asyncio.start_server(app.handle, "127.0.0.1", 0) + state["port"] = srv.sockets[0].getsockname()[1] + await app.start_remote() + + def run(): + asyncio.set_event_loop(loop) + try: + loop.run_until_complete(start()) + except Exception as e: # noqa: BLE001 - shown to the user below + logging.exception("start failed") + state["error"] = e + started.set() + loop.run_forever() + + threading.Thread(target=run, daemon=True, name="server").start() + started.wait(20) + if "port" not in state: + message(text("failed", error=state.get("error", text("timeout")))) + return + + api = Api() + api._window = webview.create_window(APP_NAME, f"http://127.0.0.1:{state['port']}/app-login?t={app.app_token}", + width=1280, height=840, min_size=(380, 560), background_color="#0b0c0f", + js_api=api) + webview.start(private_mode=False, storage_path=str(d / "webview"), + localization=WEBVIEW_DE if ui_lang() == "de" else {}) + + # window closed: disconnect the DSPs cleanly so the next connection is accepted right away + try: + asyncio.run_coroutine_threadsafe(app.shutdown(), loop).result(5) + except Exception: # noqa: BLE001 + logging.exception("shutdown") + + +if __name__ == "__main__": + main() diff --git a/dsp/__init__.py b/dsp/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dsp/device.py b/dsp/device.py new file mode 100644 index 0000000..a6cba10 --- /dev/null +++ b/dsp/device.py @@ -0,0 +1,365 @@ +"""Async client for one t.racks DSP - over the network (TCP) or USB (HID).""" + +import asyncio +import copy +import logging +import struct +import time + +from . import preset +from . import protocol as P +from . import usbhid + +log = logging.getLogger("dsp") + +RESPONSE_TIMEOUT = 0.6 +METER_INTERVAL = 0.15 +RECONNECT_DELAY = 5.0 +LINK_RESYNC_DELAY = 1.5 # re-read the config this long after the last change on a linked channel + + +class Device: + def __init__(self, dev_id: str, name: str, host: str, port: int = P.PORT, model: str = "auto", + addr: int = 1, autoconnect: bool = True, on_event=None, transport: str = "tcp", usb: str = ""): + self.id = dev_id + self.name = name + self.host = host + self.port = port + self.model_key = model # "auto", "204" or "408" + self.addr = addr + self.autoconnect = autoconnect + self.transport = "usb" if transport == "usb" else "tcp" + self.usb = usb # HID device path, "" = first DSP found + self.on_event = on_event or (lambda ev: None) + + self.status = "disconnected" # disconnected | connecting | loading | online | error + self.error = "" + self.info = "" + self.model: P.Model | None = P.MODELS.get(model) + self.state: dict | None = None + self.raw = b"" # memory image of the last config read + self.presets: list[str] = [] + self.meters: list[float] = [0.0] * 12 + + self._reader = None + self._writer = None + self._parser = P.FrameParser() + self._lock = asyncio.Lock() + self._waiter: asyncio.Future | None = None + self._pending: dict[tuple, tuple[int, bytes]] = {} + self._pending_event = asyncio.Event() + self._tasks: list[asyncio.Task] = [] + self._supervisor: asyncio.Task | None = None + self._want_connected = False + self._resync: asyncio.TimerHandle | None = None + self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits + + # ------------------------------------------------------------ public API + + def config(self) -> dict: + return {"id": self.id, "name": self.name, "host": self.host, "port": self.port, + "model": self.model_key, "addr": self.addr, "autoconnect": self.autoconnect, + "transport": self.transport, "usb": self.usb} + + def snapshot(self) -> dict: + return {**self.config(), "status": self.status, "error": self.error, "info": self.info, + "detected_model": self.model_name or None, + "n_in": self.model.n_in if self.model else 0, + "n_out": self.model.n_out if self.model else 0, + "presets": self.presets, "state": self.state} + + def start(self): + self._want_connected = True + if not self._supervisor or self._supervisor.done(): + self._supervisor = asyncio.create_task(self._supervise()) + + async def stop(self): + self._want_connected = False + self._resync: asyncio.TimerHandle | None = None + self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits + if self._supervisor: + self._supervisor.cancel() + try: + await self._supervisor + except (asyncio.CancelledError, Exception): + pass + self._supervisor = None + await self._close() + self._set_status("disconnected") + + def set_param(self, kind: str, idx: int, param: str, value): + """Update local state and queue the command (coalesced per parameter).""" + if not self.state or not self.model: + raise RuntimeError("device not loaded") + chans = self.state["inputs" if kind == "in" else "outputs"] + ch = chans[idx] + if param == "name": + value = P.clean_name(value) + P.apply_param(ch, param, value) + cmd, payload = P.param_command(self.model, kind, idx, ch, param) + key = (cmd, payload[0]) + ((payload[1],) if cmd in (P.CMD_PEQ, P.CMD_GEQ, P.CMD_MIX) else ()) + self._pending[key] = (cmd, payload) + self._pending_event.set() + self._changes += 1 + # the DSP applies the change to linked channels itself: show that right away + group = [idx] if param.split(".")[0] in P.LINK_EXCLUDED else P.link_group(chans, idx) + for i in group: + if i != idx: + P.apply_param(chans[i], param, copy.deepcopy(value)) + self.on_event({"type": "param", "device": self.id, "kind": kind, "idx": i, + "param": param, "value": value}) + if len(group) > 1: + self._schedule_resync() + + async def set_links(self, kind: str, groups: list[list[int]]): + """Link channels of one kind. The DSP copies the first channel's settings to the others.""" + if not self.state or not self.model: + raise RuntimeError("device not loaded") + n = self.model.n_in if kind == "in" else self.model.n_out + for i, mask in enumerate(P.link_masks(n, groups)): + await self._request(P.CMD_LINK, bytes([self.model.channel(kind, i)]) + struct.pack(" str: + return next((k for k, m in P.MODELS.items() if m is self.model), "") + + async def export_preset(self) -> dict: + """The DSP's current state, read fresh from the device.""" + await self.refresh() + return preset.export_doc(self.model_name, self.info, self.state, self.raw) + + async def import_preset(self, state: dict) -> list[str]: + """Put the DSP into `state` (working state only). Returns the paths that did not take.""" + if self.status != "online": + raise RuntimeError("DSP is not connected") + if self._resync: + self._resync.cancel() + failed = 0 + for cmd, payload in preset.import_commands(self.model, state, self.state): + if await self._request(cmd, payload) is None: + failed += 1 + await asyncio.sleep(0.3) + await self.refresh() + diffs = preset.differences(state, self.state) + if failed: + log.warning("%s: %d import commands unanswered", self.name, failed) + return diffs + + async def refresh(self): + await self._load_config() + self._emit_state() + + # ------------------------------------------------------------ connection + + async def _supervise(self): + while self._want_connected: + try: + await self._connect_and_run() + except asyncio.CancelledError: + raise + except Exception as e: # noqa: BLE001 - keep reconnecting on any failure + log.warning("%s: %s", self.name, e) + self.error = str(e) or e.__class__.__name__ + self._set_status("error") + await self._close() + if not self._want_connected: + break + await asyncio.sleep(RECONNECT_DELAY) + + async def _connect_and_run(self): + self._set_status("connecting") + self.error = "" + if self.transport == "usb": + self._reader, self._writer = await asyncio.wait_for(usbhid.open_stream(self.usb), timeout=5) + else: + self._reader, self._writer = await asyncio.wait_for( + asyncio.open_connection(self.host, self.port), timeout=5) + self._parser = P.FrameParser() + reader_task = asyncio.create_task(self._read_loop()) + self._tasks = [reader_task] + self._set_status("loading") + await self._initialise() + self._set_status("online") + self._emit_state() + self._tasks += [asyncio.create_task(self._write_loop()), asyncio.create_task(self._meter_loop())] + done, _ = await asyncio.wait(self._tasks, return_when=asyncio.FIRST_COMPLETED) + for t in done: + if t.exception(): + raise t.exception() + raise ConnectionError("connection closed") + + async def _close(self): + if self._resync: + self._resync.cancel() + self._resync = None + for t in self._tasks: + t.cancel() + self._tasks = [] + if self._writer: + try: + self._writer.close() + except Exception: # noqa: BLE001 + pass + self._reader = self._writer = None + if self._waiter and not self._waiter.done(): + self._waiter.cancel() + + async def _read_loop(self): + while True: + data = await self._reader.read(4096) + if not data: + raise ConnectionError("DSP closed the connection") + for frame in self._parser.feed(data): + if self._waiter and not self._waiter.done(): + self._waiter.set_result(frame) + + async def _request(self, cmd: int, payload: bytes = b"", timeout: float = RESPONSE_TIMEOUT, + expect: int | None = None) -> P.Frame | None: + """Send one command and wait for its answer (the DSP is strictly request/response).""" + if not self._writer: + raise ConnectionError("not connected") + async with self._lock: + deadline = time.monotonic() + timeout + self._writer.write(P.build_frame(cmd, payload, self.addr)) + await self._writer.drain() + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + return None + self._waiter = asyncio.get_running_loop().create_future() + try: + frame = await asyncio.wait_for(self._waiter, remaining) + except asyncio.TimeoutError: + return None + if expect is None or frame.cmd == expect: + return frame + + # ------------------------------------------------------------ init / dump + + async def _initialise(self): + await self._request(P.CMD_HANDSHAKE) + info = await self._request(P.CMD_DEVICE_INFO, expect=P.CMD_DEVICE_INFO) + self.info = info.payload.split(b"\x00")[0].decode("latin1", "replace").strip() if info else "" + detected = P.detect_model(self.info) + if self.model_key == "auto": + if not detected: + raise RuntimeError(f"unknown device '{self.info}' - set the model manually") + self.model = P.MODELS[detected] + else: + self.model = P.MODELS[self.model_key] + if detected and detected != self.model_key: + log.warning("%s: configured as %s but device reports %s", self.name, self.model_key, self.info) + count_frame = await self._request(P.CMD_PRESET_COUNT, expect=P.CMD_PRESET_COUNT) + count = count_frame.payload[-1] if count_frame and count_frame.payload else 20 + count = count if 0 < count <= 60 else 20 + await self._request(P.CMD_INIT_22) + await self._request(P.CMD_INIT_14) + presets = [] + for i in range(count): + f = await self._request(P.CMD_PRESET_NAME, bytes([i]), expect=P.CMD_PRESET_NAME) + presets.append(f.payload[1:].split(b"\x00")[0].decode("latin1", "replace").strip() if f else "") + self.presets = presets + await self._load_config() + + async def _load_config(self): + self.state = await self._read_config() + + async def _read_config(self) -> dict: + model = self.model + buf = bytearray(model.chunks * P.CHUNK_SIZE) + for n in range(model.chunks): + for _attempt in range(3): + f = await self._request(P.CMD_CONFIG_REQUEST, bytes([n]), expect=P.CMD_CONFIG_CHUNK) + if f and f.payload and f.payload[0] == n: + data = f.payload[1 : 1 + P.CHUNK_SIZE] + buf[n * P.CHUNK_SIZE : n * P.CHUNK_SIZE + len(data)] = data + break + else: + raise RuntimeError(f"config chunk {n} not received") + await self._request(P.CMD_STATUS) + self.raw = bytes(buf[: model.size]) + return P.parse_state(model, bytes(buf)) + + # ------------------------------------------------------------ background loops + + async def _write_loop(self): + while True: + await self._pending_event.wait() + while self._pending: + key = next(iter(self._pending)) + cmd, payload = self._pending.pop(key) + await self._request(cmd, payload) + self._pending_event.clear() + + async def _meter_loop(self): + misses = 0 + while True: + await asyncio.sleep(METER_INTERVAL) + if self._pending: + continue + f = await self._request(P.CMD_METER, expect=P.CMD_METER) + if f is None: + misses += 1 + if misses >= 10: + raise ConnectionError("DSP not responding") + continue + misses = 0 + self.meters = P.decode_meters(f.payload) + m = self.model + self.on_event({"type": "meters", "device": self.id, + "in": [self.meters[m.meter_index("in", i)] for i in range(m.n_in)], + "out": [self.meters[m.meter_index("out", i)] for i in range(m.n_out)], + "limit": P.decode_limit_flags(f.payload, m.n_out)}) + + # ------------------------------------------------------------ events + + def _set_status(self, status: str): + self.status = status + self.on_event({"type": "status", "device": self.id, "status": status, "error": self.error, + "info": self.info}) + + def _emit_state(self): + self.on_event({"type": "device", "device": self.id, "data": copy.deepcopy(self.snapshot())}) diff --git a/dsp/preset.py b/dsp/preset.py new file mode 100644 index 0000000..a32c129 --- /dev/null +++ b/dsp/preset.py @@ -0,0 +1,172 @@ +"""Preset files: export the DSP's current state and import it again. + +A file holds the decoded state (readable, see protocol.parse_state) plus the raw memory image. +Importing only changes the DSP's working state - the stored presets (U01...) stay untouched. +""" + +import copy +import time + +from . import protocol as P + +FORMAT = "dsp-control-preset" + +# valid raw ranges (PROTOCOL.md, "Werte-Kodierung") +_GATE = {"attack": (0, 998), "release": (9, 2999), "hold": (9, 998), "threshold": (0, 180)} +_COMP = {"ratio": (0, 15), "attack": (0, 998), "release": (9, 2999), "knee": (0, 12), "threshold": (0, 220)} +_LIMIT = {"attack": (0, 998), "release": (9, 2999), "knee": (0, 12), "threshold": (0, 220)} + + +def export_doc(model_key: str, info: str, state: dict, raw: bytes) -> dict: + return {"format": FORMAT, "version": 1, "model": model_key, "device": info, + "preset_name": state.get("preset_name", ""), + "exported": time.strftime("%Y-%m-%dT%H:%M:%S"), "state": state, "raw": raw.hex()} + + +def _int(v, lo: int, hi: int, default: int) -> int: + try: + v = int(v) + except (TypeError, ValueError): + return default + return min(hi, max(lo, v)) + + +def _filter(src, cur: dict) -> dict: + src = src if isinstance(src, dict) else {} + return {"freq": _int(src.get("freq"), 0, 300, cur["freq"]), "slope": _int(src.get("slope"), 0, 20, cur["slope"])} + + +def _peq(src, cur: list) -> list: + src = src if isinstance(src, list) else [] + out = [] + for i, c in enumerate(cur): + b = src[i] if i < len(src) and isinstance(src[i], dict) else {} + out.append({"gain": _int(b.get("gain"), 0, 240, c["gain"]), "freq": _int(b.get("freq"), 0, 300, c["freq"]), + "q": _int(b.get("q"), 0, 100, c["q"]), "type": _int(b.get("type"), 0, 8, c["type"]), + "bypass": bool(b.get("bypass", c["bypass"]))}) + return out + + +def _group(src, cur: dict, ranges: dict) -> dict: + src = src if isinstance(src, dict) else {} + return {k: _int(src.get(k), lo, hi, cur[k]) for k, (lo, hi) in ranges.items()} + + +def _common(s: dict, c: dict) -> dict: + name = s.get("name", c["name"]) + return {"name": P.clean_name(name).strip(), + "hp": _filter(s.get("hp"), c["hp"]), "lp": _filter(s.get("lp"), c["lp"]), + "gain": _int(s.get("gain"), 0, 400, c["gain"]), "polarity": bool(s.get("polarity", c["polarity"])), + "delay": _int(s.get("delay"), 0, 65280, c["delay"]), "link": _int(s.get("link"), 0, 0xFFFF, c["link"]), + "mute": bool(s.get("mute", c["mute"]))} + + +def clean_state(model: P.Model, src: dict, base: dict) -> dict: + """`src` limited to valid values; anything missing or broken is taken from `base`.""" + st = copy.deepcopy(base) + ins = src.get("inputs") if isinstance(src.get("inputs"), list) else [] + outs = src.get("outputs") if isinstance(src.get("outputs"), list) else [] + for i, c in enumerate(st["inputs"]): + s = ins[i] if i < len(ins) and isinstance(ins[i], dict) else {} + geq = s.get("geq") if isinstance(s.get("geq"), list) else [] + c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]), gate=_group(s.get("gate"), c["gate"], _GATE), + geq=[_int(geq[b], 0, 240, v) if b < len(geq) else v for b, v in enumerate(c["geq"])]) + for i, c in enumerate(st["outputs"]): + s = outs[i] if i < len(outs) and isinstance(outs[i], dict) else {} + mix = s.get("mix") if isinstance(s.get("mix"), list) else [] + c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]), + comp=_group(s.get("comp"), c["comp"], _COMP), limit=_group(s.get("limit"), c["limit"], _LIMIT), + matrix=_int(s.get("matrix"), 0, (1 << model.n_in) - 1, c["matrix"]), + mix=[_int(mix[k], 0, 400, v) if k < len(mix) else v for k, v in enumerate(c["mix"])]) + if isinstance(src.get("preset_name"), str): + st["preset_name"] = src["preset_name"][:14] + return st + + +def read_file(model_key: str, model: P.Model, current: dict, doc: dict | None = None, + raw: bytes | None = None) -> dict: + """The state to import from an uploaded file: our JSON (`doc`) or a bare memory image (`raw`).""" + if raw is not None: + if len(raw) not in (model.size, model.chunks * P.CHUNK_SIZE): + raise ValueError(f"Unknown file format ({len(raw)} bytes) – expected a DSP Control preset file " + f"or a memory image of the {model.name} ({model.size} bytes)") + return _linked_alike(clean_state(model, P.parse_state(model, raw.ljust(model.chunks * P.CHUNK_SIZE, b"\0")), current)) + if not isinstance(doc, dict) or doc.get("format") != FORMAT: + raise ValueError("Not a DSP Control preset file") + if str(doc.get("model")) != model_key: + raise ValueError(f"The file is for a DSP {doc.get('model')}, the connected device is a {model.name}") + base = current + try: # the raw image fills in anything the readable part lacks + img = bytes.fromhex(doc.get("raw") or "") + if len(img) in (model.size, model.chunks * P.CHUNK_SIZE): + base = clean_state(model, P.parse_state(model, img.ljust(model.chunks * P.CHUNK_SIZE, b"\0")), current) + except ValueError: + pass + return _linked_alike(clean_state(model, doc.get("state") if isinstance(doc.get("state"), dict) else {}, base)) + + +def _linked_alike(st: dict) -> dict: + """Linked channels share their settings on the DSP: take them from each group's first channel.""" + for chans in (st["inputs"], st["outputs"]): + for g in P.link_groups(chans): + for i in g[1:]: + P.copy_linked(chans, g[0], i) + return st + + +def import_commands(model: P.Model, st: dict, current: dict) -> list[tuple[int, bytes]]: + """Commands that take the DSP from `current` to `st` - only values that actually change. + + If the links change, they are dissolved first (otherwise the DSP would copy every value onto + the whole group), then the parameters are set, then the new links are formed. Forming a group + copies the first channel's settings to the others, so names, routing and mix levels (which + links don't share) are sent once more at the end. + """ + kinds = (("in", "inputs"), ("out", "outputs")) + relink = any(P.link_groups(st[key]) != P.link_groups(current[key]) for _, key in kinds) + cmds = [] + if relink: + for kind, key in kinds: + for i in range(len(st[key])): + cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + (1 << i).to_bytes(2, "little"))) + for kind, key in kinds: + for i, ch in enumerate(st[key]): + params = ["name", "gain", "polarity", "delay", "hp", "lp"] + [f"peq.{b}" for b in range(len(ch["peq"]))] + if kind == "in": + params += [f"geq.{b}" for b in range(len(ch["geq"]))] + ["gate"] + else: + params += ["comp", "limit", "matrix"] + [f"mix.{k}" for k in range(len(ch["mix"]))] + for p in params + ["mute"]: + cmd = P.param_command(model, kind, i, ch, p) + if relink or cmd != P.param_command(model, kind, i, current[key][i], p): + cmds.append(cmd) + if relink: + for kind, key in kinds: + chans = st[key] + groups = P.link_groups(chans) + for i, mask in enumerate(P.link_masks(len(chans), groups)): + if mask != 1 << i: + cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + mask.to_bytes(2, "little"))) + for g in groups: + for i in g[1:]: + extra = ["name"] + (["matrix"] + [f"mix.{k}" for k in range(len(chans[i]["mix"]))] if kind == "out" else []) + cmds += [P.param_command(model, kind, i, chans[i], p) for p in extra] + return cmds + + +def differences(target: dict, actual: dict) -> list[str]: + """Paths where the DSP's state differs from the imported one (the preset name is not settable).""" + diffs = [] + + def walk(a, b, path): + if isinstance(a, dict): + for k in a: + walk(a[k], b.get(k) if isinstance(b, dict) else None, f"{path}.{k}" if path else k) + elif isinstance(a, list): + for i, v in enumerate(a): + walk(v, b[i] if isinstance(b, list) and i < len(b) else None, f"{path}.{i}") + elif a != b: + diffs.append(path) + + walk({k: v for k, v in target.items() if k != "preset_name"}, actual, "") + return diffs diff --git a/dsp/protocol.py b/dsp/protocol.py new file mode 100644 index 0000000..5393953 --- /dev/null +++ b/dsp/protocol.py @@ -0,0 +1,536 @@ +"""t.racks DSP 204 / DSP 408 wire protocol (see PROTOCOL.md).""" + +import copy +import math +import struct +from dataclasses import dataclass + +PORT = 9761 + +# Read / system commands +CMD_ACK = 0x01 +CMD_HANDSHAKE = 0x10 +CMD_STATUS = 0x12 +CMD_DEVICE_INFO = 0x13 +CMD_INIT_14 = 0x14 +CMD_PRESET_RECALL = 0x20 +CMD_PRESET_STORE = 0x21 +CMD_INIT_22 = 0x22 +CMD_CONFIG_CHUNK = 0x24 +CMD_PRESET_STORE_NAME = 0x26 +CMD_CONFIG_REQUEST = 0x27 +CMD_PRESET_NAME = 0x29 +CMD_PRESET_COUNT = 0x2C +CMD_METER = 0x40 + +# Parameter commands +CMD_COMP = 0x30 +CMD_LOW_PASS = 0x31 +CMD_HIGH_PASS = 0x32 +CMD_PEQ = 0x33 +CMD_GAIN = 0x34 +CMD_MUTE = 0x35 +CMD_POLARITY = 0x36 +CMD_DELAY = 0x38 +CMD_MATRIX = 0x3A +CMD_CHANNEL_NAME = 0x3D +CMD_GATE = 0x3E +CMD_LIMIT = 0x3F +CMD_MIX = 0x41 +CMD_GEQ = 0x48 +CMD_LINK = 0x3B # [ch][u16 link mask], see link_masks() + +CHUNK_SIZE = 50 + + +def checksum(data: bytes) -> int: + """XOR over 02 .. 03 of the frame; the 02 and 03 bytes fold into the initial 0x01.""" + c = 0x01 + for b in data: + c ^= b + return c + + +def build_frame(cmd: int, payload: bytes = b"", addr: int = 1, src: int = 0) -> bytes: + body = bytes([src, addr, len(payload) + 1, cmd]) + bytes(payload) + return b"\x10\x02" + body + b"\x10\x03" + bytes([checksum(body)]) + + +@dataclass +class Frame: + src: int + dst: int + cmd: int + payload: bytes + checksum_ok: bool = True + + +class FrameParser: + """Reassembles frames from a TCP byte stream (length based, no byte stuffing).""" + + def __init__(self): + self.buf = bytearray() + + def feed(self, data: bytes) -> list[Frame]: + self.buf += data + frames = [] + while True: + start = self.buf.find(b"\x10\x02") + if start < 0: + # keep a trailing 0x10 that might start the next header + del self.buf[: max(0, len(self.buf) - 1)] + return frames + if start: + del self.buf[:start] + if len(self.buf) < 6: + return frames + length = self.buf[4] + total = 5 + length + 3 + if len(self.buf) < total: + return frames + if self.buf[5 + length] != 0x10 or self.buf[6 + length] != 0x03 or length == 0: + del self.buf[:2] # not a real header, resync + continue + body = bytes(self.buf[2 : 5 + length]) + frames.append( + Frame( + src=body[0], + dst=body[1], + cmd=body[3], + payload=body[4:], + checksum_ok=checksum(body) == self.buf[7 + length], + ) + ) + del self.buf[:total] + + +# ---------------------------------------------------------------- value scales + +Q_TABLE = [ + 0.4, 0.42, 0.45, 0.47, 0.5, 0.53, 0.56, 0.59, 0.63, 0.67, 0.71, 0.75, 0.79, 0.84, 0.89, + 0.94, 1.0, 1.06, 1.12, 1.19, 1.26, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.4, + 2.5, 2.7, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.2, 4.5, 4.8, 5.0, 5.3, 5.7, 6.0, 6.3, 6.7, + 7.1, 7.6, 8.0, 8.5, 9.0, 9.5, 10.1, 10.7, 11.3, 12.0, 12.7, 13.5, 14.0, 15.0, 16.0, 17.0, + 18.0, 19.0, 20.0, 21.0, 23.0, 24.0, 25.0, 27.0, 29.0, 30.0, 32.0, 34.0, 36.0, 38.0, 40.0, + 43.0, 45.0, 48.0, 51.0, 54.0, 57.0, 60.0, 64.0, 68.0, 72.0, 76.0, 81.0, 85.0, 91.0, 96.0, + 102.0, 108.0, 114.0, 121.0, 128.0, +] +RATIO_NAMES = ["1.0", "1.1", "1.3", "1.5", "1.7", "2.0", "2.5", "3.0", "3.5", "4.0", "5.0", + "6.0", "8.0", "10", "20", "Limit"] +PEQ_TYPES = ["Peak", "Low Shelf", "High Shelf", "HPF -6", "HPF -12", "LPF -6", "LPF -12", + "Allpass 1", "Allpass 2"] +SLOPES = ["Bypass", "BW -6", "BL -6", "BW -12", "BL -12", "LK -12", "BW -18", "BL -18", "BW -24", + "BL -24", "LK -24", "BW -30", "BL -30", "BW -36", "BL -36", "LK -36", "BW -42", "BL -42", + "BW -48", "BL -48", "LK -48"] + + +def gain_to_db(raw: int) -> float: + return raw / 2 - 60 if raw < 80 else (raw - 280) / 10 + + +def db_to_gain(db: float) -> int: + raw = round((db + 60) * 2) if db < -20 else round(db * 10 + 280) + return max(0, min(400, raw)) + + +def freq_to_hz(raw: int) -> float: + return 1000.0 * 2 ** ((raw - 170) / 30) + + +def hz_to_freq(hz: float) -> int: + return max(0, min(300, round(170 + 30 * math.log2(max(hz, 1.0) / 1000.0)))) + + +def eq_gain_to_db(raw: int) -> float: + return (raw - 120) / 10 + + +def threshold_to_db(raw: int) -> float: + return (raw - 180) / 2 + + +def delay_to_ms(raw: int) -> float: + return raw / 96 + + +def decode_meters(payload: bytes) -> list[float]: + """12 linear levels (In A-D, Out 1-8) from a 0x40 response payload.""" + levels = [] + for i in range(12): + b = payload[i * 3 : i * 3 + 3] + if len(b) < 3: + levels.append(0.0) + continue + v = struct.unpack(" 0 else 0.0) + return levels + + +def decode_limit_flags(payload: bytes, n_out: int) -> list[bool]: + """Limiter active per output, from the 2 status bytes after the levels (bit i = output i). + + Seen on a DSP 204: 00 03 while Out 1+2 limit, 00 0C for Out 3+4. That outputs 5-8 of the 408 + continue in the same 16-bit value is an assumption. + """ + if len(payload) < 38: + return [False] * n_out + flags = payload[36] << 8 | payload[37] + return [bool(flags >> i & 1) for i in range(n_out)] + + +def encode_meters(levels: list[float], limit_flags: int = 0) -> bytes: + """Inverse of decode_meters / decode_limit_flags (used by the simulator).""" + out = bytearray() + for v in levels: + raw = struct.pack("> 8 & 0xFF, limit_flags & 0xFF]) + + +# ---------------------------------------------------------------- device models + + +@dataclass(frozen=True) +class Model: + name: str + n_in: int + n_out: int + + @property + def in_size(self) -> int: + return 140 + + @property + def out_size(self) -> int: + return 96 + 2 * self.n_in + + @property + def out_base(self) -> int: + return 0x10 + self.n_in * self.in_size + + @property + def globals_base(self) -> int: + return self.out_base + self.n_out * self.out_size + + @property + def size(self) -> int: + return self.globals_base + 4 + 2 * self.n_in + 2 * self.n_out + 12 + + @property + def chunks(self) -> int: + return -(-self.size // CHUNK_SIZE) + + def channel(self, kind: str, idx: int) -> int: + """Wire channel number for input/output index.""" + return idx if kind == "in" else self.n_in + idx + + def meter_index(self, kind: str, idx: int) -> int: + return idx if kind == "in" else 4 + idx + + +MODELS = {"204": Model("DSP 204", 2, 4), "408": Model("DSP 408", 4, 8)} + + +def detect_model(info: str) -> str | None: + for key in MODELS: + if f"DSP{key}" in info.replace(" ", ""): + return key + return None + + +# ---------------------------------------------------------------- state (de)serialisation + + +_UMLAUTS = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss"}) + + +def clean_name(name) -> str: + """Channel name as the DSP stores it: printable ASCII, at most 8 characters.""" + s = str(name or "").translate(_UMLAUTS) + return "".join(c for c in s if " " <= c <= "~")[:8] + + +def _name(b: bytes) -> str: + return b.split(b"\x00")[0].decode("latin1").strip() + + +def _peq(buf: bytes, off: int, n: int) -> list[dict]: + bands = [] + for i in range(n): + gain, freq, q, typ = struct.unpack_from("= 9}) + return bands + + +def parse_state(model: Model, buf: bytes) -> dict: + """Decode the reassembled config dump into a JSON friendly dict (raw values).""" + u16 = lambda off: struct.unpack_from("> i & 1), + }) + outputs = [] + for i in range(model.n_out): + o = model.out_base + i * model.out_size + p = o + 10 + 2 * model.n_in + outputs.append({ + "name": _name(buf[o : o + 8]), + "matrix": u16(o + 8), + "mix": list(struct.unpack_from(f"<{model.n_in}H", buf, o + 10)), + "hp": {"freq": u16(p), "slope": buf[p + 4]}, + "lp": {"freq": u16(p + 2), "slope": buf[p + 5]}, + "peq": _peq(buf, p + 6, 9), + "comp": dict(zip(("ratio", "attack", "release", "knee", "threshold"), + struct.unpack_from("<5H", buf, p + 60))), + "limit": dict(zip(("attack", "release", "knee", "threshold"), + struct.unpack_from("<4H", buf, p + 70))), + "gain": u16(p + 78), + "polarity": u16(p + 80) != 0, + "delay": u16(p + 82), + "link": u16(p + 84), + "mute": bool(out_mute >> i & 1), + }) + return {"preset_name": _name(buf[2:16]), "inputs": inputs, "outputs": outputs} + + +def build_state_buffer(model: Model, state: dict) -> bytearray: + """Inverse of parse_state (used by the simulator).""" + buf = bytearray(model.chunks * CHUNK_SIZE) + pad = lambda s, n: s.encode("latin1")[:n].ljust(n, b" ") + buf[0:2] = b"\xff\xff" + buf[2:16] = pad(state["preset_name"], 14) + + def put_peq(off, bands): + for i, b in enumerate(bands): + struct.pack_into(" dict: + peq = lambda n: [{"gain": 120, "freq": 50 + i * 25, "q": 32, "type": 0, "bypass": False} + for i in range(n)] + return { + "preset_name": "Default", + "inputs": [{ + "name": f"In{chr(65 + i)}", "gate": {"attack": 0, "release": 99, "hold": 99, "threshold": 0}, + "geq": [120] * 31, "peq": peq(8), "hp": {"freq": 0, "slope": 0}, + "lp": {"freq": 300, "slope": 0}, "gain": 280, "polarity": False, "delay": 0, "mute": False, + "link": 1 << i, + } for i in range(model.n_in)], + "outputs": [{ + "name": f"Out{i + 1}", "matrix": 1 << (i % model.n_in), "mix": [280] * model.n_in, + "hp": {"freq": 0, "slope": 0}, "lp": {"freq": 300, "slope": 0}, "peq": peq(9), + "comp": {"ratio": 0, "attack": 49, "release": 499, "knee": 0, "threshold": 220}, + "limit": {"attack": 49, "release": 499, "knee": 0, "threshold": 220}, + "gain": 280, "polarity": False, "delay": 0, "mute": False, "link": 1 << i, + } for i in range(model.n_out)], + } + + +# ---------------------------------------------------------------- channel links +# +# Every channel stores a u16 link mask (bit = channel index within inputs resp. outputs): +# a free channel has only its own bit, the first channel of a group the bits of all members, +# the other members 0. The DSP itself applies a change on any member to the whole group +# (except name, routing and mix levels) and copies the first channel's settings when a group is formed. + +LINK_EXCLUDED = ("name", "mix", "matrix", "link") # per channel even when linked (e.g. Out 1 <- A, Out 2 <- B) + + +def link_groups(chans: list[dict]) -> list[list[int]]: + """Channel indices grouped by link (single channels included), in channel order.""" + seen: set[int] = set() + groups = [] + for i, ch in enumerate(chans): + if i in seen: + continue + mask = ch.get("link", 1 << i) + g = [j for j in range(len(chans)) if (j == i or mask >> j & 1) and j not in seen] + seen.update(g) + groups.append(g) + return groups + + +def link_group(chans: list[dict], idx: int) -> list[int]: + return next(g for g in link_groups(chans) if idx in g) + + +def link_masks(n: int, groups: list[list[int]]) -> list[int]: + """Per-channel link masks for the given groups (channels not mentioned stay free).""" + masks = [1 << i for i in range(n)] + for g in groups: + g = sorted({i for i in g if 0 <= i < n}) + if len(g) < 2: + continue + masks[g[0]] = sum(1 << i for i in g) + for i in g[1:]: + masks[i] = 0 + return masks + + +def copy_linked(chans: list[dict], src: int, dst: int): + for k, v in chans[src].items(): + if k not in LINK_EXCLUDED: + chans[dst][k] = copy.deepcopy(v) + + +# ---------------------------------------------------------------- parameter -> command + + +def _w(v: int) -> bytes: + return struct.pack(" tuple[int, bytes]: + """Build (cmd, payload) for a changed parameter. `ch` is the already-updated channel dict. + + `param` is a dotted path like "gain", "hp.freq", "peq.3.gain", "geq.10", "mix.1". + """ + c = model.channel(kind, idx) + top, *rest = param.split(".") + if top == "gain": + return CMD_GAIN, bytes([c]) + _w(ch["gain"]) + if top == "mute": + return CMD_MUTE, bytes([c, int(ch["mute"])]) + if top == "polarity": + return CMD_POLARITY, bytes([c, int(ch["polarity"])]) + if top == "delay": + return CMD_DELAY, bytes([c]) + _w(ch["delay"]) + if top == "name": + return CMD_CHANNEL_NAME, bytes([c]) + clean_name(ch["name"]).encode("ascii").ljust(8, b" ") + if top in ("hp", "lp"): + f = ch[top] + return (CMD_HIGH_PASS if top == "hp" else CMD_LOW_PASS), bytes([c]) + _w(f["freq"]) + bytes([f["slope"]]) + if top == "peq": + band = int(rest[0]) + b = ch["peq"][band] + return CMD_PEQ, bytes([c, band]) + _w(b["gain"]) + _w(b["freq"]) + bytes( + [b["q"], b["type"], int(b["bypass"])]) + if top == "geq" and kind == "in": + band = int(rest[0]) + return CMD_GEQ, bytes([c, band]) + _w(ch["geq"][band]) + if top == "gate" and kind == "in": + g = ch["gate"] + return CMD_GATE, bytes([c]) + b"".join(_w(g[k]) for k in ("attack", "release", "hold", "threshold")) + if top == "comp" and kind == "out": + g = ch["comp"] + return CMD_COMP, bytes([c]) + b"".join( + _w(g[k]) for k in ("ratio", "attack", "release", "knee", "threshold")) + if top == "limit" and kind == "out": + g = ch["limit"] + return CMD_LIMIT, bytes([c]) + b"".join(_w(g[k]) for k in ("attack", "release", "knee", "threshold")) + if top == "matrix" and kind == "out": + return CMD_MATRIX, bytes([c, ch["matrix"] & 0xFF]) + if top == "mix" and kind == "out": + i = int(rest[0]) + return CMD_MIX, bytes([c, i]) + _w(ch["mix"][i]) + raise ValueError(f"unknown parameter {kind}.{param}") + + +def apply_param(state_ch: dict, param: str, value): + """Write `value` into the channel dict at the dotted `param` path.""" + keys = param.split(".") + node = state_ch + for k in keys[:-1]: + node = node[int(k)] if isinstance(node, list) else node[k] + last = keys[-1] + if isinstance(node, list): + node[int(last)] = value + else: + node[last] = value + + +def apply_command(model: Model, state: dict, cmd: int, p: bytes): + """Update state from an incoming set command (used by the simulator).""" + if not p: + return + c = p[0] + kind, idx = ("in", c) if c < model.n_in else ("out", c - model.n_in) + chans = state["inputs" if kind == "in" else "outputs"] + if idx >= len(chans): + return + ch = chans[idx] + w = lambda o: struct.unpack_from("> j & 1: + copy_linked(chans, idx, j) + return + # like the real DSP: a change on a linked channel applies to the whole group + for j in link_group(chans, idx): + if j != idx: + copy_linked(chans, idx, j) diff --git a/dsp/usbhid.py b/dsp/usbhid.py new file mode 100644 index 0000000..1c4c630 --- /dev/null +++ b/dsp/usbhid.py @@ -0,0 +1,431 @@ +"""USB connection to the DSPs (USB HID, no driver needed). + +Both models enumerate as VID 0x0168 / PID 0x0821. +Every HID report carries exactly one protocol frame starting at byte 0 (the same frames as on TCP, +length = LEN + 8), sent with report ID 0 and zero-padded to the report length. + +Windows uses hid.dll via ctypes, macOS IOKit via ctypes, Linux /dev/hidraw* (Raspberry Pi). No extra packages. +""" + +import asyncio +import os +import sys +import threading + +VID, PID = 0x0168, 0x0821 + + +# ------------------------------------------------------------------ Windows (hid.dll) + +if sys.platform == "win32": + import ctypes + from ctypes import wintypes as W + + _hid = ctypes.WinDLL("hid") + _setup = ctypes.WinDLL("setupapi") + _k32 = ctypes.WinDLL("kernel32", use_last_error=True) + + class _GUID(ctypes.Structure): + _fields_ = [("d1", W.DWORD), ("d2", W.WORD), ("d3", W.WORD), ("d4", ctypes.c_ubyte * 8)] + + class _IFDATA(ctypes.Structure): + _fields_ = [("cbSize", W.DWORD), ("guid", _GUID), ("flags", W.DWORD), ("reserved", ctypes.c_void_p)] + + class _ATTR(ctypes.Structure): + _fields_ = [("Size", W.ULONG), ("VendorID", W.USHORT), ("ProductID", W.USHORT), ("Version", W.USHORT)] + + class _CAPS(ctypes.Structure): + _fields_ = [("Usage", W.USHORT), ("UsagePage", W.USHORT), ("InputReportByteLength", W.USHORT), + ("OutputReportByteLength", W.USHORT), ("FeatureReportByteLength", W.USHORT), + ("Reserved", W.USHORT * 17), ("rest", W.USHORT * 10)] + + _k32.CreateFileW.restype = W.HANDLE + _k32.CreateFileW.argtypes = [W.LPCWSTR, W.DWORD, W.DWORD, ctypes.c_void_p, W.DWORD, W.DWORD, W.HANDLE] + _k32.ReadFile.argtypes = [W.HANDLE, ctypes.c_void_p, W.DWORD, ctypes.POINTER(W.DWORD), ctypes.c_void_p] + _k32.WriteFile.argtypes = [W.HANDLE, ctypes.c_void_p, W.DWORD, ctypes.POINTER(W.DWORD), ctypes.c_void_p] + _k32.CloseHandle.argtypes = [W.HANDLE] + _k32.CancelIoEx.argtypes = [W.HANDLE, ctypes.c_void_p] + _setup.SetupDiGetClassDevsW.restype = W.HANDLE + _setup.SetupDiGetClassDevsW.argtypes = [ctypes.POINTER(_GUID), W.LPCWSTR, W.HWND, W.DWORD] + _setup.SetupDiEnumDeviceInterfaces.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.POINTER(_GUID), W.DWORD, + ctypes.POINTER(_IFDATA)] + _setup.SetupDiGetDeviceInterfaceDetailW.argtypes = [W.HANDLE, ctypes.POINTER(_IFDATA), ctypes.c_void_p, W.DWORD, + ctypes.POINTER(W.DWORD), ctypes.c_void_p] + _setup.SetupDiDestroyDeviceInfoList.argtypes = [W.HANDLE] + _hid.HidD_GetAttributes.argtypes = [W.HANDLE, ctypes.POINTER(_ATTR)] + _hid.HidD_GetProductString.argtypes = [W.HANDLE, ctypes.c_void_p, W.ULONG] + _hid.HidD_GetSerialNumberString.argtypes = [W.HANDLE, ctypes.c_void_p, W.ULONG] + _hid.HidD_GetPreparsedData.argtypes = [W.HANDLE, ctypes.POINTER(ctypes.c_void_p)] + _hid.HidD_FreePreparsedData.argtypes = [ctypes.c_void_p] + _hid.HidP_GetCaps.argtypes = [ctypes.c_void_p, ctypes.POINTER(_CAPS)] + + _INVALID = W.HANDLE(-1).value + _GENERIC_RW, _SHARE_RW, _OPEN_EXISTING = 0xC0000000, 0x3, 3 + + def _open(path: str, access: int = _GENERIC_RW): + h = _k32.CreateFileW(path, access, _SHARE_RW, None, _OPEN_EXISTING, 0, None) + if h in (None, _INVALID): + raise OSError(ctypes.get_last_error(), f"Cannot open USB device (error {ctypes.get_last_error()})") + return h + + def _string(fn, h) -> str: + buf = ctypes.create_unicode_buffer(128) + return buf.value if fn(h, buf, ctypes.sizeof(buf)) else "" + + def _paths() -> list[str]: + guid = _GUID() + _hid.HidD_GetHidGuid(ctypes.byref(guid)) + info = _setup.SetupDiGetClassDevsW(ctypes.byref(guid), None, None, 0x12) # PRESENT | DEVICEINTERFACE + paths = [] + try: + i = 0 + while True: + ifd = _IFDATA(cbSize=ctypes.sizeof(_IFDATA)) + if not _setup.SetupDiEnumDeviceInterfaces(info, None, ctypes.byref(guid), i, ctypes.byref(ifd)): + break + i += 1 + need = W.DWORD() + _setup.SetupDiGetDeviceInterfaceDetailW(info, ctypes.byref(ifd), None, 0, ctypes.byref(need), None) + buf = ctypes.create_string_buffer(need.value) + ctypes.cast(buf, ctypes.POINTER(W.DWORD))[0] = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6 + if _setup.SetupDiGetDeviceInterfaceDetailW(info, ctypes.byref(ifd), buf, need, None, None): + paths.append(ctypes.wstring_at(ctypes.addressof(buf) + 4)) + finally: + _setup.SetupDiDestroyDeviceInfoList(info) + return paths + + def list_devices() -> list[dict]: + found = [] + for path in _paths(): + try: + h = _open(path, 0) # attributes only: works even while another program has it open + except OSError: + continue + try: + a = _ATTR(Size=ctypes.sizeof(_ATTR)) + if _hid.HidD_GetAttributes(h, ctypes.byref(a)) and (a.VendorID, a.ProductID) == (VID, PID): + found.append({"path": path, "product": _string(_hid.HidD_GetProductString, h), + "serial": _string(_hid.HidD_GetSerialNumberString, h)}) + finally: + _k32.CloseHandle(h) + return found + + class HidDevice: + """One opened DSP. Separate read and write handles: a blocking ReadFile would otherwise + serialise every WriteFile behind it on a synchronous handle.""" + + def __init__(self, path: str): + self.rh = _open(path) + try: + self.wh = _open(path) + pp = ctypes.c_void_p() + caps = _CAPS() + if _hid.HidD_GetPreparsedData(self.rh, ctypes.byref(pp)): + _hid.HidP_GetCaps(pp, ctypes.byref(caps)) + _hid.HidD_FreePreparsedData(pp) + self.in_len = caps.InputReportByteLength or 65 + self.out_len = caps.OutputReportByteLength or 65 + except OSError: + _k32.CloseHandle(self.rh) + raise + + def read_report(self) -> bytes: + buf = ctypes.create_string_buffer(self.in_len) + n = W.DWORD() + if not _k32.ReadFile(self.rh, buf, self.in_len, ctypes.byref(n), None): + raise OSError(ctypes.get_last_error(), "USB connection lost") + return buf.raw[1:n.value] # drop the report ID + + def write_report(self, data: bytes): + report = (b"\x00" + data).ljust(self.out_len, b"\x00")[: self.out_len] + n = W.DWORD() + if not _k32.WriteFile(self.wh, report, len(report), ctypes.byref(n), None): + raise OSError(ctypes.get_last_error(), "USB write error") + + def close(self): + _k32.CancelIoEx(self.rh, None) # wakes up the blocked reader thread + for h in (self.rh, self.wh): + _k32.CloseHandle(h) + + +# ------------------------------------------------------------------ Linux (hidraw) + +elif sys.platform.startswith("linux"): + + def list_devices() -> list[dict]: + found = [] + base = "/sys/class/hidraw" + for name in sorted(os.listdir(base)) if os.path.isdir(base) else []: + try: + with open(f"{base}/{name}/device/uevent") as f: + ev = dict(line.strip().split("=", 1) for line in f if "=" in line) + except OSError: + continue + ids = ev.get("HID_ID", "").split(":") + if len(ids) == 3 and int(ids[1], 16) == VID and int(ids[2], 16) == PID: + found.append({"path": f"/dev/{name}", "product": ev.get("HID_NAME", ""), "serial": ev.get("HID_UNIQ", "")}) + return found + + class HidDevice: + def __init__(self, path: str): + self.fd = os.open(path, os.O_RDWR) + self.in_len = self.out_len = 65 + + def read_report(self) -> bytes: + data = os.read(self.fd, 64) # hidraw returns the report without a report ID + if not data: + raise OSError("USB connection lost") + return data + + def write_report(self, data: bytes): + os.write(self.fd, (b"\x00" + data).ljust(self.out_len, b"\x00")) + + def close(self): + try: + os.close(self.fd) + except OSError: + pass + +# ------------------------------------------------------------------ macOS (IOKit IOHIDDevice) + +elif sys.platform == "darwin": + import ctypes + import queue + + _iokit = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/IOKit.framework/IOKit") + _cf = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation") + _vp, _i32 = ctypes.c_void_p, ctypes.c_int32 + + _UTF8, _SINT32, _SINT64 = 0x08000100, 3, 4 + _REPORT_OUTPUT = 1 + _ReportCB = ctypes.CFUNCTYPE(None, _vp, _i32, _vp, ctypes.c_int, ctypes.c_uint32, + ctypes.POINTER(ctypes.c_uint8), ctypes.c_long) + _RemovalCB = ctypes.CFUNCTYPE(None, _vp, _i32, _vp) + + for _name, _res, _args in ( + ("CFStringCreateWithCString", _vp, [_vp, ctypes.c_char_p, ctypes.c_uint32]), + ("CFStringGetCString", ctypes.c_bool, [_vp, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32]), + ("CFNumberCreate", _vp, [_vp, ctypes.c_int, _vp]), + ("CFNumberGetValue", ctypes.c_bool, [_vp, ctypes.c_int, _vp]), + ("CFGetTypeID", ctypes.c_ulong, [_vp]), + ("CFStringGetTypeID", ctypes.c_ulong, []), + ("CFNumberGetTypeID", ctypes.c_ulong, []), + ("CFDictionaryCreateMutable", _vp, [_vp, ctypes.c_long, _vp, _vp]), + ("CFDictionarySetValue", None, [_vp, _vp, _vp]), + ("CFSetGetCount", ctypes.c_long, [_vp]), + ("CFSetGetValues", None, [_vp, _vp]), + ("CFRetain", _vp, [_vp]), + ("CFRelease", None, [_vp]), + ("CFRunLoopGetCurrent", _vp, []), + ("CFRunLoopRunInMode", _i32, [_vp, ctypes.c_double, ctypes.c_bool]), + ("CFRunLoopStop", None, [_vp]), + ): + getattr(_cf, _name).restype, getattr(_cf, _name).argtypes = _res, _args + for _name, _res, _args in ( + ("IOHIDManagerCreate", _vp, [_vp, ctypes.c_uint32]), + ("IOHIDManagerSetDeviceMatching", None, [_vp, _vp]), + ("IOHIDManagerCopyDevices", _vp, [_vp]), + ("IOHIDDeviceGetProperty", _vp, [_vp, _vp]), + ("IOHIDDeviceOpen", _i32, [_vp, ctypes.c_uint32]), + ("IOHIDDeviceClose", _i32, [_vp, ctypes.c_uint32]), + ("IOHIDDeviceSetReport", _i32, [_vp, ctypes.c_int, ctypes.c_long, _vp, ctypes.c_long]), + ("IOHIDDeviceRegisterInputReportCallback", None, [_vp, _vp, ctypes.c_long, _ReportCB, _vp]), + ("IOHIDDeviceRegisterRemovalCallback", None, [_vp, _RemovalCB, _vp]), + ("IOHIDDeviceScheduleWithRunLoop", None, [_vp, _vp, _vp]), + ("IOHIDDeviceUnscheduleFromRunLoop", None, [_vp, _vp, _vp]), + ): + getattr(_iokit, _name).restype, getattr(_iokit, _name).argtypes = _res, _args + + _MODE = _vp.in_dll(_cf, "kCFRunLoopDefaultMode") + _KEY_CB = _vp.in_dll(_cf, "kCFTypeDictionaryKeyCallBacks") + _VAL_CB = _vp.in_dll(_cf, "kCFTypeDictionaryValueCallBacks") + + def _cfstr(s: str): + return _cf.CFStringCreateWithCString(None, s.encode(), _UTF8) + + def _prop(dev, key: str): + k = _cfstr(key) + try: + v = _iokit.IOHIDDeviceGetProperty(dev, k) + finally: + _cf.CFRelease(k) + if not v: + return None + if _cf.CFGetTypeID(v) == _cf.CFNumberGetTypeID(): + n = ctypes.c_int64() + _cf.CFNumberGetValue(v, _SINT64, ctypes.byref(n)) + return n.value + if _cf.CFGetTypeID(v) == _cf.CFStringGetTypeID(): + buf = ctypes.create_string_buffer(256) + return buf.value.decode(errors="replace") if _cf.CFStringGetCString(v, buf, 256, _UTF8) else "" + return None + + def _path(dev) -> str: + # LocationID identifies the USB port, so a saved device is found again after replugging + return f"usb-loc:{(_prop(dev, 'LocationID') or 0) & 0xFFFFFFFF:08x}" + + def _devices() -> list: + """Retained IOHIDDeviceRefs of all connected DSPs (caller releases them).""" + mgr = _iokit.IOHIDManagerCreate(None, 0) + match = _cf.CFDictionaryCreateMutable(None, 0, ctypes.byref(_KEY_CB), ctypes.byref(_VAL_CB)) + try: + for key, val in (("VendorID", VID), ("ProductID", PID)): + k, n = _cfstr(key), ctypes.c_int32(val) + v = _cf.CFNumberCreate(None, _SINT32, ctypes.byref(n)) + _cf.CFDictionarySetValue(match, k, v) + _cf.CFRelease(k) + _cf.CFRelease(v) + _iokit.IOHIDManagerSetDeviceMatching(mgr, match) + devset = _iokit.IOHIDManagerCopyDevices(mgr) + if not devset: + return [] + count = _cf.CFSetGetCount(devset) + arr = (_vp * count)() + _cf.CFSetGetValues(devset, arr) + devs = [_cf.CFRetain(d) for d in arr] + _cf.CFRelease(devset) + return sorted(devs, key=_path) + finally: + _cf.CFRelease(match) + _cf.CFRelease(mgr) + + def list_devices() -> list[dict]: + found = [] + for dev in _devices(): + found.append({"path": _path(dev), "product": _prop(dev, "Product") or "", + "serial": _prop(dev, "SerialNumber") or ""}) + _cf.CFRelease(dev) + return found + + class HidDevice: + """One opened DSP. IOKit delivers input reports through a run loop, so a private thread + runs one and hands the reports to read_report() through a queue.""" + + def __init__(self, path: str): + devs = _devices() + self.dev = next((d for d in devs if _path(d) == path), None) + for d in devs: + if d != self.dev: + _cf.CFRelease(d) + if not self.dev: + raise OSError("USB device not found – check the cable") + ret = _iokit.IOHIDDeviceOpen(self.dev, 0) & 0xFFFFFFFF + if ret: + _cf.CFRelease(self.dev) + raise OSError(ret, "USB device is in use by another program" if ret == 0xE00002C5 + else f"Cannot open USB device (error 0x{ret:08x})") + self.in_len = _prop(self.dev, "MaxInputReportSize") or 64 + self.out_len = _prop(self.dev, "MaxOutputReportSize") or 64 + self.reports: queue.Queue = queue.Queue() + self.closed = False + self.runloop = None + self.buf = (ctypes.c_uint8 * self.in_len)() + self._on_report = _ReportCB(lambda _c, _r, _s, _t, _id, data, n: self.reports.put(ctypes.string_at(data, n))) + self._on_removal = _RemovalCB(lambda _c, _r, _s: self.reports.put(None)) + ready = threading.Event() + threading.Thread(target=self._run, args=(ready,), daemon=True, name="usb-runloop").start() + ready.wait(5) + + def _run(self, ready: threading.Event): + self.runloop = _cf.CFRunLoopGetCurrent() + _iokit.IOHIDDeviceRegisterInputReportCallback(self.dev, self.buf, self.in_len, self._on_report, None) + _iokit.IOHIDDeviceRegisterRemovalCallback(self.dev, self._on_removal, None) + _iokit.IOHIDDeviceScheduleWithRunLoop(self.dev, self.runloop, _MODE) + ready.set() + while not self.closed: + _cf.CFRunLoopRunInMode(_MODE, 0.5, False) + _iokit.IOHIDDeviceUnscheduleFromRunLoop(self.dev, self.runloop, _MODE) + _iokit.IOHIDDeviceClose(self.dev, 0) + _cf.CFRelease(self.dev) + + def read_report(self) -> bytes: + data = self.reports.get() + if data is None: + raise OSError("USB connection lost") + return data # IOKit delivers the report without a report ID + + def write_report(self, data: bytes): + report = data.ljust(self.out_len, b"\x00")[: self.out_len] + ret = _iokit.IOHIDDeviceSetReport(self.dev, _REPORT_OUTPUT, 0, report, len(report)) & 0xFFFFFFFF + if ret: + raise OSError(ret, f"USB write error (0x{ret:08x})") + + def close(self): + if not self.closed: + self.closed = True + self.reports.put(None) # wakes up the blocked reader thread + if self.runloop: + _cf.CFRunLoopStop(self.runloop) + +else: + def list_devices() -> list[dict]: + return [] + + class HidDevice: + def __init__(self, path: str): + raise OSError("USB is not supported on this system") + + +# ------------------------------------------------------------------ asyncio stream adapter + +def frame_bytes(report: bytes, carry: list) -> bytes: + """The protocol bytes in one input report (strips the zero padding after the frame). + `carry` holds the bytes still missing from a frame longer than one report.""" + if carry[0] > 0: + take = report[: carry[0]] + carry[0] -= len(take) + return take + if report[:2] != b"\x10\x02" or len(report) < 5: + return b"" + need = report[4] + 8 + take = report[:need] + carry[0] = need - len(take) + return take + + +class HidStream: + """Gives a HID device the reader/writer interface Device uses for TCP.""" + + def __init__(self, dev): + self.dev = dev + self.loop = asyncio.get_running_loop() + self.queue: asyncio.Queue = asyncio.Queue() + self.closed = False + threading.Thread(target=self._reader, daemon=True, name="usb-read").start() + + def _reader(self): + carry = [0] + try: + while not self.closed: + data = frame_bytes(self.dev.read_report(), carry) + if data: + self.loop.call_soon_threadsafe(self.queue.put_nowait, data) + except OSError: + pass + self.loop.call_soon_threadsafe(self.queue.put_nowait, b"") # EOF + + async def read(self, _n: int = -1) -> bytes: + return await self.queue.get() + + def write(self, data: bytes): + self.dev.write_report(data) + + async def drain(self): + pass + + def close(self): + if not self.closed: + self.closed = True + self.dev.close() + + +async def open_stream(path: str = "") -> tuple[HidStream, HidStream]: + """Open the DSP at `path` (empty = the first one found).""" + if not path: + devs = await asyncio.to_thread(list_devices) + if not devs: + raise ConnectionError("No DSP found via USB – check the cable") + path = devs[0]["path"] + dev = await asyncio.to_thread(HidDevice, path) + s = HidStream(dev) + return s, s diff --git a/packaging/build.py b/packaging/build.py new file mode 100644 index 0000000..5d4ae45 --- /dev/null +++ b/packaging/build.py @@ -0,0 +1,63 @@ +"""Builds the desktop programs into dist/: + + python -m pip install pyinstaller pywebview pillow + python packaging/build.py + +Windows: + dist/DSP Control.exe desktop app (own window, no PIN; optional remote access with PIN) + dist/DSP Control Pi Writer.exe SD card writer for a Raspberry Pi running the WebUI +macOS: + dist/DSP Control.app the same desktop app + dist/DSP Control.dmg disk image with the app and a link to /Applications +""" + +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SEP = ";" if sys.platform == "win32" else ":" + + +def pyinstaller(*args, onefile=True): + cmd = [sys.executable, "-m", "PyInstaller", "--noconfirm", "--onefile" if onefile else "--onedir", "--windowed", + "--distpath", str(ROOT / "dist"), "--workpath", str(ROOT / "build"), "--specpath", str(ROOT / "build"), *args] + print(">", " ".join(cmd)) + subprocess.run(cmd, cwd=ROOT, check=True) + + +def data(src, dest="."): + return ["--add-data", f"{ROOT / src}{SEP}{dest}"] + + +def build_mac(): + app = ROOT / "dist" / "DSP Control.app" + pyinstaller("--name", "DSP Control", "--icon", str(ROOT / "packaging" / "dsp-control.icns"), + "--osx-bundle-identifier", "at.thiemoo.dspcontrol", *data("static", "static"), + str(ROOT / "desktop.py"), onefile=False) # a .app bundle is always a folder + shutil.rmtree(ROOT / "dist" / "DSP Control", ignore_errors=True) # the loose onedir copy next to the .app + dmg = ROOT / "dist" / "DSP Control.dmg" + dmg.unlink(missing_ok=True) + with tempfile.TemporaryDirectory() as tmp: + shutil.copytree(app, Path(tmp) / app.name, symlinks=True) + (Path(tmp) / "Applications").symlink_to("/Applications") + subprocess.run(["hdiutil", "create", "-volname", "DSP Control", "-srcfolder", tmp, "-ov", + "-format", "UDZO", str(dmg)], check=True) + print("\nDone:", app.name, dmg.name, sep="\n ") + + +subprocess.run([sys.executable, str(ROOT / "packaging" / "make_icons.py")], check=True) + +if sys.platform == "darwin": + build_mac() + sys.exit() + +pyinstaller("--name", "DSP Control", "--icon", str(ROOT / "packaging" / "dsp-control.ico"), + *data("static", "static"), str(ROOT / "desktop.py")) + +pyinstaller("--name", "DSP Control Pi Writer", "--icon", str(ROOT / "packaging" / "pi-writer.ico"), "--uac-admin", + *data("server.py"), *data("dsp", "dsp"), *data("static", "static"), str(ROOT / "pi_writer.py")) + +print("\nDone:", *(p.name for p in (ROOT / "dist").glob("*.exe")), sep="\n ") diff --git a/packaging/dsp-control.icns b/packaging/dsp-control.icns new file mode 100644 index 0000000..8c87989 Binary files /dev/null and b/packaging/dsp-control.icns differ diff --git a/packaging/dsp-control.ico b/packaging/dsp-control.ico new file mode 100644 index 0000000..6dbd586 Binary files /dev/null and b/packaging/dsp-control.ico differ diff --git a/packaging/dsp-control.png b/packaging/dsp-control.png new file mode 100644 index 0000000..915b75c Binary files /dev/null and b/packaging/dsp-control.png differ diff --git a/packaging/make_icons.py b/packaging/make_icons.py new file mode 100644 index 0000000..fb61ee7 --- /dev/null +++ b/packaging/make_icons.py @@ -0,0 +1,53 @@ +"""Draws the two app icons (.ico, .icns) with Pillow: python packaging/make_icons.py""" + +import sys +from pathlib import Path + +from PIL import Image, ImageDraw + +HERE = Path(__file__).resolve().parent +S = 256 + + +def base(bg="#161a20"): + im = Image.new("RGBA", (S, S), (0, 0, 0, 0)) + d = ImageDraw.Draw(im) + d.rounded_rectangle((8, 8, S - 8, S - 8), radius=52, fill=bg) + return im, d + + +def bars(d, x0, y0, scale, color="#38bdf8"): + # the WebUI logo: four level bars + for x, top in ((7, 10), (13, 6), (19, 14), (25, 9)): + d.line(((x0 + x * scale, y0 + 22 * scale), (x0 + x * scale, y0 + top * scale)), fill=color, width=int(3 * scale)) + d.ellipse((x0 + x * scale - 1.5 * scale, y0 + top * scale - 1.5 * scale, + x0 + x * scale + 1.5 * scale, y0 + top * scale + 1.5 * scale), fill=color) + d.ellipse((x0 + x * scale - 1.5 * scale, y0 + 22 * scale - 1.5 * scale, + x0 + x * scale + 1.5 * scale, y0 + 22 * scale + 1.5 * scale), fill=color) + + +def app_icon(): + im, d = base() + bars(d, 0, 12, 8) + return im + + +def writer_icon(): + im, d = base() + # SD card outline with cut corner + d.polygon([(70, 40), (160, 40), (190, 70), (190, 216), (70, 216)], fill="#e8edf3") + for i in range(5): + d.rectangle((86 + i * 19, 52, 96 + i * 19, 82), fill="#c0841a") + bars(d, 74, 98, 3.6, color="#0284c7") + # Raspberry-red write arrow + d.polygon([(196, 150), (232, 150), (214, 182)], fill="#e11d48") + d.rectangle((207, 112, 221, 152), fill="#e11d48") + return im + + +for name, im in (("dsp-control.ico", app_icon()), ("pi-writer.ico", writer_icon())): + im.save(HERE / name, sizes=[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]) + im.save(HERE / name.replace(".ico", ".png")) + if sys.platform == "darwin": # the macOS app icon, only needed (and built) there + im.resize((1024, 1024), Image.LANCZOS).save(HERE / name.replace(".ico", ".icns")) + print("wrote", name) diff --git a/packaging/pi-writer.icns b/packaging/pi-writer.icns new file mode 100644 index 0000000..9d5c00c Binary files /dev/null and b/packaging/pi-writer.icns differ diff --git a/packaging/pi-writer.ico b/packaging/pi-writer.ico new file mode 100644 index 0000000..c4e663d Binary files /dev/null and b/packaging/pi-writer.ico differ diff --git a/packaging/pi-writer.png b/packaging/pi-writer.png new file mode 100644 index 0000000..5c4595a Binary files /dev/null and b/packaging/pi-writer.png differ diff --git a/pi_image.py b/pi_image.py new file mode 100644 index 0000000..4e080e1 --- /dev/null +++ b/pi_image.py @@ -0,0 +1,304 @@ +"""Raspberry Pi OS images and first-boot setup for the DSP Control SD card writer. + +The current Raspberry Pi OS Lite images are configured with cloud-init: files in the FAT boot +partition (user-data, network-config, meta-data) plus a NoCloud entry in cmdline.txt - the same +layout Raspberry Pi Imager writes. Our user-data then installs DSP Control from the boot partition +as a systemd service on port 80, so the Pi needs no internet connection. +""" + +import hashlib +import json +import re +import secrets +import shutil +import time +import urllib.request +from pathlib import Path + +import server + +OS_LIST_URL = "https://downloads.raspberrypi.com/os_list_imagingutility_v4.json" +IMAGE_NAMES = {64: "Raspberry Pi OS Lite (64-bit)", 32: "Raspberry Pi OS Lite (32-bit)"} +APP_FILES = ["server.py", "dsp", "static"] # what gets installed on the Pi +USER_AGENT = "DSP-Control-Pi-Writer/1.0" + +# Pi models offered in the writer: (name, description, os bits) +MODELS = [ + ("Raspberry Pi 5", "Pi 5, Pi 500, CM5", 64), + ("Raspberry Pi 4", "Pi 4 B, Pi 400, CM4", 64), + ("Raspberry Pi 3", "Pi 3 A+/B/B+, CM3", 64), + ("Raspberry Pi Zero 2 W", "Zero 2 W", 64), + ("Raspberry Pi 2", "Pi 2 B", 32), + ("Raspberry Pi 1", "Pi 1 A/A+/B/B+", 32), + ("Raspberry Pi Zero", "Zero, Zero W, Zero WH", 32), +] + + +# ------------------------------------------------------------------ OS list / download + +def fetch_os_list() -> dict: + req = urllib.request.Request(OS_LIST_URL, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(req, timeout=30) as r: + return json.loads(r.read()) + + +def find_image(os_list: dict, bits: int) -> dict: + """The Raspberry Pi OS Lite entry for 32 or 64 bit.""" + want = IMAGE_NAMES[bits] + + def walk(items): + for it in items: + if it.get("name") == want and it.get("url"): + return it + found = walk(it.get("subitems") or []) + if found: + return found + return None + + img = walk(os_list.get("os_list", [])) + if not img: + raise RuntimeError(f"„{want}“ nicht in der Raspberry-Pi-Liste gefunden") + if img.get("init_format") not in ("cloudinit", "cloudinit-rpi"): + raise RuntimeError(f"Unbekanntes Einrichtungsformat „{img.get('init_format')}“ – Writer aktualisieren") + return img + + +def download(img: dict, cache_dir: Path, progress) -> Path: + """Download (or reuse) the compressed image and check its SHA-256. progress(done, total).""" + cache_dir.mkdir(parents=True, exist_ok=True) + name = img["url"].rsplit("/", 1)[-1] + dest = cache_dir / name + want = (img.get("image_download_sha256") or "").lower() + if dest.exists() and want and sha256_file(dest) == want: + return dest + for old in cache_dir.glob("*.img.xz"): # keep only the current image + old.unlink(missing_ok=True) + tmp = dest.with_suffix(dest.suffix + ".part") + req = urllib.request.Request(img["url"], headers={"User-Agent": USER_AGENT}) + h = hashlib.sha256() + with urllib.request.urlopen(req, timeout=60) as r, open(tmp, "wb") as f: + total = int(r.headers.get("Content-Length") or img.get("image_download_size") or 0) + done = 0 + while chunk := r.read(1 << 20): + f.write(chunk) + h.update(chunk) + done += len(chunk) + progress(done, total) + if want and h.hexdigest() != want: + tmp.unlink(missing_ok=True) + raise RuntimeError("Download beschädigt (Prüfsumme stimmt nicht) – bitte nochmal versuchen") + tmp.replace(dest) + return dest + + +def sha256_file(path: Path) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + while chunk := f.read(1 << 20): + h.update(chunk) + return h.hexdigest() + + +# ------------------------------------------------------------------ password hash + +_ITOA = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + + +def sha512_crypt(password: str, salt: str | None = None, rounds: int = 5000) -> str: + """glibc SHA-512 crypt ("$6$..."), accepted by Linux login/PAM. Python has no crypt module on Windows.""" + if salt is None: + salt = "".join(secrets.choice(_ITOA) for _ in range(16)) + p, s = password.encode(), salt.encode()[:16] + rep = lambda block, n: (block * (n // len(block) + 1))[:n] + b = hashlib.sha512(p + s + p).digest() + a = hashlib.sha512(p + s + rep(b, len(p))) + i = len(p) + while i: + a.update(b if i & 1 else p) + i >>= 1 + c = a.digest() + pp = rep(hashlib.sha512(p * len(p)).digest(), len(p)) + ss = rep(hashlib.sha512(s * (16 + c[0])).digest(), len(s)) + for r in range(rounds): + d = hashlib.sha512(pp if r & 1 else c) + if r % 3: + d.update(ss) + if r % 7: + d.update(pp) + d.update(c if r & 1 else pp) + c = d.digest() + out = [] + + def b64(v, n): + for _ in range(n): + out.append(_ITOA[v & 63]) + v >>= 6 + + for x, y, z in ((0, 21, 42), (22, 43, 1), (44, 2, 23), (3, 24, 45), (25, 46, 4), (47, 5, 26), (6, 27, 48), + (28, 49, 7), (50, 8, 29), (9, 30, 51), (31, 52, 10), (53, 11, 32), (12, 33, 54), (34, 55, 13), + (56, 14, 35), (15, 36, 57), (37, 58, 16), (59, 17, 38), (18, 39, 60), (40, 61, 19), (62, 20, 41)): + b64(c[x] << 16 | c[y] << 8 | c[z], 4) + b64(c[63], 2) + return "$6$" + ("" if rounds == 5000 else f"rounds={rounds}$") + s.decode() + "$" + "".join(out) + + +# ------------------------------------------------------------------ first-boot files + +def yq(v: str) -> str: + """YAML double-quoted scalar.""" + return '"' + str(v).replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\r", "") + '"' + + +def validate(cfg: dict) -> list[str]: + errs = [] + if not re.fullmatch(r"[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?", cfg["hostname"]): + errs.append("Hostname: nur Kleinbuchstaben, Ziffern und „-“") + if not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", cfg["user"]) or cfg["user"] in ("root", "dspctl"): + errs.append("Benutzername: Kleinbuchstaben/Ziffern, nicht „root“") + if len(cfg["password"]) < 4: + errs.append("Passwort: mindestens 4 Zeichen") + if cfg["ssid"] and cfg["wifi_password"] and not 8 <= len(cfg["wifi_password"]) <= 63: + errs.append("WLAN-Passwort: 8 bis 63 Zeichen (leer = offenes WLAN)") + if cfg["ssid"] and not re.fullmatch(r"[A-Za-z]{2}", cfg["country"]): + errs.append("WLAN-Land: zweistelliger Code, z. B. AT") + if not re.fullmatch(r"\d{4}", cfg["pin"]): + errs.append("PIN: 4 Ziffern") + for k in ("dsp204", "dsp408"): + if cfg.get(k) and not re.fullmatch(r"\d{1,3}(\.\d{1,3}){3}", cfg[k]): + errs.append(f"IP-Adresse {k[3:]}: ungültig") + return errs + + +def user_data(cfg: dict) -> str: + lines = [ + "#cloud-config", + "manage_resolv_conf: false", + "", + f"hostname: {yq(cfg['hostname'])}", + "manage_etc_hosts: true", + f"timezone: {yq(cfg.get('timezone') or 'Europe/Vienna')}", + "", + "user:", + f" name: {yq(cfg['user'])}", + " shell: /bin/bash", + " lock_passwd: false", + f" passwd: {yq(sha512_crypt(cfg['password']))}", + " sudo: null", + "", + ] + if cfg.get("ssh"): + lines += ["ssh_pwauth: true", ""] + lines.append("runcmd:") + if cfg.get("ssh"): + lines.append(" - [ systemctl, enable, --now, ssh ]") + if not cfg["ssid"] and cfg.get("country"): + lines.append(" - [ rfkill, unblock, wifi ]") + lines.append(" - [ sh, /boot/firmware/dsp-control/install.sh ]") + return "\n".join(lines) + "\n" + + +def network_config(cfg: dict) -> str | None: + if not cfg["ssid"]: + return None # Ethernet works by default + lines = [ + "network:", + " version: 2", + " ethernets:", + " eth0:", + " dhcp4: true", + " dhcp6: true", + " optional: true", + " wifis:", + " wlan0:", + " dhcp4: true", + f" regulatory-domain: {yq(cfg['country'].upper())}", + " access-points:", + f" {yq(cfg['ssid'])}:", + ] + if cfg["wifi_password"]: + lines.append(f" password: {yq(cfg['wifi_password'])}") + else: + lines += [" auth:", " key-management: none"] + lines.append(" optional: true") + return "\n".join(lines) + "\n" + + +INSTALL_SH = """#!/bin/sh +# DSP Control first-boot install (run once by cloud-init) +set -e +SRC=/boot/firmware/dsp-control +id dspctl >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin dspctl +mkdir -p /opt/dsp-control +cp -r "$SRC/app/." /opt/dsp-control/ +install -d -o dspctl -g dspctl -m 700 /var/lib/dsp-control +if [ -f "$SRC/config.json" ]; then + [ -f /var/lib/dsp-control/config.json ] || install -o dspctl -g dspctl -m 600 "$SRC/config.json" /var/lib/dsp-control/config.json + rm -f "$SRC/config.json" +fi +# DSPs on USB (HID, VID 0168 / PID 0821): let the service user open them +echo 'SUBSYSTEM=="hidraw", ATTRS{idVendor}=="0168", ATTRS{idProduct}=="0821", MODE="0666"' > /etc/udev/rules.d/60-dsp-control.rules +udevadm control --reload-rules || true +udevadm trigger --subsystem-match=hidraw || true +install -m 644 "$SRC/dsp-control.service" /etc/systemd/system/dsp-control.service +systemctl daemon-reload +systemctl enable --now dsp-control.service +""" + +SERVICE = """[Unit] +Description=DSP Control WebUI for t.racks DSP 204/408 +After=network-online.target +Wants=network-online.target + +[Service] +User=dspctl +ExecStart=/usr/bin/python3 /opt/dsp-control/server.py --port 80 --config /var/lib/dsp-control/config.json +AmbientCapabilities=CAP_NET_BIND_SERVICE +Restart=always +RestartSec=3 + +[Install] +WantedBy=multi-user.target +""" + + +def initial_config(cfg: dict) -> dict: + salt = secrets.token_hex(16) + devices = [] + for key, name, model in (("dsp204", "DSP 204", "204"), ("dsp408", "DSP 408", "408")): + if cfg.get(key): + devices.append({"id": key, "name": name, "host": cfg[key], "port": 9761, "model": model, + "addr": 1, "autoconnect": True}) + return {"devices": devices, "auth": {"salt": salt, "hash": server.hash_pin(cfg["pin"], salt)}, "sessions": {}} + + +def write_boot_files(boot: Path, cfg: dict, app_root: Path): + """Put the first-boot setup and the DSP Control files onto the mounted boot partition.""" + if not (boot / "cmdline.txt").exists(): + raise RuntimeError(f"{boot} ist keine Raspberry-Pi-Bootpartition (cmdline.txt fehlt)") + target = boot / "dsp-control" + if target.exists(): + shutil.rmtree(target) + (target / "app").mkdir(parents=True) + for name in APP_FILES: + src = app_root / name + if src.is_dir(): + shutil.copytree(src, target / "app" / name, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + else: + shutil.copy2(src, target / "app" / name) + lf = lambda p, text: p.write_text(text, encoding="utf-8", newline="\n") + lf(target / "install.sh", INSTALL_SH) + lf(target / "dsp-control.service", SERVICE) + lf(target / "config.json", json.dumps(initial_config(cfg), indent=2)) + + instance = f"dsp-control-{int(time.time() * 1000)}" + lf(boot / "meta-data", f"instance-id: {instance}\n") + lf(boot / "user-data", user_data(cfg)) + net = network_config(cfg) + if net: + lf(boot / "network-config", net) + cmdline = (boot / "cmdline.txt").read_text(encoding="utf-8").strip() + cmdline = re.sub(r"\s*ds=nocloud;i=\S+", "", cmdline) + cmdline += f" ds=nocloud;i={instance}" + if not cfg["ssid"] and cfg.get("country") and "cfg80211.ieee80211_regdom" not in cmdline: + cmdline += f" cfg80211.ieee80211_regdom={cfg['country'].upper()}" + lf(boot / "cmdline.txt", cmdline + "\n") diff --git a/pi_writer.py b/pi_writer.py new file mode 100644 index 0000000..49582c4 --- /dev/null +++ b/pi_writer.py @@ -0,0 +1,262 @@ +"""DSP Control Pi Writer: prepares a bootable SD card with Raspberry Pi OS Lite + DSP Control. + +After the first boot (2-5 minutes) the WebUI is at http://.local - no monitor, +keyboard or internet needed on the Pi. + +Build: pyinstaller packaging/pi-writer.spec +""" + +import json +import os +import queue +import sys +import threading +import tkinter as tk +import traceback +from pathlib import Path +from tkinter import messagebox, ttk + +import pi_image +import win_disk + +APP = "DSP Control Pi Writer" +ROOT = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)) # bundled app files +SETTINGS = Path(os.environ.get("APPDATA") or Path.home()) / "DSP Control" / "pi-writer.json" +CACHE = Path(os.environ.get("LOCALAPPDATA") or Path.home()) / "DSP Control" / "pi-images" +REMEMBER = ("model", "hostname", "ssid", "country", "user", "ssh", "dsp204", "dsp408", "verify") + + +class Writer(tk.Tk): + def __init__(self): + super().__init__() + self.title(APP) + self.minsize(560, 640) + self.events: queue.Queue = queue.Queue() + self.busy = False + self.disks: list[dict] = [] + saved = self.load_settings() + + self.v = { + "model": tk.StringVar(value=saved.get("model", pi_image.MODELS[1][0])), + "disk": tk.StringVar(), + "hostname": tk.StringVar(value=saved.get("hostname", "dsp-control")), + "ssid": tk.StringVar(value=saved.get("ssid", "")), + "wifi_password": tk.StringVar(), + "country": tk.StringVar(value=saved.get("country", "AT")), + "user": tk.StringVar(value=saved.get("user", "dsp")), + "password": tk.StringVar(), + "ssh": tk.BooleanVar(value=saved.get("ssh", True)), + "pin": tk.StringVar(value="1234"), + "dsp204": tk.StringVar(value=saved.get("dsp204", "")), + "dsp408": tk.StringVar(value=saved.get("dsp408", "")), + "verify": tk.BooleanVar(value=saved.get("verify", True)), + } + self.build() + self.after(100, self.poll) + self.after(200, self.refresh_disks) + + # ------------------------------------------------------------ layout + + def build(self): + pad = {"padx": 12, "pady": 4} + root = ttk.Frame(self, padding=(8, 8)) + root.pack(fill="both", expand=True) + root.columnconfigure(0, weight=1) + + ttk.Label(root, text="Raspberry Pi für DSP Control", font=("Segoe UI", 14, "bold")).grid(sticky="w", **pad) + ttk.Label(root, text="Schreibt Raspberry Pi OS Lite mit vorinstallierter DSP-Control-WebUI auf eine SD-Karte.", + foreground="#555").grid(sticky="w", padx=12) + + def section(title): + f = ttk.LabelFrame(root, text=title, padding=(10, 6)) + f.grid(sticky="ew", padx=12, pady=6) + f.columnconfigure(0, minsize=110) + f.columnconfigure(1, weight=1) + return f + + def row(f, r, label, widget, hint=None): + ttk.Label(f, text=label).grid(row=r, column=0, sticky="w", pady=3, padx=(0, 10)) + widget.grid(row=r, column=1, sticky="ew", pady=3) + if hint: + ttk.Label(f, text=hint, foreground="#777").grid(row=r, column=2, sticky="w", padx=(8, 0)) + + f = section("1 · Gerät") + models = [f"{n} ({d})" for n, d, _ in pi_image.MODELS] + cur = next((m for m in models if m.startswith(self.v["model"].get())), models[1]) + self.model_box = ttk.Combobox(f, values=models, state="readonly") + self.model_box.set(cur) + row(f, 0, "Raspberry Pi", self.model_box) + disk_row = ttk.Frame(f) + disk_row.columnconfigure(0, weight=1) + self.disk_box = ttk.Combobox(disk_row, textvariable=self.v["disk"], state="readonly") + self.disk_box.grid(row=0, column=0, sticky="ew") + ttk.Button(disk_row, text="↻", width=3, command=self.refresh_disks).grid(row=0, column=1, padx=(6, 0)) + row(f, 1, "SD-Karte", disk_row) + + f = section("2 · Netzwerk") + row(f, 0, "Hostname", ttk.Entry(f, textvariable=self.v["hostname"]), ".local") + row(f, 1, "WLAN-Name", ttk.Entry(f, textvariable=self.v["ssid"]), "leer = nur LAN-Kabel") + row(f, 2, "WLAN-Passwort", ttk.Entry(f, textvariable=self.v["wifi_password"], show="•")) + row(f, 3, "Land", ttk.Entry(f, textvariable=self.v["country"], width=6), "z. B. AT, DE, CH") + + f = section("3 · Zugang") + row(f, 0, "Benutzer", ttk.Entry(f, textvariable=self.v["user"]), "für SSH / Wartung") + row(f, 1, "Passwort", ttk.Entry(f, textvariable=self.v["password"], show="•")) + ttk.Checkbutton(f, text="SSH aktivieren", variable=self.v["ssh"]).grid(row=2, column=1, sticky="w", pady=3) + row(f, 3, "WebUI-PIN", ttk.Entry(f, textvariable=self.v["pin"], width=8), "4 Ziffern, später änderbar") + + f = section("4 · DSPs (optional, später in der WebUI änderbar)") + row(f, 0, "IP DSP 204", ttk.Entry(f, textvariable=self.v["dsp204"]), "z. B. 192.168.1.101") + row(f, 1, "IP DSP 408", ttk.Entry(f, textvariable=self.v["dsp408"])) + + bottom = ttk.Frame(root) + bottom.grid(sticky="ew", padx=12, pady=(8, 4)) + bottom.columnconfigure(0, weight=1) + ttk.Checkbutton(bottom, text="Nach dem Schreiben überprüfen", variable=self.v["verify"]).grid(row=0, column=0, sticky="w") + self.go = ttk.Button(bottom, text="SD-Karte schreiben", command=self.start) + self.go.grid(row=0, column=1, sticky="e") + self.bar = ttk.Progressbar(root, maximum=1000) + self.bar.grid(sticky="ew", padx=12, pady=(6, 2)) + self.status = ttk.Label(root, text="Bereit.", foreground="#333") + self.status.grid(sticky="w", padx=12, pady=(0, 8)) + + # ------------------------------------------------------------ settings + + def load_settings(self) -> dict: + try: + return json.loads(SETTINGS.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + def save_settings(self, cfg: dict): + try: + SETTINGS.parent.mkdir(parents=True, exist_ok=True) + SETTINGS.write_text(json.dumps({k: cfg[k] for k in REMEMBER if k in cfg}, indent=2), encoding="utf-8") + except OSError: + pass + + # ------------------------------------------------------------ disks + + def refresh_disks(self): + if self.busy: + return + self.status.config(text="Suche SD-Karten…") + threading.Thread(target=self._list_disks, daemon=True).start() + + def _list_disks(self): + try: + self.events.put(("disks", win_disk.list_disks())) + except Exception as e: # noqa: BLE001 + self.events.put(("disks_err", str(e))) + + # ------------------------------------------------------------ run + + def collect(self) -> dict: + cfg = {k: (v.get().strip() if isinstance(v, tk.StringVar) and k not in ("password", "wifi_password") else v.get()) + for k, v in self.v.items()} + cfg["hostname"] = cfg["hostname"].lower() + cfg["user"] = cfg["user"].lower() + idx = self.model_box.current() + cfg["model"], _, cfg["bits"] = pi_image.MODELS[max(0, idx)] + return cfg + + def start(self): + if self.busy: + return + cfg = self.collect() + errs = pi_image.validate(cfg) + disk = next((d for d in self.disks if win_disk.describe(d) == cfg["disk"]), None) + if not disk: + errs.insert(0, "Bitte eine SD-Karte wählen") + if errs: + messagebox.showerror(APP, "\n".join(errs)) + return + if not messagebox.askyesno(APP, f"ALLE Daten auf\n\n{win_disk.describe(disk)}\n\nwerden gelöscht. Fortfahren?", + icon="warning"): + return + self.save_settings(cfg) + self.busy = True + self.go.config(state="disabled") + threading.Thread(target=self.job, args=(cfg, disk), daemon=True).start() + + def job(self, cfg: dict, disk: dict): + ev = self.events.put + try: + ev(("status", "Lade Raspberry-Pi-OS-Liste…", None)) + img = pi_image.find_image(pi_image.fetch_os_list(), cfg["bits"]) + ev(("status", f"{img['name']} vom {img.get('release_date', '?')}", None)) + path = pi_image.download(img, CACHE, lambda d, t: ev(("progress", f"Download {d / 1e6:.0f} / {t / 1e6:.0f} MB", d, t))) + phases = {"write": "Schreibe", "verify": "Überprüfe"} + win_disk.write_image(disk["Number"], path, int(img.get("extract_size") or 0), + lambda ph, d, t: ev(("progress", f"{phases[ph]} {d / 1e9:.2f} / {t / 1e9:.2f} GB", d, t)), + verify=cfg["verify"]) + ev(("status", "Richte DSP Control ein…", None)) + boot = win_disk.mount_boot_partition(disk["Number"]) + pi_image.write_boot_files(boot, cfg, ROOT) + win_disk.eject(boot) + ev(("done", cfg)) + except Exception as e: # noqa: BLE001 - every failure is shown to the user + traceback.print_exc() + ev(("error", str(e))) + + def poll(self): + try: + while True: + kind, *a = self.events.get_nowait() + if kind == "disks": + self.disks = a[0] + names = [win_disk.describe(d) for d in self.disks] + self.disk_box.config(values=names) + if self.v["disk"].get() not in names: + self.v["disk"].set(names[0] if len(names) == 1 else "") + self.status.config(text=f"{len(names)} SD-Karte(n) gefunden." if names + else "Keine SD-Karte gefunden – einstecken und ↻ drücken.") + elif kind == "disks_err": + self.status.config(text="Fehler beim Suchen: " + a[0]) + elif kind == "status": + self.status.config(text=a[0]) + self.bar.config(mode="indeterminate") + self.bar.start(15) + elif kind == "progress": + text, done, total = a + self.bar.stop() + self.bar.config(mode="determinate", value=1000 * done / total if total else 0) + self.status.config(text=text) + elif kind in ("done", "error"): + self.busy = False + self.go.config(state="normal") + self.bar.stop() + self.bar.config(mode="determinate", value=1000 if kind == "done" else 0) + if kind == "done": + cfg = a[0] + self.status.config(text="Fertig.") + messagebox.showinfo(APP, "Fertig! Die SD-Karte kann entnommen werden.\n\n" + "Karte in den Raspberry Pi stecken, Netzwerk (LAN oder WLAN) und Strom anschließen. " + "Der erste Start dauert 2–5 Minuten.\n\n" + f"Dann im Browser öffnen: http://{cfg['hostname']}.local\n" + f"PIN: {cfg['pin']}") + else: + self.status.config(text="Fehler: " + a[0]) + messagebox.showerror(APP, a[0]) + self.refresh_disks() + except queue.Empty: + pass + self.after(100, self.poll) + + +def main(): + if sys.platform == "win32" and not win_disk.is_admin(): + if win_disk.relaunch_as_admin(): + return + messagebox.showerror(APP, "Zum Beschreiben von SD-Karten werden Administratorrechte benötigt.") + return + try: + import ctypes + ctypes.windll.shcore.SetProcessDpiAwareness(1) # sharp text on high-DPI screens + except (AttributeError, OSError): + pass + Writer().mainloop() + + +if __name__ == "__main__": + main() diff --git a/server.py b/server.py new file mode 100644 index 0000000..b474e14 --- /dev/null +++ b/server.py @@ -0,0 +1,646 @@ +"""DSP Control - web server for t.racks DSP 204 / DSP 408. + +Usage: python server.py [--host 0.0.0.0] [--port 8080] [--config config.json] +Then open http://:8080 on your phone. +""" + +import argparse +import asyncio +import base64 +import errno +import hashlib +import json +import logging +import mimetypes +import re +import secrets +import socket +import sys +import time +import uuid +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +from dsp import preset, usbhid +from dsp.device import Device + +ROOT = Path(__file__).resolve().parent +STATIC = (ROOT / "static").resolve() # resolved: in the macOS .app bundle it is a symlink +log = logging.getLogger("server") + +DEFAULT_PIN = "1234" +SESSION_TTL = 30 * 24 * 3600 # stay logged in for 30 days +MAX_SESSIONS = 50 +COOKIE = "dspsess" +CONFIG_FORMAT = "dsp-control-config" +MAX_UNDO = 20 # automatic backups kept per DSP before each import + + +def _num(v, lo: float, hi: float, default: float = 0.0) -> float: + try: + v = float(v) + except (TypeError, ValueError): + return default + return min(hi, max(lo, v)) if v == v else default + + +def local_ips() -> list[str]: + """IPv4 addresses other devices on the LAN can reach this computer at.""" + ips = [] + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("192.0.2.1", 9)) # no packet is sent; just picks the outgoing interface + ips.append(s.getsockname()[0]) + except OSError: + pass + try: + for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET): + ip = info[4][0] + if ip not in ips and not ip.startswith(("127.", "169.254.")): + ips.append(ip) + except OSError: + pass + return ips + + +def clean_limiter(data: dict) -> dict: + """Validate the limiter calculator data (amplifier profiles + output assignments).""" + amps = [] + for a in (data.get("amps") or [])[:100]: + amps.append({ + "id": re.sub(r"[^\w-]", "", str(a.get("id") or uuid.uuid4().hex[:8]))[:16] or uuid.uuid4().hex[:8], + "name": str(a.get("name") or "Amplifier")[:40], + "mode": "gain" if a.get("mode") == "gain" else "sens", + "sens": _num(a.get("sens"), 0.05, 20, 1.4), + "gain": _num(a.get("gain"), 0, 60, 32), + "p8": _num(a.get("p8"), 0, 100000), "p4": _num(a.get("p4"), 0, 100000), "p2": _num(a.get("p2"), 0, 100000), + }) + ids = {a["id"] for a in amps} + assign = {} + for k, v in (data.get("assign") or {}).items(): + if re.fullmatch(r"[\w-]+:\d{1,2}", str(k)) and isinstance(v, dict) and v.get("amp") in ids: + assign[k] = {"amp": v["amp"], "ohm": _num(v.get("ohm"), 1, 32, 8), + "spk": _num(v.get("spk"), 0, 100000)} + ref = {str(k)[:32]: _num(v, -20, 30) for k, v in (data.get("ref") or {}).items()} + return {"amps": amps, "assign": assign, "ref": ref} + + +def hash_pin(pin: str, salt: str) -> str: + return hashlib.pbkdf2_hmac("sha256", pin.encode(), bytes.fromhex(salt), 100_000).hex() + + +def token_id(token: str) -> str: + """Sessions are stored hashed so config.json never contains a usable cookie.""" + return hashlib.sha256(token.encode()).hexdigest() + + +class App: + def __init__(self, config_path: Path): + self.config_path = config_path + self.devices: dict[str, Device] = {} + self.clients: set[asyncio.Queue] = set() + self.auth: dict = {} + self.sessions: dict[str, float] = {} # token hash -> expiry + self.failures: dict[str, tuple[int, float]] = {} # ip -> (failed attempts, locked until) + self.limiter: dict = clean_limiter({}) + # desktop app: its own window logs in with a one-time token, other devices need the PIN + self.app_token: str | None = None + self.app_sessions: set[str] = set() + self.remote = {"enabled": False, "port": 8080} + self.remote_server: asyncio.Server | None = None + self.remote_writers: set[asyncio.StreamWriter] = set() + self.remote_error = "" + self.locked = False # desktop app window read-only until unlocked with the PIN + self.lang = "" # UI language chosen in the desktop app ("" = not chosen yet, English) + + # ------------------------------------------------------------ config + + def load(self): + if self.config_path.exists(): + cfg = json.loads(self.config_path.read_text(encoding="utf-8")) + else: + cfg = {"devices": [ + {"id": "dsp204", "name": "DSP 204", "host": "192.168.1.101", "model": "204", "autoconnect": False}, + {"id": "dsp408", "name": "DSP 408", "host": "192.168.1.102", "model": "408", "autoconnect": False}, + ]} + now = time.time() + self.sessions = {k: v for k, v in cfg.get("sessions", {}).items() if v > now} + self.locked = bool(cfg.get("locked")) + self.lang = cfg.get("lang") if cfg.get("lang") in ("en", "de") else "" + self.apply_config(cfg) + + def apply_config(self, cfg: dict): + """Devices, PIN, limiter data and remote settings from a config dict (file or backup).""" + auth = cfg.get("auth") or {} + if re.fullmatch(r"[0-9a-f]{32}", str(auth.get("salt", ""))) and re.fullmatch(r"[0-9a-f]{64}", str(auth.get("hash", ""))): + self.auth = {"salt": auth["salt"], "hash": auth["hash"]} + elif not self.auth: # first start (a backup without PIN keeps the current one) + self.set_pin(DEFAULT_PIN, save=False) + self.limiter = clean_limiter(cfg.get("limiter") or {}) + r = cfg.get("remote") or {} + self.remote = {"enabled": bool(r.get("enabled")), "port": int(_num(r.get("port"), 1, 65535, 8080))} + for d in cfg.get("devices", [])[:20]: + if isinstance(d, dict): + self.add_device(d, save=False) + self.save() + + # ------------------------------------------------------------ backups + + def export_config(self) -> dict: + """App backup: devices, PIN (hashed), amplifiers/limiter data, remote access - no logins.""" + return {"format": CONFIG_FORMAT, "version": 1, "exported": time.strftime("%Y-%m-%dT%H:%M:%S"), + "devices": [d.config() for d in self.devices.values()], "auth": self.auth, + "limiter": self.limiter, "remote": self.remote} + + async def restore_config(self, doc: dict, session: str): + if not isinstance(doc, dict) or doc.get("format") != CONFIG_FORMAT: + raise ValueError("Not a DSP Control settings backup") + for dev in list(self.devices.values()): + await dev.stop() + del self.devices[dev.id] + self.broadcast({"type": "removed", "device": dev.id}) + old_auth = self.auth + self.apply_config(doc) + if self.auth != old_auth: # new PIN: other devices have to log in again + self.sessions = {k: v for k, v in self.sessions.items() if k == session or k in self.app_sessions} + self.save() + for dev in self.devices.values(): + self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) + self.broadcast({"type": "limiter", "data": self.limiter}) + if self.app_token: # desktop app: (re)start or stop the LAN listener as restored + await self.start_remote() + + @property + def undo_dir(self) -> Path: + return self.config_path.parent / "backups" + + def undo_files(self, dev_id: str) -> list[Path]: + return sorted(self.undo_dir.glob(f"{dev_id}-*.json"), reverse=True) + + async def import_preset(self, dev: Device, body: dict) -> dict: + if dev.status != "online" or not dev.state: + raise RuntimeError("DSP is not connected") + raw = base64.b64decode(body["raw"]) if body.get("raw") else None + state = preset.read_file(dev.model_name, dev.model, dev.state, doc=body.get("doc"), raw=raw) + # safety copy of the current state first, so the import can be undone + current = await dev.export_preset() + self.undo_dir.mkdir(exist_ok=True) + stamp = time.strftime("%Y%m%d-%H%M%S") + (self.undo_dir / f"{dev.id}-{stamp}.json").write_text(json.dumps(current), encoding="utf-8") + for old in self.undo_files(dev.id)[MAX_UNDO:]: + old.unlink(missing_ok=True) + diffs = await dev.import_preset(state) + return {"ok": not diffs, "differences": diffs[:20], "name": state.get("preset_name", "")} + + async def undo_import(self, dev: Device) -> dict: + files = self.undo_files(dev.id) + if not files: + raise RuntimeError("No backup available") + doc = json.loads(files[0].read_text(encoding="utf-8")) + state = preset.read_file(dev.model_name, dev.model, dev.state, doc=doc) + diffs = await dev.import_preset(state) + files[0].unlink() + return {"ok": not diffs, "differences": diffs[:20]} + + def save(self): + sessions = {k: v for k, v in self.sessions.items() if k not in self.app_sessions} + cfg = {"devices": [d.config() for d in self.devices.values()], "auth": self.auth, + "sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked} + if self.lang: + cfg["lang"] = self.lang + self.config_path.write_text(json.dumps(cfg, indent=2), encoding="utf-8") + + def add_device(self, d: dict, save=True) -> Device: + dev_id = d.get("id") or uuid.uuid4().hex[:8] + usb = d.get("transport") == "usb" + dev = Device(dev_id, d.get("name") or d.get("host") or "DSP (USB)", str(d.get("host") or ""), + int(d.get("port", 9761)), str(d.get("model", "auto")), int(d.get("addr", 1)), + bool(d.get("autoconnect", True)), on_event=self.broadcast, + transport="usb" if usb else "tcp", usb=str(d.get("usb") or "")) + self.devices[dev_id] = dev + if dev.autoconnect: + dev.start() + if save: + self.save() + return dev + + # ------------------------------------------------------------ auth + + def set_pin(self, pin: str, save=True): + salt = secrets.token_hex(16) + self.auth = {"salt": salt, "hash": hash_pin(pin, salt)} + if save: + self.save() + + def check_pin(self, pin: str) -> bool: + return secrets.compare_digest(hash_pin(str(pin), self.auth["salt"]), self.auth["hash"]) + + def session_of(self, headers: dict) -> str | None: + """Hashed session id of a valid login cookie, else None.""" + for part in headers.get("cookie", "").split(";"): + k, _, v = part.strip().partition("=") + if k == COOKIE and v: + tid = token_id(v) + if self.sessions.get(tid, 0) > time.time(): + return tid + return None + + def new_session(self) -> str: + token = secrets.token_urlsafe(32) + self.sessions[token_id(token)] = time.time() + SESSION_TTL + if len(self.sessions) > MAX_SESSIONS: + for k in sorted(self.sessions, key=self.sessions.get)[: len(self.sessions) - MAX_SESSIONS]: + del self.sessions[k] + self.save() + return token + + @staticmethod + def cookie(token: str, max_age: int) -> str: + return f"Set-Cookie: {COOKIE}={token}; Path=/; Max-Age={max_age}; HttpOnly; SameSite=Strict\r\n" + + async def guarded_pin(self, who: str, pin) -> tuple[int, dict]: + """Check a PIN with brute-force protection per client: 200 if right, else 401/429.""" + count, until = self.failures.get(who, (0, 0.0)) + if until > time.time(): + return 429, {"error": "locked", "retry": round(until - time.time())} + if self.check_pin(str(pin or "")): + self.failures.pop(who, None) + return 200, {"ok": True} + await asyncio.sleep(0.4) # slow down guessing + count += 1 + # 5 tries, then a 30 s lock that doubles with every further 5 failures (max 15 min) + lock = min(900, 30 * 2 ** (count // 5 - 1)) if count % 5 == 0 else 0 + self.failures[who] = (count, time.time() + lock) + return 401, {"error": "wrong pin", "retry": lock, "left": 5 - count % 5} + + async def login(self, ip: str, body: dict) -> tuple[int, dict, str]: + status, result = await self.guarded_pin(ip, body.get("pin")) + return status, result, self.cookie(self.new_session(), SESSION_TTL) if status == 200 else "" + + async def change_pin(self, session: str, body: dict) -> tuple[int, dict]: + new = str(body.get("new", "")) + # the desktop app window belongs to the owner of this computer: no current PIN needed (forgotten PIN) + if session not in self.app_sessions and not self.check_pin(str(body.get("current", ""))): + return 400, {"error": "Current PIN is wrong"} + if not re.fullmatch(r"\d{4}", new): + return 400, {"error": "The PIN must be 4 digits"} + self.set_pin(new, save=False) + # log out all other devices (the app window stays) + self.sessions = {k: v for k, v in self.sessions.items() if k == session or k in self.app_sessions} + self.save() + return 200, {"ok": True} + + # ------------------------------------------------------------ desktop app + + def app_login(self, token: str) -> str | None: + """Session cookie value for the app window, if the one-time token matches.""" + if not self.app_token or not secrets.compare_digest(token, self.app_token): + return None + cookie = secrets.token_urlsafe(32) + self.sessions[token_id(cookie)] = time.time() + SESSION_TTL + self.app_sessions.add(token_id(cookie)) + return cookie + + def set_locked(self, locked: bool): + self.locked = locked + self.save() + self.broadcast({"type": "lock", "locked": locked}) + + @staticmethod + def allowed_while_locked(method: str, path: str) -> bool: + """What the locked app window may still do: look at everything, export presets.""" + if path in ("/api/unlock", "/api/events", "/api/lang"): + return True + if method == "GET": + return path != "/api/backup" # holds the PIN hash + return method == "POST" and re.fullmatch(r"/api/devices/[\w-]+/(export|backups)", path) is not None + + def remote_info(self) -> dict: + return {**self.remote, "running": self.remote_server is not None, "error": self.remote_error, + "platform": sys.platform, + # only the main address: the others are usually virtual adapters (WSL, Hyper-V, VPN) + "urls": [f"http://{ip}:{self.remote['port']}" for ip in local_ips()[:1]]} + + async def start_remote(self): + """(Re)start the LAN listener for other devices according to self.remote.""" + self.stop_remote() + self.remote_error = "" + if not self.remote["enabled"]: + return + try: + self.remote_server = await asyncio.start_server( + lambda r, w: self.handle(r, w, remote=True), "0.0.0.0", self.remote["port"]) + log.info("Remote access on port %d", self.remote["port"]) + except OSError as e: + in_use = e.errno in (errno.EADDRINUSE, 98, 10048) or getattr(e, "winerror", None) == 10048 + self.remote_error = (f"Port {self.remote['port']} is already in use – please choose another port" if in_use + else f"Port {self.remote['port']} is not available ({e.strerror or e})") + log.warning("Remote access failed: %s", e) + + def stop_remote(self): + if self.remote_server: + self.remote_server.close() + self.remote_server = None + for w in list(self.remote_writers): # also end open connections (live event streams) + w.close() + self.remote_writers.clear() + + async def set_remote(self, body: dict) -> dict: + if "enabled" in body: + self.remote["enabled"] = bool(body["enabled"]) + if "port" in body: + self.remote["port"] = int(_num(body["port"], 1, 65535, 8080)) + self.save() + await self.start_remote() + return self.remote_info() + + async def shutdown(self): + self.stop_remote() + for d in self.devices.values(): + await d.stop() + + # ------------------------------------------------------------ events + + def broadcast(self, ev: dict): + msg = json.dumps(ev, separators=(",", ":")) + for q in list(self.clients): + if ev["type"] == "meters" and q.qsize() > 50: + continue # slow client: drop meter frames, never state changes + q.put_nowait(msg) + + # ------------------------------------------------------------ API + + async def api(self, method: str, path: str, body: dict): + if path == "/api/devices" and method == "GET": + return [d.snapshot() for d in self.devices.values()] + if path == "/api/devices" and method == "POST": + return self.add_device(body).snapshot() + if path == "/api/usb" and method == "GET": + return await asyncio.to_thread(usbhid.list_devices) + if path == "/api/limiter" and method == "GET": + return self.limiter + if path == "/api/limiter" and method == "PUT": + self.limiter = clean_limiter(body) + self.save() + self.broadcast({"type": "limiter", "data": self.limiter}) + return self.limiter + m = re.fullmatch(r"/api/devices/([\w-]+)(?:/(\w+))?(?:/(\w+))?", path) + if not m or m.group(1) not in self.devices: + raise KeyError(path) + dev = self.devices[m.group(1)] + action = "/".join(g for g in m.groups()[1:] if g) + if method == "DELETE" and not action: + await dev.stop() + del self.devices[dev.id] + self.save() + self.broadcast({"type": "removed", "device": dev.id}) + return {"ok": True} + if method == "PUT" and not action: + was_running = dev._want_connected + await dev.stop() + for k in ("name", "host", "model", "usb"): + if k in body: + setattr(dev, "model_key" if k == "model" else k, str(body[k])) + if "transport" in body: + dev.transport = "usb" if body["transport"] == "usb" else "tcp" + for k in ("port", "addr"): + if k in body: + setattr(dev, k, int(body[k])) + if "autoconnect" in body: + dev.autoconnect = bool(body["autoconnect"]) + self.save() + if was_running: + dev.start() + self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) + return dev.snapshot() + if method != "POST": + raise KeyError(path) + if action == "connect": + dev.start() + return {"ok": True} + if action == "disconnect": + await dev.stop() + return {"ok": True} + if action == "set": + dev.set_param(body["kind"], int(body["idx"]), body["param"], body["value"]) + return {"ok": True} + if action == "preset/recall": + await dev.recall_preset(int(body["index"])) + return {"ok": True} + if action == "preset/store": + await dev.store_preset(int(body["index"]), str(body["name"])) + return {"ok": True} + if action == "export": + return await dev.export_preset() + if action == "import": + return await self.import_preset(dev, body) + if action == "undo": + return await self.undo_import(dev) + if action == "backups": + return [{"file": f.name, "time": f.stat().st_mtime} for f in self.undo_files(dev.id)] + if action == "link": + kind = "in" if body.get("kind") == "in" else "out" + groups = [[int(i) for i in g] for g in body.get("groups") or [] if isinstance(g, list)] + await dev.set_links(kind, groups) + return {"ok": True} + if action == "refresh": + await dev.refresh() + return {"ok": True} + raise KeyError(path) + + # ------------------------------------------------------------ HTTP + + async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, remote=False): + if remote: + self.remote_writers.add(writer) + try: + await self._handle(reader, writer, remote) + finally: + self.remote_writers.discard(writer) + + async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, remote: bool): + try: + head = await reader.readuntil(b"\r\n\r\n") + except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, ConnectionError): + writer.close() + return + lines = head.decode("latin1").split("\r\n") + try: + method, target, _ = lines[0].split(" ", 2) + except ValueError: + writer.close() + return + headers = {k.lower(): v.strip() for k, _, v in (l.partition(":") for l in lines[1:] if l)} + url = urlsplit(target) + path = url.path + body = b"" + if int(headers.get("content-length", 0)): + body = await reader.readexactly(int(headers["content-length"])) + try: + if path == "/app-login" and not remote: + cookie = self.app_login(parse_qs(url.query).get("t", [""])[0]) + if cookie: + await self.respond(writer, 302, b"", "text/plain", + "Location: /\r\n" + self.cookie(cookie, SESSION_TTL)) + else: + await self.respond(writer, 401, b"invalid app token", "text/plain") + return + if path.startswith("/api/"): + try: + data = json.loads(body) if body else {} + except ValueError: + data = {} + session = self.session_of(headers) + if session in self.app_sessions and remote: + session = None # the window's session never counts on the LAN listener + is_app = session in self.app_sessions + if path == "/api/auth": + await self.respond_json(writer, 200, {"authenticated": bool(session), "app": is_app, + "locked": is_app and self.locked, + "lang": self.lang if is_app else ""}) + return + if path == "/api/login" and method == "POST": + ip = (writer.get_extra_info("peername") or ("?",))[0] + status, result, cookie = await self.login(ip, data) + await self.respond_json(writer, status, result, cookie) + return + if path == "/api/logout" and method == "POST": + if self.sessions.pop(session, None): + self.save() + await self.respond_json(writer, 200, {"ok": True}, self.cookie("", 0)) + return + if not session: + await self.respond_json(writer, 401, {"error": "login required"}) + return + if is_app and self.locked and not self.allowed_while_locked(method, path): + await self.respond_json(writer, 423, {"error": "Locked – unlock with the PIN to make changes"}) + return + if path == "/api/lang" and method == "PUT": + if is_app and data.get("lang") in ("en", "de"): + self.lang = data["lang"] + self.save() + await self.respond_json(writer, 200, {"lang": self.lang}) + return + if path in ("/api/lock", "/api/unlock") and method == "POST": + if not is_app: + await self.respond_json(writer, 403, {"error": "desktop app only"}) + elif path == "/api/lock": + self.set_locked(True) + await self.respond_json(writer, 200, {"locked": True}) + else: + status, result = await self.guarded_pin("app-unlock", data.get("pin")) + if status == 200: + self.set_locked(False) + # not 401: the page would take that for "logged out" + await self.respond_json(writer, 400 if status == 401 else status, result) + return + if path == "/api/pin" and method == "POST": + await self.respond_json(writer, *await self.change_pin(session, data)) + return + if path == "/api/backup": + if method == "GET": + await self.respond_json(writer, 200, self.export_config()) + elif not is_app and not self.check_pin(str(data.get("pin", ""))): + # on the LAN only with the PIN: a backup can replace it + await self.respond_json(writer, 400, {"error": "Wrong PIN"}) + else: + try: + await self.restore_config(data.get("doc"), session) + await self.respond_json(writer, 200, {"ok": True}) + except ValueError as e: + await self.respond_json(writer, 400, {"error": str(e)}) + return + if path == "/api/remote": + if not is_app: + await self.respond_json(writer, 403, {"error": "desktop app only"}) + elif method == "PUT": + await self.respond_json(writer, 200, await self.set_remote(data)) + else: + await self.respond_json(writer, 200, self.remote_info()) + return + if path == "/api/events": + await self.sse(writer) + return + if path.startswith("/api/"): + try: + result = await self.api(method, path, json.loads(body) if body else {}) + await self.respond(writer, 200, json.dumps(result).encode(), "application/json") + except KeyError as e: + await self.respond(writer, 404, json.dumps({"error": f"not found: {e}"}).encode(), + "application/json") + except Exception as e: # noqa: BLE001 - report any API error to the client + log.exception("API error") + await self.respond(writer, 400, json.dumps({"error": str(e)}).encode(), "application/json") + return + await self.static(writer, path) + except (ConnectionError, asyncio.CancelledError): + pass + finally: + try: + writer.close() + except Exception: # noqa: BLE001 + pass + + async def respond(self, writer, status: int, data: bytes, ctype: str, extra: str = ""): + reason = {200: "OK", 302: "Found", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", + 404: "Not Found", 423: "Locked", 429: "Too Many Requests"}.get(status, "OK") + writer.write(f"HTTP/1.1 {status} {reason}\r\nContent-Type: {ctype}\r\nContent-Length: {len(data)}\r\n" + f"Cache-Control: no-cache\r\n{extra}Connection: close\r\n\r\n".encode() + data) + await writer.drain() + + async def respond_json(self, writer, status: int, obj, extra: str = ""): + await self.respond(writer, status, json.dumps(obj).encode(), "application/json", extra) + + async def static(self, writer, path: str): + rel = "index.html" if path in ("/", "") else path.lstrip("/") + f = (STATIC / rel).resolve() + if STATIC not in f.parents or not f.is_file(): + await self.respond(writer, 404, b"not found", "text/plain") + return + ctype = mimetypes.guess_type(f.name)[0] or "application/octet-stream" + if ctype.startswith("text/") or ctype.endswith("javascript"): + ctype += "; charset=utf-8" + await self.respond(writer, 200, f.read_bytes(), ctype) + + async def sse(self, writer): + writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n" + b"Connection: keep-alive\r\nX-Accel-Buffering: no\r\n\r\n") + q: asyncio.Queue = asyncio.Queue() + self.clients.add(q) + try: + hello = {"type": "hello", "devices": [d.snapshot() for d in self.devices.values()], "limiter": self.limiter} + writer.write(f"data: {json.dumps(hello)}\n\n".encode()) + await writer.drain() + while True: + try: + msg = await asyncio.wait_for(q.get(), timeout=15) + writer.write(f"data: {msg}\n\n".encode()) + except asyncio.TimeoutError: + writer.write(b": ping\n\n") + await writer.drain() + finally: + self.clients.discard(q) + + +async def main(): + ap = argparse.ArgumentParser(description="Web control for t.racks DSP 204/408") + ap.add_argument("--host", default="0.0.0.0") + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--config", default=str(ROOT / "config.json")) + ap.add_argument("-v", "--verbose", action="store_true") + args = ap.parse_args() + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, + format="%(asctime)s %(name)s %(levelname)s %(message)s") + app = App(Path(args.config)) + app.load() + server = await asyncio.start_server(app.handle, args.host, args.port) + log.info("DSP Control running on http://%s:%d", "localhost" if args.host == "0.0.0.0" else args.host, args.port) + async with server: + await server.serve_forever() + + +if __name__ == "__main__": + try: + asyncio.run(main()) + except KeyboardInterrupt: + pass diff --git a/sim.py b/sim.py new file mode 100644 index 0000000..490faed --- /dev/null +++ b/sim.py @@ -0,0 +1,108 @@ +"""Simulated t.racks DSP for testing without hardware. + +Usage: python sim.py --model 204 --port 9761 + python sim.py --model 408 --port 9762 +""" + +import argparse +import asyncio +import copy +import logging +import math +import time + +from dsp import protocol as P + +log = logging.getLogger("sim") + + +class SimDSP: + def __init__(self, model_key: str): + self.key = model_key + self.model = P.MODELS[model_key] + self.state = P.default_state(self.model) + self.presets = [copy.deepcopy(self.state) if i == 0 else None for i in range(20)] + self.presets[0]["preset_name"] = "Default" + self.pending_name = "" + + def preset_names(self) -> list[str]: + return [p["preset_name"] if p else "" for p in self.presets] + + def handle(self, cmd: int, p: bytes) -> tuple[int, bytes]: + m = self.model + if cmd == P.CMD_DEVICE_INFO: + return cmd, f"DSP{self.key} V010 SIM".encode() + if cmd == P.CMD_PRESET_COUNT: + return cmd, bytes([0, len(self.presets)]) + if cmd == P.CMD_PRESET_NAME: + return cmd, bytes([p[0]]) + self.preset_names()[p[0]].encode("latin1").ljust(14, b" ") + if cmd == P.CMD_CONFIG_REQUEST: + buf = P.build_state_buffer(m, self.state) + n = p[0] + return P.CMD_CONFIG_CHUNK, bytes([n]) + bytes(buf[n * P.CHUNK_SIZE:(n + 1) * P.CHUNK_SIZE]) + if cmd == P.CMD_METER: + t = time.monotonic() + levels = [0.0] * 12 + for i in range(m.n_in): + ch = self.state["inputs"][i] + lv = 0.0 if ch["mute"] else 0.25 * (1 + math.sin(t * (1.3 + i))) * 10 ** (P.gain_to_db(ch["gain"]) / 20) + levels[m.meter_index("in", i)] = lv + flags = 0 + for o in range(m.n_out): + ch = self.state["outputs"][o] + src = sum(levels[m.meter_index("in", i)] for i in range(m.n_in) if ch["matrix"] >> i & 1) + lv = 0.0 if ch["mute"] else min(1.5, src * 10 ** (P.gain_to_db(ch["gain"]) / 20)) + levels[m.meter_index("out", o)] = lv + if lv > 0 and 20 * math.log10(lv) > P.threshold_to_db(ch["limit"]["threshold"]): + flags |= 1 << o + return cmd, P.encode_meters(levels, flags) + if cmd == P.CMD_PRESET_RECALL: + preset = self.presets[p[0] - 1] + if preset: + self.state = copy.deepcopy(preset) + elif cmd == P.CMD_PRESET_STORE_NAME: + self.pending_name = p.decode("latin1").strip() + elif cmd == P.CMD_PRESET_STORE: + self.state["preset_name"] = self.pending_name or f"Preset {p[0]}" + self.presets[p[0] - 1] = copy.deepcopy(self.state) + else: + P.apply_command(m, self.state, cmd, p) + return P.CMD_ACK, b"\x00" + + async def serve(self, reader, writer): + peer = writer.get_extra_info("peername") + log.info("client %s connected", peer) + parser = P.FrameParser() + try: + while data := await reader.read(4096): + for f in parser.feed(data): + if f.cmd != P.CMD_METER: + log.info("rx cmd=0x%02x payload=%s", f.cmd, f.payload.hex(" ")) + cmd, payload = self.handle(f.cmd, f.payload) + writer.write(P.build_frame(cmd, payload, addr=0, src=1)) + await writer.drain() + except ConnectionError: + pass + log.info("client %s disconnected", peer) + writer.close() + + +async def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--model", choices=list(P.MODELS), default="204") + ap.add_argument("--port", type=int, default=P.PORT) + ap.add_argument("--host", default="127.0.0.1") + args = ap.parse_args() + logging.basicConfig(level=logging.INFO, format=f"%(asctime)s sim{args.model} %(message)s") + sim = SimDSP(args.model) + server = await asyncio.start_server(sim.serve, args.host, args.port) + log.info("simulated DSP %s on %s:%d", args.model, args.host, args.port) + async with server: + await server.serve_forever() + + +if __name__ == "__main__": + try: + asyncio.run(main()) + except KeyboardInterrupt: + pass diff --git a/start.bat b/start.bat new file mode 100644 index 0000000..4bc86a1 --- /dev/null +++ b/start.bat @@ -0,0 +1,4 @@ +@echo off +cd /d "%~dp0" +python server.py %* +pause diff --git a/static/app.js b/static/app.js new file mode 100644 index 0000000..a1bdb2c --- /dev/null +++ b/static/app.js @@ -0,0 +1,1729 @@ +"use strict"; + +// ------------------------------------------------------------------ value scales (see PROTOCOL.md) + +const Q_TABLE = [0.4,0.42,0.45,0.47,0.5,0.53,0.56,0.59,0.63,0.67,0.71,0.75,0.79,0.84,0.89,0.94,1.0,1.06,1.12,1.19, + 1.26,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.4,2.5,2.7,2.8,3.0,3.2,3.4,3.6,3.8,4.0,4.2,4.5,4.8,5.0,5.3,5.7,6.0, + 6.3,6.7,7.1,7.6,8.0,8.5,9.0,9.5,10.1,10.7,11.3,12.0,12.7,13.5,14.0,15,16,17,18,19,20,21,23,24,25,27,29,30,32,34, + 36,38,40,43,45,48,51,54,57,60,64,68,72,76,81,85,91,96,102,108,114,121,128]; +const RATIOS = ["1:1.0","1:1.1","1:1.3","1:1.5","1:1.7","1:2.0","1:2.5","1:3.0","1:3.5","1:4.0","1:5.0","1:6.0", + "1:8.0","1:10","1:20","Limit"]; +const PEQ_TYPES = ["Peak","Low Shelf","High Shelf","HPF -6","HPF -12","LPF -6","LPF -12","Allpass 1","Allpass 2"]; +const PEQ_SHORT = ["PK","LS","HS","HP6","HP12","LP6","LP12","AP1","AP2"]; +const SLOPES = ["Bypass","BW -6","BL -6","BW -12","BL -12","LK -12","BW -18","BL -18","BW -24","BL -24","LK -24", + "BW -30","BL -30","BW -36","BL -36","LK -36","BW -42","BL -42","BW -48","BL -48","LK -48"]; +const GEQ_FREQS = ["20","25","31","40","50","63","80","100","125","160","200","250","315","400","500","630","800", + "1k","1.2k","1.6k","2k","2.5k","3.1k","4k","5k","6.3k","8k","10k","12k","16k","20k"]; +const IN_COLORS = ["#38bdf8", "#a78bfa", "#34d399", "#f472b6"]; + +const gainDb = r => r < 80 ? r / 2 - 60 : (r - 280) / 10; +const dbGain = db => Math.max(0, Math.min(400, db < -20 ? Math.round((db + 60) * 2) : Math.round(db * 10 + 280))); +const freqHz = r => 1000 * Math.pow(2, (r - 170) / 30); +const hzFreq = hz => Math.max(0, Math.min(300, Math.round(170 + 30 * Math.log2(Math.max(hz, 1) / 1000)))); +const eqDb = r => (r - 120) / 10; +const sign = v => (v > 0 ? "+" : "") + v.toFixed(1); +const fmtHz = hz => hz >= 1000 ? (hz / 1000).toFixed(hz >= 10000 ? 1 : 2) + " kHz" : hz.toFixed(hz < 100 ? 1 : 0) + " Hz"; +const fmtHzShort = hz => hz >= 1000 ? +(hz / 1000).toFixed(hz >= 10000 ? 0 : 1) + "k" : String(Math.round(hz)); +const nearestQ = q => Q_TABLE.reduce((best, v, i) => Math.abs(v - q) < Math.abs(Q_TABLE[best] - q) ? i : best, 0); +const num = s => parseFloat(String(s).replace(",", ".").replace(/[^0-9.+-]/g, "")); +const clamp = (v, a, b) => Math.max(a, Math.min(b, v)); + +// Parameter specs: raw range, display/parse in user units, optional 0-dB detent ("zero") +const SPEC = { + gain: { min: 0, max: 400, zero: 280, fmt: r => sign(gainDb(r)) + " dB", parse: s => dbGain(num(s)), hint: "-60 … +12 dB" }, + mix: { min: 0, max: 280, zero: 280, fmt: r => sign(gainDb(r)) + " dB", parse: s => Math.min(280, dbGain(num(s))), hint: "-60 … 0 dB" }, + delay: { min: 0, max: 65280, def: 0, fmt: r => (r / 96).toFixed(2) + " ms · " + (r / 96 * 0.343).toFixed(2) + " m", + parse: s => /m\s*$/i.test(s) && !/ms/i.test(s) ? Math.round(num(s) / 0.343 * 96) : Math.round(num(s) * 96), + hint: t("in ms, or metres with “m” (e.g. 2.5m)") }, + freq: { min: 0, max: 300, fmt: r => fmtHz(freqHz(r)), parse: s => hzFreq(/k/i.test(s) ? num(s) * 1000 : num(s)), hint: t("20 Hz … 20 kHz, e.g. 1.2k") }, + eqgain: { min: 0, max: 240, zero: 120, fmt: r => sign(eqDb(r)) + " dB", parse: s => Math.round(num(s) * 10 + 120), hint: "-12 … +12 dB" }, + q: { min: 0, max: 100, fmt: r => "Q " + Q_TABLE[r], parse: s => nearestQ(num(s)), hint: "0.4 … 128" }, + gthresh: { min: 0, max: 180, fmt: r => sign((r - 180) / 2) + " dB", parse: s => Math.round(num(s) * 2 + 180), hint: "-90 … 0 dB" }, + thresh: { min: 0, max: 220, fmt: r => sign((r - 180) / 2) + " dB", parse: s => Math.round(num(s) * 2 + 180), hint: "-90 … +20 dB" }, + attack: { min: 0, max: 998, fmt: r => (r + 1) + " ms", parse: s => Math.round(num(s)) - 1, hint: "1 … 999 ms" }, + release: { min: 9, max: 2999, fmt: r => (r + 1) + " ms", parse: s => Math.round(num(s)) - 1, hint: "10 … 3000 ms" }, + hold: { min: 9, max: 998, fmt: r => (r + 1) + " ms", parse: s => Math.round(num(s)) - 1, hint: "10 … 999 ms" }, + ratio: { min: 0, max: 15, fmt: r => RATIOS[r], parse: s => Math.max(0, RATIOS.findIndex(x => x.endsWith(s))), hint: t("e.g. 4.0") }, + knee: { min: 0, max: 12, fmt: r => r + " dB", parse: s => Math.round(num(s)), hint: "0 … 12 dB" }, +}; +const GAIN_TICKS = [[400, "+12"], [340, "+6"], [280, "0"], [220, "-6"], [160, "-12"], [80, "-20"], [40, "-40"], [0, "-60"]]; + +// ------------------------------------------------------------------ app state + +const store = { + get: k => { try { return localStorage.getItem(k); } catch { return null; } }, + set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* private mode */ } }, +}; +const S = { + devices: {}, order: [], cur: store.get("dsp.cur"), + view: store.get("dsp.view") || "mixer", settings: false, + sel: { kind: "in", idx: 0 }, band: 0, busy: false, dirty: false, + routeOpen: null, es: null, linkSel: { in: [], out: [] }, + lim: { amps: [], assign: {}, ref: {} }, +}; +const $ = sel => document.querySelector(sel); +const main = $("#main"); + +function h(tag, attrs = {}, ...children) { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (v == null || v === false) continue; + if (k.startsWith("on")) el.addEventListener(k.slice(2), v); + else if (k === "class") el.className = v; + else if (k === "style") el.style.cssText = v; + else el.setAttribute(k, v === true ? "" : v); + } + for (const c of children.flat()) if (c != null && c !== false) el.append(c.nodeType ? c : document.createTextNode(c)); + return el; +} +const svgIcon = d => { const s = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + s.setAttribute("viewBox", "0 0 24 24"); s.innerHTML = d; return s; }; +const ICON = { + prev: '', next: '', + edit: '', logout: '', + back: '', + lock: '', + unlock: '', + link: '', +}; + +function toast(msg) { + const el = $("#toast"); + el.textContent = msg; el.hidden = false; + clearTimeout(toast.timer); toast.timer = setTimeout(() => (el.hidden = true), 2500); +} +const buzz = () => { try { navigator.vibrate && navigator.vibrate(8); } catch { /* unsupported */ } }; + +async function api(method, path, body) { + const r = await fetch(path, { method, headers: { "Content-Type": "application/json" }, + body: body ? JSON.stringify(body) : undefined, credentials: "same-origin" }); + const data = await r.json().catch(() => ({})); + if (r.status === 401 && !path.startsWith("/api/login")) { showLogin(); throw new Error(t("Please log in")); } + if (!r.ok) throw new Error(trMsg(data.error || r.statusText)); + return data; +} + +const dev = () => S.devices[S.cur]; +const where = d => d.transport === "usb" ? "USB" : d.host; // connection label +const chans = (d, kind) => d.state[kind === "in" ? "inputs" : "outputs"]; +const chLabel = (kind, i) => kind === "in" ? "In " + String.fromCharCode(65 + i) : "Out " + (i + 1); +// Channel names: the DSP keeps 8 ASCII characters; on top of that a name must fit the mixer strip, +// so wide letters (W, M, @) count more. Every other place showing names is at least as wide. +const NAME_MAX = 8, NAME_PX = 76; +const UMLAUT = { ä: "ae", ö: "oe", ü: "ue", Ä: "Ae", Ö: "Oe", Ü: "Ue", ß: "ss" }; +let nameCtx; +function nameWidth(s) { + if (!nameCtx) { + nameCtx = document.createElement("canvas").getContext("2d"); + const probe = h("span", { class: "nm", style: "position:absolute;visibility:hidden" }); + const head = h("div", { class: "strip-head", style: "position:absolute;visibility:hidden" }, probe); + document.body.append(head); + const cs = getComputedStyle(probe); + nameCtx.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`; + head.remove(); + } + return nameCtx.measureText(s).width; +} +function cleanName(s) { + s = [...s.replace(/[äöüÄÖÜß]/g, c => UMLAUT[c])].filter(c => c >= " " && c <= "~").join("").slice(0, NAME_MAX); + while (s && nameWidth(s) > NAME_PX) s = s.slice(0, -1); + return s; +} + +const chTitle = (d, kind, i) => { const n = chans(d, kind)[i].name; return n ? `${chLabel(kind, i)} · ${n}` : chLabel(kind, i); }; + +// Channel links (see protocol.py): a free channel's mask is its own bit, the first channel of a +// group holds all members' bits, the others 0. The DSP mirrors changes within a group itself. +const LINK_COLORS = ["#f59e0b", "#22d3ee", "#a3e635", "#f472b6"]; +function linkGroups(list) { + const seen = new Set(), groups = []; + list.forEach((ch, i) => { + if (seen.has(i)) return; + const mask = ch.link ?? (1 << i); + const g = list.map((_, j) => j).filter(j => (j === i || mask >> j & 1) && !seen.has(j)); + g.forEach(j => seen.add(j)); + groups.push(g); + }); + return groups; +} +const linkedGroups = (d, kind) => linkGroups(chans(d, kind)).filter(g => g.length > 1); +function linkInfo(d, kind, i) { // {group, color} if the channel is linked, else null + const gs = linkedGroups(d, kind), n = gs.findIndex(g => g.includes(i)); + return n < 0 ? null : { group: gs[n], color: LINK_COLORS[n % LINK_COLORS.length] }; +} +const linkBadge = (d, kind, i) => { + const l = linkInfo(d, kind, i); + return l ? h("span", { class: "lnk", style: `--lc:${l.color}`, title: t("Linked: ") + l.group.map(j => chLabel(kind, j)).join(" + ") }, + svgIcon(ICON.link)) : null; +}; + +function getPath(obj, path) { + return path.split(".").reduce((o, k) => o[Array.isArray(o) ? +k : k], obj); +} +function setPath(obj, path, value) { + const keys = path.split("."); + const last = keys.pop(); + const node = keys.reduce((o, k) => o[Array.isArray(o) ? +k : k], obj); + node[Array.isArray(node) ? +last : last] = value; +} + +// While the user drags something, incoming updates must not rebuild the DOM under their finger. +function beginBusy() { S.busy = true; } +function endBusy() { S.busy = false; if (S.dirty) { S.dirty = false; render(); } } + +// ------------------------------------------------------------------ dialogs (no native prompt/confirm: they are blocked in some webviews) + +function modal({ title, body, actions, onOpen }) { + return new Promise(resolve => { + const root = $("#modal"); + let done = false; + const close = v => { + if (done) return; done = true; + root.hidden = true; root.replaceChildren(); + document.removeEventListener("keydown", onKey, true); + resolve(v); + }; + const primary = actions.find(a => a.primary); + const btns = actions.map(a => h("button", { class: a.cls || (a.primary ? "on" : ""), + onclick: () => { const v = a.value ? a.value() : null; if (v !== undefined) close(v); } }, a.label)); + const onKey = e => { + if (e.key === "Escape") { e.preventDefault(); close(null); } + else if (e.key === "Enter" && primary && e.target.tagName !== "TEXTAREA") { + e.preventDefault(); btns[actions.indexOf(primary)].click(); + } + }; + document.addEventListener("keydown", onKey, true); + root.replaceChildren( + h("div", { class: "backdrop", onclick: () => close(null) }), + h("div", { class: "dialog", role: "dialog", "aria-modal": "true", "aria-label": title }, + h("h2", {}, title), body, h("div", { class: "dlg-actions" }, btns))); + root.hidden = false; + const first = root.querySelector("input, select"); + setTimeout(() => { if (first) { first.focus(); first.select && first.select(); } else if (primary) btns[actions.indexOf(primary)].focus(); onOpen && onOpen(); }, 30); + }); +} + +const askConfirm = (title, text, okLabel = "OK", danger = false) => modal({ + title, body: h("p", { class: "dlg-text" }, text), + actions: [{ label: t("Cancel") }, { label: okLabel, primary: true, cls: danger ? "danger-on" : "on", value: () => true }], +}); + +// ------------------------------------------------------------------ files (desktop app: native dialogs via pywebview) + +const today = () => new Date().toISOString().slice(0, 10); +const fileSafe = s => (s || "").replace(/[^\w\- .]+/g, "").trim().replace(/\s+/g, "_") || "preset"; + +async function saveFile(name, obj) { + const text = JSON.stringify(obj, null, 2); + const papi = window.pywebview && window.pywebview.api; + if (papi && papi.save_file) return papi.save_file(name, text); + const a = h("a", { href: URL.createObjectURL(new Blob([text], { type: "application/json" })), download: name }); + document.body.append(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(a.href), 10000); + return true; +} + +// -> { name, b64, json } (json = parsed content if the file is JSON, else null), or null if cancelled +async function openFile() { + let name, bytes; + const papi = window.pywebview && window.pywebview.api; + if (papi && papi.open_file) { + const f = await papi.open_file(); + if (!f) return null; + name = f.name; bytes = Uint8Array.from(atob(f.data), c => c.charCodeAt(0)); + } else { + const file = await new Promise(resolve => { + const inp = h("input", { type: "file", accept: ".json,.bin,application/json,application/octet-stream", hidden: true }); + inp.addEventListener("change", () => resolve(inp.files[0] || null)); + document.body.append(inp); inp.click(); setTimeout(() => inp.remove(), 60000); + }); + if (!file) return null; + if (file.size > 5e6) throw new Error(t("File is too large")); + name = file.name; bytes = new Uint8Array(await file.arrayBuffer()); + } + let json = null; + try { json = JSON.parse(new TextDecoder().decode(bytes)); } catch { /* binary */ } + let bin = ""; + bytes.forEach(b => (bin += String.fromCharCode(b))); + return { name, b64: btoa(bin), json }; +} + +function askValue(label, spec, raw) { + const input = h("input", { type: "text", value: spec.fmt(raw).replace(/^Q /, "").replace(/ ·.*$/, ""), + autocomplete: "off", spellcheck: "false", enterkeyhint: "done" }); + const quick = spec.zero != null + ? h("button", { class: "chip", onclick: () => { input.value = "0"; input.focus(); } }, "0 dB") : null; + return modal({ + title: label, + body: h("div", {}, h("div", { class: "row" }, input, quick), h("p", { class: "info" }, spec.hint || "")), + actions: [{ label: t("Cancel") }, { label: t("Apply"), primary: true, value: () => { + const s = input.value.trim(); + if (!s || isNaN(num(s))) { input.classList.add("bad"); return undefined; } + return clamp(spec.parse(s), spec.min, spec.max); + } }], + }); +} + +// ------------------------------------------------------------------ sending (throttled per parameter) + +// Controls on screen that can follow a value without re-rendering (linked channels, other devices' +// changes while a fader is held): "dev|kind|idx|param" -> [update functions]. Rebuilt on every render. +const live = new Map(); +function onLive(kind, idx, param, fn) { + const key = `${S.cur}|${kind}|${idx}|${param}`; + live.set(key, [...(live.get(key) || []), fn]); +} +const showLive = (key, v) => (live.get(key) || []).forEach(fn => fn(v)); +const LINK_OWN = ["name", "mix", "matrix", "link"]; // per channel even when linked (see protocol.py) + +const sendTimers = new Map(), sendPending = new Map(), recentlySet = new Map(); +function setParam(kind, idx, param, value) { + const d = dev(); + if (!d || !d.state) return; + setPath(chans(d, kind)[idx], param, value); + const key = `${d.id}|${kind}|${idx}|${param}`; + recentlySet.set(key, Date.now()); + // the DSP applies it to linked channels itself: move them along right away + const li = !LINK_OWN.includes(param.split(".")[0]) && linkInfo(d, kind, idx); + if (li) for (const j of li.group) if (j !== idx) { + setPath(chans(d, kind)[j], param, JSON.parse(JSON.stringify(value))); + recentlySet.set(`${d.id}|${kind}|${j}|${param}`, Date.now()); + showLive(`${d.id}|${kind}|${j}|${param}`, value); + } + const body = { kind, idx, param, value }; + const fire = b => api("POST", `/api/devices/${d.id}/set`, b).catch(e => toast(t("Error: ") + e.message)); + if (sendTimers.has(key)) { sendPending.set(key, body); return; } + fire(body); + sendTimers.set(key, setTimeout(function tick() { + if (sendPending.has(key)) { + fire(sendPending.get(key)); sendPending.delete(key); + sendTimers.set(key, setTimeout(tick, 60)); + } else sendTimers.delete(key); + }, 60)); +} + +// ------------------------------------------------------------------ controls + +// −/+ button with press-and-hold auto-repeat that speeds up the longer it is held +function stepper(dir, fn) { + const b = h("button", { class: "step", "aria-label": dir > 0 ? t("Increase") : t("Decrease"), tabindex: "-1" }, dir > 0 ? "+" : "−"); + let timer = null, n = 0; + const stop = () => { if (timer !== null) { clearTimeout(timer); timer = null; endBusy(); } }; + b.addEventListener("pointerdown", e => { + e.preventDefault(); beginBusy(); n = 0; fn(dir); + timer = setTimeout(function rep() { n++; fn(dir * (n > 30 ? 10 : n > 12 ? 3 : 1)); timer = setTimeout(rep, 70); }, 380); + }); + for (const ev of ["pointerup", "pointerleave", "pointercancel"]) b.addEventListener(ev, stop); + b.addEventListener("click", e => { if (e.detail === 0) fn(dir); }); // keyboard activation + return b; +} + +// Snap to the detent if a dragged value lands within `px` pixels of it. +function detent(v, zero, range, lengthPx, px = 10) { + if (zero == null) return v; + return Math.abs(v - zero) <= Math.max(1, range * px / Math.max(60, lengthPx)) ? zero : v; +} + +function paramSlider(label, kind, idx, path, specName, onChange) { + const spec = SPEC[specName]; + const cur = () => getPath(chans(dev(), kind)[idx], path); + const val = h("button", { class: "val", title: t("Enter value") }, spec.fmt(cur())); + const input = h("input", { type: "range", min: spec.min, max: spec.max, step: 1, value: cur(), "aria-label": label }); + const home = spec.zero ?? spec.def; + const wrap = h("div", { class: "param" + (cur() === spec.zero ? " atzero" : "") }); + let dragging = false; + const commit = v => { + v = clamp(Math.round(v), spec.min, spec.max); + input.value = v; + if (v === cur()) return; + if (v === spec.zero) buzz(); + val.textContent = spec.fmt(v); + wrap.classList.toggle("atzero", v === spec.zero); + setParam(kind, idx, path, v); + onChange && onChange(v); + }; + onLive(kind, idx, path, v => { input.value = v; val.textContent = spec.fmt(v); wrap.classList.toggle("atzero", v === spec.zero); }); + input.addEventListener("input", () => { + let v = +input.value; + if (dragging) v = detent(v, spec.zero, spec.max - spec.min, input.clientWidth - 26); + commit(v); + }); + let lastTap = 0; + input.addEventListener("pointerdown", () => { + dragging = true; beginBusy(); + const now = Date.now(); + if (home != null && now - lastTap < 320) setTimeout(() => commit(home), 0); + lastTap = now; + }); + const release = () => { if (dragging) { dragging = false; endBusy(); } }; + input.addEventListener("pointerup", release); + input.addEventListener("pointercancel", release); + input.addEventListener("blur", release); + val.addEventListener("click", async () => { + const v = await askValue(label, spec, cur()); + if (v != null) commit(v); + }); + const track = h("div", { class: "rangewrap" }, + spec.zero != null ? h("div", { class: "zmark", style: `--f:${(spec.zero - spec.min) / (spec.max - spec.min)}` }) : null, input); + wrap.append( + h("div", { class: "lbl" }, h("span", {}, label), + h("div", { class: "valbox" }, stepper(-1, d => commit(cur() + d)), val, stepper(1, d => commit(cur() + d)))), + track); + return wrap; +} + +function paramSelect(kind, idx, path, options, onChange, label) { + const ch = chans(dev(), kind)[idx]; + const sel = h("select", { "aria-label": label || path, onchange: () => { setParam(kind, idx, path, +sel.value); onChange && onChange(+sel.value); } }, + options.map((o, i) => h("option", { value: i, selected: getPath(ch, path) === i }, o))); + return sel; +} + +function toggleBtn(label, kind, idx, path, cls = "", onChange) { + const ch = chans(dev(), kind)[idx]; + const b = h("button", { class: (getPath(ch, path) ? "on " : "") + cls, "aria-pressed": String(!!getPath(ch, path)) }, label); + b.addEventListener("click", () => { + const v = !getPath(chans(dev(), kind)[idx], path); + b.classList.toggle("on", v); b.setAttribute("aria-pressed", String(v)); + setParam(kind, idx, path, v); + onChange && onChange(v); + }); + onLive(kind, idx, path, v => { b.classList.toggle("on", !!v); b.setAttribute("aria-pressed", String(!!v)); onChange && onChange(v); }); + return b; +} + +// Vertical fader: drag the cap (relative), 0-dB detent, double tap on the cap = 0 dB, wheel, keyboard. +// Touching the fader anywhere else does nothing, so a swipe there scrolls (e.g. the mixer sideways). +function fader({ min, max, value, zero, ticks, label, onInput }) { + const cap = h("div", { class: "cap" }); + const tickEls = (ticks || []).map(([v, label]) => h("div", { class: "tick" + (v === zero ? " z" : ""), style: `--f:${(v - min) / (max - min)}` }, label ? h("span", {}, label) : null)); + const el = h("div", { class: "fader", tabindex: "0", role: "slider", "aria-label": label || "Fader", + "aria-valuemin": min, "aria-valuemax": max }, h("div", { class: "track" }), tickEls, cap); + let cur = value; + const place = () => { + cap.style.setProperty("--f", (cur - min) / (max - min)); + el.setAttribute("aria-valuenow", cur); + el.classList.toggle("atzero", cur === zero); + }; + const set = (v, snap) => { + v = clamp(Math.round(v), min, max); + if (v === cur) return; + if (v === zero && snap !== false) buzz(); + cur = v; place(); onInput(v); + }; + el.setValue = v => { cur = v; place(); }; + place(); + let startY = 0, startV = 0, lastTap = 0, active = null; + el.addEventListener("pointerdown", e => { + if (active !== null || !e.target.closest(".cap")) return; + active = e.pointerId; + el.setPointerCapture(e.pointerId); + beginBusy(); + startY = e.clientY; startV = cur; + const now = Date.now(); + if (zero != null && now - lastTap < 300) { set(zero); startV = zero; } + lastTap = now; + el.classList.add("grab"); + e.preventDefault(); + }); + el.addEventListener("pointermove", e => { + if (e.pointerId !== active) return; + const H = el.clientHeight - 24; + const fine = e.shiftKey ? 0.25 : 1; + const raw = startV + (startY - e.clientY) / H * (max - min) * fine; + set(detent(raw, zero, max - min, H / fine)); + }); + const end = e => { if (e.pointerId !== active) return; active = null; el.classList.remove("grab"); endBusy(); }; + el.addEventListener("pointerup", end); + el.addEventListener("pointercancel", end); + el.addEventListener("wheel", e => { e.preventDefault(); set(cur - Math.sign(e.deltaY) * (e.shiftKey ? 1 : 4), false); }, { passive: false }); + el.addEventListener("keydown", e => { + const step = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1, PageUp: 20, PageDown: -20 }[e.key]; + if (step) { e.preventDefault(); set(cur + step, false); } + else if (e.key === "Home") { e.preventDefault(); set(max, false); } + else if (e.key === "End") { e.preventDefault(); set(min, false); } + else if (e.key === "0" && zero != null) { e.preventDefault(); set(zero); } + }); + return el; +} + +// ------------------------------------------------------------------ LED meters (Pioneer-style segment bars) + +// Segment thresholds in dB (bottom to top) and their colour +const SEGS = [-48, -40, -34, -28, -24, -20, -16, -12, -9, -6, -4, -2, 0, 2, 4, 6] + .map(db => ({ db, c: db >= 4 ? "r" : db >= 0 ? "o" : "g" })); +(function meterCss() { + let css = ""; + for (let n = 1; n <= SEGS.length; n++) css += `.led[data-n="${n}"]>i:nth-child(-n+${n}),.led[data-p="${n}"]>i:nth-child(${n}){opacity:1;box-shadow:0 0 6px var(--c)}`; + document.head.append(h("style", {}, css)); +})(); + +const meterTarget = new Map(); // key -> dB from the device +const meterState = new Map(); // key -> {lvl, pk, pkT} +let meterEls = []; + +function ledMeter(devId, kind, idx, orient = "v") { + return h("div", { class: "led " + orient, "data-key": `${devId}|${kind}|${idx}`, "aria-hidden": "true" }, + SEGS.map(s => h("i", { class: s.c }))); +} +function collectMeters() { meterEls = [...document.querySelectorAll(".led[data-key]")]; limEls = [...document.querySelectorAll("[data-lim]")]; } + +// Limiter LEDs (outputs): the DSP reports "limiter active" per output with every meter reading +const limitOn = new Map(); // "dev|idx" -> time it was last reported active +let limEls = []; +const LIM_HOLD = 300; // ms an LED stays lit, so short hits are visible +const limLed = (devId, i, cls = "") => h("span", { class: "limled " + cls, "data-lim": `${devId}|${i}`, title: t("Limiter active"), "aria-hidden": "true" }, + cls ? "LIM" : null); + +function updateMeters(ev) { + for (const kind of ["in", "out"]) + (ev[kind] || []).forEach((v, i) => meterTarget.set(`${ev.device}|${kind}|${i}`, v > 0 ? 20 * Math.log10(v) : -120)); + (ev.limit || []).forEach((on, i) => { if (on) limitOn.set(`${ev.device}|${i}`, performance.now()); }); +} + +let lastFrame = performance.now(); +function meterFrame(now) { + const dt = Math.min(0.1, (now - lastFrame) / 1000); lastFrame = now; + for (const el of limEls) { + const on = now - (limitOn.get(el.dataset.lim) ?? -1e9) < LIM_HOLD; + if (el.classList.contains("on") !== on) el.classList.toggle("on", on); + } + for (const el of meterEls) { + const key = el.dataset.key; + let st = meterState.get(key); + if (!st) meterState.set(key, st = { lvl: -120, pk: 0, pkT: 0 }); + const target = meterTarget.get(key) ?? -120; + st.lvl = target > st.lvl ? target : Math.max(target, st.lvl - 26 * dt); // instant attack, ~26 dB/s fall + let n = 0; + while (n < SEGS.length && st.lvl >= SEGS[n].db) n++; + if (n >= st.pk) { st.pk = n; st.pkT = now; } + else if (now - st.pkT > 1200) { st.pk = Math.max(n, st.pk - 1); st.pkT = now - 1120; } + const ns = n ? String(n) : "", ps = st.pk ? String(st.pk) : ""; + if (el.dataset.n !== ns) el.dataset.n = ns; + if (el.dataset.p !== ps) el.dataset.p = ps; + } + requestAnimationFrame(meterFrame); +} +requestAnimationFrame(meterFrame); + +// ------------------------------------------------------------------ header / status + +function renderTabs() { + const tabs = $("#devtabs"); + tabs.replaceChildren(...S.order.map(id => { + const d = S.devices[id]; + const model = d.detected_model || (d.model !== "auto" ? d.model : ""); + return h("button", { class: "devtab" + (id === S.cur && !S.settings ? " active" : ""), title: `${d.name} · ${where(d)}`, + onclick: () => { S.cur = id; S.settings = false; store.set("dsp.cur", id); render(); } }, + h("span", { class: "dot " + d.status }), h("span", { class: "dn" }, d.name), model ? h("small", {}, model) : null); + })); + $("#btn-settings").classList.toggle("on", S.settings); + document.querySelectorAll("#viewtabs button").forEach(b => b.classList.toggle("active", !S.settings && b.dataset.view === S.view)); +} + +const STATUS_TEXT = { disconnected: t("Disconnected"), connecting: t("Connecting…"), loading: t("Loading configuration…"), + online: "Online", error: t("Error") }; + +async function storePresetDialog(d) { + const slot = h("select", {}, d.presets.map((p, i) => h("option", { value: i }, `U${String(i + 1).padStart(2, "0")} ${p || t("— empty —")}`))); + const name = h("input", { type: "text", maxlength: 14, value: d.state.preset_name || "", placeholder: t("Name (max. 14 characters)") }); + const cur = d.presets.indexOf(d.state.preset_name); + if (cur >= 0) slot.value = cur; + const res = await modal({ + title: t("Store preset"), + body: h("div", { class: "form" }, h("label", {}, t("Memory slot"), slot), h("label", {}, "Name", name), + h("p", { class: "info" }, t("Overwrites the selected memory slot in the DSP."))), + actions: [{ label: t("Cancel") }, { label: t("Save"), primary: true, + value: () => ({ index: +slot.value, name: name.value.trim().slice(0, 14) || `Preset ${+slot.value + 1}` }) }], + }); + if (!res) return; + try { await api("POST", `/api/devices/${d.id}/preset/store`, res); toast(t("Stored in U{n}", { n: res.index + 1 })); } + catch (e) { toast(t("Error: ") + e.message); } +} + +async function presetFileDialog(d) { + const backups = await api("POST", `/api/devices/${d.id}/backups`).catch(() => []); + const last = backups[0] && new Date(backups[0].time * 1000).toLocaleString(LOCALE, { dateStyle: "short", timeStyle: "short" }); + const choice = await modal({ + title: t("Preset file"), + body: h("div", {}, + h("p", { class: "dlg-text" }, t("Export saves the DSP’s current state ({name}) to a file. Import loads a file into the " + + "active state – stored presets (U01 …) stay unchanged.", { name: q(d.state.preset_name || "—") })), + last ? h("p", { class: "dlg-text" }, t("A backup is made automatically before every import. Last backup: {last}.", { last })) : null), + actions: [{ label: t("Close") }, + ...(last && !S.locked ? [{ label: t("Undo import"), value: () => "undo" }] : []), + ...(S.locked ? [] : [{ label: t("Import…"), value: () => "import" }]), + { label: t("Export"), primary: true, value: () => "export" }], + }); + try { + if (choice === "export") await exportPreset(d); + else if (choice === "import") await importPreset(d); + else if (choice === "undo") { + if (!await askConfirm(t("Undo import"), t("Restore the state from {last}?", { last }), t("Restore"))) return; + toast(t("Restoring…")); + reportImport(await api("POST", `/api/devices/${d.id}/undo`), t("Previous state restored")); + } + } catch (e) { toast(t("Error: ") + e.message); } +} + +async function exportPreset(d) { + toast(t("Reading the state from the DSP…")); + const doc = await api("POST", `/api/devices/${d.id}/export`); + if (await saveFile(`${fileSafe(doc.preset_name)}_DSP${doc.model}_${today()}.json`, doc)) toast(t("Preset exported")); +} + +async function importPreset(d) { + const f = await openFile(); + if (!f) return; + const doc = f.json; + const what = doc && doc.preset_name != null + ? `${q(doc.preset_name || "—")} (DSP ${doc.model}${doc.exported ? ", " + t("exported") + " " + doc.exported.replace("T", " ").slice(0, 16) : ""})` + : q(f.name); + if (!await askConfirm(t("Import preset"), t("Load {what} into the active state? The current state is backed up automatically first and " + + "can be brought back via File → “Undo import”. Stored presets stay unchanged – to keep it, store it into a memory slot with “Save” afterwards.", + { what }), t("Import"))) return; + toast(t("Importing… (a few seconds)")); + reportImport(await api("POST", `/api/devices/${d.id}/import`, doc ? { doc } : { raw: f.b64 }), + doc && doc.preset_name ? t("Preset {name} imported", { name: q(doc.preset_name) }) : t("Preset imported")); +} + +function reportImport(res, okMsg) { + if (res.ok) return toast(okMsg); + modal({ title: t("Import incomplete"), body: h("div", {}, + h("p", { class: "dlg-text" }, t("The DSP did not take these values:")), + h("p", { class: "dlg-text" }, h("code", {}, res.differences.join(", ")))), + actions: [{ label: "OK", primary: true, value: () => true }] }); +} + +function renderStatus() { + const bar = $("#statusbar"); + const d = dev(); + if (S.settings || !d) { bar.replaceChildren(); return; } + if (d.status !== "online" || !d.state) { + bar.replaceChildren( + h("div", { class: "preset" }, h("small", {}, `${STATUS_TEXT[d.status] || d.status} · ${d.transport === "usb" ? "USB" : d.host + ":" + d.port}`), h("b", {}, d.name), + d.error ? h("div", { class: "err" }, trMsg(d.error)) : null), + d.status === "disconnected" || d.status === "error" + ? h("button", { class: "on", onclick: () => api("POST", `/api/devices/${d.id}/connect`).catch(e => toast(e.message)) }, t("Connect")) + : h("button", { onclick: () => api("POST", `/api/devices/${d.id}/disconnect`) }, t("Cancel"))); + return; + } + const presetSel = h("select", { "aria-label": t("Recall preset") }, + h("option", { value: "" }, t("Recall preset…")), + d.presets.map((p, i) => h("option", { value: i, disabled: !p }, `U${String(i + 1).padStart(2, "0")} ${p || "—"}`))); + presetSel.addEventListener("change", async () => { + if (presetSel.value === "") return; + const i = +presetSel.value; + presetSel.value = ""; + if (!await askConfirm(t("Recall preset"), t("Recall {name} (U{n})? Unsaved changes will be lost.", { name: q(d.presets[i]), n: i + 1 }), t("Recall"))) return; + presetSel.disabled = true; + try { await api("POST", `/api/devices/${d.id}/preset/recall`, { index: i }); toast(t("Preset U{n} recalled", { n: i + 1 })); } + catch (e) { toast(t("Error: ") + e.message); } + presetSel.disabled = false; + }); + bar.replaceChildren( + h("div", { class: "preset" }, h("small", {}, `${d.info || d.name} · ${where(d)}`), h("b", {}, d.state.preset_name || "—")), + h("div", { class: "presetrow" }, presetSel, h("button", { onclick: () => storePresetDialog(d) }, t("Save")), + h("button", { onclick: () => presetFileDialog(d), title: t("Export / import preset"), "data-view-ok": "" }, t("File…")))); +} + +// ------------------------------------------------------------------ mixer + +function openChannel(kind, idx) { + S.sel = { kind, idx }; S.view = "channel"; store.set("dsp.view", "channel"); render(); window.scrollTo(0, 0); +} + +function strip(d, kind, i) { + const ch = chans(d, kind)[i]; + const db = h("button", { class: "db" + (ch.gain === 280 ? " z" : ""), title: t("Enter value") }, sign(gainDb(ch.gain))); + const showDb = v => { db.textContent = sign(gainDb(v)); db.classList.toggle("z", v === 280); }; + const el = h("div", { class: `strip ${kind}` + (ch.mute ? " muted" : ""), style: kind === "in" ? `--cc:${IN_COLORS[i]}` : "" }); + const f = fader({ min: 0, max: 400, value: ch.gain, zero: 280, ticks: GAIN_TICKS, label: `${chLabel(kind, i)} Gain`, + onInput: v => { showDb(v); setParam(kind, i, "gain", v); } }); + onLive(kind, i, "gain", v => { f.setValue(v); showDb(v); }); + db.addEventListener("click", async () => { + const v = await askValue(`${chTitle(d, kind, i)} – Gain`, SPEC.gain, chans(dev(), kind)[i].gain); + if (v != null) { f.setValue(v); showDb(v); setParam(kind, i, "gain", v); } + }); + el.append( + h("button", { class: "strip-head", onclick: () => openChannel(kind, i), title: t("Edit channel") }, + h("span", { class: "kind" }, chLabel(kind, i), linkBadge(d, kind, i)), h("span", { class: "nm" }, ch.name || " "), + kind === "out" ? limLed(d.id, i) : h("span", { class: "limled ph", "aria-hidden": "true" })), // keeps faders level with the outputs + h("div", { class: "faderbox" }, ledMeter(d.id, kind, i), f), + db, + toggleBtn("MUTE", kind, i, "mute", "mute", v => el.classList.toggle("muted", v))); + return el; +} + +function viewMixer(d) { + const group = (kind, title) => h("section", { class: "mgroup", style: `flex-grow:${chans(d, kind).length}` }, + h("h4", {}, title), h("div", { class: "strips" }, chans(d, kind).map((_, i) => strip(d, kind, i)))); + return [h("div", { class: "mixer" }, group("in", t("Inputs")), group("out", t("Outputs"))), + h("p", { class: "info hint" }, t("Drag a fader by its knob · snaps at 0 dB · double-tap the knob = 0 dB · tap the dB value to type one · tap the name = edit channel"))]; +} + +// ------------------------------------------------------------------ filter response (for the PEQ curve) + +const FS = 96000; +function biquadMag(type, f0, dbGain, q, f) { + const A = Math.pow(10, dbGain / 40), w0 = 2 * Math.PI * f0 / FS, cs = Math.cos(w0), sn = Math.sin(w0); + const alpha = sn / (2 * q); + let b0, b1, b2, a0, a1, a2; + switch (type) { + case 0: b0 = 1 + alpha * A; b1 = -2 * cs; b2 = 1 - alpha * A; a0 = 1 + alpha / A; a1 = -2 * cs; a2 = 1 - alpha / A; break; + case 1: case 2: { + const s = type === 1 ? 1 : -1, sq = 2 * Math.sqrt(A) * alpha; + b0 = A * ((A + 1) - s * (A - 1) * cs + sq); b1 = s * 2 * A * ((A - 1) - s * (A + 1) * cs); b2 = A * ((A + 1) - s * (A - 1) * cs - sq); + a0 = (A + 1) + s * (A - 1) * cs + sq; a1 = -s * 2 * ((A - 1) + s * (A + 1) * cs); a2 = (A + 1) + s * (A - 1) * cs - sq; break; + } + case 3: { const k = Math.tan(w0 / 2); b0 = 1; b1 = -1; b2 = 0; a0 = 1 + k; a1 = k - 1; a2 = 0; break; } + case 4: b0 = (1 + cs) / 2; b1 = -(1 + cs); b2 = (1 + cs) / 2; a0 = 1 + alpha; a1 = -2 * cs; a2 = 1 - alpha; break; + case 5: { const k = Math.tan(w0 / 2); b0 = k; b1 = k; b2 = 0; a0 = 1 + k; a1 = k - 1; a2 = 0; break; } + case 6: b0 = (1 - cs) / 2; b1 = 1 - cs; b2 = (1 - cs) / 2; a0 = 1 + alpha; a1 = -2 * cs; a2 = 1 - alpha; break; + default: return 0; + } + const w = 2 * Math.PI * f / FS, c1 = Math.cos(w), s1 = Math.sin(w), c2 = Math.cos(2 * w), s2 = Math.sin(2 * w); + const nr = b0 + b1 * c1 + b2 * c2, ni = -(b1 * s1 + b2 * s2), dr = a0 + a1 * c1 + a2 * c2, di = -(a1 * s1 + a2 * s2); + return 10 * Math.log10((nr * nr + ni * ni) / (dr * dr + di * di)); +} +function xoverMag(filter, f, high) { + if (!filter.slope) return 0; + const name = SLOPES[filter.slope], order = parseInt(name.split("-")[1], 10) / 6, fc = freqHz(filter.freq); + const r = high ? fc / f : f / fc; + if (name.startsWith("LK")) return -20 * Math.log10(1 + Math.pow(r, order)); + return -10 * Math.log10(1 + Math.pow(r, 2 * order)); +} +const hasGain = type => type <= 2; +const hasQ = type => [0, 4, 6, 7, 8].includes(type); + +function drawCurve(canvas, ch, selBand) { + const dpr = window.devicePixelRatio || 1, W = canvas.clientWidth, H = canvas.clientHeight; + if (!W || !H) return null; + canvas.width = W * dpr; canvas.height = H * dpr; + const g = canvas.getContext("2d"); + g.scale(dpr, dpr); + const fx = f => Math.log(f / 20) / Math.log(1000) * W; + const dy = db => H / 2 - db / 15 * (H / 2 - 10); + g.font = "10px system-ui"; g.fillStyle = "#5b6673"; g.lineWidth = 1; + for (const f of [30, 50, 100, 200, 500, 1000, 2000, 5000, 10000]) { + g.strokeStyle = [100, 1000, 10000].includes(f) ? "#252d37" : "#1a2028"; + g.beginPath(); g.moveTo(fx(f), 0); g.lineTo(fx(f), H); g.stroke(); + g.fillText(f >= 1000 ? f / 1000 + "k" : f, fx(f) + 3, H - 4); + } + for (const db of [-12, -6, 0, 6, 12]) { + g.strokeStyle = db === 0 ? "#3a4552" : "#1a2028"; + g.beginPath(); g.moveTo(0, dy(db)); g.lineTo(W, dy(db)); g.stroke(); + g.fillText((db > 0 ? "+" : "") + db, 3, dy(db) - 3); + } + const resp = f => { + let s = xoverMag(ch.hp, f, true) + xoverMag(ch.lp, f, false); + for (const b of ch.peq) if (!b.bypass) s += biquadMag(b.type, freqHz(b.freq), eqDb(b.gain), Q_TABLE[b.q], f); + return s; + }; + // selected band's own contribution, filled + const sb = ch.peq[selBand]; + if (sb && !sb.bypass) { + g.beginPath(); g.moveTo(0, dy(0)); + for (let x = 0; x <= W; x += 3) g.lineTo(x, clamp(dy(biquadMag(sb.type, freqHz(sb.freq), eqDb(sb.gain), Q_TABLE[sb.q], 20 * Math.pow(1000, x / W))), 0, H)); + g.lineTo(W, dy(0)); g.closePath(); g.fillStyle = "#f59e0b22"; g.fill(); + } + const pts = []; + for (let x = 0; x <= W; x += 2) pts.push([x, clamp(dy(resp(20 * Math.pow(1000, x / W))), 0, H)]); + g.beginPath(); g.moveTo(0, H); pts.forEach(([x, y]) => g.lineTo(x, y)); g.lineTo(W, H); g.closePath(); + const grad = g.createLinearGradient(0, 0, 0, H); grad.addColorStop(0, "#38bdf833"); grad.addColorStop(1, "#38bdf800"); + g.fillStyle = grad; g.fill(); + g.strokeStyle = "#38bdf8"; g.lineWidth = 2; g.beginPath(); + pts.forEach(([x, y], i) => i ? g.lineTo(x, y) : g.moveTo(x, y)); + g.stroke(); + ch.peq.forEach((b, i) => { + const x = fx(freqHz(b.freq)), y = dy(hasGain(b.type) ? eqDb(b.gain) : 0); + g.beginPath(); g.arc(x, y, i === selBand ? 10 : 7, 0, 2 * Math.PI); + g.fillStyle = b.bypass ? "#2a333d" : i === selBand ? "#f59e0b" : "#38bdf8cc"; g.fill(); + g.fillStyle = b.bypass ? "#6b7682" : "#0b0c0f"; g.font = "bold 10px system-ui"; g.textAlign = "center"; g.textBaseline = "middle"; + g.fillText(i + 1, x, y + 0.5); g.textAlign = "start"; g.textBaseline = "alphabetic"; + }); + return { fx, dy, W, H }; +} + +function peqCard(d, kind, idx) { + const ch = chans(d, kind)[idx]; + S.band = Math.min(S.band, ch.peq.length - 1); + const canvas = h("canvas", { class: "curve", "aria-label": t("EQ curve – drag the points") }); + const redraw = () => drawCurve(canvas, chans(dev(), kind)[idx], S.band); + const body = h("div", { class: "bandparams" }); + const bandBtns = h("div", { class: "bands", role: "tablist" }); + const renderBand = () => { + const c = chans(dev(), kind)[idx], b = c.peq[S.band], p = `peq.${S.band}`; + bandBtns.replaceChildren(...c.peq.map((bb, i) => h("button", { + class: "band" + (i === S.band ? " on" : "") + (bb.bypass ? " bypassed" : "") + (hasGain(bb.type) && bb.gain !== 120 ? " active" : ""), + role: "tab", "aria-selected": String(i === S.band), + onclick: () => { S.band = i; renderBand(); redraw(); } }, + h("b", {}, String(i + 1)), h("small", {}, fmtHzShort(freqHz(bb.freq))), + h("small", {}, hasGain(bb.type) ? sign(eqDb(bb.gain)) : PEQ_SHORT[bb.type])))); + const both = () => { renderBand(); redraw(); }; + body.replaceChildren( + h("div", { class: "row bandhead" }, + h("label", { class: "inline" }, t("Type"), paramSelect(kind, idx, p + ".type", PEQ_TYPES, both, t("Filter type"))), + toggleBtn("Bypass", kind, idx, p + ".bypass", "", both), + hasGain(b.type) ? h("button", { onclick: () => { setParam(kind, idx, p + ".gain", 120); both(); } }, "0 dB") : null), + h("div", { class: "pgrid" }, + paramSlider(t("Frequency"), kind, idx, p + ".freq", "freq", both), + hasGain(b.type) ? paramSlider("Gain", kind, idx, p + ".gain", "eqgain", both) : null, + hasQ(b.type) ? paramSlider("Q", kind, idx, p + ".q", "q", both) : null)); + }; + // drag points on the curve (gain snaps to 0 dB) + let drag = null; + canvas.addEventListener("pointerdown", e => { + const c = chans(dev(), kind)[idx], r = canvas.getBoundingClientRect(), geo = drawCurve(canvas, c, S.band); + if (!geo) return; + let best = -1, bd = 1600; + c.peq.forEach((b, i) => { + const dx = geo.fx(freqHz(b.freq)) - (e.clientX - r.left); + const dyy = geo.dy(hasGain(b.type) ? eqDb(b.gain) : 0) - (e.clientY - r.top); + if (dx * dx + dyy * dyy < bd) { bd = dx * dx + dyy * dyy; best = i; } + }); + if (best < 0) return; + e.preventDefault(); + S.band = best; beginBusy(); drag = { geo, r, id: e.pointerId }; + canvas.setPointerCapture(e.pointerId); renderBand(); redraw(); + }); + canvas.addEventListener("pointermove", e => { + if (!drag || e.pointerId !== drag.id) return; + const { geo, r } = drag, c = chans(dev(), kind)[idx], b = c.peq[S.band]; + const x = clamp(e.clientX - r.left, 0, geo.W); + const f = hzFreq(20 * Math.pow(1000, x / geo.W)); + if (f !== b.freq) setParam(kind, idx, `peq.${S.band}.freq`, f); + if (hasGain(b.type)) { + const db = (geo.H / 2 - (e.clientY - r.top)) / (geo.H / 2 - 10) * 15; + let g = clamp(Math.round(db * 10 + 120), 0, 240); + g = detent(g, 120, 300, geo.H - 20, 8); + if (g !== b.gain) { if (g === 120) buzz(); setParam(kind, idx, `peq.${S.band}.gain`, g); } + } + redraw(); + }); + const end = () => { if (drag) { drag = null; renderBand(); endBusy(); } }; + canvas.addEventListener("pointerup", end); + canvas.addEventListener("pointercancel", end); + renderBand(); + requestAnimationFrame(redraw); + new ResizeObserver(redraw).observe(canvas); + return h("div", { class: "card wide" }, + h("h3", {}, h("span", { class: "grow" }, t("Parametric EQ")), + h("button", { class: "small", onclick: async () => { + if (!await askConfirm(t("Reset EQ"), t("Set all PEQ bands of this channel to 0 dB and clear bypass?"), t("All flat"))) return; + chans(dev(), kind)[idx].peq.forEach((bb, i) => { + if (bb.gain !== 120) setParam(kind, idx, `peq.${i}.gain`, 120); + if (bb.bypass) setParam(kind, idx, `peq.${i}.bypass`, false); + }); + renderBand(); redraw(); toast(t("All bands flat")); + } }, t("All flat"))), + canvas, h("p", { class: "info" }, t("Drag the points in the curve · gain snaps at 0 dB")), bandBtns, body); +} + +function geqCard(d, idx) { + const ch = chans(d, "in")[idx]; + const faders = []; + const bands = ch.geq.map((v, b) => { + const lbl = h("span", { class: "gv" }, eqDb(v).toFixed(1)); + const f = fader({ min: 0, max: 240, value: v, zero: 120, ticks: [[240, ""], [120, ""], [0, ""]], label: `GEQ ${GEQ_FREQS[b]} Hz`, + onInput: x => { lbl.textContent = eqDb(x).toFixed(1); lbl.classList.toggle("nz", x !== 120); setParam("in", idx, `geq.${b}`, x); } }); + lbl.classList.toggle("nz", v !== 120); + faders.push([f, lbl]); + return h("div", { class: "gb" }, lbl, f, h("span", { class: "gf" }, GEQ_FREQS[b])); + }); + return h("div", { class: "card wide" }, + h("h3", {}, h("span", { class: "grow" }, t("Graphic EQ · 31 bands")), + h("button", { class: "small", onclick: async () => { + if (!await askConfirm(t("Reset GEQ"), t("Set all 31 bands to 0 dB?"), t("Reset"))) return; + chans(dev(), "in")[idx].geq.forEach((g, b) => { if (g !== 120) setParam("in", idx, `geq.${b}`, 120); }); + faders.forEach(([f, l]) => { f.setValue(120); l.textContent = "0.0"; l.classList.remove("nz"); }); + } }, t("All flat"))), + h("div", { class: "geq" }, bands), + h("p", { class: "info" }, t("Snaps at 0 dB · double-tap the knob = 0 dB"))); +} + +// ------------------------------------------------------------------ channel view + +function channelBar(d) { + const { kind, idx } = S.sel; + const all = [...chans(d, "in").map((_, i) => ["in", i]), ...chans(d, "out").map((_, i) => ["out", i])]; + const pos = all.findIndex(([k, i]) => k === kind && i === idx); + const go = p => { const [k, i] = all[(p + all.length) % all.length]; S.sel = { kind: k, idx: i }; render(); }; + const sel = h("select", { class: "chsel", "aria-label": t("Choose channel"), onchange: () => go(+sel.value) }, + h("optgroup", { label: t("Inputs") }, chans(d, "in").map((_, i) => h("option", { value: i, selected: pos === i }, chTitle(d, "in", i)))), + h("optgroup", { label: t("Outputs") }, chans(d, "out").map((_, i) => { + const p = chans(d, "in").length + i; + return h("option", { value: p, selected: pos === p }, chTitle(d, "out", i)); + }))); + return h("div", { class: "chbar" }, + h("button", { class: "icon nav", "aria-label": t("Previous channel"), onclick: () => go(pos - 1) }, svgIcon(ICON.prev)), + h("div", { class: "chselwrap", style: kind === "in" ? `--cc:${IN_COLORS[idx]}` : "" }, sel), + h("button", { class: "icon nav", "aria-label": t("Next channel"), onclick: () => go(pos + 1) }, svgIcon(ICON.next)), + ledMeter(d.id, kind, idx, "h"), + kind === "out" ? limLed(d.id, idx, "h") : null, + toggleBtn("MUTE", kind, idx, "mute", "mute")); +} + +function viewChannel(d) { + if (S.sel.idx >= chans(d, S.sel.kind).length) S.sel = { kind: "in", idx: 0 }; + const k = S.sel.kind, i = S.sel.idx, ch = chans(d, k)[i]; + const redrawPeq = () => { const c = main.querySelector("canvas.curve"); c && drawCurve(c, chans(dev(), k)[i], S.band); }; + + const li = linkInfo(d, k, i); + const basics = h("div", { class: "card" }, h("h3", {}, t("Channel")), + li ? h("p", { class: "info linknote", style: `--lc:${li.color}` }, svgIcon(ICON.link), + " " + t(k === "out" ? "Linked with {list} – changes apply to all of them (except name, routing and mix levels)." + : "Linked with {list} – changes apply to all of them (except the name).", { list: li.group.filter(j => j !== i).map(j => chLabel(k, j)).join(", ") })) : null, + h("div", { class: "row" }, + h("label", { class: "inline grow2" }, "Name", + h("input", { type: "text", maxlength: NAME_MAX, value: ch.name, placeholder: chLabel(k, i), "aria-label": t("Channel name"), + oninput: e => { // stop typing where the name would no longer fit + const c = cleanName(e.target.value); + if (c !== e.target.value) { + const pos = Math.min(e.target.selectionStart, c.length); + e.target.value = c; e.target.setSelectionRange(pos, pos); + if (Date.now() - (S.nameToast || 0) > 2000) { S.nameToast = Date.now(); toast(t("Name is full (max. 8 characters, wide letters count more)")); } + } + }, + onchange: e => { setParam(k, i, "name", cleanName(e.target.value).trim()); render(); } })), + toggleBtn("Phase Ø", k, i, "polarity")), + paramSlider("Gain", k, i, "gain", "gain"), + paramSlider("Delay", k, i, "delay", "delay")); + + const xo = (title, key) => h("div", { class: "xo" }, + h("div", { class: "row" }, h("span", { class: "sub" }, title), paramSelect(k, i, key + ".slope", SLOPES, () => { redrawPeq(); render(); }, title)), + chans(d, k)[i][key].slope ? paramSlider(t("Frequency"), k, i, key + ".freq", "freq", redrawPeq) : h("p", { class: "info off" }, t("Off (bypass)"))); + const xover = h("div", { class: "card" }, h("h3", {}, t("High- / low-pass")), + xo(t("High-pass"), "hp"), xo(t("Low-pass"), "lp")); + + const cards = [basics, xover]; + if (k === "in") { + cards.push(h("div", { class: "card" }, h("h3", {}, "Noise Gate"), + paramSlider("Threshold", k, i, "gate.threshold", "gthresh"), + paramSlider("Attack", k, i, "gate.attack", "attack"), + paramSlider("Hold", k, i, "gate.hold", "hold"), + paramSlider("Release", k, i, "gate.release", "release"))); + cards.push(peqCard(d, k, i), geqCard(d, i)); + } else { + cards.push(routingCard(d, i), peqCard(d, k, i)); + cards.push(h("div", { class: "card" }, h("h3", {}, t("Compressor")), + paramSlider("Threshold", k, i, "comp.threshold", "thresh"), + paramSlider("Ratio", k, i, "comp.ratio", "ratio"), + paramSlider("Attack", k, i, "comp.attack", "attack"), + paramSlider("Release", k, i, "comp.release", "release"), + paramSlider("Knee", k, i, "comp.knee", "knee"))); + const lc = limCalc(d.id, i, ch.limit.threshold); + cards.push(h("div", { class: "card" }, h("h3", {}, "Limiter"), + h("div", { class: "row" }, h("span", { class: "grow" }, "Threshold ", h("b", {}, SPEC.thresh.fmt(ch.limit.threshold)), + lc ? [" → ", h("b", {}, fmtW(lc.p)), ` @ ${lc.as.ohm} Ω`] : null), + h("button", { class: "small", onclick: () => { S.view = "limiter"; store.set("dsp.view", "limiter"); render(); window.scrollTo(0, 0); } }, t("Limiter tab"))))); + } + return [channelBar(d), h("div", { class: "cards" }, cards)]; +} + +// Per-output source list: on/off + level per input +function mixList(d, o) { + return chans(d, "in").map((inp, i) => { + const on = chans(d, "out")[o].matrix >> i & 1; + const btn = h("button", { class: "src" + (on ? " on" : ""), style: `--cc:${IN_COLORS[i]}`, "aria-pressed": String(!!on), + onclick: () => { + const m = chans(dev(), "out")[o].matrix ^ (1 << i); + setParam("out", o, "matrix", m); render(); + } }, h("span", { class: "sw" }), chTitle(d, "in", i)); + return h("div", { class: "mixrow" + (on ? "" : " off") }, btn, paramSlider(t("Level"), "out", o, `mix.${i}`, "mix")); + }); +} + +function routingCard(d, o) { + return h("div", { class: "card" }, h("h3", {}, t("Sources → ") + chLabel("out", o)), mixList(d, o)); +} + +// ------------------------------------------------------------------ routing view + +function viewRouting(d) { + const ins = chans(d, "in"), outs = chans(d, "out"); + const grid = h("div", { class: "xmatrix", style: `--n:${ins.length}` }); + grid.append(h("div", { class: "xcorner" }, h("span", {}, t("Input →")), h("span", {}, t("Output ↓")))); + ins.forEach((c, i) => grid.append(h("div", { class: "xin", style: `--cc:${IN_COLORS[i]}` }, + h("b", {}, chLabel("in", i)), h("small", {}, c.name || " "), ledMeter(d.id, "in", i, "h")))); + outs.forEach((oc, o) => { + const open = S.routeOpen === o; + const srcs = ins.map((_, i) => oc.matrix >> i & 1 ? chLabel("in", i).slice(3) : null).filter(Boolean); + grid.append(h("button", { class: "xout" + (open ? " open" : ""), "aria-expanded": String(open), + onclick: () => { S.routeOpen = open ? null : o; render(); } }, + h("span", { class: "xo-t" }, h("b", {}, chLabel("out", o)), h("small", {}, oc.name || " ")), + h("span", { class: "xo-s" }, srcs.length ? "← " + srcs.join("+") : "—"), + h("span", { class: "chev" }, open ? "▴" : "▾"))); + ins.forEach((_, i) => { + const on = oc.matrix >> i & 1; + grid.append(h("button", { class: "xp" + (on ? " on" : ""), style: `--cc:${IN_COLORS[i]}`, + "aria-label": `${chLabel("in", i)} → ${chLabel("out", o)}`, "aria-pressed": String(!!on), + onclick: () => { + const m = chans(dev(), "out")[o].matrix ^ (1 << i); + setParam("out", o, "matrix", m); render(); + } }, h("span", { class: "node" }), on ? h("small", {}, gainDb(oc.mix[i]) === 0 ? "0 dB" : sign(gainDb(oc.mix[i]))) : null)); + }); + if (open) grid.append(h("div", { class: "xpanel" }, h("div", { class: "xpanel-h" }, t("Level for {ch}", { ch: chTitle(d, "out", o) }), + h("button", { class: "small", onclick: () => openChannel("out", o) }, t("Open channel"))), mixList(d, o))); + }); + return h("div", { class: "card routing" }, h("h3", {}, t("Routing matrix")), grid, + h("p", { class: "info" }, t("Tap a crosspoint = connect/disconnect · tap an output = level per input"))); +} + +// ------------------------------------------------------------------ channel links + +async function saveLinks(d, kind, groups, msg) { + S.linkBusy = true; render(); + try { await api("POST", `/api/devices/${d.id}/link`, { kind, groups }); toast(msg); } + catch (e) { toast(t("Error: ") + e.message); } + S.linkBusy = false; S.linkSel[kind] = []; render(); +} + +function linkCard(d, kind) { + const list = chans(d, kind), linked = linkedGroups(d, kind); + const sel = S.linkSel[kind] = S.linkSel[kind].filter(i => i < list.length); + const btns = list.map((ch, i) => { + const l = linkInfo(d, kind, i), on = sel.includes(i); + return h("button", { class: "lkch" + (on ? " sel" : ""), style: l ? `--lc:${l.color}` : "", "aria-pressed": String(on), + disabled: S.linkBusy, onclick: () => { S.linkSel[kind] = on ? sel.filter(j => j !== i) : [...sel, i].sort((a, b) => a - b); render(); } }, + h("b", {}, chLabel(kind, i)), h("small", {}, ch.name || "\u00a0"), + h("span", { class: "lkmark" }, l ? svgIcon(ICON.link) : null)); + }); + const link = async () => { + const first = chLabel(kind, sel[0]); + const names = sel.map(i => chLabel(kind, i)).join(", "); + if (!await askConfirm(t("Link channels"), t(kind === "out" ? "Link {names}? They all take over the settings of {first} (names and routing stay)." + : "Link {names}? They all take over the settings of {first} (names stay).", { names, first }), t("Link"))) return; + const rest = linked.map(g => g.filter(i => !sel.includes(i))).filter(g => g.length > 1); + saveLinks(d, kind, [...rest, sel], t("{names} linked", { names })); + }; + const unlink = g => saveLinks(d, kind, linked.filter(x => x !== g), t("{names} unlinked", { names: g.map(i => chLabel(kind, i)).join(" + ") })); + return h("div", { class: "card" }, h("h3", {}, kind === "in" ? t("Inputs") : t("Outputs")), + h("div", { class: "lkgrid" }, btns), + h("div", { class: "row lkactions" }, + h("span", { class: "grow info" }, sel.length < 2 ? t("Tap at least two channels") : t("{n} channels selected", { n: sel.length })), + h("button", { class: "on", disabled: sel.length < 2 || S.linkBusy, onclick: link }, t("Link"))), + linked.length ? h("div", { class: "lkgroups" }, linked.map((g, n) => + h("div", { class: "row lkgroup", style: `--lc:${LINK_COLORS[n % LINK_COLORS.length]}` }, + svgIcon(ICON.link), h("span", { class: "grow" }, g.map(i => chLabel(kind, i)).join(" + ")), + h("button", { class: "small", disabled: S.linkBusy, onclick: () => unlink(g) }, t("Unlink"))))) + : h("p", { class: "info" }, t("No channels linked."))); +} + +function viewLink(d) { + return [h("div", { class: "cards" }, linkCard(d, "in"), linkCard(d, "out")), + h("p", { class: "info hint" }, t("Linked channels share all settings (gain, delay, filters, EQ, dynamics, mute) – ") + + t("a change on one channel applies to the whole group. Name, routing and mix levels stay per channel. ") + + t("The link is stored in the DSP and also applies in the Thomann editor."))]; +} + +// ------------------------------------------------------------------ limiter calculator + +// Limiter threshold -> amplifier output power. Chain: DSP output (threshold, referenced to `ref` dBu) +// × amplifier voltage gain, capped at the amplifier's clip voltage sqrt(P_rated × R). +const DBU_V = 0.7746; +const OHMS = [2, 4, 6, 8, 16]; +const limKey = (devId, o) => `${devId}:${o}`; +const limRef = devId => S.lim.ref[devId] ?? 0; +const fmtW = w => w >= 1000 ? (w / 1000).toFixed(w >= 10000 ? 1 : 2) + " kW" : Math.round(w) + " W"; + +// Rated power at any impedance from the 2/4/8 Ω datasheet values (0 = not rated that low) +function ampRated(a, ohm) { + const pts = [[2, a.p2], [4, a.p4], [8, a.p8]].filter(p => p[1] > 0); + if (!pts.length) return 0; + const hit = pts.find(p => p[0] === ohm); + if (hit) return hit[1]; + const lo = [...pts].reverse().find(p => p[0] < ohm), hi = pts.find(p => p[0] > ohm); + if (lo && hi) return lo[1] + (hi[1] - lo[1]) * (ohm - lo[0]) / (hi[0] - lo[0]); + if (lo) return lo[1] * lo[0] / ohm; // above the highest rating: same clip voltage + return 0; +} +// Linear voltage gain: from the gain in dB, or rated output voltage / input sensitivity +function ampGain(a) { + if (a.mode === "gain") return Math.pow(10, a.gain / 20); + const [r, p] = a.p8 ? [8, a.p8] : a.p4 ? [4, a.p4] : [2, a.p2]; + return p && a.sens ? Math.sqrt(p * r) / a.sens : 0; +} + +function limCalc(devId, o, thrRaw) { + const as = S.lim.assign[limKey(devId, o)]; + const amp = as && S.lim.amps.find(a => a.id === as.amp); + if (!amp) return null; + const vin = DBU_V * Math.pow(10, ((thrRaw - 180) / 2 + limRef(devId)) / 20); + const g = ampGain(amp), rated = ampRated(amp, as.ohm); + const vout = vin * g, vmax = Math.sqrt(rated * as.ohm); + const p = rated ? Math.min(vout, vmax) ** 2 / as.ohm : vout ** 2 / as.ohm; + return { amp, as, p, rated, g, over: rated ? 20 * Math.log10(vout / vmax) : 0 }; +} +// Threshold (raw) that limits to `watts` at the assigned speaker +function limThreshFor(devId, o, watts) { + const c = limCalc(devId, o, 180); + if (!c || !c.g || watts <= 0) return null; + const db = 20 * Math.log10(Math.sqrt(watts * c.as.ohm) / c.g / DBU_V) - limRef(devId); + return clamp(Math.floor(db * 2 + 1e-9) + 180, 0, 220); // round down: never above the target +} + +async function saveLim(next) { + S.lim = next; + try { S.lim = await api("PUT", "/api/limiter", next); } catch (e) { toast(t("Error: ") + e.message); } +} +const limCopy = () => JSON.parse(JSON.stringify(S.lim)); + +async function ampDialog(amp) { + const isNew = !amp; + amp = amp || { name: "", mode: "sens", sens: 1.4, gain: 32, p8: 0, p4: 0, p2: 0 }; + const numIn = (v, ph) => h("input", { type: "text", inputmode: "decimal", value: v || "", placeholder: ph, autocomplete: "off" }); + const f = { name: h("input", { type: "text", value: amp.name, placeholder: t("e.g. Crown XLS 1502"), maxlength: 40 }), + p8: numIn(amp.p8, "W"), p4: numIn(amp.p4, "W"), p2: numIn(amp.p2, "W"), + sens: numIn(amp.sens, t("e.g. 1.4")), gain: numIn(amp.gain, t("e.g. 32")) }; + let mode = amp.mode; + const modeBtns = h("div", { class: "seg" }); + const sensRow = h("label", {}, t("Input sensitivity (V RMS)"), f.sens); + const gainRow = h("label", {}, t("Gain (dB)"), f.gain); + const setMode = m => { + mode = m; + modeBtns.replaceChildren(...[["sens", t("Sensitivity")], ["gain", t("Gain")]].map(([k, label]) => + h("button", { class: k === mode ? "on" : "", onclick: () => setMode(k) }, label))); + sensRow.hidden = mode !== "sens"; gainRow.hidden = mode !== "gain"; + }; + setMode(mode); + const err = h("div", { class: "err full" }); + const v = await modal({ + title: isNew ? t("New amplifier") : t("Edit amplifier"), + body: h("div", { class: "devform ampform" }, + h("label", { class: "full" }, "Name", f.name), + h("div", { class: "full sub" }, t("Rated RMS power per channel (datasheet, empty = not specified)")), + h("label", {}, t("into 8 Ω"), f.p8), h("label", {}, t("into 4 Ω"), f.p4), h("label", {}, t("into 2 Ω"), f.p2), + h("div", { class: "full sub" }, t("Input")), h("div", { class: "full" }, modeBtns), + h("div", { class: "full" }, sensRow, gainRow), + h("p", { class: "info full" }, t("Sensitivity = input voltage for full power (e.g. 0.775 V or 1.4 V). "), + t("If the amplifier has a gain control, the value applies with it turned fully up.")), + err), + actions: [{ label: t("Cancel") }, { label: t("Save"), primary: true, value: () => { + const n = k => Math.max(0, num(f[k].value) || 0); + const r = { id: amp.id, name: f.name.value.trim() || t("Amplifier"), mode, sens: n("sens"), gain: n("gain"), + p8: n("p8"), p4: n("p4"), p2: n("p2") }; + if (!r.p8 && !r.p4 && !r.p2) { err.textContent = t("At least one power rating is missing."); return undefined; } + if (mode === "sens" && !r.sens) { err.textContent = t("Sensitivity is missing."); return undefined; } + return r; + } }], + }); + if (!v) return null; + const next = limCopy(); + if (isNew) { v.id = Math.random().toString(36).slice(2, 10); next.amps.push(v); } + else next.amps[next.amps.findIndex(a => a.id === v.id)] = v; + await saveLim(next); + render(); + return v.id; +} + +function ampCard(a) { + const used = Object.entries(S.lim.assign).filter(([, v]) => v.amp === a.id).map(([k]) => { + const [devId, o] = k.split(":"); const d = S.devices[devId]; + return (d ? d.name + " " : "") + chLabel("out", +o); + }); + const specs = [[8, a.p8], [4, a.p4], [2, a.p2]].filter(p => p[1]).map(([r, p]) => `${fmtW(p)} @ ${r} Ω`).join(" · "); + return h("div", { class: "card amp" }, + h("h3", {}, h("span", { class: "grow" }, a.name), + h("button", { class: "icon small", "aria-label": t("Edit"), title: t("Edit"), onclick: () => ampDialog(a) }, svgIcon(ICON.edit))), + h("div", { class: "ampspec" }, specs), + h("div", { class: "info" }, a.mode === "gain" ? t("Gain {v} dB", { v: a.gain }) : t("Sensitivity {v} V", { v: a.sens }), + ` (≙ ${(20 * Math.log10(ampGain(a) || 1)).toFixed(1)} dB Gain)`), + h("div", { class: "info" }, used.length ? t("Used by: ") + used.join(", ") : t("Not assigned to any output")), + h("div", { class: "actions" }, h("button", { class: "danger small", onclick: async () => { + if (!await askConfirm(t("Delete amplifier"), t("Delete {name}?", { name: q(a.name) }) + (used.length ? " " + t("Its assignments will be removed.") : ""), t("Delete"), true)) return; + const next = limCopy(); + next.amps = next.amps.filter(x => x.id !== a.id); + for (const k of Object.keys(next.assign)) if (next.assign[k].amp === a.id) delete next.assign[k]; + await saveLim(next); render(); + } }, t("Delete")))); +} + +// Live result box; returns [element, update(thrRaw)] +function limResult(d, o) { + const big = h("div", { class: "lw" }), sub = h("div", { class: "lsub" }); + const bar = h("div", { class: "lbar" }, h("i"), h("b")); + const notes = h("div", { class: "lnotes" }); + const box = h("div", { class: "lres" }, big, sub, bar, notes); + const update = raw => { + const c = limCalc(d.id, o, raw); + if (!c) { box.className = "lres none"; big.textContent = "—"; sub.textContent = t("No amplifier assigned"); notes.replaceChildren(); return; } + const spk = c.as.spk, top = Math.max(c.rated, spk, c.p) || 1; + big.replaceChildren(fmtW(c.p), h("small", {}, ` RMS @ ${c.as.ohm} Ω`)); + sub.textContent = c.rated ? t("{pct} % of {rated}", { pct: Math.round(c.p / c.rated * 100), rated: fmtW(c.rated) }) + " · " + c.amp.name : c.amp.name; + bar.style.cssText = `--p:${Math.min(1, c.p / top)};--a:${c.rated ? c.rated / top : 0};--s:${spk ? spk / top : 0}`; + bar.classList.toggle("hasspk", !!spk); + const n = []; + let lvl = "ok"; + if (!c.rated) { n.push(["bad", t("Amplifier is not rated for {ohm} Ω", { ohm: c.as.ohm })]); lvl = "bad"; } + else if (c.over > 0.05) { n.push(["bad", t("Amplifier clips – the limiter engages {db} dB too late", { db: c.over.toFixed(1) })]); lvl = "bad"; } + else n.push(["ok", t("{db} dB headroom to amplifier clipping", { db: Math.max(0, -c.over).toFixed(1) })]); + if (spk && c.p > spk * 1.01) { n.push(["warn", t("{pct} % of the speaker rating ({w} RMS)", { pct: Math.round(c.p / spk * 100), w: fmtW(spk) })]); if (lvl === "ok") lvl = "warn"; } + else if (spk) n.push(["ok", t("Speaker at {pct} % of its rating ({w} RMS)", { pct: Math.round(c.p / spk * 100), w: fmtW(spk) })]); + box.className = "lres " + lvl; + notes.replaceChildren(...n.map(([cls, text]) => h("div", { class: cls }, text))); + }; + return [box, update]; +} + +function limiterCard(d, o) { + const oc = chans(d, "out")[o], key = limKey(d.id, o); + const as = S.lim.assign[key]; + const [res, update] = limResult(d, o); + const setAssign = async patch => { + const next = limCopy(); + if (patch === null) delete next.assign[key]; + else next.assign[key] = { ohm: 8, spk: 0, ...(next.assign[key] || {}), ...patch }; + await saveLim(next); render(); + }; + const ampSel = h("select", { "aria-label": t("Amplifier"), onchange: async () => { + if (ampSel.value === "+") { const id = await ampDialog(null); if (id) setAssign({ amp: id }); else render(); } + else setAssign(ampSel.value ? { amp: ampSel.value } : null); + } }, h("option", { value: "" }, t("— no amplifier —")), + S.lim.amps.map(a => h("option", { value: a.id, selected: as && as.amp === a.id }, a.name)), + h("option", { value: "+" }, t("+ New amplifier…"))); + const ohmSel = h("select", { "aria-label": t("Impedance"), disabled: !as, onchange: () => setAssign({ ohm: +ohmSel.value }) }, + OHMS.map(r => h("option", { value: r, selected: (as ? as.ohm : 8) === r }, r + " Ω"))); + const spkIn = h("input", { type: "text", inputmode: "decimal", value: as && as.spk ? as.spk : "", placeholder: "optional", + disabled: !as, "aria-label": t("Speaker RMS"), onchange: () => setAssign({ spk: Math.max(0, num(spkIn.value) || 0) }) }); + + const target = h("input", { type: "text", inputmode: "decimal", placeholder: t("Watts"), "aria-label": t("Target power"), autocomplete: "off" }); + const apply = w => { + const raw = limThreshFor(d.id, o, w); + if (raw == null) return toast(t("Assign an amplifier first")); + setParam("out", o, "limit.threshold", raw); + target.value = ""; + target.blur(); + const hitEdge = raw === 0 || raw === 220; + toast(`Threshold ${sign((raw - 180) / 2)} dB → ${fmtW(limCalc(d.id, o, raw).p)}` + (hitEdge ? t(" (end of range reached)") : "")); + render(); + }; + const c0 = as ? limCalc(d.id, o, 180) : null; + const ampSafe = c0 && c0.rated ? c0.rated * Math.pow(10, -1 / 10) : 0; // 1 dB below amp clipping + const chips = c0 ? [ + c0.as.spk ? h("button", { class: "chip", onclick: () => apply(c0.as.spk) }, t("Speaker ") + fmtW(c0.as.spk)) : null, + ampSafe ? h("button", { class: "chip", onclick: () => apply(ampSafe) }, t("Amplifier −1 dB")) : null, + ampSafe && c0.as.spk ? h("button", { class: "chip", onclick: () => apply(Math.min(ampSafe, c0.as.spk)) }, t("Lower value")) : null, + ] : []; + + const card = h("div", { class: "card limcard" }, + h("h3", {}, h("span", { class: "grow" }, chTitle(d, "out", o)), ledMeter(d.id, "out", o, "h"), + h("button", { class: "small", onclick: () => openChannel("out", o) }, t("Channel"))), + res, + h("div", { class: "limgrid" }, + h("label", { class: "full" }, t("Amplifier"), ampSel), + h("label", {}, t("Load on channel"), ohmSel), + h("label", {}, t("Speaker RMS (W)"), spkIn)), + paramSlider("Threshold", "out", o, "limit.threshold", "thresh", update), + as ? h("div", { class: "target" }, + h("div", { class: "row" }, h("span", { class: "sub" }, t("Limit to")), target, + h("button", { class: "on", onclick: () => { const w = num(target.value); if (w > 0) apply(w); else target.focus(); } }, t("Set"))), + chips.filter(Boolean).length ? h("div", { class: "chips" }, chips) : null) : null, + timingBox(d, o)); + update(oc.limit.threshold); + return card; +} + +// Limiter timing presets per band. Rule of thumb: attack ≈ one period of the lowest frequency +// the way passes (faster distorts the waveform), release ≈ 16 × attack (slower pumps less). +// Infra/Sub/Hochton follow the MC2 Delta "auto" table and Dolby SLS LF settings (16 ms / 256 ms). +const LIM_PRESETS = [ + { id: "infra", name: "Infra", range: "< 31 Hz", a: 45, r: 720, k: 3 }, + { id: "sub", name: "Sub", range: "31–63 Hz", a: 16, r: 256, k: 2 }, + { id: "kick", name: "Kick", range: "63–250 Hz", a: 10, r: 160, k: 2 }, + { id: "mid", name: t("Mids"), range: "250 Hz–2 kHz", a: 4, r: 64, k: 1 }, + { id: "high", name: t("Highs"), range: "> 2 kHz", a: 1, r: 16, k: 0 }, + { id: "full", name: "Fullrange", range: t("no crossover"), a: 8, r: 120, k: 2 }, +]; +// Band preset picked by the channel's high-pass, i.e. its lowest frequency (20 Hz when it has none) +const AUTO_BANDS = [[31, "infra"], [63, "sub"], [250, "kick"], [2000, "mid"], [Infinity, "high"]]; +function autoPreset(ch) { + const f = ch.hp.slope ? freqHz(ch.hp.freq) : 20; + const band = AUTO_BANDS.find(([upTo]) => f < upTo)[1]; + const p = LIM_PRESETS.find(x => x.id === band); + return { ...p, id: "auto", name: "Auto", range: `${ch.hp.slope ? "HP" : t("no HP")} ${fmtHzShort(f)} → ${p.name}` }; +} + +const limOpen = new Set(); +function timingBox(d, o) { + const lim = chans(d, "out")[o].limit, key = limKey(d.id, o); + const auto = autoPreset(chans(d, "out")[o]); + const isOn = p => lim.attack === p.a - 1 && lim.release === p.r - 1 && lim.knee === p.k; + const active = [auto, ...LIM_PRESETS].find(isOn); + const set = p => { + setParam("out", o, "limit.attack", p.a - 1); + setParam("out", o, "limit.release", p.r - 1); + setParam("out", o, "limit.knee", p.k); + toast(`${p.name}: Attack ${p.a} ms · Release ${p.r} ms · Knee ${p.k} dB`); + render(); + }; + const chip = p => h("button", { class: "chip preset" + (isOn(p) ? " on" : ""), title: `${p.a} / ${p.r} ms · Knee ${p.k} dB`, onclick: () => set(p) }, + h("b", {}, p.name), h("small", {}, p.range)); + const box = h("details", { class: "more", open: limOpen.has(key), + ontoggle: () => box.open ? limOpen.add(key) : limOpen.delete(key) }, + h("summary", {}, `Attack ${lim.attack + 1} ms · Release ${lim.release + 1} ms · Knee ${lim.knee} dB`, + active ? h("span", { class: "tag" }, active.name) : null), + h("div", { class: "chips presets" }, chip(auto), LIM_PRESETS.map(chip)), + paramSlider("Attack", "out", o, "limit.attack", "attack"), + paramSlider("Release", "out", o, "limit.release", "release"), + paramSlider("Knee", "out", o, "limit.knee", "knee"), + h("p", { class: "info" }, t("Rule of thumb: attack ≈ one period of the lowest frequency (faster distorts the bass), "), + t("release ≈ 16 × attack (shorter pumps). “Auto” picks the band preset matching this channel’s high-pass."))); + return box; +} + +function refCard(d) { + const inp = h("input", { type: "text", inputmode: "decimal", value: limRef(d.id), "aria-label": t("Reference level in dBu"), class: "short", + onchange: async () => { const next = limCopy(); next.ref[d.id] = clamp(num(inp.value) || 0, -20, 30); await saveLim(next); render(); } }); + return h("div", { class: "card" }, h("h3", {}, t("Reference level · ") + d.name), + h("div", { class: "row" }, h("span", { class: "grow" }, t("Limiter 0 dB equals at the output")), inp, h("span", {}, "dBu")), + h("p", { class: "info" }, t("Thomann does not specify the reference level – 0 dBu (0.775 V) is assumed. To measure: feed a 1 kHz sine, "), + t("set the threshold to 0 dB, turn up until the limiter engages and measure the output voltage with a multimeter (AC). "), + t("dBu = 20 · log₁₀(U / 0.775 V)."))); +} + +function viewLimiter(d) { + return [ + h("div", { class: "cards" }, chans(d, "out").map((_, o) => limiterCard(d, o))), + h("p", { class: "info" }, t("Shown is the continuous sine power (RMS) once the limiter engages – music is well below that on average. "), + t("Assumes the amplifier’s gain control turned fully up (or as entered).")), + h("h2", { class: "section" }, t("Amplifiers")), + h("div", { class: "cards" }, S.lim.amps.map(ampCard), + h("button", { class: "card addcard", onclick: () => ampDialog(null) }, t("+ Add amplifier"))), + h("h2", { class: "section" }, t("Calibration")), + h("div", { class: "cards" }, refCard(d)), + ]; +} + +// ------------------------------------------------------------------ settings + +function deviceForm(d) { + const isNew = !d; + d = d || { name: "", host: "", port: 9761, model: "auto", addr: 1, autoconnect: true, transport: "tcp", usb: "" }; + const f = { + name: h("input", { type: "text", value: d.name, placeholder: t("e.g. DSP 204 stage") }), + host: h("input", { type: "text", value: d.host, placeholder: "192.168.1.101", inputmode: "decimal" }), + port: h("input", { type: "number", value: d.port }), + model: h("select", {}, [["auto", t("Automatic")], ["204", "DSP 204"], ["408", "DSP 408"]] + .map(([v, label]) => h("option", { value: v, selected: d.model === v }, label))), + autoconnect: h("input", { type: "checkbox", checked: d.autoconnect }), + usb: h("select", { "aria-label": t("USB device") }), + }; + let transport = d.transport || "tcp"; + // USB device list (both DSP models share one USB ID, so several are told apart by port/path) + const fillUsb = list => { + const opts = [["", list.length ? t("First device found") : t("No DSP found via USB")], + ...list.map((u, i) => [u.path, `${u.product || "DSP"} #${i + 1}${u.serial ? " · " + u.serial : ""}`])]; + if (d.usb && !list.some(u => u.path === d.usb)) opts.push([d.usb, t("Saved device (not plugged in)")]); + f.usb.replaceChildren(...opts.map(([v, label]) => h("option", { value: v, selected: v === (d.usb || "") }, label))); + }; + const loadUsb = () => api("GET", "/api/usb").then(fillUsb).catch(() => fillUsb([])); + fillUsb([]); + const netRows = [h("label", {}, t("IP address"), f.host), h("label", {}, "Port", f.port)]; + const usbRow = h("label", { class: "full" }, t("USB device"), + h("div", { class: "row" }, f.usb, h("button", { class: "small", type: "button", onclick: loadUsb, title: t("Search again") }, "↻"))); + const seg = h("div", { class: "seg full" }); + // existing device: the connection type and USB device are saved right away, so t("Connect") uses them + const saveConn = () => isNew || api("PUT", `/api/devices/${d.id}`, { transport, usb: f.usb.value }).catch(e => toast(e.message)); + f.usb.addEventListener("change", saveConn); + const setTransport = (mode, save) => { + transport = mode; + if (save && mode !== (d.transport || "tcp")) saveConn(); + seg.replaceChildren(...[["tcp", t("Network")], ["usb", t("USB cable")]].map(([k, label]) => + h("button", { type: "button", class: k === mode ? "on" : "", onclick: () => setTransport(k, true) }, label))); + netRows.forEach(r => (r.hidden = mode === "usb")); + usbRow.hidden = mode !== "usb"; + if (mode === "usb") loadUsb(); + }; + setTransport(transport); + const values = () => ({ name: f.name.value.trim() || (transport === "usb" ? "DSP (USB)" : f.host.value.trim()), + host: f.host.value.trim(), port: +f.port.value || 9761, model: f.model.value, autoconnect: f.autoconnect.checked, + transport, usb: f.usb.value }); + const actions = isNew + ? [h("button", { class: "on", onclick: async () => { + if (transport === "tcp" && !values().host) return toast(t("IP address missing")); + try { const nd = await api("POST", "/api/devices", values()); S.cur = nd.id; toast(t("Added")); } + catch (e) { toast(e.message); } + } }, t("Add"))] + : [ + h("button", { onclick: async () => { try { await api("PUT", `/api/devices/${d.id}`, values()); toast(t("Saved")); } catch (e) { toast(e.message); } } }, t("Save")), + d.status === "disconnected" || d.status === "error" + ? h("button", { class: "on", onclick: async () => { // connects with what the form shows, saved or not + try { await api("PUT", `/api/devices/${d.id}`, values()); await api("POST", `/api/devices/${d.id}/connect`); } + catch (e) { toast(e.message); } + } }, t("Connect")) + : h("button", { onclick: () => api("POST", `/api/devices/${d.id}/disconnect`).catch(e => toast(e.message)) }, t("Disconnect")), + h("button", { class: "danger", onclick: async () => { + if (await askConfirm(t("Remove device"), t("Remove {name} from the list?", { name: q(d.name) }), t("Remove"), true)) + await api("DELETE", `/api/devices/${d.id}`).catch(e => toast(e.message)); + } }, t("Remove")), + ]; + return h("div", { class: "card" }, + h("h3", {}, isNew ? null : h("span", { class: "dot " + d.status }), h("span", { class: "grow" }, isNew ? t("New device") : d.name), + isNew ? null : h("span", { class: "info" }, STATUS_TEXT[d.status])), + !isNew && d.info ? h("div", { class: "info" }, t("Device reports: ") + d.info) : null, + !isNew && d.error ? h("div", { class: "err" }, trMsg(d.error)) : null, + h("div", { class: "devform" }, + h("label", { class: "full" }, "Name", f.name), + h("div", { class: "full sub" }, t("Connection")), seg, + ...netRows, usbRow, + h("label", {}, t("Model"), f.model), + h("label", { class: "chk" }, f.autoconnect, t("Connect automatically")), + h("div", { class: "actions" }, actions))); +} + +// App settings backup: devices, amplifiers/limiter data, PIN, remote access (not the DSP presets) +function backupCard() { + const exportCfg = async () => { + try { if (await saveFile(`DSP-Control-${t("Settings")}_${today()}.json`, await api("GET", "/api/backup"))) toast(t("Settings backed up")); } + catch (e) { toast(t("Error: ") + e.message); } + }; + const restore = async () => { + try { + const f = await openFile(); + if (!f) return; + const doc = f.json; + if (!doc || doc.format !== "dsp-control-config") return toast(t("Not a DSP Control settings backup")); + const when = doc.exported ? doc.exported.replace("T", " ").slice(0, 16) : "?"; + const pin = h("input", { type: "password", inputmode: "numeric", maxlength: 4, autocomplete: "off", placeholder: "••••" }); + const ok = await modal({ title: t("Restore settings"), + body: h("div", { class: "form" }, + h("p", { class: "dlg-text" }, t("Devices ({n}), amplifier and limiter data, PIN and remote access will be replaced by the " + + "backup from {when}. The presets inside the DSPs stay unchanged.", { n: (doc.devices || []).length, when })), + S.isApp ? null : h("label", {}, t("Current PIN"), pin)), + actions: [{ label: t("Cancel") }, { label: t("Restore"), primary: true, value: () => true }] }); + if (!ok) return; + await api("POST", "/api/backup", { doc, pin: pin.value }); + toast(t("Settings restored")); + setTimeout(() => location.reload(), 800); + } catch (e) { toast(t("Error: ") + e.message); } + }; + return h("div", { class: "card" }, h("h3", {}, t("App settings")), + h("p", { class: "info" }, t("Saves devices, amplifiers & limiter calculator, PIN and remote access to a file. ") + + t("The settings inside the DSPs are saved per device via “File…” at the top.")), + h("div", { class: "row" }, h("button", { onclick: exportCfg }, t("Back up…")), h("button", { onclick: restore }, t("Restore…")))); +} + +// Desktop app only: let phones/tablets on the LAN use this PC as server (they need the PIN) +function remoteCard() { + const r = S.remote || { enabled: false, port: 8080, urls: [] }; + const port = h("input", { type: "number", min: 1, max: 65535, value: r.port, class: "short", "aria-label": "Port" }); + const put = async body => { + try { S.remote = await api("PUT", "/api/remote", body); } catch (e) { toast(e.message); } + render(); + }; + const sw = h("button", { class: r.enabled ? "on" : "", "aria-pressed": String(r.enabled), onclick: () => put({ enabled: !r.enabled, port: +port.value || 8080 }) }, + r.enabled ? t("On") : t("Off")); + let status; + if (r.error) status = h("div", { class: "err" }, trMsg(r.error)); + else if (r.running) status = h("div", { class: "remote-urls" }, h("div", { class: "info" }, t("Open on a phone in the same Wi-Fi:")), + r.urls.length ? r.urls.map(u => h("code", {}, u)) : h("code", {}, `http://<${t("IP of this computer")}>:${r.port}`)); + else status = h("p", { class: "info" }, t("Off – only this window has access.")); + return h("div", { class: "card" }, h("h3", {}, h("span", { class: "dot " + (r.running ? "online" : r.error ? "error" : "disconnected") }), + h("span", { class: "grow" }, t("Remote access (web server)"))), + h("div", { class: "row" }, h("span", { class: "grow" }, t("Allow phones & tablets")), sw), + h("div", { class: "row" }, h("span", { class: "grow" }, "Port"), port, + h("button", { class: "small", onclick: () => put({ port: +port.value || 8080 }) }, t("Apply"))), + status, + h("p", { class: "info" }, t("Other devices log in with the PIN (changeable below). Only runs while this app is open. "), + r.platform === "darwin" + ? t("If the macOS firewall is on, it asks the first time – choose “Allow”.") + : t("The first time, Windows Firewall asks – choose “Allow” for private networks."))); +} + +function pinCard() { + const pin = ph => h("input", { type: "password", inputmode: "numeric", pattern: "[0-9]*", maxlength: 4, autocomplete: "off", placeholder: ph }); + const cur = pin("••••"), nw = pin("••••"), rep = pin("••••"); + const err = h("div", { class: "err" }); + return h("div", { class: "card" }, h("h3", {}, S.isApp ? t("PIN for remote access") : t("Access (PIN)")), + h("div", { class: "devform" }, + S.isApp ? null : h("label", { class: "full" }, t("Current PIN"), cur), + h("label", {}, t("New PIN"), nw), h("label", {}, t("Repeat"), rep), + err, + h("div", { class: "actions" }, + h("button", { class: "on", onclick: async () => { + err.textContent = ""; + if (!/^\d{4}$/.test(nw.value)) return (err.textContent = t("The new PIN must be 4 digits.")); + if (nw.value !== rep.value) return (err.textContent = t("The new PINs do not match.")); + try { + await api("POST", "/api/pin", { current: cur.value, new: nw.value }); + cur.value = nw.value = rep.value = ""; toast(t("PIN changed – other devices were logged out")); + } catch (e) { err.textContent = e.message; } + } }, t("Change PIN")), + S.isApp ? null : h("button", { onclick: logout }, svgIcon(ICON.logout), t(" Log out")))), + h("p", { class: "info" }, S.isApp + ? t("This app needs no PIN. The default is 1234; changing it logs out all phones.") + : t("The default PIN is 1234. After changing it only this device stays logged in."))); +} + +// Language per device (stored in the browser); the desktop app also tells the server, for its own dialogs +function langCard() { + const set = async lang => { + if (lang === LANG) return; + store.set("dsp.lang", lang); + if (S.isApp) await api("PUT", "/api/lang", { lang }).catch(() => {}); + location.reload(); + }; + return h("div", { class: "card" }, h("h3", {}, "Language / Sprache"), + h("div", { class: "seg" }, Object.entries(LANGS).map(([k, label]) => + h("button", { class: k === LANG ? "on" : "", "aria-pressed": String(k === LANG), "data-view-ok": "", onclick: () => set(k) }, label)))); +} + +function viewSettings() { + return [ + h("div", { class: "cards" }, langCard()), + h("h2", { class: "section" }, t("Devices")), + h("div", { class: "cards" }, ...S.order.map(id => deviceForm(S.devices[id])), deviceForm(null)), + h("p", { class: "info" }, t("Both DSPs can be connected at the same time – switch between them at the top. "), + t("The DSPs accept only one connection: close the Thomann editor first.")), + h("h2", { class: "section" }, S.isApp ? t("Remote access") : t("Security")), + h("div", { class: "cards" }, S.isApp ? remoteCard() : null, pinCard()), + h("h2", { class: "section" }, t("Backup")), + h("div", { class: "cards" }, backupCard()), + ]; +} + +// ------------------------------------------------------------------ render + +const H_SCROLL = ".mixer, .bands, .geq, .routing"; +function render() { + if (S.busy) { S.dirty = true; return; } + if ($("#app").hidden) return; + if (!S.devices[S.cur]) S.cur = S.order[0] || null; + // keep focus on a text field (e.g. while typing a device name) – re-rendering would steal it + const ae = document.activeElement; + if (ae && main.contains(ae) && ae.matches("input[type=text], input[type=number], input[type=password]")) { S.dirty = true; return; } + renderTabs(); + renderStatus(); + const y = window.scrollY; + // keep sideways scroll positions (mixer on a phone, EQ bands …) while the view stays the same + const viewKey = `${S.cur}|${S.settings}|${S.view}|${S.sel.kind}|${S.sel.idx}`; + const xs = viewKey === render.viewKey ? [...main.querySelectorAll(H_SCROLL)].map(e => e.scrollLeft) : []; + render.viewKey = viewKey; + live.clear(); + let content; + const d = dev(); + document.body.dataset.view = S.settings || !d ? "settings" : S.view; + if (S.settings || !d) content = viewSettings(); + else if (d.status !== "online" || !d.state) + content = h("div", { class: "empty" }, h("div", { class: "spinner" + (["loading", "connecting"].includes(d.status) ? "" : " off") }), + d.status === "loading" ? t("Loading the configuration from the DSP…") + : d.status === "connecting" ? t("Connecting to {where}…", { where: where(d) }) : t("Not connected.")); + else content = ({ mixer: viewMixer, channel: viewChannel, routing: viewRouting, link: viewLink, limiter: viewLimiter }[S.view] || viewMixer)(d); + main.replaceChildren(...[content].flat().filter(Boolean)); + main.querySelectorAll(H_SCROLL).forEach((e, i) => { if (xs[i]) e.scrollLeft = xs[i]; }); + window.scrollTo(0, y); + collectMeters(); +} +// flush deferred renders once a text field loses focus +main.addEventListener("focusout", () => setTimeout(() => { + if (S.dirty && !S.busy && !main.contains(document.activeElement)) { S.dirty = false; render(); } +}, 0)); + +document.querySelectorAll("#viewtabs button").forEach(b => b.addEventListener("click", () => { + S.view = b.dataset.view; S.settings = false; store.set("dsp.view", S.view); render(); window.scrollTo(0, 0); +})); +$("#btn-settings").addEventListener("click", () => { S.settings = !S.settings; render(); window.scrollTo(0, 0); }); + +// header / status bar heights -> CSS vars (sticky channel bar, fader height that fits the screen) +new ResizeObserver(() => { + document.documentElement.style.setProperty("--hdr", $("#top").offsetHeight + "px"); + document.documentElement.style.setProperty("--sb", $("#statusbar").offsetHeight + "px"); +}).observe($("#top")); +new ResizeObserver(() => document.documentElement.style.setProperty("--sb", $("#statusbar").offsetHeight + "px")).observe($("#statusbar")); + +// ------------------------------------------------------------------ lock (desktop app window: look, don't touch) + +function showLock() { + const b = $("#btn-lock"); + b.hidden = !S.isApp; + document.body.classList.toggle("locked", !!S.locked); + b.classList.toggle("on", !!S.locked); + b.title = S.locked ? t("Locked – click to unlock") : t("Lock (view only)"); + b.setAttribute("aria-label", b.title); + b.replaceChildren(...[svgIcon(S.locked ? ICON.lock : ICON.unlock), S.locked ? h("span", {}, t("Locked")) : null].filter(Boolean)); +} + +$("#btn-lock").addEventListener("click", async () => { + if (!S.locked) { + try { await api("POST", "/api/lock"); S.locked = true; showLock(); render(); toast(t("Locked – values are view-only")); } + catch (e) { toast(t("Error: ") + e.message); } + return; + } + const pin = h("input", { type: "password", inputmode: "numeric", maxlength: 4, autocomplete: "off", placeholder: "••••", "aria-label": "PIN" }); + const err = h("div", { class: "err" }); + await modal({ title: t("Unlock"), body: h("div", { class: "form" }, h("label", {}, t("PIN (same as on the phone)"), pin), err), + actions: [{ label: t("Cancel") }, { label: t("Unlock"), primary: true, value: () => { + api("POST", "/api/unlock", { pin: pin.value }).then(() => { + S.locked = false; showLock(); render(); toast(t("Unlocked")); + $("#modal .dlg-actions button").click(); // close the dialog + }).catch(e => { + err.textContent = e.message === "locked" ? t("Too many attempts – please wait a moment") : t("Wrong PIN"); + pin.value = ""; pin.focus(); + }); + return undefined; // keep the dialog open until the PIN is confirmed + } }] }); +}); + +// While locked, everything that would change a value is swallowed; navigating and looking still works. +const VIEW_OK = ".chsel, .nav, .strip-head, .xout, .band, [data-view-ok]"; +for (const type of ["pointerdown", "mousedown", "click", "dblclick", "keydown", "wheel"]) { + document.addEventListener(type, e => { + if (!S.locked || !(e.target instanceof Element)) return; + const tgt = e.target; + if (!tgt.closest("#main, #statusbar") || tgt.closest(VIEW_OK)) return; + if (type === "wheel" && !tgt.closest(".fader, input, select")) return; // page scrolling stays + if (type === "keydown" && !tgt.closest("button, input, select, textarea, .fader, [tabindex]")) return; + if (type === "pointerdown" && !tgt.closest("button, input, select, textarea, .fader, canvas, a")) return; + e.preventDefault(); e.stopPropagation(); + if (type === "click" && Date.now() - (S.lockToast || 0) > 1500) { S.lockToast = Date.now(); toast(t("Locked – unlock at the top right to make changes")); } + }, { capture: true, passive: false }); +} + +// ------------------------------------------------------------------ live events + +function setDevices(list) { + S.devices = {}; S.order = []; + for (const d of list) { S.devices[d.id] = d; S.order.push(d.id); } +} + +function connectEvents() { + if (S.es) S.es.close(); + const es = S.es = new EventSource("/api/events"); + es.onmessage = m => { + const ev = JSON.parse(m.data); + switch (ev.type) { + case "hello": + setDevices(ev.devices); + if (ev.limiter) S.lim = ev.limiter; + if (!S.order.length) S.settings = true; + render(); break; + case "device": + if (!S.devices[ev.device]) S.order.push(ev.device); + S.devices[ev.device] = ev.data; + render(); break; + case "removed": + delete S.devices[ev.device]; S.order = S.order.filter(id => id !== ev.device); + render(); break; + case "status": { + const d = S.devices[ev.device]; + if (!d) break; + Object.assign(d, { status: ev.status, error: ev.error, info: ev.info }); + if (ev.status !== "online") render(); else renderTabs(); + break; + } + case "param": { + const d = S.devices[ev.device]; + if (!d || !d.state) break; + const ch = chans(d, ev.kind)[ev.idx]; + if (Date.now() - (recentlySet.get(`${ev.device}|${ev.kind}|${ev.idx}|${ev.param}`) || 0) < 1500) break; // own echo + if (JSON.stringify(getPath(ch, ev.param)) === JSON.stringify(ev.value)) break; + setPath(ch, ev.param, ev.value); + showLive(`${ev.device}|${ev.kind}|${ev.idx}|${ev.param}`, ev.value); // even while a fader is held + if (ev.device === S.cur && !S.settings) render(); + break; + } + case "lock": + if (S.isApp) { S.locked = ev.locked; showLock(); render(); } + break; + case "meters": + updateMeters(ev); break; + case "limiter": + S.lim = ev.data; + if (!S.busy && (S.view === "limiter" || S.view === "channel")) render(); + break; + } + }; + es.onerror = async () => { + renderTabs(); + try { const a = await (await fetch("/api/auth")).json(); if (!a.authenticated) showLogin(); } catch { /* server down: EventSource retries */ } + }; +} + +// ------------------------------------------------------------------ login + +function showLogin() { + if (S.es) { S.es.close(); S.es = null; } + $("#app").hidden = true; + $("#modal").hidden = true; + const root = $("#login"); + if (!root.hidden) return; + let pin = "", busy = false, lockT = null; + const dots = h("div", { class: "pindots" }, [0, 1, 2, 3].map(() => h("i"))); + const msg = h("div", { class: "pinmsg" }, " "); + const paint = () => [...dots.children].forEach((d, i) => d.classList.toggle("on", i < pin.length)); + const lock = secs => { + clearInterval(lockT); busy = true; + const end = Date.now() + secs * 1000; + const tick = () => { + const left = Math.ceil((end - Date.now()) / 1000); + if (left <= 0) { clearInterval(lockT); busy = false; msg.textContent = " "; pad.classList.remove("locked"); return; } + msg.textContent = t("Too many attempts – locked for {s} s", { s: left }); + }; + pad.classList.add("locked"); tick(); lockT = setInterval(tick, 500); + }; + const submit = async () => { + busy = true; + try { + const r = await fetch("/api/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pin }) }); + const data = await r.json().catch(() => ({})); + if (r.ok) { root.hidden = true; root.replaceChildren(); clearInterval(lockT); startApp(); return; } + pin = ""; paint(); + dots.classList.remove("shake"); void dots.offsetWidth; dots.classList.add("shake"); + buzz(); + busy = false; + if (data.retry) lock(data.retry); + else msg.textContent = r.status === 401 ? (data.left ? t("Wrong PIN – {n} attempts left", { n: data.left }) : t("Wrong PIN")) : t("Error: ") + trMsg(data.error || r.status); + } catch { msg.textContent = t("Server not reachable"); pin = ""; paint(); busy = false; } + }; + const press = k => { + if (busy) return; + if (k === "del") pin = pin.slice(0, -1); + else if (pin.length < 4) pin += k; + paint(); + if (pin.length === 4) submit(); + }; + const key = (k, label) => h("button", { class: "pk" + (k === "del" ? " del" : ""), "aria-label": k === "del" ? t("Delete") : k, + onpointerdown: e => { e.preventDefault(); press(k); }, onclick: e => { if (e.detail === 0) press(k); } }, label ?? k); + const pad = h("div", { class: "pinpad" }, + ["1", "2", "3", "4", "5", "6", "7", "8", "9"].map(k => key(k)), h("span"), key("0"), key("del", "⌫")); + root.replaceChildren(h("div", { class: "loginbox" }, + h("div", { class: "logo" }, $(".brand svg").cloneNode(true)), + h("h1", {}, "DSP Control"), h("p", {}, t("Enter PIN")), dots, msg, pad)); + root.hidden = false; + root.onkeydown = null; + document.onkeydown = e => { + if (root.hidden) return; + if (/^\d$/.test(e.key)) press(e.key); + else if (e.key === "Backspace") press("del"); + }; +} + +async function logout() { + await fetch("/api/logout", { method: "POST" }).catch(() => {}); + showLogin(); +} + +async function startApp() { + $("#app").hidden = false; + try { + const a = await (await fetch("/api/auth")).json(); + S.isApp = !!a.app; + // desktop app: the language chosen there is kept by the server too (survives a reset web view) + if (S.isApp && a.lang && a.lang !== LANG) { + store.set("dsp.lang", a.lang); + if (store.get("dsp.lang") === a.lang) return location.reload(); + } + S.locked = !!a.locked; + showLock(); + if (S.isApp) S.remote = await api("GET", "/api/remote"); + } catch { /* plain web UI */ } + connectEvents(); +} + +(async function init() { + try { + const a = await (await fetch("/api/auth")).json(); + if (a.authenticated) startApp(); else showLogin(); + } catch { showLogin(); } +})(); diff --git a/static/i18n.js b/static/i18n.js new file mode 100644 index 0000000..abefc7e --- /dev/null +++ b/static/i18n.js @@ -0,0 +1,323 @@ +"use strict"; +// UI language. English is the default and the language of the source; DE holds the German texts. +// t("Text with {name}", { name }) translates and fills placeholders; trMsg() does the same for +// messages coming from the server or the DSP connection (some of which contain variable parts). +// Chosen per device under ⚙ → Language (stored in the browser); the desktop app also tells the server. + +const LANGS = { en: "English", de: "Deutsch" }; +const LANG = (() => { try { return localStorage.getItem("dsp.lang") === "de" ? "de" : "en"; } catch { return "en"; } })(); +const LOCALE = LANG === "de" ? "de-AT" : "en-GB"; + +const DE = { + " (end of range reached)": " (Bereichsende erreicht)", + " Log out": " Abmelden", + "+ Add amplifier": "+ Verstärker hinzufügen", + "+ New amplifier…": "+ Neuer Verstärker…", + "20 Hz … 20 kHz, e.g. 1.2k": "20 Hz … 20 kHz, z. B. 1.2k", + "A backup is made automatically before every import. Last backup: {last}.": "Vor jedem Import wird automatisch gesichert. Letzte Sicherung: {last}.", + "a change on one channel applies to the whole group. Name, routing and mix levels stay per channel. ": "eine Änderung an einem Kanal gilt für die ganze Gruppe. Name, Routing und Mix-Pegel bleiben je Kanal. ", + "Access (PIN)": "Zugang (PIN)", + "Add": "Hinzufügen", + "Added": "Hinzugefügt", + "All bands flat": "Alle Bänder flach", + "All flat": "Alle flach", + "Allow phones & tablets": "Handy & Tablet erlauben", + "Amplifier": "Verstärker", + "Amplifier clips – the limiter engages {db} dB too late": "Verstärker clippt – Limiter greift {db} dB zu spät", + "Amplifier is not rated for {ohm} Ω": "Verstärker ist für {ohm} Ω nicht spezifiziert", + "Amplifier −1 dB": "Verstärker −1 dB", + "Amplifiers": "Verstärker", + "App settings": "App-Einstellungen", + "Apply": "Übernehmen", + "Assign an amplifier first": "Erst Verstärker zuordnen", + "Assumes the amplifier’s gain control turned fully up (or as entered).": "Voraussetzung: Gain-Regler am Verstärker auf Rechtsanschlag (bzw. so wie eingetragen).", + "At least one power rating is missing.": "Mindestens eine Leistungsangabe fehlt.", + "Automatic": "Automatisch", + "Back up…": "Sichern…", + "Backup": "Sicherung", + "Both DSPs can be connected at the same time – switch between them at the top. ": "Beide DSPs können gleichzeitig verbunden sein – oben zwischen ihnen umschalten. ", + "Calibration": "Kalibrierung", + "Cancel": "Abbrechen", + "Change PIN": "PIN ändern", + "Channel": "Kanal", + "Channel name": "Kanalname", + "Choose channel": "Kanal wählen", + "Close": "Schließen", + "Compressor": "Kompressor", + "Connect": "Verbinden", + "Connect automatically": "Automatisch verbinden", + "Connecting to {where}…": "Verbinde mit {where}…", + "Connecting…": "Verbinde…", + "Connection": "Verbindung", + "connection closed": "Verbindung beendet", + "Current PIN": "Aktuelle PIN", + "Current PIN is wrong": "Aktuelle PIN ist falsch", + "dBu = 20 · log₁₀(U / 0.775 V).": "dBu = 20 · log₁₀(U / 0,775 V).", + "Decrease": "Verringern", + "Delete": "Löschen", + "Delete amplifier": "Verstärker löschen", + "Delete {name}?": "{name} löschen?", + "desktop app only": "nur in der Desktop-App", + "device not loaded": "Gerät nicht geladen", + "Device reports: ": "Gerät meldet: ", + "Devices": "Geräte", + "Devices ({n}), amplifier and limiter data, PIN and remote access will be replaced by the backup from {when}. The presets inside the DSPs stay unchanged.": "Geräte ({n}), Verstärker- und Limiter-Daten, PIN und Fernzugriff werden durch die Sicherung vom {when} ersetzt. Die Presets in den DSPs bleiben unverändert.", + "Disconnect": "Trennen", + "Disconnected": "Getrennt", + "Drag a fader by its knob · snaps at 0 dB · double-tap the knob = 0 dB · tap the dB value to type one · tap the name = edit channel": "Fader am Knopf ziehen · rastet bei 0 dB ein · Doppeltipp auf den Knopf = 0 dB · dB-Wert antippen zum Eintippen · Name antippen = Kanal bearbeiten", + "Drag the points in the curve · gain snaps at 0 dB": "Punkte in der Kurve ziehen · Gain rastet bei 0 dB ein", + "DSP closed the connection": "DSP hat die Verbindung beendet", + "DSP is not connected": "DSP ist nicht verbunden", + "DSP not responding": "DSP antwortet nicht", + "e.g. 1.4": "z. B. 1.4", + "e.g. 32": "z. B. 32", + "e.g. 4.0": "z. B. 4.0", + "e.g. Crown XLS 1502": "z. B. Crown XLS 1502", + "e.g. DSP 204 stage": "z. B. DSP 204 Bühne", + "Edit": "Bearbeiten", + "Edit amplifier": "Verstärker bearbeiten", + "Edit channel": "Kanal bearbeiten", + "Enter PIN": "PIN eingeben", + "Enter value": "Wert eingeben", + "EQ curve – drag the points": "EQ-Kurve – Punkte ziehen", + "Error": "Fehler", + "Error: ": "Fehler: ", + "Export": "Exportieren", + "Export / import preset": "Preset exportieren / importieren", + "Export saves the DSP’s current state ({name}) to a file. Import loads a file into the active state – stored presets (U01 …) stay unchanged.": "Exportieren speichert den aktuellen Zustand des DSP ({name}) als Datei. Importieren lädt eine Datei in den aktiven Zustand – gespeicherte Presets (U01 …) bleiben unverändert.", + "exported": "exportiert", + "File is too large": "Datei ist zu groß", + "File…": "Datei…", + "Filter type": "Filtertyp", + "First device found": "Erstes gefundenes Gerät", + "Frequency": "Frequenz", + "Gain": "Verstärkung", + "Gain (dB)": "Verstärkung (dB)", + "Gain {v} dB": "Verstärkung {v} dB", + "Graphic EQ · 31 bands": "Grafischer EQ · 31 Bänder", + "High- / low-pass": "Hoch- / Tiefpass", + "High-pass": "Hochpass", + "Highs": "Hochton", + "If the amplifier has a gain control, the value applies with it turned fully up.": "Hat der Verstärker einen Gain-Regler, gilt der Wert bei Rechtsanschlag.", + "If the macOS firewall is on, it asks the first time – choose “Allow”.": "Ist die macOS-Firewall aktiv, fragt sie beim ersten Einschalten – dort „Erlauben“ wählen.", + "Impedance": "Impedanz", + "Import": "Importieren", + "Import incomplete": "Import unvollständig", + "Import preset": "Preset importieren", + "Importing… (a few seconds)": "Importiere… (einige Sekunden)", + "Import…": "Importieren…", + "in ms, or metres with “m” (e.g. 2.5m)": "in ms, oder Meter mit „m“ (z. B. 2.5m)", + "Increase": "Erhöhen", + "Input": "Eingang", + "Input sensitivity (V RMS)": "Eingangsempfindlichkeit (V RMS)", + "Input →": "Eingang →", + "Inputs": "Eingänge", + "into 2 Ω": "an 2 Ω", + "into 4 Ω": "an 4 Ω", + "into 8 Ω": "an 8 Ω", + "IP address": "IP-Adresse", + "IP address missing": "IP-Adresse fehlt", + "IP of this computer": "IP dieses PCs", + "Its assignments will be removed.": "Die Zuordnungen werden entfernt.", + "Language": "Sprache", + "Level": "Pegel", + "Level for {ch}": "Pegel für {ch}", + "Limit to": "Limiter auf", + "Limiter 0 dB equals at the output": "Limiter 0 dB entspricht am Ausgang", + "Limiter active": "Limiter aktiv", + "Limiter tab": "Limiter-Tab", + "Link": "Verknüpfen", + "Link channels": "Kanäle verknüpfen", + "Link {names}? They all take over the settings of {first} (names and routing stay).": "{names} verknüpfen? Alle übernehmen dabei die Einstellungen von {first} (Namen und Routing bleiben).", + "Link {names}? They all take over the settings of {first} (names stay).": "{names} verknüpfen? Alle übernehmen dabei die Einstellungen von {first} (Namen bleiben).", + "Linked channels share all settings (gain, delay, filters, EQ, dynamics, mute) – ": "Verknüpfte Kanäle teilen sich alle Einstellungen (Gain, Delay, Filter, EQ, Dynamik, Mute) – ", + "Linked with {list} – changes apply to all of them (except name, routing and mix levels).": "Verknüpft mit {list} – Änderungen gelten für alle (außer Name, Routing und Mix-Pegel).", + "Linked with {list} – changes apply to all of them (except the name).": "Verknüpft mit {list} – Änderungen gelten für alle (außer Name).", + "Linked: ": "Verknüpft: ", + "Load on channel": "Last am Kanal", + "Load {what} into the active state? The current state is backed up automatically first and can be brought back via File → “Undo import”. Stored presets stay unchanged – to keep it, store it into a memory slot with “Save” afterwards.": "{what} in den aktiven Zustand laden? Der aktuelle Zustand wird vorher automatisch gesichert und lässt sich über Datei → „Import rückgängig“ zurückholen. Gespeicherte Presets bleiben unverändert – zum Behalten danach mit „Speichern“ in einen Speicherplatz schreiben.", + "Loading configuration…": "Lade Konfiguration…", + "Loading the configuration from the DSP…": "Lade Konfiguration vom DSP…", + "Lock": "Sperren", + "Lock (view only)": "Sperren (nur noch ansehen)", + "Locked": "Gesperrt", + "Locked – click to unlock": "Gesperrt – zum Entsperren klicken", + "Locked – unlock at the top right to make changes": "Gesperrt – zum Ändern oben rechts entsperren", + "Locked – unlock with the PIN to make changes": "Gesperrt – zum Ändern mit der PIN entsperren", + "Locked – values are view-only": "Gesperrt – Werte nur noch ansehen", + "login required": "Anmeldung erforderlich", + "Low-pass": "Tiefpass", + "Lower value": "Kleinerer Wert", + "Memory slot": "Speicherplatz", + "Mids": "Mitten", + "Model": "Modell", + "Name (max. 14 characters)": "Name (max. 14 Zeichen)", + "Name is full (max. 8 characters, wide letters count more)": "Name ist voll (max. 8 Zeichen, breite Buchstaben zählen mehr)", + "Network": "Netzwerk", + "New amplifier": "Neuer Verstärker", + "New device": "Neues Gerät", + "New PIN": "Neue PIN", + "Next channel": "Nächster Kanal", + "No amplifier assigned": "Kein Verstärker zugeordnet", + "No backup available": "Keine Sicherung vorhanden", + "No channels linked.": "Keine Kanäle verknüpft.", + "no crossover": "ohne Weiche", + "No DSP found via USB": "Kein DSP per USB gefunden", + "No DSP found via USB – check the cable": "Kein DSP per USB gefunden – Kabel prüfen", + "no HP": "ohne HP", + "Not a DSP Control preset file": "Keine Preset-Datei von DSP Control", + "Not a DSP Control settings backup": "Keine Einstellungs-Sicherung von DSP Control", + "Not assigned to any output": "Keinem Ausgang zugeordnet", + "not connected": "nicht verbunden", + "Not connected.": "Nicht verbunden.", + "Off": "Aus", + "Off (bypass)": "Aus (Bypass)", + "Off – only this window has access.": "Aus – nur dieses Fenster hat Zugriff.", + "On": "Ein", + "Open channel": "Kanal öffnen", + "Open on a phone in the same Wi-Fi:": "Am Handy im selben WLAN öffnen:", + "Other devices log in with the PIN (changeable below). Only runs while this app is open. ": "Andere Geräte melden sich mit der PIN an (unten änderbar). Läuft nur, solange diese App offen ist. ", + "Output ↓": "Ausgang ↓", + "Outputs": "Ausgänge", + "Overwrites the selected memory slot in the DSP.": "Überschreibt den gewählten Speicherplatz im DSP.", + "Parametric EQ": "Parametrischer EQ", + "PIN (same as on the phone)": "PIN (wie am Handy)", + "PIN changed – other devices were logged out": "PIN geändert – andere Geräte wurden abgemeldet", + "PIN for remote access": "PIN für Fernzugriff", + "Please log in": "Bitte anmelden", + "Preset exported": "Preset exportiert", + "Preset file": "Preset-Datei", + "Preset imported": "Preset importiert", + "Preset U{n} recalled": "Preset U{n} geladen", + "Preset {name} imported": "Preset {name} importiert", + "Previous channel": "Vorheriger Kanal", + "Previous state restored": "Vorheriger Zustand wiederhergestellt", + "Rated RMS power per channel (datasheet, empty = not specified)": "Nennleistung RMS pro Kanal (Datenblatt, leer = nicht angegeben)", + "Reading the state from the DSP…": "Lese Zustand vom DSP…", + "Recall": "Laden", + "Recall preset": "Preset laden", + "Recall preset…": "Preset laden…", + "Recall {name} (U{n})? Unsaved changes will be lost.": "{name} (U{n}) laden? Nicht gespeicherte Änderungen gehen verloren.", + "Reference level in dBu": "Referenzpegel in dBu", + "Reference level · ": "Bezugspegel · ", + "release ≈ 16 × attack (shorter pumps). “Auto” picks the band preset matching this channel’s high-pass.": "Release ≈ 16 × Attack (zu kurz pumpt). „Auto“ wählt das Band-Preset passend zum Hochpass dieses Kanals.", + "Remote access": "Fernzugriff", + "Remote access (web server)": "Fernzugriff (Webserver)", + "Remove": "Entfernen", + "Remove device": "Gerät entfernen", + "Remove {name} from the list?": "{name} aus der Liste entfernen?", + "Repeat": "Wiederholen", + "Reset": "Zurücksetzen", + "Reset EQ": "EQ zurücksetzen", + "Reset GEQ": "GEQ zurücksetzen", + "Restore": "Wiederherstellen", + "Restore settings": "Einstellungen wiederherstellen", + "Restore the state from {last}?": "Den Zustand vom {last} wiederherstellen?", + "Restore…": "Wiederherstellen…", + "Restoring…": "Stelle wieder her…", + "Routing matrix": "Routing-Matrix", + "Rule of thumb: attack ≈ one period of the lowest frequency (faster distorts the bass), ": "Faustregel: Attack ≈ eine Schwingung der tiefsten Frequenz (zu schnell verzerrt Bässe), ", + "Save": "Speichern", + "Saved": "Gespeichert", + "Saved device (not plugged in)": "Gespeichertes Gerät (nicht angesteckt)", + "Saves devices, amplifiers & limiter calculator, PIN and remote access to a file. ": "Sichert Geräte, Verstärker & Limiter-Rechner, PIN und Fernzugriff in eine Datei. ", + "Search again": "Neu suchen", + "Security": "Sicherheit", + "Sensitivity": "Empfindlichkeit", + "Sensitivity = input voltage for full power (e.g. 0.775 V or 1.4 V). ": "Empfindlichkeit = Eingangsspannung für volle Leistung (z. B. 0.775 V oder 1.4 V). ", + "Sensitivity is missing.": "Empfindlichkeit fehlt.", + "Sensitivity {v} V": "Empfindlichkeit {v} V", + "Server not reachable": "Server nicht erreichbar", + "Set": "setzen", + "Set all 31 bands to 0 dB?": "Alle 31 Bänder auf 0 dB setzen?", + "Set all PEQ bands of this channel to 0 dB and clear bypass?": "Alle PEQ-Bänder dieses Kanals auf 0 dB setzen und Bypass aufheben?", + "set the threshold to 0 dB, turn up until the limiter engages and measure the output voltage with a multimeter (AC). ": "Threshold 0 dB, Pegel hochdrehen bis der Limiter greift und die Ausgangsspannung mit einem Multimeter (AC) messen. ", + "Settings": "Einstellungen", + "Settings backed up": "Einstellungen gesichert", + "Settings restored": "Einstellungen wiederhergestellt", + "Shown is the continuous sine power (RMS) once the limiter engages – music is well below that on average. ": "Angezeigt wird die Sinus-Dauerleistung (RMS), sobald der Limiter greift – Musik liegt im Mittel deutlich darunter. ", + "Snaps at 0 dB · double-tap the knob = 0 dB": "Rastet bei 0 dB ein · Doppeltipp = 0 dB", + "Sources → ": "Quellen → ", + "Speaker ": "Lautsprecher ", + "Speaker at {pct} % of its rating ({w} RMS)": "Lautsprecher zu {pct} % belastet ({w} RMS)", + "Speaker RMS": "Lautsprecher RMS", + "Speaker RMS (W)": "Lautsprecher RMS (W)", + "Store preset": "Preset speichern", + "Stored in U{n}": "In U{n} gespeichert", + "Tap a crosspoint = connect/disconnect · tap an output = level per input": "Kreuzungspunkt antippen = verbinden/trennen · Ausgang antippen = Pegel pro Eingang", + "Tap at least two channels": "Mindestens zwei Kanäle antippen", + "Target power": "Ziel-Leistung", + "The default PIN is 1234. After changing it only this device stays logged in.": "Standard-PIN ist 1234. Nach dem Ändern bleibt nur dieses Gerät angemeldet.", + "The DSP did not take these values:": "Diese Werte hat der DSP nicht übernommen:", + "The DSPs accept only one connection: close the Thomann editor first.": "Die DSPs erlauben nur eine Verbindung: den Thomann-Editor vorher schließen.", + "The first time, Windows Firewall asks – choose “Allow” for private networks.": "Beim ersten Einschalten fragt die Windows-Firewall – dort „Zulassen“ für private Netzwerke wählen.", + "The link is stored in the DSP and also applies in the Thomann editor.": "Die Verknüpfung wird im DSP gespeichert und gilt auch für den Thomann-Editor.", + "The new PIN must be 4 digits.": "Die neue PIN muss aus 4 Ziffern bestehen.", + "The new PINs do not match.": "Die neuen PINs stimmen nicht überein.", + "The PIN must be 4 digits": "Die PIN muss aus 4 Ziffern bestehen", + "The settings inside the DSPs are saved per device via “File…” at the top.": "Die Einstellungen in den DSPs sichert man pro Gerät oben über „Datei…“.", + "This app needs no PIN. The default is 1234; changing it logs out all phones.": "Diese App braucht keine PIN. Standard ist 1234; nach dem Ändern werden alle Handys abgemeldet.", + "Thomann does not specify the reference level – 0 dBu (0.775 V) is assumed. To measure: feed a 1 kHz sine, ": "Thomann gibt den Bezugspegel nicht an – angenommen sind 0 dBu (0,775 V). Nachmessen: Sinus 1 kHz einspeisen, ", + "TimeoutError": "Zeitüberschreitung", + "Too many attempts – locked for {s} s": "Zu viele Versuche – noch {s} s gesperrt", + "Too many attempts – please wait a moment": "Zu viele Versuche – bitte kurz warten", + "Type": "Typ", + "Undo import": "Import rückgängig", + "Unlink": "Trennen", + "Unlock": "Entsperren", + "Unlocked": "Entsperrt", + "USB cable": "USB-Kabel", + "USB connection lost": "USB-Verbindung getrennt", + "USB device": "USB-Gerät", + "USB device is in use by another program": "USB-Gerät ist von einem anderen Programm belegt", + "USB device not found – check the cable": "USB-Gerät nicht gefunden – Kabel prüfen", + "USB is not supported on this system": "USB wird auf diesem System nicht unterstützt", + "USB write error": "USB-Schreibfehler", + "Used by: ": "Belegt: ", + "View": "Ansicht", + "Watts": "Watt", + "Wrong PIN": "Falsche PIN", + "Wrong PIN – {n} attempts left": "Falsche PIN – noch {n} Versuche", + "{db} dB headroom to amplifier clipping": "{db} dB Reserve bis Verstärker-Clipping", + "{names} linked": "{names} verknüpft", + "{names} unlinked": "{names} getrennt", + "{n} channels selected": "{n} Kanäle gewählt", + "{pct} % of the speaker rating ({w} RMS)": "{pct} % der Lautsprecher-Belastbarkeit ({w} RMS)", + "{pct} % of {rated}": "{pct} % von {rated}", + "— empty —": "— leer —", + "— no amplifier —": "— kein Verstärker —", + "“{s}”": "„{s}“" +}; + +const DE_PATTERNS = [ + [/^Port (\d+) is already in use – please choose another port$/, "Port $1 ist schon belegt – bitte einen anderen Port wählen"], + [/^Port (\d+) is not available \((.*)\)$/, "Port $1 ist nicht verfügbar ($2)"], + [/^Cannot open USB device \(error (.*)\)$/, "USB-Gerät lässt sich nicht öffnen (Fehler $1)"], + [/^USB write error \((.*)\)$/, "USB-Schreibfehler ($1)"], + [/^The file is for a DSP (\w+), the connected device is a (.*)$/, "Die Datei ist für den DSP $1, verbunden ist ein $2"], + [/^Unknown file format \((\d+) bytes\) – expected a DSP Control preset file or a memory image of the (.*) \((\d+) bytes\)$/, + "Unbekanntes Dateiformat ($1 Bytes) – erwartet wird eine Preset-Datei dieser App oder ein Speicherabbild des $2 ($3 Bytes)"], + [/^unknown device '(.*)' - set the model manually$/, "Unbekanntes Gerät „$1“ – Modell bitte manuell einstellen"], + [/^config chunk (\d+) not received$/, "Konfigurations-Teil $1 nicht empfangen"], +]; + +function t(s, vars) { + const text = LANG === "de" && DE[s] != null ? DE[s] : s; + return vars ? text.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? vars[k] : m)) : text; +} +function trMsg(msg) { + msg = String(msg ?? ""); + if (LANG !== "de") return msg; + if (DE[msg] != null) return DE[msg]; + for (const [re, de] of DE_PATTERNS) if (re.test(msg)) return msg.replace(re, de); + return msg; +} +const q = s => t("“{s}”", { s }); // quoted name: “x” / „x“ + +// static texts in index.html +document.documentElement.lang = LANG; +document.querySelectorAll("[data-t]").forEach(el => (el.textContent = t(el.dataset.t))); +document.querySelectorAll("[data-t-label]").forEach(el => { + el.setAttribute("aria-label", t(el.dataset.tLabel)); + if (el.title) el.title = t(el.dataset.tLabel); +}); diff --git a/static/index.html b/static/index.html new file mode 100644 index 0000000..3da3bd3 --- /dev/null +++ b/static/index.html @@ -0,0 +1,42 @@ + + + + + + + + + +DSP Control + + + + + + + + + + + + diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..d97329e --- /dev/null +++ b/static/style.css @@ -0,0 +1,444 @@ +:root { + --bg: #0b0c0f; + --bg2: #101216; + --panel: #15181d; + --panel2: #1c2027; + --panel3: #232831; + --line: #2a303a; + --line2: #3a4250; + --text: #e8edf3; + --dim: #8a95a3; + --dim2: #5d6773; + --accent: #38bdf8; + --accent2: #0284c7; + --ok: #22c55e; + --warn: #f59e0b; + --bad: #ef4444; + --mute: #dc2626; + --led-g: #2bff6b; + --led-o: #ffa31a; + --led-r: #ff3030; + --radius: 12px; + --hdr: 56px; + --bnav: 0px; + --sb: 70px; + color-scheme: dark; +} +* { box-sizing: border-box; } +html, body { margin: 0; background: var(--bg); color: var(--text); } +body { + font: 15px/1.35 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + -webkit-tap-highlight-color: transparent; + overscroll-behavior-y: contain; + min-height: 100dvh; +} +[hidden] { display: none !important; } +button, input, select { font: inherit; color: inherit; } +button { + background: var(--panel2); border: 1px solid var(--line); border-radius: 9px; + padding: 8px 12px; min-height: 40px; cursor: pointer; touch-action: manipulation; + display: inline-flex; align-items: center; justify-content: center; gap: 6px; + transition: background .12s, border-color .12s, color .12s; +} +button:hover { border-color: var(--line2); } +button:active { filter: brightness(1.25); } +button:focus-visible, select:focus-visible, input:focus-visible, .fader:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +button.on { background: var(--accent2); border-color: var(--accent); color: #fff; } +button:disabled { opacity: .45; cursor: default; } +button.danger { color: #fca5a5; } +button.danger-on { background: #991b1b; border-color: #ef4444; color: #fff; } +button.small { min-height: 32px; padding: 4px 10px; font-size: 13px; text-transform: none; letter-spacing: 0; } +button.icon { background: none; border-color: transparent; padding: 8px; min-width: 44px; } +button.icon:hover { background: var(--panel2); } +button svg, .icon svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +select, input[type=text], input[type=number], input[type=password] { + background: var(--panel2); border: 1px solid var(--line); border-radius: 9px; + padding: 8px 10px; min-height: 40px; width: 100%; min-width: 0; +} +select { cursor: pointer; } +input.bad { border-color: var(--bad); } +label.inline { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--dim); } + +/* ------------------------------------------------------------- header */ +#top { + position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 8px; + padding: calc(6px + env(safe-area-inset-top)) max(8px, env(safe-area-inset-right)) 6px max(8px, env(safe-area-inset-left)); + background: rgba(11, 12, 15, .92); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); + border-bottom: 1px solid var(--line); +} +.brand { display: flex; flex: none; } +#devtabs { display: flex; gap: 6px; overflow-x: auto; flex: 1; min-width: 0; scrollbar-width: none; } +#devtabs::-webkit-scrollbar { display: none; } +.devtab { white-space: nowrap; flex: none; max-width: 220px; background: var(--panel); } +.devtab .dn { overflow: hidden; text-overflow: ellipsis; } +.devtab small { font-size: 11px; color: var(--dim); background: var(--panel3); border-radius: 5px; padding: 1px 5px; } +.devtab.active { background: var(--panel3); border-color: var(--accent); } +.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--dim2); flex: none; } +.dot.online { background: var(--ok); box-shadow: 0 0 6px var(--ok); } +.dot.connecting, .dot.loading { background: var(--warn); animation: blink 1s infinite; } +.dot.error { background: var(--bad); } +@keyframes blink { 50% { opacity: .3; } } + +#viewtabs { display: flex; gap: 4px; background: var(--panel); border: 1px solid var(--line); border-radius: 11px; padding: 3px; flex: none; } +#viewtabs button { border: 0; background: none; min-height: 36px; padding: 6px 14px; color: var(--dim); border-radius: 8px; } +#viewtabs button svg { width: 18px; height: 18px; } +#viewtabs button svg .f { fill: currentColor; stroke: none; } +#viewtabs button.active { background: var(--panel3); color: var(--accent); } +body[data-view=settings] #viewtabs button.active { background: none; color: var(--dim); } + +#statusbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; padding: 10px max(10px, env(safe-area-inset-right)) 6px max(10px, env(safe-area-inset-left)); } +#statusbar:empty { display: none; } +#statusbar .preset { flex: 1 1 180px; min-width: 0; } +#statusbar .preset b { display: block; font-size: 18px; letter-spacing: .01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +#statusbar .preset small { color: var(--dim); font-size: 12px; } +#statusbar .presetrow { flex: 0 1 380px; display: flex; gap: 8px; min-width: 0; } +#statusbar .presetrow select { flex: 1; min-width: 0; } +#statusbar .presetrow button { flex: none; } + +#main { padding: 4px max(10px, env(safe-area-inset-right)) calc(24px + var(--bnav)) max(10px, env(safe-area-inset-left)); max-width: 1500px; margin: 0 auto; } + +/* phones: view switcher becomes a bottom navigation bar */ +@media (max-width: 759px) { + :root { --bnav: calc(62px + env(safe-area-inset-bottom)); } + .brand { display: none; } + /* backdrop-filter would make the header the containing block of the fixed bottom bar */ + #top { backdrop-filter: none; -webkit-backdrop-filter: none; background: var(--bg); } + #viewtabs { + position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; border-radius: 0; border: 0; border-top: 1px solid var(--line); + padding: 4px 6px env(safe-area-inset-bottom); background: rgba(16, 18, 22, .96); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); + } + #viewtabs button { flex: 1; flex-direction: column; gap: 2px; font-size: 11px; min-height: 54px; padding: 4px; } + #viewtabs button svg { width: 22px; height: 22px; } + #toast { bottom: calc(var(--bnav) + 12px) !important; } +} + +/* ------------------------------------------------------------- generic blocks */ +.card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; min-width: 0; } +.card h3 { margin: 0 0 12px; font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--dim); + display: flex; align-items: center; gap: 8px; min-height: 22px; } +.grow { flex: 1; } +.cards { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 340px), 1fr)); align-items: start; margin-bottom: 10px; } +.cards .wide { grid-column: 1 / -1; } +h2.section { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--dim); margin: 14px 2px 8px; } +.empty { color: var(--dim); text-align: center; padding: 60px 16px; display: flex; flex-direction: column; align-items: center; gap: 16px; } +.spinner { width: 28px; height: 28px; border-radius: 50%; border: 3px solid var(--line); border-top-color: var(--accent); animation: spin .9s linear infinite; } +.spinner.off { display: none; } +@keyframes spin { to { transform: rotate(360deg); } } +.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.row > * { flex: 1 1 auto; } +.row > button { flex: 0 0 auto; } +.grow2 { flex: 1 1 160px !important; } +.info { font-size: 12px; color: var(--dim); margin: 8px 2px 0; } +.info.off { margin: 4px 0 6px; } +.hint { text-align: center; } +.err { color: #fca5a5; font-size: 13px; } + +/* ------------------------------------------------------------- parameter rows */ +.param { margin: 10px 0 4px; } +.param .lbl { display: flex; justify-content: space-between; align-items: center; gap: 8px; font-size: 13px; color: var(--dim); margin-bottom: 2px; } +.valbox { display: flex; align-items: center; gap: 4px; } +.valbox .val { min-width: 104px; min-height: 32px; padding: 3px 8px; background: var(--bg2); border-color: var(--line); + font-variant-numeric: tabular-nums; font-size: 14px; color: var(--text); } +.valbox .step { width: 34px; min-width: 34px; min-height: 32px; padding: 0; font-size: 18px; line-height: 1; color: var(--dim); background: var(--panel2); } +.valbox .step:hover { color: var(--text); } +.param.atzero .val { color: var(--ok); border-color: #1f5f36; } +.rangewrap { position: relative; } +.rangewrap .zmark { position: absolute; top: 6px; bottom: 6px; width: 2px; margin-left: -1px; border-radius: 1px; background: var(--line2); + left: calc(13px + (100% - 26px) * var(--f)); pointer-events: none; } +.param.atzero .zmark { background: var(--ok); } +input[type=range] { position: relative; width: 100%; height: 36px; background: transparent; -webkit-appearance: none; appearance: none; margin: 0; cursor: pointer; touch-action: pan-y; } +input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--line); border-radius: 3px; } +input[type=range]::-moz-range-track { height: 6px; background: var(--line); border-radius: 3px; } +input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 26px; height: 26px; margin-top: -10px; border-radius: 50%; + background: radial-gradient(circle at 50% 40%, #e2e8f0, #94a3b8); border: 2px solid #0b0c0f; box-shadow: 0 1px 4px #000c; } +input[type=range]::-moz-range-thumb { width: 22px; height: 22px; border-radius: 50%; background: radial-gradient(circle at 50% 40%, #e2e8f0, #94a3b8); border: 2px solid #0b0c0f; } +.param.atzero input[type=range]::-webkit-slider-thumb { box-shadow: 0 0 0 3px #22c55e55, 0 1px 4px #000c; } + +/* ------------------------------------------------------------- LED meters (segment bars) */ +.led { display: flex; gap: 2px; flex: none; } +.led > i { flex: 1; border-radius: 1.5px; background: var(--c); opacity: .13; } +.led > i.g { --c: var(--led-g); } +.led > i.o { --c: var(--led-o); } +.led > i.r { --c: var(--led-r); } +.led.v { flex-direction: column-reverse; width: 12px; height: 100%; padding: 12px 0; } +.led.h { flex-direction: row; height: 10px; width: 120px; } +.muted .led > i { filter: saturate(.25); } + +/* ------------------------------------------------------------- fader */ +/* only the cap grabs: a swipe anywhere else on the fader scrolls the page / the mixer sideways */ +.fader { --tx: 50%; position: relative; touch-action: pan-x pan-y; user-select: none; -webkit-user-select: none; border-radius: 8px; } +.fader .track { position: absolute; left: var(--tx); top: 12px; bottom: 12px; width: 6px; margin-left: -3px; background: #07080a; + border-radius: 3px; box-shadow: inset 0 0 0 1px var(--line); } +.fader .tick { position: absolute; left: calc(var(--tx) - 14px); width: 28px; height: 1px; background: var(--line2); + top: calc(12px + (100% - 24px) * (1 - var(--f))); } +.fader .tick.z { background: var(--dim); height: 2px; margin-top: -0.5px; } +.fader .tick span { position: absolute; right: calc(100% + 3px); top: -6px; font-size: 9px; line-height: 12px; color: var(--dim2); font-variant-numeric: tabular-nums; white-space: nowrap; } +.fader .tick.z span { color: var(--dim); font-weight: 600; } +.fader .cap { position: absolute; left: calc(var(--tx) - 16px); width: 32px; height: 40px; margin-top: -20px; border-radius: 5px; + top: calc(12px + (100% - 24px) * (1 - var(--f))); + background: linear-gradient(#3b4250, #262b34 45%, #1b1f26 55%, #2c323c); border: 1px solid #4a5260; + box-shadow: 0 3px 8px #000c, inset 0 1px 0 #ffffff1a; } +.fader .cap { touch-action: none; cursor: ns-resize; z-index: 1; } +.fader .cap::before { content: ""; position: absolute; inset: -10px -8px; } /* larger grip area for fingers */ +.fader .cap::after { content: ""; position: absolute; left: 3px; right: 3px; top: 50%; height: 2px; margin-top: -1px; background: #e8edf3; border-radius: 1px; } +.fader.atzero .cap::after { background: var(--ok); box-shadow: 0 0 6px var(--ok); } +.fader.grab .cap { border-color: var(--accent); } + +/* ------------------------------------------------------------- mixer */ +.mixer { display: flex; gap: 14px; overflow-x: auto; padding-bottom: 8px; scroll-snap-type: x proximity; } +.mgroup { flex: 0 0 auto; display: flex; flex-direction: column; gap: 6px; } +.mgroup h4 { margin: 0 2px; font-size: 11px; text-transform: uppercase; letter-spacing: .1em; color: var(--dim); font-weight: 600; } +.strips { display: flex; gap: 6px; } +.strip { --cc: var(--warn); flex: none; width: 92px; background: linear-gradient(var(--panel), var(--bg2)); border: 1px solid var(--line); + border-radius: var(--radius); padding: 0 6px 8px; display: flex; flex-direction: column; align-items: stretch; gap: 8px; + scroll-snap-align: start; position: relative; overflow: hidden; } +.strip::before { content: ""; height: 3px; margin: 0 -6px; background: var(--cc); opacity: .9; } +.strip-head { flex-direction: column; gap: 0; background: none; border: 0; padding: 2px 0; min-height: 38px; border-radius: 6px; } +.strip-head:hover { background: var(--panel2); } +.strip-head .kind { font-size: 11px; color: var(--dim); letter-spacing: .04em; } +.strip-head .nm { font-weight: 650; font-size: 13px; max-width: 78px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.faderbox { display: flex; justify-content: center; gap: 4px; + height: clamp(170px, calc(100dvh - var(--hdr) - var(--sb) - var(--bnav) - 196px), 560px); } +.strip .fader { --tx: 36px; width: 56px; height: 100%; } +.strip .db { min-height: 32px; padding: 2px; font-variant-numeric: tabular-nums; font-size: 13px; background: var(--bg2); } +.strip .db.z { color: var(--ok); } +.strip button.mute { min-height: 38px; font-weight: 700; font-size: 12px; letter-spacing: .06em; } +button.mute.on { background: var(--mute); border-color: #f87171; color: #fff; box-shadow: 0 0 10px #dc262655; } +.strip.muted { background: linear-gradient(#1f1517, var(--bg2)); } +@media (min-width: 1200px) { + .mgroup { flex-shrink: 1; flex-basis: 0; } + .strip { flex: 1 1 92px; max-width: 128px; } +} + +/* ------------------------------------------------------------- channel view */ +.chbar { position: sticky; top: var(--hdr); z-index: 10; display: flex; align-items: center; gap: 6px; margin: 0 -10px 10px; padding: 8px 10px; + background: rgba(11, 12, 15, .94); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid var(--line); } +.chbar .nav { flex: none; background: var(--panel2); border-color: var(--line); min-width: 44px; } +.chselwrap { --cc: var(--warn); flex: 1 1 auto; min-width: 0; position: relative; max-width: 420px; } +.chselwrap::before { content: ""; position: absolute; left: 0; top: 8px; bottom: 8px; width: 4px; border-radius: 2px; background: var(--cc); pointer-events: none; } +.chsel { font-weight: 650; font-size: 16px; padding-left: 14px; min-height: 44px; background: var(--panel2); } +.chbar .led.h { width: clamp(60px, 18vw, 200px); } +.chbar .mute { flex: none; min-width: 70px; font-weight: 700; font-size: 12px; letter-spacing: .06em; } +@media (max-width: 480px) { .chbar .led.h { display: none; } } + +.sub { font-size: 13px; color: var(--text); font-weight: 600; flex: 0 0 80px !important; } +.xo + .xo { margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--line); } +canvas.curve { width: 100%; height: clamp(200px, 32vw, 320px); display: block; background: #08090b; border: 1px solid var(--line); border-radius: 10px; touch-action: none; cursor: crosshair; } +.bands { display: flex; gap: 6px; overflow-x: auto; padding: 10px 0 4px; scrollbar-width: thin; } +.band { flex: 1 0 58px; flex-direction: column; gap: 0; padding: 5px 4px; min-height: 52px; line-height: 1.15; } +.band b { font-size: 14px; } +.band small { font-size: 10.5px; color: var(--dim); font-variant-numeric: tabular-nums; } +.band.active:not(.on) { border-color: #3b6d8a; } +.band.on { background: #3a2a0d; border-color: var(--warn); color: #fff; } +.band.on small { color: #fcd9a0; } +.band.bypassed { opacity: .45; } +.band.bypassed b { text-decoration: line-through; } +.bandhead { margin-top: 8px; } +.bandhead label { flex: 1 1 200px; } +.pgrid { display: grid; gap: 0 18px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); } + +.geq { display: flex; gap: 2px; overflow-x: auto; padding-bottom: 6px; } +.gb { flex: 1 0 30px; display: flex; flex-direction: column; align-items: center; gap: 4px; font-size: 10px; color: var(--dim); } +.gb .fader { width: 30px; height: 190px; } +.gb .fader .tick { left: 3px; width: 24px; } +.gb .fader .cap { left: 1px; width: 28px; height: 24px; margin-top: -12px; } +.gb .gv { font-variant-numeric: tabular-nums; } +.gb .gv.nz { color: var(--warn); } +.gb .gf { white-space: nowrap; } + +.mixrow { display: grid; grid-template-columns: minmax(110px, 0.6fr) 1fr; gap: 4px 12px; align-items: center; padding: 4px 0; } +.mixrow + .mixrow { border-top: 1px solid var(--line); } +.mixrow .param { margin: 4px 0; } +.mixrow .param .lbl > span:first-child { display: none; } +.mixrow .param .lbl { justify-content: flex-end; } +.mixrow.off .param { opacity: .45; } +.src { --cc: var(--accent); justify-content: flex-start; text-align: left; min-height: 44px; } +.src .sw { width: 30px; height: 18px; border-radius: 9px; background: var(--line); position: relative; flex: none; transition: background .15s; } +.src .sw::after { content: ""; position: absolute; left: 2px; top: 2px; width: 14px; height: 14px; border-radius: 50%; background: var(--dim); transition: transform .15s, background .15s; } +.src.on { background: var(--panel2); border-color: var(--cc); color: var(--text); } +.src.on .sw { background: var(--cc); } +.src.on .sw::after { transform: translateX(12px); background: #fff; } +@media (max-width: 420px) { .mixrow { grid-template-columns: 1fr; } } + +/* ------------------------------------------------------------- routing matrix */ +.routing { overflow-x: auto; } +.xmatrix { display: grid; grid-template-columns: minmax(104px, 1.1fr) repeat(var(--n), minmax(58px, 1fr)); gap: 0; min-width: min-content; } +.xcorner { display: flex; flex-direction: column; justify-content: flex-end; padding: 0 8px 8px 2px; font-size: 11px; color: var(--dim2); } +.xin { --cc: var(--accent); display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 8px 4px 10px; border-top: 3px solid var(--cc); + background: linear-gradient(color-mix(in srgb, var(--cc) 10%, transparent), transparent); border-radius: 6px 6px 0 0; margin: 0 3px; min-width: 0; } +.xin b { font-size: 14px; } +.xin small { font-size: 11px; color: var(--dim); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.xin .led.h { width: 80%; height: 6px; margin-top: 4px; } +.xout { display: grid; grid-template-columns: 1fr auto; grid-template-rows: auto auto; justify-items: start; align-items: center; gap: 0 6px; + text-align: left; border-radius: 9px 0 0 9px; border: 0; border-top: 1px solid var(--line); background: none; padding: 8px; min-height: 64px; } +.xout:hover { background: var(--panel2); } +.xout.open { background: var(--panel3); } +.xo-t { display: flex; flex-direction: column; min-width: 0; } +.xo-t b { font-size: 14px; } +.xo-t small { font-size: 11px; color: var(--dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; } +.xo-s { grid-column: 1; font-size: 11px; color: var(--accent); } +.chev { grid-column: 2; grid-row: 1 / 3; color: var(--dim); font-size: 16px; } +.xp { --cc: var(--accent); position: relative; border: 0; border-top: 1px solid var(--line); border-radius: 0; min-height: 64px; padding: 0; background: + linear-gradient(var(--line), var(--line)) center / 2px 100% no-repeat, + linear-gradient(var(--line), var(--line)) center / 100% 2px no-repeat; flex-direction: column; gap: 3px; } +.xp:hover { background-color: var(--panel2); } +.xp .node { width: 24px; height: 24px; border-radius: 50%; background: var(--bg); border: 2px solid var(--line2); transition: transform .12s, background .12s; } +.xp:hover .node { border-color: var(--dim); } +.xp.on { border-color: var(--line); color: var(--text); --lc: color-mix(in srgb, var(--cc) 60%, transparent); background: + linear-gradient(var(--lc), var(--lc)) center / 2px 100% no-repeat, + linear-gradient(var(--lc), var(--lc)) center / 100% 2px no-repeat; } +.xp.on .node { background: var(--cc); border-color: #fff; box-shadow: 0 0 0 4px color-mix(in srgb, var(--cc) 30%, transparent), 0 0 14px var(--cc); transform: scale(1.08); } +.xp small { position: absolute; bottom: 3px; left: 0; right: 0; font-size: 10px; color: var(--text); background: none; font-variant-numeric: tabular-nums; } +.xpanel { grid-column: 1 / -1; background: var(--panel3); border-radius: 0 0 10px 10px; padding: 6px 12px 10px; margin-bottom: 6px; } +.xpanel-h { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 12px; color: var(--dim); text-transform: uppercase; letter-spacing: .06em; padding: 4px 0; } + +/* ------------------------------------------------------------- settings */ +.devform { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +.devform label { font-size: 12px; color: var(--dim); display: flex; flex-direction: column; gap: 4px; } +.devform label.full, .devform .err { grid-column: 1 / -1; } +.devform label.chk { flex-direction: row; align-items: center; gap: 8px; color: var(--text); font-size: 14px; } +.devform label.chk input { width: 20px; height: 20px; } +.devform .actions { grid-column: 1 / -1; display: flex; gap: 8px; flex-wrap: wrap; } +.devform .actions button { flex: 1 1 auto; } + +/* ------------------------------------------------------------- dialogs */ +#modal { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; padding: 16px; } +.backdrop { position: absolute; inset: 0; background: #000a; animation: fade .15s; } +.dialog { position: relative; width: min(420px, 100%); background: var(--panel); border: 1px solid var(--line2); border-radius: 16px; + padding: 18px; box-shadow: 0 20px 60px #000c; animation: pop .15s ease-out; } +.dialog h2 { margin: 0 0 12px; font-size: 17px; } +.dlg-text { margin: 0 0 4px; color: var(--dim); } +.dlg-actions { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; margin-top: 16px; } +.dlg-actions button { min-width: 110px; } +.dialog .row input { flex: 1 1 140px; font-size: 18px; font-variant-numeric: tabular-nums; } +.dialog .chip { flex: none; } +.form { display: flex; flex-direction: column; gap: 10px; } +.form label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--dim); } +@keyframes fade { from { opacity: 0; } } +@keyframes pop { from { opacity: 0; transform: scale(.96) translateY(6px); } } +@media (max-width: 520px) { + #modal { align-items: flex-end; padding: 0; } + .dialog { width: 100%; border-radius: 18px 18px 0 0; padding-bottom: calc(18px + env(safe-area-inset-bottom)); animation: slideup .18s ease-out; } + .dlg-actions button { flex: 1; } +} +@keyframes slideup { from { transform: translateY(40px); opacity: 0; } } + +#toast { position: fixed; left: 50%; bottom: calc(20px + env(safe-area-inset-bottom)); transform: translateX(-50%); + background: #1f2937; border: 1px solid var(--line2); padding: 10px 16px; border-radius: 10px; z-index: 120; max-width: 90vw; box-shadow: 0 8px 24px #000a; } + +/* ------------------------------------------------------------- login */ +#login { position: fixed; inset: 0; z-index: 200; display: flex; align-items: center; justify-content: center; overflow-y: auto; + background: radial-gradient(ellipse at 50% 0%, #13253a 0%, var(--bg) 60%); padding: 20px; } +.loginbox { display: flex; flex-direction: column; align-items: center; width: min(320px, 100%); } +.loginbox .logo svg { width: 56px; height: 56px; } +.loginbox h1 { margin: 12px 0 2px; font-size: 22px; letter-spacing: .02em; } +.loginbox p { margin: 0 0 22px; color: var(--dim); } +.pindots { display: flex; gap: 18px; margin-bottom: 10px; } +.pindots i { width: 16px; height: 16px; border-radius: 50%; border: 2px solid var(--line2); transition: background .1s, border-color .1s, transform .1s; } +.pindots i.on { background: var(--accent); border-color: var(--accent); transform: scale(1.1); box-shadow: 0 0 10px #38bdf888; } +.pindots.shake { animation: shake .4s; } +.pindots.shake i { border-color: var(--bad); } +@keyframes shake { 20%, 60% { transform: translateX(-10px); } 40%, 80% { transform: translateX(10px); } } +.pinmsg { min-height: 20px; font-size: 13px; color: #fca5a5; margin-bottom: 14px; text-align: center; } +.pinpad { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; width: 100%; max-width: 280px; } +.pinpad.locked { opacity: .35; pointer-events: none; } +.pk { aspect-ratio: 1; border-radius: 50%; font-size: 26px; font-weight: 500; background: var(--panel); border: 1px solid var(--line); min-height: 0; } +.pk:active { background: var(--accent2); border-color: var(--accent); filter: none; } +.pk.del { font-size: 22px; background: none; border-color: transparent; color: var(--dim); } +@media (max-height: 560px) { .pk { aspect-ratio: auto; height: 52px; border-radius: 14px; } .pinpad { gap: 8px; } .loginbox p { margin-bottom: 10px; } } + +/* ------------------------------------------------------------- limiter calculator */ +.limcard h3 .led.h { width: clamp(50px, 14vw, 110px); height: 8px; } +.lres { --c: var(--ok); border: 1px solid var(--line); border-left: 4px solid var(--c); border-radius: 10px; padding: 10px 12px; margin-bottom: 12px; + background: linear-gradient(90deg, color-mix(in srgb, var(--c) 10%, transparent), transparent 70%); } +.lres.warn { --c: var(--warn); } +.lres.bad { --c: var(--bad); } +.lres.none { --c: var(--line2); background: none; } +.lw { font-size: 30px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.1; } +.lw small { font-size: 14px; font-weight: 500; color: var(--dim); } +.lsub { font-size: 13px; color: var(--dim); margin-top: 2px; } +.lbar { position: relative; height: 8px; border-radius: 4px; background: var(--panel3); margin: 10px 0 4px; } +.lres.none .lbar { display: none; } +.lbar i { position: absolute; inset: 0 auto 0 0; width: calc(var(--p) * 100%); border-radius: 4px; background: var(--c); transition: width .15s; } +.lbar b, .lbar::after { position: absolute; top: -4px; bottom: -4px; width: 2px; background: var(--text); left: calc(var(--a) * 100% - 1px); } +.lbar::after { content: ""; display: none; background: var(--warn); left: calc(var(--s) * 100% - 1px); } +.lbar.hasspk::after { display: block; } +.lnotes { display: grid; gap: 2px; margin-top: 6px; font-size: 12.5px; } +.lnotes .ok { color: #86efac; } .lnotes .warn { color: #fcd34d; } .lnotes .bad { color: #fca5a5; } +.lnotes div::before { content: "● "; font-size: 9px; vertical-align: 2px; } +.limgrid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 8px; } +.limgrid label { font-size: 12px; color: var(--dim); display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.limgrid label.full { grid-column: 1 / -1; } +.target { border-top: 1px solid var(--line); margin-top: 10px; padding-top: 10px; } +.target .row input { flex: 1 1 80px; min-width: 0; } +.target .sub { flex: 0 0 auto !important; } +.chips { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; } +button.chip { min-height: 30px; padding: 3px 10px; font-size: 12.5px; text-transform: none; letter-spacing: 0; border-radius: 15px; } +details.more { margin-top: 8px; } +details.more summary { cursor: pointer; font-size: 13px; color: var(--dim); padding: 6px 0; user-select: none; } +.amp .ampspec { font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; } +.amp .actions { display: flex; justify-content: flex-end; margin-top: 8px; } +.addcard { min-height: 90px; border-style: dashed; color: var(--dim); background: none; font-size: 14px; } +.addcard:hover { color: var(--accent); border-color: var(--accent); } +input.short { flex: 0 0 72px !important; width: 72px; text-align: right; } +.seg { display: flex; gap: 0; } +.seg button { flex: 1; border-radius: 0; text-transform: none; letter-spacing: 0; } +.seg button:first-child { border-radius: 8px 0 0 8px; } +.seg button:last-child { border-radius: 0 8px 8px 0; margin-left: -1px; } +.ampform { grid-template-columns: repeat(3, minmax(0, 1fr)); } +.ampform .full { grid-column: 1 / -1; } +.ampform input { min-width: 0; width: 100%; } +.ampform .sub { margin-top: 4px; } +.ampform .full > label { font-size: 12px; color: var(--dim); display: flex; flex-direction: column; gap: 4px; } +.ampform label[hidden] { display: none; } +.chips.presets { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); margin: 6px 0 10px; } +button.chip.preset { flex-direction: column; align-items: flex-start; gap: 0; border-radius: 9px; padding: 5px 9px; min-height: 42px; text-align: left; } +button.chip.preset b { font-size: 13px; } +button.chip.preset small { font-size: 10.5px; color: var(--dim); font-weight: 400; } +button.chip.preset.on small { color: #e0f2fe; } +details.more summary .tag { margin-left: 8px; font-size: 11px; padding: 1px 7px; border-radius: 9px; background: var(--panel3); color: var(--accent); } + +/* ------------------------------------------------------------- desktop app: remote access */ +.remote-urls { display: flex; flex-direction: column; gap: 4px; margin-top: 8px; } +.remote-urls code { font: 600 15px ui-monospace, Consolas, monospace; color: var(--accent); background: var(--panel2); + border: 1px solid var(--line); border-radius: 8px; padding: 6px 10px; user-select: all; } + +/* ------------------------------------------------------------- device form: network / USB */ +.devform .full { grid-column: 1 / -1; } +.devform [hidden] { display: none !important; } +.devform .sub { margin-top: 2px; color: var(--dim); font-weight: 500; font-size: 12px; } +.devform .row { flex-wrap: nowrap; } +.devform .row select { flex: 1 1 auto; min-width: 0; } + +/* channel links */ +.lnk { --lc: var(--warn); display: inline-flex; vertical-align: -2px; margin-left: 4px; color: var(--lc); } +.lnk svg, .linknote svg, .lkgroup svg, .lkmark svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; } +.linknote { --lc: var(--warn); color: var(--lc); margin: -4px 0 10px; } +.linknote svg { vertical-align: -2px; } +.lkgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 6px; } +.lkch { --lc: var(--line); position: relative; flex-direction: column; gap: 0; min-height: 58px; border-top: 3px solid var(--lc); } +.lkch small { color: var(--dim); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.lkch .lkmark { position: absolute; top: 4px; right: 5px; color: var(--lc); } +.lkch.sel { background: var(--accent2); border-color: var(--accent); color: #fff; } +.lkch.sel small { color: #dbeafe; } +.lkactions { margin-top: 10px; } +.lkgroups { display: flex; flex-direction: column; gap: 6px; margin-top: 12px; } +.lkgroup { --lc: var(--warn); border-left: 3px solid var(--lc); padding: 4px 0 4px 10px; background: var(--panel2); border-radius: 6px; } +.lkgroup svg { flex: none; color: var(--lc); } + +/* lock (desktop app) */ +#btn-lock { display: inline-flex; align-items: center; gap: 6px; } +#btn-lock[hidden] { display: none; } +#btn-lock.on { background: #3a2a0d; border-color: var(--warn); color: #fcd9a0; padding: 8px 12px; } +#btn-lock span { font-size: 13px; font-weight: 600; } +body.locked #main :is(button, input, select, .fader, canvas):not(.chsel, .nav, .strip-head, .xout, .band, [data-view-ok]), +body.locked #statusbar :is(button, select):not([data-view-ok]) { cursor: not-allowed; } + +/* limiter LED (outputs): orange bar under the channel name, lit while the DSP reports the limiter active */ +.limled { flex: none; display: block; width: 34px; height: 4px; margin-top: 3px; border-radius: 1px; + background: color-mix(in srgb, var(--led-o) 16%, transparent); transition: background .08s, box-shadow .08s; } +.limled.ph { visibility: hidden; } +.limled.on { background: var(--led-o); box-shadow: 0 0 6px var(--led-o), 0 0 2px var(--led-o); } +.limled.h { width: auto; height: auto; margin: 0; padding: 2px 6px; font-size: 10px; font-weight: 700; letter-spacing: .06em; + color: color-mix(in srgb, var(--led-o) 45%, transparent); } +.limled.h.on { color: #1a1000; } diff --git a/tests/test_protocol.py b/tests/test_protocol.py new file mode 100644 index 0000000..024e2e9 --- /dev/null +++ b/tests/test_protocol.py @@ -0,0 +1,127 @@ +"""Protocol self test: python tests/test_protocol.py""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from dsp import protocol as P # noqa: E402 + + +def test_frames_match_known_captures(): + # Known-good frames as sent to the devices (they also match the DSP 408 captures published by dsp-408-ui) + assert P.build_frame(0x10) == bytes.fromhex("10 02 00 01 01 10 10 03 11") + assert P.build_frame(0x40) == bytes.fromhex("10 02 00 01 01 40 10 03 41") + assert P.build_frame(0x29, b"\x13") == bytes.fromhex("10 02 00 01 02 29 13 10 03 38") + assert P.build_frame(0x35, b"\x0b\x01") == bytes.fromhex("10 02 00 01 03 35 0b 01 10 03 3c") + + +def test_parser_handles_split_and_embedded_dle(): + payload = bytes([5]) + b"\x10\x03\x10\x02" + bytes(46) + frame = P.build_frame(P.CMD_CONFIG_CHUNK, payload, addr=0, src=1) + parser = P.FrameParser() + out = parser.feed(b"\x00garbage" + frame[:7]) + parser.feed(frame[7:] + P.build_frame(0x01, b"\x00")) + assert [f.cmd for f in out] == [P.CMD_CONFIG_CHUNK, 0x01] + assert out[0].payload == payload and out[0].checksum_ok + + +def test_layout_matches_devices(): + m204, m408 = P.MODELS["204"], P.MODELS["408"] + assert (m204.size, m204.chunks) == (724, 15) + assert (m408.size, m408.chunks) == (1448, 29) + assert m204.out_base == 0x128 and m204.globals_base == 0x2B8 + assert m408.out_base == 0x240 and m408.globals_base == 0x580 + assert m204.channel("out", 0) == 2 and m408.channel("out", 0) == 4 + + +def test_state_roundtrip(): + for m in P.MODELS.values(): + st = P.default_state(m) + st["outputs"][-1]["comp"]["threshold"] = 123 + st["inputs"][0]["geq"][30] = 7 + st["inputs"][-1]["mute"] = True + assert P.parse_state(m, bytes(P.build_state_buffer(m, st))) == st + + +def test_scales(): + assert P.gain_to_db(0) == -60 and P.gain_to_db(80) == -20 and P.gain_to_db(280) == 0 and P.gain_to_db(400) == 12 + for raw in (0, 37, 80, 150, 280, 400): + assert P.db_to_gain(P.gain_to_db(raw)) == raw + assert round(P.freq_to_hz(0), 1) == 19.7 and round(P.freq_to_hz(300)) == 20159 + assert P.hz_to_freq(1000) == 170 + assert len(P.Q_TABLE) == 101 and len(P.SLOPES) == 21 + lv = [0.5, 0.0, 1.0, 0.001] + [0.25] * 8 + dec = P.decode_meters(P.encode_meters(lv)) + assert all(abs(a - b) < 1e-3 * max(a, 1e-3) for a, b in zip(lv, dec)) + + +def test_param_commands(): + m = P.MODELS["204"] + st = P.default_state(m) + out = st["outputs"][1] + P.apply_param(out, "peq.3.gain", 150) + assert P.param_command(m, "out", 1, out, "peq.3.gain") == (0x33, bytes([3, 3, 150, 0, 125, 0, 32, 0, 0])) + P.apply_param(out, "mix.1", 200) + assert P.param_command(m, "out", 1, out, "mix.1") == (0x41, bytes([3, 1, 200, 0])) + inp = st["inputs"][1] + assert P.param_command(m, "in", 1, inp, "gate.hold") == (0x3E, bytes([1, 0, 0, 99, 0, 99, 0, 0, 0])) + + +def test_links(): + # masks as read from a real DSP 204: In A+B, Out 1+2 and Out 3+4 linked + m = P.MODELS["204"] + st = P.default_state(m) + for ch, mask in zip(st["inputs"] + st["outputs"], [3, 0, 3, 0, 12, 0]): + ch["link"] = mask + st = P.parse_state(m, bytes(P.build_state_buffer(m, st))) + assert P.link_groups(st["inputs"]) == [[0, 1]] + assert P.link_groups(st["outputs"]) == [[0, 1], [2, 3]] + assert P.link_groups(P.default_state(m)["outputs"]) == [[0], [1], [2], [3]] + assert P.link_masks(4, [[0, 1], [2, 3]]) == [3, 0, 12, 0] + assert P.link_masks(4, [[3, 1]]) == [1, 10, 4, 0] + # the DSP applies a change on any member to the whole group, but not names + P.apply_command(m, st, P.CMD_GAIN, bytes([5, 100, 0])) + P.apply_command(m, st, P.CMD_CHANNEL_NAME, bytes([4]) + b"Sub ") + assert st["outputs"][2]["gain"] == 100 and st["outputs"][3]["name"] != "Sub" + + +def test_preset_import_commands(): + from dsp import preset + m = P.MODELS["204"] + cur = P.default_state(m) + assert preset.import_commands(m, cur, cur) == [] # identical: nothing is written + tgt = P.default_state(m) + tgt["outputs"][1]["gain"] = 300 + assert preset.import_commands(m, tgt, cur) == [(0x34, bytes([3]) + (300).to_bytes(2, "little"))] + tgt["outputs"][0]["link"], tgt["outputs"][1]["link"] = 3, 0 # new link: dissolve, set, relink + cmds = preset.import_commands(m, tgt, cur) + assert cmds[0][0] == P.CMD_LINK and (P.CMD_LINK, bytes([2, 3, 0])) in cmds + # a file is read with linked channels made alike, like the DSP keeps them + doc = preset.export_doc("204", "DSP204", tgt, bytes(P.build_state_buffer(m, tgt))[: m.size]) + st = preset.read_file("204", m, cur, doc=doc) + assert st["outputs"][1]["gain"] == st["outputs"][0]["gain"] == 280 + assert st["outputs"][1]["matrix"] == tgt["outputs"][1]["matrix"] # routing stays per channel + + + +def test_limit_flags(): + # status bytes after the 12 levels, captured on a DSP 204 while forcing the limiters + assert P.decode_limit_flags(bytes(36) + bytes([0x00, 0x03]), 4) == [True, True, False, False] + assert P.decode_limit_flags(bytes(36) + bytes([0x00, 0x0C]), 4) == [False, False, True, True] + assert P.decode_limit_flags(bytes(36), 4) == [False] * 4 + assert P.decode_limit_flags(P.encode_meters([0.0] * 12, 0x05), 4) == [True, False, True, False] + + + +def test_channel_names(): + # the DSP keeps 8 ASCII characters; umlauts are spelled out, anything else is dropped + assert P.clean_name("Bühne€ Links") == "Buehne L" + m = P.MODELS["204"] + assert P.param_command(m, "in", 0, {"name": "Süd"}, "name") == (0x3D, b"\x00Sued ") + + +if __name__ == "__main__": + for name, fn in list(globals().items()): + if name.startswith("test_"): + fn() + print("ok", name) diff --git a/win_disk.py b/win_disk.py new file mode 100644 index 0000000..8f7d16a --- /dev/null +++ b/win_disk.py @@ -0,0 +1,170 @@ +"""Raw SD card writing on Windows (needs administrator rights). + +Safety: only removable USB/SD/MMC disks that are neither the boot nor the system disk are offered. +The first MiB (partition table) is written last, so Windows does not mount half-written +partitions in the middle of the job - the same trick Raspberry Pi Imager uses. +""" + +import ctypes +import hashlib +import json +import lzma +import subprocess +import sys +import time +from pathlib import Path + +CHUNK = 4 << 20 # write size (multiple of the sector size) +HEAD = 1 << 20 # held back and written last +MAX_SIZE = 512 << 30 # larger "removable" disks are most likely not an SD card +NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0 + + +def is_admin() -> bool: + try: + return bool(ctypes.windll.shell32.IsUserAnAdmin()) + except (AttributeError, OSError): + return False + + +def relaunch_as_admin() -> bool: + """Restart this program elevated (UAC prompt). True if the elevated copy was started.""" + argv = sys.argv[1:] if getattr(sys, "frozen", False) else sys.argv # script: python