Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat(screenshare): direct-cast screenshare over a plain RTCPeerConnection (#17553)
Emil Ivovd38e93388c1e
diff --git a/conference.js b/conference.jsindex 9d275377c7..594e58499d 100644--- a/conference.js+++ b/conference.js@@ -6,6 +6,7 @@ import Logger from '@jitsi/logger';import { ENDPOINT_TEXT_MESSAGE_NAME } from './modules/API/constants';import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';import Recorder from './modules/recorder/Recorder';+import ExternalShareReceiver from './modules/screenshare-cast/ExternalShareReceiver';import { createTaskQueue } from './modules/util/helpers';import {createDeviceChangedEvent,@@ -1220,6 +1221,7 @@ export default {APP.store.dispatch(stopReceiver());this._stopProxyConnection();+ this._stopExternalShare();APP.store.dispatch(toggleScreenshotCaptureSummary(false));const tracks = APP.store.getState()['features/base/tracks'];@@ -2118,6 +2120,7 @@ export default {APP.store.dispatch(disableReceiver());this._stopProxyConnection();+ this._stopExternalShare();APP.store.dispatch(destroyLocalTracks());this._localTracksInitialized = false;@@ -2313,6 +2316,78 @@ export default {this._proxyConnection.processMessage(event);},+ /**+ * Handle a direct-cast screenshare signalling message from a remote sharer.+ *+ * Direct-cast is the successor to the {@code ProxyConnectionService} path above: a+ * remote sharer (e.g. a laptop) opens a PLAIN RTCPeerConnection straight to this+ * Jitsi Meet instance and adds its screen — and optionally system audio — tracks.+ * {@link ExternalShareReceiver} terminates that peer connection here and Jitsi moves+ * the received track(s) into the conference as the local screenshare. No+ * ProxyConnectionService, no Jingle, no XMPP/Strophe JIDs, and audio comes along for+ * free.+ *+ * @param {Object} signal - The signalling message ({ kind, sdp | candidate }).+ * @returns {void}+ */+ onExternalShareSignal(signal) {+ // A fresh offer begins a new cast session. If a receiver is already around (a+ // second/reconnecting sharer, or a stale one whose PC died), tear it down first+ // rather than feeding the new offer into the old — possibly already-published —+ // peer connection, where _publish's once-only guard would swallow it.+ // Optional chaining: signal is embedder-supplied, so it may be malformed/absent.+ if (signal?.kind === 'offer') {+ this._stopExternalShare();+ }++ if (!this._externalShare) {+ this._externalShare = new ExternalShareReceiver({++ // Reuse the meeting's own TURN credentials — the same source the old+ // proxy borrowed — minus the XMPP signalling.+ pcConfig: APP.connection?.xmpp?.connection?.jingle?.p2pIceConfig,++ onSignal: out => APP.API.sendExternalShareSignal(out),++ onTracks: ({ desktopVideoTrack, desktopAudioTrack }) => {+ APP.store.dispatch(toggleScreensharingA(true, false, {+ desktopStream: desktopVideoTrack,+ desktopAudioTrack+ }));+ },++ onClosed: ({ spontaneous, published } = {}) => {+ // If the sharer's connection dropped on its own (ICE failure, laptop+ // closed, sharer navigated away) while a share was live, the published+ // screenshare is now frozen in the meeting — take it down. Explicit+ // teardowns (hangup / _stopExternalShare) are driven from the conference+ // and remove the share through their own path, so we skip it there.+ if (spontaneous && published) {+ APP.store.dispatch(toggleScreensharingA(false, false));+ }++ this._externalShare = null;+ }+ });+ }++ this._externalShare.handleSignal(signal);+ },++ /**+ * Terminates any direct-cast screenshare connection that is active.+ *+ * @private+ * @returns {void}+ */+ _stopExternalShare() {+ if (this._externalShare) {+ this._externalShare.stop();+ }++ this._externalShare = null;+ },+/*** Sets the video muted status.*/diff --git a/modules/API/API.js b/modules/API/API.jsindex ce279ad22f..c27f31f279 100755--- a/modules/API/API.js+++ b/modules/API/API.js@@ -336,6 +336,12 @@ function initCommands() {'proxy-connection-event': event => {APP.conference.onProxyConnectionEvent(event);},+ 'external-share-signal': signal => {+ // Direct-cast screenshare — a plain RTCPeerConnection signalling message+ // from a remote sharer, the successor to 'proxy-connection-event'. See+ // conference.onExternalShareSignal.+ APP.conference.onExternalShareSignal(signal);+ },'reject-participant': (participantId, mediaType) => {if (!isLocalParticipantModerator(APP.store.getState())) {return;@@ -1354,6 +1360,21 @@ class API {});}+ /**+ * Notifies the external application (the sharer, via the embedder) of a direct-cast+ * screenshare signalling message (answer / ICE candidate). The successor to+ * {@link sendProxyConnectionEvent}; plain SDP/ICE, no Jingle.+ *+ * @param {Object} signal - The signalling message to pass back to the sharer.+ * @returns {void}+ */+ sendExternalShareSignal(signal) {+ this._sendEvent({+ name: 'external-share-signal',+ signal+ });+ }+/*** Sends event to the external application.*diff --git a/modules/API/external/external_api.js b/modules/API/external/external_api.jsindex 49c2e013dc..60f7c1a6ef 100644--- a/modules/API/external/external_api.js+++ b/modules/API/external/external_api.js@@ -135,6 +135,7 @@ const events = {'email-change': 'emailChange','error-occurred': 'errorOccurred','endpoint-text-message-received': 'endpointTextMessageReceived',+ 'external-share-signal': 'externalShareSignal','face-landmark-detected': 'faceLandmarkDetected','feedback-submitted': 'feedbackSubmitted','feedback-prompt-displayed': 'feedbackPromptDisplayed',@@ -1487,6 +1488,22 @@ export default class JitsiMeetExternalAPI extends EventEmitter {});}+ /**+ * Sends a direct-cast screenshare signalling message (offer / ICE candidate / stop)+ * from the sharer INTO this meeting's Jitsi Meet. The successor to+ * {@link sendProxyConnectionEvent} — plain SDP/ICE over a vanilla RTCPeerConnection,+ * no Jingle, no XMPP. The meeting answers via the {@code externalShareSignal} event.+ *+ * @param {Object} signal - The signalling message ({ kind, sdp | candidate }).+ * @returns {void}+ */+ sendExternalShareSignal(signal) {+ this._transport.sendEvent({+ data: [ signal ],+ name: 'external-share-signal'+ });+ }+/*** Sets the audio input device to the one with the label or id that is* passed.diff --git a/modules/screenshare-cast/ExternalShareReceiver.js b/modules/screenshare-cast/ExternalShareReceiver.jsnew file mode 100644index 0000000000..622bdabaa2--- /dev/null+++ b/modules/screenshare-cast/ExternalShareReceiver.js@@ -0,0 +1,253 @@+import Logger from '@jitsi/logger';++import JitsiMeetJS from '../../react/features/base/lib-jitsi-meet';++const logger = Logger.getLogger('modules/screenshare-cast/ExternalShareReceiver');++/**+ * ExternalShareReceiver — direct-cast wireless screenshare, RECEIVER side.+ *+ * A remote sharer (e.g. a laptop) opens a PLAIN RTCPeerConnection straight to THIS+ * Jitsi Meet instance and adds its screen — and, optionally, system audio — tracks.+ * We terminate that peer connection here, take the track(s) off `pc.ontrack`, wrap+ * them as JitsiLocalTracks via the public+ * {@code JitsiMeetJS.createLocalTracksFromMediaStreams}, and hand them to the+ * conference as the local screenshare. No lib-jitsi-meet ProxyConnectionService, no+ * Jingle, no XMPP/Strophe JIDs.+ *+ * This replaces the brittle ProxyConnectionService path. The shape — terminate the+ * peer connection at the TV's Jitsi Meet and let Jitsi move the tracks from this+ * "proxy" PC into the conference PC — is exactly what Spot's screenshare always did,+ * minus the Jingle/XMPP plumbing that made it Chromium-only and audio-less. Built on a+ * vanilla RTCPeerConnection so screenshare audio rides along for free and Firefox/Safari+ * are no longer locked out the way ProxyConnectionService locked them.+ *+ * Signalling is plain JSON, carried over any transport the embedder wires up (e.g. the+ * iframe external API) — never XMPP:+ * { kind: 'offer', sdp } sharer → here (answered with { kind:'answer', sdp })+ * { kind: 'answer', sdp } here → sharer+ * { kind: 'candidate', candidate } both ways+ * { kind: 'stop' } sharer → here (tears down)+ */+export default class ExternalShareReceiver {+ /**+ * @param {Object} options+ * @param {RTCConfiguration} [options.pcConfig] - ICE config for the peer+ * connection. The meeting's own TURN creds work here (same source the old proxy+ * borrowed) — just without the Jingle.+ * @param {Function} options.onSignal - Emit a signalling message back to the+ * sharer: {@code (signal) => void}.+ * @param {Function} options.onTracks - Publish the received screenshare:+ * {@code ({ desktopVideoTrack, desktopAudioTrack }) => void}.+ * @param {Function} [options.onClosed] - Invoked once when the connection closes:+ * {@code ({ published, spontaneous }) => void}. {@code published} is whether a share+ * had been handed to the conference; {@code spontaneous} is whether the peer+ * connection dropped on its own (vs. an explicit {@link stop}).+ */+ constructor({ pcConfig, onSignal, onTracks, onClosed }) {+ this._onSignal = onSignal;+ this._onTracks = onTracks;+ this._onClosed = onClosed;++ this._desktopVideoTrack = null;+ this._desktopAudioTrack = null;+ this._published = false;+ this._closed = false;+ this._spontaneous = false;++ if (!pcConfig) {+ // Don't fail outright — a same-LAN sharer can still connect with host+ // candidates — but make the missing TURN/STUN loud: a remote sharer behind+ // NAT will silently never reach 'connected' without it.+ logger.warn('external share: no ICE config supplied; the peer connection has '+ + 'no STUN/TURN servers, so only same-LAN sharers will connect');+ }++ const pc = new RTCPeerConnection(pcConfig || {});++ this._pc = pc;++ pc.addEventListener('icecandidate', ({ candidate }) => {+ if (candidate) {+ this._onSignal({+ kind: 'candidate',+ candidate: candidate.toJSON()+ });+ }+ });++ pc.addEventListener('connectionstatechange', () => {+ const state = pc.connectionState;++ logger.info(`external share pc state: ${state}`);++ if (state === 'connected') {+ // By the time the PC is connected, ontrack has fired for every track in+ // the offer, so we know whether audio is present. Publish exactly once.+ this._publish();+ } else if (state === 'failed' || state === 'closed') {+ // Terminal only. 'disconnected' is deliberately NOT treated as terminal —+ // it is frequently a transient blip that recovers back to 'connected', so+ // tearing the cast down on it would drop the share on a momentary glitch.+ // The peer connection dropped on its own — flag it so the conference can+ // tear down a now-frozen published share (see onClosed).+ this._spontaneous = true;+ this.stop();+ }+ });++ pc.addEventListener('track', ({ track }) => this._collectTrack(track));+ }++ /**+ * Handle one inbound signalling message from the sharer.+ *+ * Messages are processed strictly in arrival order: callers don't await us, so we+ * chain on an internal queue. Without it a trickled {@code candidate} could run its+ * {@code addIceCandidate} before the preceding {@code offer}'s asynchronous+ * {@code setRemoteDescription} has resolved — which throws ("remote description was+ * null") and silently drops the candidate.+ *+ * @param {Object} signal - The signalling message (see class doc for shapes).+ * @returns {Promise<void>}+ */+ handleSignal(signal) {+ this._signalQueue = (this._signalQueue || Promise.resolve())+ .then(() => this._processSignal(signal));++ return this._signalQueue;+ }++ /**+ * Process a single inbound signalling message. Serialized by {@link handleSignal}.+ *+ * @param {Object} signal - The signalling message (see class doc for shapes).+ * @private+ * @returns {Promise<void>}+ */+ async _processSignal(signal) {+ if (!signal || this._closed) {+ return;+ }++ try {+ if (signal.kind === 'offer') {+ await this._pc.setRemoteDescription(signal.sdp);+ const answer = await this._pc.createAnswer();++ await this._pc.setLocalDescription(answer);++ // Emit a plain { type, sdp } so it survives structured-clone over+ // whatever transport carries it (an RTCSessionDescription may not).+ this._onSignal({+ kind: 'answer',+ sdp: {+ type: this._pc.localDescription.type,+ sdp: this._pc.localDescription.sdp+ }+ });+ } else if (signal.kind === 'candidate' && signal.candidate) {+ await this._pc.addIceCandidate(signal.candidate);+ } else if (signal.kind === 'stop') {+ this.stop();+ }+ } catch (error) {+ // Signalling failed (bad SDP, unexpected state, etc.) — the connection can't+ // be salvaged, so tear it down rather than hang half-negotiated. Flag it as+ // spontaneous so a share that did get published is taken back down.+ logger.error('external share signal handling failed', error);+ this._spontaneous = true;+ this.stop();+ }+ }++ /**+ * Wrap a received MediaStreamTrack as a JitsiLocalTrack and stash it until publish.+ *+ * @param {MediaStreamTrack} track - A track arriving over the peer connection.+ * @private+ * @returns {void}+ */+ _collectTrack(track) {+ const isVideo = track.kind === 'video';++ try {+ // Each received track gets its OWN single-track MediaStream:+ // createLocalTracksFromMediaStreams throws if a stream holds 0 or >1 tracks+ // of the requested kind. Guard the call (it runs inside the 'track' event)+ // so an unexpected/extra track can't leave the handler with an uncaught+ // throw and a half-collected state.+ const stream = new MediaStream([ track ]);++ const [ jitsiTrack ] = JitsiMeetJS.createLocalTracksFromMediaStreams([ {+ stream,+ track,+ mediaType: track.kind,+ sourceType: 'proxy',+ deviceId: 'proxy:screenshare-cast',+ videoType: isVideo ? 'desktop' : undefined+ } ]);++ if (isVideo) {+ this._desktopVideoTrack = jitsiTrack;+ } else {+ this._desktopAudioTrack = jitsiTrack;+ }++ logger.info(`external share collected ${track.kind} track`);+ } catch (error) {+ logger.error(`external share failed to wrap ${track.kind} track`, error);+ }+ }++ /**+ * Hand the collected screenshare track(s) to the conference, exactly once.+ *+ * @private+ * @returns {void}+ */+ _publish() {+ if (this._published || !this._desktopVideoTrack) {+ return;+ }++ this._published = true;+ logger.info(`external share publishing (audio: ${Boolean(this._desktopAudioTrack)})`);+ this._onTracks({+ desktopVideoTrack: this._desktopVideoTrack,+ desktopAudioTrack: this._desktopAudioTrack+ });+ }++ /**+ * Tear down the peer connection. Idempotent.+ *+ * @returns {void}+ */+ stop() {+ if (this._closed) {+ return;+ }++ this._closed = true;++ try {+ this._pc.close();+ } catch (error) {+ // already torn down+ }++ // Dispose the wrapped track(s) regardless of whether they were published — a+ // double dispose is harmless, and on a pre-'connected' failure nobody else owns+ // them, so this is the only thing that stops them leaking.+ this._desktopVideoTrack?.dispose();+ this._desktopAudioTrack?.dispose();+ this._desktopVideoTrack = null;+ this._desktopAudioTrack = null;++ this._onClosed?.({+ published: this._published,+ spontaneous: this._spontaneous+ });+ }+}diff --git a/react/features/base/tracks/actions.web.ts b/react/features/base/tracks/actions.web.tsindex 18ea717d6f..235c11e8a9 100644--- a/react/features/base/tracks/actions.web.ts+++ b/react/features/base/tracks/actions.web.ts@@ -146,9 +146,16 @@ async function _toggleScreenSharing(if (enable) {let tracks;- // Spot proxy stream.+ // Spot proxy stream / direct-cast screenshare.if (shareOptions.desktopStream) {tracks = [ shareOptions.desktopStream ];++ // A direct-cast share can carry system audio as a second track. Include it+ // so it rides the native screenshare-audio path below (AudioMixer effect ++ // setScreenshareAudioTrack), exactly like a locally-captured share.+ if (shareOptions.desktopAudioTrack) {+ tracks.push(shareOptions.desktopAudioTrack);+ }} else {const { _desktopSharingSourceDevice } = state['features/base/config'];diff --git a/react/features/base/tracks/types.ts b/react/features/base/tracks/types.tsindex 6cc23dffe3..a1e99ea361 100644--- a/react/features/base/tracks/types.ts+++ b/react/features/base/tracks/types.ts@@ -72,6 +72,11 @@ export interface IToggleScreenSharingOptions {export type DesktopSharingSourceType = 'screen' | 'window';export interface IShareOptions {+ // Direct-cast screenshare: a screenshare arriving over a plain RTCPeerConnection can+ // carry system audio too. When present alongside+ // desktopStream, this audio track is published via the native screenshare-audio+ // path (AudioMixer effect + setScreenshareAudioTrack).+ desktopAudioTrack?: any;desktopSharingSourceDevice?: string;desktopSharingSources?: Array<DesktopSharingSourceType>;desktopStream?: any;