sueta / client / src / app / call.ts
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
 * Room calls (Discord-style): anyone joins the room's single call; membership
 * and mic/cam state travel as E2E-sealed datachannel messages; media rides the
 * existing per-pair RTCPeerConnections (DTLS-SRTP, peer to peer). Members not
 * in the call exchange zero media. docs/PROTOCOL.md §9.
 */

import type { Mesh } from "../lib/mesh";
import type { PeerConnState } from "../lib/protocol";

export interface CallMember {
  audio: boolean;
  video: boolean;
  name: string;
  stream?: MediaStream;
  staleTimer?: ReturnType<typeof setTimeout>;
}

export interface CallSelf {
  micOn: boolean;
  camOn: boolean;
}

interface CallWire {
  kind: "call";
  op: "join" | "state" | "leave";
  audio?: boolean;
  video?: boolean;
  seq?: number;
  ts?: number;
  name?: string;
}

const AUDIO_WARN = 8;
const VIDEO_MAX = 4;
const VIDEO_KBPS = 450;
// coturn allows 5 Mbps per allocation — relayed legs can carry full quality
const VIDEO_KBPS_RELAYED = 450;
const STALE_MS = 15_000;

const isIOS = () => /iP(hone|ad|od)/.test(navigator.userAgent) || (navigator.maxTouchPoints > 1 && /Mac/.test(navigator.userAgent));

export class CallManager {
  #mesh: Mesh;
  #myName: () => string;
  #local: MediaStream | null = null;
  #wakeLock: { release(): Promise<void> } | null = null;
  #relayed = new Set<string>();

  status: "idle" | "in-call" = "idle";
  micOn = true;
  camOn = false;
  members = new Map<string, CallMember>();

  onRoster: (self: CallSelf | null, members: Map<string, CallMember>) => void = () => {};
  onCallStarted: (fromPeer: string, fromName: string, seq: number) => void = () => {};
  onError: (msg: string) => void = () => {};
  /** UI warning channel (scale limits etc.). */
  onNotice: (msg: string) => void = () => {};

  constructor(mesh: Mesh, myName: () => string) {
    this.#mesh = mesh;
    this.#myName = myName;
    document.addEventListener("visibilitychange", () => {
      if (document.visibilityState === "visible" && this.status === "in-call") void this.#recoverTracks();
    });
  }

  get localStream(): MediaStream | null {
    return this.#local;
  }

  /** Anyone (me or others) in the call? Drives the callbar visibility. */
  get active(): boolean {
    return this.status === "in-call" || this.members.size > 0;
  }

  async join(withVideo: boolean): Promise<void> {
    if (this.status === "in-call") return;
    if (this.members.size + 1 > AUDIO_WARN) this.onNotice(`mesh calls degrade past ${AUDIO_WARN} people`);
    if (withVideo && this.#videoCount() >= VIDEO_MAX) {
      withVideo = false;
      this.onNotice(`camera is limited to ${VIDEO_MAX} in a room call — joined with mic only`);
    }
    try {
      this.#local = await navigator.mediaDevices.getUserMedia({
        audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
        ...(withVideo ? { video: videoConstraints() } : {}),
      });
    } catch {
      this.onError("microphone/camera permission denied");
      return;
    }
    this.status = "in-call";
    this.micOn = true;
    this.camOn = withVideo;
    void this.#wake();
    this.#broadcast("join");
    for (const peerId of this.members.keys()) this.#attach(peerId);
    this.onRoster(this.self(), this.members);
  }

  leave(): void {
    if (this.status !== "in-call") return;
    this.#broadcast("leave");
    this.#mesh.detachAllMedia();
    this.#local?.getTracks().forEach((t) => t.stop());
    this.#local = null;
    this.status = "idle";
    this.camOn = false;
    void this.#wakeLock?.release().catch(() => {});
    this.#wakeLock = null;
    this.onRoster(null, this.members);
  }

  toggleMic(): void {
    const track = this.#local?.getAudioTracks()[0];
    if (!track) return;
    this.micOn = !this.micOn;
    track.enabled = this.micOn;
    this.#broadcast("state");
    this.onRoster(this.self(), this.members);
  }

  async toggleCam(): Promise<void> {
    if (!this.#local) return;
    if (!this.camOn) {
      if (this.#videoCount() >= VIDEO_MAX) {
        this.onNotice(`camera is limited to ${VIDEO_MAX} in a room call`);
        return;
      }
      try {
        if (isIOS()) {
          // iOS: a second getUserMedia can kill the live mic — re-acquire both
          const fresh = await navigator.mediaDevices.getUserMedia({
            audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
            video: videoConstraints(),
          });
          this.#local.getTracks().forEach((t) => t.stop());
          this.#local = fresh;
          this.#local.getAudioTracks()[0].enabled = this.micOn;
        } else {
          const cam = await navigator.mediaDevices.getUserMedia({ video: videoConstraints() });
          this.#local.addTrack(cam.getVideoTracks()[0]);
        }
      } catch {
        this.onError("camera unavailable");
        return;
      }
      this.camOn = true;
    } else {
      for (const t of this.#local.getVideoTracks()) {
        t.stop();
        this.#local.removeTrack(t);
      }
      this.camOn = false;
    }
    for (const peerId of this.members.keys()) this.#attach(peerId);
    this.#broadcast("state");
    this.onRoster(this.self(), this.members);
  }

  self(): CallSelf | null {
    return this.status === "in-call" ? { micOn: this.micOn, camOn: this.camOn } : null;
  }

  // mesh event handlers (wired in main.ts)

  onWire(from: string, raw: unknown): void {
    const p = raw as CallWire;
    if (p?.kind !== "call") return;
    const name = String(p.name ?? "?").slice(0, 40);
    if (p.op === "leave") {
      this.#dropMember(from);
      if (this.status === "in-call") this.#mesh.detachMedia(from);
    } else if (p.op === "join" || p.op === "state") {
      const first = this.members.size === 0 && this.status !== "in-call";
      const m = this.members.get(from) ?? { audio: true, video: false, name };
      m.audio = p.audio !== false;
      m.video = p.video === true;
      m.name = name;
      this.members.set(from, m);
      if (p.op === "join") {
        if (first && typeof p.seq === "number") this.onCallStarted(from, name, p.seq);
        if (this.status === "in-call") void this.#mesh.sendTo(from, this.#statePayload("state"));
      }
      if (this.status === "in-call") this.#attach(from);
    }
    this.onRoster(this.self(), this.members);
  }

  onChannelOpen(peer: string): void {
    if (this.status === "in-call") void this.#mesh.sendTo(peer, this.#statePayload("state"));
  }

  onPeerGone(peer: string): void {
    this.#dropMember(peer);
    this.onRoster(this.self(), this.members);
  }

  onPeerState(peer: string, state: PeerConnState): void {
    if (state === "relayed") this.#relayed.add(peer);
    else if (state === "direct") this.#relayed.delete(peer);
    const m = this.members.get(peer);
    if (!m) return;
    if (state === "disconnected") {
      m.staleTimer ??= setTimeout(() => {
        this.#dropMember(peer);
        this.onRoster(this.self(), this.members);
      }, STALE_MS);
    } else if (m.staleTimer) {
      clearTimeout(m.staleTimer);
      m.staleTimer = undefined;
    }
    if (this.status === "in-call" && (state === "direct" || state === "relayed")) this.#attach(peer);
  }

  onTrack(peer: string, stream: MediaStream): void {
    const m = this.members.get(peer);
    if (!m) return;
    m.stream = stream;
    this.onRoster(this.self(), this.members);
  }

  // internals

  #attach(peerId: string): void {
    if (!this.#local) return;
    this.#mesh.attachMedia(peerId, this.#local, {
      maxVideoKbps: this.#relayed.has(peerId) ? VIDEO_KBPS_RELAYED : VIDEO_KBPS,
    });
  }

  #dropMember(peer: string): void {
    const m = this.members.get(peer);
    if (m?.staleTimer) clearTimeout(m.staleTimer);
    this.members.delete(peer);
  }

  #videoCount(): number {
    let n = this.camOn ? 1 : 0;
    for (const m of this.members.values()) if (m.video) n++;
    return n;
  }

  #statePayload(op: "join" | "state" | "leave"): Record<string, unknown> {
    return { kind: "call", op, audio: this.micOn, video: this.camOn, seq: Date.now() % 1e9, ts: Date.now(), name: this.#myName() };
  }

  #broadcast(op: "join" | "state" | "leave"): void {
    void this.#mesh.broadcast(this.#statePayload(op));
  }

  async #wake(): Promise<void> {
    try {
      this.#wakeLock = await (navigator as Navigator & { wakeLock?: { request(t: string): Promise<{ release(): Promise<void> }> } }).wakeLock?.request("screen") ?? null;
    } catch {}
  }

  /** iOS ends tracks under screen lock — re-acquire or degrade honestly. */
  async #recoverTracks(): Promise<void> {
    if (!this.#local) return;
    const dead = this.#local.getTracks().some((t) => t.readyState === "ended");
    if (!dead) return void this.#wake();
    try {
      const fresh = await navigator.mediaDevices.getUserMedia({
        audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
        ...(this.camOn ? { video: videoConstraints() } : {}),
      });
      this.#local.getTracks().forEach((t) => t.stop());
      this.#local = fresh;
      this.#local.getAudioTracks()[0].enabled = this.micOn;
      for (const peerId of this.members.keys()) this.#attach(peerId);
    } catch {
      this.camOn = false;
      this.#broadcast("state");
    }
    void this.#wake();
    this.onRoster(this.self(), this.members);
  }
}

function videoConstraints(): MediaTrackConstraints {
  return { facingMode: "user", width: { ideal: 640 }, height: { ideal: 480 }, frameRate: { ideal: 24, max: 30 } };
}