19 Commits
Author SHA1 Message Date
GivouandClaude Opus 5.5 83548c9620 README: disclaimer wording
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:52:31 +01:00
GivouandClaude Opus 5.5 cc95e2ccd8 README: vibe-coding disclaimer at the top
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:52:23 +01:00
GivouandClaude Opus 5.5 dc355fa160 Max level: grey zone between the limit and a knob set above it, red above the knob
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:42:12 +01:00
GivouandClaude Opus 5.5 06bc767f2c Max level: confirm typed values above the limit, cleaner limit display
- typing a gain above the max level shows the limit and a warning; Apply has to be
  clicked twice ("Set anyway"), the forced value also passes the server's lock
- sliders and faders show the locked range as a subtle striped zone in the track with a
  stop edge at the limit, behind the knob (no more line drawn over the knob)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:37:40 +01:00
GivouandClaude Opus 5.5 52695d20a5 Channel settings: colours before max level
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:32:22 +01:00
GivouandClaude Opus 5.5 52ecff85ce Network search, device ID, max level lock and the Channel settings tab
- network search: probes the local networks for DSPs (TCP 9761, asks for the device info)
  and adds them with one click
- device ID (address byte, 1-250) under the device's advanced settings
- the Link tab became "Channel settings": links, max level per channel and channel colours
  (colours moved here from the device settings); linked channels can't be selected again
- max level: software lock for the gain faders, enforced by the server (API, test fader,
  copy) and the UI; a DSP turned up on the device can only be pulled down until it snaps in
- global mute button only turns red (no text)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:29:41 +01:00
GivouandClaude Opus 5.5 9473fc9eca Stay in the settings after switching language or demo mode
The language switch reloads the page; it now comes back to the open settings at the same scroll position. Starting the demo selects the demo DSP without leaving the settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:15:57 +01:00
GivouandClaude Opus 5.5 5fc745cd72 Rework the settings page
- clear sections (general, devices, security / remote access, backup) with headings,
  short descriptions and a sticky quick-jump bar
- cards of equal height per row with their buttons aligned at the bottom, centred page width
- "add a DSP" is a compact card that opens the form (with cancel)
- phones: the DSP button shrinks instead of covering the mute/settings buttons

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:12:15 +01:00
GivouandClaude Opus 5.5 cf0adc01fe Top bar layout, adaptive sidebar menu and custom logo
- logo and DSP choice on the left, menu and buttons on the right
- the menu becomes a sidebar when it no longer fits in the top bar (measured, so it
  works for every language and device name); phones keep the bottom bar with short labels
- custom logo in the settings: any PNG/JPG/WebP/SVG is scaled to a 128x128 PNG,
  shown top left and as the browser icon, stored by the server and in the backup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:07:53 +01:00
GivouandClaude Opus 5.5 3a85f62225 DSP drop-down: clear chevron icon that flips when open
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:02:05 +01:00
GivouandClaude Opus 5.5 f87e6cad70 SoundField stacks (top on a distance pole on a sub), DSP selection as drop-down
- a top dropped onto a free sub stands on it (same spot, pole height); the stack moves
  as one, is drawn as one symbol and can be detached in the editor; "+ Stack" and a
  ground-stack quick start; centre cluster and height suggestions know about stacks
- the DSP tabs became one button with a drop-down menu (status dots of the other DSPs),
  so many devices fit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:59:38 +01:00
GivouandClaude Opus 5.5 eb647f62a9 Add channel colours: per channel or link group, unique per DSP, shown in mixer, channel view, routing and overlays
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:52:21 +01:00
GivouandClaude Opus 5.5 a7ee66d761 Add SoundField room planner, copy channel settings and global mute
SoundField (new tab, static/soundfield.js):
- top view of the room with stage, speakers placed by dragging and aimed with a handle,
  type presets, height, coverage, max SPL and DSP output assignment
- level map (tops by energy), sub map with phase at a chosen frequency, timing map
  for delay/fill speakers, audience statistics
- suggestions with one-click apply: aiming, main height, delay line, sub centre cluster
  (power alley), front fills, quick start layout
- delays from the speed of sound and temperature, written to the assigned DSP outputs
- plan stored by the server (shared, part of the settings backup)

Copy channel settings: level/filters/EQ/dynamics/routing to any channels of all connected DSPs.
Mute all: mutes every channel of every connected DSP and unmutes only what was open before,
also on DSPs that reconnect later; works while the app window is locked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:38:49 +01:00
GivouandClaude Opus 5.5 ffb6c05d47 Phase-inverted symbol without background, like the link symbol
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:17:09 +01:00
GivouandClaude Opus 5.5 58492e985f Fix PEQ sliders losing the mouse drag, show inverted polarity in the mixer
- PEQ sliders no longer rebuild themselves on every change (the browser lost
  the drag); only the band buttons and the curve are updated while dragging
- mixer strips show a "Ø" badge next to the link symbol when the polarity is inverted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:14:46 +01:00
GivouandClaude Opus 5.5 96640c5bff Fix overlay toggling, rework phase view, lock the app during the audio test
- overlay chips read the stored selection on every click (second click hides again)
- phase view: points keep their gain position and can be dragged in both
  directions, phase wraps are drawn as vertical lines like the original software,
  selected band shows Q / frequency / gain next to its point
- audio test: other tabs, settings and device switching are locked until the
  analog input is back; the server only accepts the test controls meanwhile
- test fader value has a fixed width and normal weight (meters no longer shift)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:01:44 +01:00
GivouandClaude Opus 5.5 ae9a20fdf8 Add phase view, channel overlays and PEQ/GEQ master bypass
- EQ curve computed as complex response: PEQ biquads (now incl. all-pass),
  crossover filters from Butterworth/Bessel/Linkwitz-Riley prototypes
- Mag/Phase switch; phase wraps at +-180 degrees like the original software
- overlay any other channel of the device in the curve (e.g. sub/top crossover)
- EQ Bypass (0x3C) for all PEQ bands, GEQ Bypass (0x49) for the inputs,
  read from the bit masks at the end of the memory image; preset import aware

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 21:47:15 +01:00
GivouandClaude Opus 5.5 66f988cf08 Add audio test tab with test generator, test fader and output mutes
- switch the DSP's test generator (pink/white noise, sine 20 Hz-20 kHz, command 0x39)
- entering lowers all outputs to -50 dB before the generator starts; one test fader
  raises them together; mute buttons for every output
- presets cannot be stored, recalled, imported or exported while the test runs
- leaving switches the generator off first, then restores every output gain
- a DSP found playing a test signal on connect goes straight into the audio test;
  saved gains survive an app restart (config.json)
- simulator and memory-image support for the test signal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 21:33:01 +01:00
GivouandClaude Opus 5.5 61400df667 Add device lock support and demo mode
Device lock (hardware lock of the DSP, independent of the app lock):
- detect a locked DSP from the 0x2C answer during connect and wait for the code
- unlock with 0x2D, optionally remember the code and unlock automatically
- set a new code (0x2F) from the device settings
- simulator: --lock CODE

Demo mode:
- switch in the settings starts a simulated DSP 204/408 inside the server
- real DSPs are disconnected and greyed out meanwhile and resume afterwards
- demo devices are never saved or exported; sim.py ships with the Pi image and EXEs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 21:14:04 +01:00
16 changed files with 2786 additions and 164 deletions

No files matched your search

+40 -3
View File
@@ -25,6 +25,31 @@ pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a system
* **`dsp/protocol.py`** – frames, checksum, value scales, model layouts (`MODELS["204"|"408"]`), memory image ↔ state * **`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. 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`). State values are **raw device values**; conversion to dB/Hz/ms happens in the UI (`SPEC` in `app.js`).
Channels also carry `peq_bypass` (master bypass, `0x3C`) and inputs `geq_bypass` (`0x49`), stored as bit masks at
the end of the memory image.
* **EQ curve** (`app.js`, `drawCurve`) – complex response per section: PEQ bands as RBJ biquads at 96 kHz, crossover
filters from analog prototypes (Butterworth poles, Bessel polynomial normalised to −3 dB, Linkwitz-Riley =
Butterworth²). Mag/Phase view (`dsp.curve` in localStorage), overlays of other channels (`dsp.overlay.<device>`).
How exactly the DSP realises the Bessel and crossover filters is not verified – the curves are the textbook ones.
* **Audio test** – `App.audio_test` / `set_test_level` / `check_audio_test` in `server.py`: entering saves the output
gains (`Device.test_saved`, persisted in `config.json` so an interrupted test is undone on the next connect),
lowers every output to −50 dB, flushes the queue and only then starts the generator (`0x39`); leaving switches the
generator off first, then restores the gains. While `Device.test_active` the server only accepts the test
controls (generator, test fader, output mutes) and the UI stays locked in the audio test tab. The state field is `state["test"] = {source, freq}`.
* **SoundField** (`static/soundfield.js`, plan stored by the server as `soundfield` in `config.json`, API
`/api/soundfield`) – room plan in metres (x across, y from the stage wall, aim 0° = into the room). Free-field model:
−6 dB per distance doubling, directivity from the coverage angle (−6 dB at its edges), tops summed by energy, subs
with phase at the chosen frequency. Delays: mains/subs aligned at the reference point, delay/fill speakers at their
target point plus the precedence offset. The canvas is only redrawn while dragging (never rebuilt), the side panels
are rebuilt after a change; the local plan object stays the one being edited (a save does not replace it).
* **Max level** – `Device.maxgain` (raw gain per channel, app-side) and `Device.gain_cap`: every gain the server sets
(API, test fader, copy) is capped at max(limit, current value), so a DSP turned up on the device can only go down
until it is below the limit again. The client mirrors this in `gainCap` (faders, sliders, `setParam`).
* **Network search** – `App.scan_network` probes the local /24 networks on TCP 9761 (handshake + device info),
skipping DSPs this app is connected to.
* **Copy settings / mute all** – `App.copy_settings` (`POST /api/copy`, groups level/filters/eq/dynamics/routing) and
`App.set_mute_all` (`POST /api/muteall`; remembers per device which channels were open, persisted in `config.json`
as `mute_all`, released devices that were offline are unmuted when they reconnect; allowed while the app is locked).
* **`dsp/preset.py`** – preset files (`dsp-control-preset` JSON with state + raw image), validation, and the minimal * **`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). 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*`. * **`dsp/usbhid.py`** – HID via ctypes only: Windows `hid.dll`/SetupAPI, macOS IOKit, Linux `/dev/hidraw*`.
@@ -33,7 +58,14 @@ pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a system
current view (`mixer`, `channel`, `routing`, `link`, `limiter`, `settings`). Live widgets register in `live` and are 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 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()`). `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. * **`sim.py`** – simulated DSP 204/408 speaking the same protocol (meters, limiter flags, links, lock code via
`--lock`). Use it for all tests. The server also imports it for the **demo mode** (`App.start_demo`: real
devices are stopped, a `SimDSP` runs on a random localhost port, a `Device` with `demo = True` connects to it;
demo devices are never saved, exported or editable). `sim.py` therefore ships with the Pi image and the EXEs.
* **Device lock** (hardware, unrelated to the app lock) – `Device._wait_for_unlock` holds the init after `0x2C`
reports a lock, tries the remembered code (`lock_code` + `auto_unlock` in `config.json`, clients only see a
boolean) or sets status `locked` and waits for `POST /api/devices/<id>/unlock {code, remember}`.
`POST …/lockcode {code}` sets a new code.
* **`desktop.py`** – starts `server.App` on 127.0.0.1 with a random port in a thread and opens a pywebview window. * **`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 `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`. named mutex (Windows) or lock file (macOS). Data in `%APPDATA%\DSP Control` / `~/Library/Application Support/DSP Control`.
@@ -77,8 +109,13 @@ Not verified yet – ask for a log (`python server.py -v`) from real hardware be
* **DSP 408 on real hardware** (layout and frames match published captures, limiter bits for Out 5–8 assumed) * **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) * 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 * Where the PEQ bypass flag lives in the memory image; format of the set-command acknowledgement; where the number
preset-count answer (`0x2C`) of preset slots comes from (20 is assumed when the `0x2C` answer carries the lock state)
* Master bypass commands `0x3C` / `0x49` and their bit masks – from the control software, simulator only
* Test signal command `0x39` and its position in the memory image – derived from the control software, simulator
only; whether the generator is pre or post input gain is unknown (the app therefore only lowers the outputs)
* Device lock (`0x2C` byte 5, `0x2D`, `0x2F`, `0x11`) – implemented from the control software's behaviour and
tested against the simulator only; no command to remove a lock is known
* Limiter calculator reference level (assumes limiter 0 dB = 0 dBu at the output; adjustable per device) * 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) * Pi Writer: raw write to a real SD card and first boot on a real Pi (only tested with an image file)
+27 -2
View File
@@ -36,7 +36,7 @@ All 16-bit words are little endian.
|-----|-----------|---------|---------| |-----|-----------|---------|---------|
| `10` | → | – | Handshake | | `10` | → | – | Handshake |
| `13` | → / ← | – / ASCII | Device info, answer starts with `DSP204` or `DSP408` | | `13` | → / ← | – / ASCII | Device info, answer starts with `DSP204` or `DSP408` |
| `2C` | → / ← | – / `[?][count]` | Number of presets (payload meaning partly *assumed*) | | `2C` | → / ← | – / `[time lock][4 bytes][device lock]` | Lock state, see [Device lock](#device-lock) |
| `22`, `14` | → | – | Init queries (sent during connect, content unknown) | | `22`, `14` | → | – | Init queries (sent during connect, content unknown) |
| `29` | → / ← | `[idx]` / `[idx][name…]` | Preset name (idx 0-based) | | `29` | → / ← | `[idx]` / `[idx][name…]` | Preset name (idx 0-based) |
| `20` | → | `[idx+1]` | Recall preset | | `20` | → | `[idx+1]` | Recall preset |
@@ -45,6 +45,9 @@ All 16-bit words are little endian.
| `27` | → | `[chunk]` | Request config chunk | | `27` | → | `[chunk]` | Request config chunk |
| `24` | ← | `[chunk][50 bytes]` | Config chunk; 204: chunks 0…14, 408: 0…28 | | `24` | ← | `[chunk][50 bytes]` | Config chunk; 204: chunks 0…14, 408: 0…28 |
| `12` | → | – | Status (sent after the dump) | | `12` | → | – | Status (sent after the dump) |
| `2D` | → / ← | `[0][code 4]` / `[0][result]` | Unlock with the lock code, result `1` = unlocked, `0` = wrong code |
| `2F` | → | `[code 4]` | Set a new lock code |
| `11` | → | – | Sent after setting a lock code (meaning not fully known) |
| `40` | → / ← | – / meters | Read levels (also serves as keepalive) | | `40` | → / ← | – / meters | Read levels (also serves as keepalive) |
### Meter answer ### Meter answer
@@ -84,6 +87,9 @@ All 16-bit words are little endian.
| `41` | Mix level (outputs) | `[ch][input][u16 level]` | | `41` | Mix level (outputs) | `[ch][input][u16 level]` |
| `3D` | Channel name | `[ch][name 8]` (printable ASCII) | | `3D` | Channel name | `[ch][name 8]` (printable ASCII) |
| `3B` | Link | `[ch][u16 link mask]` (see [Channel links](#channel-links)) | | `3B` | Link | `[ch][u16 link mask]` (see [Channel links](#channel-links)) |
| `3C` | PEQ bypass | `[ch][0/1]` – all PEQ bands of the channel bypassed |
| `49` | GEQ bypass (inputs) | `[ch][0/1]` |
| `39` | Test signal | `[source][freq]` – source 0 = analog inputs, 1 = pink noise, 2 = white noise, 3 = sine; freq = index 0–30 of the 1/3-octave frequencies 20 Hz…20 kHz (as the GEQ) |
| `15` | Delay unit | `[unit]` (display only) | | `15` | Delay unit | `[unit]` (display only) |
The format of the acknowledgement the DSP sends after a set command is not fully understood yet. The format of the acknowledgement the DSP sends after a set command is not fully understood yet.
@@ -126,6 +132,20 @@ or within the outputs):
* A member with mask `00` that is not part of a group ignores changes: when unlinking, give every channel its own * A member with mask `00` that is not part of a group ignores changes: when unlinking, give every channel its own
bit again. bit again.
## Device lock
The DSP can be protected with a 4-character code (digits and upper-case letters, e.g. `A1BA`, sent as ASCII).
* During connect, the answer to `2C` reports the lock state: byte 5 ≠ 0 means the device is locked. Byte 0 and
bytes 1–4 belong to a separate time-based lock that this app does not use.
* A locked device waits for `2D [00][code]` before the rest of the initialisation (`22`, `14`, preset names, dump).
The answer `2D [00][01]` means unlocked, `2D [00][00]` wrong code.
* `2F [code]` stores a new code; the control software sends `11` afterwards. The device asks for the new code from
the next connection on. A command to remove the lock is not known.
Status: derived from the behaviour of the control software and implemented against the simulator; **not yet
verified on a real device**.
## Config dump = memory image ## Config dump = memory image
Chunk `n` carries bytes `n·50 … n·50+49` of the device memory image. Chunk `n` carries bytes `n·50 … n·50+49` of the device memory image.
@@ -149,7 +169,12 @@ Chunk `n` carries bytes `n·50 … n·50+49` of the device memory image.
… comp: ratio, attack, release, knee, threshold (5×u16) … comp: ratio, attack, release, knee, threshold (5×u16)
… limit: attack, release, knee, threshold (4×u16) … limit: attack, release, knee, threshold (4×u16)
… u16 gain, u16 polarity, u16 delay, u16 link mask … u16 gain, u16 polarity, u16 delay, u16 link mask
u16 input mute bit mask, u16 output mute bit mask, then unknown fields u16 input mute bit mask, u16 output mute bit mask
u16[nIn + nOut] unknown
u16 test signal source, u16 test signal frequency index (see command 39)
u16 unknown
u16 PEQ bypass bit mask inputs, u16 PEQ bypass bit mask outputs (command 3C)
u16 GEQ bypass bit mask inputs (command 49)
``` ```
Total size: DSP 204 = 724 bytes (15 chunks), DSP 408 = 1448 bytes (29 chunks). Total size: DSP 204 = 724 bytes (15 chunks), DSP 408 = 1448 bytes (29 chunks).
+46 -7
View File
@@ -1,5 +1,16 @@
# BetterDSPControl # BetterDSPControl
> [!WARNING]
> **Vibe-coded – read this first.** I'm a hobbyist and wrote this app almost entirely with an AI coding assistant,
> for my own two DSPs. It works for me, but large parts have only been tested against a simulator, and some protocol
> details are educated guesses (see [Verified vs. unverified](CLAUDE.md#verified-vs-unverified)).
> It talks directly to your loudspeaker processor and can change gains, limiters and crossovers – a wrong value can
> be loud and can damage speakers. **Export a preset before you start, keep the volume down while trying things out,
> and don't use it on a show you can't afford to lose.**
> You use it entirely at your own risk. I'm not responsible for anything that happens to your DSP, your speakers,
> your ears, your gig or your neighbours – nor for anything else, should the sky fall on you while you use it.
> No warranty of any kind (see [LICENSE](LICENSE)).
**A modern, phone-friendly control app for the t.racks DSP 204 and DSP 408 loudspeaker processors.** **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. Control both devices at the same time from your phone, tablet or computer – over the network or USB.
@@ -15,20 +26,47 @@ Control both devices at the same time from your phone, tablet or computer – ov
## Features ## Features
* **Several devices at once** – switch with the tabs at the top; the model is detected automatically * **Several devices at once** – pick the DSP from the drop-down at the top (small dots show the status of the others);
the model is detected automatically
* **Mixer** – faders, mute and live meters for all inputs and outputs, limiter LED on every output (status read * **Mixer** – faders, mute and live meters for all inputs and outputs, limiter LED on every output (status read
from the DSP) from the DSP)
* **Channel** – name, gain, delay, polarity, high/low pass, 8/9-band PEQ with a draggable curve * **Channel** – name, gain, delay, polarity, high/low pass, 8/9-band PEQ with a draggable curve; the curve shows
* **Inputs** – noise gate, 31-band GEQ · **Outputs** – compressor, limiter, input routing with mix levels magnitude or phase (crossover filters, all-pass filters) and can overlay any other channel, e.g. to line up a
sub/top crossover; **EQ Bypass** switches all PEQ bands off at once
* **Inputs** – noise gate, 31-band GEQ with **GEQ Bypass** · **Outputs** – compressor, limiter, input routing with mix levels
* **Routing matrix**, recall and store presets * **Routing matrix**, recall and store presets
* **Channel links** – link channels into groups; the DSP mirrors changes within the group, the app shows them live * **Channel settings** tab – link channels into groups (the DSP mirrors changes within the group), set a **max level**
per channel (software lock: the fader can't go higher; if the DSP itself is turned up, it can only be pulled down until
it snaps into the limit again) and pick channel colours
* **Preset files** – export the current DSP state to a file and import it again. An import only changes the active * **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 state (stored presets stay untouched), writes only what actually differs and makes an automatic backup first
("Undo import") ("Undo import")
* **Limiter calculator** – enter your amplifiers' datasheet values (power at 8/4/2 Ω, sensitivity or gain), assign * **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. 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) "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 * **SoundField** – top view of the room: place mains, subs, delays and fills by dragging (tops can stand on a sub with a
distance pole – drop the top onto the sub), see a level map, a sub
map at a chosen frequency (phase-correct, shows cancellation lanes) and a timing map for delay speakers. It
suggests aiming, height, delay lines, sub placement and front fills (one click to apply), calculates the delays
from the speed of sound and writes them to the assigned DSP outputs
* **Copy channel settings** – level/delay/polarity, filters, EQ, dynamics and routing from one channel to any number
of channels on all connected DSPs
* **Channel colours** – line and lightly tinted name in the mixer, channel view, routing and curve overlays; linked
channels share one colour, every colour is used once per DSP
* **Network search** – finds DSPs in the local network and adds them with one click; the device ID (address byte,
default 1) is under the device's advanced settings
* **Custom logo** – your own logo top left and as the browser icon (settings → Logo; PNG/JPG/WebP/SVG, ideally square, ≥ 64×64 px)
* **Fits every screen** – menu in the top bar on wide screens, a sidebar when the window gets narrow, a bottom bar on phones
* **Mute all** – one button mutes every channel of every connected DSP; releasing it unmutes only what was open before
* **Settings backup** – devices, amplifier data, SoundField plan, PIN and remote access in one file
* **Device lock** – DSPs locked with their 4-character code (e.g. `A1BA`) are detected on connect and the app asks
for the code; optionally it remembers the code and unlocks automatically. A new code can be set under ⚙
* **Audio test** – switch the DSP's test generator (pink noise, white noise, sine 20 Hz–20 kHz) on and off. All
outputs drop to −50 dB first and a single test fader raises them together; mute buttons for every output.
Presets can't be saved or recalled meanwhile, and stopping the test switches the noise off before every fader
returns to its previous value. A DSP found playing a test signal on connect goes straight into this mode
* **Demo mode** – one switch under ⚙ starts a simulated DSP 204 or 408 inside the app to try everything; the real
DSPs are disconnected meanwhile and nothing is sent to them
* **Many phones at once** – every change is pushed live to all connected clients * **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 * 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
@@ -117,7 +155,8 @@ DSPs on USB, pick the right one in the drop-down.
## Testing without hardware ## Testing without hardware
A simulator emulates both models: The quickest way is the **demo mode** (⚙ → Demo mode). For development, a stand-alone simulator emulates both
models (`--lock A1BA` makes it ask for a lock code):
```bash ```bash
python sim.py --model 204 --port 9761 python sim.py --model 204 --port 9761
@@ -149,7 +188,7 @@ python tests/test_protocol.py
| `sim.py` | Simulated DSP 204/408 | | `sim.py` | Simulated DSP 204/408 |
| `desktop.py` | Desktop app (Windows/macOS): server + own window (pywebview) | | `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 | | `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` | | `static/` | Web UI (`app.js`, `style.css`, `index.html`), SoundField in `static/soundfield.js`, translations in `static/i18n.js` |
| `packaging/` | Build script and icons | | `packaging/` | Build script and icons |
| `tests/` | Protocol tests | | `tests/` | Protocol tests |
| `PROTOCOL.md` | Protocol documentation | | `PROTOCOL.md` | Protocol documentation |
+107 -7
View File
@@ -20,7 +20,9 @@ LINK_RESYNC_DELAY = 1.5 # re-read the config this long after the last change on
class Device: class Device:
def __init__(self, dev_id: str, name: str, host: str, port: int = P.PORT, model: str = "auto", 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 = ""): addr: int = 1, autoconnect: bool = True, on_event=None, transport: str = "tcp", usb: str = "",
lock_code: str = "", auto_unlock: bool = False, test_saved: list | None = None,
colors: dict | None = None, maxgain: dict | None = None):
self.id = dev_id self.id = dev_id
self.name = name self.name = name
self.host = host self.host = host
@@ -31,8 +33,18 @@ class Device:
self.transport = "usb" if transport == "usb" else "tcp" self.transport = "usb" if transport == "usb" else "tcp"
self.usb = usb # HID device path, "" = first DSP found self.usb = usb # HID device path, "" = first DSP found
self.on_event = on_event or (lambda ev: None) self.on_event = on_event or (lambda ev: None)
# hardware lock of the DSP itself (not the app lock): remembered code for automatic unlocking
self.lock_code = lock_code if P.LOCK_CODE.fullmatch(lock_code or "") else ""
self.auto_unlock = auto_unlock
self.demo = False # in-process simulator of the demo mode, never saved
self.colors: dict[str, str] = colors or {} # channel colours chosen in the app, e.g. {"in0": "#38bdf8"}
self.maxgain: dict[str, int] = maxgain or {} # software limit of the gain fader per channel (raw), e.g. {"out0": 260}
# audio test: output gains from before the test (restored when it ends) and the test fader level
self.test_saved: list[int] | None = test_saved if isinstance(test_saved, list) else None
self.test_level = -50.0
self.on_online = None # async callback(device) once a connection is fully loaded
self.status = "disconnected" # disconnected | connecting | loading | online | error self.status = "disconnected" # disconnected | connecting | loading | locked | online | error
self.error = "" self.error = ""
self.info = "" self.info = ""
self.model: P.Model | None = P.MODELS.get(model) self.model: P.Model | None = P.MODELS.get(model)
@@ -53,16 +65,22 @@ class Device:
self._want_connected = False self._want_connected = False
self._resync: asyncio.TimerHandle | None = None self._resync: asyncio.TimerHandle | None = None
self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits
self._codes: asyncio.Queue | None = None # (code, future) entered while the DSP is locked
# ------------------------------------------------------------ public API # ------------------------------------------------------------ public API
def config(self) -> dict: def config(self) -> dict:
return {"id": self.id, "name": self.name, "host": self.host, "port": self.port, return {"id": self.id, "name": self.name, "host": self.host, "port": self.port,
"model": self.model_key, "addr": self.addr, "autoconnect": self.autoconnect, "model": self.model_key, "addr": self.addr, "autoconnect": self.autoconnect,
"transport": self.transport, "usb": self.usb} "transport": self.transport, "usb": self.usb,
"lock_code": self.lock_code, "auto_unlock": self.auto_unlock, "test_saved": self.test_saved,
"colors": self.colors, "maxgain": self.maxgain}
def snapshot(self) -> dict: def snapshot(self) -> dict:
return {**self.config(), "status": self.status, "error": self.error, "info": self.info, cfg = self.config()
cfg["lock_code"] = bool(self.lock_code) # clients only learn whether a code is remembered
cfg["test_level"] = self.test_level
return {**cfg, "demo": self.demo, "status": self.status, "error": self.error, "info": self.info,
"detected_model": self.model_name or None, "detected_model": self.model_name or None,
"n_in": self.model.n_in if self.model else 0, "n_in": self.model.n_in if self.model else 0,
"n_out": self.model.n_out if self.model else 0, "n_out": self.model.n_out if self.model else 0,
@@ -75,8 +93,6 @@ class Device:
async def stop(self): async def stop(self):
self._want_connected = False 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: if self._supervisor:
self._supervisor.cancel() self._supervisor.cancel()
try: try:
@@ -121,6 +137,58 @@ class Device:
await asyncio.sleep(0.3) await asyncio.sleep(0.3)
await self.refresh() await self.refresh()
def gain_cap(self, kind: str, idx: int, value: int) -> int:
"""Software limit of a channel's gain: never above the limit - unless the DSP itself is set higher,
then only downwards (it snaps back into the limit once it is below)."""
lim = self.maxgain.get(f"{kind}{idx}")
if lim is None or not self.state:
return value
cur = self.state["inputs" if kind == "in" else "outputs"][idx]["gain"]
return min(value, max(lim, cur))
@property
def test_active(self) -> bool:
return bool(self.state and self.state.get("test", {}).get("source"))
async def set_test_signal(self, source: int, freq: int):
"""Switch the inputs to a test generator (1 pink, 2 white, 3 sine) or back to the analog inputs (0)."""
if self.status != "online" or not self.state:
raise RuntimeError("DSP is not connected")
await self.flush() # queued changes (e.g. lowered faders) reach the DSP first
await self._request(P.CMD_TEST_SIGNAL, bytes([source, freq]))
self.state["test"] = {"source": source, "freq": freq}
self.on_event({"type": "test", "device": self.id, "test": self.state["test"]})
async def flush(self):
"""Wait until every queued parameter change has been sent."""
while self._pending:
await asyncio.sleep(0.01)
async with self._lock: # the last one may still wait for its answer
pass
async def unlock(self, code: str) -> bool:
"""Try a lock code while the DSP waits for it. True if the DSP accepted it."""
code = str(code or "").strip().upper()
if not P.LOCK_CODE.fullmatch(code):
raise ValueError("The code has 4 characters: digits and letters A–Z")
if self.status != "locked" or not self._codes:
raise RuntimeError("The DSP is not locked")
fut = asyncio.get_running_loop().create_future()
await self._codes.put((code, fut))
return await fut
async def set_lock_code(self, code: str):
"""Store a new lock code in the DSP; it asks for it from the next connection on."""
code = str(code or "").strip().upper()
if not P.LOCK_CODE.fullmatch(code):
raise ValueError("The code has 4 characters: digits and letters A–Z")
if self.status != "online":
raise RuntimeError("DSP is not connected")
if self.lock_code: # keep auto-unlock working with the new code
self.lock_code = code
await self._request(P.CMD_SET_LOCK_CODE, code.encode("ascii"))
await self._request(P.CMD_LOGOUT) # as the original software does after setting the code
def _schedule_resync(self): def _schedule_resync(self):
"""Re-read the config shortly after edits on linked channels, so the app shows exactly """Re-read the config shortly after edits on linked channels, so the app shows exactly
what the DSP applied to the group (e.g. mute, which we don't mirror for certain).""" what the DSP applied to the group (e.g. mute, which we don't mirror for certain)."""
@@ -225,6 +293,8 @@ class Device:
self._set_status("online") self._set_status("online")
self._emit_state() self._emit_state()
self._tasks += [asyncio.create_task(self._write_loop()), asyncio.create_task(self._meter_loop())] self._tasks += [asyncio.create_task(self._write_loop()), asyncio.create_task(self._meter_loop())]
if self.on_online:
asyncio.create_task(self.on_online(self))
done, _ = await asyncio.wait(self._tasks, return_when=asyncio.FIRST_COMPLETED) done, _ = await asyncio.wait(self._tasks, return_when=asyncio.FIRST_COMPLETED)
for t in done: for t in done:
if t.exception(): if t.exception():
@@ -293,8 +363,11 @@ class Device:
if detected and detected != 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) 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_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 payload = count_frame.payload if count_frame else b""
count = payload[-1] if 0 < len(payload) < 6 else 20 # the long answer carries the lock state instead
count = count if 0 < count <= 60 else 20 count = count if 0 < count <= 60 else 20
if P.device_locked(payload):
await self._wait_for_unlock()
await self._request(P.CMD_INIT_22) await self._request(P.CMD_INIT_22)
await self._request(P.CMD_INIT_14) await self._request(P.CMD_INIT_14)
presets = [] presets = []
@@ -304,6 +377,33 @@ class Device:
self.presets = presets self.presets = presets
await self._load_config() await self._load_config()
async def _try_code(self, code: str) -> bool:
f = await self._request(P.CMD_UNLOCK, b"\x00" + code.encode("ascii"), timeout=2.0, expect=P.CMD_UNLOCK)
return bool(f and len(f.payload) > 1 and f.payload[1] == 1)
async def _wait_for_unlock(self):
"""The DSP is locked with its code: unlock automatically or wait until a code is entered."""
if self.auto_unlock and self.lock_code:
if await self._try_code(self.lock_code):
log.info("%s: unlocked automatically", self.name)
return
log.warning("%s: remembered lock code was rejected", self.name)
self.error = "The remembered lock code was rejected"
self._codes = asyncio.Queue()
self._set_status("locked")
try:
while True:
code, fut = await self._codes.get()
ok = await self._try_code(code)
if not fut.done():
fut.set_result(ok)
if ok:
self.error = ""
self._set_status("loading")
return
finally:
self._codes = None
async def _load_config(self): async def _load_config(self):
self.state = await self._read_config() self.state = await self._read_config()
+4 -3
View File
@@ -58,7 +58,7 @@ def _common(s: dict, c: dict) -> dict:
"hp": _filter(s.get("hp"), c["hp"]), "lp": _filter(s.get("lp"), c["lp"]), "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"])), "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"]), "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"]))} "mute": bool(s.get("mute", c["mute"])), "peq_bypass": bool(s.get("peq_bypass", c.get("peq_bypass", False)))}
def clean_state(model: P.Model, src: dict, base: dict) -> dict: def clean_state(model: P.Model, src: dict, base: dict) -> dict:
@@ -70,6 +70,7 @@ def clean_state(model: P.Model, src: dict, base: dict) -> dict:
s = ins[i] if i < len(ins) and isinstance(ins[i], dict) else {} s = ins[i] if i < len(ins) and isinstance(ins[i], dict) else {}
geq = s.get("geq") if isinstance(s.get("geq"), list) 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), c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]), gate=_group(s.get("gate"), c["gate"], _GATE),
geq_bypass=bool(s.get("geq_bypass", c.get("geq_bypass", False))),
geq=[_int(geq[b], 0, 240, v) if b < len(geq) else v for b, v in enumerate(c["geq"])]) 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"]): for i, c in enumerate(st["outputs"]):
s = outs[i] if i < len(outs) and isinstance(outs[i], dict) else {} s = outs[i] if i < len(outs) and isinstance(outs[i], dict) else {}
@@ -131,9 +132,9 @@ def import_commands(model: P.Model, st: dict, current: dict) -> list[tuple[int,
cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + (1 << i).to_bytes(2, "little"))) cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + (1 << i).to_bytes(2, "little")))
for kind, key in kinds: for kind, key in kinds:
for i, ch in enumerate(st[key]): for i, ch in enumerate(st[key]):
params = ["name", "gain", "polarity", "delay", "hp", "lp"] + [f"peq.{b}" for b in range(len(ch["peq"]))] params = ["name", "gain", "polarity", "delay", "hp", "lp", "peq_bypass"] + [f"peq.{b}" for b in range(len(ch["peq"]))]
if kind == "in": if kind == "in":
params += [f"geq.{b}" for b in range(len(ch["geq"]))] + ["gate"] params += [f"geq.{b}" for b in range(len(ch["geq"]))] + ["gate", "geq_bypass"]
else: else:
params += ["comp", "limit", "matrix"] + [f"mix.{k}" for k in range(len(ch["mix"]))] params += ["comp", "limit", "matrix"] + [f"mix.{k}" for k in range(len(ch["mix"]))]
for p in params + ["mute"]: for p in params + ["mute"]:
+47 -5
View File
@@ -2,6 +2,7 @@
import copy import copy
import math import math
import re
import struct import struct
from dataclasses import dataclass from dataclasses import dataclass
@@ -10,6 +11,7 @@ PORT = 9761
# Read / system commands # Read / system commands
CMD_ACK = 0x01 CMD_ACK = 0x01
CMD_HANDSHAKE = 0x10 CMD_HANDSHAKE = 0x10
CMD_LOGOUT = 0x11 # sent after setting a lock code
CMD_STATUS = 0x12 CMD_STATUS = 0x12
CMD_DEVICE_INFO = 0x13 CMD_DEVICE_INFO = 0x13
CMD_INIT_14 = 0x14 CMD_INIT_14 = 0x14
@@ -20,7 +22,12 @@ CMD_CONFIG_CHUNK = 0x24
CMD_PRESET_STORE_NAME = 0x26 CMD_PRESET_STORE_NAME = 0x26
CMD_CONFIG_REQUEST = 0x27 CMD_CONFIG_REQUEST = 0x27
CMD_PRESET_NAME = 0x29 CMD_PRESET_NAME = 0x29
CMD_PRESET_COUNT = 0x2C CMD_PRESET_COUNT = 0x2C # answer: [time lock][4 bytes time lock data][device lock] (see device_locked)
CMD_UNLOCK = 0x2D # [0][code 4] -> answer [0][1 = unlocked, 0 = wrong code]
CMD_SET_LOCK_CODE = 0x2F # [code 4]
CMD_PEQ_BYPASS = 0x3C # [ch][1 = all PEQ bands bypassed]
CMD_GEQ_BYPASS = 0x49 # [ch][1 = GEQ bypassed] (inputs)
CMD_TEST_SIGNAL = 0x39 # [source][freq index]: 0 = analog input, 1 = pink noise, 2 = white noise, 3 = sine
CMD_METER = 0x40 CMD_METER = 0x40
# Parameter commands # Parameter commands
@@ -41,6 +48,13 @@ CMD_GEQ = 0x48
CMD_LINK = 0x3B # [ch][u16 link mask], see link_masks() CMD_LINK = 0x3B # [ch][u16 link mask], see link_masks()
CHUNK_SIZE = 50 CHUNK_SIZE = 50
TEST_SOURCES = ("analog", "pink", "white", "sine")
LOCK_CODE = re.compile(r"[A-Z0-9]{4}") # device lock code: 4 characters, digits and upper-case letters
def device_locked(count_payload: bytes) -> bool:
"""True if the answer to CMD_PRESET_COUNT says the DSP waits for its lock code."""
return len(count_payload) > 5 and count_payload[5] != 0
def checksum(data: bytes) -> int: def checksum(data: bytes) -> int:
@@ -212,6 +226,11 @@ class Model:
def globals_base(self) -> int: def globals_base(self) -> int:
return self.out_base + self.n_out * self.out_size return self.out_base + self.n_out * self.out_size
@property
def test_base(self) -> int:
"""Test signal (source, sine frequency index), after the mute masks and one word per channel."""
return self.globals_base + 4 + 2 * self.n_in + 2 * self.n_out
@property @property
def size(self) -> int: def size(self) -> int:
return self.globals_base + 4 + 2 * self.n_in + 2 * self.n_out + 12 return self.globals_base + 4 + 2 * self.n_in + 2 * self.n_out + 12
@@ -305,7 +324,13 @@ def parse_state(model: Model, buf: bytes) -> dict:
"link": u16(p + 84), "link": u16(p + 84),
"mute": bool(out_mute >> i & 1), "mute": bool(out_mute >> i & 1),
}) })
return {"preset_name": _name(buf[2:16]), "inputs": inputs, "outputs": outputs} source, freq, _, peq_in, peq_out, geq_in = struct.unpack_from("<6H", buf, model.test_base)
test = {"source": source if source < len(TEST_SOURCES) else 0, "freq": freq if freq < 31 else 0}
for i, ch in enumerate(inputs):
ch["peq_bypass"], ch["geq_bypass"] = bool(peq_in >> i & 1), bool(geq_in >> i & 1)
for i, ch in enumerate(outputs):
ch["peq_bypass"] = bool(peq_out >> i & 1)
return {"preset_name": _name(buf[2:16]), "inputs": inputs, "outputs": outputs, "test": test}
def build_state_buffer(model: Model, state: dict) -> bytearray: def build_state_buffer(model: Model, state: dict) -> bytearray:
@@ -349,6 +374,11 @@ def build_state_buffer(model: Model, state: dict) -> bytearray:
struct.pack_into("<4H", buf, p + 78, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i)) struct.pack_into("<4H", buf, p + 78, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
out_mute |= int(ch["mute"]) << i out_mute |= int(ch["mute"]) << i
struct.pack_into("<HH", buf, model.globals_base, in_mute, out_mute) struct.pack_into("<HH", buf, model.globals_base, in_mute, out_mute)
test = state.get("test") or {}
mask = lambda chans, key: sum(int(bool(ch.get(key))) << i for i, ch in enumerate(chans))
struct.pack_into("<HH", buf, model.test_base, test.get("source", 0), test.get("freq", 0))
struct.pack_into("<3H", buf, model.test_base + 6, mask(state["inputs"], "peq_bypass"),
mask(state["outputs"], "peq_bypass"), mask(state["inputs"], "geq_bypass"))
return buf return buf
@@ -361,15 +391,16 @@ def default_state(model: Model) -> dict:
"name": f"In{chr(65 + i)}", "gate": {"attack": 0, "release": 99, "hold": 99, "threshold": 0}, "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}, "geq": [120] * 31, "peq": peq(8), "hp": {"freq": 0, "slope": 0},
"lp": {"freq": 300, "slope": 0}, "gain": 280, "polarity": False, "delay": 0, "mute": False, "lp": {"freq": 300, "slope": 0}, "gain": 280, "polarity": False, "delay": 0, "mute": False,
"link": 1 << i, "link": 1 << i, "peq_bypass": False, "geq_bypass": False,
} for i in range(model.n_in)], } for i in range(model.n_in)],
"outputs": [{ "outputs": [{
"name": f"Out{i + 1}", "matrix": 1 << (i % model.n_in), "mix": [280] * model.n_in, "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), "hp": {"freq": 0, "slope": 0}, "lp": {"freq": 300, "slope": 0}, "peq": peq(9),
"comp": {"ratio": 0, "attack": 49, "release": 499, "knee": 0, "threshold": 220}, "comp": {"ratio": 0, "attack": 49, "release": 499, "knee": 0, "threshold": 220},
"limit": {"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, "gain": 280, "polarity": False, "delay": 0, "mute": False, "link": 1 << i, "peq_bypass": False,
} for i in range(model.n_out)], } for i in range(model.n_out)],
"test": {"source": 0, "freq": 17},
} }
@@ -452,6 +483,10 @@ def param_command(model: Model, kind: str, idx: int, ch: dict, param: str) -> tu
b = ch["peq"][band] b = ch["peq"][band]
return CMD_PEQ, bytes([c, band]) + _w(b["gain"]) + _w(b["freq"]) + bytes( return CMD_PEQ, bytes([c, band]) + _w(b["gain"]) + _w(b["freq"]) + bytes(
[b["q"], b["type"], int(b["bypass"])]) [b["q"], b["type"], int(b["bypass"])])
if top == "peq_bypass":
return CMD_PEQ_BYPASS, bytes([c, int(ch["peq_bypass"])])
if top == "geq_bypass" and kind == "in":
return CMD_GEQ_BYPASS, bytes([c, int(ch["geq_bypass"])])
if top == "geq" and kind == "in": if top == "geq" and kind == "in":
band = int(rest[0]) band = int(rest[0])
return CMD_GEQ, bytes([c, band]) + _w(ch["geq"][band]) return CMD_GEQ, bytes([c, band]) + _w(ch["geq"][band])
@@ -490,6 +525,9 @@ def apply_command(model: Model, state: dict, cmd: int, p: bytes):
"""Update state from an incoming set command (used by the simulator).""" """Update state from an incoming set command (used by the simulator)."""
if not p: if not p:
return return
if cmd == CMD_TEST_SIGNAL:
state["test"] = {"source": p[0], "freq": p[1] if len(p) > 1 else 0}
return
c = p[0] c = p[0]
kind, idx = ("in", c) if c < model.n_in else ("out", c - model.n_in) kind, idx = ("in", c) if c < model.n_in else ("out", c - model.n_in)
chans = state["inputs" if kind == "in" else "outputs"] chans = state["inputs" if kind == "in" else "outputs"]
@@ -497,7 +535,11 @@ def apply_command(model: Model, state: dict, cmd: int, p: bytes):
return return
ch = chans[idx] ch = chans[idx]
w = lambda o: struct.unpack_from("<H", p, o)[0] w = lambda o: struct.unpack_from("<H", p, o)[0]
if cmd == CMD_GAIN: if cmd == CMD_PEQ_BYPASS:
ch["peq_bypass"] = bool(p[1])
elif cmd == CMD_GEQ_BYPASS:
ch["geq_bypass"] = bool(p[1])
elif cmd == CMD_GAIN:
ch["gain"] = w(1) ch["gain"] = w(1)
elif cmd == CMD_MUTE: elif cmd == CMD_MUTE:
ch["mute"] = bool(p[1]) ch["mute"] = bool(p[1])
+1 -1
View File
@@ -58,6 +58,6 @@ pyinstaller("--name", "DSP Control", "--icon", str(ROOT / "packaging" / "dsp-con
*data("static", "static"), str(ROOT / "desktop.py")) *data("static", "static"), str(ROOT / "desktop.py"))
pyinstaller("--name", "DSP Control Pi Writer", "--icon", str(ROOT / "packaging" / "pi-writer.ico"), "--uac-admin", 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")) *data("server.py"), *data("sim.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 ") print("\nDone:", *(p.name for p in (ROOT / "dist").glob("*.exe")), sep="\n ")
+1 -1
View File
@@ -19,7 +19,7 @@ import server
OS_LIST_URL = "https://downloads.raspberrypi.com/os_list_imagingutility_v4.json" 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)"} 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 APP_FILES = ["server.py", "sim.py", "dsp", "static"] # what gets installed on the Pi
USER_AGENT = "DSP-Control-Pi-Writer/1.0" USER_AGENT = "DSP-Control-Pi-Writer/1.0"
# Pi models offered in the writer: (name, description, os bits) # Pi models offered in the writer: (name, description, os bits)
+449 -13
View File
@@ -7,6 +7,7 @@ Then open http://<this-computer>:8080 on your phone.
import argparse import argparse
import asyncio import asyncio
import base64 import base64
import copy
import errno import errno
import hashlib import hashlib
import json import json
@@ -21,7 +22,9 @@ import uuid
from pathlib import Path from pathlib import Path
from urllib.parse import parse_qs, urlsplit from urllib.parse import parse_qs, urlsplit
import sim
from dsp import preset, usbhid from dsp import preset, usbhid
from dsp import protocol as P
from dsp.device import Device from dsp.device import Device
ROOT = Path(__file__).resolve().parent ROOT = Path(__file__).resolve().parent
@@ -34,6 +37,8 @@ MAX_SESSIONS = 50
COOKIE = "dspsess" COOKIE = "dspsess"
CONFIG_FORMAT = "dsp-control-config" CONFIG_FORMAT = "dsp-control-config"
MAX_UNDO = 20 # automatic backups kept per DSP before each import MAX_UNDO = 20 # automatic backups kept per DSP before each import
TEST_LEVEL = -50.0 # dB all outputs start at when an audio test begins (noise generators are loud)
TEST_MAX = 0.0 # highest level the test fader can set
def _num(v, lo: float, hi: float, default: float = 0.0) -> float: def _num(v, lo: float, hi: float, default: float = 0.0) -> float:
@@ -85,6 +90,88 @@ def clean_limiter(data: dict) -> dict:
return {"amps": amps, "assign": assign, "ref": ref} return {"amps": amps, "assign": assign, "ref": ref}
LOGO_MAX = 300_000 # characters of the data URL (the app sends a 128×128 PNG)
def clean_logo(v) -> str:
"""Custom logo as a PNG data URL, "" = the built-in one."""
v = str(v or "")
return v if v.startswith("data:image/png;base64,") and len(v) <= LOGO_MAX and re.fullmatch(r"[\w+/=]*", v[22:]) else ""
SF_ROLES = ("main", "sub", "delay", "fill")
def clean_soundfield(data) -> dict:
"""SoundField room plan: room, stage, reference position and speakers (positions in metres)."""
data = data if isinstance(data, dict) else {}
room = data.get("room") if isinstance(data.get("room"), dict) else {}
w, d = _num(room.get("w"), 4, 200, 20), _num(room.get("d"), 4, 300, 30)
stage = data.get("stage") if isinstance(data.get("stage"), dict) else {}
ref = data.get("ref") if isinstance(data.get("ref"), dict) else {}
speakers = []
for s in (data.get("speakers") or [])[:48]:
if not isinstance(s, dict):
continue
sid = re.sub(r"[^\w-]", "", str(s.get("id") or ""))[:16] or uuid.uuid4().hex[:8]
speakers.append({
"id": sid, "name": str(s.get("name") or "Speaker")[:24],
"role": s.get("role") if s.get("role") in SF_ROLES else "main",
"type": re.sub(r"[^\w-]", "", str(s.get("type") or "custom"))[:16],
"x": _num(s.get("x"), 0, w, w / 2), "y": _num(s.get("y"), 0, d, 1), "h": _num(s.get("h"), 0, 30, 2),
"aim": _num(s.get("aim"), -180, 180, 0), "cov": _num(s.get("cov"), 20, 360, 90),
"spl": _num(s.get("spl"), 80, 160, 128),
"tx": _num(s.get("tx"), 0, w, w / 2), "ty": _num(s.get("ty"), 0, d, d / 2),
"outs": [o for o in (s.get("outs") or [])[:8] if re.fullmatch(r"[\w-]+:\d{1,2}", str(o))],
"mount": re.sub(r"[^\w-]", "", str(s.get("mount") or ""))[:16], # id of the sub this top stands on (pole)
})
ids = {s["id"]: s for s in speakers}
for s in speakers: # a mount must be an existing sub, and the top stands exactly on it
m = ids.get(s["mount"])
if not m or m["role"] != "sub" or s["role"] == "sub":
s["mount"] = ""
else:
s["x"], s["y"] = m["x"], m["y"]
return {
"room": {"w": w, "d": d},
"stage": {"w": _num(stage.get("w"), 0, w, min(8, w)), "d": _num(stage.get("d"), 0, d / 2, 4)},
"temp": _num(data.get("temp"), -10, 45, 20),
"precedence": _num(data.get("precedence"), 0, 30, 5),
"ear": _num(data.get("ear"), 0.5, 3, 1.7),
"ref": {"x": _num(ref.get("x"), 0, w, w / 2), "y": _num(ref.get("y"), 0, d, d * 0.6)},
"speakers": speakers,
}
def clean_colors(v) -> dict:
"""Channel colours: {"in0": "#rrggbb", "out3": ...}. Linked channels carry their group's colour; that a colour
belongs to one channel/group only is ensured by the colour picker (it knows the link groups)."""
out = {}
for k, c in (v.items() if isinstance(v, dict) else []):
c = str(c).lower()
if re.fullmatch(r"(in|out)\d{1,2}", str(k)) and re.fullmatch(r"#[0-9a-f]{6}", c):
out[str(k)] = c
return out
def clean_maxgain(v) -> dict:
"""Software gain limits per channel: {"in0": raw 0..399} (400 = +12 dB would be no limit)."""
out = {}
for k, g in (v.items() if isinstance(v, dict) else []):
if re.fullmatch(r"(in|out)\d{1,2}", str(k)):
g = int(_num(g, 0, 400, 400))
if g < 400:
out[str(k)] = g
return out
def clean_gains(v) -> list[int] | None:
"""Saved output gains of an interrupted audio test (from config.json)."""
if not isinstance(v, list) or not v or len(v) > 8:
return None
return [int(_num(g, 0, 400, 280)) for g in v]
def hash_pin(pin: str, salt: str) -> str: def hash_pin(pin: str, salt: str) -> str:
return hashlib.pbkdf2_hmac("sha256", pin.encode(), bytes.fromhex(salt), 100_000).hex() return hashlib.pbkdf2_hmac("sha256", pin.encode(), bytes.fromhex(salt), 100_000).hex()
@@ -103,6 +190,8 @@ class App:
self.sessions: dict[str, float] = {} # token hash -> expiry self.sessions: dict[str, float] = {} # token hash -> expiry
self.failures: dict[str, tuple[int, float]] = {} # ip -> (failed attempts, locked until) self.failures: dict[str, tuple[int, float]] = {} # ip -> (failed attempts, locked until)
self.limiter: dict = clean_limiter({}) self.limiter: dict = clean_limiter({})
self.soundfield: dict = clean_soundfield({})
self.logo = ""
# desktop app: its own window logs in with a one-time token, other devices need the PIN # 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_token: str | None = None
self.app_sessions: set[str] = set() self.app_sessions: set[str] = set()
@@ -112,6 +201,12 @@ class App:
self.remote_error = "" self.remote_error = ""
self.locked = False # desktop app window read-only until unlocked with the PIN 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) self.lang = "" # UI language chosen in the desktop app ("" = not chosen yet, English)
# demo mode: the real DSPs are disconnected and a simulated one runs inside the server
self.demo = {"enabled": False, "model": "408"}
self.demo_server: asyncio.Server | None = None
self.demo_resume: set[str] = set() # real devices to reconnect when the demo ends
# global mute: per device the channels that were open before, unmuted again on release
self.mute_all = {"active": False, "restore": {}}
# ------------------------------------------------------------ config # ------------------------------------------------------------ config
@@ -127,6 +222,10 @@ class App:
self.sessions = {k: v for k, v in cfg.get("sessions", {}).items() if v > now} self.sessions = {k: v for k, v in cfg.get("sessions", {}).items() if v > now}
self.locked = bool(cfg.get("locked")) self.locked = bool(cfg.get("locked"))
self.lang = cfg.get("lang") if cfg.get("lang") in ("en", "de") else "" self.lang = cfg.get("lang") if cfg.get("lang") in ("en", "de") else ""
m = cfg.get("mute_all") or {}
self.mute_all = {"active": bool(m.get("active")), "restore": {
str(k): [[c[0], int(c[1])] for c in v if isinstance(c, list) and len(c) == 2 and c[0] in ("in", "out")]
for k, v in (m.get("restore") or {}).items() if isinstance(v, list)}}
self.apply_config(cfg) self.apply_config(cfg)
def apply_config(self, cfg: dict): def apply_config(self, cfg: dict):
@@ -137,6 +236,10 @@ class App:
elif not self.auth: # first start (a backup without PIN keeps the current one) elif not self.auth: # first start (a backup without PIN keeps the current one)
self.set_pin(DEFAULT_PIN, save=False) self.set_pin(DEFAULT_PIN, save=False)
self.limiter = clean_limiter(cfg.get("limiter") or {}) self.limiter = clean_limiter(cfg.get("limiter") or {})
if "soundfield" in cfg:
self.soundfield = clean_soundfield(cfg.get("soundfield"))
if "logo" in cfg:
self.logo = clean_logo(cfg.get("logo"))
r = cfg.get("remote") or {} r = cfg.get("remote") or {}
self.remote = {"enabled": bool(r.get("enabled")), "port": int(_num(r.get("port"), 1, 65535, 8080))} self.remote = {"enabled": bool(r.get("enabled")), "port": int(_num(r.get("port"), 1, 65535, 8080))}
for d in cfg.get("devices", [])[:20]: for d in cfg.get("devices", [])[:20]:
@@ -149,13 +252,13 @@ class App:
def export_config(self) -> dict: def export_config(self) -> dict:
"""App backup: devices, PIN (hashed), amplifiers/limiter data, remote access - no logins.""" """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"), 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, "devices": [d.config() for d in self.real_devices()], "auth": self.auth,
"limiter": self.limiter, "remote": self.remote} "limiter": self.limiter, "remote": self.remote, "soundfield": self.soundfield, "logo": self.logo}
async def restore_config(self, doc: dict, session: str): async def restore_config(self, doc: dict, session: str):
if not isinstance(doc, dict) or doc.get("format") != CONFIG_FORMAT: if not isinstance(doc, dict) or doc.get("format") != CONFIG_FORMAT:
raise ValueError("Not a DSP Control settings backup") raise ValueError("Not a DSP Control settings backup")
for dev in list(self.devices.values()): for dev in self.real_devices():
await dev.stop() await dev.stop()
del self.devices[dev.id] del self.devices[dev.id]
self.broadcast({"type": "removed", "device": dev.id}) self.broadcast({"type": "removed", "device": dev.id})
@@ -167,6 +270,8 @@ class App:
for dev in self.devices.values(): for dev in self.devices.values():
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
self.broadcast({"type": "limiter", "data": self.limiter}) self.broadcast({"type": "limiter", "data": self.limiter})
self.broadcast({"type": "soundfield", "data": self.soundfield})
self.broadcast({"type": "logo", "data": self.logo})
if self.app_token: # desktop app: (re)start or stop the LAN listener as restored if self.app_token: # desktop app: (re)start or stop the LAN listener as restored
await self.start_remote() await self.start_remote()
@@ -204,8 +309,11 @@ class App:
def save(self): def save(self):
sessions = {k: v for k, v in self.sessions.items() if k not in self.app_sessions} 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, cfg = {"devices": [d.config() for d in self.real_devices()], "auth": self.auth,
"sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked} "sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked,
"soundfield": self.soundfield, "logo": self.logo,
"mute_all": {"active": self.mute_all["active"],
"restore": {k: v for k, v in self.mute_all["restore"].items() if k != "demo"}}}
if self.lang: if self.lang:
cfg["lang"] = self.lang cfg["lang"] = self.lang
self.config_path.write_text(json.dumps(cfg, indent=2), encoding="utf-8") self.config_path.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
@@ -216,14 +324,266 @@ class App:
dev = Device(dev_id, d.get("name") or d.get("host") or "DSP (USB)", str(d.get("host") or ""), 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)), int(d.get("port", 9761)), str(d.get("model", "auto")), int(d.get("addr", 1)),
bool(d.get("autoconnect", True)), on_event=self.broadcast, bool(d.get("autoconnect", True)), on_event=self.broadcast,
transport="usb" if usb else "tcp", usb=str(d.get("usb") or "")) transport="usb" if usb else "tcp", usb=str(d.get("usb") or ""),
lock_code=str(d.get("lock_code") or ""), auto_unlock=bool(d.get("auto_unlock")),
test_saved=clean_gains(d.get("test_saved")), colors=clean_colors(d.get("colors")),
maxgain=clean_maxgain(d.get("maxgain")))
dev.on_online = self.device_online
self.devices[dev_id] = dev self.devices[dev_id] = dev
if dev.autoconnect: if dev.autoconnect:
if self.demo["enabled"]:
self.demo_resume.add(dev_id)
else:
dev.start() dev.start()
if save: if save:
self.save() self.save()
return dev return dev
# ------------------------------------------------------------ audio test
def set_test_level(self, dev: Device, db: float):
"""Every output to the same level (the test fader)."""
dev.test_level = _num(db, -60, TEST_MAX, TEST_LEVEL)
raw = P.db_to_gain(dev.test_level)
for i in range(len(dev.state["outputs"])):
dev.set_param("out", i, "gain", dev.gain_cap("out", i, raw))
def restore_gains(self, dev: Device):
for i, g in enumerate((dev.test_saved or [])[: len(dev.state["outputs"])]):
dev.set_param("out", i, "gain", g)
dev.test_saved = None
async def audio_test(self, dev: Device, body: dict) -> dict:
source = int(_num(body.get("source"), 0, len(P.TEST_SOURCES) - 1, 0))
freq = int(_num(body.get("freq"), 0, 30, dev.state["test"]["freq"] if dev.state else 17))
if not dev.state or dev.status != "online":
raise RuntimeError("DSP is not connected")
if source:
if not dev.test_active: # entering: lower every output before the generator starts
if dev.test_saved is None:
dev.test_saved = [ch["gain"] for ch in dev.state["outputs"]]
self.save()
self.set_test_level(dev, TEST_LEVEL)
await dev.set_test_signal(source, freq)
else: # leaving: generator off first, then the faders go back
await dev.set_test_signal(0, freq)
if dev.test_saved is not None:
self.restore_gains(dev)
await dev.flush()
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True}
async def device_online(self, dev: Device):
await self.check_audio_test(dev)
if not self.mute_all["active"] and self.mute_all["restore"].get(dev.id):
self.unmute_device(dev) # released while this DSP was offline
self.save()
# ------------------------------------------------------------ global mute
def mute_all_info(self) -> dict:
return {"active": self.mute_all["active"]}
def unmute_device(self, dev: Device):
for kind, i in self.mute_all["restore"].pop(dev.id, []):
chans = dev.state["inputs" if kind == "in" else "outputs"]
if i < len(chans) and chans[i]["mute"]:
dev.set_param(kind, i, "mute", False)
def set_mute_all(self, mute: bool) -> dict:
"""Mute every channel of every connected DSP; releasing unmutes only what was open before."""
online = [d for d in self.devices.values() if d.status == "online" and d.state]
if mute and not self.mute_all["active"]:
self.mute_all["restore"] = {}
for dev in online:
opened = [[kind, i] for kind, key in (("in", "inputs"), ("out", "outputs"))
for i, ch in enumerate(dev.state[key]) if not ch["mute"]]
for kind, i in opened:
dev.set_param(kind, i, "mute", True)
self.mute_all["restore"][dev.id] = opened
self.mute_all["active"] = True
elif not mute and self.mute_all["active"]:
self.mute_all["active"] = False
for dev in online:
self.unmute_device(dev) # offline ones follow when they connect again
self.save()
self.broadcast({"type": "muteall", "data": self.mute_all_info()})
return self.mute_all_info()
# ------------------------------------------------------------ copy channel settings
def copy_settings(self, body: dict) -> dict:
"""Copy groups of settings from one channel to channels of the same kind (any connected DSP)."""
src = self.devices.get(str(body.get("device")))
kind = "in" if body.get("kind") == "in" else "out"
key = "inputs" if kind == "in" else "outputs"
if not src or not src.state:
raise RuntimeError("DSP is not connected")
sch = src.state[key][int(body.get("idx", 0))]
groups = set(body.get("groups") or [])
changed = 0
for t in body.get("targets") or []:
dev = self.devices.get(str(t.get("device")))
if not dev or dev.status != "online" or not dev.state:
continue
if dev.test_active:
raise RuntimeError("Audio test is on – switch it off first")
idx = int(t.get("idx", -1))
if not 0 <= idx < len(dev.state[key]) or (dev is src and idx == int(body.get("idx", 0))):
continue
tch = dev.state[key][idx]
params = []
if "level" in groups:
params += ["gain", "delay", "polarity"]
if "filters" in groups:
params += ["hp", "lp"]
if "eq" in groups:
params += ["peq_bypass"] + [f"peq.{b}" for b in range(min(len(sch["peq"]), len(tch["peq"])))]
if kind == "in":
params += ["geq_bypass"] + [f"geq.{b}" for b in range(31)]
if "dynamics" in groups:
params += ["gate"] if kind == "in" else ["comp", "limit"]
if "routing" in groups and kind == "out":
params += [f"mix.{k}" for k in range(min(len(sch["mix"]), len(tch["mix"])))]
for p in params:
v = copy.deepcopy(self._get(sch, p))
if p == "gain":
v = dev.gain_cap(kind, idx, v)
if self._get(tch, p) != v:
dev.set_param(kind, idx, p, v)
changed += 1
if "routing" in groups and kind == "out":
m = sch["matrix"] & ((1 << len(tch["mix"])) - 1)
if tch["matrix"] != m:
dev.set_param(kind, idx, "matrix", m)
changed += 1
return {"ok": True, "changed": changed}
@staticmethod
def _get(ch: dict, path: str):
node = ch
for k in path.split("."):
node = node[int(k)] if isinstance(node, list) else node[k]
return node
async def check_audio_test(self, dev: Device):
"""On connect: a DSP still playing a test signal goes straight into the audio test (outputs lowered);
one back on its analog inputs gets the faders saved by an interrupted test back."""
try:
if dev.test_active:
if dev.test_saved is None:
dev.test_saved = [ch["gain"] for ch in dev.state["outputs"]]
self.set_test_level(dev, TEST_LEVEL)
elif dev.test_saved is not None:
self.restore_gains(dev)
else:
return
await dev.flush()
if not dev.demo:
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
except Exception as e: # noqa: BLE001 - connection lost meanwhile: checked again on the next connect
log.warning("%s: audio test check failed: %s", dev.name, e)
# ------------------------------------------------------------ network search
async def scan_network(self) -> list[dict]:
"""Look for DSPs (TCP 9761) in the local /24 networks and ask them who they are.
DSPs this app is connected to are skipped: a DSP takes only one connection."""
busy = {d.host for d in self.real_devices() if d.transport == "tcp" and d.status in ("connecting", "loading", "locked", "online")}
known = {d.host: d for d in self.real_devices() if d.transport == "tcp"}
nets = []
for ip in local_ips():
net = ip.rsplit(".", 1)[0]
if not ip.startswith("127.") and net not in nets:
nets.append(net)
sem = asyncio.Semaphore(96)
async def probe(ip: str):
if ip in busy:
d = known[ip]
return {"host": ip, "port": P.PORT, "info": d.info, "model": d.model_name or None, "known": d.name, "busy": True}
async with sem:
try:
r, w = await asyncio.wait_for(asyncio.open_connection(ip, P.PORT), 0.7)
except (OSError, asyncio.TimeoutError):
return None
info = ""
try:
w.write(P.build_frame(P.CMD_HANDSHAKE) + P.build_frame(P.CMD_DEVICE_INFO))
await w.drain()
parser, end = P.FrameParser(), time.monotonic() + 1.2
while not info and time.monotonic() < end:
data = await asyncio.wait_for(r.read(512), max(0.05, end - time.monotonic()))
if not data:
break
for f in parser.feed(data):
if f.cmd == P.CMD_DEVICE_INFO:
info = f.payload.split(b"\x00")[0].decode("latin1", "replace").strip()
except (OSError, asyncio.TimeoutError):
pass
finally:
w.close()
d = known.get(ip)
return {"host": ip, "port": P.PORT, "info": info, "model": P.detect_model(info), "known": d.name if d else "", "busy": False}
hosts = [f"{net}.{i}" for net in nets[:2] for i in range(1, 255)]
found = [x for x in await asyncio.gather(*(probe(h) for h in hosts)) if x]
return sorted(found, key=lambda x: tuple(int(p) for p in x["host"].split(".")))
def real_devices(self) -> list[Device]:
return [d for d in self.devices.values() if not d.demo]
# ------------------------------------------------------------ demo mode
def demo_info(self) -> dict:
return {**self.demo, "error": ""}
async def set_demo(self, body: dict) -> dict:
enabled = bool(body.get("enabled", self.demo["enabled"]))
model = body.get("model") if body.get("model") in ("204", "408") else self.demo["model"]
if self.demo["enabled"] and (not enabled or model != self.demo["model"]):
await self.stop_demo()
self.demo["model"] = model
if enabled and not self.demo["enabled"]:
await self.start_demo()
self.broadcast({"type": "demo", "data": self.demo_info()})
return self.demo_info()
async def start_demo(self):
"""Disconnect the real DSPs and start a simulated one inside this server."""
self.demo_resume = {d.id for d in self.real_devices() if d._want_connected}
for d in self.real_devices():
await d.stop()
model = self.demo["model"]
logging.getLogger("sim").setLevel(logging.WARNING)
dsp = sim.SimDSP(model)
dsp.presets[1] = {**dsp.presets[0], "preset_name": "Demo"}
self.demo_server = await asyncio.start_server(dsp.serve, "127.0.0.1", 0)
port = self.demo_server.sockets[0].getsockname()[1]
dev = Device("demo", f"Demo DSP {model}", "127.0.0.1", port, model, autoconnect=False, on_event=self.broadcast)
dev.demo = True
dev.on_online = self.device_online
self.devices[dev.id] = dev
self.demo["enabled"] = True
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
dev.start()
async def stop_demo(self):
dev = self.devices.pop("demo", None)
if dev:
await dev.stop()
self.broadcast({"type": "removed", "device": dev.id})
if self.demo_server:
self.demo_server.close()
self.demo_server = None
self.demo["enabled"] = False
for dev_id in self.demo_resume:
if dev_id in self.devices:
self.devices[dev_id].start()
self.demo_resume = set()
# ------------------------------------------------------------ auth # ------------------------------------------------------------ auth
def set_pin(self, pin: str, save=True): def set_pin(self, pin: str, save=True):
@@ -309,7 +669,7 @@ class App:
@staticmethod @staticmethod
def allowed_while_locked(method: str, path: str) -> bool: def allowed_while_locked(method: str, path: str) -> bool:
"""What the locked app window may still do: look at everything, export presets.""" """What the locked app window may still do: look at everything, export presets."""
if path in ("/api/unlock", "/api/events", "/api/lang"): if path in ("/api/unlock", "/api/events", "/api/lang", "/api/muteall"):
return True return True
if method == "GET": if method == "GET":
return path != "/api/backup" # holds the PIN hash return path != "/api/backup" # holds the PIN hash
@@ -356,6 +716,9 @@ class App:
async def shutdown(self): async def shutdown(self):
self.stop_remote() self.stop_remote()
if self.demo["enabled"]:
self.demo_resume = set()
await self.stop_demo()
for d in self.devices.values(): for d in self.devices.values():
await d.stop() await d.stop()
@@ -375,6 +738,32 @@ class App:
return [d.snapshot() for d in self.devices.values()] return [d.snapshot() for d in self.devices.values()]
if path == "/api/devices" and method == "POST": if path == "/api/devices" and method == "POST":
return self.add_device(body).snapshot() return self.add_device(body).snapshot()
if path == "/api/logo" and method == "PUT":
self.logo = clean_logo(body.get("logo"))
if body.get("logo") and not self.logo:
raise ValueError("The logo could not be read")
self.save()
self.broadcast({"type": "logo", "data": self.logo})
return {"logo": self.logo}
if path == "/api/logo":
return {"logo": self.logo}
if path == "/api/soundfield" and method == "PUT":
self.soundfield = clean_soundfield(body)
self.save()
self.broadcast({"type": "soundfield", "data": self.soundfield})
return self.soundfield
if path == "/api/soundfield":
return self.soundfield
if path == "/api/muteall" and method == "POST":
return self.set_mute_all(bool(body.get("mute")))
if path == "/api/muteall":
return self.mute_all_info()
if path == "/api/copy" and method == "POST":
return self.copy_settings(body)
if path == "/api/demo":
return await self.set_demo(body) if method == "PUT" else self.demo_info()
if path == "/api/scan" and method == "POST":
return await self.scan_network()
if path == "/api/usb" and method == "GET": if path == "/api/usb" and method == "GET":
return await asyncio.to_thread(usbhid.list_devices) return await asyncio.to_thread(usbhid.list_devices)
if path == "/api/limiter" and method == "GET": if path == "/api/limiter" and method == "GET":
@@ -389,6 +778,14 @@ class App:
raise KeyError(path) raise KeyError(path)
dev = self.devices[m.group(1)] dev = self.devices[m.group(1)]
action = "/".join(g for g in m.groups()[1:] if g) action = "/".join(g for g in m.groups()[1:] if g)
if dev.demo and (method in ("DELETE", "PUT") or action in ("unlock", "lockcode")):
raise RuntimeError("Not available for the demo device")
# during the audio test only the test controls work: generator, test fader, output mutes
if dev.test_active and (action in ("preset/recall", "preset/store", "export", "import", "undo", "link")
or action == "set" and body.get("param") != "mute"):
raise RuntimeError("Audio test is on – switch it off first")
if self.demo["enabled"] and not dev.demo and action == "connect":
raise RuntimeError("Demo mode is on – switch it off to connect the real DSPs")
if method == "DELETE" and not action: if method == "DELETE" and not action:
await dev.stop() await dev.stop()
del self.devices[dev.id] del self.devices[dev.id]
@@ -403,11 +800,16 @@ class App:
setattr(dev, "model_key" if k == "model" else k, str(body[k])) setattr(dev, "model_key" if k == "model" else k, str(body[k]))
if "transport" in body: if "transport" in body:
dev.transport = "usb" if body["transport"] == "usb" else "tcp" dev.transport = "usb" if body["transport"] == "usb" else "tcp"
for k in ("port", "addr"): if "port" in body:
if k in body: dev.port = int(_num(body["port"], 1, 65535, P.PORT))
setattr(dev, k, int(body[k])) if "addr" in body: # device ID of the DSP (address byte of every frame)
dev.addr = int(_num(body["addr"], 1, 250, 1))
if "autoconnect" in body: if "autoconnect" in body:
dev.autoconnect = bool(body["autoconnect"]) dev.autoconnect = bool(body["autoconnect"])
if "auto_unlock" in body:
dev.auto_unlock = bool(body["auto_unlock"])
if body.get("lock_code") == "":
dev.lock_code, dev.auto_unlock = "", False # forget the remembered code
self.save() self.save()
if was_running: if was_running:
dev.start() dev.start()
@@ -422,8 +824,16 @@ class App:
await dev.stop() await dev.stop()
return {"ok": True} return {"ok": True}
if action == "set": if action == "set":
dev.set_param(body["kind"], int(body["idx"]), body["param"], body["value"]) kind, idx, value = body["kind"], int(body["idx"]), body["value"]
return {"ok": True} if body["param"] == "gain" and not body.get("force"): # force: confirmed twice in the app
value = dev.gain_cap(kind, idx, int(value)) # software max level
dev.set_param(kind, idx, body["param"], value)
return {"ok": True, "value": value}
if action == "maxgain": # app-side setting, the DSP doesn't know it
dev.maxgain = clean_maxgain(body.get("maxgain"))
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True, "maxgain": dev.maxgain}
if action == "preset/recall": if action == "preset/recall":
await dev.recall_preset(int(body["index"])) await dev.recall_preset(int(body["index"]))
return {"ok": True} return {"ok": True}
@@ -446,6 +856,31 @@ class App:
if action == "refresh": if action == "refresh":
await dev.refresh() await dev.refresh()
return {"ok": True} return {"ok": True}
if action == "colors": # display only, stays in the app (the DSP doesn't know colours)
dev.colors = clean_colors(body.get("colors"))
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True, "colors": dev.colors}
if action == "test":
return await self.audio_test(dev, body)
if action == "testlevel":
if not dev.test_active:
raise RuntimeError("Audio test is off")
self.set_test_level(dev, body.get("db"))
return {"ok": True, "db": dev.test_level}
if action == "unlock": # hardware lock of the DSP, independent of the app lock
code = str(body.get("code") or "").strip().upper()
ok = await dev.unlock(code)
if ok and body.get("remember"):
dev.lock_code, dev.auto_unlock = code, True
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": ok}
if action == "lockcode":
await dev.set_lock_code(body.get("code"))
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True}
raise KeyError(path) raise KeyError(path)
# ------------------------------------------------------------ HTTP # ------------------------------------------------------------ HTTP
@@ -608,7 +1043,8 @@ class App:
q: asyncio.Queue = asyncio.Queue() q: asyncio.Queue = asyncio.Queue()
self.clients.add(q) self.clients.add(q)
try: try:
hello = {"type": "hello", "devices": [d.snapshot() for d in self.devices.values()], "limiter": self.limiter} hello = {"type": "hello", "devices": [d.snapshot() for d in self.devices.values()], "limiter": self.limiter,
"demo": self.demo_info(), "muteall": self.mute_all_info(), "soundfield": self.soundfield, "logo": self.logo}
writer.write(f"data: {json.dumps(hello)}\n\n".encode()) writer.write(f"data: {json.dumps(hello)}\n\n".encode())
await writer.drain() await writer.drain()
while True: while True:
+19 -4
View File
@@ -2,6 +2,7 @@
Usage: python sim.py --model 204 --port 9761 Usage: python sim.py --model 204 --port 9761
python sim.py --model 408 --port 9762 python sim.py --model 408 --port 9762
python sim.py --model 204 --port 9761 --lock A1BA (asks for that lock code on every connection)
""" """
import argparse import argparse
@@ -17,8 +18,10 @@ log = logging.getLogger("sim")
class SimDSP: class SimDSP:
def __init__(self, model_key: str): def __init__(self, model_key: str, lock_code: str = ""):
self.key = model_key self.key = model_key
self.lock_code = lock_code # hardware lock: "" = none
self.unlocked = not lock_code
self.model = P.MODELS[model_key] self.model = P.MODELS[model_key]
self.state = P.default_state(self.model) 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 = [copy.deepcopy(self.state) if i == 0 else None for i in range(20)]
@@ -33,7 +36,15 @@ class SimDSP:
if cmd == P.CMD_DEVICE_INFO: if cmd == P.CMD_DEVICE_INFO:
return cmd, f"DSP{self.key} V010 SIM".encode() return cmd, f"DSP{self.key} V010 SIM".encode()
if cmd == P.CMD_PRESET_COUNT: if cmd == P.CMD_PRESET_COUNT:
return cmd, bytes([0, len(self.presets)]) return cmd, bytes([0, 0, 0, 0, 0, 0 if self.unlocked else 1])
if cmd == P.CMD_UNLOCK:
self.unlocked = self.unlocked or p[1:5].decode("latin1") == self.lock_code
return cmd, bytes([0, 1 if self.unlocked else 0])
if cmd == P.CMD_SET_LOCK_CODE:
self.lock_code = p[:4].decode("latin1")
return P.CMD_ACK, b"\x00"
if not self.unlocked and cmd not in (P.CMD_HANDSHAKE, P.CMD_METER, P.CMD_LOGOUT):
return P.CMD_ACK, b"\x00" # locked: ignores everything until the code was entered
if cmd == P.CMD_PRESET_NAME: if cmd == P.CMD_PRESET_NAME:
return cmd, bytes([p[0]]) + self.preset_names()[p[0]].encode("latin1").ljust(14, b" ") return cmd, bytes([p[0]]) + self.preset_names()[p[0]].encode("latin1").ljust(14, b" ")
if cmd == P.CMD_CONFIG_REQUEST: if cmd == P.CMD_CONFIG_REQUEST:
@@ -43,9 +54,11 @@ class SimDSP:
if cmd == P.CMD_METER: if cmd == P.CMD_METER:
t = time.monotonic() t = time.monotonic()
levels = [0.0] * 12 levels = [0.0] * 12
noise = self.state.get("test", {}).get("source", 0) # test generator instead of the analog inputs
for i in range(m.n_in): for i in range(m.n_in):
ch = self.state["inputs"][i] 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) src = 0.7 + 0.05 * math.sin(t * 40 + i) if noise else 0.25 * (1 + math.sin(t * (1.3 + i)))
lv = 0.0 if ch["mute"] else src * 10 ** (P.gain_to_db(ch["gain"]) / 20)
levels[m.meter_index("in", i)] = lv levels[m.meter_index("in", i)] = lv
flags = 0 flags = 0
for o in range(m.n_out): for o in range(m.n_out):
@@ -72,6 +85,7 @@ class SimDSP:
async def serve(self, reader, writer): async def serve(self, reader, writer):
peer = writer.get_extra_info("peername") peer = writer.get_extra_info("peername")
log.info("client %s connected", peer) log.info("client %s connected", peer)
self.unlocked = not self.lock_code
parser = P.FrameParser() parser = P.FrameParser()
try: try:
while data := await reader.read(4096): while data := await reader.read(4096):
@@ -92,9 +106,10 @@ async def main():
ap.add_argument("--model", choices=list(P.MODELS), default="204") ap.add_argument("--model", choices=list(P.MODELS), default="204")
ap.add_argument("--port", type=int, default=P.PORT) ap.add_argument("--port", type=int, default=P.PORT)
ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--lock", default="", help="lock code (4 characters A-Z/0-9) the DSP asks for")
args = ap.parse_args() args = ap.parse_args()
logging.basicConfig(level=logging.INFO, format=f"%(asctime)s sim{args.model} %(message)s") logging.basicConfig(level=logging.INFO, format=f"%(asctime)s sim{args.model} %(message)s")
sim = SimDSP(args.model) sim = SimDSP(args.model, args.lock.upper())
server = await asyncio.start_server(sim.serve, args.host, args.port) 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) log.info("simulated DSP %s on %s:%d", args.model, args.host, args.port)
async with server: async with server:
+823 -113
View File
File diff suppressed because it is too large. Load diff
+215 -1
View File
@@ -286,7 +286,221 @@ const DE = {
"{pct} % of {rated}": "{pct} % von {rated}", "{pct} % of {rated}": "{pct} % von {rated}",
"— empty —": "— leer —", "— empty —": "— leer —",
"— no amplifier —": "— kein Verstärker —", "— no amplifier —": "— kein Verstärker —",
"“{s}”": "„{s}“" "“{s}”": "„{s}“",
// device lock, demo mode
"A code is remembered for this DSP.": "Für diesen DSP ist ein Code gespeichert.",
"Code forgotten": "Code vergessen",
"Connect the DSP to set a code.": "Zum Festlegen eines Codes den DSP verbinden.",
"DSP locked": "DSP gesperrt",
"DSP unlocked": "DSP entsperrt",
"Device lock (code)": "Gerätesperre (Code)",
"Enter code": "Code eingeben",
"Forget code": "Code vergessen",
"From the next connection on, {name} asks for the code {code} – also in the original software. Note it down: this app cannot remove the lock again.": "Ab der nächsten Verbindung fragt {name} nach dem Code {code} – auch in der Original-Software. Bitte notieren: Diese App kann die Sperre nicht wieder entfernen.",
"Hardware lock of the DSP: a locked DSP only accepts a connection after its code was entered. Independent of the lock of this app.": "Sperre im DSP selbst: Ein gesperrter DSP lässt sich erst nach Eingabe seines Codes bedienen. Unabhängig von der Sperre dieser App.",
"Lock code": "Sperrcode",
"Lock code set": "Sperrcode festgelegt",
"Locked with a code": "Mit Code gesperrt",
"No code remembered – it is asked for when the DSP is locked.": "Kein Code gespeichert – er wird abgefragt, wenn der DSP gesperrt ist.",
"Remember the code and unlock automatically": "Code merken und automatisch entsperren",
"Set a new lock code": "Neuen Sperrcode festlegen",
"Set code": "Code festlegen",
"Set lock code": "Sperrcode festlegen",
"The code has 4 characters: digits and letters A–Z": "Der Code hat 4 Zeichen: Ziffern und Buchstaben A–Z",
"This DSP is locked with a code.": "Dieser DSP ist mit einem Code gesperrt.",
"Unlock automatically with the remembered code": "Mit dem gespeicherten Code automatisch entsperren",
"Wrong code – please try again.": "Falscher Code – bitte erneut versuchen.",
"code remembered": "Code gespeichert",
"{name} is locked with a code. Enter the 4-character code (digits and letters A–Z).": "{name} ist mit einem Code gesperrt. Bitte den 4-stelligen Code eingeben (Ziffern und Buchstaben A–Z).",
"The DSP is not locked": "Der DSP ist nicht gesperrt",
"The remembered lock code was rejected": "Der gespeicherte Sperrcode wurde abgelehnt",
"Demo mode": "Demo-Modus",
"Demo mode · simulated DSP": "Demo-Modus · simulierter DSP",
"Demo mode – simulated DSP": "Demo-Modus – simulierter DSP",
"Disconnected while demo mode is on": "Getrennt, solange der Demo-Modus aktiv ist",
"Try everything with a simulated DSP – nothing is sent to real devices. While demo mode is on, the real DSPs are disconnected.": "Alles gefahrlos mit einem simulierten DSP ausprobieren – an echte Geräte wird nichts gesendet. Solange der Demo-Modus aktiv ist, sind die echten DSPs getrennt.",
"Not available for the demo device": "Für das Demo-Gerät nicht verfügbar",
"Demo mode is on – switch it off to connect the real DSPs": "Der Demo-Modus ist aktiv – zum Verbinden der echten DSPs bitte ausschalten",
// audio test
"Audio test": "Audiotest",
"Analog input": "Analog-Eingang",
"normal operation": "Normalbetrieb",
"Pink noise": "Rosa Rauschen",
"White noise": "Weißes Rauschen",
"Sine": "Sinus",
"Sine frequency": "Sinus-Frequenz",
"Input signal": "Eingangssignal",
"Test fader": "Testfader",
"all outputs": "alle Ausgänge",
"Audio test running – the DSP plays {signal} instead of its inputs.": "Audiotest läuft – der DSP spielt {signal} statt seiner Eingänge.",
"Choose a test signal above to start.": "Zum Starten oben ein Testsignal wählen.",
"Not possible during the audio test": "Während des Audiotests nicht möglich",
"Saving and recalling presets is blocked during the test. Stopping it switches the noise off first and then puts every fader back where it was.": "Presets speichern und laden ist während des Tests gesperrt. Beim Beenden wird zuerst das Rauschen abgeschaltet, danach gehen alle Fader zurück auf ihren ursprünglichen Wert.",
"Stop test – back to the analog input": "Test beenden – zurück zum Analog-Eingang",
"The test signal replaces the analog inputs of the DSP. When it is switched on, all outputs are lowered to −50 dB first – raise them slowly with the test fader.": "Das Testsignal ersetzt die Analog-Eingänge des DSP. Beim Einschalten werden zuerst alle Ausgänge auf −50 dB abgesenkt – mit dem Testfader langsam hochziehen.",
"Audio test is on – switch it off first": "Der Audiotest läuft – bitte zuerst beenden",
"Audio test is off": "Der Audiotest ist aus",
// curve
"Overlay": "Einblenden",
"Phase": "Phase",
"The rest of the app is locked until the analog input is selected again.": "Der Rest der App ist gesperrt, bis wieder der Analog-Eingang gewählt ist.",
"Phase inverted": "Phase invertiert",
// copy settings, global mute
"Copy to…": "Kopieren nach…",
"Gain, delay, polarity": "Gain, Delay, Phase",
"High / low pass": "Hoch- / Tiefpass",
"PEQ + GEQ": "PEQ + GEQ",
"Compressor + limiter": "Kompressor + Limiter",
"Routing + mix levels": "Routing + Mix-Pegel",
"Copy {ch} to…": "{ch} kopieren nach…",
"What": "Was",
"To": "Wohin",
"Copy": "Kopieren",
"The name stays. Linked target channels take the values for their whole group.": "Der Name bleibt. Verknüpfte Zielkanäle übernehmen die Werte für ihre ganze Gruppe.",
"{n} values copied": "{n} Werte kopiert",
"Nothing to change – the settings are already the same": "Nichts zu ändern – die Einstellungen sind schon gleich",
"All muted – click to unmute what was open before": "Alles stumm – klicken gibt frei, was vorher offen war",
"Mute all channels of all connected DSPs": "Alle Kanäle aller verbundenen DSPs stummschalten",
"MUTED": "STUMM",
"All channels muted": "Alle Kanäle stumm",
"Unmuted – channels that were muted before stay muted": "Freigegeben – vorher stumme Kanäle bleiben stumm",
// SoundField
">30 ms echo": ">30 ms Echo",
"A planning aid: free field without reflections, coverage from the nominal angle. Check the result by ear or measurement.": "Eine Planungshilfe: Freifeld ohne Reflexionen, Abdeckung aus dem Nennwinkel. Das Ergebnis mit dem Ohr oder einer Messung prüfen.",
"Add delay line": "Delay-Linie hinzufügen",
"Add front fills": "Front-Fills hinzufügen",
"Add speakers to calculate delays.": "Lautsprecher hinzufügen, um Delays zu berechnen.",
"Aim": "Ausrichten",
"Aim (°)": "Ausrichtung (°)",
"Aim the mains at ⅔ of the room depth on the centre line ({list}).": "Die Mains auf ⅔ der Raumtiefe in der Mitte ausrichten ({list}).",
"Apply all": "Alle übernehmen",
"Centre cluster": "Mittig bündeln",
"Column": "Säule",
"Coverage (°)": "Abstrahlwinkel (°)",
"Custom": "Eigener",
"DSP outputs": "DSP-Ausgänge",
"Delay": "Delay",
"Delays": "Delays",
"Depth (m)": "Tiefe (m)",
"Distance": "Abstand",
"Ear height (m)": "Ohrhöhe (m)",
"Fill 8″": "Fill 8″",
"Height (m)": "Höhe (m)",
"Its delay is aligned at the dashed target point (drag it to the middle of the area this speaker covers).": "Sein Delay wird am gestrichelten Zielpunkt ausgerichtet (in die Mitte des Bereichs ziehen, den dieser Lautsprecher beschallt).",
"Level in the audience area: {spread} dB spread, {pct} % within ±3 dB of the median.": "Pegel im Publikumsbereich: {spread} dB Streuung, {pct} % innerhalb ±3 dB vom Mittelwert.",
"Main": "Main",
"Main L": "Main L",
"Main R": "Main R",
"Mains and subs are aligned at the reference position, delay and fill speakers at their target point plus {ms} ms so the mains are heard first.": "Mains und Subs werden an der Referenzposition ausgerichtet, Delay- und Fill-Lautsprecher an ihrem Zielpunkt plus {ms} ms, damit man die Mains zuerst hört.",
"Max SPL @1 m (dB)": "Max. SPL @1 m (dB)",
"No DSP in the device list yet.": "Noch kein DSP in der Geräteliste.",
"Nothing to improve with the current layout.": "Mit dem aktuellen Aufbau gibt es nichts zu verbessern.",
"Now on DSP": "Jetzt im DSP",
"Offset (ms)": "Versatz (ms)",
"Quick start": "Schnellstart",
"REF": "REF",
"Raise": "Anheben",
"Raise the mains to {h} m: front-to-back difference {a} dB → {b} dB.": "Mains auf {h} m anheben: Unterschied vorne/hinten {a} dB → {b} dB.",
"Role": "Rolle",
"Room": "Raum",
"Room plan": "Raumplan",
"STAGE": "BÜHNE",
"Select a speaker in the plan, or add one above. Drag to move, use the white handle to aim, drag the reference cross to your listening / mixing position.": "Einen Lautsprecher im Plan wählen oder oben hinzufügen. Ziehen zum Verschieben, mit dem weißen Griff ausrichten, das Referenzkreuz an deine Hör- bzw. Mischposition ziehen.",
"Speaker": "Lautsprecher",
"Speed of sound at {t} °C: {c} m/s.": "Schallgeschwindigkeit bei {t} °C: {c} m/s.",
"Stage depth (m)": "Bühnentiefe (m)",
"Stage width (m)": "Bühnenbreite (m)",
"Start with a stereo pair at the front edge of the stage and a sub in the centre.": "Mit einem Stereo-Paar an der Bühnenkante und einem Sub in der Mitte beginnen.",
"Sub 18″": "Sub 18″",
"Sub 2×18″": "Sub 2×18″",
"Sub frequency": "Sub-Frequenz",
"Suggestions": "Vorschläge",
"Temperature (°C)": "Temperatur (°C)",
"The back of the room is {db} dB quieter than the front third. A delay line with {n} speaker(s) at about {y} m keeps it even.": "Hinten ist es {db} dB leiser als im vorderen Drittel. Eine Delay-Linie mit {n} Lautsprecher(n) bei etwa {y} m gleicht das aus.",
"The first rows in the centre get {db} dB less than the middle of the room – front fills at the stage edge help.": "Die ersten Reihen in der Mitte bekommen {db} dB weniger als die Raummitte – Front-Fills an der Bühnenkante helfen.",
"The subs are {m} m apart – at 80 Hz that causes cancellation lanes through the room (power alley). A centre cluster sounds even everywhere.": "Die Subs stehen {m} m auseinander – bei 80 Hz entstehen dadurch Auslöschungs-Gassen durch den Raum (Power Alley). Mittig gebündelt klingt es überall gleichmäßig.",
"Timing": "Timing",
"Timing: in {a} % of the area a delay/fill arrives before the mains, in {b} % more than 30 ms late. Check positions and apply the calculated delays.": "Timing: In {a} % der Fläche kommt ein Delay/Fill vor den Mains an, in {b} % mehr als 30 ms zu spät. Positionen prüfen und die berechneten Delays übernehmen.",
"Top 12″": "Top 12″",
"Top 15″": "Top 15″",
"Width (m)": "Breite (m)",
"audience: {spread} dB spread · {pct} % within ±3 dB": "Publikum: {spread} dB Streuung · {pct} % innerhalb ±3 dB",
"delay too early": "Delay zu früh",
"median": "Median",
"no output": "kein Ausgang",
"{m} m to the nearest main": "{m} m zum nächsten Main",
"{n} output delay(s) set": "{n} Ausgangs-Delay(s) gesetzt",
"{n} output(s) not connected": "{n} Ausgang/Ausgänge nicht verbunden",
// channel colours
"Channel colours": "Kanalfarben",
"Shown on the mixer strips and in the channel view. Linked channels share one colour; every colour can only be used once per DSP.": "Wird im Mixer und in der Kanalansicht angezeigt. Verknüpfte Kanäle teilen sich eine Farbe; jede Farbe gibt es pro DSP nur einmal.",
"Used by {ch}": "Vergeben an {ch}",
"Custom colour": "Eigene Farbe",
"Colour for {ch}": "Farbe für {ch}",
"Linked channels always share their colour.": "Verknüpfte Kanäle teilen sich immer ihre Farbe.",
"Default": "Standard",
// SoundField stacks
"Or ground stacks: a sub left and right with the top on a distance pole.": "Oder als Stacks: links und rechts ein Sub mit dem Top auf einer Distanzstange.",
"Stacks": "Stacks",
"Stack": "Stack",
"The tops then stay where they are on their own stands.": "Die Tops bleiben dann auf eigenen Stativen, wo sie sind.",
"{top} now stands on {sub} (distance pole)": "{top} steht jetzt auf {sub} (Distanzstange)",
"Own stand / flown": "Eigenes Stativ / geflogen",
"On a pole on {sub}": "Auf Distanzstange auf {sub}",
"Stand": "Aufstellung",
"Edit {name}": "{name} bearbeiten",
"{top} stands on this sub (distance pole).": "{top} steht auf diesem Sub (Distanzstange).",
"Detach": "Abnehmen",
"Height on the pole (m)": "Höhe auf der Stange (m)",
"Sub with a top on a distance pole": "Sub mit Top auf Distanzstange",
"Add a DSP…": "DSP hinzufügen…",
"simulated": "simuliert",
// logo
"Logo": "Logo",
"Your own logo top left (and as the browser icon). PNG, JPG, WebP or SVG, ideally square, at least 64×64 pixels, transparent background recommended. It is scaled to 128×128 pixels; other shapes are centred without distortion.": "Eigenes Logo oben links (und als Browser-Symbol). PNG, JPG, WebP oder SVG, am besten quadratisch, mindestens 64×64 Pixel, transparenter Hintergrund empfohlen. Es wird auf 128×128 Pixel skaliert; andere Formate werden unverzerrt zentriert.",
"Choose image…": "Bild wählen…",
"Default logo": "Standard-Logo",
"Logo replaced": "Logo ersetzt",
"Logo replaced – the image was not square and has been centred": "Logo ersetzt – das Bild war nicht quadratisch und wurde zentriert",
"Please choose a PNG, JPG, WebP or SVG image": "Bitte ein PNG-, JPG-, WebP- oder SVG-Bild wählen",
"The logo could not be read": "Das Logo konnte nicht gelesen werden",
"The image is too small – at least {n}×{n} pixels": "Das Bild ist zu klein – mindestens {n}×{n} Pixel",
"Test": "Test",
// settings page
"Language of the app on this device.": "Sprache der App auf diesem Gerät.",
"Add a DSP": "DSP hinzufügen",
"Over the network or with a USB cable": "Über das Netzwerk oder per USB-Kabel",
"General": "Allgemein",
"Language, demo mode and your logo.": "Sprache, Demo-Modus und dein Logo.",
"Several DSPs can be connected at the same time – pick one at the top. A DSP accepts only one connection: close the Thomann editor first.": "Mehrere DSPs können gleichzeitig verbunden sein – oben auswählen. Ein DSP erlaubt nur eine Verbindung: den Thomann-Editor vorher schließen.",
"Let phones and tablets in your network control this computer – they log in with the PIN.": "Handys und Tablets im Netzwerk können diesen Computer fernsteuern – sie melden sich mit der PIN an.",
"Who may use this web interface.": "Wer diese Weboberfläche benutzen darf.",
"Save and restore the settings of this app.": "Einstellungen dieser App sichern und wiederherstellen.",
// network search, device ID, links
"Already linked – unlink the group first": "Bereits verknüpft – zuerst die Gruppe trennen",
"Advanced": "Erweitert",
"Device ID": "Geräte-ID",
"Only needed if the ID was changed on the DSP (e.g. several DSPs on one RS-485 cable). Default 1.": "Nur nötig, wenn die ID am DSP geändert wurde (z. B. mehrere DSPs an einem RS-485-Kabel). Standard 1.",
"Searching the network for DSPs…": "Suche DSPs im Netzwerk…",
"Search network": "Im Netzwerk suchen",
"Unknown device": "Unbekanntes Gerät",
"in the list": "in der Liste",
"connected": "verbunden",
"no answer (another program connected, or a different device ID)": "keine Antwort (anderes Programm verbunden oder andere Geräte-ID)",
"No DSP found. Is it in the same network and switched on? Close the Thomann editor – a DSP accepts only one connection.": "Kein DSP gefunden. Ist er im selben Netzwerk und eingeschaltet? Den Thomann-Editor schließen – ein DSP erlaubt nur eine Verbindung.",
"Finds DSPs in your network automatically": "Findet DSPs in deinem Netzwerk automatisch",
"Channel settings": "Kanal­einstellungen",
"Channels": "Kanäle",
"Links": "Verknüpfungen",
"Colours": "Farben",
// max level
"Max level": "Max. Pegel",
"no limit": "keine Grenze",
"now above – set on the DSP": "liegt gerade darüber – am DSP eingestellt",
"Software lock for the gain faders: the app does not let them go higher. If the DSP itself is turned up further, the app shows it and the fader can only be pulled down until it snaps into the limit again.": "Software-Sperre für die Gain-Fader: Die App lässt sie nicht höher. Wird am DSP selbst weiter aufgedreht, zeigt die App das an, und der Fader lässt sich nur nach unten ziehen, bis er wieder in die Grenze einrastet.",
"Above the max level of {lim} – press Apply twice to set it anyway.": "Über dem max. Pegel von {lim} – zum Setzen trotzdem zweimal Übernehmen drücken.",
"Max level: {lim}": "Max. Pegel: {lim}",
"Set anyway": "Trotzdem setzen",
}; };
const DE_PATTERNS = [ const DE_PATTERNS = [
+5 -1
View File
@@ -23,9 +23,12 @@
<button data-view="mixer"><svg viewBox="0 0 24 24"><path d="M6 3v18M12 3v18M18 3v18"/><rect x="3.5" y="13" width="5" height="3" rx="1"/><rect x="9.5" y="7" width="5" height="3" rx="1"/><rect x="15.5" y="10" width="5" height="3" rx="1"/></svg><span>Mixer</span></button> <button data-view="mixer"><svg viewBox="0 0 24 24"><path d="M6 3v18M12 3v18M18 3v18"/><rect x="3.5" y="13" width="5" height="3" rx="1"/><rect x="9.5" y="7" width="5" height="3" rx="1"/><rect x="15.5" y="10" width="5" height="3" rx="1"/></svg><span>Mixer</span></button>
<button data-view="channel"><svg viewBox="0 0 24 24"><path d="M2 14c3 0 3-7 6-7s3 10 6 10 3-6 6-6h2"/></svg><span data-t="Channel">Channel</span></button> <button data-view="channel"><svg viewBox="0 0 24 24"><path d="M2 14c3 0 3-7 6-7s3 10 6 10 3-6 6-6h2"/></svg><span data-t="Channel">Channel</span></button>
<button data-view="routing"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16M8 3v18M16 3v18"/><circle cx="8" cy="6" r="2.2" class="f"/><circle cx="16" cy="12" r="2.2" class="f"/><circle cx="8" cy="18" r="2.2" class="f"/></svg><span>Routing</span></button> <button data-view="routing"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16M8 3v18M16 3v18"/><circle cx="8" cy="6" r="2.2" class="f"/><circle cx="16" cy="12" r="2.2" class="f"/><circle cx="8" cy="18" r="2.2" class="f"/></svg><span>Routing</span></button>
<button data-view="link"><svg viewBox="0 0 24 24"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg><span>Link</span></button> <button data-view="link"><svg viewBox="0 0 24 24"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg><span data-t="Channel settings">Channel settings</span><span class="short" data-t="Channels">Channels</span></button>
<button data-view="limiter"><svg viewBox="0 0 24 24"><path d="M2 7h20" stroke-dasharray="2.5 2.5"/><path d="M2 14c2 0 3-7 5-7h3c2 0 3 11 6 11s3-5 6-5"/></svg><span>Limiter</span></button> <button data-view="limiter"><svg viewBox="0 0 24 24"><path d="M2 7h20" stroke-dasharray="2.5 2.5"/><path d="M2 14c2 0 3-7 5-7h3c2 0 3 11 6 11s3-5 6-5"/></svg><span>Limiter</span></button>
<button data-view="soundfield"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M8 7l-2 2 2 2M16 7l2 2-2 2"/><path d="M7 15.5a7 7 0 0 1 10 0" stroke-dasharray="2 2"/><circle cx="12" cy="18" r="1.2" class="f"/></svg><span>SoundField</span><span class="short">Field</span></button>
<button data-view="test"><svg viewBox="0 0 24 24"><path d="M4 9v6h4l5 4V5L8 9z"/><path d="M16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12"/></svg><span data-t="Audio test">Audio test</span><span class="short" data-t="Test">Test</span></button>
</nav> </nav>
<button id="btn-muteall" class="icon" aria-label="Mute all" title="Mute all"></button>
<button id="btn-lock" class="icon" hidden aria-label="Lock" title="Lock"></button> <button id="btn-lock" class="icon" hidden aria-label="Lock" title="Lock"></button>
<button id="btn-settings" class="icon" aria-label="Settings" title="Settings" data-t-label="Settings"> <button id="btn-settings" class="icon" aria-label="Settings" title="Settings" data-t-label="Settings">
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg> <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>
@@ -38,5 +41,6 @@
<div id="toast" hidden></div> <div id="toast" hidden></div>
<script src="/i18n.js"></script> <script src="/i18n.js"></script>
<script src="/app.js"></script> <script src="/app.js"></script>
<script src="/soundfield.js"></script>
</body> </body>
</html> </html>
+679
View File
@@ -0,0 +1,679 @@
"use strict";
/* SoundField – top view of the room: place speakers, see level / sub / timing maps, get placement
suggestions and the delays to set on the DSP outputs.
Free-field model (no reflections, no air absorption): level falls 6 dB per doubling of distance,
directivity from the horizontal coverage angle (−6 dB at its edges, about −24 dB behind the box).
Subs are summed with phase (they interfere), everything else by energy. Positions are metres:
x across the room (0 = left wall), y from the stage wall into the room. Aim 0° points into the room. */
const SF_TYPES = {
top12: { role: "main", cov: 90, spl: 128, h: 2.4 },
top15: { role: "main", cov: 75, spl: 131, h: 2.6 },
column: { role: "main", cov: 120, spl: 124, h: 2.0 },
fill8: { role: "fill", cov: 100, spl: 118, h: 1.1 },
sub18: { role: "sub", cov: 360, spl: 132, h: 0.4 },
sub218: { role: "sub", cov: 360, spl: 137, h: 0.5 },
custom: {},
};
const sfTypeLabel = k => ({ top12: t("Top 12″"), top15: t("Top 15″"), column: t("Column"), fill8: t("Fill 8″"),
sub18: t("Sub 18″"), sub218: t("Sub 2×18″"), custom: t("Custom") }[k] || k);
const SF_ROLE_COLOR = { main: "#38bdf8", sub: "#f472b6", delay: "#f59e0b", fill: "#a3e635" };
const sfRoleLabel = r => ({ main: t("Main"), sub: "Sub", delay: "Delay", fill: "Fill" }[r] || r);
const SF_SUB_HZ = [40, 50, 63, 80, 100, 125];
const sf = { // view state (the plan itself is S.sf, shared through the server)
sel: null, canvas: null, geo: null, drag: null, hover: null, savedAt: 0, saveTimer: null,
panels: {}, // side panels, rebuilt after a change (never the canvas while dragging)
};
const sfMode = () => store.get("dsp.sfmap") || "level";
const sfSubHz = () => +(store.get("dsp.sfhz") || 63);
// ------------------------------------------------------------------ plan helpers
function sfDefault() {
return { room: { w: 20, d: 30 }, stage: { w: 8, d: 4 }, temp: 20, precedence: 5, ear: 1.7,
ref: { x: 10, y: 18 }, speakers: [] };
}
const sfPlan = () => S.sf || (S.sf = sfDefault());
const sfSpeed = p => 331.3 + 0.606 * p.temp; // speed of sound in m/s
const sfR = (p, s, x, y) => Math.max(0.5, Math.hypot(x - s.x, y - s.y, s.h - p.ear));
const sfMs = (p, s, x, y) => sfR(p, s, x, y) / sfSpeed(p) * 1000;
const sfDir = s => [Math.sin(s.aim * Math.PI / 180), Math.cos(s.aim * Math.PI / 180)];
const sfInAudience = (p, x, y) => !(y < p.stage.d && Math.abs(x - p.room.w / 2) < p.stage.w / 2);
function sfDirectivity(s, x, y) {
if (s.cov >= 360) return 0;
const [dx, dy] = sfDir(s), vx = x - s.x, vy = y - s.y, len = Math.hypot(vx, vy) || 1;
const th = Math.acos(clamp((vx * dx + vy * dy) / len, -1, 1)) * 180 / Math.PI, half = s.cov / 2;
return th <= half ? -6 * (th / half) ** 2 : -6 - 18 * Math.min(1, (th - half) / Math.max(1, 180 - half));
}
const sfLevel = (p, s, x, y) => s.spl - 20 * Math.log10(sfR(p, s, x, y)) + sfDirectivity(s, x, y);
// stacks: a top on a distance pole stands on a sub (same spot, higher up)
const SF_POLE = 1.8; // acoustic centre of a top on a pole, above the sub's
const sfOnSub = (p, s) => s.mount && p.speakers.find(x => x.id === s.mount && x.role === "sub");
const sfTopOf = (p, sub) => p.speakers.find(x => x.mount === sub.id);
function sfMount(p, top, sub) {
top.mount = sub.id; top.x = sub.x; top.y = sub.y;
top.h = Math.max(top.h, +(sub.h + SF_POLE).toFixed(1));
}
function sfMoveTo(p, s, x, y) { // move a speaker; a stack moves as one, delay/fill targets move along
const base = sfOnSub(p, s) || s;
const dx = x - base.x, dy = y - base.y;
for (const m of [base, ...p.speakers.filter(t2 => t2.mount === base.id)]) {
m.x = clamp(m.x + dx, 0, p.room.w); m.y = clamp(m.y + dy, 0, p.room.d);
if (m.role === "delay" || m.role === "fill") { m.tx = clamp(m.tx + dx, 0, p.room.w); m.ty = clamp(m.ty + dy, 0, p.room.d); }
}
}
// free sub close to (x, y) a top could be put on
const sfSnapSub = (p, top, x, y) => top.role === "sub" ? null : p.speakers.find(u => u.role === "sub" && Math.hypot(u.x - x, u.y - y) < 0.8 &&
(!sfTopOf(p, u) || sfTopOf(p, u) === top));
function sfSave() {
sf.savedAt = Date.now();
clearTimeout(sf.saveTimer);
// the local plan stays the one being edited (panels and drags hold references into it)
sf.saveTimer = setTimeout(() => api("PUT", "/api/soundfield", S.sf)
.then(() => { sf.savedAt = Date.now(); }).catch(e => toast(t("Error: ") + trMsg(e.message))), 350);
}
function sfOnRemote(data) { // another device changed the plan
if (Date.now() - sf.savedAt < 1500 || sf.drag) return; // our own echo, or we are in the middle of a drag
S.sf = data;
if (S.view === "soundfield" && !S.settings) sfRefresh();
}
// ------------------------------------------------------------------ delays
function sfDelays(p) {
const mains = p.speakers.filter(s => s.role === "main"), subs = p.speakers.filter(s => s.role === "sub");
const out = {}, info = {};
const R = p.ref;
const mainT = mains.length ? mains.reduce((a, s) => a + sfMs(p, s, R.x, R.y), 0) / mains.length : null;
let base = 0;
if (mainT != null) {
const subD = subs.map(s => mainT - sfMs(p, s, R.x, R.y));
base = Math.max(0, -Math.min(0, ...subD)); // a sub further away than the mains: delay the mains instead
subs.forEach((s, i) => { out[s.id] = subD[i] + base; info[s.id] = "ref"; });
}
mains.forEach(s => { out[s.id] = base; info[s.id] = "ref"; });
for (const s of p.speakers.filter(s => s.role === "delay" || s.role === "fill")) {
const tMain = mains.length ? Math.min(...mains.map(m => sfMs(p, m, s.tx, s.ty) + out[m.id])) : null;
out[s.id] = tMain == null ? 0 : Math.max(0, tMain - sfMs(p, s, s.tx, s.ty) + p.precedence);
info[s.id] = "target";
}
if (!mains.length) subs.forEach(s => { out[s.id] = 0; info[s.id] = "none"; });
return { ms: out, info };
}
// ------------------------------------------------------------------ maps
// level colours relative to the median of the audience area: cyan = clearly louder, green = typical, red = too quiet
const LEVEL_STOPS = [[9, [125, 211, 252]], [4.5, [45, 212, 191]], [0, [34, 197, 94]], [-3, [163, 230, 53]], [-6, [234, 179, 8]],
[-9, [249, 115, 22]], [-12, [239, 68, 68]], [-20, [110, 20, 20]]];
const TIME_STOPS = [[0, [34, 197, 94]], [10, [132, 204, 22]], [20, [234, 179, 8]], [30, [249, 115, 22]], [45, [239, 68, 68]]];
function sfStops(stops, v, desc) {
for (let i = 0; i < stops.length - 1; i++) {
const [a, ca] = stops[i], [b, cb] = stops[i + 1];
if (desc ? v >= b : v <= b) { const f = (v - a) / (b - a); return ca.map((c, k) => Math.round(c + (cb[k] - c) * clamp(f, 0, 1))); }
}
return stops[stops.length - 1][1];
}
// value grid over the room for the current map mode; null cells are left empty
function sfField(p, mode) {
const step = Math.max(0.2, Math.max(p.room.w, p.room.d) / 130);
const cols = Math.ceil(p.room.w / step), rows = Math.ceil(p.room.d / step);
const vals = new Float32Array(cols * rows).fill(NaN);
const dl = sfDelays(p).ms;
const tops = p.speakers.filter(s => s.role !== "sub"), subs = p.speakers.filter(s => s.role === "sub");
const mains = p.speakers.filter(s => s.role === "main"), late = p.speakers.filter(s => s.role === "delay" || s.role === "fill");
const k = 2 * Math.PI * sfSubHz() / 1000; // phase per ms
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
const x = (c + 0.5) * step, y = (r + 0.5) * step;
let v = NaN;
if (mode === "level" && tops.length) {
let e = 0; for (const s of tops) e += 10 ** (sfLevel(p, s, x, y) / 10);
v = 10 * Math.log10(e);
} else if (mode === "sub" && subs.length) {
let re = 0, im = 0;
for (const s of subs) { const a = 10 ** (sfLevel(p, s, x, y) / 20), ph = k * (sfMs(p, s, x, y) + (dl[s.id] || 0)); re += a * Math.cos(ph); im -= a * Math.sin(ph); }
v = 10 * Math.log10(re * re + im * im || 1e-12);
} else if (mode === "time" && mains.length && late.length) {
// arrival of the strongest delay/fill speaker relative to the first main arrival, where it matters (≥ main − 6 dB)
let tm = Infinity, lm = -Infinity;
for (const s of mains) { tm = Math.min(tm, sfMs(p, s, x, y) + (dl[s.id] || 0)); lm = Math.max(lm, sfLevel(p, s, x, y)); }
let best = null, bl = -Infinity;
for (const s of late) { const l = sfLevel(p, s, x, y); if (l > bl) { bl = l; best = s; } }
if (best && bl >= lm - 6) v = sfMs(p, best, x, y) + (dl[best.id] || 0) - tm;
}
vals[r * cols + c] = v;
}
return { step, cols, rows, vals };
}
function sfStats(p, field) {
const a = [];
for (let r = 0; r < field.rows; r++) for (let c = 0; c < field.cols; c++) {
const v = field.vals[r * field.cols + c];
if (!isNaN(v) && sfInAudience(p, (c + 0.5) * field.step, (r + 0.5) * field.step)) a.push(v);
}
if (!a.length) return null;
a.sort((x, y) => x - y);
const q = f => a[Math.min(a.length - 1, Math.floor(f * a.length))], med = q(0.5);
return { max: a[a.length - 1], min: a[0], med, spread: q(0.95) - q(0.05), within3: a.filter(v => Math.abs(v - med) <= 3).length / a.length,
early: a.filter(v => v < -1).length / a.length, echo: a.filter(v => v > 30).length / a.length };
}
// ------------------------------------------------------------------ suggestions
// level of the mains alone at (x, y), for the suggestions
const sfMainLevel = (p, x, y, mains = p.speakers.filter(s => s.role === "main")) =>
10 * Math.log10(mains.reduce((e, s) => e + 10 ** (sfLevel(p, s, x, y) / 10), 0) || 1e-12);
function sfSuggestions(p) {
const out = [], W = p.room.w, D = p.room.d, sd = p.stage.d;
const mains = p.speakers.filter(s => s.role === "main"), subs = p.speakers.filter(s => s.role === "sub");
const delays = p.speakers.filter(s => s.role === "delay"), fills = p.speakers.filter(s => s.role === "fill");
const add = (kind, text, apply, label) => out.push({ kind, text, apply, label });
if (!mains.length) {
add("tip", t("Start with a stereo pair at the front edge of the stage and a sub in the centre."), q => {
const x0 = W / 2 - Math.max(2, q.stage.w / 2), x1 = W / 2 + Math.max(2, q.stage.w / 2), y = Math.max(0.5, sd - 0.3);
q.speakers.push(sfNew(q, "top12", x0, y, t("Main L")), sfNew(q, "top12", x1, y, t("Main R")),
sfNew(q, "sub18", W / 2, Math.min(D - 1, sd + 0.6), "Sub"));
sfAimMains(q);
}, t("Quick start"));
add("tip", t("Or ground stacks: a sub left and right with the top on a distance pole."), q => {
const off = Math.max(2, q.stage.w / 2), y = Math.min(D - 1, sd + 0.5);
for (const [x, side] of [[W / 2 - off, "L"], [W / 2 + off, "R"]]) {
const sub = sfNew(q, "sub18", x, y, `Sub ${side}`), top = sfNew(q, "top12", x, y, t(side === "L" ? "Main L" : "Main R"));
sfMount(q, top, sub);
q.speakers.push(sub, top);
}
sfAimMains(q);
}, t("Stacks"));
return out;
}
// 1. aim of the mains: towards ⅔ of the audience depth on the centre line
const aimFor = s => Math.round(Math.atan2(W / 2 - s.x, sd + (D - sd) * 2 / 3 - s.y) * 180 / Math.PI);
const offAim = mains.filter(s => s.cov < 360 && Math.abs(aimFor(s) - s.aim) > 8);
if (offAim.length)
add("tip", t("Aim the mains at ⅔ of the room depth on the centre line ({list}).", { list: offAim.map(s => `${s.name} ${aimFor(s)}°`).join(", ") }),
q => sfAimMains(q), t("Aim"));
// 2. height of the mains: smaller difference between front and back
const fb = h => { const m = mains.map(s => ({ ...s, h })); return sfMainLevel(p, W / 2, sd + 1, m) - sfMainLevel(p, W / 2, D - 1, m); };
const hNow = mains.reduce((a, s) => a + s.h, 0) / mains.length, now = fb(hNow);
let best = hNow, bestV = now;
const hMax = mains.some(s => sfOnSub(p, s)) ? 3 : 5; // tops on poles: no higher than about 3 m
for (let h = 2; h <= hMax + 0.01; h += 0.5) { const v = fb(h); if (v < bestV - 0.01) { bestV = v; best = h; } }
if (best > hNow + 0.3 && now - bestV >= 1.5)
add("tip", t("Raise the mains to {h} m: front-to-back difference {a} dB → {b} dB.", { h: best.toFixed(1), a: now.toFixed(1), b: bestV.toFixed(1) }),
q => q.speakers.forEach(s => { if (s.role === "main") s.h = best; }), t("Raise"));
// 3. delay line when the back gets too quiet
const L0 = sfMainLevel(p, W / 2, sd + (D - sd) * 0.3), back = sfMainLevel(p, W / 2, D - 1);
if (!delays.length && L0 - back > 6 && D - sd > 12) {
let yd = D - 1;
for (let y = sd + 4; y < D - 2; y += 0.25) if (sfMainLevel(p, W / 2, y) <= L0 - 4.5) { yd = y; break; }
const throwM = D - yd, n = clamp(Math.ceil(W / Math.max(5, 2 * throwM * Math.tan(45 * Math.PI / 180))), 1, 4);
add("warn", t("The back of the room is {db} dB quieter than the front third. A delay line with {n} speaker(s) at about {y} m keeps it even.",
{ db: (L0 - back).toFixed(0), n, y: yd.toFixed(1) }), q => {
for (let i = 0; i < n; i++) {
const s = sfNew(q, "top12", W * (i + 0.5) / n, yd, `Delay ${i + 1}`);
Object.assign(s, { role: "delay", h: 3, aim: 0, tx: s.x, ty: Math.min(D - 0.5, yd + throwM * 0.5) });
q.speakers.push(s);
}
}, t("Add delay line"));
}
// 4. subs: spacing creates cancellation lanes ("power alley")
if (subs.length > 1) {
const xs = subs.map(s => s.x), spread = Math.max(...xs) - Math.min(...xs), half = sfSpeed(p) / 80 / 2;
if (spread > half)
add("warn", t("The subs are {m} m apart – at 80 Hz that causes cancellation lanes through the room (power alley). A centre cluster sounds even everywhere.",
{ m: spread.toFixed(1) }) + (subs.some(u => sfTopOf(p, u)) ? " " + t("The tops then stay where they are on their own stands.") : ""), q => {
const ss = q.speakers.filter(s => s.role === "sub");
q.speakers.forEach(s => { s.mount = ""; }); // tops on poles stay where they are, on their own stands
ss.forEach((s, i) => Object.assign(s, { x: W / 2 + (i - (ss.length - 1) / 2) * 0.7, y: Math.min(D - 1, sd + 0.6), aim: 0 }));
}, t("Centre cluster"));
}
// 5. front rows in the shadow of high mains
const front = sfMainLevel(p, W / 2, sd + 1.2), mid = sfMainLevel(p, W / 2, sd + (D - sd) * 0.4);
if (!fills.length && mid - front > 3 && p.stage.w >= 2)
add("tip", t("The first rows in the centre get {db} dB less than the middle of the room – front fills at the stage edge help.", { db: (mid - front).toFixed(0) }), q => {
const n = clamp(Math.round(q.stage.w / 4), 1, 4);
for (let i = 0; i < n; i++) {
const s = sfNew(q, "fill8", W / 2 - q.stage.w / 2 + q.stage.w * (i + 0.5) / n, Math.max(0.3, sd - 0.2), `Fill ${i + 1}`);
Object.assign(s, { tx: s.x, ty: Math.min(D - 1, sd + 3) });
q.speakers.push(s);
}
}, t("Add front fills"));
// 6. coverage and timing summary
const lv = sfStats(p, sfField(p, "level"));
if (lv) add(lv.spread <= 6 ? "ok" : "info", t("Level in the audience area: {spread} dB spread, {pct} % within ±3 dB of the median.",
{ spread: lv.spread.toFixed(1), pct: Math.round(lv.within3 * 100) }));
if (delays.length || fills.length) {
const tm = sfStats(p, sfField(p, "time"));
if (tm && (tm.early > 0.05 || tm.echo > 0.05))
add("warn", t("Timing: in {a} % of the area a delay/fill arrives before the mains, in {b} % more than 30 ms late. Check positions and apply the calculated delays.",
{ a: Math.round(tm.early * 100), b: Math.round(tm.echo * 100) }));
}
return out;
}
function sfAimMains(q) {
const W = q.room.w, aimY = q.stage.d + (q.room.d - q.stage.d) * 2 / 3;
q.speakers.forEach(s => { if (s.role === "main" && s.cov < 360) s.aim = Math.round(Math.atan2(W / 2 - s.x, aimY - s.y) * 180 / Math.PI); });
}
function sfNew(q, type, x, y, name) {
const d = SF_TYPES[type] || {};
const s = { id: Math.random().toString(36).slice(2, 10), name: name || sfTypeLabel(type), role: d.role || "main", type,
x: clamp(x, 0, q.room.w), y: clamp(y, 0, q.room.d), h: d.h ?? 2, aim: 0, cov: d.cov ?? 90, spl: d.spl ?? 125, outs: [] };
s.tx = s.x; s.ty = Math.min(q.room.d, s.y + 6);
s.mount = "";
return s;
}
// ------------------------------------------------------------------ drawing
function sfDraw() {
const cv = sf.canvas, p = sfPlan();
if (!cv || !cv.isConnected) return;
const W = cv.clientWidth;
if (!W) return;
const m = 30, maxH = Math.max(320, Math.min(window.innerHeight * 0.7, 900));
const sc = Math.min((W - 2 * m) / p.room.w, (maxH - 2 * m) / p.room.d);
const H = Math.round(p.room.d * sc + 2 * m), ox = (W - p.room.w * sc) / 2;
if (cv.style.height !== H + "px") cv.style.height = H + "px";
const dpr = window.devicePixelRatio || 1;
cv.width = W * dpr; cv.height = H * dpr;
const g = cv.getContext("2d");
g.scale(dpr, dpr);
const X = x => ox + x * sc, Y = y => m + y * sc;
sf.geo = { X, Y, sc, toM: (px, py) => [(px - ox) / sc, (py - m) / sc] };
// room
g.fillStyle = "#0e1116"; g.fillRect(X(0), Y(0), p.room.w * sc, p.room.d * sc);
// map
const mode = sfMode();
let field = null;
if (mode !== "off") {
field = sfField(p, mode);
const st = sfStats(p, field), ref = mode === "time" ? 0 : st ? st.med : 0;
const img = new ImageData(field.cols, field.rows);
for (let i = 0; i < field.vals.length; i++) {
const v = field.vals[i];
if (isNaN(v)) continue;
let col;
if (mode === "time") col = v < -1 ? [217, 70, 239] : sfStops(TIME_STOPS, v, false);
else col = sfStops(LEVEL_STOPS, Math.min(9, v - ref), true);
img.data.set([...col, 120], i * 4);
}
const off = document.createElement("canvas");
off.width = field.cols; off.height = field.rows;
off.getContext("2d").putImageData(img, 0, 0);
g.imageSmoothingEnabled = true;
g.drawImage(off, X(0), Y(0), field.cols * field.step * sc, field.rows * field.step * sc);
sf.field = field; sf.fieldRef = ref; sf.stats = st;
} else { sf.field = null; sf.stats = null; }
// grid
g.font = "10px system-ui"; g.fillStyle = "#5b6673"; g.lineWidth = 1;
for (let x = 0; x <= p.room.w + 0.001; x++) {
g.strokeStyle = x % 5 ? "#ffffff0d" : "#ffffff22"; g.beginPath(); g.moveTo(X(x), Y(0)); g.lineTo(X(x), Y(p.room.d)); g.stroke();
if (x % 5 === 0) g.fillText(x + " m", X(x) - 6, m - 8);
}
for (let y = 0; y <= p.room.d + 0.001; y++) {
g.strokeStyle = y % 5 ? "#ffffff0d" : "#ffffff22"; g.beginPath(); g.moveTo(X(0), Y(y)); g.lineTo(X(p.room.w), Y(y)); g.stroke();
if (y % 5 === 0) { g.textAlign = "end"; g.fillText(y, X(0) - 5, Y(y) + 3); g.textAlign = "start"; }
}
g.strokeStyle = "#3a4552"; g.lineWidth = 2; g.strokeRect(X(0), Y(0), p.room.w * sc, p.room.d * sc);
// stage
if (p.stage.w > 0 && p.stage.d > 0) {
const sx = X(p.room.w / 2 - p.stage.w / 2), sw = p.stage.w * sc, sh = p.stage.d * sc;
g.fillStyle = "#1c2027e6"; g.fillRect(sx, Y(0), sw, sh);
g.save(); g.beginPath(); g.rect(sx, Y(0), sw, sh); g.clip(); g.strokeStyle = "#ffffff12"; g.lineWidth = 1;
for (let i = -sh; i < sw; i += 10) { g.beginPath(); g.moveTo(sx + i, Y(0)); g.lineTo(sx + i + sh, Y(0) + sh); g.stroke(); }
g.restore();
g.fillStyle = "#8a95a3"; g.font = "600 11px system-ui"; g.textAlign = "center"; g.fillText(t("STAGE"), sx + sw / 2, Y(0) + Math.min(sh - 6, 16)); g.textAlign = "start";
}
// delay / fill targets
for (const s of p.speakers.filter(s => s.role === "delay" || s.role === "fill")) {
g.strokeStyle = SF_ROLE_COLOR[s.role] + "99"; g.setLineDash([4, 4]); g.lineWidth = 1.2;
g.beginPath(); g.moveTo(X(s.x), Y(s.y)); g.lineTo(X(s.tx), Y(s.ty)); g.stroke(); g.setLineDash([]);
g.beginPath(); g.arc(X(s.tx), Y(s.ty), 6, 0, 2 * Math.PI); g.stroke();
}
// speakers (names step aside when boxes stand close together)
const labels = [];
const order = [...p.speakers].sort((a, b) => (b.role === "sub") - (a.role === "sub")); // tops drawn on top of subs
if (sf.snap) { // a top dragged over a free sub: show where it would land
const u = p.speakers.find(x => x.id === sf.snap);
if (u) { g.strokeStyle = "#fff"; g.setLineDash([3, 3]); g.lineWidth = 1.5; g.beginPath(); g.arc(X(u.x), Y(u.y), 18, 0, 2 * Math.PI); g.stroke(); g.setLineDash([]); }
}
for (const s of order) {
const col = SF_ROLE_COLOR[s.role], sel = s.id === sf.sel || (s.role === "sub" && sfTopOf(p, s)?.id === sf.sel), x = X(s.x), y = Y(s.y);
const top = s.role === "sub" && sfTopOf(p, s), onSub = sfOnSub(p, s);
if (s.cov < 360) { // coverage wedge
const r = Math.max(40, 3 * sc), a0 = Math.PI / 2 - (s.aim + s.cov / 2) * Math.PI / 180, a1 = Math.PI / 2 - (s.aim - s.cov / 2) * Math.PI / 180;
g.beginPath(); g.moveTo(x, y); g.arc(x, y, r, a0, a1); g.closePath();
g.fillStyle = col + (sel ? "33" : "1f"); g.fill(); g.strokeStyle = col + (sel ? "aa" : "55"); g.lineWidth = 1; g.stroke();
}
g.fillStyle = col; g.strokeStyle = sel ? "#fff" : "#0b0c0f"; g.lineWidth = sel ? 2.5 : 1.5;
g.beginPath();
if (s.role === "sub") { const r = top ? 12 : 9; g.rect(x - r, y - r, 2 * r, 2 * r); }
else { const [dx, dy] = sfDir(s); g.moveTo(x + dx * 11, y + dy * 11); g.lineTo(x - dy * 9 - dx * 7, y + dx * 9 - dy * 7); g.lineTo(x + dy * 9 - dx * 7, y - dx * 9 - dy * 7); g.closePath(); }
g.fill(); g.stroke();
if (onSub) { g.fillStyle = "#0b0c0f"; g.beginPath(); g.arc(x, y, 2.5, 0, 2 * Math.PI); g.fill(); } // the pole
if (top) continue; // the stack is labelled by its top
const label = onSub ? `${s.name} + ${onSub.name}` : s.name;
g.fillStyle = "#e8edf3"; g.font = (sel ? "600 " : "") + "11px system-ui"; g.textAlign = "center";
const lw = g.measureText(label).width + 6;
let ly = y + 24;
for (let k = 0; k < 4 && labels.some(b => Math.abs(b.x - x) < (b.w + lw) / 2 && Math.abs(b.y - ly) < 13); k++) ly = k % 2 ? y + 24 + 13 * (k + 1) / 2 : y - 16 - 13 * k / 2;
labels.push({ x, y: ly, w: lw });
g.fillText(label, x, ly); g.textAlign = "start";
if (sel && s.cov < 360) { // rotation handle
const [dx, dy] = sfDir(s), hr = Math.max(34, 1.6 * sc);
g.strokeStyle = "#ffffffaa"; g.lineWidth = 1.5; g.beginPath(); g.moveTo(x, y); g.lineTo(x + dx * hr, y + dy * hr); g.stroke();
g.fillStyle = "#fff"; g.beginPath(); g.arc(x + dx * hr, y + dy * hr, 6, 0, 2 * Math.PI); g.fill();
}
}
// reference position
const rx = X(p.ref.x), ry = Y(p.ref.y);
g.strokeStyle = "#e8edf3"; g.lineWidth = 2;
g.beginPath(); g.moveTo(rx - 10, ry); g.lineTo(rx + 10, ry); g.moveTo(rx, ry - 10); g.lineTo(rx, ry + 10); g.stroke();
g.beginPath(); g.arc(rx, ry, 6, 0, 2 * Math.PI); g.stroke();
g.fillStyle = "#e8edf3"; g.font = "600 10px system-ui"; g.fillText(t("REF"), rx + 9, ry - 8);
sfLegend();
}
function sfLegend() {
const el = sf.panels.legend;
if (!el) return;
const mode = sfMode(), st = sf.stats;
const sw = (c, label) => h("span", { class: "sw" }, h("i", { style: `background:rgb(${c.join(",")})` }), label);
if (mode === "off") return el.replaceChildren();
if (mode === "time") return el.replaceChildren(sw([217, 70, 239], t("delay too early")), sw(TIME_STOPS[0][1], "0–10 ms"),
sw(TIME_STOPS[2][1], "20 ms"), sw(TIME_STOPS[4][1], t(">30 ms echo")));
el.replaceChildren(...[[6, LEVEL_STOPS[1][1]], [0, LEVEL_STOPS[2][1]], [-3, LEVEL_STOPS[3][1]], [-6, LEVEL_STOPS[4][1]], [-9, LEVEL_STOPS[5][1]], [-12, LEVEL_STOPS[6][1]]]
.map(([db, c]) => sw(c, db ? `${db > 0 ? "+" : ""}${db} dB` : t("median"))),
...(st ? [h("span", { class: "stat" }, mode === "sub" ? `${sfSubHz()} Hz · ` : "", t("audience: {spread} dB spread · {pct} % within ±3 dB",
{ spread: st.spread.toFixed(1), pct: Math.round(st.within3 * 100) }))] : []));
}
// ------------------------------------------------------------------ interaction
function sfHit(px, py) {
const p = sfPlan(), { X, Y, sc } = sf.geo;
const sel = p.speakers.find(s => s.id === sf.sel);
if (sel && sel.cov < 360) {
const [dx, dy] = sfDir(sel), hr = Math.max(34, 1.6 * sc);
if (Math.hypot(px - (X(sel.x) + dx * hr), py - (Y(sel.y) + dy * hr)) < 12) return { kind: "rot", s: sel };
}
const near = p.speakers.filter(s => Math.hypot(px - X(s.x), py - Y(s.y)) < 15);
const hit = near.find(s => s.role !== "sub") || near[near.length - 1]; // a stack is grabbed by its top
if (hit) return { kind: "move", s: hit };
for (const s of p.speakers) if ((s.role === "delay" || s.role === "fill") && Math.hypot(px - X(s.tx), py - Y(s.ty)) < 10) return { kind: "target", s };
if (Math.hypot(px - X(p.ref.x), py - Y(p.ref.y)) < 14) return { kind: "ref" };
return null;
}
function sfBindCanvas(cv) {
const pos = e => { const r = cv.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; };
const snap = v => Math.round(v * 10) / 10;
cv.addEventListener("pointerdown", e => {
if (!sf.geo) return;
const [px, py] = pos(e), hit = sfHit(px, py);
if (!hit) { if (sf.sel) { sf.sel = null; sfDraw(); sfPanels(); } return; }
e.preventDefault();
if (hit.s && sf.sel !== hit.s.id) { sf.sel = hit.s.id; sfPanels(); }
sf.drag = { ...hit, id: e.pointerId, moved: false };
cv.setPointerCapture(e.pointerId);
beginBusy();
sfDraw();
});
cv.addEventListener("pointermove", e => {
const [px, py] = pos(e);
if (!sf.drag) { sfHover(px, py); return; }
if (e.pointerId !== sf.drag.id) return;
const p = sfPlan(), [mx, my] = sf.geo.toM(px, py), x = clamp(snap(mx), 0, p.room.w), y = clamp(snap(my), 0, p.room.d);
const d = sf.drag;
if (d.kind === "move") {
if (d.s.mount && !sfOnSub(p, d.s)) d.s.mount = "";
sfMoveTo(p, d.s, x, y);
const u = !d.s.mount && sfSnapSub(p, d.s, x, y);
sf.snap = u ? u.id : null;
}
else if (d.kind === "rot") { let a = Math.atan2(mx - d.s.x, my - d.s.y) * 180 / Math.PI; if (!e.shiftKey) a = Math.round(a); else a = Math.round(a / 15) * 15; d.s.aim = a; }
else if (d.kind === "target") { d.s.tx = x; d.s.ty = y; }
else if (d.kind === "ref") { p.ref.x = x; p.ref.y = y; }
d.moved = true;
sfDraw(); sfHover(px, py);
});
const end = e => {
if (!sf.drag || e.pointerId !== sf.drag.id) return;
const moved = sf.drag.moved, d = sf.drag;
sf.drag = null;
if (sf.snap && d.kind === "move") { // dropped onto a free sub: put it on the pole
const p = sfPlan(), u = p.speakers.find(x => x.id === sf.snap);
if (u) { sfMount(p, d.s, u); toast(t("{top} now stands on {sub} (distance pole)", { top: d.s.name, sub: u.name })); }
}
sf.snap = null;
endBusy();
if (moved) { sfSave(); sfDraw(); sfPanels(); }
};
cv.addEventListener("pointerup", end);
cv.addEventListener("pointercancel", end);
cv.addEventListener("pointerleave", () => { if (!sf.drag && sf.panels.readout) sf.panels.readout.textContent = ""; });
cv.addEventListener("keydown", e => {
if ((e.key === "Delete" || e.key === "Backspace") && sf.sel) { e.preventDefault(); sfRemove(sf.sel); }
});
}
function sfHover(px, py) {
const el = sf.panels.readout;
if (!el || !sf.geo) return;
const p = sfPlan(), [x, y] = sf.geo.toM(px, py);
if (x < 0 || y < 0 || x > p.room.w || y > p.room.d) { el.textContent = ""; return; }
let txt = `x ${x.toFixed(1)} m · y ${y.toFixed(1)} m`;
const f = sf.field;
if (f) {
const c = Math.floor(x / f.step), r = Math.floor(y / f.step), v = f.vals[r * f.cols + c];
if (!isNaN(v)) txt += sfMode() === "time" ? ` · ${v >= 0 ? "+" : ""}${v.toFixed(1)} ms` : ` · ${v.toFixed(1)} dB (${(v - sf.fieldRef).toFixed(1)})`;
}
const mains = p.speakers.filter(s => s.role === "main");
if (mains.length) txt += " · " + t("{m} m to the nearest main", { m: Math.min(...mains.map(s => Math.hypot(x - s.x, y - s.y))).toFixed(1) });
el.textContent = txt;
}
function sfChange(fn, full = true) { // change the plan from a panel
fn(sfPlan());
sfSave();
sfDraw();
if (full) sfPanels();
}
function sfRemove(id) {
sfChange(p => { p.speakers = p.speakers.filter(s => s.id !== id); p.speakers.forEach(s => { if (s.mount === id) s.mount = ""; }); });
if (sf.sel === id) { sf.sel = null; sfPanels(); }
}
// ------------------------------------------------------------------ panels
const sfNum = (value, step, onset, attrs = {}) => {
const el = h("input", { type: "number", value: +(+value).toFixed(2), step, ...attrs });
el.addEventListener("change", () => { const v = parseFloat(el.value); if (!isNaN(v)) onset(v); });
return el;
};
function sfOutputs() { // every DSP output known from the device list (also offline ones)
return S.order.map(id => S.devices[id]).filter(d => !d.demo || S.demo.enabled).map(d => {
const n = d.n_out || (d.model === "204" ? 4 : d.model === "408" ? 8 : 0);
return { d, outs: Array.from({ length: n }, (_, o) => o) };
}).filter(x => x.outs.length);
}
function sfEditor() {
const p = sfPlan(), s = p.speakers.find(x => x.id === sf.sel);
if (!s) return h("div", { class: "card sfedit" }, h("h3", {}, t("Speaker")),
h("p", { class: "info" }, t("Select a speaker in the plan, or add one above. Drag to move, use the white handle to aim, drag the reference cross to your listening / mixing position.")));
const up = (k, conv = v => v) => v => sfChange(() => { s[k] = conv(v); });
const typeSel = h("select", { onchange: () => sfChange(() => { const d = SF_TYPES[typeSel.value]; s.type = typeSel.value; Object.assign(s, d.role ? { role: d.role, cov: d.cov, spl: d.spl, h: d.h } : {}); }) },
Object.keys(SF_TYPES).map(k => h("option", { value: k, selected: s.type === k }, sfTypeLabel(k))));
const roleSel = h("select", { onchange: () => sfChange(() => { s.role = roleSel.value; if ((s.role === "delay" || s.role === "fill") && s.tx === s.x && s.ty === s.y) s.ty = Math.min(p.room.d, s.y + 6); }) },
["main", "sub", "delay", "fill"].map(r => h("option", { value: r, selected: s.role === r }, sfRoleLabel(r))));
const name = h("input", { type: "text", value: s.name, maxlength: 24 });
name.addEventListener("change", () => sfChange(() => { s.name = name.value.trim() || s.name; }));
const outs = sfOutputs().map(({ d, outs }) => h("div", { class: "sfouts" }, h("small", {}, d.name),
h("div", { class: "chips" }, outs.map(o => {
const key = `${d.id}:${o}`, on = s.outs.includes(key);
return h("button", { class: "chip" + (on ? " on" : ""), "aria-pressed": String(on),
onclick: () => sfChange(() => { s.outs = s.outs.includes(key) ? s.outs.filter(x => x !== key) : [...s.outs, key]; }) }, `Out ${o + 1}`);
}))));
const base = sfOnSub(p, s), topOn = s.role === "sub" && sfTopOf(p, s);
let stand = null;
if (s.role !== "sub") { // top: free, or on the pole of a sub
const subs = p.speakers.filter(u => u.role === "sub" && (!sfTopOf(p, u) || u.id === s.mount));
const standSel = h("select", { onchange: () => sfChange(q => {
const u = q.speakers.find(x => x.id === standSel.value);
if (u) sfMount(q, s, u); else { s.mount = ""; sfMoveTo(q, s, clamp(s.x + 1, 0, q.room.w), s.y); }
}) }, h("option", { value: "" }, t("Own stand / flown")),
subs.map(u => h("option", { value: u.id, selected: s.mount === u.id }, t("On a pole on {sub}", { sub: u.name }))));
stand = h("div", { class: "row sfstand" }, h("label", { class: "grow" }, t("Stand"), standSel),
base ? h("button", { class: "small", onclick: () => { sf.sel = base.id; sfRefresh(); } }, t("Edit {name}", { name: base.name })) : null);
} else if (topOn) {
stand = h("div", { class: "row sfstand" }, h("span", { class: "grow info" }, t("{top} stands on this sub (distance pole).", { top: topOn.name })),
h("button", { class: "small", onclick: () => { sf.sel = topOn.id; sfRefresh(); } }, t("Edit {name}", { name: topOn.name })),
h("button", { class: "small", onclick: () => sfChange(q => { topOn.mount = ""; sfMoveTo(q, topOn, clamp(topOn.x + 1, 0, q.room.w), topOn.y); }) }, t("Detach")));
}
return h("div", { class: "card sfedit", style: `--rc:${SF_ROLE_COLOR[s.role]}` },
h("h3", {}, h("span", { class: "dotc" }), h("span", { class: "grow" }, s.name),
h("button", { class: "small danger", onclick: () => sfRemove(s.id) }, t("Remove"))),
h("div", { class: "sfgrid" },
h("label", { class: "full" }, "Name", name),
h("label", {}, t("Type"), typeSel), h("label", {}, t("Role"), roleSel),
h("label", {}, "x (m)", sfNum(s.x, 0.1, v => sfChange(q => sfMoveTo(q, s, clamp(v, 0, q.room.w), s.y)))),
h("label", {}, "y (m)", sfNum(s.y, 0.1, v => sfChange(q => sfMoveTo(q, s, s.x, clamp(v, 0, q.room.d))))),
h("label", {}, base ? t("Height on the pole (m)") : t("Height (m)"), sfNum(s.h, 0.1, up("h", v => clamp(v, 0, 30)))),
h("label", {}, t("Aim (°)"), sfNum(s.aim, 1, up("aim", v => ((v + 540) % 360) - 180))),
h("label", {}, t("Coverage (°)"), sfNum(s.cov, 5, up("cov", v => clamp(v, 20, 360)))),
h("label", {}, t("Max SPL @1 m (dB)"), sfNum(s.spl, 1, up("spl", v => clamp(v, 80, 160))))),
stand,
s.role === "delay" || s.role === "fill" ? h("p", { class: "info" }, t("Its delay is aligned at the dashed target point (drag it to the middle of the area this speaker covers).")) : null,
h("div", { class: "sub" }, t("DSP outputs")), outs.length ? outs : h("p", { class: "info" }, t("No DSP in the device list yet.")));
}
function sfRoomCard() {
const p = sfPlan();
const set = (fn) => v => sfChange(q => {
fn(q, v);
for (const s of q.speakers) { s.x = clamp(s.x, 0, q.room.w); s.y = clamp(s.y, 0, q.room.d); s.tx = clamp(s.tx, 0, q.room.w); s.ty = clamp(s.ty, 0, q.room.d); }
for (const s of q.speakers) { const u = sfOnSub(q, s); if (u) { s.x = u.x; s.y = u.y; } }
q.ref.x = clamp(q.ref.x, 0, q.room.w); q.ref.y = clamp(q.ref.y, 0, q.room.d);
});
return h("div", { class: "card" }, h("h3", {}, t("Room")),
h("div", { class: "sfgrid" },
h("label", {}, t("Width (m)"), sfNum(p.room.w, 0.5, set((q, v) => { q.room.w = clamp(v, 4, 200); }))),
h("label", {}, t("Depth (m)"), sfNum(p.room.d, 0.5, set((q, v) => { q.room.d = clamp(v, 4, 300); }))),
h("label", {}, t("Stage width (m)"), sfNum(p.stage.w, 0.5, set((q, v) => { q.stage.w = clamp(v, 0, q.room.w); }))),
h("label", {}, t("Stage depth (m)"), sfNum(p.stage.d, 0.5, set((q, v) => { q.stage.d = clamp(v, 0, q.room.d / 2); }))),
h("label", {}, t("Temperature (°C)"), sfNum(p.temp, 1, set((q, v) => { q.temp = clamp(v, -10, 45); }))),
h("label", {}, t("Ear height (m)"), sfNum(p.ear, 0.1, set((q, v) => { q.ear = clamp(v, 0.5, 3); })))),
h("p", { class: "info" }, t("Speed of sound at {t} °C: {c} m/s.", { t: p.temp, c: sfSpeed(p).toFixed(1) })));
}
function sfSuggestCard() {
const items = sfSuggestions(sfPlan());
return h("div", { class: "card sfsug" }, h("h3", {}, t("Suggestions")),
items.length ? items.map(it => h("div", { class: "sfitem " + it.kind },
h("span", { class: "grow" }, it.text),
it.apply ? h("button", { class: "small on", onclick: () => sfChange(q => it.apply(q)) }, it.label) : null))
: h("p", { class: "info" }, t("Nothing to improve with the current layout.")));
}
function sfDelayCard() {
const p = sfPlan(), { ms, info } = sfDelays(p);
const rows = p.speakers.filter(s => ms[s.id] != null);
const cur = s => s.outs.map(k => {
const [id, o] = k.split(":"), d = S.devices[id];
return d && d.status === "online" && d.state ? d.state.outputs[+o]?.delay / 96 : null;
});
const apply = async list => {
let n = 0, skipped = 0;
for (const s of list) for (const k of s.outs) {
const [id, o] = k.split(":"), d = S.devices[id];
if (!d || d.status !== "online" || !d.state) { skipped++; continue; }
try { await api("POST", `/api/devices/${id}/set`, { kind: "out", idx: +o, param: "delay", value: clamp(Math.round(ms[s.id] * 96), 0, 65280) }); n++; }
catch (e) { toast(t("Error: ") + trMsg(e.message)); return; }
}
toast(t("{n} output delay(s) set", { n }) + (skipped ? " · " + t("{n} output(s) not connected", { n: skipped }) : ""));
};
const withOuts = rows.filter(s => s.outs.length);
return h("div", { class: "card sfdelays" },
h("h3", {}, h("span", { class: "grow" }, t("Delays")),
withOuts.length ? h("button", { class: "small on", onclick: () => apply(withOuts) }, t("Apply all")) : null),
rows.length ? h("table", { class: "sftable" },
h("tr", {}, h("th", {}, t("Speaker")), h("th", {}, t("Distance")), h("th", {}, t("Delay")), h("th", {}, t("Now on DSP")), h("th", {}, "")),
rows.map(s => {
const pt = info[s.id] === "target" ? [s.tx, s.ty] : [p.ref.x, p.ref.y], now = cur(s).filter(v => v != null);
return h("tr", {},
h("td", {}, h("span", { class: "dotc", style: `--rc:${SF_ROLE_COLOR[s.role]}` }), s.name,
h("small", {}, s.outs.length ? s.outs.map(k => { const [id, o] = k.split(":"); return `${S.devices[id]?.name || id} Out ${+o + 1}`; }).join(", ") : t("no output"))),
h("td", {}, `${sfR(p, s, pt[0], pt[1]).toFixed(1)} m`),
h("td", { class: "num" }, `${ms[s.id].toFixed(2)} ms`),
h("td", { class: "num" }, now.length ? now.map(v => v.toFixed(2)).join(" / ") + " ms" : "—"),
h("td", {}, s.outs.length ? h("button", { class: "small", onclick: () => apply([s]) }, t("Apply")) : null));
})) : h("p", { class: "info" }, t("Add speakers to calculate delays.")),
h("p", { class: "info" }, t("Mains and subs are aligned at the reference position, delay and fill speakers at their target point plus {ms} ms so the mains are heard first.", { ms: p.precedence }),
" ", h("label", { class: "inline" }, t("Offset (ms)"), sfNum(p.precedence, 0.5, v => sfChange(q => { q.precedence = clamp(v, 0, 30); }), { class: "short" }))));
}
function sfPanels() { // rebuild everything except the canvas
const box = sf.panels.side;
if (!box || !box.isConnected) return;
box.replaceChildren(sfEditor(), sfSuggestCard(), sfDelayCard(), sfRoomCard());
sfLegend();
}
function sfRefresh() { sfDraw(); sfPanels(); }
function viewSoundField() {
const p = sfPlan();
if (sf.sel && !p.speakers.some(s => s.id === sf.sel)) sf.sel = null;
const cv = h("canvas", { class: "sfcanvas", tabindex: "0", "aria-label": t("Room plan") });
sf.canvas = cv;
sfBindCanvas(cv);
const addBtn = (type, role, label) => h("button", { class: "small", onclick: () => sfChange(q => {
const n = q.speakers.filter(s => s.role === role).length + 1;
const y = role === "delay" ? q.room.d * 0.55 : role === "fill" ? Math.max(0.3, q.stage.d - 0.2) : role === "sub" ? Math.min(q.room.d, q.stage.d + 0.6) : Math.max(0.5, q.stage.d - 0.3);
const s = sfNew(q, type, q.room.w / 2 + (n - 1) * 1.5, y, `${label} ${n}`);
s.role = role;
if (role === "delay") s.h = 3;
q.speakers.push(s); sf.sel = s.id;
}) }, "+ " + label);
const modeSeg = h("div", { class: "seg small" });
const hzSel = h("select", { class: "short", "aria-label": t("Sub frequency"), onchange: () => { store.set("dsp.sfhz", hzSel.value); sfDraw(); } },
SF_SUB_HZ.map(f => h("option", { value: f, selected: f === sfSubHz() }, `${f} Hz`)));
const setMode = m => {
store.set("dsp.sfmap", m);
modeSeg.replaceChildren(...[["level", t("Level")], ["sub", "Sub"], ["time", t("Timing")], ["off", t("Off")]].map(([k, label]) =>
h("button", { class: sfMode() === k ? "on" : "", onclick: () => { setMode(k); sfDraw(); } }, label)));
hzSel.hidden = m !== "sub";
};
setMode(sfMode());
sf.panels.legend = h("div", { class: "sflegend" });
sf.panels.readout = h("div", { class: "sfreadout" });
sf.panels.side = h("div", { class: "sfside" });
requestAnimationFrame(() => { sfDraw(); sfPanels(); });
new ResizeObserver(() => { if (!sf.drag) sfDraw(); }).observe(cv);
return h("div", { class: "sflayout" },
h("div", { class: "card sfmain" },
h("div", { class: "sfbar" },
h("h3", {}, "SoundField"),
h("div", { class: "sfadd" }, addBtn("top12", "main", t("Main")), addBtn("sub18", "sub", "Sub"),
h("button", { class: "small", title: t("Sub with a top on a distance pole"), onclick: () => sfChange(q => {
const n = q.speakers.filter(x => x.role === "sub").length + 1, x = clamp(q.room.w / 2 + (n - 1) * 1.5, 0, q.room.w), y = Math.min(q.room.d, q.stage.d + 0.5);
const sub = sfNew(q, "sub18", x, y, `Sub ${n}`), top = sfNew(q, "top12", x, y, `${t("Main")} ${q.speakers.filter(z => z.role === "main").length + 1}`);
sfMount(q, top, sub); q.speakers.push(sub, top); sf.sel = top.id;
}) }, "+ " + t("Stack")),
addBtn("top12", "delay", "Delay"), addBtn("fill8", "fill", "Fill")),
h("div", { class: "sfmode" }, modeSeg, hzSel)),
cv, h("div", { class: "sffoot" }, sf.panels.legend, sf.panels.readout),
h("p", { class: "info" }, t("A planning aid: free field without reflections, coverage from the nominal angle. Check the result by ear or measurement."))),
sf.panels.side);
}
+278 -3
View File
@@ -67,7 +67,7 @@ label.inline { display: flex; align-items: center; gap: 8px; font-size: 13px; co
border-bottom: 1px solid var(--line); border-bottom: 1px solid var(--line);
} }
.brand { display: flex; flex: none; } .brand { display: flex; flex: none; }
#devtabs { display: flex; gap: 6px; overflow-x: auto; flex: 1; min-width: 0; scrollbar-width: none; } #devtabs { display: flex; gap: 6px; flex: 0 1 auto; min-width: 0; position: relative; }
#devtabs::-webkit-scrollbar { display: none; } #devtabs::-webkit-scrollbar { display: none; }
.devtab { white-space: nowrap; flex: none; max-width: 220px; background: var(--panel); } .devtab { white-space: nowrap; flex: none; max-width: 220px; background: var(--panel); }
.devtab .dn { overflow: hidden; text-overflow: ellipsis; } .devtab .dn { overflow: hidden; text-overflow: ellipsis; }
@@ -79,7 +79,8 @@ label.inline { display: flex; align-items: center; gap: 8px; font-size: 13px; co
.dot.error { background: var(--bad); } .dot.error { background: var(--bad); }
@keyframes blink { 50% { opacity: .3; } } @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 { display: flex; gap: 4px; background: var(--panel); border: 1px solid var(--line); border-radius: 11px; padding: 3px; flex: none;
margin-left: auto; } /* logo + DSP choice on the left, menu and buttons on the right */
#viewtabs button { border: 0; background: none; min-height: 36px; padding: 6px 14px; color: var(--dim); border-radius: 8px; } #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 { width: 18px; height: 18px; }
#viewtabs button svg .f { fill: currentColor; stroke: none; } #viewtabs button svg .f { fill: currentColor; stroke: none; }
@@ -100,7 +101,8 @@ body[data-view=settings] #viewtabs button.active { background: none; color: var(
/* phones: view switcher becomes a bottom navigation bar */ /* phones: view switcher becomes a bottom navigation bar */
@media (max-width: 759px) { @media (max-width: 759px) {
:root { --bnav: calc(62px + env(safe-area-inset-bottom)); } :root { --bnav: calc(62px + env(safe-area-inset-bottom)); }
.brand { display: none; } .brand img, .brand svg { width: 24px; height: 24px; }
#btn-muteall { margin-left: auto; } /* the menu moved to the bottom bar: buttons stay on the right */
/* backdrop-filter would make the header the containing block of the fixed bottom bar */ /* 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); } #top { backdrop-filter: none; -webkit-backdrop-filter: none; background: var(--bg); }
#viewtabs { #viewtabs {
@@ -442,3 +444,276 @@ body.locked #statusbar :is(button, select):not([data-view-ok]) { cursor: not-all
.limled.h { width: auto; height: auto; margin: 0; padding: 2px 6px; font-size: 10px; font-weight: 700; letter-spacing: .06em; .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); } color: color-mix(in srgb, var(--led-o) 45%, transparent); }
.limled.h.on { color: #1a1000; } .limled.h.on { color: #1a1000; }
/* ---- demo mode */
.demo-badge { font-size: 10px; font-weight: 700; letter-spacing: .08em; color: #1a1000 !important;
background: var(--warn) !important; border-radius: 5px; padding: 1px 6px; }
.devtab.demo { border-color: var(--warn); }
.devtab.paused, .card.paused { opacity: .45; }
.devtab.paused { cursor: not-allowed; }
.card.demo-on { border-color: var(--warn); }
/* ---- device lock (hardware) */
input.code { width: 7.5em; text-align: center; font-family: ui-monospace, Menlo, Consolas, monospace;
font-size: 20px; letter-spacing: .3em; text-transform: uppercase; }
.dialog input.code { display: block; margin: 8px auto 4px; }
.lockbox .row { align-items: center; gap: 8px; margin: 6px 0; }
.lockbox .sub { margin-top: 10px; }
.dot.locked { background: var(--warn); }
.dialog label.chk { display: flex; align-items: center; gap: 8px; margin-top: 12px; font-size: 14px; }
.dialog label.chk input { width: 20px; height: 20px; }
.dialog .err { text-align: center; }
.lockbox input.code { flex: none; width: 7.5em; }
/* ---- audio test */
.test-badge { font-size: 10px; font-weight: 700; letter-spacing: .08em; color: #fff !important;
background: var(--bad) !important; border-radius: 5px; padding: 1px 6px; }
.testbanner { margin: 0 0 12px; padding: 10px 14px; border-radius: 10px; font-weight: 600;
background: color-mix(in srgb, var(--bad) 18%, transparent); border: 1px solid var(--bad); }
.cards.testcards { grid-template-columns: minmax(0, 1fr); }
.srcgrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px; }
.srcgrid .src { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; padding: 12px; text-align: left;
text-transform: none; letter-spacing: 0; min-height: 58px; }
.srcgrid .src small { color: var(--dim); font-weight: 400; }
.srcgrid .src.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 16%, var(--panel)); }
.srcgrid .src.noise.on { border-color: var(--bad); background: color-mix(in srgb, var(--bad) 16%, var(--panel)); }
.sinefreq { margin-top: 12px; align-items: center; gap: 10px; }
.sinefreq.dim { opacity: .5; }
.testfader.off .tf { opacity: .35; pointer-events: none; }
.testbody { display: flex; gap: 18px; align-items: flex-start; min-width: 0; }
.tf { display: flex; flex-direction: column; align-items: center; gap: 8px; }
.tf .fader { height: 300px; }
.testval { white-space: nowrap; width: 6.5em; text-align: center; font-size: 18px; font-weight: 500; font-variant-numeric: tabular-nums; }
.tf { flex: none; width: 6.5em; }
.tmeters { display: flex; gap: 6px; overflow-x: auto; min-width: 0; padding-bottom: 4px; }
.tmeter { display: flex; flex-direction: column; align-items: center; gap: 4px; flex: none; }
.tmeter .led { height: 300px; }
.testfader h3 .info { margin-left: 8px; text-transform: none; letter-spacing: 0; font-weight: 400; }
.tmeter small { font-size: 11px; color: var(--dim); }
button.wide { width: 100%; margin-top: 14px; }
.tmeter button.mute { padding: 6px 8px; font-size: 11px; min-width: 52px; }
.tmeter.muted .led { opacity: .35; }
/* ---- curve: phase view, overlays, master bypass */
.seg.small button { padding: 5px 10px; font-size: 12px; min-height: 0; }
.card h3 .seg.small { margin-right: 8px; }
button.bypass.on { background: #991b1b; border-color: var(--bad); color: #fff; }
.card.eq-off .bands { opacity: .45; }
.chips.overlay { margin-top: 8px; align-items: center; gap: 6px; flex-wrap: wrap; }
.chips.overlay .sub { margin-right: 4px; }
button.chip.ov { display: inline-flex; align-items: center; gap: 6px; padding: 4px 9px; font-size: 12px; text-transform: none; letter-spacing: 0; }
button.chip.ov i { width: 10px; height: 10px; border-radius: 3px; border: 2px solid var(--oc); }
button.chip.ov.on { border-color: var(--oc); background: color-mix(in srgb, var(--oc) 18%, var(--panel)); }
button.chip.ov.on i { background: var(--oc); }
.geq { position: relative; }
.geq.bypassed > * { opacity: .35; }
.geq.bypassed::after { content: "BYPASS"; position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
font: 700 34px system-ui; color: #ef444499; pointer-events: none; }
body.testlock #viewtabs button:disabled, body.testlock #btn-settings:disabled, body.testlock .devtab:disabled { opacity: .35; cursor: not-allowed; }
.testbanner small { display: block; font-weight: 400; margin-top: 2px; color: var(--dim); }
.pol { display: inline-block; margin-left: 4px; font-size: 13px; font-weight: 700; line-height: 14px; color: #e879f9; vertical-align: -1px; }
/* ---- global mute */
#btn-muteall svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
#btn-muteall.on { background: #991b1b; border-color: var(--bad); color: #fff; animation: mutepulse 1.6s ease-in-out infinite; }
@keyframes mutepulse { 50% { box-shadow: 0 0 14px #ef4444aa; } }
/* ---- copy dialog */
.copydlg .sub { margin: 12px 0 6px; }
.copygroups { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 6px 14px; }
.copygroups label.chk { display: flex; align-items: center; gap: 8px; font-size: 14px; }
.copygroups label.chk input { width: 18px; height: 18px; }
.copydev .chips { margin-top: 0; }
button.chip.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--text); }
/* ---- SoundField */
.sflayout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; }
@media (min-width: 1100px) { .sflayout { grid-template-columns: minmax(0, 1.65fr) minmax(320px, 1fr); align-items: start; } }
.sfmain { padding-bottom: 10px; }
.sfbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-bottom: 10px; }
.sfbar h3 { margin: 0 auto 0 0; }
.sfadd { display: flex; flex-wrap: wrap; gap: 6px; }
.sfmode { display: flex; gap: 6px; align-items: center; }
.sfmode select.short { width: auto; padding: 4px 8px; min-height: 0; font-size: 12px; }
.sfcanvas { display: block; width: 100%; height: 480px; touch-action: none; border-radius: 8px; outline: none; cursor: crosshair; }
.sffoot { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 6px 16px; margin-top: 8px; min-height: 18px; font-size: 12px; color: var(--dim); }
.sflegend { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: center; }
.sflegend .sw { display: inline-flex; align-items: center; gap: 5px; }
.sflegend .sw i { width: 12px; height: 12px; border-radius: 3px; opacity: .85; }
.sflegend .stat { color: var(--text); }
.sfreadout { font-variant-numeric: tabular-nums; }
.sfside { display: grid; gap: 14px; }
.sfgrid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px 10px; }
.sfgrid label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--dim); }
.sfgrid label.full { grid-column: 1 / -1; }
.sfgrid input, .sfgrid select { width: 100%; min-width: 0; }
.sfedit .dotc, .sftable .dotc { display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: var(--rc); margin-right: 8px; flex: none; }
.sfedit h3 { display: flex; align-items: center; }
.sfedit .sub { margin: 12px 0 4px; }
.sfouts { margin-top: 6px; }
.sfouts small { color: var(--dim); }
.sfouts .chips { margin-top: 4px; }
.sfsug .sfitem { display: flex; gap: 10px; align-items: center; padding: 9px 10px; border-radius: 8px; margin-top: 8px; font-size: 13px;
background: var(--panel2); border-left: 3px solid var(--accent); }
.sfsug .sfitem.warn { border-left-color: var(--warn); }
.sfsug .sfitem.ok { border-left-color: var(--ok); }
.sfsug .sfitem.info { border-left-color: var(--dim); }
.sfsug .sfitem button { flex: none; }
.sftable { width: 100%; border-collapse: collapse; font-size: 13px; }
.sftable th { text-align: left; font-weight: 600; color: var(--dim); font-size: 11px; text-transform: uppercase; letter-spacing: .05em; padding: 4px 6px; }
.sftable td { padding: 6px; border-top: 1px solid var(--line); vertical-align: middle; }
.sftable td small { display: block; color: var(--dim); font-size: 11px; margin-left: 18px; }
.sftable td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.sfdelays .info label.inline { display: inline-flex; align-items: center; gap: 6px; margin-top: 6px; }
.sfdelays .info input.short { width: 70px; }
/* ---- channel colours */
.strip.tinted .nm { color: color-mix(in srgb, var(--cc) 55%, #fff); }
.colorbox .colgrid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 14px; margin-top: 6px; }
.colorbox .sub { margin: 4px 0; }
button.colrow { display: flex; align-items: center; gap: 10px; width: 100%; margin-top: 6px; padding: 6px 10px; min-height: 0;
text-transform: none; letter-spacing: 0; font-weight: 500; text-align: left; }
button.colrow small { display: block; color: var(--dim); font-size: 11px; font-weight: 400; }
.swatch { width: 18px; height: 18px; border-radius: 5px; flex: none; border: 1px solid #ffffff33; }
.swatch.none { background: repeating-linear-gradient(45deg, #ffffff22 0 3px, transparent 3px 6px); }
.coldlg .swatches { display: grid; grid-template-columns: repeat(6, 1fr); gap: 8px; }
button.swatch.big { width: 100%; height: 38px; padding: 0; min-height: 0; border-radius: 8px; border: 2px solid transparent; }
button.swatch.big.on { border-color: #fff; box-shadow: 0 0 0 2px #0b0c0f inset; }
button.swatch.big:disabled { opacity: .25; cursor: not-allowed;
background-image: linear-gradient(135deg, transparent 46%, #0b0c0f 46%, #0b0c0f 54%, transparent 54%) !important; }
.coldlg .custom { margin-top: 12px; align-items: center; }
.coldlg input[type=color] { width: 56px; height: 34px; padding: 2px; border-radius: 8px; background: var(--panel2); border: 1px solid var(--line); }
.coldlg .custom input[type=color] { flex: none; width: 56px; }
.sfstand { align-items: flex-end; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
.sfstand label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--dim); }
/* ---- DSP drop-down */
.devpick { max-width: 320px; gap: 8px; }
.devpick .chev { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; margin: -4px -4px -4px 2px;
border-radius: 6px; background: var(--panel3); color: var(--text); }
.devpick .chev svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2.6; stroke-linecap: round; stroke-linejoin: round;
transition: transform .15s; }
.devpick .chev.open svg { transform: rotate(180deg); }
.devpick:hover .chev { background: var(--accent); color: #06121c; }
.devpick .minidots { display: inline-flex; gap: 3px; margin-left: 2px; padding-left: 8px; border-left: 1px solid var(--line); }
.devpick .minidots .dot { width: 6px; height: 6px; box-shadow: none; animation: none; }
.devmenu { position: absolute; top: calc(100% + 6px); left: 0; z-index: 60; min-width: 280px; max-width: min(420px, 92vw);
max-height: 60vh; overflow-y: auto; padding: 6px; background: var(--panel); border: 1px solid var(--line); border-radius: 12px;
box-shadow: 0 12px 40px #000a; display: flex; flex-direction: column; gap: 4px; }
button.devitem { display: flex; align-items: center; gap: 8px; width: 100%; justify-content: flex-start; text-transform: none; letter-spacing: 0;
font-weight: 500; background: transparent; border-color: transparent; padding: 9px 10px; }
button.devitem:hover:not(:disabled) { background: var(--panel2); }
button.devitem.on { background: var(--panel3); border-color: var(--accent); }
button.devitem .dn { flex: 1; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
button.devitem .where { font-size: 11px; color: var(--dim); }
button.devitem small { font-size: 11px; color: var(--dim); background: var(--panel3); border-radius: 5px; padding: 1px 5px; }
button.devitem.paused, button.devitem:disabled { opacity: .45; cursor: not-allowed; }
/* ---- custom logo */
.brand img { width: 26px; height: 26px; object-fit: contain; border-radius: 6px; display: block; }
.logorow { align-items: flex-start; gap: 14px; }
.logoprev { width: 72px; height: 72px; flex: none; display: flex; align-items: center; justify-content: center; border-radius: 12px;
background: repeating-conic-gradient(#ffffff10 0 25%, transparent 0 50%) 0 0 / 14px 14px, var(--panel2); border: 1px solid var(--line); }
.logoprev img, .logoprev svg { width: 56px; height: 56px; object-fit: contain; }
/* ---- menu as a sidebar when the top bar is too narrow (tablets, small windows) */
:root { --side: 92px; }
@media (min-width: 760px) {
body.navside #viewtabs { position: fixed; top: var(--hdr); left: 0; bottom: 0; width: var(--side); z-index: 15; margin: 0;
flex-direction: column; gap: 4px; padding: 8px 6px max(8px, env(safe-area-inset-bottom)); overflow-y: auto;
border: 0; border-right: 1px solid var(--line); border-radius: 0; background: var(--panel); }
body.navside #viewtabs button { flex-direction: column; gap: 4px; width: 100%; min-height: 60px; padding: 8px 4px; font-size: 11px;
line-height: 1.15; text-align: center; white-space: normal; }
body.navside #viewtabs button svg { width: 22px; height: 22px; }
body.navside #statusbar, body.navside #main { margin-left: var(--side); }
body.navside #main { max-width: none; }
body.navside #btn-muteall { margin-left: auto; }
/* backdrop-filter would make the header the containing block of the fixed sidebar */
body.navside #top { backdrop-filter: none; -webkit-backdrop-filter: none; background: var(--bg); }
}
/* phones: all menu items fit in the bottom bar, long labels are shortened */
@media (max-width: 759px) {
#viewtabs button { min-width: 0; font-size: 10px; letter-spacing: 0; }
#viewtabs button span { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#viewtabs button:has(.short) > span:not(.short) { display: none; } /* long labels: short form in the bottom bar */
#viewtabs button span.short { display: inline; }
}
#viewtabs button .short { display: none; }
.logorow + .actions { margin-top: 12px; }
/* ---- settings page */
.setwrap { max-width: 1180px; margin: 0 auto; }
.setnav { position: sticky; top: var(--hdr); z-index: 9; display: flex; gap: 6px; flex-wrap: wrap; padding: 10px 0; margin-bottom: 4px;
background: linear-gradient(var(--bg) 75%, transparent); }
.setnav .chip { min-height: 32px; }
.setsec { margin: 6px 0 30px; scroll-margin-top: calc(var(--hdr) + 58px); }
.setsec > header { margin: 0 2px 12px; }
.setsec > header h2 { margin: 0; font-size: 17px; font-weight: 650; letter-spacing: .01em; }
.setsec > header p { margin: 4px 0 0; color: var(--dim); font-size: 13px; max-width: 760px; }
.setgrid { display: grid; gap: 12px; align-items: stretch; grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr)); }
.setgrid.wide { grid-template-columns: repeat(auto-fill, minmax(min(100%, 420px), 1fr)); }
.setgrid > .card { display: flex; flex-direction: column; margin: 0; }
.setgrid > .card > h3 { margin-bottom: 8px; }
.setgrid > .card > p.info { margin: 0 0 12px; }
.setgrid > .card > :last-child { margin-top: auto; } /* buttons and switches line up at the bottom of each row */
.setgrid > .card > .actions { display: flex; gap: 8px; flex-wrap: wrap; padding-top: 14px; }
.setgrid > .card > .actions button { flex: 1 1 auto; }
.setgrid > .card .devform { align-content: start; }
.setgrid .seg { width: 100%; }
.setgrid .seg button { min-height: 40px; }
.setgrid > .card .row { gap: 8px; }
.setgrid > .card > .row > button { flex: 1 1 auto; }
button.devadd { min-height: 180px; border: 2px dashed var(--line); background: transparent; flex-direction: column; justify-content: center;
align-items: center; gap: 6px; text-transform: none; letter-spacing: 0; color: var(--dim); }
button.devadd:hover { border-color: var(--accent); color: var(--text); background: var(--panel); }
button.devadd .plus { font-size: 34px; line-height: 1; color: var(--accent); }
button.devadd b { font-size: 15px; color: var(--text); }
.setgrid > button.devadd > :last-child { margin-top: 0; }
/* narrow top bar: the DSP button shrinks (name gets shortened) instead of covering the buttons */
.devpick { min-width: 0; max-width: min(320px, 100%); }
.devpick .dn { min-width: 0; }
@media (max-width: 480px) { .devpick .minidots, .devpick small { display: none; } }
/* ---- link tab: channels already in a link */
.lkch.taken { cursor: not-allowed; opacity: .55; }
.lkch.taken:hover { background: inherit; }
/* ---- device ID, network search */
.idrow { display: flex; align-items: center; gap: 10px; margin-top: 6px; font-size: 13px; color: var(--text); }
.idrow input.short { width: 80px; }
button.devadd .plus svg { width: 32px; height: 32px; fill: none; stroke: currentColor; stroke-width: 2.4; stroke-linecap: round; }
.scanres { display: flex; flex-direction: column; gap: 6px; min-width: min(460px, 80vw); max-height: 55vh; overflow-y: auto; }
.scanres .empty.small { padding: 24px 8px; }
.scanrow { display: flex; align-items: center; gap: 10px; padding: 9px 10px; border-radius: 9px; background: var(--panel2); }
.scanrow small { display: block; color: var(--dim); font-size: 12px; }
/* ---- software max level: a striped "locked" zone in the track above the limit, behind the knob */
:root { --limgrey: repeating-linear-gradient(-45deg, #8a95a366 0 3px, #8a95a314 3px 6px); --limstripe: repeating-linear-gradient(-45deg, #ef444466 0 3px, #ef444414 3px 6px); }
/* --p = limit, --q = knob: between them (knob above the limit, set on the DSP) the stripes turn grey, above the knob red */
input[type=range].haslim { --p: calc(13px + var(--lim) * (100% - 26px)); --q: calc(13px + var(--val, var(--lim)) * (100% - 26px)); }
input[type=range].haslim::-webkit-slider-runnable-track {
background: linear-gradient(90deg, var(--line) 0 var(--p), #f87171 var(--p) calc(var(--p) + 2px), transparent calc(var(--p) + 2px)),
var(--limgrey) var(--p) 0 / calc(var(--q) - var(--p)) 100% no-repeat,
linear-gradient(var(--line), var(--line)) var(--p) 0 / calc(var(--q) - var(--p)) 100% no-repeat,
var(--limstripe) var(--line); }
input[type=range].haslim::-moz-range-track {
background: linear-gradient(90deg, var(--line) 0 var(--p), #f87171 var(--p) calc(var(--p) + 2px), transparent calc(var(--p) + 2px)),
var(--limgrey) var(--p) 0 / calc(var(--q) - var(--p)) 100% no-repeat,
linear-gradient(var(--line), var(--line)) var(--p) 0 / calc(var(--q) - var(--p)) 100% no-repeat,
var(--limstripe) var(--line); }
.fader .limzone { position: absolute; left: var(--tx); width: 10px; margin-left: -5px; top: 12px; border-radius: 5px 5px 2px 2px;
height: calc((1 - var(--f)) * (100% - 24px)); background: var(--limstripe); pointer-events: none; z-index: 0; }
.fader .limzone::after { content: ""; position: absolute; left: -6px; right: -6px; bottom: -1px; height: 2px; border-radius: 1px;
background: #f87171; box-shadow: 0 0 6px #ef444488; }
.limnote { display: flex; align-items: center; gap: 6px; margin: 8px 0 0; }
.limnote svg, .overlim svg { width: 14px; height: 14px; flex: none; fill: none; stroke: currentColor; stroke-width: 2; }
.overlim { display: flex; align-items: flex-start; gap: 8px; margin-top: 10px; padding: 9px 10px; border-radius: 8px; font-size: 13px;
color: #fecaca; background: #ef44441f; border: 1px solid #ef444466; }
.overlim[hidden] { display: none; }
.mlrow { display: grid; grid-template-columns: 110px minmax(0, 1fr) 84px; align-items: center; gap: 10px; margin-top: 8px; }
.mllabel { font-size: 13px; display: inline-flex; align-items: center; gap: 4px; }
.mlval { font-size: 12px; color: var(--dim); text-align: right; font-variant-numeric: tabular-nums; }
.mlval.on { color: var(--bad); font-weight: 600; }
.mlwarn { grid-column: 2 / -1; color: var(--warn); font-size: 11px; margin-top: -4px; }
.fader .limbelow { position: absolute; left: var(--tx); width: 10px; margin-left: -5px; pointer-events: none; z-index: 0;
bottom: calc(12px + var(--f) * (100% - 24px)); height: calc(max(0, var(--v, 0) - var(--f)) * (100% - 24px));
background: var(--limgrey), #0b0d10; border-radius: 2px; }
+45
View File
@@ -120,6 +120,51 @@ def test_channel_names():
assert P.param_command(m, "in", 0, {"name": "Süd"}, "name") == (0x3D, b"\x00Sued ") assert P.param_command(m, "in", 0, {"name": "Süd"}, "name") == (0x3D, b"\x00Sued ")
def test_device_lock():
# answer to 0x2C: [time lock][4 bytes time lock data][device lock]
assert P.device_locked(bytes([0, 0, 0, 0, 0, 1]))
assert not P.device_locked(bytes([0, 0, 0, 0, 0, 0]))
assert not P.device_locked(bytes([0, 20])) # short answer: no lock information
assert P.LOCK_CODE.fullmatch("A1BA") and not P.LOCK_CODE.fullmatch("a1ba") and not P.LOCK_CODE.fullmatch("A1B")
assert P.build_frame(P.CMD_UNLOCK, b"\x00A1BA")[5:11] == bytes([0x2D, 0x00]) + b"A1BA"
import sim
dsp = sim.SimDSP("204", "A1BA")
assert P.device_locked(dsp.handle(P.CMD_PRESET_COUNT, b"")[1])
assert dsp.handle(P.CMD_UNLOCK, b"\x00ZZZZ") == (P.CMD_UNLOCK, bytes([0, 0]))
assert dsp.handle(P.CMD_UNLOCK, b"\x00A1BA") == (P.CMD_UNLOCK, bytes([0, 1]))
assert not P.device_locked(dsp.handle(P.CMD_PRESET_COUNT, b"")[1])
dsp.handle(P.CMD_SET_LOCK_CODE, b"B2C3")
assert dsp.lock_code == "B2C3"
def test_test_signal():
# source/frequency follow the mute masks and one word per channel (editor: 0x2C8 on the 204, 0x59C on the 408)
assert P.MODELS["204"].test_base == 0x2C8 and P.MODELS["408"].test_base == 0x59C
for m in P.MODELS.values():
st = P.default_state(m)
st["test"] = {"source": 3, "freq": 17}
assert P.parse_state(m, bytes(P.build_state_buffer(m, st)))["test"] == {"source": 3, "freq": 17}
st = P.default_state(P.MODELS["204"])
P.apply_command(P.MODELS["204"], st, P.CMD_TEST_SIGNAL, bytes([1, 5]))
assert st["test"] == {"source": 1, "freq": 5}
def test_master_bypass():
# masks after the test signal: [?][PEQ inputs][PEQ outputs][GEQ inputs] (editor: 0x2CE/0x2D0/0x2D2 on the 204)
m = P.MODELS["204"]
assert m.test_base + 6 == 0x2CE and m.test_base + 10 == 0x2D2 == m.size - 2
st = P.default_state(m)
st["inputs"][1]["peq_bypass"] = st["inputs"][0]["geq_bypass"] = st["outputs"][3]["peq_bypass"] = True
buf = P.build_state_buffer(m, st)
assert buf[0x2CE:0x2D4] == bytes([2, 0, 8, 0, 1, 0])
back = P.parse_state(m, bytes(buf))
assert back["inputs"][1]["peq_bypass"] and back["inputs"][0]["geq_bypass"] and back["outputs"][3]["peq_bypass"]
assert not back["inputs"][0]["peq_bypass"] and not back["outputs"][0]["peq_bypass"]
assert P.param_command(m, "out", 3, back["outputs"][3], "peq_bypass") == (0x3C, bytes([5, 1]))
assert P.param_command(m, "in", 0, back["inputs"][0], "geq_bypass") == (0x49, bytes([0, 1]))
assert P.MODELS["408"].test_base + 6 == 0x5A2
if __name__ == "__main__": if __name__ == "__main__":
for name, fn in list(globals().items()): for name, fn in list(globals().items()):
if name.startswith("test_"): if name.startswith("test_"):