Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
feat(web): raise screen audio send ceiling (#128)
AAA16c08eb96f2d
diff --git a/docs/research/browser-screen-audio-quality.md b/docs/research/browser-screen-audio-quality.mdindex 1cf8c619..c726f505 100644--- a/docs/research/browser-screen-audio-quality.md+++ b/docs/research/browser-screen-audio-quality.md@@ -2,7 +2,7 @@Accessed: 2026-08-21-Status: standard music hint accepted; user-facing codec controls remain no-go.+Status: fixed 128 kbps send ceiling accepted; user-facing codec controls remain no-go.## Scope And Decision@@ -16,21 +16,24 @@ The Web sender keeps the current minimal behavior:- request audio with `audio: true`;- request window audio for a selected window and offer system audio for a fulldisplay;-- mark returned audio tracks with `contentHint = "music"`;+- retain `contentHint = "music"` only as source intent, with no quality claim;- treat an audio track as optional and warn before publishing when none exists;- preserve returned audio through source changes, picture pause, P2P, relay, andconfigured SFU routes;-- expose no channel-count, sample-rate, Opus bitrate, stereo, DTX, or FEC- quality control; and+- apply a fixed `128000` bit/s ceiling to each browser audio sender at initial+ binding and source replacement, and the same audio preset with DTX disabled+ when publishing through the pinned LiveKit SDK;+- expose no channel-count, sample-rate, Opus bitrate, stereo, DTX, or FEC user+ control; and- expose local, read-only audio RTP diagnostics without treating negotiatedcodec fields as source-quality facts.-The music hint is not a codec or quality mode. No codec-quality control is-justified yet. In particular, Screener will not add-application-owned SDP munging or a control whose value cannot be separated into-requested, applied, negotiated, and observed states using standard APIs. The-deployed reports below do justify an explicit source-scope acceptance gate and-a later native process-audio candidate; neither is a bitrate knob.+The music hint is metadata, not a codec or quality mode. Chromium accepts and+reads it back, but the inspected libwebrtc audio-track interface has no matching+content-hint input to the Opus encoder. Screener therefore does not credit the+hint with a quality change. The fixed ceiling is a measured product default,+not a user control or a reason to add application-owned SDP munging. Requested,+applied, negotiated, and observed states remain separate.## Deployed Reports And Echo Boundary@@ -53,28 +56,50 @@ audio scoped as intended in that browser environment. Current source requeststhe source-appropriate window and full-display audio choices. This is oneenvironment observation, not a cross-browser source guarantee.+## Voice-Processing Boundary++Current Chromium constraint-selection tests cover tab, system, and desktop as+content-capture sources. With no explicit processing constraint, all three+select disabled WebRTC echo cancellation and `false` for automatic gain+control, noise suppression, experimental noise suppression, high-pass filter,+and experimental automatic gain control. `disable_local_echo` is a separate+local-playback behavior and is not an audio-processing effect. Screener only+requests display audio and does not opt these content tracks into microphone+processing.++This rules out default mic-style voice processing as the source-supported+explanation for the current Chrome result. It remains Chromium implementation+evidence rather than a portable browser guarantee; a runtime regression would+need track settings or an isolated capture fixture, not speculative processing+constraints added to `getDisplayMedia()`.+## Standard API Boundary| Concern | Standard request or control | Honest readback | What it does not prove | Current product action || --- | --- | --- | --- | --- || Audio presence | `getDisplayMedia({ audio: true, video: ... })` expresses interest | `stream.getAudioTracks().length` proves only whether a track was returned | The browser may still return video only; a track does not identify system, window, tab, or selected-game audio | Keep the existing presence check and visible no-audio warning || Audio source choice | `windowAudio: "window"` asks for window audio and `systemAudio: "include"` offers system audio for monitor surfaces; a user agent may ignore either hint | There is no standard audio-source category readback corresponding to those hints | The selected audio scope, per-application isolation, or cross-browser availability | Let the picker expose the source-appropriate option without adding an inferred source label |-| Content intent | `track.contentHint = "music"` asks the media pipeline to treat the returned audio as music | The assigned hint can be read back | A codec, bitrate, stereo mode, or guarantee that browser processing changed | Apply the hint without presenting it as a quality preset |+| Content intent | `track.contentHint = "music"` records the source intent | The assigned hint can be read back | A codec, bitrate, stereo mode, or evidence that current Chromium changed Opus encoding | Keep it as metadata only; do not use it as a quality acceptance signal || Voice-app exclusion | `restrictOwnAudio` concerns audio produced by the document that invoked capture; `suppressLocalAudioPlayback` concerns local playback of a captured browser surface | The app may observe whether a returned track exists, not which OS processes it contains | Excluding Discord, KOOK, WeChat, notifications, or any other independent process from system audio | Web keeps video-only available and warns that system audio may include calls/notifications; it does not claim isolation || Capture channels | The Screen Capture specification does not list generic `channelCount` as applicable to display audio | `track.getSettings().channelCount` may describe the returned track when the browser supplies it | That the app controlled the value, or that the RTP encoder sends stereo | Observe only in a future diagnostic; absent means unknown || Capture sample rate | The Screen Capture specification does not list generic `sampleRate` as applicable to display audio | `track.getSettings().sampleRate` may be present in an implementation | The Opus mode, RTP clock semantics, receiver output rate, or end-to-end fidelity | Observe only in a future diagnostic; absent means unknown |-| RTP send bitrate | `RTCRtpSender.setParameters()` can set `encodings[].maxBitrate` for audio | A following `getParameters()` can show the applied ceiling; outbound byte deltas show actual traffic | A target, minimum, quality increase, or Opus `maxaveragebitrate`; other limits may keep traffic lower | Do not add a control without a measured need to reduce audio bandwidth |+| RTP send bitrate | `RTCRtpSender.setParameters()` can set `encodings[].maxBitrate` for audio | A following `getParameters()` can show the applied ceiling; outbound byte deltas show actual traffic | A target, minimum, audible improvement, or Opus `maxaveragebitrate`; other limits may keep traffic lower | Request a fixed 128 kbps ceiling, read it back, and retain actual bitrate as the acceptance fact || Codec | The user agent chooses among negotiated send codecs unless a separately negotiated codec selection is available | `RTCCodecStats.mimeType` and `sdpFmtpLine` identify the codec and negotiated format parameters in use | That Opus was selected before stats exist, or that negotiated preferences describe actual content | Label only observed negotiated data; do not force a codec || Stereo | No stable sender parameter controls Opus stereo | Capture settings and negotiated codec/fmtp data can be inspected separately | Capture channel count does not prove encoded stereo; `opus/48000/2` does not prove stereo content | No control and no inferred stereo badge || DTX | The current WebRTC `RTCRtpEncodingParameters` dictionary has no `dtx` member | No portable standard sender readback proves DTX operation | A deprecated, non-standard browser field or SDK option is not a cross-browser contract | No control || FEC | There is no direct, portable audio FEC on/off sender parameter | Negotiated codec/fmtp data and inbound `fecPacketsReceived`/`fecBytesReceived` may provide evidence after use | Negotiation does not prove recovery occurred; zero counters do not prove FEC was disabled | No control; retain stats only as future diagnostic evidence |-The one technically portable write, audio `maxBitrate`, is not a quality-up-knob. The WebRTC specification defines it as a maximum and allows other limits-to constrain the sender further. It also warns that an audio ceiling below the-chosen encoding's needs may require playback to stop. Leaving it unset already-avoids an application-imposed ceiling, so adding a higher value cannot promise-better game audio.+The WebRTC specification defines audio `maxBitrate` as a maximum and allows+other limits to constrain the sender further. A narrow Chrome 151 local+loopback on 2026-08-21 used a complex synthetic 48 kHz, two-channel source and+`contentHint = "music"`. With no sender ceiling, the offer selected+`audio/opus` with `minptime=10;useinbandfec=1` and sent 32.21 kbps over the+four-second measurement window. The same fixture with only+`encodings[0].maxBitrate = 128000` read back `128000` and sent 127.91 kbps;+the offer and fmtp were unchanged. This establishes that the standard setter+materially changed Chrome's encoder budget for that fixture. It does not prove+an audible improvement, stereo, a target bitrate, or equivalent behavior in+another browser or under congestion.## Capture And Browser Compatibility@@ -127,6 +152,13 @@ API that merely exposes the negotiated `sdpFmtpLine` can report those facts,but does not provide a portable setter or prove the encoder's moment-to-momentbehavior.+Current libwebrtc source calculates the default full-band Opus bitrate as+32 kbps times the negotiated channel count. It derives two encoded channels+only from `stereo=1`; otherwise it configures one. That matches the narrow+Chrome observation, whose ordinary offer had no stereo fmtp and sent about+32 kbps. It is an implementation-level explanation for the tested default,+not a portable stereo or bitrate contract.+## Reference ImplementationsNo code was copied. All repositories were inspected at pinned commits on@@ -140,7 +172,10 @@ No code was copied. All repositories were inspected at pinned commits on`RTCRtpEncodingParameters.maxBitrate`, but stereo/DTX/RED also travel inLiveKit signaling. Its transport then[munges Opus bitrate fmtp](https://github.com/livekit/client-sdk-js/blob/0a2110d39904a06722a0c4d1ddbb9390bb06ad4d/src/room/PCTransport.ts#L269-L333)- in SDP.+ in SDP. The pinned 2.22.0 SDK models `audioPreset` as a `maxBitrate`, defaults+ music to 48 kbps, and keeps `forceStereo` separate. Screener uses its+ supported preset surface at 128 kbps with DTX disabled and leaves stereo to+ actual negotiation.- lib-jitsi-meet, Apache-2.0, commit[`63a04ec`](https://github.com/jitsi/lib-jitsi-meet/tree/63a04ecabd972ea75e877f9ba12086c13cb68210):[`mungeOpus()`](https://github.com/jitsi/lib-jitsi-meet/blob/63a04ecabd972ea75e877f9ba12086c13cb68210/modules/RTC/TPCUtils.ts#L871-L929)@@ -293,6 +328,11 @@ Add a user-facing audio setting only when all of these are true:- [W3C WebRTC Statistics](https://www.w3.org/TR/webrtc-stats/)- [W3C Web Audio](https://www.w3.org/TR/webaudio-1.1/)- [W3C WebCodecs Opus registration](https://www.w3.org/TR/webcodecs-opus-codec-registration/)+- [libwebrtc Opus encoder](https://webrtc.googlesource.com/src/+/refs/heads/main/modules/audio_coding/codecs/opus/audio_encoder_opus.cc)+- [libwebrtc media-track interface](https://webrtc.googlesource.com/src/+/refs/heads/main/api/media_stream_interface.h)+- [Chromium `MediaStreamTrack` content hint](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/modules/mediastream/media_stream_track_impl.cc)+- [Chromium content-capture audio defaults](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/content/renderer/media/stream/media_stream_constraints_util_audio_unittest.cc)+- [LiveKit 2.22.0 track options](https://github.com/livekit/client-sdk-js/blob/v2.22.0/src/room/track/options.ts)- [RFC 7587: RTP Payload Format for Opus](https://www.rfc-editor.org/rfc/rfc7587.html)- [RFC 7874: WebRTC Audio Codec and Processing Requirements](https://www.rfc-editor.org/rfc/rfc7874.html)- [Discord Go Live architecture](https://discord.com/blog/how-it-all-goes-live-an-overview-of-discords-streaming-technology)diff --git a/docs/research/realtime-quality-adaptation.md b/docs/research/realtime-quality-adaptation.mdindex ab3236d6..8bd6e4cd 100644--- a/docs/research/realtime-quality-adaptation.md+++ b/docs/research/realtime-quality-adaptation.md@@ -11,11 +11,11 @@ others. `maintain-framerate` may preserve motion by reducing resolution untilgame UI, maps, subtitles, and text become unreadable; `maintain-resolution`may instead lower frame rate. Neither preference overrides congestion control.-The current bounded implementation retains the game-oriented `motion` hint,-defaults to `maintain-resolution`, and offers explicit balanced and fluid-choices. This is a readability-first default, not a quality guarantee: the-WebRTC API describes a user-agent preference rather than its algorithm, so-Chromium, Firefox, and Safari behavior still needs measured comparison.+The current bounded implementation retains the game-oriented `motion` hint and+uses `balanced` for every recommended profile and the advanced-settings initial+value. Clarity and fluid remain explicit choices. The WebRTC API describes a+user-agent preference rather than its algorithm, so the browser controls the+actual degradation and Screener observes the result through readback and stats.The inspected Chromium/libwebrtc source chain makes a screen-only shortcutespecially unsafe to assume for Screener. The JavaScript `motion` hint reaches@@ -489,17 +489,18 @@ resolution, frame rate, or bitrate.- A live profile change uses `track.applyConstraints()` and updates everycurrent sender with `RTCRtpSender.setParameters()`. It does not reopen thesource picker or renegotiate healthy peer connections.-- The video track keeps `contentHint = "motion"`; recommended profiles default- to `maintain-resolution`, with explicit `balanced` and- `maintain-framerate` choices. None promises an emitted resolution or rate.+- The video track keeps `contentHint = "motion"`; recommended profiles and the+ advanced initial value use `balanced`, with explicit `maintain-resolution`+ and `maintain-framerate` choices. None promises an emitted resolution or rate.- `maxBitrate` and `maxFramerate` are ceilings. They are neither minimums nortarget guarantees, and the project does not use SDP bitrate hacks.- The folded advanced panel accepts only 720p/1080p/1440p, integer 15-60 fps,2-12 Mbps, and the three preferences. It exposes no audio quality controls.Display capture does not standardize channel-count or sample-rate control;- the portable audio `maxBitrate` field is only a ceiling and cannot raise- quality; and stereo, DTX, and FEC require negotiated fmtp/codec behavior that- has no portable sender setter. The full boundary is recorded in+ the portable audio `maxBitrate` field is only a ceiling, though the fixed+ 128 kbps value materially raised Chrome's encoder budget in one narrow+ fixture; stereo, DTX, and FEC require negotiated fmtp/codec behavior that has+ no portable sender setter. The full boundary is recorded in`docs/research/browser-screen-audio-quality.md`.- Every sender update derives from `getParameters()`, calls `setParameters()`,then reads requested/applied bitrate, frame rate, scale, and preference.@@ -507,8 +508,8 @@ resolution, frame rate, or bitrate.- One strict room setting is last-wins for current/future peer relays and theconfigured SFU publisher. Ordinary P2P keeps that state local and does not addit to the authenticated wire.-- Pausing the picture disables the existing video track, producing black video- without closing the room or media connection. Audio remains enabled.+- Pausing sharing disables every track in the current capture stream, producing+ black video and silence without closing the room or media connection.The deployed implementation deliberately stops at manual bounded controls. Itadds no composite score, periodic adjustment, codec forcing, SDP bitratediff --git a/docs/status.md b/docs/status.mdindex 9e8760ab..24c8a4b5 100644--- a/docs/status.md+++ b/docs/status.md@@ -15,7 +15,7 @@ Flagship; parallel; min run/smoke/rollback; benchmark later. Active UI/config/lo## Current Snapshot-- Capture precedes room creation; source/quality changes preserve peers, while pause disables audio/video tracks together and keeps connections. Quality defaults to `maintain-resolution` with balanced/fluid options.+- Capture precedes room creation; source/quality changes and AV pause preserve peers. Recommended profiles and advanced defaults use `balanced`; clarity/fluid remain explicit. The browser chooses degradation; readback/stats report actual behavior.- Production access is `screener-v2`: a valid private fragment grant enters directly; every code-only Viewer must first hold site access, after which public-watch accepts the code and private rooms still require their room password. `SITE_ACCESS_PASSWORD`, `/api/site-access`, and the site-access cookie are deployed atomically; raw credentials are never stored.- Web Hosts can set their local/session display name, and the current release advertises it through the existing presence wire. The name is not an account identity.- Native v2 is source-only (memory rooms, 300s reclaim); it follows authenticated direct-child assignments up to two and fails unsupported SFU/selected ingress boundedly.diff --git "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md" "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"index da728119..db030e17 100644--- "a/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"+++ "b/docs/\346\226\271\346\241\210\350\256\276\350\256\241.md"@@ -152,9 +152,9 @@ Zod 在服务边界拒绝未知类型、超长字符串、非法 SDP/candidate| 1080p30 | 1920x1080、30 fps | 5 Mbps/peer || 720p30 | 1280x720、30 fps | 3 Mbps/peer |-浏览器可返回更低设置,界面以 `track.getSettings()` 显示实际捕获结果。Current production 保留有界手动质量控制:视频 track 使用 `contentHint = "motion"`,返回的音频 track 使用 `contentHint = "music"`;二者都是内容提示而不是 codec 或质量档位。视频默认采用清晰优先的 `degradationPreference = "maintain-resolution"`,并允许显式选择 balanced 或 fluid。折叠高级区将设置严格限制为 720p/1080p/1440p、15 至 60 整数 FPS、2 至 12 Mbps,以及 `maintain-resolution`、`balanced`、`maintain-framerate` 三种偏好。它们只是 ceiling 和浏览器偏好,不保证实际分辨率、帧率或码率。+浏览器可返回更低设置,界面以 `track.getSettings()` 显示实际捕获结果。Current source 保留有界手动质量控制:视频 track 使用 `contentHint = "motion"`,返回的音频 track 使用 `contentHint = "music"`;二者都是内容提示而不是 codec 或质量档位。三档推荐质量与折叠高级区初始值统一采用 `degradationPreference = "balanced"`,并允许显式选择 clarity 或 fluid。高级区将设置严格限制为 720p/1080p/1440p、15 至 60 整数 FPS、2 至 12 Mbps,以及 `maintain-resolution`、`balanced`、`maintain-framerate` 三种偏好。它们只是 ceiling 和浏览器偏好,不保证实际分辨率、帧率或码率。-每次 `setParameters()` 都必须从当次 `getParameters()` 派生更新,然后读回 requested/applied `maxBitrate`、`maxFramerate`、`scaleResolutionDownBy` 和 degradation preference。拒绝或浏览器改写必须进入可见状态,不能只写 `console.warn`。线上已是 clarity-first bounded controls,但用户报告的严重降级尚未完成受控分类,ADR-0007 双层发布与拓扑分类也尚未实现;不得据此宣称画质提升。下一次真实质量验收仍需在同一高动态场景采样 1、2、3 名观看者的 direct-selected peer、relay-selected peer 与 SFU/UDP 路径;不得只提高 ceiling、强制 codec 或修改 SDP。+每次 `setParameters()` 都必须从当次 `getParameters()` 派生更新,然后读回 requested/applied `maxBitrate`、`maxFramerate`、`scaleResolutionDownBy` 和 degradation preference。浏览器负责具体降级,实际结果由 stats 观测;拒绝或浏览器改写必须进入可见状态,不能只写 `console.warn`。PoC 不强制 codec,也不做 SDP munging。先通过 stats 记录实际协商 codec、`encoderImplementation` 和 `powerEfficientEncoder`,再依据目标机器测量决定是否调整 H.264、VP8、VP9 或 AV1 优先级。`getCapabilities()` 只证明可协商,Media Capabilities 的 supported/smooth/power-efficient 只提供候选证据;最终必须同时检查实际 outbound codec、区间 encode time、游戏 FPS、CPU/GPU encode 引擎和 sender 数量。AV1 压缩效率不能证明目标机器具有 WebRTC 硬件编码,强制后可能落入更重的软件路径。@@ -166,13 +166,13 @@ PoC 不强制 codec,也不做 SDP munging。先通过 stats 记录实际协商直播中切换来源仍由明确的按钮手势重新调用 `getDisplayMedia()`,不改变房间、host generation 或媒体拓扑。选源取消或失败时继续发送旧流;成功后为每个现有 sender 调用 `replaceTrack()`,健康连接不重新协商。初始 offer 预留 send-only audio transceiver,使音频可以在 `null -> track -> null` 间切换。若某个 peer 的替换或回滚失败,只重建该 peer;新流提交后才停止旧流,并以当前 stream 身份保护旧 track 的迟到 `ended` 事件。统计码率累加器在换源后重置,避免把不同 track 的计数器混算。-直播中切换质量不重新打开选源器:对当前视频 track 调用 `applyConstraints()`,再更新所有现有 sender 的参数;新加入、重建的 relay sender 和启用的 SFU publisher 使用同一权威设置。失败时保留当前分享并给出状态,不以重建整个房间补偿。临时暂停只禁用当前视频 track,使远端收到黑画面;音频、房间和连接保持不变,恢复时重新启用同一 track。+直播中切换质量不重新打开选源器:对当前视频 track 调用 `applyConstraints()`,再更新所有现有 sender 的参数;新加入、重建的 relay sender 和启用的 SFU publisher 使用同一权威设置。失败时保留当前分享并给出状态,不以重建整个房间补偿。临时暂停禁用当前 capture stream 的全部音视频 tracks,使远端收到黑画面和静音;房间与连接保持不变,恢复时重新启用同一批 tracks。Host 本地预览直接绑定现有 capture stream,不创建 viewer、`RTCPeerConnection` 或额外媒体边,也不产生 TURN/SFU/应用服务器出口。预览仍可能有本地合成、缩放和 GPU 显示成本;在同一动态场景对预览开/关采集 Host CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不变时,才把直播后的默认动态预览改为静止缩略图或隐藏并允许按需展开;隐藏预览绝不停止 capture track 或 sender encode。部署版 `769de201f7cc` 的模糊、游戏低帧、持续 `bandwidth` 提示和 Host 刷新恢复都只作为同一 release 的用户报告。首轮复现必须在相同机器、Chrome/Edge、驱动、游戏场景和单个有线 direct Viewer 上对照该 release 与最新 `main`,并分别执行只重建受影响 `HostPeer`、只替换 capture、完整 Host 重建和预览开/关;任何一次只改变一个变量。若实际 codec/encoder 不变而 BWE/发送恢复,则下调 codec 根因优先级;只有编码成本异常时才进入受控 codec spike。-当前 Web 高级区不暴露音频质量控件。Screen Capture 规范未把 `channelCount`、`sampleRate` 列为 display-audio 可控属性;`track.getSettings()` 中偶尔出现的值只能作为捕获观测。标准 `RTCRtpSender.encodings[].maxBitrate` 可设置和读回,但只降低发送 ceiling,既不能要求编码器提高质量,也不等于 Opus `maxaveragebitrate`。Opus stereo、DTX 和 in-band FEC 属于协商的 codec/fmtp 行为,没有跨主流浏览器的标准 sender setter;`opus/48000/2` 也只是 RTP 信令约定,不能证明 48 kHz 源或实际 stereo。设计不为这些控件新增应用层 SDP munging,也不把 SDK 私有设置包装成浏览器保证。详细证据与复核门槛见 `docs/research/browser-screen-audio-quality.md`。+当前 Web 高级区不暴露音频质量控件。Screen Capture 规范未把 `channelCount`、`sampleRate` 列为 display-audio 可控属性;`track.getSettings()` 中偶尔出现的值只能作为捕获观测。每个 Web Host、浏览器 relay 或 selected-edge 的实际音频 sender 在首次绑定和换源后通过标准 `RTCRtpSender.setParameters()` 请求并读回 128 kbps ceiling;SFU 发布使用同值 `audioPreset` 且关闭 DTX。该 ceiling 不是目标码率或听感保证,实际结果仍由 stats 观测,也不等于 Opus `maxaveragebitrate`。Opus stereo、DTX 和 in-band FEC 属于协商的 codec/fmtp 行为,没有跨主流浏览器的标准 sender setter;`opus/48000/2` 也只是 RTP 信令约定,不能证明 48 kHz 源或实际 stereo。设计不为这些控件新增应用层 SDP munging,也不把 SDK 设置包装成浏览器保证。详细证据与复核门槛见 `docs/research/browser-screen-audio-quality.md`。`frameRate` 约束和 sender 的 `maxFramerate` 都是目标或上限;浏览器仍控制实际捕获、重复帧处理、编码和拥塞降级。静态画面可能由浏览器减少实际编码数据,但标准没有保证每个实现以同一种方式节省采集或 GPU 开销。本 PoC 不添加画面差分、定时改约束或自定义动态 FPS 状态机,先用 `framesEncoded`、实际发送码率、`totalEncodeTime`、质量受限原因和主机资源占用测量真实问题。@@ -394,7 +394,7 @@ STUN-only;只有 controller-selected edge 可接收一次短期 grant。该边所有边都继续使用标准 WebRTC。每名 viewer 播放收到的 remote `MediaStream`,并把其中的 remote tracks 加入给唯一 child 的新 `RTCPeerConnection`。该路径会逐跳解码和重编码;实验必须记录每层 encode time、CPU/GPU、`qualityLimitationReason`、帧率、分辨率和延迟,不能称为 zero-copy 或 shared encode。-Peer-assisted 信令只接受一个严格对象:`resolution` 为 `720p | 1080p | 1440p`,`maxFramerate` 为 15 至 60 的整数,`maxBitrate` 为 2,000,000 至 12,000,000 的整数,`degradationPreference` 为 `maintain-resolution | balanced | maintain-framerate`,缺字段、多余字段和越界值都拒绝。服务端用受房间容量限制的内存 Map 保存完整设置,默认 1080p60、8 Mbps、清晰优先,不写入 SQLite;停止分享时保留,房间被放弃或过期时删除。只有 peer-assisted host 可更新,鉴权快照和在线广播携带同一完整设置;普通 P2P 的严格鉴权 wire 保持原样,host 或 viewer 在该模式发送同步消息都会被拒绝。启用 SFU 时 publisher 也使用这一设置,不另建一套质量协议。+Peer-assisted 信令只接受一个严格对象:`resolution` 为 `720p | 1080p | 1440p`,`maxFramerate` 为 15 至 60 的整数,`maxBitrate` 为 2,000,000 至 12,000,000 的整数,`degradationPreference` 为 `maintain-resolution | balanced | maintain-framerate`,缺字段、多余字段和越界值都拒绝。服务端用受房间容量限制的内存 Map 保存完整设置,默认 1080p60、8 Mbps、`balanced`,不写入 SQLite;停止分享时保留,房间被放弃或过期时删除。只有 peer-assisted host 可更新,鉴权快照和在线广播携带同一完整设置;普通 P2P 的严格鉴权 wire 保持原样,host 或 viewer 在该模式发送同步消息都会被拒绝。启用 SFU 时 publisher 也使用这一设置,不另建一套质量协议。Viewer 在处理 peer-assisted 鉴权快照时先更新 `ViewerRelay` 的 desired settings,再应用拓扑分配;同一个串行队列协调 remote stream、当前 child 更新和以后重建的 child,因此它们读取同一最新目标。每个 `HostPeer` 也把初始 sender 配置、`replaceStream()` 和 `updateProfile()` 放进同一 sender-mutation queue;desired settings 在入队前同步更新,已排队操作执行时读取最新值,使快速连续修改保持 last-wins,而不增加版本号或确认协议。这里同步的是浏览器 sender 的目标上限,不是实际分辨率、帧率、码率或 shared encoding 的性能保证。diff --git "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md" "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"index 5212a186..ec3b44a2 100644--- "a/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"+++ "b/docs/\351\234\200\346\261\202\347\220\206\350\247\243.md"@@ -27,7 +27,7 @@- [ ] 端点 fanout 硬上限:任一非服务器端点任何时刻最多维护两条 active downstream media edges,包括加入、断线、换父和恢复过程;上游接收不计入这项上传预算。当前 browser relay 因逐跳重编码仍保守限制为一个 child,只有资源矩阵通过后才可升到二。第三名及后续观看者由系统自动分配给通过验收的 peer-assisted 拓扑,不能隐藏地回退为 Host 第三条连接。没有可行 peer path 时,SFU 作为主要中央兜底 virtual parent 正常向一至两个必要 roots 送流;媒体到达 root 后其余可行观看者仍优先沿受限 peer descendants 扩散。多个无法挂到健康 root 的极端 viewer 可成为额外 server-fed 例外,但必须受显式中央 egress/admission 上限约束,不能无界整房 fanout。TURN 只作为可选的极端网络 transport 兼容层,不定义房间拓扑。- [ ] P2P 优先:每条逻辑媒体边的 ICE 必须先尝试直接 UDP 路径,服务器不得默认中转可直连的媒体。一个或两个观看者优先直接连接分享端;更多观看者的 peer-assisted 行为须先通过 ADR-0004 的实验门槛。- [ ] NAT 与传输兜底:STUN 必须可用,所有 ordinary peer `RTCPeerConnection` 只接收 STUN ICE servers。PC 失败后按一次 ICE restart、一次同 parent rebuild、一个 alternate peer、再 SFU/UDP virtual parent 的顺序恢复,任一步成功即停止;只有该 edge 的 SFU/UDP 也失败后,controller 才可授权一次短期 authenticated selected-edge TURN/UDP rebuild。授权必须绑定当前 room/share generation、viewer/parent session、route revision 与 old/new connection identity,成功、失败、超时或代次变化即消费;同一房间同时 pending 或 active 的 `peer-selected` attempt 总数最多为一,`host-sfu-ingress` 使用独立状态且不占该 last-mile 名额。不得按 participant、房间或普通 peer PC 下发,Native v2 保持 STUN-only。凭据不进入 URL、日志、浏览器持久化或 SQLite。Coturn 只验证 HMAC 与 expiry,应用必须重验 edge 代次并用短 TTL、one-use state 与 quota 限界。媒体 ICE/TCP、TURN/TCP 或 TURN/TLS 另行验收;HTTPS/WSS 仍使用 TLS/TCP。-- [ ] 质量控制:保留 1080p60(8 Mbps)、1080p30(5 Mbps)、720p30(3 Mbps)三档推荐上限,默认采用清晰优先;分享期间可直接换档或应用有界高级设置,不重新选择来源或重建健康连接。Peer-assisted relay 与已配置的 SFU 必须接收同一个严格校验的房间级权威设置,覆盖当前和以后建立的 sender;普通 P2P 信令结构保持不变。任何设置都只是浏览器上限和偏好,必须读回实际 sender 参数并显示参数拒绝、改写和持续受限原因。不做自定义动态 FPS、综合评分或周期性全房间调档。+- [ ] 质量控制:保留 1080p60(8 Mbps)、1080p30(5 Mbps)、720p30(3 Mbps)三档推荐上限,三档与高级设置初始值统一采用 `balanced`;分享期间可直接换档或应用有界高级设置,不重新选择来源或重建健康连接。Peer-assisted relay 与已配置的 SFU 必须接收同一个严格校验的房间级权威设置,覆盖当前和以后建立的 sender;普通 P2P 信令结构保持不变。任何设置都只是浏览器上限和偏好,具体降级由浏览器决定;必须读回实际 sender 参数并通过 stats 观测结果、显示参数拒绝、改写和持续受限原因。不做自定义动态 FPS、综合评分或周期性全房间调档。- [ ] 路径隔离双表示:direct/peer 继续使用每条 PeerConnection 独立的 stock WebRTC GCC,不把任何 viewer 反馈合成全房目标。每条 SFU path 从 `HIGH` ceiling 开始;优先用 pinned LiveKit 2.22.0/1.13.5 的标准两层 screen-share simulcast,在 Dynacast off 下常驻 exactly `HIGH+LOW`,让内建 per-subscriber BWE 独立降层和恢复。若该 gate 通过,Screener 不实现媒体层 selector。首 gate 使用 zero-descendant SFU leaf;root-with-children 的自动 downshift 与有界迁移是 default-on 前独立硬门。只有内建选择不满足门槛时才用标准 subscriber quality 显式限制,常驻成本不合格时再测标准 sender 手动启停。`LOW` 停编只是资源优化;active representation/layer 硬上限为二,禁止按 viewer 增长。必须实测实际接收层、硬件编码证据、游戏 FPS/p1 low、CPU/GPU、区间 encode cost、上传和分层 bytes。当前 Web P2P simulcast 缺少 receiver 选 RID 和跨 PeerConnection shared-encode 契约;当前 Web/LiveKit SVC 也缺少 direct/peer 独立选层与可移植硬件保证,且 pinned screen share 强制三层 temporal-only `L1T3`,二者按现契约静态 no-go。全部标准路径失败后才考虑 custom/native dual encode。没有合格 hardware/power-efficient 路径或额外表示破坏游戏/上传预算时 fail closed:保护健康路径并明确显示弱路径降级或不可用。- [ ] 路径级质量状态:应用的 `HIGH`/`FALLBACK` 非对称窗口只决定拓扑资格和诊断,不命令正常的媒体层切换,也不计算综合分数。SFU BWE downshift 先进入 `suspect`;多个连续窗口的 sender/viewer 关联证据确认 `FALLBACK` 后,应用不得稳定保留该 parent,并把 downstream capacity 降为 0。计划或显式质量 fallback 仅是内建路径失败后的候选:已有 children 时先在 connection/assignment generation guard 下全部迁走,失败或代次过期则保持原 assignment/quality。Autonomous downshift 无法 packet-level 预先迁移,default-on 前必须验收 descendants 的短暂影响。只有更长的稳定恢复窗口和 cooldown 后才能重新声明 relay capacity。Viewer 请求必须鉴权、限频、去重,并由 sender 的 GCC/Transport-CC、实际码率、RTT、丢包、重传、编码限制、协商 codec/profile/parameters 与 viewer 解码、丢帧、冻结证据交叉验证;不能仅凭自报生效,也不得上传 raw SDP、candidate 地址或原始设备/网络标识。- [ ] 断线恢复:临时网络变化时按不同层级做一次性恢复,而不是把同一动作机械重复三次。`failed` 边先做一次 ICE restart,再重建一次同 parent 的 `RTCPeerConnection`,随后尝试一个不同的合格 peer parent;只有 peer 路径耗尽才进入 SFU。`connecting`/`checking` 先显示不改变拓扑的慢连接状态,硬超时必须由真实移动网络证据确定,不能为了更快使用服务器而过早放弃最终可成功的 P2P。任一步恢复即停止后续动作;所有异步结果受 session、route revision、assignment/connection generation 约束。active SFU 只允许一次 fresh-token 重试,再失败即有界回到 peer baseline 或明确失败,并向 Host 显示不含 URL、地址、token 或原始错误的失败阶段。@@ -42,7 +42,7 @@- [ ] 私密房间双入口:private room 接受现有 `/r/{code}#v={grant}` 合法邀请直接进入,或“站点访问 + 房间号 + 该房间观看密码”。没有 grant 的 `/join` 或 `/r/{code}` 先显示中性的站点访问验证,通过后才显示中性的房间密码输入。Host 可设置、轮换或移除房间观看密码。密码接受 1 至 64 个可见 ASCII 字符;异步 scrypt 全局最多执行 2 个、等待 16 个派生。站点口令和房间密码都不得进入 URL/query/storage/log/SQLite;不存在、错误密码、队满和正确密码后的满房都返回通用结果。- [ ] 统一自动路由:旗舰部署开启 `PEER_ASSISTED_MEDIA` 后,所有正常房间都进入同一个 direct/peer -> SFU -> selected-edge controller;每个房间独立保存 assignment/session/revision/connection generation 和容量状态。`PEER_ASSISTED_ROOM_IDS` 已退役,room `1` 只作为历史 smoke fixture,不能作为功能开关。未启用总开关的开发/轻量部署仍可保留 ordinary P2P;普通 peer 始终 STUN-only。selected-edge TURN 只能复用当前 controller 选中的异常 edge,不能向普通 peer edge 预发 candidates。该能力不增加 UI、用户选择、百分比发布或第二套路由器。-- [ ] 质量控制扩展:推荐档位仍是默认入口;折叠高级区只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling,以及清晰/平衡/流畅三种偏好。直播中显式应用后才生效,避免滑杆产生连续控制流量。当前 Web 发送端不提供音频声道、采样率、Opus 码率、stereo、DTX 或 FEC 控件:display capture 未把声道和采样率定义为可移植控制,标准音频 `maxBitrate` 只是可能导致更低质量或停播的发送上限,其他项依赖 codec/fmtp 协商而没有可移植 sender setter。除非真实音频矩阵证明用户问题、标准 API 能应用并读回且实际结果可独立观测,否则不得为这些控件新增应用层 SDP munging 或用默认值制造伪控制。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。+- [ ] 质量控制扩展:推荐档位仍是默认入口;折叠高级区只允许 720p/1080p/1440p 分辨率 ceiling、15 至 60 的整数 FPS ceiling、2 至 12 Mbps 视频码率 ceiling,以及清晰/平衡/流畅三种偏好。直播中显式应用后才生效,避免滑杆产生连续控制流量。Web 不提供音频声道、采样率、Opus 码率、stereo、DTX 或 FEC 控件;每个实际浏览器音频 sender 固定请求并读回 128 kbps ceiling,SFU 音频发布使用同值 preset 且关闭 DTX。该值只是标准 API/SDK 支持的发送上限,实际码率仍以 stats 为准。display capture 未把声道和采样率定义为可移植控制,其他项依赖 codec/fmtp 协商而没有可移植 sender setter。不得为这些控件新增应用层 SDP munging 或用默认值制造伪控制。实际质量持续低于所选上限时必须显示可解释的限制原因;在真实拥塞、编码器和接收端证据完成前,不把任一组合称为“完美平衡”。- [ ] 本地预览性能候选:在相同动态场景中 A/B 测量 Host 动态预览开/关的 CPU、GPU、encode time 和实际 FPS。只有稳定收益且捕获、编码和远端画面不受影响时,才允许直播开始后默认显示静止缩略图或隐藏动态预览并提供按需展开;未测前不宣称收益。- [ ] Peer-assisted 媒体实验:分享端最多两个 child、每名 viewer 最多一个 child;信令服务只按深度和服务端加入序号确定性地形成两条 sticky 平衡链,不加入综合评分或主动重平衡。每个 viewer 将收到的标准 remote track 通过新的 `RTCPeerConnection` 转发,因此会逐跳解码和重编码;必须测量而不能称为 shared encode。服务端只在受房间数限制的内存状态中保存当前严格校验的质量设置,不写入 SQLite;host 鉴权后先重报设置,在线 viewers 接收更新,后加入者从鉴权快照取得当前值。该功能在 ADR-0004 的实验门槛通过并由后续 ADR 正式接受前不得成为产品路径。- [ ] 原生 shared encode 分享端:后续独立的 Electron/原生分享端必须让每个 active representation 只产生一份兼容编码结果,并在 direct、peer 与 SFU transport 间复用;健康路径选择共享 `HIGH`,最多另有一份弱路径共用的 `LOW`,是否常驻由硬件、游戏和上传门槛决定。每条连接仍保留独立 WebRTC packetization、SSRC、pacing、加密和反馈,且各自消耗上传带宽。浏览器不保证跨 `RTCPeerConnection` 复用编码器,因此当前 Web spike 不能宣称满足该保证。@@ -154,7 +154,8 @@- Given 分享过程中切换 Wi-Fi/有线网络,When ICE 连接失败,Then 客户端触发 ICE restart,并在成功或超时后给出明确状态。- Given 浏览器未返回系统音轨,When 分享开始,Then 分享者在启播前看到“当前来源没有可共享音频”的提示。- Given 分享者选择标签页或窗口,When 浏览器支持对应音频捕获,Then picker 提供该来源音频而不扩大为系统混音。Given 分享者选择整个屏幕,When 浏览器支持系统音频,Then picker 提供由用户决定的系统音频开关。应用同时请求 `windowAudio: "window"` 和 `systemAudio: "include"`,不根据 track 存在性伪造来源标签。-- Given 浏览器返回分享音轨,When 开始发布,Then 应用设置标准 `contentHint = "music"`;该提示不宣称或强制 Opus、码率、声道、采样率、FEC、DTX 或立体声。+- Given 浏览器返回分享音轨,When 开始发布,Then 应用设置标准 `contentHint = "music"` 作为内容意图元数据;该值可读回,但不作为 Opus、码率、声道、采样率、FEC、DTX 或立体声的质量证据。+- Given Web Host、浏览器 relay 或 selected-edge 建立或替换分享音轨,When 对实际音频 sender 应用发送参数,Then 从当次 `getParameters()` 派生 `encodings[0].maxBitrate = 128000`、调用 `setParameters()` 并立即读回;Given 通过 SFU 发布音轨,Then 使用 `audioPreset.maxBitrate = 128000` 与 `dtx = false`。验收分别核对 applied ceiling 和 stats 实际码率,不从 preset 名称推断 stereo。- Given 浏览器返回屏幕音轨,When 产品展示音频状态或未来连接详情,Then 只能把存在性、浏览器实际返回的 track settings、实际协商 codec/fmtp 和实际流量分别标为捕获、协商或观测事实;字段缺失必须显示为未知,且不得从 Opus 的 `48000/2` RTP 声明推断源采样率或实际 stereo。- Given Web 或后续 native sender 分享电影/视频音频,When 进行产品验收,Then 必须用独立 A/B/C 证据关联 capture audio track/settings、实际 negotiated codec/fmtp、outbound/inbound 实际码率、loss、jitter、concealment、jitter-buffer 与 A/V sync;native sender 必须通过该音质和同步矩阵,且不得把 audio `maxBitrate` ceiling 当作提质证明。- Given 分享者同时运行语音软件,When 选择仅分享游戏声音,Then supported Windows 11 native sender 只保留目标游戏及其子进程的渲染音频,观众、通知和其他应用声音不得进入分享;浏览器 system audio 无法满足时必须允许 video-only 或明确告知其可能包含语音/通知,不能用 AEC、降噪或来源标签伪称已隔离。diff --git a/src/client/media/quality.ts b/src/client/media/quality.tsindex 4ce21765..9fdd606d 100644--- a/src/client/media/quality.ts+++ b/src/client/media/quality.ts@@ -22,13 +22,13 @@ export const QUALITY_PROFILES = {resolution: "1080p",maxFramerate: 30,maxBitrate: 5_000_000,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",},"720p30": {resolution: "720p",maxFramerate: 30,maxBitrate: 3_000_000,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",},} as const satisfies Record<QualityProfileId, QualitySettings>;@@ -73,6 +73,7 @@ export interface TwoLayerVideoSenderParameterReadback {}export const SCREEN_SHARE_LOW_SCALE = 2;+export const SCREEN_AUDIO_MAX_BITRATE = 128_000;export function screenShareLowBitrate(profile: QualityProfile): number {return Math.max(150_000, Math.floor(profile.maxBitrate / 4));@@ -272,6 +273,18 @@ export async function configureVideoSender(return senderParameterReadback(requested, applied);}+export async function configureScreenAudioSender(+ sender: RTCRtpSender,+): Promise<number | null> {+ const parameters = sender.getParameters();+ if (parameters.encodings.length === 0) {+ parameters.encodings = [{}];+ }+ parameters.encodings[0]!.maxBitrate = SCREEN_AUDIO_MAX_BITRATE;+ await sender.setParameters(parameters);+ return sender.getParameters().encodings[0]?.maxBitrate ?? null;+}+export async function configureTwoLayerVideoSender(sender: RTCRtpSender,profile: QualityProfile,diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.tsindex 9a2ca1af..9ce7cce3 100644--- a/src/client/sfu/publisher.ts+++ b/src/client/sfu/publisher.ts@@ -8,6 +8,7 @@ import type {import {configureTwoLayerVideoSender,QUALITY_RESOLUTIONS,+ SCREEN_AUDIO_MAX_BITRATE,SCREEN_SHARE_LOW_SCALE,screenShareLowBitrate,senderParameterWarning,@@ -167,7 +168,7 @@ export class SfuPublisher {room,audioTrack,sdk.Track.Source.ScreenShareAudio,- { dtx: false },+ audioPublishOptions(),);if (!this.owns(room, generation)) {return false;@@ -278,7 +279,7 @@ export class SfuPublisher {room,nextAudioTrack,sdk.Track.Source.ScreenShareAudio,- { dtx: false },+ audioPublishOptions(),);if (!this.owns(room, generation)) {return false;@@ -604,6 +605,13 @@ function videoPublishOptions(};}+function audioPublishOptions(): TrackPublishOptions {+ return {+ audioPreset: { maxBitrate: SCREEN_AUDIO_MAX_BITRATE },+ dtx: false,+ };+}+async function safeDisconnect(room: Room): Promise<void> {const existing = roomDisconnects.get(room);if (existing) {diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.tsindex 3afc7437..d52f90da 100644--- a/src/client/webrtc/host-peer.ts+++ b/src/client/webrtc/host-peer.ts@@ -2,6 +2,7 @@ import type { IceConfig, SignalPayload } from "../../shared/protocol";import { createOpaqueId } from "../lib/opaque-id";import type { QualityProfile } from "../media/quality";import {+ configureScreenAudioSender,configureVideoSender,senderParameterWarning,} from "../media/quality";@@ -121,10 +122,10 @@ export class HostPeer {streams: [this.stream],}).sender;await this.enqueueSenderMutation(async () => {- if (this.disposed || !this.videoSender) {+ if (this.disposed || !this.videoSender || !this.audioSender) {return false;}- return this.configureSender(this.videoSender);+ return this.configureSender(this.videoSender, this.audioSender);});if (!(await this.createOffer(false)) || this.disposed) {return false;@@ -175,7 +176,7 @@ export class HostPeer {this.limitationReason = null;this.limitationSamples = 0;this.snapshot = { ...this.snapshot, metrics: { ...EMPTY_METRICS } };- await this.configureSender(videoSender);+ await this.configureSender(videoSender, audioSender);this.snapshot = { ...this.snapshot, error: null };this.emit();return true;@@ -410,12 +411,18 @@ export class HostPeer {this.emit();}- private async configureSender(sender: RTCRtpSender): Promise<boolean> {+ private async configureSender(+ sender: RTCRtpSender,+ audioSender?: RTCRtpSender,+ ): Promise<boolean> {try {const senderParameters = await configureVideoSender(sender,this.desiredProfile,);+ if (audioSender?.track) {+ await configureScreenAudioSender(audioSender);+ }if (this.disposed) {return false;}diff --git a/src/shared/protocol.ts b/src/shared/protocol.tsindex 2b49900f..69302851 100644--- a/src/shared/protocol.ts+++ b/src/shared/protocol.ts@@ -175,7 +175,7 @@ export const DEFAULT_QUALITY_SETTINGS = {resolution: "1080p",maxFramerate: 60,maxBitrate: 8_000_000,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",} as const satisfies QualitySettings;export const relayDownstreamEdgesSchema = z.union([diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.tsindex 956178d3..9ae7d71c 100644--- a/tests/host-peer-tracks.test.ts+++ b/tests/host-peer-tracks.test.ts@@ -361,6 +361,10 @@ describe("HostPeer source replacement", () => {expect(connection.senders[1]?.track).toBe(nextAudio);expect(connection.transceiverInputs).toHaveLength(2);expect(connection.senders[0]?.setParameters).toHaveBeenCalledTimes(2);+ expect(connection.senders[1]?.appliedMaxBitrates).toEqual([+ 128_000,+ 128_000,+ ]);});it("fills a pre-negotiated audio sender that started without a track", async () => {@@ -372,6 +376,7 @@ describe("HostPeer source replacement", () => {const connection = FakePeerConnection.latest!;expect(connection.transceiverInputs[1]?.trackOrKind).toBe("audio");expect(connection.senders[1]?.track).toBeNull();+ expect(connection.senders[1]?.appliedMaxBitrates).toEqual([]);const nextAudio = createTrack("audio", "next-audio");await expect(@@ -380,6 +385,7 @@ describe("HostPeer source replacement", () => {),).resolves.toBe(true);expect(connection.senders[1]?.track).toBe(nextAudio);+ expect(connection.senders[1]?.appliedMaxBitrates).toEqual([128_000]);});it("stops sending audio without renegotiating when the new source has none", async () => {@@ -399,6 +405,7 @@ describe("HostPeer source replacement", () => {).resolves.toBe(true);expect(connection.senders[1]?.track).toBeNull();+ expect(connection.senders[1]?.appliedMaxBitrates).toEqual([128_000]);});it("updates quality parameters without replacing media tracks", async () => {@@ -418,7 +425,7 @@ describe("HostPeer source replacement", () => {expect(connection.senders[0]?.setParameters.mock.calls.at(-1)?.[0],).toMatchObject({- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",encodings: [{ maxBitrate: 8_000_000, maxFramerate: 60 }],});});@@ -495,7 +502,7 @@ describe("HostPeer source replacement", () => {expect(videoSender.setParameters).toHaveBeenCalledTimes(3);expect(videoSender.setParameters.mock.calls.at(-1)?.[0]).toMatchObject({- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",encodings: [{ maxBitrate: 8_000_000, maxFramerate: 60 }],});});diff --git a/tests/quality.test.ts b/tests/quality.test.tsindex e69fb967..23057041 100644--- a/tests/quality.test.ts+++ b/tests/quality.test.ts@@ -3,9 +3,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";import {applyCaptureProfile,captureDisplay,+ configureScreenAudioSender,configureTwoLayerVideoSender,configureVideoSender,QUALITY_PROFILES,+ SCREEN_AUDIO_MAX_BITRATE,screenShareLowBitrate,senderParameterWarning,setMediaPaused,@@ -75,11 +77,10 @@ describe("realtime quality controls", () => {});});- it("defaults every recommended profile to clarity-first degradation", () => {+ it("defaults every recommended profile to balanced degradation", () => {expect(Object.values(QUALITY_PROFILES).every(- (profile) =>- profile.degradationPreference === "maintain-resolution",+ (profile) => profile.degradationPreference === "balanced",),).toBe(true);});@@ -107,14 +108,14 @@ describe("realtime quality controls", () => {maxBitrate: 8_000_000,maxFramerate: 60,scaleResolutionDownBy: 4 / 3,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",scalabilityMode: null,},applied: {maxBitrate: 8_000_000,maxFramerate: 60,scaleResolutionDownBy: 4 / 3,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",scalabilityMode: null,},mismatches: [],@@ -123,11 +124,28 @@ describe("realtime quality controls", () => {expect(setParameters).toHaveBeenCalledOnce();});+ it("applies and reads back the screen audio send ceiling", async () => {+ let applied = { encodings: [] } as unknown as RTCRtpSendParameters;+ const sender = {+ getParameters: () => applied,+ setParameters: vi.fn(async (parameters: RTCRtpSendParameters) => {+ applied = parameters;+ }),+ } as unknown as RTCRtpSender;++ await expect(configureScreenAudioSender(sender)).resolves.toBe(+ SCREEN_AUDIO_MAX_BITRATE,+ );+ expect(applied.encodings).toEqual([+ { maxBitrate: SCREEN_AUDIO_MAX_BITRATE },+ ]);+ });+it("reports fields the browser does not retain", async () => {const before = { encodings: [{}] } as RTCRtpSendParameters;const after = {encodings: [{ maxBitrate: 8_000_000 }],- degradationPreference: "balanced",+ degradationPreference: "maintain-resolution",} as unknown as RTCRtpSendParameters;const getParameters = vi.fn<() => RTCRtpSendParameters>()@@ -167,7 +185,7 @@ describe("realtime quality controls", () => {scalabilityMode: "L1T2",},],- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",} as unknown as RTCRtpSendParameters;const sender = {track: { getSettings: () => ({ width: 1920, height: 1080 }) },@@ -202,7 +220,7 @@ describe("realtime quality controls", () => {},{ rid: "high", scalabilityMode: "L1T2" },],- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",} as unknown as RTCRtpSendParameters;const sender = {track: { getSettings: () => ({ width: 1920, height: 1080 }) },@@ -242,7 +260,7 @@ describe("realtime quality controls", () => {);expect(applied).toMatchObject({- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",encodings: [{rid: "q",diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.tsindex 4572194f..53e9724c 100644--- a/tests/server-signal.test.ts+++ b/tests/server-signal.test.ts@@ -31,7 +31,7 @@ const defaultQualitySettings = {resolution: "1080p",maxFramerate: 60,maxBitrate: 8_000_000,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",} as const;const balancedQualitySettings = {resolution: "1080p",diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.tsindex 0d0d7aaf..f8fe4d92 100644--- a/tests/sfu-client.test.ts+++ b/tests/sfu-client.test.ts@@ -266,7 +266,7 @@ const qualityProfile = {resolution: "1080p",maxFramerate: 60,maxBitrate: 8_000_000,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",} as const;function track(kind: "video" | "audio", id: string): MediaStreamTrack {@@ -420,10 +420,11 @@ describe("SfuPublisher", () => {},}),],- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",});expect(room.localParticipant.publishTrack).toHaveBeenNthCalledWith(2, audio, {source: Track.Source.ScreenShareAudio,+ audioPreset: { maxBitrate: 128_000 },dtx: false,});expect(sender.setParameters).toHaveBeenCalledOnce();@@ -446,14 +447,14 @@ describe("SfuPublisher", () => {maxBitrate: 8_000_000,maxFramerate: 60,scaleResolutionDownBy: 1,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",scalabilityMode: null,},applied: {maxBitrate: 8_000_000,maxFramerate: 60,scaleResolutionDownBy: 1,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",scalabilityMode: null,},mismatches: [],@@ -675,6 +676,24 @@ describe("SfuPublisher", () => {expect(localTrack.currentTrack).toBe(previousVideo);});+ it("uses the screen audio preset when a replacement adds audio", async () => {+ const publisher = new SfuPublisher();+ const audio = track("audio", "audio-2");+ await publisher.connect(connection);+ await publisher.activate(stream(track("video", "video-1")), qualityProfile);+ const room = livekit.state.rooms[0];++ await expect(+ publisher.replaceStream(stream(track("video", "video-2"), audio)),+ ).resolves.toBe(true);++ expect(room.localParticipant.publishTrack).toHaveBeenNthCalledWith(2, audio, {+ source: Track.Source.ScreenShareAudio,+ audioPreset: { maxBitrate: 128_000 },+ dtx: false,+ });+ });+it("reapplies and retains the current sender settings after replacing video", async () => {const publisher = new SfuPublisher();await publisher.connect(connection);@@ -689,7 +708,7 @@ describe("SfuPublisher", () => {expect(publisher.getSenderParameters()?.requested).toMatchObject({maxBitrate: 8_000_000,maxFramerate: 60,- degradationPreference: "maintain-resolution",+ degradationPreference: "balanced",});});