From ab1cc4e12e5a007bdbc9d80c2f8f9010c263c72f Mon Sep 17 00:00:00 2001 From: AAA <35992542+TNTcraftHIM@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:08:31 -0500 Subject: [PATCH] feat(connection): show current media preparation and source capabilities --- docs/todo.md | 34 ++++------ prototype/channel-native/src/peer.rs | 3 + prototype/channel-native/src/peer/metrics.rs | 2 + .../src/peer/tests/transport.rs | 22 ++++++- prototype/channel-native/src/session.rs | 9 ++- .../src/session/composition_tests.rs | 63 +++++++++++++++++++ src/client/channel/app-link.ts | 2 +- .../channel/components/ChannelConnections.tsx | 7 ++- .../channel/components/ChannelMedia.tsx | 12 ++-- .../channel/components/ChannelVoiceRooms.tsx | 20 ++++-- .../components/channel-voice-rooms.css | 6 +- src/client/channel/media.ts | 32 +++++----- src/client/channel/presentation.ts | 4 +- src/client/channel/session.ts | 2 +- src/client/channel/types.ts | 8 ++- src/client/channel/use-voice-playback.ts | 28 ++++++--- .../components/living/CaptureSourcePicker.tsx | 4 +- src/client/locales/en.ts | 3 + src/client/locales/zh.ts | 3 + src/client/pages/ChannelPage.tsx | 6 +- src/client/pages/ChannelRoomPreview.tsx | 25 ++++++-- tests/channel-connections.test.ts | 8 ++- tests/channel-session.test.ts | 44 ++++++++++--- tests/viewer-playback.test.ts | 2 +- tests/voice-playback.test.ts | 40 +++++++++++- 25 files changed, 293 insertions(+), 96 deletions(-) diff --git a/docs/todo.md b/docs/todo.md index bb1575644..9967d018d 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -57,9 +57,9 @@ views follow during the feedback period; they do not delay that delivery. [Apple IPv4 source-selection fix](https://github.com/n0-computer/noq/pull/912) in macOS acceptance before changing the UDP dependency. Keep patch ownership in the [Native provenance](../prototype/channel-native/README.md#rtc-dependency). -- [ ] **Audio device acceptance.** Verify physical output selection, unplugging - and recovery across shared players. Keep failures actionable without silently - changing the selected device. Check audible message alerts with the Windows +- [ ] **Audio device acceptance.** Verify physical output selection across shared + players. On unplug, check that the waiting player offers a device choice, + retains the selection and recovers on replug. Check audible message alerts with the Windows App focused and in the background, including when it is visible but unfocused or behind another fullscreen window. Check alert suppression while its room's conversation popout is focused. Compare throw sounds in their intended window @@ -68,8 +68,7 @@ views follow during the feedback period; they do not delay that delivery. - [ ] **Capture device loss.** On real hardware, validate what a Windows share does when its graphics device is lost (`capture/gpu.rs`, `capture/frames.rs`), then state the accepted behaviour in the - [media standard](./standards/media-quality.md). The published line states a - rule; 3.0 has the code path and no accepted description. + [media standard](./standards/media-quality.md). - [ ] **Webpage source selection and watching continuity.** Complete matching-package GUI checks for document navigation, popup selection, consecutive source replacements and a viewer reselecting its local video. @@ -97,9 +96,7 @@ views follow during the feedback period; they do not delay that delivery. Host capture and encoding continue during the observed cycle. - [ ] **Original webpage closes when a viewer joins.** On the reporting Windows setup, correlate the stop reason with the activity, selected page and App - control connection. Preserve original-page playback when the selected video - element changes its resource URL; keep media-byte grants bound to the selected - resource. [Original-page controls](./verification-status.md#current-evidence) + control connection. [Original-page controls](./verification-status.md#current-evidence) - [ ] **Freeze the first public 3.0 contract.** Decide [ADR-0017](./adr/0017-contracts-fixed-before-release.md) against actual readers, writers and release storage fixtures. The @@ -314,8 +311,7 @@ views follow during the feedback period; they do not delay that delivery. separate mechanical format pass and review actionable Clippy findings by owner. Keep style-only changes separate from behavior fixes and new lint gates. - [ ] **3.0 documentation ownership.** Review remaining research files that - differ from their 2.x copies, unused research data and outdated couch markers - against current readers and code. + differ from their 2.x copies. Keep differences current readers or code still need. - [ ] **Whole-page collaboration.** Choose the intended co-browsing flow before extending synchronized playback. Evaluate a shared page with explicitly granted page-scoped input and each site's own collaborative links. Reuse the @@ -357,10 +353,8 @@ views follow during the feedback period; they do not delay that delivery. concurrent use. [Random-mapping and linear-extension controls](./research/nat-traversal.md#random-mapping-collision-control) Compare parallel surveys and search budgets under the same preparation deadline before changing the accepted limits. - Prepare the isolated survey observer independently of the Demo service. - Package the survey client only after carrying forward its candidate-window - and reply-origin corrections; verify same-IP filtering separately from - cross-IP mapping and preserve destination identity in offline replay. + Package the corrected survey client. Verify same-IP filtering separately + from cross-IP mapping. Evaluate the isolated allocator proposal against held-out per-destination mappings, including burst allocations and missing observations; then verify a bounded schedule through authenticated preparation and ICE transfer. @@ -369,16 +363,14 @@ views follow during the feedback period; they do not delay that delivery. address. Compare it under the present deadline. Run a physical pair across a network with a counter per destination on the present search order and default servers. Measure partial-observation recovery and the defaults from several - regions after the survey reports missing defaults even with zero or one - response. Then compare a wider bounded set that keeps each request's index + regions. Then compare a wider bounded set that keeps each request's index and treats a step across a gap as unknown. [Allocator controls](./research/nat-traversal.md#allocator-prediction-controls) Verify interface-scoped mDNS candidate resolution before adding a resolver. Define optional Server-port STUN exposure and authenticated ICE dispatch before adding a discovery responder to its existing socket owner. - [ ] **Codec capability and efficiency comparison.** Measure actual platform - encoder/decoder and Browser capabilities, then compare one available codec - with H.264 using synthetic text and motion. Compare hardware and software + encoder/decoder and Browser capabilities. Compare hardware and software execution under CPU/GPU contention, separating capture/copy, encoding and network cost. Include compatible H.264 forwarding cost and sustained runtime adaptation; keep congestion control with the RTC owner. Actual GPU-contention @@ -406,7 +398,8 @@ views follow during the feedback period; they do not delay that delivery. before extending discovery. Verify provider restoration in the matching App and explicit audio selection on a real page with multiple AAC tracks. Retry girigirilove when the original player is - accessible. Explain the trusted-site scope and local website login before use. + accessible. Add the local website sign-in instruction to the Japanese, Korean + and Traditional Chinese picker text. [Playback and authority boundaries](./research/channel-network-design.md#synchronized-video-sources) · [Website evidence](./verification-status.md#current-evidence) - [ ] **3.0 Native platform acceptance.** Complete same-room Windows/Android @@ -459,8 +452,7 @@ views follow during the feedback period; they do not delay that delivery. ## Parked Product Work -- **First-Join pacing.** The supported-scale control showed no queue benefit. - Reopen only on an observed admission burst that closes a room writer; review +- **First-Join pacing.** Reopen only on an observed admission burst that closes a room writer; review the directory visibility and synchronization contract before adding a queue. - **NDI and additional codecs (#535, #530).** Assess NDI through the existing OBS/DistroAV-to-WHIP input before considering another native dependency. diff --git a/prototype/channel-native/src/peer.rs b/prototype/channel-native/src/peer.rs index 11a74c0e7..d2a13c397 100644 --- a/prototype/channel-native/src/peer.rs +++ b/prototype/channel-native/src/peer.rs @@ -1310,6 +1310,9 @@ impl Driver { pair_id: id, connection_id: measured.connection_id, peer_id: pair.plan.peer_id, + preparing_udp: self.preparings.get(&id).is_some_and(|pending| { + pending.instance == measured.connection_id && !pending.task.is_finished() + }).then_some(true), sample_timestamp_ms: measured.sample_timestamp_ms, age_ms: measured.age_ms, rtt_ms: measured.rtt_ms, diff --git a/prototype/channel-native/src/peer/metrics.rs b/prototype/channel-native/src/peer/metrics.rs index 4667998c9..d22583d22 100644 --- a/prototype/channel-native/src/peer/metrics.rs +++ b/prototype/channel-native/src/peer/metrics.rs @@ -16,6 +16,8 @@ pub struct PeerConnectionMetrics { pub pair_id: Uuid, pub connection_id: Uuid, pub peer_id: Uuid, + #[serde(skip_serializing_if = "Option::is_none")] + pub preparing_udp: Option, pub sample_timestamp_ms: Option, pub age_ms: Option, pub rtt_ms: Option, diff --git a/prototype/channel-native/src/peer/tests/transport.rs b/prototype/channel-native/src/peer/tests/transport.rs index 3a4633426..ce80cbf21 100644 --- a/prototype/channel-native/src/peer/tests/transport.rs +++ b/prototype/channel-native/src/peer/tests/transport.rs @@ -2055,14 +2055,27 @@ async fn ordinary_connection_stops_preparation_only_on_stun_only_sites() -> Resu } driver.ice = vec![IceServer { urls, username: "test".into(), credential: "test".into() }]; let id = Uuid::new_v4(); + let screen = piik_channel_core::wire::PublicationInfo { + id: Uuid::new_v4(), room_id: "other-room".into(), session_id: Uuid::from_u128(1), + user_id: Uuid::new_v4(), kind: piik_channel_core::wire::Kind::Screen, + screen: None, paused: false, audience: vec![], video_settings: None, + }; let plan = PairInfo { id, peer_id: Uuid::from_u128(1), udp_preparation: Some(UdpPreparation::Available), - can_receive_video_layers: false, rooms: vec![], incoming: vec![], outgoing: vec![], + can_receive_video_layers: false, rooms: vec!["metrics-room".into(), "other-room".into()], + incoming: vec![piik_channel_core::wire::FlowBinding { + id: Uuid::new_v4(), publication_id: screen.id, input_flow_id: None, + presentation: false, selected: true, + }], outgoing: vec![], }; - driver.update(vec![plan.clone()], vec![], vec![]).await; + driver.update(vec![plan.clone()], vec![screen.clone()], vec![]).await; let rtc = driver.pairs[&id].pc.clone(); let job = driver.preparings[&id].task.abort_handle(); + ensure!(driver.connection_metrics("metrics-room", None).await?[0].preparing_udp == Some(true)); + ensure!(driver.connection_metrics("other-room", Some(screen.id)).await?[0].preparing_udp == Some(true)); + ensure!(driver.connection_metrics("metrics-room", Some(screen.id)).await?.is_empty()); + let remote = Runtime::new(Some(ServerUdp::bind(&[("[::1]:0".parse()?, None)])?)); let (peer, mut peer_events) = endpoint(&remote, id).await?; let (left, right) = open(&rtc, &peer, &mut peer_events).await?; @@ -2078,7 +2091,10 @@ async fn ordinary_connection_stops_preparation_only_on_stun_only_sites() -> Resu NativeEvent::Command(Command::Signal { pair_id, payload: Signal {udp: Some(UdpSignal::Unavailable {}), ..} }) if pair_id == id)); ensure!(driver.preparings.contains_key(&id) == turn && refused != turn, "configured TURN={turn}, pending={}, sent refusal={refused}, job ended={}", driver.preparings.contains_key(&id), job.is_finished()); - if !turn { ensure!(job.is_finished()); } + if !turn { + ensure!(job.is_finished()); + ensure!(driver.connection_metrics("metrics-room", None).await?[0].preparing_udp.is_none()); + } exchange(&left, &right, "ordinary").await?; if turn { // An authenticated winner completes on the old instance just before its lease disappears. diff --git a/prototype/channel-native/src/session.rs b/prototype/channel-native/src/session.rs index c853f60b0..e34cacb64 100644 --- a/prototype/channel-native/src/session.rs +++ b/prototype/channel-native/src/session.rs @@ -1475,7 +1475,14 @@ impl Session { publication.id == stream.publication_id && publication.room_id == room_id }) }); - !connection.streams.is_empty() + let preparation_in_scope = pair.udp_preparation.is_some() && match publication_id { + Some(id) => pair.incoming.iter().chain(&pair.outgoing).any(|flow| flow.publication_id == id), + None => pair.rooms.iter().any(|id| id == room_id), + }; + if !preparation_in_scope { + connection.preparing_udp = None; + } + connection.preparing_udp.is_some() || !connection.streams.is_empty() || (publication_id.is_none() && pair.rooms.iter().any(|id| id == room_id)) }); Ok(NativeConnectionMetrics { diff --git a/prototype/channel-native/src/session/composition_tests.rs b/prototype/channel-native/src/session/composition_tests.rs index b0a92d79f..14a345dc2 100644 --- a/prototype/channel-native/src/session/composition_tests.rs +++ b/prototype/channel-native/src/session/composition_tests.rs @@ -1049,3 +1049,66 @@ async fn confirmed_registration_replies_locally_after_its_carrier_disconnects() ensure!(reply.await?.map_err(anyhow::Error::msg)?.id == id); native.release().await } + +#[tokio::test] +async fn streamless_preparation_metrics_follow_room_publication_and_binding() -> Result<()> { + use piik_channel_core::wire::{FlowBinding, PairInfo, PublicationInfo, UdpPreparation}; + let (core, mut native, _directory, _ready, _welcome) = room_review_session()?; + let a = &core.room_ids[0]; + let b = &core.room_ids[1]; + let live = native.live.as_mut().unwrap(); + let snapshot = live.room.snapshot.clone(); + let mut view = snapshot.borrow().as_ref().unwrap().clone(); + for room in &mut view.channel.rooms { + room.available = true; + room.authorized = true; + room.delivery = Some(RoomDelivery { host_session_id: core.session, binding_id: Uuid::new_v4() }); + } + let peer = Uuid::new_v4(); + let screen = PublicationInfo { + id: Uuid::new_v4(), room_id: a.clone(), session_id: peer, user_id: core.user, + kind: Kind::Screen, screen: None, paused: false, audience: vec![], video_settings: None, + }; + let other = PublicationInfo { id: Uuid::new_v4(), room_id: b.clone(), ..screen.clone() }; + let pair = PairInfo { + id: Uuid::new_v4(), peer_id: peer, udp_preparation: Some(UdpPreparation::Available), + can_receive_video_layers: false, rooms: vec![a.clone(), b.clone()], + incoming: [&screen, &other].map(|publication| FlowBinding { + id: Uuid::new_v4(), publication_id: publication.id, input_flow_id: None, + presentation: false, selected: true, + }).into(), outgoing: vec![], + }; + view.pairs = vec![pair]; + view.publications = vec![screen.clone(), other.clone()]; + snapshot.send_replace(Some(view.clone())); + let first = tokio::net::UdpSocket::bind("127.0.0.1:0").await?; + let second = tokio::net::UdpSocket::bind("127.0.0.1:0").await?; + let ice = crate::peer::IceServer { + urls: vec![format!("stun:{}", first.local_addr()?), format!("stun:{}", second.local_addr()?)], + username: String::new(), credential: String::new(), + }; + live.peers.close().await?; + let (commands, events) = mpsc::channel(64); + live.peers = NativePeers::new(core.session, vec![ice], commands); + live.commands = events; + live.pairs.insert(view.pairs[0].id); + live.peers.update(view.pairs.clone(), view.publications.clone(), vec![], vec![]).await?; + let mut sink = RecordedSink::default(); + let measured = native.connection_metrics(a, Some(screen.id), &mut sink).await?; + let [connection] = measured.connections.as_slice() else { bail!("expected one preparing connection") }; + ensure!(connection.streams.is_empty() && connection.preparing_udp == Some(true)); + let denied = native.connection_metrics(a, Some(other.id), &mut sink).await.unwrap_err(); + ensure!(denied.to_string() == "publication_unavailable"); + + { + let mut read = std::pin::pin!(native.connection_metrics(a, Some(screen.id), &mut sink)); + ensure!(futures_util::poll!(&mut read).is_pending()); + snapshot.send_modify(|view| { + let room = view.as_mut().unwrap().channel.rooms.iter_mut().find(|room| &room.id == a).unwrap(); + room.delivery.as_mut().unwrap().binding_id = Uuid::new_v4(); + }); + ensure!(read.await.unwrap_err().to_string() == "room_context_changed"); + } + native.live.as_mut().unwrap().peers.close().await?; + Ok(()) +} diff --git a/src/client/channel/app-link.ts b/src/client/channel/app-link.ts index 37111ac07..ca233a9b9 100644 --- a/src/client/channel/app-link.ts +++ b/src/client/channel/app-link.ts @@ -55,7 +55,7 @@ const nativeMetricStreamsSchema = z.array(z.union([ ])).transform(streams => streams.filter(stream => stream !== null)); export const nativeConnectionMetricsSchema = z.object({ sessionId: z.uuid(), bindingId: z.uuid(), connections: z.array(z.object({ - pairId: z.uuid(), connectionId: z.uuid(), peerId: z.uuid(), + pairId: z.uuid(), connectionId: z.uuid(), peerId: z.uuid(), preparingUdp: z.boolean().optional(), sampleTimestampMs: measured.nullable(), ageMs: measured.nullable(), rttMs: measured.nullable(), bweBps: measured.nullable(), streams: nativeMetricStreamsSchema, })), diff --git a/src/client/channel/components/ChannelConnections.tsx b/src/client/channel/components/ChannelConnections.tsx index b543bc603..e345a2d54 100644 --- a/src/client/channel/components/ChannelConnections.tsx +++ b/src/client/channel/components/ChannelConnections.tsx @@ -18,6 +18,7 @@ import "./channel-room-controls.css"; interface Observations { scope: string; + preparingUdp: boolean; topology: ChannelTopology | null; metrics: ChannelConnectionSample[]; unavailable: Array<"connection.topologyUnavailable" | "connection.browserMetricsUnavailable" | "connection.appMetricsUnavailable">; @@ -103,7 +104,9 @@ function ConnectionBody({ channel, roomId, active }: { channel: ChannelControlle if (topology.status === "rejected") unavailable.push("connection.topologyUnavailable"); if (metrics.status === "rejected" || metrics.value.unavailable) unavailable.push("connection.browserMetricsUnavailable"); if (native.status === "rejected" || appExpected && !owner.appConnected) unavailable.push("connection.appMetricsUnavailable"); - setResult({ scope, topology: graph, metrics: samples, unavailable }); + const preparingUdp = !denied && current.current.appConnected && native.status === "fulfilled" + && !!native.value?.connections.some(connection => connection.preparingUdp); + setResult({ scope, preparingUdp, topology: graph, metrics: samples, unavailable }); timer = setTimeout(read, 1000); }; void read(); @@ -127,6 +130,8 @@ function ConnectionBody({ channel, roomId, active }: { channel: ChannelControlle ?

{t("connection.unavailable")}

: !observation && } + {room?.authorized && room.available && room.delivery && observation?.preparingUdp && +

{t("connection.preparingUdp")}

} {observation?.unavailable.map(reason =>

{t(reason)}

)} {room?.authorized && room.available && state && sessionId && observation && ; } -export type ScreenStageStatus = ScreenStage & { peer?: ScreenStagePeer }; +export type ScreenStageStatus = ReceiveStage & { peer?: StagePeer }; /** The one illustration of a picture box that has no picture. The stylesheet shows it where the box is wide enough, in place of the glyph that follows it. */ export function PictureComic({ kind }: { kind: ComicKind }) { @@ -458,7 +458,7 @@ export function screenStageComic(stage: ScreenStageStatus): ComicKind | undefine case "requesting": return "signal-connecting"; case "routing": return undefined; case "connecting": case "connected": return stage.peer === "site" ? "connecting-sfu" : stage.peer ? "connecting-p2p" : undefined; - case "decoded": return undefined; + case "ready": return undefined; } } @@ -479,7 +479,7 @@ export function ScreenStageCaption({ stage }: { stage: ScreenStageStatus }) { else if (stage.peer) label = t(stage.peer.sharer ? "screen.stage.connecting" : "screen.stage.connectingThrough", { name: stage.peer.name }); else label = t("screen.stage.connectingUnknown"); break; - case "decoded": return null; + case "ready": return null; } return {label}{slow && <>
{t("screen.stage.slow")}}
; } @@ -701,7 +701,7 @@ export function ChannelVideo({ stream, owned, localSource, sourcePaused = false, {(sourcePaused || waitingForFrame) && {comic && } {sourcePaused ? : } - {sourcePaused ? t("host.pauseNotice") : stage && stage.step !== "decoded" ? : t("screen.waitingPicture")}} + {sourcePaused ? t("host.pauseNotice") : stage && stage.step !== "ready" ? : t("screen.waitingPicture")}} {failure && } } {blocked && !sourcePaused &&
1 || status === "joining"; + // While a voice is on its way the line names the step it is at, as a watched picture does. + const waiting = status === "joining" ? waitingVoicePublication(state, channel.sessionId, roomId, renderingBySpeaker) : undefined; + const stage = waiting && channel.receiveStage(waiting.id); + const peer = waiting && stage?.peerId ? stagePeer(state, waiting, stage.peerId) : undefined; + const statusLabel = stage?.step === "routing" ? t("channel.voiceDock.voiceRouting") + : stage?.step !== "connecting" || !peer ? t(VOICE_STATUS_LABEL[status]) + : peer === "site" ? t("screen.stage.connectingSite") + : t(peer.sharer ? "screen.stage.connecting" : "screen.stage.connectingThrough", { name: peer.name }); return { dismiss?.(); onBrowse(roomId); }} />; }; @@ -84,12 +93,11 @@ function ChannelVoiceRoomDisclosure({ count, layoutAnchor, children }: {
; } -function ChannelVoiceRoomRow({ channel, activity, name, current, visible, direct, labelled, status, showRoomInfo, shortcuts, toolsHome, others, onBrowse }: { +function ChannelVoiceRoomRow({ channel, activity, name, current, visible, direct, labelled, status, statusLabel, showRoomInfo, shortcuts, toolsHome, others, onBrowse }: { channel: ChannelController; activity: VoiceActivity; name: string; current: boolean; visible: boolean; - direct: boolean; labelled: boolean; showRoomInfo: boolean; status: keyof typeof VOICE_STATUS_LABEL; shortcuts?: Shortcuts; onBrowse: () => void; + direct: boolean; labelled: boolean; showRoomInfo: boolean; status: keyof typeof VOICE_STATUS_LABEL; statusLabel: string; shortcuts?: Shortcuts; onBrowse: () => void; toolsHome?: (element: HTMLElement | null) => void; others?: ReactNode; }) { - const { t } = useCopy(); const id = useId(); const { roomId, sessionId, muted, deafened } = activity; const read = useCallback(() => channel.voiceActivity(roomId, true), [channel.voiceActivity, roomId]); @@ -103,7 +111,7 @@ function ChannelVoiceRoomRow({ channel, activity, name, current, visible, direct - {(direct || status !== "joined") && {t(VOICE_STATUS_LABEL[status])}} + {(direct || status !== "joined") && {statusLabel}} } {others}
diff --git a/src/client/channel/components/channel-voice-rooms.css b/src/client/channel/components/channel-voice-rooms.css index db206c14e..77def4daa 100644 --- a/src/client/channel/components/channel-voice-rooms.css +++ b/src/client/channel/components/channel-voice-rooms.css @@ -53,7 +53,11 @@ } .c3-voice-room-name > button:hover { text-decoration: underline; text-underline-offset: 3px; } .c3-voice-room-row .c3-voice-room-name > button[aria-current] { font-weight: var(--type-weight-strong); } -.c3-voice-room-row small { display: block; color: var(--live-ink); font-size: var(--type-caption-size); line-height: var(--type-caption-line); } +/* The status keeps the row's measure, as the room's name does: two lines at most, however long the peer's name. */ +.c3-voice-room-row small { + display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; overflow-wrap: anywhere; + color: var(--live-ink); font-size: var(--type-caption-size); line-height: var(--type-caption-line); +} .c3-voice-room-row small[data-status="joining"] { color: var(--busy); } .c3-voice-room-actions, .c3-voice-shared-tools { display: flex; diff --git a/src/client/channel/media.ts b/src/client/channel/media.ts index 7969e53fc..d7a294b5f 100644 --- a/src/client/channel/media.ts +++ b/src/client/channel/media.ts @@ -3,7 +3,7 @@ import { collectConnectionMetrics, collectTrackConnectionMetrics, createStatsAcc import { P2pQualityProbe } from "../media/candidate-quality-probe"; import { VIEWER_QUALITY_EVIDENCE_INTERVAL_MS } from "../../shared/protocol"; import type { ChannelCommand, ChannelPair, ChannelSignal, ChannelSnapshot } from "./protocol"; -import type { ChannelMediaMetric, ChannelMediaMetrics, ChannelScreenInput, ScreenPresentation, ScreenBufferStatus, ScreenStage } from "./types"; +import type { ChannelMediaMetric, ChannelMediaMetrics, ChannelScreenInput, ScreenPresentation, ScreenBufferStatus, ReceiveStage } from "./types"; import { ChannelTransport, type OutgoingMedia } from "./transport"; import { applyCaptureProfile, screenAudioBitrate, screenContentHint, type QualityProfile } from "../media/quality"; import { automaticVideoCodecPreference, VP8_ONLY_VIDEO_CODEC, type BrowserVideoCodecPreference } from "../webrtc/video-codec"; @@ -52,7 +52,7 @@ export class ChannelMedia { private local = new Map(); private streams = new Map(); private screenInputs = new Map(); - private screenStages = new Map(); + private receiveStages = new Map(); private relayMedia = new Map(); private videoPool = new BrowserEncodingPool(); @@ -227,7 +227,7 @@ export class ChannelMedia { const current = this.peers.get(plan.id); if (current?.transport === transport) this.reportConnected(current); }, - connectionStateChanged: () => this.publishScreenChanges(), + connectionStateChanged: () => this.publishChanges(), disconnected: () => { if (this.peers.get(plan.id)?.transport === transport) { this.send({ type: "link_state", pairId: plan.id, state: "disconnected" }); @@ -460,20 +460,20 @@ export class ChannelMedia { return null; } - screenStage(publicationId: string, requested: boolean): ScreenStage | undefined { - const subscribed = this.screenStages.get(publicationId); + receiveStage(publicationId: string, requested: boolean): ReceiveStage | undefined { + const subscribed = this.receiveStages.get(publicationId); if (requested && subscribed === undefined) return { step: "requesting" }; return subscribed ?? undefined; } - private subscribedScreenStage(publicationId: string): ScreenStage | undefined { + private subscribedStage(publicationId: string): ReceiveStage | undefined { for (const plan of this.plans) { const flow = plan.incoming.find(flow => flow.publicationId === publicationId && flow.selected); if (!flow) continue; const peer = this.peers.get(plan.id), input = peer?.inputs.get(flow.id); const route = { peerId: plan.peerId, flowId: flow.id }; if (input?.failed) return; - if (input?.ready || input?.shown) return { step: "decoded", ...route }; + if (input?.ready || input?.shown) return { step: "ready", ...route }; switch (peer?.transport.pc.connectionState) { case "new": case "connecting": return { step: "connecting", ...route }; case "connected": return { step: "connected", ...route }; @@ -483,19 +483,19 @@ export class ChannelMedia { return { step: "routing" }; } - private publishScreenChanges(mediaChanged = false): void { - const stages = new Map(); + private publishChanges(mediaChanged = false): void { + const stages = new Map(); for (const publication of this.publications) { - if (publication.kind !== "screen" || !this.subscriptions.includes(publication.id)) continue; - const stage = this.subscribedScreenStage(publication.id); + if (!this.subscriptions.includes(publication.id)) continue; + const stage = this.subscribedStage(publication.id); if (!stage) { stages.set(publication.id, null); continue; } - const previous = this.screenStages.get(publication.id); + const previous = this.receiveStages.get(publication.id); // Mounting the video for an arriving track keeps the age of the same step and flow. stages.set(publication.id, previous?.step === stage.step && previous.flowId === stage.flowId && previous.peerId === stage.peerId ? previous : { ...stage, since: performance.now() }); } - if (!mediaChanged && stages.size === this.screenStages.size && [...stages].every(([id, stage]) => this.screenStages.get(id) === stage)) return; - this.screenStages = stages; + if (!mediaChanged && stages.size === this.receiveStages.size && [...stages].every(([id, stage]) => this.receiveStages.get(id) === stage)) return; + this.receiveStages = stages; this.changed(this.streams, this.screenInputs); } @@ -508,7 +508,7 @@ export class ChannelMedia { if (state === "shown") { if (flow.selected && !input.shown) { input.shown = true; - this.publishScreenChanges(); + this.publishChanges(); } } else if (state === "failed") { if (onSelectedFailure && this.selectedInput(flow.publicationId)?.input === input) onSelectedFailure(flow.publicationId); @@ -670,7 +670,7 @@ export class ChannelMedia { } if (streamsChanged) this.streams = streams; if (inputsChanged) this.screenInputs = screenInputs; - this.publishScreenChanges(streamsChanged || inputsChanged); + this.publishChanges(streamsChanged || inputsChanged); } private syncRelayMedia(needed: ReadonlyMap): void { diff --git a/src/client/channel/presentation.ts b/src/client/channel/presentation.ts index dbfa7cd9e..5610f5709 100644 --- a/src/client/channel/presentation.ts +++ b/src/client/channel/presentation.ts @@ -4,9 +4,9 @@ import type { GlyphName } from "../ui/icons"; import type { ChannelMessage, ChannelPublication, ChannelRoom, ChannelSnapshot, ChannelUser, ScreenSource, WatchActivity } from "./protocol"; import type { WatchPlayer } from "./watch-playback"; -export type ScreenStagePeer = "site" | { name: string; sharer: boolean }; +export type StagePeer = "site" | { name: string; sharer: boolean }; -export function screenStagePeer(state: ChannelSnapshot, publication: Pick, peerId: string): ScreenStagePeer | undefined { +export function stagePeer(state: ChannelSnapshot, publication: Pick, peerId: string): StagePeer | undefined { const room = state.channel.rooms.find(room => room.id === publication.roomId); const source = peerId === publication.sessionId; const writer = peerId === room?.delivery?.hostSessionId; diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index fb50696d7..3752addc6 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -224,7 +224,7 @@ export class ChannelSession { localScreens: new Set(), state: null, sessionId: null, self: null, profiles: new Map(), connection: "connecting", messagesByRoom: {}, historyChangesByRoom: {}, historyByRoom: {}, readByRoom: {}, streams: new Map(), screenInputs: new Map(), inputChannels: new Map(), remoteControls: new Map(), error: null, roomOpenFailures: new Map(), siteURL: null, pending: new Set(), - screenStage: id => this.media.screenStage(id, this.watching.has(id) + receiveStage: id => this.media.receiveStage(id, this.watching.has(id) || this.view.pending.has(`watch:${id}`) && this.intents.get(id)?.state !== "left"), }; private listeners = new Set<() => void>(); diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts index f2d50431c..8e5c29789 100644 --- a/src/client/channel/types.ts +++ b/src/client/channel/types.ts @@ -58,8 +58,10 @@ export interface ChannelScreenInput { switchReady: boolean; } -export interface ScreenStage { - step: "requesting" | "routing" | "connecting" | "connected" | "decoded"; +/** How far this endpoint has come in receiving a publication it asked for, a picture or a voice, and from which immediate peer. */ +export interface ReceiveStage { + // Ready describes the selected input. Presentation is established by its consumer. + step: "requesting" | "routing" | "connecting" | "connected" | "ready"; peerId?: string; flowId?: string; since?: number; @@ -113,7 +115,7 @@ export interface ChannelView { readByRoom: Record; streams: ReadonlyMap; screenInputs: ReadonlyMap; - screenStage(publicationId: string): ScreenStage | undefined; + receiveStage(publicationId: string): ReceiveStage | undefined; inputChannels: ReadonlyMap; remoteControls: ReadonlyMap; error: string | null; diff --git a/src/client/channel/use-voice-playback.ts b/src/client/channel/use-voice-playback.ts index 9a3b06d97..16a729179 100644 --- a/src/client/channel/use-voice-playback.ts +++ b/src/client/channel/use-voice-playback.ts @@ -20,18 +20,28 @@ export function voicePlaybackPublications(state: ChannelSnapshot | null, session export type RoomVoiceStatus = "joining" | "connected" | "joined"; export type VoiceRendering = "playing" | "blocked"; +/** The voices a listening member of the room should hear: live publications of its other unmuted members. */ +function roomVoiceCandidates(state: ChannelSnapshot, sessionId: string | null, roomId: string): ChannelPublication[] { + const members = state.voice.filter(voice => voice.roomId === roomId); + const self = members.find(voice => voice.sessionId === sessionId); + if (!self || self.deafened) return []; + const speakers = new Set(members.filter(voice => voice.sessionId !== sessionId && !voice.muted).map(voice => voice.sessionId)); + return state.publications.filter(publication => publication.kind === "voice" && publication.roomId === roomId + && !publication.paused && speakers.has(publication.sessionId)); +} + +/** A voice this listener asked for and does not hear yet: the one a room's connecting line is about. */ +export function waitingVoicePublication(state: ChannelSnapshot, sessionId: string | null, roomId: string, + renderingBySpeaker: ReadonlyMap): ChannelPublication | undefined { + return roomVoiceCandidates(state, sessionId, roomId).find(publication => state.subscriptions.includes(publication.id) + && renderingBySpeaker.get(publication.sessionId) === undefined); +} + /** One microphone can render through its publication in a sibling room. */ export function roomVoiceStatus(state: ChannelSnapshot, sessionId: string | null, roomId: string, renderingBySpeaker: ReadonlyMap): RoomVoiceStatus { - const members = state.voice.filter(voice => voice.roomId === roomId); - const self = members.find(voice => voice.sessionId === sessionId); - if (!self || self.deafened) return "joined"; - const speakers = new Set(members.filter(voice => voice.sessionId !== sessionId && !voice.muted).map(voice => voice.sessionId)); - const candidates = state.publications.filter(publication => publication.kind === "voice" && publication.roomId === roomId - && !publication.paused && speakers.has(publication.sessionId)); - if (candidates.some(publication => renderingBySpeaker.get(publication.sessionId) === "playing")) return "connected"; - return candidates.some(publication => state.subscriptions.includes(publication.id) - && renderingBySpeaker.get(publication.sessionId) !== "blocked") ? "joining" : "joined"; + if (roomVoiceCandidates(state, sessionId, roomId).some(publication => renderingBySpeaker.get(publication.sessionId) === "playing")) return "connected"; + return waitingVoicePublication(state, sessionId, roomId, renderingBySpeaker) ? "joining" : "joined"; } /** Retain the current audible publication without choosing or changing any route. */ diff --git a/src/client/components/living/CaptureSourcePicker.tsx b/src/client/components/living/CaptureSourcePicker.tsx index a6ced2682..7b8e66d57 100644 --- a/src/client/components/living/CaptureSourcePicker.tsx +++ b/src/client/components/living/CaptureSourcePicker.tsx @@ -168,7 +168,7 @@ export function CaptureSourcePicker({ const exclusionUnavailable = activeTab === "display" && shareAudio && !!excludeAudio && (!canExcludeAudio || missingExclusion); const refreshing = activeTab === "camera" ? cameraSources.busy : nativeSources.kind === "loading"; const refreshLabel = t(refreshing ? "host.sourcePicker.loading" : "host.sourcePicker.refresh"); - const audioAction = t(!anyNativeAudio ? "host.noAudio" : audioLocked + const audioAction = t(!anyNativeAudio ? "host.sourcePicker.audioUnavailable" : audioLocked ? "host.sourcePicker.audioLocked" : shareAudio ? "host.sourcePicker.audioOff" : "host.sourcePicker.audioOn"); const audioLabel = t( @@ -306,7 +306,7 @@ export function CaptureSourcePicker({ kind={!anyNativeAudio ? "no-audio" : audioLocked ? (shareAudio ? "hint-share-audio-fixed" : "hint-silent-share-fixed") : shareAudio ? "hint-stop-audio" : "hint-share-audio"} - text={`${audioAction}\n${t("host.sourcePicker.audioHint")}`} + text={anyNativeAudio ? `${audioAction}\n${t("host.sourcePicker.audioHint")}` : audioAction} place="below" > {audioSwitch} diff --git a/src/client/locales/en.ts b/src/client/locales/en.ts index c3653dbdb..27a8bde49 100644 --- a/src/client/locales/en.ts +++ b/src/client/locales/en.ts @@ -510,6 +510,7 @@ export const en: Record = { "channel.voiceDock.adjustOverlay": "Adjust voice overlay", "channel.voiceDock.pinOverlay": "Pin voice overlay", "channel.voiceDock.voiceJoined": "Voice joined", + "channel.voiceDock.voiceRouting": "Waiting for a voice route…", "channel.voiceDock.voiceConnecting": "Connecting voice…", "channel.voiceDock.voiceConnected": "Voice connected", "channel.invitationLink.copied": "Copied", @@ -1250,6 +1251,7 @@ export const en: Record = { "host.sourcePicker.display": "Share screen: {title}", "host.sourcePicker.system": "System screen or window picker", "host.sourcePicker.systemAction": "Choose a screen or window with the system picker", + "host.sourcePicker.audioUnavailable": "Sound capture is unavailable for these sources.", "host.sourcePicker.audioHint": "Window audio shares the selected app’s sound. Window or full-screen audio can include the call if it captures the app playing it.", "host.sourcePicker.refresh": "Refresh sharing sources", "host.sourcePicker.loading": "Finding sharing sources", @@ -1372,6 +1374,7 @@ export const en: Record = { "connection.unavailable": "Connection details are temporarily unavailable.", "connection.topologyUnavailable": "The room path could not be read. This panel will retry while it stays open.", "connection.browserMetricsUnavailable": "Some browser measurements could not be read. Available data is shown; this panel will retry while it stays open.", + "connection.preparingUdp": "The App is trying a UDP connection.", "connection.appMetricsUnavailable": "The App measurements could not be read. Available data is shown; this panel will retry while it stays open.", "connection.appMetricScope": "App connection statistics provide network measurements. They do not report picture resolution, frame rate or encoding time.", "host.details.hide": "Hide connection details", diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.ts index 9f2aad056..9ad8b161f 100644 --- a/src/client/locales/zh.ts +++ b/src/client/locales/zh.ts @@ -508,6 +508,7 @@ export const zh = { "channel.voiceDock.adjustOverlay": "调整语音浮层", "channel.voiceDock.pinOverlay": "固定语音浮层", "channel.voiceDock.voiceJoined": "语音已加入", + "channel.voiceDock.voiceRouting": "正在等待语音线路…", "channel.voiceDock.voiceConnecting": "正在接通语音…", "channel.voiceDock.voiceConnected": "语音已接通", "channel.invitationLink.copied": "已复制", @@ -1248,6 +1249,7 @@ export const zh = { "host.sourcePicker.display": "分享屏幕:{title}", "host.sourcePicker.system": "系统屏幕与窗口选择器", "host.sourcePicker.systemAction": "使用系统选择器选择屏幕或窗口", + "host.sourcePicker.audioUnavailable": "这些来源不支持声音采集。", "host.sourcePicker.audioHint": "窗口分享所选应用的声音。如果分享范围包含播放通话的应用,窗口或整屏分享都可能把通话传回来。", "host.sourcePicker.refresh": "刷新分享来源", "host.sourcePicker.loading": "正在查找分享来源", @@ -1370,6 +1372,7 @@ export const zh = { "connection.unavailable": "暂时无法读取连接详情。", "connection.topologyUnavailable": "未能读取房间线路。保持此面板打开会自动重试。", "connection.browserMetricsUnavailable": "部分浏览器统计未能读取。已显示可用数据,保持此面板打开会自动重试。", + "connection.preparingUdp": "App 正在尝试 UDP 连接。", "connection.appMetricsUnavailable": "未能读取 App 统计。已显示可用数据,保持此面板打开会自动重试。", "connection.appMetricScope": "App 连接统计提供网络测量,不包含画面分辨率、帧率和编码耗时。", "host.details.hide": "隐藏连接详情", diff --git a/src/client/pages/ChannelPage.tsx b/src/client/pages/ChannelPage.tsx index 7293b2e95..25f7ff183 100644 --- a/src/client/pages/ChannelPage.tsx +++ b/src/client/pages/ChannelPage.tsx @@ -48,7 +48,7 @@ import { ChannelCouch } from "../channel/components/ChannelCouch"; import { ChannelRoomTool, type RoomToolSurface } from "../channel/components/ChannelRoomTool"; import { ChannelConnections } from "../channel/components/ChannelConnections"; import { ChannelDiagnosisHelp } from "../components/ChannelDiagnosisHelp"; -import { roomHasUnread, roomPeople, roomSessionViewing, viewingAppearance, screenAudience, screenDeliveryFailed, screenStagePeer, screenTitle, userProfile, watchAudience } from "../channel/presentation"; +import { roomHasUnread, roomPeople, roomSessionViewing, viewingAppearance, screenAudience, screenDeliveryFailed, stagePeer, screenTitle, userProfile, watchAudience } from "../channel/presentation"; import { useVoicePlayback, type VoiceRendering } from "../channel/use-voice-playback"; import { VoicePlaybackContext } from "../media/viewer-audio"; import { resolveVoiceDockControls } from "../channel/voice-dock-controls"; @@ -292,8 +292,8 @@ export function ChannelRoomPage({ channel, selected, onSelect, restoreRoom, appC const screens = publications.filter(value => value.kind === "screen"); const mine = screens.filter(value => channel.ownedScreens.has(value.id)); const screenStages = new Map(screens.map(publication => { - const stage = channel.ownedScreens.has(publication.id) ? undefined : channel.screenStage(publication.id); - const peer = stage?.peerId && state ? screenStagePeer(state, publication, stage.peerId) : undefined; + const stage = channel.ownedScreens.has(publication.id) ? undefined : channel.receiveStage(publication.id); + const peer = stage?.peerId && state ? stagePeer(state, publication, stage.peerId) : undefined; return [publication.id, stage && { ...stage, peer }] as const; })); const watched = screens.filter(value => !channel.ownedScreens.has(value.id) diff --git a/src/client/pages/ChannelRoomPreview.tsx b/src/client/pages/ChannelRoomPreview.tsx index a3717691b..9106541c4 100644 --- a/src/client/pages/ChannelRoomPreview.tsx +++ b/src/client/pages/ChannelRoomPreview.tsx @@ -7,7 +7,7 @@ import { participantColor } from "../components/living/participant-color"; import { Glyph } from "../ui/icons"; import { useCopy } from "../ui/copy"; import { screenVideoSettings } from "../media/quality"; -import type { ChannelController, ScreenStage } from "../channel/types"; +import type { ChannelController, ReceiveStage } from "../channel/types"; import { LONG_WAIT_MS } from "../ui/long-wait"; import type { WatchIndexedChoice, WatchMpdChoice } from "../channel/watch-page-media"; import { roomCreationPolicySchema, type ChannelRoom, type RoomCreationPolicy, type WatchActivity } from "../channel/protocol"; @@ -171,8 +171,12 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) ? [...audience.filter(viewer => viewer.sessionId !== sample.channel.sessionId), { sessionId: sample.channel.sessionId!, state: "failed" as const }] : audience }; }); const ownedScreens = new Set(publications.filter(publication => publication.userId === "sample-ada").map(publication => publication.id)); + // voice-step=routing|connecting puts a friend's voice on its way; voice-peer=friend sends it through another person. + const voiceStep = query.get("voice-step"), sampleVoiceId = "sample-voice-bo"; + const sampleVoice = voiceStep && roomIds.has("friday") ? [{ audience: [], id: sampleVoiceId, kind: "voice" as const, roomId: "friday", + sessionId: "sample-bo-session", userId: "sample-bo", paused: false }] : []; const requesting = picture === "requesting" && omitSamplePicture && !unwatched.has(samplePictureId); - const subscriptions = publications.filter(publication => !unwatched.has(publication.id) && !(requesting && publication.id === samplePictureId)).map(publication => publication.id); + const subscriptions = [...publications.filter(publication => !unwatched.has(publication.id) && !(requesting && publication.id === samplePictureId)), ...sampleVoice].map(publication => publication.id); const needsSamples = ownedScreens.size > 0 || subscriptions.length > 0 || !!watchActivity || !!pageSample; // Keep the same samples while any player needs them. useEffect(() => { @@ -224,7 +228,7 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) const selectedSample = sampleInputs?.find(input => input.selected); const sitePeer = rooms.find(room => room.id === "friday")?.delivery?.hostSessionId; const samplePeer = siteForwarding ? sitePeer : hasSamplePeer && picturePeer === "friend" ? "sample-dora-session" : `${screenUsers[0].id}-session`; - const sampleStage = useMemo((): ScreenStage => { + const sampleStage = useMemo((): ReceiveStage => { const since = performance.now(); switch (picture) { case "requesting": return { step: "requesting" }; @@ -326,7 +330,7 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) ...publications.filter(publication => publication.roomId === room.id).flatMap(publication => [publication.sessionId, ...publication.audience.map(viewer => viewer.sessionId)]), ...(watchActivity?.roomId === room.id ? watchSessions : []), ])] })), - }, publications: [...sample.channel.state!.publications.filter(publication => roomIds.has(publication.roomId) && (!watchOnly || publication.kind !== "voice")), ...publications], + }, publications: [...sample.channel.state!.publications.filter(publication => roomIds.has(publication.roomId) && (!watchOnly || publication.kind !== "voice")), ...publications, ...sampleVoice], voice: sample.channel.state!.voice.filter(voice => !watchOnly && roomIds.has(voice.roomId) && !(hostOffline && voice.roomId === "friday")), users, subscriptions, @@ -525,10 +529,21 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean }) ownedScreens, localScreens: nativePauseRejected ? new Set() : ownedScreens, hostMediaTargets: query.has("host-media") ? previewHostMediaTargets : sample.channel.hostMediaTargets, screenInputs: new Map(sampleInputs ? [[samplePictureId, sampleInputs]] : []), inputChannels: new Map(), remoteControls: new Map(), voicePlaybackByUser: new Map(), - screenStage: id => id === samplePictureId && omitSamplePicture && !unwatched.has(id) ? sampleStage : undefined, + receiveStage: id => id === samplePictureId && omitSamplePicture && !unwatched.has(id) ? sampleStage + : id === sampleVoiceId ? { step: voiceStep === "routing" ? "routing" : "connecting", + peerId: query.get("voice-peer") === "friend" ? "sample-dora-session" : "sample-bo-session" } : undefined, browse: () => {}, sendMessage: sample.onSend, loadHistory: async () => sample.received(), loadLatestHistory: async () => sample.received(), historyByRoom: Object.fromEntries(state.channel.rooms.map(room => [room.id, { hasMore: false, atLatest: true }])), + appConnectionMetrics: async roomId => { + const metrics = await sample.channel.appConnectionMetrics(roomId); + return metrics && roomId === "friday" && query.has("udp-preparing") ? { + ...metrics, connections: [...metrics.connections, { + pairId: "sample-udp-pair", connectionId: "sample-udp", peerId: "sample-bo-session", preparingUdp: true, + sampleTimestampMs: null, ageMs: null, rttMs: null, bweBps: null, streams: [], + }], + } : metrics; + }, roomTopology: async (roomId, publicationId) => sampleRoomTopology(state, roomId, publicationId), screenQuality: () => ({ requested: sample.channel.quality, applied: sample.channel.quality }), screenCodec: () => ({ mode: sample.channel.videoCodecMode }), sourceAudio: id => ownedScreens.has(id) ? { level: 1, muted: false, bitrate: sample.channel.quality.maxAudioBitrate ?? 128_000, diff --git a/tests/channel-connections.test.ts b/tests/channel-connections.test.ts index a2a56aa13..d3e9a2a2b 100644 --- a/tests/channel-connections.test.ts +++ b/tests/channel-connections.test.ts @@ -88,16 +88,18 @@ describe("connection sampling lifetime", () => { connectionId: "c", pairId: "p", peerId: "peer", rttMs: 20, bweBps: null, streams: [{ flowId: "f", publicationId: "voice", selected: true, direction: "send", media: "audio", outputId: null, mid: "0", rid: null, codec: "audio/opus", bytes, sampleTimestampMs, rttMs: null, lossFraction: 0, jitterMs: 1 }] }] }); - const app = [async () => stream(1_000, 1_000), async () => { throw new Error("request_pending"); }, async () => stream(4_000, 3_000), async () => stream(8_000, 5_000), async () => stream(9_000, 6_000)]; + const app = [async () => ({ ...stream(1_000, 1_000), connections: [ + ...stream(1_000, 1_000).connections, { connectionId: "pending", preparingUdp: true, streams: [] }, + ] }), async () => { throw new Error("request_pending"); }, async () => stream(4_000, 3_000), async () => stream(8_000, 5_000), async () => stream(9_000, 6_000)]; const { channel, requests, updates, cleanup, visibility, settle, next } = observation({ appConnectionMetrics: () => app.shift()!() }); visibility("visible"); requests[0].finish({ plan: "first" }); await settle(); - expect(updates[0]).toMatchObject({ topology: { plan: "first" }, unavailable: [] }); + expect(updates[0]).toMatchObject({ topology: { plan: "first" }, preparingUdp: true, unavailable: [] }); expect(updates[0].metrics).toHaveLength(1); // The room is rearranging its routes and the App is busy: neither read answers this second. next(); requests[1].fail(new Error("room_unavailable")); await settle(); - expect(updates[1]).toMatchObject({ topology: { plan: "first" }, unavailable: ["connection.topologyUnavailable", "connection.appMetricsUnavailable"] }); + expect(updates[1]).toMatchObject({ topology: { plan: "first" }, preparingUdp: false, unavailable: ["connection.topologyUnavailable", "connection.appMetricsUnavailable"] }); expect(updates[1].metrics).toEqual(updates[0].metrics); next(); requests[2].finish({ plan: "second" }); await settle(); diff --git a/tests/channel-session.test.ts b/tests/channel-session.test.ts index 2eaa7c115..684d4b097 100644 --- a/tests/channel-session.test.ts +++ b/tests/channel-session.test.ts @@ -15,7 +15,7 @@ import { FeedbackAudio } from "../src/client/channel/feedback-audio"; import { channelErrorPresentation } from "../src/client/ui/error-presentation"; import * as hosting from "../src/client/channel/hosting"; import type { BackupHistoryRow } from "../prototype/channel-browser/src/hosting-contract"; -import { listeningVoicePublications, roomPeople, roomSessionViewing, screenAudience, screenDeliveryFailed, screenStagePeer } from "../src/client/channel/presentation"; +import { listeningVoicePublications, roomPeople, roomSessionViewing, screenAudience, screenDeliveryFailed, stagePeer } from "../src/client/channel/presentation"; import { resolveRoomVoiceControls } from "../src/client/channel/voice-dock-controls"; import * as backupArchive from "../src/client/channel/backup-archive"; import * as appLink from "../src/client/channel/app-link"; @@ -8322,12 +8322,12 @@ test("screen peer names distinguish a person's other endpoint, the hosted writer const state = structuredClone(session.getSnapshot().state!); const publication = { roomId: "first", sessionId: "sharer", userId: "self" }; state.sessions.push({ ...state.sessions[0], id: "host" }, { ...state.sessions[0], id: "owner-endpoint" }); - expect(screenStagePeer(state, publication, "endpoint")).toEqual({ name: state.users[0].name, sharer: true }); - expect(screenStagePeer(state, publication, "host")).toEqual({ name: state.users[0].name, sharer: true }); - expect(screenStagePeer(state, publication, "owner-endpoint")).toBeUndefined(); - expect(screenStagePeer(state, publication, "unknown")).toBeUndefined(); + expect(stagePeer(state, publication, "endpoint")).toEqual({ name: state.users[0].name, sharer: true }); + expect(stagePeer(state, publication, "host")).toEqual({ name: state.users[0].name, sharer: true }); + expect(stagePeer(state, publication, "owner-endpoint")).toBeUndefined(); + expect(stagePeer(state, publication, "unknown")).toBeUndefined(); state.channel.hostingMode = "hosted"; - expect(screenStagePeer(state, publication, "host")).toBe("site"); + expect(stagePeer(state, publication, "host")).toBe("site"); } finally { session.close(); } }); @@ -8338,7 +8338,7 @@ test.each(["decoded", "shown"])("a watched screen follows the subscription, sele state.publications = [{ id: "picture", roomId: "first", sessionId: "z", userId: "friend", kind: "screen", audience: [], paused: false, source: { kind: "screen", name: null }, title: null }]; const update = () => socket.receive({ type: "state", state }); - const stage = () => session.getSnapshot().screenStage("picture"); + const stage = () => session.getSnapshot().receiveStage("picture"); const notified = vi.fn(() => stage()?.step); const unsubscribe = session.subscribe(notified); try { @@ -8389,9 +8389,9 @@ test.each(["decoded", "shown"])("a watched screen follows the subscription, sele session.screenPresentation(flow.id, stream, "shown"); expect(socket.sent).toHaveLength(sent); } - await vi.waitFor(() => expect(notified).toHaveLastReturnedWith("decoded")); + await vi.waitFor(() => expect(notified).toHaveLastReturnedWith("ready")); pc.connectionState = "disconnected"; pc.onconnectionstatechange?.(); - expect(stage()?.step).toBe("decoded"); + expect(stage()?.step).toBe("ready"); const stop = session.unwatch("picture"); const stopRequest = socket.sent.at(-1)!; @@ -8403,6 +8403,32 @@ test.each(["decoded", "shown"])("a watched screen follows the subscription, sele } finally { unsubscribe(); session.close(); } }); +test("a subscribed voice reports its route and its transport as a watched screen does", async () => { + vi.stubGlobal("RTCPeerConnection", RoomPeerConnection); + const { session, socket } = await setup(1000, false); + const state = structuredClone(session.getSnapshot().state!); + state.publications = [{ id: "voice", roomId: "first", sessionId: "z", userId: "friend", kind: "voice", audience: [], paused: false }]; + const update = () => socket.receive({ type: "state", state }); + const stage = () => session.getSnapshot().receiveStage("voice"); + try { + update(); + expect(stage()).toBeUndefined(); + state.subscriptions = ["voice"]; + update(); + expect(stage()?.step).toBe("routing"); + state.pairs = [{ id: "pair", peerId: "z", canReceiveVideoLayers: false, rooms: [], + incoming: [{ id: "voice-flow", publicationId: "voice", selected: true, inputFlowId: null }], outgoing: [] }]; + update(); + const pc = RoomPeerConnection.instances.at(-1)!; + expect(stage()).toMatchObject({ step: "connecting", peerId: "z" }); + pc.connected(); + expect(stage()).toMatchObject({ step: "connected", peerId: "z" }); + state.subscriptions = []; + update(); + expect(stage()).toBeUndefined(); + } finally { session.close(); } +}); + test("selected screen input changes notify only when the media projection changes", async () => { const fixture = await screenFixture(); const { media, state, changed, session } = fixture; diff --git a/tests/viewer-playback.test.ts b/tests/viewer-playback.test.ts index c2b28b0bd..2c86791f1 100644 --- a/tests/viewer-playback.test.ts +++ b/tests/viewer-playback.test.ts @@ -254,7 +254,7 @@ describe("Picture surface between flows", () => { expect(selected).toContain(en["screen.stage.connected"]); expect(selected).not.toContain(en["screen.stage.routing"]); expect(selected).not.toContain("c3-picture-comic"); - const decoded = render({ ...steps[2], stage: { step: "decoded" } }); + const decoded = render({ ...steps[2], stage: { step: "ready" } }); expect(decoded).toContain(" const { state } = fixture(); const rendering = new Map(); const status = (roomId: string) => roomVoiceStatus(state, "listener", roomId, rendering); + // The connecting line is about the voice that was asked for and is not heard yet. + const waiting = (roomId: string) => waitingVoicePublication(state, "listener", roomId, rendering)?.id; expect([status("a"), status("b")]).toEqual(["joining", "joining"]); + expect([waiting("a"), waiting("b")]).toEqual(["voice-a", "voice-b"]); rendering.set("speaker", "playing"); expect([status("a"), status("b")]).toEqual(["connected", "connected"]); + expect(waiting("a")).toBeUndefined(); rendering.set("speaker", "blocked"); expect(status("a")).toBe("joined"); + expect(waiting("a")).toBeUndefined(); rendering.clear(); state.voice.find(voice => voice.sessionId === "listener" && voice.roomId === "a")!.deafened = true; state.subscriptions = state.subscriptions.filter(id => id !== "voice-b"); expect([status("a"), status("b")]).toEqual(["joined", "joined"]); + expect([waiting("a"), waiting("b")]).toEqual([undefined, undefined]); +}); + +test.each<[ReceiveStage | undefined, string]>([ + [undefined, t("en", "channel.voiceDock.voiceConnecting")], + [{ step: "routing" }, t("en", "channel.voiceDock.voiceRouting")], + [{ step: "connecting", peerId: "speaker" }, t("en", "screen.stage.connecting", { name: "Friend" })], + [{ step: "connecting", peerId: "relay" }, t("en", "screen.stage.connectingThrough", { name: "Relay" })], + [{ step: "connecting", peerId: "nobody" }, t("en", "channel.voiceDock.voiceConnecting")], + [{ step: "connected", peerId: "speaker" }, t("en", "channel.voiceDock.voiceConnecting")], +])("a room's connecting line names the step its awaited voice is at: %j", (stage, line) => { + setCopy({ lang: "en" }); + const { state } = fixture(); + Object.assign(state, { + channel: { rooms: [{ id: "a", name: "Room A", participantSessionIds: [] }], hostingMode: "lightweight", ownerId: "owner" }, + users: [{ id: "friend", name: "Friend" }, { id: "other", name: "Relay" }], + sessions: [{ id: "speaker", userId: "friend" }, { id: "relay", userId: "other" }], + }); + const receiveStage = vi.fn(() => stage); + const channel = { sessionId: "listener", receiveStage, voiceActivity: async () => new Map(), voiceMicrophonePending: () => false, + canUnmute: () => true } as unknown as ChannelController; + const html = renderToStaticMarkup(createElement(ChannelVoiceRooms, { channel, state, + joined: state.voice.filter(voice => voice.sessionId === "listener" && voice.roomId === "a"), browsingRoomId: "a", onBrowse() {}, + renderingBySpeaker: new Map(), shortcuts: { bindings: {} as never, mac: false } })); + expect(html).toContain(`${line}`); + expect(receiveStage).toHaveBeenCalledWith("voice-a"); });