Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) A proper spectrum analyzer in EQ-8 and EQ-3 (#265) (#357)

Chris Laupamae7053d0dcef7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d02c65f2..1b80bc00 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,14 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **A proper spectrum analyzer in EQ-8 and EQ-3** (#265): the spectrum behind the curve is now
+ a smooth, filled area that rises at once and falls back over about 300 ms, read from 256
+ points in 1/6-octave bands, so a tone reads at its own level and pink noise reads flat. EQ-8
+ draws the output filled with the input as a dim line (Pre fills the input), and gains
+ **Range** (60 / 90 / 120 dB) and **Peak** hold next to Pre / Post / Off; both are saved with
+ the device and older projects open at 90 dB, peak off. It also fixes why the old display
+ jumped: half of every analysis window held stale audio. The sound is unchanged. MCP
+ `set_eq8` `analyzerRangeDb` / `analyzerPeak`.
- **A plug-in's card shows its interface** (#270): once you've opened a plug-in's window,
its device card stands on a picture of it, darkened by a wash in the theme's card colour
so the name, facts and buttons stay readable — the whole small card, and the info column
diff --git a/FEATURES.md b/FEATURES.md
index 81ca27b5..2fe4b502 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -694,7 +694,8 @@ audio effects after it keep running and keep their settings; saved with the proj
slope for the cuts and a channel — stereo, Mid, Side, Left or Right. Scale (0–200 % of every
shelf and bell gain), Output ±12 dB and Auto gain. A full-width response graph (draggable
numbered nodes, the selected band's curve, a separate Side curve, an input / output spectrum
- analyzer switched Pre / Post / Off), band chips, a panel for the selected band; 34 factory
+ analyzer — a filled 1/6-octave curve with fast-rise / slow-fall ballistics, switched Pre / Post /
+ Off, with a 60 / 90 / 120 dB Range and Peak hold), band chips, a panel for the selected band; 34 factory
presets; MCP `read_eq8`, `set_eq8_band`, `set_eq8`.
- **Nota Compressor** (1) — 5 character models (Clean/Glue/Punch/Opto/FET), soft knee,
look-ahead (reported as latency for PDC), Peak/RMS/Auto detection, hold, auto-release,
@@ -803,7 +804,7 @@ audio effects after it keep running and keep their settings; saved with the proj
- **Nota EQ-3** (16) — three-band DJ isolator: Low / Mid / High faders (−24 … +6 dB, or the
Classic ±15 dB range) with a 0 dB detent and KILL buttons, two crossovers, 24 / 48 dB/oct
Linkwitz-Riley slopes (phase-aligned, flat at unity), output gain. A response graph with each
- band's curve, the brass sum and the output spectrum (engine FFT) — drag the crossover handles,
+ band's curve, the brass sum and the output spectrum (the same filled analyzer as EQ-8) — drag the crossover handles,
or ride a band's gain in its zone; a status strip; 30 factory presets; MCP `read_eq3`,
`set_eq3`.
- **Nota Level** (18) — loudness leveler (BS.1770 LUFS): Auto rides the gain to a Target
diff --git a/specs/046-eq-spectrum-analyzer/checklists/requirements.md b/specs/046-eq-spectrum-analyzer/checklists/requirements.md
new file mode 100644
index 00000000..e64e2d40
--- /dev/null
+++ b/specs/046-eq-spectrum-analyzer/checklists/requirements.md
@@ -0,0 +1,32 @@
+# Specification Quality Checklist: EQ spectrum analyzer
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-28
+**Feature**: [spec.md](../spec.md)
+
+## Content Quality
+
+- [x] No implementation details beyond the constraints the issue names (off the audio thread, FFT size)
+- [x] Focused on user value and business needs
+- [x] Written for non-technical stakeholders
+- [x] All mandatory sections completed
+
+## Requirement Completeness
+
+- [x] No [NEEDS CLARIFICATION] markers remain
+- [x] Requirements are testable and unambiguous
+- [x] Success criteria are measurable
+- [x] All acceptance scenarios are defined
+- [x] Edge cases are identified
+- [x] Scope is clearly bounded (EQ-8 + EQ-3; Lens, Auto Filter, Dynamic EQ, Crush, Prism are follow-ups)
+- [x] Dependencies and assumptions identified
+
+## Feature Readiness
+
+- [x] All functional requirements have clear acceptance criteria
+- [x] User scenarios cover primary flows
+- [x] Feature meets measurable outcomes defined in Success Criteria
+
+## Notes
+
+- FFT size and "off the audio thread" are named in the issue itself, so they stay in the spec.
diff --git a/specs/046-eq-spectrum-analyzer/plan.md b/specs/046-eq-spectrum-analyzer/plan.md
new file mode 100644
index 00000000..80177c67
--- /dev/null
+++ b/specs/046-eq-spectrum-analyzer/plan.md
@@ -0,0 +1,43 @@
+# Implementation Plan: EQ spectrum analyzer
+
+**Branch**: `feat/eq8-analyzer` | **Date**: 2026-10-28 | **Spec**: [spec.md](spec.md)
+
+## Summary
+
+Replace the 96-band analysis in EQ-8 and EQ-3 with a shared engine `SpectrumAnalyzer`
+(256 points, 1/6-octave band energy, fast-rise / 300 ms fall, optional 1.5 s peak hold, falls on
+silence), still run from `scopeRead` off the audio thread. EQ-8 gains Range and Peak params
+(appended, default 90 dB / off). The cards draw the spectrum as a filled low-contrast area under
+the curve through one shared helper.
+
+## Technical Context
+
+C++20 engine (Signalsmith RealFFT), .NET 10 / Avalonia app. No new dependencies. Audio thread
+untouched: the rings and their writes stay as they are.
+
+## Constitution Check
+
+- Audio-thread rules: analysis stays on the reading thread under the device mutex (pass).
+- Pure C ABI: no ABI change; telemetry goes through the existing `nota_device_scope` (pass).
+- Backwards compatibility: params appended, older projects load with defaults (pass).
+- Tests: smoke test drives the analyzer with sine, pink noise and silence (pass).
+
+## Project Structure
+
+```text
+src/native/nota.engine/src/dsp/primitives/SpectrumAnalyzer.{h,cpp} new
+src/native/nota.engine/src/devices/effects/Eq.{h,cpp} uses it, 2 params, layout
+src/native/nota.engine/src/devices/effects/Eq3.{h,cpp} uses it, layout
+src/native/nota.engine/CMakeLists.txt new source
+src/managed/Nota.App/Controls/SpectrumFill.cs new drawing helper
+src/managed/Nota.App/Controls/Eq8Views.cs, Eq3Views.cs fill, peak, range
+src/managed/Nota.App/DeviceCards/Bodies/EqDeviceBody.cs, Eq3DeviceBody.cs layout, controls
+tests/Nota.SmokeTest/EqAnalyzerTests.cs (+ Program.cs `--eq-analyzer`)
+```
+
+## Phases
+
+1. Engine analyzer + EQ-8/EQ-3 wiring + smoke tests (sine level, pink flatness, flicker, fall
+ time, silence, timing, params default on an old-layout project, bit-identical render).
+2. App drawing and controls.
+3. Docs (EN + RU), CHANGELOG, FEATURES; macOS check with before/after screenshots.
diff --git a/specs/046-eq-spectrum-analyzer/research.md b/specs/046-eq-spectrum-analyzer/research.md
new file mode 100644
index 00000000..b84fc449
--- /dev/null
+++ b/specs/046-eq-spectrum-analyzer/research.md
@@ -0,0 +1,80 @@
+# Research: EQ spectrum analyzer
+
+## R1. What is wrong with today's analyzer
+
+`Eq::analyse()` (Eq.cpp) already uses a Hann-windowed 4096/8192-point FFT, so resolution is not
+the problem. What reads as coarse and jumpy:
+
+- **96 points**, drawn as a 1 px polyline; at a 400 px card that is a visible step every 4 px.
+- **Bands narrower than a bin** below ~300 Hz: `k0 = k1 = round(centre / binHz)`, so several
+ points repeat one bin and the low end is a staircase.
+- **Symmetric smoothing**: a 200 ms one-pole on power, both up and down. Hits are smeared on the
+ way up and the shape keeps wobbling with the noise of each frame.
+- **Freezes on silence**: when the ring stops advancing (`w == lastAnaW_`, e.g. EQ asleep) the last
+ shape is returned as is.
+- **Line only**: no fill, so it competes with the EQ curve instead of sitting under it.
+- **A ring bug (the main cause)**: in `Eq::process` the post-ring loop carried on from the pre
+ pass's write index instead of starting at the block's, so each block wrote its pre samples at
+ [w, w+F) and its post samples at [w+F, w+2F), and the index advanced 2F per block. Every FFT
+ window was half stale data, in both rings, which is what made the spectrum jump from frame to
+ frame. Fixed by restarting the post loop at the block's first index. Audio is not affected.
+
+EQ-3 (Eq3.cpp) has a copy of the same code with one ring.
+
+## R2. Band energy instead of tilt
+
+Decision: each of 256 points sums bin power over a 1/6-octave band around it.
+Rationale: a constant-Q band holds all of a sine's energy (Hann main lobe ±1 bin), so a sine reads
+its level (+0.5 dB for the Hann lobe) wherever it sits between bins; and pink noise has equal
+energy per fraction of an octave, so it reads flat with no tilt parameter. Bands overlap (point
+spacing 1/25.6 octave), which is the smoothing.
+Alternatives: per-bin magnitude plus a +3 or +4.5 dB/oct display tilt (Lens, Pro-Q): a sine then
+reads off its level by the tilt, and a smoothing pass is needed; rejected for the EQ cards.
+Below the frequency where a 1/6-octave band is narrower than a bin (about 100 Hz at 4096/48 kHz)
+the point interpolates the two nearest bins' power. Noise there reads per bin (rising 3 dB/oct
+towards the bottom); sines still read right.
+
+## R3. Ballistics
+
+Rise: one-pole in dB with τ = 20 ms (at 30 updates/s that is 80 % of the way per frame, reads as
+instant but takes the edge off frame noise). Fall: linear in dB at 66.7 dB/s (20 dB in 300 ms).
+Peak: holds 1.5 s, then falls at 33.3 dB/s, never below the curve. Silence: if the ring has not
+advanced since the last update, the target is the floor (−150 dB), so the curve falls away.
+
+## R4. Where the analyzer lives
+
+`src/dsp/primitives/SpectrumAnalyzer.{h,cpp}`, a plain class with no locks: the owning device
+calls `analyse()` under its own `mx_` from `scopeRead` (the card's reading thread), as today.
+It reads the device's existing power-of-two ring, so the audio thread is untouched (FR-001,
+SC-006). Signalsmith RealFFT, as Eq already uses.
+
+## R5. Parameters and persistence
+
+Two params appended to EQ-8 (`AnaRange` 0/1/2 = 60/90/120 dB, default 1; `AnaPeak` 0/1, default
+0), making `kNumParams` 62. Device params are stored by index; an older project has 60 values and
+leaves the two at their defaults. The UI already guards on `DeviceParamCount > AnalyzerP`; the
+new ones get the same guard. Neither param is read by `process()`, so audio is bit-identical.
+
+## R6. Telemetry layout
+
+EQ-8: `kTele` 16, then input curve, output curve and peak curve, 256 floats each (`S_Bands` =
+256). The peak curve follows what is shown: the output on Post, the input on Pre. EQ-3: `kTele` +
+256. Both cards read `kScope` from the same constants; nothing else reads these layouts (MCP
+`read_eq` reads only the telemetry block).
+
+## R7. Drawing
+
+A shared `SpectrumFill` helper in the app: a closed StreamGeometry from the curve down to the
+bottom edge, filled with a low-alpha neutral wash; points below the range floor clamp to the
+bottom so silence draws nothing visible. The input on Post is a dim 1 px line; the peak a 1 px
+line at a slightly higher alpha. EQ-3 uses the same helper with its own dB mapping.
+
+## R6 — The Peak line on drums (macOS check)
+
+On a Drum Rack loop the held Peak line showed narrow notches and spikes. Each point's 1.5 s
+hold runs out on its own, so a point whose top came earlier than its neighbours' falls while
+they still hold: a notch up to tens of dB deep and one point wide. After each update the held
+line's slope between neighbouring points is now limited to 2 dB per point (about 51 dB per
+octave), in both directions; it only ever raises points, so the line stays at or above the
+curve. The drum-loop smoke check measures the deepest notch and tallest spike against the
+neighbours (before: 10.6 / 8.5 dB, after: 1.9 / 2.0 dB).
diff --git a/specs/046-eq-spectrum-analyzer/spec.md b/specs/046-eq-spectrum-analyzer/spec.md
new file mode 100644
index 00000000..333e5128
--- /dev/null
+++ b/specs/046-eq-spectrum-analyzer/spec.md
@@ -0,0 +1,178 @@
+# Feature Specification: EQ spectrum analyzer
+
+**Feature Branch**: `feat/eq8-analyzer`
+
+**Created**: 2026-10-28
+
+**Status**: Draft
+
+**Input**: User description: "EQ-8: a proper spectrum analyzer (nota-daw/nota#265). The analyzer
+behind EQ-8's curve looks coarse, jumpy and hard to read. Proper FFT analysis with windowing,
+enough bins and log-frequency smoothing; fast-attack, slower-release ballistics and an optional
+peak hold; a Pre/Post toggle and a range setting; drawn as a filled low-contrast area under the
+EQ curve; the same analyzer reused where EQ-3 and the other EQ cards show a spectrum. Analysis
+off the audio thread."
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Read the mix through EQ-8 (Priority: P1)
+
+A producer puts EQ-8 on a bus and plays the song. Today the spectrum is a thin, stepped line made
+of 96 points that wobbles up and down with every frame, so it is hard to tell where the energy
+sits. With the new analyzer, they see a smooth, filled shape under the EQ curve. It rises at once
+when a kick hits and falls back gently, so the shape of the mix holds still enough to read, and a
+peak line shows where it reached in the last moments.
+
+**Why this priority**: This is the issue. An EQ is judged first by its analyzer, and a reviewer
+said the current one would be better gone.
+
+**Independent Test**: Play pink noise, a sine and a drum loop through EQ-8 and look at the card.
+Pink noise reads as a nearly flat, steady shape; a 1 kHz sine reads as one narrow peak at 1 kHz
+near its level; the drum loop's hits rise at once and fall away smoothly.
+
+**Acceptance Scenarios**:
+
+1. **Given** EQ-8 with the analyzer on Post, **When** audio plays, **Then** the output spectrum
+ is drawn as a filled, low-contrast area under the EQ curve, with a smooth edge (no visible
+ steps between points at the card's normal size), and the EQ curve and band nodes stay on top
+ and fully readable.
+2. **Given** a steady 1 kHz sine at −12 dBFS, **When** it plays, **Then** the spectrum shows one
+ peak at 1 kHz, reading within ±3 dB of −12 dB, and the shape does not visibly flicker.
+3. **Given** a drum loop, **When** a hit arrives, **Then** the spectrum rises within one display
+ frame, and **When** the hit ends, **Then** it falls back over roughly a third of a second
+ rather than dropping at once.
+4. **Given** Post, **Then** the input spectrum is also shown, as a dim line, so the EQ's effect
+ reads as the gap between the two. **Given** Pre, **Then** only the input spectrum is shown
+ (filled). **Given** Off, **Then** no spectrum is drawn and no analysis runs.
+5. **Given** the transport stops or the input goes silent, **Then** the spectrum falls away to
+ nothing and does not freeze at its last shape.
+
+---
+
+### User Story 2 - Peak hold and range (Priority: P2)
+
+A mixing engineer wants to see the loudest a resonance got over the last chorus, and to zoom the
+analyzer in on the top of the mix.
+
+**Why this priority**: The issue asks for both; they are what turns the display into a tool.
+
+**Independent Test**: Turn Peak on, play a loop with one loud hit, and see a thin line hold at the
+hit's level and then fall. Switch Range between its settings and see the vertical scale change.
+
+**Acceptance Scenarios**:
+
+1. **Given** Peak on, **When** audio plays, **Then** a thin line above the spectrum marks each
+ frequency's highest recent level, holds for about 1.5 seconds and then falls.
+2. **Given** Peak off, **Then** no peak line is drawn.
+3. **Given** Range set to 60, 90 or 120 dB, **Then** the analyzer's vertical scale runs from
+ 0 dBFS at the top to −60, −90 or −120 dBFS at the bottom. The default is 90 dB. The EQ
+ curve's own ±dB scale does not change.
+4. **Given** the user sets Peak and Range, **When** the project is saved and reopened, or the
+ device is duplicated or saved as a preset, **Then** both settings come back.
+5. **Given** a project saved before this change, **When** it opens, **Then** EQ-8 loads with its
+ bands, Pre/Post/Off choice and sound unchanged, Peak off and Range at 90 dB.
+
+---
+
+### User Story 3 - The same analyzer in EQ-3 (Priority: P3)
+
+A user moves from EQ-8 to EQ-3 on another track. Its spectrum reads the same way: the same
+smoothing, ballistics and fill, so levels compare across the two cards.
+
+**Why this priority**: The issue asks for reuse where a spectrum is shown. EQ-3 shares EQ-8's old
+96-band analysis code, so it moves to the shared analyzer with it.
+
+**Independent Test**: Put EQ-8 (Post) and EQ-3 on the same signal. Their spectra match in shape
+and level.
+
+**Acceptance Scenarios**:
+
+1. **Given** EQ-3 on a track, **When** audio plays, **Then** its spectrum uses the shared
+ analyzer and is drawn as a filled area, like EQ-8's.
+2. **Given** the same signal into EQ-8 (Post, flat) and EQ-3 (flat), **Then** both spectra read
+ within 1 dB of each other at every frequency.
+
+### Edge Cases
+
+- **Sample rate**: at 44.1/48 kHz the analysis uses a 4096-point FFT, at 88.2 kHz and above
+ 8192, so the bins stay about 11 Hz apart. The frequency axis stays 20 Hz–20 kHz.
+- **Low frequencies**: below a few hundred hertz a display point is narrower than an FFT bin; the
+ curve interpolates between bins there instead of repeating one bin as a flat step.
+- **Silence**: below the bottom of the range the area is not drawn at all (no line along the
+ floor).
+- **Several EQ cards open**: each analyses only while its card is shown, at no more than 30
+ updates a second, so hidden cards cost nothing.
+- **Offline render / freeze**: the analyzer never runs on the audio thread and never touches the
+ rendered audio.
+- **Mid/Side or Left/Right bands**: the spectrum stays the mono sum of the input and the output,
+ as today.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: The analysis MUST stay off the audio thread. The audio thread only writes samples
+ into the existing lock-free rings; the FFT and all smoothing run when the card reads telemetry.
+- **FR-002**: The analysis MUST use a Hann-windowed FFT of 4096 points (8192 above 50 kHz) over
+ the latest input, at up to 30 updates per second.
+- **FR-003**: The analyzer MUST map the FFT onto a log-frequency curve of at least 256 points from
+ 20 Hz to 20 kHz. Each point MUST read the energy in a 1/6-octave band around it (summed in the
+ power domain), so neighbouring points overlap and the curve is smooth. Where the band is
+ narrower than an FFT bin, the point MUST interpolate between the two nearest bins instead of
+ repeating one bin.
+- **FR-004**: Because each point reads a constant fraction of an octave, a sine MUST read at its
+ own level and pink noise MUST read flat, with no extra tilt.
+- **FR-005**: Each point MUST rise to a new higher level at once and fall at a fixed rate that
+ takes about 300 ms to drop 20 dB.
+- **FR-006**: With Peak on, each point's peak MUST hold for 1.5 s and then fall at half the
+ spectrum's fall rate; with Peak off no peak data is drawn.
+- **FR-007**: EQ-8 MUST add two saved parameters at the end of its parameter list: **Range**
+ (60, 90 or 120 dB; default 90) and **Peak** (off or on; default off). Older projects and
+ presets, which lack them, MUST load with the defaults and otherwise unchanged.
+- **FR-008**: The EQ-8 card MUST show the spectrum as a filled, low-contrast area under the EQ
+ curve: the output when on Post (with the input as a dim line), the input when on Pre. The peak
+ line, when on, MUST be a thin line in the same hue.
+- **FR-009**: The EQ-8 card MUST give Range and Peak controls next to the existing Pre/Post/Off
+ control.
+- **FR-010**: EQ-3 MUST use the same shared analyzer and the same fill drawing; it keeps its
+ fixed 90 dB range and no peak line.
+- **FR-011**: The analyzer MUST reset (fall to nothing) when the device is reset or the input is
+ silent, and MUST NOT show a stale shape when the card is reopened.
+- **FR-012**: The MCP device help for EQ-8 MUST list the new parameters.
+- **FR-013**: EQ-8's input and output rings MUST hold the block's samples at the same indices,
+ so each analysis window is contiguous audio (found while specifying: the output ring ran on
+ from the input pass, leaving half of every window stale).
+
+### Key Entities
+
+- **Spectrum analyzer**: an engine object owned by a device. It reads a ring of mono samples,
+ runs the FFT, and keeps the smoothed curve, the peak curve and their ages. One instance per
+ analysed signal (EQ-8 has two: input and output).
+- **Spectrum telemetry**: the curve points the card reads with the device's other telemetry.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: A steady sine at any frequency from 50 Hz to 15 kHz reads within ±3 dB of its
+ level, at its frequency (within one display point).
+- **SC-002**: Steady pink noise reads flat within ±3 dB from 100 Hz to 15 kHz (below about
+ 100 Hz a band is narrower than a bin and the reading follows the bins).
+- **SC-003**: With a steady sine, consecutive frames differ by less than 0.5 dB at the sine's
+ frequency; with steady pink noise, the mean frame-to-frame change across the curve is under
+ 1.5 dB.
+- **SC-004**: After a full-scale burst stops, the curve falls 20 dB in 250–400 ms.
+- **SC-005**: One analysis update of EQ-8 (two curves) takes under 1 ms on the CI machines, and
+ the audio-thread cost of EQ-8 and EQ-3 is unchanged (the perf gate passes without an override).
+- **SC-006**: Every existing EQ-8 and EQ-3 project, preset and smoke render plays back
+ bit-identical audio.
+
+## Assumptions
+
+- The Pre/Post/Off control already exists and keeps its meaning and its parameter index.
+- Peak hold time and fall rates are fixed values, not user settings; Lens remains the device for
+ full analyzer control (FFT size, window, averaging, tilt).
+- Lens keeps its own analyzer for now: it already has every control the issue asks for, and moving
+ it is a refactor with no user-visible change. Auto Filter (which analyses in the app), Dynamic
+ EQ, Crush and Prism are follow-ups.
+- The analyzer's vertical range is a view setting saved with the device, like Pre/Post/Off.
diff --git a/specs/046-eq-spectrum-analyzer/tasks.md b/specs/046-eq-spectrum-analyzer/tasks.md
new file mode 100644
index 00000000..23821295
--- /dev/null
+++ b/specs/046-eq-spectrum-analyzer/tasks.md
@@ -0,0 +1,12 @@
+# Tasks: EQ spectrum analyzer
+
+- [x] T001 `SpectrumAnalyzer` (prepare, reset, analyse, curve, peak) in src/dsp/primitives; add to CMake
+- [x] T002 EQ-8: use two analyzers, append AnaRange / AnaPeak params (names, ranges, defaults, text, MCP help)
+- [x] T003 EQ-8: telemetry layout 16 + 3 × 256; skip analysis when Off; reset on deviceAction / prepare
+- [x] T004 EQ-3: use one analyzer, layout 16 + 256
+- [x] T005 Smoke tests `--eq-analyzer`: sine level 50 Hz–15 kHz, pink flatness, flicker, fall time, silence, peak hold, timing, old project defaults, bit-identical audio
+- [x] T006 App: SpectrumFill helper; Eq8Views fill + dim input + peak + range mapping
+- [x] T007 App: EQ-8 card Range and Peak controls
+- [x] T008 App: Eq3Views fill through the helper; Eq3DeviceBody layout
+- [x] T009 CHANGELOG, FEATURES, nota-docs EN + RU (EQ-8 and EQ-3 pages)
+- [ ] T010 Full smoke run, macOS check with before/after screenshots
diff --git a/src/managed/Nota.App/Controls/Eq3Views.cs b/src/managed/Nota.App/Controls/Eq3Views.cs
index aad92e97..2f1bd306 100644
--- a/src/managed/Nota.App/Controls/Eq3Views.cs
+++ b/src/managed/Nota.App/Controls/Eq3Views.cs
@@ -182,7 +182,7 @@ internal sealed class Eq3Graph : Control
private readonly bool[] _kill = new bool[3];
private double _f1 = 250, _f2 = 2500, _top = 6;
private bool _lr8, _iso = true, _specValid;
- private readonly float[] _spec = new float[96];
+ private readonly float[] _spec = new float[256]; // dsp::SpectrumAnalyzer::kPoints
private int _specN;
// Drag state: 0 / 1 = a crossover handle, 2 + b = band b's gain.
@@ -345,22 +345,8 @@ internal sealed class Eq3Graph : Control
double y0 = Math.Round(Y(0, h)) + 0.5;
ctx.DrawLine(new Pen(NotaPalette.GridBar, 1), new Point(0, y0), new Point(w, y0));
- // Output spectrum, behind everything: 0 dBFS at the top, −84 at the bottom.
- if (_specValid)
- {
- var g = new StreamGeometry();
- using (var gc = g.Open())
- {
- for (int i = 0; i < _specN; i++)
- {
- double x = (i + 0.5) / _specN * w;
- double y = Math.Clamp(-_spec[i] / 84.0, 0, 1) * h;
- if (i == 0) gc.BeginFigure(new Point(x, y), false); else gc.LineTo(new Point(x, y));
- }
- gc.EndFigure(false);
- }
- ctx.DrawGeometry(null, new Pen(NotaPalette.BorderStrong, 1, lineJoin: PenLineJoin.Round), g);
- }
+ // Output spectrum, behind everything, filled as on EQ-8: 0 dBFS at the top, −90 at the bottom.
+ if (_specValid) SpectrumFill.Draw(ctx, _spec, w, h, 90, _specN);
// Band curves and the sum.
int n = (int)Math.Clamp(w / 2, 60, 320);
diff --git a/src/managed/Nota.App/Controls/Eq8Views.cs b/src/managed/Nota.App/Controls/Eq8Views.cs
index ed2fa7a9..25e30b80 100644
--- a/src/managed/Nota.App/Controls/Eq8Views.cs
+++ b/src/managed/Nota.App/Controls/Eq8Views.cs
@@ -2,8 +2,10 @@
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
// Nota EQ-8 (device kind 0) response graph, a build of the "Nota EQ-8" mockup. The window
-// draws the analyzer behind everything (the input spectrum dim, the output spectrum a step
-// brighter — Pre shows the input alone, Post both, Off neither), the selected band's own curve
+// draws the analyzer behind everything (specs/046: the output spectrum as a low-contrast filled
+// area with the input as a dim line over it — Pre fills the input alone, Off draws neither — and
+// with Peak on a thin line at each frequency's recent top, over the Range's 60 / 90 / 120 dB
+// below 0 dBFS), the selected band's own curve
// as a faint accent line, the Side path as a teal line when any band works on the Side, and
// the main response (stereo — or the Mid when the Side has its own curve) as the neutral primary
// curve. Every band is a numbered node at its effective gain (Scale applied) — selected accent,
@@ -29,13 +31,14 @@ internal static class Eq8
{
public const int Bands = 8, PerBand = 5;
public const int On = 0, TypeF = 1, FreqF = 2, GainF = 3, QF = 4;
- public const int SlopeBase = 40, ChannelBase = 48, ScaleP = 56, OutputP = 57, AutoGainP = 58, AnalyzerP = 59, ParamCount = 60;
+ public const int SlopeBase = 40, ChannelBase = 48, ScaleP = 56, OutputP = 57, AutoGainP = 58, AnalyzerP = 59,
+ AnaRangeP = 60, AnaPeakP = 61, ParamCount = 62;
public const int LowCut = 0, LowShelf = 1, Bell = 2, Notch = 3, HighShelf = 4, HighCut = 5;
public const int St = 0, Mid = 1, Side = 2, Left = 3, Right = 4;
public const int AnaPre = 0, AnaPost = 1, AnaOff = 2;
// Telemetry (Eq::S_* / kTele / kSpec).
public const int S_InPeak = 0, S_OutPeak = 1, S_AutoGain = 2, S_SampleRate = 3, S_Cpu = 4, S_Analysed = 5, S_Latency = 6,
- kTele = 16, kSpec = 96, PreAt = kTele, PostAt = kTele + kSpec, kScope = kTele + 2 * kSpec;
+ kTele = 16, kSpec = 256, PreAt = kTele, PostAt = kTele + kSpec, PeakAt = kTele + 2 * kSpec, kScope = kTele + 3 * kSpec;
public const double Fmin = 20, Fmax = 20000;
public static readonly string[] TypeNames = DynEq.TypeNames;
@@ -46,6 +49,8 @@ internal static class Eq8
public static readonly string[] ChannelShort = { "St", "M", "S", "L", "R" };
public static readonly string[] SlopeSeg = { "12", "24", "48\u2009dB" };
public static readonly string[] AnalyzerSeg = { "Pre", "Post", "Off" };
+ public static readonly string[] RangeSeg = { "60", "90", "120" };
+ public static double RangeDb(int i) => i switch { 0 => 60, 2 => 120, _ => 90 };
public static bool HasGain(int type) => DynEq.HasGain(type);
public static bool IsCut(int type) => type is LowCut or HighCut;
@@ -104,9 +109,7 @@ public sealed class Eq8Curve : Control
private static readonly IPen GridFaint = new Pen(NotaPalette.GridSubBeat, 1);
private static readonly IPen GridMid = new Pen(NotaPalette.GridBeat, 1);
private static readonly IPen ZeroPen = new Pen(NotaPalette.TrackOff, 1);
- private static readonly IPen PrePen = new Pen(NotaPalette.BorderDefault, 1);
- private static readonly IPen PreDimPen = new Pen(NotaPalette.Wash(NotaPalette.BorderDefault, 0x99), 1);
- private static readonly IPen PostPen = new Pen(NotaPalette.TextAxis, 1);
+ private static readonly IPen PreDimPen = new Pen(NotaPalette.Wash(NotaPalette.TextAxis, 0x66), 1);
private static readonly IPen SelPen = new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x5A), 1);
private static readonly IPen SidePen = new Pen(NotaPalette.Wash(NotaPalette.Teal, 0xE6), NotaGraph.SecondaryWidth, lineJoin: PenLineJoin.Round);
private static readonly IPen RingPen = new Pen(NotaPalette.BgSunken, 2);
@@ -118,6 +121,7 @@ public sealed class Eq8Curve : Control
private readonly float[] _pre = new float[Eq8.kSpec];
private readonly float[] _post = new float[Eq8.kSpec];
+ private readonly float[] _peak = new float[Eq8.kSpec];
private bool _specOk;
public event Action? SelectionChanged;
@@ -155,6 +159,7 @@ public sealed class Eq8Curve : Control
{
Array.Copy(scope, Eq8.PreAt, _pre, 0, Eq8.kSpec);
Array.Copy(scope, Eq8.PostAt, _post, 0, Eq8.kSpec);
+ Array.Copy(scope, Eq8.PeakAt, _peak, 0, Eq8.kSpec);
}
InvalidateVisual();
}
@@ -176,6 +181,8 @@ public sealed class Eq8Curve : Control
private int Chan(int b) => Math.Clamp((int)Math.Round(Pd(Eq8.ChannelBase + b)), 0, 4);
private double ScaleK => _engine.DeviceParamCount(_track, _device) > Eq8.ScaleP ? Math.Clamp(Pd(Eq8.ScaleP), 0, 200) / 100.0 : 1.0;
private int Analyzer => _engine.DeviceParamCount(_track, _device) > Eq8.AnalyzerP ? Math.Clamp((int)Math.Round(Pd(Eq8.AnalyzerP)), 0, 2) : Eq8.AnaPost;
+ private double RangeDb => Eq8.RangeDb(_engine.DeviceParamCount(_track, _device) > Eq8.AnaRangeP ? (int)Math.Round(Pd(Eq8.AnaRangeP)) : 1);
+ private bool PeakOn => _engine.DeviceParamCount(_track, _device) > Eq8.AnaPeakP && Pd(Eq8.AnaPeakP) >= 0.5f;
private double Sr => _engine.SampleRate > 0 ? _engine.SampleRate : 48000;
// ---- geometry: the plot is the whole control ----
@@ -318,7 +325,7 @@ public sealed class Eq8Curve : Control
mi.Click += (_, _) => { Gesture(Eq8.P(b, Eq8.TypeF), () => SetP(b, Eq8.TypeF, tt)); Edited?.Invoke(); InvalidateVisual(); };
fly.Items.Add(mi);
}
- bool extended = _engine.DeviceParamCount(_track, _device) >= Eq8.ParamCount;
+ bool extended = _engine.DeviceParamCount(_track, _device) > Eq8.AnalyzerP;
if (extended)
{
fly.Items.Add(new Separator());
@@ -353,18 +360,6 @@ public sealed class Eq8Curve : Control
=> new(s, CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
mono ? (bold ? NotaFonts.MonoBold : NotaFonts.Mono) : bold ? NotaFonts.SansSemiBold : NotaFonts.Sans, size, ink);
- private StreamGeometry SpecLine(float[] spec, double w, double h)
- {
- var sg = new StreamGeometry();
- using var g = sg.Open();
- for (int i = 0; i < Eq8.kSpec; i++)
- {
- double x = (i + 0.5) / Eq8.kSpec * w;
- double y = Math.Clamp(-spec[i] / 80.0, 0, 1) * h; // 0 dBFS at the top … −80 at the bottom
- if (i == 0) g.BeginFigure(new Point(x, y), false); else g.LineTo(new Point(x, y));
- }
- return sg;
- }
public override void Render(DrawingContext ctx)
{
@@ -380,12 +375,16 @@ public sealed class Eq8Curve : Control
foreach (var db in new[] { -12.0, -6.0, 6.0, 12.0 }) ctx.DrawLine(GridFaint, new Point(0, Y(db)), new Point(w, Y(db)));
ctx.DrawLine(ZeroPen, new Point(0, Y(0)), new Point(w, Y(0)));
- // analyzer: Pre — the input; Post — the output over a dimmer input; Off — neither
+ // analyzer: Pre — the input filled; Post — the output filled under a dim input line; Off —
+ // neither. Its points sit on the graph's own 20 Hz – 20 kHz axis.
int ana = Analyzer;
if (_specOk && ana != Eq8.AnaOff)
{
- ctx.DrawGeometry(null, ana == Eq8.AnaPre ? PrePen : PreDimPen, SpecLine(_pre, w, h));
- if (ana == Eq8.AnaPost) ctx.DrawGeometry(null, PostPen, SpecLine(_post, w, h));
+ double range = RangeDb;
+ var shown = ana == Eq8.AnaPre ? _pre : _post;
+ SpectrumFill.Draw(ctx, shown, w, h, range);
+ if (ana == Eq8.AnaPost) SpectrumFill.Line(ctx, _pre, w, h, range, PreDimPen);
+ if (PeakOn) SpectrumFill.Line(ctx, _peak, w, h, range, SpectrumFill.PeakPen);
}
// band coefficients (effective gain = gain × Scale)
diff --git a/src/managed/Nota.App/Controls/SpectrumFill.cs b/src/managed/Nota.App/Controls/SpectrumFill.cs
new file mode 100644
index 00000000..e59e91ef
--- /dev/null
+++ b/src/managed/Nota.App/Controls/SpectrumFill.cs
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// How the EQ cards draw the engine's spectrum (specs/046, dsp::SpectrumAnalyzer): a curve of
+// log-spaced points from 20 Hz to 20 kHz, in dBFS, drawn as a low-contrast filled area under the
+// EQ curve with a faint edge, or as a plain line (the input under Post, the peak hold). 0 dBFS
+// is the top of the graph and −range dB the bottom; below that the area stays on the bottom
+// edge, so silence draws nothing.
+
+using System;
+using Avalonia;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal static class SpectrumFill
+{
+ private static readonly IBrush Fill = NotaPalette.Wash(NotaPalette.TextAxis, 0x2E);
+ private static readonly IPen Edge = new Pen(NotaPalette.Wash(NotaPalette.TextAxis, 0x8C), 1, lineJoin: PenLineJoin.Round);
+ public static readonly IPen PeakPen = new Pen(NotaPalette.Wash(NotaPalette.TextAxis, 0xB0), 1, lineJoin: PenLineJoin.Round);
+
+ private static double Y(float db, double h, double range) => Math.Clamp(-db / range, 0, 1) * h;
+ private static double X(int i, int n, double w) => i / (double)(n - 1) * w;
+
+ /// <summary>The spectrum as a filled area with a faint top edge.</summary>
+ public static void Draw(DrawingContext ctx, float[] spec, double w, double h, double range, int count = -1)
+ {
+ int n = count > 0 ? Math.Min(count, spec.Length) : spec.Length;
+ if (n < 2) return;
+ var area = new StreamGeometry();
+ using (var g = area.Open())
+ {
+ g.BeginFigure(new Point(0, h), true);
+ for (int i = 0; i < n; i++) g.LineTo(new Point(X(i, n, w), Y(spec[i], h, range)));
+ g.LineTo(new Point(w, h));
+ g.EndFigure(true);
+ }
+ ctx.DrawGeometry(Fill, null, area);
+ ctx.DrawGeometry(null, Edge, Polyline(spec, n, w, h, range));
+ }
+
+ /// <summary>The spectrum as a line alone.</summary>
+ public static void Line(DrawingContext ctx, float[] spec, double w, double h, double range, IPen pen, int count = -1)
+ {
+ int n = count > 0 ? Math.Min(count, spec.Length) : spec.Length;
+ if (n >= 2) ctx.DrawGeometry(null, pen, Polyline(spec, n, w, h, range));
+ }
+
+ // A line through the points, broken wherever it would run along the bottom edge (both ends
+ // below the range): a fading signal leaves no line there, and silence draws nothing.
+ private static StreamGeometry Polyline(float[] spec, int n, double w, double h, double range)
+ {
+ var sg = new StreamGeometry();
+ using var g = sg.Open();
+ bool open = false;
+ for (int i = 0; i < n; i++)
+ {
+ bool below = spec[i] <= -range, prevBelow = i > 0 && spec[i - 1] <= -range;
+ var p = new Point(X(i, n, w), Y(spec[i], h, range));
+ if (open && !(below && prevBelow)) { g.LineTo(p); continue; }
+ if (open) g.EndFigure(false);
+ g.BeginFigure(p, false);
+ open = true;
+ }
+ if (open) g.EndFigure(false);
+ return sg;
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/Eq3DeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/Eq3DeviceBody.cs
index 1604805c..632c389f 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/Eq3DeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/Eq3DeviceBody.cs
@@ -30,7 +30,7 @@ internal sealed class Eq3DeviceBody : IDeviceBody
FreqLo = 6, FreqHi = 7, Slope = 8, Gain = 9, Range = 10;
// Scope layout (Eq3::S_* / kTele / kSpec).
private const int S_SampleRate = 5, S_Cpu = 6, S_Analysed = 7, S_Latency = 8,
- kTele = 16, kSpec = 96, kScope = kTele + kSpec;
+ kTele = 16, kSpec = 256, kScope = kTele + kSpec;
public double Width => 700;
public bool FullBleed => true;
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/EqDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/EqDeviceBody.cs
index 889541bd..c2d0004d 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/EqDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/EqDeviceBody.cs
@@ -45,7 +45,8 @@ internal sealed class EqDeviceBody : IDeviceBody
if (mx[p] <= mn[p]) mx[p] = mn[p] + 1;
}
// Defaults of the appended params, for a device that somehow lacks them.
- float P(int p) => p < pc ? engine.DeviceGetParam(track, di, p) : p == Eq8.ScaleP ? 100f : p == Eq8.AnalyzerP ? Eq8.AnaPost : 0f;
+ float P(int p) => p < pc ? engine.DeviceGetParam(track, di, p)
+ : p == Eq8.ScaleP ? 100f : p == Eq8.AnalyzerP ? Eq8.AnaPost : p == Eq8.AnaRangeP ? 1f : 0f;
float B(int b, int f) => P(Eq8.P(b, f));
void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
@@ -138,10 +139,21 @@ internal sealed class EqDeviceBody : IDeviceBody
Learn(anaSeg, Eq8.AnalyzerP);
ToolTip.SetTip(anaSeg, "Analyzer — Pre: the input spectrum · Post: the output over a dimmer input · Off");
readouts.Add(anaSync);
+ // Range (dB below 0 dBFS at the graph's bottom) and Peak hold, shown while the analyzer is on.
+ bool AnaOn() => Math.Clamp((int)Math.Round(P(Eq8.AnalyzerP)), 0, 2) != Eq8.AnaOff;
+ var rangeSeg = Segments(Eq8.RangeSeg, () => Math.Clamp((int)Math.Round(P(Eq8.AnaRangeP)), 0, 2),
+ i => { SetP(Eq8.AnaRangeP, i); RefreshAll(); curve.InvalidateVisual(); }, out var rangeSync, padX: 4);
+ Learn(rangeSeg, Eq8.AnaRangeP);
+ ToolTip.SetTip(rangeSeg, "Analyzer range — the graph's bottom edge, in dB below 0\u2009dBFS");
+ bool PeakOn() => P(Eq8.AnaPeakP) >= 0.5f;
+ var peakSw = Switch("Peak", PeakOn, () => { SetP(Eq8.AnaPeakP, PeakOn() ? 0 : 1); RefreshAll(); }, out var peakSync);
+ Learn(peakSw, Eq8.AnaPeakP);
+ ToolTip.SetTip(peakSw, "Peak hold — a thin line at each frequency's highest level of the last moments");
+ readouts.Add(() => { rangeSync(); peakSync(); rangeSeg.IsVisible = peakSw.IsVisible = AnaOn() && pc > Eq8.AnaPeakP; });
var anaBar = new StackPanel
{
Orientation = Orientation.Horizontal, Spacing = 5, Margin = new Thickness(5, 3), HorizontalAlignment = HorizontalAlignment.Left,
- VerticalAlignment = VerticalAlignment.Top, Children = { Caps("ANALYZER"), anaSeg },
+ VerticalAlignment = VerticalAlignment.Top, Children = { Caps("ANALYZER"), anaSeg, rangeSeg, peakSw },
};
anaBar.RenderTransform = new ScaleTransform(0.85, 0.85);
anaBar.RenderTransformOrigin = new RelativePoint(0, 0, RelativeUnit.Relative);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
index 3a3ea97a..21d186e1 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs
@@ -267,6 +267,10 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_fx_selftest")]
internal static partial int FxSelfTest();
+ [LibraryImport(Lib, EntryPoint = "nota_spectrum_analyze_offline")]
+ internal static partial int SpectrumAnalyzeOffline(float[] mono, int n, double sampleRate, int hop, double dt,
+ [Out] float[] curves, int maxFrames);
+
[LibraryImport(Lib, EntryPoint = "nota_plugin_open_editor")]
internal static partial NotaResult PluginOpenEditor(IntPtr engine, int trackId, int deviceIndex);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
index 16ee635a..974cc172 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs
@@ -317,6 +317,16 @@ public sealed partial class NotaEngine
/// <summary>Deterministic DSP self-test of the built-in EQ + Compressor. True if sane.</summary>
public static bool FxSelfTest() => NativeMethods.FxSelfTest() != 0;
+ /// <summary>The EQ cards' spectrum analyzer over <paramref name="mono"/> on a fixed clock (a
+ /// frame every <paramref name="hop"/> samples, <paramref name="dt"/> s apart), for tests:
+ /// each frame's 256-point curve in dB.</summary>
+ public static float[][] SpectrumAnalyzeOffline(float[] mono, double sampleRate, int hop, double dt, int maxFrames)
+ {
+ const int pts = 256;
+ var flat = new float[maxFrames * pts];
+ int n = NativeMethods.SpectrumAnalyzeOffline(mono, mono.Length, sampleRate, hop, dt, flat, maxFrames);
+ return Enumerable.Range(0, Math.Max(0, n)).Select(f => flat.AsSpan(f * pts, pts).ToArray()).ToArray();
+ }
/// <summary>Opens a hosted plugin's native GUI. deviceIndex &lt; 0 = the instrument.</summary>
public void OpenPluginEditor(int trackId, int deviceIndex)
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 67fcba3b..01103674 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -1309,7 +1309,7 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
private Eq3Reading Eq3Read(int trackId, int deviceIndex, bool spectrum)
{
- const int tele = 16, spec = 96;
+ const int tele = 16, spec = AnalyzerPoints;
var sc = new float[tele + spec];
int n = E.DeviceScope(trackId, deviceIndex, sc, spectrum ? sc.Length : tele);
float V(int i) => n > i ? sc[i] : 0f;
@@ -1328,13 +1328,7 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
}
var sp = new List<DynEqSpectrumBand>();
bool valid = spectrum && n >= sc.Length && V(7) > 0.5f;
- if (valid)
- for (int k = 0; k < 24; k++)
- {
- double pw = 0;
- for (int b = 4 * k; b < 4 * k + 4; b++) pw += Math.Pow(10, sc[tele + b] / 10);
- sp.Add(new DynEqSpectrumBand(Math.Round(20 * Math.Pow(1000, (k + 0.5) / 24)), R1(Math.Max(-120, 10 * Math.Log10(Math.Max(1e-12, pw))))));
- }
+ if (valid) sp.AddRange(AnalyzerBands(sc, tele));
return new Eq3Reading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
iso ? "Isolator" : "Classic", iso ? -24 : -15, iso ? 6 : 15,
Math.Round(50 * Math.Pow(40, Pm(6))), Math.Round(500 * Math.Pow(36, Pm(7))), Pm(8) >= 0.5f ? 48 : 24, R1((Pm(9) - 0.5) * 48),
@@ -1414,11 +1408,29 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
public sealed record Eq8Band(int Band, bool On, string Type, double FreqHz, double GainDb, double EffectiveGainDb, double Q,
int SlopeDbPerOct, string Channel);
public sealed record Eq8Reading(string Summary, string Live, double ScalePercent, double OutputDb, bool AutoGain, double AutoGainNowDb,
- string Analyzer, double InputPeakDb, double OutputPeakDb, double SampleRate, Eq8Band[] Bands,
+ string Analyzer, int AnalyzerRangeDb, bool AnalyzerPeak, double InputPeakDb, double OutputPeakDb, double SampleRate, Eq8Band[] Bands,
bool SpectrumValid, DynEqSpectrumBand[] InputSpectrum, DynEqSpectrumBand[] OutputSpectrum);
private static readonly string[] Eq8Channels = { "Stereo", "Mid", "Side", "Left", "Right" };
private static readonly string[] Eq8Analyzer = { "Pre", "Post", "Off" };
+ private static readonly int[] Eq8RangeDb = { 60, 90, 120 };
+
+ // The EQ cards' spectrum (dsp::SpectrumAnalyzer): AnalyzerPoints log-spaced points from 20 Hz to
+ // 20 kHz in dBFS, each already a 1/6-octave band. For a reader: 24 bands, each the loudest
+ // point inside it, so a tone reads at its own level.
+ private const int AnalyzerPoints = 256;
+ private static DynEqSpectrumBand[] AnalyzerBands(float[] sc, int at)
+ {
+ var sp = new DynEqSpectrumBand[24];
+ for (int k = 0; k < 24; k++)
+ {
+ int i0 = (int)Math.Ceiling(k / 24.0 * (AnalyzerPoints - 1)), i1 = (int)Math.Floor((k + 1) / 24.0 * (AnalyzerPoints - 1));
+ double db = -120;
+ for (int i = i0; i <= Math.Max(i0, i1) && at + i < sc.Length; i++) db = Math.Max(db, sc[at + i]);
+ sp[k] = new DynEqSpectrumBand(Math.Round(20 * Math.Pow(1000, (k + 0.5) / 24)), Math.Round(db, 1));
+ }
+ return sp;
+ }
private Eq8Band Eq8BandRead(int trackId, int deviceIndex, int b)
{
@@ -1435,8 +1447,8 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
private Eq8Reading Eq8Read(int trackId, int deviceIndex, bool spectrum)
{
if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 0) throw new ArgumentException("not a Nota EQ-8 (kind 0)");
- const int tele = 16, spec = 96;
- var sc = new float[tele + 2 * spec];
+ const int tele = 16, spec = AnalyzerPoints;
+ var sc = new float[tele + 3 * spec];
int n = E.DeviceScope(trackId, deviceIndex, sc, spectrum ? sc.Length : tele);
float V(int i) => n > i ? sc[i] : 0f;
float Db(int i) => n > i ? sc[i] : -120f;
@@ -1446,29 +1458,20 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
var bands = new Eq8Band[8];
for (int b = 0; b < 8; b++) bands[b] = Eq8BandRead(trackId, deviceIndex, b);
bool valid = spectrum && n >= sc.Length && V(5) > 0.5f;
- DynEqSpectrumBand[] Spec(int at)
- {
- var sp = new List<DynEqSpectrumBand>();
- if (valid)
- for (int k = 0; k < 24; k++)
- {
- double pw = 0;
- for (int b = 4 * k; b < 4 * k + 4; b++) pw += Math.Pow(10, sc[at + b] / 10);
- sp.Add(new DynEqSpectrumBand(Math.Round(20 * Math.Pow(1000, (k + 0.5) / 24)), R1(Math.Max(-120, 10 * Math.Log10(Math.Max(1e-12, pw))))));
- }
- return sp.ToArray();
- }
+ DynEqSpectrumBand[] Spec(int at) => valid ? AnalyzerBands(sc, at) : Array.Empty<DynEqSpectrumBand>();
return new Eq8Reading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1), R1(Pm(56)), R1(Pm(57)),
- Pm(58) >= 0.5f, R1(V(2)), Eq8Analyzer[Math.Clamp((int)Math.Round(Pm(59)), 0, 2)], R1(Db(0)), R1(Db(1)), V(3), bands,
+ Pm(58) >= 0.5f, R1(V(2)), Eq8Analyzer[Math.Clamp((int)Math.Round(Pm(59)), 0, 2)],
+ Eq8RangeDb[Math.Clamp((int)Math.Round(pc > 60 ? Pm(60) : 1f), 0, 2)], Pm(61) >= 0.5f, R1(Db(0)), R1(Db(1)), V(3), bands,
valid, Spec(tele), Spec(tele + spec));
}
[McpServerTool(Name = "read_eq8"), Description(
"Read a Nota EQ-8 (built-in effect kind 0 — eight-band parametric EQ): Scale (% applied to every shelf and bell gain), "
- + "output, whether Auto gain is on and the gain it adds now, the analyzer mode the card shows (Pre / Post / Off), in / out "
+ + "output, whether Auto gain is on and the gain it adds now, the analyzer mode the card shows (Pre / Post / Off) with its range "
+ + "(60 / 90 / 120 dB) and peak hold, in / out "
+ "peaks; per band: on, type, frequency, gain, the effective gain after Scale, Q (the resonance on the cuts), slope "
+ "(12 / 24 / 48 dB/oct, cuts only) and channel (Stereo / Mid / Side / Left / Right); plus the input and output spectra "
- + "in 24 log bands (dB). Levels read −120 while silent; they move only while audio runs through the track. "
+ + "in 24 log bands (dB, the loudest 1/6-octave reading in each). Levels read −120 while silent; they move only while audio runs through the track. "
+ "set_eq8_band edits a band, set_eq8 the globals.")]
public Task<Eq8Reading> ReadEq8(int trackId, int deviceIndex) => Read(() => Eq8Read(trackId, deviceIndex, true));
@@ -1516,9 +1519,11 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
"Set the global controls of a Nota EQ-8 (built-in effect kind 0) — only the fields you pass change; each change is recorded "
+ "like a hand edit. scalePercent 0..200 multiplies every shelf and bell gain (100 = as set, 0 = flat). outputDb ±12. "
+ "autoGain adds the opposite of the average level of the shelves and bells (cuts and notches do not count; ±12 dB max). analyzer \"Pre\" | \"Post\" | \"Off\" picks the "
- + "spectrum the card draws. Returns the device as read back (without the spectra).")]
+ + "spectrum the card draws; analyzerRangeDb 60, 90 or 120 sets how far below 0 dBFS its bottom edge is; analyzerPeak "
+ + "turns its peak-hold line on. All three are display only. Returns the device as read back (without the spectra).")]
public Task<Eq8Reading> SetEq8(int trackId, int deviceIndex, [Description("0..200 %")] double? scalePercent = null,
- [Description("−12..+12 dB")] double? outputDb = null, bool? autoGain = null, string? analyzer = null) => Mutate(() =>
+ [Description("−12..+12 dB")] double? outputDb = null, bool? autoGain = null, string? analyzer = null,
+ [Description("60, 90 or 120")] int? analyzerRangeDb = null, bool? analyzerPeak = null) => Mutate(() =>
{
if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 0) throw new ArgumentException("not a Nota EQ-8 (kind 0)");
int pc = E.DeviceParamCount(trackId, deviceIndex);
@@ -1538,6 +1543,13 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
if (i < 0) throw new ArgumentException("analyzer must be Pre, Post or Off");
S(59, i);
}
+ if (analyzerRangeDb is { } rd)
+ {
+ int i = Array.IndexOf(Eq8RangeDb, rd);
+ if (i < 0) throw new ArgumentException("analyzerRangeDb must be 60, 90 or 120");
+ S(60, i);
+ }
+ if (analyzerPeak is { } ap) S(61, ap ? 1 : 0);
return Eq8Read(trackId, deviceIndex, false);
});
diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txt
index 55e39007..de712da6 100644
--- a/src/native/nota.engine/CMakeLists.txt
+++ b/src/native/nota.engine/CMakeLists.txt
@@ -191,6 +191,7 @@ set(NOTA_ENGINE_SOURCES
src/dsp/primitives/Oversampler.cpp # HIIR 2x/4x/8x
src/dsp/primitives/Convolution.cpp # partitioned FFT conv
src/dsp/primitives/TruePeakMeter.cpp # 4x SIMD true-peak
+ src/dsp/primitives/SpectrumAnalyzer.cpp # EQ card spectra (control thread)
src/dsp/primitives/CompensationDelay.cpp # PDC + isIdle
src/dsp/poly/SynthVoice.cpp # voice state
src/dsp/poly/PolyVoiceManager.cpp # voice allocation
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 2961dee5..bc9b825c 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -1768,6 +1768,12 @@ NOTA_API void nota_device_set_sidechain_tap_pre(NotaEngine* engine, int32
NOTA_API int32_t nota_device_sidechain_tap_pre(const NotaEngine* engine, int32_t track_id, int32_t device_index);
/* Deterministic DSP self-test of the built-in EQ + Compressor: 1 = sane. */
NOTA_API int32_t nota_fx_selftest(void);
+/* Runs the EQ cards' spectrum analyzer (specs/046) over `n` mono samples on a fixed clock,
+ for tests: a frame every `hop` samples, `dt` seconds apart, from the first full window on.
+ Writes each frame's 256-point curve (dB) into `curves` (max_frames × 256); returns the
+ frames written. */
+NOTA_API int32_t nota_spectrum_analyze_offline(const float* mono, int32_t n, double sample_rate,
+ int32_t hop, double dt, float* curves, int32_t max_frames);
/* ---- Instrument Rack (nested container instrument) ----------------- */
/* A RackInstrument hosts N parallel chains (each an instrument + insert devices)
diff --git a/src/native/nota.engine/src/abi/nota_engine_device.cpp b/src/native/nota.engine/src/abi/nota_engine_device.cpp
index 741abb60..330c0a98 100644
--- a/src/native/nota.engine/src/abi/nota_engine_device.cpp
+++ b/src/native/nota.engine/src/abi/nota_engine_device.cpp
@@ -9,6 +9,7 @@
#include "nota_engine_internal.h"
#include "dsp/primitives/CompensationDelay.h"
+#include "dsp/primitives/SpectrumAnalyzer.h"
#include "devices/effects/Compressor.h"
#include "devices/effects/Delay.h"
#include "devices/effects/Eq.h"
@@ -339,6 +340,25 @@ void nota_device_set_sidechain_tap_pre(NotaEngine* e, int32_t track_id, int32_t
int32_t nota_device_sidechain_tap_pre(const NotaEngine* e, int32_t track_id, int32_t device_index) {
return e ? CENG(e)->deviceSidechainTapPre(track_id, device_index) : 0;
}
+int32_t nota_spectrum_analyze_offline(const float* mono, int32_t n, double sample_rate, int32_t hop,
+ double dt, float* curves, int32_t max_frames) {
+ using nota::dsp::SpectrumAnalyzer;
+ if (!mono || !curves || n <= 0 || hop <= 0 || max_frames <= 0 || sample_rate <= 0) return 0;
+ SpectrumAnalyzer a;
+ a.prepare(sample_rate);
+ const int fft = a.fftSize();
+ if (n < fft) return 0;
+ uint32_t size = 1;
+ while (size < static_cast<uint32_t>(n)) size <<= 1;
+ std::vector<float> ring(size, 0.0f);
+ std::copy(mono, mono + n, ring.begin());
+ int32_t frames = 0;
+ for (int64_t w = fft; w <= n && frames < max_frames; w += hop, ++frames) {
+ a.analyse(ring.data(), size - 1, static_cast<uint32_t>(w), frames == 0 ? 0.0 : dt, false);
+ std::copy(a.curve(), a.curve() + SpectrumAnalyzer::kPoints, curves + frames * SpectrumAnalyzer::kPoints);
+ }
+ return frames;
+}
int32_t nota_fx_selftest(void) {
constexpr int N = 2048;
constexpr double sr = 44100.0, kPi = 3.14159265358979323846;
diff --git a/src/native/nota.engine/src/devices/effects/Eq.cpp b/src/native/nota.engine/src/devices/effects/Eq.cpp
index bebda3ec..6d33eccd 100644
--- a/src/native/nota.engine/src/devices/effects/Eq.cpp
+++ b/src/native/nota.engine/src/devices/effects/Eq.cpp
@@ -36,6 +36,8 @@ Eq::Eq() {
p_[Output].store(0.0f);
p_[AutoGain].store(0.0f);
p_[Analyzer].store((float)AnaPost);
+ p_[AnaRange].store(1.0f);
+ p_[AnaPeak].store(0.0f);
setSampleRate(44100.0, 0);
}
@@ -53,25 +55,15 @@ void Eq::setSampleRate(double sr, int32_t /*maxBlock*/) {
inPk_ = outPk_ = 0.0f;
quietSamples_ = 0;
idle_ = false;
- fftN_ = sr_ > 50000.0 ? 8192 : 4096;
+ const int fftN = dsp::SpectrumAnalyzer::fftSizeFor(sr_);
size_t ring = 1;
- while (ring < (size_t)fftN_ * 2) ring <<= 1;
+ while (ring < (size_t)fftN * 2) ring <<= 1;
for (auto& r : ring_) r.assign(ring, 0.0f);
ringMask_ = (uint32_t)(ring - 1);
ringW_.store(0, std::memory_order_relaxed);
- fft_.resize((size_t)fftN_);
- win_.assign((size_t)fftN_, 0.0f);
- tBuf_.assign((size_t)fftN_, 0.0f);
- fBuf_.assign((size_t)fftN_ / 2, {});
- for (int i = 0; i < fftN_; ++i) win_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * kPi * i / fftN_));
+ for (auto& a : ana_) a.prepare(sr_);
lastAnaS_ = -1.0;
- lastAnaW_ = 0;
anaValid_ = false;
- for (int k = 0; k < 2; ++k)
- for (int b = 0; b < kSpec; ++b) {
- aSpec_[k][b] = 0.0;
- spec_[k][b] = -120.0f;
- }
}
void Eq::wake() {
@@ -316,8 +308,11 @@ void Eq::process(float* buf, int32_t frames) {
}
(void)moving;
- // Gain stage: smoothed auto/output gains, output peak, post ring.
+ // Gain stage: smoothed auto/output gains, output peak, post ring. The post ring is written
+ // at the same indices as the pre ring, so the two stay aligned and the ring advances one
+ // sample per frame (it used to run on from the pre pass, leaving every other block stale).
float outPk = 0.0f;
+ w = w0;
for (int32_t i = 0; i < frames; ++i) {
autoCur_ += (autoTarget - autoCur_) * glide;
outCur_ += (outTarget - outCur_) * glide;
@@ -366,6 +361,8 @@ const char* Eq::paramName(int32_t i) const {
if (i == Output) return "Output";
if (i == AutoGain) return "Auto Gain";
if (i == Analyzer) return "Analyzer";
+ if (i == AnaRange) return "Analyzer Range";
+ if (i == AnaPeak) return "Analyzer Peak";
static thread_local char buf[16];
if (i >= SlopeBase && i < ChannelBase) {
std::snprintf(buf, sizeof(buf), "%d Slope", i - SlopeBase + 1);
@@ -384,7 +381,7 @@ const char* Eq::paramName(int32_t i) const {
float Eq::paramMin(int32_t i) const {
if (i == Output) return -12.0f;
- if (i < 0 || i >= kBandParams) return 0.0f; // Slope, Channel, Scale, Auto Gain, Analyzer
+ if (i < 0 || i >= kBandParams) return 0.0f; // Slope, Channel, Scale, Auto Gain, Analyzer…
switch (i % kPerBand) {
case On: return 0.0f;
case Type: return 0.0f;
@@ -401,6 +398,8 @@ float Eq::paramMax(int32_t i) const {
if (i == Output) return 12.0f;
if (i == AutoGain) return 1.0f;
if (i == Analyzer) return 2.0f;
+ if (i == AnaRange) return 2.0f;
+ if (i == AnaPeak) return 1.0f;
switch (i % kPerBand) {
case On: return 1.0f;
case Type: return kNumTypes - 1;
@@ -436,7 +435,9 @@ int32_t Eq::scopeRead(float* out, int32_t maxSamples) const {
t[S_Analysed] = analyse() ? 1.0f : 0.0f;
for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
for (int s = 0; s < 2; ++s)
- for (int b = 0; b < kSpec && n < maxSamples; ++b) out[n++] = spec_[s][b];
+ for (int b = 0; b < kSpec && n < maxSamples; ++b) out[n++] = ana_[s].curve()[b];
+ const float* pk = ana_[analyzerMode() == AnaPre ? 0 : 1].peak();
+ for (int b = 0; b < kSpec && n < maxSamples; ++b) out[n++] = pk[b];
return n;
}
for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
@@ -451,11 +452,7 @@ void Eq::deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) {
outPkA_.store(-120.0f, std::memory_order_relaxed);
lastAnaS_ = -1.0;
anaValid_ = false;
- for (int k = 0; k < 2; ++k)
- for (int b = 0; b < kSpec; ++b) {
- aSpec_[k][b] = 0.0;
- spec_[k][b] = -120.0f;
- }
+ for (auto& a : ana_) a.reset();
}
std::string Eq::deviceText(int32_t id) const {
@@ -521,44 +518,26 @@ std::string Eq::deviceText(int32_t id) const {
"shelf and bell gain. 57 Output -12..+12 dB. 58 Auto Gain 0/1 adds the opposite of the average level of "
"the "
"shelves and bells (cuts and notches do not count; max +-12 dB). 59 Analyzer 0 Pre, 1 Post, 2 Off "
- "(display only).";
+ "(display only). 60 Analyzer Range 0 = 60, 1 = 90, 2 = 120 dB (display only). 61 Analyzer Peak "
+ "0/1 peak hold (display only).";
}
return {};
}
bool Eq::analyse() const {
- if (ring_[0].empty() || fftN_ <= 0) return false;
+ const int mode = analyzerMode();
+ if (ring_[0].empty() || mode == AnaOff) return false;
const double now = nowSeconds();
+ if (lastAnaS_ >= 0 && now - lastAnaS_ < 1.0 / 30.0) return anaValid_;
+ const double dt = lastAnaS_ < 0 ? 0.0 : now - lastAnaS_;
const uint32_t w = ringW_.load(std::memory_order_acquire);
- if (lastAnaS_ >= 0 && (now - lastAnaS_ < 1.0 / 30.0 || w == lastAnaW_)) return anaValid_;
- if (w < (uint32_t)fftN_) return anaValid_;
- const int n = fftN_;
- const uint32_t start = w - (uint32_t)n;
- const int half = n / 2;
- const double binHz = sr_ / n;
- const double ref = 0.25 * (double)n * n * 0.25; // Hann: a full-scale sine's bin power
- const bool stale = lastAnaS_ < 0 || now - lastAnaS_ > 1.2;
- const double a = stale ? 1.0 : 1.0 - std::exp(-(now - lastAnaS_) / 0.2);
- double tot = 0.0;
- for (int s = 0; s < 2; ++s) {
- for (int i = 0; i < n; ++i) tBuf_[(size_t)i] = ring_[s][(start + (uint32_t)i) & ringMask_] * win_[(size_t)i];
- fft_.fft(tBuf_.data(), fBuf_.data());
- for (int b = 0; b < kSpec; ++b) {
- const double lo = kSpecLo * std::pow(kSpecHi / kSpecLo, (double)b / kSpec);
- const double hi = kSpecLo * std::pow(kSpecHi / kSpecLo, (double)(b + 1) / kSpec);
- int k0 = std::max(1, (int)std::ceil(lo / binHz)), k1 = std::min(half - 1, (int)std::ceil(hi / binHz) - 1);
- if (k1 < k0) k0 = k1 = std::clamp((int)std::lround(std::sqrt(lo * hi) / binHz), 1, half - 1);
- double e = 0.0;
- for (int k = k0; k <= k1; ++k) e += std::norm(fBuf_[(size_t)k]);
- tot += e;
- aSpec_[s][b] += a * (e - aSpec_[s][b]);
- spec_[s][b] =
- aSpec_[s][b] > ref * 1e-12 ? (float)std::max(-120.0, 10.0 * std::log10(aSpec_[s][b] / ref)) : -120.0f;
- }
- }
+ const bool peak = get(AnaPeak) >= 0.5f;
+ // Pre shows only the input; Post both, with the peak on the output.
+ ana_[0].analyse(ring_[0].data(), ringMask_, w, dt, peak && mode == AnaPre);
+ if (mode == AnaPost) ana_[1].analyse(ring_[1].data(), ringMask_, w, dt, peak);
+ else ana_[1].reset();
lastAnaS_ = now;
- lastAnaW_ = w;
- anaValid_ = tot > ref * 1e-10;
+ anaValid_ = ana_[0].valid() || (mode == AnaPost && ana_[1].valid());
return anaValid_;
}
diff --git a/src/native/nota.engine/src/devices/effects/Eq.h b/src/native/nota.engine/src/devices/effects/Eq.h
index 34f8a75f..260499a8 100644
--- a/src/native/nota.engine/src/devices/effects/Eq.h
+++ b/src/native/nota.engine/src/devices/effects/Eq.h
@@ -5,15 +5,15 @@
// ). Filter math runs through shared dsp::BiquadCascade sections in
// 64-sample blocks (routing branch hoisted out of the loop); pitch/dB mapping
// uses FastMath; silent stretches auto-sleep via the isIdle() contract.
-// Analyzer, params, blob layout and defaults are unchanged (: existing
-// .nota projects and presets load identically).
+// Params, blob layout and defaults are unchanged (: existing .nota projects and presets load
+// identically); the analyzer's Range and Peak (specs/046) are appended after Analyzer, so an
+// older project leaves them at their defaults. The spectra come from dsp::SpectrumAnalyzer.
#pragma once
#include "devices/Device.h"
#include "dsp/primitives/BiquadCascade.h"
-
-#include <signalsmith-linear/fft.h>
+#include "dsp/primitives/SpectrumAnalyzer.h"
#include <algorithm>
#include <atomic>
@@ -46,8 +46,10 @@ class Eq : public Device {
Output,
AutoGain,
Analyzer,
+ AnaRange, // 0 = 60, 1 = 90, 2 = 120 dB below 0 dBFS (display only)
+ AnaPeak, // 0 / 1 peak hold (display only)
kNumParams
- }; // 60
+ }; // 62
enum { AnaPre = 0, AnaPost = 1, AnaOff = 2 };
// Telemetry slots (scopeRead).
@@ -62,10 +64,11 @@ class Eq : public Device {
S_Bands, // kSpec
kTele = 16
};
- static constexpr int kSpec = 96;
- static constexpr double kSpecLo = 20.0, kSpecHi = 20000.0;
- static constexpr int kPreAt = kTele, kPostAt = kTele + kSpec;
- static constexpr int kScope = kTele + 2 * kSpec;
+ // Then the input curve, the output curve and the peak of the shown one (the output on Post,
+ // the input on Pre), kSpec log-spaced points each from 20 Hz to 20 kHz, in dBFS.
+ static constexpr int kSpec = dsp::SpectrumAnalyzer::kPoints;
+ static constexpr int kPreAt = kTele, kPostAt = kTele + kSpec, kPeakAt = kTele + 2 * kSpec;
+ static constexpr int kScope = kTele + 3 * kSpec;
Eq();
void setSampleRate(double sr, int32_t maxBlock) override;
@@ -123,6 +126,7 @@ class Eq : public Device {
const bool* on, const int* ty, const int* ch, const dsp::BiquadCoeffs (*c)[kMaxSec], double sr);
bool analyse() const;
+ int analyzerMode() const { return std::clamp((int)std::lround(get(Analyzer)), 0, 2); }
static double nowSeconds() {
return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
@@ -152,16 +156,9 @@ class Eq : public Device {
std::vector<float> ring_[2];
uint32_t ringMask_ = 0;
std::atomic<uint32_t> ringW_{0};
- int fftN_ = 0;
mutable std::mutex mx_;
- mutable signalsmith::linear::RealFFT<float> fft_;
- std::vector<float> win_;
- mutable std::vector<float> tBuf_;
- mutable std::vector<std::complex<float>> fBuf_;
- mutable double aSpec_[2][kSpec] = {};
- mutable float spec_[2][kSpec] = {};
+ mutable dsp::SpectrumAnalyzer ana_[2];
mutable double lastAnaS_ = -1.0;
- mutable uint32_t lastAnaW_ = 0;
mutable bool anaValid_ = false;
};
diff --git a/src/native/nota.engine/src/devices/effects/Eq3.cpp b/src/native/nota.engine/src/devices/effects/Eq3.cpp
index 3a600bab..0b6c6ee0 100644
--- a/src/native/nota.engine/src/devices/effects/Eq3.cpp
+++ b/src/native/nota.engine/src/devices/effects/Eq3.cpp
@@ -39,24 +39,15 @@ void Eq3::setSampleRate(double sr, int32_t /*maxBlock*/) {
for (auto& v : bandPk_) v = 0.0f;
quietSamples_ = 0;
idle_ = false;
- fftN_ = sr_ > 50000.0 ? 8192 : 4096;
+ const int fftN = dsp::SpectrumAnalyzer::fftSizeFor(sr_);
size_t ring = 1;
- while (ring < (size_t)fftN_ * 2) ring <<= 1;
+ while (ring < (size_t)fftN * 2) ring <<= 1;
ring_.assign(ring, 0.0f);
ringMask_ = (uint32_t)(ring - 1);
ringW_.store(0, std::memory_order_relaxed);
- fft_.resize((size_t)fftN_);
- win_.assign((size_t)fftN_, 0.0f);
- tBuf_.assign((size_t)fftN_, 0.0f);
- fBuf_.assign((size_t)fftN_ / 2, {});
- for (int i = 0; i < fftN_; ++i) win_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * 3.14159265358979 * i / fftN_));
+ ana_.prepare(sr_);
lastAnaS_ = -1.0;
- lastAnaW_ = 0;
anaValid_ = false;
- for (int b = 0; b < kSpec; ++b) {
- aSpec_[b] = 0.0;
- spec_[b] = -120.0f;
- }
}
void Eq3::wake() {
@@ -262,7 +253,7 @@ int32_t Eq3::scopeRead(float* out, int32_t maxSamples) const {
std::lock_guard<std::mutex> lock(mx_);
t[S_Analysed] = analyse() ? 1.0f : 0.0f;
for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
- for (int b = 0; b < kSpec && n < maxSamples; ++b) out[n++] = spec_[b];
+ for (int b = 0; b < kSpec && n < maxSamples; ++b) out[n++] = ana_.curve()[b];
return n;
}
for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
@@ -278,10 +269,7 @@ void Eq3::deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) {
for (auto& a : lvlA_) a.store(-120.0f, std::memory_order_relaxed);
lastAnaS_ = -1.0;
anaValid_ = false;
- for (int b = 0; b < kSpec; ++b) {
- aSpec_[b] = 0.0;
- spec_[b] = -120.0f;
- }
+ ana_.reset();
}
std::string Eq3::deviceText(int32_t id) const {
@@ -342,35 +330,13 @@ std::string Eq3::deviceText(int32_t id) const {
}
bool Eq3::analyse() const {
- if (ring_.empty() || fftN_ <= 0) return false;
+ if (ring_.empty()) return false;
const double now = nowSeconds();
- const uint32_t w = ringW_.load(std::memory_order_acquire);
- if (lastAnaS_ >= 0 && (now - lastAnaS_ < 1.0 / 30.0 || w == lastAnaW_)) return anaValid_;
- if (w < (uint32_t)fftN_) return anaValid_;
- const int n = fftN_;
- const uint32_t start = w - (uint32_t)n;
- for (int i = 0; i < n; ++i) tBuf_[(size_t)i] = ring_[(start + (uint32_t)i) & ringMask_] * win_[(size_t)i];
- fft_.fft(tBuf_.data(), fBuf_.data());
- const int half = n / 2;
- const double binHz = sr_ / n;
- const double ref = 0.25 * (double)n * n * 0.25; // Hann: a full-scale sine's bin power
- const bool stale = lastAnaS_ < 0 || now - lastAnaS_ > 1.2;
- const double a = stale ? 1.0 : 1.0 - std::exp(-(now - lastAnaS_) / 0.2);
- double tot = 0.0;
- for (int b = 0; b < kSpec; ++b) {
- const double lo = kSpecLo * std::pow(kSpecHi / kSpecLo, (double)b / kSpec);
- const double hi = kSpecLo * std::pow(kSpecHi / kSpecLo, (double)(b + 1) / kSpec);
- int k0 = std::max(1, (int)std::ceil(lo / binHz)), k1 = std::min(half - 1, (int)std::ceil(hi / binHz) - 1);
- if (k1 < k0) k0 = k1 = std::clamp((int)std::lround(std::sqrt(lo * hi) / binHz), 1, half - 1);
- double s = 0.0;
- for (int k = k0; k <= k1; ++k) s += std::norm(fBuf_[(size_t)k]);
- tot += s;
- aSpec_[b] += a * (s - aSpec_[b]);
- spec_[b] = aSpec_[b] > ref * 1e-12 ? (float)std::max(-120.0, 10.0 * std::log10(aSpec_[b] / ref)) : -120.0f;
- }
+ if (lastAnaS_ >= 0 && now - lastAnaS_ < 1.0 / 30.0) return anaValid_;
+ const double dt = lastAnaS_ < 0 ? 0.0 : now - lastAnaS_;
+ ana_.analyse(ring_.data(), ringMask_, ringW_.load(std::memory_order_acquire), dt, false);
lastAnaS_ = now;
- lastAnaW_ = w;
- anaValid_ = tot > ref * 1e-10;
+ anaValid_ = ana_.valid();
return anaValid_;
}
diff --git a/src/native/nota.engine/src/devices/effects/Eq3.h b/src/native/nota.engine/src/devices/effects/Eq3.h
index 9ac98ff0..872efcdb 100644
--- a/src/native/nota.engine/src/devices/effects/Eq3.h
+++ b/src/native/nota.engine/src/devices/effects/Eq3.h
@@ -9,8 +9,8 @@
#pragma once
#include "devices/Device.h"
+#include "dsp/primitives/SpectrumAnalyzer.h"
-#include <signalsmith-linear/fft.h>
#include <algorithm>
#include <atomic>
@@ -58,8 +58,7 @@ class Eq3 : public Device {
S_Bands = 14, // kSpec
kTele = 16
};
- static constexpr int kSpec = 96;
- static constexpr double kSpecLo = 20.0, kSpecHi = 20000.0;
+ static constexpr int kSpec = dsp::SpectrumAnalyzer::kPoints; // log points 20 Hz..20 kHz, dBFS
static constexpr int kScope = kTele + kSpec;
Eq3();
@@ -176,16 +175,9 @@ class Eq3 : public Device {
std::vector<float> ring_;
uint32_t ringMask_ = 0;
std::atomic<uint32_t> ringW_{0};
- int fftN_ = 0;
mutable std::mutex mx_;
- mutable signalsmith::linear::RealFFT<float> fft_;
- std::vector<float> win_;
- mutable std::vector<float> tBuf_;
- mutable std::vector<std::complex<float>> fBuf_;
- mutable double aSpec_[kSpec] = {};
- mutable float spec_[kSpec] = {};
+ mutable dsp::SpectrumAnalyzer ana_;
mutable double lastAnaS_ = -1.0;
- mutable uint32_t lastAnaW_ = 0;
mutable bool anaValid_ = false;
};
diff --git a/src/native/nota.engine/src/dsp/primitives/SpectrumAnalyzer.cpp b/src/native/nota.engine/src/dsp/primitives/SpectrumAnalyzer.cpp
new file mode 100644
index 00000000..efeeca11
--- /dev/null
+++ b/src/native/nota.engine/src/dsp/primitives/SpectrumAnalyzer.cpp
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+
+#include "dsp/primitives/SpectrumAnalyzer.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace nota::dsp {
+namespace {
+
+constexpr double kPi = 3.14159265358979323846;
+
+} // namespace
+
+void SpectrumAnalyzer::prepare(double sampleRate) {
+ sr_ = sampleRate > 0 ? sampleRate : 44100.0;
+ n_ = fftSizeFor(sr_);
+ fft_.resize((size_t)n_);
+ win_.assign((size_t)n_, 0.0f);
+ time_.assign((size_t)n_, 0.0f);
+ freq_.assign((size_t)n_ / 2, {});
+ pow_.assign((size_t)n_ / 2, 0.0);
+ double sum = 0.0;
+ for (int i = 0; i < n_; ++i) {
+ win_[(size_t)i] = (float)(0.5 - 0.5 * std::cos(2.0 * kPi * i / n_));
+ sum += win_[(size_t)i];
+ }
+ // A full-scale sine: its peak bin's power is (Σw / 2)², and the Hann main lobe (the bins
+ // either side at half the amplitude) holds 1.5 times that.
+ refBin_ = (sum * 0.5) * (sum * 0.5);
+ ref_ = refBin_ * 1.5;
+
+ const int bins = n_ / 2;
+ const double binHz = sr_ / n_;
+ const double edge = std::pow(2.0, kHalfOct);
+ pts_.assign(kPoints, {});
+ weights_.clear();
+ for (int i = 0; i < kPoints; ++i) {
+ const double f = kLo * std::pow(kHi / kLo, i / (double)(kPoints - 1));
+ Point& p = pts_[(size_t)i];
+ p.x = std::clamp(f / binHz, 1.0, bins - 2.0);
+ const int k0 = std::clamp((int)std::ceil(f / edge / binHz), 1, bins - 1);
+ const int k1 = std::clamp((int)std::floor(f * edge / binHz), 1, bins - 1);
+ p.k0 = k0;
+ p.first = (int)weights_.size();
+ // Fewer than three bins under the window can't resolve a lobe: interpolate instead.
+ if (k1 - k0 < 2) continue;
+ for (int k = k0; k <= k1; ++k) {
+ const double d = std::log2(k * binHz / f) / kHalfOct; // −1 … 1 across the window
+ weights_.push_back((float)(0.5 + 0.5 * std::cos(kPi * std::clamp(d, -1.0, 1.0))));
+ }
+ p.count = k1 - k0 + 1;
+ }
+ reset();
+}
+
+void SpectrumAnalyzer::reset() {
+ std::fill(curve_.begin(), curve_.end(), kFloorDb);
+ std::fill(peak_.begin(), peak_.end(), kFloorDb);
+ std::fill(peakAge_.begin(), peakAge_.end(), 0.0f);
+ primed_ = false;
+ valid_ = false;
+ stalled_ = 0.0;
+ gap_ = 0.0;
+}
+
+void SpectrumAnalyzer::analyse(const float* ring, uint32_t mask, uint32_t w, double dt, bool peakHold) {
+ if (!ring || n_ <= 0 || mask + 1 < (uint32_t)n_) return;
+ const bool snap = !primed_ || dt <= 0.0 || dt > 1.2;
+ const double elapsed = std::max(0.0, dt); // a long gap still counts as a pause
+ dt = snap ? 0.0 : dt;
+ // No new samples for longer than a callback: the input has stopped, so let the curve fall.
+ // A shorter pause is a read between two callbacks: the same window measures again.
+ if (primed_ && w == lastW_) stalled_ += elapsed;
+ else {
+ // The callback period, held at its recent longest: a burst of quick callbacks (a late
+ // one catching up) mustn't shrink it so the next ordinary wait reads as a stop.
+ if (primed_) gap_ = std::min(std::max(stalled_ + elapsed, 0.9 * gap_), kStalledMaxS);
+ stalled_ = 0.0;
+ }
+ const bool silent = stalled_ > std::clamp(1.5 * gap_, kStalledMinS, kStalledMaxS);
+ if (!silent && w >= (uint32_t)n_) {
+ const uint32_t start = w - (uint32_t)n_;
+ for (int i = 0; i < n_; ++i) time_[(size_t)i] = ring[(start + (uint32_t)i) & mask] * win_[(size_t)i];
+ fft_.fft(time_.data(), freq_.data());
+ for (size_t k = 0; k < pow_.size(); ++k) pow_[k] = std::norm(freq_[k]);
+ } else {
+ std::fill(pow_.begin(), pow_.end(), 0.0);
+ }
+ lastW_ = w;
+ primed_ = true;
+
+ const double rise = snap ? 1.0 : 1.0 - std::exp(-dt / kRiseS);
+ const double fall = kFallDbPerS * dt, peakFall = kPeakFallDbPerS * dt;
+ bool any = false;
+ for (int i = 0; i < kPoints; ++i) {
+ const Point& p = pts_[(size_t)i];
+ double e = 0.0, ref = ref_;
+ if (p.count > 0) {
+ const float* wt = weights_.data() + p.first;
+ for (int j = 0; j < p.count; ++j) e += wt[j] * pow_[(size_t)(p.k0 + j)];
+ } else {
+ const int ka = (int)p.x;
+ const double fr = p.x - ka;
+ e = pow_[(size_t)ka] * (1.0 - fr) + pow_[(size_t)ka + 1] * fr;
+ ref = refBin_;
+ }
+ const double t = e > ref * 1e-15 ? std::max((double)kFloorDb, 10.0 * std::log10(e / ref)) : kFloorDb;
+ float& c = curve_[(size_t)i];
+ if (snap) c = (float)t;
+ else if (t >= c) c = (float)(c + rise * (t - c));
+ else c = (float)std::max(t, c - fall);
+ if (c > kFloorDb + 1.0f) any = true;
+
+ float& pk = peak_[(size_t)i];
+ float& age = peakAge_[(size_t)i];
+ if (!peakHold || snap || c >= pk) {
+ pk = c;
+ age = 0.0f;
+ } else {
+ age += (float)dt;
+ if (age > kPeakHoldS) pk = (float)std::max((double)c, pk - peakFall);
+ }
+ if (peakHold && pk > kFloorDb + 1.0f) any = true; // a held peak still shows after the curve has gone
+ }
+ if (peakHold) { // keep the held line a line: limit its slope between neighbouring points
+ for (int i = 1; i < kPoints; ++i) peak_[(size_t)i] = std::max(peak_[(size_t)i], peak_[(size_t)i - 1] - kPeakSlopeDb);
+ for (int i = kPoints - 2; i >= 0; --i) peak_[(size_t)i] = std::max(peak_[(size_t)i], peak_[(size_t)i + 1] - kPeakSlopeDb);
+ }
+ valid_ = any;
+}
+
+} // namespace nota::dsp
diff --git a/src/native/nota.engine/src/dsp/primitives/SpectrumAnalyzer.h b/src/native/nota.engine/src/dsp/primitives/SpectrumAnalyzer.h
new file mode 100644
index 00000000..5a1f53c0
--- /dev/null
+++ b/src/native/nota.engine/src/dsp/primitives/SpectrumAnalyzer.h
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The spectrum the EQ cards draw (specs/046). Reads the latest samples of a device's mono ring,
+// runs a Hann-windowed FFT (4096 points, 8192 above 50 kHz) and maps it onto kPoints log-spaced
+// points from 20 Hz to 20 kHz. Each point reads the energy around it through a raised-cosine
+// window ±1/6 octave wide (1/6 octave effective), so a sine reads its own level at its own point
+// and pink noise reads flat; where the window holds no bin the point interpolates the two
+// nearest bins. Ballistics: a fast rise, a fixed 300 ms-per-20 dB
+// fall, and an optional peak that holds 1.5 s. A ring that has stopped advancing counts as
+// silence, so the curve falls away instead of freezing.
+//
+// Not real-time code: the owner calls analyse() from its telemetry read, under its own lock,
+// never from the audio thread.
+
+#pragma once
+
+#include <signalsmith-linear/fft.h>
+
+#include <complex>
+#include <cstdint>
+#include <vector>
+
+namespace nota::dsp {
+
+class SpectrumAnalyzer {
+ public:
+ static constexpr int kPoints = 256;
+ static constexpr double kLo = 20.0, kHi = 20000.0;
+ static constexpr float kFloorDb = -150.0f;
+ static constexpr double kHalfOct = 1.0 / 6.0; // half-width of a point's window, octaves
+ static constexpr double kRiseS = 0.020; // rise time constant
+ static constexpr double kFallDbPerS = 20.0 / 0.3;
+ static constexpr double kPeakHoldS = 1.5;
+ static constexpr double kPeakFallDbPerS = kFallDbPerS * 0.5;
+ // A pause past 1.5 callback periods (within these bounds) is the input stopping, not a
+ // read that fell between two callbacks (2048 frames at 44.1 kHz arrive 46 ms apart).
+ static constexpr double kStalledMinS = 0.03, kStalledMaxS = 0.25;
+ // The held peak may not fall away from a neighbouring point faster than this (dB per point,
+ // ~51 dB/octave): each point's hold runs out on its own, and without it the line breaks
+ // into notches and spikes on drums.
+ static constexpr float kPeakSlopeDb = 2.0f;
+
+ /// FFT size for a sample rate (the ring must hold at least this many samples).
+ static int fftSizeFor(double sampleRate) { return sampleRate > 50000.0 ? 8192 : 4096; }
+
+ void prepare(double sampleRate);
+ void reset();
+
+ /// Analyses the fftSize() samples that end at write index `w` of a power-of-two ring
+ /// (`mask` = size − 1), `dt` seconds after the previous call (≤ 0: the first, which snaps).
+ void analyse(const float* ring, uint32_t mask, uint32_t w, double dt, bool peakHold);
+
+ const float* curve() const { return curve_.data(); }
+ const float* peak() const { return peak_.data(); }
+ int fftSize() const { return n_; }
+ /// True once something above the floor has been seen since the last reset or silence.
+ bool valid() const { return valid_; }
+
+ private:
+ struct Point {
+ int first = 0, count = 0; // weights_[first .. first + count) apply to bins k0 ..
+ int k0 = 1;
+ double x = 1.0; // fractional bin of the point's centre (count 0: interpolate)
+ };
+
+ double sr_ = 44100.0;
+ int n_ = 0;
+ signalsmith::linear::RealFFT<float> fft_;
+ std::vector<float> win_, time_;
+ std::vector<std::complex<float>> freq_;
+ std::vector<double> pow_;
+ std::vector<Point> pts_;
+ std::vector<float> weights_;
+ std::vector<float> curve_ = std::vector<float>(kPoints, kFloorDb);
+ std::vector<float> peak_ = std::vector<float>(kPoints, kFloorDb);
+ std::vector<float> peakAge_ = std::vector<float>(kPoints, 0.0f);
+ double ref_ = 1.0, refBin_ = 1.0;
+ uint32_t lastW_ = 0;
+ double stalled_ = 0.0; // seconds the write index hasn't moved
+ double gap_ = 0.0; // seconds between its moves, held at the recent longest (≈ the callback period)
+ bool primed_ = false, valid_ = false;
+};
+
+} // namespace nota::dsp
diff --git a/tests/Nota.SmokeTest/EqAnalyzerTests.cs b/tests/Nota.SmokeTest/EqAnalyzerTests.cs
new file mode 100644
index 00000000..3bfbe330
--- /dev/null
+++ b/tests/Nota.SmokeTest/EqAnalyzerTests.cs
@@ -0,0 +1,451 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The EQ cards' spectrum analyzer (specs/046, #265): sines read at their level and frequency,
+// pink noise reads flat, a steady signal holds still, the curve rises at once and falls 20 dB in
+// about 300 ms, the peak holds, silence falls away, Off analyses nothing, and the appended Range
+// and Peak params default on an older project without touching the sound. The analysis runs on
+// the reading thread at up to 30 updates a second against the wall clock, so each read waits a
+// frame. Also runnable alone: `--eq-analyzer`.
+
+using System.Diagnostics;
+using Nota.Application;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class EqAnalyzerTests
+{
+ private const int Eq8Kind = 0, Eq3Kind = 16;
+ private const int Points = 256, Tele = 16, PreAt = Tele, PostAt = Tele + Points, PeakAt = Tele + 2 * Points;
+ private const int Scope8 = Tele + 3 * Points, Scope3 = Tele + Points;
+ private const int Analyzer = 59, AnaRange = 60, AnaPeak = 61, Analysed = 5;
+ private const int Rate = 44100;
+ private const double SineDb = -12.0;
+
+ private static double PointHz(int i) => 20.0 * Math.Pow(1000.0, i / (double)(Points - 1));
+
+ public static IEnumerable<(bool, string)> Run()
+ {
+ var tmp = new List<string>();
+ try
+ {
+ foreach (var r in Sines(tmp)) yield return r;
+ foreach (var r in Pink(tmp)) yield return r;
+ foreach (var r in Ballistics(tmp)) yield return r;
+ foreach (var r in ParamsAndSound(tmp)) yield return r;
+ }
+ finally { foreach (var f in tmp) try { File.Delete(f); } catch (IOException) { } }
+ }
+
+ // ---- signals ----------------------------------------------------------------------------
+
+ private static string Sine(List<string> tmp, double hz, double seconds = 2.0)
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"nota-eqa-{hz:0}-{Guid.NewGuid():N}.wav");
+ int n = (int)(Rate * seconds);
+ double a = Math.Pow(10, SineDb / 20);
+ var x = new float[n * 2];
+ for (int i = 0; i < n; i++) x[2 * i] = x[2 * i + 1] = (float)(a * Math.Sin(2 * Math.PI * hz * i / Rate));
+ using (var w = new Nota.Infrastructure.WavWriter(path, Rate, 2, WavBitDepth.Float32)) w.WriteFrames(x, n);
+ tmp.Add(path);
+ return path;
+ }
+
+ // Paul Kellet's pink filter over seeded white noise, about −20 dBFS RMS.
+ private static string PinkNoise(List<string> tmp, double seconds = 4.0)
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"nota-eqa-pink-{Guid.NewGuid():N}.wav");
+ int n = (int)(Rate * seconds);
+ var mono = PinkSamples(n);
+ var x = new float[n * 2];
+ for (int i = 0; i < n; i++) x[2 * i] = x[2 * i + 1] = mono[i];
+ using (var w = new Nota.Infrastructure.WavWriter(path, Rate, 2, WavBitDepth.Float32)) w.WriteFrames(x, n);
+ tmp.Add(path);
+ return path;
+ }
+
+ // Seeded pink noise (Paul Kellet's filter), mono.
+ private static float[] PinkSamples(int n)
+ {
+ var rnd = new Random(46);
+ double b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0;
+ var x = new float[n];
+ for (int i = 0; i < n; i++)
+ {
+ double wv = rnd.NextDouble() * 2 - 1;
+ b0 = 0.99886 * b0 + wv * 0.0555179; b1 = 0.99332 * b1 + wv * 0.0750759;
+ b2 = 0.96900 * b2 + wv * 0.1538520; b3 = 0.86650 * b3 + wv * 0.3104856;
+ b4 = 0.55000 * b4 + wv * 0.5329522; b5 = -0.7616 * b5 - wv * 0.0168980;
+ double p = b0 + b1 + b2 + b3 + b4 + b5 + b6 + wv * 0.5362;
+ b6 = wv * 0.115926;
+ x[i] = (float)(p * 0.025);
+ }
+ return x;
+ }
+
+ // A seeded drum loop at 120 BPM: a kick on the beat (a falling 55 Hz sine), a snare on 2 and
+ // 4 (noise and a 180 Hz body) and a closed hat on the eighths (bright noise), like the
+ // Drum Rack loop the Peak line was first seen spiking on.
+ private static string DrumLoop(List<string> tmp, double seconds = 5.0)
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"nota-eqa-drums-{Guid.NewGuid():N}.wav");
+ int n = (int)(Rate * seconds), eighth = Rate / 4;
+ var rnd = new Random(265);
+ var x = new float[n * 2];
+ double hp = 0, prev = 0;
+ for (int i = 0; i < n; i++)
+ {
+ int step = i / eighth, at = i % eighth;
+ double ts = at / (double)Rate, v = 0;
+ double noise = rnd.NextDouble() * 2 - 1;
+ hp = 0.85 * (hp + noise - prev); prev = noise; // one-pole high-pass: the hat's brightness
+ if (step % 2 == 0) v += 0.7 * Math.Sin(2 * Math.PI * (55 * ts + 40 * (1 - Math.Exp(-ts * 30)) / 30)) * Math.Exp(-ts * 9);
+ if (step % 4 == 2) v += (0.35 * noise + 0.3 * Math.Sin(2 * Math.PI * 180 * ts)) * Math.Exp(-ts * 22);
+ v += 0.25 * hp * Math.Exp(-ts * 70);
+ x[2 * i] = x[2 * i + 1] = (float)v;
+ }
+ using (var w = new Nota.Infrastructure.WavWriter(path, Rate, 2, WavBitDepth.Float32)) w.WriteFrames(x, n);
+ tmp.Add(path);
+ return path;
+ }
+
+ private sealed class Rig : IDisposable
+ {
+ public readonly NotaEngine E = new();
+ public readonly int T, D;
+ private readonly float[] _sc;
+ private bool _playing;
+ public Rig(string wav, int kind = Eq8Kind)
+ {
+ E.SetBpm(120);
+ T = E.AddAudioTrack();
+ E.AddAudioClip(T, wav, 0.0);
+ D = E.AddBuiltinDevice(T, kind);
+ _sc = new float[kind == Eq8Kind ? Scope8 : Scope3];
+ }
+ /// <summary>Plays the next <paramref name="frames"/> of the clip through the device, carrying
+ /// on from the last call (no seek, so no start ramp in the analysed audio).</summary>
+ public void Feed(int frames)
+ {
+ var b = new float[frames * 2];
+ if (!_playing) { E.Seek(0); E.Play(); _playing = true; }
+ E.RenderOffline(b, frames);
+ }
+ /// <summary>Waits a display frame, then reads the telemetry (which runs the analysis).</summary>
+ public float[] Read(int waitMs = 35)
+ {
+ Thread.Sleep(waitMs);
+ E.DeviceScope(T, D, _sc, _sc.Length);
+ return _sc;
+ }
+ public void Reset()
+ {
+ E.DeviceAction(T, D, 0, 0, 0);
+ if (_playing) E.StopTransport();
+ _playing = false;
+ }
+ public void Dispose() => E.Dispose();
+ }
+
+ private static int Argmax(float[] s, int at)
+ {
+ int best = 0;
+ for (int i = 1; i < Points; i++) if (s[at + i] > s[at + best]) best = i;
+ return best;
+ }
+
+ // ---- tests ------------------------------------------------------------------------------
+
+ private static IEnumerable<(bool, string)> Sines(List<string> tmp)
+ {
+ var bad = new List<string>();
+ var lines = new List<string>();
+ foreach (double hz in new[] { 50.0, 100.0, 250.0, 1000.0, 4000.0, 10000.0, 15000.0 })
+ {
+ // Within one display point, or one FFT bin where a bin is wider (the low end).
+ double tol = Math.Max(1.5 / 25.5, Math.Log(1 + (Rate / 4096.0) / hz, 2));
+ using var r = new Rig(Sine(tmp, hz));
+ r.Reset();
+ r.Feed(8192);
+ var s = r.Read();
+ int pk = Argmax(s, PostAt);
+ double at = PointHz(pk), lvl = s[PostAt + pk];
+ lines.Add($"{hz:0} Hz → {at:0} Hz {lvl:F1} dB");
+ if (Math.Abs(Math.Log(at / hz, 2)) > tol || Math.Abs(lvl - SineDb) > 3) bad.Add($"{hz:0} Hz");
+ }
+ yield return (bad.Count == 0, $"a −12 dBFS sine reads at its frequency and level, 50 Hz–15 kHz ({string.Join(", ", lines)})");
+
+ // Steady sine: the peak point holds still frame to frame.
+ using (var r = new Rig(Sine(tmp, 1000)))
+ {
+ r.Reset();
+ r.Feed(8192);
+ var prev = (float[])r.Read().Clone();
+ int pk = Argmax(prev, PostAt);
+ double worst = 0;
+ for (int f = 0; f < 8; f++)
+ {
+ r.Feed(1470); // one 30 Hz frame of audio
+ var s = r.Read();
+ worst = Math.Max(worst, Math.Abs(s[PostAt + pk] - prev[PostAt + pk]));
+ Array.Copy(s, prev, s.Length);
+ }
+ yield return (worst < 0.5, $"a steady sine holds still (largest frame-to-frame change {worst:F2} dB at its peak)");
+ // A flat EQ: the output reads as the input. Before the fix the post ring ran on from the
+ // pre pass, so half of each ring was stale and the two read apart.
+ double gap = Math.Abs(prev[PostAt + pk] - prev[PreAt + pk]);
+ yield return (gap < 0.1, $"through a flat EQ-8 the output spectrum matches the input ({gap:F3} dB apart)");
+ }
+
+ // EQ-3 reads the same as EQ-8 on the same signal.
+ using (var a = new Rig(Sine(tmp, 1000)))
+ using (var b = new Rig(Sine(tmp, 1000), Eq3Kind))
+ {
+ a.Reset(); b.Reset();
+ a.Feed(8192); b.Feed(8192);
+ var s8 = a.Read(); var s3 = b.Read(0);
+ int p8 = Argmax(s8, PostAt), p3 = Argmax(s3, Tele);
+ double d = Math.Abs(s8[PostAt + p8] - s3[Tele + p3]);
+ yield return (p8 == p3 && d < 1, $"EQ-3 uses the same analyzer: the 1 kHz sine at point {p3} vs {p8}, {d:F2} dB apart");
+ }
+ }
+
+ private static IEnumerable<(bool, string)> Pink(List<string> tmp)
+ {
+ // Flat: through the device, averaged over frames (timing doesn't matter for a mean).
+ using (var r = new Rig(PinkNoise(tmp)))
+ {
+ r.Reset();
+ r.Feed(8192);
+ var sum = new double[Points];
+ int frames = 0;
+ for (; frames < 30; frames++)
+ {
+ r.Feed(1470);
+ var s = r.Read();
+ for (int i = 0; i < Points; i++) sum[i] += s[PostAt + i];
+ }
+ var avg = Band().Select(i => sum[i] / frames).ToList();
+ double mid = avg.OrderBy(v => v).ElementAt(avg.Count / 2);
+ double lo = avg.Min() - mid, hi = avg.Max() - mid;
+ yield return (lo > -3 && hi < 3, $"pink noise reads flat from 100 Hz to 15 kHz ({lo:F1} / +{hi:F1} dB around {mid:F1} dB)");
+ }
+ // Steady (SC-003): the ballistics run on the display clock, so measure them on a fixed one,
+ // 1470 new samples every 1/30 s, rather than on a CI runner's scheduling.
+ {
+ var curves = NotaEngine.SpectrumAnalyzeOffline(PinkSamples(Rate * 3), Rate, 1470, 1470.0 / Rate, 80);
+ const int Settle = 10; // the curve rises from the floor first
+ double change = 0; int pairs = 0;
+ for (int f = Settle + 1; f < curves.Length; f++, pairs++)
+ foreach (int i in Band()) change += Math.Abs(curves[f][i] - curves[f - 1][i]);
+ double meanChange = change / (Math.Max(1, pairs) * Band().Count);
+ yield return (pairs >= 30 && meanChange < 1.5,
+ $"pink noise holds steady (mean frame-to-frame change {meanChange:F2} dB over {pairs} display frames)");
+ }
+ }
+
+ private static List<int> Band() => Enumerable.Range(0, Points).Where(i => PointHz(i) >= 100 && PointHz(i) <= 15000).ToList();
+
+ private static IEnumerable<(bool, string)> Ballistics(List<string> tmp)
+ {
+ // Rise at once, then fall 20 dB in ~300 ms once the input stops.
+ using (var r = new Rig(Sine(tmp, 1000)))
+ {
+ r.Reset();
+ r.Feed(8192);
+ var s = r.Read();
+ int pk = Argmax(s, PostAt);
+ float top = s[PostAt + pk];
+ var sw = Stopwatch.StartNew();
+ double dropAt = -1;
+ while (sw.ElapsedMilliseconds < 1500)
+ {
+ s = r.Read(10);
+ if (top - s[PostAt + pk] >= 20) { dropAt = sw.Elapsed.TotalMilliseconds; break; }
+ }
+ yield return (dropAt >= 230 && dropAt <= 420, $"after the input stops, the curve falls 20 dB in {dropAt:0} ms (target 300)");
+ Thread.Sleep(2600);
+ s = r.Read();
+ yield return (s[Analysed] < 0.5f && s[PostAt + pk] < -120, $"silence falls away instead of freezing (analysed {s[Analysed]}, {s[PostAt + pk]:F0} dB)");
+ }
+
+ // A large buffer (2048 frames ≈ 46 ms) with the display reading every ~10 ms: most reads
+ // fall between two callbacks, which is not silence, so a steady tone doesn't dip. The tone
+ // outlasts the loop: at most 8 s of 46 ms feeds (≈ 8.2 s of audio).
+ using (var r = new Rig(Sine(tmp, 1000, seconds: 10.0)))
+ {
+ r.Reset();
+ r.Feed(8192);
+ var s = r.Read();
+ int pk = Argmax(s, PostAt);
+ float lo = float.MaxValue, hi = float.MinValue;
+ var sw = Stopwatch.StartNew();
+ long nextFeed = 0, lastFeed = 0, feedGap = 0;
+ int counted = 0;
+ // Only reads while the "callbacks" keep their period count: a stalled CI runner that
+ // misses a feed by a whole period really has stopped the input for that long.
+ while (sw.ElapsedMilliseconds < 8000 && counted < 60)
+ {
+ long now = sw.ElapsedMilliseconds;
+ if (now >= nextFeed) { r.Feed(2048); feedGap = now - lastFeed; lastFeed = now; nextFeed += 46; }
+ s = r.Read(10);
+ if (feedGap > 70 || sw.ElapsedMilliseconds - lastFeed > 70) continue;
+ lo = Math.Min(lo, s[PostAt + pk]);
+ hi = Math.Max(hi, s[PostAt + pk]);
+ counted++;
+ }
+ yield return (counted >= 20 && hi - lo < 1.0f,
+ $"a steady tone in 2048-frame callbacks holds still between them ({hi - lo:F2} dB swing over {counted} reads)");
+ }
+
+ // Peak hold: the peak stays ~1.5 s after the curve falls, then falls too.
+ using (var r = new Rig(Sine(tmp, 1000)))
+ {
+ r.E.DeviceSetParam(r.T, r.D, AnaPeak, 1);
+ r.Reset();
+ r.Feed(8192);
+ var s = r.Read();
+ int pk = Argmax(s, PostAt);
+ float top = s[PostAt + pk];
+ // Read at display cadence: the ballistics run on wall-clock time and a read after a
+ // gap over 1.2 s snaps everything to the floor, which a slow runner's long sleep can hit.
+ var sw = Stopwatch.StartNew();
+ float curve1 = float.NaN, peak1 = float.NaN, peak2 = float.NaN;
+ while (sw.ElapsedMilliseconds < 2500)
+ {
+ Thread.Sleep(33);
+ s = r.Read();
+ if (float.IsNaN(curve1) && sw.ElapsedMilliseconds >= 900) { curve1 = s[PostAt + pk]; peak1 = s[PeakAt + pk]; }
+ peak2 = s[PeakAt + pk];
+ }
+ yield return (curve1 < top - 20 && Math.Abs(peak1 - top) < 0.5 && peak2 < top - 10,
+ $"Peak holds the top ({top:F1} → {peak1:F1} dB at 0.9 s while the curve is at {curve1:F1}) and then falls ({peak2:F1} dB at 2.5 s)");
+ // Read at the display's cadence (a gap over 1.2 s restarts the analysis): once the curve
+ // has fallen to the floor, the held peak is still there, so the card keeps drawing it.
+ r.Reset();
+ r.Feed(8192);
+ s = r.Read();
+ var gone = Stopwatch.StartNew();
+ while (gone.ElapsedMilliseconds < 3500 && s[PostAt + pk] > -149.5f) s = r.Read(33);
+ yield return (s[Analysed] > 0.5f && s[PostAt + pk] <= -149.5f && s[PeakAt + pk] > -140,
+ $"the held peak keeps showing after the curve has gone (analysed {s[Analysed]}, curve {s[PostAt + pk]:F0} dB, peak {s[PeakAt + pk]:F0} dB)");
+ r.E.DeviceSetParam(r.T, r.D, AnaPeak, 0);
+ r.Reset();
+ r.Feed(8192);
+ s = r.Read();
+ Thread.Sleep(600);
+ s = r.Read();
+ yield return (Math.Abs(s[PeakAt + pk] - s[PostAt + pk]) < 0.01, "Peak off: the peak curve is the curve");
+ }
+
+ // On drums the Peak line stays a line: no single point drops into a notch or sticks out as
+ // a spike against its neighbours (it did on the Mac, as points' holds ran out apart).
+ using (var r = new Rig(DrumLoop(tmp)))
+ {
+ r.E.DeviceSetParam(r.T, r.D, AnaPeak, 1);
+ r.Reset();
+ double notch = 0, spike = 0, below = 0;
+ for (int f = 0; f < 130; f++)
+ {
+ r.Feed(1470);
+ var s = r.Read(30);
+ if (f < 30) continue;
+ for (int i = 1; i < Points - 1; i++)
+ {
+ if (PointHz(i) < 40 || PointHz(i) > 16000) continue;
+ float p = s[PeakAt + i], a = s[PeakAt + i - 1], b = s[PeakAt + i + 1];
+ notch = Math.Max(notch, Math.Min(a, b) - p);
+ spike = Math.Max(spike, p - Math.Max(a, b));
+ below = Math.Max(below, s[PostAt + i] - p);
+ }
+ }
+ yield return (notch < 3 && spike < 3 && below <= 0.01,
+ $"on a drum loop the Peak line has no notches or spikes (deepest notch {notch:F1} dB, tallest spike {spike:F1} dB) and never dips under the curve ({below:F2})");
+ }
+
+ // Pre shows the input with its peak; Off analyses nothing.
+ using (var r = new Rig(Sine(tmp, 1000)))
+ {
+ r.E.DeviceSetParam(r.T, r.D, Analyzer, 0);
+ r.Reset();
+ r.Feed(8192);
+ var s = r.Read();
+ int pk = Argmax(s, PreAt);
+ yield return (s[Analysed] > 0.5f && Math.Abs(s[PreAt + pk] - SineDb) < 3 && s[PostAt + pk] < -140,
+ $"Pre analyses the input alone ({s[PreAt + pk]:F1} dB in, {s[PostAt + pk]:F0} dB out)");
+ r.E.DeviceSetParam(r.T, r.D, Analyzer, 2);
+ r.Reset();
+ r.Feed(8192);
+ s = r.Read();
+ yield return (s[Analysed] < 0.5f && s[PreAt + pk] < -140, "Off analyses nothing");
+ }
+
+ // One analysis update (two curves) is cheap.
+ using (var r = new Rig(Sine(tmp, 1000)))
+ {
+ r.Reset();
+ var sc = new float[Scope8];
+ // The median of 21 updates: one read the OS preempted on a busy machine isn't the cost.
+ var took = new List<double>();
+ for (int i = 0; i < 21; i++)
+ {
+ r.Feed(2048);
+ Thread.Sleep(35);
+ var sw = Stopwatch.StartNew();
+ r.E.DeviceScope(r.T, r.D, sc, sc.Length);
+ took.Add(sw.Elapsed.TotalMilliseconds);
+ }
+ took.Sort();
+ double median = took[took.Count / 2];
+ yield return (median < 1.0, $"an EQ-8 analysis update takes {median:F3} ms (median of 21, under 1 ms; slowest {took[^1]:F3})");
+ }
+ }
+
+ private static IEnumerable<(bool, string)> ParamsAndSound(List<string> tmp)
+ {
+ string wav = Sine(tmp, 440);
+ using var e = new NotaEngine();
+ int t = e.AddAudioTrack();
+ e.AddAudioClip(t, wav, 0.0);
+ int d = e.AddBuiltinDevice(t, Eq8Kind);
+ yield return (e.DeviceParamCount(t, d) == 62 && e.DeviceGetParam(t, d, AnaRange) == 1f && e.DeviceGetParam(t, d, AnaPeak) == 0f
+ && e.DeviceParamName(t, d, AnaRange) == "Analyzer Range" && e.DeviceParamName(t, d, AnaPeak) == "Analyzer Peak",
+ "EQ-8 appends Analyzer Range (default 90 dB) and Analyzer Peak (default off)");
+
+ float[] Render()
+ {
+ var b = new float[8192 * 2];
+ e.Seek(0); e.Play(); e.RenderOffline(b, 8192); e.StopTransport();
+ return b;
+ }
+ e.DeviceSetParam(t, d, 3, 6f); // band 1 shelf +6 dB, so the EQ does something
+ Render(); Render(); // let the gain glide settle
+ var before = Render();
+ bool repeatable = before.AsSpan().SequenceEqual(Render());
+ e.DeviceSetParam(t, d, AnaRange, 2f);
+ e.DeviceSetParam(t, d, AnaPeak, 1f);
+ var after = Render();
+ yield return (repeatable && before.AsSpan().SequenceEqual(after), $"Range and Peak are display only: the sound is bit-identical (render repeatable: {repeatable})");
+
+ var doc = ProjectService.Capture(e, new TransportState(120.0, 1.0, false, false), new List<string>());
+ var dev = doc.Tracks.SelectMany(tr => tr.Devices).First(x => x.BuiltinKind == Eq8Kind);
+ bool saved = dev.Params.Length == 62 && dev.Params[AnaRange] == 2f && dev.Params[AnaPeak] == 1f;
+ dev.Params = dev.Params[..60]; // as written before 0.58.1
+ string dir = Path.Combine(Path.GetTempPath(), "nota-smoke-eqa-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ try
+ {
+ using var old = new NotaEngine();
+ ProjectService.Apply(doc, old, dir);
+ int ot = -1;
+ for (int i = 0; i < old.TrackCount; i++)
+ if (old.TryGetTrackInfo(i, out var ti) && !ti.IsInstrument && !ti.IsReturn && !ti.IsGroup) { ot = ti.Id; break; }
+ int od = 0;
+ yield return (saved && ot >= 0 && old.DeviceGetParam(ot, od, AnaRange) == 1f && old.DeviceGetParam(ot, od, AnaPeak) == 0f
+ && old.DeviceGetParam(ot, od, 3) == 6f,
+ "Range and Peak are saved; an older project opens with the defaults and its bands unchanged");
+ }
+ finally { Directory.Delete(dir, true); }
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 1cd85505..629d0492 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -469,6 +469,14 @@ if (args.Length >= 1 && args[0] == "--pad-warp")
Console.WriteLine(failures == 0 ? "PAD WARP PASSED" : $"PAD WARP FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// The EQ cards' spectrum analyzer alone (specs/046): `--eq-analyzer`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--eq-analyzer")
+{
+ Console.WriteLine("-- eq analyzer --");
+ foreach (var (ok, label) in EqAnalyzerTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "EQ ANALYZER PASSED" : $"EQ ANALYZER FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// Preset state alone: `--preset-state` (specs/048). Also part of the full run.
if (args.Length >= 1 && args[0] == "--preset-state")
{
@@ -4347,7 +4355,7 @@ Check(m4Dry > 1e-4f, $"instrument audible (rms={m4Dry:0.0000})");
int eqDev = engine.AddBuiltinDevice(fxT, 0); // 0 = EQ-8 (flat by default = passthrough)
Check(eqDev >= 0, "add built-in EQ-8");
Check(engine.DeviceName(fxT, eqDev) == "Nota EQ-8", "EQ-8 device name");
-Check(engine.DeviceParamCount(fxT, eqDev) == 60, "EQ-8 exposes 60 params (8 bands × 5, slopes, channels, globals)");
+Check(engine.DeviceParamCount(fxT, eqDev) == 62, "EQ-8 exposes 62 params (8 bands × 5, slopes, channels, globals, analyzer range and peak)");
engine.Seek(0);
engine.RenderOffline(buf, frames);
Check(Rms(buf, frames) > 1e-4f, $"audio flows through flat EQ-8 (rms={Rms(buf, frames):0.0000})");
@@ -5637,12 +5645,12 @@ Console.WriteLine("-- Nota EQ-3 --");
Render(4096); // the kill's 5 ms glide
qe.DeviceAction(qt, qd, 0, 0, 0); // fresh meters
Render(8192);
- var qs = new float[112];
+ var qs = new float[16 + 256];
int qn = qe.DeviceScope(qt, qd, qs, qs.Length);
- Check(qn == 112 && qs[3] > qs[2] + 20 && qs[3] > -30 && qs[11] < 0.01f && Math.Abs(qs[12] - 1) < 0.01f && Math.Abs(qs[9] - 250) < 5 && Math.Abs(qs[10] - 2500) < 30,
+ Check(qn == qs.Length && qs[3] > qs[2] + 20 && qs[3] > -30 && qs[11] < 0.01f && Math.Abs(qs[12] - 1) < 0.01f && Math.Abs(qs[9] - 250) < 5 && Math.Abs(qs[10] - 2500) < 30,
$"telemetry: band levels L {qs[2]:F0} / M {qs[3]:F1} dBFS, low gain {qs[11]:F3} (killed), crossovers {qs[9]:F0} / {qs[10]:F0} Hz");
- int pk = 0; for (int b = 1; b < 96; b++) if (qs[16 + b] > qs[16 + pk]) pk = b;
- double pkHz = 20 * Math.Pow(1000, (pk + 0.5) / 96);
+ int pk = 0; for (int b = 1; b < 256; b++) if (qs[16 + b] > qs[16 + pk]) pk = b;
+ double pkHz = 20 * Math.Pow(1000, pk / 255.0);
Check(qs[7] > 0.5f && pkHz > 380 && pkHz < 520, $"the output spectrum peaks at the sine (~{pkHz:0} Hz)");
// Texts.
@@ -6043,8 +6051,11 @@ Console.WriteLine("-- Nota Chamber --");
Check(ce.DeviceLayerWave(ct, cd, 2, pv, pv.Length) == 128 && ce.DeviceLayerWave(ct, cd, 3, pv, pv.Length) == 128, "Chamber exposes result + echogram previews");
ce.DeviceScope(ct, cd, csc, csc.Length);
float res0 = csc[19], echo0 = csc[20];
- ce.DeviceSetParam(ct, cd, IrSize, 1f); ce.DeviceSetParam(ct, cd, AlgoDecay, 0.9f); Settle();
- ce.DeviceScope(ct, cd, csc, csc.Length);
+ ce.DeviceSetParam(ct, cd, IrSize, 1f); ce.DeviceSetParam(ct, cd, AlgoDecay, 0.9f);
+ // The IR worker publishes in the background: give a slow CI runner up to 3 s.
+ var pvClock = System.Diagnostics.Stopwatch.StartNew();
+ do { Settle(); ce.DeviceScope(ct, cd, csc, csc.Length); }
+ while (!(csc[19] > res0 * 1.8f && csc[20] > echo0 * 2f) && pvClock.ElapsedMilliseconds < 3000);
Check(csc[19] > res0 * 1.8f && csc[20] > echo0 * 2f, $"previews follow Size + Decay (result {res0:F2}→{csc[19]:F2} s, echogram {echo0:F2}→{csc[20]:F2} s)");
ce.DeviceSetParam(ct, cd, IrSize, 0.5f); ce.DeviceSetParam(ct, cd, AlgoDecay, ce.DeviceParamDefault(ct, cd, AlgoDecay)); Settle();
}
@@ -6969,7 +6980,7 @@ Console.WriteLine("-- EQ-8 --");
engine.AddMidiClip(et, 0.0, 4.0);
engine.SetClipNotes(et, 0, new[] { new NotaNote(69, 0.0, 3.0, 0.9f) }); // A4 = 440 Hz + harmonics
int eq = engine.AddBuiltinDevice(et, 0);
- Check(engine.DeviceParamCount(et, eq) == 60, "EQ-8 has 60 params on a fresh track");
+ Check(engine.DeviceParamCount(et, eq) == 62, "EQ-8 has 62 params on a fresh track");
// Band 3 (index 2) is a bell; param base = 2*5. On=+0, Type=+1, Freq=+2, Gain=+3, Q=+4.
int b2 = 2 * 5;
@@ -7081,11 +7092,11 @@ Console.WriteLine("-- EQ-8 --");
// Spectra: pre and post peak at the sine; the shelf lifts post over pre.
qe.DeviceAction(qt, qd, 0, 0, 0);
Render(8192);
- var sc = new float[16 + 2 * 96];
+ var sc = new float[16 + 3 * 256];
int sn = qe.DeviceScope(qt, qd, sc, sc.Length);
int pkPre = 0, pkPost = 0;
- for (int b = 1; b < 96; b++) { if (sc[16 + b] > sc[16 + pkPre]) pkPre = b; if (sc[112 + b] > sc[112 + pkPost]) pkPost = b; }
- double hzPre = 20 * Math.Pow(1000, (pkPre + 0.5) / 96), lift = sc[112 + pkPost] - sc[16 + pkPre];
+ for (int b = 1; b < 256; b++) { if (sc[16 + b] > sc[16 + pkPre]) pkPre = b; if (sc[272 + b] > sc[272 + pkPost]) pkPost = b; }
+ double hzPre = 20 * Math.Pow(1000, pkPre / 255.0), lift = sc[272 + pkPost] - sc[16 + pkPre];
Check(sn == sc.Length && sc[5] > 0.5f && hzPre > 380 && hzPre < 520 && pkPre == pkPost && lift > 3 && sc[1] > sc[0] + 3,
$"spectra: pre / post peak at the sine (~{hzPre:0} Hz), post {lift:+0.0} dB over pre; out peak {sc[1]:F1} over in {sc[0]:F1} dBFS");
@@ -7123,12 +7134,18 @@ Console.WriteLine("-- EQ-8 --");
bool threw = false;
try { tools.SetEq8Band(qt, qd, 1, channel: "Centre").GetAwaiter().GetResult(); } catch (ArgumentException) { threw = true; }
Check(threw, "MCP set_eq8_band rejects an unknown channel");
+ var ma = tools.SetEq8(qt, qd, analyzerRangeDb: 120, analyzerPeak: true).Result;
+ Check(ma.AnalyzerRangeDb == 120 && ma.AnalyzerPeak && qe.DeviceGetParam(qt, qd, 60) == 2 && qe.DeviceGetParam(qt, qd, 61) == 1,
+ $"MCP set_eq8 sets the analyzer range and peak hold ({ma.AnalyzerRangeDb} dB, peak {ma.AnalyzerPeak})");
+ tools.SetEq8(qt, qd, analyzerRangeDb: 90, analyzerPeak: false).GetAwaiter().GetResult();
// An original-EQ-8 preset (the 40 band params only) keeps the appended params at their defaults.
var legacy = new PresetDocument { Type = "builtin-effect", BuiltinKind = 0, NamedParams = new Dictionary<string, float> { ["1 Type"] = 1f, ["1 Freq"] = 110f, ["1 Gain"] = 5f } };
PresetService.ApplyInPlace(legacy, qe, qt, qd);
Check(qe.DeviceGetParam(qt, qd, Scale) == 100 && qe.DeviceGetParam(qt, qd, AutoG) == 0 && qe.DeviceGetParam(qt, qd, Output) == 0
- && qe.DeviceGetParam(qt, qd, SlopeB + 4) == 0 && qe.DeviceGetParam(qt, qd, ChanB + 4) == 0, "an original EQ-8 preset loads with scale 100 %, stereo, 12 dB/oct");
+ && qe.DeviceGetParam(qt, qd, SlopeB + 4) == 0 && qe.DeviceGetParam(qt, qd, ChanB + 4) == 0
+ && qe.DeviceGetParam(qt, qd, 60) == 1 && qe.DeviceGetParam(qt, qd, 61) == 0,
+ "an original EQ-8 preset loads with scale 100 %, stereo, 12 dB/oct, analyzer range 90 dB, peak off");
// Every factory preset names only real params and renders finite.
var cat = new FactoryPresetCatalog();
@@ -15202,6 +15219,8 @@ foreach (var (ok, label) in DeviceFoldTests.Run()) Check(ok, label);
Console.WriteLine("-- preset state --");
foreach (var (ok, label) in PresetStateTests.Run()) Check(ok, label);
+Console.WriteLine("-- eq analyzer --");
+foreach (var (ok, label) in EqAnalyzerTests.Run()) Check(ok, label);
Console.WriteLine("-- scope view --");
foreach (var (ok, label) in ScopeViewTests.Run()) Check(ok, label);