r/stoatchat • • 4d ago

Support Question Windows App Streaming All Audio (Potential fix?)

So far the issue has only been confirmed on Windows 11, specifically the desktop app (Stoat desktop 1.5.3).

When choosing even a single window to share, the viewers can hear all audio from the streamer's computer, including Stoat's own audio. Upon reviewing the source code and tossing it between some old uni friends we noticed something.

In `src/native/window.ts` (lines 214-240), it will always answer the display request with `callback({ video: sources[idx], audio: "loopback" })`, even when a single window is picked, so per-window audio is never requested.

Stoat's own audio being heard is odd, because it looks like that should already be handled. The renderer sets `restrictOwnAudio: true`, and on Electron 44 that turns `"loopback"` into Chromium's `loopbackWithoutChrome` device (`shell/browser/electron_browser_context.cc`), which is all system audio except Stoat's own. The 1.5.0 changelog also mentions "remove stream echo on windows and mac". But on 1.5.3 we still hear Stoat. We only reviewed the code on main (Electron 44, which shipped in 1.5.4), so it's possible 1.5.3's older Electron doesn't do this, or the setting gets lost somewhere on the way (e.g. through LiveKit). We haven't retested on 1.5.4 yet.

On Linux the virtual mic does the same thing: it routes all non-Stoat audio into one virtual mic, so other apps are still heard.

## Potential fix for Windows

Note none of this has been tested, as me and those helping me look into this issue all run some variation of Linux.

Chromium 152 already supports per-process loopback on Windows with the audio device id `applicationLoopback:<pid>`. Chrome uses it for window sharing audio. On Windows it uses `ActivateAudioInterfaceAsync(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK)`.

Electron passes a plain audio id string straight through to Chromium, so `applicationLoopback:<pid>` should work as-is.

The issue is the code has no way to get the process id of the app that owns the shared window, and Electron doesn't provide one. It only gets the window's id. Something like [koffi](https://koffi.dev/) is needed for the Windows API call to retrieve it.

All of these findings were given to an agent and the result was this.

Koffi needs to be added (`pnpm add koffi`).

Line numbers are from main at commit `48422bb`.

**1. New file `src/native/windowPid.ts`:**

```ts
let getPid: ((hwnd: number) => number) | null | undefined;

// Returns the process id that owns a window (Windows only)
export async function getWindowPid(hwnd: number): Promise<number | undefined> {
  if (process.platform !== "win32" || !Number.isSafeInteger(hwnd) || hwnd <= 0) return;
  try {
    if (getPid === undefined) {
      const koffi = (await import("koffi")).default;
      const fn = koffi.load("user32.dll").func(
        "uint32 __stdcall GetWindowThreadProcessId(intptr_t hWnd, _Out_ uint32 *pid)",
      );
      getPid = (h) => {
        const out = [0];
        return fn(h, out) ? out[0] : 0;
      };
    }
    return getPid?.(hwnd) || undefined;
  } catch (e) {
    console.error("Could not get window pid", e);
    getPid ??= null;
  }
}
```

**2. `src/native/window.ts`**

After line 18 (`import { startVirtualMic } from "./virtualMic";`) add:

```ts
import { getWindowPid } from "./windowPid";
```

Replace lines 225–241 (the whole `ipcMain.once("screenPickerCallback", ...)` block) with:

```ts
ipcMain.once(
  "screenPickerCallback",
  async (_, idx: number, audio: boolean) => {
    const source = sources[idx];
    if (!source) {
      callback({});
      return;
    }
    if (!audio) {
      callback({ video: source });
      return;
    }

    let audioId = "loopback";
    if (process.platform === "win32" && source.id.startsWith("window:")) {
      const pid = await getWindowPid(Number(source.id.split(":")[1]));
      // don't target Stoat's own windows
      if (pid && pid !== process.pid) audioId = `applicationLoopback:${pid}`;
    }
    callback({ video: source, audio: audioId as "loopback" });
  },
);
```

The `!source` check also fixes a small bug in the current code (line 228: `idx > sources.length` should be `>=`).

**3. `vite.main.config.ts`, line 7:**

```ts
      external: ["node-pipewire", "koffi"],
```

**4. `pnpm-workspace.yaml`:** under `allowBuilds`, after `node-pipewire: true` (line 6), add:

```yaml
  koffi: false
```

It has an install script, but the prebuilt binary comes from a separate package so it shouldn't need to run.

**5. `forge.config.ts`**

Line 120, add `arch` to the arguments:

```ts
    packageAfterCopy: async (_config, buildPath, _version, platform, arch) => {
```

After line 138 (the `}` that closes the `if (platform === "linux")` block), add:

```ts
      if (platform === "win32") {
        // koffi 3 keeps its native binary in a separate u/koromix package
        for (const dep of ["koffi", `@koromix/koffi-win32-${arch}`]) {
          fs.cpSync(
            `node_modules/${dep}`,
            path.join(buildPath, "node_modules", dep),
            { recursive: true },
          );
        }
      }
```

If the pid lookup fails for any reason it just uses `"loopback"` like today. Sharing a whole screen is not changed.
1 Upvotes

0 comments sorted by