feat(session): changer de source en plein partage sans reconnecter
CI / Formatting, tests and builds (push) Successful in 4m44s

L'hôte ouvre la nouvelle source, la met à la place de l'ancienne dans
SwitchableMedia, puis seulement arrête l'ancienne: les sessions passent
à la nouvelle capture à l'image suivante, avec une image clé, sans
renégociation ni nouveau QR code. Si le portail refuse, l'ancienne
source reste partagée et l'interface le dit.

La room publie la source; chaque connexion envoie source_changed (nature
et taille, jamais un titre de fenêtre), que le viewer affiche quelques
secondes sans quitter le plein écran. La coque gagne un bouton « Changer
de source » pendant le partage.

Refs #26

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guillaume ASSIERandClaude Opus 5.5 committed 2026-10-30 15:34:56 +01:00
1 parent 8c36876989
commit 1b4a153d4a
15 files changed
+329 -19

No files matched your search

+3 -3
View File
@@ -15,7 +15,7 @@ Ce qui tourne: capture Linux réelle (portail et PipeWire sous Wayland, X11 en r
moniteur RandR, une fenêtre seule), écran virtuel par le portail (GNOME 46, KDE), conversion BGRA
vers I420, encodage VP8 ou VP9 temps réel qui suit les changements de résolution, session str0m par
spectateur, serveur local avec jeton qui expire et code court, appareils de confiance qui reviennent sans lien
par une clé Ed25519 (ADR 0011), viewer React qui reprend seul après
par une clé Ed25519 (ADR 0011), changement de source en plein partage sans reconnexion, viewer React qui reprend seul après
une coupure ou une veille, tourne l'image et suit le thème, coque desktop Tauri avec icône de
barre système, réglages persistants, interface en français et en anglais, inhibition de veille,
journal JSON local et archive de diagnostics.
@@ -192,8 +192,8 @@ Le journal JSON (`~/.local/state/rustscreen/logs`) nomme les étapes d'une sessi
(avec `cause`), `capture_revoked`, `capture_failed`, `encode_failed`, et côté hôte `share_started`,
`share_ended`, `share_interrupted`, `viewer_disconnected`, `resolution_changed`, `sleep_inhibited`,
`sleep_released`, `wake_detected`, `capture_restarted`, `address_changed`, `settings_changed`,
`access_regenerated`, `code_accepted`, `code_rejected`, `trust_changed`, et côté serveur
`trusted_device_admitted`. Avant la 0.6, ces noms étaient en français
`access_regenerated`, `code_accepted`, `code_rejected`, `trust_changed`, `source_switched`,
`source_switch_failed`, et côté serveur `trusted_device_admitted`. Avant la 0.6, ces noms étaient en français
(champ `evenement`). Ne jamais y écrire un titre de fenêtre ni une image (ADR 0008).
Le spike historique `spikes/str0m-mire` reste pour comparer les mesures:
+12
View File
@@ -86,6 +86,17 @@ async fn trust_device(host: State<'_, Host>, connection: u64) -> Result<(), Stri
host.trust_device(connection).await
}
#[tauri::command]
async fn switch_source(
host: State<'_, Host>,
last: State<'_, LastSource>,
choice: SourceChoice,
) -> Result<(), String> {
host.switch_source(choice.clone()).await?;
*last.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(choice);
Ok(())
}
#[tauri::command]
async fn revoke_device(host: State<'_, Host>, key: String) -> Result<(), String> {
host.revoke_device(&key).await
@@ -263,6 +274,7 @@ fn main() {
regenerate_access,
trust_device,
revoke_device,
switch_source,
translate_tray,
quit,
settings,
+47 -3
View File
@@ -37,6 +37,8 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
const [sending, setSending] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [confirmQuit, setConfirmQuit] = useState(false);
// Picking another source while sharing (#26): viewers stay connected.
const [switching, setSwitching] = useState(false);
const [theme, setTheme] = useState<Theme>('system');
// The state comes from the host, always complete: subscribe before reading,
@@ -112,6 +114,13 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
}
};
const portal = selection?.type === 'portal';
const live = state.phase === 'live' && state.share !== null;
const picking = switching && live;
const switchTo = (choice: SourceChoice) =>
send(async () => {
await host.switchSource(choice);
setSwitching(false);
});
return (
<div className='app'>
@@ -134,7 +143,7 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
<main className='content'>
<Banners state={state} />
{state.phase === 'live' && state.share ? (
{state.phase === 'live' && state.share && !picking ? (
<SharePanel
share={state.share}
onDisconnect={(connection) => send(() => host.disconnect(connection))}
@@ -145,7 +154,7 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
<SourcePicker
sources={sources}
selection={selection}
enabled={buttons.pick}
enabled={buttons.pick || picking}
onPick={setSelection}
onRefresh={refresh}
/>
@@ -153,12 +162,47 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n
</main>
<footer className='action-bar'>
{state.phase === 'starting' && (
{(state.phase === 'starting' || (picking && sending)) && (
<p className='waiting' role='status'>
{portal ? t('waitingDesktop') : t('waiting')}
</p>
)}
<span className='spacer' />
{picking && (
<>
<button
type='button'
className='button'
disabled={sending}
onClick={() => setSwitching(false)}
>
{t('cancel')}
</button>
<button
type='button'
className='button primary'
disabled={!selection || sending}
onClick={() => selection && switchTo(selection)}
>
{t('switchTo')}
</button>
</>
)}
{live && !picking && (
<button
type='button'
className='button'
title={t('switchHelp')}
disabled={sending}
onClick={() => {
setSelection(null);
refresh();
setSwitching(true);
}}
>
{t('switchSource')}
</button>
)}
{buttons.start.visible && (
<button
type='button'
+3
View File
@@ -27,6 +27,8 @@ export type Host = {
trustDevice(connection: number): Promise<void>;
/** Stops trusting a key; a device connected with it is sent away. */
revokeDevice(key: string): Promise<void>;
/** Shares another source without cutting viewers off (#26). */
switchSource(choice: SourceChoice): Promise<void>;
settings(): Promise<Settings>;
/** Rejects with the list of refused values. */
updateSettings(settings: Settings): Promise<SettingsOutcome>;
@@ -50,6 +52,7 @@ export const tauriHost: Host = {
regenerateAccess: () => invoke<boolean>('regenerate_access'),
trustDevice: (connection) => invoke<void>('trust_device', { connection }),
revokeDevice: (key) => invoke<void>('revoke_device', { key }),
switchSource: (choice) => invoke<void>('switch_source', { choice }),
settings: () => invoke<Settings>('settings'),
updateSettings: (settings) => invoke<SettingsOutcome>('update_settings', { settings }),
interfaces: () => invoke<InterfaceOption[]>('interfaces'),
+21
View File
@@ -21,6 +21,9 @@ import { type VideoStats, ViewerSession, type ViewerState } from './lib/session'
import { applyTheme, nextTheme, readTheme, saveTheme, type Theme } from './lib/theme';
import { isTrusted } from './lib/trust';
import { useActivity } from './lib/useActivity';
import type { SourceInfo } from './proto';
const SWITCH_NOTICE_MS = 2500;
export function App() {
const { t } = useI18n();
@@ -44,6 +47,7 @@ export function App() {
const [mirror, setMirror] = useState(() => readMirror());
const [pinned, setPinned] = useState(() => readPinned());
const [held, setHeld] = useState(false);
const [switched, setSwitched] = useState<SourceInfo | null>(null);
const active = useActivity(IDLE_DELAY_MS);
const sessionRef = useRef<ViewerSession | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
@@ -59,6 +63,7 @@ export function App() {
wsUrl: signalingUrl(window.location),
onState: setState,
onStream: setStream,
onSourceChanged: setSwitched,
});
sessionRef.current = session;
session.start();
@@ -85,6 +90,13 @@ export function App() {
};
}, [state.kind]);
// The notice of a source switch stays briefly, then goes.
useEffect(() => {
if (!switched) return;
const timer = setTimeout(() => setSwitched(null), SWITCH_NOTICE_MS);
return () => clearTimeout(timer);
}, [switched]);
useEffect(() => {
const onChange = () => setIsFullscreen(Boolean(document.fullscreenElement));
document.addEventListener('fullscreenchange', onChange);
@@ -269,6 +281,15 @@ export function App() {
rotation={rotation}
mirror={mirror}
/>
{switched && (
<div className='switch-notice' role='status'>
{t('sourceChanged', {
kind: t(`sourceKinds.${switched.kind}`),
width: switched.width,
height: switched.height,
})}
</div>
)}
{state.kind === 'failed' && <ErrorPanel state={state} onRetry={retry} />}
</main>
+41
View File
@@ -116,3 +116,44 @@ describe('coming back by key (#34)', () => {
expect(states.at(-1)).toEqual({ kind: 'failed', code: 'not_trusted' });
});
});
describe('source switch (#26)', () => {
beforeEach(() => {
vi.stubGlobal('WebSocket', ScriptedWebSocket);
vi.stubGlobal('RTCPeerConnection', StubPeerConnection);
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('reports the new source without leaving the session', async () => {
const states: ViewerState[] = [];
const switched: unknown[] = [];
const viewer = new ViewerSession({
room: 'abc234',
token: '0123456789abcdef0123456789abcdef',
key: null,
wsUrl: 'ws://127.0.0.1:1/ws',
watchLifecycle: false,
onState: (state) => states.push(state),
onStream: () => undefined,
onSourceChanged: (source) => switched.push(source),
});
viewer.start();
await Promise.resolve();
const source = {
id: 'x11',
kind: 'window',
name: '',
width: 800,
height: 600,
available: true,
};
ScriptedWebSocket.last?.answer({ type: 'source_changed', source });
await Promise.resolve();
expect(switched).toEqual([source]);
expect(states.some((s) => s.kind === 'failed' || s.kind === 'reconnecting')).toBe(false);
viewer.stop();
});
});
+13 -3
View File
@@ -8,7 +8,13 @@
*/
import { PROTOCOL_VERSION } from '../proto';
import type { ClientMessage, DeviceInfo, ServerMessage, StreamSettings } from '../proto';
import type {
ClientMessage,
DeviceInfo,
ServerMessage,
SourceInfo,
StreamSettings,
} from '../proto';
import type { Translate } from './i18n';
import { deviceId } from './device';
import { type WakeReason, watchLifecycle } from './lifecycle';
@@ -56,6 +62,8 @@ export type SessionOptions = {
watchLifecycle?: boolean;
onState: (state: ViewerState) => void;
onStream: (stream: MediaStream | null) => void;
/** The host switched source during the share (#26): the stream stays. */
onSourceChanged?: (source: SourceInfo) => void;
};
/** Codes after which retrying is useless: the host refuses on principle. */
@@ -360,9 +368,11 @@ export class ViewerSession {
// resume would overwrite the user's choice.
break;
case 'source_changed':
// The frames switch on the host side, in the same track: no
// renegotiation, the full screen and the stats go on (#26).
this.options.onSourceChanged?.(message.source);
break;
case 'ice_candidate':
// The stream is replaced on the host side; nothing to do here
// before the issue on hot source switching.
break;
default:
break;
+14
View File
@@ -425,3 +425,17 @@ body {
transition: none;
}
}
/* Brief notice of a source switch (#26): over the picture, never in the way. */
.switch-notice {
position: absolute;
top: 1rem;
left: 50%;
transform: translateX(-50%);
padding: 0.4rem 0.9rem;
border-radius: 999px;
background: var(--veil);
color: var(--fg);
font-size: 0.9rem;
pointer-events: none;
}
+68 -7
View File
@@ -578,6 +578,7 @@ impl Host {
.with_validity(validity(settings.code_validity_min)),
);
room.set_trusted(trusted_keys(&settings));
room.set_source(source_info(&source));
let server = self.spawn_server(listener, tls.clone(), room.clone(), media.clone());
let inhibition = match Inhibition::acquire("screen sharing in progress").await {
@@ -748,15 +749,61 @@ impl Host {
});
}
/// Shares another source in the same room, without cutting anyone off
/// (#26): viewers keep their connection, their token and their full
/// screen, and get the new picture at the next keyframe. If the new source
/// cannot be opened (portal refused), the current one stays shared.
pub async fn switch_source(&self, choice: SourceChoice) -> Result<(), String> {
let source = match self.replace_capture(Some(choice)).await {
Ok(source) => source,
Err(error) => {
tracing::warn!(event = "source_switch_failed", %error, "source not switched");
self.warn(format!(
"Source not switched, the previous one is still shared: {error}"
));
return Err(error);
}
};
if let Some(source) = source {
tracing::info!(
event = "source_switched",
backend = %source.backend,
width = source.width,
height = source.height,
"shared source switched"
);
}
self.refresh();
Ok(())
}
/// Restarts the capture of a share whose source stopped during sleep,
/// without changing room: viewers resume on their own.
async fn restart_capture(&self) -> Result<(), String> {
if self.replace_capture(None).await?.is_some() {
tracing::info!(
event = "capture_restarted",
"capture restarted after wake-up"
);
}
Ok(())
}
/// Opens a capture (`choice`, or the current one again) and puts it in
/// place of the running one. Returns the new source, `None` without a
/// share. The old capture is stopped only once the new one runs.
async fn replace_capture(
&self,
choice: Option<SourceChoice>,
) -> Result<Option<SharedSource>, String> {
let mut active = self.0.active.lock().await;
let Some(opened) = active.as_mut() else {
return Ok(());
return Ok(None);
};
let switching = choice.is_some();
let choice = choice.unwrap_or_else(|| opened.choice.clone());
let started = capture::start(
&opened.choice,
&choice,
&opened.settings,
opened.codec,
self.0.portal.as_ref(),
@@ -766,8 +813,13 @@ impl Host {
let old_media = opened.media.replace(started.media);
let old_live = std::mem::replace(&mut opened.live, started.live.clone());
let old_portal = std::mem::replace(&mut opened.portal, started.portal);
opened.choice = choice;
if let Some(view) = lock(&self.0.view).as_mut() {
view.live = started.live;
view.source = started.source.clone();
}
if switching {
opened.room.set_source(source_info(&started.source));
}
drop(active);
if let Some(session) = old_portal {
@@ -775,11 +827,7 @@ impl Host {
}
// Stopping a capture joins its thread: outside the runtime.
let _ = tokio::task::spawn_blocking(move || drop((old_media, old_live))).await;
tracing::info!(
event = "capture_restarted",
"capture restarted after wake-up"
);
Ok(())
Ok(Some(started.source))
}
// -- State ------------------------------------------------------------------
@@ -1129,6 +1177,19 @@ async fn watch_sleep(weak: Weak<Inner>) {
}
/// How long an access stays valid, `None` for no limit.
/// The source as the viewer sees it. A window title stays on the host: the
/// viewer learns the kind and the size, which is what it shows (#26).
fn source_info(source: &SharedSource) -> rs_proto::SourceInfo {
rs_proto::SourceInfo {
id: rs_proto::SourceId(source.backend.clone()),
kind: source.kind,
name: String::new(),
width: source.width,
height: source.height,
available: true,
}
}
/// The keys the room checks, from the saved list. An entry without a usable
/// key (written before #34) lets nobody in.
fn trusted_keys(settings: &Settings) -> Vec<rs_signaling::TrustedKey> {
+51
View File
@@ -289,6 +289,57 @@ async fn a_trusted_device_comes_back_without_a_link_until_revoked() {
host.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn switching_source_keeps_the_viewer_and_tells_it() {
if no_network() {
return;
}
let (host, _dir) = host("switch", 0).await;
host.start(test_pattern()).await.expect("share");
let (port, room, token) = identifiers(&host.state().share.unwrap().url);
let (mut ws, welcome) = viewer(port, &room, &token, "tablet").await;
assert_eq!(welcome["source"]["width"], 64, "{welcome}");
let mut states = host.subscribe();
let before = tokio::time::timeout(
Duration::from_secs(3),
states.wait_for(|s| s.share.as_ref().is_some_and(|p| p.devices.len() == 1)),
)
.await
.unwrap()
.unwrap()
.share
.clone()
.unwrap()
.devices[0]
.connection;
let start = std::time::Instant::now();
host.switch_source(SourceChoice::Synthetic {
width: 128,
height: 96,
})
.await
.expect("switched");
let told = next(&mut ws).await;
assert!(start.elapsed() < Duration::from_secs(1), "switch too slow");
assert_eq!(told["type"], "source_changed", "{told}");
assert_eq!(told["source"]["width"], 128);
assert_eq!(told["source"]["height"], 96);
assert_eq!(
told["source"]["name"], "",
"no window title leaves the host"
);
// Same connection: no reconnection, nothing to scan again.
let share = host.state().share.unwrap();
assert_eq!(share.devices.len(), 1);
assert_eq!(share.devices[0].connection, before);
assert_eq!(share.source.width, 128);
assert_eq!(share.url, host.state().share.unwrap().url);
host.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn stopping_tells_viewers_the_share_ended_and_frees_the_port() {
if no_network() {
+19 -2
View File
@@ -251,7 +251,9 @@ pub struct Room {
/// Devices admitted at least once: they come back with an old or expired
/// token of this room, a resume is not a new entry.
admitted: Mutex<Vec<String>>,
pub source: Option<SourceInfo>,
/// The shared source. The host may replace it during the share (#26):
/// every connection watches it and tells its viewer.
source: watch::Sender<Option<SourceInfo>>,
pub settings: StreamSettings,
limit: AtomicU8,
connected: AtomicU8,
@@ -280,7 +282,7 @@ impl Room {
validity: Mutex::new(None),
attempts: Mutex::new(Attempts::default()),
admitted: Mutex::new(Vec::new()),
source,
source: watch::Sender::new(source),
settings,
limit: AtomicU8::new(limit.max(1)),
connected: AtomicU8::new(0),
@@ -301,6 +303,21 @@ impl Room {
self
}
/// The source being shared, as the viewer sees it.
pub fn source(&self) -> Option<SourceInfo> {
self.source.borrow().clone()
}
/// Announces a new source to every connected viewer (#26).
pub fn set_source(&self, source: SourceInfo) {
self.source.send_replace(Some(source));
}
/// Gets notified when the host switches source.
pub fn watch_source(&self) -> watch::Receiver<Option<SourceInfo>> {
self.source.subscribe()
}
/// The current token, the one the QR code carries.
pub fn token(&self) -> SessionToken {
lock(&self.access).token.clone()
+13 -1
View File
@@ -640,7 +640,7 @@ async fn handle_socket(mut socket: WebSocket, state: Arc<AppState>, peer: Socket
let welcome = ServerMessage::Welcome {
version: PROTOCOL_VERSION,
room: state.room.id.clone(),
source: state.room.source.clone(),
source: state.room.source(),
settings: state.room.settings,
connected,
limit: state.room.limit(),
@@ -655,8 +655,20 @@ async fn handle_socket(mut socket: WebSocket, state: Arc<AppState>, peer: Socket
// right away, not at its next connection (#34).
let mut changes = state.room.subscribe();
let mut trusted = by_key;
// The source announced in the welcome is seen: only a switch is told.
let mut sources = state.room.watch_source();
sources.mark_unchanged();
let cause = loop {
tokio::select! {
Ok(()) = sources.changed() => {
// The frames switch on their own (the shared media follows the
// new capture, with a keyframe): the viewer only needs to know,
// to show it. No renegotiation (#26).
let source = sources.borrow_and_update().clone();
if let Some(source) = source {
let _ = send(&mut socket, &ServerMessage::SourceChanged { source }).await;
}
}
Ok(()) = changes.changed() => {
let now = is_trusted(&state.room, key.as_deref());
// Came in by its key and lost it: it is being sent away with
+8
View File
@@ -57,6 +57,14 @@ capture et l'encodeur vivent dans un thread unique, et chaque session reçoit un
son propre curseur sur la dernière image publiée. Un spectateur qui rejoint demande une image clé
(`request_keyframe`), sinon son décodeur attendrait la suivante, parfois plusieurs secondes.
**Changer de source ne renégocie rien** (#26). `SwitchableMedia` délègue à une capture
remplaçable: l'hôte ouvre la nouvelle source, la met en place, puis seulement arrête l'ancienne;
chaque session passe à la nouvelle capture à l'image suivante, avec une image clé. Le codec reste
celui du partage (les sessions l'ont négocié), la résolution peut changer: VP8 et VP9 la portent
dans l'image clé, et le navigateur suit sans nouvelle offre SDP. Le spectateur reçoit
`source_changed` (nature et taille, jamais le titre d'une fenêtre) et l'affiche brièvement. Si la
nouvelle source est refusée, par exemple au portail, l'ancienne reste partagée.
Le partage n'est pas une optimisation de confort : avec un encodeur par spectateur, trois sessions
720p tombaient à 16 i/s et la troisième échouait sur une machine à un cœur. Le détail des mesures
est dans `docs/perf.md`.
+8
View File
@@ -50,6 +50,11 @@
"insecureHint": "The page and signalling travel unencrypted on the local network. The video stream itself is encrypted end to end (DTLS-SRTP).",
"trustedBadge": "Trusted",
"trustedHint": "The host trusts this device: open this address again to come back, without a QR code.",
"sourceChanged": "Now showing: {kind}, {width} × {height}",
"sourceKinds": {
"screen": "a screen",
"window": "a window"
},
"networkFallback": "Connection lost. Check that you are on the same network as the host.",
"errors": {
"bad_token": "This link matches no session on this host. Scan its QR code again, or type its short code.",
@@ -84,6 +89,9 @@
"start": "Start sharing",
"cancel": "Cancel",
"stop": "Stop sharing",
"switchSource": "Change source",
"switchHelp": "Share another screen or window: viewers stay connected.",
"switchTo": "Share this source",
"waitingDesktop": "The desktop is asking for permission to share: answer its window to continue.",
"waiting": "Opening the capture…",
"scan": "Scan to watch",
+8
View File
@@ -50,6 +50,11 @@
"insecureHint": "La page et le signalement circulent en clair sur le réseau local. Le flux vidéo, lui, est chiffré de bout en bout (DTLS-SRTP).",
"trustedBadge": "De confiance",
"trustedHint": "L'hôte fait confiance à cet appareil : rouvrez cette adresse pour revenir, sans QR code.",
"sourceChanged": "Source changée : {kind}, {width} × {height}",
"sourceKinds": {
"screen": "un écran",
"window": "une fenêtre"
},
"networkFallback": "Connexion perdue. Vérifiez que vous êtes sur le même réseau que l’hôte.",
"errors": {
"bad_token": "Ce lien ne correspond à aucune session de cet hôte. Scannez à nouveau son QR code, ou tapez son code court.",
@@ -84,6 +89,9 @@
"start": "Démarrer le partage",
"cancel": "Annuler",
"stop": "Arrêter le partage",
"switchSource": "Changer de source",
"switchHelp": "Partager un autre écran ou une autre fenêtre : les spectateurs restent connectés.",
"switchTo": "Partager cette source",
"waitingDesktop": "Le bureau demande l’autorisation de partager: répondez à sa fenêtre pour continuer.",
"waiting": "Ouverture de la capture…",
"scan": "Scannez pour regarder",