// One viewing session of a TS6 screenshare (P2P path). DOM-free: the RTCPeerConnection factory is injected. // // Wire (server text channel, via core `stream_*` commands / `stream` events): // join → joinstreamrequest id clid msg is_remove=0 // offer ← notifyrespondjoinstreamrequest decision=1 offer= // answer → streamsignaling json={"cmd":"answer","args":{"answer":}} // ICE ↔ {"cmd":"iceCandidate","args":{"mLine","mid","sdp"}} // realign← {"cmd":"offer"|"reconnectOffer","args":{"offer":}} must be answered or media never starts // leave → joinstreamrequest … is_remove=1 export const JOIN_TIMEOUT_MS = 90_000; /** Terminal states: no further signaling is accepted once one is reached. */ const TERMINAL = new Set(['declined', 'ended', 'removed', 'failed', 'stopped', 'unsupported']); export class StreamViewerSession { /** * @param {object} o * @param {string} o.streamId * @param {number} o.clientId streamer clid * @param {number} o.ownClientId * @param {string} o.message join message (our nickname) * @param {{join:Function, send:Function, leave:Function}} o.signal async core calls * @param {(config:object)=>RTCPeerConnection} o.createPeerConnection * @param {RTCIceServer[]} [o.iceServers] * @param {(state:string, detail?:string)=>void} [o.onState] * @param {(track:MediaStreamTrack)=>void} [o.onTrack] * @param {(level:string, msg:string)=>void} [o.log] * @param {(fn:Function, ms:number)=>any} [o.setTimer] * @param {(id:any)=>void} [o.clearTimer] */ constructor(o) { this.streamId = String(o.streamId); this.clientId = Number(o.clientId); this.ownClientId = Number(o.ownClientId); this.message = o.message ?? ''; this.signal = o.signal; this.createPeerConnection = o.createPeerConnection; this.iceServers = o.iceServers ?? []; this.onState = o.onState ?? (() => {}); this.onTrack = o.onTrack ?? (() => {}); this.log = o.log ?? (() => {}); this.setTimer = o.setTimer ?? ((fn, ms) => setTimeout(fn, ms)); this.clearTimer = o.clearTimer ?? ((id) => clearTimeout(id)); this.state = 'idle'; this.detail = ''; this.pc = null; this.queue = Promise.resolve(); this.pendingRemote = []; this.pendingLocal = []; this.answersSent = 0; this.offersApplied = 0; this.remoteCandidatesAdded = 0; this.staleCandidates = 0; this.candidateErrors = 0; this.joinTimer = null; } get closed() { return TERMINAL.has(this.state); } async start() { this._setState('requesting'); this.joinTimer = this.setTimer(() => { if (this.state === 'requesting') this._finish('failed', 'no_response', true); }, JOIN_TIMEOUT_MS); try { await this.signal.join(this.streamId, this.clientId, this.message); this.log('info', `watch: join sent id=${this.streamId} clid=${this.clientId}`); } catch (err) { if (!this.closed) this._finish('failed', describe(err), false); } } /** User stopped or cancelled. Sends is_remove=1 unless the stream is already gone. */ stop() { if (this.closed) return; this._finish('stopped', '', true); } /** The stream or the connection went away underneath us: no leave command. */ terminate(reason) { if (this.closed) return; this._finish('ended', reason, false); } /** True when the notification belongs to this session (stream id + streamer/our clid). */ matches(item) { if (!item || String(item.id) !== this.streamId) return false; if (item.clid === undefined || item.clid === '') return true; const clid = Number(item.clid); return clid === this.clientId || clid === this.ownClientId; } /** Feeds one `stream` event item. Returns true when consumed. */ handle(name, item) { if (this.closed) return false; switch (name) { case 'notifyrespondjoinstreamrequest': { if (!this.matches(item)) return false; this._clearJoinTimer(); const offer = typeof item.offer === 'string' ? item.offer : ''; if (item.decision === '1' && offer) { this.log('info', `watch: join accepted, offer ${offer.length} chars (clid field=${item.clid ?? '-'})`); this._enqueue(() => this._applyOffer(offer, 'join')); } else { this.log('info', `watch: join declined decision=${item.decision ?? '-'}`); this._finish('declined', item.msg || '', false); } return true; } case 'notifystreamsignaling': { if (!this.matches(item)) return false; let message; try { message = JSON.parse(item.json ?? ''); } catch { this.log('warn', 'watch: unparseable signaling json'); return true; } this._onSignal(message); return true; } case 'notifystreamstopped': { if (String(item.id) !== this.streamId) return false; this._finish('ended', 'stream_stopped', false); return true; } case 'notifystreamclientleft': { if (String(item.id) !== this.streamId) return false; if (Number(item.clid) === this.ownClientId) { this._finish('removed', '', false); return true; } return false; } case 'notifysfuaccessinfo': { // The server routes this stream through its SFU (mediasoup); TeamsPeach only speaks the P2P path. if (this.state === 'requesting' || this.matches(item)) { this._finish('unsupported', 'sfu', true); return true; } return false; } default: return false; } } _onSignal(message) { const cmd = message && message.cmd; const args = (message && message.args) || {}; switch (cmd) { case 'offer': case 'reconnectOffer': { const sdp = typeof args.offer === 'string' ? args.offer : typeof args.sdp === 'string' ? args.sdp : ''; if (!sdp) { this.log('warn', `watch: ${cmd} without sdp`); return; } this.log('info', `watch: ${cmd} received (${sdp.length} chars)`); this._enqueue(() => this._applyOffer(sdp, cmd)); return; } case 'iceCandidate': this._enqueue(() => this._addRemoteCandidate(args)); return; default: this.log('info', `watch: ignored signaling cmd=${String(cmd)}`); } } _ensurePc() { if (this.pc) return this.pc; const pc = this.createPeerConnection({ iceServers: this.iceServers }); this.pc = pc; pc.onicecandidate = (event) => { const c = event.candidate; if (!c || !c.candidate || this.closed) return; const msg = { cmd: 'iceCandidate', args: { mLine: c.sdpMLineIndex ?? 0, mid: c.sdpMid ?? String(c.sdpMLineIndex ?? 0), sdp: c.candidate }, }; if (this.answersSent === 0) this.pendingLocal.push(msg); else this._send(msg).catch(() => {}); }; pc.ontrack = (event) => { if (!this.closed) this.onTrack(event.track); }; pc.onconnectionstatechange = () => { if (this.closed) return; const s = pc.connectionState; this.log('info', `watch: connectionState=${s}`); if (s === 'connected') this._setState('live'); else if (s === 'disconnected') this._setState('unstable'); else if (s === 'failed') this._finish('failed', 'ice_failed', true); }; return pc; } async _applyOffer(sdp, reason) { if (this.closed) return; const pc = this._ensurePc(); if (this.state === 'requesting') this._setState('connecting'); if (pc.signalingState === 'have-remote-offer') { // A newer offer superseded one we never answered: discard the stale one. await pc.setRemoteDescription({ type: 'rollback' }); } await pc.setRemoteDescription({ type: 'offer', sdp }); if (this.closed) return; this.offersApplied += 1; await this._flushRemoteCandidates(); const answer = await pc.createAnswer(); if (this.closed) return; await pc.setLocalDescription(answer); if (this.closed) return; await this._send({ cmd: 'answer', args: { answer: pc.localDescription.sdp } }); if (this.closed) return; this.answersSent += 1; this.log('info', `watch: answer sent for ${reason} (#${this.answersSent})`); const local = this.pendingLocal.splice(0); for (const msg of local) this._send(msg).catch(() => {}); } async _addRemoteCandidate(args) { if (this.closed) return; const sdp = typeof args.sdp === 'string' ? args.sdp : typeof args.candidate === 'string' ? args.candidate : ''; if (!sdp) return; // end-of-candidates marker const mLine = Number(args.mLine); const init = { candidate: sdp, sdpMid: args.mid === undefined || args.mid === null ? null : String(args.mid), sdpMLineIndex: Number.isInteger(mLine) ? mLine : null, }; if (init.sdpMid === null && init.sdpMLineIndex === null) init.sdpMLineIndex = 0; if (!this.pc || !this.pc.remoteDescription) { this.pendingRemote.push(init); return; } await this._addCandidate(init); } async _flushRemoteCandidates() { const list = this.pendingRemote.splice(0); for (const init of list) await this._addCandidate(init); } async _addCandidate(init) { const ufrag = candidateUfrag(init.candidate); const current = remoteUfrags(this.pc.remoteDescription?.sdp ?? ''); if (ufrag && current.size > 0 && !current.has(ufrag)) { // Belongs to an ICE generation replaced by a newer (reconnect) offer: skip deliberately. this.staleCandidates += 1; this.log('info', `watch: skipped candidate of previous ICE generation (${this.staleCandidates})`); return; } try { await this.pc.addIceCandidate(init); this.remoteCandidatesAdded += 1; } catch (err) { this.candidateErrors += 1; this.log('warn', `watch: current-generation candidate rejected (mid=${init.sdpMid} mLine=${init.sdpMLineIndex}): ${describe(err)}`); } } /** No signaling leaves a closed session, so nothing can follow our is_remove=1. */ _send(json) { if (this.closed) return Promise.resolve(); return this.signal.send(this.streamId, this.clientId, json).catch((err) => { this.log('warn', `watch: signaling send failed: ${describe(err)}`); throw err; }); } _enqueue(task) { this.queue = this.queue.then(task).catch((err) => { if (!this.closed) this._finish('failed', describe(err), true); }); return this.queue; } _clearJoinTimer() { if (this.joinTimer !== null) { this.clearTimer(this.joinTimer); this.joinTimer = null; } } _finish(state, detail, sendLeave) { if (this.closed) return; this._clearJoinTimer(); this.pendingRemote = []; this.pendingLocal = []; if (this.pc) { this.pc.onicecandidate = null; this.pc.ontrack = null; this.pc.onconnectionstatechange = null; try { this.pc.close(); } catch { // already closed } } this._setState(state, detail); if (sendLeave) { this.signal.leave(this.streamId, this.clientId).catch((err) => this.log('info', `watch: leave failed: ${describe(err)}`)); } } _setState(state, detail = '') { this.state = state; this.detail = detail; this.onState(state, detail); } } /** `ufrag` attribute of an ICE candidate line, if present. */ export function candidateUfrag(candidate) { const m = / ufrag (\S+)/.exec(candidate); return m ? m[1] : null; } /** All `a=ice-ufrag` values of the applied remote description. */ export function remoteUfrags(sdp) { const set = new Set(); for (const m of sdp.matchAll(/^a=ice-ufrag:(\S+)/gm)) set.add(m[1]); return set; } function describe(err) { if (!err) return 'unknown'; if (typeof err === 'string') return err; return err.code ? `${err.code}: ${err.message ?? ''}` : String(err.message ?? err); }