## Problem and outcome Connection recovery and packet repair could leave stale pictures, missing sound or unreliable remote input. This maintenance release repairs media/route ownership, H.264 negotiation, voice forwarding and Windows input recovery, and makes shared mobile controls and popovers easier to use. ## 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.1 improves sharing recovery, voice playback and remote control, with clearer mobile controls. It keeps the existing 2.x compatibility baseline. - Improve H.264 selection and picture recovery after reconnecting, changing sources or recovering lost packets; keep a working share when a replacement source fails. - Keep audio and room voice continuous, and prevent duplicate sound when switching playback windows. - Improve Windows input recovery and release remote-control permissions when their connection ends. - Keep mobile controls together and popovers usable after layout changes or in short viewports. - Open the appropriate Android update download, including the Gitee ZIP containing the APK. Self-hosted SFU servers refresh public addresses for new connections without a restart. - Add macOS source-thumbnail support. Update the App and self-hosted site together to receive all fixes. Browser settings and existing room data are retained. ### 中文 Piik v2.5.1 改善分享恢复、语音播放与远程控制的稳定性,让手机操作更顺手,沿用现有 2.x 兼容基线。 - 改善 H.264 编码选择,以及重连、切换分享源和丢包后的画面恢复;新分享源切换失败时保留正常分享。 - 保持声音与房间语音连续,避免切换播放窗口时出现双重声音。 - 改善 Windows 输入恢复,并在连接结束时释放远程控制授权。 - 手机控件保持成组,浮层在布局变化或可见高度较小时仍可操作。 - Android 更新打开对应下载入口,Gitee 提供内含 APK 的 ZIP;自部署 SFU 为新连接刷新公网地址,无需重启服务。 - 补齐 macOS 选源缩略图支持。 请一起更新 App 与自部署站点,以获得全部修复。浏览器设置与已有房间数据保留。 ## Validation - Full frontend typecheck, test and production-build acceptance; current Windows App/Server packaging, extracted-file checks and exact served JavaScript verified locally. - Existing Go, vulnerability, native media and controlled-network results retained at their tested revisions. The final production delta from the fully checked candidate is the shared short-viewport popover correction. - The diagnostic report supplied for #502 informed the Windows input fixes. #500 sharing is confirmed working; its missing source previews are implemented. Original-device follow-up remains separate from this release's verified local fixes. ## Compatibility and scope Preserves the published 2.x Browser/server, Native control, capture and SQLite contracts. No 3.0 or iOS implementation or external contributor patch is included. Related: #500, #502, #510, #512.
801 lines
37 KiB
TypeScript
801 lines
37 KiB
TypeScript
import { afterEach, expect, it, vi } from "vitest";
|
|
import type { SignalPayload } from "../src/shared/protocol";
|
|
import type { NativeClient } from "../src/client/native/client";
|
|
import { NativeMediaBridge } from "../src/client/native/media-bridge";
|
|
import { VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS, ViewerPeer } from "../src/client/webrtc/viewer-peer";
|
|
import { EMPTY_METRICS, type PeerSnapshot } from "../src/client/types";
|
|
import type { NativeClientEvent } from "../src/client/native/wire";
|
|
import {
|
|
NativeCapableViewerPeer,
|
|
offerHasNativeVideoCodec,
|
|
} from "../src/client/native/native-viewer-peer";
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
it.each(["commit", "expired", "rpc-expired"].flatMap(outcome =>
|
|
[undefined, 20].map(maxRelayChildren => ({ outcome, maxRelayChildren })),
|
|
))("scopes optional connection preparation to its route: $outcome, backend capacity $maxRelayChildren", async ({ outcome, maxRelayChildren }) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
const client = {
|
|
health: { nativeMedia: { maxRelayChildren } },
|
|
preparePunch: vi.fn(async () => ({ address: "198.51.100.1", port: 40000, step: 1 })),
|
|
runPunch: vi.fn(async () => true), closePunch: vi.fn(async () => undefined),
|
|
receiveOffer: vi.fn(async () => ({ answer: { type: "answer", sdp: "answer" }, audio: false, codec: "vp8" })),
|
|
onEvent: () => () => {}, onClose: () => () => {},
|
|
closeReceiver: vi.fn(async () => {}), closeEdge: vi.fn(async () => {}),
|
|
} as unknown as NativeClient;
|
|
const unavailable = vi.fn(), exhausted = vi.fn(() => true), sent = vi.fn(() => true);
|
|
const peer = new NativeCapableViewerPeer({
|
|
iceServers: [{ urls: ["stun:site.example:3478"] }],
|
|
natPredictionStunUrls: ["stun:site.example:3479", "stun:site.example:3480"],
|
|
}, { sendSignal: sent, sendRestartRequest: () => true, onStream: () => {}, onUpdate: () => {}, onRecoveryExhausted: exhausted },
|
|
{ natPredictionEnabled: true, recoveryOwner: "route" }, async () => client, unavailable, "session", 20);
|
|
// The page accepts a failure only while this peer owns that connection.
|
|
exhausted.mockImplementation(() => peer.hasConnectionId("current"));
|
|
const prepare: SignalPayload = { kind: "punch", connectionId: "current", punch: { phase: "prepare", secret: "42".repeat(32) } };
|
|
try {
|
|
await peer.acceptSignal("parent", prepare);
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(client.preparePunch).toHaveBeenCalledWith("session", "current", expect.anything(), expect.any(String), maxRelayChildren ?? 3);
|
|
await peer.acceptSignal("parent", { kind: "punch", connectionId: "current", punch: {
|
|
phase: "start", prediction: { address: "198.51.100.2", port: 50000, step: 1 },
|
|
} });
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
if (outcome === "expired") await vi.advanceTimersByTimeAsync(3_500);
|
|
if (outcome === "rpc-expired") vi.mocked(client.receiveOffer).mockRejectedValueOnce(new Error("prepared socket expired"));
|
|
await peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current", punched: true,
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
if (outcome === "commit") {
|
|
expect(exhausted).not.toHaveBeenCalled();
|
|
expect(client.receiveOffer).toHaveBeenCalledWith("session", "current", expect.anything(), expect.anything(), maxRelayChildren ?? 3, true);
|
|
await peer.acceptSignal("parent", prepare);
|
|
expect(client.preparePunch).toHaveBeenCalledOnce();
|
|
} else {
|
|
expect(exhausted).toHaveBeenCalledExactlyOnceWith("parent", "current");
|
|
expect(exhausted.mock.results[0].value).toBe(true);
|
|
if (outcome === "expired") expect(client.receiveOffer).not.toHaveBeenCalled();
|
|
}
|
|
} finally { peer.dispose(); }
|
|
});
|
|
|
|
it("uses the offer's STUN destinations for prediction while the next ICE config changes", async () => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
let onEvent!: (event: NativeClientEvent) => void;
|
|
const client = {
|
|
receiveOffer: vi.fn(async () => ({ answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8" })),
|
|
onEvent: (handler: typeof onEvent) => { onEvent = handler; return () => {}; },
|
|
onClose: () => () => {},
|
|
closeReceiver: vi.fn(async () => {}), closeEdge: vi.fn(async () => {}),
|
|
} as unknown as NativeClient;
|
|
const original = {
|
|
iceServers: [{ urls: ["stun:site.example:3478", "stun:other.example:3478"] }],
|
|
natPredictionStunUrls: ["stun:site.example:3479", "stun:site.example:3480"],
|
|
};
|
|
const sent: SignalPayload[] = [];
|
|
const peer = new NativeCapableViewerPeer(original, {
|
|
sendSignal: (_parent, payload) => { sent.push(payload); return true; },
|
|
sendRestartRequest: () => true, onStream: () => {}, onUpdate: () => {},
|
|
}, { natPredictionEnabled: true }, async () => client, () => {}, "session", 2);
|
|
const emit = (index: number, port: number) => onEvent({
|
|
version: 10, type: "edge-candidate", shareId: "session", connectionId: "current",
|
|
candidate: { candidate: `candidate:ns${index} 1 udp 1 203.0.113.7 ${port} typ srflx` },
|
|
});
|
|
const candidates = () => sent.flatMap(payload => payload.kind === "candidate" ? [payload.candidate] : []);
|
|
try {
|
|
await peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current",
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
peer.updateIceConfig({
|
|
...original, iceServers: [{ urls: ["stun:other.example:3478", "stun:site.example:3478"] }],
|
|
});
|
|
emit(3, 40006);
|
|
emit(2, 40003); // Ordinary extra destination must not complete a predicted sequence.
|
|
emit(1, 40000);
|
|
expect(candidates()).toHaveLength(3);
|
|
emit(4, 40012);
|
|
expect(candidates()).toHaveLength(12); // Four ordinary candidates plus the bounded eight predictions.
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each([false, true])("keeps restarted Native candidates after a delayed previous gathering end (prediction=%s)", async (prediction) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
let event!: (event: NativeClientEvent) => void;
|
|
const result = { answer: { type: "answer" as const, sdp: "answer" }, audio: false, codec: "vp8" as const, reused: true };
|
|
const receiveOffer = vi.fn(async () => result);
|
|
const client = {
|
|
health: { nativeMedia: { receiverReuse: true } }, receiveOffer,
|
|
onEvent: (listener: typeof event) => { event = listener; return () => {}; },
|
|
onClose: () => () => {}, closeReceiver: vi.fn(async () => {}), closeEdge: vi.fn(async () => {}),
|
|
} as unknown as NativeClient;
|
|
const sent: SignalPayload[] = [];
|
|
const peer = new NativeCapableViewerPeer({
|
|
iceServers: [{ urls: "stun:site.example:3478" }],
|
|
natPredictionStunUrls: ["stun:site.example:3479", "stun:site.example:3480"],
|
|
}, {
|
|
sendSignal: (_parent, payload) => { sent.push(payload); return true; },
|
|
sendRestartRequest: () => true, onStream: () => {}, onUpdate: () => {},
|
|
}, { natPredictionEnabled: prediction }, async () => client, () => {}, "session", 2);
|
|
const offer = (fragment: string): SignalPayload => ({
|
|
kind: "description", connectionId: "current", description: { type: "offer",
|
|
sdp: `v=0\r\na=ice-ufrag:${fragment}\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n` },
|
|
});
|
|
const emit = (candidate: Extract<NativeClientEvent, { type: "edge-candidate" }>["candidate"]) =>
|
|
event({ version: 10, type: "edge-candidate", shareId: "session", connectionId: "current", candidate });
|
|
try {
|
|
await peer.acceptSignal("parent", offer("first"));
|
|
emit({ candidate: "candidate:ns1 1 udp 1 203.0.113.7 40000 typ srflx", usernameFragment: "previous" });
|
|
let finish!: () => void;
|
|
receiveOffer.mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve(result); }));
|
|
const restarting = peer.acceptSignal("parent", offer("restarted"));
|
|
await vi.waitFor(() => expect(receiveOffer).toHaveBeenCalledTimes(2));
|
|
// The room WS delivered the new offer before an old event already written
|
|
// by the independent App WS. The same physical receiver survives restart.
|
|
emit(null);
|
|
for (let index = 1; index <= 3; index++) {
|
|
emit({ candidate: `candidate:ns${index} 1 udp 1 203.0.113.7 ${50000 + index * 3} typ srflx`, usernameFragment: "next" });
|
|
}
|
|
finish();
|
|
await restarting;
|
|
const candidates = sent.flatMap(payload => payload.kind === "candidate" ? [payload.candidate] : []);
|
|
expect(candidates.filter(candidate => candidate?.candidate && candidate.usernameFragment === "next")).toHaveLength(prediction ? 11 : 3);
|
|
expect(candidates.find(candidate => candidate?.candidate === "")).toMatchObject({ usernameFragment: "previous" });
|
|
expect(candidates).not.toContain(null);
|
|
} finally { peer.dispose(); }
|
|
});
|
|
|
|
it("retires queued candidates when disposed during their delivery", async () => {
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
let finishCandidate!: () => void;
|
|
const accept = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockImplementation(
|
|
async (_parent, payload) => {
|
|
if (payload.kind === "candidate") {
|
|
await new Promise<void>(resolve => { finishCandidate = resolve; });
|
|
}
|
|
},
|
|
);
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => true, sendRestartRequest: () => true,
|
|
onStream: () => undefined, onUpdate: () => undefined,
|
|
},
|
|
{}, async () => null, () => undefined, "session", 2,
|
|
);
|
|
try {
|
|
for (const port of [5000, 5001]) {
|
|
await peer.acceptSignal("parent", {
|
|
kind: "candidate", connectionId: "current",
|
|
candidate: { candidate: `candidate:1 1 UDP 2122260223 192.0.2.1 ${port} typ host` },
|
|
});
|
|
}
|
|
const accepting = peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current",
|
|
description: { type: "offer", sdp: "v=0\r\n" },
|
|
});
|
|
await vi.waitFor(() => expect(accept).toHaveBeenCalledTimes(2));
|
|
peer.dispose();
|
|
finishCandidate();
|
|
await expect(accepting).resolves.toBeUndefined();
|
|
expect(accept).toHaveBeenCalledTimes(2);
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each(["viewer", "route"] as const)("retires a connected Native receiver on control loss (%s)", async (recoveryOwner) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
vi.spyOn(NativeMediaBridge.prototype, "collectMetrics").mockResolvedValue({ ...EMPTY_METRICS });
|
|
vi.spyOn(NativeMediaBridge.prototype, "decodedVideoFrames").mockResolvedValue(null);
|
|
let onEvent!: (event: NativeClientEvent) => void;
|
|
let onClose!: () => void;
|
|
const client = {
|
|
receiveOffer: async () => ({
|
|
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
|
|
}),
|
|
onEvent: (handler: typeof onEvent) => { onEvent = handler; return () => undefined; },
|
|
onClose: (handler: typeof onClose) => { onClose = handler; return () => undefined; },
|
|
closeReceiver: vi.fn(async () => undefined),
|
|
closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
const unavailable = vi.fn();
|
|
const restart = vi.fn(() => true);
|
|
const exhausted = vi.fn(() => true);
|
|
const updates: PeerSnapshot[] = [];
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => true, sendRestartRequest: restart,
|
|
onStream: () => undefined, onUpdate: (value) => updates.push(value),
|
|
onRecoveryExhausted: exhausted,
|
|
},
|
|
{ recoveryOwner }, async () => client, unavailable, "session", 2,
|
|
);
|
|
try {
|
|
await peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current",
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
const connected = {
|
|
version: 10, shareId: "session", connectionId: "current", type: "edge-state", state: "connected",
|
|
} as const;
|
|
onEvent(connected);
|
|
expect(peer.isConnected()).toBe(true);
|
|
expect(peer.nativeSource).not.toBeNull();
|
|
|
|
onClose();
|
|
expect(peer.isConnected()).toBe(false);
|
|
expect(peer.nativeSource).toBeNull();
|
|
expect(updates.at(-1)?.connectionState).toBe("failed");
|
|
// A queued event cannot revive the receiver that owns the dead bridge.
|
|
onEvent(connected);
|
|
onClose();
|
|
expect(peer.isConnected()).toBe(false);
|
|
expect(unavailable).toHaveBeenCalledOnce();
|
|
if (recoveryOwner === "viewer") {
|
|
expect(restart).toHaveBeenCalledExactlyOnceWith("parent", "current", true);
|
|
expect(exhausted).not.toHaveBeenCalled();
|
|
await vi.advanceTimersByTimeAsync(VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS);
|
|
} else {
|
|
expect(restart).not.toHaveBeenCalled();
|
|
}
|
|
expect(exhausted).toHaveBeenCalledExactlyOnceWith("parent", "current");
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each([false, true])("ignores a late Native offer after control loss (disposed=%s)", async (disposeOnFailure) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
let resolveOffer!: (value: Awaited<ReturnType<NativeClient["receiveOffer"]>>) => void;
|
|
const receiveOffer = vi.fn(() => new Promise<Awaited<ReturnType<NativeClient["receiveOffer"]>>>((resolve) => {
|
|
resolveOffer = resolve;
|
|
}));
|
|
let onClose!: () => void;
|
|
const closeReceiver = vi.fn(async () => undefined);
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: () => () => undefined,
|
|
onClose: (handler: typeof onClose) => { onClose = handler; return () => undefined; },
|
|
closeReceiver, closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
const sendSignal = vi.fn(() => true);
|
|
const onStream = vi.fn();
|
|
const restart = vi.fn(() => true);
|
|
const unavailable = vi.fn();
|
|
const updates: PeerSnapshot[] = [];
|
|
let peer!: NativeCapableViewerPeer;
|
|
peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal, sendRestartRequest: restart, onStream,
|
|
onUpdate: (value) => {
|
|
updates.push(value);
|
|
if (disposeOnFailure && value.connectionState === "failed") peer.dispose();
|
|
},
|
|
},
|
|
{}, async () => client, unavailable, "session", 2,
|
|
);
|
|
try {
|
|
const accepting = peer.acceptSignal("parent", {
|
|
kind: "description", connectionId: "current",
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
await vi.waitFor(() => expect(receiveOffer).toHaveBeenCalledOnce());
|
|
onClose();
|
|
resolveOffer({ answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8", reused: false });
|
|
await accepting;
|
|
|
|
expect(updates.at(-1)?.connectionState).toBe("failed");
|
|
expect(peer.isConnected()).toBe(false);
|
|
expect(peer.nativeSource).toBeNull();
|
|
expect(closeReceiver).toHaveBeenCalledWith("session", "current");
|
|
expect(sendSignal).not.toHaveBeenCalled();
|
|
expect(onStream).not.toHaveBeenCalled();
|
|
expect(bridgeStart).not.toHaveBeenCalled();
|
|
expect(unavailable).toHaveBeenCalledOnce();
|
|
expect(restart).toHaveBeenCalledTimes(disposeOnFailure ? 0 : 1);
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each(["reused", "replaced", "answer-lost", "control-lost"])("keeps Native receiver lifetimes coherent through renegotiation (%s)", async (outcome) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
const bridges: NativeMediaBridge[] = [];
|
|
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockImplementation(async function (this: NativeMediaBridge) {
|
|
bridges.push(this);
|
|
return {} as MediaStream;
|
|
});
|
|
let closeControl!: () => void;
|
|
let event!: (event: NativeClientEvent) => void;
|
|
const receiveOffer = vi.fn(async () => ({
|
|
answer: { type: "answer" as const, sdp: "answer-sdp" }, audio: false, codec: "vp8" as const, reused: false,
|
|
}));
|
|
const closeReceiver = vi.fn(async () => undefined);
|
|
const closeEdge = vi.fn(async () => undefined);
|
|
const client = {
|
|
health: { nativeMedia: { receiverReuse: true } }, receiveOffer, closeReceiver, closeEdge,
|
|
onEvent: (listener: typeof event) => { event = listener; return () => {}; },
|
|
onClose: (listener: typeof closeControl) => { closeControl = listener; return () => {}; },
|
|
} as unknown as NativeClient;
|
|
const sendSignal = vi.fn(() => true);
|
|
const onStream = vi.fn();
|
|
const unavailable = vi.fn();
|
|
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
|
|
sendSignal, sendRestartRequest: () => true, onStream, onUpdate: () => {},
|
|
}, {}, async () => client, unavailable, "session", 2);
|
|
const offer = (ice: string): SignalPayload => ({
|
|
kind: "description", connectionId: "current", description: { type: "offer",
|
|
sdp: `v=0\r\na=ice-ufrag:${ice}\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n` },
|
|
});
|
|
try {
|
|
await peer.acceptSignal("parent", offer("first"));
|
|
event({ version: 10, type: "edge-state", shareId: "session", connectionId: "current", state: "connected" });
|
|
const source = peer.nativeSource;
|
|
receiveOffer.mockImplementationOnce(async () => {
|
|
if (outcome === "replaced") {
|
|
// Replacement closes the old local edge before its answer reaches JS.
|
|
(bridges[0] as unknown as { onFailed(): void }).onFailed();
|
|
}
|
|
if (outcome === "control-lost") closeControl();
|
|
return { answer: { type: "answer", sdp: "new-answer-sdp" }, audio: false, codec: "vp8", reused: outcome !== "replaced" };
|
|
});
|
|
if (outcome === "answer-lost") sendSignal.mockReturnValue(false);
|
|
await peer.acceptSignal("parent", offer("restarted"));
|
|
expect(receiveOffer).toHaveBeenCalledTimes(2);
|
|
if (outcome === "control-lost") {
|
|
expect(peer.nativeSource).toBeNull();
|
|
expect(unavailable).toHaveBeenCalledOnce();
|
|
} else {
|
|
expect(closeReceiver).not.toHaveBeenCalled();
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
expect(bridgeStart).toHaveBeenCalledTimes(outcome === "replaced" ? 2 : 1);
|
|
expect(onStream).toHaveBeenCalledTimes(outcome === "replaced" ? 2 : 1);
|
|
expect(peer.nativeSource?.generation).toBe(source!.generation + (outcome === "replaced" ? 1 : 0));
|
|
if (outcome !== "replaced") {
|
|
expect(closeEdge).not.toHaveBeenCalled();
|
|
expect(peer.isConnected()).toBe(true);
|
|
}
|
|
}
|
|
} finally { peer.dispose(); }
|
|
});
|
|
|
|
it("admits one active sending H264 or VP8 video section, not unrelated SDP codec text", () => {
|
|
const video = (codec: string, direction = "sendonly", port = 9, payload = 96) => [
|
|
`m=video ${port} UDP/TLS/RTP/SAVPF ${payload}`,
|
|
`a=${direction}`,
|
|
`a=rtpmap:96 ${codec}/90000`,
|
|
"a=fmtp:96 profile-level-id=42e01f;packetization-mode=1",
|
|
"",
|
|
].join("\r\n");
|
|
expect(offerHasNativeVideoCodec(video("H264"))).toBe(true);
|
|
expect(offerHasNativeVideoCodec(video("VP8"))).toBe(true);
|
|
expect(offerHasNativeVideoCodec(video("VP8", "sendrecv"))).toBe(true);
|
|
expect(offerHasNativeVideoCodec("a=group:BUNDLE 0\r\n" +
|
|
video("VP8", "sendonly", 0) + "a=bundle-only\r\na=mid:0\r\n")).toBe(true);
|
|
expect(offerHasNativeVideoCodec("m=video 9 UDP/TLS/RTP/SAVPF 96 97\r\n" +
|
|
"a=sendonly\r\na=rtpmap:96 H264/90000\r\na=rtpmap:97 VP8/90000\r\n")).toBe(true);
|
|
for (const offer of [
|
|
video("VP8", "recvonly"), video("VP8", "inactive"),
|
|
video("VP8", "sendonly", 0), video("VP8", "sendonly", 9, 97),
|
|
video("VP8", "sendonly", 0) + "a=bundle-only\r\na=mid:0\r\n",
|
|
video("VP9"), video("H264") + video("VP8"),
|
|
"m=audio 9 UDP/TLS/RTP/SAVPF 96\r\na=rtpmap:96 VP8/90000\r\n",
|
|
]) expect(offerHasNativeVideoCodec(offer)).toBe(false);
|
|
});
|
|
|
|
it.each([
|
|
["42e01f", "1", true], ["42c01f", "1", true],
|
|
["4de01f", "1", true], ["58c01f", "1", true],
|
|
["42e00b", "1", true], ["42e033", "1", true], ["42e034", "1", true],
|
|
["42e03c", "1", false],
|
|
["4d001f", "1", false], ["64001f", "1", false], ["42001f", "1", false],
|
|
["42e11f", "1", false], ["42e035", "1", false], ["42e03c", "1", false],
|
|
["42e01f=invalid", "1", false],
|
|
["", "1", false], ["42e01f", "0", false], ["42e01f", "", false],
|
|
])("matches Native H264 forwarding admission: profile=%s, packetization=%s", (profile, mode, supported) => {
|
|
const offer = "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" +
|
|
"a=rtpmap:96 H264/90000\r\n" +
|
|
`a=fmtp:96 profile-level-id=${profile};packetization-mode=${mode}\r\n`;
|
|
expect(offerHasNativeVideoCodec(offer)).toBe(supported);
|
|
});
|
|
|
|
it("sends an unsupported Native format straight to the Browser without failing the App", async () => {
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
const browserSignal = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockResolvedValue();
|
|
const acquire = vi.fn(async () => null);
|
|
const unavailable = vi.fn();
|
|
const restart = vi.fn(() => true);
|
|
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
|
|
sendSignal: () => true, sendRestartRequest: restart,
|
|
onStream: () => undefined, onUpdate: () => undefined,
|
|
}, {}, acquire, unavailable, "session", 2);
|
|
const offer: SignalPayload = { kind: "description", connectionId: "current", description: {
|
|
type: "offer", sdp: "m=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n" +
|
|
"a=rtpmap:96 H264/90000\r\na=fmtp:96 profile-level-id=64001f;packetization-mode=1\r\n",
|
|
}};
|
|
try {
|
|
await peer.acceptSignal("parent", offer);
|
|
expect(browserSignal).toHaveBeenCalledExactlyOnceWith("parent", offer);
|
|
expect(acquire).not.toHaveBeenCalled();
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
expect(restart).not.toHaveBeenCalled();
|
|
} finally { peer.dispose(); }
|
|
});
|
|
|
|
it("does not create a browser backend after deferred native discovery is disposed", async () => {
|
|
let resolveClient: (value: null) => void = () => undefined;
|
|
const nativeClient = new Promise<null>((resolve) => {
|
|
resolveClient = resolve;
|
|
});
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => true,
|
|
sendRestartRequest: () => true,
|
|
onStream: () => undefined,
|
|
onUpdate: () => undefined,
|
|
},
|
|
{},
|
|
() => nativeClient,
|
|
() => undefined,
|
|
"session",
|
|
2,
|
|
);
|
|
const accepted = peer.acceptSignal("parent", {
|
|
kind: "description",
|
|
connectionId: "connection",
|
|
description: {
|
|
type: "offer",
|
|
sdp: [
|
|
"v=0",
|
|
"m=video 9 UDP/TLS/RTP/SAVPF 96",
|
|
"a=sendonly",
|
|
"a=rtpmap:96 H264/90000",
|
|
"",
|
|
].join("\r\n"),
|
|
},
|
|
});
|
|
peer.dispose();
|
|
resolveClient(null);
|
|
await accepted;
|
|
expect(peer.getConnectionIdentity()).toBeNull();
|
|
});
|
|
|
|
it.each(["route", "viewer"] as const)("recovers an answer signaling failure without disabling native (%s)", async (recoveryOwner) => {
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
const receiveOffer = vi.fn(async () => ({
|
|
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
|
|
}));
|
|
const closeReceiver = vi.fn(async () => undefined);
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: () => () => undefined,
|
|
onClose: () => () => undefined,
|
|
closeReceiver,
|
|
closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
let available = true;
|
|
const acquire = vi.fn(async () => available ? client : null);
|
|
const unavailable = vi.fn(() => { available = false; });
|
|
const restart = vi.fn(() => true);
|
|
const exhausted = vi.fn(() => true);
|
|
let signalOnline = false;
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => signalOnline,
|
|
sendRestartRequest: restart,
|
|
onStream: () => undefined,
|
|
onUpdate: () => undefined,
|
|
onRecoveryExhausted: exhausted,
|
|
},
|
|
{ recoveryOwner },
|
|
acquire,
|
|
unavailable,
|
|
"session",
|
|
2,
|
|
);
|
|
const offer = (connectionId: string): SignalPayload => ({
|
|
kind: "description", connectionId,
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
try {
|
|
// A transient room-signaling outage at the answer must not disable
|
|
// Native reception for the session: close only this receiver and run
|
|
// the ordinary recovery path.
|
|
await peer.acceptSignal("parent", offer("first"));
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
expect(peer.nativeSource).toBeNull();
|
|
expect(closeReceiver).toHaveBeenCalledWith("session", "first");
|
|
if (recoveryOwner === "viewer") {
|
|
expect(restart).toHaveBeenCalledWith("parent", "first", true);
|
|
expect(exhausted).not.toHaveBeenCalled();
|
|
} else {
|
|
expect(exhausted).toHaveBeenCalledWith("parent", "first");
|
|
expect(restart).not.toHaveBeenCalled();
|
|
}
|
|
|
|
// With signaling back online, the next offer re-acquires the native path.
|
|
signalOnline = true;
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue(
|
|
new (class {})() as never,
|
|
);
|
|
await peer.acceptSignal("parent", offer("second"));
|
|
expect(acquire).toHaveBeenCalledTimes(2);
|
|
expect(receiveOffer).toHaveBeenCalledTimes(2);
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it("still disables native on a genuine failure after a signaling failure", async () => {
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
let eventHandler: ((event: unknown) => void) | null = null;
|
|
const receiveOffer = vi.fn(async () => ({
|
|
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
|
|
}));
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: (handler: (event: unknown) => void) => {
|
|
eventHandler = handler;
|
|
return () => undefined;
|
|
},
|
|
onClose: () => () => undefined,
|
|
closeReceiver: vi.fn(async () => undefined),
|
|
closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
const unavailable = vi.fn();
|
|
const peer = new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => false,
|
|
sendRestartRequest: () => true,
|
|
onStream: () => undefined,
|
|
onUpdate: () => undefined,
|
|
onRecoveryExhausted: () => true,
|
|
},
|
|
{},
|
|
async () => client,
|
|
unavailable,
|
|
"session",
|
|
2,
|
|
);
|
|
try {
|
|
await peer.acceptSignal("parent", {
|
|
kind: "description",
|
|
connectionId: "first",
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
|
|
// A genuine native failure on the same connection must still disable
|
|
// Native for the session: the signaling path must not have latched the
|
|
// failure state.
|
|
eventHandler!({ shareId: "session", type: "share-ended", failed: true });
|
|
expect(unavailable).toHaveBeenCalledOnce();
|
|
} finally {
|
|
peer.dispose();
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
["route", "initialize"], ["route", "start"],
|
|
["viewer", "initialize"], ["viewer", "start"],
|
|
] as const)("keeps %s bridge %s failure unavailable across replacement peers", async (recoveryOwner, failureStage) => {
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class {
|
|
constructor() { if (failureStage === "initialize") throw new DOMException("Peer unavailable", "NotSupportedError"); }
|
|
close() {}
|
|
});
|
|
const browserSignal = vi.spyOn(ViewerPeer.prototype, "acceptSignal").mockResolvedValue();
|
|
const bridgeStart = vi.spyOn(NativeMediaBridge.prototype, "start").mockRejectedValue(new Error("bridge failed"));
|
|
const receiveOffer = vi.fn(async () => ({
|
|
answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8",
|
|
}));
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: () => () => undefined,
|
|
onClose: () => () => undefined,
|
|
closeReceiver: vi.fn(async () => undefined),
|
|
closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
let available = true;
|
|
const acquire = vi.fn(async () => available ? client : null);
|
|
const unavailable = vi.fn(() => { available = false; });
|
|
const recover = vi.fn(() => {
|
|
expect(available).toBe(false);
|
|
return true;
|
|
});
|
|
const create = () => new NativeCapableViewerPeer(
|
|
{ iceServers: [] },
|
|
{
|
|
sendSignal: () => true,
|
|
sendRestartRequest: recover,
|
|
onStream: () => undefined,
|
|
onUpdate: () => undefined,
|
|
onRecoveryExhausted: recover,
|
|
},
|
|
{ recoveryOwner },
|
|
acquire,
|
|
unavailable,
|
|
"session",
|
|
2,
|
|
);
|
|
const offer = (connectionId: string): SignalPayload => ({
|
|
kind: "description", connectionId,
|
|
description: { type: "offer", sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" },
|
|
});
|
|
const first = create();
|
|
const queued = create();
|
|
try {
|
|
await first.acceptSignal("parent", offer("first"));
|
|
await vi.waitFor(() => expect(unavailable).toHaveBeenCalledOnce());
|
|
expect(recover).toHaveBeenCalledOnce();
|
|
first.dispose();
|
|
await queued.acceptSignal("parent", offer("queued"));
|
|
expect(browserSignal).toHaveBeenCalledOnce();
|
|
const replacement = create();
|
|
try {
|
|
await replacement.acceptSignal("parent", offer("replacement"));
|
|
expect(browserSignal).toHaveBeenCalledTimes(2);
|
|
expect(receiveOffer).toHaveBeenCalledOnce();
|
|
expect(bridgeStart).toHaveBeenCalledTimes(failureStage === "initialize" ? 0 : 1);
|
|
expect(acquire).toHaveBeenCalledTimes(3);
|
|
} finally {
|
|
replacement.dispose();
|
|
}
|
|
} finally {
|
|
first.dispose();
|
|
queued.dispose();
|
|
}
|
|
});
|
|
|
|
it("defers local bridge decoded proof while its prepared Native network edge is disconnected", async () => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
vi.spyOn(NativeMediaBridge.prototype, "collectMetrics").mockResolvedValue({ ...EMPTY_METRICS });
|
|
let finishStats!: (frames: number) => void;
|
|
const stats = new Promise<number>(resolve => { finishStats = resolve; });
|
|
vi.spyOn(NativeMediaBridge.prototype, "decodedVideoFrames").mockReturnValue(stats);
|
|
let event!: (event: NativeClientEvent) => void;
|
|
const client = {
|
|
receiveOffer: vi.fn(async () => ({ answer: { type: "answer", sdp: "answer" }, audio: false, codec: "vp8" })),
|
|
onEvent: (listener: typeof event) => { event = listener; return () => {}; }, onClose: () => () => {},
|
|
closeReceiver: vi.fn(async () => {}), closeEdge: vi.fn(async () => {}),
|
|
} as unknown as NativeClient;
|
|
const decoded = vi.fn(() => true), restart = vi.fn(() => true), unavailable = vi.fn();
|
|
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
|
|
sendSignal: () => true, sendRestartRequest: restart, onStream: () => {}, onUpdate: () => {}, onFirstDecodedFrame: decoded,
|
|
}, { recoveryOwner: "route" }, async () => client, unavailable, "session", 2);
|
|
const state = (value: "connected" | "disconnected") => event({
|
|
version: 10, shareId: "session", connectionId: "prepared", type: "edge-state", state: value,
|
|
});
|
|
try {
|
|
await peer.acceptSignal("host", { kind: "description", connectionId: "prepared", description: { type: "offer",
|
|
sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" } });
|
|
state("connected"); state("disconnected");
|
|
finishStats(1);
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(decoded).not.toHaveBeenCalled();
|
|
state("connected");
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(decoded).toHaveBeenCalledExactlyOnceWith("prepared");
|
|
expect(client.receiveOffer).toHaveBeenCalledOnce();
|
|
expect(restart).not.toHaveBeenCalled();
|
|
expect(unavailable).not.toHaveBeenCalled();
|
|
} finally { peer.dispose(); }
|
|
});
|
|
|
|
it.each(["first", "replacement", "failed-offer"])("keeps committed route recovery and its budget across backend replacement (%s)", async (scenario) => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("window", globalThis);
|
|
vi.stubGlobal("MediaStream", class { getTracks() { return []; } });
|
|
vi.stubGlobal("RTCPeerConnection", class { close() {} });
|
|
vi.spyOn(NativeMediaBridge.prototype, "start").mockResolvedValue({} as MediaStream);
|
|
vi.spyOn(NativeMediaBridge.prototype, "collectMetrics").mockResolvedValue({ ...EMPTY_METRICS });
|
|
vi.spyOn(NativeMediaBridge.prototype, "decodedVideoFrames").mockResolvedValue(null);
|
|
let onEvent!: (event: NativeClientEvent) => void;
|
|
const receiveOffer = vi.fn(async () => ({ answer: { type: "answer", sdp: "v=0\r\n" }, audio: false, codec: "vp8" }));
|
|
const client = {
|
|
receiveOffer,
|
|
onEvent: (fn: typeof onEvent) => { onEvent = fn; return () => undefined; },
|
|
onClose: () => () => undefined,
|
|
closeReceiver: vi.fn(async () => undefined), closeEdge: vi.fn(async () => undefined),
|
|
} as unknown as NativeClient;
|
|
const restart = vi.fn(() => true);
|
|
const exhausted = vi.fn(() => true);
|
|
const options = { recoveryOwner: "route" as const };
|
|
const peer = new NativeCapableViewerPeer({ iceServers: [] }, {
|
|
sendSignal: () => true, sendRestartRequest: restart,
|
|
onStream: () => undefined, onUpdate: () => undefined, onRecoveryExhausted: exhausted,
|
|
}, options, async () => client, () => undefined, "session", 2);
|
|
const offer = (connectionId: string) => ({ kind: "description" as const, connectionId,
|
|
description: { type: "offer" as const, sdp: "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\na=rtpmap:96 VP8/90000\r\n" }});
|
|
const state = (connectionId: string, value: "connected" | "failed") => onEvent({
|
|
version: 10, shareId: "session", connectionId, type: "edge-state", state: value,
|
|
});
|
|
try {
|
|
await peer.acceptSignal("parent", offer("first"));
|
|
state("first", "connected");
|
|
peer.activatePreparedRoute();
|
|
expect(options.recoveryOwner).toBe("route"); // Caller options are not mutable route state.
|
|
const connectionId = scenario === "replacement" ? "replacement" : "first";
|
|
if (scenario === "replacement") {
|
|
await peer.acceptSignal("parent", offer(connectionId));
|
|
state(connectionId, "connected");
|
|
}
|
|
state(connectionId, "failed");
|
|
expect(restart).toHaveBeenCalledExactlyOnceWith("parent", connectionId, false);
|
|
expect(exhausted).not.toHaveBeenCalled();
|
|
await vi.advanceTimersByTimeAsync(VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS);
|
|
expect(restart).toHaveBeenNthCalledWith(2, "parent", connectionId, true);
|
|
|
|
// A new physical ID is the requested rebuild, not a recovered parent.
|
|
const retiredEvent = onEvent;
|
|
if (scenario === "failed-offer") receiveOffer.mockRejectedValueOnce(new Error("receiver unavailable"));
|
|
await peer.acceptSignal("parent", offer("rebuilt"));
|
|
retiredEvent({ version: 10, shareId: "session", connectionId, type: "edge-state", state: "connected" });
|
|
state("rebuilt", "failed");
|
|
expect(restart).toHaveBeenCalledTimes(2);
|
|
expect(exhausted).toHaveBeenCalledExactlyOnceWith("parent", "rebuilt");
|
|
|
|
// Explicit retry owns a new bounded request and must report its outcome.
|
|
expect(peer.requestRecovery(true)).toBe(true);
|
|
await vi.advanceTimersByTimeAsync(VIEWER_AUTOMATIC_RECOVERY_TIMEOUT_MS);
|
|
expect(exhausted).toHaveBeenCalledTimes(2);
|
|
|
|
// Only actual recovery or a different parent gives a fresh budget.
|
|
await peer.acceptSignal("parent", offer("healthy"));
|
|
state("healthy", "connected");
|
|
state("healthy", "failed");
|
|
expect(restart).toHaveBeenNthCalledWith(4, "parent", "healthy", false);
|
|
await peer.acceptSignal("other-parent", offer("other-connection"));
|
|
state("other-connection", "failed");
|
|
expect(restart).toHaveBeenNthCalledWith(5, "other-parent", "other-connection", false);
|
|
} finally { peer.dispose(); }
|
|
});
|