cautpartener / client / src / lib / media.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/**
 * Media-only WebRTC for room calls (PROTOCOL.md v2 §calls). libp2p's WebRTC
 * transport carries data only, so calls run their own per-pair
 * RTCPeerConnections carrying nothing but audio/video (DTLS-SRTP, own
 * ICE/TURN). SDP/ICE ride sealed signaling envelopes (kSig — the same keys
 * and AADs as v1 signaling) over the /sueta/2/call-sig/1.0 libp2p stream, so
 * an established call keeps flowing even if the libp2p path dies — signaling
 * is only needed for (re)negotiation.
 *
 * The negotiation machinery — perfect negotiation with politeness, transceiver
 * reuse, replaceTrack mutes, restartIce + deterministic rebuild — is lifted
 * from the v1 mesh (lib/mesh.ts) minus everything datachannel.
 */

import type { Envelope, RoomCrypto } from "./crypto";
import type { Net } from "./net";
import type { SignalPayload } from "./protocol";
import type { IceConfig } from "./turn";

export const CALL_SIG_PROTOCOL = "/sueta/2/call-sig/1.0";
const FAILED_REBUILD_MS = 10_000;

export interface MediaEvents {
  track(peer: string, stream: MediaStream): void;
  /** The MEDIA path's transport class (drives bitrate caps), not libp2p's. */
  mediaState(peer: string, state: "direct" | "relayed"): void;
}

class MediaPeer {
  readonly id: string;
  readonly polite: boolean;
  pc!: RTCPeerConnection;
  makingOffer = false;
  ignoreOffer = false;
  settingRemoteAnswer = false;
  pendingCandidates: (RTCIceCandidateInit | null)[] = [];
  wantedStream: MediaStream | null = null;
  maxVideoKbps?: number;
  mediaQueue: Promise<void> = Promise.resolve();
  queue: Promise<void> = Promise.resolve(); // serializes signal handling
  rebuildTimer: ReturnType<typeof setTimeout> | null = null;

  constructor(id: string, myId: string) {
    this.id = id;
    this.polite = myId < id; // deterministic, asymmetric per pair
  }

  destroy(): void {
    if (this.rebuildTimer) clearTimeout(this.rebuildTimer);
    try {
      this.pc?.close();
    } catch {}
  }
}

export class Media {
  #crypto: RoomCrypto;
  #ice: IceConfig;
  #net: Net;
  #myName: () => string;
  #ev: MediaEvents;
  #peers = new Map<string, MediaPeer>();
  #closed = false;

  constructor(opts: { crypto: RoomCrypto; ice: IceConfig; net: Net; myName: () => string; events: MediaEvents }) {
    this.#crypto = opts.crypto;
    this.#ice = opts.ice;
    this.#net = opts.net;
    this.#myName = opts.myName;
    this.#ev = opts.events;
    void this.#net.handleFrames(CALL_SIG_PROTOCOL, (from, frame) => void this.#onSigFrame(from, frame));
  }

  /**
   * Declaratively set the media sent to one peer; creates the media pc on
   * first use. Diffs against current senders; a stream missing a kind
   * soft-mutes it. Survives pc rebuilds.
   */
  attachMedia(peerId: string, stream: MediaStream, opts?: { maxVideoKbps?: number }): void {
    if (this.#closed) return;
    let peer = this.#peers.get(peerId);
    if (!peer) {
      peer = new MediaPeer(peerId, this.#net.myId);
      this.#peers.set(peerId, peer);
      void this.#setupPC(peer);
    }
    peer.wantedStream = stream;
    if (opts?.maxVideoKbps !== undefined) peer.maxVideoKbps = opts.maxVideoKbps;
    peer.mediaQueue = peer.mediaQueue.then(() => this.#applyMedia(peer));
  }

  /** Stop sending AND receiving media with this peer. */
  detachMedia(peerId: string): void {
    const peer = this.#peers.get(peerId);
    if (!peer?.pc) return;
    peer.wantedStream = null;
    peer.mediaQueue = peer.mediaQueue.then(async () => {
      if (peer.wantedStream) return; // re-attached since — skip the stale detach
      for (const t of peer.pc.getTransceivers()) {
        if (t.receiver.track?.kind === undefined) continue;
        await t.sender.replaceTrack(null).catch(() => {});
        try {
          t.direction = "inactive";
        } catch {}
      }
    });
  }

  detachAllMedia(): void {
    for (const id of [...this.#peers.keys()]) this.detachMedia(id);
  }

  /** Tear down the pair's media pc entirely (peer left the call/room). */
  dropPeer(peerId: string): void {
    const peer = this.#peers.get(peerId);
    if (!peer) return;
    peer.destroy();
    this.#peers.delete(peerId);
  }

  close(): void {
    this.#closed = true;
    for (const p of this.#peers.values()) p.destroy();
    this.#peers.clear();
  }

  debugState(): Record<string, unknown>[] {
    return [...this.#peers.values()].map((p) => ({
      id: p.id,
      conn: p.pc?.connectionState,
      sending: p.pc
        ?.getSenders()
        .filter((s) => s.track)
        .map((s) => s.track!.kind),
    }));
  }

  // ---- pc lifecycle (lifted from mesh.ts) ----------------------------------

  async #setupPC(peer: MediaPeer): Promise<void> {
    const config = await this.#ice.get();
    if (this.#closed || peer.pc) return;
    const pc = new RTCPeerConnection(config);
    peer.pc = pc;

    pc.ontrack = (e) => {
      const stream = e.streams[0] ?? new MediaStream([e.track]);
      this.#ev.track(peer.id, stream);
    };

    pc.onnegotiationneeded = async () => {
      try {
        peer.makingOffer = true;
        await pc.setLocalDescription();
        this.#sendSignal(peer.id, { kind: "offer", sdp: pc.localDescription!.sdp, name: this.#myName() });
      } catch (err) {
        console.warn("call negotiation failed", err);
      } finally {
        peer.makingOffer = false;
      }
    };
    pc.onicecandidate = (e) => {
      this.#sendSignal(peer.id, {
        kind: "ice",
        candidate: e.candidate ? e.candidate.toJSON() : null,
        name: this.#myName(),
      });
    };
    pc.onconnectionstatechange = () => {
      switch (pc.connectionState) {
        case "connected":
          if (peer.rebuildTimer) {
            clearTimeout(peer.rebuildTimer);
            peer.rebuildTimer = null;
          }
          void this.#classifyTransport(peer);
          break;
        case "failed":
          pc.restartIce();
          peer.rebuildTimer ??= setTimeout(() => {
            peer.rebuildTimer = null;
            // deterministic single re-initiator avoids a double rebuild
            if (isDead(pc) && this.#net.myId < peer.id) void this.#rebuild(peer);
          }, FAILED_REBUILD_MS);
          break;
      }
    };

    // rebuild path: a fresh pc must get the media the app still wants
    if (peer.wantedStream) void this.#applyMedia(peer);
  }

  async #applyMedia(peer: MediaPeer): Promise<void> {
    const pc = peer.pc;
    if (!pc || pc.connectionState === "closed") return;
    for (const kind of ["audio", "video"] as const) {
      const want = peer.wantedStream?.getTracks().find((t) => t.kind === kind) ?? null;
      const tx = pc.getTransceivers().find((t) => t.receiver.track?.kind === kind);
      try {
        if (want) {
          if (tx) {
            if (tx.sender.track !== want) await tx.sender.replaceTrack(want);
            if (tx.direction !== "sendrecv") tx.direction = "sendrecv";
          } else {
            pc.addTrack(want, peer.wantedStream!);
          }
        } else if (tx?.sender.track) {
          await tx.sender.replaceTrack(null); // soft mute — no renegotiation
        }
      } catch (err) {
        console.warn("applyMedia", kind, err);
      }
    }
    // bitrate cap on the video sender (relayed pairs can get a lower cap)
    const vSender = pc.getSenders().find((s) => s.track?.kind === "video");
    if (vSender && peer.maxVideoKbps) {
      try {
        const p = vSender.getParameters();
        p.encodings = p.encodings?.length ? p.encodings : [{}];
        p.encodings[0].maxBitrate = peer.maxVideoKbps * 1000;
        await vSender.setParameters(p);
      } catch {}
    }
  }

  // ---- sealed signaling over the libp2p stream -----------------------------

  #sendSignal(to: string, payload: SignalPayload): void {
    void this.#crypto
      .sealSignal(to, payload)
      .then((env) => this.#net.sendFrame(CALL_SIG_PROTOCOL, to, new TextEncoder().encode(JSON.stringify(env))))
      .catch(() => {});
  }

  async #onSigFrame(from: string, frame: Uint8Array): Promise<void> {
    let env: Envelope;
    try {
      env = JSON.parse(new TextDecoder().decode(frame)) as Envelope;
    } catch {
      return;
    }
    const payload = (await this.#crypto.openSignal(from, env)) as SignalPayload | null;
    if (payload === null) return; // not a member — drop silently (v1 §3)
    let peer = this.#peers.get(from);
    if (!peer) {
      // callee side: the offerer's first signal creates our media pc
      peer = new MediaPeer(from, this.#net.myId);
      this.#peers.set(from, peer);
      await this.#setupPC(peer);
    }
    const p = peer;
    p.queue = p.queue.then(() => this.#handleSignal(p, payload)); // serialize per peer
  }

  async #handleSignal(peer: MediaPeer, payload: SignalPayload): Promise<void> {
    const pc = peer.pc;
    try {
      if (payload.kind === "offer" || payload.kind === "answer") {
        const description: RTCSessionDescriptionInit = { type: payload.kind, sdp: payload.sdp };
        const readyForOffer = !peer.makingOffer && (pc.signalingState === "stable" || peer.settingRemoteAnswer);
        const offerCollision = description.type === "offer" && !readyForOffer;
        peer.ignoreOffer = !peer.polite && offerCollision;
        if (peer.ignoreOffer) return;
        peer.settingRemoteAnswer = description.type === "answer";
        await pc.setRemoteDescription(description);
        peer.settingRemoteAnswer = false;
        for (const c of peer.pendingCandidates.splice(0)) await this.#addCandidate(peer, c);
        if (description.type === "offer") {
          await pc.setLocalDescription();
          this.#sendSignal(peer.id, { kind: "answer", sdp: pc.localDescription!.sdp, name: this.#myName() });
        }
      } else if (payload.kind === "ice") {
        if (!pc.remoteDescription) {
          peer.pendingCandidates.push(payload.candidate);
        } else {
          await this.#addCandidate(peer, payload.candidate);
        }
      }
    } catch (err) {
      console.warn("call signal handling failed", err);
    }
  }

  async #addCandidate(peer: MediaPeer, candidate: RTCIceCandidateInit | null): Promise<void> {
    try {
      await peer.pc.addIceCandidate(candidate ?? undefined);
    } catch (err) {
      if (!peer.ignoreOffer) console.warn("addIceCandidate failed", err);
    }
  }

  async #classifyTransport(peer: MediaPeer): Promise<void> {
    try {
      const stats = await peer.pc.getStats();
      let selected: RTCIceCandidatePairStats | undefined;
      const locals = new Map<string, { candidateType?: string }>();
      stats.forEach((s) => {
        if (s.type === "local-candidate") locals.set(s.id, s as { candidateType?: string });
        if (s.type === "candidate-pair" && (s as RTCIceCandidatePairStats).nominated && s.state === "succeeded") {
          selected = s as RTCIceCandidatePairStats;
        }
        if (s.type === "transport" && (s as { selectedCandidatePairId?: string }).selectedCandidatePairId) {
          const pair = stats.get((s as { selectedCandidatePairId: string }).selectedCandidatePairId);
          if (pair) selected = pair as RTCIceCandidatePairStats;
        }
      });
      const local = selected && locals.get(selected.localCandidateId);
      this.#ev.mediaState(peer.id, local?.candidateType === "relay" ? "relayed" : "direct");
    } catch {
      this.#ev.mediaState(peer.id, "direct");
    }
  }

  async #rebuild(peer: MediaPeer): Promise<void> {
    const stream = peer.wantedStream;
    const kbps = peer.maxVideoKbps;
    this.dropPeer(peer.id);
    if (stream) {
      this.attachMedia(peer.id, stream, kbps !== undefined ? { maxVideoKbps: kbps } : undefined);
    }
  }
}

function isDead(pc: RTCPeerConnection | undefined): boolean {
  return !pc || pc.connectionState === "failed" || pc.connectionState === "closed";
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git