Compare commits

...
  • fix(media): stabilize native sharing and relay recovery (#521)
    Windows native sharing could end when a refresh frame carried an older timestamp. Concurrent route preparation, source changes and upstream reconnection could also disturb an already committed relay path. This maintenance phase fixes those owners and improves large-frame reception, App return handling and update visibility.
    
    The existing 2.x wire and storage contracts are unchanged. The App update indicator uses the approved App's build identity and shares the launcher's release check and download component.
    
    Validation: `npm run check`, `node scripts/check-go.mjs --all`, repository hygiene, and the existing controlled three-viewer H.264 routing/recovery and App-return checks. The [cross-platform v2.5.3 candidate build](https://github.com/TNTcraftHIM/Piik/actions/runs/41716820555) passes all six App and three Server packages. Its only follow-up changes align the App card and retain the version label's accessible text in visual mode; those changes pass type checks, focused tests and desktop/mobile browser checks in both themes.
    
    Refs #519.
    
    ## Release notes
    
    **Piik, now in your pocket.**
    
    Piik App supports Android screen sharing, with touch controls for a friend's computer.
    
    **手机,也能开播。**
    
    Piik App 支持 Android 屏幕分享,也能用手机控制朋友的电脑。
    
    ### English
    
    Piik v2.5.3 improves Windows native sharing, relay recovery and App update notices. It preserves the existing 2.x compatibility baseline.
    
    - Fix backward refresh-frame timestamps that could end Windows native sharing, and improve H.264 compatibility for small native outputs.
    - Preserve committed routes and relay children during upstream reconnection, overlapping route preparation and source changes.
    - Reduce large-frame UDP burst loss, keep quality comparisons within their route deadline, and release retired media-statistics work promptly.
    - Show App updates from the connected page as well as the launcher. Refresh App identity after returning to the browser and allow local-network permission prompts to finish.
    - Use AtomGit for the download mirror and show a clear startup error when page controls cannot load.
    
    Update the App and self-hosted Server to receive all fixes, then refresh open pages. Existing room data and browser settings are retained.
    
    ### 中文
    
    Piik v2.5.3 改善 Windows 原生分享、转发线路恢复和 App 更新提醒,沿用现有 2.x 兼容基线。
    
    - 修复补帧时间戳倒退导致 Windows 原生分享结束的问题,改善小尺寸原生画面的 H.264 兼容性。
    - 上游重连、线路准备重叠或分享源变化时,保留已生效的线路和下游转发。
    - 减少大画面帧突发传输时的 UDP 丢包,让画质比较遵守当前线路时限,并及时释放已退出的媒体统计任务。
    - 在已联动网页和启动页显示 App 更新提醒;返回浏览器后刷新 App 信息,并允许本地网络权限提示完成。
    - 下载镜像改用 AtomGit;页面控件加载失败时显示清晰的错误提示。
    
    请更新 App 和自部署 Server,以获得全部修复,随后刷新已打开的页面。已有房间数据与浏览器设置保留。
64 changed files with 1288 additions and 336 deletions

No files matched your search

+3 -3
View File
@@ -19,7 +19,7 @@ import (
// The Browser notice and operator checker read the same published release.
const defaultReleaseAPIURL = "https://api.github.com/repos/TNTcraftHIM/Piik/releases/latest"
const mirrorReleaseAPIURL = "https://gitee.com/api/v5/repos/TNTcraftHIM/Piik/releases"
const mirrorReleaseAPIURL = "https://api.atomgit.com/api/v5/repos/TNTcraftHIM/Piik/releases"
// deploy/check-release.sh forwards these codes without installing anything.
const (
@@ -29,7 +29,7 @@ const (
releaseTimeout = 5 * time.Second
releaseURLPrefix = "https://github.com/TNTcraftHIM/Piik/releases/tag/"
releaseAPIHost = "api.github.com"
mirrorReleasePrefix = "https://gitee.com/TNTcraftHIM/Piik/releases/tag/"
mirrorReleaseURL = "https://atomgit.com/TNTcraftHIM/Piik/releases"
)
var fullRevisionPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
@@ -288,5 +288,5 @@ func parseMirrorReleaseMetadata(payload []byte) (version, revision, releaseURL s
if !ok {
return "", "", "", false
}
return version, revision, mirrorReleasePrefix + version, true
return version, revision, mirrorReleaseURL, true
}
+1 -1
View File
@@ -309,7 +309,7 @@ func TestMirrorFallbackUsesOriginalSourceAndCompleteStablePagination(t *testing.
}))
defer mirror.Close()
result := checkRelease(t.Context(), deployedVersion, deployedRevision, primary.URL, "operator-secret", mirror.URL)
assertResult(t, result, statusUpdateAvailable, deployedVersion, latestVersion, deployedRevision, latestRevision, mirrorReleasePrefix+latestVersion)
assertResult(t, result, statusUpdateAvailable, deployedVersion, latestVersion, deployedRevision, latestRevision, mirrorReleaseURL)
if mirrorCalls != 2 {
t.Fatalf("mirror calls = %d", mirrorCalls)
}
+6 -2
View File
@@ -57,8 +57,12 @@ over the existing official App.
### macOS blocks first launch
Current Mac builds are unsigned and unnotarized. To open one, verify the
download and allow this App through macOS's first-launch check:
Current Mac builds are not Developer ID-signed or notarized by Apple. For
first-launch warnings, verify the download and allow this App through macOS:
If macOS reports malware, says the App will damage your computer, or moves it
to Trash automatically, [report the exact alert and download link](#reporting-a-problem).
Do not use the quarantine command below for those alerts.
1. Download the matching Mac ZIP from the project's Releases and compare its
SHA-256 with the checksum published for that release. In Terminal, run
+3
View File
@@ -52,6 +52,9 @@ outline: 2
当前 Mac 版本未进行 Developer ID 签名和 Apple 公证。首次打开时,先校验下载文件,再为这个 App 放行:
若 macOS 提示恶意软件、「会损坏你的电脑」,或自动将 App 移到废纸篓,
请[保留完整提示和下载链接反馈](#反馈问题),不要使用下方的隔离标记命令。
1. 从项目 Releases 下载对应的 Mac ZIP,核对同一版本公布的 SHA-256。
在终端运行 `shasum -a256 ~/Downloads/piik-app-darwin-arm64.zip`;
Intel Mac 将文件名中的 `arm64` 换为 `amd64`。校验不一致时应重新下载,不要绕过警告。
+4
View File
@@ -513,6 +513,10 @@ an absent optional property or readback no longer rejects an otherwise usable
encoder. Required CBR, bitrate and GOP checks, Constrained Baseline bitstream
admission, actual H.264 output and Auto's measured frame cadence retain their owners.
The [H264 burst and recovery assessment](./webrtc-encoder-pool.md#h264-burst-and-recovery)
records the measured scene-change queue delay and the rejected one-frame HRD
override. Average bitrate and optional low-latency mode do not bound each AU.
Issue [#432](https://github.com/TNTcraftHIM/Piik/issues/432) reports more visible
blocking with native H.264 than VP8 on v1.6.7. Review of its attached Browser
report confirms 720p30 in both comparison windows, roughly 11 Mbps received,
+6
View File
@@ -426,6 +426,12 @@ Pion's existing 1.5 pacing headroom. This follows the
Both queue controls must pass; correcting old-packet delay alone does not
establish healthy Native sending.
A 2026-11-03 2.x headroom-only comparison retained that same healthy-link gate
and diagnostic observation code. Raising headroom to 2.5 downgraded the high
output after 4.27 seconds. The matching 1.5 control completed 12.19 seconds,
retained the high output without congestion and received about 4.8–5.02 Mbps.
The larger headroom was rejected; the existing 1.5 setting remains.
Allocation also distinguishes source measurements from changed capacity. A
stable 1 Mbps connection must not drop its output merely because that source's
measurement changes from 900 kbps to 1.05 Mbps, or because a lower output's
+3 -2
View File
@@ -916,8 +916,9 @@ For 200 samples, Browser input dispatch and AES-GCM-to-send each had a 0.1 ms
at the 95th percentile, matching the short timer rather than a rendering-frame
wait. Encrypted Pion delivery through Host authorization to a recorded input
sink was 0.13 ms at the 95th percentile. No slow point appeared in these local
components. End-to-end timing still needs target execution, Native capture and
encoding, remote transport and physical display response in the same trial.
components. The later [Native H264 end-to-end control](./webrtc-encoder-pool.md#h264-burst-and-recovery)
includes real OS input, capture, encoding and Browser compositor presentation;
its remaining scene-change delay is traced to the send queue.
The reviewed implementation uses WGC capture and the documented Windows input
API, without game-memory access, injected game code or an input driver.
+30
View File
@@ -469,6 +469,36 @@ path remains. The four-second decision budget is unchanged. Current grouping
at that point still folded multiple weak consumers into one low budget; the
following integration addresses that independent requirement.
#### H264 Burst And Recovery
A 2026-11-03 Windows 2.x control traced Native H264 scene-change delay through
normal Host approval, real clicks on an owned window, capture and Browser
presentation. At a 5 Mbps / 30 fps ceiling, the actual 826×612 output supplied
six AUs of 170–181 KB, each marked `Recovery=false`.
Matching source packets and received frame timestamps placed 154–168 ms in the
send queue before dequeue; the segmented writer control observed no synchronous
write over 5 ms. The five-click input-to-compositor median was 235.1 ms.
A follow-up with the original settings parsed all six 172–182 KB AUs through
Pion's H264 reader with SEI included. Each contained one type-1 non-IDR VCL NAL;
AUD, prefix NAL and Annex-B start codes accounted for only 19 bytes. There was
no SEI or trailing zero padding. All 139 observed wire markers matched their
source AU uniquely, and the six large AUs spent 155–170 ms in the send queue.
The burst is coded picture data, not removable filler. `Recovery=false` remains
an independent encoder flag; a type-1 NAL does not identify its slice type.
A candidate applied optional H264
[HRD buffer size](https://learn.microsoft.com/en-us/windows/win32/directshow/avenccommonbuffersize-property)
in bytes, using one frame of the current rate at initialization and live updates.
In the same control it reduced the largest AU to 38 KB and the median to
54.5 ms, with matching sampled colours. The existing 76-second
`TestAdaptiveOutputFixture` then rejected it: after 2 Mbps → 100 kbps → 2 Mbps,
output remained 320×180 at about 120–124 kbps through the end, with no restored
full-size frames. Optional setters did not avoid the earlier recovery failure.
The candidate was removed and was not applied to the Rust MF owner. Its latency
gain does not justify restoring the one-frame HRD override; the existing
encoding and pacing settings remain.
### Budget Restoration
Transport allocation and encoder resolution recover separately. Replaying the
+4 -2
View File
@@ -215,8 +215,10 @@ in [introduction design](./public-introduction.md) and the [website runbook](../
Queued events retain physical-owner validity until the final serialized write;
readiness commits also require the resource's current state. Reused logical
IDs do not identify a replacement instance. A child's attachment failure does
not retire its shared producer. New subscriptions follow the old owner's
retirement, including repeated cleanup callers.
not retire its shared producer. Replacing an exclusive subscription waits for
the current owner's retirement; repeated cleanup callers await that same work.
For shared leases, the owning controller confirms the replacement before
releasing a healthy lease.
Closing a Browser connection may leave its API promises pending. Its owner
cancels the corresponding waits so a serialized successor never depends on
completion from a retired connection; late results still need identity checks.
+5
View File
@@ -159,6 +159,9 @@ voice readiness never becomes evidence that a video frame has arrived.
## Reconciliation
One room controller owns the committed graph and one bounded child transition.
Committed child membership applies immediately, independently of asynchronous
upstream activation. A later child preparation does not retire an already
committed upstream that is still being promoted locally.
Healthy current edges remain sticky. When admitted overlap exists, a usable old
route stays active until the exact candidate child decodes a first new frame;
the candidate must still be connected when that proof is accepted and when it
@@ -224,6 +227,8 @@ Committed P2P recovery first requests an ICE restart, then requests a rebuild
if necessary, within the existing two-request budget. A sender without restart
support, including the current Native sender, replaces its connection on that
first request.
Restart authority follows the exact retained edge and its endpoint sessions;
an ancestor repairing its own ingress does not revoke that edge's recovery.
The budget belongs to the current parent and survives physical connection or
Browser/Native backend replacement. Only a connected transport or a new parent
resets it; replacing an unconnected backend cannot renew recovery indefinitely.
+6
View File
@@ -156,6 +156,12 @@ notice. Unknown SHA is not inferred from a branch name in GitHub metadata.
The publisher records a full SHA in `target_commitish` and verifies actual tag
identity separately. Stable update notices ignore prereleases.
Mode entry and the Site's App control share the check against the App's compiled
identity. A newer stable release marks that App control; its panel groups the
installed version, manual download and App management. This also covers starred
Site startup, which bypasses mode entry. Approved health supplies build identity;
older Apps without that metadata retain their ordinary connection and management.
### Major-Upgrade Guidance
The App update notice keeps direct download as its primary action, with a small
+25 -23
View File
@@ -1,48 +1,46 @@
# Current TODO Ledger
Last reviewed: 2026-11-01
Last reviewed: 2026-11-03
This ledger contains unfinished work and explicit owner holds. Product modules
own behavior; research and Git/PRs own evidence and completed history.
## Now
- [ ] **Public-invitation candidate retirement.** Capture the parent and server
reason when a candidate is retired before its first SDP offer. Keep this
separate from candidates that actually enter ICE and fail.
- [ ] **Browser sharing falls to low source FPS during motion.** Trace raw
capture, sender-owned track input and encoding on Windows Chrome with mixed
direct/SFU delivery. The observed source fell to roughly 2 fps during video
or game playback; reproduce with real window/display capture. Keep the
separate SFU packet-loss stage distinct from source-frame production.
- [ ] **Windows App sharing ends unexpectedly.** Identify WGC/source, device or
encoder termination in the supplied release feedback using the native stage
and HRESULT, and reproduce the unexpected termination.
- [ ] **Native screen sound recaptures room voice.** Exclude Piik voice while
retaining intended source audio. Verify Browser own-document exclusion and
Native process exclusion; keep acoustic echo and duplicate commentary with
their separate microphone owners.
- [ ] **Unclassified capture termination in older Windows feedback.** Identify
the Native failure stage and HRESULT in the original v2.4.1/v2.5.1 attempts.
Their Browser reports show Native failure before page cleanup but do not
identify its trigger.
- [ ] **Room voice in Native display sound.** Resolve the remaining case where
system loopback recaptures Browser voice, while excluding the Browser process
also removes its other audio. Browser own-document exclusion and Native
process-tree exclusion are already implemented; acoustic echo and duplicate
commentary retain their separate microphone owners.
- [ ] **Virtual-LAN page loading.** Investigate the UU report where only the tab
title appears and the page never loads. Static compression reduces transfer
size; capture the stalled document/script response to locate this failure.
- [ ] **Remote-control end-to-end latency.** Measure input-to-visible-response
on an attended target, covering OS execution, Native capture/encoding, remote
transport and display in the same trial. The
[input assessment](./research/room-interactions.md#window-capture-and-game-input)
owns completed local component measurements.
- [ ] **Native H264 scene-change latency.** Reduce large-AU send-queue delay
while preserving bitrate restoration. The
[end-to-end control](./research/webrtc-encoder-pool.md#h264-burst-and-recovery)
locates the delay and rejects the one-frame HRD override that prevents recovery.
- [ ] **Linux capture ends after selection (#499).** Follow
[#499](https://github.com/TNTcraftHIM/Piik/issues/499) on niri/Wayland with
GStreamer NVENC. The Browser report records capture ending before connection
cleanup; obtain the native capture failure to distinguish the encoder and Portal.
- [ ] **macOS source-picker thumbnails (#500).** The reporter confirmed normal
sharing on 2026-10-28; the remaining [#500](https://github.com/TNTcraftHIM/Piik/issues/500)
report concerns missing screen thumbnails in the source picker. The macOS
helper now implements the existing preview command; verify its build and
display/window thumbnails on a physical Mac before closing the issue.
- [ ] **Mouse input stops when Host Chrome is minimized (#502).** Follow
[#502](https://github.com/TNTcraftHIM/Piik/issues/502) on the original Windows
host: the v2.5.1 follow-up retains the grant, but mouse movement and left/right
clicks stop until Chrome is restored. The diagnostic candidate adds aggregate
input-stage and sink-API counts without recording input values. Obtain App ZIPs
during the minimized failure and after restoration; the local controlled
Chrome trial did not reproduce the original machine's trigger.
host. The supplied v2.5.2 reports retain the grant and receive authorized mouse
events, but Windows `SendInput` rejects a button event and subsequent release
attempts. Identify that OS refusal trigger and verify held-button recovery;
the local controlled Chrome trial did not reproduce it.
- [ ] **Return LiveKit to an upstream pin.** Follow
[upstream #5016](https://github.com/livekit/livekit/pull/5016). Once upstream
supplies the allocator input Piik needs, verify recovery and remove the
@@ -56,6 +54,10 @@ own behavior; research and Git/PRs own evidence and completed history.
## Next
- [ ] **Stronger microphone noise suppression (#518).** Assess the
[requested speech-processing option](https://github.com/TNTcraftHIM/Piik/issues/518)
through the shared microphone input. Browser voice processing is already the
default; keep screen and system audio unprocessed.
- [ ] **3.0 semantic reconstruction.** Continue the isolated `feat/channel-prototype`
from the accepted domain/room/participant model. Map existing behavior and
ownership, remove accidental constraints, then implement cohesive Rust runtimes
+8
View File
@@ -2,6 +2,7 @@
package buildinfo
import (
"runtime"
"strings"
"golang.org/x/mod/semver"
@@ -11,6 +12,13 @@ import (
var Release = "development"
var Revision = "development"
func PackageTarget() string {
if runtime.GOOS == "android" {
return "android-universal"
}
return runtime.GOOS + "-" + runtime.GOARCH
}
func Version() string {
version := strings.TrimSpace(Release)
if version != "" && semver.Canonical(version) == version && semver.Prerelease(version) == "" {
+2 -6
View File
@@ -12,12 +12,12 @@ import (
"net"
"net/http"
"net/url"
"runtime"
"slices"
"strings"
"sync"
"time"
"github.com/TNTcraftHIM/Piik/internal/app/buildinfo"
appconfig "github.com/TNTcraftHIM/Piik/internal/app/config"
"github.com/TNTcraftHIM/Piik/internal/app/failure"
"github.com/TNTcraftHIM/Piik/internal/app/lan"
@@ -298,17 +298,13 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.Re
target, resultErr = attempt.target, attempt.err
starting = !attempt.completed
}
packageTarget := runtime.GOOS + "-" + runtime.GOARCH
if runtime.GOOS == "android" {
packageTarget = "android-universal"
}
state := map[string]any{
"sites": slices.Clone(server.sites),
"startupSite": server.startupSite,
"localAccessPassword": server.localAccessPassword,
"version": server.version,
"revision": server.revision,
"packageTarget": packageTarget,
"packageTarget": buildinfo.PackageTarget(),
"controlPort": server.controlPort,
"target": target,
"starting": starting,
+7
View File
@@ -16,6 +16,7 @@ import (
"sync"
"time"
"github.com/TNTcraftHIM/Piik/internal/app/buildinfo"
appconfig "github.com/TNTcraftHIM/Piik/internal/app/config"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/coder/websocket"
@@ -70,6 +71,9 @@ type Endpoint struct {
}
type Health struct {
Version string `json:"version"`
Revision string `json:"revision"`
PackageTarget string `json:"packageTarget"`
Protocol int `json:"protocol"`
Service string `json:"service"`
Port int `json:"port"`
@@ -417,6 +421,9 @@ func (server *Server) handleHealth(response http.ResponseWriter, request *http.R
}
response.Header().Set("Cache-Control", "no-store")
writeJSON(response, http.StatusOK, Health{
Version: buildinfo.Version(),
Revision: buildinfo.Revision,
PackageTarget: buildinfo.PackageTarget(),
Protocol: ProtocolVersion,
Service: ServiceName,
Port: server.endpoint.Port,
+5
View File
@@ -13,6 +13,7 @@ import (
"testing"
"time"
"github.com/TNTcraftHIM/Piik/internal/app/buildinfo"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
)
@@ -52,6 +53,9 @@ func TestHealthActivationURLIsOptionalAndOriginBound(t *testing.T) {
}
func TestStartServesHealthAndStrictControlHandshake(t *testing.T) {
release, revision := buildinfo.Release, buildinfo.Revision
buildinfo.Release, buildinfo.Revision = "v2.5.2", strings.Repeat("a", 40)
t.Cleanup(func() { buildinfo.Release, buildinfo.Revision = release, revision })
expectedMedia := NativeMediaCapabilities{
Video: true, ProcessAudio: false, SystemAudio: true, HardwareH264: true, MaxRelayChildren: 20,
}
@@ -71,6 +75,7 @@ func TestStartServesHealthAndStrictControlHandshake(t *testing.T) {
}
response.Body.Close()
if health.Protocol != ProtocolVersion || health.Service != ServiceName ||
health.Version != buildinfo.Version() || health.Revision != buildinfo.Revision || health.PackageTarget != buildinfo.PackageTarget() ||
health.Port != endpoint.Port || health.InstanceToken != endpoint.InstanceToken ||
health.NativeMedia != expectedMedia {
t.Fatalf("health = %+v", health)
+7 -4
View File
@@ -48,17 +48,20 @@ func (engine *Engine) newICESocket(servers []webrtc.ICEServer, mapping bool) (*i
// Adoption happens before the one PeerConnection is constructed. Discovery and
// media then keep this exact socket, including any authenticated punched tuple.
func (engine *Engine) adoptICESocket(connection net.PacketConn, servers []webrtc.ICEServer, mapping bool) (*iceSocket, error) {
var punchedPeer *net.UDPAddr
if prepared, ok := connection.(*PunchedSocket); ok {
punchedPeer = prepared.remote
connection = prepared.PacketConn
}
ctx, cancel := context.WithCancel(engine.ctx)
socket := &iceSocket{
engine: engine, ctx: ctx, cancel: cancel,
localPort: connection.LocalAddr().(*net.UDPAddr).Port,
localPort: connection.LocalAddr().(*net.UDPAddr).Port,
punchedPeer: punchedPeer,
mux: forwarding.NewUDPMux(ice.UDPMuxParams{
Logger: diagnostics.PionLoggerFactory().NewLogger("piik-ice"), UDPConn: connection,
}),
}
if prepared, ok := connection.(*PunchedSocket); ok {
socket.punchedPeer = prepared.remote
}
if engine.portMapping && mapping && len(stunServers(servers)) > 0 {
socket.portMapping = portmapping.Start(socket.localPort)
}
+5
View File
@@ -42,6 +42,11 @@ func AddICECandidate(connection *webrtc.PeerConnection, candidate webrtc.ICECand
// addresses at each gathering. Its default stdnet snapshot otherwise survives
// ICE restart (and every new SFU connection sharing that mux).
func NewUDPMux(params ice.UDPMuxParams) *ice.UDPMuxDefault {
// Size the actual media socket before Pion starts reading. Preparation's
// unused candidate sockets keep their ordinary OS buffers.
if connection, ok := params.UDPConn.(interface{ SetReadBuffer(int) error }); ok {
_ = connection.SetReadBuffer(2 * 1024 * 1024)
}
if params.Net == nil {
params.Net = &muxNetwork{}
}
+6 -4
View File
@@ -488,6 +488,8 @@ type EgressStats struct {
Packets, RTPBytes, DroppedPackets uint64
}
const pacingHeadroom = 1.5
// The SDK owns packet timing; bounded tickets keep original packet ownership
// here until a ticket sends or Stop retires it. SFU's unpaced writer assumes
// already-paced input, which does not hold for locally encoded whole frames.
@@ -512,7 +514,7 @@ func newPacedQueue(log logger.Logger, limit, bitrate int) *boundedPacer {
// prevents a stale low estimate from trapping already encoded frames for
// seconds; this is not a network latency promise.
queue := newBoundedPacer(packetpacer.NewPacerLeakyBucket(3*time.Millisecond,
int(float64(bitrate)*1.5), 200*time.Millisecond, log), log, limit)
int(float64(bitrate)*pacingHeadroom), 200*time.Millisecond, log), log, limit)
queue.bitrate.Store(int64(bitrate))
return queue
}
@@ -525,7 +527,7 @@ func newBoundedPacer(packetPacer packetpacer.Pacer, log logger.Logger, limit int
func (queue *boundedPacer) SetBitrate(bitrate int) {
queue.bitrate.Store(int64(bitrate))
queue.Pacer.SetBitrate(int(float64(bitrate) * 1.5))
queue.Pacer.SetBitrate(int(float64(bitrate) * pacingHeadroom))
}
func (queue *boundedPacer) Enqueue(packet *pacer.Packet) {
@@ -582,11 +584,11 @@ func (queue *boundedPacer) SetPacerProbeObserverListener(listener pacer.PacerPro
func (queue *boundedPacer) StartProbeCluster(info ccutils.ProbeClusterInfo) {
queue.sender.StartProbeCluster(info)
queue.Pacer.SetBitrate(int(float64(info.Goal.DesiredBps) * 1.5))
queue.Pacer.SetBitrate(int(float64(info.Goal.DesiredBps) * pacingHeadroom))
}
func (queue *boundedPacer) EndProbeCluster(id ccutils.ProbeClusterId) ccutils.ProbeClusterInfo {
queue.Pacer.SetBitrate(int(float64(queue.bitrate.Load()) * 1.5))
queue.Pacer.SetBitrate(int(float64(queue.bitrate.Load()) * pacingHeadroom))
return queue.sender.EndProbeCluster(id)
}
+13
View File
@@ -557,6 +557,19 @@ func (r *router) isActivePeerParentOf(roomID, parentPeerID, childPeerID string)
return ok && activeParent == parentPeerID
}
// A retained child connection can restart while its parent repairs its own
// ingress. The full source path need not be ready, but this inbound edge must
// still own the exact endpoint sessions and connection.
func (r *router) peerRestartAuthorized(input peerSignalInput) bool {
rm, _ := r.rooms.Get(input.roomID)
if rm == nil || rm.controller == nil {
return false
}
edge, ok := rm.controller.Snapshot().UpstreamByViewer.Get(input.sourcePeerID)
return ok && edge.Kind == route.UpstreamPeer && edge.ParentPeerID == input.targetPeerID &&
r.peerSignalAuthorization(input) == signalAuthorizationAllowed
}
// resolveActivePeerEdge returns false when the child has no active Peer edge.
func (r *router) resolveActivePeerEdge(roomID, childPeerID string) (revision int64, parentPeerID string, ok bool) {
edge, found := r.resolveActiveViewerMediaEdge(roomID, childPeerID)
+7 -4
View File
@@ -1779,15 +1779,18 @@ func (s *Server) routePeerAssistedSignal(sess *session, source *authenticatedSes
func (s *Server) routePeerAssistedRestart(sess *session, source *authenticatedSession, message protocol.ClientRestartRequestMessage) {
targetPeerID := message.TargetPeerID
if targetPeerID == "" || !s.router.isActivePeerParentOf(source.roomID, targetPeerID, source.peerID) {
s.sendError(sess, "FORBIDDEN", "Restart target is not the assigned media parent")
return
}
parent, hasParent := s.connectedPeer(source.roomID, targetPeerID)
if !hasParent {
s.sendError(sess, "PEER_NOT_FOUND", "Media parent is not connected")
return
}
if !s.router.peerRestartAuthorized(peerSignalInput{
roomID: source.roomID, sourcePeerID: source.peerID, sourceSessionID: sess.sessionID,
targetPeerID: targetPeerID, targetSessionID: parent.SessionID, connectionID: message.ConnectionID,
}) {
s.sendError(sess, "FORBIDDEN", "Restart target is not the assigned media parent")
return
}
s.sendToSession(parent.SessionID, protocol.ServerRestartRequestMessage{
Type: "restart-request",
FromPeerID: source.peerID,
+71
View File
@@ -2780,6 +2780,77 @@ func TestSignalKeepsMediaIdentityThroughGraceWhilePresenceReturnsOnce(t *testing
`{"fromPeerId":%q,"connectionId":"connection-during-grace","rebuild":false}`, firstViewerAuth.PeerID))
}
func TestSignalAllowsRetainedChildRestartWhileRelayRepairsIngress(t *testing.T) {
h := startHarness(t, harnessOptions{endpointMediaCopyCapacity: 1})
host := openClient(t, h)
hostAuth := authenticate(t, host, h.room, protocol.RoleHost, "restart-host-client", 0, "", presenceOptions{})
relay := openClient(t, h)
relayAuth := authenticate(t, relay, h.room, protocol.RoleViewer, "restart-relay-client", 1, "", presenceOptions{})
commitPreparedRoute(t, relay)
child := openClient(t, h)
childAuth := authenticate(t, child, h.room, protocol.RoleViewer, "restart-child-client", 0, "", presenceOptions{})
active := commitPreparedRoute(t, child)
if active.Assignment.Upstream != protocol.PeerUpstream(relayAuth.PeerID) {
t.Fatalf("child upstream = %v, want the relay", active.Assignment.Upstream)
}
var relayEdge, childEdge activeViewerMediaEdge
h.locked(func() {
var ok bool
relayEdge, ok = h.server.router.resolveActiveViewerMediaEdge(h.room.RoomID, relayAuth.PeerID)
if !ok {
t.Fatal("relay ingress must be active")
}
childEdge, ok = h.server.router.resolveActiveViewerMediaEdge(h.room.RoomID, childAuth.PeerID)
if !ok {
t.Fatal("child ingress must be active")
}
})
relay.sendJSON(map[string]any{
"type": "route-failed", "phase": "active", "revision": relayEdge.revision,
"connectionId": relayEdge.connectionID,
})
repair := nextPreparedRoute(t, relay)
h.locked(func() {
rm, _ := h.server.router.rooms.Get(h.room.RoomID)
snapshot := rm.controller.Snapshot()
edge, ok := snapshot.UpstreamByViewer.Get(childAuth.PeerID)
if !ok || !edge.PhysicalActive || !edge.Usable || videoConnectionID(snapshot, edge) != childEdge.connectionID {
t.Fatal("relay repair must retain its child's physical connection")
}
if _, ok := h.server.router.resolveActiveViewerMediaEdge(h.room.RoomID, childAuth.PeerID); ok {
t.Fatal("a retained subtree must not claim the repairing source path is ready")
}
})
child.sendJSON(map[string]any{
"type": "restart-request", "targetPeerId": relayAuth.PeerID,
"connectionId": childEdge.connectionID, "rebuild": false,
})
forwarded, ok := relay.tryNext("restart-request", defaultWait)
if !ok {
denial, _ := child.tryNext("error", 0)
t.Fatalf("retained child restart was not forwarded: %s", denial.raw)
}
expectMatch(t, forwarded.raw, fmt.Sprintf(
`{"fromPeerId":%q,"connectionId":%q,"rebuild":false}`, childAuth.PeerID, childEdge.connectionID))
for _, request := range []map[string]any{
{"type": "restart-request", "targetPeerId": hostAuth.PeerID, "connectionId": childEdge.connectionID, "rebuild": true},
{"type": "restart-request", "targetPeerId": relayAuth.PeerID, "connectionId": "retired_connection_12345678", "rebuild": true},
} {
child.sendJSON(request)
expectMatch(t, child.next("error").raw, `{"code":"FORBIDDEN"}`)
}
relay.sendJSON(map[string]any{
"type": "restart-request", "targetPeerId": childAuth.PeerID,
"connectionId": childEdge.connectionID, "rebuild": true,
})
expectMatch(t, relay.next("error").raw, `{"code":"FORBIDDEN"}`)
relay.sendJSON(map[string]any{
"type": "restart-request", "targetPeerId": repair.Assignment.Upstream.PeerID,
"connectionId": repair.Candidate.ConnectionID, "rebuild": true,
})
expectMatch(t, relay.next("error").raw, `{"code":"FORBIDDEN"}`)
}
// ---------------------------------------------------------------------------
// capacity and abandonment
// ---------------------------------------------------------------------------
+13
View File
@@ -506,6 +506,19 @@ std::vector<UINT8> ReadSample(IMFSample* sample) {
}
std::copy(raw, raw + current, bytes.begin());
Check(buffer->Unlock(), "output-buffer-unlock");
// Some local MFTs encode Baseline Level 1b using level_idc 9. RFC 6184
// represents it as level_idc 11 with constraint_set3 for this profile.
for (auto start = FindStartCode(bytes, 0); start;) {
const size_t nal = start->first + start->second;
const auto next = FindStartCode(bytes, nal);
const size_t end = next ? next->first : bytes.size();
if (end - nal >= 4 && (bytes[nal] & 0x1f) == 7 &&
bytes[nal + 1] == 0x42 && bytes[nal + 3] == 9) {
bytes[nal + 2] |= 0x10;
bytes[nal + 3] = 11;
}
start = next;
}
return bytes;
}
+12 -6
View File
@@ -1541,11 +1541,18 @@ struct CaptureInput final {
UINT64 capture_timestamp = 0;
};
std::shared_ptr<const CaptureInput> RefreshCaptureInput(const CaptureInput& latest) {
UINT64 NextPresentationTimestamp(UINT64 candidate, UINT64 previous) {
constexpr UINT64 rtp_tick_100ns = (10'000'000 + 90'000 - 1) / 90'000;
return std::max(candidate, previous + rtp_tick_100ns);
}
std::shared_ptr<const CaptureInput> RefreshCaptureInput(
const CaptureInput& latest, UINT64 previous_presentation) {
auto input = std::make_shared<CaptureInput>(latest);
// WGC SystemRelativeTime and MFGetSystemTime share the 100 ns QPC clock.
// A requested still frame is presented now, including after a quiet gap.
input->timestamp = static_cast<UINT64>(MFGetSystemTime());
// Delayed capture can already have advanced presentation beyond the clock.
input->timestamp = NextPresentationTimestamp(
static_cast<UINT64>(MFGetSystemTime()), previous_presentation);
return input;
}
@@ -1555,8 +1562,7 @@ std::optional<UINT64> CapturePresentationTimestamp(
if (captured <= previous_capture || captured < minimum_capture) return std::nullopt;
// A real frame can have been captured before a requested still was presented.
// Retain its new pixels and keep separate access units at least one RTP tick apart.
constexpr UINT64 rtp_tick_100ns = (10'000'000 + 90'000 - 1) / 90'000;
return std::max(captured, previous_presentation + rtp_tick_100ns);
return NextPresentationTimestamp(captured, previous_presentation);
}
class OutputWorker final {
@@ -2196,7 +2202,7 @@ void RunVideoCapture(ProductArguments arguments) {
if (wait == WAIT_TIMEOUT) {
// An explicit output/control request may reuse a quiet source; silence is not EOF.
if (refresh_input && latest_input) {
submit(RefreshCaptureInput(*latest_input));
submit(RefreshCaptureInput(*latest_input, previous_timestamp));
}
continue;
}
+52 -7
View File
@@ -71,7 +71,7 @@ void CheckQuietCaptureRefresh() {
latest.capture_timestamp = latest.timestamp;
const auto previous = latest.timestamp;
const auto before = static_cast<UINT64>(MFGetSystemTime());
const auto refreshed = RefreshCaptureInput(latest);
const auto refreshed = RefreshCaptureInput(latest, previous);
const auto after = static_cast<UINT64>(MFGetSystemTime());
assert(refreshed->timestamp >= before && refreshed->timestamp <= after);
assert(refreshed->timestamp - previous >= 50'000'000);
@@ -81,6 +81,17 @@ void CheckQuietCaptureRefresh() {
refreshed->presentation.cx == latest.presentation.cx &&
refreshed->presentation.cy == latest.presentation.cy &&
refreshed->color_space == latest.color_space && refreshed->texture.Get() == latest.texture.Get());
// A delayed real frame can advance presentation beyond the current QPC time.
CaptureInput ahead = latest;
ahead.timestamp = after + 10'000'000;
const auto after_ahead = RefreshCaptureInput(latest, ahead.timestamp);
assert(after_ahead->timestamp > ahead.timestamp);
assert((after_ahead->timestamp - ahead.timestamp) * 90'000 >= 10'000'000);
const auto repeated = RefreshCaptureInput(latest, after_ahead->timestamp);
assert(repeated->timestamp > after_ahead->timestamp);
assert((repeated->timestamp - after_ahead->timestamp) * 90'000 >= 10'000'000);
assert(repeated->capture_timestamp == latest.capture_timestamp);
assert(latest.timestamp == previous);
// The compositor changed the picture just before the refresh, but its frame
// callback arrives afterwards. It is new capture input, not a stale still.
const auto delayed_capture = before - 1;
@@ -150,14 +161,16 @@ void CheckRetainedContentAtAdaptedCadence(ID3D11Device* device) {
input->presentation = {64, 64};
input->timestamp = static_cast<UINT64>(MFGetSystemTime());
input->capture_timestamp = input->timestamp;
UINT64 previous_timestamp = 0;
auto submit = [&](std::shared_ptr<const CaptureInput> next) {
for (auto& worker : workers) worker->Submit(next);
previous_timestamp = next->timestamp;
};
const auto deadline = EncoderClock::now() + std::chrono::seconds(3);
auto wait = [&](auto done) {
while (!done()) {
assert(EncoderClock::now() < deadline);
if (refresh.exchange(false)) submit(RefreshCaptureInput(*input));
if (refresh.exchange(false)) submit(RefreshCaptureInput(*input, previous_timestamp));
std::this_thread::sleep_for(std::chrono::milliseconds(34));
}
};
@@ -172,20 +185,20 @@ void CheckRetainedContentAtAdaptedCadence(ID3D11Device* device) {
submit(input);
wait([&] { return changed[0] > 0 && changed[1] > 0; });
// One rendition's drop must not reopen the other rendition's delivered content.
if (refresh.exchange(false)) submit(RefreshCaptureInput(*input));
if (refresh.exchange(false)) submit(RefreshCaptureInput(*input, previous_timestamp));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
assert(!refresh.load());
const auto before = keys[0].load();
workers[0]->RequestKeyFrame();
submit(RefreshCaptureInput(*input));
submit(RefreshCaptureInput(*input, previous_timestamp));
wait([&] { return keys[0] > before; });
if (refresh.exchange(false)) submit(RefreshCaptureInput(*input));
if (refresh.exchange(false)) submit(RefreshCaptureInput(*input, previous_timestamp));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
assert(!refresh.load());
workers[0]->SetBitrate(profile.bit_rate);
submit(RefreshCaptureInput(*input));
submit(RefreshCaptureInput(*input, previous_timestamp));
wait([&] { return published_bitrate[0] == profile.bit_rate; });
if (refresh.exchange(false)) submit(RefreshCaptureInput(*input));
if (refresh.exchange(false)) submit(RefreshCaptureInput(*input, previous_timestamp));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
assert(!refresh.load());
for (auto& worker : workers) worker->Stop();
@@ -371,6 +384,37 @@ void CheckH264ProfileCompatibility() {
CloseHandle(read);
}
void CheckLocalH264Level1b() {
Runtime runtime;
// Include both start-code lengths, ordinary Baseline, a different profile,
// non-SPS data and a truncated SPS: only the local Baseline 1b bytes change.
const std::vector<UINT8> input{
0, 0, 0, 1, 0x67, 0x42, 0xc0, 9, 0x80,
0, 0, 1, 0x67, 0x42, 0xe0, 9, 0x80,
0, 0, 1, 0x67, 0x42, 0xc0, 31, 0x80,
0, 0, 1, 0x67, 0x64, 0, 9, 0x80,
0, 0, 1, 0x65, 0x42, 0xc0, 9,
0, 0, 1, 0x67, 0x42, 0xc0};
auto expected = input;
expected[6] = 0xd0;
expected[7] = 11;
expected[14] = 0xf0;
expected[15] = 11;
ComPtr<IMFSample> sample;
Check(MFCreateSample(&sample), "fixture-sample");
ComPtr<IMFMediaBuffer> buffer;
Check(MFCreateMemoryBuffer(static_cast<DWORD>(input.size()), &buffer), "fixture-buffer");
BYTE* raw = nullptr;
Check(buffer->Lock(&raw, nullptr, nullptr), "fixture-lock");
std::copy(input.begin(), input.end(), raw);
Check(buffer->Unlock(), "fixture-unlock");
Check(buffer->SetCurrentLength(static_cast<DWORD>(input.size())), "fixture-length");
Check(sample->AddBuffer(buffer.Get()), "fixture-add-buffer");
assert(ReadSample(sample.Get()) == expected);
assert(SupportsH264ProfileLevelId("42d00b"));
assert(!SupportsH264ProfileLevelId("42c009"));
}
void CheckEncoderCandidates() {
const std::vector<EncoderCandidate> candidates{{0, 0}, {1, 0}, {1, 1}, {2, 0}};
const EncoderCandidate preferred{1, 0};
@@ -747,6 +791,7 @@ int main() {
CheckEncoderCandidates();
CheckQuietCaptureRefresh();
CheckH264ProfileCompatibility();
CheckLocalH264Level1b();
CheckPrimaryFailureDetails();
CheckAudioCapabilityIsolation();
CheckOutputSampleAlignment();
+10 -3
View File
@@ -24,6 +24,7 @@ const probe = String.raw`(() => {
localStorage.setItem('piik:ui-lang', 'en');
localStorage.setItem('piik:ui-mode', 'text');
const pcs = [], requests = [], sockets = [], errors = [];
let sourceAudioAvailable = null;
window.addEventListener('unhandledrejection', (e) => errors.push(String(e.reason)));
const codecPreferences = RTCRtpTransceiver.prototype.setCodecPreferences;
RTCRtpTransceiver.prototype.setCodecPreferences = function(value) {
@@ -36,6 +37,11 @@ const probe = String.raw`(() => {
window.WebSocket = class extends WS {
constructor(...args) { super(...args); if (String(args[0]).includes('/control')) {
sockets.push(this);
} else if (new URL(String(args[0]), location.href).pathname === '/signal') {
this.addEventListener('message', ({data}) => {
const message = JSON.parse(data);
if (message.type === 'audio-presence') sourceAudioAvailable = message.available;
});
} }
send(raw) {
if (this.url.includes('/control')) {
@@ -108,7 +114,7 @@ const probe = String.raw`(() => {
edgeRequests: requests.filter((r) => r === 'prepare-edge').length,
controlOpen: sockets.some((s) => s.readyState === WS.OPEN),
codecSelected: [...document.querySelectorAll('button.lr-chip.is-selected')].map((b) => b.textContent),
audio: video?.srcObject?.getAudioTracks().length || 0,
audio: video?.srcObject?.getAudioTracks().length || 0, sourceAudioAvailable,
buttons: [...document.querySelectorAll('.lr-host-share-slot button')].map((b) => b.getAttribute('aria-label')) };
}
};
@@ -314,9 +320,10 @@ async function main(): Promise<void> {
await click(host, 'button[aria-label="Switch source"]');
await click(host, 'button[data-source-tab="browser"]');
await click(host, 'button.lr-source-option[aria-label="Choose what to share"]');
await waitForSample(() => read(host), (s) => s.receiveRequests === 2 && s.captures === 2 && s.sharing, 15000);
await waitForSample(() => read(host), (s) => s.receiveRequests === 1 && s.captures === 2 && s.sharing, 15000);
const beforeSource = await read(viewers[1]!);
await waitForSample(() => read(viewers[1]!), (s) => s.width > 0 && s.frames >= beforeSource.frames+20 && s.audio===Number(!initialAudio), 25000);
// Source sound changes independently of the stable mixed transport track.
await waitForSample(() => read(viewers[1]!), (s) => s.width > 0 && s.frames >= beforeSource.frames+20 && s.sourceAudioAvailable === !initialAudio, 25000);
checks.sourceAudioChange = true;
stage = "app-exit";
app.stdin.write("\n");
+10 -3
View File
@@ -2579,9 +2579,16 @@ async function startHost(
return true;
})()`,
);
await waitForPage(cdp, page, `document.querySelector('button.lr-source-option[aria-label="Choose what to share"]')`,
5_000, "Browser capture choice", signal);
await evaluate(cdp, page, `document.querySelector('button.lr-source-option[aria-label="Choose what to share"]').click()`);
await waitForPage(cdp, page, `(() => {
const tab = document.querySelector('button[data-source-tab="browser"]');
return tab instanceof HTMLButtonElement && !tab.disabled && tab.getClientRects().length > 0;
})()`, 5_000, "Browser capture tab", signal);
await evaluate(cdp, page, `document.querySelector('button[data-source-tab="browser"]').click()`);
await waitForPage(cdp, page, `(() => {
const choice = document.querySelector('[role="tabpanel"] button.lr-source-option');
return choice instanceof HTMLButtonElement && !choice.disabled && choice.getClientRects().length > 0;
})()`, 5_000, "Browser capture choice", signal);
await evaluate(cdp, page, `document.querySelector('[role="tabpanel"] button.lr-source-option').click()`);
await waitForPage(
cdp,
page,
@@ -27,6 +27,7 @@ export function summarizeConnectionMetrics(samples: readonly ConnectionMetricSam
jitterMs: mean(numbers(metrics.map(metric => metric.jitterMs))),
packetLossPercent: metrics.length === 1 ? metrics[0]!.packetLossPercent
: direction === "send" ? mean(numbers(metrics.map(metric => metric.packetLossPercent)))
: packetSamples.length !== metrics.length ? null
: packetLossPercentFromDeltas(sum(packetSamples.map(metric => metric.intervalPacketsReceived!)), sum(packetSamples.map(metric => metric.intervalPacketsLost!))),
resolution: resolutions.length ? [resolutions[0]!, resolutions.at(-1)!] as const : null,
framesPerSecond: frames.length ? [Math.min(...frames), Math.max(...frames)] as const : null,
@@ -9,6 +9,9 @@ import { HintComic } from "./hints";
import { LoadingStatus } from "./WaitingStatus";
import { useAnchoredPopover } from "./use-anchored-popover";
import { androidAppIntent } from "../../native/activation";
import type { AppReleaseIdentity } from "../../lib/release-update";
import { useReleaseUpdate } from "../../lib/use-release-update";
import { AppReleaseNotice } from "./AppReleaseNotice";
interface AppConnectionProps {
onConnected?: () => void;
@@ -33,6 +36,12 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {
useAnchoredPopover(trigger, help);
const pending = useRef<ConnectionAttempt | null>(null);
const healthCheck = useRef<AbortController | null>(null);
const [build, setBuild] = useState<AppReleaseIdentity>();
const { update: release, refresh: checkRelease } = useReleaseUpdate(build);
function rememberBuild(health: Partial<AppReleaseIdentity> | null) {
setBuild(health?.version && health.revision
? { version: health.version, revision: health.revision, packageTarget: health.packageTarget } : undefined);
}
useEffect(() => {
const refresh = async () => {
if (pending.current || help.current?.matches(":popover-open") || !isClientActivated()) return;
@@ -42,9 +51,13 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {
if (current.signal.aborted) return;
try {
const health = await native.discoverNativeHealth({ signal: current.signal, waitForPermission: false });
if (!current.signal.aborted && !pending.current) setState(health ? "ready" : "idle");
if (!current.signal.aborted && !pending.current) {
rememberBuild(health);
setState(health ? "ready" : "idle");
}
} catch (error) {
if (!current.signal.aborted && !pending.current) {
rememberBuild(null);
setState(error instanceof native.NativeCompatibilityError ? "incompatible" : "idle");
}
}
@@ -79,10 +92,16 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {
const verifyApproval = async (reported = false) => {
if (approving || signal.aborted) return;
approving = true;
const health = await native?.discoverNativeHealth({ signal }).catch(() => null);
const health = await native?.discoverNativeHealth({ signal, ...(manage ? { waitForPermission: false } : {}) }).catch(() => null);
if (signal.aborted) return;
approving = false;
if (manage) {
rememberBuild(health ?? null);
if (!health) finish("idle");
return;
}
if (health) {
rememberBuild(health);
finish("ready");
activateClient();
onConnected?.();
@@ -112,7 +131,7 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {
attempt.cancel = () => finish(manage ? "ready" : "idle");
const onFocus = () => {
if (waking) { attempt.open?.(); return; }
if (attempt.popup) void verifyApproval();
if (attempt.popup || manage) void verifyApproval();
};
const onVisible = () => { if (document.visibilityState === "visible") onFocus(); };
window.addEventListener("message", onMessage);
@@ -133,6 +152,7 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {
if (!url) { finish("unavailable"); return; }
const health = await native.discoverNativeHealth({ signal, waitForPermission: false });
if (signal.aborted) return;
rememberBuild(health);
manage = manage && health !== null;
if (health && !manage) {
finish("ready");
@@ -174,19 +194,23 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {
state === "waking" ? "client.connect.returnToBrowser" : state === "ready" ? "client.connect.manage" : state === "incompatible" ? "native.incompatible" :
state === "unavailable" ? "client.connect.unavailable" : "client.connect.action");
const failed = state === "unavailable" || state === "incompatible";
return <><Tooltip kind={state === "ready" ? "hint-app-ready" : state === "unavailable" ? "signal-failed" : state === "incompatible" ? "warning" : "hint-client-site"}
text={vis ? undefined : state === "idle" ? t("client.connect.hint") : label} disabled={helpOpen}
const update = state === "ready" ? release : null;
const availableUpdate = update?.kind === "update-available" || update?.kind === "major-update";
const title = availableUpdate ? t("client.connect.update", { current: build!.version, version: update.version }) : label;
return <><Tooltip kind={availableUpdate ? "update-available" : state === "ready" ? "hint-app-ready" : state === "unavailable" ? "signal-failed" : state === "incompatible" ? "warning" : "hint-client-site"}
text={vis ? undefined : state === "idle" ? t("client.connect.hint") : title} disabled={helpOpen}
place="below" align="end">
<button ref={trigger} type="button" className={`lr-btn is-compact lr-app-connect${state === "ready" ? " is-ready" : ""}`}
aria-label={label} aria-busy={busy || undefined}
aria-label={title} aria-busy={busy || undefined} data-update={availableUpdate || undefined}
popoverTarget={failed || state === "approval" ? helpId : undefined} aria-haspopup="dialog"
onClick={failed || state === "approval" ? undefined : event => {
// Failure may attach popoverTarget during this click; do not toggle the
// recovery card closed immediately after opening it.
event.preventDefault();
checkRelease();
void connect();
}} disabled={busy}>
<Glyph name={state === "ready" ? "check" : busy ? "loader" : state === "unavailable" || state === "incompatible" ? "alert" : "window"}
<Glyph name={availableUpdate ? "arrowUp" : state === "ready" ? "check" : busy ? "loader" : state === "unavailable" || state === "incompatible" ? "alert" : "window"}
size={16} className={busy ? "lr-spin" : undefined} />
{vis ? null : <span className="lr-cap">App</span>}
</button>
@@ -208,6 +232,11 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {
</button>
</div>
<p id={`${helpId}-message`} className={vis ? "visually-hidden" : undefined}>{state === "busy" ? t("client.connect.permissionHint") : label}</p>
{state === "ready" && build && <p className="lr-app-connect-version">
<span className={vis ? "visually-hidden" : undefined}>{t("client.launch.version", { version: build.version })}</span>
{vis && <span aria-hidden="true">{build.version}</span>}
</p>}
{update && <AppReleaseNotice update={update} />}
<div className="lr-app-connect-actions">
{state !== "busy" && <button type="button" className="lr-btn" aria-label={t(state === "approval" || state === "ready" ? "client.connect.open" : state === "waking" ? "client.connect.continue" : "common.retry")} onClick={() => void connect()}>
<Glyph name={state === "approval" || state === "ready" ? "arrowRight" : "refresh"} size={16} /><span className={vis ? "visually-hidden" : undefined}>{t(state === "approval" || state === "ready" ? "client.connect.open" : state === "waking" ? "client.connect.continue" : "common.retry")}</span>
@@ -219,7 +248,7 @@ export function AppConnectionButton({ onConnected }: AppConnectionProps) {
<Glyph name="arrowDown" size={16} /><span className={vis ? "visually-hidden" : undefined}>{t("client.connect.download")}</span>
</a>}
</div>
<p className={vis ? "visually-hidden" : "lr-app-connect-optional"}>{t("client.connect.browserHint")}</p>
{state !== "ready" && <p className={vis ? "visually-hidden" : "lr-app-connect-optional"}>{t("client.connect.browserHint")}</p>}
</div>
</>;
}
@@ -15,21 +15,20 @@ export function AppReleaseNotice({ update }: { update: ReleaseUpdateNotice }) {
const { vis, t } = useCopy();
const warningId = useId();
const major = update.kind === "major-update";
const label = `${t(labels[update.kind])} · ${update.version}${update.extractAPK ? " (ZIP)" : ""}`;
const updateHint = major ? t("client.update.majorHint") : vis ? update.version : label;
const hint = update.extractAPK ? `${updateHint} ${t("client.update.extractAPK")}` : updateHint;
const label = `${t(labels[update.kind])} ${update.version}`;
const caption = major || update.kind === "update-available" ? t("client.update.download", { version: update.version }) : label;
return <div className="lr-client-release">
<Tooltip kind="update-available" text={hint}>
<Tooltip kind="update-available" text={major ? t("client.update.majorHint") : vis ? update.version : label}>
<a className="lr-btn lr-client-update" href={update.url} target="_blank" rel="noopener noreferrer"
aria-label={label} aria-describedby={major ? warningId : undefined}>
<Glyph name={major ? "alert" : "arrowUp"} size={17} />
<span className={vis ? "visually-hidden" : undefined}>{label}</span>
<span className={vis ? "visually-hidden" : undefined}>{caption}</span>
{vis && <span aria-hidden="true">{update.version}</span>}
</a>
</Tooltip>
<a className="lr-client-release-mirror" href="https://gitee.com/TNTcraftHIM/Piik/releases"
<a className="lr-client-release-mirror" href="https://atomgit.com/TNTcraftHIM/Piik/releases"
target="_blank" rel="noopener noreferrer" aria-label={t("client.update.downloads")}>
{vis ? <>Gitee <Glyph name="arrowDown" size={14} /></> : t("client.update.downloads")}
{vis ? <>AtomGit <Glyph name="arrowDown" size={14} /></> : t("client.update.downloads")}
<span aria-hidden="true"> ↗</span>
</a>
{major && <a id={warningId} className="lr-client-release-warning" href={update.releaseURL}
@@ -0,0 +1,20 @@
import { useCopy } from "../../ui/copy";
import { Comic } from "./Comic";
import { Btn } from "./primitives";
export function StartupFailure() {
const { t, vis } = useCopy();
return <div className="lr-app">
<main className="lr-join">
<div className="lr-join-panel">
<Comic kind="warning" theme="paper" tone="bad" />
<div className={vis ? "visually-hidden" : "lr-access-text"} role="alert">
<h1>{t("startup.failed")}</h1>
<p>{t("startup.retry")}</p>
</div>
<Btn icon="refresh" title="common.refresh" cap="common.refresh"
onClick={() => window.location.reload()} />
</div>
</main>
</div>;
}
+19 -19
View File
@@ -2,21 +2,23 @@ import { compare, major, valid } from "semver";
export const DEFAULT_RELEASE_API_URL =
"https://api.github.com/repos/TNTcraftHIM/Piik/releases/latest";
export const MIRROR_RELEASE_API_URL = "https://gitee.com/api/v5/repos/TNTcraftHIM/Piik/releases";
export const MIRROR_RELEASE_API_URL = "https://api.atomgit.com/api/v5/repos/TNTcraftHIM/Piik/releases";
const RELEASE_PAGE = "https://github.com/TNTcraftHIM/Piik/releases/tag/";
const MIRROR_RELEASE_PAGE = "https://gitee.com/TNTcraftHIM/Piik/releases/tag/";
const MIRROR_RELEASE_PAGE = "https://atomgit.com/TNTcraftHIM/Piik/releases";
export interface ReleaseIdentity {
version: string;
revision: string;
}
export interface AppReleaseIdentity extends ReleaseIdentity {
packageTarget?: string;
}
interface PublishedRelease {
version: string;
revision: string | null;
url: string;
releaseURL: string;
publishedAt?: string;
extractAPK?: boolean;
}
export interface ReleaseUpdateNotice extends PublishedRelease {
kind: "update-available" | "major-update" | "different-build" | "official-release";
@@ -32,25 +34,23 @@ function normalizeVersion(value: unknown): string | null {
return version ? `v${version}` : null;
}
function packageDownload(release: PublishedRelease, assets: unknown, target?: string): Pick<PublishedRelease, "url" | "extractAPK"> {
if (!target || !/^[a-z0-9]+-[a-z0-9]+$/.test(target) || !Array.isArray(assets)) return { url: release.url };
const android = target === "android-universal";
const mirror = release.url.startsWith(MIRROR_RELEASE_PAGE);
const extension = android && !mirror ? "apk" : "zip";
function packageDownloadURL(release: PublishedRelease, assets: unknown, target?: string): string {
if (!target || !/^[a-z0-9]+-[a-z0-9]+$/.test(target) || !Array.isArray(assets)) return release.url;
const extension = target === "android-universal" ? "apk" : "zip";
const mirror = release.releaseURL === MIRROR_RELEASE_PAGE;
const names = [`piik-app-${target}.${extension}`];
if (release.revision && !android) names.push(`piik-app-${target}-${release.revision.slice(0, 7)}.zip`);
if (release.revision && extension === "zip") names.push(`piik-app-${target}-${release.revision.slice(0, 7)}.zip`);
for (const name of names) {
const matches = assets.filter(asset => asset?.name === name);
if (!matches.length) continue;
const asset = matches[0];
const expectedURL = `${release.url.replace("/releases/tag/", "/releases/download/")}/${name}`;
return matches.length === 1 && (mirror ||
const expectedURL = mirror ? `${MIRROR_RELEASE_PAGE}/download/${release.version}/${name}`
: `${release.releaseURL.replace("/releases/tag/", "/releases/download/")}/${name}`;
return matches.length === 1 && (mirror ? asset.type === "attach" :
(Number.isSafeInteger(asset.size) && asset.size > 0 && asset.state === "uploaded")) &&
asset.browser_download_url === expectedURL
? { url: asset.browser_download_url, ...(android && mirror ? { extractAPK: true } : {}) }
: { url: release.url };
asset.browser_download_url === expectedURL ? asset.browser_download_url : release.url;
}
return { url: release.url };
return release.url;
}
export function parseReleaseMetadata(value: unknown, packageTarget?: string): PublishedRelease | null {
@@ -71,7 +71,7 @@ export function parseReleaseMetadata(value: unknown, packageTarget?: string): Pu
releaseURL: RELEASE_PAGE + version,
...(Number.isFinite(publishedTime) ? { publishedAt: new Date(publishedTime).toISOString() } : {}),
};
return { ...normalized, ...packageDownload(normalized, release.assets, packageTarget) };
return { ...normalized, url: packageDownloadURL(normalized, release.assets, packageTarget) };
}
export function parseMirrorReleaseMetadata(value: unknown, packageTarget?: string): PublishedRelease | null {
@@ -86,9 +86,9 @@ export function parseMirrorReleaseMetadata(value: unknown, packageTarget?: strin
target_commitish: sources[0][1],
});
if (!normalized) return null;
const mirror = { ...normalized, url: MIRROR_RELEASE_PAGE + normalized.version,
releaseURL: MIRROR_RELEASE_PAGE + normalized.version };
return { ...mirror, ...packageDownload(mirror, release.assets, packageTarget) };
const mirror = { ...normalized, url: MIRROR_RELEASE_PAGE,
releaseURL: MIRROR_RELEASE_PAGE };
return { ...mirror, url: packageDownloadURL(mirror, release.assets, packageTarget) };
}
export function releaseUpdateNotice(
+20
View File
@@ -0,0 +1,20 @@
import { useEffect, useState } from "react";
import { checkReleaseUpdate, type AppReleaseIdentity, type ReleaseUpdateNotice } from "./release-update";
/** Each surface checks the connected App build, independently of the Site build. */
export function useReleaseUpdate(identity?: AppReleaseIdentity) {
const version = identity?.version, revision = identity?.revision, packageTarget = identity?.packageTarget;
const key = JSON.stringify([version, revision, packageTarget]);
const [result, setResult] = useState<{ key: string; notice: ReleaseUpdateNotice | null }>();
const [check, setCheck] = useState(0);
useEffect(() => {
if (!version || !revision) return;
let current = true;
void checkReleaseUpdate({ version, revision }, { packageTarget }).then(notice => {
if (current) setResult({ key, notice });
}).catch(() => undefined);
return () => { current = false; };
}, [version, revision, packageTarget, key, check]);
return { update: result?.key === key ? result.notice : null,
refresh: () => setCheck(value => value + 1) };
}
+5 -2
View File
@@ -251,6 +251,7 @@ export const en: Record<CopyKey, string> = {
"client.connect.remove": "Revoke this Site's App access",
"client.connect.openOnStart": "Open this site when App starts",
"client.connect.manage": "App is ready. Manage App.",
"client.connect.update": "App {current}. Update to {version}.",
"client.connect.approveTitle": "Allow this Site to use Piik App?",
"client.connect.approveHint": "This Site will be able to use this device's screens, windows and microphone. Check that you trust this address.",
"client.connect.approve": "Allow access",
@@ -296,8 +297,8 @@ export const en: Record<CopyKey, string> = {
"client.update.available": "A newer Piik release is available",
"client.update.major": "New major Piik release",
"client.update.majorHint": "This update includes breaking changes. Read the release notes before upgrading.",
"client.update.downloads": "Gitee mirror",
"client.update.extractAPK": "Extract the ZIP, then install the APK.",
"client.update.downloads": "AtomGit mirror",
"client.update.download": "Download {version}",
"client.update.differentBuild": "This build differs from the official release",
"client.update.official": "An official Piik release is available",
@@ -311,6 +312,8 @@ export const en: Record<CopyKey, string> = {
"gate.malformed": "Invalid room code format",
"gate.malformedHint": "Enter a four-digit room code between 1000 and 9999",
"gate.unavailableRoute": "Unavailable",
"startup.failed": "Page couldn’t load",
"startup.retry": "Refresh the page to try again.",
"join.title": "Join a room",
"join.hint": "Enter a room code for {site}",
+5 -2
View File
@@ -251,6 +251,7 @@ export const zh = {
"client.connect.remove": "取消此站点的 App 授权",
"client.connect.openOnStart": "启动 App 时打开此站点",
"client.connect.manage": "App 已就绪,点击管理。",
"client.connect.update": "App {current},可更新至 {version}。",
"client.connect.approveTitle": "允许使用 Piik App?",
"client.connect.approveHint": "此站点将可以使用本机的屏幕、窗口和麦克风。请确认你信任这个网址。",
"client.connect.approve": "允许使用",
@@ -296,8 +297,8 @@ export const zh = {
"client.update.available": "发现新的 Piik 版本",
"client.update.major": "发现新的 Piik 大版本",
"client.update.majorHint": "此更新含不兼容改动。升级前请查看版本说明。",
"client.update.downloads": "Gitee 备用下载",
"client.update.extractAPK": "解压 ZIP 后安装 APK。",
"client.update.downloads": "AtomGit 备用下载",
"client.update.download": "下载 {version}",
"client.update.differentBuild": "当前构建与官方发行版不同",
"client.update.official": "可获取 Piik 正式发行版",
@@ -311,6 +312,8 @@ export const zh = {
"gate.malformed": "房间号格式不正确",
"gate.malformedHint": "请输入 1000 至 9999 的四位房间号",
"gate.unavailableRoute": "无法访问",
"startup.failed": "页面未能加载",
"startup.retry": "请刷新页面后重试。",
"join.title": "加入房间",
"join.hint": "输入 {site} 的房间号",
+9 -2
View File
@@ -1,12 +1,19 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
import { StartupFailure } from "./components/living/StartupFailure";
import "./styles.css";
async function main() {
let app = <App />;
// Room controls share the Popover API; install it before any component mounts.
if (!("popover" in HTMLElement.prototype)) {
await import("./ui/popover-polyfill");
try {
await import("./ui/popover-polyfill");
} catch (error) {
console.error("Could not initialize page controls", error);
app = <StartupFailure />;
}
}
const root = document.getElementById("root");
@@ -16,7 +23,7 @@ async function main() {
createRoot(root).render(
<StrictMode>
<App />
{app}
</StrictMode>,
);
}
+6 -4
View File
@@ -2,6 +2,7 @@ import { createOpaqueId } from "../lib/opaque-id";
import { browserDebugEnabled, debugError, debugEvent } from "../lib/debug";
import { EMPTY_METRICS, type ConnectionMetrics } from "../types";
import { captureMetrics, collectConnectionMetricsFromReport, createStatsAccumulator } from "../webrtc/stats";
import { waitForConnectionOperation } from "../webrtc/connection-operation";
import { BrowserEncodingProducer } from "./browser-encoding-producer";
import { BROWSER_CARRIER_SIZE, type BrowserEncodingOutput } from "./browser-encoding-output";
import { codecIdentity, fits, nativeVideoBudget, negotiatedCodec, noRegression, observeVideo,
@@ -28,7 +29,7 @@ type Member = {
profile: QualityProfile; encoded: BrowserEncodingOutput;
configureCarrier: () => Promise<boolean>;
requestKey: () => Promise<void>; onFatal: () => void;
paused: boolean; disabled: boolean; disposed: boolean; mixed: boolean; carrier: boolean;
paused: boolean; disabled: boolean; readonly disposed: boolean; abort: AbortController; mixed: boolean; carrier: boolean;
codec?: RTCRtpCodec; codecKey?: string; budget?: number; raw?: RTCOutboundRtpStreamStats;
encoderStats: ReturnType<typeof createStatsAccumulator>;
current?: Group; pending?: { group: Group; selecting?: boolean };
@@ -53,7 +54,8 @@ export class BrowserEncodingPool {
onFatal: () => void): BrowserPooledSender | null {
if (this.disposed || this.failedSources.has(source) || source.kind !== "video" || source.readyState !== "live") return null;
const member: Member = { id: createOpaqueId(), source, sender, connection, profile: { ...profile }, encoded, configureCarrier, requestKey, onFatal,
paused: !source.enabled, disabled: false, disposed: false, mixed: false, carrier: encoded.snapshot().frames === 0,
paused: !source.enabled, disabled: false, abort: new AbortController(),
get disposed() { return this.abort.signal.aborted; }, mixed: false, carrier: encoded.snapshot().frames === 0,
encoderStats: createStatsAccumulator() };
this.members.add(member);
// A fresh connection has no useful raw output to preserve. Start its
@@ -153,7 +155,7 @@ export class BrowserEncodingPool {
await Promise.allSettled([
...[...this.members].map(async (member) => {
if (member.disposed || member.disabled || member.connection.connectionState !== "connected") { member.budget = undefined; return; }
const report = await member.connection.getStats().catch(() => null);
const report = await waitForConnectionOperation(member.abort.signal, () => member.connection.getStats()).catch(() => null);
if (member.disposed) return;
if (!report) { member.budget = undefined; return; }
const codec = negotiatedCodec(report);
@@ -409,7 +411,7 @@ export class BrowserEncodingPool {
private remove(member: Member): void {
if (member.disposed) return;
member.disposed = true;
member.abort.abort();
this.members.delete(member);
member.encoded.passthrough(member.requestKey);
member.carrier = false;
@@ -11,6 +11,7 @@ import {
videoQualitySettingsEqual, type QualityProfile,
} from "./quality";
import { cloneSenderVideoTrack, stopSenderVideoTrack } from "./sender-video-track";
import { waitForConnectionOperation } from "../webrtc/connection-operation";
// Leave time for ordinary encoding before the outer Viewer/route deadline.
// Bound local transport setup, not frame production from a quiet source.
@@ -163,7 +164,10 @@ export class BrowserEncodingProducer {
async report(): Promise<RTCStatsReport> {
this.requireSender();
const connection = this.send!;
const report = await connection.getStats().catch((error) => { debugRtcFailure(connection, error); throw error; });
const report = await waitForConnectionOperation(this.streamAbort.signal, () => connection.getStats()).catch((error) => {
if (!this.disposed) debugRtcFailure(connection, error);
throw error;
});
debugRtcStats(connection, report);
if (!this.disposed && this.startupPending &&
(this.startupFrames ?? 0) >= STARTUP_VIDEO_ENCODED_FRAMES) {
+36 -8
View File
@@ -5,7 +5,7 @@ interface DeliveredVideoSample {
timestampMs: number;
windowMs: number;
pixels: number;
framesPerSecond: number;
framesDecoded: number;
bitrateKbps: number | null;
}
@@ -28,7 +28,7 @@ function deliveredNothingSample(
timestampMs: sampleTimestampMs,
windowMs: sampleWindowMs,
pixels: 0,
framesPerSecond: 0,
framesDecoded: 0,
bitrateKbps: 0,
};
}
@@ -67,8 +67,7 @@ function deliveredVideoSample(
timestampMs: sampleTimestampMs,
windowMs: sampleWindowMs,
pixels: frameWidth * frameHeight,
// Native framesPerSecond covers the last second, not this comparison window.
framesPerSecond: Math.round((intervalFramesDecoded * 1_000) / sampleWindowMs),
framesDecoded: intervalFramesDecoded,
bitrateKbps:
typeof bitrateKbps === "number" &&
Number.isFinite(bitrateKbps) &&
@@ -103,6 +102,24 @@ function comparableSamples(
return [currentVideo, candidateVideo];
}
function frameRateDoesNotRegress(
current: DeliveredVideoSample,
candidate: DeliveredVideoSample,
): boolean {
return frameCountDeficit(
current.framesDecoded, current.windowMs,
candidate.framesDecoded, candidate.windowMs,
) <= 1;
}
function frameCountDeficit(
currentFrames: number, currentWindowMs: number,
candidateFrames: number, candidateWindowMs: number,
): number {
// Normalize discrete counters to one window; a boundary frame is not a rate change.
return Math.round(currentFrames * candidateWindowMs / currentWindowMs) - candidateFrames;
}
export function sfuCandidateDoesNotRegress(
current: ConnectionMetrics,
candidate: ConnectionMetrics,
@@ -122,7 +139,7 @@ export function sfuCandidateDoesNotRegress(
candidate.intervalPauseCount === 0 &&
candidate.intervalPauseDurationMs === 0 &&
candidateVideo.pixels >= currentVideo.pixels &&
candidateVideo.framesPerSecond >= currentVideo.framesPerSecond &&
frameRateDoesNotRegress(currentVideo, candidateVideo) &&
candidateVideo.bitrateKbps >= currentVideo.bitrateKbps
);
}
@@ -140,7 +157,7 @@ export function p2pCandidateDoesNotRegress(
candidate.intervalPauseCount === 0 &&
candidate.intervalPauseDurationMs === 0 &&
candidateVideo.pixels >= currentVideo.pixels &&
candidateVideo.framesPerSecond >= currentVideo.framesPerSecond
frameRateDoesNotRegress(currentVideo, candidateVideo)
);
}
@@ -149,6 +166,7 @@ class ConsecutiveCandidateQualityProbe {
private lastCurrentTimestampMs: number | null = null;
private consecutiveApprovedWindows = 0;
private consecutiveRejectedWindows = 0;
private consecutiveFrameDeficit = 0;
constructor(
private readonly compare: (
@@ -197,14 +215,23 @@ class ConsecutiveCandidateQualityProbe {
return "pending";
}
if (approved) {
// The whole proof run shares one frame of resolution, not one per window.
this.consecutiveFrameDeficit += frameCountDeficit(
current.intervalFramesDecoded!, current.sampleWindowMs!,
candidate.intervalFramesDecoded!, candidate.sampleWindowMs!,
);
if (this.consecutiveFrameDeficit > 1) {
this.resetRuns();
return "pending";
}
this.consecutiveApprovedWindows += 1;
this.consecutiveRejectedWindows = 0;
return this.consecutiveApprovedWindows >=
PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS
return this.consecutiveApprovedWindows >= PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS
? "approved"
: "pending";
}
this.consecutiveApprovedWindows = 0;
this.consecutiveFrameDeficit = 0;
this.consecutiveRejectedWindows += 1;
return this.consecutiveRejectedWindows >=
PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS
@@ -221,6 +248,7 @@ class ConsecutiveCandidateQualityProbe {
private resetRuns(): void {
this.consecutiveApprovedWindows = 0;
this.consecutiveRejectedWindows = 0;
this.consecutiveFrameDeficit = 0;
}
}
+49 -26
View File
@@ -44,6 +44,7 @@ export interface HostPublisherTransport {
interface HostPublisherSlot {
revision: number;
activationToken: RouteOperationToken | null;
connectionId: string;
publicationGeneration: string;
publisher: HostPublisherTransport;
@@ -56,7 +57,7 @@ interface HostSfuRouteEvents {
getStream: () => MediaStream | null;
getProfile: () => QualityProfile;
getVideoCodec: () => BrowserVideoCodec;
reconcileChildren: (childPeerIds: string[]) => void;
reconcileChildren: (assignment: ParticipantRouteAssignment, revision: number) => void;
send: (message: ClientMessage) => boolean;
onSenderUpdate?: (
metrics: ConnectionMetrics,
@@ -102,8 +103,8 @@ export class HostSfuRoute {
update.assignment.sfuPublicationGeneration,
)
: null;
if (pausedActiveReconciliation) {
this.events.reconcileChildren(update.assignment.childPeerIds);
if (update.phase === "active" && result !== "duplicate") {
this.events.reconcileChildren(update.assignment, update.revision);
}
if (this.paused && update.phase === "prepare") {
this.clearPending();
@@ -113,10 +114,19 @@ export class HostSfuRoute {
this.recovery = null;
this.lastFailureStage = null;
}
if (
update.phase === "active" && this.pending &&
this.pending.publicationGeneration === update.assignment.sfuPublicationGeneration &&
(this.pending.revision === update.revision || this.pending.activationToken)
) {
this.pending.activationToken = this.route.getActiveToken();
this.pending.revision = update.revision;
this.pending.publisher.updateConfig(this.pending);
}
if (update.phase === "prepare") {
if (
this.pending &&
(this.pending.revision !== update.revision ||
((!this.pending.activationToken && this.pending.revision !== update.revision) ||
this.pending.publicationGeneration !==
update.assignment.sfuPublicationGeneration)
) {
@@ -128,7 +138,7 @@ export class HostSfuRoute {
return result;
}
const token = this.route.token();
const token = this.route.getActiveToken();
if (retiredActive) {
void this.queueTransition(() =>
this.disconnectRetiredPublisher(retiredActive),
@@ -163,8 +173,12 @@ export class HostSfuRoute {
this.route.reset();
this.recovery = null;
const closing = this.retirePublishers();
const accepted = this.route.accept(update);
this.events.reconcileChildren([]);
this.events.reconcileChildren({
upstream: { kind: "none" },
childPeerIds: [],
sfuPublicationGeneration: null,
}, update.revision);
const accepted = this.accept(update);
await this.queueTransition(() => closing);
@@ -172,8 +186,8 @@ export class HostSfuRoute {
return "stale";
}
this.resyncing = false;
const token = this.route.token();
if (token && this.route.getPhase() === "active") {
const token = this.route.getActiveToken();
if (token) {
await this.queueActivation(token);
}
return accepted;
@@ -215,7 +229,8 @@ export class HostSfuRoute {
return;
}
if (
this.pending?.revision === message.revision &&
this.pending &&
(this.pending.revision === message.revision || this.pending.activationToken) &&
this.pending.publicationGeneration === publicationGeneration &&
this.pending.connectionId === message.connectionId &&
!this.pending.failed
@@ -238,6 +253,7 @@ export class HostSfuRoute {
});
slot = {
revision: message.revision,
activationToken: phase === "active" ? this.route.getActiveToken() : null,
connectionId: message.connectionId,
publicationGeneration,
publisher,
@@ -249,7 +265,7 @@ export class HostSfuRoute {
try {
const connected = await publisher.connect(message);
if (!connected) {
if (this.pending === slot && this.route.owns(token)) {
if (this.pending === slot && this.ownsPublisherSlot(slot)) {
this.handleFailure(slot);
} else {
if (this.pending === slot) {
@@ -260,7 +276,7 @@ export class HostSfuRoute {
await this.disconnectPublisher(slot);
return;
}
if (this.pending !== slot || !this.route.owns(token)) {
if (this.pending !== slot || !this.ownsPublisherSlot(slot)) {
if (this.pending === slot) {
this.pending = null;
}
@@ -271,7 +287,7 @@ export class HostSfuRoute {
slot.connected = true;
let prepared = false;
await this.queueTransition(async () => {
if (this.pending !== slot || !this.route.owns(token)) {
if (this.pending !== slot || !this.ownsPublisherSlot(slot)) {
if (this.pending === slot) {
this.pending = null;
}
@@ -284,8 +300,8 @@ export class HostSfuRoute {
if (!prepared) {
return;
}
if (phase === "active" && !this.resyncing) {
await this.queueActivation(token);
if (slot.activationToken && !this.resyncing) {
await this.queueActivation(slot.activationToken);
}
} catch {
this.failPublisherSlot(slot);
@@ -308,7 +324,7 @@ export class HostSfuRoute {
slot && !slot.failed && slot.connectionId === message.connectionId &&
slot.publicationGeneration === message.publicationGeneration,
);
if (slot === this.pending && slot?.revision !== message.revision) return;
if (slot === this.pending && !slot?.activationToken && slot?.revision !== message.revision) return;
await slot?.publisher.acceptSignal(message);
}
@@ -417,8 +433,12 @@ export class HostSfuRoute {
token: RouteOperationToken,
retireUnreferenced = false,
): Promise<void> {
const pending = this.pending;
return this.queueTransition(async () => {
if (this.closed || this.resyncing || !this.route.owns(token, "active")) {
if (
this.closed || this.resyncing || !this.route.ownsActive(token) ||
(pending?.activationToken && this.pending !== pending && this.active !== pending)
) {
return;
}
const assignment = this.route.getActiveAssignment();
@@ -429,11 +449,11 @@ export class HostSfuRoute {
assignment.sfuPublicationGeneration
) {
await this.retireActive();
if (!this.route.owns(token, "active")) {
if (!this.route.ownsActive(token)) {
return;
}
}
await this.activate(assignment, token);
await this.activate(assignment, token, pending);
}
});
}
@@ -447,20 +467,19 @@ export class HostSfuRoute {
private async activate(
assignment: ParticipantRouteAssignment,
token: RouteOperationToken,
pendingAtQueue: HostPublisherSlot | null,
): Promise<void> {
const publicationGeneration = assignment.sfuPublicationGeneration;
if (publicationGeneration === null) {
this.clearPending();
if (this.pending === pendingAtQueue) this.clearPending();
await this.retireActive();
if (!this.route.owns(token, "active")) {
if (!this.route.ownsActive(token)) {
return;
}
this.events.reconcileChildren(assignment.childPeerIds);
this.commitMedia(token);
return;
}
this.events.reconcileChildren(assignment.childPeerIds);
if (
this.active &&
!this.active.failed &&
@@ -468,8 +487,9 @@ export class HostSfuRoute {
this.pending?.publicationGeneration !== publicationGeneration
) {
this.active.revision = token.revision;
this.active.activationToken = token;
this.active.publisher.updateConfig(this.active);
this.clearPending();
if (this.pending === pendingAtQueue) this.clearPending();
if (this.active.active) {
this.commitMedia(token);
}
@@ -484,7 +504,7 @@ export class HostSfuRoute {
!pending.connected ||
!pending.active
) {
if (this.route.owns(token, "active")) {
if (this.route.ownsActive(token)) {
this.requestRecovery(token.revision);
}
return;
@@ -558,6 +578,7 @@ export class HostSfuRoute {
}
private ownsPublisherSlot(slot: HostPublisherSlot): boolean {
if (slot.activationToken) return this.route.ownsActive(slot.activationToken);
return (
this.route.getRevision() === slot.revision &&
this.route.getPlannedAssignment()?.sfuPublicationGeneration ===
@@ -624,6 +645,8 @@ export class HostSfuRoute {
}
const wasActive = this.active === slot;
const wasPending = this.pending === slot;
const wasCommitted = slot.activationToken !== null &&
this.route.ownsActive(slot.activationToken);
if (!wasActive && !wasPending) {
slot.failed = true;
return;
@@ -649,7 +672,7 @@ export class HostSfuRoute {
}
if (phase === "prepare") {
const activeRevision = this.route.getActiveRevision();
if (wasActive) {
if (wasActive || wasCommitted) {
if (
activeRevision !== null &&
this.route.getActiveAssignment()?.sfuPublicationGeneration ===
+15 -6
View File
@@ -43,7 +43,7 @@ export class MediaRouteTransition {
private plannedAssignment: ParticipantRouteAssignment | null = null;
private activeAssignment: ParticipantRouteAssignment | null = null;
// Preparation advances the operation without replacing committed authority.
private activeRevision: number | null = null;
private activeToken: RouteOperationToken | null = null;
private mediaAssignment: ParticipantRouteAssignment | null = null;
private preparedCandidate: PreparedRouteCandidate | null = null;
private generation = 0;
@@ -73,11 +73,11 @@ export class MediaRouteTransition {
this.plannedAssignment = cloneAssignment(update.assignment);
this.preparedCandidate =
update.phase === "prepare" ? cloneCandidate(update.candidate) : null;
this.generation += 1;
if (update.phase === "active") {
this.activeAssignment = cloneAssignment(update.assignment);
this.activeRevision = update.revision;
this.activeToken = { revision: update.revision, generation: this.generation };
}
this.generation += 1;
return "accepted";
}
@@ -101,7 +101,7 @@ export class MediaRouteTransition {
}
markMediaActive(token: RouteOperationToken): boolean {
if (!this.owns(token, "active") || !this.activeAssignment) {
if (!this.ownsActive(token) || !this.activeAssignment) {
return false;
}
this.mediaAssignment = cloneAssignment(this.activeAssignment);
@@ -127,7 +127,16 @@ export class MediaRouteTransition {
}
getActiveRevision(): number | null {
return this.activeRevision;
return this.activeToken?.revision ?? null;
}
getActiveToken(): RouteOperationToken | null {
return this.activeToken ? { ...this.activeToken } : null;
}
ownsActive(token: RouteOperationToken): boolean {
return token.revision === this.activeToken?.revision &&
token.generation === this.activeToken.generation;
}
getMediaAssignment(): ParticipantRouteAssignment | null {
@@ -145,7 +154,7 @@ export class MediaRouteTransition {
this.phase = null;
this.plannedAssignment = null;
this.activeAssignment = null;
this.activeRevision = null;
this.activeToken = null;
this.mediaAssignment = null;
this.preparedCandidate = null;
this.generation += 1;
+3 -1
View File
@@ -219,7 +219,9 @@ export function reduceViewerPresentation(
},
routeStatus: action.authoritative
? null
: !committedRoute && state.routeStatus?.revision === action.revision
: !committedRoute &&
(state.routeStatus?.revision === action.revision ||
(action.kind === "none" && state.routeStatus?.state === "failed"))
? state.routeStatus
: null,
connection: action.authoritative && state.media === null
+86 -61
View File
@@ -107,7 +107,11 @@ export class ViewerSfuRoute {
private readonly route = new MediaRouteTransition();
private pending: ViewerSubscriberSlot | null = null;
private active: ViewerSubscriberSlot | null = null;
private pendingPeer: { revision: number; connectionId: string } | null = null;
private pendingPeer: {
revision: number;
connectionId: string;
activationToken: RouteOperationToken | null;
} | null = null;
private transitionTail: Promise<void> = Promise.resolve();
private resyncGeneration = 0;
private resyncing = false;
@@ -123,12 +127,7 @@ export class ViewerSfuRoute {
if (this.closed) {
return "stale";
}
const previousRevision = this.route.getRevision();
const previousMediaAssignment = this.route.getMediaAssignment();
const sameCommittedMedia = sameUpstream(
previousMediaAssignment,
update.assignment,
);
const previousActiveAssignment = this.route.getActiveAssignment();
const result = this.route.accept(update);
if (result === "stale") {
return result;
@@ -141,7 +140,8 @@ export class ViewerSfuRoute {
const retiredActive = pausedActiveReconciliation
? this.detachUnreferencedActive(update.assignment)
: null;
if (pausedActiveReconciliation) {
// Committed child permissions cannot wait for unrelated upstream SDP.
if (update.phase === "active" && result !== "duplicate") {
this.activateChildren(update.assignment.childPeerIds, update.revision);
}
if (this.paused && update.phase === "prepare") {
@@ -156,13 +156,28 @@ export class ViewerSfuRoute {
this.disconnectRetiredSubscriber(retiredActive),
);
}
if (previousRevision !== update.revision && !sameCommittedMedia) {
if (
update.phase !== "prepare" &&
this.pendingPeer !== null
) {
this.events.preparePeer?.(null);
this.pendingPeer = null;
if (update.phase === "active") {
const token = this.route.getActiveToken()!;
if (this.pendingPeer) {
if (update.assignment.upstream.kind === "peer" &&
(this.pendingPeer.revision === update.revision ||
(this.pendingPeer.activationToken && sameUpstream(previousActiveAssignment, update.assignment)))) {
this.pendingPeer.activationToken = token;
} else {
this.pendingPeer = null;
this.events.preparePeer?.(null);
}
}
if (this.pending) {
if (update.assignment.upstream.kind === "sfu" &&
this.pending.publicationGeneration === update.assignment.sfuPublicationGeneration &&
(this.pending.revision === update.revision || this.pending.activationToken)) {
this.pending.activationToken = token;
this.pending.revision = update.revision;
this.pending.subscriber.updateConfig(this.pending);
} else {
this.clearPending();
}
}
}
if (update.phase === "prepare") {
@@ -176,33 +191,39 @@ export class ViewerSfuRoute {
ownsChildCandidate ? update.assignment.childPeerIds : undefined,
ownsChildCandidate ? update.revision : undefined,
);
if (!ownsUpstreamCandidate) {
// A child operation cannot retire an incoming resource already committed
// by the server, even while its local activation is still queued.
if (this.pendingPeer && !this.pendingPeer.activationToken) {
this.pendingPeer = null;
this.events.preparePeer?.(null);
}
if (this.pending && !this.pending.activationToken) this.clearPending();
return result;
}
const replacedPeerCandidate = this.pendingPeer !== null;
if (replacedPeerCandidate) {
this.events.preparePeer?.(null);
this.pendingPeer = null;
}
const needsPeerCandidate =
ownsUpstreamCandidate &&
candidate.transport !== "sfu" &&
update.assignment.upstream.kind === "peer" &&
candidate.connectionId.length > 0;
const replacedPeerCandidate = this.pendingPeer !== null;
if (replacedPeerCandidate) {
this.pendingPeer = null;
this.events.preparePeer?.(null);
}
if (needsPeerCandidate && update.assignment.upstream.kind === "peer") {
this.pendingPeer = {
revision: update.revision,
connectionId: candidate.connectionId,
activationToken: null,
};
this.events.preparePeer?.(update.assignment, update.revision, candidate);
} else if (
update.assignment.upstream.kind !== "peer" &&
!replacedPeerCandidate
) {
} else if (update.assignment.upstream.kind !== "peer" && !replacedPeerCandidate) {
this.events.preparePeer?.(null);
}
if (this.pending?.revision !== update.revision) {
this.clearPending();
}
if (
!ownsUpstreamCandidate ||
candidate.transport !== "sfu" ||
update.assignment.upstream.kind !== "sfu"
) {
@@ -211,11 +232,11 @@ export class ViewerSfuRoute {
return result;
}
const token = this.route.token();
const token = this.route.getActiveToken();
if (!token) {
return result;
}
if (this.pendingPeer?.revision !== update.revision) {
if (!this.pendingPeer) {
this.preparePeer(update.assignment);
}
if (this.resyncing) {
@@ -293,7 +314,6 @@ export class ViewerSfuRoute {
if (identityChanged) {
this.viewerPeerId = viewerPeerId;
}
this.pendingPeer = null;
const currentMediaAssignment = this.route.getMediaAssignment();
const preservesActiveMedia = Boolean(
!identityChanged &&
@@ -327,6 +347,7 @@ export class ViewerSfuRoute {
const resyncGeneration = ++this.resyncGeneration;
this.resyncing = true;
this.pendingPeer = null;
this.route.reset();
this.events.prepareChild?.(null);
const pending = this.pending;
@@ -342,6 +363,9 @@ export class ViewerSfuRoute {
const accepted = this.route.accept(update);
this.preparePeer(update.assignment);
this.events.resetMedia?.();
if (update.phase === "active") {
this.activateChildren(update.assignment.childPeerIds, update.revision);
}
await this.queueTransition(async () => {
if (active?.activated) {
@@ -363,8 +387,8 @@ export class ViewerSfuRoute {
return "stale";
}
this.resyncing = false;
const token = this.route.token();
if (token && this.route.getPhase() === "active") {
const token = this.route.getActiveToken();
if (token) {
await this.queueActiveRoute(token, false);
}
return accepted;
@@ -461,11 +485,6 @@ export class ViewerSfuRoute {
);
if (slot.qualityResult === "approved") {
this.sendPendingReady(slot);
} else if (
slot.qualityResult === "rejected" &&
this.routeFailed(slot.revision, "prepare")
) {
this.clearPending();
}
}
}
@@ -558,9 +577,9 @@ export class ViewerSfuRoute {
}
retryPeerActivation(connectionId: string): boolean {
const token = this.route.token();
if (this.closed || this.resyncing || !token || !this.route.owns(token, "active") ||
this.pendingPeer?.revision !== token.revision || this.pendingPeer.connectionId !== connectionId) return false;
const token = this.pendingPeer?.activationToken;
if (this.closed || this.resyncing || !token || !this.route.ownsActive(token) ||
this.pendingPeer?.connectionId !== connectionId) return false;
void this.queueActiveRoute(token, false);
return true;
}
@@ -570,7 +589,7 @@ export class ViewerSfuRoute {
slot && !slot.failed && slot.connectionId === message.connectionId &&
slot.publicationGeneration === message.publicationGeneration,
);
if (slot === this.pending && slot?.revision !== message.revision) return;
if (slot === this.pending && !slot?.activationToken && slot?.revision !== message.revision) return;
await slot?.subscriber.acceptSignal(message);
}
@@ -627,8 +646,12 @@ export class ViewerSfuRoute {
acknowledge: boolean,
retireUnreferenced = false,
): Promise<void> {
const pendingPeer = this.pendingPeer;
const pendingSfu = this.pending;
return this.queueTransition(async () => {
if (this.closed || this.resyncing || !this.route.owns(token, "active")) {
if (this.closed || this.resyncing || !this.route.ownsActive(token) ||
(pendingPeer?.activationToken && this.pendingPeer !== pendingPeer) ||
(pendingSfu?.activationToken && this.pending !== pendingSfu && this.active !== pendingSfu)) {
return;
}
const assignment = this.route.getActiveAssignment();
@@ -644,12 +667,11 @@ export class ViewerSfuRoute {
this.active?.publicationGeneration !== assignedPublicationGeneration
) {
await this.retireActive();
if (!this.route.owns(token, "active")) {
if (!this.route.ownsActive(token)) {
return;
}
}
if (assignment.upstream.kind === "sfu") {
this.activateChildren(assignment.childPeerIds, token.revision);
const mediaAssignment = this.route.getMediaAssignment();
if (
mediaAssignment?.upstream.kind === "sfu" &&
@@ -659,7 +681,7 @@ export class ViewerSfuRoute {
!this.active.failed &&
this.pending?.publicationGeneration !== assignment.sfuPublicationGeneration
) {
this.clearPending();
if (this.pending === pendingSfu) this.clearPending();
this.active.revision = token.revision;
this.active.subscriber.updateConfig(this.active);
this.commitMedia(token);
@@ -669,36 +691,38 @@ export class ViewerSfuRoute {
return;
}
const pendingPeer = this.pendingPeer;
const promoted =
pendingPeer?.revision === token.revision
? await this.events.activatePeer(assignment, token.revision)
pendingPeer?.activationToken && this.route.ownsActive(pendingPeer.activationToken)
? await this.events.activatePeer(assignment, pendingPeer.revision)
: false;
if (!this.route.owns(token, "active")) {
if (pendingPeer) {
if (this.pendingPeer !== pendingPeer) return;
if (pendingPeer.activationToken) token = pendingPeer.activationToken;
}
if (!this.route.ownsActive(token)) {
return;
}
if (promoted === "waiting") return;
if (pendingPeer?.revision === token.revision && promoted !== true) {
if (pendingPeer?.activationToken && promoted !== true) {
// Readiness may reach the server before a candidate's local failure.
// Once committed, report against the exact active connection for recovery.
this.routeFailed(token.revision, "active", pendingPeer.connectionId);
return;
}
this.pendingPeer = null;
this.clearPending();
if (this.pendingPeer === pendingPeer) this.pendingPeer = null;
if (this.pending === pendingSfu) this.clearPending();
if (this.active) {
await this.retireActive();
}
if (!this.route.owns(token, "active")) {
if (!this.route.ownsActive(token)) {
return;
}
if (!promoted) {
await this.events.activatePeer(assignment);
}
if (!this.route.owns(token, "active")) {
if (!this.route.ownsActive(token)) {
return;
}
this.activateChildren(assignment.childPeerIds, token.revision);
this.commitMedia(token);
});
}
@@ -743,14 +767,13 @@ export class ViewerSfuRoute {
) {
if (
acknowledge &&
this.route.owns(token, "active") &&
this.route.ownsActive(token) &&
pending === null
) {
this.events.send({ type: "refresh-sfu", revision: token.revision });
}
return;
}
pending.activationToken = token;
await this.promotePendingSfu(pending);
}
@@ -776,10 +799,12 @@ export class ViewerSfuRoute {
if (this.paused || !slot.activated) {
return false;
}
const assignment = this.route.getPlannedAssignment();
const phase = this.route.getPhase();
const committed = slot.activationToken && this.route.ownsActive(slot.activationToken);
const assignment = committed ? this.route.getActiveAssignment() : this.route.getPlannedAssignment();
const phase = committed ? "active" : this.route.getPhase();
const revision = committed ? this.route.getActiveRevision() : this.route.getRevision();
if (
this.route.getRevision() !== slot.revision ||
revision !== slot.revision ||
assignment?.upstream.kind !== "sfu" ||
assignment.sfuPublicationGeneration !== slot.publicationGeneration ||
phase === null
@@ -826,7 +851,7 @@ export class ViewerSfuRoute {
!slot.stream ||
!slot.decodedFrame ||
!token ||
!this.route.owns(token, "active") ||
!this.route.ownsActive(token) ||
assignment?.upstream.kind !== "sfu"
) {
return;
@@ -959,7 +984,7 @@ export class ViewerSfuRoute {
if (revision === null || phase === null) {
return;
}
if (wasActive) {
if (wasActive || (slot.activationToken && this.route.ownsActive(slot.activationToken))) {
const activeRevision = this.route.getActiveRevision();
const activeAssignment = this.route.getActiveAssignment();
if (
+15 -12
View File
@@ -60,14 +60,13 @@ export function isLoopbackPage(): boolean {
return ["localhost", "127.0.0.1", "[::1]"].includes(window.location.hostname);
}
async function ungrantedLocalPermission(): Promise<PermissionState | null> {
async function localPermission(): Promise<PermissionStatus | null> {
// App Local already runs on loopback. Its permission can say "prompt" even
// though loopback-to-loopback requests do not need consent.
if (isLoopbackPage()) return null;
for (const name of ["loopback-network", "local-network-access"]) {
try {
const { state } = await navigator.permissions.query({ name: name as PermissionName });
return state === "granted" ? null : state;
return await navigator.permissions.query({ name: name as PermissionName });
} catch {
// Older Chromium uses the combined name; other browsers may expose neither.
}
@@ -149,21 +148,23 @@ async function discoverNative<T>(
{ waitForPermission = true, signal }: NativeDiscoveryOptions,
): Promise<T | null> {
if (signal?.aborted) return null;
if (!waitForPermission) {
const permission = await ungrantedLocalPermission();
if (permission) {
debugEvent("native", "unavailable", { stage: "permission", permission });
return null;
}
const permission = await localPermission();
if (!waitForPermission && permission && permission.state !== "granted") {
debugEvent("native", "unavailable", { stage: "permission", permission: permission.state });
return null;
}
if (signal?.aborted) return null;
const controller = new AbortController();
const abort = () => controller.abort(signal?.reason);
signal?.addEventListener("abort", abort, { once: true });
// The first request may wait for browser permission. One shared deadline
// bounds the scan; a silent port must not hide an App on another port.
const timer = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
// Permission waiting is user-owned; the parallel scan has one network deadline.
let timer: number | undefined;
const startDeadline = () => { timer ??= window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); };
const permissionChanged = () => { if (permission?.state !== "prompt") startDeadline(); };
const awaitingPermission = permission?.state === "prompt";
try {
if (awaitingPermission) permission.addEventListener("change", permissionChanged);
permissionChanged();
// An explicit launch stays with its App even when another approved App is faster.
const selectedPort = clientRuntimePort();
const ports = selectedPort === null ? Array.from({
@@ -175,6 +176,7 @@ async function discoverNative<T>(
signal: controller.signal,
...(isLoopbackPage() ? {} : { targetAddressSpace: "loopback" }),
} as RequestInit);
startDeadline();
if (!response.ok) throw new Error("Piik App discovery was not accepted");
const body: unknown = await response.json();
const identity = nativeDiscoveryIdentitySchema.safeParse(body);
@@ -201,6 +203,7 @@ async function discoverNative<T>(
debugEvent("native", "unavailable", { stage: "discovery", timedOut: controller.signal.aborted });
return null;
} finally {
if (awaitingPermission) permission.removeEventListener("change", permissionChanged);
signal?.removeEventListener("abort", abort);
window.clearTimeout(timer);
controller.abort();
+3
View File
@@ -27,6 +27,9 @@ export const nativeDiscoveryIdentitySchema = z.object({
export const nativeHealthSchema = nativeDiscoveryIdentitySchema.extend({
protocol: z.literal(NATIVE_CLIENT_PROTOCOL),
version: z.string().optional(),
revision: z.string().optional(),
packageTarget: z.string().optional(),
qualityPreference: z.boolean().optional(),
activationURL: z.literal("piik://media").optional(),
instanceToken: z
+5 -16
View File
@@ -13,10 +13,8 @@ import { consoleLanguage } from "../locales";
import { Glyph } from "../ui/icons";
import { currentThemePreference, subscribeTheme } from "../ui/theme";
import { clientLaunchURL, type ClientLaunchPresentation } from "../lib/session";
import {
checkReleaseUpdate,
type ReleaseUpdateNotice,
} from "../lib/release-update";
import type { AppReleaseIdentity } from "../lib/release-update";
import { useReleaseUpdate } from "../lib/use-release-update";
const launcherStateSchema = z.object({
sites: z.array(z.string()),
@@ -60,7 +58,8 @@ export function AppLauncherPage() {
const [debugError, setDebugError] = useState(false);
const [reload, setReload] = useState(0);
const [lan, setLan] = useState<z.infer<typeof launcherStateSchema>["lan"]>();
const [update, setUpdate] = useState<ReleaseUpdateNotice | null>(null);
const [build, setBuild] = useState<AppReleaseIdentity>();
const { update } = useReleaseUpdate(build);
const [version, setVersion] = useState<string>();
const [target, setTarget] = useState<string>();
const [controlPort, setControlPort] = useState<number>();
@@ -92,7 +91,6 @@ export function AppLauncherPage() {
useEffect(() => {
let current = true;
let timer: ReturnType<typeof setTimeout> | undefined;
let checkedRelease = false;
let restoredSettings = false;
let reading = false;
const readState = () => {
@@ -132,16 +130,7 @@ export function AppLauncherPage() {
: previous?.kind === "load" ? null : previous);
setLoading(false);
if (state.starting) timer = setTimeout(() => void readState(), 750);
if (checkedRelease) return;
checkedRelease = true;
void checkReleaseUpdate({
version: state.version,
revision: state.revision,
}, { packageTarget: state.packageTarget })
.then((notice) => {
if (current && notice) setUpdate(notice);
})
.catch(() => undefined);
setBuild({ version: state.version, revision: state.revision, packageTarget: state.packageTarget });
})
.catch(() => {
if (!fresh()) return;
+3 -4
View File
@@ -861,12 +861,13 @@ export function HostPage({
}
return new SfuPublisher(events);
},
reconcileChildren: (childPeerIds) => {
reconcileChildren: (assignment, revision) => {
if (
isCurrentGeneration(generation) &&
hostSfuRouteRef.current === route
) {
reconcileHostChildren(childPeerIds, generation);
activatePreparedHostChild(revision, assignment);
reconcileHostChildren(assignment.childPeerIds, generation);
}
},
send: (message) =>
@@ -2571,8 +2572,6 @@ export function HostPage({
} else {
discardPreparedHostChild();
}
} else {
activatePreparedHostChild(message.revision, message.assignment);
}
if (
message.phase === "active" &&
+7
View File
@@ -7,6 +7,7 @@ import { StatusIndicator } from "../components/living/StatusIndicator";
import { ShareFailureHelp } from "../components/living/ShareFailureHelp";
import { hostFailureChecks } from "./host-page-notices";
import { LoadingStatus } from "../components/living/WaitingStatus";
import { StartupFailure } from "../components/living/StartupFailure";
import { Pill } from "../components/living/primitives";
import { deriveViewerPresentation } from "../media/viewer-presentation";
import {
@@ -44,6 +45,11 @@ function StatusMark({ status }: { status: StatusDescriptor }) {
}
export function StatusPreviewPage() {
return new URLSearchParams(location.search).has("startup-failure")
? <StartupFailure /> : <StatusCatalog />;
}
function StatusCatalog() {
usePreviewAnchor();
const { lang, vis, t, titleFrames } = useCopy();
const [selected, setSelected] = useState("playing");
@@ -203,6 +209,7 @@ export function StatusPreviewPage() {
<header><h2>加载与等待</h2>
<p>页面加载与站点检查只显示真实状态。App 启动与媒体等待保留一句次要短句,每 15 秒轮换,隐藏时暂停;连续等待中的状态变化不会重新抽句。</p>
</header>
<p><a href="/__status-preview?startup-failure">{t("startup.failed")}</a></p>
<label>入口状态 <select value={loadingLabel} onChange={event => setLoadingLabel(event.target.value as CopyKey | "")}>
<option value="common.loading">页面加载</option>
<option value="gate.checking">站点检查</option>
+2 -14
View File
@@ -1194,7 +1194,7 @@ export function ViewerPage({
},
onSfuStream: (
nextStream,
assignment,
_assignment,
initialVideoStream,
revision,
) => {
@@ -1203,7 +1203,7 @@ export function ViewerPage({
}
const previousChildPeerIds = currentAssignment.childPeerIds;
currentAssignment = limitMediaAssignment(
{ parentPeerId: null, childPeerIds: assignment.childPeerIds },
{ parentPeerId: null, childPeerIds: currentAssignment.childPeerIds },
endpointMediaCopyCapacity,
);
reconcileRelayChildren(previousChildPeerIds);
@@ -1375,18 +1375,6 @@ export function ViewerPage({
activePeerMetrics,
snapshot.metrics,
);
if (
probe.qualityResult === "rejected" &&
signal.send({
type: "route-failed",
revision: probe.revision,
phase: "prepare",
connectionId: probe.candidateConnectionId,
})
) {
discardPendingPeer();
return;
}
}
}
provePendingPeer();
+10 -4
View File
@@ -77,8 +77,11 @@ export class BrowserVoiceEndpoint {
const connections = [...this.connections.values()].filter(connection => !connection.config.pending && connection.pc.connectionState === "connected");
await Promise.all(connections.map(async connection => {
const received = [...this.received].filter(([, binding]) => binding.connectionId === connection.config.connectionId);
const stats = await connection.pc.getStats();
if (!this.current(connection) || connection.config.pending || connection.pc.connectionState !== "connected") return;
const stats = await this.wait(connection, () => connection.pc.getStats()).catch(error => {
if (this.current(connection)) throw error;
return null;
});
if (!stats || !this.current(connection) || connection.config.pending || connection.pc.connectionState !== "connected") return;
for (const [key, binding] of received) {
if (this.received.get(key) !== binding) continue;
const publisher = this.state?.publications.find(pub => pub.id === binding.publicationId)?.peerId;
@@ -95,8 +98,11 @@ export class BrowserVoiceEndpoint {
const samples = await Promise.all(connections.map(async connection => {
const received = [...this.received].filter(([, binding]) => binding.connectionId === connection.config.connectionId);
const senders = [...connection.senders].map(([publicationId, sender]) => ({ publicationId, sender, track: sender.track }));
const report = await connection.pc.getStats();
if (!this.current(connection) || connection.config.pending || connection.pc.connectionState !== "connected") return [];
const report = await this.wait(connection, () => connection.pc.getStats()).catch(error => {
if (this.current(connection)) throw error;
return null;
});
if (!report || !this.current(connection) || connection.config.pending || connection.pc.connectionState !== "connected") return [];
const { config } = connection;
const samples: VoiceConnectionMetric[] = [];
const retained = new Set([...config.send.map(id => `send/${id}`), ...config.receive.map(id => `receive/${id}`)]);
+7 -3
View File
@@ -924,6 +924,7 @@ body.lr-theater-open .lr-top { visibility: hidden; }
/* ---------- buttons & chips ---------- */
.lr-app-connect.is-ready > svg { color: var(--live); }
.lr-app-connect.is-ready[data-update] > svg { color: var(--primary); }
.lr-anchored-card {
position: fixed; inset: auto; margin: 0; padding: 16px;
width: min(300px, calc(100vw - 16px)); box-sizing: border-box;
@@ -932,11 +933,14 @@ body.lr-theater-open .lr-top { visibility: hidden; }
box-shadow: var(--control-shadow), 0 12px 36px #101a2c33;
overflow: auto; overscroll-behavior: contain;
}
.lr-app-connect-help p { margin: 12px 0; font-size: 13px; line-height: 1.6; }
.lr-app-connect-help p { margin: 12px 0; font-size: 13px; line-height: 1.6; text-align: center; }
.lr-app-connect-help .lr-app-connect-version { color: var(--muted); font-size: 12px; }
.lr-app-connect-help .lr-client-release { margin-block: 12px; }
.lr-anchored-card:is(:popover-open, .\:popover-open) { animation: lr-language-open 180ms var(--spring); }
.lr-anchored-card.is-above { --language-offset: 5px; }
.lr-app-connect-head { display: flex; align-items: flex-start; gap: 8px; }
.lr-app-connect-close { flex: none; }
.lr-app-connect-head { display: grid; grid-template-columns: var(--control-dense-size) minmax(0, 1fr) var(--control-dense-size); align-items: start; }
.lr-app-connect-head > :first-child { grid-area: 1 / 2; }
.lr-app-connect-close { grid-area: 1 / 3; justify-self: end; }
.lr-app-connect-scene { width: min(220px, 100%); aspect-ratio: 10 / 3; margin-inline: auto; }
.lr-app-connect-scene > svg { width: 100% !important; }
.lr-app-connect-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }
+15 -3
View File
@@ -376,7 +376,11 @@ export class ViewerRelay {
candidate,
);
} catch (error) {
debugError("webrtc", "relay-prepare-failed", error, { connectionId: candidate.connectionId });
debugError("webrtc", "relay-prepare-failed", error, {
revision,
connectionId: candidate.connectionId,
stage: "create",
});
this.discardPreparedChild();
this.events.onPreparedChildFailed?.(revision, candidate.connectionId);
return;
@@ -393,7 +397,14 @@ export class ViewerRelay {
};
void peer
.start()
.catch(() => false)
.catch((error) => {
debugError("webrtc", "relay-prepare-failed", error, {
revision,
connectionId: candidate.connectionId,
stage: "start",
});
return false;
})
.then((started) => {
if (!started && this.preparedChild?.peer === peer) {
this.failPreparedChild(peer);
@@ -426,7 +437,8 @@ export class ViewerRelay {
if (
preparedPeer &&
this.preparedChild?.peer === preparedPeer &&
!(await this.replacePeerStream(preparedPeer, stream))
!(await this.replacePeerStream(preparedPeer, stream)) &&
this.stream === stream
) {
this.failPreparedChild(preparedPeer);
}
+37 -3
View File
@@ -41,9 +41,11 @@ const source = ts.createSourceFile("AppConnectionButton.tsx", readFileSync(
new URL("../src/client/components/living/AppConnectionButton.tsx", import.meta.url), "utf8",
), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let connect: string | undefined;
let rememberBuild: string | undefined;
const effects: string[] = [];
function collect(node: ts.Node): void {
if (ts.isFunctionDeclaration(node) && node.name?.text === "connect") connect = node.getText(source);
if (ts.isFunctionDeclaration(node) && node.name?.text === "rememberBuild") rememberBuild = node.getText(source);
if (ts.isCallExpression(node) && node.expression.getText(source) === "useEffect") {
effects.push(node.arguments[0]!.getText(source));
}
@@ -51,7 +53,7 @@ function collect(node: ts.Node): void {
}
collect(source);
if (!connect || !effects.length) throw new Error("Missing App connection operation or cleanup");
const executable = ts.transpileModule(`${connect}\nconst cleanups = [${effects.map(effect => `(${effect})()`).join(",")}];
const executable = ts.transpileModule(`${rememberBuild}\n${connect}\nconst cleanups = [${effects.map(effect => `(${effect})()`).join(",")}];
({ connect, cleanup: () => cleanups.reverse().forEach(fn => fn?.()) });`, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
}).outputText;
@@ -74,10 +76,11 @@ function mount(activated = false, state: "idle" | "ready" = "idle", android = fa
const help = { current: { hidePopover: vi.fn(), matches: vi.fn(() => false) } };
const showHelp = vi.fn();
const setState = vi.fn();
const setBuild = vi.fn();
const activateClient = vi.fn();
const onConnected = vi.fn();
const operation = runInNewContext(executable, {
window, document, pending, healthCheck, help, showHelp, setState, activateClient, onConnected, AbortController, URL,
window, document, pending, healthCheck, help, showHelp, setState, setBuild, activateClient, onConnected, AbortController, URL,
wakeURL: android ? "intent://app#Intent;scheme=piik;package=tv.piik.android;end" : null,
state, isClientActivated: () => activated,
watchClientActivation: (changed: () => void) => {
@@ -96,10 +99,20 @@ function mount(activated = false, state: "idle" | "ready" = "idle", android = fa
}
const activateElsewhere = () => { activated = true; window.dispatchEvent(new Event("activation")); };
const openApproval = async () => { await operation.connect(); await operation.connect(); };
return { ...operation, openApproval, popup, window, document, native, pending, help, showHelp, setState, activateClient, activateElsewhere, onConnected, message };
return { ...operation, openApproval, popup, window, document, native, pending, help, showHelp, setState, setBuild, activateClient, activateElsewhere, onConnected, message };
}
describe("App connection approval", () => {
it("uses the approved App's build and drops credentials from the update input", async () => {
const page = mount(true);
const build = { version: "v2.5.1", revision: "a".repeat(40), packageTarget: "android-universal" };
page.native.discoverNativeHealth.mockResolvedValue({ ...build, token: "local-secret" });
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.setBuild).toHaveBeenLastCalledWith(build);
expect(page.setBuild.mock.calls.flat()).not.toContainEqual(expect.objectContaining({ token: expect.anything() }));
page.cleanup();
});
it("uses fresh authorized health instead of offering approval again", async () => {
const page = mount();
page.native.discoverNativeHealth.mockResolvedValue({});
@@ -207,6 +220,27 @@ describe("App connection approval", () => {
expect(page.popup.closed).toBe(false);
});
it("rechecks the managed App on return without interrupting approval or retaining a disconnected build", async () => {
const page = mount(true, "ready");
await page.connect();
const build = { version: "v2.5.2", revision: "b".repeat(40), packageTarget: "windows-amd64" };
page.native.discoverNativeHealth.mockResolvedValue(build);
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.native.discoverNativeHealth).toHaveBeenLastCalledWith({ signal: expect.any(AbortSignal), waitForPermission: false });
expect(page.setBuild).toHaveBeenLastCalledWith(build);
expect(page.pending.current).not.toBeNull();
expect(page.onConnected).not.toHaveBeenCalled();
page.native.discoverNativeHealth.mockResolvedValue(null);
page.window.dispatchEvent(new Event("focus"));
await settle();
expect(page.setBuild).toHaveBeenLastCalledWith(undefined);
expect(page.setState).toHaveBeenLastCalledWith("idle");
expect(page.pending.current).toBeNull();
expect(page.window.open).not.toHaveBeenCalled();
page.cleanup();
});
it("offers recovery without activation or a stranded popup when no App is found", async () => {
const page = mount();
page.native.discoverNativeConnect.mockResolvedValue(null);
+5 -7
View File
@@ -45,17 +45,16 @@ function mount(fetch: ReturnType<typeof vi.fn>, manualSite = false) {
const state: Record<string, unknown> = {};
const setters = Object.fromEntries([
"Mode", "Modes", "LocalAccessPassword", "Lan", "Version", "ControlPort", "Target", "Starting", "Sites", "StartupSite",
"AppDebug", "Debug", "Error", "Loading", "Update", "RemoteControlPrototype",
"AppDebug", "Debug", "Error", "Loading", "Build", "RemoteControlPrototype",
"SiteBusy", "SiteError", "DebugBusy", "DebugError", "Reload",
].map(name => [`set${name}`, vi.fn((value: unknown) => {
state[name] = typeof value === "function" ? value(state[name]) : value;
})]));
const window = Object.assign(new EventTarget(), { location: { replace: vi.fn() } });
const checkReleaseUpdate = vi.fn(async () => null);
const timers = new Map<number, () => void>();
let nextTimer = 0;
const actions = runInNewContext(executable, {
...setters, z, fetch, window, checkReleaseUpdate,
...setters, z, fetch, window,
stateChanges: { current: { revision: 0, pending: 0 } },
siteBusy: false, debugBusy: false, starting: false, sites: saved.sites, manualSite, openOnApproval: false,
mode: "link", lang: "en", vis: false, debug: false, appDebug: false, localAccessPassword: "",
@@ -67,7 +66,7 @@ function mount(fetch: ReturnType<typeof vi.fn>, manualSite = false) {
},
clearTimeout: (id: number) => timers.delete(id),
}) as { cleanup(): void; changeSite(site: string, setting?: "site" | "startup-site", starAfterApproval?: boolean, allowed?: boolean): Promise<boolean>; approveSite(site: string): Promise<void>; enableDebug(): Promise<void>; launch(event: { preventDefault(): void }): Promise<void> };
return { state, setters, ...actions, checkReleaseUpdate, navigate: window.location.replace, focus: () => window.dispatchEvent(new Event("focus")),
return { state, setters, ...actions, navigate: window.location.replace, focus: () => window.dispatchEvent(new Event("focus")),
retry: () => {
expect(timers.size).toBe(1);
const [id, callback] = [...timers][0]!;
@@ -86,7 +85,7 @@ describe("App launcher state recovery", () => {
const page = mount(vi.fn(async () => response({ ...saved, version, revision })));
await settle();
expect(page.state.Version).toBe(label);
expect(page.checkReleaseUpdate).toHaveBeenCalledWith({ version, revision }, { packageTarget: undefined });
expect(page.state.Build).toEqual({ version, revision, packageTarget: undefined });
page.cleanup();
});
@@ -229,7 +228,7 @@ describe("App launcher state recovery", () => {
await settle();
expect(page.state).toMatchObject({ Mode: "link", LocalAccessPassword: "edited", Lan: { selected: "192.0.2.2" } });
expect(fetch).toHaveBeenCalledTimes(3);
expect(page.checkReleaseUpdate).toHaveBeenCalledOnce();
expect(page.state.Build).toMatchObject({ version: saved.version, revision: saved.revision });
page.cleanup();
});
@@ -258,7 +257,6 @@ describe("App launcher state recovery", () => {
page.focus();
expect(fetch).toHaveBeenCalledOnce();
expect(page.state).toEqual({});
expect(page.checkReleaseUpdate).not.toHaveBeenCalled();
for (const setter of Object.values(page.setters)) expect(setter).not.toHaveBeenCalled();
});
+14 -3
View File
@@ -34,11 +34,11 @@ function member(budget = 2_000_000, configureCarrier = async () => true) {
select, cancelSelection, push: vi.fn(), passthrough: vi.fn(() => { producerId = null; }), setPaused: vi.fn(),
snapshot: () => ({ frames: producerId ? 30 : 0, width: 1920, height: 1080, timestamp: Date.now(), lastProducerId: producerId }),
} as unknown as BrowserEncodingOutput;
const connection = { connectionState: "connected", getStats: async () => stats({ targetBitrate: demand.budget }, demand.codec) };
const connection = { connectionState: "connected", getStats: vi.fn(async () => stats({ targetBitrate: demand.budget }, demand.codec)) };
const fatal = vi.fn();
const handle = pool.create(source, {} as RTCRtpSender, connection as RTCPeerConnection, profile,
const handle = pool.create(source, {} as RTCRtpSender, connection as unknown as RTCPeerConnection, profile,
encoded, configureCarrier, async () => undefined, fatal)!;
return { demand, select, cancelSelection, fatal, handle, encoded, producerId: () => producerId };
return { demand, select, cancelSelection, fatal, handle, encoded, connection, producerId: () => producerId };
}
async function sample(count = 1) {
@@ -86,6 +86,17 @@ afterEach(() => {
});
describe("Browser encoding pool ownership", () => {
it("keeps sampling healthy members after retiring a pending connection stats wait", async () => {
const retired = member(), healthy = member();
retired.connection.getStats.mockReturnValueOnce(new Promise(() => {}));
await sample();
retired.handle.dispose();
await sample(4);
expect(healthy.producerId()).not.toBeNull();
expect(healthy.connection.getStats).toHaveBeenCalledTimes(5);
expect(healthy.fatal).not.toHaveBeenCalled();
});
it.each(["false", "rejected"])("isolates a connection's %s carrier attachment from its shared source", async (outcome) => {
const healthy = member();
let finish!: (applied: boolean) => void, reject!: (error: Error) => void;
+46
View File
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BrowserEncodingProducer } from "../src/client/media/browser-encoding-producer";
import { BrowserEncodingPool } from "../src/client/media/browser-encoding-pool";
import type { BrowserEncodingOutput } from "../src/client/media/browser-encoding-output";
import { applyVideoCaptureProfile, configureVideoSender, QUALITY_PROFILES } from "../src/client/media/quality";
import { cloneSenderVideoTrack } from "../src/client/media/sender-video-track";
@@ -231,6 +233,50 @@ describe("Browser encoding producer startup", () => {
expect(next.producer.track?.readyState).toBe("live");
});
it("releases a pending stats wait when retired without failing the producer", async () => {
const { producer, source, failed } = createProducer();
await producer.start();
Connection.instances[0].getStats.mockReturnValueOnce(new Promise(() => {}));
let outcome = "pending";
void producer.report().then(() => { outcome = "resolved"; }, error => { outcome = error.name; });
producer.dispose();
await vi.advanceTimersByTimeAsync(0);
expect(outcome).toBe("AbortError");
expect(failed).not.toHaveBeenCalled();
expect(source.stop).not.toHaveBeenCalled();
});
it("keeps the pool sampling after retiring a producer with pending stats", async () => {
vi.stubGlobal("RTCRtpSender", { getCapabilities: () => ({ codecs: [{ mimeType: "video/VP8", clockRate: 90_000 }] }) });
const pool = new BrowserEncodingPool();
const addMember = () => {
const source = Object.assign(new Track(), { kind: "video" });
const getStats = vi.fn(async () => new Map([
["video", { type: "outbound-rtp", kind: "video", codecId: "codec", targetBitrate: 2_000_000 }],
["codec", { type: "codec", mimeType: "video/VP8", clockRate: 90_000 }],
]) as unknown as RTCStatsReport);
const output = { snapshot: () => ({ frames: 0 }), select: vi.fn(), passthrough: vi.fn() } as unknown as BrowserEncodingOutput;
const fatal = vi.fn();
const handle = pool.create(source as unknown as MediaStreamTrack, { getStats } as unknown as RTCRtpSender,
{ connectionState: "connected", getStats } as unknown as RTCPeerConnection, QUALITY_PROFILES["1080p30"],
output, async () => true, async () => undefined, fatal)!;
return { handle, getStats, fatal };
};
try {
const retired = addMember(), healthy = addMember();
await vi.advanceTimersByTimeAsync(500);
Connection.instances[0].getStats.mockReturnValueOnce(new Promise(() => {}));
await vi.advanceTimersByTimeAsync(500);
expect(Connection.instances[0].getStats).toHaveBeenCalledOnce();
retired.handle.dispose();
await vi.advanceTimersByTimeAsync(500);
expect(healthy.getStats).toHaveBeenCalledTimes(3);
expect(healthy.fatal).not.toHaveBeenCalled();
expect(Connection.instances[0].close).toHaveBeenCalledOnce();
expect(Connection.instances[2].close).not.toHaveBeenCalled();
} finally { pool.dispose(); }
});
it("routes keyframe request failure through the producer owner, not the outgoing connection", async () => {
const { producer, source, failed } = createProducer();
await producer.start();
+38
View File
@@ -206,6 +206,28 @@ describe("SFU quality probe", () => {
expect(probe.observe(metrics(7_000), metrics(7_100))).toBe("pending");
});
it.each([P2pQualityProbe, SfuQualityProbe])(
"preserves clean delivery evidence across one-frame sampling boundaries",
(Probe) => {
const probe = new Probe();
const results = [20, 19, 20].map((frames, index) => probe.observe(
metrics(10_000 + index * 2_000, {
sampleWindowMs: 2002.045166015625, intervalFramesDecoded: 20,
}),
metrics(10_100 + index * 2_000, {
sampleWindowMs: 2002.046875, intervalFramesDecoded: frames,
}),
));
expect(results).toEqual(["pending", "pending", "approved"]);
probe.reset();
for (const timestamp of [20_000, 22_000, 24_000]) {
const result = probe.observe(metrics(timestamp, { intervalFramesDecoded: 20 }),
metrics(timestamp + 100, { intervalFramesDecoded: 18 }));
expect(result).toBe(timestamp === 24_000 ? "rejected" : "pending");
}
},
);
it("rejects after three comparable regressing P2P windows", () => {
const probe = new P2pQualityProbe();
const candidate = (timestampMs: number) =>
@@ -215,6 +237,22 @@ describe("SFU quality probe", () => {
expect(probe.observe(metrics(5_000), candidate(5_100))).toBe("rejected");
});
it.each([P2pQualityProbe, SfuQualityProbe])(
"does not accumulate a new frame allowance in every low-rate window",
(Probe) => {
const probe = new Probe();
for (const timestamp of [10_000, 12_000, 14_000, 16_000]) {
expect(probe.observe(metrics(timestamp, { intervalFramesDecoded: 2 }),
metrics(timestamp + 100, { intervalFramesDecoded: 1 }))).toBe("pending");
}
for (const timestamp of [18_000, 20_000, 22_000]) {
const result = probe.observe(metrics(timestamp, { intervalFramesDecoded: 2 }),
metrics(timestamp + 100, { intervalFramesDecoded: 2 }));
expect(result).toBe(timestamp === 22_000 ? "approved" : "pending");
}
},
);
it("keeps unknown evidence pending instead of counting it as rejection", () => {
const probe = new P2pQualityProbe();
expect(probe.observe(metrics(1_000), metrics(1_100))).toBe("pending");
+10 -1
View File
@@ -20,7 +20,7 @@ describe("progressive connection details", () => {
const samples = [
{ connectionId: "relay", metrics: { ...EMPTY_METRICS, bitrateKbps: 80, rttMs: 20, intervalPacketsReceived: 90, intervalPacketsLost: 10 } },
{ connectionId: "relay", metrics: { ...EMPTY_METRICS, bitrateKbps: 60, rttMs: 20, intervalPacketsReceived: 990, intervalPacketsLost: 10 } },
{ connectionId: "direct", metrics: { ...EMPTY_METRICS, bitrateKbps: 70, rttMs: 60 } },
{ connectionId: "direct", metrics: { ...EMPTY_METRICS, bitrateKbps: 70, rttMs: 60, intervalPacketsReceived: 0, intervalPacketsLost: 0 } },
];
expect(summarizeConnectionMetrics(samples, "receive")).toMatchObject({ bitrateKbps: 210, rttMs: 40, packetLossPercent: 100 * 20 / 1100 });
});
@@ -33,4 +33,13 @@ describe("progressive connection details", () => {
expect(html.match(/class="lr-media-detail lr-connection-summary"/g)).toHaveLength(4);
expect(renderToStaticMarkup(createElement(ConnectionDetails, { rows: [] }))).toBe("");
});
it("keeps mixed receive loss unknown when a Native report has no window counts", () => {
const browser = { connectionId: "browser", metrics: { ...EMPTY_METRICS,
packetLossPercent: 0, intervalPacketsReceived: 100, intervalPacketsLost: 0 } };
const native = { connectionId: "native", metrics: { ...EMPTY_METRICS, packetLossPercent: 50 } };
expect(summarizeConnectionMetrics([browser, native], "receive").packetLossPercent).toBeNull();
expect(summarizeConnectionMetrics([native], "receive").packetLossPercent).toBe(50);
expect(summarizeConnectionMetrics([browser, native], "send").packetLossPercent).toBe(25);
});
});
+83
View File
@@ -5,6 +5,7 @@ import {
type QualityProfile,
} from "../src/client/media/quality.ts";
import { HostProvisionalChild } from "../src/client/media/host-provisional-child.ts";
import { ViewerSfuRoute } from "../src/client/media/viewer-sfu-route.ts";
import { senderQualityEvidenceFromSnapshot } from "../src/client/media/sender-quality-evidence.ts";
import { EMPTY_METRICS, type PeerSnapshot } from "../src/client/types.ts";
import { HostPeer, RENEGOTIATION_ANSWER_TIMEOUT_MS, type HostMediaPeer } from "../src/client/webrtc/host-peer.ts";
@@ -2560,6 +2561,53 @@ describe("ViewerRelay downstream ownership", () => {
qualityProbe: false,
});
it("admits a relay replacement after retirement while upstream activation is awaiting SDP", async () => {
const relay = new ViewerRelay({ iceServers: [] }, QUALITY_PROFILES["720p30"], {
sendSignal: () => true,
});
relay.setStream(createStream(createTrack("video", "standing-source"), null));
let finishActivation!: () => void;
const upstreamSdp = new Promise<void>((resolve) => { finishActivation = resolve; });
let waitForSdp = false;
const activating = vi.fn();
const admissions: boolean[] = [];
const children = vi.fn((ids: readonly string[], revision: number) => relay.activateChildren(revision, ids));
const route = new ViewerSfuRoute("parent-viewer", {
activatePeer: () => {
if (waitForSdp) { activating(); return upstreamSdp; }
},
activateChildren: children,
prepareChild: (candidate, planned, revision) => {
if (candidate && planned && revision !== undefined) admissions.push(relay.prepareChild(revision, candidate, planned));
else relay.discardPreparedChild();
},
onSfuStream: () => undefined,
send: () => true,
});
const assignment = (childPeerIds: string[]): ParticipantRouteAssignment => ({
upstream: { kind: "peer", peerId: "upstream" }, childPeerIds, sfuPublicationGeneration: null,
});
try {
route.accept({ revision: 1, phase: "active", assignment: assignment(["retired-child"]) });
await vi.waitFor(() => expect(children).toHaveBeenCalledWith(["retired-child"], 1));
waitForSdp = true;
route.accept({ revision: 2, phase: "active", assignment: assignment([]) });
await vi.waitFor(() => expect(activating).toHaveBeenCalledOnce());
route.accept({ revision: 3, phase: "prepare", assignment: assignment(["replacement-child"]),
candidate: routeCandidate(3, "replacement-child") });
expect(admissions).toEqual([true]);
finishActivation();
await upstreamSdp;
await vi.waitFor(() => expect(relay.getSignalRouteRevision(
"replacement-child", routeCandidate(3, "replacement-child").connectionId, 2,
)).toBe(3));
} finally {
finishActivation();
await route.disconnect();
relay.dispose();
}
});
it("prepares against the current source and codec after an in-flight probe is replaced", async () => {
let finishOld!: (codec: "vp8") => void;
let finishCurrent!: (codec: "h264") => void;
@@ -3033,6 +3081,41 @@ describe("ViewerRelay downstream ownership", () => {
relay.dispose();
});
it("keeps a prepared child when a superseded stream replacement fails", async () => {
const onPreparedChildFailed = vi.fn();
const signals: Array<{ connectionId: string }> = [];
const relay = new ViewerRelay(
{ iceServers: [] },
QUALITY_PROFILES["720p30"],
{ sendSignal: (_peerId, payload) => { signals.push(payload); return true; }, onPreparedChildFailed },
);
let finish!: () => void;
const paused = new Promise<void>(resolve => { finish = resolve; });
try {
relay.setStream(createStream(createTrack("video", "initial-video"), null));
expect(relay.prepareChild(7, routeCandidate(7, "prepared-child"), ["prepared-child"])).toBe(true);
await vi.waitFor(() => expect(signals).toHaveLength(1));
const prepared = FakePeerConnection.latest!;
const sender = prepared.senders[0]!;
const replace = vi.spyOn(sender, "replaceTrack").mockImplementationOnce(async () => {
await paused;
throw new Error("superseded stream was rejected");
});
relay.setStream(createStream(createTrack("video", "superseded-video"), null));
await vi.waitFor(() => expect(replace).toHaveBeenCalledOnce());
const finalVideo = createTrack("video", "current-video");
relay.setStream(createStream(finalVideo, null));
finish();
await vi.waitFor(() => expect(sender.track?.id).toBe(finalVideo.id));
expect(onPreparedChildFailed).not.toHaveBeenCalled();
expect(prepared.connectionState).not.toBe("closed");
expect(FakePeerConnection.instances).toHaveLength(1);
prepared.connectionState = "connected";
relay.activateChildren(7, ["prepared-child"]);
expect(relay.getSnapshot("prepared-child")?.connectionId).toBe(signals[0]!.connectionId);
} finally { finish(); relay.dispose(); }
});
it("syncs same-stream audio changes into the prepared connection", async () => {
const relay = new ViewerRelay(
{ iceServers: [] },
+61 -5
View File
@@ -138,9 +138,12 @@ describe("native App private wire", () => {
await expect(discoverNativeConnect()).resolves.toBeNull();
});
it("cancels the whole approval scan with its caller", async () => {
it.each([false, true])("cancels the whole approval scan with its caller (permission prompt: %s)", async prompting => {
vi.spyOn(AbortSignal, "any").mockImplementation(() => { throw new TypeError("AbortSignal.any is not a function"); });
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
if (prompting) vi.stubGlobal("navigator", { permissions: {
query: vi.fn().mockResolvedValue(Object.assign(new EventTarget(), { state: "prompt" })),
} });
const signals: AbortSignal[] = [];
vi.stubGlobal("fetch", vi.fn((_url: string, init: RequestInit) => new Promise((_resolve, reject) => {
const signal = init.signal!;
@@ -149,6 +152,7 @@ describe("native App private wire", () => {
})));
const controller = new AbortController();
const result = discoverNativeConnect(controller.signal);
await vi.waitFor(() => expect(signals).toHaveLength(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1));
controller.abort();
await expect(result).resolves.toBeNull();
expect(signals).toHaveLength(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1);
@@ -277,11 +281,11 @@ describe("native App private wire", () => {
it("still lets explicit source discovery ask for local permission", async () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: { hostname: "piik.example" } });
const query = vi.fn().mockResolvedValue({ state: "prompt" });
const query = vi.fn().mockResolvedValue(Object.assign(new EventTarget(), { state: "prompt" }));
vi.stubGlobal("navigator", { permissions: { query } });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(health))));
await expect(discoverNativeHealth()).resolves.toMatchObject({ port: health.port });
expect(query).not.toHaveBeenCalled();
expect(query).toHaveBeenCalledOnce();
});
it.each(["localhost", "127.0.0.1", "[::1]"])("keeps App Local reception on %s available without cross-address-space consent", async (hostname) => {
@@ -371,6 +375,35 @@ describe("native App private wire", () => {
expect(vi.getTimerCount()).toBe(0);
});
it("does not spend the discovery deadline while the user decides local permission", async () => {
vi.useFakeTimers();
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
const permission = Object.assign(new EventTarget(), { state: "prompt" as PermissionState });
const query = vi.fn().mockResolvedValue(permission);
const remove = vi.spyOn(permission, "removeEventListener");
vi.stubGlobal("navigator", { permissions: { query } });
let respond!: (response: Response) => void;
vi.stubGlobal("fetch", vi.fn((url: string, options: RequestInit) => {
if (Number(new URL(url).port) !== health.port) return Promise.reject(new TypeError("No listener"));
return new Promise<Response>((resolve, reject) => {
respond = resolve;
options.signal!.addEventListener("abort", () => reject(options.signal!.reason), { once: true });
});
}));
const settled = vi.fn();
const discovery = discoverNativeHealth().then(settled);
await vi.advanceTimersByTimeAsync(12_000);
expect(settled).not.toHaveBeenCalled();
permission.state = "granted";
permission.dispatchEvent(new Event("change"));
respond(Response.json(health));
await discovery;
expect(settled).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ port: health.port }));
expect(query).toHaveBeenCalledOnce();
expect(remove).toHaveBeenCalledWith("change", expect.any(Function));
expect(vi.getTimerCount()).toBe(0);
});
it("finds a later App without waiting for a silent port and aborts the unused probe", async () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
let silentSignal: AbortSignal | undefined;
@@ -389,18 +422,27 @@ describe("native App private wire", () => {
expect(silentSignal?.aborted).toBe(true);
});
it("bounds all silent discovery ports with one deadline", async () => {
it.each(["unsupported", "grant", "response"])("bounds silent discovery ports with one network deadline after %s", async mode => {
vi.useFakeTimers();
vi.spyOn(AbortSignal, "any").mockImplementation(() => { throw new TypeError("AbortSignal.any is not a function"); });
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
const permission = Object.assign(new EventTarget(), { state: "prompt" as PermissionState });
if (mode !== "unsupported") vi.stubGlobal("navigator", { permissions: { query: vi.fn().mockResolvedValue(permission) } });
const signals: AbortSignal[] = [];
vi.stubGlobal("fetch", vi.fn(async (_url: string, options: RequestInit) => {
vi.stubGlobal("fetch", vi.fn(async (url: string, options: RequestInit) => {
signals.push(options.signal!);
if (mode === "response" && Number(new URL(url).port) === health.port) return new Response(null, { status: 403 });
return new Promise<Response>((_resolve, reject) => {
options.signal!.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
});
}));
const discovery = discoverNativeHealth({ signal: new AbortController().signal });
if (mode === "grant") {
await vi.advanceTimersByTimeAsync(12_000);
expect(signals.every(signal => !signal.aborted)).toBe(true);
permission.state = "granted";
permission.dispatchEvent(new Event("change"));
}
await vi.advanceTimersByTimeAsync(8_000);
await expect(discovery).resolves.toBeNull();
expect(signals).toHaveLength(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1);
@@ -408,6 +450,20 @@ describe("native App private wire", () => {
expect(vi.getTimerCount()).toBe(0);
});
it("does not wait for a permission decision when every discovery port rejects", async () => {
vi.useFakeTimers();
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
const permission = Object.assign(new EventTarget(), { state: "prompt" });
const remove = vi.spyOn(permission, "removeEventListener");
vi.stubGlobal("navigator", { permissions: { query: vi.fn().mockResolvedValue(permission) } });
const fetcher = vi.fn().mockRejectedValue(new TypeError("No listener"));
vi.stubGlobal("fetch", fetcher);
await expect(discoverNativeHealth()).resolves.toBeNull();
expect(fetcher).toHaveBeenCalledTimes(NATIVE_CLIENT_PORT_END - NATIVE_CLIENT_PORT_START + 1);
expect(remove).toHaveBeenCalledWith("change", expect.any(Function));
expect(vi.getTimerCount()).toBe(0);
});
it("identifies an incompatible App even when that protocol uses different token or media metadata", async () => {
vi.stubGlobal("window", { setTimeout, clearTimeout, location: new URL("https://piik.example/") });
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
+16 -30
View File
@@ -49,31 +49,17 @@ describe("App release update notice", () => {
.toBe(current.browser_download_url);
});
it("selects the GitHub Android APK and the mirror ZIP with installation guidance", async () => {
it("selects the Android APK from either release provider", () => {
const name = "piik-app-android-universal.apk";
const asset = { name, size: 1024, state: "uploaded",
browser_download_url: `https://github.com/TNTcraftHIM/Piik/releases/download/${release.tag_name}/${name}` };
const zipName = name.replace(".apk", ".zip");
const zip = { ...asset, name: zipName, browser_download_url: asset.browser_download_url.replace(".apk", ".zip") };
const primary = parseReleaseMetadata({ ...release, assets: [zip, asset] }, "android-universal");
expect(primary?.url).toBe(asset.browser_download_url);
expect(primary?.extractAPK).toBeUndefined();
const mirrorAsset = { name: zipName,
browser_download_url: `https://gitee.com/TNTcraftHIM/Piik/releases/download/${release.tag_name}/${zipName}` };
const mirror = { tag_name: release.tag_name, prerelease: false,
body: `<!-- piik-source: ${latestRevision} -->`, assets: [mirrorAsset] };
const fetchImpl = vi.fn<typeof fetch>(async input => String(input) === DEFAULT_RELEASE_API_URL
? new Response(null, { status: 503 }) : Response.json([mirror]));
await expect(checkReleaseUpdate({ version: "v1.1.0", revision: currentRevision },
{ fetchImpl, packageTarget: "android-universal" })).resolves.toMatchObject({
url: mirrorAsset.browser_download_url, extractAPK: true,
});
for (const assets of [[], [{ ...mirrorAsset, name }], [mirrorAsset, mirrorAsset],
[{ ...mirrorAsset, browser_download_url: mirrorAsset.browser_download_url.replace("gitee.com", "evil.example") }]]) {
const legacy = parseMirrorReleaseMetadata({ ...mirror, assets }, "android-universal");
expect(legacy?.url).toBe(`https://gitee.com/TNTcraftHIM/Piik/releases/tag/${release.tag_name}`);
expect(legacy?.extractAPK).toBeUndefined();
}
expect(parseReleaseMetadata({ ...release, assets: [asset] }, "android-universal")?.url)
.toBe(asset.browser_download_url);
const mirrorAsset = { name, type: "attach",
browser_download_url: `https://atomgit.com/TNTcraftHIM/Piik/releases/download/${release.tag_name}/${name}` };
expect(parseMirrorReleaseMetadata({ tag_name: release.tag_name, prerelease: false,
body: `<!-- piik-source: ${latestRevision} -->`, assets: [mirrorAsset] }, "android-universal")?.url)
.toBe(mirrorAsset.browser_download_url);
});
it("keeps the release page when a matching safe ZIP is missing, without trying another provider", async () => {
@@ -94,21 +80,21 @@ describe("App release update notice", () => {
it.each(["windows-amd64", "darwin-arm64", "darwin-amd64", "linux-amd64", "linux-arm64"])("uses a listed mirror %s ZIP only after the existing primary check fails", async (packageTarget) => {
const name = `piik-app-${packageTarget}.zip`;
const mirrorAsset = { name,
browser_download_url: `https://gitee.com/TNTcraftHIM/Piik/releases/download/${release.tag_name}/${name}` };
const mirrorAsset = { name, type: "attach",
browser_download_url: `https://atomgit.com/TNTcraftHIM/Piik/releases/download/${release.tag_name}/${name}` };
const mirrored = { tag_name: release.tag_name, prerelease: false,
body: `<!-- piik-source: ${latestRevision} -->`, assets: [mirrorAsset] };
const fetchImpl = vi.fn<typeof fetch>(async (input) => String(input) === DEFAULT_RELEASE_API_URL
? new Response(null, { status: 503 }) : Response.json([mirrored]));
await expect(checkReleaseUpdate({ version: "v1.1.0", revision: currentRevision },
{ fetchImpl, packageTarget })).resolves.toMatchObject({ url: mirrorAsset.browser_download_url,
releaseURL: `https://gitee.com/TNTcraftHIM/Piik/releases/tag/${release.tag_name}` });
releaseURL: `https://atomgit.com/TNTcraftHIM/Piik/releases` });
expect(fetchImpl).toHaveBeenCalledTimes(2);
for (const assets of [[], [mirrorAsset, mirrorAsset],
[{ ...mirrorAsset, browser_download_url: mirrorAsset.browser_download_url.replace("gitee.com", "evil.example") }],
for (const assets of [[], [mirrorAsset, mirrorAsset], [{ ...mirrorAsset, type: "source" }],
[{ ...mirrorAsset, browser_download_url: mirrorAsset.browser_download_url.replace("atomgit.com", "evil.example") }],
[{ ...mirrorAsset, browser_download_url: mirrorAsset.browser_download_url.replace("v1.2.0", "v1.1.0") }],
]) expect(parseMirrorReleaseMetadata({ ...mirrored, assets }, packageTarget)?.url)
.toBe(`https://gitee.com/TNTcraftHIM/Piik/releases/tag/${release.tag_name}`);
.toBe(`https://atomgit.com/TNTcraftHIM/Piik/releases`);
});
it("checks a release without sending installed identity or credentials", async () => {
@@ -183,8 +169,8 @@ describe("App release update notice", () => {
const current = { version: "v1.9.0", revision: currentRevision };
await expect(checkReleaseUpdate(current, { fetchImpl })).resolves.toEqual({
kind: "update-available", version: "v1.10.0", revision: latestRevision,
url: "https://gitee.com/TNTcraftHIM/Piik/releases/tag/v1.10.0",
releaseURL: "https://gitee.com/TNTcraftHIM/Piik/releases/tag/v1.10.0",
url: "https://atomgit.com/TNTcraftHIM/Piik/releases",
releaseURL: "https://atomgit.com/TNTcraftHIM/Piik/releases",
});
await expect(checkReleaseUpdate({ ...current, version: "v2.0.0" }, { fetchImpl })).resolves.toBeNull();
});
+64
View File
@@ -73,6 +73,70 @@ class Peer {
afterEach(() => { vi.unstubAllGlobals(); Peer.instances = []; });
it.each(["levels", "metrics"])("finishes %s for healthy voice peers when a pending observer's connection retires", async observation => {
class AudioElement extends EventTarget {
volume = 1; muted = false; paused = true; ended = false;
srcObject: unknown = null;
play = async () => { this.paused = false; };
pause = () => { this.paused = true; };
remove = () => {};
}
vi.stubGlobal("Audio", AudioElement);
vi.stubGlobal("document", { body: { append: () => {} } });
vi.stubGlobal("MediaStream", class {
constructor(private tracks: MediaStreamTrack[]) {}
getAudioTracks() { return this.tracks; }
});
const tracks = ["retired", "healthy"].map(id => ({ id, kind: "audio", readyState: "live" }));
const report = (index: number, audioLevel: number) => new Map([["audio", {
id: "audio", type: "inbound-rtp", kind: "audio", ssrc: index + 1, timestamp: 1000,
trackIdentifier: tracks[index]!.id, audioLevel, bytesReceived: 100,
}]]) as unknown as RTCStatsReport;
let finishStats!: (report: RTCStatsReport) => void;
const delayed = new Promise<RTCStatsReport>(resolve => { finishStats = resolve; });
const healthyStats = vi.fn(async () => report(1, .25));
vi.stubGlobal("RTCPeerConnection", class extends Peer {
getStats = vi.fn((): Promise<RTCStatsReport> => this === Peer.instances[0] ? delayed : healthyStats());
getTransceivers = (): unknown[] => [{ mid: "0", direction: "recvonly",
receiver: { track: tracks[this === Peer.instances[0] ? 0 : 1] }, sender: { track: null } }];
});
const endpoint = new BrowserVoiceEndpoint({ iceServers: [] }, () => true, () => {});
const state = (ids: string[], revision: number): RoomVoiceState => ({
type: "room-voice-state", revision, enabled: true, hostPeerId: "host", unavailable: [],
members: [{ peerId: "self", connected: true, joined: true, upstream: { kind: "sfu" } }],
publications: ids.map(id => ({ id, peerId: id })),
connections: ids.map(id => ({ connectionId: id, childPeerId: "self", transport: "sfu", revision,
pending: false, send: [], receive: [id] })),
});
const observe = () => observation === "levels" ? endpoint.levels() : endpoint.connectionMetrics();
const expectHealthy = (sample: Awaited<ReturnType<typeof observe>>) => {
if (observation === "levels") expect([...sample]).toEqual([["healthy", .25]]);
else expect(sample).toEqual([expect.objectContaining({ connectionId: "healthy", peerId: "healthy", direction: "receive" })]);
};
try {
endpoint.setAuthority(state(["retired", "healthy"], 1), "self");
await endpoint.reconcile();
for (const id of ["retired", "healthy"]) await endpoint.receive({
type: "room-voice-signal", connectionId: id, description: {
revision: 1, sdp: { type: "offer", sdp: "offer" }, tracks: [{ mid: "0", publicationId: id }],
},
});
const pending = observe();
endpoint.setAuthority(state(["healthy"], 2), "self");
// Retirement completes this observation without waiting for the old stats.
const sample = await pending;
expectHealthy(sample);
expect(Peer.instances[0]!.close).toHaveBeenCalledOnce();
expect(Peer.instances[1]!.close).not.toHaveBeenCalled();
finishStats(report(0, .9));
expectHealthy(await observe());
expectHealthy(sample);
healthyStats.mockRejectedValueOnce(new Error("stats unavailable"));
await expect(observe()).rejects.toThrow("stats unavailable");
expectHealthy(await observe());
} finally { finishStats(report(0, .9)); endpoint.close(); }
});
it.each(["levels", "metrics"].flatMap(observation => [false, true].map(replaced => ({ observation, replaced }))))(
"keeps in-flight $observation tied to its receiver publication (replaced=$replaced)", async ({ observation, replaced }) => {
class AudioElement extends EventTarget {
+172 -14
View File
@@ -210,6 +210,8 @@ describe("minimal route transition contracts", () => {
await vi.waitFor(() => expect(subscriber.disconnect).toHaveBeenCalledOnce());
expect(activatePeer).toHaveBeenCalledWith(replacement, 3);
} else {
route.accept({ revision: 3, phase: "prepare", assignment: peerAssignment("candidate_parent", ["next_child"]),
candidate: candidate(3, "next_child") });
status = outcome;
expect(route.retryPeerActivation(candidate(2).connectionId)).toBe(true);
if (outcome === "connected") await vi.waitFor(() => expect(subscriber.disconnect).toHaveBeenCalledOnce());
@@ -349,6 +351,81 @@ describe("minimal route transition contracts", () => {
});
});
it.each(["prepare", "active"] as const)("promotes a committed upstream behind SDP while preserving the next child %s", async (phase) => {
let finishSdp!: () => void;
const sdp = new Promise<void>((resolve) => { finishSdp = resolve; });
const activatePeer = vi.fn((_assignment: ParticipantRouteAssignment, revision?: number) =>
revision === undefined ? sdp : true);
const preparePeer = vi.fn();
const prepareChild = vi.fn();
const route = new ViewerSfuRoute("viewer_12345678", {
activatePeer, preparePeer, prepareChild,
onSfuStream: () => undefined,
send: () => true,
});
const committed = peerAssignment("next_parent");
const withChild = peerAssignment("next_parent", ["next_child"]);
const nextChild = candidate(3, "next_child");
try {
route.accept({ revision: 1, phase: "active", assignment: peerAssignment("old_parent") });
await vi.waitFor(() => expect(activatePeer).toHaveBeenCalledOnce());
route.accept({ revision: 2, phase: "prepare", assignment: committed, candidate: candidate(2) });
// Active is the server's acceptance of this prepared input's readiness.
route.accept({ revision: 2, phase: "active", assignment: committed });
const preparations = preparePeer.mock.calls.length;
route.accept({ revision: 3, phase: "prepare", assignment: withChild, candidate: nextChild });
if (phase === "active") route.accept({ revision: 3, phase, assignment: withChild });
expect.soft(preparePeer.mock.calls.slice(preparations)).not.toContainEqual([null]);
finishSdp();
await vi.waitFor(() => expect(activatePeer).toHaveBeenCalledWith(phase === "active" ? withChild : committed, 2));
expect(prepareChild).toHaveBeenLastCalledWith(nextChild, ["next_child"], 3);
} finally {
finishSdp();
await route.disconnect();
}
});
it.each(["promote", "fail"] as const)("keeps committed SFU input behind SDP during a child operation, then %s", async outcome => {
let finishSdp!: () => void;
const sdp = new Promise<void>(resolve => { finishSdp = resolve; });
const onSfuStream = vi.fn();
const messages: ClientMessage[] = [];
let subscriber!: ReturnType<typeof createFakeSubscriber>;
const route = new ViewerSfuRoute("viewer_12345678", {
activatePeer: () => sdp, onSfuStream,
send: message => { messages.push(message); return true; },
createSubscriber: events => (subscriber = createFakeSubscriber(events, [], "committed")),
});
const stream = {} as MediaStream;
const assignment = viewerSfuAssignment(["next_child"]);
try {
route.accept({ revision: 1, phase: "active", assignment: peerAssignment("old_parent") });
// Let the preceding active transition enter its pending SDP operation.
await Promise.resolve();
route.accept({ revision: 2, phase: "prepare", assignment: viewerSfuAssignment(),
candidate: candidate(2, "viewer_12345678", "sfu") });
await route.acceptConfig(sfuConfig(2));
subscriber.events.onStream(stream);
subscriber.events.onFirstDecodedFrame();
expect(messages).toContainEqual({ type: "route-ready", revision: 2, phase: "prepare" });
route.accept({ revision: 2, phase: "active", assignment: viewerSfuAssignment() });
route.accept({ revision: 3, phase: "prepare", assignment, candidate: candidate(3, "next_child") });
route.accept({ revision: 3, phase: "active", assignment });
expect(subscriber.disconnect).not.toHaveBeenCalled();
if (outcome === "fail") subscriber.events.onDisconnected();
finishSdp();
if (outcome === "promote") {
await vi.waitFor(() => expect(onSfuStream).toHaveBeenCalledWith(stream, assignment, true, 3));
} else {
expect(messages).toContainEqual({ type: "route-failed", revision: 3, phase: "active", connectionId: sfuConfig(2).connectionId });
expect(onSfuStream).not.toHaveBeenCalled();
}
} finally {
finishSdp();
await route.disconnect();
}
});
it("keeps old media through prepare and commits only exact active authority", () => {
const route = new MediaRouteTransition();
const oldAssignment = peerAssignment("old-parent");
@@ -366,6 +443,7 @@ describe("minimal route transition contracts", () => {
});
expect(route.getMediaAssignment()).toEqual(oldAssignment);
expect(route.markMediaActive(route.token()!)).toBe(false);
expect(route.ownsActive(oldToken)).toBe(true);
route.accept({ revision: 2, phase: "active", assignment: nextAssignment });
expect(route.markMediaActive(route.token()!)).toBe(true);
@@ -373,6 +451,10 @@ describe("minimal route transition contracts", () => {
expect(
route.accept({ revision: 1, phase: "active", assignment: oldAssignment }),
).toBe("stale");
const committed = route.getActiveToken()!;
route.reset();
route.accept({ revision: 2, phase: "active", assignment: nextAssignment });
expect(route.ownsActive(committed)).toBe(false);
});
it("treats child assignment order as presentation-only", () => {
@@ -691,7 +773,7 @@ describe("minimal route transition contracts", () => {
getStream: () => ({}) as MediaStream,
getProfile: () => QUALITY_PROFILES["720p30"],
getVideoCodec: () => "vp8",
reconcileChildren: (children) => reconciledChildren.push(children),
reconcileChildren: (assignment) => reconciledChildren.push(assignment.childPeerIds),
send: () => true,
createPublisher: () => createFakePublisher([], "publisher"),
});
@@ -969,7 +1051,7 @@ describe("minimal route transition contracts", () => {
getStream: () => ({}) as MediaStream,
getProfile: () => QUALITY_PROFILES["720p30"],
getVideoCodec: () => "vp8",
reconcileChildren: (children) => reconciledChildren.push(children),
reconcileChildren: (assignment) => reconciledChildren.push(assignment.childPeerIds),
send: () => true,
createPublisher: () => {
const publisher = createFakePublisher(
@@ -1466,14 +1548,15 @@ describe("minimal route transition contracts", () => {
await route.disconnect();
});
it("rejects a quality SFU candidate after three comparable regressions", async () => {
it("keeps a low-quality SFU candidate until recovery proves non-regression", async () => {
const messages: ClientMessage[] = [];
const subscribers: ReturnType<typeof createFakeSubscriber>[] = [];
let currentMetrics = receiveMetrics(1_000);
const onSfuStream = vi.fn();
const route = new ViewerSfuRoute("viewer_12345678", {
activatePeer: () => true,
reconcileSfuChildren: () => undefined,
onSfuStream: () => undefined,
onSfuStream,
currentPeerMetrics: () => currentMetrics,
qualityProbeEligible: () => true,
send: (message) => {
@@ -1519,16 +1602,21 @@ describe("minimal route transition contracts", () => {
);
}
expect(messages.at(-1)).toEqual({
type: "route-failed",
revision: 2,
phase: "prepare",
connectionId: null,
});
expect(subscriber.disconnect).toHaveBeenCalledOnce();
expect(
messages.filter((message) => message.type === "route-ready"),
).toEqual([]);
expect(messages.filter(message => message.type === "route-failed" || message.type === "route-ready")).toEqual([]);
expect(subscriber.disconnect).not.toHaveBeenCalled();
expect(onSfuStream).not.toHaveBeenCalled();
for (const timestampMs of [7_100, 9_100, 11_100]) {
currentMetrics = receiveMetrics(timestampMs - 100);
subscriber.events.onStats(receiveMetrics(timestampMs));
}
expect(messages.filter(message => message.type === "route-failed")).toEqual([]);
expect(messages.filter(message => message.type === "route-ready")).toEqual([
{ type: "route-ready", revision: 2, phase: "prepare" },
]);
expect(subscriber.disconnect).not.toHaveBeenCalled();
expect(onSfuStream).not.toHaveBeenCalled();
await route.disconnect();
});
it("reconnects only the active SFU subscriber on the current route", async () => {
@@ -1960,4 +2048,74 @@ describe("minimal route transition contracts", () => {
peerAssignment("retained-parent", ["retained-child"]),
);
});
it("preserves a committed Host publication while old source retirement delays activation", async () => {
const publishers: ReturnType<typeof createFakePublisher>[] = [];
const reconciledChildren: Array<{ childPeerIds: string[]; revision: number }> = [];
const stream = {} as MediaStream;
const route = new HostSfuRoute({
getStream: () => stream,
getProfile: () => QUALITY_PROFILES["720p30"],
getVideoCodec: () => "h264",
reconcileChildren: (assignment, revision) => {
reconciledChildren.push({ childPeerIds: assignment.childPeerIds, revision });
},
send: () => true,
createPublisher: () => {
const publisher = createFakePublisher([], "publisher-" + publishers.length);
publishers.push(publisher);
return publisher;
},
});
await route.acceptAndWait({
revision: 1,
phase: "active",
assignment: hostAssignment("publication-old"),
});
await route.acceptConfig(sfuConfig(1, "publication-old"));
route.accept({
revision: 2,
phase: "prepare",
assignment: hostAssignment("publication-new", ["committed-child"]),
candidate: candidate(2, "viewer_first_12345678", "sfu"),
});
await route.acceptConfig(sfuConfig(2, "publication-new"));
expect(publishers[1]!.activate).toHaveBeenCalledOnce();
let releaseOld!: () => void;
const oldRetirement = new Promise<void>((resolve) => {
releaseOld = resolve;
});
publishers[0]!.replaceStream.mockResolvedValue(false);
publishers[0]!.disconnect.mockImplementation(() => oldRetirement);
const replacing = route.replaceStream({} as MediaStream);
const nextChild = {
revision: 3,
phase: "prepare" as const,
assignment: hostAssignment("publication-new", ["committed-child", "viewer_next_12345678"]),
candidate: candidate(3, "viewer_next_12345678", "direct"),
};
try {
await vi.waitFor(() => expect(publishers[0]!.disconnect).toHaveBeenCalledOnce());
// HostPage accepts route updates without awaiting local activation.
route.accept({
revision: 2,
phase: "active",
assignment: hostAssignment("publication-new", ["committed-child"]),
});
expect(reconciledChildren.at(-1)).toEqual({
childPeerIds: ["committed-child"],
revision: 2,
});
route.accept(nextChild);
expect(publishers[1]!.disconnect).not.toHaveBeenCalled();
releaseOld();
await replacing;
await route.acceptAndWait(nextChild);
expect(publishers[1]!.disconnect).not.toHaveBeenCalled();
} finally {
releaseOld();
await replacing;
await route.disconnect();
}
});
});
+29
View File
@@ -23,6 +23,35 @@ function applyFrom(
}
describe("Viewer presentation reducer", () => {
it("keeps route exhaustion across unrelated unassigned broadcasts until a new preparation", () => {
let state = apply(
{ type: "access", access: "ready" },
{ type: "signal", signal: "connected" },
{ type: "host", host: "online" },
{ type: "route", revision: 154, phase: "prepare", kind: "p2p" },
{ type: "route", revision: 155, phase: "active", kind: "none" },
{ type: "route-status", revision: 155, state: "failed" },
);
for (const revision of [157, 159, 161, 163, 165, 167]) {
state = reduceViewerPresentation(state, {
type: "route", revision, phase: "active", kind: "none",
});
expect(state.revision).toBe(revision);
expect(deriveViewerPresentation(state)).toMatchObject({
stage: "route-failed", failureCode: "ROUTE_EXHAUSTED",
});
}
const preparing = applyFrom(state,
{ type: "route", revision: 172, phase: "prepare", kind: "p2p" });
expect(deriveViewerPresentation(preparing).stage).toBe("preparing-p2p");
expect(preparing.routeStatus).toBeNull();
const playing = applyFrom(preparing,
{ type: "route", revision: 172, phase: "active", kind: "p2p" },
{ type: "media-bound", generation: 1, revision: 172 },
{ type: "frame-presented", generation: 1, proofEpoch: 0, revision: 172 });
expect(deriveViewerPresentation(playing).stage).toBe("playing");
});
it("retains receiving rejection through route exhaustion but not fresh negotiation or stop", () => {
const failed = apply(
{ type: "access", access: "ready" }, { type: "host", host: "online" },