Skip to content

armgit / nota

Public Imported from GitHub
0

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

(fix) Nota Remote: no audio dropouts from the USB-link lookup on macOS (#519)

Egor Khindikaynenb50317f3bac7
diff --git a/.specify/bugs/remote-networksetup-dropouts/assessment.md b/.specify/bugs/remote-networksetup-dropouts/assessment.md
new file mode 100644
index 00000000..904258c4
--- /dev/null
+++ b/.specify/bugs/remote-networksetup-dropouts/assessment.md
@@ -0,0 +1,60 @@
+# Bug Assessment: Audio dropouts every ~10 s while Nota Remote is open
+
+- **Slug**: remote-networksetup-dropouts
+- **Created**: 2026-11-05
+- **Source**: https://github.com/nota-daw/nota/issues/511 (host: github.com, policy: allowlisted; the issue was filed from this session's investigation, so its content is first-hand)
+- **Verdict**: valid
+- **Severity**: high
+
+## Report (verbatim or summarized)
+
+[nota-daw/nota#511](https://github.com/nota-daw/nota/issues/511) — "Audio dropouts every ~10 s while Nota Remote is open (networksetup spawned from the app process)". In 0.59.1 on macOS (Apple Silicon, built-in output, 44.1 kHz / 128 frames) the log shows `WARN Audio dropout #N` at a steady 10.07 s interval while a Remote client (browser tab) is connected or the Remote popup is open. A `networksetup` process caught at 16:08:18.413Z coincides with dropout #39 logged at 16:08:18.415Z. Average DSP load is ~14 %, so the audio callback is not CPU-bound.
+
+## Symptom
+
+With Remote in use, audible dropouts recur every ~10 s regardless of what is playing. Expected: Remote has no effect on audio.
+
+## Reproduction
+
+1. macOS, 128-frame buffer, any project playing.
+2. Enable Remote; open it in a browser tab (or keep the Remote popup open).
+3. `WARN Audio dropout #N` appears in `~/Library/Application Support/Nota/logs/nota-YYYYMMDD.log` about every 10 s.
+4. Close the tab and popup — dropouts stop.
+
+## Suspected Code Paths
+
+- `src/managed/Nota.Remote/RemoteLinks.cs:UsbDevices()` — caches the device→hardware-port map for only 10 s, then calls `ListHardwarePorts()`.
+- `src/managed/Nota.Remote/RemoteLinks.cs:ListHardwarePorts()` — `Process.Start("/usr/sbin/networksetup", "-listallhardwareports")`.
+- `src/managed/Nota.App/Remote/RemoteService.cs:Links` — the popup reads it every second → `RemoteLinks.All()` → `UsbDevices()`.
+- `src/managed/Nota.Remote/RemoteHub.cs:UsbLink()` — every `Devices` read, per connected client → `RemoteLinks.OnUsbLink()` → `UsbDevices()`.
+
+## Root Cause Hypothesis
+
+Confidence: high. While anything polls Remote's links or devices, `UsbDevices()` re-runs `networksetup` every 10 s. Spawning a child process from the large, many-threaded .NET app process (fork/exec) briefly stalls the whole process — COW page-table setup / VM-map contention — long enough for the real-time CoreAudio callback to miss its ~2.9 ms deadline. The timing match (2 ms) between the spawn and the dropout confirms the spawn as the trigger.
+
+## Proposed Remediation
+
+**Preferred**: Never spawn a process for this. On macOS read the BSD name → hardware-port map from SystemConfiguration (`SCNetworkInterfaceCopyAll`, `SCNetworkInterfaceGetBSDName`, `SCNetworkInterfaceGetLocalizedDisplayName`) via P/Invoke — an in-process call that returns the same strings `networksetup` prints ("iPhone USB", "Wi-Fi", "Thunderbolt Bridge"…). Additionally drop the 10 s time-to-live: keep the map until `NetworkChange.NetworkAddressChanged` fires (an interface appearing is exactly when a cable comes up), so even the in-process call happens only on a network change.
+
+**Alternatives**:
+- Keep `networksetup` but refresh only on network change — still a spawn whenever the network changes mid-playback (Wi-Fi roaming, AWDL), so dropouts remain possible.
+
+**Files likely to change**:
+- `src/managed/Nota.Remote/RemoteLinks.cs`
+- `tests/Nota.SmokeTest/RemoteTests.cs`
+- `CHANGELOG.md`
+
+**Tests to add or update**:
+- Smoke: on macOS the SystemConfiguration map is non-empty and names the built-in Wi-Fi/Ethernet port by BSD name (`en0` …) — proves the interop works without a process.
+- Smoke: repeated `RemoteLinks.All()` / `OnUsbLink()` calls do not re-read the map until it is invalidated.
+- Keep `ParseHardwarePorts` only if still used; otherwise remove it and its test.
+
+## Risks & Considerations
+
+- P/Invoke into SystemConfiguration/CoreFoundation: CF ownership rules (Copy → CFRelease; Get → no release) must be followed to avoid leaks/crashes.
+- `SCNetworkInterfaceGetLocalizedDisplayName` is localized; the USB check matches "USB"/"Android", which Apple keeps untranslated in port names ("iPhone USB"). Same exposure as `networksetup`, which also prints localized names.
+- Windows/Linux paths are unaffected (no process spawn there).
+
+## Open Questions
+
+- None blocking.
diff --git a/.specify/bugs/remote-networksetup-dropouts/fix.md b/.specify/bugs/remote-networksetup-dropouts/fix.md
new file mode 100644
index 00000000..616f7ff2
--- /dev/null
+++ b/.specify/bugs/remote-networksetup-dropouts/fix.md
@@ -0,0 +1,51 @@
+# Bug Fix: Audio dropouts every ~10 s while Nota Remote is open
+
+- **Slug**: remote-networksetup-dropouts
+- **Fixed**: 2026-11-05
+- **Assessment**: ./assessment.md
+- **Status**: applied
+
+## Summary
+
+Remote no longer spawns `networksetup` to tell USB network links apart. The device → hardware-port
+map is read in-process from SystemConfiguration and kept until the network changes, so nothing
+on Remote's polling path can start a child process and stall the audio callback.
+
+## Changes
+
+| File | Change | Notes |
+|------|--------|-------|
+| `src/managed/Nota.Remote/RemoteLinks.cs` | modified | `UsbDevices()` reads via the new `MacHardwarePorts` (P/Invoke: `SCNetworkInterfaceCopyAll`, `SCNetworkInterfaceGetBSDName`, `SCNetworkInterfaceGetLocalizedDisplayName`, CF array/string helpers); the 10 s TTL is gone — the map is cached until `Invalidate()`, which `NetworkChange.NetworkAddressChanged` calls; `ParseHardwarePorts`/`ListHardwarePorts` and `System.Diagnostics` removed; `HardwarePorts()` and `PortReads` exposed for the smoke test |
+| `src/managed/Nota.App/Remote/RemoteService.cs` | modified | `OnNetworkChanged` also calls `RemoteLinks.Invalidate()` so the map is fresh before the QR refresh |
+| `tests/Nota.SmokeTest/RemoteTests.cs` | updated test | the `networksetup` parser check is replaced by two macOS checks (below) |
+| `CHANGELOG.md` | modified | `[Unreleased]` → `Fixed` entry (#511) |
+
+## Diff Highlights (optional)
+
+```csharp
+lock (Gate)
+{
+ if (_ports is not null) return _ports;
+ _ports = MacHardwarePorts.Read(); // in-process, no child process
+ PortReads++;
+ return _ports;
+}
+```
+
+## Tests Added or Updated
+
+- `RemoteTests.Links` — "macOS hardware ports read in-process from SystemConfiguration": the map is non-empty with non-empty device and port names.
+- `RemoteTests.Links` — "link queries reuse the port map until the network changes": after `Invalidate()`, 20 × (`All()` + `OnUsbLink()`) read the map exactly once.
+
+## Local Verification
+
+- Commands run: `scripts/build.sh` (worktree `../nota-remote-fix`, fresh engine build) → exit 0; `SCANNER SELFTEST PASSED`, `SMOKE TEST PASSED`, `SCAN SCALE PASSED`; both new checks `[PASS]`.
+- Manual checks: the map read through SystemConfiguration (`en4=Ethernet Adapter (en4)`, `en5`, `en6`, `bridge0=Thunderbolt Bridge`, `en0=Wi-Fi`, `en1..en3=Thunderbolt 1..3`) is identical to `networksetup -listallhardwareports` on this Mac.
+
+## Deviations from Assessment
+
+- `RemoteService.OnNetworkChanged` (not listed in the assessment) gained one `RemoteLinks.Invalidate()` call, so the invalidation does not depend on the order of the two `NetworkAddressChanged` handlers.
+
+## Follow-ups
+
+- Runtime check in the real app with a connected Remote client (xrun count stays flat, no `networksetup` processes) — `/speckit-bug-test`.
diff --git a/.specify/bugs/remote-networksetup-dropouts/test.md b/.specify/bugs/remote-networksetup-dropouts/test.md
new file mode 100644
index 00000000..5d2e3ebd
--- /dev/null
+++ b/.specify/bugs/remote-networksetup-dropouts/test.md
@@ -0,0 +1,40 @@
+# Bug Verification: Audio dropouts every ~10 s while Nota Remote is open
+
+- **Slug**: remote-networksetup-dropouts
+- **Tested**: 2026-11-05
+- **Assessment**: ./assessment.md
+- **Fix**: ./fix.md
+- **Result**: verified
+
+## Summary
+
+The reproduction no longer reproduces: with the fixed build playing `demo17.nota` and a Remote client connected, three minutes passed with zero dropouts and no `networksetup` process, where 0.59.1 dropped out every ~10 s in the same setup. The full build and smoke suite pass.
+
+## Checks Performed
+
+| Check | Command / Action | Result | Notes |
+|-------|------------------|--------|-------|
+| Reproduction (pre-fix baseline) | 0.59.1 from /Applications, `demo17.nota` playing a Session scene, Remote open in a browser | fail (bug present) | dropouts #1–#98 at a steady ~10.07 s; a `networksetup` spawn matched dropout #39 within 2 ms |
+| Reproduction (post-fix) | worktree Release build (`Nota.App`), same user data dir, same project playing, Remote client connected (192.168.31.249 → :7789 ESTABLISHED); 180 s watch of the log and `pgrep -x networksetup` every 50 ms | pass | 0 new `Audio dropout` lines; 0 `networksetup` processes; engine `xruns` = 0 over MCP while `playing: true` |
+| New / updated tests | `scripts/build.sh` (smoke) | pass | `macOS hardware ports read in-process from SystemConfiguration`; `link queries reuse the port map until the network changes (read 1× for 40 queries)` |
+| Regression suite | `scripts/build.sh` | pass | `SCANNER SELFTEST PASSED`, `SMOKE TEST PASSED`, `SCAN SCALE PASSED`, exit 0 |
+| Port-map equivalence | SystemConfiguration map vs `networksetup -listallhardwareports` | pass | identical 8 device/port pairs on this Mac |
+| Lint / type-check | `dotnet build Nota.sln -c Release` (inside build.sh) | pass | no new warnings in the changed files |
+
+## Output Excerpts
+
+```
+start 22:39:50 dropouts_in_log=96
+end 22:42:50 new_dropouts=0 networksetup_seen=0
+{"sampleRate":44100,"xruns":0,"sceneCount":8}
+```
+
+## Residual Risks
+
+- Not exercised: an actual USB-tethered phone (iPhone USB / Android) appearing mid-session — the map now refreshes on `NetworkAddressChanged` only; the read path is the same SystemConfiguration call the smoke test covers.
+- Whether the Remote popup was open during the post-fix window was not recorded; the connected client alone drove `RemoteHub.Devices` → `OnUsbLink`, the path that spawned before.
+- Only macOS 26.6 / Apple Silicon was tested; Windows and Linux paths are unchanged.
+
+## Recommendation
+
+Close the bug — verified end-to-end on the reporter's setup. Optionally confirm USB tethering still shows the USB address first in the Remote popup before release.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37b8ef40..22b98375 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
more clips on the Scenes screen together launched none of them, or only one — iOS Safari
only sends a tap for a single finger. Every clip, scene and Stop button now takes its own
finger, and a drag that scrolls the grid still launches nothing.
+- **Nota Remote no longer causes audio dropouts on macOS** (#511): while a phone or browser
+ tab was connected, or the Remote popup was open, the sound dropped out about every
+ 10 seconds. Nota started a system helper on that interval to find USB network links; it now
+ reads them directly and only again when the network changes.
## [0.59.1] — 2026-11-05
diff --git a/src/managed/Nota.App/Remote/RemoteService.cs b/src/managed/Nota.App/Remote/RemoteService.cs
index 6bc7c903..d7d132b5 100644
--- a/src/managed/Nota.App/Remote/RemoteService.cs
+++ b/src/managed/Nota.App/Remote/RemoteService.cs
@@ -54,6 +54,7 @@ public sealed class RemoteService
private void OnNetworkChanged()
{
_linksAt = DateTime.MinValue; // the USB map may have changed with the addresses
+ RemoteLinks.Invalidate();
_networkRetry?.Dispose();
_networkRetry = new System.Threading.Timer(_ => { RaiseChanged(); _networkRetry?.Dispose(); _networkRetry = null; },
null, 800, -1);
diff --git a/src/managed/Nota.Remote/RemoteLinks.cs b/src/managed/Nota.Remote/RemoteLinks.cs
index 8daf215c..55c70644 100644
--- a/src/managed/Nota.Remote/RemoteLinks.cs
+++ b/src/managed/Nota.Remote/RemoteLinks.cs
@@ -6,10 +6,10 @@
// millisecond latency and no radio to drop — so when one is up it leads the QR. The same
// server socket serves every interface; this only decides what Nota shows.
-using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
+using System.Runtime.InteropServices;
namespace Nota.Remote;
@@ -112,54 +112,98 @@ public static class RemoteLinks
|| ni.Name.StartsWith("usb", StringComparison.Ordinal)));
}
- /// <summary>macOS: device (en7) → hardware port ("iPhone USB"). Cached; the helper it
- /// shells out to is not free and ports appear only when something is plugged in.</summary>
+ /// <summary>macOS: device (en7) → hardware port ("iPhone USB"). Read in-process from
+ /// SystemConfiguration and kept until the network changes — ports appear only when something
+ /// is plugged in, and that always brings an address with it. Never a child process: spawning
+ /// one from this app stalls the whole process long enough to drop out the audio callback.</summary>
private static Dictionary<string, string> UsbDevices()
{
if (!OperatingSystem.IsMacOS()) return new();
lock (Gate)
{
- if (DateTime.UtcNow - _portsAt < TimeSpan.FromSeconds(10)) return _ports;
- _ports = ListHardwarePorts();
- _portsAt = DateTime.UtcNow;
+ if (_ports is not null) return _ports;
+ _ports = MacHardwarePorts.Read();
+ PortReads++;
return _ports;
}
}
+ static RemoteLinks()
+ {
+ NetworkChange.NetworkAddressChanged += (_, _) => Invalidate();
+ }
+
+ /// <summary>Forget the device → port map; the next query reads it again.</summary>
+ public static void Invalidate()
+ {
+ lock (Gate) { _ports = null; Invalidations++; }
+ }
+
+ /// <summary>The macOS device → hardware-port map, as the USB check sees it. Public for the
+ /// smoke test.</summary>
+ public static IReadOnlyDictionary<string, string> HardwarePorts() => UsbDevices();
+
+ /// <summary>How many times the port map has been read since launch. Public so the smoke test
+ /// can check that link queries reuse it.</summary>
+ public static int PortReads { get; private set; }
+
+ /// <summary>How many times the map has been forgotten (a network change or
+ /// <see cref="Invalidate"/>). Public so the smoke test can allow for a real network change
+ /// landing mid-check.</summary>
+ public static int Invalidations { get; private set; }
+
private static readonly object Gate = new();
- private static Dictionary<string, string> _ports = new();
- private static DateTime _portsAt = DateTime.MinValue;
+ private static Dictionary<string, string>? _ports;
+}
- /// <summary>Parses `networksetup -listallhardwareports`: blocks of "Hardware Port:", then
- /// "Device:". Public so the smoke test can check it without shelling out.</summary>
- public static Dictionary<string, string> ParseHardwarePorts(string output)
+/// <summary>SCNetworkInterfaceCopyAll: the same device/port pairs `networksetup
+/// -listallhardwareports` prints, without leaving the process.</summary>
+internal static class MacHardwarePorts
+{
+ private const string SystemConfiguration = "/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration";
+ private const string CoreFoundation = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
+ private const uint Utf8 = 0x08000100; // kCFStringEncodingUTF8
+
+ public static Dictionary<string, string> Read()
{
var map = new Dictionary<string, string>(StringComparer.Ordinal);
- string port = "";
- foreach (var line in output.Split('\n'))
+ try
{
- string l = line.Trim();
- if (l.StartsWith("Hardware Port:", StringComparison.Ordinal)) port = l["Hardware Port:".Length..].Trim();
- else if (l.StartsWith("Device:", StringComparison.Ordinal) && port.Length > 0)
+ IntPtr all = SCNetworkInterfaceCopyAll(); // owned: released below
+ if (all == IntPtr.Zero) return map;
+ try
{
- map[l["Device:".Length..].Trim()] = port;
- port = "";
+ long n = CFArrayGetCount(all);
+ for (long i = 0; i < n; i++)
+ {
+ IntPtr ni = CFArrayGetValueAtIndex(all, i); // borrowed from the array
+ string? device = Str(SCNetworkInterfaceGetBSDName(ni));
+ string? port = Str(SCNetworkInterfaceGetLocalizedDisplayName(ni));
+ if (!string.IsNullOrEmpty(device) && !string.IsNullOrEmpty(port)) map[device] = port;
+ }
}
+ finally { CFRelease(all); }
}
+ catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException) { }
return map;
}
- private static Dictionary<string, string> ListHardwarePorts()
+ // A borrowed CFString (a Get, not a Copy) as UTF-8 text.
+ private static string? Str(IntPtr cf)
{
- try
- {
- using var p = Process.Start(new ProcessStartInfo("/usr/sbin/networksetup", "-listallhardwareports")
- { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true });
- if (p is null) return new();
- string text = p.StandardOutput.ReadToEnd();
- p.WaitForExit(2000);
- return ParseHardwarePorts(text);
- }
- catch { return new(); }
+ if (cf == IntPtr.Zero) return null;
+ var buf = new byte[256];
+ if (!CFStringGetCString(cf, buf, buf.Length, Utf8)) return null;
+ int len = Array.IndexOf(buf, (byte)0);
+ return System.Text.Encoding.UTF8.GetString(buf, 0, len < 0 ? buf.Length : len);
}
+
+ [DllImport(SystemConfiguration)] private static extern IntPtr SCNetworkInterfaceCopyAll();
+ [DllImport(SystemConfiguration)] private static extern IntPtr SCNetworkInterfaceGetBSDName(IntPtr networkInterface);
+ [DllImport(SystemConfiguration)] private static extern IntPtr SCNetworkInterfaceGetLocalizedDisplayName(IntPtr networkInterface);
+ [DllImport(CoreFoundation)] private static extern long CFArrayGetCount(IntPtr array);
+ [DllImport(CoreFoundation)] private static extern IntPtr CFArrayGetValueAtIndex(IntPtr array, long index);
+ [DllImport(CoreFoundation)] [return: MarshalAs(UnmanagedType.U1)]
+ private static extern bool CFStringGetCString(IntPtr str, byte[] buffer, long bufferSize, uint encoding);
+ [DllImport(CoreFoundation)] private static extern void CFRelease(IntPtr cf);
}
diff --git a/tests/Nota.SmokeTest/RemoteTests.cs b/tests/Nota.SmokeTest/RemoteTests.cs
index 399d05a3..f0949cfa 100644
--- a/tests/Nota.SmokeTest/RemoteTests.cs
+++ b/tests/Nota.SmokeTest/RemoteTests.cs
@@ -56,13 +56,20 @@ internal static class RemoteTests
private static IEnumerable<(bool, string)> Links()
{
- var ports = RemoteLinks.ParseHardwarePorts(
- "Hardware Port: Wi-Fi\nDevice: en0\nEthernet Address: aa\n\n" +
- "Hardware Port: iPhone USB\nDevice: en7\nEthernet Address: bb\n\n" +
- "Hardware Port: Thunderbolt Bridge\nDevice: bridge0\nEthernet Address: cc\n\n" +
- "Hardware Port: USB 10/100/1000 LAN\nDevice: en8\nEthernet Address: dd\n");
- yield return (ports.Count == 4 && ports["en7"] == "iPhone USB" && ports["en8"].Contains("USB"),
- "macOS hardware ports parse to their devices (iPhone USB on en7)");
+ if (OperatingSystem.IsMacOS())
+ {
+ var ports = RemoteLinks.HardwarePorts();
+ yield return (ports.Count > 0 && ports.Keys.All(d => d.Length > 0) && ports.Values.All(p => p.Length > 0),
+ $"macOS hardware ports read in-process from SystemConfiguration ({string.Join(", ", ports.Select(kv => kv.Key + "=" + kv.Value))})");
+
+ RemoteLinks.Invalidate();
+ int before = RemoteLinks.PortReads, cleared = RemoteLinks.Invalidations;
+ for (int i = 0; i < 20; i++) { RemoteLinks.All(); RemoteLinks.OnUsbLink(IPAddress.Parse("192.0.2.2")); }
+ // A real network change mid-loop clears the map once more and earns one more read.
+ int reads = RemoteLinks.PortReads - before, changes = RemoteLinks.Invalidations - cleared;
+ yield return (reads >= 1 && reads <= 1 + changes,
+ $"link queries reuse the port map until the network changes (read {reads}× for 40 queries, {changes} network change(s))");
+ }
yield return (RemoteLinks.InSubnet(IPAddress.Parse("192.0.2.2"), IPAddress.Parse("192.0.2.1"), 24),
"a phone on the USB subnet is recognised (192.0.2.2 in 192.0.2.1/24)");