## 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.
975 lines
39 KiB
TypeScript
975 lines
39 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { QUALITY_PROFILES } from "../src/client/media/quality.ts";
|
|
import { SfuPublisher } from "../src/client/sfu/publisher.ts";
|
|
import { SfuSubscriber } from "../src/client/sfu/subscriber.ts";
|
|
import { ViewerSfuRoute } from "../src/client/media/viewer-sfu-route.ts";
|
|
import * as senderTracks from "../src/client/media/sender-video-track";
|
|
import {
|
|
clientMessageSchema,
|
|
type ClientMessage,
|
|
type SfuSignalMessage,
|
|
} from "../src/shared/protocol.ts";
|
|
|
|
class FakeTrack extends EventTarget {
|
|
readonly id = crypto.randomUUID();
|
|
enabled = true;
|
|
contentHint = "";
|
|
readyState = "live";
|
|
readonly clones: FakeTrack[] = [];
|
|
readonly stop = vi.fn(() => {
|
|
this.readyState = "ended";
|
|
});
|
|
readonly getSettings = vi.fn(() => ({
|
|
width: 1920,
|
|
height: 1080,
|
|
frameRate: 30,
|
|
}));
|
|
readonly applyConstraints = vi.fn(
|
|
async (_constraints: MediaTrackConstraints) => undefined,
|
|
);
|
|
getConstraints() { return {}; }
|
|
readonly clone = vi.fn(() => {
|
|
const next = new FakeTrack(this.kind);
|
|
this.clones.push(next);
|
|
return next;
|
|
});
|
|
constructor(readonly kind: "audio" | "video") {
|
|
super();
|
|
}
|
|
}
|
|
|
|
class FakeStream {
|
|
constructor(private tracks: FakeTrack[] = []) {}
|
|
getTracks(): FakeTrack[] {
|
|
return [...this.tracks];
|
|
}
|
|
getVideoTracks(): FakeTrack[] {
|
|
return this.tracks.filter((track) => track.kind === "video");
|
|
}
|
|
getAudioTracks(): FakeTrack[] {
|
|
return this.tracks.filter((track) => track.kind === "audio");
|
|
}
|
|
addTrack(track: FakeTrack): void {
|
|
this.tracks.push(track);
|
|
}
|
|
removeTrack(track: FakeTrack): void {
|
|
this.tracks = this.tracks.filter((current) => current !== track);
|
|
}
|
|
}
|
|
|
|
class FakeSender {
|
|
readonly getParameters = vi.fn(() => structuredClone(this.parameters));
|
|
readonly setParameters = vi.fn(async (parameters: RTCRtpSendParameters) => {
|
|
this.parameters = structuredClone(parameters);
|
|
});
|
|
readonly replaceTrack = vi.fn(async (track: FakeTrack | null) => {
|
|
this.track = track;
|
|
});
|
|
readonly getStats = vi.fn(async () => new Map());
|
|
parameters: RTCRtpSendParameters;
|
|
constructor(
|
|
public track: FakeTrack | null,
|
|
encodings: RTCRtpEncodingParameters[],
|
|
) {
|
|
this.parameters = {
|
|
encodings,
|
|
codecs: [],
|
|
headerExtensions: [],
|
|
rtcp: {},
|
|
transactionId: "test",
|
|
};
|
|
}
|
|
static getCapabilities(kind: string) {
|
|
return {
|
|
codecs:
|
|
kind === "audio"
|
|
? [{ mimeType: "audio/opus", clockRate: 48000, channels: 2 }]
|
|
: [
|
|
{ mimeType: "video/VP8", clockRate: 90000 },
|
|
{
|
|
mimeType: "video/H264",
|
|
clockRate: 90000,
|
|
sdpFmtpLine: "packetization-mode=1;profile-level-id=42e01f",
|
|
},
|
|
{ mimeType: "video/VP9", clockRate: 90000 },
|
|
],
|
|
};
|
|
}
|
|
}
|
|
|
|
class FakePc extends EventTarget {
|
|
static instances: FakePc[] = [];
|
|
onicecandidate: ((event: { candidate: unknown }) => void) | null = null;
|
|
onconnectionstatechange: (() => void) | null = null;
|
|
ontrack: ((event: unknown) => void) | null = null;
|
|
connectionState: RTCPeerConnectionState = "new";
|
|
signalingState: RTCSignalingState = "stable";
|
|
localDescription: RTCSessionDescriptionInit | null = null;
|
|
remoteDescription: RTCSessionDescriptionInit | null = null;
|
|
readonly transceivers: Array<{
|
|
sender: FakeSender;
|
|
setCodecPreferences: ReturnType<typeof vi.fn>;
|
|
}> = [];
|
|
report = new Map();
|
|
readonly getStats = vi.fn(async () => this.report);
|
|
readonly close = vi.fn(() => {
|
|
this.connectionState = "closed";
|
|
});
|
|
readonly createOffer = vi.fn(async (_options?: RTCOfferOptions) => ({
|
|
type: "offer" as const,
|
|
sdp: "offer",
|
|
}));
|
|
readonly createAnswer = vi.fn(async () => ({
|
|
type: "answer" as const,
|
|
sdp: "answer",
|
|
}));
|
|
readonly setLocalDescription = vi.fn(
|
|
async (description: RTCSessionDescriptionInit) => {
|
|
this.localDescription = description;
|
|
this.signalingState =
|
|
description.type === "offer" ? "have-local-offer" : "stable";
|
|
this.onicecandidate?.({
|
|
candidate: {
|
|
protocol: "udp",
|
|
candidate: "candidate:1 1 UDP 1 127.0.0.1 4000 typ host",
|
|
toJSON: () => ({
|
|
candidate: "candidate:1 1 UDP 1 127.0.0.1 4000 typ host",
|
|
}),
|
|
},
|
|
});
|
|
},
|
|
);
|
|
readonly setRemoteDescription = vi.fn(
|
|
async (description: RTCSessionDescriptionInit) => {
|
|
this.remoteDescription = description;
|
|
this.signalingState =
|
|
description.type === "offer" ? "have-remote-offer" : "stable";
|
|
},
|
|
);
|
|
readonly addIceCandidate = vi.fn(
|
|
async (_candidate: RTCIceCandidateInit) => undefined,
|
|
);
|
|
constructor(readonly configuration: RTCConfiguration) {
|
|
super();
|
|
FakePc.instances.push(this);
|
|
}
|
|
addTransceiver(track: FakeTrack | string, options: RTCRtpTransceiverInit) {
|
|
const transceiver = {
|
|
sender: new FakeSender(
|
|
typeof track === "string" ? null : track,
|
|
options.sendEncodings ?? [{}],
|
|
),
|
|
setCodecPreferences: vi.fn(),
|
|
};
|
|
this.transceivers.push(transceiver);
|
|
return transceiver;
|
|
}
|
|
state(state: RTCPeerConnectionState): void {
|
|
this.connectionState = state;
|
|
this.onconnectionstatechange?.();
|
|
this.dispatchEvent(new Event("connectionstatechange"));
|
|
}
|
|
}
|
|
|
|
const config = {
|
|
revision: 4,
|
|
publicationGeneration: "publication_12345678",
|
|
connectionId: "connection_12345678",
|
|
};
|
|
const signal = (payload: Partial<SfuSignalMessage>): SfuSignalMessage => ({
|
|
type: "sfu-signal",
|
|
...config,
|
|
kind: "description",
|
|
...payload,
|
|
});
|
|
const cleanups: Array<() => Promise<void>> = [];
|
|
const stream = (...tracks: FakeTrack[]): MediaStream =>
|
|
new FakeStream(tracks) as unknown as MediaStream;
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
FakePc.instances = [];
|
|
vi.stubGlobal("MediaStream", FakeStream);
|
|
vi.stubGlobal("RTCPeerConnection", FakePc);
|
|
vi.stubGlobal("RTCRtpSender", FakeSender);
|
|
});
|
|
afterEach(async () => {
|
|
for (const cleanup of cleanups.splice(0)) await cleanup();
|
|
vi.useRealTimers();
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
async function publisher(audio = true) {
|
|
const send = vi.fn((_message: SfuSignalMessage) => true);
|
|
const onDisconnected = vi.fn();
|
|
const video = new FakeTrack("video");
|
|
const sound = new FakeTrack("audio");
|
|
const publisher = new SfuPublisher({ send, onDisconnected });
|
|
cleanups.push(() => publisher.disconnect());
|
|
await publisher.connect(config);
|
|
await publisher.activate(
|
|
stream(video, ...(audio ? [sound] : [])),
|
|
QUALITY_PROFILES["1080p30"],
|
|
"h264",
|
|
);
|
|
return {
|
|
publisher,
|
|
send,
|
|
onDisconnected,
|
|
video,
|
|
sound,
|
|
pc: FakePc.instances[0]!,
|
|
};
|
|
}
|
|
|
|
function feedVideoStats(
|
|
pc: FakePc,
|
|
trackId: string,
|
|
framesEncoded: number,
|
|
): void {
|
|
pc.report.clear();
|
|
pc.report.set("outbound-video", {
|
|
id: "outbound-video",
|
|
type: "outbound-rtp",
|
|
kind: "video",
|
|
timestamp: 1_000,
|
|
ssrc: 10,
|
|
framesEncoded,
|
|
mediaSourceId: "media-source-video",
|
|
});
|
|
pc.report.set("media-source-video", {
|
|
id: "media-source-video",
|
|
type: "media-source",
|
|
kind: "video",
|
|
timestamp: 1_000,
|
|
trackIdentifier: trackId,
|
|
});
|
|
}
|
|
|
|
describe("embedded SFU browser transport", () => {
|
|
it("rejects publication without a real Browser source", async () => {
|
|
const send = vi.fn(() => true);
|
|
const host = new SfuPublisher({ send, onDisconnected: vi.fn() });
|
|
cleanups.push(() => host.disconnect());
|
|
await host.connect(config);
|
|
await expect(host.activate(null, QUALITY_PROFILES["720p30"], "h264")).rejects.toThrow("SFU source has no stream");
|
|
expect(host.getFailureStage()).toBe("source");
|
|
expect(FakePc.instances[0]!.transceivers).toHaveLength(0);
|
|
expect(send).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([100_000, 200_000, 50_000_000])("keeps every simulcast output within the %i bps source ceiling", async (maxBitrate) => {
|
|
const send = vi.fn(() => true);
|
|
const host = new SfuPublisher({ send, onDisconnected: vi.fn() });
|
|
cleanups.push(() => host.disconnect());
|
|
await host.connect(config);
|
|
expect(await host.activate(stream(new FakeTrack("video")),
|
|
{ ...QUALITY_PROFILES["1080p30"], maxBitrate, maxFramerate: 5 }, "h264")).toBe(true);
|
|
const encodings = FakePc.instances[0]!.transceivers[0]!.sender.getParameters().encodings;
|
|
expect(encodings).toHaveLength(2);
|
|
expect(encodings[1]!.maxBitrate).toBe(maxBitrate);
|
|
for (const encoding of encodings) {
|
|
expect(encoding.maxBitrate).toBeGreaterThan(0);
|
|
expect(encoding.maxBitrate).toBeLessThanOrEqual(maxBitrate);
|
|
expect(encoding.maxFramerate).toBe(5);
|
|
}
|
|
});
|
|
|
|
it("uses capture dimensions for simulcast before a generated sender has its first frame", async () => {
|
|
class Generator extends FakeTrack {
|
|
writable = new WritableStream<VideoFrame>();
|
|
constructor() { super("video"); this.getSettings.mockReturnValue({} as never); }
|
|
}
|
|
let frames!: ReadableStreamDefaultController<VideoFrame>;
|
|
vi.stubGlobal("MediaStreamTrackGenerator", Generator);
|
|
vi.stubGlobal("MediaStreamTrackProcessor", class {
|
|
readable = new ReadableStream<VideoFrame>({ start(controller) { frames = controller; } });
|
|
});
|
|
const video = new FakeTrack("video"), send = vi.fn(() => true), onDisconnected = vi.fn();
|
|
video.getSettings.mockReturnValue({ ...video.getSettings(), displaySurface: "browser" } as never);
|
|
const host = new SfuPublisher({ send, onDisconnected });
|
|
cleanups.push(() => host.disconnect());
|
|
await host.connect(config);
|
|
expect(await host.activate(stream(video), QUALITY_PROFILES["1080p30"], "h264")).toBe(true);
|
|
const sender = FakePc.instances[0]!.transceivers[0]!.sender;
|
|
expect(sender.track!.getSettings()).toEqual({});
|
|
expect(sender.parameters.encodings.map(e => e.scaleResolutionDownBy)).toEqual([2, 1]);
|
|
expect(send).toHaveBeenCalledWith(expect.objectContaining({ media: expect.objectContaining({ layers: [
|
|
expect.objectContaining({ width: 960, height: 540 }), expect.objectContaining({ width: 1920, height: 1080 }),
|
|
] }) }));
|
|
frames.error(new Error("display frame input failed"));
|
|
for (let i = 0; i < 30; i++) await Promise.resolve();
|
|
expect(onDisconnected).toHaveBeenCalledOnce();
|
|
expect(video.stop).not.toHaveBeenCalled();
|
|
expect(video.clones[0]!.readyState).toBe("ended");
|
|
});
|
|
|
|
it.each(["current", "replaced", "pending", "configuring"])("handles a %s frame input ending without affecting the source", async (phase) => {
|
|
const endings: Array<{ track: FakeTrack; end: () => void }> = [];
|
|
vi.spyOn(senderTracks, "cloneSenderVideoTrack").mockImplementation((source, onEnded) => {
|
|
const track = source.clone() as unknown as FakeTrack;
|
|
endings.push({ track, end() { track.stop(); onEnded(track as unknown as MediaStreamTrack); } });
|
|
return track as unknown as MediaStreamTrack;
|
|
});
|
|
const { publisher: host, pc, onDisconnected, video } = await publisher();
|
|
if (phase === "current") endings[0]!.end();
|
|
else {
|
|
const next = new FakeTrack("video");
|
|
if (phase === "pending") pc.transceivers[1]!.sender.replaceTrack.mockImplementationOnce(async () => endings[1]!.end());
|
|
if (phase === "configuring") pc.transceivers[0]!.sender.setParameters.mockImplementationOnce(async () => endings[1]!.end());
|
|
expect(await host.replaceStream(stream(next))).toBe(phase === "replaced");
|
|
if (phase === "replaced") endings[0]!.end();
|
|
expect(pc.transceivers[0]!.sender.track).toBe(endings[phase === "replaced" ? 1 : 0]!.track);
|
|
expect(next.stop).not.toHaveBeenCalled();
|
|
}
|
|
expect(onDisconnected).toHaveBeenCalledTimes(phase === "current" ? 1 : 0);
|
|
expect(video.stop).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["queued", "active"])("preserves publication after a %s candidate rejection", async (phase) => {
|
|
const { publisher: host, pc, onDisconnected, video } = await publisher();
|
|
const rejected = signal({ kind: "candidate", candidate: { candidate: "candidate:1 1 UDP 1 127.0.0.1 4100 typ host" } });
|
|
const valid = signal({ kind: "candidate", candidate: { candidate: "candidate:2 1 UDP 1 127.0.0.1 4101 typ host" } });
|
|
pc.addIceCandidate.mockRejectedValueOnce(new DOMException("Rejected candidate", "OperationError"));
|
|
if (phase === "queued") {
|
|
await host.acceptSignal(rejected);
|
|
await host.acceptSignal(valid);
|
|
}
|
|
await host.acceptSignal(signal({ description: { type: "answer", sdp: "answer" } }));
|
|
pc.state("connected");
|
|
if (phase === "active") {
|
|
await host.acceptSignal(rejected);
|
|
await host.acceptSignal(valid);
|
|
}
|
|
expect(pc.addIceCandidate).toHaveBeenCalledWith(valid.candidate);
|
|
expect(onDisconnected).not.toHaveBeenCalled();
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
expect(video.clones[0]!.readyState).toBe("live");
|
|
});
|
|
|
|
it("publishes one bounded simulcast PC, offers before ICE and admits only the selected codec", async () => {
|
|
const { publisher: host, pc, send, video } = await publisher();
|
|
expect(pc.configuration).toEqual({ iceServers: [] });
|
|
expect(pc.transceivers).toHaveLength(2);
|
|
expect(pc.transceivers[0]!.sender.track).toBe(video.clones[0]);
|
|
const offer = send.mock.calls[0]![0];
|
|
expect(offer.kind).toBe("description");
|
|
expect(offer.media).toEqual({
|
|
codec: "h264",
|
|
layers: [
|
|
{ rid: "q", width: 960, height: 540, bitrate: 1_250_000 },
|
|
{ rid: "h", width: 1920, height: 1080, bitrate: 5_000_000 },
|
|
],
|
|
audio: true,
|
|
audioBitrate: 128_000,
|
|
});
|
|
expect(send.mock.calls[1]![0].kind).toBe("candidate");
|
|
expect(clientMessageSchema.safeParse(offer).success).toBe(true);
|
|
expect(pc.transceivers[0]!.setCodecPreferences.mock.calls[0]![0]).toEqual([
|
|
expect.objectContaining({ mimeType: "video/H264" }),
|
|
]);
|
|
await host.acceptSignal(
|
|
signal({ description: { type: "answer", sdp: "answer" } }),
|
|
);
|
|
expect(pc.remoteDescription?.type).toBe("answer");
|
|
});
|
|
|
|
it("queues remote ICE and rejects retired connection/publication identities", async () => {
|
|
const { publisher: host, pc } = await publisher();
|
|
const candidate = {
|
|
candidate: "candidate:1 1 UDP 1 127.0.0.1 4100 typ host",
|
|
};
|
|
await host.acceptSignal(signal({ kind: "candidate", candidate }));
|
|
expect(pc.addIceCandidate).not.toHaveBeenCalled();
|
|
await host.acceptSignal(
|
|
signal({
|
|
connectionId: "retired_12345678",
|
|
description: { type: "answer", sdp: "stale" },
|
|
}),
|
|
);
|
|
await host.acceptSignal(
|
|
signal({
|
|
publicationGeneration: "retired_12345678",
|
|
description: { type: "answer", sdp: "stale" },
|
|
}),
|
|
);
|
|
expect(pc.setRemoteDescription).not.toHaveBeenCalled();
|
|
await host.acceptSignal(
|
|
signal({ description: { type: "answer", sdp: "answer" } }),
|
|
);
|
|
expect(pc.addIceCandidate).toHaveBeenCalledWith(candidate);
|
|
});
|
|
|
|
it("updates all existing encodings and audio without changing the PC or codec", async () => {
|
|
const { publisher: host, pc, send } = await publisher();
|
|
const profile = {
|
|
...QUALITY_PROFILES["720p30"],
|
|
maxAudioBitrate: 192000 as const,
|
|
};
|
|
expect(await host.updateProfile(profile)).toBe(true);
|
|
expect(pc.transceivers[0]!.sender.parameters.encodings).toEqual([
|
|
expect.objectContaining({
|
|
rid: "q",
|
|
maxBitrate: 750_000,
|
|
scaleResolutionDownBy: 3,
|
|
}),
|
|
expect.objectContaining({
|
|
rid: "h",
|
|
maxBitrate: 3_000_000,
|
|
scaleResolutionDownBy: 1.5,
|
|
}),
|
|
]);
|
|
expect(pc.transceivers[1]!.sender.parameters.encodings[0]!.maxBitrate).toBe(192_000);
|
|
expect(send.mock.calls.at(-1)![0]).toMatchObject({
|
|
kind: "media",
|
|
media: { codec: "h264", audioBitrate: 192_000 },
|
|
});
|
|
expect(FakePc.instances).toHaveLength(1);
|
|
expect(pc.createOffer).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it.each([false, true])("keeps established SFU video through audio-only addition and removal (initial audio=%s)", async (audio) => {
|
|
const { publisher: host, pc, video, send } = await publisher(audio);
|
|
const sender = pc.transceivers[0]!.sender;
|
|
const ownedVideo = video.clones[0]!;
|
|
feedVideoStats(pc, ownedVideo.id, 6);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
expect(sender.parameters.degradationPreference).toBe("balanced");
|
|
const parameters = sender.setParameters.mock.calls.length;
|
|
const constraints = ownedVideo.applyConstraints.mock.calls.length;
|
|
const voice = new FakeTrack("audio");
|
|
for (const tracks of [[voice], []]) {
|
|
expect(await host.replaceStream(stream(video, ...tracks))).toBe(true);
|
|
expect(sender.track).toBe(ownedVideo);
|
|
expect(sender.replaceTrack).not.toHaveBeenCalled();
|
|
expect(sender.setParameters).toHaveBeenCalledTimes(parameters);
|
|
expect(ownedVideo.applyConstraints).toHaveBeenCalledTimes(constraints);
|
|
expect(ownedVideo.stop).not.toHaveBeenCalled();
|
|
expect(sender.parameters.degradationPreference).toBe("balanced");
|
|
expect(send).toHaveBeenLastCalledWith(expect.objectContaining({ kind: "media", media: expect.objectContaining({ audio: tracks.length > 0 }) }));
|
|
}
|
|
expect(video.clones).toHaveLength(1);
|
|
expect(pc.createOffer).toHaveBeenCalledOnce();
|
|
expect(voice.clones[0]!.stop).toHaveBeenCalledOnce();
|
|
await host.disconnect();
|
|
expect(ownedVideo.stop).toHaveBeenCalledOnce();
|
|
expect(video.stop).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rolls back a rejected audio-only update without mutating the video", async () => {
|
|
const { publisher: host, pc, video, sound, send } = await publisher();
|
|
const videoSender = pc.transceivers[0]!.sender;
|
|
const audioSender = pc.transceivers[1]!.sender;
|
|
const ownedVideo = video.clones[0]!;
|
|
const previousAudio = sound.clones[0]!;
|
|
feedVideoStats(pc, ownedVideo.id, 6);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
const parameters = videoSender.setParameters.mock.calls.length;
|
|
const voice = new FakeTrack("audio");
|
|
send.mockReturnValueOnce(false);
|
|
expect(await host.replaceStream(stream(video, voice))).toBe(false);
|
|
expect(videoSender.track).toBe(ownedVideo);
|
|
expect(videoSender.replaceTrack).not.toHaveBeenCalled();
|
|
expect(videoSender.setParameters).toHaveBeenCalledTimes(parameters);
|
|
expect(ownedVideo.stop).not.toHaveBeenCalled();
|
|
expect(audioSender.track).toBe(previousAudio);
|
|
expect(previousAudio.stop).not.toHaveBeenCalled();
|
|
expect(voice.clones[0]!.stop).toHaveBeenCalledOnce();
|
|
expect(videoSender.parameters.degradationPreference).toBe("balanced");
|
|
});
|
|
|
|
it("reuses the audio transceiver when source audio appears and retires clones only", async () => {
|
|
const { publisher: host, pc, video, send } = await publisher(false);
|
|
const nextVideo = new FakeTrack("video");
|
|
const nextAudio = new FakeTrack("audio");
|
|
host.setPaused(true);
|
|
expect(await host.replaceStream(stream(nextVideo, nextAudio))).toBe(true);
|
|
expect(video.clones[0]!.stop).toHaveBeenCalledOnce();
|
|
expect(video.stop).not.toHaveBeenCalled();
|
|
expect(pc.transceivers).toHaveLength(2);
|
|
expect(nextVideo.clones[0]!.enabled).toBe(false);
|
|
expect(nextAudio.clones[0]!.enabled).toBe(false);
|
|
expect(send.mock.calls.at(-1)![0]).toMatchObject({
|
|
kind: "media",
|
|
media: { audio: true },
|
|
});
|
|
await host.disconnect();
|
|
expect(nextVideo.clones[0]!.stop).toHaveBeenCalledOnce();
|
|
expect(nextAudio.clones[0]!.stop).toHaveBeenCalledOnce();
|
|
expect(nextVideo.stop).not.toHaveBeenCalled();
|
|
expect(nextAudio.stop).not.toHaveBeenCalled();
|
|
expect(pc.close).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it.each([0, 250])("counts new publication frames from a valid baseline of %s", async (baseline) => {
|
|
const { publisher: host, pc, video } = await publisher();
|
|
const sender = pc.transceivers[0]!.sender;
|
|
expect(sender.parameters.degradationPreference).toBe(
|
|
"maintain-resolution",
|
|
);
|
|
feedVideoStats(pc, video.clones[0]!.id, 6);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
expect(sender.parameters.degradationPreference).toBe("balanced");
|
|
|
|
const nextVideo = new FakeTrack("video");
|
|
expect(await host.replaceStream(stream(nextVideo))).toBe(true);
|
|
expect(sender.parameters.degradationPreference).toBe(
|
|
"maintain-resolution",
|
|
);
|
|
|
|
// The old source, an empty report, and an absent counter are all unknown.
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
pc.report.clear();
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
feedVideoStats(pc, nextVideo.clones[0]!.id, 0);
|
|
delete pc.report.get("outbound-video").framesEncoded;
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
|
|
feedVideoStats(pc, nextVideo.clones[0]!.id, baseline);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
expect(sender.parameters.degradationPreference).toBe(
|
|
"maintain-resolution",
|
|
);
|
|
feedVideoStats(pc, nextVideo.clones[0]!.id, baseline + 4);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
expect(sender.parameters.degradationPreference).toBe(
|
|
"maintain-resolution",
|
|
);
|
|
feedVideoStats(pc, nextVideo.clones[0]!.id, baseline + 5);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
expect(sender.parameters.degradationPreference).toBe("balanced");
|
|
});
|
|
|
|
it("applies the latest committed profile when startup recovery lands", async () => {
|
|
const { publisher: host, pc, video } = await publisher();
|
|
const sender = pc.transceivers[0]!.sender;
|
|
const clone = video.clones[0]!;
|
|
let releaseConstraints!: () => void;
|
|
clone.applyConstraints.mockImplementationOnce(
|
|
() =>
|
|
new Promise<undefined>((resolve) => {
|
|
releaseConstraints = () => resolve(undefined);
|
|
}),
|
|
);
|
|
const update = host.updateProfile(QUALITY_PROFILES["720p30"]);
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
feedVideoStats(pc, clone.id, 6);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
releaseConstraints();
|
|
expect(await update).toBe(true);
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
|
|
// The user's 720p30 change must survive the queued startup recovery; a
|
|
// stats-time snapshot must not re-apply the previous 1080p30 profile.
|
|
expect(sender.parameters.degradationPreference).toBe("balanced");
|
|
expect(sender.parameters.encodings[1]).toMatchObject({
|
|
maxBitrate: 3_000_000,
|
|
});
|
|
});
|
|
|
|
it("rolls back a failed source replacement and releases its unused clone", async () => {
|
|
const { publisher: host, pc, video, send } = await publisher();
|
|
const videoSender = pc.transceivers[0]!.sender;
|
|
feedVideoStats(pc, video.clones[0]!.id, 6);
|
|
await vi.advanceTimersByTimeAsync(2_000);
|
|
send.mockReturnValueOnce(false);
|
|
const replacement = new FakeTrack("video");
|
|
expect(await host.replaceStream(stream(replacement))).toBe(false);
|
|
expect(pc.transceivers[0]!.sender.track).toBe(video.clones[0]);
|
|
expect(video.clones[0]!.stop).not.toHaveBeenCalled();
|
|
expect(replacement.clones[0]!.stop).toHaveBeenCalledOnce();
|
|
expect(videoSender.parameters.degradationPreference).toBe("balanced");
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
const replacements = videoSender.replaceTrack.mock.calls.length;
|
|
expect(await host.replaceStream(stream(video, new FakeTrack("audio")))).toBe(true);
|
|
expect(videoSender.replaceTrack).toHaveBeenCalledTimes(replacements);
|
|
expect(video.clones).toHaveLength(1);
|
|
});
|
|
|
|
it("preserves media during a signaling outage and updates only the route fence", async () => {
|
|
const { publisher: host, pc, send, onDisconnected } = await publisher();
|
|
await host.acceptSignal(
|
|
signal({ description: { type: "answer", sdp: "answer" } }),
|
|
);
|
|
pc.state("connected");
|
|
send.mockReturnValue(false);
|
|
expect(await host.updateProfile(QUALITY_PROFILES["720p30"])).toBe(false);
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
expect(onDisconnected).not.toHaveBeenCalled();
|
|
send.mockReturnValue(true);
|
|
host.updateConfig({ ...config, revision: 9 });
|
|
expect(await host.updateProfile(QUALITY_PROFILES["720p30"])).toBe(true);
|
|
const updated = send.mock.calls.at(-1)![0];
|
|
expect(updated.revision).toBe(9);
|
|
expect(clientMessageSchema.safeParse(updated).success).toBe(true);
|
|
});
|
|
|
|
it("answers the server offer and commits only decoded video, preserving media during ICE restart", async () => {
|
|
const send = vi.fn(() => true);
|
|
const onFirstDecodedFrame = vi.fn(() => true);
|
|
const onStream = vi.fn();
|
|
const onDisconnected = vi.fn();
|
|
const subscriber = new SfuSubscriber({
|
|
send,
|
|
onStream,
|
|
onFirstDecodedFrame,
|
|
onDisconnected,
|
|
});
|
|
cleanups.push(() => subscriber.disconnect());
|
|
await subscriber.connect(config);
|
|
subscriber.activate();
|
|
subscriber.armDecodedFrameProof();
|
|
const pc = FakePc.instances[0]!;
|
|
await subscriber.acceptSignal(
|
|
signal({ description: { type: "offer", sdp: "offer" } }),
|
|
);
|
|
let framesDecoded = 0;
|
|
const video = new FakeTrack("video");
|
|
pc.ontrack?.({
|
|
track: video,
|
|
receiver: {
|
|
getStats: async () =>
|
|
new Map([
|
|
[
|
|
"video",
|
|
{
|
|
id: "video",
|
|
type: "inbound-rtp",
|
|
kind: "video",
|
|
framesDecoded,
|
|
},
|
|
],
|
|
]),
|
|
},
|
|
});
|
|
pc.state("connected");
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(onFirstDecodedFrame).not.toHaveBeenCalled();
|
|
framesDecoded = 1;
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(onFirstDecodedFrame).toHaveBeenCalledOnce();
|
|
expect(onStream).toHaveBeenCalledOnce();
|
|
expect(subscriber.reconnect()).toBe(true);
|
|
expect(send).toHaveBeenLastCalledWith(
|
|
expect.objectContaining({
|
|
kind: "subscribe",
|
|
connectionId: config.connectionId,
|
|
}),
|
|
);
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
expect(onDisconnected).not.toHaveBeenCalled();
|
|
await subscriber.disconnect();
|
|
expect(onStream).toHaveBeenLastCalledWith(null);
|
|
});
|
|
|
|
it("waits for the exact SFU transport when decoded proof or commit arrives during disconnection", async () => {
|
|
const messages: ClientMessage[] = [];
|
|
const onSfuStream = vi.fn(), activatePeer = vi.fn(() => true);
|
|
const route = new ViewerSfuRoute("viewer_12345678", {
|
|
activatePeer, onSfuStream,
|
|
send: message => { messages.push(message); return true; },
|
|
});
|
|
cleanups.push(() => route.disconnect());
|
|
route.setPlaybackBufferTarget(350);
|
|
route.accept({ revision: 3, phase: "active", assignment: {
|
|
upstream: { kind: "peer", peerId: "healthy_parent" }, childPeerIds: [], sfuPublicationGeneration: null,
|
|
} });
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
const assignment = { upstream: { kind: "sfu" as const }, childPeerIds: [], sfuPublicationGeneration: config.publicationGeneration };
|
|
route.accept({ revision: config.revision, phase: "prepare", assignment, candidate: {
|
|
childPeerId: "viewer_12345678", connectionId: config.connectionId, transport: "sfu", qualityProbe: false,
|
|
} });
|
|
await route.acceptConfig({ type: "sfu-config", ...config });
|
|
const pc = FakePc.instances[0]!;
|
|
await route.acceptSignal(signal({ description: { type: "offer", sdp: "offer" } }));
|
|
let completeStats!: (report: Map<string, object>) => void;
|
|
const report = new Promise<Map<string, object>>(resolve => { completeStats = resolve; });
|
|
const bufferedReceiver = { getStats: () => report, jitterBufferTarget: null as number | null };
|
|
pc.ontrack?.({ track: new FakeTrack("video"), receiver: bufferedReceiver });
|
|
expect(bufferedReceiver.jitterBufferTarget).toBe(350);
|
|
expect(route.getPlaybackBufferStatus()).toBeNull();
|
|
route.setPlaybackBufferTarget(500);
|
|
expect(bufferedReceiver.jitterBufferTarget).toBe(500);
|
|
pc.state("connected");
|
|
pc.state("disconnected");
|
|
completeStats(new Map([["video", { id: "video", type: "inbound-rtp", kind: "video", framesDecoded: 1 }]]));
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(messages.filter(message => message.type === "route-ready")).toEqual([]);
|
|
expect(onSfuStream).not.toHaveBeenCalled();
|
|
|
|
pc.state("connected");
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(messages.filter(message => message.type === "route-ready")).toEqual([
|
|
{ type: "route-ready", revision: config.revision, phase: "prepare" },
|
|
]);
|
|
pc.state("disconnected");
|
|
route.accept({ revision: config.revision, phase: "active", assignment });
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(onSfuStream).not.toHaveBeenCalled();
|
|
pc.state("connected");
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(onSfuStream).toHaveBeenCalledOnce();
|
|
expect(route.getPlaybackBufferStatus()).toBe("supported");
|
|
route.setPlaybackBufferTarget(null);
|
|
expect(bufferedReceiver.jitterBufferTarget).toBeNull();
|
|
expect(FakePc.instances).toHaveLength(1);
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps a healthy subscription when a manual restart cannot be sent", async () => {
|
|
const send = vi.fn(() => true);
|
|
const onState = vi.fn(), onDisconnected = vi.fn();
|
|
const subscriber = new SfuSubscriber({ send, onStream: vi.fn(), onState, onDisconnected });
|
|
cleanups.push(() => subscriber.disconnect());
|
|
await subscriber.connect(config);
|
|
subscriber.activate();
|
|
const pc = FakePc.instances[0]!;
|
|
pc.state("connected");
|
|
onState.mockClear();
|
|
send.mockReturnValue(false);
|
|
|
|
expect(subscriber.reconnect()).toBe(false);
|
|
subscriber.resync();
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
expect(onDisconnected).not.toHaveBeenCalled();
|
|
expect(onState).not.toHaveBeenCalled();
|
|
|
|
send.mockReturnValue(true);
|
|
expect(subscriber.reconnect()).toBe(true);
|
|
expect(onState).toHaveBeenCalledExactlyOnceWith("reconnecting");
|
|
});
|
|
|
|
it("reports Browser video rejection through the existing SFU failure owner", async () => {
|
|
const send = vi.fn(() => true), onDisconnected = vi.fn();
|
|
const subscriber = new SfuSubscriber({ send, onStream: vi.fn(), onDisconnected });
|
|
cleanups.push(() => subscriber.disconnect());
|
|
await subscriber.connect(config);
|
|
const pc = FakePc.instances[0]!;
|
|
pc.createAnswer.mockResolvedValueOnce({ type: "answer", sdp: "m=video 0 UDP/TLS/RTP/SAVPF 120\r\n" });
|
|
await subscriber.acceptSignal(signal({ description: { type: "offer",
|
|
sdp: "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" } }));
|
|
expect(onDisconnected).toHaveBeenCalledExactlyOnceWith("VIDEO_REJECTED");
|
|
expect(pc.close).toHaveBeenCalledOnce();
|
|
expect(send).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
[false, false], [true, false], [false, true], [true, true],
|
|
])("retires an unfinished ICE restart on reauthentication (send=%s, answer=%s)", async (sent, answered) => {
|
|
const send = vi.fn(() => sent);
|
|
const onDisconnected = vi.fn();
|
|
const subscriber = new SfuSubscriber({ send, onStream: vi.fn(), onDisconnected });
|
|
cleanups.push(() => subscriber.disconnect());
|
|
await subscriber.connect(config);
|
|
subscriber.activate();
|
|
const pc = FakePc.instances[0]!;
|
|
pc.state("connected");
|
|
subscriber.resync();
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
pc.state("disconnected");
|
|
subscriber.updateConfig({ ...config, revision: 9 });
|
|
expect(send).toHaveBeenCalledOnce();
|
|
if (answered) await subscriber.acceptSignal(
|
|
signal({ description: { type: "offer", sdp: "restart offer" } }),
|
|
);
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
subscriber.resync();
|
|
subscriber.resync();
|
|
expect(pc.close).toHaveBeenCalledOnce();
|
|
expect(onDisconnected).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("bounds pending remote ICE without retiring the publication and flushes retained candidates", async () => {
|
|
const { publisher: host, pc, onDisconnected } = await publisher();
|
|
for (let index = 0; index < 65; index++) {
|
|
await host.acceptSignal(
|
|
signal({
|
|
kind: "candidate",
|
|
candidate: { candidate: `candidate:${index}` },
|
|
}),
|
|
);
|
|
}
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
expect(onDisconnected).not.toHaveBeenCalled();
|
|
await host.acceptSignal(signal({ description: { type: "answer", sdp: "answer" } }));
|
|
expect(pc.addIceCandidate.mock.calls.map(([candidate]) => candidate.candidate))
|
|
.toEqual(Array.from({ length: 64 }, (_, index) => `candidate:${index}`));
|
|
pc.state("failed");
|
|
expect(pc.close).toHaveBeenCalledOnce();
|
|
expect(onDisconnected).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("bounds local ICE during signaling loss and flushes retained candidates on return", async () => {
|
|
const { publisher: host, pc, send, onDisconnected } = await publisher();
|
|
pc.state("connected");
|
|
send.mockReturnValue(false);
|
|
for (let index = 0; index < 65; index++) {
|
|
const value = { candidate: `candidate:${index}` };
|
|
pc.onicecandidate?.({ candidate: { ...value, protocol: "udp", toJSON: () => value } });
|
|
}
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
expect(onDisconnected).not.toHaveBeenCalled();
|
|
send.mockClear().mockReturnValue(true);
|
|
host.updateConfig({ ...config, revision: 5 });
|
|
expect(send.mock.calls.map(([message]) => message.candidate?.candidate))
|
|
.toEqual(Array.from({ length: 64 }, (_, index) => `candidate:${index}`));
|
|
pc.state("failed");
|
|
expect(pc.close).toHaveBeenCalledOnce();
|
|
expect(onDisconnected).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("changes audio ceilings without touching video capture or sender parameters", async () => {
|
|
const { publisher: host, pc, video } = await publisher();
|
|
const constraints = video.clones[0]!.applyConstraints.mock.calls.length;
|
|
const parameters =
|
|
pc.transceivers[0]!.sender.setParameters.mock.calls.length;
|
|
expect(
|
|
await host.updateProfile({
|
|
...QUALITY_PROFILES["1080p30"],
|
|
maxAudioBitrate: 64000,
|
|
}),
|
|
).toBe(true);
|
|
expect(video.clones[0]!.applyConstraints).toHaveBeenCalledTimes(
|
|
constraints,
|
|
);
|
|
expect(pc.transceivers[0]!.sender.setParameters).toHaveBeenCalledTimes(
|
|
parameters,
|
|
);
|
|
expect(pc.transceivers[1]!.sender.parameters.encodings[0]!.maxBitrate).toBe(64_000);
|
|
});
|
|
|
|
it.each(["replaceTrack", "setParameters"] as const)("closes every owned clone while %s remains pending without stopping the sources", async (operation) => {
|
|
const { publisher: host, pc, video, sound } = await publisher();
|
|
let release!: () => void;
|
|
const blocked = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
pc.transceivers[0]!.sender[operation].mockImplementationOnce(
|
|
async () => blocked,
|
|
);
|
|
const replacement = new FakeTrack("video");
|
|
const replacing = host.replaceStream(stream(replacement));
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
host.setPaused(true);
|
|
expect(replacement.clones[0]!.enabled).toBe(false);
|
|
await host.disconnect();
|
|
expect(await replacing).toBe(false);
|
|
for (const track of [
|
|
video.clones[0]!,
|
|
sound.clones[0]!,
|
|
replacement.clones[0]!,
|
|
])
|
|
expect(track.stop).toHaveBeenCalledOnce();
|
|
for (const source of [video, sound, replacement])
|
|
expect(source.stop).not.toHaveBeenCalled();
|
|
expect(pc.close).toHaveBeenCalledOnce();
|
|
const audioCalls = pc.transceivers[1]!.sender.replaceTrack.mock.calls.length;
|
|
release();
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(pc.transceivers[1]!.sender.replaceTrack).toHaveBeenCalledTimes(audioCalls);
|
|
});
|
|
|
|
it("fails closed when restoring a replaced sender fails", async () => {
|
|
const { publisher: host, pc, onDisconnected, video } = await publisher();
|
|
pc.transceivers[0]!.sender.replaceTrack.mockRejectedValue(
|
|
new Error("sender failed"),
|
|
);
|
|
const replacement = new FakeTrack("video");
|
|
expect(await host.replaceStream(stream(replacement))).toBe(false);
|
|
expect(onDisconnected).toHaveBeenCalledOnce();
|
|
expect(pc.close).toHaveBeenCalledOnce();
|
|
expect(video.clones[0]!.stop).toHaveBeenCalledOnce();
|
|
expect(replacement.clones[0]!.stop).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("uses the fenced SFU demand prefix without live profiles reactivating upper layers", async () => {
|
|
const { publisher: host, pc } = await publisher();
|
|
await host.acceptSignal(signal({ kind: "layers", activeCount: 1 }));
|
|
expect(
|
|
pc.transceivers[0]!.sender.parameters.encodings.map(
|
|
(encoding) => encoding.active,
|
|
),
|
|
).toEqual([true, false]);
|
|
await host.updateProfile(QUALITY_PROFILES["720p30"]);
|
|
expect(
|
|
pc.transceivers[0]!.sender.parameters.encodings.map(
|
|
(encoding) => encoding.active,
|
|
),
|
|
).toEqual([true, false]);
|
|
await host.acceptSignal(
|
|
signal({
|
|
kind: "layers",
|
|
activeCount: 0,
|
|
connectionId: "retired_connection",
|
|
}),
|
|
);
|
|
expect(
|
|
pc.transceivers[0]!.sender.parameters.encodings.map(
|
|
(encoding) => encoding.active,
|
|
),
|
|
).toEqual([true, false]);
|
|
await host.acceptSignal(signal({ kind: "layers", activeCount: 0 }));
|
|
expect(
|
|
pc.transceivers[0]!.sender.parameters.encodings.map(
|
|
(encoding) => encoding.active,
|
|
),
|
|
).toEqual([false, false]);
|
|
await host.acceptSignal(signal({ kind: "layers", activeCount: 2 }));
|
|
expect(
|
|
pc.transceivers[0]!.sender.parameters.encodings.map(
|
|
(encoding) => encoding.active,
|
|
),
|
|
).toEqual([true, true]);
|
|
expect(FakePc.instances).toHaveLength(1);
|
|
});
|
|
|
|
it("resumes an unsent ICE-restart offer after signaling returns on the same connection", async () => {
|
|
const { publisher: host, pc, send, onDisconnected } = await publisher();
|
|
await host.acceptSignal(
|
|
signal({ description: { type: "answer", sdp: "answer" } }),
|
|
);
|
|
send.mockReturnValue(false);
|
|
pc.state("disconnected");
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(pc.createOffer).toHaveBeenLastCalledWith({ iceRestart: true });
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
send.mockClear();
|
|
send.mockReturnValue(true);
|
|
host.updateConfig({ ...config, revision: 5 });
|
|
expect(send.mock.calls.map(([message]) => message.kind)).toEqual([
|
|
"description",
|
|
"candidate",
|
|
]);
|
|
expect(send.mock.calls[0]![0].revision).toBe(5);
|
|
expect(pc.close).not.toHaveBeenCalled();
|
|
expect(onDisconnected).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
it("keeps a buffer target on SFU tracks, late audio and replacement while resetting automatic", async () => {
|
|
const changed=vi.fn();
|
|
const subscriber=new SfuSubscriber({send:()=>true,onStream:()=>{},onPlaybackBufferStatus:changed});
|
|
cleanups.push(()=>subscriber.disconnect());
|
|
subscriber.setPlaybackBufferTarget(300);
|
|
await subscriber.connect(config);
|
|
const pc=FakePc.instances.at(-1)!;
|
|
const video=new FakeTrack("video");
|
|
const first={track:video,jitterBufferTarget:null as number|null,getStats:async()=>new Map()};
|
|
pc.ontrack?.({track:video,receiver:first});
|
|
expect(first.jitterBufferTarget).toBe(300);
|
|
const audio=new FakeTrack("audio");
|
|
const second={track:audio,jitterBufferTarget:null as number|null,getStats:async()=>new Map()};
|
|
pc.ontrack?.({track:audio,receiver:second});
|
|
expect(second.jitterBufferTarget).toBe(300);
|
|
subscriber.setPlaybackBufferTarget(600);
|
|
const replaced=new FakeTrack("video");
|
|
const third={track:replaced,jitterBufferTarget:null as number|null,getStats:async()=>new Map()};
|
|
pc.ontrack?.({track:replaced,receiver:third});
|
|
expect(third.jitterBufferTarget).toBe(600);
|
|
subscriber.setPlaybackBufferTarget(null);
|
|
expect(third.jitterBufferTarget).toBeNull();expect(second.jitterBufferTarget).toBeNull();
|
|
expect(first.jitterBufferTarget).toBe(600);
|
|
await subscriber.disconnect();expect(changed).toHaveBeenLastCalledWith(null);
|
|
});
|