diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d3fad01c..cfb42086c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,6 +146,15 @@ if(ARMIX_SONKU_EXPERIMENTAL_P99_VOCAL_DEPTH AND endif() set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) +# P0 Windows 10 fresh-install portability: the compiler's default /MD +# silently requires a machine-wide Microsoft VC++ Redistributable which is +# present on CI runners but NOT guaranteed on end-user Windows 10 PCs. +# Choose one matching static CRT across BOTH JUCE static libraries and the +# native mixer, before JUCE targets are created. Explicit downstream +# toolchain selection remains respected. Does NOT replace WebView2 Runtime. +if (MSVC AND WIN32 AND NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() if (NOT DEFINED JUCE_ROOT) message(FATAL_ERROR "Pass -DJUCE_ROOT=C:/path/to/JUCE (8.0.15+ required)") @@ -1300,6 +1309,9 @@ if(BUILD_TESTING) target_compile_features(ARMixProductionRenderAuditTests PRIVATE cxx_std_20) add_test(NAME M3ActualProductionRenderPathAndFailSilentCounters COMMAND ARMixProductionRenderAuditTests) add_dependencies(ARMixMixerRoutingTests ARMixApprovedRoutingPcmTests) + add_executable(ARMixPhysicalLoopbackTests tests/physical_loopback_test.cpp) + add_test(NAME physical_loopback_cpp COMMAND ARMixPhysicalLoopbackTests) + add_executable(ARMixLatencyCompensationTests tests/dynamic_latency_compensation_test.cpp) target_compile_features(ARMixLatencyCompensationTests PRIVATE cxx_std_20) add_test(NAME NativeGraphLatencyAlignedFanInAndHardwarePCM COMMAND ARMixLatencyCompensationTests) diff --git a/docs/INT1B_AUDIO_RELIABILITY_PROFILING_20261120.md b/docs/INT1B_AUDIO_RELIABILITY_PROFILING_20261120.md new file mode 100644 index 000000000..c66536d93 --- /dev/null +++ b/docs/INT1B_AUDIO_RELIABILITY_PROFILING_20261120.md @@ -0,0 +1,44 @@ +# INT-1B — real audio-reliability evidence, no speculative DSP refactor + +**Repository:** [ArSonMix](https://github.com/masarray/arsonmix) · parent [INT-1 #837](https://github.com/masarray/arsonmix/issues/837) +**Scope:** existing single-primary-ASIO native PCM/VST3 graph and approved `/preview/`. No multi-device ASIO, graphical overhaul, changed buffer or auto-tuned audio driver. + +## What actually changed + +1. The existing `LiveAudioEngine::status()` publishes the 13 already-accumulated `RealtimeHealthHistogram` bucket counts, with exact provenance. The audio callback keeps precisely its existing relaxed-atomic histogram update; **no allocations, locks, new timers, IO, COM, driver opens or new render graph**. +2. The existing 1 Hz `AUDIO_HEALTH` log now writes a compact, versioned **parseable JSON subset** of the status already fetched by the message thread. The earlier full status can include long FX/device arrays and exceed the 4096-byte async queue entry. The small health record avoids silent JSON truncation without reducing the original interactive SIGNAL CHECK / COPY FULL REPORT data. The log itself stays on the existing asynchronous worker, is local/private and rotates at 2 MB. +3. `scripts/audio_reliability_profile.mjs` compares **changes between consecutive 1 Hz histogram snapshots**. It outputs per-window p95/p99 **callback deadline bucket ceilings**, over-budget per 1,000 callbacks, late scheduling indicators and device-generation changes. It splits samples whenever a device/route/driver/rate/buffer/mode changes, counters reset, the callback disconnects or the recording has a gap over 5 s. It refuses a DRY/FX comparison when hardware parameters differ. Raw buckets permit real *interval* percentiles rather than a stale lifetime average. +4. Portable regression contracts cover malformed/truncated/legacy records, true 13-bucket delta percentiles, >100% deadline, **actual accepted insert/rack/global bypass classification**, matching dry vs FX, device epoch changes, counter resets and unknown hardware XRUN status. Expensive CI is only required once for the final native candidate, not for each test change. + +## Operator procedure — collect once on an exact Windows build + +Use the new INT-1B installer/portable **only when an exact-SHA Windows FAT artifact exists**. Save your existing `.smix` first. ASIO interface and physical output remain chosen explicitly by you. Start at low headphone volume, never auto-arm speakers. + +1. In the approved native application, open **SIGNAL CHECK**, verify driver, exact input/output pins, rate and buffer. Keep the same ASIO device (for example, 48 kHz / 256 frames) and an accepted CH→MAIN routing. +2. Use the **native GLOBAL FX POWER/BYPASS control** (wait for exact accepted ACK/readback) to bypass all FX for at least **2 minutes**, without a route/device change. The old `dryTest` flag is only UI intent and is **not reliable evidence** that the accepted ChannelId DSP is bypassed. Keep the audio signal continuous. `AUDIO_HEALTH` snapshots are collected automatically at the existing 1 Hz rate without any extra GUI telemetry activity. +3. Enable GLOBAL FX POWER and verify at least one installed native FX insert is **actually processing** (accepted rack/slot/global bypass readback). Keep **identical** driver/device/rate/buffer and monitor level, and record at least **2 minutes**. Mark any audible crackle using **MARK CRACKLE**. Do not conflate manual silence with a dropout. +4. In SIGNAL CHECK choose **OPEN DIAGNOSTIC LOG**. The local `audio-diagnostics.log` contains records. It is **not uploaded** by ArSonMix. On a development machine with Node 20+ and the ArSonMix source, run: + +```powershell +node scripts/audio_reliability_profile.mjs "C:\path\to\audio-diagnostics.log" --json int1b-profile.json --markdown int1b-profile.md +``` + +5. Review private device names or FX details before sharing the Markdown/JSON evidence. If the log rotated, analyze each part separately and compare equivalent driver/rate/buffer conditions. Only a single window with >=30 seconds and accepted physical routing is considered minimally comparable; **120 s per mode recommended** for reliability evidence. Never claim long-run stability from 30 seconds. + +## How to interpret accurately + +- **p95/p99** are *upper limits of coarse callback-processing deadline buckets* based on cumulative-count **deltas**, not exact processing-time percentiles or OS CPU percentage. The >100% bucket remains explicitly unknown/unbounded. +- **Over-budget** means measured callback processing time exceeded its actual block-period budget. **Late callback / gap** refers to START-to-START cadence relative to the *previous* variable JUCE quantum. Both are **indicators**, not proof of an actual render-underrun. +- `backendXrunMeaning=WASAPI_CAPTURE_DISCONTINUITIES_ONLY` is specifically **capture flags**, not DAC starvation. `DRIVER_DEFINED` has driver-dependent semantics. True render-hardware XRUN remains **UNAVAILABLE** through the currently pinned JUCE AudioIODevice API. +- `worstPluginUs` is a **cumulative maximum**, not necessarily measured inside the reported window. No automated causal plugin verdict based solely on that value. +- **Verified DRY vs FX:** DRY means effective accepted processing-insert count `0` across both ChannelId FX **and the original externally leased CH1 vendor/Orbit rack**, either by global/rack/slot bypass or no inserts. FX means effective processing-insert count >0, after native ACK/readback; the legacy `dryTest` flag cannot establish either. A non-auditable external lease is rejected rather than falsely labeled DRY. The DRY interval must immediately precede FX in the SAME app session with no more than 60 seconds of transition; never compare a prior launch or stale archive. Device generation, exact hexadecimal ASIO input/output pin masks, native graph revision, input/output names and channel counts must all match. A mere identical driver name is NOT sufficient. Compare p99 bucket ceiling, over-budget/1000, cadence and audible observations together. Only after an actual regression is observed should the responsible DSP/FX/device/GUI subsystem be optimized with a targeted patch and before/after proof. +- Profiling cannot measure acoustic round-trip latency, DPC/ISR or hard OS page faults; those require independent synchronized hardware/Windows tools. Existing [CrackleEvidenceWindow](../engine/diagnostics/CrackleEvidenceWindow.h) and [Windows GUI sampling](../scripts/collect_gui_perf_windows.ps1) remain separate instruments. + +## Exit gates + +- Windows MSVC Release + native CTest + quick source contracts at exact SHA, controlled release artifact installation/upgrade/uninstall **when a user-test binary is required**. +- Read `audio-diagnostics.log` from that exact user-installed binary; assert parseable profile counts, no log truncation and retained device/session/provenance. +- **Physical hardware FAT** (ASIO driver model, hardware, listening, glitch markers, loaded VST3 chain) must be reported PASS/FAIL/NOT RUN. Never infer physical FAT from CI. +- I/O #825/#830 and Graphic EQ #835 remain distinct experiments; no dual-ASIO UI claim. + +**Measured source-workload win:** one existing native status read and 1 Hz asynchronous log write are reused, instead of adding a callback probe, UI polling timer or another audio thread. Without real hardware evidence this does not justify a numerical reduction in CPU, latency or XRUN. diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index e28eb2243..03174bab4 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -178,6 +178,11 @@ class DynamicChannelFxLeaseBank final { std::uint64_t revision() const noexcept{return revision_;} std::size_t lanes() const noexcept{return rows_.size();} ChannelId externalChannel() const noexcept{return external_.id;} + // Read-only CONTROL-plane visibility of the EXACT accepted external + // render lease. No refcount, mutation or render-side ownership change. + const ExternalLease* externalLeaseForControl() const noexcept { + return external_.valid() ? &external_ : nullptr; + } std::size_t insertCount(ChannelId id) const noexcept { const auto* p=find(id);return p?p->count:0; } diff --git a/engine/diagnostics/PhysicalLoopback.h b/engine/diagnostics/PhysicalLoopback.h new file mode 100644 index 000000000..5f78c9251 --- /dev/null +++ b/engine/diagnostics/PhysicalLoopback.h @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace armix::diagnostics { + +struct PhysicalLoopback final { + static constexpr int chips = 383; + static constexpr int chipFrames = 8; + static constexpr int pulseFrames = chips * chipFrames; + static constexpr float amplitude = 0.025f; // -32 dBFS peak; line-level cable only + + enum class State { idle, capturing, complete, cancelled }; + static_assert(std::atomic::is_always_lock_free); + struct Capture { + int rate = 0; + int guard = 0; + int maxDelay = 0; + std::array pulse {}; + std::vector received; + }; + struct Result { + int frames = 0; + double confidence = 0; + const char* error = nullptr; + }; + + // CONTROL allocates and publishes once. The callback is the sole writer + // until complete/cancelled is released. No callback borrows a worker buffer. + bool start(int rate, int block, int input, int output, int inputs, int outputs, + std::uint64_t deviceEpoch) + { + if (state() != State::idle || rate < 44100 || rate > 192000 || + block < 16 || block > 2048 || input < 0 || input >= inputs || + output < 0 || output >= outputs || deviceEpoch == 0) + return false; + capture_.rate = rate; + capture_.guard = rate / 10; + capture_.maxDelay = rate / 2; + capture_.received.resize(static_cast( + capture_.guard + capture_.maxDelay + pulseFrames)); + std::uint32_t seed = 0x481b2a63; + for (int chip = 0; chip < chips; ++chip) { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + std::fill_n(capture_.pulse.data() + chip * chipFrames, chipFrames, + (seed & 1u) ? amplitude : -amplitude); + } + block_ = block; + input_ = input; + output_ = output; + inputs_ = inputs; + outputs_ = outputs; + deviceEpoch_ = deviceEpoch; + cursor_ = 0; + cancellationRequested_.store(false, std::memory_order_relaxed); + state_.store(State::capturing, std::memory_order_release); + return true; + } + + State state() const noexcept { return state_.load(std::memory_order_acquire); } + + void requestCancel() noexcept + { + cancellationRequested_.store(true, std::memory_order_release); + } + + // Callback or serialized device lifecycle only. + void interrupted() noexcept + { + if (state() == State::capturing) + state_.store(State::cancelled, std::memory_order_release); + } + + // Read before graph rendering: some drivers alias input/output buffers. + bool captureInput(const float* const* inputs, int count, int frames) noexcept + { + if (state() != State::capturing) + return false; + if (!inputs || count != inputs_ || frames != block_ || !inputs[input_]) { + interrupted(); + return false; + } + const auto remaining = static_cast(capture_.received.size()) - cursor_; + std::copy_n(inputs[input_], std::min(frames, remaining), + capture_.received.data() + cursor_); + return true; + } + + // Only true when this block replaced physical output with the isolated + // probe. No graph/stream mutation, analysis, allocation, or audio rearm. + bool emitProbe(float* const* outputs, + int outputCount, int frames, std::uint64_t epoch, bool permitted, + const std::array& mainPair) noexcept + { + if (state() != State::capturing) + return false; + if (cancellationRequested_.load(std::memory_order_acquire) || !permitted || + epoch != deviceEpoch_ || frames != block_ || + outputCount != outputs_ || !outputs || + !outputs[output_] || (output_ != mainPair[0] && output_ != mainPair[1])) { + interrupted(); + return false; + } + const auto captured = static_cast(capture_.received.size()); + const int n = std::min(frames, captured - cursor_); + for (int channel = 0; channel < outputCount; ++channel) + if (auto* out = outputs[channel]) + std::fill_n(out, frames, 0.0f); + const int begin = std::max(cursor_, capture_.guard); + const int end = std::min(cursor_ + n, capture_.guard + pulseFrames); + if (begin < end) + std::copy_n(capture_.pulse.data() + begin - capture_.guard, end - begin, + outputs[output_] + begin - cursor_); + cursor_ += n; + if (cursor_ == captured) + state_.store(State::complete, std::memory_order_release); + return true; + } + + // CONTROL consumes only after the callback has stopped touching this capture. + Capture take() + { + Capture result = std::move(capture_); + state_.store(State::idle, std::memory_order_release); + return result; + } + + // Worker only. Centered normalized correlation with a quiet pre-roll, + // clipping/invalid-sample checks, an ambiguity check and a noise margin. + static Result analyse(const Capture& capture) + { + const auto& received = capture.received; + double noiseEnergy = 0, noiseSum = 0, pulseSum = 0, pulseEnergy = 0; + for (std::size_t i = 0; i < received.size(); ++i) { + const double x = received[i]; + if (!std::isfinite(x) || std::abs(x) >= 0.98) + return {0, 0, "Clipped or invalid line input. Lower the interface gain."}; + if (i < static_cast(capture.guard)) { + noiseEnergy += x*x; + noiseSum += x; + } + } + for (const double x : capture.pulse) { + pulseSum += x; + pulseEnergy += x*x; + } + pulseEnergy -= pulseSum*pulseSum / pulseFrames; + const double noiseVariance = std::max(0.0, noiseEnergy/capture.guard - + std::pow(noiseSum/capture.guard, 2)); + std::vector prefix(received.size() + 1); + std::vector squares(received.size() + 1); + for (std::size_t i = 0; i < received.size(); ++i) { + const double x = received[i]; + prefix[i + 1] = prefix[i] + x; + squares[i + 1] = squares[i] + x*x; + } + std::vector scores(static_cast(capture.maxDelay + 1)); + int best = 0; + for (int offset = 0; offset <= capture.maxDelay; ++offset) { + const int begin = capture.guard + offset; + const int end = begin + pulseFrames; + const double sum = prefix[end] - prefix[begin]; + const double energy = squares[end] - squares[begin] - sum*sum/pulseFrames; + if (energy < pulseFrames * std::max(0.00000004, 16*noiseVariance)) + continue; + double dot = 0; + for (int chip = 0; chip < chips; ++chip) { + const int index = begin + chip * chipFrames; + dot += capture.pulse[chip * chipFrames] * + (prefix[index + chipFrames] - prefix[index]); + } + scores[offset] = std::min(1.0, std::abs(dot - pulseSum*sum/pulseFrames) / + std::sqrt(pulseEnergy*energy)); + if (scores[offset] > scores[best]) + best = offset; + } + const double confidence = scores[best]; + if (confidence < 0.70 || best < 1 || best == capture.maxDelay) + return {0, confidence, "No reliable wired return. Check the cable, line input and noise."}; + for (int offset = 0; offset <= capture.maxDelay; ++offset) + if (std::abs(offset - best) > chipFrames * 2 && scores[offset] >= confidence * 0.85) + return {0, confidence, "Multiple strong returns. Disable hardware monitoring or feedback."}; + return {best, confidence, nullptr}; + } + +private: + std::atomic state_ { State::idle }; + std::atomic cancellationRequested_ { false }; + Capture capture_; + std::uint64_t deviceEpoch_ = 0; + int input_ = -1, output_ = -1, inputs_ = 0, outputs_ = 0, block_ = 0, cursor_ = 0; +}; +} // namespace armix::diagnostics diff --git a/installer/ArSonMix.iss b/installer/ArSonMix.iss index 6ced1b257..796051149 100644 --- a/installer/ArSonMix.iss +++ b/installer/ArSonMix.iss @@ -66,6 +66,7 @@ Source: "ArSonMixVBCableInstall.ps1"; DestDir: "{app}\ThirdParty\VB-Audio"; Flag Source: "ArSonMixUpdateShutdown.ps1"; Flags: dontcopy ; The updater runs outside JUCE, never in the realtime audio callback. Source: "ArSonMixAutoUpdate.ps1"; DestDir: "{app}"; Flags: ignoreversion +Source: "ArSonMixStartupDiagnostics.ps1"; DestDir: "{app}"; Flags: ignoreversion Source: "{#SourceRoot}\verified-gui.exe"; DestDir: "{app}"; DestName: "ArSonMix.exe"; Flags: ignoreversion Source: "{#SourceRoot}\BUILD_PROVENANCE.json"; DestDir: "{app}"; Flags: ignoreversion ; The complete original and vendor legal documents are embedded both in @@ -84,15 +85,23 @@ Name: "{autoprograms}\ArSonMix"; Filename: "{app}\ArSonMix.exe"; WorkingDir: "{a ; User-facing fallback when the main EXE cannot even open. The helper ; authenticates the published current release and repairs in place. Name: "{autoprograms}\Repair ArSonMix"; Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File ""{app}\ArSonMixAutoUpdate.ps1"" -RecoveryMode"; WorkingDir: "{app}" +Name: "{autoprograms}\Diagnose ArSonMix Startup"; Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File ""{app}\ArSonMixStartupDiagnostics.ps1"" -ShowReport"; WorkingDir: "{app}" +Name: "{autoprograms}\Start ArSonMix with Recovery Profile"; Filename: "{app}\ArSonMix.exe"; Parameters: "--safe-webview-profile"; WorkingDir: "{app}" ; Do not create a second copy of an already running mixer. Restart Manager ; preflight closes the prior verified app before [Files]; [Run] launches exactly ; one new executable only after a successful interactive install/update. ; Silent enterprise/FAT installs deliberately do not launch desktop audio. +[Tasks] +; P0 Win10 first-run: VB-CABLE is an OPTIONAL virtual-audio feature, not +; a dependency of the ASIO/WASAPI mixer. Never silently elevate/replace an +; audio driver or block a first launch for a driver reboot. Owner opt-in only. +Name: "installvbcable_driver"; Description: "Install optional VB-CABLE virtual audio driver (may require administrator approval and restart)"; GroupDescription: "Optional audio driver:"; Flags: unchecked dontinheritcheck + [Run] ; Check on interactive Setup before opening the mixer. Only a missing driver ; can reach the independently verified vendor EXE and its Windows approval. ; Silent updates and enterprise installs retain their noninteractive behavior. -Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -ExecutionPolicy Bypass -File ""{app}\ThirdParty\VB-Audio\ArSonMixVBCableInstall.ps1"" -Archive ""{app}\ThirdParty\VB-Audio\VBCABLE_Driver_Pack45.zip"" -ExpectedSha256 ""{#VBCableSha256}"" -RestartMarker ""{tmp}\ArSonMixVBCableRestart"""; WorkingDir: "{app}"; StatusMsg: "Checking VB-Audio VB-CABLE for automatic audio setup..."; Flags: runasoriginaluser skipifsilent waituntilterminated runhidden +Filename: "{sys}\WindowsPowerShell\v1.0\powershell.exe"; Parameters: "-NoLogo -NoProfile -ExecutionPolicy Bypass -File ""{app}\ThirdParty\VB-Audio\ArSonMixVBCableInstall.ps1"" -Archive ""{app}\ThirdParty\VB-Audio\VBCABLE_Driver_Pack45.zip"" -ExpectedSha256 ""{#VBCableSha256}"" -RestartMarker ""{tmp}\ArSonMixVBCableRestart"""; WorkingDir: "{app}"; StatusMsg: "Installing OPTIONAL VB-CABLE audio driver..."; Tasks: installvbcable_driver; Flags: runasoriginaluser skipifsilent waituntilterminated runhidden Filename: "{app}\ArSonMix.exe"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser skipifsilent; Check: CanLaunchMixer ; Never delete private Studio data on install/update/uninstall; never install diff --git a/installer/ArSonMixStartupDiagnostics.ps1 b/installer/ArSonMixStartupDiagnostics.ps1 new file mode 100644 index 000000000..fc05367f9 --- /dev/null +++ b/installer/ArSonMixStartupDiagnostics.ps1 @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: AGPL-3.0-only +[CmdletBinding()] +param([switch]$SafeWebViewProfile, [switch]$ShowReport) + +$ErrorActionPreference = 'Stop' +$folder = Join-Path $env:LOCALAPPDATA 'ArSonMix\diagnostics' +[IO.Directory]::CreateDirectory($folder) | Out-Null +$report = Join-Path $folder 'windows-startup-report.txt' +$os = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' +$build = [int]$os.CurrentBuildNumber +$exe = @('ArSonMix.exe','ArSonMix-GUI10CH-P012-Windows-x64.exe') | + ForEach-Object { Join-Path $PSScriptRoot $_ } | + Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1 +$lines = @( + "Observed: $([DateTimeOffset]::Now.ToString('o'))" + "Windows build: $build.$($os.UBR)" + "64-bit OS: $([Environment]::Is64BitOperatingSystem)" + "Minimum Windows x64 build: 17763" +) +if ($exe) { + $lines += "Executable SHA256: $((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash)" +} else { + $lines += 'Executable missing. Try Repair ArSonMix from the Start menu.' +} +# Evergreen WebView2 Runtime registration is per-machine or per-user. +$webViewKey = '{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' +$registrations = @( + "HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\$webViewKey" + "HKLM:\SOFTWARE\Microsoft\EdgeUpdate\Clients\$webViewKey" + "HKCU:\SOFTWARE\Microsoft\EdgeUpdate\Clients\$webViewKey" +) | ForEach-Object { + (Get-ItemProperty -LiteralPath $_ -Name pv -ErrorAction SilentlyContinue).pv +} | Where-Object { $_ -and $_ -ne '0.0.0.0' } | Sort-Object -Unique +if ($registrations) { + $lines += "WebView2 Evergreen registration: $($registrations -join ', ')" +} else { + $lines += 'WebView2 Evergreen registration absent. Download or repair the Microsoft WebView2 Runtime.' +} +$startupLog = Join-Path $folder 'startup-failure.txt' +if (Test-Path -LiteralPath $startupLog -PathType Leaf) { + $lines += '' + $lines += 'Latest native startup trace (match timestamp and SHA before using):' + $lines += Get-Content -LiteralPath $startupLog -TotalCount 12 +} +$lines += '' +$lines += 'Windows Application log (Application Error, WER, Application Hang and SideBySide):' +try { + $events = @(Get-WinEvent -FilterHashtable @{ + LogName = 'Application'; Id = @(33,59,1000,1001,1002) + StartTime = (Get-Date).AddDays(-7) + } -MaxEvents 240 -ErrorAction SilentlyContinue | + Where-Object { $_.Message -match '(?i)ArSonMix[-\w]*\.exe|AR[- ]?Mix.*\.exe' } | + Select-Object -First 12) + foreach ($event in $events) { + $lines += "$($event.TimeCreated) | $($event.ProviderName) | event $($event.Id)" + $lines += ($event.Message -split '\r?\n' | + Where-Object { $_ -match '(?i)fault|exception|\.dll|side-by-side' } | + Select-Object -First 5) + } + if (!$events.Count) { $lines += 'No matching event in the recent query.' } +} catch { + $lines += "Application log could not be read: $($_.Exception.Message)" +} +if ($SafeWebViewProfile -and $exe -and $build -ge 17763 -and [Environment]::Is64BitOperatingSystem) { + try { + Start-Process -FilePath $exe -ArgumentList '--safe-webview-profile' -WorkingDirectory $PSScriptRoot + $lines += 'Recovery requested with a separate WebView2 profile. Check the native trace for GUI_READY.' + } catch { + $lines += "Windows could not launch the executable: $($_.Exception.Message)" + } +} +$lines | Set-Content -LiteralPath $report -Encoding UTF8 +Write-Output $report +if ($ShowReport) { Start-Process -FilePath (Join-Path $env:WINDIR 'notepad.exe') -ArgumentList ('"' + $report + '"') } diff --git a/scripts/audio_reliability_profile.mjs b/scripts/audio_reliability_profile.mjs new file mode 100644 index 000000000..0973a0336 --- /dev/null +++ b/scripts/audio_reliability_profile.mjs @@ -0,0 +1,313 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// INT-1B: offline-only analyzer for the 1 Hz AUDIO_HEALTH native diagnostic log. +// NEVER runs in the JUCE audio callback, opens devices, or uploads evidence. +import {readFileSync, writeFileSync} from "node:fs"; +import {resolve} from "node:path"; +import {pathToFileURL} from "node:url"; + +export const SCHEMA="arsonmix.audio-health.int1b.v1"; +export const BUCKET_UPPER=[1,2,4,8,12,20,30,40,55,70,85,100,null]; +const COUNTERS=["callbackCount","overBudgetCount","slowCallbackCount", + "lateCallbackIntervals","callbackGapCount","callbackCadenceClockRegressions", + "deviceStartCount","deviceStopCount"]; +const isCount=x=>Number.isSafeInteger(x)&&x>=0; +const finitePositive=x=>typeof x==="number"&&Number.isFinite(x)&&x>0; +const percent=(a,b)=>b>0?Math.round(10000*a/b)/100:null; + +export function parseHealthLog(log) { + const samples=[], warnings=[], rejectedLines=[]; + let sessionId=0; + for(const [idx,line] of String(log).split(/\r?\n/).entries()){ + if(/ \| SESSION \| started\s*$/.test(line)){sessionId++;continue;} + if(!line.includes(" | AUDIO_HEALTH | "))continue; + const m=/^(\S+) \| AUDIO_HEALTH \| (\{.*\})$/.exec(line); + if(!m){warnings.push("line "+(idx+1)+": malformed/truncated AUDIO_HEALTH");rejectedLines.push(idx+1);continue;} + let sample; + try {sample=JSON.parse(m[2]);} + catch {warnings.push("line "+(idx+1)+": invalid AUDIO_HEALTH JSON");rejectedLines.push(idx+1);continue;} + if(!sample || typeof sample!=="object" || Array.isArray(sample) || + sample.schema!==SCHEMA){ + warnings.push("line "+(idx+1)+": legacy/unknown schema (excluded)"); + rejectedLines.push(idx+1); + continue; + } + const time=Date.parse(m[1]); + if(!Number.isFinite(time)||!finitePositive(sample.rate)|| + !isCount(sample.buffer)||sample.buffer===0|| + !isCount(sample.deviceGeneration)||!isCount(sample.callbackCount)|| + typeof sample.liveBackendClass!=="string" || + typeof sample.dryTest!=="boolean" || typeof sample.connected!=="boolean" || + typeof sample.nativeGlobalFxBypassed!=="boolean" || + !isCount(sample.nativeFxInstalledCount) || + !isCount(sample.nativeFxProcessingCount) || + sample.nativeFxProcessingCount>sample.nativeFxInstalledCount || + sample.nativeFxActivityComplete!==true || + typeof sample.nativeExternalCh1Leased!=="boolean" || + !isCount(sample.nativeExternalCh1InstalledCount) || + !isCount(sample.nativeExternalCh1ProcessingCount) || + sample.nativeExternalCh1ProcessingCount>sample.nativeExternalCh1InstalledCount || + sample.nativeExternalCh1InstalledCount>sample.nativeFxInstalledCount || + sample.nativeExternalCh1ProcessingCount>sample.nativeFxProcessingCount || + (!sample.nativeExternalCh1Leased && sample.nativeExternalCh1InstalledCount!==0) || + (sample.nativeGlobalFxBypassed && sample.nativeFxProcessingCount!==0) || + typeof sample.nativeFxGraphRevision!=="string" || + !/^\d+$/.test(sample.nativeFxGraphRevision) || + typeof sample.activeInputMaskHex!=="string" || + typeof sample.activeOutputMaskHex!=="string" || + !/^[0-9a-f]*$/i.test(sample.activeInputMaskHex) || + !/^[0-9a-f]*$/i.test(sample.activeOutputMaskHex)){ + warnings.push("line "+(idx+1)+": invalid source metadata/counters"); + rejectedLines.push(idx+1); + continue; + } + const buckets=sample.callbackBudgetBuckets; + if(!Array.isArray(buckets)||buckets.length!==13||!buckets.every(isCount)){ + warnings.push("line "+(idx+1)+": missing/invalid 13 histogram buckets"); + rejectedLines.push(idx+1); + continue; + } + if(!COUNTERS.every(key=>isCount(sample[key]))){ + warnings.push("line "+(idx+1)+": missing/invalid cumulative counter"); + rejectedLines.push(idx+1); + continue; + } + samples.push({...sample,atMs:time,line:idx+1,sessionId}); + } + return {samples,warnings,rejectedLines}; +} + +export function p95p99FromDelta(counts) { + if(!Array.isArray(counts)||counts.length!==13||!counts.every(isCount)) + return {p95:null,p99:null,samples:0}; + const total=counts.reduce((n,x)=>n+x,0); + if(!Number.isSafeInteger(total)||total===0) + return {p95:null,p99:null,samples:0}; + const bound=percentile=>{ + const target=Math.ceil(total*percentile); + let seen=0; + for(let i=0;i<13;i++){ + seen+=counts[i]; + if(seen>=target)return BUCKET_UPPER[i]; + } + return null; + }; + return {p95:bound(0.95),p99:bound(0.99),samples:total}; +} + +// Immutable hardware/graph provenance must survive the DRY -> FX switch. +// Mode keys are separate so only the actual accepted global power transition +// can bridge adjacent windows; all other boundary reasons invalidate pairing. +const STABLE_SCOPE_KEYS=[ + "sessionId","deviceGeneration","device","liveBackendClass","driver","rate","buffer", + "inputDevice","outputDevice","deviceInputChannels","deviceOutputChannels", + "activeInputMaskHex","activeOutputMaskHex","nativeFxGraphRevision", + "nativeFxInstalledCount","nativeExternalCh1Leased","nativeExternalCh1InstalledCount", + "connected","diagnosticRoute","productionRoutingState","directRouteAuthorized", + "backendXrunMeaning" +]; +const MODE_KEYS=[ + "nativeFxProcessingCount","nativeGlobalFxBypassed", + "nativeExternalCh1ProcessingCount","dryTest" +]; +const sameValues=(a,b,keys)=>keys.every(k=>a[k]===b[k]); +const nondecreasing=(a,b,key)=>isCount(a[key])&&isCount(b[key])&&b[key]>=a[key]; +const continuousEvidence=(a,b)=>b.atMs>a.atMs && b.atMs-a.atMs<=5000 && + COUNTERS.every(k=>nondecreasing(a,b,k))&& + a.callbackBudgetBuckets.every((x,i)=>b.callbackBudgetBuckets[i]>=x); +const validInterval=(a,b)=>continuousEvidence(a,b) && + sameValues(a,b,STABLE_SCOPE_KEYS)&&sameValues(a,b,MODE_KEYS); +const acceptedGlobalPowerTransition=(a,b)=>continuousEvidence(a,b) && + sameValues(a,b,STABLE_SCOPE_KEYS) && a.connected===true && b.connected===true && + a.nativeGlobalFxBypassed===true && b.nativeGlobalFxBypassed===false && + a.nativeFxProcessingCount===0 && b.nativeFxProcessingCount>0; + +function describeSegment(segment){ + const s=segment.start, first=segment.start, last=segment.last; + const p=p95p99FromDelta(segment.histogram); + const callbacks=segment.delta.callbackCount, period=1000000*s.buffer/s.rate; + const durationSeconds=Math.round(segment.durationMs/100)/10; + const missing=segment.intervals===0||p.samples===0; + const over=segment.delta.overBudgetCount,late=segment.delta.lateCallbackIntervals; + const gap=segment.delta.callbackGapCount; + let diagnosis="INSUFFICIENT_EVIDENCE"; + if(!missing){ + if(segment.delta.deviceStopCount>0||segment.delta.deviceStartCount>0) + diagnosis="DEVICE_LIFECYCLE_CHANGE"; + else if(over>0&&late>0)diagnosis="BOTH_DSP_BUDGET_AND_SCHEDULING_INDICATORS"; + else if(over>0)diagnosis="DSP_BUDGET_PRESSURE_INDICATOR"; + else if(late>0||gap>0)diagnosis="CALLBACK_SCHEDULING_INDICATOR"; + else diagnosis="NO_HOST_TIMING_ANOMALY_OBSERVED"; + } + return { + // The legacy dryTest control is only a UI intent; actual DRY/FX is + // derived from accepted native INSERT+rack+GLOBAL bypass readback. + lineStart:first.line,lineEnd:last.line, + invalidBefore:segment.invalidBefore, + sessionId:s.sessionId,startedAt:new Date(first.atMs).toISOString(), + endedAt:new Date(last.atMs).toISOString(), + startTimeMs:first.atMs,endTimeMs:last.atMs, + mode:s.nativeFxProcessingCount===0?"DRY":"FX", + nativeFxInstalledCount:s.nativeFxInstalledCount, + nativeFxProcessingCount:s.nativeFxProcessingCount, + nativeGlobalFxBypassed:s.nativeGlobalFxBypassed, + nativeExternalCh1Leased:s.nativeExternalCh1Leased, + nativeExternalCh1InstalledCount:s.nativeExternalCh1InstalledCount, + nativeExternalCh1ProcessingCount:s.nativeExternalCh1ProcessingCount, + device:String(s.device??"UNKNOWN"),backend:s.liveBackendClass, + inputDevice:s.inputDevice??"UNKNOWN",outputDevice:s.outputDevice??"UNKNOWN", + inputMask:s.activeInputMaskHex,outputMask:s.activeOutputMaskHex, + nativeFxGraphRevision:s.nativeFxGraphRevision, + inputChannels:s.deviceInputChannels??null, + outputChannels:s.deviceOutputChannels??null, + sampleRate:s.rate,bufferFrames:s.buffer,periodUs:Math.round(period*10)/10, + deviceGeneration:s.deviceGeneration, + diagnosticRoute:s.diagnosticRoute??"UNKNOWN", + productionRoutingState:s.productionRoutingState??"UNKNOWN", + directRouteAuthorized:s.directRouteAuthorized===true, + durationSeconds,intervals:segment.intervals,callbackCount:callbacks, + windowHistogramSamples:p.samples, + p95BudgetUpperPct:p.p95,p99BudgetUpperPct:p.p99, + overBudgetCallbacks:over,overBudgetPer1000:callbacks?Math.round(100000*over/callbacks)/100:null, + slowCallbacks:segment.delta.slowCallbackCount, + lateCallbackIntervals:late,callbackGaps:gap, + clockRegressions:segment.delta.callbackCadenceClockRegressions, + deviceStarts:segment.delta.deviceStartCount,deviceStops:segment.delta.deviceStopCount, + pluginWorstUsCumulative:last.worstPluginUs??null, + processWorkingSetMiB:last.processWorkingSetMiB??null, + processPrivateCommitMiB:last.processPrivateCommitMiB??null, + backendXrunMeaning:s.backendXrunMeaning??"UNAVAILABLE", + backendXrunDelta:nondecreasing(first,last,"backendXrunCount")? + last.backendXrunCount-first.backendXrunCount:null, + renderHardwareXrun:"UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE", + diagnosis,comparable:!missing&&durationSeconds>=30&&callbacks>0&& + s.connected===true&& + s.productionRoutingState==="NATIVE_ROUTE_ACCEPTED"&& + s.directRouteAuthorized===true, + notes:["Actual DRY/FX includes admitted external CH1 vendor leases and the accepted ChannelId insert-bypass readback.", + "Actual DRY/FX is accepted native insert-bypass readback, NOT the dryTest UI flag.", + "Host callback p95/p99 are bucket CEILINGS, not exact CPU utilization.", + "Callback cadence/over-budget are indicators, not driver render XRUN.", + "Device/driver capture discontinuities are backend-specific.", + "Reported plugin worst time can predate this window; it is not an interval peak."] + }; +} + +export function analyzeHealthLog(log) { + const {samples,warnings,rejectedLines}=parseHealthLog(log); + const groups=[]; + let segment=null; + const start=(s,invalidBefore=false)=>({start:s,last:s,intervals:0,durationMs:0, + delta:Object.fromEntries(COUNTERS.map(k=>[k,0])), + histogram:Array(13).fill(0),invalidBefore}); + for(const current of samples){ + if(!segment){segment=start(current);continue;} + // Rejected telemetry is an absolute comparison barrier, including a + // failed opaque vendor lease. Only an uninterrupted *accepted* global + // bypass ON -> OFF transition may connect a DRY/FX pair. + const missingBetween=rejectedLines.some(line=>line>segment.last.line&&lines.comparable&& + s.diagnosticRoute==="NORMAL"&&s.renderHardwareXrun==="UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE"); + // Pair only an immediately preceding accepted DRY window with the next + // accepted FX window. Never compare an earlier app session, an unrelated + // third run, or a hours-old source recording with today's loaded inserts. + const fxIndex=analysis.segments.findLastIndex(s=>ready.includes(s) && + s.mode==="FX" && s.nativeFxInstalledCount>0 && s.nativeFxProcessingCount>0); + const fx=fxIndex>=0?analysis.segments[fxIndex]:null; + const dry=fxIndex>0?analysis.segments[fxIndex-1]:null; + if(!fx||!dry||!dry.comparable||fx.invalidBefore||dry.mode!=="DRY"|| + dry.diagnosticRoute!=="NORMAL") + return {comparable:false,reason:"Need contiguous real NORMAL/DRY then NORMAL/FX windows, each >=30s."}; + if(dry.sessionId!==fx.sessionId || + fx.startTimeMs60000) + return {comparable:false,reason:"DRY/FX windows belong to different app sessions or are more than 60s apart."}; + for(const key of ["backend","device","inputDevice","outputDevice", + "sessionId","deviceGeneration","nativeFxGraphRevision", + "inputMask","outputMask","inputChannels","outputChannels", + "sampleRate","bufferFrames"]){ + if(dry[key]!==fx[key])return {comparable:false,reason:"Mismatched "+key+": do not compare unlike hardware profiles."}; + } + return {comparable:true,baseline:"DRY",candidate:"FX", + device:dry.device,sampleRate:dry.sampleRate,bufferFrames:dry.bufferFrames, + dry:{p95:dry.p95BudgetUpperPct,p99:dry.p99BudgetUpperPct, + overBudgetPer1000:dry.overBudgetPer1000,late:dry.lateCallbackIntervals}, + fx:{p95:fx.p95BudgetUpperPct,p99:fx.p99BudgetUpperPct, + overBudgetPer1000:fx.overBudgetPer1000,late:fx.lateCallbackIntervals}, + deltaOverBudgetPer1000:Math.round(100*(fx.overBudgetPer1000-dry.overBudgetPer1000))/100, + qualification:"HOST_TIMING_ONLY_NOT_PHYSICAL_XRUN_OR_ROUND_TRIP_FAT"}; +} + +export function markdownReport(analysis){ + const cmp=compareDryFx(analysis); + const lines=["# ArSonMix INT-1B — Audio Reliability Profile","", + "This is native host timing, not physical render-XRUN, GPU, ASIO round-trip or CPU profiling.", + "Real hardware FAT and operator listening remain separately required.","", + "| Mode | Driver | Rate/Frames | Seconds | p95/p99 budget ceiling | Over-budget/1000 | Late callback | RAM working set / private MiB | Observation |", + "|---|---|---|---:|---:|---:|---:|---|"]; + for(const s of analysis.segments){ + const pct=x=>x===null?">100% / N/A":x+"%"; + lines.push("| "+s.mode+" | "+s.backend+" | "+s.sampleRate+"/"+s.bufferFrames+ + " | "+s.durationSeconds+" | "+pct(s.p95BudgetUpperPct)+"/"+pct(s.p99BudgetUpperPct)+ + " | "+(s.overBudgetPer1000??"N/A")+" | "+s.lateCallbackIntervals+ + " | "+(s.processWorkingSetMiB??"N/A")+" / "+(s.processPrivateCommitMiB??"N/A")+ + " | "+s.diagnosis+" |"); + } + lines.push("",cmp.comparable? + "**Matched actual native dry→FX comparison:** Δ over-budget per 1000 callbacks = "+cmp.deltaOverBudgetPer1000+ + "; **NOT** a hardware XRUN or causal DSP proof.": + "**No valid matched dry/FX comparison:** "+cmp.reason); + if(analysis.warnings.length)lines.push("","Data warnings: "+analysis.warnings.slice(0,12).join("; ")); + lines.push("","Only optimize the measured problematic path; keep primary ASIO direct and one PCM/FX graph."); + return lines.join("\n")+"\n"; +} + +function main(args){ + if(!args.length||args.includes("--help")){ + process.stdout.write("Usage: node scripts/audio_reliability_profile.mjs audio-diagnostics.log [--json report.json] [--markdown report.md]\n"); + return args.includes("--help")?0:2; + } + const input=args[0]; + const opt=name=>{const i=args.indexOf(name);return i>=0?args[i+1]:null;}; + if(args.some((x,i)=>x.startsWith("--")&& + (!["--json","--markdown"].includes(x)||!args[i+1]))) + throw Error("Invalid output option; use --json FILE or --markdown FILE"); + const result=analyzeHealthLog(readFileSync(input,"utf8")); + if(result.totalSamples===0)throw Error("No valid INT-1B AUDIO_HEALTH snapshots; check schema/log rotation"); + const json=opt("--json"), md=opt("--markdown"); + if(json)writeFileSync(json,JSON.stringify({...result,dryFxComparison:compareDryFx(result)},null,2)+"\n"); + if(md)writeFileSync(md,markdownReport(result)); + if(!json&&!md)process.stdout.write(markdownReport(result)); + return 0; +} +if(process.argv[1]&&import.meta.url===pathToFileURL(resolve(process.argv[1])).href){ + try {process.exitCode=main(process.argv.slice(2));} + catch(err){console.error("INT1B_PROFILE_ERROR: "+err.message);process.exitCode=1;} +} diff --git a/scripts/build_verify_windows_installer.ps1 b/scripts/build_verify_windows_installer.ps1 index 2a39740c7..c72cb7df6 100644 --- a/scripts/build_verify_windows_installer.ps1 +++ b/scripts/build_verify_windows_installer.ps1 @@ -8,6 +8,11 @@ $sha=(& git rev-parse HEAD).Trim() $manifest=Get-Content -LiteralPath (Join-Path $dist "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json $exe=Join-Path $dist "ArSonMix-GUI10CH-P012-Windows-x64.exe" $appHash=(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() +# Binary-level fresh-Win10 prerequisite gate: GitHub runners have the VC++ +# redist preinstalled, so a successful CI launch alone cannot catch /MD. +# Inspect real PE import and delay-import tables BEFORE shipping/installation. +& python scripts/verify_win10_pe_runtime.py --exe $exe +if($LASTEXITCODE -ne 0){throw "Packaged PE still requires dynamic MSVC redistributable"} if($LASTEXITCODE -ne 0 -or $manifest.sourceCommit -ne $sha -or $manifest.exeSha256 -ne $appHash -or $manifest.fatStatus -ne "SOFTWARE_VERIFIED_PREVIEW_CANDIDATE" -or (Get-Item -LiteralPath $exe).Length -ne $manifest.guiExeBytes -or @@ -35,6 +40,9 @@ $sentinel=Join-Path $studio ("installer-test-"+[guid]::NewGuid().ToString("N")+" $fixtureReady=Join-Path $env:RUNNER_TEMP ("arsonmix-fixture-ready-"+[guid]::NewGuid().ToString("N")) $fixtureClosed=Join-Path $env:RUNNER_TEMP ("arsonmix-fixture-closed-"+[guid]::NewGuid().ToString("N")) $fixtureProcess=$null +$probeProcess=$null +$probeToken=[guid]::NewGuid().ToString('D') +$probeMarker=Join-Path $env:LOCALAPPDATA "ArSonMix\Updates\health\$probeToken.ready" try { New-Item -ItemType Directory -Force -Path $stage | Out-Null Copy-Item -LiteralPath $exe -Destination (Join-Path $stage "verified-gui.exe") @@ -66,6 +74,35 @@ try { } $installedManifest=Get-Content -LiteralPath (Join-Path $install "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json if($installedManifest.sourceCommit -ne $sha){throw "Wrong installed provenance"} + $diagnosticHelper=Join-Path $install "ArSonMixStartupDiagnostics.ps1" + if ((Get-FileHash -LiteralPath $diagnosticHelper -Algorithm SHA256).Hash.ToLowerInvariant() -ne + $manifest.startupDiagnosticsSha256) { + throw "Installed diagnostics helper differs from the verified portable source" + } + # Verify the genuine installed GUI enters the approved native WebView. + # Unique probe GUID inhibits device discovery, plugin restore and output. + $info=[Diagnostics.ProcessStartInfo]::new() + $info.FileName=$installedExe + $info.WorkingDirectory=$install + $info.UseShellExecute=$false + $info.EnvironmentVariables['ARSONMIX_UPDATE_PROBE']=$probeToken + $probeProcess=[Diagnostics.Process]::Start($info) + $deadline=[DateTime]::UtcNow.AddSeconds(45) + while (!(Test-Path -LiteralPath $probeMarker -PathType Leaf) -and + !$probeProcess.HasExited -and [DateTime]::UtcNow -lt $deadline) { + Start-Sleep -Milliseconds 250 + } + if (!(Test-Path -LiteralPath $probeMarker -PathType Leaf) -or + (Get-Content -LiteralPath $probeMarker -Raw).Trim() -cne 'GUI_READY_NO_AUDIO' -or + !$probeProcess.WaitForExit(12000) -or $probeProcess.ExitCode -ne 0) { + try { + & $diagnosticHelper | Write-Host + $diagnosticReport=Join-Path $env:LOCALAPPDATA 'ArSonMix\diagnostics\windows-startup-report.txt' + Get-Content -LiteralPath $diagnosticReport -TotalCount 80 | Write-Host + } catch { Write-Warning $_ } + throw "Installed ArSonMix did not complete its native GUI-only startup probe" + } + Write-Host "INSTALLER_NATIVE_GUI_READY_NO_AUDIO: runner build $([Environment]::OSVersion.Version.Build)" # Full AGPL and third-party terms live in ArSonMix.exe and Setup itself. # The installed directory must have NO redundant top-level legal files. & python scripts/verify_embedded_legal.py --binary $installedExe @@ -158,11 +195,22 @@ try { installerSha256=(Get-FileHash -LiteralPath $setup -Algorithm SHA256).Hash.ToLowerInvariant() certification="PREVIEW__INSTALLER_INTEGRITY_AND_UPDATE_TESTED";mode="PER_USER_NO_AUTOARM" updaterTest="WM_CLOSE_IN_PLACE_SHA256_AND_USER_DATA_PRESERVED" + guiStartup="NATIVE_WEBVIEW_READY_NO_AUDIO" + guiStartupRunnerBuild=[Environment]::OSVersion.Version.Build } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $out "INSTALLER_PROVENANCE.json") -Encoding UTF8 Write-Host "INSTALLER_RC_VERIFIED: first install, graceful running-app graceful update, SHA-matched PE, uninstall, private Studio intact" Write-Host "OWNER_FIELD_AUDIO_LISTENING_REPORTED__PER_BUILD_HARDWARE_REPORT_SEPARATE" } finally { + if($null -ne $probeProcess) { + # CI-owned child only. The production updater never kills ArSonMix. + if(!$probeProcess.HasExited) { + $probeProcess.Kill() + [void]$probeProcess.WaitForExit(5000) + } + $probeProcess.Dispose() + } + Remove-Item -LiteralPath $probeMarker -Force -ErrorAction SilentlyContinue # Only a failing *test fixture* may be terminated in CI teardown. # Production Inno Setup never force-kills the user's audio application. if($null -ne $fixtureProcess){ diff --git a/scripts/package_native_windows.ps1 b/scripts/package_native_windows.ps1 index 5378316d1..1cc447878 100644 --- a/scripts/package_native_windows.ps1 +++ b/scripts/package_native_windows.ps1 @@ -106,6 +106,7 @@ Copy-Item -LiteralPath $readme -Destination (Join-Path $OutputDir "README.md") & python scripts/verify_embedded_legal.py --binary $destination if ($LASTEXITCODE -ne 0) { throw "Compiled native mixer lacks the exact-source embedded legal texts" } Copy-Item -LiteralPath $fatGuide -Destination (Join-Path $OutputDir "HARDWARE_FAT_GUIDE.md") +Copy-Item -LiteralPath "installer/ArSonMixStartupDiagnostics.ps1" -Destination $OutputDir # Selective FAT-only extraction from parked #270, no PCM or GUI production code. $fatBundleFiles = @("collect_hardware_fat_windows.ps1", "m3e_fat_evidence_gate.mjs") foreach ($file in $fatBundleFiles) { @@ -139,6 +140,7 @@ $manifest = [ordered]@{ peFormat = "PE32+" peSubsystem = "WINDOWS_GUI (2)" exeSha256 = (Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash.ToLowerInvariant() + startupDiagnosticsSha256 = (Get-FileHash -LiteralPath (Join-Path $OutputDir "ArSonMixStartupDiagnostics.ps1") -Algorithm SHA256).Hash.ToLowerInvariant() fatCollectorSha256 = (Get-FileHash -LiteralPath (Join-Path $OutputDir "collect_hardware_fat_windows.ps1") -Algorithm SHA256).Hash.ToLowerInvariant() fatGateSha256 = (Get-FileHash -LiteralPath (Join-Path $OutputDir "m3e_fat_evidence_gate.mjs") -Algorithm SHA256).Hash.ToLowerInvariant() legalEmbedding = "JUCE_BINARYDATA_OFFLINE_LEGAL_CENTER_V1" diff --git a/scripts/verify_native_windows_artifact.ps1 b/scripts/verify_native_windows_artifact.ps1 index 60b251820..752f4646a 100644 --- a/scripts/verify_native_windows_artifact.ps1 +++ b/scripts/verify_native_windows_artifact.ps1 @@ -12,6 +12,7 @@ $expected = @( "HARDWARE_FAT_GUIDE.md", "README.md", "portable_mode.txt", + "ArSonMixStartupDiagnostics.ps1", "collect_hardware_fat_windows.ps1", "m3e_fat_evidence_gate.mjs", "FACTORYFX_STAGE_REPORT.json" @@ -65,6 +66,14 @@ if (-not $agplText.StartsWith("GNU AFFERO GENERAL PUBLIC LICENSE") -or & python scripts/verify_embedded_legal.py --binary (Join-Path $OutputDir $expected[0]) if ($LASTEXITCODE -ne 0) { throw "Exact-source embedded legal scan failed" } # FAT tools match source bytes, distributed bytes AND the current SHA manifest. +$startupDiagnostics = "ArSonMixStartupDiagnostics.ps1" +foreach ($path in @((Join-Path "installer" $startupDiagnostics), (Join-Path $OutputDir $startupDiagnostics))) { + if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -ne $manifest.startupDiagnosticsSha256) { + throw "Startup diagnostic script differs from exact-source manifest" + } +} +& python scripts/verify_win10_pe_runtime.py --exe (Join-Path $OutputDir $expected[0]) +if ($LASTEXITCODE -ne 0) { throw "Packaged PE dependency audit failed" } $fatTools = @{ "collect_hardware_fat_windows.ps1" = [string]$manifest.fatCollectorSha256 "m3e_fat_evidence_gate.mjs" = [string]$manifest.fatGateSha256 diff --git a/scripts/verify_win10_pe_runtime.py b/scripts/verify_win10_pe_runtime.py new file mode 100644 index 000000000..f23f5269f --- /dev/null +++ b/scripts/verify_win10_pe_runtime.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Fail closed if a Windows x64 PE imports Visual C++ redistributable DLLs. + +Runs on the exact EXE that the per-user Inno installer will ship. /MT is +configured for the WHOLE JUCE target graph; this is an independent binary +check, not evidence that WebView2 or hardware ASIO is installed. +Standard-library only, no downloads or machine-wide changes. +""" +from __future__ import annotations + +import argparse +import os +import pathlib +import re +import struct +import sys + + +def imports(path: pathlib.Path) -> set[str]: + data = path.read_bytes() + + def u16(at: int) -> int: + if at < 0 or at + 2 > len(data): + raise ValueError("Truncated PE word") + return struct.unpack_from(" int: + if at < 0 or at + 4 > len(data): + raise ValueError("Truncated PE dword") + return struct.unpack_from(" len(data): + raise ValueError("Truncated optional header") + directory = optional + 112 + if directory + 16 * 8 > optional + opt_bytes or u32(optional + 108) < 16: + raise ValueError("Missing import data-directory") + sections = optional + opt_bytes + section_rows: list[tuple[int, int, int]] = [] + for i in range(count): + sec = sections + i * 40 + vaddr = u32(sec + 12) + rsize = u32(sec + 16) + raw = u32(sec + 20) + if raw + rsize > len(data): + raise ValueError("Section exceeds PE file") + section_rows.append((vaddr, rsize, raw)) + + def rva_to_offset(rva: int) -> int: + for va, size, raw in section_rows: + if va <= rva < va + size and raw + rva - va < len(data): + return raw + rva - va + raise ValueError(f"Unmapped import RVA {rva:x}") + + def cstring(rva: int) -> str: + at = rva_to_offset(rva) + end = data.find(b"\x00", at, min(len(data), at + 512)) + if end < 0: + raise ValueError("Unterminated DLL import") + return data[at:end].decode("ascii").lower() + + names: set[str] = set() + # Standard and delay-import descriptor tables have distinct record sizes. + for index, width, name_offset in ((1, 20, 12), (13, 32, 4)): + table = u32(directory + index * 8) + size = u32(directory + index * 8 + 4) + if not table and not size: + continue + if not table or size < width: + raise ValueError("Invalid import descriptor table") + for position in range(0, min(size, 1024 * width) - width + 1, width): + at = rva_to_offset(table + position) + end = rva_to_offset(table + position + width - 1) + if end != at + width - 1: + raise ValueError("Import descriptor crosses file sections") + if not any(data[at:end + 1]): + break + if index == 13 and not u32(at) & 1: + raise ValueError("Unsupported absolute-VA delay import") + names.add(cstring(u32(at + name_offset))) + else: + raise ValueError("Unterminated PE imports") + return names + + +def check(path: pathlib.Path) -> None: + names = imports(path) + if not names: + raise ValueError("No imported libraries: unexpected native GUI PE") + forbidden = [n for n in sorted(names) if re.fullmatch( + r"(?:(?:vcruntime|msvcp|msvcr|concrt|mfcm?|vcomp|vcamp|vccorlib)\d+[a-z0-9_-]*|" + r"ucrtbased|webview2loader)\.dll", n)] + if forbidden: + raise ValueError("Unexpected runtime dependency: " + ", ".join(forbidden)) + if sys.platform == "win32": + system32 = pathlib.Path(os.environ["SystemRoot"]) / "System32" + missing = sorted(name for name in names if + not name.startswith(("api-ms-win-", "ext-ms-win-")) and + (pathlib.PureWindowsPath(name).name != name or + not (system32 / name).is_file())) + if missing: + raise ValueError("Non-OS or missing runtime dependencies: " + ", ".join(missing)) + print("WIN10_STATIC_CRT_PE_PASS: audited direct/delay DLLs: " + ", ".join(sorted(names))) + print("WEBVIEW2_RUNTIME_REQUIRED_SEPARATELY_NOT_PROVEN") + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--exe", type=pathlib.Path, required=True) + args = parser.parse_args() + try: + check(args.exe) + except (OSError, ValueError, struct.error) as err: + print("WIN10_STATIC_CRT_PE_FAIL: " + str(err), file=sys.stderr) + sys.exit(1) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 42951518e..884b7519e 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -6,6 +6,7 @@ #include "NativePresetArchive.h" #include "VstBusLayout.h" #include "LiveGraphHandoff.h" +#include "../engine/diagnostics/PhysicalLoopback.h" #include "LiveDryRoutingLab.h" #include "NativeMixerSessionFxRestore.h" #include "NativeTopologyEditSafety.h" @@ -2501,6 +2502,91 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setNativeBusMix(epoch,revision,id,gain,pan); } + struct LoopbackPins { + juce::String identity; + juce::Array inputs, outputs; + int rate = 0, block = 0, inputOrdinal = -1, outputOrdinal = -1; + int inputCount = 0, outputCount = 0; + std::uint64_t epoch = 0; + }; + + std::optional inspectLoopback(int input = -1, int output = -1) + { + if (independent_.active() || !directFence_.permitted() || + !dryRoutingLab_.channelIdPhysicalPcmActive() || !asioPinnedRegistration_.valid()) + return {}; + auto* device = deviceManager_.getCurrentAudioDevice(); + if (!device || device->getTypeName() != "ASIO" || + device->getName().containsIgnoreCase("ASIO4ALL")) + return {}; + const auto epoch = dryRoutingLab_.epoch(); + armix::device::JuceActivePortSnapshot pins; + armix::device::JuceActivePortSnapshot::Fault fault{}; + if (!armix::device::JuceActivePortSnapshot::capture(device, epoch, pins, fault)) + return {}; + const auto inputNames = device->getInputChannelNames(); + const auto main = dryRoutingLab_.acceptedMainCallbackPair(); + LoopbackPins info; + info.epoch = epoch; + const auto rate = device->getCurrentSampleRate(); + info.block = device->getCurrentBufferSizeSamples(); + if (rate < 44100 || rate > 192000 || std::floor(rate) != rate || + info.block < 16 || info.block > 2048 || epoch != dryRoutingLab_.epoch()) + return {}; + info.rate = static_cast(rate); + info.inputCount = pins.inputs.enabledCount; + info.outputCount = pins.outputCount; + for (int i = 0; i < info.inputCount; ++i) + if (const int pin = pins.inputs.physicalIndex(i); pin >= 0 && pin < 64 && + pin < inputNames.size() && dryRoutingLab_.loopbackInputUnpatched(i)) + info.inputs.add(pin); + for (const int i : main) + if (const int pin = pins.outputPhysicalPort(i); pin >= 0 && pin < 64 && + pin < pins.outputNames.size()) + info.outputs.addIfNotAlreadyThere(pin); + if (info.inputs.isEmpty() || info.outputs.isEmpty()) + return {}; + if (info.inputs.contains(input) && info.outputs.contains(output)) { + info.inputOrdinal = pins.inputs.callbackIndex(input); + info.outputOrdinal = output == pins.outputPhysicalPort(main[0]) ? main[0] : main[1]; + // Exact configured driver and physical pin scope. The raw probe + // bypasses the mixer graph, FX, and compensating delays. + juce::Array key; + key.add("arsonmix.physical-loopback.v1"); + key.add(pins.typeName); + key.add(pins.deviceName); + key.add(juce::String(asioPinnedRegistration_.registryKey.c_str())); + key.add(juce::String(asioPinnedRegistration_.canonicalClsid.c_str())); + key.add(device->getActiveInputChannels().toString(16)); + key.add(device->getActiveOutputChannels().toString(16)); + key.add(info.rate); + key.add(info.block); + key.add(input); + key.add(inputNames[input]); + key.add(output); + key.add(pins.outputNames[output]); + info.identity = juce::JSON::toString(juce::var(key), true); + } + return info; + } + + using Loopback = armix::diagnostics::PhysicalLoopback; + bool beginLoopback(const LoopbackPins& pins) + { + if (pins.identity.isEmpty() || pins.epoch != dryRoutingLab_.epoch() || + !directFence_.permitted() || isOutputMuted() || secondaryOutput_.armed() || + masterMute_.load(std::memory_order_acquire) || handoff_.busy() || + routeReconfiguring_.load(std::memory_order_acquire) || + topologyPublicationMute_.load(std::memory_order_acquire) || + diagnosticRoute() != armix::diagnostics::Route::normal) + return false; + return loopback_.start(pins.rate, pins.block, pins.inputOrdinal, pins.outputOrdinal, + pins.inputCount, pins.outputCount, pins.epoch); + } + Loopback::State loopbackState() const noexcept { return loopback_.state(); } + Loopback::Capture takeLoopback() { return loopback_.take(); } + void cancelLoopback() noexcept { loopback_.requestCancel(); } + bool dryRoutingLabActive() const noexcept {return dryRoutingLab_.active();} bool hasBoundMixerRoute() const noexcept {return dryRoutingLab_.hasExplicitRoute();} // Existing verified ASIO external-pair intent is a valid output user @@ -2518,7 +2604,96 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback auto* d = dual ? independent_.renderDevice() : deviceManager_.getCurrentAudioDevice(); auto* capture = dual ? independent_.captureDevice() : d; - o->setProperty ("dryRoutingLab",dryRoutingLab_.status(capture)); + const auto nativeRoutingStatus = dryRoutingLab_.status(capture); + o->setProperty ("dryRoutingLab", nativeRoutingStatus); + // INT-1B: native DRY is an accepted DSP fact, NOT the legacy + // dryTest_ UI flag (which only tracks operator intent). + // Count installed/effectively processing inserts from the already + // generated CONTROL readback. No extra render/FX scan on RT. + const bool globalFxBypassed = dryRoutingLab_.globalFxBypassed(); + int installedNativeFx = 0, processingNativeFx = 0; + const auto accountInserts = [&] (const juce::var& inserts, + bool rackBypassed) + { + if (const auto* list = inserts.getArray()) + for (const auto& insert : *list) + if (insert.isObject()) + { + ++installedNativeFx; + if (!globalFxBypassed && !rackBypassed && + !bool (insert.getProperty ("bypassed", false))) + ++processingNativeFx; + } + }; + const auto bus = nativeRoutingStatus.getProperty ("nativeBus", {}); + if (bus.isObject()) + { + const auto channelRows = bus.getProperty ("channels", {}); + if (const auto* channels = channelRows.getArray()) + for (const auto& channel : *channels) + accountInserts ( + channel.getProperty ("inserts", {}), + bool (channel.getProperty ("fxRackBypassed", false))); + } + else + { + const auto rackFlags = + nativeRoutingStatus.getProperty ("fxRackBypassed", {}); + const auto* flags = rackFlags.getArray(); + const auto rackInstances = + nativeRoutingStatus.getProperty ("fxInstances", {}); + if (const auto* racks = rackInstances.getArray()) + for (int lane = 0; lane < racks->size(); ++lane) + accountInserts ((*racks)[lane], + flags != nullptr && lane < flags->size() + && bool ((*flags)[lane])); + } + // Original Channel 1 vendor/Orbit inserts are one SHARED Graph + // leased by the admitted ChannelId renderer, not ordinary entries + // of nativeBus.channels[].inserts. Those entries are intentionally + // zero for the external channel. Never report the live vendor rack + // as DRY simply because its FX live in a distinct native lease. + int externalCh1Installed = 0, externalCh1Processing = 0; + const auto* acceptedExternal = + dryRoutingLab_.acceptedOriginalCh1ExternalLeaseForControl(); + // Admit only OUR historical JUCE Graph callback. Future external + // lease types must not be cast into Graph or falsely labeled DRY. + const bool externalCh1Leased = acceptedExternal != nullptr && + acceptedExternal->render == &processOwnedChannelOne; + const bool externalFxActivityComplete = + !bool (nativeRoutingStatus.getProperty ( + "originalCh1GraphLeased", false)) || externalCh1Leased; + if (externalCh1Leased) + { + const auto* acceptedGraph = + static_cast (acceptedExternal->context); + const bool externalRackBypassed = + acceptedGraph->rackBypassed.load (std::memory_order_acquire); + for (int i = 0; i < acceptedGraph->count; ++i) + { + const int physical = acceptedGraph->physicalAt (i); + if (!acceptedGraph->slots[physical].processor) + continue; + ++externalCh1Installed; + if (!globalFxBypassed && !externalRackBypassed && + !acceptedGraph->bypassFlags[physical].load ( + std::memory_order_acquire)) + ++externalCh1Processing; + } + installedNativeFx += externalCh1Installed; + processingNativeFx += externalCh1Processing; + } + o->setProperty ("nativeFxActivityComplete", externalFxActivityComplete); + o->setProperty ("nativeExternalCh1Leased", externalCh1Leased); + o->setProperty ("nativeExternalCh1InstalledCount", externalCh1Installed); + o->setProperty ("nativeExternalCh1ProcessingCount", externalCh1Processing); + o->setProperty ("nativeGlobalFxBypassed", globalFxBypassed); + o->setProperty ("nativeFxInstalledCount", installedNativeFx); + o->setProperty ("nativeFxProcessingCount", processingNativeFx); + o->setProperty ("nativeFxCountProvenance", + "ACCEPTED_CHANNELID_PLUS_LEASED_EXTERNAL_CH1_SLOT_RACK_GLOBAL_BYPASS_NOT_dryTest"); + o->setProperty ("nativeFxGraphRevision", + nativeRoutingStatus.getProperty ("revision", {}).toString()); o->setProperty("waitingAsioInputs",dryRoutingLab_.waitingAsioInputCount()); // NORMAL mode is never silently served by the legacy CH1 fallback. // This state is for operator feedback; it does not authorize output. @@ -2627,6 +2802,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("outputDevice", dual && d ? d->getName() : setup.outputDeviceName); o->setProperty ("deviceInputChannels", capture ? capture->getActiveInputChannels().countNumberOfSetBits() : 0); o->setProperty ("deviceOutputChannels", d ? d->getActiveOutputChannels().countNumberOfSetBits() : 0); + // Control-only pin-mask evidence: matching channel COUNTS do not + // imply the same physical ASIO pin assignment after a remap. + o->setProperty ("activeInputMaskHex", capture ? + capture->getActiveInputChannels().toString (16) : juce::String()); + o->setProperty ("activeOutputMaskHex", d ? + d->getActiveOutputChannels().toString (16) : juce::String()); o->setProperty ("callbackInputChannels", callbackInputs_.load()); o->setProperty ("callbackOutputChannels", callbackOutputs_.load()); o->setProperty ("callbackCount", static_cast (callbackCount_.load())); @@ -2663,6 +2844,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("callbackP95BeyondDeadline", histogram.p95Ceiling < 0); o->setProperty ("callbackP99BeyondDeadline", histogram.p99Ceiling < 0); o->setProperty ("callbackBudgetSamples", static_cast (histogram.total)); + // INT-1B: cumulative buckets enable true 1 Hz interval percentiles + // without resetting/replacing RT atomics at ASIO device transitions. + // The message thread alone allocates this 13-value readback array. + // Never label these host callback timing buckets as hardware XRUNs. + juce::Array budgetBuckets; + for (const auto count : histogram.counts) + budgetBuckets.add (static_cast (count)); + o->setProperty ("callbackBudgetBuckets", juce::var (budgetBuckets)); + o->setProperty ("callbackBudgetBucketProvenance", + "HOST_CALLBACK_BUDGET_CUMULATIVE_13_BUCKETS_NOT_DRIVER_RENDER_XRUN"); o->setProperty ("inputPeak", inputPeak_.load()); o->setProperty ("inputPeakProvenance", "RAW_PCM_BEFORE_HARDWARE_MUTE"); // First Sound: JUCE supplies callback-COMPACT input channels. @@ -2961,6 +3152,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Indexed atomic bypass flags: instant RT-safe toggles, no graph detachment. // Temporary publication silence never changes operator MONITOR or MAIN MUTE. // The DIRECT device fence and physical-output verification remain separate. + Loopback loopback_; + std::atomic_flag loopbackRendering_=ATOMIC_FLAG_INIT; std::atomic topologyPublicationMute_ { false }; // Persistent in-process operator intent; independent of audio device epoch. armix::device::OutputContinuityIntent mainOutputIntent_; @@ -3059,6 +3252,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback resumeMainAfterAsioReset_.store(true,std::memory_order_release); } setOutputMuted(true); // transient hardware gate, NOT an operator MUTE + loopback_.interrupted(); secondaryOutput_.invalidateSource(); // source clock may have changed dryRoutingLab_.prepareDevice(d); // exact active mask, before callback if (!independent_.active()) @@ -3119,6 +3313,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback resumeMainAfterAsioReset_.store(true,std::memory_order_release); } monitor_.store(false,std::memory_order_release); + loopback_.interrupted(); secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop masterLoudness_.prepare (0.0); // clear validity across device epoch dryRoutingLab_.deviceStopped(); @@ -3239,6 +3434,19 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // allocations, OS calls or device restart on the realtime callback. // An independent WASAPI bridge has its own verified endpoint guard. const auto activeDiagnosticRoute = diagnosticRoute_.load (std::memory_order_acquire); + std::optional probePermit; + if (loopback_.state() == Loopback::State::capturing) { + probePermit.emplace(loopbackRendering_); + if (!*probePermit) { + for (int c=0; cexternalChannel()==target && target==nativeAccepted_.graph.ids.inputs[0]; } + // Off-RT diagnostic only: do not infer the active external vendor Graph + // from the latest graphOwned_ pointer, which can differ during a staged + // FX handoff. Read the strong, accepted PCM lease under CONTROL instead. + const armix::mixer::DynamicChannelFxLeaseBank::ExternalLease* + acceptedOriginalCh1ExternalLeaseForControl() const noexcept + { + if (!channelIdPhysicalPcmActive() || !nativeAccepted_.fxOwners) + return nullptr; + const auto* lease = + nativeAccepted_.fxOwners->externalLeaseForControl(); + return lease != nullptr && + lease->id == nativeAccepted_.graph.ids.inputs[0] + ? lease : nullptr; + } // Single global A/B override for M4 and the authoritative ChannelId PCM // graph. Never rewrite saved rack/slot bypass flags or rebuild processors. // A physical ACK requires an accepted CURRENT epoch/revision. @@ -3054,6 +3068,16 @@ class LiveDryRoutingLab final { return {{-1,-1}}; } + bool loopbackInputUnpatched(int ordinal) const noexcept { + if (!channelIdPhysicalPcmActive() || !ready() || ordinal < 0) + return false; + const auto& sources = nativeAccepted_.graph.request.sources; + return std::none_of(sources.begin(), sources.end(), [ordinal](const auto& source) { + return source.kind == armix::mixer::DynamicSourceKind::physical && + (source.inputL == ordinal || (source.stereo && source.inputR == ordinal)); + }); + } + // JUCE render callback, with a verified single-clock device. Routing // publishes at the BLOCK boundary. Missing/stale ports output SILENCE. // A failed run never falls through to an unrelated microphone/plugin path. diff --git a/src/Main.cpp b/src/Main.cpp index 90e6965a2..d7337420b 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -78,6 +78,8 @@ #include "../engine/player/PlayerLibraryPolicy.h" #include #include +#include +#include namespace { @@ -115,11 +117,21 @@ std::optional assetFor (const juce::String& return resource; } +juce::File webViewProfile() +{ + const auto folder=armix::storage::PortableWorkspace::browserDataRoot(); +#if defined(_WIN32) + if (juce::JUCEApplication::getCommandLineParameterArray().contains("--safe-webview-profile")) + return folder.getSiblingFile("WebView2Recovery"); +#endif + return folder; +} + // Materialize browser cache BEFORE WebView2 construction (USB portable mode). // This single options factory also drives the startup preflight below. juce::WebBrowserComponent::Options webViewOptions() { - const auto folder = armix::storage::PortableWorkspace::browserDataRoot(); + const auto folder = webViewProfile(); folder.createDirectory(); #if defined(_WIN32) // Windows must keep the proven WebView2 profile, loader and native bridge. @@ -138,25 +150,61 @@ juce::WebBrowserComponent::Options webViewOptions() #endif } +void writeStartupDiagnostic(const juce::String& phase,const juce::String& detail={}) +{ +#if defined(_WIN32) + const auto local = juce::SystemStats::getEnvironmentVariable ("LOCALAPPDATA", {}); + if (local.isNotEmpty()) + { + const auto report = juce::File (local).getChildFile ("ArSonMix") + .getChildFile ("diagnostics").getChildFile ("startup-failure.txt"); + if (report.getParentDirectory().createDirectory().wasOk()) + (void)report.replaceWithText( + "ArSonMix "+juce::String(ARMIX_BUILD_SOURCE_SHA)+"\nTime: " + + juce::Time::getCurrentTime().toISO8601 (true) + + "\nOS: " + juce::SystemStats::getOperatingSystemName() + + "\nStage: "+phase+"\n"+detail.substring(0,512)+"\n"); + } +#else + juce::ignoreUnused(phase,detail); +#endif +} + void showWebViewStartupError (const juce::String& detail) { + writeStartupDiagnostic("WEBVIEW_STARTUP_FAILED",detail); juce::NativeMessageBox::showAsync ( juce::MessageBoxOptions{} .withIconType (juce::MessageBoxIconType::WarningIcon) #if defined(_WIN32) - .withTitle ("ArSonMix - WebView2 unavailable") - .withMessage ("The offline ArSonMix mixer needs Microsoft Edge WebView2 Runtime.\\n\\n" - + detail + "\\n\\nDownload / repair from Microsoft:\\n" - "https://developer.microsoft.com/en-us/microsoft-edge/webview2/\\n\\n" - "No VST3, mixer presets or session data were deleted.") + .withTitle ("ArSonMix - Windows GUI cannot start") + .withMessage ("The offline ArSonMix mixer needs Microsoft Edge WebView2 Runtime.\n\n" + + detail + "\n\nDownload / repair from Microsoft:\n" + "https://developer.microsoft.com/en-us/microsoft-edge/webview2/\n\n" + "Use Start ArSonMix with Recovery Profile from the Start menu to use a separate browser profile.\n" + "Local diagnostic: %LOCALAPPDATA%\\ArSonMix\\diagnostics\\startup-failure.txt") #else .withTitle ("ArSonMix - native WebKit unavailable") .withMessage ("ArSonMix requires the system WebKit browser backend " - "(WKWebView on macOS, WebKitGTK on Linux).\\n\\n" - + detail + "\\n\\nNo Show, plugin or preset data were deleted.") + "(WKWebView on macOS, WebKitGTK on Linux).\n\n" + + detail + "\n\nNo Show, plugin or preset data were deleted.") +#endif +#if defined(_WIN32) + .withButton ("Download / Repair WebView2") #endif .withButton ("Close"), - [] (int) { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }); + [] (int result) + { +#if defined(_WIN32) + // JUCE 8 pinned NativeMessageBox uses 0-based button indices. + // Only an explicit click opens the signed vendor download page. + // No driver installation, audio output or private data mutation. + if (result == 0) + juce::URL ("https://developer.microsoft.com/en-us/microsoft-edge/webview2/") + .launchInDefaultBrowser(); +#endif + juce::JUCEApplication::getInstance()->systemRequestedQuit(); + }); } class Browser final : public juce::WebBrowserComponent @@ -327,6 +375,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr handleNativeChannelIdentitySet(args); }) .withEventListener ("arMixLogicalIntent", [this] (juce::var args) { + cancelPhysicalLoopback(); handleLogicalMixerIntent(args); }) .withEventListener ("arMixHotkeyIntent", [this] (juce::var args) { @@ -346,6 +395,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr .withEventListener ("arMixConsoleIntent", [this] (juce::var args) { // The native control thread owns ONLY accepted mutations. // No GUI-side PCM, no legacy ordinal fallback and no fake ACK. + cancelPhysicalLoopback(); handleApprovedNativeControl(args); }) .withEventListener ("arMixPerfControl", [this] (juce::var args) { onGuiPerfControl(args); }) @@ -852,6 +902,52 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return out; } + // INT-1B: preserve a parseable, bounded 1 Hz native health timeline. + // The entire UI status contains large device/FX arrays and can exceed the + // diagnostic worker's 4096-byte record; silently truncated JSON makes + // offline p95/p99 profiling impossible. Reuse the EXISTING status read, + // only on the message thread, with no new timer or audio callback work. + static juce::var makeAudioHealthRecord (const juce::var& state, + const armix::diagnostics::CrackleEvidenceWindow::MemoryPressure& memory) + { + auto compact = std::make_unique(); + compact->setProperty ("schema", "arsonmix.audio-health.int1b.v1"); + for (const char* key : { + "connected", "liveBackendClass", "device", "driver", + "inputDevice", "outputDevice", "deviceInputChannels", + "deviceOutputChannels", "activeInputMaskHex", + "activeOutputMaskHex", "rate", "buffer", "periodUs", + "deviceGeneration", + "deviceStartCount", "deviceStopCount", "diagnosticRoute", + "productionRoutingState", "directRouteAuthorized", + "dryTest", "nativeGlobalFxBypassed", + "nativeFxInstalledCount", "nativeFxProcessingCount", + "nativeFxCountProvenance", "nativeFxGraphRevision", + "nativeExternalCh1Leased", "nativeExternalCh1InstalledCount", + "nativeExternalCh1ProcessingCount", + "nativeFxActivityComplete", + "callbackCount", "callbackBudgetBuckets", + "callbackBudgetBucketProvenance", "callbackBudgetSamples", + "callbackP95BudgetUpperPct", "callbackP99BudgetUpperPct", + "slowCallbackCount", "overBudgetCount", "callbackGapCount", + "lateCallbackIntervals", "callbackCadenceClockRegressions", + "callbackCadenceComparedIntervals", "worstCallbackUs", + "worstPluginUs", "slowPluginCount", + "backendXrunCount", "backendXrunMeaning", + "renderUnderrunSource", "secondaryOutputUnderflow", + "secondaryOutputOverflow", "secondaryOutputFrames"}) + { + const auto value = state.getProperty (key, {}); + if (!value.isVoid()) + compact->setProperty (juce::Identifier (key), value); + } + if (memory.processAvailable) { + compact->setProperty ("processWorkingSetMiB",static_cast(memory.processWorkingSetMiB)); + compact->setProperty ("processPrivateCommitMiB",static_cast(memory.processPrivateCommitMiB)); + } + return juce::var (compact.release()); + } + static juce::String compactMemoryWindowReport ( const armix::diagnostics::CrackleEvidenceWindow::Window& window) { @@ -2132,6 +2228,144 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr #endif } + struct LoopbackJob { + juce::String id, identity; + int input = -1, output = -1, rate = 0; + std::uint64_t epoch = 0; + juce::uint32 started = 0; + bool cancelled = false; + }; + std::optional loopbackJob_; + std::future loopbackAnalysis_; + + static juce::File loopbackCalibrationFile(const juce::String& identity) + { + const juce::SHA256 digest(identity.toRawUTF8(),identity.getNumBytesAsUTF8()); + return settingsDirectory().getChildFile("latency-calibration") + .getChildFile(digest.toHexString()+".json"); + } + + void emitLoopback(const juce::String& id,const juce::String& state, + const juce::String& message={},const juce::var& result={}) + { + if (!browser_.loaded) return; + auto response=std::make_unique(); + response->setProperty("requestId",id); + response->setProperty("state",state); + response->setProperty("message",message); + response->setProperty("result",result); + browser_.emitEventIfBrowserIsVisible("arMixPhysicalLoopback",juce::var(response.release())); + } + + void cancelPhysicalLoopback() + { + if (!loopbackJob_) return; + loopbackJob_->cancelled=true; + engine_.cancelLoopback(); + } + + void requestPhysicalLoopback(const juce::var& args,bool measure) + { + const auto id=args.getProperty("requestId",{}).toString(); + if (id.isEmpty() || id.length()>64) return; + if (loopbackJob_) + return emitLoopback(id,"UNKNOWN","A round-trip measurement is already in progress."); + const auto inputValue=args.getProperty("inputPin",-1); + const auto outputValue=args.getProperty("outputPin",-1); + const int input=static_cast(inputValue), output=static_cast(outputValue); + if (input<0 || input>=64 || output<0 || output>=64 || + static_cast(inputValue)!=input || static_cast(outputValue)!=output) + return emitLoopback(id,"UNKNOWN","Select an enabled line input and MAIN output."); + const auto pins=engine_.inspectLoopback(input,output); + const auto epoch=armix::console::nativeSessionTokenValue(args.getProperty("deviceEpoch",{})); + if (!pins || pins->identity.isEmpty() || pins->epoch!=epoch) + return emitLoopback(id,"UNKNOWN","The accepted ASIO device or pins changed. Reopen Audio I/O."); + if (!measure) { + const auto file=loopbackCalibrationFile(pins->identity); + if (!file.existsAsFile() || file.getSize()>4096) + return emitLoopback(id,"UNKNOWN"); + const auto saved=juce::JSON::parse(file); + const int frames=static_cast(saved.getProperty("frames",0)); + const double confidence=static_cast(saved.getProperty("confidence",0.0)); + if (saved.getProperty("identity",{}).toString()!=pins->identity || + frames<=0 || frames>=pins->rate/2 || + !(confidence>=0.70 && confidence<=1.0)) + return emitLoopback(id,"UNKNOWN"); + return emitLoopback(id,"MEASURED_LOOPBACK","Saved wired calibration",saved); + } + const auto confirmed=args.getProperty("wiredLineLevel",false); + bool started=false; + try { + if (confirmed.isBool() && static_cast(confirmed) && !nativeShowBusy_ && !studioBackupBusy_) + started=engine_.beginLoopback(*pins); + } catch (const std::bad_alloc&) { + return emitLoopback(id,"UNKNOWN","Could not allocate the bounded capture buffer."); + } + if (!started) + return emitLoopback(id,"UNKNOWN", + "Use verified, already armed ASIO MAIN, an unused line input, and disarm secondary output."); + loopbackJob_=LoopbackJob{id,pins->identity,input,output,pins->rate,pins->epoch, + juce::Time::getMillisecondCounter(),false}; + emitLoopback(id,"CAPTURING","Measuring wired round-trip…"); + } + + void servicePhysicalLoopback() + { + using Probe=LiveAudioEngine::Loopback; + if (!loopbackJob_) return; + auto& job=*loopbackJob_; + if (engine_.loopbackState()==Probe::State::capturing && + juce::Time::getMillisecondCounter()-job.started>3000u) { + const bool reported=job.cancelled; + cancelPhysicalLoopback(); + if (!reported) + emitLoopback(job.id,"UNKNOWN","No stable ASIO callback. Measurement cancelled."); + return; + } + const auto finish=[this,&job](const juce::String& state,const juce::String& message, + const juce::var& value={}) { + emitLoopback(job.id,state,message,value); + loopbackJob_.reset(); + }; + if (engine_.loopbackState()==Probe::State::cancelled) { + (void)engine_.takeLoopback(); + return finish("UNKNOWN","Measurement cancelled. Check output arm, stream and routing."); + } + try { + if (engine_.loopbackState()==Probe::State::complete) { + auto pcm=engine_.takeLoopback(); + if (job.cancelled) return finish("UNKNOWN","Measurement cancelled."); + loopbackAnalysis_=std::async(std::launch::async,[pcm=std::move(pcm)] { + return Probe::analyse(pcm); + }); + } + if (!loopbackAnalysis_.valid() || + loopbackAnalysis_.wait_for(std::chrono::seconds(0))!=std::future_status::ready) + return; + const auto result=loopbackAnalysis_.get(); + const auto current=engine_.inspectLoopback(job.input,job.output); + if (job.cancelled || !current || current->epoch!=job.epoch || + current->identity!=job.identity) + return finish("UNKNOWN","Device or pin configuration changed. Measure again."); + if (result.error) + return finish("UNKNOWN",result.error); + auto record=std::make_unique(); + record->setProperty("identity",job.identity); + record->setProperty("provenance","MEASURED_LOOPBACK"); + record->setProperty("frames",result.frames); + record->setProperty("rate",job.rate); + record->setProperty("confidence",result.confidence); + const juce::var saved(record.release()); + const auto file=loopbackCalibrationFile(job.identity); + const bool written=file.getParentDirectory().createDirectory().wasOk() && + file.replaceWithText(juce::JSON::toString(saved,true)); + finish("MEASURED_LOOPBACK",written ? + "Saved for these ASIO pins · FX excluded" : "Measured · calibration file could not be saved",saved); + } catch (const std::exception&) { + finish("UNKNOWN","Could not analyse the wired return."); + } + } + juce::var currentDeviceSnapshot() { // This readback is used for UI and ACK, never to claim that a staged @@ -2152,6 +2386,23 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto live=engine_.status(); o->setProperty("deviceGeneration",live.getProperty("deviceGeneration",0)); o->setProperty("mainOutputs",live.getProperty("dryRoutingLab",{}).getProperty("mainOutputs",{})); + // DAW-style AUDIO SETUP telemetry: JUCE's driver-provided input/output + // latency hints in SAMPLES, plus the host's current admitted DSP delay. + // The WebView must never present an untrusted draft as measured audio. + const bool latencyReady = device != nullptr && device->isOpen() && + engine_.directRouteAuthorized(); + o->setProperty("driverInputLatencyFrames",latencyReady + ? live.getProperty("driverReportedInputLatencyFrames",{}) : juce::var()); + o->setProperty("driverOutputLatencyFrames",latencyReady + ? live.getProperty("driverReportedOutputLatencyFrames",{}) : juce::var()); + o->setProperty("hostFxLatencyFrames",latencyReady + ? live.getProperty("latencySamples",{}) : juce::var()); + o->setProperty("latencyClockScope", + bool (live.getProperty("adaptiveClockActive",false)) + ? "INDEPENDENT_CLOCKS_NO_DIRECT_ROUNDTRIP_ESTIMATE" + : "SINGLE_CLOCK_DRIVER_HINTS"); + o->setProperty("latencyProvenance", + "JUCE_DRIVER_REPORTED_NOT_MEASURED_LOOPBACK_OR_ASIO_RTL"); juce::Array inputNames,outputNames,inputPins,outputPins,rates,buffers; if(device!=nullptr&&device->isOpen()) { const auto inputs=device->getInputChannelNames(); @@ -2174,6 +2425,16 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr o->setProperty("outputNames",juce::var(outputNames)); o->setProperty("enabledInputs",juce::var(inputPins)); o->setProperty("enabledOutputs",juce::var(outputPins)); + if (const auto loopback=engine_.inspectLoopback()) { + juce::Array capture,playback; + for (const auto pin : loopback->inputs) capture.add(pin); + for (const auto pin : loopback->outputs) playback.add(pin); + auto probe=std::make_unique(); + probe->setProperty("inputs",juce::var(capture)); + probe->setProperty("outputs",juce::var(playback)); + probe->setProperty("deviceEpoch",static_cast(loopback->epoch)); + o->setProperty("physicalLoopback",juce::var(probe.release())); + } o->setProperty("rates",juce::var(rates)); o->setProperty("buffers",juce::var(buffers)); return juce::var(o.release()); @@ -4235,6 +4496,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr void onAction (const juce::var& args) { auto action = args.getProperty ("action", {}).toString(); + if (action=="audioLoopbackRead" || action=="audioLoopbackMeasure") { + if (!deviceApply_.busy()) + requestPhysicalLoopback(args,action=="audioLoopbackMeasure"); + return; + } + if (action=="audioLoopbackCancel") + return cancelPhysicalLoopback(); + if (action!="audioDeviceInventory" && action!="copyDiagnosticReport") + cancelPhysicalLoopback(); if(deviceApply_.busy() && action!="audioDeviceApply")return; const auto value = args.getProperty ("value", {}); const int slot = static_cast (args.getProperty ("slot", -1)); @@ -7607,6 +7877,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } #endif if(deviceApply_.busy())return; // a vendor modal loop may re-enter JUCE + servicePhysicalLoopback(); // Always disabled unless the user explicitly starts a bounded trace. const bool timing = guiPerf_.active; const double tickStart = timing ? juce::Time::getMillisecondCounterHiRes() : 0.0; @@ -7638,15 +7909,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Existing message-thread 12 Hz timer: no extra worker or DSP work. // Never allow a hidden broken GUI to continue unattended audio. if (!browser_.loaded && !webViewStartupNoticeSent_ && - juce::Time::getMillisecondCounter() - webViewStartupTick_ > 10000u) + juce::Time::getMillisecondCounter() - webViewStartupTick_ > 25000u) { webViewStartupNoticeSent_ = true; diagnostics_.record ("WEBVIEW2_GUI_READY_TIMEOUT", "No native ArSonMix UI handshake"); engine_.stop(); if (onStartupStage_) onStartupStage_ (3); // dismiss splash before error dialog if (!updaterProbeMode_) - showWebViewStartupError ("The embedded mixer did not initialize in 10 seconds." + showWebViewStartupError ("The embedded mixer did not initialize in 25 seconds." " Check the WebView2 Runtime and browser-cache folder permissions."); + else + writeStartupDiagnostic("WEBVIEW_GUI_READY_TIMEOUT"); return; } // Health probes verify WebView/native readiness without opening any @@ -7819,8 +8092,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (timerTicks_ % 12 == 0 && !browser_.loaded) { const auto health = engine_.status(); - crackleEvidence_.push (makeEvidenceSample (health)); - diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (health, false)); + const auto evidence=makeEvidenceSample (health); + crackleEvidence_.push (evidence); + diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (makeAudioHealthRecord (health,evidence.memory), true)); } if (deviceSettingsDirty_) @@ -8015,8 +8289,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Preserve real device/hotplug/First Sound evidence and the async writer. if (timerTicks_ % 12 == 0) { - crackleEvidence_.push (makeEvidenceSample (state)); - diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (state, false)); + const auto evidence=makeEvidenceSample (state); + crackleEvidence_.push (evidence); + diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (makeAudioHealthRecord (state,evidence.memory), true)); } // Guard borrowed VST parameter pointers when a native graph edit, // device epoch change or Show recall retires the instance. @@ -8201,10 +8476,11 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer return; } startupAttempted_ = true; + writeStartupDiagnostic("WEBVIEW_PROFILE_PREFLIGHT"); // Remain active only as a lightweight update handshake (4 Hz). // Do not touch audio-device selection, callback, or GUI geometry. startTimer (250); - const auto folder = armix::storage::PortableWorkspace::browserDataRoot(); + const auto folder = webViewProfile(); if (!folder.createDirectory().wasOk() && !folder.isDirectory()) { splash_.reset(); @@ -8230,11 +8506,13 @@ class ConsoleApp final : public juce::JUCEApplication, private juce::Timer showWebViewStartupError ("The native browser backend could not be initialized on this machine."); return; } + writeStartupDiagnostic("WEBVIEW_AWAITING_GUI_READY"); window_ = std::make_unique ([this] (int stage) { if (splash_) splash_->setStage (stage); if (stage >= 2) { + if (stage==2) writeStartupDiagnostic("GUI_READY"); splash_.reset(); // no overlay over live mixer after engine init #if defined(_WIN32) // A real JUCE/WebView ready acknowledgement, not simply diff --git a/tests/approved_device_pin_identity_contract.test.cjs b/tests/approved_device_pin_identity_contract.test.cjs index bb7af4d71..0aa120b5c 100644 --- a/tests/approved_device_pin_identity_contract.test.cjs +++ b/tests/approved_device_pin_identity_contract.test.cjs @@ -539,3 +539,40 @@ test("MV-12 approved bridge invalidates transient UI leases, not durable JUCE st readback.indexOf("appearanceFromNative(next)"), "stale cosmetic ACK cannot settle before device identity fence"); }); + + +test("P0 approved Audio I/O latency shows real driver frames, never a fake loopback",()=>{ + const active={open:true,backend:"ASIO",rate:48000,buffer:256, + driverInputLatencyFrames:240,driverOutputLatencyFrames:360, + hostFxLatencyFrames:96,latencyClockScope:"SINGLE_CLOCK_DRIVER_HINTS", + latencyProvenance:"JUCE_DRIVER_REPORTED_NOT_MEASURED_LOOPBACK_OR_ASIO_RTL"}; + const ready=vm.setupLatencyReadback(active); + assert.equal(ready.ready,true); + assert.equal(ready.line,"Input 5.00 ms · Output 7.50 ms · Buffer 5.33 ms · FX/PDC 2.00 ms"); + assert.equal(ready.driverIoHintMs,12.5); + assert.equal(ready.estimatedTotalMs,14.5); + assert.match(ready.note,/Estimated total I\/O 14.50 ms/); + assert.equal(vm.setupLatencyReadback({...active,authorized:false}).ready,false); + assert.equal(vm.setupLatencyReadback({...active,hostFxLatencyFrames:null}).estimatedTotalMs,null); + assert.equal(vm.setupLatencyReadback({...active,rate:44100,driverInputLatencyFrames:1, + driverOutputLatencyFrames:1,hostFxLatencyFrames:1}).estimatedTotalMs,3000/44100); + assert.equal(vm.setupLatencyReadback({...active,rate:0}).ready,false); + const missing=vm.setupLatencyReadback({...active,driverInputLatencyFrames:null}); + assert.equal(missing.inputMs,null); + assert.equal(missing.driverIoHintMs,null); + assert.match(missing.line,/Input N\/A/); + const separate=vm.setupLatencyReadback({...active, + latencyClockScope:"INDEPENDENT_CLOCKS_NO_DIRECT_ROUNDTRIP_ESTIMATE"}); + assert.equal(separate.driverIoHintMs,null); + assert.equal(separate.estimatedTotalMs,null); + assert.equal(vm.setupLatencyReadback({...active,driverOutputLatencyFrames:-1}).outputMs,null); + assert.equal(vm.setupLatencyReadback({...active,driverInputLatencyFrames:0}).inputMs,0); + const bridge=readFileSync("web/approved-native-bridge.js","utf8"); + assert.match(bridge,/data-audio-latency/); + assert.match(bridge,/deviceVM\.setupLatencyReadback\(active\)/); + assert.match(bridge,/Electrical round-trip requires physical loopback calibration/); + const host=readFileSync("src/Main.cpp","utf8"); + for(const key of ["driverInputLatencyFrames","driverOutputLatencyFrames", + "hostFxLatencyFrames","latencyClockScope","latencyProvenance"]) + assert.ok(host.includes("setProperty(\""+key+"\"")); +}); diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index 0cbec11dc..0d98c35de 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -155,7 +155,8 @@ def emit_device_readback(actual, epoch): io_inventory['active']=out_active emit(page,'arMixAudioDeviceInventory',io_inventory) assert capture_select.input_value()=='' # reopening does not auto-patch a mic - page.locator('.armix-audio-dialog details summary').click() + page.locator('.armix-audio-dialog summary', + has_text='Advanced · rate, buffer and channel pins').click() assign_main=page.locator('[data-audio-main-pins]') def playback_pin(index): return page.locator(f'[data-audio-pin="output"][data-pin-index="{index}"]') @@ -179,6 +180,42 @@ def playback_pin(index): assert progress.is_visible() and apply.is_disabled() emit_device_readback(main_active,'71') assert page.locator('.armix-audio-shade').is_hidden() + # Optional calibration is a native request with an explicit + # consent boundary. Browser fixtures never emit real PCM. + page.locator('.command-bar [data-native-io]').click() + asio='Studio ASIO' + emit(page,'arMixAudioDeviceInventory',{ + 'types':[dict(name='ASIO',separate=False,inputs=[asio],outputs=[asio])], + 'active':dict(backend='ASIO',captureDevice=asio,playbackDevice=asio, + open=True,authorized=True,deviceGeneration=71, + inputNames=['Mic','Spare line 2'],outputNames=['Line left','Line right'], + enabledInputs=[0,1],enabledOutputs=[0,1],rates=[48000],buffers=[256], + rate=48000,buffer=256,driverInputLatencyFrames=240, + driverOutputLatencyFrames=360,hostFxLatencyFrames=96, + latencyClockScope='SINGLE_CLOCK_DRIVER_HINTS', + physicalLoopback=dict(deviceEpoch=71,inputs=[1],outputs=[0,1])), + }) + latency=page.locator('[data-audio-latency]') + assert 'Estimated total I/O 14.50 ms' in latency.inner_text() + details=page.locator('[data-audio-loopback-details]') + details.locator('summary').click() + measure=page.locator('[data-audio-loopback-start]') + assert measure.is_disabled() + assert page.evaluate("""()=>window.__events.every(e=> + e.payload?.action!=='audioLoopbackMeasure')""") + page.locator('[data-audio-loopback-output]').select_option('1') + page.locator('[data-audio-loopback-confirmed]').check() + measure.click() + measured=page.evaluate("""()=>window.__events.filter(e=> + e.payload?.action==='audioLoopbackMeasure').at(-1)?.payload""") + assert measured['wiredLineLevel'] is True + assert (measured['deviceEpoch'],measured['inputPin'],measured['outputPin'])==(71,1,1) + emit(page,'arMixPhysicalLoopback',dict(requestId=measured['requestId'], + state='MEASURED_LOOPBACK',result=dict(rate=48000,frames=720,confidence=0.98))) + assert 'Measured wired round-trip 15.00 ms' in page.locator( + '[data-audio-loopback-result]').inner_text() + assert measure.is_disabled() + page.locator('[data-audio-close]').click() g0=json.loads((ROOT/'integration/console-v6/fixtures.json').read_text())['g0'] g0['device']['epoch']='72' g0['mixerSession']={'authority':'NONE','deviceEpoch':g0['device']['epoch'],'channels':[]} diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index 5f7d97c9f..a59b8202d 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -110,8 +110,13 @@ test('ASIO/WASAPI DIRECT authorizes the exact active input/output channel map',( const fence=read('engine/device/DirectRouteFence.h'); // Bind BOTH untruncated JUCE BigInteger masks at startup, manual selection, // and verified DIRECT restore, rather than only the friendly device name. - assert.equal(engine.split('getActiveInputChannels().toString (16)').length-1,3); - assert.equal(engine.split('getActiveOutputChannels().toString (16)').length-1,3); + // INT-1B reads the same two untruncated masks once more on CONTROL + // for evidence-only status. Retain ALL three exact direct-fence checks + // below: telemetry is not authorization to arm a different device. + assert.equal(engine.split('getActiveInputChannels().toString (16)').length-1,4); + assert.equal(engine.split('getActiveOutputChannels().toString (16)').length-1,4); + assert.match(engine, /setProperty \("activeInputMaskHex"/); + assert.match(engine, /setProperty \("activeOutputMaskHex"/); for (const operation of ['approve','resumeExpected','observeStart']) { // Match the verified native device/mask inputs independently of cosmetic // line wrapping introduced by the ASIO control-plane identity guard. diff --git a/tests/mixer_io_operator_contract_test.mjs b/tests/mixer_io_operator_contract_test.mjs index e6b87165f..cc4614830 100644 --- a/tests/mixer_io_operator_contract_test.mjs +++ b/tests/mixer_io_operator_contract_test.mjs @@ -721,3 +721,16 @@ test('M2b native AUDIO SETUP holds one lease through visible selection and rebin assert.match(cpp,/Purpose::explicitApply/); assert.doesNotMatch(setup,/\.closeAudioDevice\(/); }); + + +test('P0 Audio Setup reports native driver latency ms, never fake measured loopback',()=>{ + assert.match(main,/setProperty\("driverInputLatencyFrames",latencyReady/); + assert.match(main,/setProperty\("driverOutputLatencyFrames",latencyReady/); + assert.match(main,/setProperty\("hostFxLatencyFrames",latencyReady/); + assert.match(main,/JUCE_DRIVER_REPORTED_NOT_MEASURED_LOOPBACK_OR_ASIO_RTL/); + const bridge=read('web/approved-native-bridge.js'); + assert.match(bridge,/deviceVM\.setupLatencyReadback\(active\)/); + assert.match(bridge,/Input and output are driver-reported/); + assert.match(bridge,/action:measure\?"audioLoopbackMeasure":"audioLoopbackRead"/); + assert.match(main,/action=="audioLoopbackCancel"/); +}); diff --git a/tests/p0_diagnostic_contract_test.mjs b/tests/p0_diagnostic_contract_test.mjs index 9813362a5..b651157e8 100644 --- a/tests/p0_diagnostic_contract_test.mjs +++ b/tests/p0_diagnostic_contract_test.mjs @@ -52,9 +52,9 @@ test('P0 crackle marker records a bounded pre-event source-labeled evidence wind assert.match(host,/RENDER_HARDWARE_XRUN=UNAVAILABLE_THROUGH_JUCE/); // Stage B: connected WebView reuses the 12 Hz status sample for // health logging; an unready WebView still retains safety evidence at 1 Hz. - assert.match(host,/crackleEvidence_\.push \(makeEvidenceSample \(state\)\)/); + assert.match(host,/const auto evidence=makeEvidenceSample \(state\);\s*crackleEvidence_\.push \(evidence\)/); assert.match(host,/timerTicks_ % 12 == 0 && !browser_\.loaded/); - assert.match(host,/crackleEvidence_\.push \(makeEvidenceSample \(health\)\)/); + assert.match(host,/const auto evidence=makeEvidenceSample \(health\);\s*crackleEvidence_\.push \(evidence\)/); assert.doesNotMatch(host,/approvedNativeSnapshot \(health\)/); assert.match(host,/crackleEvidence_\.mark\s*\(\s*makeEvidenceSample\(status\)\s*\)/); assert.match(host,/AUDIO_GLITCH_MEMORY/); diff --git a/tests/physical_loopback_test.cpp b/tests/physical_loopback_test.cpp new file mode 100644 index 000000000..7ccc821b4 --- /dev/null +++ b/tests/physical_loopback_test.cpp @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/diagnostics/PhysicalLoopback.h" +#include +#include +#include + +using Probe = armix::diagnostics::PhysicalLoopback; +constexpr std::array mainPair {1, 2}; + +static void require(bool valid, const char* condition) +{ + if (!valid) { + std::cerr << condition << '\n'; + std::exit(1); + } +} + +static Probe::Capture capture(int rate,int block,int delay,bool echo=false) +{ + Probe probe; + require(probe.start(rate,block,1,2,2,3,42),"Calibrator admits valid device format"); + std::vector history(static_cast(rate)); + std::vector unused(block), input(block), left(block), right(block); + const float* inputs[] {unused.data(),input.data()}; + float* outputs[] {unused.data(),left.data(),right.data()}; + for (int begin=0;probe.state()==Probe::State::capturing;begin+=block) { + for (int f=0;f(((begin+f)*37)%31-15); + input[f]=0.001f+noise+(offset>=0?history[offset]*0.3f:0.0f); + if (echo && offset>=96) input[f]+=history[offset-96]*0.3f; + } + require(probe.captureInput(inputs,2,block),"Raw callback capture"); + // Emulate accepted graph writes on memory aliased with an input. + std::fill(input.begin(),input.end(),0.97f); + require(probe.emitProbe(outputs,3,block,42,true,mainPair),"Probe writes to accepted MAIN"); + for (int f=0;f pair,bool cancel) +{ + Probe probe; + float input[64]{},output[64]{}; + const float* inputs[]{input}; + float* outputs[]{output}; + require(probe.start(48000,64,0,0,1,1,42),"Start probe"); + if(cancel) probe.requestCancel(); + require(probe.captureInput(inputs,1,64),"Capture pending block"); + require(!probe.emitProbe(outputs,1,64,epoch,permitted,pair),"Probe must decline output"); + require(probe.state()==Probe::State::cancelled,"Probe cancels instead of resuming"); +} + +int main() +{ + for (const int rate : {44100,48000,96000}) { + for (const int block : {64,128,256,512}) { + const int frames=3*block+19; + const auto result=Probe::analyse(capture(rate,block,frames)); + require(!result.error && result.frames==frames && result.confidence>0.99, + "Known wired sample delay and confidence"); + } + } + auto pcm=capture(48000,128,459); + std::fill(pcm.received.begin(),pcm.received.end(),0.0f); + require(Probe::analyse(pcm).error,"Silence cannot pass as zero latency"); + for (std::size_t i=0;i((i*16127)%3989-1994.0); + require(Probe::analyse(pcm).error,"Clipped noise must fail"); + for (auto& sample : pcm.received) sample*=0.02f; + require(Probe::analyse(pcm).error,"Uncorrelated background noise must fail"); + require(Probe::analyse(capture(48000,128,459,true)).error,"Ambiguous doubled/feedback returns fail"); + rejectsUnauthorisedBlock(false,42,{0,-1},false); + rejectsUnauthorisedBlock(true,43,{0,-1},false); + rejectsUnauthorisedBlock(true,42,{1,-1},false); + rejectsUnauthorisedBlock(true,42,{0,-1},true); + std::cout << "Wired loopback matrix passed\n"; +} diff --git a/tests/smart_audio_diagnostic_contract_test.mjs b/tests/smart_audio_diagnostic_contract_test.mjs index 7865acd51..04ec4a763 100644 --- a/tests/smart_audio_diagnostic_contract_test.mjs +++ b/tests/smart_audio_diagnostic_contract_test.mjs @@ -2,6 +2,7 @@ // Permanent source contracts. CPU/FIFO functional correctness is independently // tested by Release-active native CTest, not source regexes alone. import test from 'node:test'; +import {analyzeHealthLog,compareDryFx,p95p99FromDelta,parseHealthLog,markdownReport,SCHEMA} from '../scripts/audio_reliability_profile.mjs'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; const read = p=>readFileSync(p,'utf8'); @@ -145,3 +146,257 @@ test('P0 capture block-head evidence is a single-pass RT heuristic, not invented assert.match(fixture,/100000/); assert.match(cmake,/add_test\(NAME P0CaptureZeroHeadBoundaryCandidates COMMAND ARMixCaptureBoundaryTests\)/); }); + + +// INT-1B: a real 1Hz log reader with deterministic native-source fixtures. +function int1bSample(second,{dryTest=true,deviceGeneration=2,device="ASIO Driver", + rate=48000,buffer=256,over=0,late=0,connected=true, + nativeGlobalFxBypassed=dryTest, + nativeFxProcessingCount=nativeGlobalFxBypassed?0:1, + nativeExternalCh1Leased=false, + nativeExternalCh1InstalledCount=0, + nativeExternalCh1ProcessingCount=0}={}) { + const cumulative=(second+1)*100; + const buckets=Array(13).fill(0); + buckets[3]=cumulative-over; + buckets[12]=over; + return {schema:SCHEMA,connected,liveBackendClass:"ASIO_DIRECT_ZERO_EXTRA_FIFO", + driver:"ASIO",device,inputDevice:"Interface Input",outputDevice:"Interface Output", + deviceInputChannels:2,deviceOutputChannels:2, + activeInputMaskHex:"3",activeOutputMaskHex:"3", + nativeFxGraphRevision:"100", + rate,buffer,periodUs:1000000*buffer/rate, + deviceGeneration,deviceStartCount:deviceGeneration,deviceStopCount:0, + diagnosticRoute:"NORMAL",productionRoutingState:"NATIVE_ROUTE_ACCEPTED", + directRouteAuthorized:true,dryTest, + nativeGlobalFxBypassed,nativeFxInstalledCount:1,nativeFxProcessingCount, + nativeFxActivityComplete:true, + nativeExternalCh1Leased,nativeExternalCh1InstalledCount, + nativeExternalCh1ProcessingCount, + callbackCount:cumulative, + callbackBudgetBuckets:buckets,overBudgetCount:over,slowCallbackCount:over, + lateCallbackIntervals:late,callbackGapCount:0, + callbackCadenceClockRegressions:0,backendXrunMeaning:"UNAVAILABLE", + renderUnderrunSource:"UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE"}; +} +function int1bLine(second,properties){ + return new Date(Date.UTC(2026,10,20,8,0,second)).toISOString()+ + ' | AUDIO_HEALTH | '+JSON.stringify(int1bSample(second,properties)); +} +test('INT-1B native log is bounded and uses one existing off-RT 1Hz snapshot',()=>{ + assert.match(engine,/callbackBudgetBuckets/); + assert.match(engine,/HOST_CALLBACK_BUDGET_CUMULATIVE_13_BUCKETS_NOT_DRIVER_RENDER_XRUN/); + assert.match(host,/arsonmix\.audio-health\.int1b\.v1/); + assert.match(engine,/nativeFxProcessingCount/); + assert.match(engine,/dryRoutingLab_\.globalFxBypassed\(\)/); + assert.match(host,/nativeFxInstalledCount/); + assert.match(engine,/originalCh1GraphLeased/); + assert.match(engine,/acceptedGraph->rackBypassed\.load/); + assert.match(engine,/acceptedGraph->bypassFlags\[physical\]\.load/); + assert.match(host,/nativeExternalCh1InstalledCount/); + assert.match(engine,/acceptedOriginalCh1ExternalLeaseForControl\(\)/); + assert.match(engine,/acceptedExternal->render == &processOwnedChannelOne/); + assert.match(engine,/nativeFxActivityComplete/); + assert.match(host,/nativeFxActivityComplete/); + assert.match(engine,/nativeFxGraphRevision/); + assert.match(engine,/activeInputMaskHex/); + assert.match(host,/makeAudioHealthRecord \(const juce::var& state,/); + assert.match(host,/juce::JSON::toString \(makeAudioHealthRecord \(health,evidence\.memory\), true\)/); + assert.match(host,/juce::JSON::toString \(makeAudioHealthRecord \(state,evidence\.memory\), true\)/); + assert.doesNotMatch(engine,/realtimeHistogram_\.reset\(/); + assert.ok(int1bLine(0,{dryTest:false}).length<4096, + 'single schema record fits existing rotating log queue'); +}); +test('INT-1B interval histogram is a 13-bin delta, not cumulative p99',()=>{ + const pct=p95p99FromDelta([0,0,0,950,0,0,0,0,0,0,0,0,50]); + assert.equal(pct.p95,8); + assert.equal(pct.p99,null); // over deadline, never fabricate 100% p99 + assert.equal(pct.samples,1000); + assert.equal(p95p99FromDelta(Array(13).fill(0)).p95,null); + assert.equal(p95p99FromDelta([1]).samples,0); +}); +test('INT-1B dry vs FX matched 60s evidence and no fabricated physical XRUN',()=>{ + const lines=[]; + for(let s=0;s<=60;s++)lines.push(int1bLine(s,{dryTest:true})); + // Separate 1Hz capture, same physical driver/port/rate/buffer but FX chain. + for(let s=61;s<=122;s++)lines.push(int1bLine(s,{ + dryTest:false,over:(s-61)*4,late:s-61 + })); + const report=analyzeHealthLog(lines.join('\n')); + assert.equal(report.totalSamples,123); + assert.equal(report.segments.length,2); + assert.equal(report.segments[0].durationSeconds,60); + assert.equal(report.segments[0].p99BudgetUpperPct,8); + assert.equal(report.segments[0].overBudgetCallbacks,0); + assert.equal(report.segments[1].p99BudgetUpperPct,null); + assert.equal(report.segments[1].overBudgetPer1000,40); + assert.equal(report.segments[0].nativeGlobalFxBypassed,true); + assert.equal(report.segments[0].nativeFxProcessingCount,0); + assert.equal(report.segments[1].nativeFxProcessingCount,1); + assert.equal(report.segments[1].diagnosis, + 'BOTH_DSP_BUDGET_AND_SCHEDULING_INDICATORS'); + assert.equal(report.segments[1].renderHardwareXrun, + 'UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE'); + const compared=compareDryFx(report); + assert.equal(compared.comparable,true); + assert.equal(compared.deltaOverBudgetPer1000,40); + assert.match(markdownReport(report),/not physical render-XRUN/i); +}); +test('INT-1B refuses device mismatches, resets, gaps, malformed and legacy logs',()=>{ + const legacy='2026-11-20T08:00:00.000Z | AUDIO_HEALTH | {"callbackCount":99}'; + const malformed='2026-11-20T08:00:00.000Z | AUDIO_HEALTH | {"bad":'; + const badLog=[legacy,malformed,int1bLine(0,{}),int1bLine(1,{}), + int1bLine(7,{deviceGeneration:3}),int1bLine(8,{deviceGeneration:3}), + int1bLine(9,{deviceGeneration:2})].join('\n'); + const parsed=parseHealthLog(badLog); + assert.equal(parsed.samples.length,5); + assert.equal(parsed.warnings.length,2); + const analysis=analyzeHealthLog(badLog); + assert.equal(analysis.segments.length,3); + assert.equal(compareDryFx(analysis).comparable,false); + assert.ok(analysis.warnings.some(w=>w.includes('device/graph/epoch'))); + // An interval with a counter going backwards is NOT negative optimization. + const previous=int1bSample(20,{}); + const invalid={...int1bSample(21,{}),callbackCount:1}; + const time=s=>new Date(Date.UTC(2026,10,20,8,0,s)).toISOString(); + const report=analyzeHealthLog( + time(20)+' | AUDIO_HEALTH | '+JSON.stringify(previous)+'\n'+ + time(21)+' | AUDIO_HEALTH | '+JSON.stringify(invalid)); + assert.equal(report.segments.length,2); + const swapped={...int1bSample(21,{}),inputDevice:"Other Driver Input"}; + const mismatch=analyzeHealthLog( + time(20)+' | AUDIO_HEALTH | '+JSON.stringify(previous)+'\n'+ + time(21)+' | AUDIO_HEALTH | '+JSON.stringify(swapped)); + assert.equal(mismatch.segments.length,2, + 'Physical input endpoint change disqualifies the previous timing window'); + const changedPins=analyzeHealthLog( + time(20)+' | AUDIO_HEALTH | '+JSON.stringify(previous)+'\n'+ + time(21)+' | AUDIO_HEALTH | '+ + JSON.stringify({...int1bSample(21,{}),activeInputMaskHex:"c"})); + assert.equal(changedPins.segments.length,2, + 'The same ASIO channel count can hide changed hardware pin ordinals'); + const missing=analyzeHealthLog( + time(20)+' | AUDIO_HEALTH | '+JSON.stringify(previous)+'\n'+ + time(20)+' | AUDIO_HEALTH | null'+'\n'+ + time(21)+' | AUDIO_HEALTH | '+JSON.stringify(int1bSample(21,{}))); + assert.equal(missing.segments.length,2, + 'A malformed/unknown middle snapshot is a hard gap, not a green interval'); + const changedGeneration=[]; + for(let s=0;s<=40;s++)changedGeneration.push(int1bLine(s,{dryTest:true})); + for(let s=41;s<=82;s++)changedGeneration.push(int1bLine(s,{ + dryTest:false,deviceGeneration:3 + })); + assert.equal(compareDryFx(analyzeHealthLog(changedGeneration.join('\n'))).comparable,false, + 'Same-named driver reopened in a new generation is not a matched DRY/FX pair'); +}); +test('INT-1B ignores legacy dryTest visual intent when native FX still processes',()=>{ + const lines=[]; + for(let s=0;s<=40;s++)lines.push(int1bLine(s,{ + dryTest:true,nativeGlobalFxBypassed:false,nativeFxProcessingCount:1 + })); + const result=analyzeHealthLog(lines.join('\n')); + assert.equal(result.segments.length,1); + assert.equal(result.segments[0].mode,'FX', + 'The only DRY proof is actual native DSP bypass/insert readback'); + assert.equal(compareDryFx(result).comparable,false); +}); + +test('INT-1B never pairs another app session or a stale DRY baseline',()=>{ + const makeWindow=(start,end,dryTest)=>Array.from( + {length:end-start+1},(_,i)=>int1bLine(start+i,{dryTest})); + const sessionHeader=new Date(Date.UTC(2026,10,20,8,0,40)).toISOString()+ + ' | SESSION | started'; + const differentApp=analyzeHealthLog([ + ...makeWindow(0,40,true),sessionHeader,...makeWindow(41,81,false) + ].join('\n')); + assert.equal(differentApp.segments.length,2); + assert.equal(compareDryFx(differentApp).comparable,false, + 'the same generation on a new process is not comparable'); + const stale=analyzeHealthLog([ + ...makeWindow(0,40,true),...makeWindow(200,240,false) + ].join('\n')); + assert.equal(compareDryFx(stale).comparable,false, + 'a session gap must not silently pair different performances'); + const intervening=analyzeHealthLog([ + ...makeWindow(0,40,true),...makeWindow(41,81,false), + ...makeWindow(82,122,true) + ].join('\n')); + assert.equal(compareDryFx(intervening).comparable,true, + 'a complete adjacent dry then fx pair remains valid even with a later DRY run'); +}); + +test('INT-1B external-only CH1 vendor rack is FX when powered and DRY when bypassed',()=>{ + const lines=[]; + for(let s=0;s<=40;s++)lines.push(int1bLine(s,{ + dryTest:false,nativeGlobalFxBypassed:true,nativeFxProcessingCount:0, + nativeExternalCh1Leased:true,nativeExternalCh1InstalledCount:1, + nativeExternalCh1ProcessingCount:0 + })); + for(let s=41;s<=81;s++)lines.push(int1bLine(s,{ + dryTest:false,nativeGlobalFxBypassed:false,nativeFxProcessingCount:1, + nativeExternalCh1Leased:true,nativeExternalCh1InstalledCount:1, + nativeExternalCh1ProcessingCount:1 + })); + const report=analyzeHealthLog(lines.join('\n')); + assert.deepEqual(report.segments.map(s=>s.mode),['DRY','FX']); + assert.equal(report.segments[0].nativeExternalCh1InstalledCount,1); + assert.equal(report.segments[1].nativeExternalCh1ProcessingCount,1); + assert.equal(compareDryFx(report).comparable,true, + 'External-only original CH1 Graph is not silently omitted from native FX'); + const malformed=lines.slice(); + malformed[50]=malformed[50].replace('"nativeExternalCh1ProcessingCount":1', + '"nativeExternalCh1ProcessingCount":2'); + assert.ok(analyzeHealthLog(malformed.join('\n')).warnings.some(s=>s.includes('invalid source metadata')), + 'External count cannot exceed the accepted authoritative total'); +}); + +test('INT-1B P2: no DRY/FX match through malformed or opaque-lease telemetry',()=>{ + const dry=[],fx=[]; + for(let s=0;s<=40;s++)dry.push(int1bLine(s,{dryTest:true})); + for(let s=41;s<=82;s++)fx.push(int1bLine(s,{dryTest:false})); + const baseline=analyzeHealthLog([...dry,...fx].join('\n')); + assert.equal(compareDryFx(baseline).comparable,true, + 'An accepted global bypass ON -> OFF transition is allowed'); + assert.equal(baseline.segments[1].invalidBefore,false); + + const midpoint='2026-11-20T08:00:40.500Z | AUDIO_HEALTH | {"invalid":'; + const malformed=analyzeHealthLog([...dry,midpoint,...fx].join('\n')); + assert.equal(malformed.segments.length,2); + assert.equal(malformed.segments[1].invalidBefore,true); + assert.equal(compareDryFx(malformed).comparable,false, + 'Malformed source between two valid 40s windows must invalidate pairing'); + + const opaque={...int1bSample(41,{dryTest:false}),nativeFxActivityComplete:false}; + const rejected='2026-11-20T08:00:41.000Z | AUDIO_HEALTH | '+JSON.stringify(opaque); + const incomplete=analyzeHealthLog([...dry,rejected,...fx.slice(1)].join('\n')); + assert.equal(incomplete.segments.length,2); + assert.equal(incomplete.segments[1].invalidBefore,true); + assert.equal(compareDryFx(incomplete).comparable,false, + 'Rejected opaque external CH1 FX lease is a hard comparability barrier'); + + const regressed={...int1bSample(41,{dryTest:false}),callbackCount:1}; + const counterReset=analyzeHealthLog([...dry, + '2026-11-20T08:00:41.000Z | AUDIO_HEALTH | '+JSON.stringify(regressed), + ...fx.slice(1)].join('\n')); + assert.equal(compareDryFx(counterReset).comparable,false, + 'Counter regression during mode transition must not be a valid pair'); + + const unprovenDry=[],unprovenFx=[]; + for(let s=0;s<=40;s++)unprovenDry.push(int1bLine(s,{ + dryTest:true,nativeGlobalFxBypassed:false,nativeFxProcessingCount:0 + })); + for(let s=41;s<=82;s++)unprovenFx.push(int1bLine(s,{dryTest:false})); + assert.equal(compareDryFx(analyzeHealthLog( + [...unprovenDry,...unprovenFx].join('\n'))).comparable,false, + 'Global power OFF -> OFF is not a verified global FX bypass transition'); +}); + +test('INT-1B rejects missed/unknown data rather than counting missing as zero',()=>{ + const s=int1bSample(1,{}); + delete s.callbackBudgetBuckets; + const p=parseHealthLog( + new Date(Date.UTC(2026,10,20,8,0,1)).toISOString()+ + ' | AUDIO_HEALTH | '+JSON.stringify(s)); + assert.equal(p.samples.length,0); + assert.match(p.warnings[0],/missing\/invalid 13/); +}); diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 2d8bcb195..90157d5c9 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -33,7 +33,7 @@ test('per-user Inno Setup upgrades the same app and retains private Studio data' assert.match(iss, /Source: "\.\.\\docs\\THIRD_PARTY_8D_SONKU_HRTF\.md"; Flags: dontcopy/); }); -test('official standard VB-CABLE ZIP is pinned and checked automatically without elevating ArSonMix', () => { +test('optional signed VB-CABLE driver does not block clean Windows 10 first launch', () => { const m = JSON.parse(read('config/vbcable-official-package.json')); const pack = read('scripts/prepare_vbcable_package.ps1'); const bootstrap = read('installer/ArSonMixVBCableInstall.ps1'); @@ -43,12 +43,18 @@ test('official standard VB-CABLE ZIP is pinned and checked automatically without assert.match(m.sha256, /^[a-f0-9]{64}$/); assert.match(m.proof, /actions\/runs\/43079930924/); assert.match(iss, /^PrivilegesRequired=lowest$/m); - assert.doesNotMatch(iss, /^\[Tasks\]$|Tasks: vbcable_driver/m); + assert.match(iss, /^\[Tasks\]$/m); + assert.match(iss, /Name: "installvbcable_driver";[^\n]*Flags: unchecked/); + assert.equal((iss.match(/Name: "installvbcable_driver"/g) || []).length, 1); assert.match(iss, /VBCABLE_Driver_Pack45\.zip/); assert.match(iss, /ArSonMixVBCableInstall\.ps1/); const run = iss.slice(iss.indexOf('[Run]'), iss.indexOf('[Code]')); - assert.match(run, /StatusMsg: "Checking VB-Audio VB-CABLE[^"]*"; Flags: runasoriginaluser skipifsilent waituntilterminated runhidden/); + assert.match(run, /StatusMsg: "Installing OPTIONAL VB-CABLE[^"]*"; Tasks: installvbcable_driver; Flags: runasoriginaluser skipifsilent waituntilterminated runhidden/); assert.ok(run.indexOf('ArSonMixVBCableInstall.ps1') < run.indexOf('Filename: "{app}\\ArSonMix.exe"')); + const vendorRunLine=run.split('\n').find(s=>s.includes('ArSonMixVBCableInstall.ps1')); + assert.ok(vendorRunLine,'optional vendor installer remains available'); + assert.match(vendorRunLine,/Tasks: installvbcable_driver/); + assert.equal((run.match(/Tasks: installvbcable_driver/g)||[]).length,1); assert.match(iss, /Check: CanLaunchMixer/); assert.match(iss, /function NeedRestart\(\): Boolean;[\s\S]*?FileExists/); assert.match(bootstrap, /if\(\$stateName -eq 'PENDING_REBOOT'\)\{[\s\S]*?New-Item -ItemType File -Path \$RestartMarker/); @@ -479,3 +485,25 @@ test('updater rechecks both verified installer binaries before execution and rol assert.match(script, /if\(-not \(Test-StagedAsset \$oldPath \$oldAsset\)\)/); assert.match(script, /INSTALLER_BYTES_CHANGED_UPDATE_DEFERRED/); }); + + +test('P0 Windows 10 fresh install needs no VC redistributable and reports missing WebView2',()=>{ + const cmake=read('CMakeLists.txt'),native=read('src/Main.cpp'); + assert.match(cmake,/if \(MSVC AND WIN32 AND NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY\)/); + assert.match(cmake,/set\(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded\$<\$:Debug>"\)/); + assert.ok(cmake.indexOf('set(CMAKE_MSVC_RUNTIME_LIBRARY')< + cmake.indexOf('add_subdirectory("${JUCE_ROOT}"'), + 'static CRT must apply to JUCE and app as one ABI'); + assert.match(native,/Download \/ Repair WebView2/); + assert.match(native,/developer\.microsoft\.com\/en-us\/microsoft-edge\/webview2/); + assert.match(native,/if \(result == 0\)/); + assert.match(iss,/Flags: unchecked/); + const packaged=read('scripts/build_verify_windows_installer.ps1'); + const pe=read('scripts/verify_win10_pe_runtime.py'); + assert.match(packaged,/verify_win10_pe_runtime\.py --exe \$exe/); + assert.match(pe,/WIN10_STATIC_CRT_PE_PASS/); + assert.match(pe,/delay-import descriptors|delay-import|Delay-load descriptors/i); + assert.match(pe,/vcruntime/); + assert.match(pe,/msvcp/); + assert.match(pe,/WEBVIEW2_RUNTIME_REQUIRED_SEPARATELY_NOT_PROVEN/); +}); diff --git a/web/approved-device-view-model.js b/web/approved-device-view-model.js index d2068c015..fc30280c5 100644 --- a/web/approved-device-view-model.js +++ b/web/approved-device-view-model.js @@ -124,6 +124,34 @@ outputPins:Array.isArray(active.enabledOutputs)?active.enabledOutputs.slice():null, rate:0,buffer:0}; } + // DAW-style read-only latency from the ACTUAL active JUCE device. + // Driver input/output hints are not an electrical loopback measurement. + // Unavailable or independently clocked paths are NEVER converted to 0 ms. + function setupLatencyReadback(active) { + const rate=Number(active?.rate); + if(active?.open!==true || active.authorized===false || !Number.isFinite(rate)||rate<=0) + return Object.freeze({ready:false}); + const frames=value=>Number.isSafeInteger(value)&&value>=0?value:null; + const input=frames(active.driverInputLatencyFrames); + const output=frames(active.driverOutputLatencyFrames); + const fx=frames(active.hostFxLatencyFrames); + const buffer=frames(active.buffer); + const sameClock=active.latencyClockScope==="SINGLE_CLOCK_DRIVER_HINTS"; + const driverIo=sameClock&&input!==null&&output!==null?input+output:null; + // Driver I/O reports may already include buffering. The callback period + // is a separate metric, not an extra term in the estimate. + const total=driverIo!==null&&fx!==null?driverIo+fx:null; + const ms=value=>value===null?null:1000*value/rate; + const fmt=value=>value===null?"N/A":ms(value).toFixed(2)+" ms"; + return Object.freeze({ + ready:true,inputMs:ms(input),outputMs:ms(output),fxMs:ms(fx),bufferMs:ms(buffer), + estimatedTotalMs:ms(total),driverIoHintMs:ms(driverIo), + line:"Input "+fmt(input)+" · Output "+fmt(output)+ + " · Buffer "+fmt(buffer)+" · FX/PDC "+fmt(fx), + note:"Estimated total I/O "+fmt(total)+" · JUCE driver + host FX/PDC", + provenance:active.latencyProvenance||"UNKNOWN" + }); + } function setupPresentation(inventory,draft,state=setupInitial()) { const active=inventory?.active||{},types=inventory?.types||[]; const type=types.find(t=>t?.name===draft?.backend); @@ -423,7 +451,7 @@ return Object.freeze({kind:"SAME",expirePending:false}); } return Object.freeze({activeInputPins,inputChoices,inputLabel,outputChoices, - externalPresentation,setupDraft,setupPresentation,setupEditDraft, + externalPresentation,setupDraft,setupPresentation,setupLatencyReadback,setupEditDraft, setupInitial,setupBegin,setupAck,setupReadback, setupTimeout,setupClearResult,nativeLifecycleLease,nativeLifecycleDecision, nativeTransientReadbackPolicy}); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 930bb8c00..4620e538c 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2075,6 +2075,55 @@ window.clearTimeout(toastTimer); toastTimer=window.setTimeout(()=>{element.hidden=true;},3400); } + let loopbackSerial=0,loopbackId="",loopbackPending=false; + const loopbackField=name=>devicePanel?.querySelector("[data-audio-loopback-"+name+"]"); + function closeNativeAudioIO(){ + if(deviceBusy())return; + if(loopbackPending)backend.emitEvent("arMixAction",{action:"audioLoopbackCancel"}); + loopbackId=""; + loopbackPending=false; + loopbackField("confirmed").checked=false; + for(const side of ["input","output"])loopbackField(side).disabled=false; + devicePanel.hidden=true; + } + function requestLoopback(measure){ + const scope=deviceInventory?.active?.physicalLoopback; + if(!scope||deviceBusy()||loopbackPending)return; + const input=loopbackField("input"),output=loopbackField("output"); + const wired=loopbackField("confirmed"); + if(input.value===""||output.value===""||(measure&&!wired.checked))return; + loopbackId="audio-loopback-"+(++loopbackSerial); + loopbackPending=measure; + const start=loopbackField("start"); + start.disabled=measure||!wired.checked; + loopbackField("result").textContent=measure?"Starting wired measurement…":""; + backend.emitEvent("arMixAction",{ + action:measure?"audioLoopbackMeasure":"audioLoopbackRead", + requestId:loopbackId,deviceEpoch:scope.deviceEpoch, + inputPin:Number(input.value),outputPin:Number(output.value),wiredLineLevel:wired.checked + }); + } + function renderLoopbackPins(active){ + const details=loopbackField("details"); + if(!details)return; + const scope=active?.physicalLoopback; + details.hidden=!scope; + if(!scope)return; + for(const [side,values,names] of [ + ["input",scope.inputs,active.inputNames],["output",scope.outputs,active.outputNames]]){ + const select=loopbackField(side),prior=select.value; + select.replaceChildren(); + for(const pin of values){ + const option=document.createElement("option"); + option.value=String(pin); + option.textContent=String(names?.[pin]||("Pin "+(pin+1))); + select.append(option); + } + if(values.some(pin=>String(pin)===prior))select.value=prior; + } + loopbackField("start").disabled=deviceBusy()||loopbackPending|| + !loopbackField("confirmed").checked; + } function openNativeAudioIO(){ if(!devicePanel){ const style=document.createElement("style"); @@ -2105,6 +2154,9 @@ .armix-device-progress span{display:block;margin-top:2px;color:#f2e0bf} .armix-audio-dialog details{border-top:1px solid #345666;padding-top:8px} .armix-audio-dialog summary{cursor:pointer;color:#c5e1ed} + .armix-loopback-pins{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:8px 0} + .armix-audio-dialog .armix-loopback-confirm{display:flex;align-items:flex-start;gap:6px;margin:8px 0} + .armix-loopback-result{margin-top:6px} .armix-audio-dialog{max-height:90vh;overflow:auto} .armix-output-overview{border-top:1px solid #345666;padding-top:8px} .armix-output-heading{color:#c5e1ed;font-weight:500} @@ -2137,6 +2189,22 @@
Reading current audio device…
+
+ Latency · waiting for native device readback +
+ `; - devicePanel.querySelector("[data-audio-close]").onclick=()=>{ - if(!deviceBusy())devicePanel.hidden=true; - }; + devicePanel.querySelector("[data-audio-close]").onclick=closeNativeAudioIO; devicePanel.addEventListener("click",e=>{ - if(e.target===devicePanel&&!deviceBusy())devicePanel.hidden=true; + if(e.target===devicePanel)closeNativeAudioIO(); }); + loopbackField("start").onclick=()=>requestLoopback(true); + loopbackField("confirmed").onchange=e=>{ + if(!e.target.checked&&loopbackPending) + backend.emitEvent("arMixAction",{action:"audioLoopbackCancel"}); + loopbackField("start").disabled=!e.target.checked||loopbackPending; + }; + for(const side of ["input","output"]) + loopbackField(side).onchange=()=>{ + loopbackField("confirmed").checked=false; + loopbackField("start").disabled=true; + requestLoopback(false); + }; devicePanel.addEventListener("change",e=>{ if(deviceBusy()||!deviceChoice||!deviceInventory)return; const side=e.target.dataset.audioPin; @@ -2286,6 +2364,15 @@ } const activeText=devicePanel.querySelector("[data-audio-active]"); if(activeText&&!deviceBusy())activeText.textContent=view.activeText; + const latencyText=devicePanel.querySelector("[data-audio-latency]"); + if(latencyText){ + const latency=deviceVM.setupLatencyReadback(active); + latencyText.textContent=latency.ready? + latency.line+" · "+latency.note: + "AUDIO LATENCY · select an active device to read driver estimates"; + latencyText.title="Input and output are driver-reported. Buffer period is shown separately. Electrical round-trip requires physical loopback calibration."; + } + renderLoopbackPins(active); devicePanel.querySelector("[data-audio-apply]").disabled= deviceBusy()||!view.canApply; const assignMain=devicePanel.querySelector("[data-audio-main-pins]"); @@ -2371,6 +2458,20 @@ deviceInventory=inventory; deviceChoice=null; renderDevicePanel(); + if(devicePanel&&!devicePanel.hidden&&!loopbackPending)requestLoopback(false); + }); + backend.addEventListener("arMixPhysicalLoopback",message=>{ + if(!loopbackId||message?.requestId!==loopbackId||!devicePanel||devicePanel.hidden)return; + loopbackPending=message.state==="CAPTURING"; + const result=message.result; + const measured=message.state==="MEASURED_LOOPBACK"&&result?.rate>0&&result?.frames>0; + loopbackField("result").textContent=measured? + "Measured wired round-trip "+(1000*result.frames/result.rate).toFixed(2)+ + " ms · "+result.frames+" frames · correlation "+result.confidence.toFixed(2)+ + " · "+message.message:message.message||"No calibration saved for these pins"; + if(!loopbackPending)loopbackField("confirmed").checked=false; + for(const side of ["input","output"])loopbackField(side).disabled=loopbackPending; + loopbackField("start").disabled=loopbackPending||!loopbackField("confirmed").checked; }); backend.addEventListener("arMixAudioDeviceApplyAck",ack=>{ if(!devicePanel)return;