diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..c6eaef5 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,56 @@ +name: SPLMeter tests + +# Runs the unit and processor regression tests on every push and pull request. +# Deliberately separate from build-chain.yml (main only), which signs, notarizes +# and uploads release artifacts and is too slow/expensive for feature branches. + +on: + push: + branches: ['**'] + pull_request: + workflow_dispatch: + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + CMAKE_POLICY_VERSION_MINIMUM: "3.5" + +jobs: + tests-linux: + name: Tests (Linux) + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v6.0.2 + + - name: Install system dependencies + run: | + sudo apt-get update -qq + sudo apt-get install -y \ + libasound2-dev \ + libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxext-dev \ + libgl1-mesa-dev \ + libfreetype-dev libfontconfig1-dev \ + libgtk-3-dev \ + xvfb + + - name: Cache deps (JUCE + Catch2) + uses: actions/cache@v5.0.4 + with: + path: | + build/_deps + key: juce-8.0.7-catch2-3.7.1-tests-v1-linux + + - name: Configure CMake + run: cmake -B build -DCMAKE_BUILD_TYPE=Release -DSPLMETER_TFLITE=OFF -DSPLMETER_BUILD_TESTS=ON + + - name: Build tests + run: cmake --build build --config Release --target SPLMeterTests SPLMeterProcessorTests -- -j$(nproc) + + - name: Unit tests + run: ./build/SPLMeterTests + + - name: Processor regression tests + # Golden files come from macOS arm64; the default tolerance mode absorbs + # libm/FMA differences between platforms. + run: xvfb-run -a ./build/SPLMeterProcessorTests diff --git a/.gitignore b/.gitignore index 5dd061a..2692bdc 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,9 @@ Vendor/asiosdk/ *.a *.d *.dia + +# Local CMake build trees +build-*/ + +# Stray artefact of a mis-quoted path (Vendor:asiosdk:common) +Vendor:asiosdk:common/ diff --git a/Builds/MacOSX/Info-AU.plist b/Builds/MacOSX/Info-AU.plist index cc5b965..8013ee2 100644 --- a/Builds/MacOSX/Info-AU.plist +++ b/Builds/MacOSX/Info-AU.plist @@ -18,9 +18,9 @@ CFBundleSignature ???? CFBundleShortVersionString - 2.5.0 + 3.6.0 CFBundleVersion - 2.5.0 + 3.6.0 NSHumanReadableCopyright 2025 Philipp Paul Klose Audio Engineering NSHighResolutionCapable @@ -41,7 +41,7 @@ subtype Splm version - 132352 + 198144 resourceUsage network.client diff --git a/Builds/MacOSX/Info-Standalone_Plugin.plist b/Builds/MacOSX/Info-Standalone_Plugin.plist index f616cf5..980125e 100644 --- a/Builds/MacOSX/Info-Standalone_Plugin.plist +++ b/Builds/MacOSX/Info-Standalone_Plugin.plist @@ -18,9 +18,9 @@ CFBundleSignature ???? CFBundleShortVersionString - 2.5.0 + 3.6.0 CFBundleVersion - 2.5.0 + 3.6.0 NSHumanReadableCopyright 2025 Philipp Paul Klose Audio Engineering NSHighResolutionCapable diff --git a/Builds/MacOSX/Info-VST3.plist b/Builds/MacOSX/Info-VST3.plist index 0c439ba..8cd60e3 100644 --- a/Builds/MacOSX/Info-VST3.plist +++ b/Builds/MacOSX/Info-VST3.plist @@ -18,9 +18,9 @@ CFBundleSignature ???? CFBundleShortVersionString - 2.6.1 + 3.6.0 CFBundleVersion - 2.6.1 + 3.6.0 NSHumanReadableCopyright 2025 Philipp Paul Klose Audio Engineering NSHighResolutionCapable diff --git a/Builds/MacOSX/Info-VST3_Manifest_Helper.plist b/Builds/MacOSX/Info-VST3_Manifest_Helper.plist index 1cf0f39..09a3a6c 100644 --- a/Builds/MacOSX/Info-VST3_Manifest_Helper.plist +++ b/Builds/MacOSX/Info-VST3_Manifest_Helper.plist @@ -18,9 +18,9 @@ CFBundleSignature CFBundleShortVersionString - 2.6.1 + 3.6.0 CFBundleVersion - 2.6.1 + 3.6.0 NSHumanReadableCopyright 2025 Philipp Paul Klose Audio Engineering NSHighResolutionCapable diff --git a/CMakeLists.txt b/CMakeLists.txt index 03371d9..a84a046 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.22) -project(SPLMeter VERSION 3.5.2) +project(SPLMeter VERSION 3.6.0) set(CMAKE_CXX_STANDARD 17) @@ -98,7 +98,7 @@ if(UNIX AND NOT APPLE) endif() juce_add_plugin(SPLMeter - VERSION 3.5.2 + VERSION 3.6.0 PLUGIN_MANUFACTURER_CODE Manu PLUGIN_CODE Splm FORMATS ${SPLMETER_FORMATS} @@ -317,6 +317,12 @@ if(SPLMETER_BUILD_TESTS) Tests/StateSerializationTests.cpp Tests/MarkerTests.cpp Tests/LeqTests.cpp + Tests/VibrationDspTests.cpp + Tests/VibrationAssessmentTests.cpp + Tests/RewTransportTests.cpp + Tests/RewSequenceTests.cpp + Tests/RewSequencerTests.cpp + Tests/RewRunResultsTests.cpp ) target_include_directories(SPLMeterTests PRIVATE Source) @@ -334,8 +340,33 @@ if(SPLMETER_BUILD_TESTS) JUCE_UNIT_TESTS=1 ) + # Regression tests against the real processor. Separate executable because it + # links the plugin's shared-code library, which already contains the compiled + # JUCE modules (linking juce:: modules again would duplicate symbols). + add_executable(SPLMeterProcessorTests + Tests/ProcessorRegressionTests.cpp + Tests/SensorRoleTests.cpp + Tests/FftSourceTests.cpp + Tests/VibrationProcessorTests.cpp + Tests/VibrationReportTests.cpp + Tests/RewProcessorTests.cpp + ) + target_link_libraries(SPLMeterProcessorTests PRIVATE + SPLMeter + Catch2::Catch2WithMain + ) + target_include_directories(SPLMeterProcessorTests PRIVATE + Source + $ + ) + target_compile_definitions(SPLMeterProcessorTests PRIVATE + $ + SPLMETER_GOLDEN_DIR="${CMAKE_CURRENT_SOURCE_DIR}/Tests/golden" + ) + include(CTest) list(APPEND CMAKE_MODULE_PATH ${catch2_SOURCE_DIR}/extras) include(Catch) catch_discover_tests(SPLMeterTests) + catch_discover_tests(SPLMeterProcessorTests) endif() diff --git a/JuceLibraryCode/JucePluginDefines.h b/JuceLibraryCode/JucePluginDefines.h index 4b1ec99..8199b4e 100644 --- a/JuceLibraryCode/JucePluginDefines.h +++ b/JuceLibraryCode/JucePluginDefines.h @@ -77,13 +77,13 @@ #define JucePlugin_EditorRequiresKeyboardFocus 1 #endif #ifndef JucePlugin_Version - #define JucePlugin_Version 3.5.2 + #define JucePlugin_Version 3.6.0 #endif #ifndef JucePlugin_VersionCode - #define JucePlugin_VersionCode 0x30502 + #define JucePlugin_VersionCode 0x30600 #endif #ifndef JucePlugin_VersionString - #define JucePlugin_VersionString "3.5.2" + #define JucePlugin_VersionString "3.6.0" #endif #ifndef JucePlugin_VSTUniqueID #define JucePlugin_VSTUniqueID JucePlugin_PluginCode @@ -155,7 +155,7 @@ #define JucePlugin_ARAFactoryID "com.PhilippPaulKloseAudioEngineering.SPLMeter.factory" #endif #ifndef JucePlugin_ARADocumentArchiveID - #define JucePlugin_ARADocumentArchiveID "com.PhilippPaulKloseAudioEngineering.SPLMeter.aradocumentarchive.3.5.2" + #define JucePlugin_ARADocumentArchiveID "com.PhilippPaulKloseAudioEngineering.SPLMeter.aradocumentarchive.3.6.0" #endif #ifndef JucePlugin_ARACompatibleArchiveIDs #define JucePlugin_ARACompatibleArchiveIDs "" diff --git a/README.md b/README.md index ae1d524..0e3c038 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # SPLMeter -A professional Sound Pressure Level (SPL) meter built with JUCE, available as a macOS/Windows/Linux standalone app and as VST3 / AU plugin. +A professional Sound Pressure Level (SPL) meter built with JUCE, available as a macOS/Windows/Linux standalone app and as VST3 / AU plugin. Since v3.6 it also measures **vibration** with an IEPE accelerometer, alongside the microphone. ![SPLMeter v3.5 screenshot](screenShot.png) @@ -61,17 +61,38 @@ Continuous real-time estimation of: | Specific Loudness | Perceived loudness approximation (sone) | | Psychoacoustic Annoyance | Combined annoyance index (Zwicker & Fastl 1999): N × (1 + √(w_S² + w_FR²)) | +### Vibration Measurement (Accelerometer) +Full guide: [docs/VIBRATION_GUIDE.md](docs/VIBRATION_GUIDE.md) +- **One IEPE accelerometer** (triaxial or uniaxial) **plus the microphone** at the same time — each input gets a role (Mic, Accel X/Y/Z, Accel uniaxial, Off) in **Settings → Inputs and Sensors…**; only Mic inputs feed the SPL meter +- **Calibration per axis** with a handheld calibrator (10 m/s² / 1 g at 159.2 Hz, or custom) or from the datasheet sensitivity and the interface's full scale +- **Signal chain** in double precision: high-pass, integration to velocity or displacement, ISO 8041 frequency weightings (Wb, Wc, Wd, We, Wf, Wh, Wj, Wk, Wm), DIN 4150-2 KB weighting, or a band limit +- **Detectors**: running RMS, peak, peak-to-peak, a_w,rms, MTVV, VDV, crest factor, PPV with dominant frequency, KB_Fmax / KB_FTr, vector sum with k-factors, A(8), 1/3-octave spectrum (1 Hz – 1250 Hz) +- **Measurement profiles**: structure-borne, machinery (ISO 20816), whole-body health and comfort (ISO 2631-1), hand-arm (ISO 5349-1), building perception (DIN 4150-2), building structural (DIN 4150-3) +- **Assessment** against editable reference values: EU 2002/44/EC and German LärmVibrationsArbSchV action/limit values, ISO 10816-3 / 20816-3 zones A–D, DIN 4150-2 A_u / A_o / A_r, DIN 4150-3 guideline values; shown as a status dot in the panel +- **Vibration panel** below the SPL meter, **timeline traces** (Vib X · Y · Z · Σ), vibration **CSV columns**, **multichannel WAV** with roles and calibration, and an **HTML vibration report** +- Indicative measurements: SPLMeter is not a type-tested ISO 8041-1 / DIN 45669-1 instrument + +### REW Measurement Sequencer +Full guide: [docs/REW_SEQUENCER_GUIDE.md](docs/REW_SEQUENCER_GUIDE.md) +- **Tools → REW Measurement Sequencer…** runs a list of [Room EQ Wizard](https://www.roomeqwizard.com/) sweep measurements one after the other through REW's REST API (REW Pro, API enabled, same computer) +- **Per step**: name and notes, output, second output (ASIO) / invert, input range, level, sweep range and length, repetitions, timing reference, clipping / SPL-limit protection, REW group, *wait for me* prompt, delay; unset settings keep REW's value +- **Add positions…** for multi-position measurements, loops, gap between steps, stop / skip / retry on errors, dry run, pause and abort; REW's settings are restored after the run +- **SPLMeter measures each sweep too**: LAeq, LCeq, LZeq, LAFmax, LCSmax, LCpeak and, with an accelerometer, vibration RMS and peak per axis — saved with the run as **CSV and JSON**, plus one **timeline marker** per sweep +- Sequences are saved as `*.rewseq.json`; the run continues when the window or editor is closed + ### Input Modes -- **Real Time** — live microphone / audio interface input, up to **32 channels** +- **Real Time** — live microphone / audio interface input, up to **32 channels**; each input can be a microphone or an accelerometer axis - **File** — load and analyse an audio file (WAV, AIFF, FLAC, MP3, OGG) - **Monitor button** — speaker icon; output is muted by default, click to enable pass-through ### Export -Accessible via the **Save…** button (popup menu): -- **Save CSV** — exports the full measurement log (timestamps, all SPL values, all psychoacoustic metrics) as a CSV file -- **Save WAV** — saves the last *Keep Last* seconds of Input 01 and 02 as a stereo 24-bit WAV file +Accessible via the **Ex-/Import…** button (popup menu): +- **Save CSV** — exports the full measurement log (timestamps, all SPL values, all psychoacoustic metrics; with an accelerometer also the vibration values) as a CSV file +- **Save WAV** — saves the last *Keep Last* seconds of Input 01 and 02 as a stereo 24-bit WAV file; with an accelerometer, every non-Off input (up to 8 tracks) with roles and calibration in the file - **Save Screenshot** — exports the current view as a JPEG image - **Save All** — saves CSV, WAV, and screenshot in one step into a chosen folder +- **Save Vibration Report** — one self-contained HTML file (setup, results, assessment, charts, events, disclaimer), printable to PDF +- **Save / Load Settings** — JSON file with all settings, including input roles, accelerometer calibration and assessment values ### Analysis Tools Accessible via the **Tools…** button (popup menu): @@ -80,6 +101,7 @@ Accessible via the **Tools…** button (popup menu): - **ViSQOL** *(macOS / Windows when pre-built lib is present)* — perceptual audio quality analysis (MOS-LQO + per-band NSIM) - **Correction Filter** — load a frequency-response correction curve (.txt / .csv: Hz + dB pairs); applied as a linear-phase FIR filter before metering (configured in Settings) - **Graph Overlay** — load a reference curve and display it as a dashed blue line in the FFT view (configured in Settings) +- **REW Measurement Sequencer** *(not on iOS)* — runs a list of REW sweep measurements with per-step settings and measures each sweep with SPLMeter (see above) ### Title Bar Utilities - **Live clock** — auto-updating date/time display (updates every second) @@ -94,7 +116,7 @@ Opened via the **Settings** button. A wide, two-column, card-based window with a | **FFT** | FFT enable toggle, FFT Gain fader, FFT Smooth fader, FFT Size (32 – 524,288 samples), Band Resolution, Display Mode, Window Function, Overlap, Peak Hold, RTA +3 dB/oct | | **Spectrogram** | FFT Size (32 – 524,288 samples) for the Spectrogram window | | **Analysis** | Correction Filter (enable / load / clear), Graph Overlay (enable / load / clear) | -| **Input Channels** | Per-channel mute buttons for IN01 – IN32 | +| **Input Channels** | Per-channel mute buttons for IN01 – IN32 (with the role tag), **Inputs and Sensors…** window for roles, accelerometer calibration, profile and assessment | ### MIDI Learn Right-click any of the three faders to assign or clear a MIDI CC mapping: @@ -307,6 +329,7 @@ GitHub Actions workflows build the standalone for macOS and Windows on every pus |---|---|---|---| | **JUCE** | 8.0.7 | ISC / GPL-3.0 | https://github.com/juce-framework/JUCE | | **Steinberg VST3 SDK** (incl. ASIO SDK) | latest | Steinberg VST3 License | https://github.com/steinbergmedia/vst3sdk | +| **Room EQ Wizard REST API** (used by the REW Measurement Sequencer; REW is not bundled) | API 0.9.9 (REW 5.40) | REW EULA | https://www.roomeqwizard.com/help/help_en-GB/html/api.html | ### Standards & Psychoacoustic Models @@ -315,11 +338,32 @@ GitHub Actions workflows build the standalone for macOS and Windows on every pus | **IEC 61672-1:2013** | Electroacoustics — Sound level meters. Defines FAST (125 ms) and SLOW (1 s) time weighting and A/C frequency weighting curves. | | **ISO 266:1997** | Preferred frequencies — defines the 31 standard 1/3-octave band centre frequencies (20 Hz – 20 kHz). | | **Zwicker & Fastl, *Psychoacoustics: Facts and Models* (3rd ed., Springer, 2007)** | Theoretical basis for the Roughness, Sharpness, Fluctuation Strength, Specific Loudness, and Psychoacoustic Annoyance estimators. | +| **ISO 8041-1, ISO 2631-1/-2/-4, ISO 5349-1** | Human vibration frequency weightings and evaluation (a_w, MTVV, VDV, A(8), comfort scale). | +| **Directive 2002/44/EC, LärmVibrationsArbSchV** | Whole-body and hand-arm exposure action and limit values (EU, Germany). | +| **ISO 10816-3 / ISO 20816-3** | Machinery vibration severity zones A–D. | +| **DIN 4150-2, DIN 4150-3** | Building vibration: effects on people (KB weighting, A_u / A_o / A_r) and on structures (PPV guideline values). | +| **IEC 61260-1** | 1/3-octave band centre frequencies (base 10) of the vibration spectrum. | + +Sources and verification status of all vibration parameters: [docs/VIBRATION_SPEC.md](docs/VIBRATION_SPEC.md) §14. --- ## Changelog +### [v3.6.0](https://github.com/ppklose/ppkSPLMeter/releases/tag/v3.6.0) +- **Vibration measurement with an IEPE accelerometer** alongside the microphone — see [docs/VIBRATION_GUIDE.md](docs/VIBRATION_GUIDE.md) +- **Inputs and Sensors window** (Settings → Input Channels): a role per input (Mic, Accel X/Y/Z, Accel uniaxial, Off), live level meters, per-axis calibration (handheld calibrator or datasheet) with date and method +- **Accelerometer signal chain**: high-pass, integration to velocity / displacement, ISO 8041 weightings (Wb, Wc, Wd, We, Wf, Wh, Wj, Wk, Wm), DIN 4150-2 KB weighting, band limit; detectors for RMS, peak, a_w,rms, MTVV, VDV, crest factor, PPV with dominant frequency, KB_Fmax / KB_FTr, vector sum, A(8), 1/3-octave spectrum +- **Measurement profiles** for structure-borne sound, machinery, whole-body health and comfort, hand-arm, building perception and building structural +- **Assessment** with editable reference values (EU / Germany, ISO 20816-3, DIN 4150-2, DIN 4150-3) and a status dot in the new **Vibration panel** below the SPL meter +- **Timeline** vibration traces, **CSV** vibration columns, **JSON settings** with roles, calibration and limits +- **Multichannel WAV recording** with roles and calibration in the file; file playback uses them +- **HTML vibration report** (Ex-/Import → Save Vibration Report…) +- **REW Measurement Sequencer** (Tools → REW Measurement Sequencer…): runs a list of Room EQ Wizard sweeps through REW's REST API with per-step output, second output / invert, inputs, level, sweep, repetitions, timing reference, protection, group and *wait for me* prompts; dry run, pause, abort, loops, error policy; REW's settings restored afterwards. SPLMeter measures every sweep (LAeq … LCpeak, vibration per axis) and saves the run as CSV and JSON, with a timeline marker per sweep — see [docs/REW_SEQUENCER_GUIDE.md](docs/REW_SEQUENCER_GUIDE.md) +- **FFT source** selector (mix, Dual 1+2, or a single input) replaces the Dual FFT toggle; v3.5.2 settings load unchanged +- The standalone app now accepts devices that open more than 8 inputs (up to 32); before, they fell back to a single input +- Default behaviour without accelerometer roles is unchanged (bit-identical SPL results, verified by regression tests) + ### [v3.5.2](https://github.com/ppklose/ppkSPLMeter/releases/tag/v3.5.2) - **All user settings now persist across launches** — previously some changes were silently reverted on quit, because the app's preferences shared a file with JUCE's standalone wrapper, which rewrote it from a stale copy. Preferences now live in their own `SPLMeter.prefs` (migrated automatically) and are saved every few seconds, so they also survive a crash or force-quit. Newly remembered: window size, timeline series checkboxes and psychoacoustic metric, FFT overlay toggle, Spectrogram view settings, Long-term SPL toggles and Y range, Sound Detective threshold and TFLite model, Impulse Fidelity frequency, loaded correction filter and graph overlays, MIDI CC assignments and channel names - **Dual FFT** (Settings → FFT): the timeline FFT overlay can show separate spectra for input 1 (green) and input 2 (red), overlaid with a legend. Both use identical analysis settings; the crosshair reads out both levels diff --git a/SPLMeter.jucer b/SPLMeter.jucer index 0bda04d..b84e671 100644 --- a/SPLMeter.jucer +++ b/SPLMeter.jucer @@ -1,6 +1,6 @@ - +#include "PluginProcessor.h" +#include + +//============================================================================== +// "Inputs and Sensors" window (vibration spec §7.1): a role per input, live level, +// accelerometer calibration, and the accelerometer sensor settings. +namespace InputsUi +{ +// Source literals are UTF-8; juce::String (const char*) would read them as ASCII +inline juce::String U (const char* utf8) { return juce::String::fromUTF8 (utf8); } + +struct Palette +{ + juce::Colour bg, card, border, text, subtext, field, accent, ok, warn, bad; + + static Palette get (bool light) + { + if (light) + return { juce::Colour (0xffe5e5ea), juce::Colour (0xfff5f5f7), juce::Colour (0xffc7c7cc), + juce::Colour (0xff1c1c1e), juce::Colour (0xff6c6c70), juce::Colour (0xffd1d1d6), + juce::Colour (0xff007aff), juce::Colour (0xff248a3d), juce::Colour (0xffc93400), + juce::Colour (0xffd70015) }; + return { juce::Colour (0xff2c2c2e), juce::Colour (0xff333335), juce::Colour (0xff48484a), + juce::Colours::white, juce::Colour (0xff8e8e93), juce::Colour (0xff3a3a3c), + juce::Colour (0xff5ac8fa), juce::Colour (0xff34c759), juce::Colour (0xffff9f0a), + juce::Colour (0xffff453a) }; + } + + void style (juce::ComboBox& c) const + { + c.setColour (juce::ComboBox::backgroundColourId, field); + c.setColour (juce::ComboBox::textColourId, text); + c.setColour (juce::ComboBox::outlineColourId, border); + c.setColour (juce::ComboBox::arrowColourId, subtext); + } +}; + +inline juce::String roleName (SensorRole r) +{ + switch (r) + { + case SensorRole::Mic: return "Mic"; + case SensorRole::AccelX: return "Accel X"; + case SensorRole::AccelY: return "Accel Y"; + case SensorRole::AccelZ: return "Accel Z"; + case SensorRole::AccelUniaxial: return "Accel (uniaxial)"; + case SensorRole::Off: return "Off"; + } + return {}; +} + +// Short tag shown on the channel buttons in Settings +inline juce::String roleTag (SensorRole r) +{ + switch (r) + { + case SensorRole::AccelX: return "X"; + case SensorRole::AccelY: return "Y"; + case SensorRole::AccelZ: return "Z"; + case SensorRole::AccelUniaxial: return "ACC"; + case SensorRole::Off: return "OFF"; + case SensorRole::Mic: break; + } + return {}; +} + +inline juce::String weightingName (vib::Weighting w) +{ + switch (w) + { + case vib::Weighting::None: return "Unweighted"; + case vib::Weighting::BandLimit: return "Band limit"; + case vib::Weighting::Wb: return "Wb vertical, rail (ISO 2631-4)"; + case vib::Weighting::Wc: return "Wc seat back (ISO 2631-1)"; + case vib::Weighting::Wd: return "Wd whole body x/y (ISO 2631-1)"; + case vib::Weighting::We: return "We rotational (ISO 2631-1)"; + case vib::Weighting::Wf: return "Wf motion sickness (ISO 2631-1)"; + case vib::Weighting::Wh: return "Wh hand-arm (ISO 5349-1)"; + case vib::Weighting::Wj: return "Wj head, recumbent (ISO 2631-1)"; + case vib::Weighting::Wk: return "Wk whole body z (ISO 2631-1)"; + case vib::Weighting::Wm: return "Wm buildings (ISO 2631-2)"; + case vib::Weighting::KB: return "KB DIN 4150-2 (velocity)"; + } + return {}; +} + +// Short form for the combo box text; the full name goes into the tooltip. +inline juce::String weightingShortName (vib::Weighting w) +{ + switch (w) + { + case vib::Weighting::None: return "Unweighted"; + case vib::Weighting::BandLimit: return "Band limit"; + case vib::Weighting::Wb: return "Wb rail"; + case vib::Weighting::Wc: return "Wc seat back"; + case vib::Weighting::Wd: return "Wd body x/y"; + case vib::Weighting::We: return "We rotational"; + case vib::Weighting::Wf: return "Wf sickness"; + case vib::Weighting::Wh: return "Wh hand-arm"; + case vib::Weighting::Wj: return "Wj head"; + case vib::Weighting::Wk: return "Wk body z"; + case vib::Weighting::Wm: return "Wm buildings"; + case vib::Weighting::KB: return "KB DIN 4150-2"; + } + return {}; +} + +inline juce::String formatAccel (double ms2) +{ + if (ms2 <= 0.0) return U ("0 m/s²"); + if (ms2 >= 100.0) return juce::String (ms2, 0) + U (" m/s²"); + if (ms2 >= 1.0) return juce::String (ms2, 2) + U (" m/s²"); + if (ms2 >= 0.01) return juce::String (ms2 * 1000.0, 1) + U (" mm/s²"); + return juce::String (ms2 * 1.0e6, 0) + U (" µm/s²"); +} + +inline juce::String formatDbfs (double rms) +{ + return rms > 1.0e-6 ? juce::String (20.0 * std::log10 (rms), 1) + " dBFS" : juce::String (U ("−∞ dBFS")); +} + +//============================================================================== +// Click-to-edit number with range and unit +class NumberField : public juce::Label +{ +public: + std::function onValueChange; + + NumberField (double minV, double maxV, int decimals, juce::String unit = {}) + : min_ (minV), max_ (maxV), decimals_ (decimals), unit_ (std::move (unit)) + { + setEditable (true, true, false); + setJustificationType (juce::Justification::centred); + onTextChange = [this] + { + const auto t = getText().retainCharacters ("0123456789.,-eE").replaceCharacter (',', '.'); + const double v = t.isNotEmpty() ? t.getDoubleValue() : value_; + setValue (juce::jlimit (min_, max_, v), juce::sendNotification); + }; + } + + void setValue (double v, juce::NotificationType n = juce::dontSendNotification) + { + const bool changed = std::abs (v - value_) > 1.0e-12; + value_ = v; + setText (juce::String (v, decimals_) + (unit_.isNotEmpty() ? " " + unit_ : juce::String()), + juce::dontSendNotification); + if (changed && n != juce::dontSendNotification && onValueChange) + onValueChange (v); + } + double getValue() const noexcept { return value_; } + + void style (const Palette& p) + { + setColour (juce::Label::backgroundColourId, p.field); + setColour (juce::Label::textColourId, p.text); + setColour (juce::Label::textWhenEditingColourId, p.text); + setColour (juce::TextEditor::backgroundColourId, p.field); + setColour (juce::TextEditor::textColourId, p.text); + setColour (juce::TextEditor::highlightColourId, p.accent.withAlpha (0.4f)); + } + +protected: + juce::TextEditor* createEditorComponent() override + { + auto* ed = juce::Label::createEditorComponent(); + ed->setText (juce::String (value_, decimals_), false); + ed->setJustification (juce::Justification::centred); + return ed; + } + +private: + double min_, max_; + int decimals_; + juce::String unit_; + double value_ = std::numeric_limits::quiet_NaN(); +}; + +//============================================================================== +// Horizontal level bar: RMS bar + decaying peak tick, −80 … 0 dBFS +class LevelBar : public juce::Component +{ +public: + void setLevels (float rms, float peak) + { + rms_ = rms; + peak_ = std::max (peak, peak_ * 0.85f); + repaint(); + } + void setPalette (const Palette& p) { pal_ = p; repaint(); } + + void paint (juce::Graphics& g) override + { + const auto b = getLocalBounds().toFloat().reduced (0.0f, 6.0f); + g.setColour (pal_.field); + g.fillRoundedRectangle (b, 3.0f); + + auto toX = [&] (float lin) + { + const float db = lin > 1.0e-6f ? 20.0f * std::log10 (lin) : -120.0f; + return b.getX() + b.getWidth() * juce::jlimit (0.0f, 1.0f, (db + 80.0f) / 80.0f); + }; + const float xr = toX (rms_); + const auto col = peak_ >= 0.99f ? pal_.bad : (peak_ >= 0.5f ? pal_.warn : pal_.ok); + g.setColour (col.withAlpha (0.85f)); + g.fillRoundedRectangle (b.withRight (xr), 3.0f); + if (peak_ > 1.0e-6f) + { + g.setColour (col); + const float xp = toX (peak_); + g.fillRect (juce::Rectangle (xp - 1.0f, b.getY(), 2.0f, b.getHeight())); + } + } + +private: + float rms_ = 0.0f, peak_ = 0.0f; + Palette pal_ = Palette::get (false); +}; + +//============================================================================== +// Calibration dialog for one accelerometer input (spec §4) +class CalibrationComponent : public juce::Component, + private juce::Timer +{ +public: + CalibrationComponent (SPLMeterAudioProcessor& p, int channel, bool light) + : processor_ (p), ch_ (channel), pal_ (Palette::get (light)) + { + auto setupLabel = [this] (juce::Label& l, const juce::String& text, bool sub = false) + { + l.setText (text, juce::dontSendNotification); + l.setFont (juce::Font (juce::FontOptions().withHeight (sub ? 12.5f : 14.0f))); + l.setColour (juce::Label::textColourId, sub ? pal_.subtext : pal_.text); + addAndMakeVisible (l); + }; + auto setupButton = [this] (juce::TextButton& b) + { + b.setColour (juce::TextButton::buttonColourId, pal_.field); + b.setColour (juce::TextButton::buttonOnColourId, pal_.accent); + b.setColour (juce::TextButton::textColourOffId, pal_.text); + b.setColour (juce::TextButton::textColourOnId, juce::Colours::black); + addAndMakeVisible (b); + }; + + setupLabel (titleLabel_, processor_.getChannelName (ch_) + U (" · ") + + roleName (processor_.getChannelRole (ch_))); + titleLabel_.setFont (juce::Font (juce::FontOptions().withHeight (16.0f).withStyle ("Bold"))); + setupLabel (currentLabel_, {}, true); + setupLabel (levelLabel_, {}, true); + + for (auto* b : { &calibratorTab_, &datasheetTab_ }) + { + setupButton (*b); + b->setClickingTogglesState (true); + b->setRadioGroupId (4711); + b->onClick = [this] { updateMode(); }; + } + calibratorTab_.setToggleState (true, juce::dontSendNotification); + + // --- Calibrator --- + setupLabel (refLabel_, "Reference"); + refCombo_.addItem (U ("10 m/s² RMS at 159.2 Hz (140 dB)"), 1); + refCombo_.addItem ("1 g RMS at 159.2 Hz (139.8 dB)", 2); + refCombo_.addItem ("Custom", 3); + refCombo_.setSelectedId (1, juce::dontSendNotification); + refCombo_.onChange = [this] { updateMode(); }; + addAndMakeVisible (refCombo_); + setupLabel (customLevelLabel_, "Level"); + setupLabel (customFreqLabel_, "Frequency"); + customLevel_.setValue (10.0); + customFreq_.setValue (159.2); + for (auto* f : { &customLevel_, &customFreq_ }) { f->style (pal_); addAndMakeVisible (*f); } + setupButton (measureButton_); + measureButton_.onClick = [this] { toggleMeasurement(); }; + addAndMakeVisible (progress_); + progress_.setColour (juce::ProgressBar::foregroundColourId, pal_.accent); + progress_.setColour (juce::ProgressBar::backgroundColourId, pal_.field); + setupLabel (resultLabel_, "Mount the sensor on the calibrator, switch it on, then press Measure.", true); + resultLabel_.setJustificationType (juce::Justification::topLeft); + + // --- Datasheet --- + setupLabel (sensLabel_, "Sensitivity"); + sensField_.setValue (10.2); + sensUnit_.addItem (U ("mV/(m/s²)"), 1); + sensUnit_.addItem ("mV/g", 2); + sensUnit_.setSelectedId (1, juce::dontSendNotification); + setupLabel (fsLabel_, "Interface full scale"); + fsField_.setValue (1.0); + fsUnit_.addItem ("Vrms at 0 dBFS", 1); + fsUnit_.addItem ("dBu at 0 dBFS", 2); + fsUnit_.setSelectedId (1, juce::dontSendNotification); + for (auto* f : { &sensField_, &fsField_ }) + { + f->style (pal_); + f->onValueChange = [this] (double) { updateDatasheet(); }; + addAndMakeVisible (*f); + } + for (auto* c : { &refCombo_, &sensUnit_, &fsUnit_ }) + pal_.style (*c); + for (auto* c : { &sensUnit_, &fsUnit_ }) + { + c->onChange = [this] { updateDatasheet(); }; + addAndMakeVisible (*c); + } + setupLabel (datasheetResult_, {}, true); + datasheetResult_.setJustificationType (juce::Justification::topLeft); + + setupButton (applyButton_); + setupButton (closeButton_); + applyButton_.onClick = [this] { apply(); }; + closeButton_.onClick = [this] { closeDialog(); }; + + updateMode(); + updateDatasheet(); + timerCallback(); + startTimerHz (15); + setSize (560, 400); + } + + ~CalibrationComponent() override + { + stopTimer(); + if (measuring_) + processor_.cancelAccelCalibration(); + } + + void paint (juce::Graphics& g) override { g.fillAll (pal_.bg); } + + void resized() override + { + auto r = getLocalBounds().reduced (16); + titleLabel_.setBounds (r.removeFromTop (24)); + currentLabel_.setBounds (r.removeFromTop (20)); + levelLabel_.setBounds (r.removeFromTop (20)); + r.removeFromTop (8); + auto tabs = r.removeFromTop (28); + calibratorTab_.setBounds (tabs.removeFromLeft (tabs.getWidth() / 2).reduced (2, 0)); + datasheetTab_.setBounds (tabs.reduced (2, 0)); + r.removeFromTop (12); + + auto buttons = r.removeFromBottom (30); + closeButton_.setBounds (buttons.removeFromRight (100)); + buttons.removeFromRight (8); + applyButton_.setBounds (buttons.removeFromRight (160)); + r.removeFromBottom (8); + + // Calibrator + { + auto c = r; + auto row = c.removeFromTop (28); + refLabel_.setBounds (row.removeFromLeft (150)); + refCombo_.setBounds (row); + c.removeFromTop (6); + row = c.removeFromTop (28); + customLevelLabel_.setBounds (row.removeFromLeft (150)); + customLevel_.setBounds (row.removeFromLeft (110)); + row.removeFromLeft (16); + customFreqLabel_.setBounds (row.removeFromLeft (80)); + customFreq_.setBounds (row.removeFromLeft (110)); + c.removeFromTop (10); + row = c.removeFromTop (28); + measureButton_.setBounds (row.removeFromLeft (150)); + row.removeFromLeft (10); + progress_.setBounds (row.reduced (0, 4)); + c.removeFromTop (8); + resultLabel_.setBounds (c); + } + // Datasheet + { + auto c = r; + auto row = c.removeFromTop (28); + sensLabel_.setBounds (row.removeFromLeft (150)); + sensField_.setBounds (row.removeFromLeft (110)); + row.removeFromLeft (8); + sensUnit_.setBounds (row.removeFromLeft (130)); + c.removeFromTop (6); + row = c.removeFromTop (28); + fsLabel_.setBounds (row.removeFromLeft (150)); + fsField_.setBounds (row.removeFromLeft (110)); + row.removeFromLeft (8); + fsUnit_.setBounds (row.removeFromLeft (160)); + c.removeFromTop (10); + datasheetResult_.setBounds (c); + } + } + +private: + bool calibratorMode() const { return calibratorTab_.getToggleState(); } + + double referenceRms() const + { + switch (refCombo_.getSelectedId()) + { + case 2: return vib::calibration::kGravity; + case 3: return customLevel_.getValue(); + default: return vib::calibration::kCalibratorRms; + } + } + double referenceHz() const { return refCombo_.getSelectedId() == 3 ? customFreq_.getValue() : 159.2; } + + void updateMode() + { + const bool cal = calibratorMode(); + const bool custom = refCombo_.getSelectedId() == 3; + for (juce::Component* c : std::initializer_list { + &refLabel_, &refCombo_, &measureButton_, &progress_, &resultLabel_ }) + c->setVisible (cal); + for (juce::Component* c : std::initializer_list { + &customLevelLabel_, &customLevel_, &customFreqLabel_, &customFreq_ }) + c->setVisible (cal && custom); + for (juce::Component* c : std::initializer_list { + &sensLabel_, &sensField_, &sensUnit_, &fsLabel_, &fsField_, &fsUnit_, &datasheetResult_ }) + c->setVisible (! cal); + customLevel_.setEnabled (! measuring_); + customFreq_.setEnabled (! measuring_); + refCombo_.setEnabled (! measuring_); + updateApply(); + } + + void updateApply() + { + const bool ready = calibratorMode() ? measuredCalDb_.has_value() : datasheetCalDb_.has_value(); + applyButton_.setEnabled (ready && ! measuring_); + const auto v = calibratorMode() ? measuredCalDb_ : datasheetCalDb_; + applyButton_.setButtonText (v ? "Apply " + juce::String (*v, 2) + " dB" : juce::String ("Apply")); + } + + void updateDatasheet() + { + double S = sensField_.getValue(); + if (sensUnit_.getSelectedId() == 2) + S = vib::calibration::mVperMs2FromMVperG (S); + const double fs = fsField_.getValue(); + const double vrms = fsUnit_.getSelectedId() == 2 ? vib::calibration::dBuToVrms (fs) : fs; + + datasheetCalDb_.reset(); + if (S > 0.0 && vrms > 0.0) + { + const double cal = vib::calibration::calDbFromDatasheet (vrms, S); + if (cal >= vib::calibration::kMinCalDb && cal <= vib::calibration::kMaxCalDb) + { + datasheetCalDb_ = cal; + datasheetResult_.setText (U ("Cal = 120 + 20·log10(√2 · ") + juce::String (vrms * 1000.0, 1) + + " mV / " + juce::String (S, 3) + U (" mV/(m/s²)) = ") + + juce::String (cal, 2) + U (" dB re 1 µm/s²\n") + + "Full-scale sine = " + formatAccel (vib::calibration::scale (cal) / std::sqrt (2.0)) + + " RMS", + juce::dontSendNotification); + } + else + { + datasheetResult_.setText (U ("Result outside 60–220 dB — check the values."), juce::dontSendNotification); + } + } + else + { + datasheetResult_.setText ("Enter sensitivity and interface full scale.", juce::dontSendNotification); + } + updateApply(); + } + + void toggleMeasurement() + { + if (measuring_) + { + processor_.cancelAccelCalibration(); + measuring_ = false; + resultLabel_.setText ("Measurement cancelled.", juce::dontSendNotification); + } + else + { + measuredCalDb_.reset(); + if (! processor_.startAccelCalibration (ch_, referenceHz())) + { + resultLabel_.setText ("Cannot start: the input is not available or the frequency is out of range.", + juce::dontSendNotification); + return; + } + measuring_ = true; + progressValue_ = 0.0; + resultLabel_.setText (U ("Measuring…"), juce::dontSendNotification); + } + measureButton_.setButtonText (measuring_ ? "Cancel" : "Measure"); + updateMode(); + } + + void timerCallback() override + { + const double calDb = processor_.getAccelCalDb (ch_); + const auto info = processor_.getAccelCalInfo (ch_); + currentLabel_.setText ("Current calibration: " + juce::String (calDb, 2) + U (" dB re 1 µm/s²") + + (info.isNotEmpty() ? " (" + info + ")" : juce::String (" (not calibrated yet)")), + juce::dontSendNotification); + const double rms = processor_.getInputRms (ch_); + levelLabel_.setText ("Input: " + formatDbfs (rms) + U (" · ") + formatAccel (rms * vib::calibration::scale (calDb)) + + " RMS with the current calibration", + juce::dontSendNotification); + + if (! measuring_) + return; + progressValue_ = processor_.getAccelCalibrationProgress(); + vib::CalibratorMeasurement::Result r; + if (! processor_.takeAccelCalibrationResult (r)) + return; + + measuring_ = false; + measureButton_.setButtonText ("Measure"); + using S = vib::CalibratorMeasurement::Status; + const juce::String meas = "Measured " + formatDbfs (r.rmsFS) + " at " + juce::String (r.freqHz, 1) + + U (" Hz, stability ±") + juce::String (r.fluctuationDb, 2) + " dB.\n"; + switch (r.status) + { + case S::Ok: + { + const double cal = vib::calibration::calDbFromCalibrator (r.rmsFS, referenceRms()); + if (cal >= vib::calibration::kMinCalDb && cal <= vib::calibration::kMaxCalDb) + { + measuredCalDb_ = cal; + resultLabel_.setText (meas + "New calibration: " + juce::String (cal, 2) + U (" dB re 1 µm/s² (") + + juce::String (cal - calDb, 2) + " dB change).", + juce::dontSendNotification); + } + else + { + resultLabel_.setText (meas + U ("The result is outside 60–220 dB."), juce::dontSendNotification); + } + break; + } + case S::Clipped: resultLabel_.setText (meas + U ("The input clips — reduce the interface gain."), juce::dontSendNotification); break; + case S::TooLow: resultLabel_.setText (meas + U ("No calibrator signal — check the sensor and the input."), juce::dontSendNotification); break; + case S::FrequencyOff: resultLabel_.setText (meas + U ("The frequency deviates more than ±5 % from ") + + juce::String (referenceHz(), 1) + " Hz.", juce::dontSendNotification); break; + case S::Unstable: resultLabel_.setText (meas + U ("The level fluctuates more than ±0.2 dB — hold the calibrator steady."), juce::dontSendNotification); break; + case S::Running: break; + } + updateMode(); + } + + void apply() + { + const auto v = calibratorMode() ? measuredCalDb_ : datasheetCalDb_; + if (! v) return; + processor_.setAccelCalDb (ch_, *v); + processor_.setAccelCalInfo (ch_, calibratorMode() ? "calibrator" : "datasheet"); + closeDialog(); + } + + void closeDialog() + { + if (auto* dw = findParentComponentOfClass()) + dw->exitModalState (0); + } + + SPLMeterAudioProcessor& processor_; + const int ch_; + Palette pal_; + bool measuring_ = false; + double progressValue_ = 0.0; + std::optional measuredCalDb_, datasheetCalDb_; + + juce::Label titleLabel_, currentLabel_, levelLabel_; + juce::TextButton calibratorTab_ { "Handheld calibrator" }, datasheetTab_ { "Datasheet" }; + juce::Label refLabel_, customLevelLabel_, customFreqLabel_, resultLabel_; + juce::ComboBox refCombo_; + NumberField customLevel_ { 0.001, 1000.0, 3, U ("m/s²") }, customFreq_ { 1.0, 10000.0, 1, "Hz" }; + juce::TextButton measureButton_ { "Measure" }; + juce::ProgressBar progress_ { progressValue_ }; + juce::Label sensLabel_, fsLabel_, datasheetResult_; + NumberField sensField_ { 0.001, 100000.0, 3 }, fsField_ { -60.0, 100.0, 3 }; + juce::ComboBox sensUnit_, fsUnit_; + juce::TextButton applyButton_ { "Apply" }, closeButton_ { "Close" }; + + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CalibrationComponent) +}; + +//============================================================================== +// One row of the inputs table +class InputRow : public juce::Component +{ +public: + std::function onCalibrate; + + InputRow (SPLMeterAudioProcessor& p, int channel) : processor_ (p), ch_ (channel) + { + addAndMakeVisible (nameLabel_); + for (int r = 0; r <= (int) SensorRole::Off; ++r) + roleCombo_.addItem (roleName ((SensorRole) r), r + 1); + roleCombo_.onChange = [this] + { + processor_.setChannelRole (ch_, SensorConfig::fromInt (roleCombo_.getSelectedId() - 1)); + }; + addAndMakeVisible (roleCombo_); + addAndMakeVisible (level_); + addAndMakeVisible (levelText_); + levelText_.setJustificationType (juce::Justification::centredRight); + calField_.onValueChange = [this] (double v) + { + processor_.setAccelCalDb (ch_, v); + processor_.setAccelCalInfo (ch_, "manual"); + }; + addAndMakeVisible (calField_); + calButton_.onClick = [this] { if (onCalibrate) onCalibrate (ch_); }; + addAndMakeVisible (calButton_); + addAndMakeVisible (calInfo_); + for (auto* l : { &nameLabel_, &levelText_, &calInfo_ }) + l->setFont (juce::Font (juce::FontOptions().withHeight (13.0f))); + } + + int channel() const noexcept { return ch_; } + + void applyPalette (const Palette& p) + { + pal_ = p; + nameLabel_.setColour (juce::Label::textColourId, p.text); + levelText_.setColour (juce::Label::textColourId, p.subtext); + calInfo_.setColour (juce::Label::textColourId, p.subtext); + calField_.style (p); + p.style (roleCombo_); + level_.setPalette (p); + calButton_.setColour (juce::TextButton::buttonColourId, p.field); + calButton_.setColour (juce::TextButton::textColourOffId, p.text); + repaint(); + } + + // Columns are shared with the table header + static void columns (juce::Rectangle r, juce::Rectangle (&out)[6]) + { + out[0] = r.removeFromLeft (110); // channel + out[1] = r.removeFromLeft (150); // role + out[2] = r.removeFromLeft (190); // level bar + out[3] = r.removeFromLeft (110); // level text + out[4] = r.removeFromLeft (100); // cal (dB) + out[5] = r; // calibrate + info + } + + void resized() override + { + juce::Rectangle c[6]; + columns (getLocalBounds(), c); + nameLabel_.setBounds (c[0]); + roleCombo_.setBounds (c[1].reduced (2, 3)); + level_.setBounds (c[2].reduced (6, 0)); + levelText_.setBounds (c[3]); + calField_.setBounds (c[4].reduced (6, 4)); + auto last = c[5]; + calButton_.setBounds (last.removeFromLeft (100).reduced (2, 3)); + calInfo_.setBounds (last.withTrimmedLeft (6)); + } + + void paint (juce::Graphics& g) override + { + if (invalid_) + { + g.setColour (pal_.bad.withAlpha (0.18f)); + g.fillRoundedRectangle (getLocalBounds().toFloat(), 4.0f); + } + } + + // Called by the window's timer + void refresh (bool invalid) + { + const auto role = processor_.getChannelRole (ch_); + const bool accel = SensorConfig::isAccel (role); + nameLabel_.setText (processor_.getChannelName (ch_), juce::dontSendNotification); + if (! roleCombo_.isPopupActive()) + roleCombo_.setSelectedId ((int) role + 1, juce::dontSendNotification); + + const float rms = processor_.getInputRms (ch_); + const float peak = processor_.takeInputPeak (ch_); + level_.setLevels (rms, peak); + + calField_.setVisible (accel); + calButton_.setVisible (accel); + calInfo_.setVisible (accel); + if (accel) + { + const double calDb = processor_.getAccelCalDb (ch_); + if (! calField_.isBeingEdited()) + calField_.setValue (calDb); + levelText_.setText (formatAccel (rms * vib::calibration::scale (calDb)), juce::dontSendNotification); + const auto info = processor_.getAccelCalInfo (ch_); + calInfo_.setText (info.isNotEmpty() ? info : juce::String ("not calibrated"), juce::dontSendNotification); + } + else + { + levelText_.setText (role == SensorRole::Off ? juce::String() : formatDbfs (rms), juce::dontSendNotification); + } + level_.setAlpha (role == SensorRole::Off ? 0.4f : 1.0f); + + if (invalid != invalid_) { invalid_ = invalid; repaint(); } + } + +private: + SPLMeterAudioProcessor& processor_; + const int ch_; + Palette pal_ = Palette::get (false); + bool invalid_ = false; + + juce::Label nameLabel_, levelText_, calInfo_; + juce::ComboBox roleCombo_; + LevelBar level_; + NumberField calField_ { vib::calibration::kMinCalDb, vib::calibration::kMaxCalDb, 2, "dB" }; + juce::TextButton calButton_ { U ("Calibrate…") }; +}; + +//============================================================================== +class InputsComponent : public juce::Component, + private juce::Timer +{ +public: + InputsComponent (SPLMeterAudioProcessor& p, bool light) : processor_ (p) + { + auto setupLabel = [this] (juce::Label& l, const juce::String& text, float h = 13.0f, bool bold = false) + { + l.setText (text, juce::dontSendNotification); + auto f = juce::FontOptions().withHeight (h); + l.setFont (juce::Font (bold ? f.withStyle ("Bold") : f)); + l.setInterceptsMouseClicks (false, false); + addAndMakeVisible (l); + }; + + setupLabel (inputsTitle_, "INPUTS", 11.0f, true); + setupLabel (inputsDesc_, "Assign a role to each active (not muted) input. Only Mic inputs feed the SPL meter; " + "accelerometer inputs bypass the mix, bandpass and correction filter.", 11.5f); + setupLabel (statusLabel_, {}, 13.0f, true); + const juce::String headers[6] = { "Channel", "Role", "Level", "", U ("Cal (dB re 1 µm/s²)"), "Calibration" }; + for (int i = 0; i < 6; ++i) + setupLabel (headerLabels_[i], headers[i], 11.0f, true); + addAndMakeVisible (viewport_); + viewport_.setViewedComponent (&rowsHolder_, false); + viewport_.setScrollBarsShown (true, false); + + // --- Accelerometer group --- + setupLabel (accelTitle_, "ACCELEROMETER", 11.0f, true); + setupLabel (accelDesc_, "Applies to all axes of the sensor. Changes restart the vibration readings.", 11.5f); + // Profile (spec §6): applying one sets everything below; edits make it custom + setupLabel (profileLabel_, "Profile"); + for (int p = 0; p < (int) vib::Profile::NumProfiles; ++p) + profileCombo_.addItem (juce::String::fromUTF8 (vib::profileDefinition ((vib::Profile) p).name), p + 1); + profileCombo_.setTooltip ("Sets quantity, weighting, filters, k-factors, time constant, main value and unit"); + profileCombo_.onChange = [this] + { + if (profileCombo_.getSelectedId() > 0) + processor_.applyVibrationProfile ((vib::Profile) (profileCombo_.getSelectedId() - 1)); + }; + addAndMakeVisible (profileCombo_); + + setupLabel (mainLabel_, "Main value"); + mainCombo_.addItem (U ("\xe2\x80\x94"), 1); + mainCombo_.addItem ("Max axis RMS", 2); + mainCombo_.addItem (U ("Max k\xc2\xb7" "axis RMS"), 3); + mainCombo_.addItem (U ("\xce\xa3 RMS (vector sum)"), 4); + mainCombo_.addItem ("Max axis peak since reset", 5); + mainCombo_.addItem (U ("Max k\xc2\xb7" "a_w over the measurement"), 6); + mainCombo_.addItem (U ("\xce\xa3 a_w over the measurement"), 7); + mainCombo_.addItem ("Max axis KB_Fmax", 8); + mainCombo_.onChange = [this] { auto s = processor_.getVibrationSettings(); + s.main = (vib::MainValue) (mainCombo_.getSelectedId() - 1); + processor_.setVibrationSettings (s); }; + addAndMakeVisible (mainCombo_); + + setupLabel (quantityLabel_, "Quantity"); + quantityCombo_.addItem ("Acceleration", 1); + quantityCombo_.addItem ("Velocity", 2); + quantityCombo_.addItem ("Displacement", 3); + quantityCombo_.onChange = [this] { auto s = processor_.getVibrationSettings(); + s.quantity = (vib::Quantity) (quantityCombo_.getSelectedId() - 1); + processor_.setVibrationSettings (s); }; + addAndMakeVisible (quantityCombo_); + + setupLabel (highPassLabel_, "High-pass"); + highPass_.onValueChange = [this] (double v) { auto s = processor_.getVibrationSettings(); + s.highPassHz = v; processor_.setVibrationSettings (s); }; + addAndMakeVisible (highPass_); + + setupLabel (tauLabel_, U ("RMS τ")); + tauCombo_.setTooltip ("Time constant of the running RMS (ISO 2631-1 uses 1 s)"); + for (int i = 0; i < (int) kTaus.size(); ++i) + tauCombo_.addItem (juce::String (kTaus[(size_t) i], kTaus[(size_t) i] < 1.0 ? 3 : 0) + " s", i + 1); + tauCombo_.onChange = [this] { auto s = processor_.getVibrationSettings(); + s.tauSec = kTaus[(size_t) juce::jlimit (0, (int) kTaus.size() - 1, tauCombo_.getSelectedId() - 1)]; + processor_.setVibrationSettings (s); }; + addAndMakeVisible (tauCombo_); + + const char* axisNames[3] = { "Weighting X", "Weighting Y", "Weighting Z" }; + const char* kNames[3] = { "k x", "k y", "k z" }; + for (int a = 0; a < 3; ++a) + { + setupLabel (weightingLabels_[a], axisNames[a]); + for (int w = 0; w <= (int) vib::Weighting::KB; ++w) + weightingCombos_[a].addItem (weightingShortName ((vib::Weighting) w), w + 1); + weightingCombos_[a].onChange = [this, a] { auto s = processor_.getVibrationSettings(); + s.weighting[a] = (vib::Weighting) (weightingCombos_[a].getSelectedId() - 1); + weightingCombos_[a].setTooltip (weightingName (s.weighting[a])); + processor_.setVibrationSettings (s); }; + addAndMakeVisible (weightingCombos_[a]); + + setupLabel (kLabels_[a], kNames[a]); + kFields_[a].onValueChange = [this, a] (double v) { auto s = processor_.getVibrationSettings(); + s.k[a] = v; processor_.setVibrationSettings (s); }; + addAndMakeVisible (kFields_[a]); + } + + setupLabel (bandLabel_, "Band limit"); + bandLow_.onValueChange = [this] (double v) { auto s = processor_.getVibrationSettings(); + s.bandLowHz = v; processor_.setVibrationSettings (s); }; + bandHigh_.onValueChange = [this] (double v) { auto s = processor_.getVibrationSettings(); + s.bandHighHz = v; processor_.setVibrationSettings (s); }; + addAndMakeVisible (bandLow_); + addAndMakeVisible (bandHigh_); + + setupLabel (serialLabel_, "Sensor serial"); + serialEditor_.onTextChange = [this] { auto i = processor_.getAccelSensorInfo(); + i.serial = serialEditor_.getText().trim(); + processor_.setAccelSensorInfo (i); }; + addAndMakeVisible (serialEditor_); + setupLabel (exposureLabel_, "Exposure / day"); + exposure_.setTooltip (U ("Daily exposure time T for A(8) = a_w \xc2\xb7 sqrt(T / 8 h)")); + exposure_.onValueChange = [this] (double v) { auto i = processor_.getAccelSensorInfo(); + i.exposureHours = v; processor_.setAccelSensorInfo (i); }; + addAndMakeVisible (exposure_); + setupLabel (rangeLabel_, "Usable range"); + lowerLimit_.onValueChange = [this] (double v) { auto i = processor_.getAccelSensorInfo(); + i.lowerLimitHz = v; processor_.setAccelSensorInfo (i); }; + upperLimit_.onValueChange = [this] (double v) { auto i = processor_.getAccelSensorInfo(); + i.upperLimitHz = v; processor_.setAccelSensorInfo (i); }; + addAndMakeVisible (lowerLimit_); + addAndMakeVisible (upperLimit_); + + // --- Assessment group (spec §9.3): the controls depend on the profile --- + setupLabel (assessTitle_, "ASSESSMENT", 11.0f, true); + setupLabel (assessDesc_, {}, 11.5f); + for (int i = 0; i < kAssessCombos; ++i) + { + setupLabel (assessComboLabels_[i], {}); + assessCombos_[i].onChange = [this, i] + { + if (assessCombos_[i].getSelectedId() <= 0 || i >= (int) comboSetters_.size()) return; + auto l = processor_.getAssessmentLimits(); + comboSetters_[(size_t) i] (l, assessCombos_[i].getSelectedId() - 1); + processor_.setAssessmentLimits (l); + loadAssessment(); + }; + addAndMakeVisible (assessCombos_[i]); + } + for (int i = 0; i < kAssessFields; ++i) + { + setupLabel (assessFieldLabels_[i], {}); + assessFields_[i].onValueChange = [this, i] (double v) + { + if (i >= (int) fieldMembers_.size()) return; + auto l = processor_.getAssessmentLimits(); + l.*fieldMembers_[(size_t) i] = v; + processor_.setAssessmentLimits (l); + }; + addAndMakeVisible (assessFields_[i]); + } + assessDefaults_.setTooltip ("Reload the reference values of the selected standard, group, zone or line"); + assessDefaults_.onClick = [this] + { + auto l = processor_.getAssessmentLimits(); + vib::applyWholeBodyPreset (l, l.wbPreset); + vib::applyMachineryPreset (l, l.machGroup, l.machFoundation); + vib::applyDin4150_2Preset (l, l.din2Zone, l.din2Night); + vib::applyDin4150_3Preset (l, l.din3Line, l.din3Location, l.din3LongTerm); + const auto d = vib::defaultAssessmentLimits(); + l.haAction = d.haAction; l.haLimit = d.haLimit; + processor_.setAssessmentLimits (l); + loadAssessment(); + }; + addAndMakeVisible (assessDefaults_); + + setLightMode (light); + loadAccelSettings(); + rebuildRows(); + timerCallback(); + startTimerHz (20); + } + + ~InputsComponent() override + { + stopTimer(); + closeCalibration(); // the dialog refers to the processor + } + + void setLightMode (bool light) + { + light_ = light; + pal_ = Palette::get (light); + for (auto* l : { &inputsTitle_, &accelTitle_ }) + l->setColour (juce::Label::textColourId, pal_.subtext); + for (auto* l : { &inputsDesc_, &accelDesc_ }) + l->setColour (juce::Label::textColourId, pal_.subtext.withAlpha (0.85f)); + for (auto& l : headerLabels_) + l.setColour (juce::Label::textColourId, pal_.subtext); + for (auto* l : { &profileLabel_, &mainLabel_, &exposureLabel_, + &quantityLabel_, &highPassLabel_, &tauLabel_, &bandLabel_, &serialLabel_, &rangeLabel_, + &weightingLabels_[0], &weightingLabels_[1], &weightingLabels_[2], + &kLabels_[0], &kLabels_[1], &kLabels_[2] }) + l->setColour (juce::Label::textColourId, pal_.text); + for (auto* f : { &exposure_, &highPass_, &bandLow_, &bandHigh_, &lowerLimit_, &upperLimit_, + &kFields_[0], &kFields_[1], &kFields_[2] }) + f->style (pal_); + for (auto* c : { &profileCombo_, &mainCombo_, &quantityCombo_, &tauCombo_, + &weightingCombos_[0], &weightingCombos_[1], &weightingCombos_[2] }) + pal_.style (*c); + assessTitle_.setColour (juce::Label::textColourId, pal_.subtext); + assessDesc_.setColour (juce::Label::textColourId, pal_.subtext.withAlpha (0.85f)); + for (auto& l : assessComboLabels_) l.setColour (juce::Label::textColourId, pal_.text); + for (auto& l : assessFieldLabels_) l.setColour (juce::Label::textColourId, pal_.text); + for (auto& c : assessCombos_) pal_.style (c); + for (auto& f : assessFields_) f.style (pal_); + assessDefaults_.setColour (juce::TextButton::buttonColourId, pal_.field); + assessDefaults_.setColour (juce::TextButton::textColourOffId, pal_.text); + serialEditor_.setColour (juce::TextEditor::backgroundColourId, pal_.field); + serialEditor_.setColour (juce::TextEditor::textColourId, pal_.text); + serialEditor_.setColour (juce::TextEditor::outlineColourId, pal_.border); + for (auto& row : rows_) + row->applyPalette (pal_); + repaint(); + } + + void paint (juce::Graphics& g) override + { + g.fillAll (pal_.bg); + for (auto* b : { &inputsCard_, &accelCard_, &assessCard_ }) + { + if (b->isEmpty()) continue; + g.setColour (pal_.card); + g.fillRoundedRectangle (b->toFloat(), 10.0f); + g.setColour (pal_.border); + g.drawRoundedRectangle (b->toFloat(), 10.0f, 1.0f); + } + } + + void resized() override + { + constexpr int margin = 16, pad = 14, rowH = 30; + auto page = getLocalBounds().reduced (margin); + + // Accelerometer and assessment cards at the bottom (fixed height), inputs card fills the rest + accelCard_ = {}; + assessCard_ = {}; + if (accelVisible_) + { + assessCard_ = page.removeFromBottom (pad * 2 + 16 + 3 + 16 + 10 + 3 * 28 + 2 * 6); + page.removeFromBottom (16); + { + auto c = assessCard_.reduced (pad); + auto titleRow = c.removeFromTop (16); + assessDefaults_.setBounds (titleRow.removeFromRight (90).withHeight (22).translated (0, -2)); + assessTitle_.setBounds (titleRow); + c.removeFromTop (3); + assessDesc_.setBounds (c.removeFromTop (16)); + c.removeFromTop (10); + const int colW = c.getWidth() / 3; + auto cell = [&] (juce::Rectangle row, int col, juce::Label& label, juce::Component& comp) + { + auto r = row.withX (row.getX() + col * colW).withWidth (colW - 12); + label.setBounds (r.removeFromLeft (128)); + comp.setBounds (r.reduced (0, 2)); + }; + auto row = c.removeFromTop (28); + for (int i = 0; i < kAssessCombos; ++i) + cell (row, i, assessComboLabels_[i], assessCombos_[i]); + for (int r = 0; r < 2; ++r) + { + c.removeFromTop (6); + row = c.removeFromTop (28); + for (int i = 0; i < 3; ++i) + cell (row, i, assessFieldLabels_[r * 3 + i], assessFields_[r * 3 + i]); + } + } + + accelCard_ = page.removeFromBottom (pad * 2 + 16 + 3 + 16 + 10 + 6 * 28 + 5 * 6); + page.removeFromBottom (16); + auto c = accelCard_.reduced (pad); + accelTitle_.setBounds (c.removeFromTop (16)); + c.removeFromTop (3); + accelDesc_.setBounds (c.removeFromTop (16)); + c.removeFromTop (10); + + const int colW = c.getWidth() / 3; + auto cell = [&] (juce::Rectangle row, int col, juce::Label& label, juce::Component& comp, int labelW = 96) + { + auto r = row.withX (row.getX() + col * colW).withWidth (colW - 12); + label.setBounds (r.removeFromLeft (labelW)); + comp.setBounds (r.reduced (0, 2)); + }; + auto row = c.removeFromTop (28); + { + auto r = row.withWidth (2 * colW - 12); + profileLabel_.setBounds (r.removeFromLeft (96)); + profileCombo_.setBounds (r.reduced (0, 2)); + } + cell (row, 2, mainLabel_, mainCombo_); + c.removeFromTop (6); + row = c.removeFromTop (28); + cell (row, 0, quantityLabel_, quantityCombo_); + cell (row, 1, highPassLabel_, highPass_); + cell (row, 2, tauLabel_, tauCombo_); + c.removeFromTop (6); + row = c.removeFromTop (28); + for (int a = 0; a < 3; ++a) + cell (row, a, weightingLabels_[a], weightingCombos_[a]); + c.removeFromTop (6); + row = c.removeFromTop (28); + for (int a = 0; a < 3; ++a) + cell (row, a, kLabels_[a], kFields_[a]); + c.removeFromTop (6); + row = c.removeFromTop (28); + cell (row, 0, serialLabel_, serialEditor_); + { + auto r = row.withX (row.getX() + colW).withWidth (colW - 12); + rangeLabel_.setBounds (r.removeFromLeft (96)); + upperLimit_.setBounds (r.removeFromRight ((r.getWidth() - 8) / 2).reduced (0, 2)); + r.removeFromRight (8); + lowerLimit_.setBounds (r.reduced (0, 2)); + } + { + auto r = row.withX (row.getX() + 2 * colW).withWidth (colW - 12); + bandLabel_.setBounds (r.removeFromLeft (96)); + bandHigh_.setBounds (r.removeFromRight ((r.getWidth() - 8) / 2).reduced (0, 2)); + r.removeFromRight (8); + bandLow_.setBounds (r.reduced (0, 2)); + } + c.removeFromTop (6); + row = c.removeFromTop (28); + cell (row, 0, exposureLabel_, exposure_); + } + + inputsCard_ = page; + auto c = page.reduced (pad); + inputsTitle_.setBounds (c.removeFromTop (16)); + c.removeFromTop (3); + inputsDesc_.setBounds (c.removeFromTop (16)); + c.removeFromTop (8); + statusLabel_.setBounds (c.removeFromTop (20)); + c.removeFromTop (8); + + juce::Rectangle cols[6]; + InputRow::columns (c.removeFromTop (18).withTrimmedRight (viewport_.getScrollBarThickness()), cols); + for (int i = 0; i < 6; ++i) + headerLabels_[i].setBounds (cols[i]); + c.removeFromTop (4); + viewport_.setBounds (c); + + const int w = c.getWidth() - viewport_.getScrollBarThickness(); + rowsHolder_.setSize (w, (int) rows_.size() * rowH); + for (size_t i = 0; i < rows_.size(); ++i) + rows_[i]->setBounds (0, (int) i * rowH, w, rowH - 2); + } + +private: + static constexpr std::array kTaus { 0.125, 0.5, 1.0, 2.0, 8.0 }; + + int numInputs() const { return juce::jmin (processor_.getTotalNumInputChannels(), SensorConfig::kMaxInputs); } + + // Inputs listed in the table: every active (not muted) input, plus muted ones + // that still have a sensor role, so a configured input never disappears + std::vector listedChannels() const + { + std::vector list; + for (int ch = 0; ch < numInputs(); ++ch) + { + const bool muted = processor_.apvts.getRawParameterValue ("channelMute" + juce::String (ch))->load() > 0.5f; + if (! muted || processor_.getChannelRole (ch) != SensorRole::Mic) + list.push_back (ch); + } + return list; + } + + void rebuildRows() + { + rows_.clear(); + listed_ = listedChannels(); + for (int ch : listed_) + { + auto row = std::make_unique (processor_, ch); + row->applyPalette (pal_); + row->onCalibrate = [this] (int c) { openCalibration (c); }; + rowsHolder_.addAndMakeVisible (*row); + rows_.push_back (std::move (row)); + } + resized(); + } + + void closeCalibration() + { + delete calDialog_.getComponent(); + } + + void openCalibration (int ch) + { + closeCalibration(); + juce::DialogWindow::LaunchOptions o; + o.content.setOwned (new CalibrationComponent (processor_, ch, light_)); + o.dialogTitle = "Calibrate " + processor_.getChannelName (ch); + o.dialogBackgroundColour = pal_.bg; + o.escapeKeyTriggersCloseButton = true; + o.useNativeTitleBar = false; + o.resizable = false; + o.componentToCentreAround = this; + calDialog_ = o.launchAsync(); + } + + // Reflects the stored settings in the controls (not while one is being edited) + void loadAccelSettings() + { + const auto s = processor_.getVibrationSettings(); + if (! profileCombo_.isPopupActive()) + { + const auto base = processor_.getVibrationProfile(); + if (base == vib::Profile::Custom || vib::settingsMatchProfile (s, base)) + profileCombo_.setSelectedId ((int) base + 1, juce::dontSendNotification); + else if (profileCombo_.getText() != processor_.getVibrationProfileLabel()) + profileCombo_.setText (processor_.getVibrationProfileLabel(), juce::dontSendNotification); + } + if (! mainCombo_.isPopupActive()) + mainCombo_.setSelectedId ((int) s.main + 1, juce::dontSendNotification); + quantityCombo_.setSelectedId ((int) s.quantity + 1, juce::dontSendNotification); + if (! highPass_.isBeingEdited()) highPass_.setValue (s.highPassHz); + int tauIdx = 0; + for (int i = 0; i < (int) kTaus.size(); ++i) + if (std::abs (kTaus[(size_t) i] - s.tauSec) < std::abs (kTaus[(size_t) tauIdx] - s.tauSec)) tauIdx = i; + tauCombo_.setSelectedId (tauIdx + 1, juce::dontSendNotification); + bool anyBand = false; + for (int a = 0; a < 3; ++a) + { + if (! weightingCombos_[a].isPopupActive()) + { + weightingCombos_[a].setSelectedId ((int) s.weighting[a] + 1, juce::dontSendNotification); + weightingCombos_[a].setTooltip (weightingName (s.weighting[a])); + } + if (! kFields_[a].isBeingEdited()) kFields_[a].setValue (s.k[a]); + anyBand = anyBand || s.weighting[a] == vib::Weighting::BandLimit; + } + if (! bandLow_.isBeingEdited()) bandLow_.setValue (s.bandLowHz); + if (! bandHigh_.isBeingEdited()) bandHigh_.setValue (s.bandHighHz); + bandLabel_.setAlpha (anyBand ? 1.0f : 0.4f); + bandLow_.setEnabled (anyBand); + bandHigh_.setEnabled (anyBand); + + const auto info = processor_.getAccelSensorInfo(); + if (! serialEditor_.hasKeyboardFocus (true)) + serialEditor_.setText (info.serial, false); + if (! lowerLimit_.isBeingEdited()) lowerLimit_.setValue (info.lowerLimitHz); + if (! upperLimit_.isBeingEdited()) upperLimit_.setValue (info.upperLimitHz); + if (! exposure_.isBeingEdited()) exposure_.setValue (info.exposureHours); + } + + void timerCallback() override + { + if (listedChannels() != listed_) + rebuildRows(); + + const auto roles = processor_.getChannelRoles(); + const auto validity = processor_.getSensorValidity(); + const bool valid = SensorConfig::isValid (validity); + + // Status line + juce::String text; + juce::Colour col = pal_.subtext; + auto axisList = [&] + { + juce::StringArray parts; + const char* names[3] = { "X", "Y", "Z" }; + for (int a = 0; a < 3; ++a) + for (int ch = 0; ch < numInputs(); ++ch) + if (roles[(size_t) ch] == (SensorRole) ((int) SensorRole::AccelX + a)) + parts.add (juce::String (names[a]) + " = " + processor_.getChannelName (ch)); + return parts.joinIntoString (", "); + }; + switch (validity) + { + case SensorConfig::Validity::NoAccelerometer: + text = "No accelerometer assigned."; break; + case SensorConfig::Validity::Triaxial: + text = "Triaxial accelerometer: " + axisList(); col = pal_.ok; break; + case SensorConfig::Validity::Biaxial: + case SensorConfig::Validity::SingleAxis: + text = "Accelerometer axes: " + axisList(); col = pal_.ok; break; + case SensorConfig::Validity::Uniaxial: + for (int ch = 0; ch < numInputs(); ++ch) + if (roles[(size_t) ch] == SensorRole::AccelUniaxial) + text = "Uniaxial accelerometer on " + processor_.getChannelName (ch); + col = pal_.ok; break; + case SensorConfig::Validity::DuplicateAxis: + text = U ("An axis is assigned to more than one input — accelerometer inactive."); col = pal_.bad; break; + case SensorConfig::Validity::MixedKinds: + text = U ("Use either X/Y/Z or one uniaxial input (one sensor per session) — accelerometer inactive."); + col = pal_.bad; break; + } + bool anyMic = false; + for (int ch = 0; ch < numInputs(); ++ch) + anyMic = anyMic || roles[(size_t) ch] == SensorRole::Mic; + if (! anyMic && numInputs() > 0) + { + text << U (" No Mic input — the SPL meter has no signal."); + if (valid) col = pal_.warn; + } + if (listed_.empty()) + text = "All inputs are muted. Unmute inputs in Settings to assign roles."; + statusLabel_.setText (text, juce::dontSendNotification); + statusLabel_.setColour (juce::Label::textColourId, col); + + // Rows: with an invalid configuration, every accelerometer row is marked + for (auto& row : rows_) + row->refresh (! valid && SensorConfig::isAccel (roles[(size_t) row->channel()])); + + // Accelerometer group: shown when any input has an accelerometer role + bool anyAccel = false; + bool uniaxial = false; + for (int ch = 0; ch < numInputs(); ++ch) + { + anyAccel = anyAccel || SensorConfig::isAccel (roles[(size_t) ch]); + uniaxial = uniaxial || roles[(size_t) ch] == SensorRole::AccelUniaxial; + } + if (anyAccel != accelVisible_ || uniaxial != uniaxial_) + { + accelVisible_ = anyAccel; + uniaxial_ = uniaxial; + for (juce::Component* comp : accelComponents()) + comp->setVisible (anyAccel); + assessKey_ = -1; // loadAssessment() re-applies the per-profile visibility + for (int i = 0; i < kAssessCombos; ++i) { assessComboLabels_[i].setVisible (false); assessCombos_[i].setVisible (false); } + for (int i = 0; i < kAssessFields; ++i) { assessFieldLabels_[i].setVisible (false); assessFields_[i].setVisible (false); } + assessDefaults_.setVisible (false); + // Uniaxial: one weighting, no vector sum + weightingLabels_[0].setText (uniaxial ? "Weighting" : "Weighting X", juce::dontSendNotification); + for (int a = 1; a < 3; ++a) + { + weightingLabels_[a].setVisible (anyAccel && ! uniaxial); + weightingCombos_[a].setVisible (anyAccel && ! uniaxial); + } + for (int a = 0; a < 3; ++a) + { + kLabels_[a].setVisible (anyAccel && ! uniaxial); + kFields_[a].setVisible (anyAccel && ! uniaxial); + } + resized(); + repaint(); + } + if (anyAccel) + { + loadAccelSettings(); + loadAssessment(); + } + } + + //========================================================================== + // Assessment group: which controls a profile uses (spec §9.3) + using Limits = vib::AssessmentLimits; + using Setter = std::function; + + struct AssessLayout + { + juce::String desc; + std::vector> combos; // label, items + std::vector setters; + std::vector> fields; // label, member + }; + + static AssessLayout assessLayout (vib::Profile p, const Limits& l) + { + AssessLayout a; + switch (p) + { + case vib::Profile::WholeBodyHealth: + a.desc = U ("A(8) of the highest k·" "a_w, or the daily VDV; exposure time from the accelerometer group."); + a.combos = { { "Standard", { "EU 2002/44/EC", U ("Germany (LärmVibrationsArbSchV)") } }, + { "Criterion", { "A(8)", "VDV" } } }; + a.setters = { [] (Limits& x, int v) { vib::applyWholeBodyPreset (x, (vib::WholeBodyPreset) v); }, + [] (Limits& x, int v) { x.wbCriterion = (vib::WholeBodyCriterion) v; } }; + a.fields = { { U ("Action (m/s²)"), &Limits::wbAction }, + { U ("Limit X/Y (m/s²)"), &Limits::wbLimitXY }, + { U ("Limit Z (m/s²)"), &Limits::wbLimitZ }, + { "VDV action", &Limits::wbVdvAction }, + { "VDV limit", &Limits::wbVdvLimit } }; + break; + case vib::Profile::HandArm: + a.desc = "A(8) of a_hv against the EU 2002/44/EC action and limit values."; + a.fields = { { U ("Action (m/s²)"), &Limits::haAction }, + { U ("Limit (m/s²)"), &Limits::haLimit } }; + break; + case vib::Profile::WholeBodyComfort: + a.desc = "ISO 2631-1 Annex C comfort scale for a_v (informative, no limit values)."; + break; + case vib::Profile::MachineryIso20816: + case vib::Profile::MachineryLowSpeed: + a.desc = U ("Largest axis v_rms over the measurement → zones A–" "D (ISO 10816-3 / 20816-3)."); + a.combos = { { "Machine group", { U ("Group 1 (> 300 kW)"), U ("Group 2 (15–" "300 kW)") } }, + { "Foundation", { "Rigid", "Flexible" } } }; + a.setters = { [] (Limits& x, int v) { vib::applyMachineryPreset (x, (vib::MachineGroup) v, x.machFoundation); }, + [] (Limits& x, int v) { vib::applyMachineryPreset (x, x.machGroup, (vib::Foundation) v); } }; + a.fields = { { "A/B (mm/s)", &Limits::machAB }, { "B/C (mm/s)", &Limits::machBC }, { "C/D (mm/s)", &Limits::machCD } }; + break; + case vib::Profile::BuildingPerception: + a.desc = U ("DIN 4150-2: KB_Fmax against A_u / A_o, then KB_FTr = KB_FTm · sqrt(T_e / T_r) against A_r."); + a.combos = { { "Zone", { "Industrial (GI)", "Commercial (GE)", "Mixed (MI, MD, MK)", + "Residential (WR, WA)", "Hospitals, spa (SO)" } }, + { "Period", { U ("Day (T_r 16 h)"), U ("Night (T_r 8 h)") } } }; + a.setters = { [] (Limits& x, int v) { vib::applyDin4150_2Preset (x, (vib::Din4150Zone) v, x.din2Night); }, + [] (Limits& x, int v) { vib::applyDin4150_2Preset (x, x.din2Zone, v == 1); } }; + a.fields = { { "A_u", &Limits::din2Au }, { "A_o", &Limits::din2Ao }, { "A_r", &Limits::din2Ar }, + { "T_e exposure (h)", &Limits::din2ExposureHours } }; + break; + case vib::Profile::BuildingStructural: + a.desc = l.din3Location == vib::Din4150Location::Foundation + ? U ("DIN 4150-3: PPV per axis against the value at its dominant frequency (linear between 10, 50 and 100 Hz).") + : U ("DIN 4150-3: PPV against one value for all frequencies (top floor: X/Y, floor slab: Z)."); + a.combos = { { "Building", { "Line 1 commercial", "Line 2 residential", "Line 3 sensitive" } }, + { "Duration", { "Short-term", "Long-term" } }, + { "Location", { "Foundation", "Top floor, horizontal", "Floor slab, vertical" } } }; + a.setters = { [] (Limits& x, int v) { vib::applyDin4150_3Preset (x, (vib::Din4150Line) v, x.din3Location, x.din3LongTerm); }, + [] (Limits& x, int v) { vib::applyDin4150_3Preset (x, x.din3Line, x.din3Location, v == 1); }, + [] (Limits& x, int v) { vib::applyDin4150_3Preset (x, x.din3Line, (vib::Din4150Location) v, x.din3LongTerm); } }; + if (l.din3Location == vib::Din4150Location::Foundation) + a.fields = { { U ("1–" "10 Hz (mm/s)"), &Limits::din3At10 }, + { "50 Hz (mm/s)", &Limits::din3At50 }, + { "100 Hz (mm/s)", &Limits::din3At100 } }; + else + a.fields = { { "Guideline (mm/s)", &Limits::din3Single } }; + break; + case vib::Profile::Custom: + case vib::Profile::StructureBorne: + case vib::Profile::NumProfiles: + a.desc = "No assessment for this profile."; + break; + } + return a; + } + + static int comboValue (vib::Profile p, const Limits& l, int i) + { + switch (p) + { + case vib::Profile::WholeBodyHealth: return i == 0 ? (int) l.wbPreset : (int) l.wbCriterion; + case vib::Profile::MachineryIso20816: + case vib::Profile::MachineryLowSpeed: return i == 0 ? (int) l.machGroup : (int) l.machFoundation; + case vib::Profile::BuildingPerception: return i == 0 ? (int) l.din2Zone : (l.din2Night ? 1 : 0); + case vib::Profile::BuildingStructural: return i == 0 ? (int) l.din3Line : i == 1 ? (l.din3LongTerm ? 1 : 0) + : (int) l.din3Location; + default: break; + } + return 0; + } + + void loadAssessment() + { + const auto p = processor_.getVibrationProfile(); + const auto l = processor_.getAssessmentLimits(); + const int key = (int) p * 16 + (int) l.din3Location; + if (key != assessKey_) + { + assessKey_ = key; + const auto a = assessLayout (p, l); + assessDesc_.setText (a.desc, juce::dontSendNotification); + comboSetters_ = a.setters; + for (int i = 0; i < kAssessCombos; ++i) + { + const bool used = i < (int) a.combos.size(); + assessCombos_[i].clear (juce::dontSendNotification); + if (used) + { + assessComboLabels_[i].setText (a.combos[(size_t) i].first, juce::dontSendNotification); + assessCombos_[i].addItemList (a.combos[(size_t) i].second, 1); + } + assessComboLabels_[i].setVisible (accelVisible_ && used); + assessCombos_[i].setVisible (accelVisible_ && used); + } + fieldMembers_.clear(); + for (int i = 0; i < kAssessFields; ++i) + { + const bool used = i < (int) a.fields.size(); + if (used) + { + assessFieldLabels_[i].setText (a.fields[(size_t) i].first, juce::dontSendNotification); + fieldMembers_.push_back (a.fields[(size_t) i].second); + } + assessFieldLabels_[i].setVisible (accelVisible_ && used); + assessFields_[i].setVisible (accelVisible_ && used); + } + assessDefaults_.setVisible (accelVisible_ && (! a.fields.empty())); + } + for (int i = 0; i < (int) comboSetters_.size(); ++i) + if (! assessCombos_[i].isPopupActive()) + assessCombos_[i].setSelectedId (comboValue (p, l, i) + 1, juce::dontSendNotification); + for (int i = 0; i < (int) fieldMembers_.size(); ++i) + if (! assessFields_[i].isBeingEdited()) + assessFields_[i].setValue (l.*fieldMembers_[(size_t) i]); + } + + std::vector accelComponents() + { + std::vector v { &accelTitle_, &accelDesc_, &profileLabel_, &profileCombo_, + &mainLabel_, &mainCombo_, &quantityLabel_, &quantityCombo_, + &highPassLabel_, &highPass_, &tauLabel_, &tauCombo_, + &bandLabel_, &bandLow_, &bandHigh_, &serialLabel_, &serialEditor_, + &rangeLabel_, &lowerLimit_, &upperLimit_, &exposureLabel_, &exposure_, + &assessTitle_, &assessDesc_ }; + for (int a = 0; a < 3; ++a) + { + v.push_back (&weightingLabels_[a]); v.push_back (&weightingCombos_[a]); + v.push_back (&kLabels_[a]); v.push_back (&kFields_[a]); + } + return v; + } + + SPLMeterAudioProcessor& processor_; + bool light_ = false; + Palette pal_ = Palette::get (false); + bool accelVisible_ = true, uniaxial_ = true; // forces the first update + juce::Rectangle inputsCard_, accelCard_; + juce::Component::SafePointer calDialog_; + + juce::Label inputsTitle_, inputsDesc_, statusLabel_; + juce::Label headerLabels_[6]; + juce::Viewport viewport_; + juce::Component rowsHolder_; + std::vector> rows_; + std::vector listed_; + + juce::Label accelTitle_, accelDesc_; + juce::Label profileLabel_, mainLabel_; + juce::ComboBox profileCombo_, mainCombo_; + juce::Label quantityLabel_, highPassLabel_, tauLabel_, bandLabel_, serialLabel_, rangeLabel_; + juce::ComboBox quantityCombo_, tauCombo_; + NumberField highPass_ { 0.1, 20.0, 2, "Hz" }; + juce::Label weightingLabels_[3], kLabels_[3]; + juce::ComboBox weightingCombos_[3]; + NumberField kFields_[3] { { 0.0, 2.0, 2 }, { 0.0, 2.0, 2 }, { 0.0, 2.0, 2 } }; + NumberField bandLow_ { 0.1, 1000.0, 1, "Hz" }, bandHigh_ { 1.0, 20000.0, 0, "Hz" }; + juce::TextEditor serialEditor_; + NumberField lowerLimit_ { 0.01, 1000.0, 2, "Hz" }, upperLimit_ { 1.0, 100000.0, 0, "Hz" }; + juce::Label exposureLabel_; + NumberField exposure_ { 0.01, 24.0, 2, "h" }; + + static constexpr int kAssessCombos = 3, kAssessFields = 6; + juce::Rectangle assessCard_; + juce::Label assessTitle_, assessDesc_; + juce::Label assessComboLabels_[kAssessCombos], assessFieldLabels_[kAssessFields]; + juce::ComboBox assessCombos_[kAssessCombos]; + NumberField assessFields_[kAssessFields] { { 0.0, 1000.0, 2 }, { 0.0, 1000.0, 2 }, { 0.0, 1000.0, 2 }, + { 0.0, 1000.0, 2 }, { 0.0, 1000.0, 2 }, { 0.0, 1000.0, 2 } }; + juce::TextButton assessDefaults_ { "Defaults" }; + std::vector comboSetters_; + std::vector fieldMembers_; + int assessKey_ = -1; // profile + DIN 4150-3 location the controls are laid out for + + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputsComponent) +}; + +//============================================================================== +class InputsWindow : public juce::DocumentWindow +{ +public: + InputsWindow (SPLMeterAudioProcessor& p, bool light) + : juce::DocumentWindow ("Inputs and Sensors", juce::Colour (0xff1c1c1e), juce::DocumentWindow::closeButton) + { + setUsingNativeTitleBar (false); + content_ = new InputsComponent (p, light); + content_->setSize (960, 880); + setContentOwned (content_, true); + setResizable (true, false); + setResizeLimits (860, 640, 1600, 1400); + } + + void setLightMode (bool light) { content_->setLightMode (light); } + void closeButtonPressed() override { setVisible (false); } + +private: + InputsComponent* content_ = nullptr; // owned by the window + juce::TooltipWindow tooltipWindow_ { this, 500 }; + + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InputsWindow) +}; +} // namespace InputsUi diff --git a/Source/LogComponent.cpp b/Source/LogComponent.cpp index d90e459..95f9abf 100644 --- a/Source/LogComponent.cpp +++ b/Source/LogComponent.cpp @@ -24,6 +24,22 @@ const juce::Colour LogComponent::colTonality { 0xff30d158 }; // lime gree const juce::Colour LogComponent::colBassComfort { 0xff7d5fff }; // indigo const juce::Colour LogComponent::colFftIn1 { 0xff34c759 }; // green const juce::Colour LogComponent::colFftIn2 { 0xffff453a }; // red +const juce::Colour LogComponent::colVib[3] { juce::Colour (0xffac8e68), // X brown + juce::Colour (0xff63e6be), // Y mint + juce::Colour (0xff8fa8c8) }; // Z slate + +namespace +{ + // Smallest 1 / 2 / 5 × 10^n ≥ v + float niceCeil (float v) + { + if (v <= 0.0f) return 1.0f; + const float p = std::pow (10.0f, std::floor (std::log10 (v))); + for (float m : { 1.0f, 2.0f, 5.0f, 10.0f }) + if (m * p >= v * 0.9999f) return m * p; + return 10.0f * p; + } +} //============================================================================== LogComponent::LogComponent (SPLMeterAudioProcessor& p) @@ -86,6 +102,20 @@ LogComponent::LogComponent (SPLMeterAudioProcessor& p) setupPsychoBtn (tonalityVisButton, colTonality, PsychoMetric::Tonality); setupPsychoBtn (bassComfortVisButton, colBassComfort, PsychoMetric::BassComfort); + // Vibration toggles: Σ and Z on by default + { + const char* names[4] = { "Vib X", "Vib Y", "Vib Z", "Vib \xce\xa3" }; + const char* keys[4] = { "logShowVibX", "logShowVibY", "logShowVibZ", "logShowVibSum" }; + for (int i = 0; i < 4; ++i) + { + auto& b = vibVisButtons_[i]; + b.setButtonText (juce::String::fromUTF8 (names[i])); + setupVisBtn (b, i < 3 ? colVib[i] : juce::Colours::white, i >= 2); + b.setVisible (false); + UserPrefs::bind (processor, b, keys[i]); + } + } + // Restore the user's last series selection and record future changes UserPrefs::bind (processor, splVisButton, "logShowSPL"); UserPrefs::bind (processor, dbaVisButton, "logShowDBA"); @@ -181,8 +211,10 @@ void LogComponent::setLightMode (bool light) noexcept &roughnessVisButton, &fluctuationVisButton, &sharpnessVisButton, &loudnessVisButton, &annoyanceVisButton, &impulsivenessVisButton, - &tonalityVisButton, &bassComfortVisButton }) + &tonalityVisButton, &bassComfortVisButton, + &vibVisButtons_[0], &vibVisButtons_[1], &vibVisButtons_[2], &vibVisButtons_[3] }) b->setColour (juce::ToggleButton::textColourId, textPrimary); + vibVisButtons_[3].setColour (juce::ToggleButton::tickColourId, textPrimary); repaint(); } @@ -206,6 +238,9 @@ void LogComponent::resized() splVisButton.setBounds (juce::Rectangle (plotX, btnY, colW, btnH).toNearestInt()); dbaVisButton.setBounds (juce::Rectangle (plotX + colW, btnY, colW, btnH).toNearestInt()); dbcVisButton.setBounds (juce::Rectangle (plotX + colW*2, btnY, colW, btnH).toNearestInt()); + for (int i = 0; i < 4; ++i) // 4th column: vibration traces + vibVisButtons_[i].setBounds (juce::Rectangle (plotX + colW * 3 + colW / 4.0f * i, btnY, + colW / 4.0f, btnH).toNearestInt()); // Row 2 — psychoacoustic (4 columns) const float row2Y = btnY + btnH + rowGap; @@ -256,6 +291,21 @@ void LogComponent::timerCallback() if (fftEnabled_) computeFftBands(); rows = processor.copyLog(); + + // Live accelerometer, or playback of a recording with one + const bool vibAvailable = processor.isVibrationAvailable(); + const auto snap = processor.getVibrationSnapshot(); + const bool uniaxial = snap.valid ? snap.uniaxial + : processor.getSensorValidity() == SensorConfig::Validity::Uniaxial; + if (vibAvailable != vibAvailable_ || uniaxial != vibUniaxial_) + { + vibAvailable_ = vibAvailable; + vibUniaxial_ = uniaxial; + // Uniaxial: one trace, shown by the X toggle + vibVisButtons_[0].setButtonText (uniaxial ? "Vib" : "Vib X"); + for (int i = 0; i < 4; ++i) + vibVisButtons_[i].setVisible (vibAvailable && (i == 0 || ! uniaxial)); + } repaint(); } @@ -336,6 +386,71 @@ void LogComponent::paint (juce::Graphics& g) return plot.getBottom() - t * plot.getHeight(); }; + // ---- Vibration traces take the right axis (spec §7.3); a psychoacoustic + // metric shown at the same time keeps its own (unlabelled) scale ---- + const juce::Colour textPrimary = lightMode_ ? juce::Colour (0xff1c1c1e) : juce::Colours::white; + const auto vibUnit = processor.getVibrationDisplayUnit(); + bool vibOn[4]; + bool anyVibOn = false; + for (int i = 0; i < 4; ++i) + { + vibOn[i] = vibVisButtons_[i].isVisible() && vibVisButtons_[i].getToggleState(); + anyVibOn = anyVibOn || vibOn[i]; + } + int vibQuantity = -1; + for (auto it = rows.rbegin(); it != rows.rend() && anyVibOn; ++it) + if (it->vib.valid) { vibQuantity = it->vib.quantity; break; } + const bool vibDb = vib::units::effective (vibUnit, (vib::Quantity) juce::jmax (0, vibQuantity)) == vib::DisplayUnit::Db; + auto vibSlotShown = [&] (const VibrationLog& v, int slot) + { + if (! v.valid || v.quantity != vibQuantity || ! vibOn[slot]) return false; + if (slot == vib::AxisSum) + { + const int axes = (v.axisMask & 1) + ((v.axisMask >> 1) & 1) + ((v.axisMask >> 2) & 1); + return ! v.uniaxial && axes > 1; + } + return ((v.axisMask >> slot) & 1) != 0; + }; + auto vibValue = [&] (float si) { return (float) vib::units::convert (si, vibUnit, (vib::Quantity) vibQuantity); }; + float vibMin = 0.0f, vibMax = 0.0f; + bool vibAxis = false; + if (vibQuantity >= 0) + { + float lo = 1.0e30f, hi = -1.0e30f; + for (const auto& e : rows) + for (int slot = 0; slot < 4; ++slot) + if (vibSlotShown (e.vib, slot)) + { + const float v = vibValue (e.vib.rms[slot]); + lo = juce::jmin (lo, v); + hi = juce::jmax (hi, v); + } + if (hi >= lo) + { + vibAxis = true; + if (vibDb) + { + vibMax = std::ceil (hi / 10.0f) * 10.0f; + vibMin = juce::jmin (std::floor (lo / 10.0f) * 10.0f, vibMax - 20.0f); + } + else + { + vibMin = 0.0f; + vibMax = niceCeil (hi * 1.05f); + } + } + } + auto vibToY = [&] (float v) -> float { + float t = (v - vibMin) / (vibMax - vibMin); + t = juce::jlimit (0.0f, 1.0f, t); + return plot.getBottom() - t * plot.getHeight(); + }; + const float axisMin = vibAxis ? vibMin : rightMin; + const float axisMax = vibAxis ? vibMax : rightMax; + const auto axisColour = vibAxis ? textPrimary : psychoColour; + const auto axisUnit = vibAxis ? juce::String::fromUTF8 (vib::units::label (vibUnit, (vib::Quantity) vibQuantity)) + : rightUnit; + // ---- Left Y-axis grid + labels ---- g.setFont (juce::Font (juce::FontOptions().withHeight (20.0f))); { @@ -387,15 +502,18 @@ void LogComponent::paint (juce::Graphics& g) const int numTicks = 4; for (int i = 0; i <= numTicks; ++i) { - float val = rightMin + (rightMax - rightMin) * i / numTicks; - float y = rightToY (val); + float val = axisMin + (axisMax - axisMin) * i / numTicks; + float y = plot.getBottom() - plot.getHeight() * (float) i / numTicks; g.setColour (gridColour); g.drawHorizontalLine (static_cast(y), plot.getX(), plot.getRight()); - g.setColour (psychoColour.withAlpha (0.8f)); - const float range = rightMax - rightMin; - juce::String label = (range < 10.0f) - ? juce::String (val, 1) - : juce::String (static_cast(val + 0.5f)); + g.setColour (axisColour.withAlpha (0.8f)); + const float range = axisMax - axisMin; + juce::String label; + if (vibAxis && ! vibDb) + label = juce::String (val, range < 0.1f ? 4 : range < 1.0f ? 3 : range < 10.0f ? 2 : range < 100.0f ? 1 : 0); + else + label = (range < 10.0f) ? juce::String (val, 1) + : juce::String (static_cast(val + 0.5f)); g.drawText (label, static_cast(plot.getRight()) + 4, static_cast(y) - 14, static_cast(marginR) - 8, 28, @@ -406,14 +524,16 @@ void LogComponent::paint (juce::Graphics& g) { juce::Graphics::ScopedSaveState ss (g); g.setFont (juce::Font (juce::FontOptions().withHeight (18.0f).withStyle ("Bold"))); - g.setColour (psychoColour); + g.setColour (axisColour); float rx = plot.getRight() + marginR - 18.0f; + // Long vibration units sit above the zoom button + const float cy = plot.getCentreY() - (vibAxis ? 70.0f : 0.0f); g.addTransform (juce::AffineTransform::rotation ( - juce::MathConstants::halfPi, rx, plot.getCentreY())); - g.drawText (rightUnit, - static_cast(rx - 40.0f), - static_cast(plot.getCentreY()) - 10, - 80, 20, juce::Justification::centred, false); + juce::MathConstants::halfPi, rx, cy)); + g.drawText (axisUnit, + static_cast(rx - 100.0f), + static_cast(cy) - 10, + 200, 20, juce::Justification::centred, false); } } @@ -555,6 +675,27 @@ void LogComponent::paint (juce::Graphics& g) g.strokePath (path, juce::PathStrokeType (2.5f)); } + // ---- Vibration traces (right axis); gaps where there are no live readings ---- + if (vibAxis) + { + for (int slot = 0; slot < 4; ++slot) + { + if (! vibOn[slot]) continue; + juce::Path path; + bool started = false; + for (const auto& e : rows) + { + if (! vibSlotShown (e.vib, slot)) { started = false; continue; } + const float x = timeToX (e.timestampMs); + const float y = vibToY (vibValue (e.vib.rms[slot])); + if (! started) { path.startNewSubPath (x, y); started = true; } + else { path.lineTo (x, y); } + } + g.setColour (slot < 3 ? colVib[slot] : textPrimary); + g.strokePath (path, juce::PathStrokeType (slot == vib::AxisSum ? 3.0f : 2.0f)); + } + } + // ---- Sound event markers ---- { const juce::Colour flagBg (0xccff453a); @@ -806,7 +947,7 @@ void LogComponent::paint (juce::Graphics& g) for (int c = 0; c < numFftChannels(); ++c) { - g.setColour (fftDual_ ? (c == 0 ? colFftIn1 : colFftIn2) : crossCol); + g.setColour (fftDual() ? (c == 0 ? colFftIn1 : colFftIn2) : crossCol); const float y = dbToY (fftCh_[c].bandsSmoothed[bestBand]); g.fillEllipse (crossX - 4.0f, y - 4.0f, 8.0f, 8.0f); } @@ -817,7 +958,8 @@ void LogComponent::paint (juce::Graphics& g) : juce::String (static_cast (bandFreq + 0.5f)) + " Hz"; juce::String label = freqStr; for (int c = 0; c < numFftChannels(); ++c) - label << " " << (fftDual_ ? processor.getChannelName (c) + " " : juce::String()) + label << " " << (fftSourceChannel (c) >= 0 ? processor.getChannelName (fftSourceChannel (c)) + " " + : juce::String()) << juce::String (fftCh_[c].bandsSmoothed[bestBand], 1) << " dB"; g.setFont (juce::Font (juce::FontOptions().withHeight (16.0f).withStyle ("Bold"))); @@ -850,13 +992,13 @@ void LogComponent::computeFftBands() const int fftOrder = kFftOrders[sizeIdx]; const int fftSize = 1 << fftOrder; - // Switching between mono mix and Dual FFT changes what each channel state - // is fed with, so its history must start over too - const bool dual = processor.apvts.getRawParameterValue ("fftDual")->load() > 0.5f; + // Switching the FFT source (mix / input / dual) changes what each channel + // state is fed with, so its history must start over too + const int source = processor.getFftSource(); - if (fftOrder != currentFftOrder_ || dual != fftDual_) + if (fftOrder != currentFftOrder_ || source != fftSource_) { - if (dual != fftDual_) + if (source != fftSource_) { for (auto& ch : fftCh_) { @@ -867,7 +1009,7 @@ void LogComponent::computeFftBands() } currentFftOrder_ = fftOrder; - fftDual_ = dual; + fftSource_ = source; fft_ = std::make_unique (fftOrder); windowCoeffs_.assign (fftSize, 0.0f); for (auto& ch : fftCh_) @@ -921,7 +1063,7 @@ void LogComponent::computeFftBands() } for (int c = 0; c < numFftChannels(); ++c) - processFftChannel (fftCh_[c], fftDual_ ? c : -1); + processFftChannel (fftCh_[c], fftSourceChannel (c)); } // Runs one analysis frame for a single signal. All channels share the FFT size, @@ -1134,10 +1276,26 @@ void LogComponent::drawFftOverlay (juce::Graphics& g, const juce::Rectangle (lx + 14.0f, legendY, tw + 4.0f, 16.0f), + juce::Justification::centredLeft, false); + legendY += 18.0f; + }; + + if (! fftDual()) { drawChannel (fftCh_[0], juce::Colour (0xff34c759), juce::Colour (0xaa34c759), juce::Colour (0xffffcc00)); // amber peak line + if (fftSourceChannel (0) >= 0) // single input: name it, the mix needs no legend + drawLegend ("FFT " + processor.getChannelName (fftSourceChannel (0)), juce::Colour (0xff34c759)); } else { @@ -1145,20 +1303,8 @@ void LogComponent::drawFftOverlay (juce::Graphics& g, const juce::Rectangle (lx + 14.0f, ly, tw + 4.0f, 16.0f), - juce::Justification::centredLeft, false); - ly += 18.0f; - } + drawLegend ("FFT " + processor.getChannelName (0), colFftIn1); + drawLegend ("FFT " + processor.getChannelName (1), colFftIn2); } // ---- Graph Overlay: dashed blue frequency-response curve ---- diff --git a/Source/LogComponent.h b/Source/LogComponent.h index eba4c7b..4e5cfd4 100644 --- a/Source/LogComponent.h +++ b/Source/LogComponent.h @@ -61,12 +61,20 @@ class LogComponent : public juce::Component, juce::ToggleButton tonalityVisButton { "Tonality" }; juce::ToggleButton bassComfortVisButton { "Bass LCeq-LAeq" }; + // Vibration traces X / Y / Z / Σ (vibration spec §7.3), shown when an + // accelerometer is configured; they take over the right axis + juce::ToggleButton vibVisButtons_[4]; + bool vibAvailable_ = false; + bool vibUniaxial_ = false; + static const juce::Colour colVib[3]; // X brown, Y mint, Z slate (Σ: text colour) + // FFT static constexpr int kMaxFftOrder = 19; // 2^19 = 524288, matches PluginProcessor::kFftCircBufSize static constexpr int kMaxFftBands = 256; // enough for 1/24-Oct (~240 bands) - // Per-signal analysis state. Mono mode uses fftCh_[0] fed by the input mix; - // Dual FFT feeds fftCh_[0] / fftCh_[1] from inputs 1 / 2 with identical settings. + // Per-signal analysis state. Mix / single-input mode uses fftCh_[0]; Dual FFT + // feeds fftCh_[0] / fftCh_[1] from inputs 1 / 2 with identical settings. + // fftSource_ is the processor's FftSource value. struct FftChannel { std::vector inputHistory; // overlap history @@ -79,7 +87,16 @@ class LogComponent : public juce::Component, double peakTimestamps[kMaxFftBands] {}; }; void processFftChannel (FftChannel&, int sourceChannel); - int numFftChannels() const noexcept { return fftDual_ ? 2 : 1; } + bool fftDual() const noexcept { return fftSource_ == SPLMeterAudioProcessor::FftSourceDual; } + int numFftChannels() const noexcept { return fftDual() ? 2 : 1; } + // Processor channel feeding fftCh_[c]: -1 = mix, otherwise the input index + int fftSourceChannel (int c) const noexcept + { + if (fftDual()) return c; + if (fftSource_ >= SPLMeterAudioProcessor::FftSourceInput1) + return fftSource_ - SPLMeterAudioProcessor::FftSourceInput1; + return -1; + } static const juce::Colour colFftIn1; // Dual FFT: input 1 (green) static const juce::Colour colFftIn2; // Dual FFT: input 2 (red) @@ -91,7 +108,7 @@ class LogComponent : public juce::Component, int currentNumBands_ = 0; int currentBandN_ = -1; int currentWindowType_ = -1; - bool fftDual_ = false; + int fftSource_ = SPLMeterAudioProcessor::FftSourceMix; bool fftEnabled_ = false; bool lightMode_ = false; diff --git a/Source/MeterComponent.cpp b/Source/MeterComponent.cpp index 2d55579..7768847 100644 --- a/Source/MeterComponent.cpp +++ b/Source/MeterComponent.cpp @@ -488,6 +488,16 @@ void MeterComponent::paint (juce::Graphics& g) drawCell (0, 3, "Annoyance", juce::String (psychoAnnoyance_, 2)); } + // No input has the Mic role (vibration spec §7.1): cover readout and bar + if (noMicInput_) + { + const auto cover = juce::Rectangle (barAreaX, peakReadoutY, barAreaW, peakY + barH - peakReadoutY); + g.setColour (bgMain.withAlpha (0.94f)); + g.fillRoundedRectangle (cover, 6.0f); + g.setColour (textSecond); + g.setFont (juce::Font (juce::FontOptions().withHeight (20.0f).withStyle ("Bold"))); + g.drawText ("No microphone input", cover, juce::Justification::centred, false); + } } //============================================================================== diff --git a/Source/MeterComponent.h b/Source/MeterComponent.h index 5aad1ce..2ff6dfc 100644 --- a/Source/MeterComponent.h +++ b/Source/MeterComponent.h @@ -85,6 +85,12 @@ class MeterComponent : public juce::Component, if (lightMode_ != light) { lightMode_ = light; repaint(); } } + // All inputs are accelerometers or off: the SPL readout has no signal + void setNoMicInput (bool v) noexcept + { + if (noMicInput_ != v) { noMicInput_ = v; repaint(); } + } + private: float peakSPL_ = 0.0f; float peakDBASPL_ = 0.0f; @@ -109,6 +115,7 @@ class MeterComponent : public juce::Component, juce::String taCategoryShort_ { "WA" }; bool lightMode_ = false; + bool noMicInput_ = false; bool psychoVisible_ = true; bool dinVisible_ = true; Band selectedBand_ = Band::SPL; diff --git a/Source/PluginEditor.cpp b/Source/PluginEditor.cpp index 76d5608..4d46418 100644 --- a/Source/PluginEditor.cpp +++ b/Source/PluginEditor.cpp @@ -1,4 +1,9 @@ #include "PluginEditor.h" +#include "VibrationCsv.h" +#include "VibrationReport.h" +#if JucePlugin_Build_Standalone + #include +#endif #include static juce::File splmeterLastFolder() { return UserPrefs::lastUsedFolder(); } @@ -58,6 +63,8 @@ SPLMeterAudioProcessorEditor::SPLMeterAudioProcessorEditor (SPLMeterAudioProcess { addAndMakeVisible (meter); addAndMakeVisible (log); + vibPanel.onUnitChange = [this] (vib::DisplayUnit u) { audioProcessor.setVibrationDisplayUnit (u); }; + addAndMakeVisible (vibPanel); resetButton.setColour (juce::TextButton::buttonColourId, juce::Colour (0xff3a3a3c)); resetButton.setColour (juce::TextButton::textColourOffId, juce::Colour (0xffff453a)); @@ -73,7 +80,7 @@ SPLMeterAudioProcessorEditor::SPLMeterAudioProcessorEditor (SPLMeterAudioProcess saveMenuButton.setColour (juce::TextButton::buttonColourId, juce::Colour (0xff3a3a3c)); saveMenuButton.setColour (juce::TextButton::textColourOffId, juce::Colours::white); - saveMenuButton.setTooltip ("Save CSV log, WAV recording, or screenshot"); + saveMenuButton.setTooltip ("Save CSV log, WAV recording, screenshot or vibration report; save or load settings"); saveMenuButton.onClick = [this] { juce::PopupMenu menu; @@ -83,6 +90,8 @@ SPLMeterAudioProcessorEditor::SPLMeterAudioProcessorEditor (SPLMeterAudioProcess menu.addSeparator(); menu.addItem (4, "Save All..."); menu.addSeparator(); + menu.addItem (7, "Save Vibration Report...", canSaveVibrationReport()); + menu.addSeparator(); menu.addItem (5, "Save Settings..."); menu.addItem (6, "Load Settings..."); menu.showMenuAsync ( @@ -97,6 +106,7 @@ SPLMeterAudioProcessorEditor::SPLMeterAudioProcessorEditor (SPLMeterAudioProcess case 4: doSaveAll(); break; case 5: doSaveSettingsJson(); break; case 6: doLoadSettingsJson(); break; + case 7: doSaveVibrationReport(); break; default: break; } }); @@ -268,7 +278,7 @@ SPLMeterAudioProcessorEditor::SPLMeterAudioProcessorEditor (SPLMeterAudioProcess if (basicMode_) { extendedHeight_ = getHeight(); - const int basicH = 100 + 215 + 24; // title + meter + build strip + const int basicH = basicHeight(); setResizeLimits (480, basicH, 3840, 2160); setSize (getWidth(), basicH); } @@ -318,6 +328,10 @@ SPLMeterAudioProcessorEditor::SPLMeterAudioProcessorEditor (SPLMeterAudioProcess menu.addItem (3, "SoundDetective..."); menu.addItem (5, "Long-term SPL"); menu.addItem (6, "Impulse Fidelity"); +#if ! JUCE_IOS + menu.addSeparator(); + menu.addItem (7, "REW Measurement Sequencer..."); +#endif #if SPLMETER_HAS_VISQOL || JUCE_MAC menu.addItem (2, "ViSQOL"); #endif @@ -363,6 +377,11 @@ SPLMeterAudioProcessorEditor::SPLMeterAudioProcessorEditor (SPLMeterAudioProcess else if (result == 6) openWindow (impulseFidelityWindow, [this] { return std::make_unique (audioProcessor); }); +#if ! JUCE_IOS + else if (result == 7) + openWindow (rewSequencerWindow, + [this] { return std::make_unique (audioProcessor, lightMode_); }); +#endif #if SPLMETER_HAS_VISQOL || JUCE_MAC else if (result == 2) { @@ -425,7 +444,8 @@ SPLMeterAudioProcessorEditor::SPLMeterAudioProcessorEditor (SPLMeterAudioProcess dawSyncToggle.setVisible (!basicMode_); meter.setPsychoVisible (!basicMode_); meter.setDinVisible (!basicMode_); - const int basicH = 100 + 215 + 24; + updateVibrationPanel(); + const int basicH = basicHeight(); if (basicMode_) { setResizeLimits (480, basicH, 3840, 2160); @@ -468,7 +488,7 @@ void SPLMeterAudioProcessorEditor::paint (juce::Graphics& g) // Build info strip at the bottom g.setFont (juce::Font (juce::FontOptions().withHeight (14.0f))); g.setColour (textFnt); - g.drawText ("v3.5.2 Build: " + juce::String (__DATE__) + " " + __TIME__, + g.drawText ("v" JucePlugin_VersionString " Build: " + juce::String (__DATE__) + " " + __TIME__, 0, getHeight() - 22, getWidth(), 20, juce::Justification::centred, false); } @@ -510,9 +530,11 @@ void SPLMeterAudioProcessorEditor::resized() monitorGainSlider.setBounds (monitorButton.getRight() + 4, 8, 60, 80); outputVUMeter.setBounds (monitorGainSlider.getRight() + 4, 4, 22, 84); - const int meterHeight = 270; + // Basic mode shows only the top 215 px of the meter (no psycho/DIN rows) + const int meterHeight = basicMode_ ? 215 : 270; auto meterArea = area.removeFromTop (meterHeight); meter.setBounds (meterArea); + vibPanel.setBounds (area.removeFromTop (vibPanel.preferredHeight())); // FAST/SLOW buttons right-aligned in the numeric readout row of the meter // MeterComponent: margin=20, peakReadoutY=20, readoutH=40 @@ -532,6 +554,130 @@ void SPLMeterAudioProcessorEditor::resized() } //============================================================================== +bool SPLMeterAudioProcessorEditor::updateVibrationPanel() +{ + using Kind = VibrationPanel::State::Kind; + const int heightBefore = vibPanel.preferredHeight(); + + const auto roles = audioProcessor.getChannelRoles(); + const int numInputs = juce::jmin (audioProcessor.getTotalNumInputChannels(), SensorConfig::kMaxInputs); + + // Accelerometer roles on inputs this device or bus does not have + juce::StringArray missing; + bool anyAccel = false, anyMic = false; + for (int ch = 0; ch < SensorConfig::kMaxInputs; ++ch) + { + const auto r = roles[(size_t) ch]; + if (ch < numInputs) + anyMic = anyMic || r == SensorRole::Mic; + if (! SensorConfig::isAccel (r)) + continue; + anyAccel = true; + if (ch >= numInputs) + { + const char* axis[] = { "", "X", "Y", "Z", "uniaxial" }; + missing.add (audioProcessor.getChannelName (ch) + " (" + axis[(int) r] + ")"); + } + } + meter.setNoMicInput (numInputs > 0 && ! anyMic); + + VibrationPanel::State st; + st.unit = audioProcessor.getVibrationDisplayUnit(); + const auto settings = audioProcessor.getVibrationSettings(); + st.tauSec = settings.tauSec; + st.profileLabel = audioProcessor.getVibrationProfileLabel(); + st.mainLabel = audioProcessor.getVibrationMainLabel(); + for (int a = 0; a < 3; ++a) + st.k[a] = settings.k[a]; + st.exposureHours = audioProcessor.getAccelSensorInfo().exposureHours; + st.limits = audioProcessor.getAssessmentLimits(); + const auto missingText = missing.isEmpty() ? juce::String() + : missing.joinIntoString (", ") + (missing.size() == 1 ? " is" : " are") + + " not available on this input"; + + const auto validity = audioProcessor.getSensorValidity(); + const bool fileVib = audioProcessor.isFileModeActive() && audioProcessor.fileHasAccelerometer(); + if (fileVib) + { + // Playback of an accelerometer recording: its own roles and calibration + st.kind = Kind::Running; + st.snap = audioProcessor.getVibrationSnapshot(); + if (! st.snap.valid) + { + st.snap = {}; + st.snap.quantity = (int) settings.quantity; + const auto tracks = audioProcessor.getFileTracks(); + for (const auto& t : tracks) + { + switch (t.role) + { + case SensorRole::AccelX: st.snap.axisMask |= 1; break; + case SensorRole::AccelY: st.snap.axisMask |= 2; break; + case SensorRole::AccelZ: st.snap.axisMask |= 4; break; + case SensorRole::AccelUniaxial: st.snap.axisMask |= 1; st.snap.uniaxial = true; break; + case SensorRole::Mic: + case SensorRole::Off: break; + } + } + for (int a = 0; a < 3; ++a) + st.snap.weighting[a] = (int) settings.weighting[a]; + st.snap.mainKind = (int) settings.main; + } + st.note = "file playback with recorded roles and calibration"; + } + else if (! anyAccel) + { + st.kind = Kind::Hidden; + } + else if (! SensorConfig::isValid (validity)) + { + st.kind = Kind::Message; + st.messageIsError = true; + st.message = "Accelerometer roles are invalid (an axis is assigned twice, or uniaxial is mixed with X/Y/Z)." + " Fix them in Settings > Inputs and Sensors."; + } + else if (validity == SensorConfig::Validity::NoAccelerometer) + { + st.kind = Kind::Message; + st.message = missingText + "."; + } + else + { + st.kind = Kind::Running; + st.snap = audioProcessor.getVibrationSnapshot(); + if (! st.snap.valid) + { + // Before the first readout: lay out the rows from the configuration + st.snap = {}; + st.snap.quantity = (int) settings.quantity; + for (int ch = 0; ch < numInputs; ++ch) + { + switch (roles[(size_t) ch]) + { + case SensorRole::AccelX: st.snap.axisMask |= 1; break; + case SensorRole::AccelY: st.snap.axisMask |= 2; break; + case SensorRole::AccelZ: st.snap.axisMask |= 4; break; + case SensorRole::AccelUniaxial: st.snap.axisMask |= 1; st.snap.uniaxial = true; break; + case SensorRole::Mic: + case SensorRole::Off: break; + } + } + for (int a = 0; a < 3; ++a) + st.snap.weighting[a] = (int) settings.weighting[a]; + st.snap.mainKind = (int) settings.main; + } + if (audioProcessor.isFileModeActive()) + st.note = "the played file has no accelerometer tracks"; + else if (missingText.isNotEmpty()) + st.note = missingText; + } + if (st.kind == Kind::Running) + st.assessment = vib::assess (audioProcessor.getVibrationProfile(), st.snap, st.k, st.exposureHours, st.limits); + vibPanel.setState (st); + vibPanel.setVisible (st.kind != Kind::Hidden); + return vibPanel.preferredHeight() != heightBefore; +} + void SPLMeterAudioProcessorEditor::updateModeButtons() { realTimeButton.setToggleState (!fileMode, juce::dontSendNotification); @@ -586,6 +732,11 @@ void SPLMeterAudioProcessorEditor::applyTheme (bool light) meter.setLightMode (light); log.setLightMode (light); + vibPanel.setLightMode (light); +#if ! JUCE_IOS + if (rewSequencerWindow != nullptr) + rewSequencerWindow->setLightMode (light); +#endif #if SPLMETER_HAS_VISQOL || JUCE_MAC if (visqolWindow != nullptr) @@ -601,13 +752,16 @@ void SPLMeterAudioProcessorEditor::applyTheme (bool light) //============================================================================== void SPLMeterAudioProcessorEditor::writeCsvRows (juce::OutputStream& stream, const std::vector& rows, - const std::vector& markers) + const std::vector& markers, + vib::DisplayUnit vibUnit, + const juce::String& vibProfile) { stream.writeText ("Timestamp,Peak dB SPL,Peak dBA SPL,Peak dBC SPL," "RMS dB SPL,RMS dBA SPL,RMS dBC SPL," "LAeq,LCeq," "Roughness (%),Fluctuation (%),Sharpness (acum)," - "Specific Loudness (sone),Psychoacoustic Annoyance,Marker\n", + "Specific Loudness (sone),Psychoacoustic Annoyance,Marker" + + VibrationCsv::header() + "\n", false, false, nullptr); // Build a lookup: for each marker, find the closest log entry timestamp @@ -660,7 +814,8 @@ void SPLMeterAudioProcessorEditor::writeCsvRows (juce::OutputStream& stream, + juce::String (e.sharpness, 3) + "," + juce::String (e.loudnessSone, 3) + "," + juce::String (e.psychoAnnoyance, 3) + "," - + markerText + "\n"; + + markerText + + VibrationCsv::columns (e.vib, vibUnit, vibProfile) + "\n"; stream.writeText (line, false, false, nullptr); } } @@ -674,9 +829,11 @@ void SPLMeterAudioProcessorEditor::doSaveCsv() splmeterLastFolder().getChildFile ("SPLMeter.csv"), "*.csv"); auto markers = markerEvents_; // snapshot for async lambda + const auto vibUnit = audioProcessor.getVibrationDisplayUnit(); + const auto vibProfile = audioProcessor.getVibrationProfileKey(); fileChooser->launchAsync ( juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles, - [rows, markers] (const juce::FileChooser& fc) + [rows, markers, vibUnit, vibProfile] (const juce::FileChooser& fc) { auto file = fc.getResult(); if (file == juce::File{}) return; @@ -684,10 +841,149 @@ void SPLMeterAudioProcessorEditor::doSaveCsv() juce::FileOutputStream stream (file); if (!stream.openedOk()) return; stream.setPosition (0); stream.truncate(); - writeCsvRows (stream, rows, markers); + writeCsvRows (stream, rows, markers, vibUnit, vibProfile); }); } +//============================================================================== +// Vibration report (spec §9): metadata dialog → file chooser → HTML +bool SPLMeterAudioProcessorEditor::canSaveVibrationReport() const +{ + const auto s = audioProcessor.getVibrationSnapshot(); + return s.valid && s.seconds > 0.0; +} + +namespace +{ + juce::String reportDeviceName (SPLMeterAudioProcessor& p) + { + #if JucePlugin_Build_Standalone + if (juce::JUCEApplicationBase::isStandaloneApp()) + if (auto* holder = juce::StandalonePluginHolder::getInstance()) + if (auto* dev = holder->deviceManager.getCurrentAudioDevice()) + return dev->getName() + " (" + dev->getTypeName() + ")"; + #endif + juce::ignoreUnused (p); + return juce::String ("Plugin in ") + juce::PluginHostType().getHostDescription(); + } + + juce::String reportRoleName (SensorRole r) + { + switch (r) + { + case SensorRole::Mic: return "Mic"; + case SensorRole::AccelX: return "Accel X"; + case SensorRole::AccelY: return "Accel Y"; + case SensorRole::AccelZ: return "Accel Z"; + case SensorRole::AccelUniaxial: return "Accel (uniaxial)"; + case SensorRole::Off: return "Off"; + } + return {}; + } + + const char* const kReportKeys[5] = { "project", "location", "operator", "mounting", "notes" }; +} + +void SPLMeterAudioProcessorEditor::doSaveVibrationReport() +{ + if (! canSaveVibrationReport()) + return; + + auto stored = audioProcessor.getUiState().getOrCreateChildWithName ("Report", nullptr); + auto* aw = new juce::AlertWindow ("Save Vibration Report", + "Details for the report header (remembered for the next report):", + juce::MessageBoxIconType::NoIcon); + const char* labels[5] = { "Project:", "Location / measurement point:", "Operator:", "Sensor mounting:", "Notes:" }; + for (int i = 0; i < 5; ++i) + aw->addTextEditor (kReportKeys[i], stored.getProperty (kReportKeys[i], juce::String()).toString(), labels[i]); + aw->addButton ("Continue", 1, juce::KeyPress (juce::KeyPress::returnKey)); + aw->addButton ("Cancel", 0, juce::KeyPress (juce::KeyPress::escapeKey)); + + aw->enterModalState (true, juce::ModalCallbackFunction::create ([this, aw] (int result) + { + std::unique_ptr owner (aw); + if (result != 1) + return; + + auto node = audioProcessor.getUiState().getOrCreateChildWithName ("Report", nullptr); + for (auto* key : kReportKeys) + node.setProperty (key, aw->getTextEditorContents (key).trim(), nullptr); + + // Collect everything now; the file chooser is asynchronous + VibrationReport::Input in; + in.meta = { aw->getTextEditorContents ("project").trim(), aw->getTextEditorContents ("location").trim(), + aw->getTextEditorContents ("operator").trim(), aw->getTextEditorContents ("mounting").trim(), + aw->getTextEditorContents ("notes").trim() }; + in.version = JucePlugin_VersionString; + in.created = juce::Time::getCurrentTime(); + in.device = reportDeviceName (audioProcessor); + in.sampleRate = audioProcessor.getSampleRate(); + const auto info = audioProcessor.getAccelSensorInfo(); + in.serial = info.serial; + in.lowerLimitHz = info.lowerLimitHz; + in.upperLimitHz = info.upperLimitHz; + in.exposureHours = info.exposureHours; + in.profile = audioProcessor.getVibrationProfile(); + in.profileLabel = audioProcessor.getVibrationProfileLabel(); + in.mainLabel = audioProcessor.getVibrationMainLabel(); + in.settings = audioProcessor.getVibrationSettings(); + in.unit = audioProcessor.getVibrationDisplayUnit(); + in.snap = audioProcessor.getVibrationSnapshot(); + in.limits = audioProcessor.getAssessmentLimits(); + in.log = audioProcessor.copyLog(); + in.timeWeighting = audioProcessor.apvts.getRawParameterValue ("splTimeWeight")->load() > 0.5f ? "S" : "F"; + + if (audioProcessor.isFileModeActive() && audioProcessor.fileHasAccelerometer()) + { + for (const auto& t : audioProcessor.getFileTracks()) + { + in.channels.push_back ({ t.name.isNotEmpty() ? t.name : "Track " + juce::String (t.input + 1), + reportRoleName (t.role), t.calDb, "from the recording", + SensorConfig::isAccel (t.role) }); + in.hasMic = in.hasMic || t.role == SensorRole::Mic; + } + in.device = "File playback"; + } + else + { + const int numInputs = juce::jmin (audioProcessor.getTotalNumInputChannels(), SensorConfig::kMaxInputs); + for (int ch = 0; ch < numInputs; ++ch) + { + const auto role = audioProcessor.getChannelRole (ch); + const bool muted = audioProcessor.apvts.getRawParameterValue ("channelMute" + juce::String (ch))->load() > 0.5f; + if (muted && role == SensorRole::Mic) + continue; + const bool accel = SensorConfig::isAccel (role); + in.channels.push_back ({ audioProcessor.getChannelName (ch), reportRoleName (role), + accel ? audioProcessor.getAccelCalDb (ch) : 0.0, + accel ? audioProcessor.getAccelCalInfo (ch) : juce::String(), accel }); + in.hasMic = in.hasMic || (role == SensorRole::Mic && ! muted); + } + } + for (const auto& m : markerEvents_) + in.events.push_back ({ m.timestampMs, 0, m.text, false }); + for (const auto& p : pauseEvents_) + in.events.push_back ({ p.startMs, p.durationMs, {}, true }); + + fileChooser = std::make_unique ( + "Save vibration report", splmeterLastFolder().getChildFile (VibrationReport::suggestedFileName (in)), "*.html"); + fileChooser->launchAsync ( + juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles + | juce::FileBrowserComponent::warnAboutOverwriting, + [in] (const juce::FileChooser& fc) + { + auto file = fc.getResult(); + if (file == juce::File{}) return; + if (! file.hasFileExtension ("html;htm")) + file = file.withFileExtension ("html"); + splmeterSaveLastFolder (file); + if (! file.replaceWithText (VibrationReport::generateHtml (in), false, false, "\n")) + juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, + "Save Vibration Report", "Could not write " + file.getFullPathName()); + }); + }), false); +} + void SPLMeterAudioProcessorEditor::doSaveWav() { fileChooser = std::make_unique ( @@ -733,11 +1029,13 @@ void SPLMeterAudioProcessorEditor::doSaveAll() auto rows = audioProcessor.copyLog(); auto markers = markerEvents_; auto snapshot = createComponentSnapshot (getLocalBounds()); + const auto vibUnit = audioProcessor.getVibrationDisplayUnit(); + const auto vibProfile = audioProcessor.getVibrationProfileKey(); fileChooser = std::make_unique ( "Choose destination folder", splmeterLastFolder()); fileChooser->launchAsync ( juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories, - [this, rows, markers, snapshot] (const juce::FileChooser& fc) + [this, rows, markers, snapshot, vibUnit, vibProfile] (const juce::FileChooser& fc) { auto folder = fc.getResult(); if (folder == juce::File{} || !folder.isDirectory()) return; @@ -750,7 +1048,7 @@ void SPLMeterAudioProcessorEditor::doSaveAll() if (!rows.empty()) { juce::FileOutputStream csv (base.withFileExtension ("csv")); - if (csv.openedOk()) { csv.setPosition (0); csv.truncate(); writeCsvRows (csv, rows, markers); } + if (csv.openedOk()) { csv.setPosition (0); csv.truncate(); writeCsvRows (csv, rows, markers, vibUnit, vibProfile); } } // WAV @@ -821,6 +1119,7 @@ void SPLMeterAudioProcessorEditor::doSaveSettingsJson() p->setProperty ("fftOverlap", getInt ("fftOverlap")); p->setProperty ("fftRTAMode", getBool ("fftRTAMode")); p->setProperty ("fftDual", getBool ("fftDual")); + p->setProperty ("fftSource", getInt ("fftSource")); p->setProperty ("bandpassEnabled", getBool ("bandpassEnabled")); p->setProperty ("line94Enabled", getBool ("line94Enabled")); p->setProperty ("correctionEnabled", getBool ("correctionEnabled")); @@ -852,6 +1151,10 @@ void SPLMeterAudioProcessorEditor::doSaveSettingsJson() audioProcessor.getMidiCC (i)); r->setProperty ("midiCC", midi); + // Sensor roles, accelerometer calibration and settings (vibration spec §8) + r->setProperty ("inputs", audioProcessor.getInputsJson()); + r->setProperty ("accel", audioProcessor.getAccelJson()); + splmeterSaveLastFolder (file); file.replaceWithText (juce::JSON::toString (root, true)); }); @@ -915,7 +1218,13 @@ void SPLMeterAudioProcessorEditor::doLoadSettingsJson() applyB ("fftPeakHold"); applyI ("fftDisplayMode"); applyI ("fftBandRes"); applyI ("fftWindowType"); applyI ("fftOverlap"); applyB ("fftRTAMode"); - applyB ("fftDual"); + // fftSource supersedes fftDual; files from ≤ 3.5.2 only have fftDual + if (p->hasProperty ("fftSource")) + audioProcessor.setFftSource ((int) p->getProperty ("fftSource")); + else if (p->hasProperty ("fftDual")) + audioProcessor.setFftSource (static_cast (p->getProperty ("fftDual")) + ? SPLMeterAudioProcessor::FftSourceDual + : SPLMeterAudioProcessor::FftSourceMix); applyB ("bandpassEnabled"); applyB ("line94Enabled"); applyB ("correctionEnabled"); applyB ("graphOverlayEnabled"); applyB ("graphOverlay2Enabled"); @@ -943,6 +1252,9 @@ void SPLMeterAudioProcessorEditor::doLoadSettingsJson() audioProcessor.setMidiCC (i, (int) midi->getProperty (id)); } + // Sensor roles + accelerometer (absent in files from ≤ 3.5.2: unchanged) + audioProcessor.setInputsAndAccelFromJson (parsed["inputs"], parsed["accel"]); + // Refresh settings window channel names if open if (settingsWindow != nullptr) if (auto* sc = dynamic_cast ( @@ -1076,6 +1388,16 @@ void SPLMeterAudioProcessorEditor::timerCallback() audioProcessor.getTonality()); meter.setPeak (audioProcessor.getPeakSPL()); + if (updateVibrationPanel()) + { + if (basicMode_) + { + setResizeLimits (480, basicHeight(), 3840, 2160); + setSize (getWidth(), basicHeight()); + } + resized(); + } + // Compute LAeq / LCeq from log entries (energy average over logDuration) // and DIN 15905-5 LAeq,30min (sliding 30-min window over the available log) { @@ -1203,6 +1525,15 @@ void SPLMeterAudioProcessorEditor::timerCallback() } } + // Markers from REW sequencer runs (the processor owns the run) + { + const auto pending = audioProcessor.takePendingMarkers(); + for (const auto& m : pending) + markerEvents_.push_back (LogComponent::MarkerEvent { m.timestampMs, m.text }); + if (! pending.empty()) + log.setMarkerEvents (markerEvents_); + } + // Pass pause events to log (trim those older than the visible window) { const float logDuration = audioProcessor.apvts.getRawParameterValue ("logDuration")->load(); diff --git a/Source/PluginEditor.h b/Source/PluginEditor.h index 7082ef1..37e90e0 100644 --- a/Source/PluginEditor.h +++ b/Source/PluginEditor.h @@ -3,6 +3,7 @@ #include "PluginProcessor.h" #include "UserPrefs.h" #include "MeterComponent.h" +#include "VibrationPanel.h" #include "LogComponent.h" #include "SettingsComponent.h" #include "SpectrogramComponent.h" @@ -10,6 +11,9 @@ #include "LFFTComponent.h" #include "LongTermSPLComponent.h" #include "ImpulseFidelityComponent.h" +#if ! JUCE_IOS + #include "RewSequencerComponent.h" +#endif #if SPLMETER_HAS_VISQOL || JUCE_MAC #include "VisqolComponent.h" #endif @@ -275,9 +279,12 @@ class SPLMeterAudioProcessorEditor : public juce::AudioProcessorEditor, void doSaveJpg(); void doSaveAll(); void doSaveSettingsJson(); + void doSaveVibrationReport(); + bool canSaveVibrationReport() const; void doLoadSettingsJson(); static void writeCsvRows (juce::OutputStream&, const std::vector&, - const std::vector&); + const std::vector&, vib::DisplayUnit, + const juce::String& vibProfile); SPLMeterAudioProcessor& audioProcessor; // Must stay above the child components so they are built from the restored state @@ -285,6 +292,12 @@ class SPLMeterAudioProcessorEditor : public juce::AudioProcessorEditor, MeterComponent meter; LogComponent log; + VibrationPanel vibPanel; + + // Vibration panel (spec §7.2): state from roles + snapshot; returns true when + // the panel's height changed and the layout must follow + bool updateVibrationPanel(); + int basicHeight() const { return 100 + 215 + 24 + vibPanel.preferredHeight(); } // title + meter + panel + build strip juce::TooltipWindow tooltipWindow { this, 400 }; // 400 ms delay juce::TextButton settingsButton { "Settings..." }; @@ -337,6 +350,9 @@ class SPLMeterAudioProcessorEditor : public juce::AudioProcessorEditor, std::unique_ptr lfftWindow; std::unique_ptr longTermSPLWindow; std::unique_ptr impulseFidelityWindow; +#if ! JUCE_IOS + std::unique_ptr rewSequencerWindow; +#endif std::vector allSoundEvents_; #if SPLMETER_HAS_VISQOL || JUCE_MAC std::unique_ptr visqolWindow; diff --git a/Source/PluginProcessor.cpp b/Source/PluginProcessor.cpp index 6db3dc1..3b432ee 100644 --- a/Source/PluginProcessor.cpp +++ b/Source/PluginProcessor.cpp @@ -95,7 +95,15 @@ SPLMeterAudioProcessor::createParameterLayout() "fftRTAMode", "FFT RTA +3dB/oct", false)); params.push_back (std::make_unique ( - "fftDual", "Dual FFT (Input 1 + 2)", false)); + "fftDual", "Dual FFT (Input 1 + 2)", false)); // legacy (≤ 3.5.2), mirrors fftSource == Dual + + { + juce::StringArray sources { "Mix", "Dual (1+2)" }; + for (int ch = 1; ch <= SPLMeterAudioProcessor::kMaxFftChannels; ++ch) + sources.add ("Input " + juce::String (ch)); + params.push_back (std::make_unique ( + "fftSource", "FFT Source", sources, 0)); + } params.push_back (std::make_unique ( "bandpassEnabled", "20-20k Bandpass", false)); @@ -177,12 +185,20 @@ SPLMeterAudioProcessor::SPLMeterAudioProcessor() formatManager.registerBasicFormats(); } -SPLMeterAudioProcessor::~SPLMeterAudioProcessor() {} +SPLMeterAudioProcessor::~SPLMeterAudioProcessor() +{ + delete vibPending_.exchange (nullptr); + delete vibRetired_.exchange (nullptr); + delete vibActive_; +} //============================================================================== void SPLMeterAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock) { currentSampleRate = sampleRate; + rewFastAlpha_ = 1.0 - std::exp (-1.0 / (0.125 * sampleRate)); + rewSlowAlpha_ = 1.0 - std::exp (-1.0 / (1.0 * sampleRate)); + rewFastA_ = rewSlowC_ = 0.0; aWeightL.prepare (sampleRate); cWeightL.prepare (sampleRate); roughnessEst.prepare (sampleRate); @@ -204,14 +220,7 @@ void SPLMeterAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlo logIntervalSamples = static_cast (0.125 * sampleRate); logSampleCounter = 0; - // WAV circular buffer: sized to current logDuration - { - const float logDurS = apvts.getRawParameterValue ("logDuration")->load(); - wavBufSize_ = static_cast (logDurS * sampleRate); - wavCircBuf_[0].assign (wavBufSize_, 0.0f); - wavCircBuf_[1].assign (wavBufSize_, 0.0f); - wavWritePos_.store (0, std::memory_order_relaxed); - } + // WAV recorder: sized to the current logDuration (built after currentSampleRate is set) // 20-20k bandpass: 8th-order Butterworth Q values for each biquad stage static const double bpQ[kBpStages] = { 0.5098, 0.6013, 0.8999, 2.5629 }; @@ -237,7 +246,38 @@ void SPLMeterAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlo rebuildCorrectionFIR(); transportSource.prepareToPlay (samplesPerBlock, sampleRate); - fileReadBuffer.setSize (2, samplesPerBlock, false, true, false); + fileReadBuffer.setSize (WavRecording::kMaxTracks, samplesPerBlock, false, true, false); // capacity for 8-track files + + // Per-input FFT buffers: grow only (never freed while the GUI may read them). + // Inputs 1 + 2 always exist so Dual FFT works on mono devices too. + for (int ch = 0; ch < juce::jlimit (2, kMaxFftChannels, getTotalNumInputChannels()); ++ch) + { + if (fftChStorage_[(size_t) ch] == nullptr) + { + fftChStorage_[(size_t) ch] = std::make_unique ((size_t) kFftCircBufSize); // zeroed + fftChBuf_[(size_t) ch].store (fftChStorage_[(size_t) ch].get(), std::memory_order_release); + } + } + + // Accelerometer engine for the new sample rate. The audio thread is stopped here, + // so the active engine can be replaced directly. + delete vibPending_.exchange (nullptr); + delete vibRetired_.exchange (nullptr); + delete vibActive_; + vibActive_ = buildVibrationEngine().release(); + vibWork_ = {}; + vibSnapshot_.write (vibWork_); + vibFile_.replaceNow (buildFileVibrationEngine()); + vibSource_ = 0; + rebuildWavRecorder (true); + + // A running calibrator measurement was set up for the old rate: abandon it + calState_.store (CalIdle, std::memory_order_release); + calProgress_.store (0.0, std::memory_order_relaxed); + inputMs_.fill (0.0); + + nonMicScratch_.setSize (juce::jmax (1, juce::jmin (getTotalNumInputChannels(), SensorConfig::kMaxInputs)), + samplesPerBlock, false, true, false); } void SPLMeterAudioProcessor::releaseResources() @@ -313,6 +353,8 @@ void SPLMeterAudioProcessor::processBlock (juce::AudioBuffer& buffer, dawIsPlaying_.store (dawPlaying); } const bool skipMetering = paused_.load() || (isDawSyncEnabled && !dawPlaying); + handleRewStep (calOffset); + const bool rewStep = stepState_.load (std::memory_order_relaxed) == kStepRunning; const int numSamples = buffer.getNumSamples(); const int numChannels = buffer.getNumChannels(); @@ -324,11 +366,105 @@ void SPLMeterAudioProcessor::processBlock (juce::AudioBuffer& buffer, buffer.clear (ch, 0, numSamples); } + // --- Sensor roles: only Mic inputs feed the SPL mix, bandpass and correction --- + // (File mode keeps mixing all file channels; role-aware playback follows with + // multichannel recording, vibration spec §7.5.) + bool isMic[SensorConfig::kMaxInputs]; + bool allMic = true; + for (int ch = 0; ch < SensorConfig::kMaxInputs; ++ch) + { + isMic[ch] = channelRoles_[(size_t) ch].load (std::memory_order_relaxed) == (int) SensorRole::Mic; + allMic = allMic && (isMic[ch] || ch >= numChannels); + } + // --- File mode: pull audio from transport instead of live input --- const bool fileMode = fileModeActive.load(); + + // --- Accelerometer: take over a newly built engine, then feed the live inputs --- + // (before bandpass/correction, which never touch accelerometer inputs anyway; + // file playback gets role-aware analysis with multichannel recording, spec §7.5) + if (vibPending_.load (std::memory_order_acquire) != nullptr + && vibRetired_.load (std::memory_order_acquire) == nullptr) + { + if (auto* next = vibPending_.exchange (nullptr, std::memory_order_acq_rel)) + { + vibRetired_.store (vibActive_, std::memory_order_release); + vibActive_ = next; + vibWork_ = {}; + vibSnapshot_.write (vibWork_); // invalid until the new engine publishes + } + } + // File playback has its own engine (recorded roles + calibration) + if (vibFile_.acquire() && fileMode) + { + vibWork_ = {}; + vibSnapshot_.write (vibWork_); + } + auto* vibEngine = fileMode ? vibFile_.active() : vibActive_; + if (vibSource_ != (fileMode ? 1 : 0)) + { + vibSource_ = fileMode ? 1 : 0; // live ↔ file: start the readings afresh + vibWork_ = {}; + vibSnapshot_.write (vibWork_); + if (vibEngine != nullptr) vibEngine->requestReset(); + } + if (vibActive_ != nullptr && vibActive_->hasAxes() && ! fileMode) + { + if (vibResetRequest_.exchange (false, std::memory_order_acq_rel)) + vibActive_->requestReset(); + const float* axisIn[3]; + for (int a = 0; a < 3; ++a) + { + const int ch = vibActive_->inputChannel (a); + axisIn[a] = (ch >= 0 && ch < numChannels) ? buffer.getReadPointer (ch) : nullptr; + } + if (vibActive_->process (axisIn, numSamples, ! skipMetering, vibWork_)) + { + vibSnapshot_.write (vibWork_); + if (rewStep && ! skipMetering) + stepAccum_.addVib (vibWork_); + } + } + + // --- Live input level per channel (Inputs table) --- + const int numLiveInputs = juce::jmin (getTotalNumInputChannels(), numChannels, SensorConfig::kMaxInputs); + if (numSamples > 0) + { + const double a = 1.0 - std::exp (-numSamples / (0.125 * currentSampleRate)); + for (int ch = 0; ch < numLiveInputs; ++ch) + { + const float* x = buffer.getReadPointer (ch); + double sumSq = 0.0; + float peak = 0.0f; + for (int s = 0; s < numSamples; ++s) + { + sumSq += (double) x[s] * x[s]; + peak = juce::jmax (peak, std::abs (x[s])); + } + auto& ms = inputMs_[(size_t) ch]; + ms += a * (sumSq / numSamples - ms); + inputRms_[(size_t) ch].store ((float) std::sqrt (ms), std::memory_order_relaxed); + if (peak > inputPeak_[(size_t) ch].load (std::memory_order_relaxed)) + inputPeak_[(size_t) ch].store (peak, std::memory_order_relaxed); + } + } + + // --- Calibrator measurement on one live input --- + { + const int cs = calState_.load (std::memory_order_acquire); + if (cs == CalCancel) + calState_.store (CalIdle, std::memory_order_release); + else if (cs == CalRunning && calChannel_ < numLiveInputs) + { + calMeas_.process (buffer.getReadPointer (calChannel_), numSamples); + calProgress_.store (calMeas_.progress(), std::memory_order_relaxed); + if (calMeas_.finished()) + calState_.store (CalDone, std::memory_order_release); + } + } if (fileMode) { - fileReadBuffer.setSize (2, numSamples, false, true, true); + fileReadBuffer.setSize (fileNumChannels_.load (std::memory_order_relaxed), numSamples, false, true, true); juce::AudioSourceChannelInfo info (&fileReadBuffer, 0, numSamples); transportSource.getNextAudioBlock (info); @@ -341,32 +477,38 @@ void SPLMeterAudioProcessor::processBlock (juce::AudioBuffer& buffer, } } - // Push Ch0 + Ch1 to WAV circular buffer (before bandpass/correction) - if (wavBufSize_ > 0) + // Accelerometer tracks of a recording (before bandpass/correction) + if (fileMode && vibEngine != nullptr && vibEngine->hasAxes()) { - const juce::AudioBuffer& wavSrc = fileMode ? fileReadBuffer : buffer; - const int nSrc = wavSrc.getNumChannels(); - const float* ch0 = nSrc > 0 ? wavSrc.getReadPointer (0) : nullptr; - const float* ch1 = nSrc > 1 ? wavSrc.getReadPointer (1) : ch0; - int pos = wavWritePos_.load (std::memory_order_relaxed); - for (int s = 0; s < numSamples; ++s) + if (vibResetRequest_.exchange (false, std::memory_order_acq_rel)) + vibEngine->requestReset(); + const float* axisIn[3]; + for (int a = 0; a < 3; ++a) { - wavCircBuf_[0][pos] = ch0 ? ch0[s] : 0.0f; - wavCircBuf_[1][pos] = ch1 ? ch1[s] : 0.0f; - if (++pos >= wavBufSize_) pos = 0; + const int ch = vibEngine->inputChannel (a); + axisIn[a] = (ch >= 0 && ch < fileReadBuffer.getNumChannels()) ? fileReadBuffer.getReadPointer (ch) : nullptr; } - wavWritePos_.store (pos, std::memory_order_release); + if (vibEngine->process (axisIn, numSamples, ! skipMetering, vibWork_)) + vibSnapshot_.write (vibWork_); } + vibLogLive_ = vibEngine != nullptr && vibEngine->hasAxes() && vibWork_.valid; + + // WAV recorder (before bandpass/correction) + wavRec_.acquire(); + if (auto* rec = wavRec_.active()) + rec->push (fileMode ? fileReadBuffer : buffer, numSamples); // 20Hz-20kHz bandpass (48dB/oct) applied per channel before mono mix if (apvts.getRawParameterValue ("bandpassEnabled")->load() > 0.5f) { - auto applyBP = [this] (juce::AudioBuffer& buf) + auto applyBP = [this, &isMic] (juce::AudioBuffer& buf, bool respectRoles) { const int nCh = std::min (buf.getNumChannels(), 8); const int nSa = buf.getNumSamples(); for (int ch = 0; ch < nCh; ++ch) { + if (respectRoles && ! isMic[ch]) + continue; float* data = buf.getWritePointer (ch); for (int st = 0; st < kBpStages; ++st) { @@ -375,8 +517,8 @@ void SPLMeterAudioProcessor::processBlock (juce::AudioBuffer& buffer, } } }; - if (fileMode) applyBP (fileReadBuffer); - else applyBP (buffer); + if (fileMode) applyBP (fileReadBuffer, false); + else applyBP (buffer, true); } // Correction filter (applied after bandpass, before metering) @@ -401,8 +543,22 @@ void SPLMeterAudioProcessor::processBlock (juce::AudioBuffer& buffer, const auto chClamped = juce::jmin (block.getNumChannels(), (size_t) correctionPreparedCh_); auto sub = block.getSubsetChannelBlock (0, chClamped); + + // The convolution runs on all channels at once: keep non-Mic inputs untouched + const bool keepNonMic = ! fileMode && ! allMic + && numSamples <= nonMicScratch_.getNumSamples(); + if (keepNonMic) + for (int ch = 0; ch < juce::jmin ((int) chClamped, nonMicScratch_.getNumChannels()); ++ch) + if (! isMic[ch]) + nonMicScratch_.copyFrom (ch, 0, src, ch, 0, numSamples); + juce::dsp::ProcessContextReplacing ctx (sub); correctionConv_.process (ctx); + + if (keepNonMic) + for (int ch = 0; ch < juce::jmin ((int) chClamped, nonMicScratch_.getNumChannels()); ++ch) + if (! isMic[ch]) + src.copyFrom (ch, 0, nonMicScratch_, ch, 0, numSamples); } } @@ -413,16 +569,30 @@ void SPLMeterAudioProcessor::processBlock (juce::AudioBuffer& buffer, // Muted channels have already been zeroed above, so they contribute 0 here. int activeChannels = 0; for (int ch = 0; ch < numChannels; ++ch) - if (buffer.getMagnitude (ch, 0, numSamples) > 1e-9f) + if ((ch >= SensorConfig::kMaxInputs || isMic[ch]) + && buffer.getMagnitude (ch, 0, numSamples) > 1e-9f) ++activeChannels; if (activeChannels == 0) activeChannels = 1; // silence guard const float channelScale = 1.0f / static_cast (activeChannels); - // Inputs 1 + 2 individually, for the Dual FFT (same processing stage as the mono mix) - const juce::AudioBuffer& dualSrc = fileMode ? fileReadBuffer : buffer; - const float* dualCh[2] = { - dualSrc.getNumChannels() > 0 ? dualSrc.getReadPointer (0) : nullptr, - dualSrc.getNumChannels() > 1 ? dualSrc.getReadPointer (1) : nullptr }; + // Each input individually, for per-input / Dual FFT (same processing stage as the mono mix) + const juce::AudioBuffer& chSrc = fileMode ? fileReadBuffer : buffer; + const float* chIn[kMaxFftChannels]; + float* chOut[kMaxFftChannels]; + for (int ch = 0; ch < kMaxFftChannels; ++ch) + { + chIn[ch] = ch < chSrc.getNumChannels() ? chSrc.getReadPointer (ch) : nullptr; + chOut[ch] = fftChBuf_[(size_t) ch].load (std::memory_order_acquire); + } + + // File playback mixes its Mic tracks (all tracks for files without SPLMeter metadata) + const float* fileMicIn[WavRecording::kMaxTracks]; + int fileMicCount = 0; + if (fileMode) + for (int ch = 0; ch < juce::jmin (fileReadBuffer.getNumChannels(), WavRecording::kMaxTracks); ++ch) + if (fileRoles_[(size_t) ch].load (std::memory_order_relaxed) == (int) SensorRole::Mic) + fileMicIn[fileMicCount++] = fileReadBuffer.getReadPointer (ch); + const float fileScl = 1.0f / static_cast (juce::jmax (1, fileMicCount)); for (int s = 0; s < numSamples; ++s) { @@ -430,28 +600,41 @@ void SPLMeterAudioProcessor::processBlock (juce::AudioBuffer& buffer, float raw = 0.0f; if (fileMode) { - const int fileCh = fileReadBuffer.getNumChannels(); - const float fileScl = fileCh > 0 ? 1.0f / static_cast (fileCh) : 1.0f; - for (int ch = 0; ch < fileCh; ++ch) - raw += fileReadBuffer.getReadPointer (ch)[s]; + for (int ch = 0; ch < fileMicCount; ++ch) + raw += fileMicIn[ch][s]; raw *= fileScl; } else { for (int ch = 0; ch < numChannels; ++ch) - raw += buffer.getReadPointer (ch)[s]; + if (ch >= SensorConfig::kMaxInputs || isMic[ch]) + raw += buffer.getReadPointer (ch)[s]; raw *= channelScale; } float aSample = aWeightL.processSample (raw); float cSample = cWeightL.processSample (raw); + // REW per-step L_AFmax / L_CSmax: own FAST-A and SLOW-C detectors, independent + // of the meter's FAST/SLOW choice and settled before a step starts + if (! skipMetering) + { + rewFastA_ += rewFastAlpha_ * ((double) aSample * aSample - rewFastA_); + rewSlowC_ += rewSlowAlpha_ * ((double) cSample * cSample - rewSlowC_); + } + if (rewStep) + { + if (skipMetering) ++stepAccum_.pausedSamples; + else stepAccum_.add (raw, aSample, cSample, rewFastA_, rewSlowC_); + } + // Feed FFT circular buffer { int pos = fftWritePos_.load (std::memory_order_relaxed); fftCircBuf_[pos] = raw; - fftCircBufDual_[0][pos] = dualCh[0] != nullptr ? dualCh[0][s] : 0.0f; - fftCircBufDual_[1][pos] = dualCh[1] != nullptr ? dualCh[1][s] : 0.0f; + for (int ch = 0; ch < kMaxFftChannels; ++ch) + if (chOut[ch] != nullptr) + chOut[ch][pos] = chIn[ch] != nullptr ? chIn[ch][s] : 0.0f; fftWritePos_.store ((pos + 1) % kFftCircBufSize, std::memory_order_release); } @@ -635,6 +818,21 @@ void SPLMeterAudioProcessor::pushLogEntry (float rawPk, float aPk, float cPk, e.impulsiveness = impulsiveness; e.tonality = tonality; + if (vibLogLive_) + { + e.vib.valid = true; + e.vib.quantity = vibWork_.quantity; + e.vib.axisMask = vibWork_.axisMask; + e.vib.uniaxial = vibWork_.uniaxial; + e.vib.mainKind = vibWork_.mainKind; + e.vib.main = vibWork_.main; + for (int a = 0; a < vib::kNumAxisSlots; ++a) + { + e.vib.rms[a] = vibWork_.axis[a].rms; + e.vib.peak[a] = vibWork_.axis[a].peak; + } + } + { const float N = loudnessSone; const float R = roughness / 100.0f; @@ -662,7 +860,17 @@ void SPLMeterAudioProcessor::pruneLog (float logDurationSeconds) void SPLMeterAudioProcessor::copyFftWindow (float* dest, int size, int channel) const noexcept { - const auto& src = (channel == 0 || channel == 1) ? fftCircBufDual_[(size_t) channel] : fftCircBuf_; + const float* src = fftCircBuf_.data(); + if (channel >= 0) + { + src = channel < kMaxFftChannels ? fftChBuf_[(size_t) channel].load (std::memory_order_acquire) + : nullptr; + if (src == nullptr) + { + std::fill (dest, dest + size, 0.0f); + return; + } + } int writePos = fftWritePos_.load (std::memory_order_acquire); for (int i = 0; i < size; ++i) { @@ -717,6 +925,18 @@ void SPLMeterAudioProcessor::restoreStateXml (const juce::XmlElement& xml) for (int i = 0; i < 32; ++i) channelNames_[i] = xml.getStringAttribute ("channelName_" + juce::String (i), ""); apvts.replaceState (juce::ValueTree::fromXml (xml)); + loadChannelRolesFromState(); + rebuildVibrationEngine(); + + // ≤ 3.5.2 sessions have no fftSource: derive it from the legacy Dual FFT flag + { + bool hasSource = false; + for (auto* child : xml.getChildWithTagNameIterator ("PARAM")) + hasSource = hasSource || child->getStringAttribute ("id") == "fftSource"; + if (! hasSource) + setFftSource (apvts.getRawParameterValue ("fftDual")->load() > 0.5f ? FftSourceDual + : FftSourceMix); + } // Apply the non-parameter settings held in UIState auto ui = getUiState(); @@ -772,14 +992,672 @@ void SPLMeterAudioProcessor::setStateInformation (const void* data, int sizeInBy restoreStateXml (*xml); } +//============================================================================== +int SPLMeterAudioProcessor::getFftSource() const noexcept +{ + return juce::jlimit (0, kNumFftSources - 1, + (int) apvts.getRawParameterValue ("fftSource")->load()); +} + +void SPLMeterAudioProcessor::setFftSource (int source) +{ + source = juce::jlimit (0, kNumFftSources - 1, source); + if (auto* p = apvts.getParameter ("fftSource")) + p->setValueNotifyingHost (p->convertTo0to1 ((float) source)); + if (auto* d = apvts.getParameter ("fftDual")) + d->setValueNotifyingHost (source == FftSourceDual ? 1.0f : 0.0f); +} + +//============================================================================== +// Sensor roles — persisted in UIState/Inputs as "role" (non-Mic entries only) +void SPLMeterAudioProcessor::setChannelRole (int ch, SensorRole role) +{ + if (ch < 0 || ch >= SensorConfig::kMaxInputs) + return; + channelRoles_[(size_t) ch].store ((int) role, std::memory_order_relaxed); + + auto inputs = getUiState().getOrCreateChildWithName ("Inputs", nullptr); + const juce::Identifier key ("role" + juce::String (ch)); + if (role == SensorRole::Mic) inputs.removeProperty (key, nullptr); + else inputs.setProperty (key, (int) role, nullptr); + + rebuildVibrationEngine(); +} + +//============================================================================== +// Accelerometer settings and engine +namespace +{ + const juce::Identifier kAccelNode ("Accel"); + const char* const kWeightingKeys[3] = { "weightingX", "weightingY", "weightingZ" }; + const char* const kKKeys[3] = { "kx", "ky", "kz" }; +} + +vib::VibrationSettings SPLMeterAudioProcessor::getVibrationSettings() const +{ + vib::VibrationSettings s; + const auto node = apvts.state.getChildWithName ("UIState").getChildWithName (kAccelNode); + if (! node.isValid()) + return s; + s.highPassHz = juce::jlimit (0.05, 50.0, (double) node.getProperty ("highPassHz", s.highPassHz)); + s.quantity = static_cast (juce::jlimit (0, 2, (int) node.getProperty ("quantity", 0))); + for (int a = 0; a < 3; ++a) + { + s.weighting[a] = static_cast (juce::jlimit (0, (int) vib::Weighting::KB, + (int) node.getProperty (kWeightingKeys[a], 0))); + s.k[a] = juce::jlimit (0.0, 5.0, (double) node.getProperty (kKKeys[a], 1.0)); + } + s.bandLowHz = juce::jlimit (0.1, 1000.0, (double) node.getProperty ("bandLowHz", s.bandLowHz)); + s.bandHighHz = juce::jlimit (1.0, 20000.0, (double) node.getProperty ("bandHighHz", s.bandHighHz)); + s.tauSec = juce::jlimit (0.01, 10.0, (double) node.getProperty ("tauSec", s.tauSec)); + s.main = static_cast (juce::jlimit (0, vib::kNumMainValues - 1, + (int) node.getProperty ("mainValue", 0))); + return s; +} + +void SPLMeterAudioProcessor::setVibrationSettings (const vib::VibrationSettings& s) +{ + auto node = getUiState().getOrCreateChildWithName (kAccelNode, nullptr); + node.setProperty ("highPassHz", s.highPassHz, nullptr); + node.setProperty ("quantity", (int) s.quantity, nullptr); + for (int a = 0; a < 3; ++a) + { + node.setProperty (kWeightingKeys[a], (int) s.weighting[a], nullptr); + node.setProperty (kKKeys[a], s.k[a], nullptr); + } + node.setProperty ("bandLowHz", s.bandLowHz, nullptr); + node.setProperty ("bandHighHz", s.bandHighHz, nullptr); + node.setProperty ("tauSec", s.tauSec, nullptr); + node.setProperty ("mainValue", (int) s.main, nullptr); + rebuildVibrationEngine(); +} + +double SPLMeterAudioProcessor::getAccelCalDb (int ch) const +{ + const auto inputs = apvts.state.getChildWithName ("UIState").getChildWithName ("Inputs"); + const double v = inputs.isValid() ? (double) inputs.getProperty ("cal" + juce::String (ch), 140.0) : 140.0; + return juce::jlimit (vib::calibration::kMinCalDb, vib::calibration::kMaxCalDb, v); +} + +void SPLMeterAudioProcessor::setAccelCalDb (int ch, double calDb) +{ + if (ch < 0 || ch >= SensorConfig::kMaxInputs) + return; + getUiState().getOrCreateChildWithName ("Inputs", nullptr) + .setProperty ("cal" + juce::String (ch), + juce::jlimit (vib::calibration::kMinCalDb, vib::calibration::kMaxCalDb, calDb), nullptr); + rebuildVibrationEngine(); +} + +namespace +{ + // Engine for the given channel roles; calOf(ch) gives the calibration of a channel + template + std::unique_ptr makeVibrationEngine (double fs, const vib::VibrationSettings& settings, + const SensorConfig::Roles& roles, int numInputs, + CalOf&& calOf) + { + vib::AxisInput axes[3]; + bool uniaxial = false; + if (SensorConfig::isValid (SensorConfig::validate (roles, numInputs))) + { + for (int ch = 0; ch < numInputs; ++ch) + { + int axis = -1; + switch (roles[(size_t) ch]) + { + case SensorRole::AccelX: axis = vib::AxisX; break; + case SensorRole::AccelY: axis = vib::AxisY; break; + case SensorRole::AccelZ: axis = vib::AxisZ; break; + case SensorRole::AccelUniaxial: axis = vib::AxisX; uniaxial = true; break; + case SensorRole::Mic: + case SensorRole::Off: break; + } + if (axis >= 0) + axes[axis] = { ch, calOf (ch) }; + } + } + // Without a (valid) accelerometer this is an empty engine: hasAxes() == false + return std::make_unique (fs, settings, axes, uniaxial); + } +} + +std::unique_ptr SPLMeterAudioProcessor::buildFileVibrationEngine() const +{ + auto roles = SensorConfig::defaultRoles(); + const int n = juce::jmin ((int) fileTracks_.size(), WavRecording::kMaxTracks); + for (int t = 0; t < n; ++t) + roles[(size_t) t] = fileTracks_[(size_t) t].role; + return makeVibrationEngine (currentSampleRate, getVibrationSettings(), roles, n, + [this] (int t) { return fileTracks_[(size_t) t].calDb; }); +} + +std::unique_ptr SPLMeterAudioProcessor::buildVibrationEngine() const +{ + return makeVibrationEngine (currentSampleRate, getVibrationSettings(), getChannelRoles(), + juce::jmin (getTotalNumInputChannels(), SensorConfig::kMaxInputs), + [this] (int ch) { return getAccelCalDb (ch); }); +} + +void SPLMeterAudioProcessor::rebuildVibrationEngine() +{ + delete vibRetired_.exchange (nullptr, std::memory_order_acq_rel); // no longer used by the audio thread + delete vibPending_.exchange (buildVibrationEngine().release(), std::memory_order_acq_rel); + vibFile_.publish (buildFileVibrationEngine()); // follows settings changes + rebuildWavRecorder (false); // follows role changes +} + +SensorConfig::Roles SPLMeterAudioProcessor::getChannelRoles() const noexcept +{ + SensorConfig::Roles r; + for (int ch = 0; ch < SensorConfig::kMaxInputs; ++ch) + r[(size_t) ch] = getChannelRole (ch); + return r; +} + +void SPLMeterAudioProcessor::loadChannelRolesFromState() +{ + const auto inputs = getUiState().getChildWithName ("Inputs"); + for (int ch = 0; ch < SensorConfig::kMaxInputs; ++ch) + { + const int v = inputs.isValid() ? (int) inputs.getProperty ("role" + juce::String (ch), 0) : 0; + channelRoles_[(size_t) ch].store ((int) SensorConfig::fromInt (v), std::memory_order_relaxed); + } +} + +SPLMeterAudioProcessor::AccelSensorInfo SPLMeterAudioProcessor::getAccelSensorInfo() const +{ + AccelSensorInfo info; + const auto node = apvts.state.getChildWithName ("UIState").getChildWithName (kAccelNode); + if (! node.isValid()) + return info; + info.serial = node.getProperty ("sensorSerial", juce::String()).toString(); + info.lowerLimitHz = juce::jlimit (0.01, 1000.0, (double) node.getProperty ("lowerLimitHz", info.lowerLimitHz)); + info.upperLimitHz = juce::jlimit (1.0, 100000.0, (double) node.getProperty ("upperLimitHz", info.upperLimitHz)); + info.exposureHours = juce::jlimit (0.01, 24.0, (double) node.getProperty ("exposureHours", info.exposureHours)); + return info; +} + +void SPLMeterAudioProcessor::setAccelSensorInfo (const AccelSensorInfo& info) +{ + auto node = getUiState().getOrCreateChildWithName (kAccelNode, nullptr); + node.setProperty ("sensorSerial", info.serial, nullptr); + node.setProperty ("lowerLimitHz", info.lowerLimitHz, nullptr); + node.setProperty ("upperLimitHz", info.upperLimitHz, nullptr); + node.setProperty ("exposureHours", info.exposureHours, nullptr); +} + +vib::Profile SPLMeterAudioProcessor::getVibrationProfile() const +{ + const auto node = apvts.state.getChildWithName ("UIState").getChildWithName (kAccelNode); + return vib::profileFromInt (node.isValid() ? (int) node.getProperty ("profile", 0) : 0); +} + +void SPLMeterAudioProcessor::applyVibrationProfile (vib::Profile profile) +{ + getUiState().getOrCreateChildWithName (kAccelNode, nullptr).setProperty ("profile", (int) profile, nullptr); + if (profile == vib::Profile::Custom) + return; // keeps the current settings + const auto& def = vib::profileDefinition (profile); + setVibrationDisplayUnit (def.unit); + setVibrationSettings (def.settings); +} + +juce::String SPLMeterAudioProcessor::getVibrationProfileLabel() const +{ + return juce::String::fromUTF8 (vib::profileLabel (getVibrationSettings(), getVibrationProfile()).c_str()); +} + +juce::String SPLMeterAudioProcessor::getVibrationProfileKey() const +{ + const auto p = getVibrationProfile(); + const juce::String key (vib::profileDefinition (p).key); + if (p == vib::Profile::Custom || vib::settingsMatchProfile (getVibrationSettings(), p)) + return key; + return "custom(" + key + ")"; +} + +juce::String SPLMeterAudioProcessor::getVibrationMainLabel() const +{ + return juce::String::fromUTF8 (vib::mainValueLabel (getVibrationSettings(), getVibrationProfile()).c_str()); +} + +vib::DisplayUnit SPLMeterAudioProcessor::getVibrationDisplayUnit() const +{ + const auto node = apvts.state.getChildWithName ("UIState").getChildWithName (kAccelNode); + return (vib::DisplayUnit) juce::jlimit (0, (int) vib::DisplayUnit::Db, + node.isValid() ? (int) node.getProperty ("displayUnit", 0) : 0); +} + +void SPLMeterAudioProcessor::setVibrationDisplayUnit (vib::DisplayUnit unit) +{ + getUiState().getOrCreateChildWithName (kAccelNode, nullptr).setProperty ("displayUnit", (int) unit, nullptr); +} + +namespace +{ + const juce::Identifier kLimitsNode ("AccelLimits"); + + // Numeric assessment limits: key + member (enums and flags are handled separately) + struct LimitKey { const char* key; double vib::AssessmentLimits::* member; double lo, hi; }; + const LimitKey kLimitKeys[] = { + { "wbAction", &vib::AssessmentLimits::wbAction, 0.01, 100.0 }, + { "wbLimitXY", &vib::AssessmentLimits::wbLimitXY, 0.01, 100.0 }, + { "wbLimitZ", &vib::AssessmentLimits::wbLimitZ, 0.01, 100.0 }, + { "wbVdvAction", &vib::AssessmentLimits::wbVdvAction, 0.01, 1000.0 }, + { "wbVdvLimit", &vib::AssessmentLimits::wbVdvLimit, 0.01, 1000.0 }, + { "haAction", &vib::AssessmentLimits::haAction, 0.01, 100.0 }, + { "haLimit", &vib::AssessmentLimits::haLimit, 0.01, 100.0 }, + { "machAB", &vib::AssessmentLimits::machAB, 0.01, 1000.0 }, + { "machBC", &vib::AssessmentLimits::machBC, 0.01, 1000.0 }, + { "machCD", &vib::AssessmentLimits::machCD, 0.01, 1000.0 }, + { "din2Au", &vib::AssessmentLimits::din2Au, 0.001, 100.0 }, + { "din2Ao", &vib::AssessmentLimits::din2Ao, 0.001, 100.0 }, + { "din2Ar", &vib::AssessmentLimits::din2Ar, 0.001, 100.0 }, + { "din2ExposureHours", &vib::AssessmentLimits::din2ExposureHours, 0.0, 16.0 }, + { "din3At10", &vib::AssessmentLimits::din3At10, 0.01, 1000.0 }, + { "din3At50", &vib::AssessmentLimits::din3At50, 0.01, 1000.0 }, + { "din3At100", &vib::AssessmentLimits::din3At100, 0.01, 1000.0 }, + { "din3Single", &vib::AssessmentLimits::din3Single, 0.01, 1000.0 }, + }; + const char* const kLimitEnumKeys[] = { "wbPreset", "wbCriterion", "machGroup", "machFoundation", + "din2Zone", "din2Night", "din3Line", "din3Location", "din3LongTerm" }; + + // Keys of UIState/Accel exchanged with JSON settings files + const char* const kAccelJsonKeys[] = { "highPassHz", "quantity", "weightingX", "weightingY", "weightingZ", + "kx", "ky", "kz", "bandLowHz", "bandHighHz", "tauSec", + "sensorSerial", "lowerLimitHz", "upperLimitHz", "displayUnit", + "mainValue", "profile", "exposureHours" }; +} + +vib::AssessmentLimits SPLMeterAudioProcessor::getAssessmentLimits() const +{ + auto l = vib::defaultAssessmentLimits(); + const auto node = apvts.state.getChildWithName ("UIState").getChildWithName (kLimitsNode); + if (! node.isValid()) + return l; + for (const auto& k : kLimitKeys) + l.*k.member = juce::jlimit (k.lo, k.hi, (double) node.getProperty (k.key, l.*k.member)); + auto e = [&] (const char* key, int current, int maxV) { return juce::jlimit (0, maxV, (int) node.getProperty (key, current)); }; + l.wbPreset = (vib::WholeBodyPreset) e ("wbPreset", (int) l.wbPreset, 1); + l.wbCriterion = (vib::WholeBodyCriterion) e ("wbCriterion", (int) l.wbCriterion, 1); + l.machGroup = (vib::MachineGroup) e ("machGroup", (int) l.machGroup, 1); + l.machFoundation = (vib::Foundation) e ("machFoundation", (int) l.machFoundation, 1); + l.din2Zone = (vib::Din4150Zone) e ("din2Zone", (int) l.din2Zone, 4); + l.din2Night = e ("din2Night", l.din2Night ? 1 : 0, 1) != 0; + l.din3Line = (vib::Din4150Line) e ("din3Line", (int) l.din3Line, 2); + l.din3Location = (vib::Din4150Location) e ("din3Location", (int) l.din3Location, 2); + l.din3LongTerm = e ("din3LongTerm", l.din3LongTerm ? 1 : 0, 1) != 0; + return l; +} + +void SPLMeterAudioProcessor::setAssessmentLimits (const vib::AssessmentLimits& l) +{ + auto node = getUiState().getOrCreateChildWithName (kLimitsNode, nullptr); + for (const auto& k : kLimitKeys) + node.setProperty (k.key, l.*k.member, nullptr); + node.setProperty ("wbPreset", (int) l.wbPreset, nullptr); + node.setProperty ("wbCriterion", (int) l.wbCriterion, nullptr); + node.setProperty ("machGroup", (int) l.machGroup, nullptr); + node.setProperty ("machFoundation", (int) l.machFoundation, nullptr); + node.setProperty ("din2Zone", (int) l.din2Zone, nullptr); + node.setProperty ("din2Night", l.din2Night ? 1 : 0, nullptr); + node.setProperty ("din3Line", (int) l.din3Line, nullptr); + node.setProperty ("din3Location", (int) l.din3Location, nullptr); + node.setProperty ("din3LongTerm", l.din3LongTerm ? 1 : 0, nullptr); +} + +vib::Assessment SPLMeterAudioProcessor::getVibrationAssessment() const +{ + const auto s = getVibrationSettings(); + return vib::assess (getVibrationProfile(), getVibrationSnapshot(), s.k, + getAccelSensorInfo().exposureHours, getAssessmentLimits()); +} + +rew::Sequence SPLMeterAudioProcessor::getRewSequence() const +{ + rew::Sequence q; + const auto node = apvts.state.getChildWithName ("UIState").getChildWithName ("RewSequencer"); + if (node.isValid()) + rew::sequenceFromVar (juce::JSON::parse (node.getProperty ("json").toString()), q); + return q; +} + +void SPLMeterAudioProcessor::setRewSequence (const rew::Sequence& sequence) +{ + getUiState().getOrCreateChildWithName ("RewSequencer", nullptr) + .setProperty ("json", rew::toJsonText (sequence), nullptr); +} + +bool SPLMeterAudioProcessor::startRewRun (bool dryRun, std::unique_ptr transport, + rew::RunOptions options) +{ + if (rewSequencer_.isRunning()) + return false; + const auto seq = getRewSequence(); + if (transport == nullptr) + transport = std::make_unique (seq.port); + options.dryRun = dryRun; + + // Header of the results, read here on the message thread (spec §6.2) + rew::RunInfo info; + info.splmeterVersion = JucePlugin_VersionString; + info.calOffsetDb = apvts.getRawParameterValue ("calOffset")->load(); + info.vibUnit = getVibrationDisplayUnit(); + for (int ch = 0; ch < juce::jmin (getTotalNumInputChannels(), SensorConfig::kMaxInputs); ++ch) + { + const auto role = getChannelRole (ch); + if (! SensorConfig::isAccel (role)) + continue; + static const char* names[] = { "Mic", "X", "Y", "Z", "uniaxial", "Off" }; + auto line = juce::String (names[(int) role]) + ": " + getChannelName (ch) + ", " + + juce::String (getAccelCalDb (ch), 2) + " dB"; + if (const auto calInfo = getAccelCalInfo (ch); calInfo.isNotEmpty()) + line << " (" << calInfo << ")"; + info.vibCalibration.add (line); + } + if (! info.vibCalibration.isEmpty()) + info.vibProfile = getVibrationProfileKey(); + + { + std::lock_guard l (rewMutex_); + rewLevels_.clear(); + rewResultsFile_ = juce::File(); + } + + rew::Hooks hooks; + const int total = rew::totalSweeps (seq); + auto sweep = std::make_shared (0); + hooks.stepStarted = [this, sweep, total, markers = seq.addLogMarkers] (const rew::StepResult& r) + { + beginRewStepMeasurement(); + if (r.attempts == 1) + ++*sweep; + if (markers) + { + const auto now = juce::Time::currentTimeMillis() - getPauseOffsetMs(); + auto text = "REW " + juce::String (*sweep) + "/" + juce::String (total) + " " + r.title; + if (r.attempts > 1) text << " (retry)"; + std::lock_guard l (rewMutex_); + if (pendingMarkers_.size() < 1000) + pendingMarkers_.push_back ({ now, text }); + } + }; + hooks.stepFinished = [this] (const rew::StepResult&) + { + const auto levels = endRewStepMeasurement(); // invalid for steps without a sweep + std::lock_guard l (rewMutex_); + rewLevels_.push_back (levels); + }; + hooks.runFinished = [this, seq, info] (const rew::Progress& p) -> juce::String + { + if (p.dryRun || p.results.empty()) + return {}; + auto runInfo = info; + runInfo.finished = juce::Time::getCurrentTime(); + juce::String error; + const auto file = rew::writeResults (seq, p, getRewStepLevels(), runInfo, error); + std::lock_guard l (rewMutex_); + rewResultsFile_ = file; + return file != juce::File() ? "Results: " + file.getFullPathName() : "Results not saved: " + error; + }; + return rewSequencer_.start (seq, std::move (transport), options, std::move (hooks)); +} + +void SPLMeterAudioProcessor::beginRewStepMeasurement() noexcept +{ + stepState_.store (kStepBegin, std::memory_order_release); +} + +rew::StepLevels SPLMeterAudioProcessor::endRewStepMeasurement() +{ + int expected = kStepRunning; + if (! stepState_.compare_exchange_strong (expected, kStepEnd, std::memory_order_acq_rel)) + { + stepState_.store (kStepIdle, std::memory_order_release); // never started (no audio) or idle + return {}; + } + auto take = [this] + { + const auto r = stepResult_; + stepState_.store (kStepIdle, std::memory_order_release); + return r; + }; + for (int i = 0; i < 100; ++i) + { + if (stepState_.load (std::memory_order_acquire) == kStepDone) + return take(); + juce::Thread::sleep (5); + } + expected = kStepEnd; // audio stopped: give up, unless it finished just now + if (stepState_.compare_exchange_strong (expected, kStepIdle, std::memory_order_acq_rel)) + return {}; + return stepState_.load (std::memory_order_acquire) == kStepDone ? take() : rew::StepLevels {}; +} + +void SPLMeterAudioProcessor::handleRewStep (float calOffset) noexcept +{ + int st = stepState_.load (std::memory_order_acquire); + if (st == kStepBegin) + { + stepAccum_ = {}; + stepState_.compare_exchange_strong (st, kStepRunning, std::memory_order_acq_rel); + } + else if (st == kStepEnd) + { + const auto& a = stepAccum_; + auto db = [calOffset] (double ms) { return 10.0 * std::log10 (std::max (ms, 1.0e-20)) + calOffset; }; + rew::StepLevels r; + r.valid = a.n > 0; + r.seconds = (double) a.n / currentSampleRate; + r.pausedSeconds = (double) a.pausedSamples / currentSampleRate; + if (a.n > 0) + { + r.laeq = db (a.sumA / (double) a.n); + r.lceq = db (a.sumC / (double) a.n); + r.lzeq = db (a.sumZ / (double) a.n); + r.lafmax = db (a.maxFastA); + r.lcsmax = db (a.maxSlowC); + r.lcpeak = db ((double) a.peakC * a.peakC); + } + r.vibValid = a.vibCount > 0; + r.quantity = a.vibQuantity; + r.axisMask = a.vibAxisMask; + r.uniaxial = a.vibUniaxial; + for (int slot = 0; slot < vib::kNumAxisSlots && r.vibValid; ++slot) + { + r.vibRms[slot] = std::sqrt (a.vibSumSq[slot] / (double) a.vibCount); + r.vibPeak[slot] = a.vibPeak[slot]; + } + stepResult_ = r; + stepState_.compare_exchange_strong (st, kStepDone, std::memory_order_acq_rel); + } +} + +std::vector SPLMeterAudioProcessor::getRewStepLevels() const +{ + std::lock_guard l (rewMutex_); + return rewLevels_; +} + +juce::File SPLMeterAudioProcessor::getRewResultsFile() const +{ + std::lock_guard l (rewMutex_); + return rewResultsFile_; +} + +std::vector SPLMeterAudioProcessor::takePendingMarkers() +{ + std::lock_guard l (rewMutex_); + return std::exchange (pendingMarkers_, {}); +} + +juce::var SPLMeterAudioProcessor::getInputsJson() const +{ + juce::Array list; + const auto inputs = apvts.state.getChildWithName ("UIState").getChildWithName ("Inputs"); + for (int ch = 0; ch < SensorConfig::kMaxInputs; ++ch) + { + const auto chs = juce::String (ch); + if (getChannelRole (ch) == SensorRole::Mic && ! inputs.hasProperty ("cal" + chs)) + continue; // defaults are not written + auto* o = new juce::DynamicObject(); + o->setProperty ("channel", ch); + o->setProperty ("role", (int) getChannelRole (ch)); + o->setProperty ("calDb", getAccelCalDb (ch)); + o->setProperty ("calDate", inputs.getProperty ("calDate" + chs, juce::String())); + o->setProperty ("calMethod", inputs.getProperty ("calMethod" + chs, juce::String())); + list.add (juce::var (o)); + } + return list; +} + +juce::var SPLMeterAudioProcessor::getAccelJson() const +{ + auto* o = new juce::DynamicObject(); + const auto node = apvts.state.getChildWithName ("UIState").getChildWithName (kAccelNode); + if (node.isValid()) + for (auto* key : kAccelJsonKeys) + if (node.hasProperty (key)) + o->setProperty (key, node.getProperty (key)); + const auto limits = apvts.state.getChildWithName ("UIState").getChildWithName (kLimitsNode); + if (limits.isValid()) + { + auto* l = new juce::DynamicObject(); + for (int i = 0; i < limits.getNumProperties(); ++i) + l->setProperty (limits.getPropertyName (i), limits.getProperty (limits.getPropertyName (i))); + o->setProperty ("limits", juce::var (l)); + } + return juce::var (o); +} + +void SPLMeterAudioProcessor::setInputsAndAccelFromJson (const juce::var& inputs, const juce::var& accel) +{ + if (auto* list = inputs.getArray()) + { + auto node = getUiState().getOrCreateChildWithName ("Inputs", nullptr); + node.removeAllProperties (nullptr); // the file describes the complete input setup + for (const auto& v : *list) + { + const int ch = v.getProperty ("channel", -1); + if (ch < 0 || ch >= SensorConfig::kMaxInputs) + continue; + const auto chs = juce::String (ch); + const auto role = SensorConfig::fromInt (v.getProperty ("role", 0)); + if (role != SensorRole::Mic) + node.setProperty ("role" + chs, (int) role, nullptr); + if (v.hasProperty ("calDb")) + node.setProperty ("cal" + chs, juce::jlimit (vib::calibration::kMinCalDb, vib::calibration::kMaxCalDb, + (double) v.getProperty ("calDb", 140.0)), nullptr); + for (auto* key : { "calDate", "calMethod" }) + if (v.getProperty (key, juce::String()).toString().isNotEmpty()) + node.setProperty (key + chs, v.getProperty (key, {}), nullptr); + } + loadChannelRolesFromState(); + } + if (auto* obj = accel.getDynamicObject()) + { + auto node = getUiState().getOrCreateChildWithName (kAccelNode, nullptr); + for (auto* key : kAccelJsonKeys) + if (obj->hasProperty (key)) + node.setProperty (key, obj->getProperty (key), nullptr); + if (auto* lim = obj->getProperty ("limits").getDynamicObject()) + { + auto ln = getUiState().getOrCreateChildWithName (kLimitsNode, nullptr); + for (const auto& k : kLimitKeys) + if (lim->hasProperty (k.key)) + ln.setProperty (k.key, lim->getProperty (k.key), nullptr); + for (auto* key : kLimitEnumKeys) + if (lim->hasProperty (key)) + ln.setProperty (key, lim->getProperty (key), nullptr); + } + } + rebuildVibrationEngine(); // getters clamp every value +} + +juce::String SPLMeterAudioProcessor::getAccelCalInfo (int ch) const +{ + const auto inputs = apvts.state.getChildWithName ("UIState").getChildWithName ("Inputs"); + if (! inputs.isValid()) + return {}; + const auto date = inputs.getProperty ("calDate" + juce::String (ch), juce::String()).toString(); + const auto method = inputs.getProperty ("calMethod" + juce::String (ch), juce::String()).toString(); + if (date.isEmpty()) + return {}; + return method.isNotEmpty() ? date + " · " + method : date; +} + +void SPLMeterAudioProcessor::setAccelCalInfo (int ch, const juce::String& method) +{ + if (ch < 0 || ch >= SensorConfig::kMaxInputs) + return; + auto inputs = getUiState().getOrCreateChildWithName ("Inputs", nullptr); + inputs.setProperty ("calDate" + juce::String (ch), juce::Time::getCurrentTime().formatted ("%Y-%m-%d"), nullptr); + inputs.setProperty ("calMethod" + juce::String (ch), method, nullptr); +} + +//============================================================================== +// Calibrator measurement (spec §4) +bool SPLMeterAudioProcessor::startAccelCalibration (int ch, double referenceHz) +{ + if (ch < 0 || ch >= juce::jmin (getTotalNumInputChannels(), SensorConfig::kMaxInputs) + || referenceHz <= 0.0 || referenceHz > 0.4 * currentSampleRate) + return false; + + // Only from Idle or Done: the audio thread does not touch calMeas_ then + int s = calState_.load (std::memory_order_acquire); + if (s != CalIdle && s != CalDone) + return false; + calChannel_ = ch; + calMeas_.prepare (currentSampleRate, referenceHz); + calProgress_.store (0.0, std::memory_order_relaxed); + return calState_.compare_exchange_strong (s, CalRunning, std::memory_order_acq_rel); +} + +void SPLMeterAudioProcessor::cancelAccelCalibration() noexcept +{ + int s = CalRunning; + if (! calState_.compare_exchange_strong (s, CalCancel, std::memory_order_acq_rel) && s == CalDone) + calState_.store (CalIdle, std::memory_order_release); +} + +bool SPLMeterAudioProcessor::takeAccelCalibrationResult (vib::CalibratorMeasurement::Result& result) noexcept +{ + if (calState_.load (std::memory_order_acquire) != CalDone) + return false; + result = calMeas_.result(); + calState_.store (CalIdle, std::memory_order_release); + return true; +} + //============================================================================== void SPLMeterAudioProcessor::loadFile (const juce::File& file) { auto* reader = formatManager.createReaderFor (file); if (reader == nullptr) return; + // Track roles + calibration of an SPLMeter recording (spec §7.5); other + // files: every channel is a microphone channel, as before + std::vector tracks; + if (! WavRecording::fromJson (reader->metadataValues.getValue (juce::WavAudioFormat::aswgUserData, {}), tracks)) + tracks.clear(); + const int fileChannels = (int) reader->numChannels; + tracks.resize ((size_t) juce::jmin (fileChannels, WavRecording::kMaxTracks)); // missing entries: Mic + fileTracks_ = tracks; + bool anyAccel = false; + for (int t = 0; t < WavRecording::kMaxTracks; ++t) + { + const auto role = t < (int) tracks.size() ? tracks[(size_t) t].role : SensorRole::Mic; + fileRoles_[(size_t) t].store ((int) role, std::memory_order_relaxed); + anyAccel = anyAccel || SensorConfig::isAccel (role); + } + fileHasAccel_.store (anyAccel); + fileNumChannels_.store (juce::jlimit (2, WavRecording::kMaxTracks, fileChannels)); + vibFile_.publish (buildFileVibrationEngine()); + auto newSource = std::make_unique (reader, true); - transportSource.setSource (newSource.get(), 0, nullptr, reader->sampleRate); + // Up to 8 tracks (the transport passes only 2 channels by default) + transportSource.setSource (newSource.get(), 0, nullptr, reader->sampleRate, WavRecording::kMaxTracks); readerSource = std::move (newSource); transportSource.setPosition (0.0); @@ -1066,40 +1944,73 @@ void SPLMeterAudioProcessor::clearGraphOverlay2() //============================================================================== bool SPLMeterAudioProcessor::saveWavToFile (const juce::File& destFile) { - if (wavBufSize_ <= 0 || currentSampleRate < 1.0) return false; + const auto* rec = wavRec_.current(); + if (rec == nullptr || currentSampleRate < 1.0) return false; - const float logDurS = apvts.getRawParameterValue ("logDuration")->load(); - const int numSamplesToSave = juce::jmin (wavBufSize_, - static_cast (logDurS * currentSampleRate)); + const float logDurS = apvts.getRawParameterValue ("logDuration")->load(); + const int numSamplesToSave = juce::jmin (rec->size(), static_cast (logDurS * currentSampleRate)); if (numSamplesToSave <= 0) return false; - // Snapshot: copy the most recent numSamplesToSave samples from the circular buffer. - // Reading across the audio-thread write is a benign race for audio data. - const int writePos = wavWritePos_.load (std::memory_order_acquire); - - juce::AudioBuffer snapBuf (2, numSamplesToSave); - float* out0 = snapBuf.getWritePointer (0); - float* out1 = snapBuf.getWritePointer (1); + const auto snapBuf = rec->snapshot (numSamplesToSave); - for (int s = 0; s < numSamplesToSave; ++s) + // Track roles + calibration (only for accelerometer recordings: the default + // stereo recording stays as in 3.5.2) + juce::StringPairArray metadata; + std::vector tracks; + bool anyAccel = false; + for (int input : rec->inputs()) { - const int readPos = (writePos - numSamplesToSave + s + wavBufSize_) % wavBufSize_; - out0[s] = wavCircBuf_[0][readPos]; - out1[s] = wavCircBuf_[1][readPos]; + WavRecording::Track t; + t.input = input; + t.role = getChannelRole (input); + t.calDb = getAccelCalDb (input); + t.name = getChannelName (input); + anyAccel = anyAccel || SensorConfig::isAccel (t.role); + tracks.push_back (t); } + if (anyAccel) + metadata.set (juce::WavAudioFormat::aswgUserData, WavRecording::toJson (tracks)); - // Write stereo 24-bit WAV juce::WavAudioFormat wavFmt; auto stream = std::make_unique (destFile); if (!stream->openedOk()) return false; stream->setPosition (0); stream->truncate(); - auto* writer = wavFmt.createWriterFor (stream.release(), currentSampleRate, 2, 24, {}, 0); + std::unique_ptr writer ( + wavFmt.createWriterFor (stream.get(), currentSampleRate, (unsigned int) snapBuf.getNumChannels(), + 24, metadata, 0)); if (writer == nullptr) return false; + stream.release(); // owned by the writer now + return writer->writeFromAudioSampleBuffer (snapBuf, 0, numSamplesToSave); +} + +std::vector SPLMeterAudioProcessor::getRecordedInputs() const +{ + if (const auto* rec = wavRec_.current()) + return rec->inputs(); + return {}; +} - std::unique_ptr writerOwner (writer); - return writerOwner->writeFromAudioSampleBuffer (snapBuf, 0, numSamplesToSave); +void SPLMeterAudioProcessor::rebuildWavRecorder (bool audioStopped) +{ + auto layout = WavRecording::layoutFor (getChannelRoles(), getTotalNumInputChannels()); + if (! audioStopped && layout == wavLayout_ && wavRec_.current() != nullptr) + return; // same tracks: keep the recorded history + wavLayout_ = layout; + const float logDurS = apvts.getRawParameterValue ("logDuration")->load(); + auto rec = std::make_unique (std::move (layout), + static_cast (logDurS * currentSampleRate)); + if (audioStopped) wavRec_.replaceNow (std::move (rec)); + else wavRec_.publish (std::move (rec)); +} + +bool SPLMeterAudioProcessor::isVibrationAvailable() const +{ + if (isFileModeActive()) + return fileHasAccelerometer(); + const auto v = getSensorValidity(); + return SensorConfig::isValid (v) && v != SensorConfig::Validity::NoAccelerometer; } //============================================================================== diff --git a/Source/PluginProcessor.h b/Source/PluginProcessor.h index e621529..1b94e2c 100644 --- a/Source/PluginProcessor.h +++ b/Source/PluginProcessor.h @@ -8,10 +8,34 @@ #include "ImpulsivenessEstimator.h" #include "TonalityEstimator.h" #include "SoundDetective.h" +#include "SensorConfig.h" +#include "Vibration/VibrationEngine.h" +#include "Vibration/CalibratorMeasurement.h" +#include "Vibration/Units.h" +#include "Vibration/Profiles.h" +#include "Vibration/Assessment.h" +#include "Rew/RewRunResults.h" +#include "RtHandover.h" +#include "WavRecording.h" +#include #include #include //============================================================================== +// Accelerometer values of one log entry (vibration spec §7.3), SI units of the +// quantity (m/s², m/s, m). Slots X, Y, Z, Σ as vib::Axis. +struct VibrationLog +{ + bool valid = false; // live accelerometer readings in this entry + int quantity = 0; // vib::Quantity + int axisMask = 0; // present X/Y/Z + bool uniaxial = false; + float rms[4] {}; + float peak[4] {}; // max |x| in the last snapshot interval + int mainKind = 0; // vib::MainValue of the profile + float main = 0.0f; // the profile's main value +}; + struct LogEntry { juce::int64 timestampMs; @@ -29,6 +53,7 @@ struct LogEntry float psychoAnnoyance = 0.0f; float impulsiveness = 0.0f; float tonality = 0.0f; + VibrationLog vib; }; //============================================================================== @@ -49,8 +74,12 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor bool isBusesLayoutSupported (const BusesLayout& layouts) const override { + // The standalone app takes every input the device opens (up to the 32 + // mute/role slots); plugins keep 1–8 (vibration spec §10). Rejecting a + // device with more inputs would make JUCE fall back to a single input. + const int maxIns = wrapperType == wrapperType_Standalone ? SensorConfig::kMaxInputs : 8; int n = layouts.getMainInputChannels(); - return n >= 1 && n <= 8; + return n >= 1 && n <= maxIns; } //========================================================================== @@ -143,8 +172,19 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor // FFT circular buffer (audio thread → GUI, lock-free) // Sized to the largest selectable L_FFT window (524288 = 512k samples). static constexpr int kFftCircBufSize = 524288; - // channel -1 = mono mix of all inputs; 0 / 1 = input 1 / 2 alone (Dual FFT) + // channel -1 = mono mix of all inputs; 0 … kMaxFftChannels-1 = that input alone + // (post mute / bandpass / correction). Inputs without a buffer read as silence. + static constexpr int kMaxFftChannels = 8; void copyFftWindow (float* dest, int size, int channel = -1) const noexcept; + + // FFT source (parameter "fftSource"): what the timeline FFT analyses. + // Values are persisted — only append new entries. + enum FftSource { FftSourceMix = 0, FftSourceDual = 1, FftSourceInput1 = 2 }; + static constexpr int kNumFftSources = FftSourceInput1 + kMaxFftChannels; + int getFftSource() const noexcept; + // Sets "fftSource" and keeps the legacy "fftDual" flag in step, so sessions + // stay readable by v3.5.2 (message thread). + void setFftSource (int source); int pullSpectroSamples (float* dest, int maxSamples) noexcept; double getSampleRate() const noexcept { return currentSampleRate; } @@ -176,7 +216,11 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor // DIN 15905-5: session-long C-weighted peak (does not decay with peakHoldTime) float getSessionPeakDBCSPL () const noexcept { return sessionPeakDBCSPL_.load (std::memory_order_relaxed); } - void resetSessionPeak () noexcept { sessionPeakDBCSPL_.store (-999.0f, std::memory_order_relaxed); } + void resetSessionPeak () noexcept + { + sessionPeakDBCSPL_.store (-999.0f, std::memory_order_relaxed); + resetVibrationStats(); // session statistics reset together (spec §5.3) + } // NIOSH REL: cumulative 8-hour noise-dose percentage (100% = 85 dB(A) for 8 h, // 3 dB exchange rate, 80 dB(A) threshold). @@ -223,8 +267,17 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor const std::vector>& getGraphOverlay2Points() const { return graphOverlay2Points_; } //========================================================================== - // WAV recorder + // WAV recorder: inputs 1 + 2, or every non-Off input (≤ 8) with an + // accelerometer, with track roles + calibration in the iXML chunk (spec §7.5) bool saveWavToFile (const juce::File& destFile); + std::vector getRecordedInputs() const; + + // File playback of an SPLMeter recording: the recorded track roles and + // calibration drive the mix and the vibration analysis + std::vector getFileTracks() const { return fileTracks_; } + bool fileHasAccelerometer() const noexcept { return fileHasAccel_.load(); } + // Vibration readings exist: live accelerometer, or playback of a recording with one + bool isVibrationAvailable() const; //========================================================================== // Impulse Fidelity @@ -268,6 +321,120 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor channelNames_[ch] = name; } + //========================================================================== + // Sensor roles per input (vibration spec §3.1). Default: all Mic. + // Persisted in UIState/Inputs; mirrored into atomics for the audio thread. + SensorRole getChannelRole (int ch) const noexcept + { + jassert (ch >= 0 && ch < SensorConfig::kMaxInputs); + return SensorConfig::fromInt (channelRoles_[(size_t) ch].load (std::memory_order_relaxed)); + } + void setChannelRole (int ch, SensorRole role); + SensorConfig::Roles getChannelRoles() const noexcept; + SensorConfig::Validity getSensorValidity() const noexcept + { + return SensorConfig::validate (getChannelRoles(), getTotalNumInputChannels()); + } + + //========================================================================== + // Accelerometer (vibration spec §3–§5). Settings persist in UIState/Accel, + // per-input calibration in UIState/Inputs ("cal"). Message thread only. + vib::VibrationSettings getVibrationSettings() const; + void setVibrationSettings (const vib::VibrationSettings& settings); + double getAccelCalDb (int ch) const; + void setAccelCalDb (int ch, double calDb); + + // Latest readout (published every 125 ms); valid == false without accelerometer + vib::VibrationSnapshot getVibrationSnapshot() const noexcept + { + vib::VibrationSnapshot s; + if (! vibSnapshot_.read (s)) s.valid = false; + return s; + } + void resetVibrationStats() noexcept { vibResetRequest_.store (true, std::memory_order_release); } + + // Sensor information for the report (UIState/Accel; no engine rebuild) + struct AccelSensorInfo + { + juce::String serial; + double lowerLimitHz = 0.5; // usable range from the datasheet (spec §3.2) + double upperLimitHz = 10000.0; + double exposureHours = 8.0; // daily exposure time T for A(8) + }; + AccelSensorInfo getAccelSensorInfo() const; + void setAccelSensorInfo (const AccelSensorInfo& info); + + // Measurement profile (spec §6, UIState/Accel "profile"): applying one sets the + // accelerometer settings and display unit; later edits make it "Custom (based on …)" + vib::Profile getVibrationProfile() const; + void applyVibrationProfile (vib::Profile profile); + juce::String getVibrationProfileLabel() const; // e.g. "Custom (based on Hand-arm (ISO 5349-1))" + juce::String getVibrationProfileKey() const; // CSV/JSON: "hand-arm" or "custom(hand-arm)" + juce::String getVibrationMainLabel() const; // e.g. "a_w" + + // Assessment reference values (spec §9.3, UIState/AccelLimits); defaults from the standards + vib::AssessmentLimits getAssessmentLimits() const; + void setAssessmentLimits (const vib::AssessmentLimits& limits); + vib::Assessment getVibrationAssessment() const; // of the latest snapshot for the current profile + + // REW measurement sequencer (REW sequencer spec §3): the last edited + // sequence, persisted in UIState/RewSequencer. Message thread only. + rew::Sequence getRewSequence() const; + void setRewSequence (const rew::Sequence& sequence); + + // Runs the stored sequence. The processor owns the run (spec Q4), so it goes on + // when the window or editor closes. transport: nullptr = HTTP to REW on the + // sequence's port (tests pass a simulated REW). False if a run is active. + bool startRewRun (bool dryRun, std::unique_ptr transport = nullptr, + rew::RunOptions options = {}); + rew::Sequencer& getRewSequencer() noexcept { return rewSequencer_; } + + // Per-step measurement for the REW sequencer (spec §6.1), independent of the + // user's LAeq, log and vibration accumulators. Not on the audio thread; the + // end waits up to 0.5 s for the audio thread and returns invalid levels if + // no audio ran. + void beginRewStepMeasurement() noexcept; + rew::StepLevels endRewStepMeasurement(); + std::vector getRewStepLevels() const; // current/last run, in result order + juce::File getRewResultsFile() const; // CSV of the last run ({} = none) + + // Timeline markers added outside the editor (one per REW sweep); the editor collects them + struct TimelineMarker { juce::int64 timestampMs; juce::String text; }; + std::vector takePendingMarkers(); + + // Display unit of the vibration readout (UIState/Accel "displayUnit") + vib::DisplayUnit getVibrationDisplayUnit() const; + void setVibrationDisplayUnit (vib::DisplayUnit unit); + + // JSON settings export/import (spec §8): "inputs" (role + calibration per input) + // and "accel" (sensor settings). Import ignores absent blocks (older files). + juce::var getInputsJson() const; + juce::var getAccelJson() const; + void setInputsAndAccelFromJson (const juce::var& inputs, const juce::var& accel); + + // Calibration date/method per input (UIState/Inputs "calDate", "calMethod") + juce::String getAccelCalInfo (int ch) const; // e.g. "2026-11-12 · calibrator", empty if never + void setAccelCalInfo (int ch, const juce::String& method); // stamps today's date + + // Live input level per channel (raw, after mute), for the Inputs table. + // RMS is smoothed with τ = 125 ms; the peak is the maximum since the last read. + float getInputRms (int ch) const noexcept + { + return ch >= 0 && ch < SensorConfig::kMaxInputs ? inputRms_[(size_t) ch].load (std::memory_order_relaxed) : 0.0f; + } + float takeInputPeak (int ch) noexcept + { + return ch >= 0 && ch < SensorConfig::kMaxInputs ? inputPeak_[(size_t) ch].exchange (0.0f, std::memory_order_relaxed) : 0.0f; + } + + // Handheld-calibrator measurement on one input (spec §4). Message thread: + // start → poll getAccelCalibrationProgress() → takeAccelCalibrationResult(). + bool startAccelCalibration (int ch, double referenceHz); + void cancelAccelCalibration() noexcept; + double getAccelCalibrationProgress() const noexcept { return calProgress_.load (std::memory_order_relaxed); } + // Returns true (and fills result) once the measurement has finished + bool takeAccelCalibrationResult (vib::CalibratorMeasurement::Result& result) noexcept; + //========================================================================== juce::AudioProcessorValueTreeState apvts; @@ -278,6 +445,42 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor AWeightingFilter aWeightL; CWeightingFilter cWeightL; + // Sensor roles (audio-thread mirror of UIState/Inputs) + std::array, SensorConfig::kMaxInputs> channelRoles_ {}; + void loadChannelRolesFromState(); + + // Accelerometer engine hand-over (real-time safe): the message thread builds a + // complete engine and puts it in vibPending_; the audio thread swaps it in at the + // start of a block and parks the previous one in vibRetired_, which the message + // thread deletes on its next rebuild (or in the destructor). The audio thread only + // swaps when vibRetired_ is empty, so it never allocates or frees. + std::unique_ptr buildVibrationEngine() const; + void rebuildVibrationEngine(); + std::atomic vibPending_ { nullptr }; + std::atomic vibRetired_ { nullptr }; + vib::VibrationEngine* vibActive_ = nullptr; // audio thread + std::atomic vibResetRequest_ { false }; + vib::SeqLock vibSnapshot_; + vib::VibrationSnapshot vibWork_; // audio thread + bool vibLogLive_ = false; // audio thread: vibWork_ is current + + // Input level meters (audio thread writes) + std::array, SensorConfig::kMaxInputs> inputRms_ {}, inputPeak_ {}; + std::array inputMs_ {}; // audio thread + + // Calibrator measurement hand-over: the message thread configures calMeas_ + // only while calState_ is Idle, the audio thread uses it only while Running, + // and the message thread reads the result once it is Done. + enum CalState : int { CalIdle = 0, CalRunning, CalCancel, CalDone }; + std::atomic calState_ { CalIdle }; + std::atomic calProgress_ { 0.0 }; + int calChannel_ = -1; + vib::CalibratorMeasurement calMeas_; + + // Accelerometer channels are restored from here after the correction + // convolution, which processes all channels at once (allocated in prepareToPlay) + juce::AudioBuffer nonMicScratch_; + // 20Hz-20kHz bandpass: 8th-order Butterworth = 4 cascaded biquad stages static constexpr int kBpStages = 4; juce::IIRFilter bpHP[32][kBpStages]; @@ -324,7 +527,11 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor std::atomic midiLearnParamIndex { -1 }; std::array fftCircBuf_ {}; - std::array, 2> fftCircBufDual_ {}; // inputs 1 + 2, same write pos + // Per-input FFT ring buffers (same write position as fftCircBuf_). Allocated in + // prepareToPlay for the inputs present and never freed or moved afterwards, so + // the GUI can read through the published pointer at any time. + std::array, kMaxFftChannels> fftChStorage_; + std::array, kMaxFftChannels> fftChBuf_ {}; std::atomic fftWritePos_ { 0 }; std::atomic spectroReadPos_ { 0 }; @@ -386,9 +593,18 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor juce::String channelNames_[32]; // WAV circular buffer: stereo (Ch0 + Ch1), sized to logDuration at prepareToPlay - std::vector wavCircBuf_[2]; - std::atomic wavWritePos_ { 0 }; - int wavBufSize_ { 0 }; + RtHandover wavRec_; + std::vector wavLayout_; // message thread: inputs of the published recorder + void rebuildWavRecorder (bool audioStopped); + + // File playback (roles per file channel; Mic for files without SPLMeter metadata) + std::array, WavRecording::kMaxTracks> fileRoles_ {}; + std::atomic fileNumChannels_ { 2 }; + std::atomic fileHasAccel_ { false }; + std::vector fileTracks_; // message thread + RtHandover vibFile_; // engine for file playback + std::unique_ptr buildFileVibrationEngine() const; + int vibSource_ = 0; // audio thread: 0 live, 1 file // Impulse Fidelity test signal generator + capture juce::AudioBuffer impFidTestSignal_; @@ -397,5 +613,63 @@ class SPLMeterAudioProcessor : public juce::AudioProcessor std::atomic impFidPos_ { 0 }; int impFidSignalLen_ { 0 }; + // REW per-step measurement (spec §6.1): the audio thread owns stepAccum_ and + // writes stepResult_ before publishing kStepDone + struct StepAccum + { + double sumA = 0.0, sumC = 0.0, sumZ = 0.0; + long long n = 0, pausedSamples = 0; + double maxFastA = 0.0, maxSlowC = 0.0; + float peakC = 0.0f; + double vibSumSq[4] {}; + float vibPeak[4] {}; + long long vibCount = 0; + int vibQuantity = 0, vibAxisMask = 0; + bool vibUniaxial = false; + + // fastA / slowC: the continuously running detectors (settled before the step) + void add (float z, float a, float c, double fastA, double slowC) noexcept + { + sumZ += (double) z * z; + sumA += (double) a * a; + sumC += (double) c * c; + ++n; + maxFastA = std::max (maxFastA, fastA); + maxSlowC = std::max (maxSlowC, slowC); + peakC = std::max (peakC, std::abs (c)); + } + // Once per vibration snapshot (125 ms): the mean of the running mean + // squares is the mean square over the step + void addVib (const vib::VibrationSnapshot& v) noexcept + { + if (! v.valid) return; + for (int slot = 0; slot < vib::kNumAxisSlots; ++slot) + { + vibSumSq[slot] += (double) v.axis[slot].rms * v.axis[slot].rms; + vibPeak[slot] = std::max (vibPeak[slot], v.axis[slot].peak); + } + ++vibCount; + vibQuantity = v.quantity; + vibAxisMask = v.axisMask; + vibUniaxial = v.uniaxial; + } + }; + enum : int { kStepIdle = 0, kStepBegin, kStepRunning, kStepEnd, kStepDone }; + std::atomic stepState_ { kStepIdle }; + StepAccum stepAccum_; // audio thread + double rewFastA_ = 0.0, rewSlowC_ = 0.0; // FAST-A / SLOW-C mean squares, always running + double rewFastAlpha_ = 0.0, rewSlowAlpha_ = 0.0; + rew::StepLevels stepResult_; // audio thread → reader after kStepDone + void handleRewStep (float calOffset) noexcept; // audio thread, start of block + + mutable std::mutex rewMutex_; + std::vector rewLevels_; + juce::File rewResultsFile_; + std::vector pendingMarkers_; + + // Declared last, so it is destroyed first: aborts a run and restores REW + // before anything a run uses goes away + rew::Sequencer rewSequencer_; + JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SPLMeterAudioProcessor) }; diff --git a/Source/Rew/RewRunResults.h b/Source/Rew/RewRunResults.h new file mode 100644 index 0000000..05d354c --- /dev/null +++ b/Source/Rew/RewRunResults.h @@ -0,0 +1,282 @@ +#pragma once +#include "RewSequencer.h" +#include "../Vibration/Units.h" +#include + +namespace rew +{ +//============================================================================== +// REW sequencer spec §6: what SPLMeter measured during each sweep. REW keeps the +// acoustic response; SPLMeter adds its own levels and, with an accelerometer, +// the vibration (REW cannot measure vibration). +struct StepLevels +{ + bool valid = false; // the step was measured (audio was running) + double seconds = 0.0; // metered time from trigger to the measurement's arrival + double pausedSeconds = 0.0; // time SPLMeter was paused within the step + + // Microphone, dB SPL + double laeq = 0.0, lceq = 0.0, lzeq = 0.0; + double lafmax = 0.0, lcsmax = 0.0, lcpeak = 0.0; + + // Accelerometer (SI units, see vib::Quantity); X, Y, Z, Σ + bool vibValid = false; + int quantity = 0, axisMask = 0; + bool uniaxial = false; + double vibRms[4] {}, vibPeak[4] {}; + + bool vibSlotPresent (int slot) const + { + int axes = 0; + for (int a = 0; a < 3; ++a) axes += (axisMask >> a) & 1; + if (slot == 3) return ! uniaxial && axes > 1; + return ((axisMask >> slot) & 1) != 0; + } +}; + +// Context written into the results header +struct RunInfo +{ + juce::String splmeterVersion; + double calOffsetDb = 0.0; + vib::DisplayUnit vibUnit = vib::DisplayUnit::Linear; + juce::String vibProfile; // profile key, e.g. "machinery" + juce::StringArray vibCalibration; // "X: IN 2 151.5 dB (calibrator 2026-11-12)" … + juce::Time finished; +}; + +namespace results +{ + inline juce::String csvField (const juce::String& s) + { + if (s.containsAnyOf (",\"\n\r")) + return "\"" + s.replace ("\"", "\"\"") + "\""; + return s; + } + + inline juce::String num (double v, int decimals) + { + return std::isfinite (v) ? juce::String (v, decimals) : juce::String(); + } + + inline juce::String numG (double v) + { + char buf[32]; + std::snprintf (buf, sizeof (buf), "%.6g", v); + return buf; + } + + inline juce::String outputText (const Step& s) + { + return s.output ? *s.output : juce::String(); + } + + inline juce::String secondOutputText (const Step& s) + { + if (! s.secondOutput) return {}; + juce::String t = s.secondOutput->enabled ? s.secondOutput->output : juce::String ("off"); + if (s.secondOutput->invert) t << " (inverted)"; + return t; + } + + inline juce::String inputText (const Step& s) + { + if (! s.input) return {}; + return s.lastInput ? *s.input + "-" + *s.lastInput : *s.input; + } + + inline juce::String levelText (const Step& s) + { + return s.level ? juce::String (s.level->value, 1) + " " + s.level->unit : juce::String(); + } + + inline juce::String vibUnitLabel (const StepLevels& l, vib::DisplayUnit u) + { + return juce::String::fromUTF8 (vib::units::label (u, (vib::Quantity) l.quantity)); + } + + inline double vibDisplay (const StepLevels& l, double si, vib::DisplayUnit u) + { + return vib::units::convert (si, u, (vib::Quantity) l.quantity); + } +} + +//============================================================================== +// CSV: one row per step result (spec §6.2). Header lines start with '#'. +inline juce::String toCsv (const Sequence& seq, const Progress& p, const std::vector& levels, + const RunInfo& info) +{ + using namespace results; + juce::StringArray lines; + lines.add ("# SPLMeter " + info.splmeterVersion + " - REW measurement sequencer run"); + lines.add ("# Sequence: " + seq.name); + if (p.version.valid()) + lines.add ("# REW: " + p.version.rew + ", API " + p.version.api); + lines.add ("# Result: " + juce::String (toString (p.state)) + (p.dryRun ? " (dry run)" : "")); + lines.add ("# Finished: " + info.finished.toISO8601 (true)); + lines.add ("# Microphone calibration offset: " + juce::String (info.calOffsetDb, 2) + " dB"); + if (info.vibProfile.isNotEmpty()) + lines.add ("# Vibration profile: " + info.vibProfile); + for (const auto& c : info.vibCalibration) + lines.add ("# Accelerometer " + c); + if (p.savedMdat.isNotEmpty()) + lines.add ("# REW measurements saved to: " + p.savedMdat); + + lines.add ("step,loop,name,status,start,duration_s,messages,rew_uuids,output,second_output,input,level," + "LAeq,LCeq,LZeq,LAFmax,LCSmax,LCpeak,metered_s,paused_s," + "vib_unit,vibX_rms,vibY_rms,vibZ_rms,vibSum_rms,vibX_pk,vibY_pk,vibZ_pk,vibSum_pk"); + + for (size_t i = 0; i < p.results.size(); ++i) + { + const auto& r = p.results[i]; + const auto& s = seq.steps[(size_t) r.step]; + const StepLevels l = i < levels.size() ? levels[i] : StepLevels {}; + + juce::StringArray f; + f.add (juce::String (r.step + 1)); + f.add (juce::String (r.loop + 1)); + f.add (csvField (r.title)); + f.add (toString (r.status)); + f.add (r.start != juce::Time() ? r.start.toISO8601 (true) : juce::String()); + f.add (num (r.durationSec, 2)); + f.add (csvField (r.messages.joinIntoString (" | "))); + f.add (csvField (r.uuids.joinIntoString (" "))); + f.add (csvField (outputText (s))); + f.add (csvField (secondOutputText (s))); + f.add (csvField (inputText (s))); + f.add (csvField (levelText (s))); + if (l.valid) + { + for (double v : { l.laeq, l.lceq, l.lzeq, l.lafmax, l.lcsmax, l.lcpeak }) + f.add (num (v, 1)); + f.add (num (l.seconds, 2)); + f.add (num (l.pausedSeconds, 2)); + } + else + { + for (int k = 0; k < 8; ++k) f.add ({}); + } + if (l.valid && l.vibValid) + { + f.add (csvField (vibUnitLabel (l, info.vibUnit))); + for (const double* values : { l.vibRms, l.vibPeak }) + for (int slot = 0; slot < 4; ++slot) + f.add (l.vibSlotPresent (slot) ? numG (vibDisplay (l, values[slot], info.vibUnit)) : juce::String()); + } + else + { + for (int k = 0; k < 9; ++k) f.add ({}); + } + lines.add (f.joinIntoString (",")); + } + return lines.joinIntoString ("\n") + "\n"; +} + +//============================================================================== +// JSON: the same data plus the full sequence, so a run can be traced later +inline juce::var toJson (const Sequence& seq, const Progress& p, const std::vector& levels, + const RunInfo& info) +{ + using namespace results; + auto obj = [] { return new juce::DynamicObject(); }; + + auto* root = obj(); + root->setProperty ("format", "splmeter-rew-run"); + root->setProperty ("version", 1); + root->setProperty ("splmeter", info.splmeterVersion); + if (p.version.valid()) + root->setProperty ("rew", p.version.rew + " (API " + p.version.api + ")"); + root->setProperty ("result", toString (p.state)); + root->setProperty ("dryRun", p.dryRun); + root->setProperty ("finished", info.finished.toISO8601 (true)); + root->setProperty ("message", p.message); + root->setProperty ("savedMdat", p.savedMdat); + root->setProperty ("calOffsetDb", info.calOffsetDb); + root->setProperty ("vibProfile", info.vibProfile); + root->setProperty ("vibUnit", (int) info.vibUnit); + juce::Array cal; + for (const auto& c : info.vibCalibration) cal.add (c); + root->setProperty ("vibCalibration", cal); + root->setProperty ("sequence", toVar (seq)); + + juce::Array steps; + for (size_t i = 0; i < p.results.size(); ++i) + { + const auto& r = p.results[i]; + const StepLevels l = i < levels.size() ? levels[i] : StepLevels {}; + auto* o = obj(); + o->setProperty ("step", r.step + 1); + o->setProperty ("loop", r.loop + 1); + o->setProperty ("name", r.title); + o->setProperty ("status", toString (r.status)); + o->setProperty ("start", r.start != juce::Time() ? r.start.toISO8601 (true) : juce::String()); + o->setProperty ("durationSec", r.durationSec); + o->setProperty ("attempts", r.attempts); + juce::Array msgs, uuids; + for (auto& m : r.messages) msgs.add (m); + for (auto& u : r.uuids) uuids.add (u); + o->setProperty ("messages", msgs); + o->setProperty ("rewUuids", uuids); + if (l.valid) + { + auto* m = obj(); + m->setProperty ("LAeq", l.laeq); + m->setProperty ("LCeq", l.lceq); + m->setProperty ("LZeq", l.lzeq); + m->setProperty ("LAFmax", l.lafmax); + m->setProperty ("LCSmax", l.lcsmax); + m->setProperty ("LCpeak", l.lcpeak); + m->setProperty ("meteredSec", l.seconds); + m->setProperty ("pausedSec", l.pausedSeconds); + o->setProperty ("sound", juce::var (m)); + } + if (l.valid && l.vibValid) + { + static const char* names[4] = { "X", "Y", "Z", "Sum" }; + auto* v = obj(); + v->setProperty ("unit", vibUnitLabel (l, info.vibUnit)); + for (int slot = 0; slot < 4; ++slot) + if (l.vibSlotPresent (slot)) + { + auto* a = obj(); + a->setProperty ("rms", vibDisplay (l, l.vibRms[slot], info.vibUnit)); + a->setProperty ("peak", vibDisplay (l, l.vibPeak[slot], info.vibUnit)); + v->setProperty (names[slot], juce::var (a)); + } + o->setProperty ("vibration", juce::var (v)); + } + steps.add (juce::var (o)); + } + root->setProperty ("steps", steps); + return juce::var (root); +} + +inline juce::File defaultResultsFolder() +{ + return juce::File::getSpecialLocation (juce::File::userDocumentsDirectory) + .getChildFile ("SPLMeter").getChildFile ("REW runs"); +} + +// Writes __