Files
piik/src/client/sfu/subscriber.ts
T
TNTcraft e25bd00950 feat(maintenance): improve invitations and playback controls
## Problem and outcome / 问题与结果

Inviting another device, changing sources and adjusting playback should preserve the selected access and accepted settings. This update adds local QR invitations, optional translations and a video buffer setting, and repairs App discovery, source retirement, shared controls, remote-input geometry and audio reporting within the existing 2.x contracts.

## Release notes

### English

This update makes invitations easier to share and playback easier to adjust, while improving App connection, source switching and everyday controls. It also adds optional interface translations and more useful audio diagnostics.

- Show the current invitation as a locally generated QR code for another device to scan, preserving the selected access information.
- Add optional Traditional Chinese, Japanese and Korean translations. Chinese and English remain direct choices; the third menu includes extra languages and visual mode. Missing translations use English.
- Add an **Increase playback buffering** switch with an adjustable target. More buffering may reduce stalls from uneven packet arrival, at the cost of added viewing delay. Automatic remains the default.
- Ignore remote-control clicks on blank space outside a zoomed or rotated video.
- Check for a local Piik App once when a site opens. Automatic discovery respects local-network permission; explicit connection keeps approval under your control, and passive failures stay quiet.
- Keep a pending Browser screen or camera selection when the previous Native source ends or the App disconnects. Release the old source while allowing the new selection to finish; cancellation and Stop still end the operation correctly.
- Improve App-to-App connections when port mappings shift during setup.
- Keep playback hints clear of sharing controls, selection indicators inside their tracks, disabled action icons visible, and numeric settings aligned with accepted values.
- Use receiver audio reports for outgoing shared-sound loss statistics, and add opt-in Windows capture-progress diagnostics to help locate missing audio.

Existing 2.x App/site compatibility, saved room data and invitation privacy are preserved. Update the App for Native changes. After updating a hosted Server, refresh open site pages; App-local pages use the Web UI included in the updated App package.

### 中文

本次更新让邀请分享和播放调整更方便,并改善 App 连接、切换来源及日常控件。同时增加可选界面译文和更有帮助的音频诊断。

- 将当前邀请在本地生成二维码,保留所选访问凭证,方便另一台设备扫码加入。
- 增加繁体中文、日语和韩语可选译文。中英文保留快捷入口,第三个菜单提供附加语言与纯视觉模式;缺少的译文回退英文。
- 增加 **增加播放缓冲** 开关,并可调整目标值。更多缓冲可减少数据到达不均造成的停顿,但会增加观看延迟;默认仍由系统自动决定。
- 缩放或旋转画面后,不再把画面外空白区域的点击误传给远端。
- 打开站点时检查一次本地 Piik App。自动发现遵循本地网络权限,主动连接时才由你批准访问;被动发现失败保持安静。
- 旧 Native 来源结束或 App 断开时,保留正在进行的浏览器屏幕或摄像头选择。释放旧来源后仍可完成新选择;取消或主动停止时正确收尾。
- 改善建立连接时端口映射变化情况下的 App 间连接。
- 避免播放提示遮挡分享控件,让选中指示保持在轨道内,保留禁用按钮图标,并让数值设置显示实际接受的值。
- 共享声音的发送端丢包统计改用接收方音频报告,并增加可选的 Windows 采集进度诊断,帮助定位无声发生在哪一段。

保留现有 2.x App/站点兼容性、已保存的房间数据和邀请隐私。Native 改动需要更新 App。托管 Server 更新后请刷新已打开的页面;App 本地页面使用新版 App 包内的网页。

## Verification / 验证

- Complete frontend check: TypeScript, 110 test files / 2001 tests, Web build. Go core check: format, tests, vet and supported cross-target builds; macOS App builds require their native SDK.
- QR invitations passed independent local decoding, credential/rotation checks and short-window layout. Language/visual menus and guidance passed native and forced-polyfill Browser checks.
- Native preparation passed actual Pion socket adoption, VP8 SRTP and reverse SRTCP controls. Remote-input geometry and accepted numeric settings have focused regressions.
- Optional buffer transitions passed real P2P and actual SFU subscriber receiver-API controls for automatic to 300 ms to automatic. The SFU control used a Browser mock upstream rather than the embedded backend; Native preview delegation has unit coverage only.
- Windows diagnostics passed strict translation compilation, counter tests and stderr-to-diagnostic-ZIP verification. Physical capture, optical QR scanning and a public-network success-rate improvement are not claimed.

## Impact / 影响

Compatible 2.x update: Browser/server v24, Native control v10, capture v7 and SQLite schema 2 remain unchanged. Optional translations preserve English fallback and the independent visual preference. Playback buffer is a local viewing preference and leaves the default automatic. Existing room authority and invitation handling are preserved.

The HTTP compression dependency receives a compatible patch update. Mirror preparation detects a rejected missing tag before original-artifact downloads; the platform restriction remains open, with original-package validation and continuation rules intact. This does not establish fixes for #499, #502, #529 or #534.
2026-11-15 18:23:50 -04:00

289 lines
9.8 KiB
TypeScript

import { applyPlaybackBufferTarget, validatePlaybackBufferTarget, type PlaybackBufferStatus } from "../webrtc/receiver-buffer-target";
import type { SfuSignalMessage } from "../../shared/protocol";
import { RemoteInputChannel } from "../webrtc/remote-input-channel";
import type { ConnectionMetrics } from "../types";
import { debugRtcFailure, debugRtcStats } from "../lib/debug-webrtc";
import {
collectConnectionMetricsFromReport,
createStatsAccumulator,
decodedVideoFrames,
} from "../webrtc/stats";
import { preferScreenAudioStereo } from "../webrtc/opus-receive-sdp";
import { requireReceivingVideo, VideoReceiveRejectedError } from "../webrtc/video-codec";
import { observeDecodedFrameProof } from "../media/decoded-frame-proof";
import { SfuPeer, type SfuConnectionConfig } from "./peer";
interface SubscriberEvents {
onPlaybackBufferStatus?: (status: PlaybackBufferStatus) => void;
onInputChanged?: () => void;
send: (message: SfuSignalMessage) => boolean;
onStream: (stream: MediaStream | null) => void;
onVideoAvailability?: (available: boolean) => void;
onStats?: (metrics: ConnectionMetrics) => void;
onFirstDecodedFrame?: () => boolean;
onState?: (state: "connected" | "reconnecting") => void;
onDisconnected?: (failure?: "VIDEO_REJECTED") => void;
}
interface SubscribedTrack {
track: MediaStreamTrack;
receiver: RTCRtpReceiver;
onEnded: () => void;
}
export class SfuSubscriber {
private readonly remoteInput = new RemoteInputChannel(() => this.events.onInputChanged?.());
getRemoteInput(): RTCDataChannel | null { return this.remoteInput.current; }
private peer: SfuPeer | null = null;
private video: SubscribedTrack | null = null;
private audio: SubscribedTrack | null = null;
private readonly stream = new MediaStream();
private active = false;
private closed = false;
private restartPending = false;
private streamEmitted = false;
private stats = createStatsAccumulator();
private statsInFlight: typeof this.stats | null = null;
private statsTimer: ReturnType<typeof setInterval> | null = null;
private proofMode: "fresh" | "progress" | null = null;
private stopProof: (() => void) | null = null;
private playbackBufferTargetMs: number | null = null;
private playbackBufferStatus: PlaybackBufferStatus = null;
constructor(private readonly events: SubscriberEvents) {}
setPlaybackBufferTarget(target: number | null): PlaybackBufferStatus {
validatePlaybackBufferTarget(target);
this.playbackBufferTargetMs = target;
return this.applyPlaybackBuffer();
}
getPlaybackBufferStatus(): PlaybackBufferStatus { return this.playbackBufferStatus; }
private applyPlaybackBuffer(): PlaybackBufferStatus {
const status = applyPlaybackBufferTarget([this.video, this.audio].flatMap(track => track ? [track.receiver] : []), this.playbackBufferTargetMs);
this.playbackBufferStatus = status;
this.events.onPlaybackBufferStatus?.(status);
return status;
}
async connect(config: SfuConnectionConfig): Promise<boolean> {
if (this.peer || this.closed)
throw new Error("SFU subscriber cannot be connected twice");
this.peer = new SfuPeer(config, {
send: this.events.send,
onTrack: (event) => this.addTrack(event),
onState: (state) => {
if (state === "failed") this.fail();
else if (state === "connected") {
this.restartPending = false;
this.events.onState?.("connected");
this.startProof();
} else if (state === "disconnected") this.reconnect();
},
});
this.remoteInput.attach(this.peer.pc);
return true;
}
updateConfig(config: SfuConnectionConfig): void {
this.peer?.updateConfig(config);
}
isConnected(): boolean { return this.peer?.pc.connectionState === "connected"; }
// Reauthentication cannot establish whether a lost offer/answer was applied.
// Retire that exact subscription through the route owner; do not replay SDP.
resync(): void {
if (this.restartPending) this.fail();
}
async acceptSignal(message: SfuSignalMessage): Promise<void> {
const peer = this.peer;
if (!peer) return;
try {
await peer.acceptSignal(message, async (description) => {
if (description.type !== "offer")
throw new Error("SFU subscriber expected an offer");
await peer.waitForOperation(() => peer.pc.setRemoteDescription(description));
if (this.peer !== peer) return;
const answer = preferScreenAudioStereo(await peer.waitForOperation(() => peer.pc.createAnswer()));
requireReceivingVideo(description, answer);
await peer.sendDescription(answer);
if (peer.pc.connectionState === "connected") this.restartPending = false;
});
} catch (error) {
if (this.peer === peer) this.fail(error instanceof VideoReceiveRejectedError ? "VIDEO_REJECTED" : undefined);
}
}
activate(): boolean {
if (!this.peer || this.closed) return false;
if (this.active) return true;
this.active = true;
this.statsTimer = setInterval(() => void this.updateStats(), 2_000);
this.emitStream();
this.startProof();
return true;
}
deactivate(): boolean {
void this.disconnect();
return true;
}
reconnect(): boolean {
if (
!this.active ||
this.restartPending || !this.peer
)
return false;
const sent = this.peer.send({ kind: "subscribe" });
// An unsent manual request cannot retire media that is still connected.
// A disconnected transport still needs reconciliation after signaling returns.
if (sent || this.peer.pc.connectionState !== "connected") {
this.restartPending = true;
this.events.onState?.("reconnecting");
}
return sent;
}
armDecodedFrameProof(requireProgress = false): void {
this.proofMode = requireProgress ? "progress" : "fresh";
this.startProof();
}
stopDecodedFrameProof(): void {
this.proofMode = null;
this.stopProof?.();
this.stopProof = null;
}
async disconnect(): Promise<void> {
if (this.closed) return;
this.closed = true;
this.remoteInput.dispose();
this.active = false;
const peer = this.peer;
this.peer = null;
peer?.close();
this.stopDecodedFrameProof();
if (this.statsTimer !== null) clearInterval(this.statsTimer);
this.statsTimer = null;
const hadVideo = this.video !== null;
this.detach(this.video);
this.detach(this.audio);
this.video = null;
this.audio = null;
this.applyPlaybackBuffer();
this.stats = createStatsAccumulator();
if (hadVideo) this.events.onVideoAvailability?.(false);
if (this.streamEmitted) this.events.onStream(null);
this.streamEmitted = false;
}
private fail(failure?: "VIDEO_REJECTED"): void {
if (this.closed) return;
void this.disconnect();
this.events.onDisconnected?.(failure);
}
private addTrack({ track, receiver }: RTCTrackEvent): void {
if (track.kind !== "video" && track.kind !== "audio") return;
const isVideo = track.kind === "video";
const previous = isVideo ? this.video : this.audio;
if (previous?.track === track) return;
this.detach(previous);
const subscribed: SubscribedTrack = {
track,
receiver,
onEnded: () => {
if ((isVideo ? this.video : this.audio) !== subscribed) return;
this.detach(subscribed);
if (isVideo) {
this.video = null;
this.stopProof?.();
this.stopProof = null;
this.events.onVideoAvailability?.(false);
} else this.audio = null;
this.applyPlaybackBuffer();
this.stats = createStatsAccumulator();
this.emitStream();
},
};
track.addEventListener("ended", subscribed.onEnded, { once: true });
this.stream.addTrack(track);
if (isVideo) this.video = subscribed;
else this.audio = subscribed;
this.applyPlaybackBuffer();
this.stats = createStatsAccumulator();
this.emitStream();
if (isVideo) {
this.events.onVideoAvailability?.(true);
this.startProof();
}
}
private detach(subscribed: SubscribedTrack | null): void {
if (!subscribed) return;
subscribed.track.removeEventListener("ended", subscribed.onEnded);
this.stream.removeTrack(subscribed.track);
}
private emitStream(): void {
if (!this.active || !this.video) return;
this.streamEmitted = true;
this.events.onStream(this.stream);
}
private startProof(): void {
this.stopProof?.();
this.stopProof = null;
const peer = this.peer;
const video = this.video;
const mode = this.proofMode;
if (!peer || !video || !mode || !this.active) return;
this.stopProof = observeDecodedFrameProof({
readFramesDecoded: async () =>
decodedVideoFrames(await video.receiver.getStats()),
owns: () =>
this.peer === peer &&
this.active &&
this.video === video &&
this.proofMode === mode,
requireProgress: mode === "progress",
onProof: () => {
if (!this.isConnected()) return false;
const accepted = this.events.onFirstDecodedFrame?.() ?? true;
if (accepted) {
this.proofMode = null;
this.stopProof = null;
}
return accepted;
},
});
}
private async updateStats(): Promise<void> {
const peer = this.peer;
const video = this.video;
const stats = this.stats;
if (!peer || !this.active) return;
if (!video || this.statsInFlight === stats) return;
this.statsInFlight = stats;
try {
const report = await peer.pc.getStats();
debugRtcStats(peer.pc, report);
if (this.peer !== peer || this.video !== video || this.stats !== stats)
return;
const metrics = collectConnectionMetricsFromReport(
report,
"receive",
stats,
);
this.events.onStats?.(metrics);
} catch (error) {
debugRtcFailure(peer.pc, error);
} finally {
if (this.statsInFlight === stats) this.statsInFlight = null;
}
}
}