## Problem and outcome / 问题与结果 Piik's media settings were coupled to a small preset list, and using native App capture on a Site required a separate launcher mode. This release separates numeric media requests from presets and bounded runtime admission, remembers successfully applied settings, and lets a running App serve an explicitly approved Site independently of Local/public room startup. The same phase repairs confirmed capture-retirement, ICE discovery, media-recovery and storage failures. P2P-first routing, one room authority and the existing Browser/Native media owners remain. This phase targets **v2.0.0** with incompatible Web/App contracts. The owner authorized publication after final acceptance; the verified package and deployment records own delivery completion. ## Release notes ### 中文 Piik 2.0 扩展了画质设置,简化了 App 与站点的连接,并集中修复采集和断线恢复问题。**本次升级调整了通信协议,App 与所用站点需要一起升级。** #### 新功能与改进 - **自定义画面设置:** 保留三档推荐预设,支持填写分辨率上限、1–240 帧的帧率上限和 0.1–240 Mbps 的视频码率上限。滑动条沿用常用范围,更高数值可直接填写并显示为“自定义”。帧率范围随画幅变化,可请求 1080p240、1440p144、4K60 和超宽画面;输出保留来源比例。 - **自定义音频质量:** 在原有三档音频预设之外,可填写 6–320 kbps 的来源音频码率上限。 - **双端 App 协同连接:** 启用增强 NAT 穿透后,适用的重试可协调双方 App 准备 UDP 连接;首次连接仍走普通 ICE,不适用时继续现有流程。已通过受控网络验证,实际连通性仍取决于双方网络。 - **记住分享设置:** 下次打开时恢复已应用的画面与音频质量。仅用浏览器时按站点保存;通过新版 App 使用时,更换临时公网邀请网址也能保留设置。 - **更直接地连接 App:** 启动页提供本地房间和公网邀请,首次默认选择公网邀请。使用已有站点时,保持 App 运行,在站点点击 **App** 并确认授权即可。App 打开的本地房主页自动获得授权,站点按钮会显示 App 就绪状态。启动页可查看或取消授权;从另一个站点连接并批准,会替换原授权。 - **置顶聊天窗口:** 支持的桌面浏览器可将聊天移入独立置顶窗口,保留当前消息、草稿和阅读位置;关闭窗口后回到原页面。 #### 修复 - **连接与恢复:** 完善备用 STUN 与 NAT 采样信息的处理;重新收集 ICE 候选时刷新网卡地址。修正观众重连的机会计数、本机媒体连接恢复,以及恢复后遗留的发送队列和带宽统计问题。保留视频编码对应的标准重传能力,改善网络地址变化后的画面恢复。 - **采集稳定性:** 修正 Windows 停止采集或预览时的异步资源释放问题,保留采集边框偏好,更快跳过无法正常输出的编码器。采集与应用音频能力按实际接口探测,不再按 Windows 版本号排除;修正 Linux Portal 来源识别和早期采集失败通知,改善摄像头与原生采集的画面比例处理。 - **状态与清理:** 房间失效时及时释放 App 连接和待完成的选源请求;本地或公网房间启动失败时,App 保持待机并保留其他已授权站点的连接;公网邀请启动失败保留底层错误。修正启动页旧查询覆盖新设置的问题,并限制原生连接准备的待完成任务。SFU 诊断区分房主发布和观众接收状态。 - **其他维护:** 收到尚不支持的表情时跳过该效果;修正 SQLite 写入失败后的事务恢复。Gitee 镜像可独立重试,官网交互、指南和依赖同步更新。App 连接失败时提供重试与下载入口;统一选源设置与自定义数值的反馈。减少重复的随机短语,仅在持续等待时定时轮换。 #### 升级须知 **2.0 与 1.x 不能混用。** 自建站点请更新 Server 和连接该站点的 App,并刷新所有分享与观看页面。本地房间或公网邀请用户请停止分享、关闭旧 App,完整解压新版程序包后重新发送邀请链接。 本次不变更房间数据库结构。重启会中断正在进行的分享;麦克风、采集权限和设备选择不会自动恢复。4K60 等设置是输出上限,实际清晰度与帧率取决于来源、设备和网络。macOS/Linux 采集及部分移动设备仍需更多实机反馈。 ### English Piik 2.0 adds more control over sharing quality, simplifies connecting the App to a Site, and fixes capture and connection-recovery failures. **The communication contracts change in this release: update the App and its Site together.** #### Highlights - **Custom picture settings:** Keep the three recommended presets or enter a resolution ceiling, a 1–240 fps limit and a 0.1–240 Mbps video bitrate limit. Sliders retain their familiar ranges; higher entered values are clearly marked as custom. Frame-rate limits depend on picture size, admitting requests such as 1080p240, 1440p144, 4K60 and ultrawide pictures while preserving source proportions. - **Custom audio quality:** Enter a 6–320 kbps source-audio bitrate limit alongside the three existing audio presets. - **Coordinated App connections:** With enhanced NAT traversal enabled, eligible retries can coordinate UDP preparation between two Apps. The first attempt remains ordinary ICE, and ineligible preparation continues through the existing path. Controlled network checks pass; real-world connectivity still depends on both networks. - **Remember sharing settings:** Restore successfully applied picture and audio quality next time. Browser-only use saves settings per site; an updated App can retain them across changing temporary public-invitation addresses. - **Connect the App from a Site:** The launcher offers Local room and Public invite, with Public invite selected on first use. For an existing Site, keep the App running, click **App** on the Site and confirm its authorization. Host pages opened locally by App are authorized automatically, and the Site button reflects verified App readiness. View or revoke approval in the launcher. Connecting and approving another Site replaces the previous approval. - **Always-on-top chat:** Supported desktop browsers can move chat into a separate always-on-top window while retaining messages, drafts and reading position. Closing the window returns chat to the page. #### Fixes - **Connections and recovery:** Improve fallback STUN discovery and NAT survey handling, and refresh interface addresses during ICE gathering. Fix Viewer recovery-opportunity accounting, local media-connection recovery, stale send queues and bandwidth accounting after recovery. Preserve standard video retransmission when selecting a codec to improve picture recovery after network-address changes. - **Capture stability:** Fix asynchronous Windows resource retirement after capture or preview ends, retain the capture-border preference, and reject non-performing encoder candidates earlier. Detect capture and process-audio support through actual APIs rather than Windows-version gates. Correct Linux Portal target identification and early capture-failure delivery; improve source-aspect handling for camera and native capture. - **State and cleanup:** Release App connections and pending source selection when room authority ends. Keep the App on standby and preserve other authorized Site connections when interactive Local/public room startup fails. Retain underlying public-invitation startup errors. Prevent stale launcher reads from replacing newer settings, bound pending native connection-preparation work, and distinguish Host publication from Viewer reception in SFU diagnostics. - **Maintenance:** Skip unsupported incoming reaction effects, recover SQLite transactions after write failures, and retry Gitee mirroring independently. Update website interactions, guides and dependencies; clarify App connection recovery, source-selection settings and custom-value feedback. Reduce repeated playful captions, with timed rotation reserved for ongoing waits. #### Upgrading **2.0 and 1.x cannot be mixed.** For a hosted Site, update its Server and connected Apps, then refresh every Host and Viewer page. For Local rooms or Public invites, stop sharing, close the old App, extract the complete new package and send a fresh invitation. The room database schema is unchanged. Restarting interrupts active shares; microphone activation, capture permission and device selection are not restored automatically. Settings such as 4K60 are output ceilings: actual resolution and frame rate depend on the source, device and network. macOS/Linux capture and some mobile devices still need more physical-device feedback. ## Verification / 验证 - Product candidate: `24a28738241b9012c0476386356a515aab21f1a5`, built as `v2.0.0`. [Final full candidate CI](https://github.com/TNTcraftHIM/Piik/actions/runs/38555494851) covers core validation, vulnerabilities, races, five App packages and both Server/container targets without publishing. Later commits extend race coverage, correct the capture test fixture's inherited Go race-exit delay, and update documentation/staged website screenshots; shipped product code is unchanged. [Additional control/loopback race checks](https://github.com/TNTcraftHIM/Piik/actions/runs/38561191343) use that updated collector. Product shutdown deadlines and test assertions are unchanged. - Local Web acceptance passes **91 files / 1,612 tests**, type checking and production build. Full Go/native checks, Windows capture compilation, five-repeat control regressions, website/documentation build and repository checks pass. Existing documentation-size and bundle-size warnings remain visible. - The Windows candidate's original descriptor, revision and SHA-256 are checked before extraction and packaged Local/control acceptance. All candidate packages pass the release publisher's read-only identity/checksum verification. - Serial Windows native H.264 Host acceptance passes live/paused/custom/4K settings, background/source recovery and stop/re-share. VP8 two-room SFU and H.264 SFU-only checks pass live quality/audio changes, subscription/page-reload recovery and retirement; stopping one room preserves the other room's media. Browser-to-App fanout and App-exit fallback also pass. Gates clean their processes, profiles and listeners. These checks do not establish sustained game/4K performance. - The final network run passes **37 cases and six negative controls**, with **32 actual media outcomes and five unavailable observations**. It covers all Browser/App pairings, IPv6, remapping, STUN backup, outages, quality recovery, healthy siblings and SFU policies. Sequential-NAT App/App preparation delivers media; a mixed sequential case also connects in this run, without a claim of deterministic benefit. Fault controls reject absent faults/frozen video and verify cancellation/cleanup. No public success percentage is inferred. - Twenty Viewer topology acceptance delivers increasing decoded frames to all Viewers, preserves the two-copy bound and recovers from relay loss. Invitation privacy checks find no grant leakage in requests, cookies, persistent storage or logs. Both are bounded synthetic-source checks, not public-network endurance. - Current UI checks cover Chinese/English/visual, both themes and 320/360/768/1366-pixel layouts, numeric limits, source selection, App approval/revocation, architecture downloads and reader navigation. Chat/PiP retains draft/history/scroll and returns to the page on close; retirement and refused opening clean up. Real Host/Viewer UI chat continues after capture stops and while the Host is absent. Film controls, mute/seek/end/replay, mobile containment and pointer-close unloading pass. README stills and the staged launcher now use current navigation. Scoped axe checks report no violations; contrast and physical assistive-technology coverage are not certified. - Physical macOS/Linux capture, limited decoders, mixed HDR displays, mobile permissions and sustained game/4K use retain their [evidence limits](https://github.com/TNTcraftHIM/Piik/blob/ci/gitee-mirror/docs/verification-status.md). Unmatched field reports remain open. Gitee activation and public-domain checks are publication postflight; original v1.9.2 artifact/mirror recovery already passed without remote writes. ## Boundaries and contributor credit / 边界与贡献 The candidate uses Browser/server v24 and Native control v10; capture v7 and SQLite schema 2 are unchanged. Numeric wire values remain separate from codec/allocation admission. H.264/VP8, framework-owned adaptation and automatic P2P-first routing remain; this candidate adds neither codecs, room voice, end-to-end HDR, surround audio nor Magicsock. Local controls confirm specific repairs, not the causes of unmatched user reports or a measured increase in NAT success rate. The STUN report in #471 remains subject to paired endpoint/network evidence. Gitee's separate workflow activation still needs post-merge verification; its original-artifact and anonymous-download path has passed against v1.9.2. The Linux Portal fix from @AkazaAkali in #470 is incorporated with original commit authorship and the co-author trailer below. #462 and #469 propose higher audio rates and 4K; neither patch is merged. Their preset-expansion implementation is superseded by the independently established numeric-media contract, so overlapping functionality alone does not warrant merging or co-authorship. #475 identifies the Linux desktop entry’s missing terminal controls; that defect is independently corrected without accepting tray or Browser-owned process-exit additions. The settings request in #460 is implemented; issue/PR closure remains part of release follow-up. Co-authored-by: AkazaAkalin <478080766@qq.com>
575 lines
24 KiB
TypeScript
575 lines
24 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { BrowserEncodingPool } from "../src/client/media/browser-encoding-pool";
|
|
import { BrowserEncodingProducer } from "../src/client/media/browser-encoding-producer";
|
|
import type { BrowserEncodingOutput } from "../src/client/media/browser-encoding-output";
|
|
import { QUALITY_PROFILES } from "../src/client/media/quality";
|
|
|
|
const codec = { mimeType: "video/VP8", clockRate: 90_000 };
|
|
const profile = QUALITY_PROFILES["1080p30"];
|
|
const source = { kind: "video", readyState: "live", enabled: true, id: "source" } as MediaStreamTrack;
|
|
const producers = new Map<BrowserEncodingProducer, {
|
|
budget: number; bitrate: number; bytes: number; frames: number; fps: number; width: number; height: number; reason: string;
|
|
}>();
|
|
let pool: BrowserEncodingPool;
|
|
|
|
function stats(row: Record<string, unknown>, negotiated: RTCRtpCodec = codec): RTCStatsReport {
|
|
return new Map([
|
|
["video", { id: "video", timestamp: Date.now(), type: "outbound-rtp", kind: "video", codecId: "codec", ...row }],
|
|
["codec", { id: "codec", timestamp: Date.now(), type: "codec", ...negotiated }],
|
|
]) as unknown as RTCStatsReport;
|
|
}
|
|
|
|
function member(budget = 2_000_000) {
|
|
const demand = { budget, codec: { ...codec } as RTCRtpCodec };
|
|
let producerId: string | null = null;
|
|
const select = vi.fn((id: string, _requestKey: () => Promise<void>, selected: () => void,
|
|
accept: (metadata: RTCEncodedVideoFrameMetadata) => boolean) => {
|
|
const [, output] = [...producers].find(([producer]) => producer.id === id)!;
|
|
if (!accept({ width: output.width, height: output.height })) return;
|
|
producerId = id;
|
|
selected();
|
|
});
|
|
const cancelSelection = vi.fn(() => true);
|
|
const encoded = {
|
|
select, cancelSelection, push: vi.fn(), passthrough: vi.fn(() => { producerId = null; }), setPaused: vi.fn(),
|
|
snapshot: () => ({ frames: producerId ? 30 : 0, width: 1920, height: 1080, timestamp: Date.now(), lastProducerId: producerId }),
|
|
} as unknown as BrowserEncodingOutput;
|
|
const connection = { connectionState: "connected", getStats: async () => stats({ targetBitrate: demand.budget }, demand.codec) };
|
|
const fatal = vi.fn();
|
|
const handle = pool.create(source, {} as RTCRtpSender, connection as RTCPeerConnection, profile,
|
|
encoded, async () => true, async () => undefined, fatal)!;
|
|
return { demand, select, cancelSelection, fatal, handle, encoded, producerId: () => producerId };
|
|
}
|
|
|
|
async function sample(count = 1) {
|
|
await vi.advanceTimersByTimeAsync(500 * count);
|
|
}
|
|
|
|
function holdNextProducerStart(): () => void {
|
|
let ready!: () => void;
|
|
const start = vi.mocked(BrowserEncodingProducer.prototype.start).getMockImplementation()!;
|
|
vi.mocked(BrowserEncodingProducer.prototype.start).mockImplementationOnce(async function (this: BrowserEncodingProducer, budget) {
|
|
await start.call(this, budget);
|
|
await new Promise<void>((resolve) => { ready = resolve; });
|
|
});
|
|
return () => ready();
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("RTCRtpSender", { getCapabilities: () => ({ codecs: [codec] }) });
|
|
producers.clear();
|
|
vi.spyOn(BrowserEncodingProducer.prototype, "start").mockImplementation(async function (this: BrowserEncodingProducer, budget) {
|
|
producers.set(this, { budget: budget!, bitrate: budget! / 2, bytes: 0, frames: 0, fps: 30,
|
|
width: 1920, height: 1080, reason: "none" });
|
|
});
|
|
vi.spyOn(BrowserEncodingProducer.prototype, "report").mockImplementation(async function (this: BrowserEncodingProducer) {
|
|
const output = producers.get(this)!;
|
|
output.bytes += output.bitrate / 16;
|
|
output.frames += output.fps / 2;
|
|
return stats({ bytesSent: output.bytes, framesEncoded: output.frames, frameWidth: output.width, frameHeight: output.height,
|
|
qualityLimitationReason: output.reason });
|
|
});
|
|
vi.spyOn(BrowserEncodingProducer.prototype, "update").mockImplementation(async function (this: BrowserEncodingProducer, _profile, budget) {
|
|
producers.get(this)!.budget = budget!;
|
|
});
|
|
vi.spyOn(BrowserEncodingProducer.prototype, "setPaused").mockImplementation(() => undefined);
|
|
vi.spyOn(BrowserEncodingProducer.prototype, "dispose").mockImplementation(() => undefined);
|
|
pool = new BrowserEncodingPool();
|
|
});
|
|
|
|
afterEach(() => {
|
|
pool.dispose();
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
describe("Browser encoding pool ownership", () => {
|
|
it.each(["joining", "active", "changed"])("isolates codec fallback for a %s member from healthy siblings", async (state) => {
|
|
const healthy = member();
|
|
let limited = state === "joining" ? null : member();
|
|
await sample(4);
|
|
const producer = [...producers.keys()][0]!;
|
|
limited ??= member();
|
|
if (state === "changed") {
|
|
limited.demand.codec = { mimeType: "video/H264", clockRate: 90_000,
|
|
sdpFmtpLine: "packetization-mode=1;profile-level-id=42e01f" };
|
|
vi.stubGlobal("RTCRtpSender", { getCapabilities: () => ({ codecs: [codec, limited!.demand.codec] }) });
|
|
} else limited.demand.codec = { ...codec, sdpFmtpLine: "max-fr=15;max-fs=1200" };
|
|
await sample(3);
|
|
|
|
expect(limited.encoded.passthrough).toHaveBeenCalledTimes(1);
|
|
expect(limited.fatal).not.toHaveBeenCalled();
|
|
expect(healthy.producerId()).toBe(producer.id);
|
|
expect(healthy.encoded.passthrough).not.toHaveBeenCalled();
|
|
expect(producer.dispose).not.toHaveBeenCalled();
|
|
const later = member();
|
|
expect(later.handle).not.toBeNull();
|
|
await sample(3);
|
|
expect(later.producerId()).toBe(producer.id);
|
|
});
|
|
|
|
it("pauses a shared producer only when all of its members pause", async () => {
|
|
const first = member(), second = member();
|
|
await sample(4);
|
|
expect(producers.size).toBe(1);
|
|
const producer = [...producers.keys()][0]!;
|
|
|
|
first.handle.setPaused(true);
|
|
expect(producer.setPaused).toHaveBeenLastCalledWith(false);
|
|
second.handle.setPaused(true);
|
|
expect(producer.setPaused).toHaveBeenLastCalledWith(true);
|
|
first.handle.setPaused(false);
|
|
expect(producer.setPaused).toHaveBeenLastCalledWith(false);
|
|
expect(first.producerId()).toBe(second.producerId());
|
|
expect(producer.dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("selects a prepared producer without waiting for another budget sample", async () => {
|
|
const ready = holdNextProducerStart();
|
|
const first = member();
|
|
await sample();
|
|
expect(first.select).not.toHaveBeenCalled();
|
|
ready();
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(first.producerId()).toBe([...producers.keys()][0]!.id);
|
|
});
|
|
|
|
it("keeps a shared encoder through a bitrate spike with unchanged native demand", async () => {
|
|
const first = member(), second = member();
|
|
await sample(4);
|
|
expect(producers.size).toBe(1);
|
|
const [producer, output] = [...producers][0];
|
|
expect(first.producerId()).toBe(producer.id);
|
|
expect(second.producerId()).toBe(producer.id);
|
|
|
|
output.bitrate = output.budget + 16;
|
|
await sample();
|
|
output.bitrate = output.budget / 2;
|
|
await sample(2);
|
|
|
|
expect(producers.size).toBe(1);
|
|
expect(first.select).toHaveBeenCalledTimes(1);
|
|
expect(second.select).toHaveBeenCalledTimes(1);
|
|
expect(producer.dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("updates shared demand in place when all children need a lower rate", async () => {
|
|
const first = member(), second = member();
|
|
await sample(4);
|
|
const [producer, output] = [...producers][0];
|
|
first.demand.budget = second.demand.budget = 500_000;
|
|
await sample(2);
|
|
|
|
expect(producers.size).toBe(1);
|
|
expect(output.budget).toBe(500_000);
|
|
expect(producer.update).toHaveBeenCalledWith(profile, 500_000);
|
|
expect(first.select).toHaveBeenCalledTimes(1);
|
|
expect(second.select).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("gives a weaker child its own rate owner and reunites it after recovery", async () => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [original, output] = [...producers][0];
|
|
weak.demand.budget = 500_000;
|
|
await sample(3);
|
|
|
|
expect(producers.size).toBe(2);
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(weak.producerId()).not.toBe(original.id);
|
|
expect(output.budget).toBe(2_000_000);
|
|
expect(strong.select).toHaveBeenCalledTimes(1);
|
|
|
|
weak.demand.budget = 2_000_000;
|
|
await sample(3);
|
|
expect(weak.producerId()).toBe(original.id);
|
|
expect(producers.size).toBe(2);
|
|
expect(strong.fatal).not.toHaveBeenCalled();
|
|
expect(weak.fatal).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not move a healthy child to a lower-budget output with briefly higher FPS", async () => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [original, originalOutput] = [...producers][0];
|
|
weak.demand.budget = 500_000;
|
|
await sample(3);
|
|
const [candidate, candidateOutput] = [...producers][1];
|
|
|
|
originalOutput.fps = 27;
|
|
candidateOutput.fps = 29;
|
|
await sample(4);
|
|
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(weak.producerId()).toBe(candidate.id);
|
|
expect(strong.select).toHaveBeenCalledTimes(1);
|
|
expect(originalOutput.budget).toBe(2_000_000);
|
|
expect(candidateOutput.budget).toBe(500_000);
|
|
});
|
|
|
|
it("keeps unequal rate owners through scene changes until native demand recovers", async () => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [original, originalOutput] = [...producers][0];
|
|
weak.demand.budget = 500_000;
|
|
await sample(3);
|
|
const [lower] = [...producers][1];
|
|
|
|
// A quiet scene fits both paths, but the shared encoder is still free to
|
|
// consume the stronger child's allocation when motion returns.
|
|
for (const bitrate of [250_000, 1_000_000, 250_000, 1_000_000]) {
|
|
originalOutput.bitrate = bitrate;
|
|
await sample(3);
|
|
expect(weak.producerId()).toBe(lower.id);
|
|
expect(strong.producerId()).toBe(original.id);
|
|
}
|
|
expect(producers.size).toBe(2);
|
|
expect(weak.select).toHaveBeenCalledTimes(2);
|
|
|
|
weak.demand.budget = 2_000_000;
|
|
await sample(3);
|
|
expect(weak.producerId()).toBe(original.id);
|
|
});
|
|
|
|
it("does not admit a new weak child to a quiet higher-rate producer", async () => {
|
|
const strong = member();
|
|
await sample(4);
|
|
const [original, output] = [...producers][0];
|
|
output.bitrate = 250_000;
|
|
await sample(2);
|
|
|
|
const weak = member(500_000);
|
|
await sample(4);
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(weak.producerId()).not.toBe(original.id);
|
|
expect(producers.size).toBe(2);
|
|
expect([...producers.values()][1].budget).toBe(500_000);
|
|
});
|
|
|
|
it("keeps an existing weaker child's encoder when a stronger child joins", async () => {
|
|
const weak = member(1_000_000);
|
|
await sample(4);
|
|
const [original, output] = [...producers][0];
|
|
const strong = member(2_000_000);
|
|
await sample(4);
|
|
output.bitrate = 1_500_000;
|
|
await sample(2);
|
|
|
|
expect(weak.producerId()).toBe(original.id);
|
|
expect(strong.producerId()).not.toBe(original.id);
|
|
expect(output.budget).toBe(1_000_000);
|
|
expect(producers.size).toBe(2);
|
|
});
|
|
|
|
it.each(["rising newcomer", "falling incumbent"])("uses current demand for optional reuse with a %s", async (change) => {
|
|
const first = member(1_000_000), second = member(2_000_000);
|
|
await sample(4);
|
|
const [[original, originalOutput], [candidate, candidateOutput]] = [...producers];
|
|
originalOutput.fps = 27;
|
|
if (change === "falling incumbent") {
|
|
candidateOutput.reason = "bandwidth";
|
|
first.demand.budget = 2_000_000;
|
|
await sample(2);
|
|
second.demand.budget = 1_000_000;
|
|
} else first.demand.budget = 3_000_000;
|
|
candidateOutput.fps = 30;
|
|
candidateOutput.reason = "none";
|
|
candidateOutput.bitrate = second.demand.budget + 100_000;
|
|
await sample(4);
|
|
|
|
expect(first.producerId()).toBe(original.id);
|
|
expect(second.producerId()).toBe(candidate.id);
|
|
expect(originalOutput.budget).toBe(first.demand.budget);
|
|
expect(candidateOutput.budget).toBe(second.demand.budget);
|
|
expect(producers.size).toBe(2);
|
|
});
|
|
|
|
it("shares a group's current demand while its previous budget is being reduced", async () => {
|
|
const first = member(2_000_000);
|
|
await sample(4);
|
|
const [original, output] = [...producers][0];
|
|
first.demand.budget = 1_000_000;
|
|
const second = member(1_000_000);
|
|
await sample(4);
|
|
|
|
expect(first.producerId()).toBe(original.id);
|
|
expect(second.producerId()).toBe(original.id);
|
|
expect(output.budget).toBe(1_000_000);
|
|
expect(producers.size).toBe(1);
|
|
});
|
|
|
|
it.each(["preparation", "recovery frame"])("keeps a necessary downgrade through quiet output during %s", async (stage) => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [original, originalOutput] = [...producers][0];
|
|
let resume!: () => void;
|
|
if (stage === "preparation") resume = holdNextProducerStart();
|
|
else {
|
|
const select = weak.select.getMockImplementation()!;
|
|
weak.select.mockImplementationOnce((...args) => { resume = () => select(...args); });
|
|
}
|
|
weak.demand.budget = 500_000;
|
|
await sample();
|
|
const [candidate, candidateOutput] = [...producers][1];
|
|
candidateOutput.width = 640; candidateOutput.height = 360;
|
|
originalOutput.bitrate = 250_000;
|
|
await sample(2);
|
|
resume();
|
|
await sample(2);
|
|
|
|
expect(vi.mocked(BrowserEncodingProducer.prototype.dispose).mock.contexts).not.toContain(candidate);
|
|
expect(weak.producerId()).toBe(candidate.id);
|
|
expect(strong.producerId()).toBe(original.id);
|
|
originalOutput.bitrate = 1_000_000;
|
|
await sample(3);
|
|
expect(producers.size).toBe(2);
|
|
expect(weak.producerId()).toBe(candidate.id);
|
|
expect(weak.fatal).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["demand recovers", "stronger sibling leaves"])("retires an unnecessary downgrade when %s", async (change) => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [original] = [...producers][0];
|
|
const ready = holdNextProducerStart();
|
|
weak.demand.budget = 500_000;
|
|
await sample();
|
|
const [candidate] = [...producers][1];
|
|
if (change === "demand recovers") weak.demand.budget = 2_000_000;
|
|
else strong.handle.dispose();
|
|
await sample(2);
|
|
ready();
|
|
await sample(2);
|
|
|
|
expect(vi.mocked(BrowserEncodingProducer.prototype.dispose).mock.contexts).toEqual([candidate]);
|
|
expect(weak.producerId()).toBe(original.id);
|
|
expect(producers.size).toBe(2);
|
|
expect(producers.get(original)!.budget).toBe(weak.demand.budget);
|
|
});
|
|
|
|
it("replans a waiting child when another member raises a quiet producer's budget", async () => {
|
|
const ready = holdNextProducerStart();
|
|
const strong = member(), weak = member();
|
|
await sample();
|
|
weak.handle.setPaused(true);
|
|
const [original, output] = [...producers][0];
|
|
output.bitrate = 250_000;
|
|
strong.demand.budget = 4_000_000;
|
|
ready();
|
|
await sample(3);
|
|
expect(output.budget).toBe(4_000_000);
|
|
expect(weak.select).not.toHaveBeenCalled();
|
|
|
|
weak.handle.setPaused(false);
|
|
await sample(4);
|
|
expect(weak.producerId()).not.toBe(original.id);
|
|
expect(weak.producerId()).toBe([...producers.keys()][1].id);
|
|
expect(weak.select).toHaveBeenCalledTimes(1);
|
|
expect(strong.producerId()).toBe(original.id);
|
|
});
|
|
|
|
it.each([
|
|
{ currentFps: 30, candidateFps: 32, improves: false },
|
|
{ currentFps: 20, candidateFps: 30, improves: true },
|
|
])("compares $currentFps to $candidateFps fps within the Host ceiling", async ({ currentFps, candidateFps, improves }) => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [original, originalOutput] = [...producers][0];
|
|
weak.demand.budget = 500_000;
|
|
await sample(3);
|
|
const [candidate, candidateOutput] = [...producers][1];
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(weak.producerId()).toBe(candidate.id);
|
|
|
|
originalOutput.fps = currentFps;
|
|
candidateOutput.fps = candidateFps;
|
|
weak.demand.budget = 2_000_000;
|
|
await sample(4);
|
|
|
|
const selected = improves ? candidate : original;
|
|
expect(strong.producerId()).toBe(selected.id);
|
|
expect(weak.producerId()).toBe(selected.id);
|
|
expect(strong.select).toHaveBeenCalledTimes(improves ? 2 : 1);
|
|
expect(weak.select).toHaveBeenCalledTimes(improves ? 2 : 3);
|
|
expect(vi.mocked(BrowserEncodingProducer.prototype.dispose).mock.contexts)
|
|
.toEqual([improves ? original : candidate]);
|
|
});
|
|
|
|
it.each([
|
|
{ change: "frame rate", output: { fps: 10 } },
|
|
{ change: "dimensions", output: { width: 1280, height: 720 } },
|
|
{ change: "bitrate", output: { bitrate: 3_000_000 } },
|
|
{ change: "native limitation", output: { reason: "bandwidth" } },
|
|
])("rechecks a pending improvement's $change before selection", async ({ output }) => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [original, originalOutput] = [...producers][0];
|
|
weak.demand.budget = 500_000;
|
|
await sample(3);
|
|
const [candidate, candidateOutput] = [...producers][1];
|
|
|
|
originalOutput.fps = 20;
|
|
weak.demand.budget = 2_000_000;
|
|
await sample();
|
|
expect(candidateOutput.budget).toBe(2_000_000);
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(weak.producerId()).toBe(candidate.id);
|
|
|
|
Object.assign(candidateOutput, output);
|
|
await sample();
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(strong.select).toHaveBeenCalledTimes(1);
|
|
expect(weak.fatal).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["key dimensions", "quiet current", "unknown current", "sampled limitation", "budget", "target demand", "profile"])(
|
|
"rejects an optional handoff when %s changes while waiting for its key", async (change) => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [original, originalOutput] = [...producers][0];
|
|
weak.demand.budget = 500_000;
|
|
await sample(3);
|
|
const [candidate, candidateOutput] = [...producers][1];
|
|
let accept!: (metadata: RTCEncodedVideoFrameMetadata) => boolean;
|
|
strong.select.mockImplementationOnce((_id, _key, _commit, validate) => { accept = validate; });
|
|
originalOutput.fps = 20;
|
|
weak.demand.budget = 2_000_000;
|
|
await sample(2);
|
|
expect(accept).toBeDefined();
|
|
expect(strong.producerId()).toBe(original.id);
|
|
|
|
if (change === "sampled limitation") { candidateOutput.reason = "bandwidth"; await sample(); }
|
|
if (change === "quiet current") { originalOutput.fps = 0; await sample(); }
|
|
if (change === "unknown current") {
|
|
vi.spyOn(original, "report").mockResolvedValueOnce(new Map() as unknown as RTCStatsReport);
|
|
await sample();
|
|
}
|
|
if (change === "budget") { strong.demand.budget = 500_000; await sample(); }
|
|
if (change === "target demand") { weak.demand.budget = 500_000; await sample(); }
|
|
if (change === "profile") await strong.handle.updateProfile({ ...profile, resolution: { width: 1280, height: 720 } });
|
|
const key = ["key dimensions", "quiet current", "unknown current"].includes(change)
|
|
? { width: 960, height: 540 } : { width: 1920, height: 1080 };
|
|
expect(accept(key)).toBe(false);
|
|
// No pending reference may keep a rejected producer alive after its real
|
|
// user leaves, nor may the healthy current producer have been retired.
|
|
weak.handle.dispose();
|
|
expect(vi.mocked(BrowserEncodingProducer.prototype.dispose).mock.contexts).toEqual([candidate]);
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(strong.fatal).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("accepts a necessary lower-resolution handoff at the recovery frame", async () => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const original = [...producers.keys()][0]!;
|
|
let accept!: (metadata: RTCEncodedVideoFrameMetadata) => boolean, commit!: () => void;
|
|
weak.select.mockImplementationOnce((_id, _key, selected, validate) => { accept = validate; commit = selected; });
|
|
weak.demand.budget = 500_000;
|
|
await sample(3);
|
|
expect(accept({ width: 320, height: 180 })).toBe(true);
|
|
commit();
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(original.dispose).not.toHaveBeenCalled();
|
|
expect(weak.fatal).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("retains the owner of an accepted recovery frame until its write completes", async () => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const [, originalOutput] = [...producers][0];
|
|
weak.demand.budget = 500_000;
|
|
await sample(3);
|
|
const [candidate] = [...producers][1];
|
|
const select = strong.select.getMockImplementation()!;
|
|
let complete!: () => void;
|
|
strong.select.mockImplementationOnce((id, key, selected, accept) => select(id, key, () => {
|
|
complete = selected;
|
|
strong.cancelSelection.mockReturnValue(false);
|
|
}, accept));
|
|
originalOutput.fps = 20;
|
|
weak.demand.budget = 2_000_000;
|
|
await sample(2);
|
|
expect(complete).toBeDefined();
|
|
weak.demand.budget = 500_000;
|
|
await sample(2);
|
|
weak.handle.dispose();
|
|
expect(vi.mocked(BrowserEncodingProducer.prototype.dispose).mock.contexts).not.toContain(candidate);
|
|
complete();
|
|
await sample(2);
|
|
expect(strong.producerId()).toBe(candidate.id);
|
|
expect(strong.select).toHaveBeenCalledTimes(2);
|
|
expect(strong.fatal).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("starts protection at committed output, ignoring retired selection callbacks", async () => {
|
|
const begin = vi.spyOn(BrowserEncodingProducer.prototype, "beginOutput");
|
|
const first = member();
|
|
let selected: (() => void) | undefined;
|
|
first.select.mockImplementation((_id, _requestKey, commit) => { selected = commit; });
|
|
await sample(3);
|
|
expect(selected).toBeDefined();
|
|
expect(begin).not.toHaveBeenCalled();
|
|
selected!();
|
|
expect(begin).toHaveBeenCalledOnce();
|
|
|
|
const late = member();
|
|
let retired: (() => void) | undefined;
|
|
late.select.mockImplementation((_id, _requestKey, commit) => { retired = commit; });
|
|
await sample(2);
|
|
expect(retired).toBeDefined();
|
|
late.handle.dispose();
|
|
retired!();
|
|
expect(begin).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("rechecks a ready handoff after applying a falling budget, without another stats tick", async () => {
|
|
const strong = member(), weak = member();
|
|
await sample(4);
|
|
const original = [...producers.keys()][0]!;
|
|
const ready = holdNextProducerStart();
|
|
weak.demand.budget = 500_000;
|
|
await sample();
|
|
const candidate = [...producers.keys()][1]!;
|
|
let complete!: () => void;
|
|
vi.mocked(candidate.update).mockImplementationOnce(async (_profile, budget) => {
|
|
await new Promise<void>((resolve) => { complete = resolve; });
|
|
producers.get(candidate)!.budget = budget;
|
|
});
|
|
weak.demand.budget = 100_000;
|
|
await sample();
|
|
ready();
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(candidate.update).toHaveBeenCalledWith(profile, 100_000);
|
|
expect(weak.producerId()).toBe(original.id);
|
|
complete();
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(weak.producerId()).toBe(candidate.id);
|
|
expect(strong.producerId()).toBe(original.id);
|
|
expect(producers.get(original)!.budget).toBe(2_000_000);
|
|
});
|
|
|
|
it.each(["failed", "retired"])("does not install a %s budget update's candidate", async (outcome) => {
|
|
member();
|
|
const weak = member();
|
|
await sample(4);
|
|
const ready = holdNextProducerStart();
|
|
weak.demand.budget = 500_000;
|
|
await sample();
|
|
const candidate = [...producers.keys()][1]!;
|
|
let resolve!: () => void, reject!: (error: Error) => void;
|
|
vi.mocked(candidate.update).mockImplementationOnce(() => new Promise<void>((yes, no) => { resolve = yes; reject = no; }));
|
|
weak.demand.budget = 100_000;
|
|
await sample();
|
|
ready();
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
const selections = weak.select.mock.calls.length;
|
|
if (outcome === "retired") { weak.handle.dispose(); resolve(); }
|
|
else reject(new Error("encoder settings failed"));
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(weak.select).toHaveBeenCalledTimes(selections);
|
|
expect(weak.fatal).not.toHaveBeenCalled();
|
|
});
|
|
});
|