Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
fix(media): restore native quality adaptation (#257)
AAA31d8b354c08f
diff --git a/AGENTS.md b/AGENTS.mdindex 15349d6b..4815a0ac 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -4,9 +4,10 @@- Every task and action in this repository must follow the complete repo-tracked [`stop-that-shit` skill](./.agents/skills/stop-that-shit/SKILL.md). Read it before work; that file is the Screener authority for generic task boundaries, and any installed copy must stay synchronized with it rather than becoming a divergent variant.- Core summary: within higher-priority instructions, the latest explicit user decision defines the task; take only requested actions and proven necessary consequences, and do not treat review/research/implementation as authority for implementation/deployment/cleanup beyond its task type. Broad words such as improve or optimize add no unnamed scope. Prefer standards and one owning invariant over example-specific mechanisms, while preserving unrelated work and necessary callers/tests/security. Reconstruct each deliverable from the accepted current result so it stands alone without rejected alternatives, process narration, or modification traces; inspect only the pending changes and report the result with completion evidence. The full skill governs when this summary is incomplete.-- Highest priority for repository changes: before implementation, cleanup, or deployment, settle the meaning against the whole product model and evidence, challenge contradictions or needless complexity, and write the accepted decision to its owning truth documents. Never turn a partial interpretation into code or a branch.+- Before a material product-contract, route-model, security, infrastructure, or irreversible change, settle the meaning against the whole product model and evidence, challenge contradictions or needless complexity, and update its single owning truth document. An ordinary scoped implementation or bug fix does not require a truth checkpoint unless it actually changes durable semantics or a current production/execution snapshot.- Until the owner explicitly declares a public release, maintain only the current internal product contract. Do not preserve backward or forward compatibility, legacy wire/config aliases, dual parsers or writers, translators, deprecated APIs, migration shims, or tests whose only consumer is an older release. Upgrade the private deployment atomically, reject stale clients before authority, delete replaced surfaces, and use Git history for rollback. Reassess compatibility only when public release requirements are explicitly opened.-- Before dependent work starts, update the single actual owner among requirement, design, ADR or research, and update `docs/project-memory.md` or `docs/status.md` only when its snapshot materially changes. Do not create parallel owners or mirror source details across documents. Checkpoint the consistent truth in Git; chat is not durable truth.+- Use the lean path by default for ordinary scoped work: inspect the affected code and owner, make the smallest change, run focused checks, inspect the diff, stage the requested files, and report. Do not automatically expand a small change into broad research, multiple truth-document edits, a full test suite, independent reviews, PR/merge, deployment, worktree cleanup, or a release postflight. Use the full integration/release path only when the owner explicitly asks for it or when closing a major phase or changing a public contract, route/security model, infrastructure, persistent/irreversible state, or release boundary.+- When durable semantics do change, update the single actual owner among requirement, design, ADR or research, and update `docs/project-memory.md` or `docs/status.md` only when its snapshot materially changes. Do not create parallel owners or mirror source details across documents. Ordinary UI details, self-evident code behavior, one-off fixes, routine validation, and completed history stay in code, tests, pull requests, and Git.- If semantics remain disputed, record the hold in `docs/todo.md` and freeze only dependent work. Do not encode a guess as accepted truth.- Queue new observations in their owner and continue the active milestone unless the user requests immediate investigation or the evidence reveals a P0 blocker.@@ -25,6 +26,7 @@- Every non-server endpoint uses one server-authoritative steady outbound media-copy cap: default `2`, configurable as `1`, `2`, or `3`. A peer child or the Host's single SFU publication consumes one slot; upstream receive is free, and SFU subscriber egress is accounted at the server. Browser role, UA, visibility, and client advertisement do not create another tier.- The accepted route model is one committed graph, one event-driven reconciliation loop, and at most one room-serial child operation. That operation owns one deterministic candidate list/cursor, one current candidate with its reservations, and one total deadline; its exact child commits on the first newly decoded frame. Join/waiting, child reparent, relay ingress repair with subtree retention, confirmed departure, and effective-capacity reduction all use this operation. A failed exact candidate is already tried for that operation, so other direct parents come first and SFU is the bounded suffix; no persistent parent blacklist is created.- WebRTC and LiveKit own ICE/DTLS/consent, congestion control, transient reconnect, and SFU stream state. Screener does not add all-pairs endpoint probing, parent-wide quality inference, a weighted route score, periodic rebalancing, or an independent depth cap. SFU is one Host publication with per-Viewer subscriptions, and endpoint overlap plus SFU resources remain independently admitted and bounded. Any future strict-firewall transport must be accepted as a LiveKit-internal capability from real evidence, not added as another application route candidate.+- WebRTC and LiveKit also own media-quality adaptation, bandwidth estimation, representation/layer selection, and recovery. Screener may express standard content intent, user-selected ceilings, codec choice, and documented component options, but it does not invent or maintain an application resolution/FPS/bitrate ladder, representation formula, quality score, hysteresis loop, periodic media controller, or manual SFU selector. Browser game-screen video uses the standard `contentHint = "motion"`; do not silently unset it or replace native adaptation unless the owner explicitly accepts a primary-source-supported mature alternative. Prefer pinned component defaults over hand-built SFU layers.## 4. Canonical Repository And Integration@@ -44,7 +46,7 @@## 6. Engineering Defaults- Research non-trivial design, implementation, and bug fixes from current primary sources. Record durable findings and license boundaries under `docs/research/`.-- Add tests and independent review in proportion to risk. Batch expensive browser, network, endurance, and deployment checks at acceptance boundaries; use reproducible WebRTC measurements for performance claims.+- Add focused tests in proportion to the changed risk. Full-suite tests, independent review, expensive browser/network/endurance checks, and deployment validation belong at an explicitly requested or major acceptance boundary; use reproducible WebRTC measurements for performance claims.- Keep scripts and hooks deterministic, fast, cross-platform, and CI-runnable.- Support Windows, macOS, and Linux; avoid absolute paths and OS-specific separators. Text files use LF, and new filenames use ASCII unless an established user-facing convention requires otherwise.- Before finishing material work, inspect Git status, report untracked project artifacts, and stage requested files unless told otherwise.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ff0c6c5e..85ad25eb 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1,17 +1,27 @@# Contributing-## Normal Workflow--1. Start from the canonical repository root on an up-to-date `main` with a clean working tree. Do not keep `main` checked out in an auxiliary worktree; preserve any overlapping user changes explicitly before restoring the canonical root.-2. Create one short-lived branch for one coherent change. Use `feat/`, `fix/`, `docs/`, `refactor/`, `test/`, `chore/`, or `spike/` followed by a short description.-3. For non-trivial design, implementation, or bug fixing, inspect the repository and research current primary sources before changing code. Record durable findings under `docs/research/`.-4. Reconcile the requested outcome against the whole current product model and conflicting evidence. Before implementation, update every affected owning requirement/design/ADR/research document and current memory/status, replace stale current text, and checkpoint that nonvolatile truth in Git. If semantics remain disputed, record a hold and stop dependent implementation.-5. Implement from that checkpoint under the repo-tracked [`stop-that-shit` skill](./.agents/skills/stop-that-shit/SKILL.md). Add tests in proportion to risk, and keep operational/current-truth updates in the same coherent pull request when implementation changes source facts.-6. Run `sh scripts/check-project-state.sh` on macOS/Linux/Git Bash or `./scripts/check-project-state.ps1` on PowerShell, plus `npm run check` and any relevant manual browser/network checks. Record this local evidence in the pull request; feature branches and pull requests use local gates, while GitHub Actions are reserved for `main` integration, releases, and explicit manual runs. Do not retry zero-step or infrastructure failures.-7. Merge an accepted truth checkpoint before dependent candidates. Rebase or rebuild a retained candidate from that main once, keeping main's owning truth on conflicts and transplanting only approved scoped code, tests, and new facts. Make focused commits using `type(scope): summary` where practical, then push the branch.- Create any new implementation branch or parallel worktree from that exact canonical `main` commit, never from an older candidate or auxiliary worktree.-8. Open a pull request using the repository template. Resolve review comments and required local checks before merging.-9. Prefer squash merge for a single coherent change; preserve separate commits when they carry independently useful history. Delete the merged branch.+## Lean Workflow++This is the default for an ordinary scoped implementation or bug fix.++1. Start from the canonical repository root on a clean, current `main`; preserve unrelated user work.+2. Inspect the affected code, current owner, and reachable evidence. Research primary sources only when the issue is non-trivial or component behavior is uncertain.+3. Make the smallest coherent change under the repo-tracked [`stop-that-shit` skill](./.agents/skills/stop-that-shit/SKILL.md).+4. Run the focused tests or checks that exercise the changed behavior, inspect the pending diff, stage requested files, and report the result and evidence.++Do not automatically create a truth checkpoint, edit status/memory, run `npm run check`, request independent reviews, open or merge a pull request, deploy, or clean branches/worktrees for every small change. Do not record ordinary UI details, self-evident implementation, one-off fixes, routine test output, or completed history in long-lived truth documents.++## Full Integration And Release Workflow++Use this path only when the owner explicitly requests it or when closing a major phase or changing a public contract, route/security model, infrastructure, persistent/irreversible state, or release boundary.++1. Create one short-lived branch/worktree from exact canonical `main`; use `feat/`, `fix/`, `docs/`, `refactor/`, `test/`, `chore/`, or `spike/` followed by a short description.+2. Update only the single durable owner for changed semantics and any materially changed current snapshot. If semantics remain disputed, record a hold and stop dependent work.+3. Implement and run repository hygiene, `npm run check`, the relevant browser/network gates, and review in proportion to the whole acceptance boundary.+4. Merge an accepted truth checkpoint before dependent candidates. Rebase or rebuild a retained candidate from that exact `main` once, preserving main's owning truth on conflicts and transplanting only approved scoped code, tests, and new facts.+5. Open the pull request, resolve required review/checks, merge, deploy when authorized, perform scoped postflight, then audit references and reparse safety before cleanup.++Prefer squash merge for one coherent change and preserve separate commits only when they carry independently useful history.Direct commits to `main` are reserved for an explicit user-approved exception. Never force-push shared branches or rewrite shared history without explicit approval.@@ -31,7 +41,7 @@ Clean up worktrees and branches only after semantic review and integration are cA pull request should explain the problem, the chosen design, verification performed, user-visible or operational effects, and remaining risks.-Changes are not complete when only code is updated. Durable changes must update the relevant documentation and current-memory snapshot in the same pull request.+Durable semantic or current-snapshot changes must update their single owner in the same integration boundary. Ordinary implementation and bug fixes may be complete with code plus focused evidence.## Local Hooksdiff --git a/src/client/media/quality.ts b/src/client/media/quality.tsindex c5796d5e..dc05bfd3 100644--- a/src/client/media/quality.ts+++ b/src/client/media/quality.ts@@ -78,9 +78,6 @@ export const SCREEN_AUDIO_BITRATES = {} as const satisfies Record<ScreenAudioQuality, number>;export const SCREEN_AUDIO_RECEIVE_MAX_BITRATE =SCREEN_AUDIO_BITRATES["very-high"];-export const SCREEN_SHARE_LOW_SCALE = 2;-const SCREEN_SHARE_LOW_MAX_FRAMERATE = 30;-const SCREEN_SHARE_LOW_MIN_BITRATE = 150_000;export interface VideoSenderParameterValues {maxBitrate: number | null;@@ -114,21 +111,6 @@ export function screenAudioBitrate(return SCREEN_AUDIO_BITRATES[resolveScreenAudioQuality(quality)];}-export function screenShareLowFramerate(profile: QualityProfile): number {- return Math.min(profile.maxFramerate, SCREEN_SHARE_LOW_MAX_FRAMERATE);-}--export function screenShareLowBitrate(profile: QualityProfile): number {- const lowFramerate = screenShareLowFramerate(profile);- return Math.max(- SCREEN_SHARE_LOW_MIN_BITRATE,- Math.floor(- (profile.maxBitrate * lowFramerate) /- (SCREEN_SHARE_LOW_SCALE ** 2 * profile.maxFramerate),- ),- );-}-export function qualitySettingsEqual(left: QualitySettings,right: QualitySettings,@@ -214,6 +196,7 @@ export async function captureDisplay(stream.getTracks().forEach((track) => track.stop());throw new Error("浏览器没有返回可分享的视频轨道");}+ videoTrack.contentHint = "motion";for (const audioTrack of stream.getAudioTracks()) {audioTrack.contentHint = "music";}@@ -322,7 +305,6 @@ export async function configureVideoSender(parameters.encodings = [{}];}// Pinned LiveKit orders simulcast encodings by increasing spatial resolution.- // Its lower encoding remains SDK-owned so Dynacast cannot race this write.const encodingIndex = parameters.encodings.length - 1;parameters.encodings[encodingIndex]!.maxBitrate = profile.maxBitrate;parameters.encodings[encodingIndex]!.maxFramerate = profile.maxFramerate;diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.tsindex 93a85394..2e94acdf 100644--- a/src/client/sfu/publisher.ts+++ b/src/client/sfu/publisher.ts@@ -9,13 +9,9 @@ import {audioSenderParameterWarning,configureScreenAudioSender,configureVideoSender,- QUALITY_RESOLUTIONS,resolveScreenAudioQuality,screenAudioQualityEqual,screenAudioBitrate,- screenShareLowBitrate,- screenShareLowFramerate,- SCREEN_SHARE_LOW_SCALE,senderParameterWarning,videoQualitySettingsEqual,type AudioSenderParameterReadback,@@ -56,11 +52,6 @@ interface PublishedTrack {rawTrack: MediaStreamTrack;}-interface PublishedVideoOptionsState {- publication: TrackPublishOptions | undefined;- track: TrackPublishOptions | undefined;-}-interface PublishedVideoConfiguration {readback: VideoSenderParameterReadback;warning: string | null;@@ -197,7 +188,7 @@ export class SfuPublisher {room,videoTrack,sdk.Track.Source.ScreenShare,- videoPublishOptions(sdk, profile, videoTrack),+ videoPublishOptions(profile),);if (!this.owns(room, generation)) {return false;@@ -206,7 +197,6 @@ export class SfuPublisher {const videoConfiguration = await configurePublishedVideo(video,profile,- sdk,() => this.owns(room, generation),);if (!videoConfiguration || !this.owns(room, generation)) {@@ -340,18 +330,11 @@ export class SfuPublisher {const previousAudio = this.audio;let videoReplaceAttempted = false;let audioReplaceAttempted = false;- let previousVideoOptions: PublishedVideoOptionsState | null = null;let audioConfiguration: PublishedAudioConfiguration | null = null;let audioWarning: string | null = null;this.stopStats();try {- previousVideoOptions = retainPublishedVideoOptions(- previousVideo,- profile,- sdk,- nextVideoTrack,- );videoReplaceAttempted = true;await replacePublishedTrack(previousVideo, nextVideoTrack);if (!this.owns(room, generation)) {@@ -409,7 +392,6 @@ export class SfuPublisher {const videoConfiguration = await configurePublishedVideo(previousVideo,profile,- sdk,() => this.owns(room, generation),);if (!videoConfiguration || !this.owns(room, generation)) {@@ -436,9 +418,6 @@ export class SfuPublisher {if (!this.owns(room, generation)) {return false;}- if (previousVideoOptions) {- restorePublishedVideoOptions(previousVideo, previousVideoOptions);- }const failureWarning = "切换 SFU 分享来源失败";// A rejected publish/unpublish may have changed server state without@@ -466,7 +445,6 @@ export class SfuPublisher {const videoConfiguration = await configurePublishedVideo(previousVideo,previousVideoProfile,- sdk,() => this.owns(room, generation),);if (!videoConfiguration || !this.owns(room, generation)) {@@ -553,7 +531,6 @@ export class SfuPublisher {const configured = await configurePublishedVideo(video,profile,- sdk,() =>this.owns(room, generation) &&requestedRevision === this.profileRevision &&@@ -585,7 +562,6 @@ export class SfuPublisher {const rolledBack = await configurePublishedVideo(video,previousVideoProfile,- sdk,() =>this.owns(room, generation) &&requestedRevision === this.profileRevision &&@@ -1130,7 +1106,6 @@ async function unpublishTrack(room: Room, published: PublishedTrack): Promise<voasync function configurePublishedVideo(published: PublishedTrack,profile: QualityProfile,- sdk: LiveKit,ownsPublication: () => boolean,): Promise<PublishedVideoConfiguration | null> {const videoTrack = published.publication.videoTrack;@@ -1153,54 +1128,19 @@ async function configurePublishedVideo(}return null;}- retainPublishedVideoOptions(- published,- profile,- sdk,- videoTrack.mediaStreamTrack,- );+ const retainedPublishOptions = {+ ...published.publication.options,+ ...videoTrack.publishOptions,+ ...videoPublishOptions(profile),+ };+ published.publication.options = retainedPublishOptions;+ videoTrack.publishOptions = retainedPublishOptions;return {readback,warning: senderParameterWarning(readback),};}-function retainPublishedVideoOptions(- published: PublishedTrack,- profile: QualityProfile,- sdk: LiveKit,- track: MediaStreamTrack,-): PublishedVideoOptionsState {- const videoTrack = published.publication.videoTrack;- if (!videoTrack) {- throw new Error("SFU publication has no local video track");- }- const previous = {- publication: published.publication.options,- track: videoTrack.publishOptions,- };- const retained = {- ...published.publication.options,- ...videoTrack.publishOptions,- ...videoPublishOptions(sdk, profile, track),- };- published.publication.options = retained;- videoTrack.publishOptions = retained;- return previous;-}--function restorePublishedVideoOptions(- published: PublishedTrack,- previous: PublishedVideoOptionsState,-): void {- const videoTrack = published.publication.videoTrack;- if (!videoTrack) {- throw new Error("SFU publication has no local video track");- }- published.publication.options = previous.publication;- videoTrack.publishOptions = previous.track;-}-async function configurePublishedAudio(published: PublishedTrack,sender: RTCRtpSender,@@ -1274,15 +1214,7 @@ function mergeQualityWarnings(...warnings: Array<string | null>): string | nullreturn present.length > 0 ? present.join(";") : null;}-function videoPublishOptions(- sdk: LiveKit,- profile: QualityProfile,- track: MediaStreamTrack,-): TrackPublishOptions {- const requestedResolution = QUALITY_RESOLUTIONS[profile.resolution];- const settings = track.getSettings();- const sourceWidth = settings.width ?? requestedResolution.width;- const sourceHeight = settings.height ?? requestedResolution.height;+function videoPublishOptions(profile: QualityProfile): TrackPublishOptions {return {backupCodec: false,videoCodec: "vp8",@@ -1290,14 +1222,6 @@ function videoPublishOptions(maxBitrate: profile.maxBitrate,maxFramerate: profile.maxFramerate,},- screenShareSimulcastLayers: [- new sdk.VideoPreset(- Math.floor(sourceWidth / SCREEN_SHARE_LOW_SCALE),- Math.floor(sourceHeight / SCREEN_SHARE_LOW_SCALE),- screenShareLowBitrate(profile),- screenShareLowFramerate(profile),- ),- ],degradationPreference: profile.degradationPreference,};}diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.tsindex c41ac610..bca96c32 100644--- a/src/client/webrtc/host-peer.ts+++ b/src/client/webrtc/host-peer.ts@@ -419,6 +419,19 @@ export class HostPeer {return;}await this.flushCandidates();+ await this.enqueueSenderMutation(async () => {+ const videoSender = this.videoSender;+ const audioSender = this.audioSender;+ if (this.disposed || !videoSender || !audioSender) {+ return false;+ }+ return this.configureSender(videoSender, audioSender, {+ profile: this.desiredProfile,+ profileRevision: this.profileRevision,+ video: true,+ audio: false,+ });+ });if (this.ownsAnswer(epoch)) {this.ordinaryAnswerEpoch = null;}diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.tsindex 2c20b928..e8ffd98f 100644--- a/tests/host-peer-tracks.test.ts+++ b/tests/host-peer-tracks.test.ts@@ -746,7 +746,7 @@ describe("HostPeer source replacement", () => {);});- it("accepts an answer without reapplying the selected profile", async () => {+ it("reapplies the selected video profile after accepting an answer", async () => {const video = createTrack("video", "video");const peer = createPeer(createStream(video, createTrack("audio", "audio")));@@ -768,7 +768,13 @@ describe("HostPeer source replacement", () => {expect(connection.remoteDescription?.type).toBe("answer");expect(connection.addedIceCandidates).toEqual([pendingCandidate]);expect(connection.senders[0]?.track).toBe(video);- expect(connection.senders[0]?.setParameters).toHaveBeenCalledOnce();+ expect(connection.senders[0]?.setParameters).toHaveBeenCalledTimes(2);+ expect(+ connection.senders[0]?.setParameters.mock.calls.at(-1)?.[0],+ ).toMatchObject({+ degradationPreference: "balanced",+ encodings: [{ maxBitrate: 3_000_000, maxFramerate: 30 }],+ });expect(connection.senders[1]?.setParameters).toHaveBeenCalledOnce();});diff --git a/tests/quality.test.ts b/tests/quality.test.tsindex 866cd604..0bf6e0cc 100644--- a/tests/quality.test.ts+++ b/tests/quality.test.ts@@ -11,8 +11,6 @@ import {QUALITY_RESOLUTIONS,qualitySettingsEqual,SCREEN_AUDIO_BITRATES,- screenShareLowBitrate,- screenShareLowFramerate,senderParameterWarning,setMediaPaused,} from "../src/client/media/quality.ts";@@ -90,7 +88,7 @@ describe("realtime quality controls", () => {systemAudio: "include",windowAudio: "window",});- expect(videoTrack.contentHint).toBe("");+ expect(videoTrack.contentHint).toBe("motion");expect(audioTrack.contentHint).toBe("music");});@@ -120,14 +118,6 @@ describe("realtime quality controls", () => {).toBe(true);});- it("derives a half-resolution lower representation without exceeding 30 fps", () => {- expect(screenShareLowFramerate(QUALITY_PROFILES["1080p60"])).toBe(30);- expect(screenShareLowBitrate(QUALITY_PROFILES["1080p60"])).toBe(1_000_000);- expect(screenShareLowFramerate(QUALITY_PROFILES["1080p30"])).toBe(30);- expect(screenShareLowBitrate(QUALITY_PROFILES["1080p30"])).toBe(1_250_000);- expect(screenShareLowBitrate(QUALITY_PROFILES["720p30"])).toBe(750_000);- });-it("keeps audio selection orthogonal while defaulting old settings to music", () => {const saver = {...QUALITY_PROFILES["1080p60"],diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.tsindex 23755934..894af8db 100644--- a/tests/sfu-client.test.ts+++ b/tests/sfu-client.test.ts@@ -61,7 +61,6 @@ const livekit = vi.hoisted(() => {currentTrack: MediaStreamTrack;sender: FakeSender;publishOptions?: Record<string, unknown>;- readonly replaceTrackOptions: Array<Record<string, unknown> | undefined> = [];savedDegradationPreference: RTCDegradationPreference | null = null;constructor(track: MediaStreamTrack) {@@ -75,7 +74,6 @@ const livekit = vi.hoisted(() => {readonly replaceTrack = vi.fn(async (nextTrack: MediaStreamTrack): Promise<void> => {- this.replaceTrackOptions.push(this.publishOptions);this.currentTrack = nextTrack;this.sender.track = nextTrack;},@@ -93,19 +91,6 @@ const livekit = vi.hoisted(() => {}}- class FakeVideoPreset {- readonly encoding: { maxBitrate: number; maxFramerate: number };-- constructor(- readonly width: number,- readonly height: number,- maxBitrate: number,- maxFramerate: number,- ) {- this.encoding = { maxBitrate, maxFramerate };- }- }-class FakeLocalParticipant {readonly publications: Array<{track: FakeLocalTrack;@@ -135,30 +120,20 @@ const livekit = vi.hoisted(() => {];}const screenShareEncoding = options.screenShareEncoding;- const layers = options.screenShareSimulcastLayers;if (rawTrack.kind === "video" &&+ options.simulcast === false &&typeof screenShareEncoding === "object" &&- screenShareEncoding !== null &&- Array.isArray(layers) &&- layers.length === 1+ screenShareEncoding !== null) {- const high = screenShareEncoding as {+ const encoding = screenShareEncoding as {maxBitrate?: number;maxFramerate?: number;};- const lower = layers[0] as FakeVideoPreset;localTrack.sender.parameters.encodings = [{- rid: "q",- maxBitrate: lower.encoding.maxBitrate,- maxFramerate: lower.encoding.maxFramerate,- scaleResolutionDownBy: 2,- },- {- rid: "h",- maxBitrate: high.maxBitrate,- maxFramerate: high.maxFramerate,+ maxBitrate: encoding.maxBitrate,+ maxFramerate: encoding.maxFramerate,scaleResolutionDownBy: 1,},];@@ -281,7 +256,6 @@ const livekit = vi.hoisted(() => {FakeRemoteParticipant,FakeRemotePublication,FakeRoom,- FakeVideoPreset,state,};});@@ -311,7 +285,6 @@ vi.mock("livekit-client", () => ({Room: livekit.FakeRoom,RoomEvent,Track,- VideoPreset: livekit.FakeVideoPreset,}));class FakeMediaStream {@@ -351,15 +324,11 @@ const qualityProfile = {degradationPreference: "maintain-resolution",} as const;-function track(- kind: "video" | "audio",- id: string,- settings: MediaTrackSettings = {},-): MediaStreamTrack {+function track(kind: "video" | "audio", id: string): MediaStreamTrack {return Object.assign(new EventTarget(), {id,kind,- getSettings: () => settings,+ getSettings: () => ({}),}) as MediaStreamTrack;}@@ -572,21 +541,6 @@ describe("SfuPublisher", () => {});await expect(publisher.replaceStream(stream(nextVideo))).resolves.toBe(true);expect(updates.at(-1)).toBeNull();- const currentPublication = livekit.state.rooms[0].localParticipant.publications[0];- expect(currentPublication.options).toMatchObject({- screenShareSimulcastLayers: [- {- width: 640,- height: 360,- encoding: { maxBitrate: 1_000_000, maxFramerate: 30 },- },- ],- });- expect(currentPublication.track.replaceTrackOptions[0]).toMatchObject({- screenShareSimulcastLayers: [- expect.objectContaining({ width: 640, height: 360 }),- ],- });resolveOld(senderReport(previousVideo.id, 5_000, 500_000, 300));await Promise.resolve();expect(updates.at(-1)).toBeNull();@@ -693,7 +647,7 @@ describe("SfuPublisher", () => {expect(livekit.state.rooms[0]?.disconnect).toHaveBeenCalledWith(false);});- it("publishes a lightweight half-resolution VP8 representation", async () => {+ it("leaves VP8 screen-share simulcast layers to LiveKit defaults", async () => {const publisher = new SfuPublisher();const video = track("video", "video-1");const audio = track("audio", "audio-1");@@ -713,13 +667,6 @@ describe("SfuPublisher", () => {maxBitrate: 8_000_000,maxFramerate: 60,},- screenShareSimulcastLayers: [- {- width: 960,- height: 540,- encoding: { maxBitrate: 1_000_000, maxFramerate: 30 },- },- ],degradationPreference: "maintain-resolution",});expect(@@ -734,18 +681,12 @@ describe("SfuPublisher", () => {expect(sender.setParameters).toHaveBeenCalledOnce();expect(sender.parameters.encodings).toEqual([{- rid: "q",- maxBitrate: 1_000_000,- maxFramerate: 30,- scaleResolutionDownBy: 2,- },- {- rid: "h",maxBitrate: 8_000_000,maxFramerate: 60,scaleResolutionDownBy: 1,},]);+ expect(sender.parameters.encodings[0]).not.toHaveProperty("rid");expect(publisher.getSenderParameters()).toEqual({requested: {maxBitrate: 8_000_000,@@ -769,37 +710,6 @@ describe("SfuPublisher", () => {expect(room.disconnect).not.toHaveBeenCalled();});- it("derives the lower representation from the actual capture dimensions", async () => {- const publisher = new SfuPublisher();- const video = track("video", "video-1", { width: 1904, height: 928 });- await publisher.connect(connection);-- await expect(publisher.activate(stream(video), qualityProfile)).resolves.toBe(- true,- );-- const publication = livekit.state.rooms[0].localParticipant.publications[0];- expect(publication.options).toMatchObject({- screenShareSimulcastLayers: [- {- width: 952,- height: 464,- encoding: { maxBitrate: 1_000_000, maxFramerate: 30 },- },- ],- });- expect(publication.track.sender.parameters.encodings).toEqual([- expect.objectContaining({- rid: "q",- scaleResolutionDownBy: 2,- }),- expect.objectContaining({- rid: "h",- scaleResolutionDownBy: 1,- }),- ]);- });-it.each([["saver", 64_000],["music", 128_000],@@ -876,13 +786,6 @@ describe("SfuPublisher", () => {degradationPreference: "balanced",encodings: [expect.objectContaining({- rid: "q",- maxBitrate: 1_000_000,- maxFramerate: 30,- scaleResolutionDownBy: 2,- }),- expect.objectContaining({- rid: "h",maxBitrate: 3_000_000,maxFramerate: 30,scaleResolutionDownBy: 1,@@ -1235,13 +1138,6 @@ describe("SfuPublisher", () => {degradationPreference: "maintain-framerate",encodings: [{- rid: "q",- maxBitrate: 1_000_000,- maxFramerate: 30,- scaleResolutionDownBy: 2,- },- {- rid: "h",maxBitrate: 3_000_000,maxFramerate: 30,scaleResolutionDownBy: 1,@@ -1256,13 +1152,6 @@ describe("SfuPublisher", () => {maxBitrate: 3_000_000,maxFramerate: 30,},- screenShareSimulcastLayers: [- {- width: 640,- height: 360,- encoding: { maxBitrate: 750_000, maxFramerate: 30 },- },- ],degradationPreference: "maintain-framerate",});@@ -1419,12 +1308,6 @@ describe("SfuPublisher", () => {degradationPreference: "maintain-resolution",encodings: [expect.objectContaining({- rid: "q",- maxBitrate: 1_000_000,- maxFramerate: 30,- }),- expect.objectContaining({- rid: "h",maxBitrate: 8_000_000,maxFramerate: 60,}),@@ -1472,20 +1355,13 @@ describe("SfuPublisher", () => {});it("restores the previous video after a partially applied replacement fails", async () => {- const previousVideo = track("video", "video-1", {- width: 1904,- height: 928,- });- const nextVideo = track("video", "video-2", {- width: 1280,- height: 720,- });+ const previousVideo = track("video", "video-1");+ const nextVideo = track("video", "video-2");const publisher = new SfuPublisher();await publisher.connect(connection);await publisher.activate(stream(previousVideo), qualityProfile);const localTrack = livekit.state.rooms[0].localParticipant.publications[0].track;localTrack.replaceTrack.mockImplementationOnce(async (replacement) => {- localTrack.replaceTrackOptions.push(localTrack.publishOptions);localTrack.currentTrack = replacement;throw new Error("sender swap failed after applying");});@@ -1495,25 +1371,6 @@ describe("SfuPublisher", () => {expect(localTrack.replaceTrack).toHaveBeenNthCalledWith(1, nextVideo);expect(localTrack.replaceTrack).toHaveBeenNthCalledWith(2, previousVideo);expect(localTrack.currentTrack).toBe(previousVideo);- expect(localTrack.publishOptions).toMatchObject({- screenShareSimulcastLayers: [- expect.objectContaining({ width: 952, height: 464 }),- ],- });- expect(localTrack.sender.parameters.encodings).toEqual([- expect.objectContaining({ rid: "q", scaleResolutionDownBy: 2 }),- expect.objectContaining({ rid: "h", scaleResolutionDownBy: 1 }),- ]);- expect(localTrack.replaceTrackOptions[0]).toMatchObject({- screenShareSimulcastLayers: [- expect.objectContaining({ width: 640, height: 360 }),- ],- });- expect(localTrack.replaceTrackOptions[1]).toMatchObject({- screenShareSimulcastLayers: [- expect.objectContaining({ width: 952, height: 464 }),- ],- });});it("uses the screen audio preset when a replacement adds audio", async () => {