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.

16.1 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Screen sharing: hidden capture window (getDisplayMedia + RTCPeerConnection, the offerer),
// session numbering, rtc.* relay between the capture window and the Windows client, stats.
// We capture only while a viewer is open on the other side (its `screen.policy
// {accept}`); a peer that never sends one is an older app and always gets the picture.
//
// Events: 'change' — this.view changed (pushed to the control window as state.stream).
'use strict';

const path = require('path');
const ScreenCodec = require('../shared/screencodec.js');
const { loopback } = require('./audiohub.js');
const util = require('util');
const { BrowserWindow, ipcMain, session, desktopCapturer, systemPreferences } = require('electron');
const { EventEmitter } = require('events');
const P = require('../shared/protocol.js');

const RETRY_MS = 2000;
// Stopped with nobody to share to (no session, or sharing off): the hidden capture window goes after
// this long. While a session is on and sharing is on it stays, so a viewer that opens again starts at once.
const DROP_MS = 30000;

class Stream extends EventEmitter {
  constructor(server, displays, getSettings, hub) {
    super();
    this.server = server;
    this.displays = displays;
    this.getSettings = getSettings;
    this.hub = hub; // shared system-audio capture (audiohub.js)
    this.audio = { on: false, error: null }; // sound travelling with the screen
    this.win = null;
    this.session = 0;
    this.active = null; // {session, displayId, width, height} while a session runs
    this.retryTimer = null;
    this.viewer = null; // the peer's screen.policy accept; null = never said (older app: always watching)
    this.view = { status: 'off', display: null, width: 0, height: 0, fps: 0, mbps: 0, encoder: '', codec: '' };

    session.defaultSession.setDisplayMediaRequestHandler(async (_req, cb) => {
      try {
        if (!this.active) return cb({});
        // The sound, when asked for: Chromium's loopback (audiohub.js loopback()).
        const active = this.active, win = this.win;
        const target = this.displays.target();
        if (!target || target.id !== active.displayId) return cb({});
        const source = await this._source(target);
        cb(this.active === active && this.win === win && this.displays.target()?.id === target.id ? { video: source, ...(_req.audioRequested ? { audio: 'loopback' } : {}) } : {});
      } catch (e) {
        console.error(`[stream] no capture source: ${e.message}`);
        cb({});
      }
    });

    // A new peer says within moments whether its viewer is open (screen.policy); an older app never
    // does. So wait up to 1.5 s before sending anything, then treat silence as "watching".
    server.on('client', () => {
      this.viewer = null;
      this.waitingPolicy = true;
      clearTimeout(this.policyTimer);
      this.policyTimer = setTimeout(() => {
        this.waitingPolicy = false;
        if (this.viewer === null) this.restart('older viewer');
      }, 1500);
      this._stopWindow(this.getSettings().sharing.on ? 'no viewer' : 'off');
    });
    server.on(`t:${P.T.SCREEN_POLICY}`, (msg) => {
      const on = !!msg.accept;
      // A phone's viewer says how big it is: Extend becomes a screen of that shape.
      const c = this.server.current;
      if (c && P.isPhoneOs(c.os) && on && msg.width > 0 && msg.height > 0) {
        this.phoneSize = { width: msg.width | 0, height: msg.height | 0 };
        this.displays.setOverride(this.phoneSize);
      }
      this.waitingPolicy = false;
      clearTimeout(this.policyTimer);
      if (on === this.viewer) return;
      this.viewer = on;
      if (on) this.restart('viewer open');
      else this._stopWindow(this.getSettings().sharing.on ? 'no viewer' : 'off');
    });
    server.on('closed', () => {
      if (!server.current || !P.isPhoneOs(server.current.os)) {
        this.phoneSize = null;
        this.displays.setOverride(null);
      }
      if (!server.current) this._stopWindow('nothing connected');
    });
    // The session moved (Bluetooth -> a Wi-Fi Direct link, or back): a session offered on the old
    // path has no candidates for the new one and never connects. Start again on this one.
    server.on('transport', (c) => {
      const moved = this.active ? this.active.transport !== c.transport : this.view.status === 'waiting for Wi-Fi' && c.transport !== 'ble';
      if (moved) this.restart(`moved to ${c.transport === 'ble' ? 'Bluetooth' : 'Wi-Fi'}`);
    });
    server.on(`t:${P.T.RTC_ANSWER}`, (msg) => this._toWindow('remote', msg));
    server.on(`t:${P.T.RTC_ICE}`, (msg) => this._toWindow('remote', msg));
    server.on(`t:${P.T.RTC_DETAIL}`, (msg, ctx, socket) => {
      const owner = this.active?.detailOwner;
      if (!owner || socket !== owner || server.outbound(ctx) !== owner ||
          msg.session !== this.session || msg.session !== this.active.session ||
          !this.getSettings().sharing.on || this.displays.target()?.id !== this.active.displayId) return;
      this._toWindow('remote', { t: P.T.RTC_DETAIL, session: msg.session, height: msg.height });
    });
    displays.on('change', () => this._displaysChanged());

    ipcMain.on('capture:out', (e, msg) => {
      if (!this._fromCapture(e) || !this.active || msg.session !== this.active.session) return;
      if (msg.t === P.T.RTC_OFFER && process.env.TWINDESK_DEBUG_STREAM) console.log(`[stream] offer #${msg.session} -> ${server.current ? server.current.name : 'nobody'}`);
      if (msg.t === P.T.RTC_OFFER || msg.t === P.T.RTC_ICE) server.sendToClient(msg);
    });
    ipcMain.on('capture:stats', (e, s) => {
      if (!this._fromCapture(e) || !this.active || s.session !== this.active.session) return;
      const { fps, mbps, encoder, codec, qp, encodeMs, limit, targetMbps } = s;
      Object.assign(this.view, { fps, mbps, encoder, codec, qp, encodeMs, limit, targetMbps });
      if (process.env.MACSHARE_DEBUG_STATS) console.log(`[stream] ${JSON.stringify(s)}`);
      if (s.width) Object.assign(this.view, { width: s.width, height: s.height });
      this.emit('change');
    });
    // Chromium gave no sound (capture.js): the helper's capture instead.
    ipcMain.handle('capture:helperAudio', async (e) => {
      if (!this._fromCapture(e) || !this.active) return false;
      this.hub.loopback('screen', false);
      const ok = await this.hub.acquire('screen', this.win.webContents);
      this.audio.error = ok ? null : this.hub.error;
      this.audio.on = ok;
      this.emit('change');
      return ok;
    });
    ipcMain.on('capture:state', (e, s) => {
      if (!this._fromCapture(e) || !this.active || s.session !== this.active.session) return;
      this._setStatus(s.status);
      if (s.status === 'failed' || s.status.startsWith('error')) this._scheduleRetry();
    });
  }

  _releaseAudio() {
    this.hub.release('screen');
    this.hub.loopback('screen', false);
  }

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

  async _source(target = this.displays.target()) {
    for (let attempt = 0; attempt < 6; attempt++) {
      const sources = await desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 0, height: 0 } });
      const listed = this.displays.list?.() || [];
      const src = target && (sources.find((s) => s.display_id === String(target.id)) ||
        (sources.length === 1 && !sources[0].display_id && listed.length === 1 && String(listed[0].id) === String(target.id) ? sources[0] : null));
      if (src) return src;
      if (systemPreferences.getMediaAccessStatus('screen') !== 'granted') throw new Error('Screen Recording permission required');
      if (attempt < 5) await new Promise((resolve) => setTimeout(resolve, 200));
    }
    const error = new Error('no display to share');
    error.code = 'NO_DISPLAY';
    throw error;
  }

  _ensureWindow() {
    clearTimeout(this.dropTimer);
    if (this.win && !this.win.isDestroyed()) return Promise.resolve();
    const w = this.win = new BrowserWindow({
      show: false,
      webPreferences: {
        preload: path.join(__dirname, 'preload-capture.js'),
        contextIsolation: true,
        nodeIntegration: false,
        backgroundThrottling: false,
      },
    });
    this.win.webContents.on('render-process-gone', (_e, d) => {
      if (this.win !== w) return; // closed on purpose (_drop)
      console.error(`[stream] capture window gone: ${d.reason}`);
      this.win = null;
      this._scheduleRetry();
    });
    this.win.webContents.on('console-message', (e) => console.log(`[capture] ${e.message}`));
    return this.win.loadFile(path.join(__dirname, 'capture.html'));
  }

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

  _setStatus(status) {
    this.view.status = status;
    this.emit('change');
  }

  _scheduleRetry() {
    clearTimeout(this.retryTimer);
    this.retryTimer = setTimeout(() => this.restart('retry'), RETRY_MS);
  }

  // Start a fresh WebRTC session (or stop, if sharing is off or no PC is connected).
  async restart(reason) {
    clearTimeout(this.retryTimer);
    if (!this.getSettings().sharing.on) return this.stop('off');
    if (!this.server.current) return this._stopWindow('nothing connected');
    if (this.viewer === false || this.waitingPolicy) return this._stopWindow('no viewer');
    // Bluetooth can't carry the picture: it starts once the session is on Wi-Fi (netlink.js, 'transport').
    if (this.server.current.transport === 'ble') return this._stopWindow('waiting for Wi-Fi');
    this.displays.captureWanted?.(this, true);
    const target = this.displays.target();
    if (!target) return this._waitDisplay();

    const s = ++this.session;
    const { width, height } = this._outSize(target);
    // Sound goes with the screen only when "Share sound with the screen" is on (else: none, for latency):
    // 'loopback' (Chromium captures it; the helper's if it can't), else the helper's capture.
    let audio = false;
    if (this.getSettings().sharing.audio && loopback()) {
      this.hub.release('screen');
      this.hub.loopback('screen', true);
      this.audio.error = null;
      audio = 'loopback';
    } else if (this.getSettings().sharing.audio) {
      await this._ensureWindow();
      audio = await this.hub.acquire('screen', this.win.webContents);
      this.audio.error = audio ? null : this.hub.error;
    } else {
      this._releaseAudio();
    }
    this.audio.on = !!audio;
    if (this.session !== s) return;
    const detailOwner = this.server.current.os === P.OS.ANDROID ? this.server.outbound?.(this.server.current) : null;
    this.active = { session: s, displayId: target.id, width: target.pixelWidth, height: target.pixelHeight, transport: this.server.current.transport, detailOwner };
    Object.assign(this.view, { display: target.label, width, height, fps: 0, mbps: 0 });
    this._setStatus('starting');
    console.log(`[stream] session ${s} (${reason}): ${target.label} ${target.pixelWidth}x${target.pixelHeight} -> ${width}x${height}`);
    this.server.sendToClient({ t: P.T.STREAM_INFO, name: target.label, width, height, audio: !!audio });
    try {
      await this._ensureWindow();
      if (!this.active || this.active.session !== s) return;
      const src = await this._source(target);
      if (!this.active || this.active.session !== s || this.displays.target()?.id !== target.id) return;
      const set = this.getSettings();
      this._toWindow('start', {
        session: s, bitrateMbps: set.bitrateMbps, // Share screen › Quality, for phones too
        sourceId: src.id, width, height, audio,
        detailSource: detailOwner ? { width: target.pixelWidth, height: target.pixelHeight } : null,
        ice: (this.server.current && this.server.current.ice) || null, // a phone on the USB cable: through the relay
        fps: ScreenCodec.fps(target.hz, set.sharing && set.sharing.fps), // Share screen › Frame rate
        steady: !!(set.sharing && set.sharing.pace === 'steady'), // Playback › Steady (shared/screencodec.js)
        codec: ScreenCodec.mode(set.sharing && set.sharing.codec), // Share screen › Encoder
      });
    } catch (e) {
      if (!this.active || this.active.session !== s) return;
      if (e.code === 'NO_DISPLAY') { this.displays.uncapturable?.(target.id); return this._waitDisplay(); }
      // The rejection isn't always an Error (Screen Recording not allowed): say what it was.
      const why = (e && e.message) || util.inspect(e);
      console.error(`[stream] start failed: ${why} (Screen Recording: ${systemPreferences.getMediaAccessStatus('screen')})`);
      this._setStatus(`error: ${why}`);
      this._scheduleRetry();
    }
  }

  // Capture size: the display's pixels, scaled down to settings.streamMaxHeight if that is smaller.
  // Encoding 4K costs ~30 ms of latency on an M3; a GPU downscale to 1440p costs almost nothing.
  // A phone too: its Receive screen page has the same Resolution (pair.sync 'res').
  _outSize(d) {
    const max = this.getSettings().streamMaxHeight;
    const k = max && d.pixelHeight > max ? max / d.pixelHeight : 1;
    if (k >= 1) return { width: d.pixelWidth, height: d.pixelHeight };
    return { width: Math.round((d.pixelWidth * k) / 2) * 2, height: Math.round((d.pixelHeight * k) / 2) * 2 };
  }

  _phone() {
    return !!(this.server.current && P.isPhoneOs(this.server.current.os));
  }

  // Advances when the selected display id changes, including a return to an id
  // that was current earlier. A desktop switch captured the previous number.
  noteViewIdentity() {
    const Spaces = require('../shared/mac-spaces.js');
    if (!this.viewSlot) this.viewSlot = { key: null, generation: 0 };
    let id = '';
    try {
      const want = this.displays.target();
      if (want && want.id != null) id = String(want.id);
    } catch (_) { id = 'err'; }
    return Spaces.noteGeneration(this.viewSlot, `default:${id}:${this.session}`);
  }

  // The display this viewer is being shown, or null while the picture is off or still catching
  // up with a newly picked screen. A desktop switch uses this and no other display.
  // generation is the selection epoch above, so A→B→A does not look unchanged.
  viewedDisplay() {
    const generation = this.noteViewIdentity();
    const view = require('../shared/mac-spaces.js').viewedDisplay({
      viewer: this.viewer,
      waitingPolicy: this.waitingPolicy,
      sharing: this.getSettings().sharing.on === true,
      activeId: this.active ? this.active.displayId : null,
      want: this.displays.target(),
    });
    if (!view) return null;
    // session is the capture that active names. It is assigned before a frame is decoded.
    const session = this.active && this.active.session;
    return { ...view, generation, session };
  }

  _displaysChanged() {
    this.noteViewIdentity();
    if (!this.active) {
      if (this.awaitingDisplay && this.displays.target()) this.restart('display available');
      return;
    }
    const t = this.displays.target();
    if (!t || t.id !== this.active.displayId || t.pixelWidth !== this.active.width || t.pixelHeight !== this.active.height) {
      this.restart('display changed');
    }
  }

  _waitDisplay() {
    this._stopWindow('no display to share', true);
    this.awaitingDisplay = true;
  }

  _stopWindow(status, waiting = false) {
    this.session++;
    this.awaitingDisplay = false;
    if (!waiting) this.displays.captureWanted?.(this, false);
    clearTimeout(this.retryTimer);
    this._releaseAudio();
    this.audio.on = false;
    this.active = null;
    this._toWindow('stop', {});
    Object.assign(this.view, { fps: 0, mbps: 0 });
    this._setStatus(status);
    clearTimeout(this.dropTimer);
    if (this.win) this.dropTimer = setTimeout(() => this._drop(), DROP_MS);
  }

  // The capture window and its renderer, gone while there's nobody to share to.
  _drop() {
    if (this.active || !this.win || (this.server.current && this.getSettings().sharing.on)) return;
    const w = this.win;
    this.win = null;
    if (!w.isDestroyed()) w.destroy();
  }

  // Sharing off: tell Windows too, so it shows "Mac is not sharing".
  stop(status = 'off') {
    if (this.server.current) this.server.sendToClient({ t: P.T.STREAM_STOP });
    this._stopWindow(status);
  }
}

module.exports = { Stream };