Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

9.1 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Standalone sound, both ways, independent of the screen:
//   m2w — this Mac's sound to the PC: sent when "Send this Mac's sound" is on, the PC accepts
//         (`audio.policy`) and the screen session isn't already carrying it.
//   w2m — the PC's sound here: we tell the PC with `audio.policy {accept}` and answer its offers.
//
// Events: 'change' — this.view changed.
'use strict';

const path = require('path');
const { BrowserWindow, ipcMain } = require('electron');
const { EventEmitter } = require('events');
const P = require('../shared/protocol.js');
const { Routes } = require('../shared/sound-route.js');

const DROP_MS = 30000;

class Audio extends EventEmitter {
  // capName: this one's consumer in the capture hub (audiohub.js); Multi-device has one Audio per device,
  // each its own (mesh/audioset.js).
  constructor({ server, hub, stream, getSettings, saveSettings = () => {}, meshHub = null, capName = 'audio' }) {
    super();
    Object.assign(this, { server, hub, stream, getSettings, meshHub, capName });
    // The mixer (shared/sound-route.js): which of our speakers its sound plays on, and its speakers ours.
    this.routes = new Routes({
      send: (m) => this.server.current && this.server.sendToClient(m), toWin: (m) => this._toWin('route', m), cfg: () => this.cfg,
      peerId: () => (this.server.current && this.server.current.deviceId) || '', save: saveSettings,
      onChange: () => this.emit('change'), receiving: () => !!(this.receiving && this.receiving.status === 'live'),
    });
    this.saidSync = null; // Keep speakers in sync, as last said to it while sending
    this.win = null;
    this.peerAccepts = false; // the PC plays our sound
    this.sendSession = 0;
    this.sending = null; // { session, status }
    this.receiving = null; // { session, status }

    server.on('client', () => {
      this.peerAccepts = false;
      this.routes.reset();
      this.saidSync = null;
      this._policy();
      this.evaluate();
      this._syncAudioSticky();
      this.routes.hello(); // our speakers, said at once (the mixer lists them before any sound)
    });
    server.on('closed', () => {
      if (server.current) return;
      this._stopSend(false);
      this._stopRecv();
      this.routes.reset();
      this.saidSync = null;
      this._idle();
      this._syncAudioSticky();
    });
    server.on(`t:${P.T.AUDIO_ROUTE}`, (m) => this.routes.onRoute(m)); // the sender's pick of our speakers, its sync
    server.on(`t:${P.T.AUDIO_OUTS}`, (m) => this.routes.onOuts(m)); // the receiver's speakers for our sound
    server.on(`t:${P.T.AUDIO_POLICY}`, (m) => {
      this.peerAccepts = m.accept === true;
      this.evaluate();
    });
    server.on(`t:${P.T.AUDIO_OFFER}`, (m) => m.dir === 'w2m' && this._onOffer(m));
    server.on(`t:${P.T.AUDIO_STOP}`, (m) => m.dir === 'w2m' && this._stopRecv());
    for (const t of [P.T.AUDIO_ANSWER, P.T.AUDIO_ICE]) server.on(`t:${t}`, (m) => this._toWin('remote', m));
    stream.on('change', () => this.evaluate()); // the screen may have started/stopped carrying sound

    ipcMain.on('audio:out', (e, m) => {
      if (!this._fromWin(e)) return;
      const ours = m.dir === 'm2w' ? this.sending : this.receiving;
      if (ours && m.session === ours.session) this.server.sendToClient(m);
    });
    ipcMain.on('audio:state', (e, s) => {
      if (!this._fromWin(e) || !s) return;
      if (s.info) return this.routes.onWin(s.info); // its speakers and the delay heard (shared/sound-outs.js)
      const ours = s.dir === 'm2w' ? this.sending : this.receiving;
      if (!ours || s.session !== ours.session) return;
      const started = s.dir === 'w2m' && s.status === 'connected' && ours.status !== 'live';
      ours.status = s.status === 'connected' ? 'live' : s.status;
      if (started) this.routes.tell(true); // its sound plays here: our speakers to it
      this._syncAudioSticky();
      this.emit('change');
    });
  }

  get cfg() {
    return this.getSettings().audio;
  }

  // Send / Play for the device the sound is with. In the mesh the Audio page's switches are the selected
  // device's pair; sound that stays with another device (the sticky route) goes by that device's own (#245).
  _on(key) {
    const cur = !!this.cfg[key];
    if (!this.meshHub) return cur;
    const c = this.server.current;
    const consent = this.meshHub.consent; // this device's own pair (shared/consent.js)
    return consent && c ? !!consent.get(c.deviceId, 'audio', key === 'send' ? 'out' : 'in') : cur;
  }

  _syncAudioSticky() {
    if (!this.meshHub) return;
    const c = this.server.current;
    const live = !!(this.sending || this.receiving);
    this.meshHub.setAudioSticky('sound', live && c ? c.deviceId : null);
  }

  _fromWin(e) {
    return this.win && !this.win.isDestroyed() && e.sender === this.win.webContents;
  }

  async _ensureWin() {
    clearTimeout(this.dropTimer);
    if (this.win && !this.win.isDestroyed()) return;
    this.win = new BrowserWindow({
      show: false,
      webPreferences: { preload: path.join(__dirname, 'preload-audio.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false },
    });
    this.win.webContents.on('console-message', (e) => e.level === 'error' && console.log(`[audio-window] ${e.message}`));
    await this.win.loadFile(path.join(__dirname, 'audio.html'));
    this._toWin('volume', this.cfg.volume);
    this.routes.push();
  }

  _toWin(channel, msg) {
    if (this.win && !this.win.isDestroyed()) this.win.webContents.send(channel, msg);
  }

  _policy() {
    this.server.sendToClient({ t: P.T.AUDIO_POLICY, accept: this._on('receive') });
  }

  // m2w: start or stop sending to match the switches.
  async evaluate() {
    const screenCarries = this.stream.audio.on;
    const want = !!(this._on('send') && this.peerAccepts && this.server.current && !screenCarries);
    if (want && !this.sending) {
      const session = ++this.sendSession;
      this.sending = { session, status: 'starting' };
      this.emit('change');
      await this._ensureWin();
      if (!this.sending || this.sending.session !== session) return;
      if (!(await this.hub.acquire(this.capName, this.win.webContents))) {
        this.sending = { session, status: `error: ${this.hub.error}` };
        return this.emit('change');
      }
      this._toWin('send-start', { session, ice: (this.server.current && this.server.current.ice) || null });
    } else if (!want && this.sending) {
      this._stopSend(true);
    }
    // Keep speakers in sync: said to it while we send, again when it changes.
    const sync = want ? !!this.cfg.sync : null;
    if (sync !== null && sync !== this.saidSync) this.routes.sayingSync(sync);
    this.saidSync = sync;
    this._syncAudioSticky();
    this.emit('change');
  }

  _stopSend(tell) {
    if (!this.sending) return;
    this.sending = null;
    this.hub.release(this.capName);
    this._toWin('send-stop', {});
    if (tell && this.server.current) this.server.sendToClient({ t: P.T.AUDIO_STOP, dir: 'm2w' });
    this._syncAudioSticky();
    this.emit('change');
    this._idle();
  }

  // Nothing playing either way and nobody who would (no session, or both switches off): the hidden
  // window and its renderer go after DROP_MS; the next sound makes it again.
  _idle() {
    clearTimeout(this.dropTimer);
    if (!this.win) return;
    this.dropTimer = setTimeout(() => {
      if (this.sending || this.receiving || !this.win || (this.server.current && (this._on('send') || this._on('receive')))) return;
      const w = this.win;
      this.win = null;
      if (!w.isDestroyed()) w.destroy();
    }, DROP_MS);
  }

  // w2m: the PC offers its sound.
  async _onOffer(m) {
    if (!this._on('receive')) return;
    this.receiving = { session: m.session, status: 'connecting' };
    await this._ensureWin();
    this._toWin('recv', { session: m.session, sdp: m.sdp, ice: (this.server.current && this.server.current.ice) || null });
    this._syncAudioSticky();
    this.emit('change');
  }

  _stopRecv() {
    if (!this.receiving) return;
    this.receiving = null;
    this._toWin('recv-stop', {});
    this._syncAudioSticky();
    this.emit('change');
    this._idle();
  }

  // After the Audio tab changed.
  applySettings() {
    this._policy();
    if (!this._on('receive')) this._stopRecv();
    this._toWin('volume', this.cfg.volume);
    this.routes.push();
    this.hub.applyMute();
    this.evaluate();
    this._idle();
  }

  get view() {
    return {
      peerAccepts: this.peerAccepts,
      screenCarries: this.stream.audio.on,
      sending: this.sending,
      receiving: this.receiving,
      error: this.hub.error,
      ...this.routes.view(),
    };
  }

  // The mixer: the receiver's speakers for our sound (From this Mac), or ours for its (To).
  // This Mac's speakers as its settings window lists them (shared/sound-route.js setOwn).
  setSpeakers(list) {
    this.routes.setOwn(list);
  }

  setRoute(dir, outs) {
    if (outs === null) return dir === 'in' ? this.routes.clear() : this.routes.clearRemote(); // System default
    return dir === 'in' ? this.routes.setLocal(outs) : this.routes.setRemote(outs);
  }
}

module.exports = { Audio };