Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

fix(media): fix quality convergence and video track ratcheting (#334)

AAAbe311fb6180a
diff --git a/docs/adr/0005-automatic-hybrid-media-routing.md b/docs/adr/0005-automatic-hybrid-media-routing.md
index 4b85aa44..ec88c2e7 100644
--- a/docs/adr/0005-automatic-hybrid-media-routing.md
+++ b/docs/adr/0005-automatic-hybrid-media-routing.md
@@ -232,10 +232,12 @@ Viewer's continuing decoded progress. Screener does not combine loss, RTT,
jitter, bitrate, FPS, resolution, or freezes into a weighted route score.
Routing degradation requires three consecutive complete degraded deltas for the
-same sender identity. Healthy, unknown, stale, reset, source change, or identity
-change clears that run. This is the same persistence semantic used by the Host
-quality warning; a single native limitation interval remains diagnostic.
-
+same exact sender identity. Unknown, stale, reset, source change, or identity
+change clears that run. A newly committed availability or direct-convergence
+edge may establish a new run without first reporting healthy. Quality- and
+root-convergence commits remain disarmed until the new active identity reports
+a fresh healthy delta; an explicit sender reset clears the old latch and starts a
+new sequence. A single native limitation interval remains diagnostic.
When the current sender remains persistently limited, the controller
considers the shallowest affected child first and uses the existing
deterministic candidate filters, ordering, cursor, reservations, and total
@@ -243,9 +245,11 @@ deadline. Candidate Peer parents need a usable source path and available steady
capacity; clear native paths are tried before the remaining deterministic Peer
candidates but are not a hard eligibility tier. Only one candidate runs at a
time and the old route keeps playing. The same Viewer compares fresh,
-overlapping old and candidate receive windows. A P2P candidate commits only after first decoded
-frame and three consecutive windows with no freeze/pause, no lower pixel area or
-rounded FPS, and a strict improvement in at least one of those dimensions.
+overlapping old and candidate receive windows. A P2P candidate commits only
+after first decoded frame, one fresh healthy delta from its exact candidate
+sender, and three consecutive windows with no freeze/pause and no lower pixel
+area or rounded FPS. Strict improvement during overlap is not required because
+shared source adaptation can hide recovery until the old sender closes.
An otherwise complete current-route window with zero decoded frames is compared
as zero delivered pixels, FPS, and bitrate. It can approve only a temporally
overlapping candidate window that actually decoded video and satisfies the same
@@ -253,14 +257,12 @@ freeze, pause, and P2P/SFU partial-order checks. If both routes decode nothing,
the source may be stalled, so the window remains unknown and cannot justify a
move.
Bitrate does not rank P2P candidates because codec and content phase make it
-non-monotonic. Three consecutive comparable non-improving windows reject the
-candidate and advance the existing cursor without resetting the deadline. A
-persistently limited exact candidate sender is also vetoed even when receiver
-comparison approves it. Unknown or incomparable evidence waits only within the
-existing deadline; none of these outcomes creates a score. Old-edge recovery,
-authority change, or deadline aborts the experiment. A successful commit clears
-and rebaselines the affected subtree.
-
+non-monotonic. Three consecutive comparable regressing windows reject the
+candidate and advance the existing cursor without resetting the deadline.
+Unknown candidate-sender evidence waits within the existing deadline; a stale
+relative proof rejects that candidate and advances the existing cursor, while a
+degraded candidate sender cannot commit. None creates a score. Old-edge
+recovery, authority change, or deadline aborts the experiment. A successful commit clears and rebaselines the affected subtree.
The same rule supplies both active parent change and relay abdication. A bad
relay ingress reparents that relay while retaining its subtree. A bad exact
parent-to-child sender moves only that child. If several senders on one parent
@@ -290,12 +292,13 @@ Host-to-SFU ingress proof and each exact SFU-to-Viewer subscription proof remain
separate. A successful Viewer canary cannot authorize any other Viewer, and a
new publication generation invalidates all prior ingress authority.
-After commit, the new active identity starts from unknown and must establish a
-fresh healthy delta before a later degradation can trigger another move. There
-is no periodic wake, weighted prediction, global optimizer, persistent parent
-blacklist, custom congestion controller, or manual SFU layer selection. The
-result converges gradually to a local stable topology: no current degraded edge
-has a proved healthy candidate under the current graph and resource facts. It
+After a quality- or root-convergence commit, the new active identity starts from
+unknown and must establish a fresh healthy delta before another degradation can
+trigger a move. There is no periodic wake, weighted prediction, global
+optimizer, persistent parent blacklist, custom congestion controller, or manual
+SFU layer selection. The result converges gradually to a local stable topology:
+no current degraded edge has a proved healthy candidate under the current graph
+and resource facts. It
does not promise a static mathematical global optimum.
Two pre-share gates constrain this same controller. Peer-only policy removes
diff --git a/docs/adr/0007-path-isolated-representation-quality.md b/docs/adr/0007-path-isolated-representation-quality.md
index 2d7be934..561107a3 100644
--- a/docs/adr/0007-path-isolated-representation-quality.md
+++ b/docs/adr/0007-path-isolated-representation-quality.md
@@ -2,7 +2,7 @@
- Status: Accepted
- Date: 2026-08-19
-- Last reviewed: 2026-08-28
+- Last reviewed: 2026-08-30
## Context
@@ -42,8 +42,13 @@ it does not need a second bitrate, resolution, FPS, or layer-control system.
3. The three recommended profiles and advanced controls supply capture and
sender ceilings plus `degradationPreference`. Every sender reads back the
parameters that the browser actually accepted.
-4. Direct and peer paths leave media adaptation to each `RTCPeerConnection`.
- After accepting an answer, the Host reapplies the current video profile to
+4. Every direct, Browser-relay, and Host SFU video sender owns one
+ `MediaStreamTrack` clone. The original capture or received track remains a
+ source and local presentation track and is never attached directly to an
+ outbound sender. The sender owner retains the game-motion content intent and
+ current enabled state, applies live Host capture constraints to Host-owned
+ clones, and stops the clone on replacement, rollback, failure, unpublish, or
+ teardown. After accepting an answer, the Host still reapplies the current video profile to
the negotiated sender because the browser may replace or rewrite encoding
parameters during negotiation.
5. Auto direct and Browser-relay offers with a proved sender order H.264 before
@@ -52,10 +57,10 @@ it does not need a second bitrate, resolution, FPS, or layer-control system.
VP8 only; manual H264 offers H.264 mode 1 only. Existing edges are not
renegotiated when a later relay gate completes; its result applies to future
children.
-6. The SFU publisher uses the Host source decision for its one publication,
- disables backup codec, sets the selected HIGH ceiling and degradation
- preference, but does not set `screenShareSimulcastLayers`, mutate lower
- encodings, or select a subscriber layer. Pinned LiveKit defaults own the
+6. The SFU publisher uses the Host source decision and one sender-owned clone for
+ its publication, disables backup codec, sets the selected HIGH ceiling and
+ degradation preference, but does not set `screenShareSimulcastLayers`, mutate
+ lower encodings, or select a subscriber layer. Pinned LiveKit defaults own the
selected codec's representation set and source-replacement/republish behavior.
7. LiveKit Dynacast and server send-side BWE remain enabled. AdaptiveStream
remains disabled because a Viewer may relay its received track to peer
@@ -96,6 +101,14 @@ versus encoded-frame progress separated them. Chrome 153 then sustained the
same H.264 path with two senders, Browser relay re-encoding, and one pinned
LiveKit HIGH+LOW publication without backup codec.
+A separate Chrome 151 display-capture experiment distinguished bare cloning
+from sender-owned clone generations. With a preview-only original track, a
+constrained sender could remain adapted after its bitrate budget recovered, but
+retiring that sender and its clone let a new clone return immediately to about
+30 fps at high resolution. Simultaneous clones still showed transient shared-
+source interference, so this decision prevents adaptation inheritance rather
+than claiming complete source isolation.
+
## Consequences
- Screener owns fewer media mechanisms and follows the pinned frameworks'
@@ -106,6 +119,10 @@ LiveKit HIGH+LOW publication without backup codec.
- A constrained Viewer may receive a lower LiveKit representation without
lowering every subscriber, subject to the publisher and network actually
sustaining the framework contract.
+- A retired sender cannot leave its adapted video track attached to the source
+ generation used by a replacement sender. Cloning adds one track adapter per
+ outbound video sender but no additional capture or encoder beyond the sender
+ that already exists.
- A Host may need to lower its explicit share profile when encoder or uplink
capacity is insufficient; Screener does not silently remove constrained
Viewer support.
@@ -124,11 +141,13 @@ LiveKit HIGH+LOW publication without backup codec.
- No quality score, all-pairs probing, periodic rebalancing, or parent switching
outside ADR-0005's native-edge operation.
- No AdaptiveStream while a subscriber can relay the track.
+- No claim that track clones isolate their shared underlying media source.
- No quality or hardware claim from configured options alone.
## References
- [MediaStreamTrack Content Hints](https://www.w3.org/TR/mst-content-hint/)
+- [Media Capture and Streams](https://www.w3.org/TR/mediacapture-streams/)
- [WebRTC](https://www.w3.org/TR/webrtc/)
- [WebRTC Statistics](https://www.w3.org/TR/webrtc-stats/)
- [LiveKit video simulcast and Dynacast](https://docs.livekit.io/transport/media/advanced/)
diff --git a/docs/product/media-quality.md b/docs/product/media-quality.md
index c2068c5e..75640bf2 100644
--- a/docs/product/media-quality.md
+++ b/docs/product/media-quality.md
@@ -13,14 +13,15 @@ adaptation decision.
- Share and source-switch requests ask the Browser for available audio by
default. Missing audio is reported clearly but does not block video-only
sharing.
-- Authoritative pause disables all current capture tracks while retaining the
- room and established routes. Black frames, track mute, or network failure are
- not interpreted as a user pause.
+- Authoritative pause disables the current source and sender-owned tracks while
+ retaining the room and established routes. Black frames, track mute, or
+ network failure are not interpreted as a user pause.
- The Host preview displays the capture stream directly and creates no Viewer or
media route. Hiding the page may pause only that local video element; it must
not intentionally stop capture, encoding, or upload.
-- Live quality changes update the current capture constraints and sender
- ceilings without reopening source selection or replacing a healthy route.
+- Live quality changes update the current capture and Host sender-track
+ constraints plus sender ceilings without reopening source selection or
+ replacing a healthy route.
## Video Profiles
@@ -66,16 +67,27 @@ specific MFT, NVENC, AMF, or QSV implementation.
## Framework-Owned Adaptation
-Each direct or relay PeerConnection keeps its own stock WebRTC congestion and
-quality adaptation. The Host's one SFU publication uses the share-generation
-codec and selected ceiling but no application-defined simulcast ladder or backup
-codec. Pinned LiveKit defaults construct representations; Dynacast aggregates
-demand and server send-side BWE selects subscriber forwarding. AdaptiveStream
-stays disabled because any Viewer may relay its received track.
+Each direct, relay, or SFU video sender owns one clone of its capture or received
+source track. The original track remains a source and local presentation track;
+it is never attached directly to an outbound sender. Replacing or retiring a
+sender also stops its clone, so native adaptation state cannot survive by being
+inherited through the original track. Host pause and live capture constraints
+are propagated to current Host-owned clones.
+
+Each PeerConnection still owns stock WebRTC congestion control and sender
+adaptation. Clones share one underlying media source and therefore do not provide
+complete simultaneous isolation: framework source-wants aggregation may still
+partially reduce frames available to sibling clones. Sibling outputs may differ;
+Screener does not impose a room-wide minimum. The Host's one SFU publication uses
+the share-generation codec and selected ceiling but no application-defined
+simulcast ladder or backup codec. Pinned LiveKit defaults construct
+representations; Dynacast aggregates demand and server send-side BWE selects
+subscriber forwarding. AdaptiveStream stays disabled because any Viewer may
+relay its received track.
Screener does not maintain an application bitrate/resolution ladder, scene
-detector, periodic quality controller, manual SFU layer selector, or whole-room
-lowest-common-denominator target.
+detector, periodic quality controller, manual SFU layer selector, or
+application-defined whole-room lowest-common-denominator target.
## Screen Audio
diff --git a/docs/product/routing-transport.md b/docs/product/routing-transport.md
index f013fc1b..a54084a9 100644
--- a/docs/product/routing-transport.md
+++ b/docs/product/routing-transport.md
@@ -111,13 +111,19 @@ WebRTC and LiveKit own ICE, consent, congestion control, bitrate, frame rate,
resolution, retransmission, reconnect, and SFU layer selection. When the
per-share convergence gate is enabled, Screener uses an exact persistent native
sender limitation only to trigger one measured experiment through the existing
-serial operation. The same Viewer must then prove a P2P candidate strictly
-improves delivered pixel area or rounded FPS without regressing either dimension
-or producing a freeze/pause across three fresh overlapping windows. A complete
+serial operation. Three fresh complete limited deltas from one exact sender may
+trigger that experiment on a newly committed availability or direct-convergence
+edge without a preceding clear delta. A quality- or root-convergence result must
+recover clear before it can rearm. The same Viewer must then prove three fresh
+overlapping P2P candidate windows with no freeze or pause and no lower delivered
+pixel area or rounded FPS, while the exact candidate sender has fresh clear
+native evidence at commit. The candidate need not show a strict gain before the
+retained sender closes. A complete
zero-frame current window counts as zero delivery only when an overlapping
candidate actually decodes clean video; two zero-frame paths remain unknown. A
-persistently limited exact candidate sender cannot commit. Ordinary quality
-moves remain Peer-to-Peer. SFU may
+missing or limited exact candidate sender cannot commit; an expired one-shot
+relative proof rejects that candidate. Ordinary quality moves remain
+Peer-to-Peer. SFU may
join quality work only as Host fanout relief when every current Host-origin Peer
edge, with at least two such edges, is persistently degraded; one Viewer moves
before the controller observes the new topology again. During that overlap, the
diff --git a/docs/research/realtime-quality-adaptation.md b/docs/research/realtime-quality-adaptation.md
index 7e770a8b..76f692fc 100644
--- a/docs/research/realtime-quality-adaptation.md
+++ b/docs/research/realtime-quality-adaptation.md
@@ -1,6 +1,6 @@
# Realtime Screen-Share Quality Evidence
-- Reviewed: 2026-08-29
+- Reviewed: 2026-08-30
- Scope: Browser game capture, codecs, startup adaptation, relay, and LiveKit
- Status: current evidence; product behavior is owned by
[media quality](../product/media-quality.md) and
@@ -75,11 +75,40 @@ deriving endpoint capacity from one RTCStats field. A low-motion control also
sustained 29.8 fps while using only about 0.24 Mbps, so payload bitrate alone is
not a quality measure.
-An additional same-track versus per-sender `MediaStreamTrack.clone()` A/B gave
-no material isolation benefit. A constrained sender fell near 320x180 at 9-10
-fps while the healthy sender stayed near 960x540 at 28-30 fps in both arms; both
-returned to 720p30 after the constrained sender closed. Clone stop did not stop
-the original capture, but source cloning is not an accepted resource remedy.
+An initial same-track versus `MediaStreamTrack.clone()` A/B left a sender on the
+original track in both arms. A constrained sender fell near 320x180 at 9-10 fps
+while the healthier sender stayed near 960x540 at 28-30 fps; both returned to
+720p30 after the constrained sender closed. That experiment established partial
+coupling and correctly rejected a bare clone added alongside an original-track
+sender. It did not test sender-owned clone generations with a preview-only
+original track.
+
+A later Chrome 151 display-capture experiment tested that missing ownership
+boundary. The original track fed only local preview; two PeerConnections each
+owned a separate clone. Constraining one sender to 120 kbps still caused some
+transient cross-clone frame-rate and resolution disturbance, so clones do not
+provide complete simultaneous isolation. The constrained sender then remained
+limited after its budget returned to 5 Mbps. Closing that sender and stopping
+its clone, followed by a new sender with a fresh clone, restored both paths to
+1768x938 at about 30 fps for the full 24-second observation. Reusing the original
+track instead had repeatedly created a low-resolution replacement sender.
+
+This establishes a Chrome 151 generation-ratchet and a standards-based escape:
+an outbound video sender can own one independently constrained clone and retire
+the adapted track with the sender. It does not establish complete source
+isolation, cross-Browser behavior, or a new congestion controller. Any product
+implementation must also preserve live capture-profile changes, `contentHint`,
+Host pause/resume, source replacement rollback, and explicit clone disposal.
+
+Production room evidence showed the same partial coupling and ratchet shape at
+larger scale. One Host sender remained bandwidth-limited while both same-track
+Host outputs fell
+near 320x180 at 7-10 fps, even when its sibling reported no native limitation
+and materially higher outgoing BWE. After the constrained edge departed, the
+surviving path recovered through high-resolution, full-cadence windows. Together
+with the controlled experiments, this supports partial shared-source coupling
+and track-generation retention; it does not establish a universal all-senders
+minimum or quantify its share relative to uplink contention.
## H.264 Root Cause And Gate
@@ -251,8 +280,13 @@ Its cumulative `qualityLimitationDurations` can prove a same-identity interval
spent in `none`, `bandwidth`, or `cpu`; missing or reset values remain unknown.
This supplies a categorical native edge state rather than an application score.
One report is still not a future guarantee, so a candidate must carry real media
-while the working route remains and prove a complete healthy delta before
-commit. Failure remains inconclusive without cutting the old route.
+while the working route remains. A P2P candidate needs fresh healthy evidence
+from its exact sender plus clean overlapping same-Viewer receive windows that do
+not regress delivered dimensions or frame rate. Requiring an immediate strict
+gain can deadlock while the retained and candidate senders still share source
+adaptation. An expired one-shot relative proof rejects that candidate rather than
+holding the operation until its deadline. Failure remains inconclusive without
+cutting the old route.
Production observation on 2026-08-27 showed that one two-second degraded delta
could move an otherwise usable Host Peer edge to an already-active SFU whose
@@ -324,6 +358,7 @@ percentages, and tuning loops are not adopted for this Browser product.
- [MediaStreamTrack Content Hints](https://www.w3.org/TR/mst-content-hint/)
- [Screen Capture](https://www.w3.org/TR/screen-capture/)
- [libwebrtc adaptation](https://webrtc.googlesource.com/src/+/HEAD/video/g3doc/adaptation.md)
+- [libwebrtc source-wants aggregation](https://webrtc.googlesource.com/src/+/refs/heads/main/api/video/video_broadcaster.cc)
- [libwebrtc VP8 encoder](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/video_coding/codecs/vp8/libvpx_vp8_encoder.cc)
- [libwebrtc startup frame dropper](https://webrtc.googlesource.com/src/+/f20ebb8adbf4fa781830e4384c61f732bd28a217/video/adaptation/video_stream_encoder_resource_manager.cc)
- [Chromium WebRTC encoder factory](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.cc)
diff --git a/docs/status.md b/docs/status.md
index 81b1a6eb..5d1011d9 100644
--- a/docs/status.md
+++ b/docs/status.md
@@ -68,16 +68,17 @@ This is the current execution index. Git history owns completed timelines;
when that Viewer departs or the room is deleted. A replacement Host identity
resets physical route ownership without discarding Viewer capacity. Retiring
SFU roots remain only as inactive anchors while Peer descendants reassign.
-- WebRTC/LiveKit own media adaptation. With the per-share convergence gate
- enabled, one fresh degraded native edge may enter the existing serial route
- operation after availability work. A P2P candidate commits only after the same
- Viewer sees first-frame readiness plus three fresh windows that strictly
- improve delivered resolution or rounded FPS without regressing either. A
- complete zero-frame incumbent is zero delivery only against a clean,
- overlapping candidate that actually decodes video. Peer candidates stay
- first; bounded SFU is only the suffix for whole-Host-root
- degradation and retains native publication proof. The gate defaults on in
- source and remains a locked pre-share opt-out.
+- WebRTC/LiveKit own media adaptation. After availability work, one persistently
+ degraded native edge may use the existing serial operation. A P2P candidate
+ needs first-frame readiness, fresh native healthy sender evidence, and three
+ clean receive windows that do not regress resolution or rounded FPS. A zero-
+ frame incumbent is zero delivery only against an overlapping candidate that
+ decodes video. Peer candidates stay first; bounded SFU remains only the whole-
+ Host-root suffix. The pre-share gate defaults on and locks while sharing.
+- Every direct, Browser-relay, and Host SFU video sender owns one clone of its
+ source track; the original remains presentation and source authority only.
+ Replacement, rollback, unpublish, physical LiveKit sender recreation, and
+ teardown retire that clone. Sibling clones may still share source pressure.
- Screener has no custom SFU layer list, quality score, layer selector,
all-pairs probe, parent-wide prediction or periodic rebalancing. P2P and SFU
still recover their current route before actual failure enters reassignment.
@@ -94,9 +95,9 @@ This is the current execution index. Git history owns completed timelines;
## Source/Production Delta
-- Production application code is exact revision
- `2f35f3e161f6f2b64d666d49b67a900085801002`; the following truth checkpoint
- changes documentation only.
+- Production remains exact revision `2f35f3e161f6f2b64d666d49b67a900085801002`;
+ current source fixes degraded-edge eligibility, bounds relative quality proof,
+ rejects stale metrics, and owns one track generation per outbound video sender.
## Active Boundaries
diff --git a/docs/todo.md b/docs/todo.md
index 04ed787b..92b6cae7 100644
--- a/docs/todo.md
+++ b/docs/todo.md
@@ -1,6 +1,6 @@
# Current TODO Ledger
-Last reviewed: 2026-08-29
+Last reviewed: 2026-08-30
Only **Now** is executable. Observations, old branches, experiments, and parked
topics are not implementation authority.
@@ -13,9 +13,12 @@ until their stated boundary is met.
## Parked Product Work
1. **Broader quality optimization.** Weighted/global optimization,
- parent-wide prediction, startup-limited inference, and alternative SFU
- policies remain unaccepted. Reopen only from exact path evidence; do not add
- a score, all-pairs probe, periodic rebalancer, or ordinary SFU preference.
+ parent-wide prediction, startup-limited inference, complete cross-clone
+ source isolation, and alternative SFU policies remain unaccepted. Reopen only
+ from exact path evidence; do not add a score, all-pairs probe, periodic
+ rebalancer, or ordinary SFU preference. Validate whether a quality move merely
+ shifts residual shared-source pressure to the new parent's siblings before
+ widening it.
2. **Startup codec budget.** Reconcile the bounded Auto codec probe with the
first-frame target from measured Browser evidence; do not silently weaken
Auto or move an unproved result into the availability path.
diff --git a/src/client/media/candidate-quality-probe.ts b/src/client/media/candidate-quality-probe.ts
index 971b6575..819bee98 100644
--- a/src/client/media/candidate-quality-probe.ts
+++ b/src/client/media/candidate-quality-probe.ts
@@ -129,7 +129,7 @@ export function sfuCandidateDoesNotRegress(
);
}
-export function p2pCandidateStrictlyImproves(
+export function p2pCandidateDoesNotRegress(
current: ConnectionMetrics,
candidate: ConnectionMetrics,
): boolean | null {
@@ -142,9 +142,7 @@ export function p2pCandidateStrictlyImproves(
candidate.intervalPauseCount === 0 &&
candidate.intervalPauseDurationMs === 0 &&
candidateVideo.pixels >= currentVideo.pixels &&
- candidateVideo.framesPerSecond >= currentVideo.framesPerSecond &&
- (candidateVideo.pixels > currentVideo.pixels ||
- candidateVideo.framesPerSecond > currentVideo.framesPerSecond)
+ candidateVideo.framesPerSecond >= currentVideo.framesPerSecond
);
}
@@ -241,6 +239,6 @@ export class SfuQualityProbe extends ConsecutiveCandidateQualityProbe {
export class P2pQualityProbe extends ConsecutiveCandidateQualityProbe {
constructor() {
- super(p2pCandidateStrictlyImproves);
+ super(p2pCandidateDoesNotRegress);
}
}
diff --git a/src/client/media/host-provisional-child.ts b/src/client/media/host-provisional-child.ts
index 036d3702..73119abc 100644
--- a/src/client/media/host-provisional-child.ts
+++ b/src/client/media/host-provisional-child.ts
@@ -168,7 +168,11 @@ export class HostProvisionalChild {
updateProfile(profile: QualityProfile): Promise<boolean> {
const peer = this.livePeer();
- return peer ? peer.updateProfile(profile) : Promise.resolve(true);
+ return peer ? peer.updateCaptureProfile(profile) : Promise.resolve(true);
+ }
+
+ setPaused(paused: boolean): void {
+ this.livePeer()?.setPaused(paused);
}
async replaceStream(stream: MediaStream): Promise<boolean> {
diff --git a/src/client/media/host-sfu-route.ts b/src/client/media/host-sfu-route.ts
index 61104501..75e25427 100644
--- a/src/client/media/host-sfu-route.ts
+++ b/src/client/media/host-sfu-route.ts
@@ -31,6 +31,7 @@ interface HostPublisherTransport {
deactivate(): Promise<boolean>;
replaceStream(stream: MediaStream): Promise<boolean>;
updateProfile(profile: QualityProfile): Promise<boolean>;
+ setPaused(paused: boolean): void;
getQualityWarning?(): string | null;
getFailureStage?(): SfuPublisherFailureStage | null;
disconnect(): Promise<void>;
@@ -302,6 +303,9 @@ export class HostSfuRoute {
setPaused(paused: boolean): void {
this.paused = paused;
+ for (const slot of this.publishingSlots()) {
+ slot.publisher.setPaused(paused);
+ }
if (paused) {
this.clearPending();
}
diff --git a/src/client/media/quality.ts b/src/client/media/quality.ts
index 400c4b96..49fce497 100644
--- a/src/client/media/quality.ts
+++ b/src/client/media/quality.ts
@@ -213,7 +213,23 @@ export async function applyCaptureProfile(
if (!videoTrack) {
throw new Error(say("host.capture.noSource"));
}
- await videoTrack.applyConstraints(captureConstraints(profile));
+ await applyVideoCaptureProfile(videoTrack, profile);
+}
+
+export function cloneSenderVideoTrack(
+ source: MediaStreamTrack,
+): MediaStreamTrack {
+ const clone = source.clone();
+ clone.contentHint = source.contentHint || "motion";
+ clone.enabled = source.enabled;
+ return clone;
+}
+
+export async function applyVideoCaptureProfile(
+ track: MediaStreamTrack,
+ profile: QualityProfile,
+): Promise<void> {
+ await track.applyConstraints(captureConstraints(profile));
}
export function setMediaPaused(stream: MediaStream, paused: boolean): boolean {
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index d0e83935..35b25439 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -1164,7 +1164,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
Promise.all(
[
...[...peersRef.current.values()].map((peer) =>
- peer.updateProfile(nextProfile),
+ peer.updateCaptureProfile(nextProfile),
),
...(hostProvisionalChildRef.current
? [hostProvisionalChildRef.current.updateProfile(nextProfile)]
@@ -1237,9 +1237,13 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
setNoticeKey("host.pause.noTracksResume");
return;
}
+ for (const peer of peersRef.current.values()) peer.setPaused(false);
+ hostProvisionalChildRef.current?.setPaused(false);
hostSfuRouteRef.current?.setPaused(false);
if (signalRef.current?.setSharingPaused(false) !== true) {
setMediaPaused(activeStream, true);
+ for (const peer of peersRef.current.values()) peer.setPaused(true);
+ hostProvisionalChildRef.current?.setPaused(true);
hostSfuRouteRef.current?.setPaused(true);
signalRef.current?.confirmSharingPaused();
setNoticeKey("host.pause.signalRecovering");
@@ -1254,6 +1258,8 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
setNoticeKey("host.pause.noTracksPause");
return;
}
+ for (const peer of peersRef.current.values()) peer.setPaused(true);
+ hostProvisionalChildRef.current?.setPaused(true);
sharingPausedRef.current = true;
setSharingPaused(true);
hostSfuRouteRef.current?.setPaused(true);
@@ -1661,6 +1667,8 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
if (activeStream) {
setMediaPaused(activeStream, true);
}
+ for (const peer of peersRef.current.values()) peer.setPaused(true);
+ hostProvisionalChildRef.current?.setPaused(true);
hostSfuRouteRef.current?.setPaused(true);
sharingPausedRef.current = true;
setSharingPaused(true);
@@ -2487,7 +2495,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
const viewerState = connected
? "connected"
: (snapshot?.connectionState ?? "routing");
- const detailMetrics = hasMatchingQualityEvidence
+ const detailMetrics = hasCurrentQualityEvidence
? metricsFromQualityEvidence(qualityEvidence)
: snapshot && hasPeerRouteEvidence(snapshot)
? snapshot.metrics
@@ -2500,7 +2508,7 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
: "sfu"
: null,
metrics: detailMetrics,
- direction: hasMatchingQualityEvidence ? "receive" : "send",
+ direction: hasCurrentQualityEvidence ? "receive" : "send",
tag: connected
? undefined
: {
diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.ts
index d5cde2db..9b1671dc 100644
--- a/src/client/sfu/publisher.ts
+++ b/src/client/sfu/publisher.ts
@@ -8,6 +8,8 @@ import type {
import {
audioSenderParameterWarning,
+ applyVideoCaptureProfile,
+ cloneSenderVideoTrack,
configureScreenAudioSender,
configureVideoSender,
needsStartupVideoProfile,
@@ -58,7 +60,9 @@ export type SfuPublisherFailureStage =
interface PublishedTrack {
publication: LocalTrackPublication;
+ sourceTrack: MediaStreamTrack;
rawTrack: MediaStreamTrack;
+ stopOnRelease: boolean;
}
interface PublishedVideoConfiguration {
@@ -205,73 +209,82 @@ export class SfuPublisher {
const audioTrack = stream.getAudioTracks()[0] ?? null;
failureStage = "video-publish";
- const video = await publishTrack(
+ const video = await publishVideoTrack(
room,
videoTrack,
+ profile,
sdk.Track.Source.ScreenShare,
videoPublishOptions(effectiveVideoProfile, videoCodec),
);
- if (!this.owns(room, generation)) {
- return false;
- }
- failureStage = "sender-config";
- const videoConfiguration = await configurePublishedVideo(
- video,
- effectiveVideoProfile,
- () => this.owns(room, generation),
- );
- if (!videoConfiguration || !this.owns(room, generation)) {
- return false;
- }
-
- let audio: PublishedTrack | null = null;
- let audioConfiguration: PublishedAudioConfiguration | null = null;
- let audioWarning: string | null = null;
- if (audioTrack) {
- failureStage = "audio-publish";
- audio = await publishTrack(
- room,
- audioTrack,
- sdk.Track.Source.ScreenShareAudio,
- audioPublishOptions(sdk, profile.screenAudioQuality),
- );
+ let adoptedVideo = false;
+ try {
if (!this.owns(room, generation)) {
return false;
}
- retainPublishedAudioOptions(audio, profile, sdk);
- try {
- const audioSender = publishedAudioSender(audio);
- audioConfiguration = await configurePublishedAudio(
- audio,
- audioSender,
- profile,
- () => this.owns(room, generation),
+ failureStage = "sender-config";
+ const videoConfiguration = await configurePublishedVideo(
+ video,
+ effectiveVideoProfile,
+ () => this.owns(room, generation),
+ );
+ if (!videoConfiguration || !this.owns(room, generation)) {
+ return false;
+ }
+
+ let audio: PublishedTrack | null = null;
+ let audioConfiguration: PublishedAudioConfiguration | null = null;
+ let audioWarning: string | null = null;
+ if (audioTrack) {
+ failureStage = "audio-publish";
+ audio = await publishTrack(
+ room,
+ audioTrack,
+ sdk.Track.Source.ScreenShareAudio,
+ audioPublishOptions(sdk, profile.screenAudioQuality),
);
- if (!audioConfiguration || !this.owns(room, generation)) {
- return false;
- }
- audioWarning = audioConfiguration.warning;
- } catch (error) {
if (!this.owns(room, generation)) {
return false;
}
- audioWarning = audioSenderFailureWarning(error);
+ retainPublishedAudioOptions(audio, profile, sdk);
+ try {
+ const audioSender = publishedAudioSender(audio);
+ audioConfiguration = await configurePublishedAudio(
+ audio,
+ audioSender,
+ profile,
+ () => this.owns(room, generation),
+ );
+ if (!audioConfiguration || !this.owns(room, generation)) {
+ return false;
+ }
+ audioWarning = audioConfiguration.warning;
+ } catch (error) {
+ if (!this.owns(room, generation)) {
+ return false;
+ }
+ audioWarning = audioSenderFailureWarning(error);
+ }
}
- }
- this.video = video;
- this.audio = audio;
- this.appliedVideoProfile = effectiveVideoProfile;
- this.retainSenderParameters(
- videoConfiguration,
- audioConfiguration?.readback ?? null,
- audioWarning,
- audioConfiguration?.sender ?? null,
- );
- this.failureStage = null;
- this.state = "active";
- this.startStats(video);
- return true;
+ this.video = video;
+ this.audio = audio;
+ adoptedVideo = true;
+ this.appliedVideoProfile = effectiveVideoProfile;
+ this.retainSenderParameters(
+ videoConfiguration,
+ audioConfiguration?.readback ?? null,
+ audioWarning,
+ audioConfiguration?.sender ?? null,
+ );
+ this.failureStage = null;
+ this.state = "active";
+ this.startStats(video);
+ return true;
+ } finally {
+ if (!adoptedVideo) {
+ releasePublishedTrack(video);
+ }
+ }
} catch (error) {
if (this.owns(room, generation)) {
this.failureStage = failureStage;
@@ -348,9 +361,19 @@ export class SfuPublisher {
}
const effectiveVideoProfile = startupVideoProfile(profile);
- const nextVideoTrack = requiredVideoTrack(stream);
+ const nextVideoSource = requiredVideoTrack(stream);
+ const nextVideoTrack = cloneSenderVideoTrack(nextVideoSource);
+ try {
+ await applyVideoCaptureProfile(nextVideoTrack, profile);
+ } catch {
+ nextVideoTrack.stop();
+ this.failureStage = "source";
+ return false;
+ }
const nextAudioTrack = stream.getAudioTracks()[0] ?? null;
const previousAudio = this.audio;
+ const previousVideoTrack = previousVideo.rawTrack;
+ let retainedNextVideoTrack = false;
let videoReplaceAttempted = false;
let audioReplaceAttempted = false;
let audioConfiguration: PublishedAudioConfiguration | null = null;
@@ -421,6 +444,9 @@ export class SfuPublisher {
return false;
}
previousVideo.rawTrack = nextVideoTrack;
+ previousVideo.sourceTrack = nextVideoSource;
+ retainedNextVideoTrack = true;
+ previousVideoTrack.stop();
if (previousAudio && nextAudioTrack) {
previousAudio.rawTrack = nextAudioTrack;
}
@@ -463,7 +489,7 @@ export class SfuPublisher {
}
}
if (videoReplaceAttempted) {
- await replacePublishedTrack(previousVideo, previousVideo.rawTrack);
+ await replacePublishedTrack(previousVideo, previousVideoTrack);
if (!this.owns(room, generation)) {
return false;
}
@@ -490,6 +516,10 @@ export class SfuPublisher {
}
throw rollbackError;
}
+ } finally {
+ if (!retainedNextVideoTrack) {
+ nextVideoTrack.stop();
+ }
}
});
}
@@ -565,6 +595,7 @@ export class SfuPublisher {
let videoSucceeded = true;
if (updateVideo) {
try {
+ await applyVideoCaptureProfile(video.rawTrack, profile);
const configured = await configurePublishedVideo(
video,
effectiveVideoProfile,
@@ -596,6 +627,10 @@ export class SfuPublisher {
videoSucceeded = false;
const failureWarning = say("host.fail.sfuParams");
try {
+ await applyVideoCaptureProfile(
+ video.rawTrack,
+ previousVideoProfile,
+ );
const rolledBack = await configurePublishedVideo(
video,
previousVideoProfile,
@@ -736,6 +771,15 @@ export class SfuPublisher {
return this.audioSenderParameters;
}
+ setPaused(paused: boolean): void {
+ if (this.video) {
+ this.video.rawTrack.enabled = !paused;
+ }
+ if (this.audio) {
+ this.audio.rawTrack.enabled = !paused;
+ }
+ }
+
private reapplyAudioAfterReconnect(room: Room, generation: number): void {
void this.enqueue(async () => {
if (!this.owns(room, generation) || this.state !== "active") {
@@ -756,7 +800,7 @@ export class SfuPublisher {
? currentPublishedTrack(
room,
sdk.Track.Source.ScreenShare,
- previousVideo.rawTrack,
+ previousVideo,
)
: null;
const videoSender = currentVideo?.publication.videoTrack?.sender ?? null;
@@ -769,7 +813,7 @@ export class SfuPublisher {
? currentPublishedTrack(
room,
sdk.Track.Source.ScreenShareAudio,
- previousAudio.rawTrack,
+ previousAudio,
)
: null;
const audioSender = currentAudio?.publication.audioTrack?.sender ?? null;
@@ -788,6 +832,33 @@ export class SfuPublisher {
const audio = audioChanged ? currentAudio : previousAudio;
if (videoChanged) {
this.stopStats();
+ const profile = this.desiredProfile;
+ if (!profile) {
+ this.failureStage = "transport";
+ await this.failClosed(room, generation);
+ return false;
+ }
+ const previousRawTrack = video.rawTrack;
+ const nextRawTrack = cloneSenderVideoTrack(video.sourceTrack);
+ let retainedNextTrack = false;
+ try {
+ await applyVideoCaptureProfile(nextRawTrack, profile);
+ await replacePublishedTrack(video, nextRawTrack);
+ if (!this.owns(room, generation)) {
+ return false;
+ }
+ video.rawTrack = nextRawTrack;
+ retainedNextTrack = true;
+ previousRawTrack.stop();
+ } catch {
+ this.failureStage = "transport";
+ await this.failClosed(room, generation);
+ return false;
+ } finally {
+ if (!retainedNextTrack) {
+ nextRawTrack.stop();
+ }
+ }
}
this.video = video;
this.audio = audio;
@@ -940,6 +1011,7 @@ export class SfuPublisher {
this.stopStats();
this.state = "disconnected";
const room = this.room;
+ releasePublishedTrack(this.video);
this.room = null;
this.sdk = null;
this.video = null;
@@ -1148,7 +1220,32 @@ async function publishTrack(
if (!publication.track) {
throw new Error("SFU did not retain the published track");
}
- return { publication, rawTrack };
+ return {
+ publication,
+ sourceTrack: rawTrack,
+ rawTrack,
+ stopOnRelease: false,
+ };
+}
+
+async function publishVideoTrack(
+ room: Room,
+ sourceTrack: MediaStreamTrack,
+ profile: QualityProfile,
+ source: Track.Source,
+ options: TrackPublishOptions,
+): Promise<PublishedTrack> {
+ const rawTrack = cloneSenderVideoTrack(sourceTrack);
+ try {
+ await applyVideoCaptureProfile(rawTrack, profile);
+ const published = await publishTrack(room, rawTrack, source, options);
+ published.sourceTrack = sourceTrack;
+ published.stopOnRelease = true;
+ return published;
+ } catch (error) {
+ rawTrack.stop();
+ throw error;
+ }
}
async function replacePublishedTrack(
@@ -1163,11 +1260,23 @@ async function replacePublishedTrack(
}
async function unpublishTrack(room: Room, published: PublishedTrack): Promise<void> {
- const localTrack = published.publication.track;
- if (!localTrack) {
- throw new Error("SFU publication has no local track");
+ try {
+ const localTrack = published.publication.track;
+ if (!localTrack) {
+ throw new Error("SFU publication has no local track");
+ }
+ await room.localParticipant.unpublishTrack(localTrack, false);
+ } finally {
+ releasePublishedTrack(published);
}
- await room.localParticipant.unpublishTrack(localTrack, false);
+}
+
+function releasePublishedTrack(published: PublishedTrack | null): void {
+ if (!published?.stopOnRelease) {
+ return;
+ }
+ published.stopOnRelease = false;
+ published.rawTrack.stop();
}
async function configurePublishedVideo(
@@ -1245,18 +1354,23 @@ function publishedAudioSender(published: PublishedTrack): RTCRtpSender {
function currentPublishedTrack(
room: Room,
source: Track.Source,
- expectedRawTrack: MediaStreamTrack,
+ expected: PublishedTrack,
): PublishedTrack | null {
const publication = room.localParticipant.getTrackPublication(source);
const rawTrack = publication?.track?.mediaStreamTrack;
if (
!publication ||
!rawTrack ||
- rawTrack !== expectedRawTrack
+ rawTrack !== expected.rawTrack
) {
return null;
}
- return { publication, rawTrack };
+ return {
+ publication,
+ sourceTrack: expected.sourceTrack,
+ rawTrack,
+ stopOnRelease: expected.stopOnRelease,
+ };
}
function retainPublishedAudioOptions(
diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.ts
index c378beae..9bf0449b 100644
--- a/src/client/webrtc/host-peer.ts
+++ b/src/client/webrtc/host-peer.ts
@@ -7,6 +7,8 @@ import {
import { createOpaqueId } from "../lib/opaque-id";
import {
audioSenderParameterWarning,
+ applyVideoCaptureProfile,
+ cloneSenderVideoTrack,
configureScreenAudioSender,
configureVideoSender,
needsStartupVideoProfile,
@@ -53,6 +55,7 @@ export class HostPeer {
private readonly connection: RTCPeerConnection;
private readonly pendingCandidates: SignalCandidate[] = [];
private statsAccumulator = createStatsAccumulator();
+ private senderVideoTrack: MediaStreamTrack | null;
private videoSender: RTCRtpSender | null = null;
private audioSender: RTCRtpSender | null = null;
private statsTimer: number | null = null;
@@ -89,6 +92,10 @@ export class HostPeer {
connectionId = createOpaqueId(),
) {
this.connectionId = connectionId;
+ const sourceVideoTrack = stream.getVideoTracks()[0] ?? null;
+ this.senderVideoTrack = sourceVideoTrack
+ ? cloneSenderVideoTrack(sourceVideoTrack)
+ : null;
this.startupVideoProfilePending = needsStartupVideoProfile(desiredProfile);
this.connection = new RTCPeerConnection({
iceServers: iceConfig.iceServers,
@@ -108,7 +115,7 @@ export class HostPeer {
}
async start(): Promise<boolean> {
- const videoTrack = this.stream.getVideoTracks()[0];
+ const videoTrack = this.senderVideoTrack;
if (!videoTrack) {
this.setError(new Error(say("host.capture.noSource")), say("host.err.createConnection"));
return false;
@@ -149,20 +156,27 @@ export class HostPeer {
}
async replaceStream(nextStream: MediaStream): Promise<boolean> {
- const nextVideoTrack = nextStream.getVideoTracks()[0];
- if (this.disposed || !nextVideoTrack) {
+ const nextSourceVideoTrack = nextStream.getVideoTracks()[0];
+ if (this.disposed || !nextSourceVideoTrack) {
return false;
}
return this.enqueueSenderMutation(async () => {
const videoSender = this.videoSender;
const audioSender = this.audioSender;
- if (this.disposed || !videoSender || !audioSender) {
+ const previousVideoTrack = this.senderVideoTrack;
+ if (
+ this.disposed ||
+ !videoSender ||
+ !audioSender ||
+ !previousVideoTrack
+ ) {
return false;
}
+ const nextVideoTrack = cloneSenderVideoTrack(nextSourceVideoTrack);
+ let retainedNextVideoTrack = false;
const nextAudioTrack = nextStream.getAudioTracks()[0] ?? null;
- const previousVideoTrack = videoSender.track;
const previousAudioTrack = audioSender.track;
this.statsSamplingBlocked = true;
this.statsAccumulator = createStatsAccumulator();
@@ -172,10 +186,13 @@ export class HostPeer {
await videoSender.replaceTrack(nextVideoTrack);
await audioSender.replaceTrack(nextAudioTrack);
} catch (error) {
- await Promise.allSettled([
+ const [videoRollback] = await Promise.allSettled([
videoSender.replaceTrack(previousVideoTrack),
audioSender.replaceTrack(previousAudioTrack),
]);
+ if (videoRollback.status === "rejected") {
+ this.dispose();
+ }
this.setError(error, say("host.fail.source"));
return false;
}
@@ -183,7 +200,10 @@ export class HostPeer {
if (this.disposed) {
return false;
}
+ this.senderVideoTrack = nextVideoTrack;
this.stream = nextStream;
+ retainedNextVideoTrack = true;
+ previousVideoTrack.stop();
this.startupVideoProfilePending = needsStartupVideoProfile(
this.desiredProfile,
);
@@ -200,6 +220,9 @@ export class HostPeer {
this.emit();
return true;
} finally {
+ if (!retainedNextVideoTrack) {
+ nextVideoTrack.stop();
+ }
this.statsAccumulator = createStatsAccumulator();
this.statsSamplingBlocked = false;
}
@@ -207,6 +230,27 @@ export class HostPeer {
}
updateProfile(profile: QualityProfile): Promise<boolean> {
+ return this.updateOwnedProfile(profile, false);
+ }
+
+ updateCaptureProfile(profile: QualityProfile): Promise<boolean> {
+ return this.updateOwnedProfile(profile, true);
+ }
+
+ setPaused(paused: boolean): void {
+ if (this.senderVideoTrack) {
+ this.senderVideoTrack.enabled = !paused;
+ }
+ const audioTrack = this.audioSender?.track;
+ if (audioTrack) {
+ audioTrack.enabled = !paused;
+ }
+ }
+
+ private updateOwnedProfile(
+ profile: QualityProfile,
+ updateCaptureConstraints: boolean,
+ ): Promise<boolean> {
if (this.disposed) {
return Promise.resolve(false);
}
@@ -231,14 +275,26 @@ export class HostPeer {
return this.enqueueSenderMutation(async () => {
const videoSender = this.videoSender;
const audioSender = this.audioSender;
+ const videoTrack = this.senderVideoTrack;
if (
this.disposed ||
!videoSender ||
!audioSender ||
+ !videoTrack ||
requestedRevision !== this.profileRevision
) {
return false;
}
+ if (updateCaptureConstraints) {
+ await applyVideoCaptureProfile(videoTrack, profile);
+ if (
+ this.disposed ||
+ this.senderVideoTrack !== videoTrack ||
+ requestedRevision !== this.profileRevision
+ ) {
+ return false;
+ }
+ }
const updateVideo =
this.connection.connectionState === "connected" &&
(requestedVideo ||
@@ -344,6 +400,8 @@ export class HostPeer {
this.statsTimer = null;
}
this.connection.close();
+ this.senderVideoTrack?.stop();
+ this.senderVideoTrack = null;
}
private bindConnectionEvents(): void {
@@ -517,11 +575,11 @@ export class HostPeer {
) {
return;
}
- const captureTrack = this.videoSender?.track ?? null;
+ const captureTrack = this.senderVideoTrack;
const captureAudioTrack = this.audioSender?.track ?? null;
if (
!captureTrack ||
- this.stream.getVideoTracks()[0] !== captureTrack ||
+ this.videoSender?.track !== captureTrack ||
(this.stream.getAudioTracks()[0] ?? null) !== captureAudioTrack
) {
return;
@@ -544,8 +602,8 @@ export class HostPeer {
this.disposed ||
this.statsSamplingBlocked ||
this.statsAccumulator !== statsAccumulator ||
+ this.senderVideoTrack !== captureTrack ||
this.videoSender?.track !== captureTrack ||
- this.stream.getVideoTracks()[0] !== captureTrack ||
(this.audioSender?.track ?? null) !== captureAudioTrack ||
(this.stream.getAudioTracks()[0] ?? null) !== captureAudioTrack ||
(metrics.trackIdentifier !== null &&
diff --git a/src/server/room-route-controller.ts b/src/server/room-route-controller.ts
index 8b4416ae..8190c237 100644
--- a/src/server/room-route-controller.ts
+++ b/src/server/room-route-controller.ts
@@ -133,6 +133,7 @@ interface Attempt<Resource> {
senderQualityConsecutiveDegradedWindows?: number;
senderQualitySampleTimestampMs?: number;
senderQualityIdentity?: string;
+ relativeQualityApprovedAtMs?: number;
}
interface ChildOperation<Resource> {
@@ -1152,11 +1153,8 @@ export class RoomRouteController<Resource = unknown> {
previous !== undefined &&
input.acceptedAtMs <
previous.lastAcceptedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;
- const senderIdentityChanged =
- sameIdentity && previous?.senderIdentity !== input.senderIdentity;
- const baselineRequired = this.senderQualityBaselines.has(
- input.childPeerId,
- );
+ const baselineRequired =
+ this.senderQualityBaselines.get(input.childPeerId) === true;
if (input.state === "healthy") {
this.senderQualityBaselines.delete(input.childPeerId);
}
@@ -1177,8 +1175,7 @@ export class RoomRouteController<Resource = unknown> {
lastSampleTimestampMs: input.sampleTimestampMs,
lastAcceptedAtMs: input.acceptedAtMs,
consumedAtFactVersion:
- (baselineRequired || senderIdentityChanged) &&
- input.state === "degraded"
+ baselineRequired && input.state === "degraded"
? this.factVersion
: sameSenderIdentity &&
previous?.state === "degraded" &&
@@ -1539,15 +1536,23 @@ export class RoomRouteController<Resource = unknown> {
if (parent?.sessionId !== parentSessionId) {
return [];
}
+ const children = new Set(this.childrenOf(parentPeerId));
for (const [childPeerId, observation] of this.senderQualityObservations) {
if (
observation.parentPeerId === parentPeerId &&
observation.parentSessionId === parentSessionId
) {
- this.senderQualityObservations.delete(childPeerId);
- this.senderQualityBaselines.set(childPeerId, true);
+ children.add(childPeerId);
}
}
+ for (const childPeerId of children) {
+ this.senderQualityObservations.delete(childPeerId);
+ // Reset means the next exact sender sequence is a new observation
+ // window. A quality/root commit still installs the explicit rearm latch
+ // below; a visibility or source reset must not deadlock a persistently
+ // limited edge waiting for a healthy sample.
+ this.senderQualityBaselines.delete(childPeerId);
+ }
if (parentPeerId === this.options.hostPeerId) {
this.sfuPublisherQualityObservation = undefined;
}
@@ -1989,10 +1994,24 @@ export class RoomRouteController<Resource = unknown> {
released: validation.released,
};
}
- const relativeP2pApproved =
+ const relativeP2pProof =
operation.reason === "quality-convergence" &&
attempt.tuple.kind === "peer" &&
proof.relativeQualityApproved === true;
+ if (relativeP2pProof && attempt.relativeQualityApprovedAtMs === undefined) {
+ attempt.relativeQualityApprovedAtMs = nowMs;
+ }
+ const relativeP2pApproved =
+ operation.reason === "quality-convergence" &&
+ attempt.tuple.kind === "peer" &&
+ attempt.relativeQualityApprovedAtMs !== undefined &&
+ nowMs <
+ attempt.relativeQualityApprovedAtMs + VIEWER_QUALITY_EVIDENCE_EXPIRY_MS;
+ const relativeP2pExpired =
+ operation.reason === "quality-convergence" &&
+ attempt.tuple.kind === "peer" &&
+ attempt.relativeQualityApprovedAtMs !== undefined &&
+ !relativeP2pApproved;
const relativeP2pPending =
operation.reason === "quality-convergence" &&
attempt.tuple.kind === "peer" &&
@@ -2031,6 +2050,12 @@ export class RoomRouteController<Resource = unknown> {
};
}
}
+ if (relativeP2pExpired) {
+ // A one-shot client proof cannot be renewed by a late sender sample.
+ // Release this candidate so the existing bounded cursor can try the
+ // next route instead of waiting for the whole operation deadline.
+ return this.candidateFailed(guard, nowMs);
+ }
if (relativeP2pPending) {
return {
accepted: true,
@@ -2040,6 +2065,22 @@ export class RoomRouteController<Resource = unknown> {
released: validation.released,
};
}
+ if (
+ relativeP2pApproved &&
+ (attempt.senderQualityState !== "healthy" ||
+ attempt.senderQualityAcceptedAtMs === undefined ||
+ nowMs >=
+ attempt.senderQualityAcceptedAtMs +
+ VIEWER_QUALITY_EVIDENCE_EXPIRY_MS)
+ ) {
+ return {
+ accepted: true,
+ committed: false,
+ failedPeerIds: failedPeerIdsFrom(validation),
+ activeRevision: this.revision,
+ released: validation.released,
+ };
+ }
if (nativeCandidateProof) {
const candidateQualityState =
attempt.tuple.kind === "sfu" && attempt.tuple.publication === "reuse"
@@ -2622,7 +2663,11 @@ export class RoomRouteController<Resource = unknown> {
}
}
this.requireSenderQualityBaseline(operation.childPeerId, true);
- this.senderQualityBaselines.set(operation.childPeerId, false);
+ this.senderQualityBaselines.set(
+ operation.childPeerId,
+ operation.reason === "quality-convergence" ||
+ operation.reason === "root-convergence",
+ );
this.revision = attempt.revision;
this.operation = undefined;
this.pruneRetiringSfuAnchors();
@@ -2958,6 +3003,7 @@ export class RoomRouteController<Resource = unknown> {
const observation = this.senderQualityObservations.get(peerId);
return Boolean(
edge?.kind === "peer" &&
+ this.senderQualityBaselines.get(peerId) !== true &&
observation?.consumedAtFactVersion !== this.factVersion &&
this.senderQualityPersistentlyDegraded(peerId, edge, nowMs),
);
diff --git a/tests/candidate-quality-probe.test.ts b/tests/candidate-quality-probe.test.ts
index 24c2ebbd..9aab8957 100644
--- a/tests/candidate-quality-probe.test.ts
+++ b/tests/candidate-quality-probe.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import {
P2pQualityProbe,
SfuQualityProbe,
- p2pCandidateStrictlyImproves,
+ p2pCandidateDoesNotRegress,
sfuCandidateDoesNotRegress,
} from "../src/client/media/candidate-quality-probe.ts";
import {
@@ -68,7 +68,7 @@ describe("SFU quality probe", () => {
).toBeNull();
});
- it("requires a strict P2P receive improvement without a tradeoff", () => {
+ it("accepts clean P2P receive windows that do not regress", () => {
const current = metrics(2_000, {
frameWidth: 320,
frameHeight: 180,
@@ -76,7 +76,7 @@ describe("SFU quality probe", () => {
bitrateKbps: 200,
});
expect(
- p2pCandidateStrictlyImproves(
+ p2pCandidateDoesNotRegress(
current,
metrics(2_100, {
frameWidth: 1_280,
@@ -87,7 +87,7 @@ describe("SFU quality probe", () => {
),
).toBe(true);
expect(
- p2pCandidateStrictlyImproves(
+ p2pCandidateDoesNotRegress(
{ ...current, bitrateKbps: null },
metrics(2_100, {
frameWidth: 1_280,
@@ -97,9 +97,9 @@ describe("SFU quality probe", () => {
}),
),
).toBe(true);
- expect(p2pCandidateStrictlyImproves(current, { ...current })).toBe(false);
+ expect(p2pCandidateDoesNotRegress(current, { ...current })).toBe(true);
expect(
- p2pCandidateStrictlyImproves(
+ p2pCandidateDoesNotRegress(
current,
metrics(2_100, {
frameWidth: 1_280,
@@ -109,7 +109,17 @@ describe("SFU quality probe", () => {
),
).toBe(false);
expect(
- p2pCandidateStrictlyImproves(
+ p2pCandidateDoesNotRegress(
+ current,
+ metrics(2_100, {
+ frameWidth: 160,
+ frameHeight: 90,
+ framesPerSecond: 60,
+ }),
+ ),
+ ).toBe(false);
+ expect(
+ p2pCandidateDoesNotRegress(
current,
metrics(2_100, { intervalFreezeCount: 1 }),
),
@@ -134,7 +144,7 @@ describe("SFU quality probe", () => {
});
expect(
- p2pCandidateStrictlyImproves(current(10_000), candidate(11_100)),
+ p2pCandidateDoesNotRegress(current(10_000), candidate(11_100)),
).toBeNull();
for (const timestampMs of [10_000, 13_000, 16_000]) {
expect(
@@ -143,7 +153,7 @@ describe("SFU quality probe", () => {
}
});
- it("keeps the original comparison for overlapping samples", () => {
+ it("compares overlapping samples", () => {
const current = metrics(10_000, {
sampleWindowMs: 1_000,
frameWidth: 320,
@@ -157,35 +167,25 @@ describe("SFU quality probe", () => {
framesPerSecond: 30,
});
- expect(p2pCandidateStrictlyImproves(current, candidate)).toBe(true);
+ expect(p2pCandidateDoesNotRegress(current, candidate)).toBe(true);
});
- it("requires three consecutive strict P2P improvements", () => {
+ it("requires three consecutive non-regressing P2P windows", () => {
const probe = new P2pQualityProbe();
- const current = (timestampMs: number) =>
- metrics(timestampMs, {
- frameWidth: 320,
- frameHeight: 180,
- framesPerSecond: 10,
- });
- const candidate = (timestampMs: number) =>
- metrics(timestampMs, {
- frameWidth: 1_280,
- frameHeight: 720,
- framesPerSecond: 30,
- });
- expect(probe.observe(current(1_000), candidate(1_100))).toBe("pending");
- expect(probe.observe(current(3_000), candidate(3_100))).toBe("pending");
- expect(probe.observe(current(5_000), candidate(5_100))).toBe("approved");
+ expect(probe.observe(metrics(1_000), metrics(1_100))).toBe("pending");
+ expect(probe.observe(metrics(3_000), metrics(3_100))).toBe("pending");
+ expect(probe.observe(metrics(5_000), metrics(5_100))).toBe("approved");
probe.reset();
- expect(probe.observe(current(7_000), candidate(7_100))).toBe("pending");
+ expect(probe.observe(metrics(7_000), metrics(7_100))).toBe("pending");
});
- it("rejects after three comparable non-improving P2P windows", () => {
+ it("rejects after three comparable regressing P2P windows", () => {
const probe = new P2pQualityProbe();
- expect(probe.observe(metrics(1_000), metrics(1_100))).toBe("pending");
- expect(probe.observe(metrics(3_000), metrics(3_100))).toBe("pending");
- expect(probe.observe(metrics(5_000), metrics(5_100))).toBe("rejected");
+ const candidate = (timestampMs: number) =>
+ metrics(timestampMs, { framesPerSecond: 30 });
+ expect(probe.observe(metrics(1_000), candidate(1_100))).toBe("pending");
+ expect(probe.observe(metrics(3_000), candidate(3_100))).toBe("pending");
+ expect(probe.observe(metrics(5_000), candidate(5_100))).toBe("rejected");
});
it("keeps unknown evidence pending instead of counting it as rejection", () => {
diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.ts
index 248d29bb..6f681f4c 100644
--- a/tests/host-peer-tracks.test.ts
+++ b/tests/host-peer-tracks.test.ts
@@ -368,7 +368,21 @@ function withOutboundAudio(
}
function createTrack(kind: "video" | "audio", id: string): MediaStreamTrack {
- return { id, kind } as MediaStreamTrack;
+ const track = Object.assign(new EventTarget(), {
+ id,
+ kind,
+ contentHint: "",
+ enabled: true,
+ getSettings: () => ({}),
+ applyConstraints: vi.fn(async () => undefined),
+ stop: vi.fn(),
+ }) as unknown as MediaStreamTrack;
+ track.clone = vi.fn(() => {
+ const clone = createTrack(kind, id);
+ clone.getSettings = track.getSettings.bind(track);
+ return clone;
+ });
+ return track;
}
function createConfiguredVideoTrack(
@@ -377,11 +391,12 @@ function createConfiguredVideoTrack(
height: number,
frameRate: number,
): MediaStreamTrack {
- return {
- id,
- kind: "video",
- getSettings: () => ({ width, height, frameRate }),
- } as unknown as MediaStreamTrack;
+ const track = createTrack("video", id);
+ track.getSettings = () => ({ width, height, frameRate });
+ track.clone = vi.fn(() =>
+ createConfiguredVideoTrack(id, width, height, frameRate),
+ );
+ return track;
}
function createStream(
@@ -713,6 +728,8 @@ describe("HostPeer source replacement", () => {
await expect(peer.start()).resolves.toBe(true);
await acceptPeerAnswer(peer);
const connection = FakePeerConnection.latest!;
+ const oldSenderVideo = connection.senders[0]!.track!;
+ expect(oldSenderVideo).not.toBe(oldVideo);
expect(connection.transceiverInputs).toHaveLength(2);
expect(connection.transceiverInputs.map(({ init }) => init?.direction)).toEqual([
"sendonly",
@@ -725,14 +742,58 @@ describe("HostPeer source replacement", () => {
peer.replaceStream(createStream(nextVideo, nextAudio)),
).resolves.toBe(true);
- expect(connection.senders[0]?.track).toBe(nextVideo);
+ const nextSenderVideo = connection.senders[0]?.track;
+ expect(nextSenderVideo).not.toBe(nextVideo);
+ expect(nextSenderVideo?.id).toBe(nextVideo.id);
expect(connection.senders[1]?.track).toBe(nextAudio);
+ expect(oldVideo.stop).not.toHaveBeenCalled();
+ expect(oldSenderVideo.stop).toHaveBeenCalledOnce();
expect(connection.transceiverInputs).toHaveLength(2);
expect(connection.senders[0]?.setParameters).toHaveBeenCalledTimes(3);
expect(connection.senders[1]?.appliedMaxBitrates).toEqual([
192_000,
192_000,
]);
+ peer.dispose();
+ expect(nextVideo.stop).not.toHaveBeenCalled();
+ expect(nextSenderVideo?.stop).toHaveBeenCalledOnce();
+ });
+
+ it("keeps capture controls on the sender-owned video clone", async () => {
+ const sourceVideo = createConfiguredVideoTrack(
+ "capture-video",
+ 1920,
+ 1080,
+ 30,
+ );
+ sourceVideo.contentHint = "motion";
+ const sourceAudio = createTrack("audio", "capture-audio");
+ const peer = createPeer(createStream(sourceVideo, sourceAudio));
+
+ await expect(peer.start()).resolves.toBe(true);
+ const senderVideo = FakePeerConnection.latest!.senders[0]!.track!;
+ expect(senderVideo).not.toBe(sourceVideo);
+ expect(senderVideo.contentHint).toBe("motion");
+
+ peer.setPaused(true);
+ expect(senderVideo.enabled).toBe(false);
+ expect(sourceVideo.enabled).toBe(true);
+ peer.setPaused(false);
+ expect(senderVideo.enabled).toBe(true);
+
+ await expect(
+ peer.updateCaptureProfile(QUALITY_PROFILES["1080p60"]),
+ ).resolves.toBe(true);
+ expect(senderVideo.applyConstraints).toHaveBeenLastCalledWith({
+ width: { ideal: 1920, max: 1920 },
+ height: { ideal: 1080, max: 1080 },
+ frameRate: { ideal: 60, max: 60 },
+ });
+ expect(sourceVideo.applyConstraints).not.toHaveBeenCalled();
+
+ peer.dispose();
+ expect(senderVideo.stop).toHaveBeenCalledOnce();
+ expect(sourceVideo.stop).not.toHaveBeenCalled();
});
it("fills a pre-negotiated audio sender that started without a track", async () => {
@@ -912,7 +973,8 @@ describe("HostPeer source replacement", () => {
expect(connection.remoteDescription?.type).toBe("answer");
expect(connection.addedIceCandidates).toEqual([pendingCandidate]);
- expect(connection.senders[0]?.track).toBe(video);
+ expect(connection.senders[0]?.track).not.toBe(video);
+ expect(connection.senders[0]?.track?.id).toBe(video.id);
expect(connection.senders[0]?.setParameters).toHaveBeenCalledOnce();
connection.connectionState = "connected";
@@ -1125,11 +1187,8 @@ describe("HostPeer source replacement", () => {
height: 1080,
frameRate: 59.94,
}));
- const videoTrack = {
- id: "capture-video",
- kind: "video",
- getSettings,
- } as unknown as MediaStreamTrack;
+ const videoTrack = createTrack("video", "capture-video");
+ videoTrack.getSettings = getSettings;
const updates: PeerSnapshot[] = [];
const peer = createPeer(
createStream(videoTrack, null),
@@ -1294,6 +1353,7 @@ describe("HostPeer source replacement", () => {
const connection = FakePeerConnection.latest!;
const videoSender = connection.senders[0]!;
const audioSender = connection.senders[1]!;
+ const initialSenderVideo = videoSender.track;
connection.statsReports.push(
sendStatsReport({
bytesSent: 500_000,
@@ -1339,7 +1399,12 @@ describe("HostPeer source replacement", () => {
videoSender.releaseDeferredReplaceTrack();
await expect(replacing).resolves.toBe(result);
const committedVideo = committed === "old" ? oldVideo : nextVideo;
- expect(videoSender.track).toBe(committedVideo);
+ if (committed === "old") {
+ expect(videoSender.track).toBe(initialSenderVideo);
+ } else {
+ expect(videoSender.track).not.toBe(nextVideo);
+ expect(videoSender.track?.id).toBe(nextVideo.id);
+ }
expect(updates.at(-1)?.metrics.sampleTimestampMs).toBe(
committed === "old" ? 500 : null,
);
@@ -1459,6 +1524,7 @@ describe("HostPeer source replacement", () => {
const connection = FakePeerConnection.latest!;
const videoSender = connection.senders[0]!;
const audioSender = connection.senders[1]!;
+ const oldSenderVideo = videoSender.track;
audioSender.failNextReplace = true;
const nextVideo = createTrack("video", "next-video");
@@ -1467,11 +1533,16 @@ describe("HostPeer source replacement", () => {
peer.replaceStream(createStream(nextVideo, nextAudio)),
).resolves.toBe(false);
- expect(videoSender.replaceTrack).toHaveBeenNthCalledWith(1, nextVideo);
- expect(videoSender.replaceTrack).toHaveBeenNthCalledWith(2, oldVideo);
+ const nextSenderVideo = videoSender.replaceTrack.mock.calls[0]?.[0];
+ expect(nextSenderVideo).not.toBe(nextVideo);
+ expect(nextSenderVideo?.id).toBe(nextVideo.id);
+ expect(videoSender.replaceTrack).toHaveBeenNthCalledWith(2, oldSenderVideo);
expect(audioSender.replaceTrack).toHaveBeenNthCalledWith(1, nextAudio);
expect(audioSender.replaceTrack).toHaveBeenNthCalledWith(2, oldAudio);
- expect(videoSender.track).toBe(oldVideo);
+ expect(videoSender.track).toBe(oldSenderVideo);
+ expect(nextSenderVideo?.stop).toHaveBeenCalledOnce();
+ expect(oldSenderVideo?.stop).not.toHaveBeenCalled();
+ expect(oldVideo.stop).not.toHaveBeenCalled();
expect(audioSender.track).toBe(oldAudio);
});
});
@@ -1620,7 +1691,8 @@ describe("Host provisional child runtime ownership", () => {
await expect(
owner.replaceStream(createStream(replacement, null)),
).resolves.toBe(true);
- expect(connection.senders[0]!.track).toBe(replacement);
+ expect(connection.senders[0]!.track).not.toBe(replacement);
+ expect(connection.senders[0]!.track?.id).toBe(replacement.id);
const activation = owner.activate({
revision: input.revision,
@@ -1637,6 +1709,34 @@ describe("Host provisional child runtime ownership", () => {
});
describe("ViewerRelay downstream ownership", () => {
+ it("gives each downstream sender its own video clone", async () => {
+ const sourceVideo = createTrack("video", "relay-source");
+ const relay = new ViewerRelay(
+ { iceServers: [] },
+ QUALITY_PROFILES["720p30"],
+ { sendSignal: () => true },
+ );
+
+ relay.setChildren(["child-one", "child-two"]);
+ relay.setStream(createStream(sourceVideo, null));
+ await vi.waitFor(() =>
+ expect(FakePeerConnection.instances).toHaveLength(2),
+ );
+ const [firstTrack, secondTrack] = FakePeerConnection.instances.map(
+ (connection) => connection.senders[0]!.track!,
+ );
+ expect(firstTrack).not.toBe(sourceVideo);
+ expect(secondTrack).not.toBe(sourceVideo);
+ expect(firstTrack).not.toBe(secondTrack);
+ expect(firstTrack.contentHint).toBe("motion");
+ expect(secondTrack.contentHint).toBe("motion");
+
+ relay.stop();
+ expect(firstTrack.stop).toHaveBeenCalledOnce();
+ expect(secondTrack.stop).toHaveBeenCalledOnce();
+ expect(sourceVideo.stop).not.toHaveBeenCalled();
+ });
+
const routeCandidate = (
revision: number,
childPeerId: string,
@@ -1800,7 +1900,7 @@ describe("ViewerRelay downstream ownership", () => {
const replacementVideo = createTrack("video", "replacement-video");
relay.setStream(createStream(replacementVideo, null));
await vi.waitFor(() =>
- expect(preparedConnection.senders[0]!.track).toBe(replacementVideo),
+ expect(preparedConnection.senders[0]!.track?.id).toBe(replacementVideo.id),
);
expect(FakePeerConnection.instances).toHaveLength(instanceCount);
preparedConnection.connectionState = "connected";
@@ -2154,7 +2254,10 @@ describe("ViewerRelay downstream ownership", () => {
const nextVideo = createTrack("video", "next-video");
const nextAudio = createTrack("audio", "next-audio");
relay.setStream(createStream(nextVideo, nextAudio));
- await vi.waitFor(() => expect(connection.senders[0]?.track).toBe(nextVideo));
+ await vi.waitFor(() =>
+ expect(connection.senders[0]?.track?.id).toBe(nextVideo.id),
+ );
+ expect(connection.senders[0]?.track).not.toBe(nextVideo);
expect(FakePeerConnection.latest).toBe(connection);
expect(connection.senders[1]?.track).toBe(nextAudio);
diff --git a/tests/room-route-controller.test.ts b/tests/room-route-controller.test.ts
index e93f1848..bebd4217 100644
--- a/tests/room-route-controller.test.ts
+++ b/tests/room-route-controller.test.ts
@@ -262,6 +262,7 @@ function observeSenderState(
state: "healthy" | "degraded";
acceptedAtMs: number;
parentPeerId?: string;
+ senderIdentity?: string;
},
) {
const parentPeerId = input.parentPeerId ?? HOST;
@@ -272,7 +273,8 @@ function observeSenderState(
childPeerId: input.childPeerId,
routeRevision: routes.snapshot().revision,
connectionId: input.connectionId,
- senderIdentity: `${input.connectionId}-rtp\u0000track`,
+ senderIdentity:
+ input.senderIdentity ?? `${input.connectionId}-rtp\u0000track`,
sampleTimestampMs: input.acceptedAtMs,
state: input.state,
acceptedAtMs: input.acceptedAtMs,
@@ -442,6 +444,125 @@ describe("RoomRouteController", () => {
});
});
+ it("lets a newly committed availability edge report persistent degradation before healthy", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ addViewer(routes, A, 2, 0);
+ const joined = routes.reconcile(0).operation!;
+ expect(joined.childPeerId).toBe(A);
+ commitCurrent(routes, 1, "a_from_host");
+
+ for (const acceptedAtMs of [2, 3, 4]) {
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ state: "degraded",
+ acceptedAtMs,
+ }).accepted,
+ ).toBe(true);
+ }
+
+ expect(routes.reconcile(5).operation).toMatchObject({
+ childPeerId: A,
+ reason: "quality-convergence",
+ });
+ });
+
+ it("starts a fresh degradation run when an availability sender identity changes", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ addViewer(routes, A, 2, 0);
+ routes.reconcile(0);
+ commitCurrent(routes, 1, "a_from_host");
+
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ senderIdentity: "old-rtp\u0000track",
+ state: "degraded",
+ acceptedAtMs: 2,
+ }).accepted,
+ ).toBe(true);
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ senderIdentity: "old-rtp\u0000track",
+ state: "degraded",
+ acceptedAtMs: 3,
+ }).accepted,
+ ).toBe(true);
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ senderIdentity: "new-rtp\u0000track",
+ state: "degraded",
+ acceptedAtMs: 4,
+ }).accepted,
+ ).toBe(true);
+ expect(routes.reconcile(4).operation).toBeUndefined();
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ senderIdentity: "new-rtp\u0000track",
+ state: "degraded",
+ acceptedAtMs: 5,
+ }).accepted,
+ ).toBe(true);
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ senderIdentity: "new-rtp\u0000track",
+ state: "degraded",
+ acceptedAtMs: 6,
+ }).accepted,
+ ).toBe(true);
+ expect(routes.reconcile(7).operation).toMatchObject({
+ childPeerId: A,
+ reason: "quality-convergence",
+ });
+ });
+
+ it("lets a reset sender begin a new degradation run without a healthy sample", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ addViewer(routes, A, 2, 0);
+ routes.reconcile(0);
+ commitCurrent(routes, 1, "a_from_host");
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ state: "healthy",
+ acceptedAtMs: 2,
+ }).accepted,
+ ).toBe(true);
+
+ routes.resetSenderQuality(HOST, "host_session", 3);
+ for (const acceptedAtMs of [4, 5, 6]) {
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ state: "degraded",
+ acceptedAtMs,
+ }).accepted,
+ ).toBe(true);
+ }
+ expect(routes.reconcile(7).operation).toMatchObject({
+ childPeerId: A,
+ reason: "quality-convergence",
+ });
+ });
+
it("keeps isolated limitation windows diagnostic", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
@@ -582,8 +703,21 @@ describe("RoomRouteController", () => {
}),
).toMatchObject({
accepted: true,
- committed: true,
+ committed: false,
});
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: "a_from_b",
+ senderIdentity: "a-from-b-rtp\u0000a-track",
+ sampleTimestampMs: 106,
+ state: "healthy",
+ acceptedAtMs: 106,
+ }).committed,
+ ).toBe(true);
expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
kind: "peer",
parentPeerId: B,
@@ -603,13 +737,17 @@ describe("RoomRouteController", () => {
state,
acceptedAtMs: at,
});
- expect(observeMigrated("degraded", 107).accepted).toBe(true);
- expect(routes.reconcile(108).operation).toBeUndefined();
- expect(observeMigrated("healthy", 109).accepted).toBe(true);
- expect(observeMigrated("degraded", 110).accepted).toBe(true);
- expect(observeMigrated("degraded", 111).accepted).toBe(true);
+ for (const acceptedAtMs of [107, 108, 109]) {
+ expect(observeMigrated("degraded", acceptedAtMs).accepted).toBe(true);
+ }
+ expect(routes.reconcile(110).operation).toBeUndefined();
+ routes.touchExternalFacts();
+ expect(routes.reconcile(110).operation).toBeUndefined();
+ expect(observeMigrated("healthy", 111).accepted).toBe(true);
expect(observeMigrated("degraded", 112).accepted).toBe(true);
- expect(routes.reconcile(113).operation?.reason).toBe(
+ expect(observeMigrated("degraded", 113).accepted).toBe(true);
+ expect(observeMigrated("degraded", 114).accepted).toBe(true);
+ expect(routes.reconcile(115).operation?.reason).toBe(
"quality-convergence",
);
});
@@ -678,7 +816,40 @@ describe("RoomRouteController", () => {
expect(
routes.snapshot().upstreamByViewer.get(convergence.childPeerId),
).toMatchObject({ parentPeerId: A });
- expect(routes.reconcile(17).operation).toBeUndefined();
+ const migratedChildPeerId = convergence.childPeerId;
+ for (const acceptedAtMs of [17, 18, 19]) {
+ expect(
+ observeSenderState(routes, {
+ childPeerId: migratedChildPeerId,
+ connectionId: "root_convergence_candidate",
+ parentPeerId: A,
+ state: "degraded",
+ acceptedAtMs,
+ }).accepted,
+ ).toBe(true);
+ }
+ expect(routes.reconcile(20).operation).toBeUndefined();
+ expect(
+ observeSenderState(routes, {
+ childPeerId: migratedChildPeerId,
+ connectionId: "root_convergence_candidate",
+ parentPeerId: A,
+ state: "healthy",
+ acceptedAtMs: 21,
+ }).accepted,
+ ).toBe(true);
+ for (const acceptedAtMs of [22, 23, 24]) {
+ expect(
+ observeSenderState(routes, {
+ childPeerId: migratedChildPeerId,
+ connectionId: "root_convergence_candidate",
+ parentPeerId: A,
+ state: "degraded",
+ acceptedAtMs,
+ }).accepted,
+ ).toBe(true);
+ }
+ expect(routes.reconcile(25).operation?.reason).toBe("quality-convergence");
});
it("gives each unconnected Peer candidate its own bounded progress window", () => {
@@ -794,7 +965,7 @@ describe("RoomRouteController", () => {
expect(routes.routeDiagnosticSnapshot(7_301).children[0]?.quality).toBeNull();
});
- it("does not let one candidate limitation window override relative proof", () => {
+ it("waits for a fresh healthy candidate sender after relative proof", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
@@ -852,10 +1023,138 @@ describe("RoomRouteController", () => {
undefined,
{ relativeQualityApproved: true },
).committed,
+ ).not.toBe(true);
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: "a_from_b",
+ senderIdentity: "a-from-b-rtp\u0000track",
+ sampleTimestampMs: 107,
+ state: "healthy",
+ acceptedAtMs: 107,
+ }).committed,
).toBe(true);
});
- it("does not let unknown candidate sender evidence veto relative proof", () => {
+ it("does not commit a relative proof after its freshness window expires", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, A, 2);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ observePersistentDegraded(routes, A, "a_from_host", 99);
+ routes.reconcile(103);
+ const begin = beginCandidate(routes, {
+ nowMs: 104,
+ connectionId: "a_from_b_stale_proof",
+ reservation: { kind: "direct" },
+ });
+ const current = begin.operation!.current!;
+ const guard: CandidateGuard = {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_b_stale_proof",
+ };
+ expect(routes.candidateTransportConnected(guard, 105).accepted).toBe(true);
+
+ expect(
+ routes.candidateReady(guard, 105, undefined, {
+ relativeQualityApproved: true,
+ }).committed,
+ ).not.toBe(true);
+ expect(
+ routes.candidateReady(guard, 109, undefined, {
+ relativeQualityApproved: true,
+ }).committed,
+ ).not.toBe(true);
+ for (const acceptedAtMs of [5_105, 5_106, 5_107]) {
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ state: "degraded",
+ acceptedAtMs,
+ }).accepted,
+ ).toBe(true);
+ }
+ const settled = routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: guard.connectionId,
+ senderIdentity: "stale-proof-rtp\u0000track",
+ sampleTimestampMs: 5_111,
+ state: "healthy",
+ acceptedAtMs: 5_111,
+ });
+ expect(settled).toMatchObject({ accepted: true, committed: false });
+ expect(routes.snapshot().operation).toBeUndefined();
+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ parentPeerId: HOST,
+ connectionId: "a_from_host",
+ });
+ });
+
+ it("abandons a pending quality move when the incumbent recovers", () => {
+ const routes = controller(2, { qualityConvergenceEnabled: true });
+ addViewer(routes, A, 2);
+ addViewer(routes, B, 2);
+ routes.hydrateEdge(A, peerEdge(HOST, "a_from_host"));
+ routes.hydrateEdge(B, peerEdge(HOST, "b_from_host"));
+ observePersistentDegraded(routes, A, "a_from_host", 99);
+ routes.reconcile(103);
+ const begin = beginCandidate(routes, {
+ nowMs: 104,
+ connectionId: "a_from_b_incumbent_recovery",
+ reservation: { kind: "direct" },
+ });
+ const current = begin.operation!.current!;
+ const guard: CandidateGuard = {
+ childPeerId: A,
+ childSessionId: `${A}_session`,
+ revision: current.revision,
+ connectionId: "a_from_b_incumbent_recovery",
+ };
+ expect(
+ routes.candidateReady(guard, 105, undefined, {
+ relativeQualityApproved: true,
+ }).committed,
+ ).not.toBe(true);
+
+ expect(
+ observeSenderState(routes, {
+ childPeerId: A,
+ connectionId: "a_from_host",
+ state: "healthy",
+ acceptedAtMs: 106,
+ }).accepted,
+ ).toBe(true);
+ expect(routes.snapshot().operation).toBeUndefined();
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: guard.connectionId,
+ senderIdentity: "late-healthy-rtp\u0000track",
+ sampleTimestampMs: 107,
+ state: "healthy",
+ acceptedAtMs: 107,
+ }).accepted,
+ ).toBe(false);
+ expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
+ parentPeerId: HOST,
+ connectionId: "a_from_host",
+ });
+ });
+
+ it("persists relative proof while candidate sender evidence is unknown", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
@@ -900,6 +1199,19 @@ describe("RoomRouteController", () => {
undefined,
{ relativeQualityApproved: true },
).committed,
+ ).not.toBe(true);
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: "a_from_b",
+ senderIdentity: "a-from-b-rtp\u0000track",
+ sampleTimestampMs: 107,
+ state: "healthy",
+ acceptedAtMs: 107,
+ }).committed,
).toBe(true);
expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
kind: "peer",
@@ -1008,6 +1320,19 @@ describe("RoomRouteController", () => {
undefined,
{ relativeQualityApproved: true },
).committed,
+ ).not.toBe(true);
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: secondParent,
+ parentSessionId: `${secondParent}_session`,
+ childPeerId: A,
+ routeRevision: second.current!.revision,
+ connectionId: "second_quality_candidate",
+ senderIdentity: "second-quality-rtp\u0000track",
+ sampleTimestampMs: 111,
+ state: "healthy",
+ acceptedAtMs: 111,
+ }).committed,
).toBe(true);
expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
parentPeerId: secondParent,
@@ -1196,7 +1521,7 @@ describe("RoomRouteController", () => {
});
});
- it("uses relative proof after candidate native state expires", () => {
+ it("waits for a fresh candidate sender after prior evidence expires", () => {
const routes = controller(2, { qualityConvergenceEnabled: true });
addViewer(routes, A, 2);
addViewer(routes, B, 2);
@@ -1282,6 +1607,19 @@ describe("RoomRouteController", () => {
undefined,
{ relativeQualityApproved: true },
).committed,
+ ).not.toBe(true);
+ expect(
+ routes.observeSenderQualityEvidence({
+ parentPeerId: B,
+ parentSessionId: `${B}_session`,
+ childPeerId: A,
+ routeRevision: current.revision,
+ connectionId: "a_from_b_stale",
+ senderIdentity: "a-stale-rtp\u0000a-track",
+ sampleTimestampMs: 5_105,
+ state: "healthy",
+ acceptedAtMs: 5_105,
+ }).committed,
).toBe(true);
expect(routes.snapshot().upstreamByViewer.get(A)).toMatchObject({
parentPeerId: B,
diff --git a/tests/route-transition.test.ts b/tests/route-transition.test.ts
index 165d604e..138e1f48 100644
--- a/tests/route-transition.test.ts
+++ b/tests/route-transition.test.ts
@@ -76,6 +76,7 @@ function createFakePublisher(log: string[], label: string) {
}),
replaceStream: vi.fn(async () => true),
updateProfile: vi.fn(async () => true),
+ setPaused: vi.fn(),
disconnect: vi.fn(async () => {
log.push(`${label}:disconnect`);
}),
@@ -559,6 +560,7 @@ describe("minimal route transition contracts", () => {
});
await route.acceptConfig(sfuConfig(1));
route.setPaused(true);
+ expect(publishers[0]?.setPaused).toHaveBeenCalledWith(true);
await route.acceptAndWait({
revision: 2,
diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.ts
index 0da72a84..79fe3cee 100644
--- a/tests/sfu-client.test.ts
+++ b/tests/sfu-client.test.ts
@@ -326,11 +326,21 @@ const qualityProfile = {
} as const;
function track(kind: "video" | "audio", id: string): MediaStreamTrack {
- return Object.assign(new EventTarget(), {
+ const mediaTrack = Object.assign(new EventTarget(), {
id,
kind,
+ contentHint: "",
+ enabled: true,
getSettings: () => ({}),
- }) as MediaStreamTrack;
+ applyConstraints: vi.fn(async () => undefined),
+ stop: vi.fn(),
+ }) as unknown as MediaStreamTrack;
+ mediaTrack.clone = vi.fn(() => {
+ const clone = track(kind, id);
+ clone.getSettings = mediaTrack.getSettings.bind(mediaTrack);
+ return clone;
+ });
+ return mediaTrack;
}
function remoteTrack(
@@ -758,7 +768,10 @@ describe("SfuPublisher", () => {
const room = livekit.state.rooms[0];
const sender = room.localParticipant.publications[0].track.sender;
- expect(room.localParticipant.publishTrack).toHaveBeenNthCalledWith(1, video, {
+ const publishedVideo = room.localParticipant.publishTrack.mock.calls[0]?.[0];
+ expect(publishedVideo).not.toBe(video);
+ expect(publishedVideo?.id).toBe(video.id);
+ expect(room.localParticipant.publishTrack).toHaveBeenNthCalledWith(1, publishedVideo, {
source: Track.Source.ScreenShare,
backupCodec: false,
videoCodec: "vp8",
@@ -807,9 +820,41 @@ describe("SfuPublisher", () => {
await expect(publisher.deactivate()).resolves.toBe(true);
expect(room.localParticipant.unpublishTrack).toHaveBeenCalledTimes(2);
+ expect(publishedVideo?.stop).toHaveBeenCalledOnce();
+ expect(video.stop).not.toHaveBeenCalled();
expect(room.disconnect).not.toHaveBeenCalled();
});
+ it("owns SFU video clone controls without stopping the capture source", async () => {
+ const publisher = new SfuPublisher();
+ const sourceVideo = track("video", "capture-video");
+ sourceVideo.contentHint = "motion";
+ await publisher.connect(connection);
+ await publisher.activate(stream(sourceVideo), qualityProfile);
+ const publishedVideo = livekit.state.rooms[0].localParticipant.publications[0]
+ .rawTrack;
+
+ expect(publishedVideo).not.toBe(sourceVideo);
+ expect(publishedVideo.contentHint).toBe("motion");
+ publisher.setPaused(true);
+ expect(publishedVideo.enabled).toBe(false);
+ expect(sourceVideo.enabled).toBe(true);
+ publisher.setPaused(false);
+
+ await expect(
+ publisher.updateProfile(QUALITY_PROFILES["720p30"]),
+ ).resolves.toBe(true);
+ expect(publishedVideo.applyConstraints).toHaveBeenLastCalledWith({
+ width: { ideal: 1280, max: 1280 },
+ height: { ideal: 720, max: 720 },
+ frameRate: { ideal: 30, max: 30 },
+ });
+
+ await publisher.disconnect();
+ expect(publishedVideo.stop).toHaveBeenCalledOnce();
+ expect(sourceVideo.stop).not.toHaveBeenCalled();
+ });
+
it.each([
["saver", 64_000],
["music", 128_000],
@@ -841,13 +886,18 @@ describe("SfuPublisher", () => {
it("fails closed when initial sender configuration is rejected", async () => {
const disconnected = vi.fn();
const publisher = new SfuPublisher({ onDisconnected: disconnected });
+ const sourceVideo = track("video", "video-1");
await publisher.connect(connection);
livekit.state.nextSenderParameterError = new Error("parameters rejected");
await expect(
- publisher.activate(stream(track("video", "video-1")), qualityProfile),
+ publisher.activate(stream(sourceVideo), qualityProfile),
).rejects.toThrow("parameters rejected");
+ const publishedVideo = livekit.state.rooms[0].localParticipant.publications[0]
+ .rawTrack;
+ expect(publishedVideo.stop).toHaveBeenCalledOnce();
+ expect(sourceVideo.stop).not.toHaveBeenCalled();
expect(livekit.state.rooms[0].disconnect).toHaveBeenCalledWith(false);
expect(disconnected).toHaveBeenCalledOnce();
expect(publisher.getSenderParameters()).toBeNull();
@@ -1085,9 +1135,10 @@ describe("SfuPublisher", () => {
it("rebinds republished tracks after a full reconnect", async () => {
const publisher = new SfuPublisher();
+ const sourceVideo = track("video", "video-1");
await publisher.connect(connection);
await publisher.activate(
- stream(track("video", "video-1"), track("audio", "audio-1")),
+ stream(sourceVideo, track("audio", "audio-1")),
{ ...qualityProfile, screenAudioQuality: "music" },
);
await expect(
@@ -1099,6 +1150,7 @@ describe("SfuPublisher", () => {
const room = livekit.state.rooms[0];
const oldVideoPublication = room.localParticipant.publications[0];
const oldAudioPublication = room.localParticipant.publications[1];
+ const oldPublishedVideo = oldVideoPublication.rawTrack;
await room.localParticipant.republishForReconnect();
const videoPublication = room.localParticipant.getTrackPublication(
@@ -1113,8 +1165,12 @@ describe("SfuPublisher", () => {
room.emit(RoomEvent.Reconnected);
await vi.waitFor(() =>
- expect(publisher.getAudioSenderParameters()).not.toBeNull(),
+ expect(videoPublication.track.currentTrack).not.toBe(oldPublishedVideo),
);
+ expect(publisher.getAudioSenderParameters()).not.toBeNull();
+ expect(videoPublication.track.currentTrack.id).toBe(sourceVideo.id);
+ expect(oldPublishedVideo.stop).toHaveBeenCalledOnce();
+ expect(sourceVideo.stop).not.toHaveBeenCalled();
expect(audioPublication.track.sender.setParameters).not.toHaveBeenCalled();
expect(audioPublication.track.sender.parameters.encodings[0]?.maxBitrate).toBe(
192_000,
@@ -1485,6 +1541,7 @@ describe("SfuPublisher", () => {
await publisher.connect(connection);
await publisher.activate(stream(previousVideo), qualityProfile);
const localTrack = livekit.state.rooms[0].localParticipant.publications[0].track;
+ const previousPublishedVideo = localTrack.currentTrack;
localTrack.replaceTrack.mockImplementationOnce(async (replacement) => {
localTrack.currentTrack = replacement;
throw new Error("sender swap failed after applying");
@@ -1492,9 +1549,16 @@ describe("SfuPublisher", () => {
await expect(publisher.replaceStream(stream(nextVideo))).resolves.toBe(false);
- expect(localTrack.replaceTrack).toHaveBeenNthCalledWith(1, nextVideo);
- expect(localTrack.replaceTrack).toHaveBeenNthCalledWith(2, previousVideo);
- expect(localTrack.currentTrack).toBe(previousVideo);
+ const nextPublishedVideo = localTrack.replaceTrack.mock.calls[0]?.[0];
+ expect(nextPublishedVideo).not.toBe(nextVideo);
+ expect(nextPublishedVideo?.id).toBe(nextVideo.id);
+ expect(localTrack.replaceTrack).toHaveBeenNthCalledWith(
+ 2,
+ previousPublishedVideo,
+ );
+ expect(localTrack.currentTrack).toBe(previousPublishedVideo);
+ expect(nextPublishedVideo?.stop).toHaveBeenCalledOnce();
+ expect(previousPublishedVideo.stop).not.toHaveBeenCalled();
});
it("uses the screen audio preset when a replacement adds audio", async () => {
@@ -1544,6 +1608,7 @@ describe("SfuPublisher", () => {
await publisher.connect(connection);
await publisher.activate(stream(previousVideo), qualityProfile);
const localTrack = livekit.state.rooms[0].localParticipant.publications[0].track;
+ const previousPublishedVideo = localTrack.currentTrack;
localTrack.sender.setParameters.mockRejectedValueOnce(
new Error("replacement parameters rejected"),
);
@@ -1553,7 +1618,7 @@ describe("SfuPublisher", () => {
).resolves.toBe(false);
expect(localTrack.replaceTrack).toHaveBeenCalledTimes(2);
- expect(localTrack.currentTrack).toBe(previousVideo);
+ expect(localTrack.currentTrack).toBe(previousPublishedVideo);
expect(localTrack.sender.setParameters).toHaveBeenCalledTimes(3);
expect(publisher.getSenderParameters()?.applied.maxBitrate).toBe(8_000_000);
expect(publisher.getQualityWarning()).toBe("切换 SFU 分享来源失败");