oficina / meet Public

Calls: Safari's screen stalls were the Mac's encoder; offer Baseline, and stop the ladder looping (spec 15.27)

Paul (Mac 0.4.10) to Farshad in Safari, 2026-10-21, problem report
6BPJVTGF: the screen reported stalled every 40 s, rebuilt, restored, and
stalled again. Reproduced with the app's core sharing to Playwright's
WebKit: Safari answers the screen in Constrained High 3.1 (640c1f), and
VideoToolbox refuses every frame (-12902/-12911) once the quality scaler
lets a Balanced share past the level's 3,600 blocks, so nothing is sent.
Chromium answers Constrained Baseline and never meets it.

- The screen offers Constrained Baseline first; a High-family screencast
  is held to its level's MaxFS.
- The sharer's own watch counts "bandwidth" as the link only below a
  400 kbit/s target, so an encoder that stops at a healthy target is seen.
- Apps and browser: a rebuild or share again that only mends it briefly,
  twice in a row, is a loop, and neither is taken for that person for
  ten minutes.
- The browser's receiver counts painted frames as movement too.
- Quality reports carry stalls and their verdict, held-back steps and
  encoder stalls; the quality line carries the screen's sums on its top
  level, which is all carlos logs prints.
- quality-summary reads carlos logs' printed format and fetches a problem
  report by -field ref= -n 5000.
- native-screen-receivers.mjs (make native-webkit): WebKit and Chromium
  receiving still, slow, moving and stalled screens; CallsInterop gains
  screen-still.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev c47ca82f626366e89da5d55c78ea9e036bcc42e9 parent 882eab8
21 files changed, +1,244 −49
  • Makefile +6 −4
  • cmd/quality-summary/main.go +213 −11
  • cmd/quality-summary/main_test.go +78 −0
  • docs/superpowers/specs/2026-09-07-meet-design.md +77 −0
  • internal/calls/quality.go +47 −1
  • internal/calls/static/room.js +87 −8
  • internal/callstest/native_browser_test.go +42 −0
  • internal/callstest/quality_test.go +45 −0
  • native/apple/Sources/CallsInterop/Interop.swift +11 −0
  • native/apple/Sources/CallsInterop/SyntheticVideo.swift +52 −4
  • native/apple/Sources/CallsKit/Call.swift +6 −1
  • native/apple/Sources/CallsKit/Media.swift +21 −6
  • native/apple/Sources/CallsKit/QualityReport.swift +35 −3
  • native/apple/Sources/CallsKit/ScreenSendPolicy.swift +64 −4
  • native/apple/Sources/CallsKit/ScreenWatchdog.swift +67 −2
  • native/apple/Tests/CallsKitTests/ScreenSendTests.swift +31 −0
  • native/apple/Tests/CallsKitTests/ScreenWatchdogTests.swift +31 −2
  • protocol/quality.go +11 −0
  • test/browser/native-screen-receivers.mjs +285 −0
  • test/browser/room-quality.test.mjs +15 −0
  • test/browser/room-screen.test.mjs +20 −3
diff --git a/Makefile b/Makefile
index 976b7e1..5c24cbc 100644
--- a/Makefile
+++ b/Makefile
@@ -184,14 +184,16 @@ native-browser: native-mac
# The Mac app in a call with Playwright's WebKit (not iOS Safari; see
# test/browser/native-webkit.mjs): codecs, Opus FEC, a thin path, and the
-# tab getting its camera and microphone back. Apart from native-browser
-# because it needs WebKit installed.
+# tab getting its camera and microphone back; and the app's screen to
+# WebKit and Chromium, still, slow, moving and wedged
+# (native-screen-receivers.mjs). Apart from native-browser because it
+# needs WebKit installed.
.PHONY: native-webkit
native-webkit: native-mac
swift build --package-path native/apple --product CallsInterop
npm install --no-save playwright@1.62.1
- npx playwright install webkit
- CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CGO_ENABLED=0 go test -tags browser -count=1 -timeout 10m -run 'TestNativeMacWebKit' -v ./internal/callstest/
+ npx playwright install webkit chromium
+ CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CALLS_SYNTHETIC_SCREEN_HEIGHT=1246 CGO_ENABLED=0 go test -tags browser -count=1 -timeout 45m -run 'TestNativeMac(WebKit|ScreenReceivers)' -v ./internal/callstest/
# Two apps in one call, sharing screens to each other. Separate from
# native-browser because two unsigned apps on one Mac do not reliably
diff --git a/cmd/quality-summary/main.go b/cmd/quality-summary/main.go
index e70288c..619775e 100644
--- a/cmd/quality-summary/main.go
+++ b/cmd/quality-summary/main.go
@@ -25,7 +25,9 @@ import (
"io"
"os"
"os/exec"
+ "regexp"
"sort"
+ "strconv"
"strings"
"time"
@@ -62,8 +64,7 @@ func run(args []string, stdin *os.File, out io.Writer) error {
}
var in io.Reader = stdin
if st, err := stdin.Stat(); err == nil && st.Mode()&os.ModeCharDevice != 0 {
- cmd := exec.Command("carlos", "logs", "--app", o.app, "--account", o.account, "--since", o.since,
- "-n", "5000", "--grep", "^calls: (quality|problem report)")
+ cmd := exec.Command("carlos", carlosArgs(o)...)
cmd.Stderr = os.Stderr
b, err := cmd.Output()
if err != nil {
@@ -103,6 +104,21 @@ func run(args []string, stdin *os.File, out io.Writer) error {
return nil
}
+// carlosArgs is the `carlos logs` the summary runs when nothing is piped
+// in. A problem report is fetched by its own field: its diagnostics are
+// many lines of a few records each, and a window of every quality line
+// would push them out of the 5,000 carlos returns at most.
+func carlosArgs(o options) []string {
+ args := []string{"logs", "-app", o.app, "-account", o.account, "-since", o.since, "-n", "5000"}
+ if o.problem != "" {
+ return append(args, "-field", "ref="+strings.ToUpper(o.problem))
+ }
+ if o.call != "" {
+ return append(args, "-field", "call="+o.call)
+ }
+ return append(args, "-grep", "^calls: (quality|problem report)")
+}
+
// parseAt reads "15:40" as today in loc, or "2026-10-03 15:40".
func parseAt(s string, loc *time.Location, now time.Time) (time.Time, error) {
if t, err := time.ParseInLocation("2006-01-02 15:04", s, loc); err == nil {
@@ -135,7 +151,11 @@ type line struct {
Part int `json:"part"`
Of int `json:"of"`
Text string `json:"text"`
- Report struct {
+ // Head is the line's numeric top-level fields, as carlos prints them
+ // (freezes, maxLossPct, screenStalls…): all there is of a quality line
+ // read from carlos, which leaves out `report`.
+ Head map[string]float64 `json:"-"`
+ Report struct {
Seconds *float64 `json:"seconds"`
Devices *protocol.Devices `json:"devices"`
Events *protocol.CallEvents `json:"events"`
@@ -143,31 +163,167 @@ type line struct {
} `json:"report"`
}
-// parse takes every line that carries a report, whatever carlos put in
-// front of it: the JSON object starts at the first "{".
+// parse takes every line that carries a report, in either of the two
+// shapes it reaches here in. The app writes JSON, and a line piped from
+// somewhere that keeps it (the fixture, an export) carries the object
+// after whatever prefix: it starts at the first `{"time"`. `carlos logs`
+// prints the record instead: its own prefix, the message, then the
+// line's top-level fields as key=value in key order, values unquoted and
+// any newline in one printed as it is, so a problem report's diagnostics
+// run over many lines (spec §15.26; 2026-10-21, quality-summary found no
+// report 6BPJVTGF in a file that held all of it). Nested members — the
+// quality line's `report` — are not printed at all, so from carlos a
+// quality line is its headline fields.
func parse(r io.Reader) ([]line, error) {
var out []line
sc := bufio.NewScanner(r)
- sc.Buffer(make([]byte, 0, 64<<10), 1<<20)
+ sc.Buffer(make([]byte, 0, 64<<10), 4<<20)
+ var record strings.Builder
+ inRecord := false
+ flush := func() {
+ if !inRecord {
+ return
+ }
+ inRecord = false
+ if l, ok := parseRecord(record.String()); ok {
+ out = append(out, l)
+ }
+ record.Reset()
+ }
for sc.Scan() {
s := sc.Text()
- i := strings.Index(s, `{"time"`)
- if i < 0 {
+ if i := strings.Index(s, `{"time"`); i >= 0 {
+ flush()
+ var l line
+ if json.Unmarshal([]byte(s[i:]), &l) == nil && strings.HasPrefix(l.Msg, "calls: ") {
+ out = append(out, l)
+ }
+ continue
+ }
+ if m := carlosPrefix.FindStringIndex(s); m != nil {
+ flush()
+ rest := s[m[1]:]
+ if strings.HasPrefix(rest, "calls: ") {
+ record.WriteString(rest)
+ inRecord = true
+ }
continue
}
- var l line
- if json.Unmarshal([]byte(s[i:]), &l) != nil || !strings.HasPrefix(l.Msg, "calls: ") {
+ // carlos's own footer, when it held lines back.
+ if strings.HasPrefix(s, "(showing the newest ") {
+ flush()
continue
}
- out = append(out, l)
+ // Anything else continues the record before it: a newline inside
+ // a value, printed as it is.
+ if inRecord {
+ record.WriteString("\n")
+ record.WriteString(s)
+ }
}
+ flush()
return out, sc.Err()
}
+// carlosPrefix is what `carlos logs` puts before each record: the time it
+// arrived, the stream, and the instance's host.
+var carlosPrefix = regexp.MustCompile(`^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d \[[a-z]+\] \S+\s+`)
+
+// recordKey is one ` key=` in a printed record.
+var recordKey = regexp.MustCompile(` ([A-Za-z][A-Za-z0-9]*)=`)
+
+// freeText are the fields whose values are free text, and so may hold
+// spaces, newlines and anything that looks like ` key=`.
+var freeText = map[string]bool{"note": true, "text": true}
+
+// parseRecord reads one printed record: "calls: quality app=mac
+// call=… time=2026-…Z version=0.4.10". carlos prints the fields in key
+// order, which is what tells a field from text inside a value: a key
+// only starts a field if it sorts after the one before it, and a free
+// text value runs to the earliest point after which the rest of the
+// record is nothing but plain fields.
+func parseRecord(s string) (line, bool) {
+ var l line
+ keys := recordKey.FindAllStringSubmatchIndex(s, -1)
+ if len(keys) == 0 {
+ return l, false
+ }
+ l.Msg = s[:keys[0][0]]
+ fields := map[string]string{}
+ prev := ""
+ for i := 0; i < len(keys); i++ {
+ k := s[keys[i][2]:keys[i][3]]
+ if k <= prev {
+ continue
+ }
+ start := keys[i][1]
+ end := len(s)
+ next := -1
+ for j := i + 1; j < len(keys); j++ {
+ nk := s[keys[j][2]:keys[j][3]]
+ if nk <= k {
+ continue
+ }
+ if freeText[k] && !plainTail(s[keys[j][0]:], k) {
+ continue
+ }
+ if !freeText[k] && strings.ContainsAny(s[start:keys[j][0]], " \n") {
+ // A plain value has no space: this key is inside it, or
+ // the one before was free text after all.
+ continue
+ }
+ next = j
+ end = keys[j][0]
+ break
+ }
+ fields[k] = s[start:end]
+ prev = k
+ if next < 0 {
+ break
+ }
+ i = next - 1
+ }
+ t, err := time.Parse(time.RFC3339Nano, fields["time"])
+ if err != nil {
+ return l, false
+ }
+ l.Time = t
+ l.Call, l.Peer, l.App, l.Version = fields["call"], fields["peer"], fields["app"], fields["version"]
+ l.Browser, l.BrowVer, l.OS, l.OSVer = fields["browser"], fields["browserVersion"], fields["os"], fields["osVersion"]
+ l.Ref, l.Note, l.Text = fields["ref"], fields["note"], fields["text"]
+ l.Final, l.Live = fields["final"] == "true", fields["live"] == "true"
+ l.Part, _ = strconv.Atoi(fields["part"])
+ l.Of, _ = strconv.Atoi(fields["of"])
+ l.Head = map[string]float64{}
+ for k, v := range fields {
+ if f, err := strconv.ParseFloat(v, 64); err == nil && !freeText[k] {
+ l.Head[k] = f
+ }
+ }
+ return l, true
+}
+
+// plainTail says whether s (" key=value key=value…") is nothing but plain
+// fields, each sorting after the last and after `after`.
+func plainTail(s, after string) bool {
+ prev := after
+ for _, tok := range strings.Split(strings.TrimPrefix(s, " "), " ") {
+ k, _, ok := strings.Cut(tok, "=")
+ if !ok || k <= prev || strings.Contains(tok, "\n") || !recordKey.MatchString(" "+k+"=") {
+ return false
+ }
+ prev = k
+ }
+ return true
+}
+
type person struct {
tag, app, version, platform string
devices string
reports int
+ // head sums (or, for the max* fields, maxes) each quality line's
+ // headline fields: all a line read from carlos has.
+ head map[string]float64
}
// direction is what one person received from another, over every window.
@@ -270,6 +426,22 @@ func lossPct(packets, lost *float64) float64 {
func (c *call) addQuality(p *person, l line) {
p.reports++
+ if p.head == nil {
+ p.head = map[string]float64{}
+ }
+ for k, v := range l.Head {
+ switch {
+ case k == "remotes":
+ p.head[k] = max(p.head[k], v)
+ case strings.HasPrefix(k, "max"):
+ p.head[k] = max(p.head[k], v)
+ default:
+ p.head[k] += v
+ }
+ }
+ if l.Head["screenStalls"] > 0 || l.Head["screenRebuilds"] > 0 || l.Head["screenReshares"] > 0 || l.Head["screenFailures"] > 0 {
+ c.events = append(c.events, event{l.Time, short(p.tag) + ": screen " + headScreen(l.Head)})
+ }
r := l.Report
if r.Devices != nil {
p.devices = fmt.Sprintf("input %s, output %s", orDash(r.Devices.Input), orDash(r.Devices.Output))
@@ -391,6 +563,13 @@ func (c *call) print(out io.Writer, loc *time.Location) {
fmt.Fprintf(out, " (%s)", p.devices)
}
fmt.Fprintln(out)
+ if h := p.head; len(h) > 0 {
+ fmt.Fprintf(out, " worst loss %g%%, worst RTT %g ms, freezes in %g, \"Reconnecting…\" %g", h["maxLossPct"], h["maxRtt"], h["freezes"], h["reconnecting"])
+ if s := headScreen(h); s != "" {
+ fmt.Fprintf(out, ", screen %s", s)
+ }
+ fmt.Fprintln(out)
+ }
}
if len(c.dirs) > 0 {
fmt.Fprintln(out, " Connections (what the first heard from the second)")
@@ -441,6 +620,29 @@ func (c *call) print(out io.Writer, loc *time.Location) {
fmt.Fprintln(out)
}
+// headScreen is a quality line's screen fields in words (spec §15.22's
+// ladder and the receiver's watch), or "" when there are none.
+func headScreen(h map[string]float64) string {
+ var parts []string
+ for _, f := range []struct{ key, words string }{
+ {"screenStalls", "stalls reported here"},
+ {"screenStallsNoPackets", "with nothing arriving"},
+ {"screenStallsUndecoded", "arriving, not decoded"},
+ {"screenReattaches", "pictures re-attached"},
+ {"screenKeyframes", "keyframes sent for reports"},
+ {"screenRebuilds", "rebuilds"},
+ {"screenReshares", "shares again"},
+ {"screenFailures", "gave up"},
+ {"screenDamped", "steps held back as a loop"},
+ {"screenEncoderStalls", "times the screen stopped leaving"},
+ } {
+ if v := h[f.key]; v > 0 {
+ parts = append(parts, fmt.Sprintf("%g %s", v, f.words))
+ }
+ }
+ return strings.Join(parts, ", ")
+}
+
func ofWhat(kind string) string {
if kind == "" {
return ""
diff --git a/cmd/quality-summary/main_test.go b/cmd/quality-summary/main_test.go
index dab6cce..4460b63 100644
--- a/cmd/quality-summary/main_test.go
+++ b/cmd/quality-summary/main_test.go
@@ -72,3 +72,81 @@ func TestSummaryByCallTagAndAProblemReport(t *testing.T) {
t.Fatalf("--problem:\n%s", out)
}
}
+
+// carlosFixture is `carlos logs` as it really prints (2026-10-21): the
+// message, then the top-level fields as key=value in key order, values
+// unquoted, a diagnostics chunk's newlines printed as they are, and no
+// `report` at all. Diagnostics text that looks like fields (" in=1",
+// " time=") must stay text.
+const carlosFixture = `2026-10-21 14:38:52 [app] calls.bds.oncarlos.com calls: quality app=mac call=ayhk4nffb2gz7eur final=false freezes=4 maxLossPct=0.1 maxRtt=195.9 os=macos osVersion=27.0.0 peer=p2pq7kdbzubekeu6 reconnecting=0 relay=false remotes=1 screenRebuilds=1 screenStalls=0 seconds=30.9 time=2026-10-21T14:38:52.887559374Z version=0.4.10
+2026-10-21 14:39:06 [app] calls.bds.oncarlos.com calls: quality app=web browser=safari browserVersion=26.5 call=ayhk4nffb2gz7eur final=false freezes=0 maxLossPct=0 maxRtt=141 os=macos peer=ce5xx2f463fimkpi reconnecting=0 relay=false remotes=1 screenStalls=2 screenStallsUndecoded=2 seconds=30.2 time=2026-10-21T14:39:06.364245764Z version=882eab8
+2026-10-21 15:06:37 [app] calls.bds.oncarlos.com calls: problem report app=mac call=ayhk4nffb2gz7eur live=true note=it froze, then a=b os=macos osVersion=27.0.0 parts=2 peer=p2pq7kdbzubekeu6 ref=6BPJVTGF time=2026-10-21T15:06:37.899381736Z version=0.4.10
+2026-10-21 15:06:37 [app] calls.bds.oncarlos.com calls: problem report diagnostics call=ayhk4nffb2gz7eur of=2 part=1 peer=p2pq7kdbzubekeu6 ref=6BPJVTGF text=Calls diagnostics — a call's details
+## Devices
+device: Microphone [x] in=1 out=0 48000 Hz built-in
+15:48:58.392 info keyframe for p time=2026-10-21T15:06:37.899431639Z
+2026-10-21 15:06:37 [app] calls.bds.oncarlos.com calls: problem report diagnostics call=ayhk4nffb2gz7eur of=2 part=2 peer=p2pq7kdbzubekeu6 ref=6BPJVTGF text=eer:ce5xx2f463fimkpi
+stamp time=now ok
+ time=2026-10-21T15:06:37.8995183Z
+(showing the newest 5 lines of this window — narrow it, or raise -n)
+`
+
+func runOnText(t *testing.T, text string, args ...string) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "logs")
+ if err := os.WriteFile(path, []byte(text), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ var out bytes.Buffer
+ if err := run(append([]string{"--zone", "Europe/Dublin"}, args...), f, &out); err != nil {
+ t.Fatal(err)
+ }
+ return out.String()
+}
+
+func TestCarlosPrintedProblemReport(t *testing.T) {
+ out := runOnText(t, carlosFixture, "--problem", "6bpjvtgf")
+ t.Log("\n" + out)
+ want := "Calls diagnostics — a call's details\n## Devices\ndevice: Microphone [x] in=1 out=0 48000 Hz built-in\n" +
+ "15:48:58.392 info keyframe for peer:ce5xx2f463fimkpi\nstamp time=now ok\n"
+ if !strings.Contains(out, want) {
+ t.Errorf("diagnostics not reassembled; want\n%s", want)
+ }
+ if !strings.Contains(out, "note: it froze, then a=b\n") || !strings.Contains(out, "mac 0.4.10") {
+ t.Error("the head's note or client was misread")
+ }
+}
+
+func TestCarlosPrintedQualityHeadlines(t *testing.T) {
+ out := runOnText(t, carlosFixture, "--call", "ayhk4nffb2gz7eur")
+ t.Log("\n" + out)
+ for _, want := range []string{
+ "Call ayhk4nffb2gz7eur",
+ "p2pq7k mac 0.4.10 macos 27.0.0 1 reports",
+ "worst loss 0.1%, worst RTT 195.9 ms, freezes in 4",
+ "screen 1 rebuilds",
+ "ce5xx2 web 882eab8 safari 26.5 on macos 1 reports",
+ "screen 2 stalls reported here, 2 arriving, not decoded",
+ "Problem 6BPJVTGF",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("missing %q", want)
+ }
+ }
+}
+
+func TestCarlosArgs(t *testing.T) {
+ got := strings.Join(carlosArgs(options{app: "calls", account: "oficina", since: "24h", problem: "6bpjvtgf"}), " ")
+ if !strings.Contains(got, "-field ref=6BPJVTGF") || !strings.Contains(got, "-n 5000") || strings.Contains(got, "-grep") {
+ t.Errorf("--problem fetches %q", got)
+ }
+ got = strings.Join(carlosArgs(options{app: "calls", account: "oficina", since: "2h"}), " ")
+ if !strings.Contains(got, "-n 5000") || !strings.Contains(got, "-grep") {
+ t.Errorf("the summary fetches %q", got)
+ }
+}
diff --git a/docs/superpowers/specs/2026-09-07-meet-design.md b/docs/superpowers/specs/2026-09-07-meet-design.md
index 4904922..1ec1e1a 100644
--- a/docs/superpowers/specs/2026-09-07-meet-design.md
+++ b/docs/superpowers/specs/2026-09-07-meet-design.md
@@ -2901,3 +2901,80 @@ a new call; both rate limits; the kill switch; a problem report's reference,
parts and scrubbing. `hub/report_test.go`: the sweep and the bound. The
browser gate's `quality` scenario and the native gate's check: real clients'
lines in the log, a shared call tag, no names.
+
+### 15.27 §15.21, §15.22 — Safari's screen, and a ladder that loops (2026-10-21)
+
+**Why.** Paul, 2026-10-21, sharing from the Mac app (0.4.10) to Farshad in
+Safari 26.5 on the web: "screen sharing keeps getting interrupted". His
+problem report (6BPJVTGF) had the screen log of a loop, 15:48 to 16:04:
+Safari reported the screen stalled, three keyframes did nothing, the Mac
+rebuilt the screen for him ("view restored after the rebuild" a second
+later) or shared it again, and about 25 s after every rebuild Safari
+reported it stalled again — for sixteen minutes, every rebuild itself an
+interruption.
+
+**What the harness measured** (`native-screen-receivers.mjs`, the Mac's
+core sharing a 1920×1246 page to Playwright's WebKit and to Chromium, every
+second the receiver's statistics and what its tile painted):
+
+- The stall was real, and the sender's. Safari answers the screen's H.264
+ in Constrained High at level 3.1 (`640c1f`); Chromium answers Constrained
+ Baseline (`42e01f`). WebRTC sets a High stream up on a VideoToolbox
+ session that holds it to its level, as §15.21 found for a source that is
+ not a screencast: a Balanced share starts small on WebKit's slow ramp,
+ the quality scaler lets it up, and at 1440×930 (5,220 blocks against
+ 3.1's 3,600) every frame is refused (-12902, then -12911). Nothing at all
+ is sent — WebKit's statistics were right: no packets, nothing to decode,
+ nothing painted, 23 s and more. Keyframes cannot mend that; a rebuild
+ starts a new encoder small, and twenty seconds later the scaler lets it
+ up again. That is the 25 s of the report. Chromium, the same page and
+ modes: never.
+- The sharer's own watch did not see it: WebRTC went on naming bandwidth as
+ the screen's limit at a 2.5 Mbit/s target, and §15.21 leaves a
+ bandwidth-limited screen to the link.
+- A still screen and one changing every few seconds stalled on neither
+ receiver: Safari's decoded count and its painted frames moved with every
+ repeat. Neither the four seconds nor Safari's statistics were the cause.
+
+**Decision.**
+
+- **The screen offers Constrained Baseline first** (the Mac and iPhone
+ apps), then the other Baselines, then the rest of H.264, mode 1 before 0:
+ what Chromium settles on and what carries a full-size screencast
+ (§15.22). Safari takes it (measured: `42e01f`, 150 s of motion, no
+ refusal).
+- **A screencast in a High-family profile is held to its level** where a
+ connection still negotiates one: the screen scaled to the level's MaxFS,
+ as a source that is not a screencast always was.
+- **"The link is holding it back" needs a low target**: bandwidth named
+ as the limit counts only below 400 kbit/s, so a screen that takes frames
+ in and sends nothing at a healthy target is the encoder's, and gets the
+ §15.21 steps.
+- **A loop is not answered with more of the same** (apps and browser): a
+ report back within two minutes of a rebuild or a share again having
+ restored that person's view is the step mending it only briefly; two in a
+ row and neither is taken for that person for ten minutes. The sharer is
+ told "Couldn't restore …'s view — try Stop and Share again", keyframes go
+ on, and the next stall after the ten minutes gets the whole ladder.
+- **The browser's receiver** reads frames its tile presented
+ (requestVideoFrameCallback) as movement alongside frames decoded: a
+ picture still being painted is never reported on one counter's word.
+- **Telemetry.** The quality report (§15.26) gains, per peer, the stalls a
+ client judged and its verdict (`in.screen.stalls`, `stallsNoPackets`,
+ `stallsUndecoded`), and the sharer's held-back steps and encoder stalls
+ (`out.screen.damped`, `encoderStalls`). The `calls: quality` line carries
+ the screen's sums on its top level (`screenStalls`, `screenRebuilds`,
+ `screenReshares`, `screenFailures`, `screenDamped`, `screenEncoderStalls`
+ and the rest, only when not zero), because `carlos logs` prints the top
+ level and leaves `report` out. `quality-summary` reads `carlos logs` as it
+ prints (key=value, newlines in a value printed as they are), and fetches
+ a problem report by `-field ref=` with `-n 5000`.
+
+**Compatibility.** Nothing on the signalling wire changes. The new report
+members are numbers, which an older server drops. A Safari receiver of an
+older app still gets High and the old ladder; the loop rule bounds what
+that costs it once the browser and the server are new.
+
+**Not done.** WebKit's slow start (its screen starts at 480×310 where
+Chromium's starts at full size, the same before and after) is WebKit's
+bandwidth estimate, and is left alone.
diff --git a/internal/calls/quality.go b/internal/calls/quality.go
index a0d3776..74f2fa4 100644
--- a/internal/calls/quality.go
+++ b/internal/calls/quality.go
@@ -324,8 +324,17 @@ func (a *app) logQuality(rep hub.Reporter, q protocol.QualityReport) {
slog.Float64("maxRtt", sum.rtt),
slog.Float64("freezes", sum.freezes),
slog.Float64("reconnecting", sum.reconnecting),
- slog.Any("report", body),
)
+ // The screen's headline, only what happened: `carlos logs` prints the
+ // top-level fields and leaves `report` out, so these are what shows a
+ // screen recovery loop without anyone sending a problem report
+ // (2026-10-21).
+ for _, f := range sum.screen {
+ if f.v > 0 {
+ attrs = append(attrs, slog.Float64(f.name, f.v))
+ }
+ }
+ attrs = append(attrs, slog.Any("report", body))
a.reportLog.LogAttrs(context.Background(), slog.LevelInfo, "calls: quality", attrs...)
}
@@ -349,6 +358,13 @@ func tagOrUnknown(rep hub.Reporter, id protocol.PeerID) string {
type qualitySummary struct {
relay bool
lossPct, rtt, freezes, reconnecting float64
+ screen []screenHead
+}
+
+// screenHead is one of the quality line's screen fields.
+type screenHead struct {
+ name string
+ v float64
}
// summarize is the line's headline: whether any connection went through
@@ -371,6 +387,36 @@ func summarize(q protocol.QualityReport) qualitySummary {
if q.Events != nil {
s.reconnecting += val(q.Events.Reconnecting)
}
+ var stalls, noPackets, undecoded, reported, reattaches float64
+ var keyframes, rebuilds, reshares, failures, damped, encoderStalls float64
+ for _, p := range q.Peers {
+ if p.In != nil && p.In.Screen != nil {
+ v := p.In.Screen
+ stalls += val(v.Stalls)
+ noPackets += val(v.StallsNoPackets)
+ undecoded += val(v.StallsUndecoded)
+ reattaches += val(v.Reattaches)
+ }
+ if p.Events != nil && p.Events.ScreenStalled {
+ reported++
+ }
+ if p.Out != nil && p.Out.Screen != nil {
+ o := p.Out.Screen
+ keyframes += val(o.Keyframes)
+ rebuilds += val(o.Rebuilds)
+ reshares += val(o.Reshares)
+ failures += val(o.Failures)
+ damped += val(o.Damped)
+ encoderStalls += val(o.EncoderStalls)
+ }
+ }
+ // A client from before the counts says only that a report was out.
+ s.screen = []screenHead{
+ {"screenStalls", max(stalls, reported)}, {"screenStallsNoPackets", noPackets},
+ {"screenStallsUndecoded", undecoded}, {"screenReattaches", reattaches},
+ {"screenKeyframes", keyframes}, {"screenRebuilds", rebuilds}, {"screenReshares", reshares},
+ {"screenFailures", failures}, {"screenDamped", damped}, {"screenEncoderStalls", encoderStalls},
+ }
for _, p := range q.Peers {
if p.Path != nil && (p.Path.Local == "relay" || p.Path.Remote == "relay") {
s.relay = true
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js
index 4fd5382..0a935a5 100644
--- a/internal/calls/static/room.js
+++ b/internal/calls/static/room.js
@@ -313,6 +313,17 @@
const SCREEN_REBUILD_EVERY = 60000;
const SCREEN_RESHARE_EVERY = 300000;
const SCREEN_ESCALATE_SENT = 3;
+ // 2026-10-21, a loop: Paul's screen to Farshad in Safari was rebuilt,
+ // restored within a second and reported stalled again 25 s later, for
+ // eight minutes, every rebuild an interruption that mended nothing for
+ // long. A report back within SCREEN_LOOP_WITHIN of a rebuild or a share
+ // again restoring that person's view is that step mending it only
+ // briefly; SCREEN_LOOP_LIMIT of them in a row and neither is taken for
+ // them for SCREEN_LOOP_REST: the notice says it could not be restored,
+ // and keyframes go on.
+ const SCREEN_LOOP_WITHIN = 120000;
+ const SCREEN_LOOP_LIMIT = 2;
+ const SCREEN_LOOP_REST = 600000;
// The screen's timeline, for "Copy call diagnostics": its last lines.
const SCREEN_LOG_LINES = 200;
// §15.23 (2026-09-30), "Reconnecting…" only for a problem that lasts:
@@ -428,14 +439,20 @@
const screenMoving = new Map();
let screenReattaches = 0;
const shareRebuiltAt = new Map();
+ // peer -> {restoredAt, loops, dampedUntil}: escalateShare's loop record,
+ // kept across reports.
+ const shareLoops = new Map();
let shareResharedAt = 0;
- const shareCounts = { keyframes: 0, rebuilds: 0, reshares: 0, failures: 0 };
+ const shareCounts = { keyframes: 0, rebuilds: 0, reshares: 0, failures: 0, damped: 0 };
const screenLines = [];
// §15.26: the same ladder and mending, per peer, taken by each quality
// report (peer id -> counts). shareCounts above is the whole call's,
// for the diagnostics.
const shareCountsBy = new Map();
const reattachesBy = new Map();
+ // And the stalls this tab judged, per peer, by what the statistics said
+ // (peer id -> {stalls, noPackets, undecoded}).
+ const stallsBy = new Map();
// §15.23: when the stream went down (0 while it is up), and the watch.
let streamDownSince = 0;
const reconnect = reconnectRecord();
@@ -4582,6 +4599,15 @@
const reading = screenReadings.get(key);
screenLog('screen from ' + id.slice(0, 6) + ' stalled here: reporting it; since it last moved ' +
(reading ? readingMoved(reading, screenMoving.get(key)) : 'no reading'));
+ // §15.26: counted with what the statistics said.
+ const c = stallsBy.get(id) || { stalls: 0, noPackets: 0, undecoded: 0 };
+ c.stalls += 1;
+ const was = screenMoving.get(key);
+ if (reading && was && was.mid === reading.mid) {
+ if (reading.packets === was.packets) c.noPackets += 1;
+ else if (reading.decoded === was.decoded) c.undecoded += 1;
+ }
+ stallsBy.set(id, c);
}
for (const id of screenStalled) {
if (stalled.includes(id)) continue;
@@ -4605,7 +4631,12 @@
const asking = !!(share && me && m && m.screenStalled && m.screenStalled.includes(me));
if (!asking) {
const gone = screenAsks.get(id);
- if (gone && gone.stage && share) screenLog(id.slice(0, 6) + '\u2019s view restored after ' + stageWords(gone.stage));
+ if (gone && gone.stage && share) {
+ screenLog(id.slice(0, 6) + '\u2019s view restored after ' + stageWords(gone.stage));
+ const loop = shareLoops.get(id) || {};
+ shareRestored(Object.assign(loop, { stage: gone.stage }), now);
+ shareLoops.set(id, loop);
+ }
screenAsks.delete(id);
continue;
}
@@ -4632,12 +4663,15 @@
// negotiated with them at all (a rebuild that never came back).
const negotiated = !!(entry && entry.shareTx && entry.shareSend);
const owed = !negotiated || (entry.shareSentSince || 0) >= SCREEN_ESCALATE_SENT;
- const rec = { stage: ask.stage, at: ask.stageAt, lastRebuild: shareRebuiltAt.get(id) || 0 };
+ const loop = shareLoops.get(id) || {};
+ const rec = { stage: ask.stage, at: ask.stageAt, lastRebuild: shareRebuiltAt.get(id) || 0,
+ restoredAt: loop.restoredAt || 0, loops: loop.loops || 0, dampedUntil: loop.dampedUntil || 0 };
const before = rec.stage;
const reshareFree = reshare || !shareResharedAt || now - shareResharedAt >= SCREEN_RESHARE_EVERY;
const action = escalateShare(rec, now, owed, reshareFree);
ask.stage = rec.stage;
ask.stageAt = rec.at;
+ shareLoops.set(id, { restoredAt: rec.restoredAt, loops: rec.loops, dampedUntil: rec.dampedUntil });
if (rec.stage !== before && entry) entry.shareSentSince = 0;
if (action === 'rebuild') {
shareRebuiltAt.set(id, now);
@@ -4649,6 +4683,13 @@
reshare = true;
countShareStep(id, 'reshares');
screenLog(id.slice(0, 6) + ' still reports a stall' + (before === 'rebuilt' ? ' after the rebuild' : ', rebuilt under a minute ago') + ': sharing again');
+ } else if (action === 'damped') {
+ shareCounts.failures += 1;
+ shareCounts.damped += 1;
+ countShareStep(id, 'failures');
+ countShareStep(id, 'damped');
+ screenLog(id.slice(0, 6) + ' still reports a stall, and rebuilding has only mended it briefly: not rebuilding or sharing again for ' +
+ Math.round((rec.dampedUntil - now) / 1000) + ' s');
} else if (action === 'failed') {
shareCounts.failures += 1;
countShareStep(id, 'failures');
@@ -5075,17 +5116,22 @@
if (typeof p.id !== 'string' || !/^[0-9a-f]{32}$/.test(p.id)) continue;
const q = qualityPeer(p.prev, p.now, o.seconds);
const ladder = {};
- for (const k of ['keyframes', 'rebuilds', 'reshares', 'failures']) {
+ for (const k of ['keyframes', 'rebuilds', 'reshares', 'failures', 'damped']) {
if (p.ladder && p.ladder[k] > 0) qualitySet(ladder, k, p.ladder[k]);
}
if (Object.keys(ladder).length) {
q.out = q.out || {};
q.out.screen = Object.assign(q.out.screen || {}, ladder);
}
- if (p.reattaches > 0) {
+ if (p.reattaches > 0 || (p.stalls && p.stalls.stalls > 0)) {
q.in = q.in || {};
q.in.screen = q.in.screen || {};
- qualitySet(q.in.screen, 'reattaches', p.reattaches);
+ if (p.reattaches > 0) qualitySet(q.in.screen, 'reattaches', p.reattaches);
+ if (p.stalls && p.stalls.stalls > 0) {
+ qualitySet(q.in.screen, 'stalls', p.stalls.stalls);
+ if (p.stalls.noPackets > 0) qualitySet(q.in.screen, 'stallsNoPackets', p.stalls.noPackets);
+ if (p.stalls.undecoded > 0) qualitySet(q.in.screen, 'stallsUndecoded', p.stalls.undecoded);
+ }
}
if (p.events && Object.keys(p.events).length) q.events = p.events;
if (!Object.keys(q).length) continue;
@@ -5126,7 +5172,7 @@
function countShareStep(id, step) {
let c = shareCountsBy.get(id);
if (!c) {
- c = { keyframes: 0, rebuilds: 0, reshares: 0, failures: 0 };
+ c = { keyframes: 0, rebuilds: 0, reshares: 0, failures: 0, damped: 0 };
shareCountsBy.set(id, c);
}
c[step] += 1;
@@ -5190,12 +5236,14 @@
now: reading,
ladder: shareCountsBy.get(id) || null,
reattaches: reattachesBy.get(id) || 0,
+ stalls: stallsBy.get(id) || null,
events: events.peers.get(id) || null,
});
}
for (const id of Array.from(qualityPrev.keys())) if (!pcs.has(id)) qualityPrev.delete(id);
shareCountsBy.clear();
reattachesBy.clear();
+ stallsBy.clear();
refreshOutputKind();
if (!reportToken || qualityServerOff || !qualityOn()) return;
const track = local && local.getAudioTracks()[0];
@@ -5596,11 +5644,27 @@
rec.at = now;
};
if (!rec.stage) {
+ // A new report. Back soon after a restart restored the view: that
+ // restart mended it only briefly, and twice in a row is a loop.
+ if (rec.restoredAt && now - rec.restoredAt < SCREEN_LOOP_WITHIN) {
+ rec.loops = (rec.loops || 0) + 1;
+ if (rec.loops >= SCREEN_LOOP_LIMIT) {
+ rec.dampedUntil = now + SCREEN_LOOP_REST;
+ rec.loops = 0;
+ }
+ } else {
+ rec.loops = 0;
+ }
+ rec.restoredAt = 0;
move('keyframes');
return '';
}
if (rec.stage === 'keyframes') {
if (now - rec.at < SCREEN_REBUILD_AFTER || !owed) return '';
+ if (rec.dampedUntil && now < rec.dampedUntil) {
+ move('failed');
+ return 'damped';
+ }
if (!rec.lastRebuild || now - rec.lastRebuild >= SCREEN_REBUILD_EVERY) {
move('rebuilt');
rec.lastRebuild = now;
@@ -5623,6 +5687,14 @@
return 'failed';
}
+ // shareRestored is a report clearing: the ladder ends, and a view a
+ // rebuild or a share again restored is remembered, for the loop.
+ // Pure, and lifted by name in the node test.
+ function shareRestored(rec, now) {
+ if (rec.stage === 'rebuilt' || rec.stage === 'reshared') rec.restoredAt = now;
+ rec.stage = '';
+ }
+
function stageWords(stage) {
return { keyframes: 'keyframes', rebuilt: 'the rebuild', reshared: 'sharing again', failed: 'giving up' }[stage] || stage;
}
@@ -7817,7 +7889,14 @@
if (!key) return;
decoded.set(key, report.framesDecoded);
if (key !== id) {
- screens.set(key, report.framesDecoded);
+ // What the receiver's watch reads as movement: frames decoded
+ // and, where the browser says so, frames its tile presented
+ // (requestVideoFrameCallback). 2026-10-21: a screen Safari
+ // reported stalled every 40 s — the stall was real, the
+ // sender's (ScreenSendPolicy.levelMacroblocks), but a decoder
+ // count is one browser's word on it, and a picture still being
+ // painted is never reported stalled on that word alone.
+ screens.set(key, report.framesDecoded + (HAS_RVFC ? (frames.get(key) || 0) : 0));
const t = tiles.get(key);
screenReports.set(key, screenReading(report, !!(t && t.track && t.track.muted)));
}
diff --git a/internal/callstest/native_browser_test.go b/internal/callstest/native_browser_test.go
index e51c3d3..2cc5be7 100644
--- a/internal/callstest/native_browser_test.go
+++ b/internal/callstest/native_browser_test.go
@@ -962,3 +962,45 @@ func TestNativeMacWebKit(t *testing.T) {
t.Fatalf("native-webkit: %v", err)
}
}
+
+// TestNativeMacScreenReceivers is the Mac app sharing a screen to WebKit
+// and to Chromium, its stall watch held to what the browser shows
+// (2026-10-21: Farshad, in Safari, "screen sharing keeps getting
+// interrupted" — Safari reported Paul's screen stalled every 40 s, and
+// the rebuilds that answered were the interruption). A still screen, a
+// slowly changing one and a moving one must never be reported; a
+// genuine stall (the app's encoder stopped, a wedged receiver) still is,
+// and mends.
+// test/browser/native-screen-receivers.mjs has the scenarios.
+// SCREEN_ENGINES and SCREEN_RECEIVER_SCENARIOS narrow it.
+func TestNativeMacScreenReceivers(t *testing.T) {
+ root, err := filepath.Abs("../..")
+ if err != nil {
+ t.Fatal(err)
+ }
+ binary := filepath.Join(root, "native/apple/.build/debug/CallsInterop")
+ if _, err := os.Stat(binary); err != nil {
+ t.Fatal("build native interop executable with make native-mac first")
+ }
+ engines := strings.Split(envOr("SCREEN_ENGINES", "webkit,chromium"), ",")
+ scenarios := strings.Split(envOr("SCREEN_RECEIVER_SCENARIOS", "still,slow,motion,encoder,wedge"), ",")
+ for _, engine := range engines {
+ for _, scenario := range scenarios {
+ t.Run(engine+"/"+scenario, func(t *testing.T) {
+ rig := newBrowserRig(t)
+ room, _ := rig.createMeeting(t)
+ ctx, cancel := context.WithTimeout(t.Context(), 4*time.Minute)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, "node", filepath.Join(root, "test/browser/native-screen-receivers.mjs"), rig.origin, room, binary, scenario)
+ cookies, _ := json.Marshal([]map[string]string{{"name": rig.cookieName, "value": rig.cookieB}})
+ input, _ := json.Marshal(map[string]string{"origin": rig.origin, "room": room, "cookies": string(cookies)})
+ cmd.Env = append(os.Environ(), "SCREEN_ENGINE="+engine, "CALLS_COOKIE_NAME="+rig.cookieName, "CALLS_COOKIE_A="+rig.cookieA, "CALLS_NATIVE_INPUT="+string(input))
+ out, err := cmd.CombinedOutput()
+ t.Log(string(out))
+ if err != nil {
+ t.Fatalf("native-screen-receivers %s %s: %v", engine, scenario, err)
+ }
+ })
+ }
+ }
+}
diff --git a/internal/callstest/quality_test.go b/internal/callstest/quality_test.go
index 82255d8..8fe8e43 100644
--- a/internal/callstest/quality_test.go
+++ b/internal/callstest/quality_test.go
@@ -237,6 +237,12 @@ func TestQualityReportsShareACallTagAndNameNothing(t *testing.T) {
t.Errorf("line[%q] = %v (%T), want %v", k, a[k], a[k], want)
}
}
+ // Nothing happened to the screen, so the line names none of it.
+ for k := range a {
+ if strings.HasPrefix(k, "screen") {
+ t.Errorf("a quiet screen still put %q on the line", k)
+ }
+ }
if got := peers[0].(map[string]any)["rtt"]; got != 48.3 {
t.Errorf("rtt %v, want rounded to a tenth (48.3)", got)
}
@@ -601,3 +607,42 @@ func TestAProblemReportIsLoggedUnderItsReferenceAndScrubbed(t *testing.T) {
t.Errorf("65 KB of diagnostics: %d, want 413", resp.StatusCode)
}
}
+
+// TestQualityLineCarriesTheScreenHeadline: carlos logs prints a line's
+// top-level fields and not `report`, so a screen recovery loop
+// (2026-10-21: Safari reporting Paul's screen stalled every 40 s, the Mac
+// rebuilding it each time) has to be on the top level to be seen at all.
+func TestQualityLineCarriesTheScreenHeadline(t *testing.T) {
+ r := newReportRig(t, "")
+ sharer := sampleQuality(r.peerB)
+ sharer.Peers[0].Out.Screen = &protocol.OutStream{Keyframes: num(3), Rebuilds: num(1), Reshares: num(1), Failures: num(1), Damped: num(1), EncoderStalls: num(2)}
+ resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, sharer))
+ if resp.StatusCode != http.StatusAccepted {
+ t.Fatalf("the sharer's report: %d", resp.StatusCode)
+ }
+ watcher := sampleQuality(r.peerA)
+ watcher.Peers[0].In.Screen = &protocol.InVideo{Stalls: num(2), StallsNoPackets: num(2), Reattaches: num(1)}
+ watcher.Peers[0].Events.ScreenStalled = true
+ resp, _ = r.b.report(r.sqid, "quality", r.tokB, mustJSON(t, watcher))
+ if resp.StatusCode != http.StatusAccepted {
+ t.Fatalf("the watcher's report: %d", resp.StatusCode)
+ }
+ lines := r.reports.lines(t, "calls: quality")
+ if len(lines) != 2 {
+ t.Fatalf("%d lines", len(lines))
+ }
+ for k, want := range map[string]float64{"screenKeyframes": 3, "screenRebuilds": 1, "screenReshares": 1, "screenFailures": 1, "screenDamped": 1, "screenEncoderStalls": 2} {
+ if lines[0][k] != want {
+ t.Errorf("sharer line[%q] = %v, want %v", k, lines[0][k], want)
+ }
+ }
+ for k, want := range map[string]float64{"screenStalls": 2, "screenStallsNoPackets": 2, "screenReattaches": 1} {
+ if lines[1][k] != want {
+ t.Errorf("watcher line[%q] = %v, want %v", k, lines[1][k], want)
+ }
+ }
+ if _, ok := lines[1]["screenStallsUndecoded"]; ok {
+ t.Error("a count of none is left off the line")
+ }
+ r.assertClean(t)
+}
diff --git a/native/apple/Sources/CallsInterop/Interop.swift b/native/apple/Sources/CallsInterop/Interop.swift
index 3a61045..08c5066 100644
--- a/native/apple/Sources/CallsInterop/Interop.swift
+++ b/native/apple/Sources/CallsInterop/Interop.swift
@@ -209,6 +209,17 @@ struct Input: Decodable {
print("{\"screenSharing\":\(on)}")
fflush(stdout)
}
+ // A still page repeated once a second as the Mac's capture repeats
+ // one, changed every N seconds (0: never): `screen-still 0`.
+ if command.hasPrefix("screen-still") {
+ let every = Double(command.split(separator: " ").dropFirst().first ?? "") ?? 0
+ let screen = await SyntheticScreen(stillChangingEvery: every)
+ await MainActor.run { Interop.screen = screen }
+ await call.shareScreen(screen)
+ let on = await call.sharingScreen
+ print("{\"screenSharing\":\(on)}")
+ fflush(stdout)
+ }
// A thin uplink, for the same gate: `uplink 1200000`, or `uplink 0`
// to lift it.
if command.hasPrefix("uplink ") {
diff --git a/native/apple/Sources/CallsInterop/SyntheticVideo.swift b/native/apple/Sources/CallsInterop/SyntheticVideo.swift
index 1ddf271..dfca09c 100644
--- a/native/apple/Sources/CallsInterop/SyntheticVideo.swift
+++ b/native/apple/Sources/CallsInterop/SyntheticVideo.swift
@@ -99,6 +99,13 @@ import LiveKitWebRTC
private let page: ScrollingPage?
init(motion: Bool = false) { page = motion ? ScrollingPage() : nil }
+ /// A still page, as the Mac's real capture sends one (2026-10-21, a
+ /// Safari receiver reporting stalls every 40 s): the page once, then the
+ /// same pixels again once a second while nothing changes, as
+ /// MacScreenCapture's repeat does; and, every `changeEvery` seconds
+ /// (never when zero), a new view of the page, as a slide advancing or a
+ /// scroll would.
+ init(stillChangingEvery changeEvery: Double) { page = ScrollingPage(stillChangingEvery: changeEvery) }
func start(source: RTCVideoSource, ended: @escaping @MainActor () -> Void) async throws {
self.source = source
@@ -208,7 +215,15 @@ final class ScrollingPage: @unchecked Sendable {
set { lock.withLock { stalledFlag = newValue } }
}
- init() {
+ /// Nil for the 30 fps scroll; otherwise a still page, changed this
+ /// often (never when zero) and repeated once a second between changes.
+ private let changeEvery: Double?
+ private var last: CVPixelBuffer?
+ private var lastSent = 0.0
+ private var lastChange = 0.0
+
+ init(stillChangingEvery changeEvery: Double? = nil) {
+ self.changeEvery = changeEvery
let stride = Self.width * 4
var texture = [UInt8](repeating: 0xF4, count: stride * rows)
var seed: UInt64 = 0x9E37_79B9_7F4A_7C15
@@ -246,6 +261,10 @@ final class ScrollingPage: @unchecked Sendable {
}
func start(source: RTCVideoSource, capturer: RTCVideoCapturer) {
+ if let changeEvery {
+ startStill(source: source, capturer: capturer, changeEvery: changeEvery)
+ return
+ }
// Strict: a lenient timer on a background process is coalesced to a
// third of this rate, which measured the timer and not WebRTC.
let timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
@@ -263,6 +282,35 @@ final class ScrollingPage: @unchecked Sendable {
timer.resume()
}
+ /// MacScreenCapture.ScreenFrames' shape: a timer every half second that
+ /// sends the last frame again when a second has passed since anything
+ /// was sent, with a fresh capture time, the same pixel buffer.
+ private func startStill(source: RTCVideoSource, capturer: RTCVideoCapturer, changeEvery: Double) {
+ let timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
+ timer.schedule(deadline: .now(), repeating: .milliseconds(500), leeway: .milliseconds(50))
+ timer.setEventHandler { [weak self] in
+ guard let self, !self.stalled else { return }
+ let now = Double(DispatchTime.now().uptimeNanoseconds) / 1e9
+ if self.last == nil || (changeEvery > 0 && now - self.lastChange >= changeEvery) {
+ self.offset = (self.offset + 22 * 9) % self.rows
+ self.last = self.next(still: true)
+ self.lastChange = now
+ } else if now - self.lastSent < 1 {
+ return
+ }
+ guard let pixel = self.last else { return }
+ self.lastSent = now
+ source.capturer(
+ capturer,
+ didCapture: RTCVideoFrame(
+ buffer: RTCCVPixelBuffer(pixelBuffer: pixel), rotation: ._0,
+ timeStampNs: Int64(DispatchTime.now().uptimeNanoseconds)))
+ self.lock.withLock { self.count += 1 }
+ }
+ self.timer = timer
+ timer.resume()
+ }
+
func stop() {
timer?.cancel()
timer = nil
@@ -273,7 +321,7 @@ final class ScrollingPage: @unchecked Sendable {
return lap < span ? lap : 2 * span - lap
}
- private func next() -> CVPixelBuffer? {
+ private func next(still: Bool = false) -> CVPixelBuffer? {
guard let pool else { return nil }
var pixel: CVPixelBuffer?
CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool, &pixel)
@@ -301,12 +349,12 @@ final class ScrollingPage: @unchecked Sendable {
guard let source = raw.baseAddress else { return }
for y in 0..<Self.height {
memcpy(base + y * destination, source + ((first + y) % rows) * stride, stride)
- if y >= wy, y < wy + 450 {
+ if !still, y >= wy, y < wy + 450 {
memcpy(base + y * destination + wx * 4, source + (jump + y - wy) * stride + shift, 800 * 4)
}
}
}
- offset = (offset + 12) % rows
+ if !still { offset = (offset + 12) % rows }
return pixel
}
}
diff --git a/native/apple/Sources/CallsKit/Call.swift b/native/apple/Sources/CallsKit/Call.swift
index 501feb0..cc0fd0c 100644
--- a/native/apple/Sources/CallsKit/Call.swift
+++ b/native/apple/Sources/CallsKit/Call.swift
@@ -1047,7 +1047,7 @@ private final class Events: NSObject, BridgeListenerProtocol {
let sending = reports.mapValues {
ScreenSendCounts(
encoded: $0.framesEncoded, sent: $0.framesSent, keyframes: $0.keyFramesEncoded,
- bandwidthLimited: $0.limitation == "bandwidth")
+ bandwidthLimited: ScreenWatchdog.linkLimited(limitation: $0.limitation, targetBitrate: $0.targetBitrate))
}
let failuresBefore = screenWatchdog.failures
var actions = screenWatchdog.observe(
@@ -1143,6 +1143,9 @@ private final class Events: NSObject, BridgeListenerProtocol {
ScreenLog.info(
"screen from \(ScreenWatchdog.short(peer)) stalled here: reporting it; since it last moved \(report.moved(since: moving)) — \(report.diagnosis(since: moving))")
ScreenLog.info("screen from \(ScreenWatchdog.short(peer)): \(report.summary)")
+ let verdict = report.diagnosis(since: moving)
+ qualityTally.count(
+ .stall(arriving: !verdict.hasPrefix("no packets"), decoding: !verdict.contains("arriving")), for: peer)
}
for peer in screenReceiveWatch.reattach {
let report = screenReceived[peer] ?? ScreenReceiveReport()
@@ -1440,6 +1443,8 @@ extension Call {
case .restartCapture, .recreateEncoder: break
}
}
+ for peer in screenWatchdog.newlyStarved { qualityTally.count(.encoderStall, for: peer) }
+ for peer in screenWatchdog.newlyDamped { qualityTally.count(.damped, for: peer) }
guard failed > 0 else { return }
for peer in stalledBy where screenWatchdog.escalation(of: peer) == .failed {
qualityTally.count(.failure, for: peer)
diff --git a/native/apple/Sources/CallsKit/Media.swift b/native/apple/Sources/CallsKit/Media.swift
index 751f573..8c20dfd 100644
--- a/native/apple/Sources/CallsKit/Media.swift
+++ b/native/apple/Sources/CallsKit/Media.swift
@@ -246,9 +246,15 @@ import LiveKitWebRTC
screenSize = (width, height)
applySendPolicy()
}
- var screenPlan: EncodingPlan {
- ScreenSendPolicy.screen(
- screenMode, width: screenSize.width, height: screenSize.height, screencast: screenIsScreencast)
+ var screenPlan: EncodingPlan { screenPlanFor(nil) }
+ /// The plan for one connection, given the H.264 format it negotiated.
+ var screenPlanFor: @Sendable ([String: String]?) -> EncodingPlan {
+ let mode = screenMode
+ let size = screenSize
+ let screencast = screenIsScreencast
+ return { fmtp in
+ ScreenSendPolicy.screen(mode, width: size.width, height: size.height, screencast: screencast, negotiated: fmtp)
+ }
}
/// Whether this share's source was made as a screencast: fixed when the
/// share starts, whatever the mode is changed to afterwards.
@@ -673,12 +679,21 @@ struct PeerAudioReading: Equatable, Sendable {
func applySendPolicy() {
guard let pc, !closed, let engine else { return }
let screen = screenTx?.sender
- var screenPlan = engine.screenPlan
- if nudge > 1 { screenPlan.scaleResolutionDownBy = (screenPlan.scaleResolutionDownBy ?? 1) * nudge }
+ let plan = engine.screenPlanFor
+ let nudge = self.nudge
let cameraTrack = engine.localVideo
let camera = ScreenSendPolicy.camera(sharing: screenTx != nil)
AudioWork.post {
- if let screen { screen.apply(screenPlan) }
+ if let screen {
+ // The format this connection negotiated, which may hold the
+ // screen to a level (ScreenSendPolicy.levelMacroblocks).
+ let fmtp = screen.parameters.codecs.first.flatMap { codec -> [String: String]? in
+ codec.name.uppercased() == "H264" ? codec.parameters as? [String: String] : nil
+ }
+ var screenPlan = plan(fmtp)
+ if nudge > 1 { screenPlan.scaleResolutionDownBy = (screenPlan.scaleResolutionDownBy ?? 1) * nudge }
+ screen.apply(screenPlan)
+ }
let id = cameraTrack?.trackId
if let sender = pc.senders.first(where: { $0.track != nil && $0.track?.trackId == id }) {
sender.apply(camera)
diff --git a/native/apple/Sources/CallsKit/QualityReport.swift b/native/apple/Sources/CallsKit/QualityReport.swift
index aa52bba..f63bae9 100644
--- a/native/apple/Sources/CallsKit/QualityReport.swift
+++ b/native/apple/Sources/CallsKit/QualityReport.swift
@@ -123,6 +123,10 @@ public struct QualityOutStream: Encodable, Equatable, Sendable {
public var rebuilds: Double?
public var reshares: Double?
public var failures: Double?
+ /// Steps held back as a loop, and times the screen stopped leaving here
+ /// (2026-10-21).
+ public var damped: Double?
+ public var encoderStalls: Double?
}
public struct QualityInbound: Encodable, Equatable, Sendable {
@@ -156,6 +160,11 @@ public struct QualityInVideo: Encodable, Equatable, Sendable {
public var height: Double?
public var fps: Double?
public var reattaches: Double?
+ /// Times this side judged the screen stalled, and what its statistics
+ /// said: nothing arriving, or arriving and not decoded (2026-10-21).
+ public var stalls: Double?
+ public var stallsNoPackets: Double?
+ public var stallsUndecoded: Double?
}
public struct QualityPeerEvents: Encodable, Equatable, Sendable {
@@ -443,7 +452,13 @@ enum QualityWords {
public struct QualityEventTally: Equatable, Sendable {
/// A screen recovery step, toward a peer (the sharer's) or for their
/// screen here (the receiver's).
- public enum Step: Sendable { case keyframe, rebuild, reshare, failure, reattach }
+ public enum Step: Sendable {
+ case keyframe, rebuild, reshare, failure, reattach, damped, encoderStall
+ /// The receiver judged the screen stalled: `arriving` false when no
+ /// packets came since it last moved, `decoding` false when they came
+ /// and nothing was decoded.
+ case stall(arriving: Bool, decoding: Bool)
+ }
struct Peer: Equatable, Sendable {
var reconnecting = 0
@@ -458,6 +473,11 @@ public struct QualityEventTally: Equatable, Sendable {
var reshares = 0
var failures = 0
var reattaches = 0
+ var damped = 0
+ var encoderStalls = 0
+ var stalls = 0
+ var stallsNoPackets = 0
+ var stallsUndecoded = 0
}
/// The longest a look is taken to cover: the level watch looks five
@@ -507,6 +527,13 @@ public struct QualityEventTally: Equatable, Sendable {
case .reshare: peers[peer, default: Peer()].reshares += 1
case .failure: peers[peer, default: Peer()].failures += 1
case .reattach: peers[peer, default: Peer()].reattaches += 1
+ case .damped: peers[peer, default: Peer()].damped += 1
+ case .encoderStall: peers[peer, default: Peer()].encoderStalls += 1
+ case .stall(let arriving, let decoding):
+ peers[peer, default: Peer()].stalls += 1
+ if !arriving { peers[peer, default: Peer()].stallsNoPackets += 1 } else if !decoding {
+ peers[peer, default: Peer()].stallsUndecoded += 1
+ }
}
}
@@ -607,20 +634,25 @@ public struct QualityReportBuilder: Equatable, Sendable {
if events != QualityPeerEvents() { peer.events = events }
// The sharer's recovery steps toward this peer belong with the screen
// going out to them, even in a window where it sent nothing.
- if e.keyframes + e.rebuilds + e.reshares + e.failures > 0 {
+ if e.keyframes + e.rebuilds + e.reshares + e.failures + e.damped + e.encoderStalls > 0 {
var out = peer.out ?? QualityOutbound()
var screen = out.screen ?? QualityOutStream()
screen.keyframes = steps(e.keyframes)
screen.rebuilds = steps(e.rebuilds)
screen.reshares = steps(e.reshares)
screen.failures = steps(e.failures)
+ screen.damped = steps(e.damped)
+ screen.encoderStalls = steps(e.encoderStalls)
out.screen = screen
peer.out = out
}
- if e.reattaches > 0 {
+ if e.reattaches + e.stalls > 0 {
var inbound = peer.in ?? QualityInbound()
var screen = inbound.screen ?? QualityInVideo()
screen.reattaches = steps(e.reattaches)
+ screen.stalls = steps(e.stalls)
+ screen.stallsNoPackets = steps(e.stallsNoPackets)
+ screen.stallsUndecoded = steps(e.stallsUndecoded)
inbound.screen = screen
peer.in = inbound
}
diff --git a/native/apple/Sources/CallsKit/ScreenSendPolicy.swift b/native/apple/Sources/CallsKit/ScreenSendPolicy.swift
index dda0220..5373be3 100644
--- a/native/apple/Sources/CallsKit/ScreenSendPolicy.swift
+++ b/native/apple/Sources/CallsKit/ScreenSendPolicy.swift
@@ -125,11 +125,22 @@ public enum ScreenSendPolicy {
/// The screen's encoding, for a source of the given size (zero while
/// it is not known yet, which leaves the scale alone). `screencast` is
/// whether the source was made as one (see `realtimeMacroblocks`).
+ ///
+ /// `negotiated` is the H.264 format the connection settled on, where
+ /// known (its fmtp parameters): a screencast sent in a High-family
+ /// profile is held to that level too (see `levelMacroblocks`).
static func screen(
- _ mode: ScreenShareMode, width: Int = 0, height: Int = 0, screencast: Bool? = nil
+ _ mode: ScreenShareMode, width: Int = 0, height: Int = 0, screencast: Bool? = nil,
+ negotiated: [String: String]? = nil
) -> EncodingPlan {
let longest = Double(max(width, height))
- let capped = levelCapped && !(screencast ?? Self.screencast(mode)) && width > 0 && height > 0
+ let limit: Int? = {
+ guard levelCapped, width > 0, height > 0 else { return nil }
+ if !(screencast ?? Self.screencast(mode)) { return Self.realtimeMacroblocks }
+ return negotiated.flatMap(levelMacroblocks)
+ }()
+ let capped = limit != nil
+ let blockLimit = limit ?? Self.realtimeMacroblocks
func fit(_ side: Double) -> Double? {
var scale = longest > side ? longest / side : 1
if capped {
@@ -138,7 +149,7 @@ public enum ScreenSendPolicy {
func blocks(_ s: Double) -> Int {
((Int(Double(width) / s) + 15) / 16) * ((Int(Double(height) / s) + 15) / 16)
}
- while blocks(scale) > realtimeMacroblocks { scale *= 1.01 }
+ while blocks(scale) > blockLimit { scale *= 1.01 }
}
return scale > 1 ? scale : nil
}
@@ -160,13 +171,62 @@ public enum ScreenSendPolicy {
}
}
+ /// The most 16×16 blocks a screencast may have in the H.264 format a
+ /// connection negotiated, or nil when it is not held to one.
+ ///
+ /// 2026-10-21, Paul sharing from the Mac app (0.4.10) to Farshad in
+ /// Safari: "screen sharing keeps getting interrupted". Safari answers the
+ /// screen in Constrained High at level 3.1 (640c1f) where Chromium answers
+ /// Constrained Baseline (42e01f), and this build of WebRTC sets a High
+ /// stream up on a VideoToolbox session that holds it to the level, as it
+ /// holds a source that is not a screencast: once the quality scaler let a
+ /// Balanced share up to 1440×930 (5,220 blocks), every frame was refused
+ /// (-12902, then -12911) and nothing at all was sent, until a rebuild
+ /// started a new encoder small — and twenty seconds later the scaler let
+ /// it up again (native-screen-receivers.mjs, `webkit` / `motion`).
+ /// Baseline at the same level was measured carrying 1920×1246 (§15.22),
+ /// so only the High family is held, at its level's MaxFS (H.264 Table
+ /// A-1).
+ static func levelMacroblocks(_ fmtp: [String: String]) -> Int? {
+ guard let id = fmtp["profile-level-id"]?.lowercased(), id.count == 6,
+ let profile = UInt8(id.prefix(2), radix: 16), let level = UInt8(id.suffix(2), radix: 16)
+ else { return nil }
+ // 0x42 Baseline (constrained or not) and 0x4d Main: not held.
+ guard profile != 0x42, profile != 0x4d else { return nil }
+ let maxFS: [UInt8: Int] = [
+ 10: 99, 11: 396, 12: 396, 13: 396, 20: 396, 21: 792, 22: 1620, 30: 1620, 31: 3600, 32: 5120,
+ 40: 8192, 41: 8192, 42: 8704, 50: 22080, 51: 36864, 52: 36864,
+ ]
+ return maxFS[level]
+ }
+
/// The sender's codecs with H.264 first, the rest after it in their own
/// order: Apple's hardware encoder where the far side can take H.264,
/// and everything else still on offer where it cannot, so a browser
/// without H.264 negotiates what it always did. Held on the screen's
/// transceiver so a renegotiation the far side offers keeps it.
+ ///
+ /// Among the H.264 formats, Constrained Baseline first, then the other
+ /// Baselines, then the rest, each in packetization mode 1 before 0
+ /// (2026-10-21): what Chromium settles on, and the one that carries a
+ /// full-size screencast. Safari, offered High first, took it and the
+ /// level that comes with it (see `levelMacroblocks`).
static func preferringH264(_ codecs: [RTCRtpCodecCapability]) -> [RTCRtpCodecCapability] {
- codecs.filter { $0.name.uppercased() == "H264" } + codecs.filter { $0.name.uppercased() != "H264" }
+ let h264 = codecs.enumerated().filter { $0.element.name.uppercased() == "H264" }
+ .sorted { a, b in
+ let ra = h264Rank(a.element.parameters), rb = h264Rank(b.element.parameters)
+ return ra != rb ? ra < rb : a.offset < b.offset
+ }
+ .map(\.element)
+ return h264 + codecs.filter { $0.name.uppercased() != "H264" }
+ }
+
+ /// An H.264 format's place in the screen's preference, lowest first.
+ static func h264Rank(_ fmtp: [String: String]) -> Int {
+ let id = (fmtp["profile-level-id"] ?? "").lowercased()
+ let profile: Int
+ if id.hasPrefix("42e0") { profile = 0 } else if id.hasPrefix("42") { profile = 1 } else { profile = 2 }
+ return profile * 2 + (fmtp["packetization-mode"] == "1" ? 0 : 1)
}
/// The camera's encoding: capped while this app shares a screen, and
diff --git a/native/apple/Sources/CallsKit/ScreenWatchdog.swift b/native/apple/Sources/CallsKit/ScreenWatchdog.swift
index dbcd5db..ccde2bf 100644
--- a/native/apple/Sources/CallsKit/ScreenWatchdog.swift
+++ b/native/apple/Sources/CallsKit/ScreenWatchdog.swift
@@ -142,6 +142,28 @@ struct ScreenWatchdog: Equatable {
static let giveUpAfter = 10.0
static let rebuildEvery = 60.0
static let reshareEvery = 300.0
+ /// A loop (2026-10-21): Paul's screen to Farshad in Safari was rebuilt,
+ /// restored within a second, and reported stalled again 25 s later, for
+ /// eight minutes — every rebuild an interruption that mended nothing for
+ /// long. A report that comes back within `loopWithin` of a rebuild or a
+ /// share again having restored the view is that step mending it only
+ /// briefly; `loopLimit` of those in a row and the steps that interrupt
+ /// everyone's picture are not taken for that person for `loopRest`: the
+ /// sharer is told it could not be restored, and keyframes go on.
+ static let loopWithin = 120.0
+ static let loopLimit = 2
+ static let loopRest = 600.0
+ /// "The link is holding the screen back" only while WebRTC's target for
+ /// it is this low. WebRTC goes on naming bandwidth as the limit long
+ /// after the target has recovered, and a screen whose encoder refused
+ /// every frame at a 2.5 Mbit/s target (2026-10-21) was left alone for it.
+ static let linkStarvedBelow: UInt64 = 400_000
+
+ /// Whether WebRTC's own account says the link is what holds the screen
+ /// back: bandwidth named as the limit, at a target this low.
+ static func linkLimited(limitation: String, targetBitrate: UInt64) -> Bool {
+ limitation == "bandwidth" && targetBitrate < linkStarvedBelow
+ }
struct Peer: Equatable {
var last = ScreenSendCounts()
@@ -161,6 +183,12 @@ struct ScreenWatchdog: Equatable {
/// screen the link is holding back, or one with nothing new to send,
/// is not taken further.
var sentSinceStage: UInt64 = 0
+ /// When a rebuild or a share again last restored this person's view.
+ var restoredByRestartAt: Double?
+ /// Reports in a row that came back soon after such a restore.
+ var loops = 0
+ /// No rebuild or share again for this person before this time.
+ var dampedUntil = 0.0
}
/// Frames that must leave for a receiver before its report is taken
/// further than keyframes.
@@ -183,6 +211,14 @@ struct ScreenWatchdog: Equatable {
private(set) var rebuilds = 0
private(set) var reshares = 0
private(set) var failures = 0
+ /// Steps held back because they only ever mended it briefly.
+ private(set) var damped = 0
+ /// Times this side's own screen stopped encoding or sending to someone.
+ private(set) var encoderStalls = 0
+ /// The peers this look found newly stalled on the way out, and the
+ /// peers whose steps it held back: for the quality report (§15.26).
+ private(set) var newlyStarved: [String] = []
+ private(set) var newlyDamped: [String] = []
private var lastReshare: Double?
/// One line on what the watchdog is doing, for the device panel.
private(set) var status = "watching"
@@ -202,6 +238,8 @@ struct ScreenWatchdog: Equatable {
stalledBy: Set<String>
) -> [ScreenRecovery] {
var out: [ScreenRecovery] = []
+ newlyStarved = []
+ newlyDamped = []
// The capture.
let fresh = heartbeats == nil
if let beats = capture.heartbeats {
@@ -271,6 +309,10 @@ struct ScreenWatchdog: Equatable {
// encoder would only take the picture down for nothing (Text and
// detail after a thin link, the motion gate, 2026-09-28). Only a
// screen that has stopped here as well goes further.
+ if starved && peer.step == 0 {
+ encoderStalls += 1
+ newlyStarved.append(id)
+ }
switch starved ? peer.step : 0 {
case 0:
out.append(.keyframe(id))
@@ -323,8 +365,12 @@ struct ScreenWatchdog: Equatable {
if peer.escalation != .none {
switch peer.escalation {
case .keyframes: ScreenLog.info("\(Self.short(id))'s view restored after keyframes")
- case .rebuilt: ScreenLog.info("\(Self.short(id))'s view restored after the rebuild")
- case .reshared: ScreenLog.info("\(Self.short(id))'s view restored after sharing again")
+ case .rebuilt:
+ ScreenLog.info("\(Self.short(id))'s view restored after the rebuild")
+ peer.restoredByRestartAt = now
+ case .reshared:
+ ScreenLog.info("\(Self.short(id))'s view restored after sharing again")
+ peer.restoredByRestartAt = now
case .failed: ScreenLog.info("\(Self.short(id))'s view came back after all")
case .none: break
}
@@ -338,6 +384,25 @@ struct ScreenWatchdog: Equatable {
switch peer.escalation {
case .none:
peer.escalation = .keyframes(since: now)
+ if let restored = peer.restoredByRestartAt, now - restored < Self.loopWithin {
+ peer.loops += 1
+ ScreenLog.info(
+ "\(Self.short(id)) reports a stall again \(Int(now - restored)) s after a restart restored it (\(peer.loops) in a row)")
+ if peer.loops >= Self.loopLimit {
+ peer.dampedUntil = now + Self.loopRest
+ peer.loops = 0
+ }
+ } else {
+ peer.loops = 0
+ }
+ peer.restoredByRestartAt = nil
+ case .keyframes(let since) where now - since >= Self.rebuildAfter && owed && now < peer.dampedUntil:
+ peer.escalation = .failed
+ failures += 1
+ damped += 1
+ newlyDamped.append(id)
+ ScreenLog.error(
+ "\(Self.short(id)) still reports a stall, and rebuilding has only mended it briefly: not rebuilding or sharing again for \(Int(peer.dampedUntil - now)) s")
case .keyframes(let since) where now - since >= Self.rebuildAfter && owed:
if canRebuild {
out.append(.rebuild(id))
diff --git a/native/apple/Tests/CallsKitTests/ScreenSendTests.swift b/native/apple/Tests/CallsKitTests/ScreenSendTests.swift
index 04f2cc2..d237c31 100644
--- a/native/apple/Tests/CallsKitTests/ScreenSendTests.swift
+++ b/native/apple/Tests/CallsKitTests/ScreenSendTests.swift
@@ -87,6 +87,37 @@ final class ScreenSendTests: XCTestCase {
XCTAssertTrue(preferred.contains { $0.name == "VP8" }, "a browser without H.264 still has VP8")
}
+ func testConstrainedBaselineIsOfferedFirstForTheScreen() {
+ // 2026-10-21: Safari, offered High first, answered Constrained High
+ // 3.1, and VideoToolbox refused a Balanced share there once it grew.
+ let factory = RTCPeerConnectionFactory(
+ encoderFactory: RTCDefaultVideoEncoderFactory(), decoderFactory: RTCDefaultVideoDecoderFactory())
+ let preferred = ScreenSendPolicy.preferringH264(factory.rtpSenderCapabilities(forKind: "video").codecs)
+ let first = preferred.first?.parameters ?? [:]
+ XCTAssertEqual(first["profile-level-id"]?.lowercased().prefix(4), "42e0")
+ XCTAssertEqual(first["packetization-mode"], "1")
+ XCTAssertLessThan(ScreenSendPolicy.h264Rank(["profile-level-id": "42e01f", "packetization-mode": "1"]),
+ ScreenSendPolicy.h264Rank(["profile-level-id": "640c1f", "packetization-mode": "1"]))
+ }
+
+ func testAHighProfileScreencastIsHeldToItsLevel() {
+ // Constrained High 3.1, as Safari answers it: 3,600 blocks at most.
+ let high = ["profile-level-id": "640c1f", "packetization-mode": "1"]
+ XCTAssertEqual(ScreenSendPolicy.levelMacroblocks(high), 3600)
+ let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1246, screencast: true, negotiated: high)
+ let scale = plan.scaleResolutionDownBy ?? 1
+ let blocks = ((Int(1920 / scale) + 15) / 16) * ((Int(1246 / scale) + 15) / 16)
+ XCTAssertLessThanOrEqual(blocks, 3600)
+ XCTAssertGreaterThan(blocks, 3400, "and no smaller than it needs to be")
+ // Baseline at the same level carries the full size (§15.22), and so
+ // does a level that holds it.
+ XCTAssertNil(ScreenSendPolicy.levelMacroblocks(["profile-level-id": "42e01f"]))
+ XCTAssertNil(ScreenSendPolicy.screen(.balanced, width: 1920, height: 1246, screencast: true,
+ negotiated: ["profile-level-id": "42e01f"]).scaleResolutionDownBy)
+ XCTAssertNil(ScreenSendPolicy.screen(.balanced, width: 1920, height: 1246, screencast: true,
+ negotiated: ["profile-level-id": "640c34"]).scaleResolutionDownBy)
+ }
+
func testAScreenLargerThan1920IsNeverSentLarger() {
for mode in ScreenShareMode.allCases {
let plan = ScreenSendPolicy.screen(mode, width: 3840, height: 2160)
diff --git a/native/apple/Tests/CallsKitTests/ScreenWatchdogTests.swift b/native/apple/Tests/CallsKitTests/ScreenWatchdogTests.swift
index 85aa5c4..510d7b2 100644
--- a/native/apple/Tests/CallsKitTests/ScreenWatchdogTests.swift
+++ b/native/apple/Tests/CallsKitTests/ScreenWatchdogTests.swift
@@ -265,13 +265,42 @@ final class ScreenWatchdogTests: XCTestCase {
// share again; that works too.
let second = escalating(20..<50, stalledBy: { (25..<34).contains($0) ? ["vicky"] : [] }, dog: &dog)
XCTAssertEqual(second.filter { $0.1 == .reshare || $0.1 == .rebuild("vicky") }.map(\.1), [.reshare])
- // A third, past the minute but inside five: rebuilt, and then there is
+ // A third, past the minute but inside five (and more than two minutes
+ // after the last restore, so not a loop): rebuilt, and then there is
// no share again to be had, so it is given up.
- let third = escalating(80..<120, stalledBy: { $0 >= 85 ? ["vicky"] : [] }, dog: &dog)
+ let third = escalating(160..<200, stalledBy: { $0 >= 165 ? ["vicky"] : [] }, dog: &dog)
XCTAssertEqual(third.filter { $0.1 == .reshare || $0.1 == .rebuild("vicky") }.map(\.1), [.rebuild("vicky")])
XCTAssertEqual(dog.escalation(of: "vicky"), .failed)
}
+ func testARestartThatMendsItOnlyBrieflyIsNotTakenAgain() {
+ // Paul to Farshad in Safari, 2026-10-21: reported, rebuilt, restored
+ // within a second, reported again 25 s later, for eight minutes. Here
+ // a report of nine seconds every forty: the first rebuilt, the second
+ // shared again, and the third, the second to come back within two
+ // minutes of a restart restoring it, is a loop: nothing more that
+ // interrupts the picture for ten minutes, and the sharer is told.
+ var dog = ScreenWatchdog()
+ let log = escalating(0..<600, stalledBy: { $0 % 40 >= 3 && $0 % 40 < 12 ? ["vicky"] : [] }, dog: &dog)
+ let restarts = log.filter { $0.1 == .reshare || $0.1 == .rebuild("vicky") }
+ XCTAssertEqual(restarts.map(\.1), [.rebuild("vicky"), .reshare])
+ XCTAssertEqual(restarts.map(\.0), [9, 49])
+ XCTAssertGreaterThan(dog.damped, 0, "every stall after the loop is held back, and said")
+ XCTAssertGreaterThanOrEqual(dog.failures, 1)
+ XCTAssertTrue(log.contains { $0.0 > 89 && $0.1 == .keyframe("vicky") }, "keyframes go on")
+ // Ten minutes on, a stall gets the whole ladder again.
+ let later = escalating(700..<760, stalledBy: { $0 >= 705 ? ["vicky"] : [] }, dog: &dog)
+ XCTAssertTrue(later.contains { $0.1 == .rebuild("vicky") })
+ }
+
+ func testALinkLimitAtAHealthyTargetIsNotTheLink() {
+ // 2026-10-21: WebRTC named bandwidth as the limit at a 2.5 Mbit/s
+ // target while VideoToolbox refused every frame.
+ XCTAssertFalse(ScreenWatchdog.linkLimited(limitation: "bandwidth", targetBitrate: 2_500_000))
+ XCTAssertTrue(ScreenWatchdog.linkLimited(limitation: "bandwidth", targetBitrate: 150_000))
+ XCTAssertFalse(ScreenWatchdog.linkLimited(limitation: "cpu", targetBitrate: 150_000))
+ }
+
func testNothingSentIsNothingToEscalate() {
// A still screen with nothing new to send, or a link holding it all
// back: the receiver cannot be failing to decode frames that never
diff --git a/protocol/quality.go b/protocol/quality.go
index 1619aa4..74e8827 100644
--- a/protocol/quality.go
+++ b/protocol/quality.go
@@ -124,6 +124,11 @@ type OutStream struct {
Rebuilds *float64 `json:"rebuilds,omitempty"`
Reshares *float64 `json:"reshares,omitempty"`
Failures *float64 `json:"failures,omitempty"`
+ // Steps held back because rebuilding only ever mended it briefly (a
+ // loop), and times the screen stopped leaving for this peer while
+ // frames went in (2026-10-21).
+ Damped *float64 `json:"damped,omitempty"`
+ EncoderStalls *float64 `json:"encoderStalls,omitempty"`
}
// QualityLimits are qualityLimitationReason's values.
@@ -163,6 +168,12 @@ type InVideo struct {
Height *float64 `json:"height,omitempty"`
FPS *float64 `json:"fps,omitempty"`
Reattaches *float64 `json:"reattaches,omitempty"` // a stalled screen handed to its view again (§15.22)
+ // Times this client judged the screen stalled (§15.21), and of those,
+ // how many with no packets arriving and how many with packets arriving
+ // and nothing decoded: the receiver's verdict (2026-10-21).
+ Stalls *float64 `json:"stalls,omitempty"`
+ StallsNoPackets *float64 `json:"stallsNoPackets,omitempty"`
+ StallsUndecoded *float64 `json:"stallsUndecoded,omitempty"`
}
// PeerEvents are the notices about this peer during the window.
diff --git a/test/browser/native-screen-receivers.mjs b/test/browser/native-screen-receivers.mjs
new file mode 100644
index 0000000..c0e36b8
--- /dev/null
+++ b/test/browser/native-screen-receivers.mjs
@@ -0,0 +1,285 @@
+// native-screen-receivers.mjs — the Mac app shares a screen to a browser,
+// WebKit or Chromium, and the browser's own screen watch is held to what
+// it actually shows.
+//
+// Written for 2026-10-21: Paul (Mac 0.4.10) shared to Farshad in Safari,
+// who said "screen sharing keeps getting interrupted". Paul's screen log
+// had Safari reporting the screen stalled every 40 s or so, keyframes,
+// rebuilds and shares again answering it, and the report back 25 s later.
+//
+// Scenarios, one per run (argv[4]):
+// still a still page repeated once a second, as the Mac's capture
+// repeats one (CallsInterop `screen-still 0`)
+// slow the same page, changed every five seconds (`screen-still 5`)
+// motion the 30 fps scrolling page (`screen-motion`)
+// encoder the moving page, and then the app's screen encoding switched
+// off behind its back (`screen-encoder-stall`): a stall that is
+// real and the sender's, as 2026-10-21's was, which the browser
+// must report and the app's own watch must mend
+// wedge (Chromium only: WebKit's encoded transform does not take hold
+// of a receiver already started) the still page, and then every
+// frame of the browser's screen receiver swallowed before its
+// decoder: a stall that is real and the receiver's
+//
+// SCREEN_ENGINE is webkit (the default) or chromium; SCREEN_MODE the
+// share's "Optimise for" (balanced by default); SCREEN_SECONDS how long
+// the share is watched (60). Every second it logs the browser's screen
+// statistics and what its tile is painting (requestVideoFrameCallback
+// and the element's clock), so a stall can be told apart from a screen
+// with nothing new on it. SCREEN_ASSERT=0 only logs.
+//
+// Run by TestNativeMacScreenReceivers (make native-webkit).
+import { webkit, chromium } from 'playwright';
+import { spawn } from 'node:child_process';
+import { createInterface } from 'node:readline';
+import assert from 'node:assert/strict';
+
+const [origin, room, binary, scenario] = process.argv.slice(2);
+const engine = process.env.SCREEN_ENGINE || 'webkit';
+const SECONDS = Number(process.env.SCREEN_SECONDS || 60);
+const asserting = process.env.SCREEN_ASSERT !== '0';
+const verbose = process.env.SCREEN_VERBOSE === '1';
+
+const browser = engine === 'chromium'
+ ? await chromium.launch({ headless: true, args: [
+ '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream',
+ '--autoplay-policy=no-user-gesture-required', '--disable-features=WebRtcHideLocalIpsWithMdns', '--mute-audio'] })
+ : await webkit.launch({ headless: true });
+// bypassCSP: the wedge's encoded transform runs in a worker made from a
+// blob, which the page's own policy would refuse. The gate's, never the
+// page's.
+const context = await browser.newContext({ permissions: ['camera', 'microphone'], bypassCSP: true });
+await context.addCookies([{ name: process.env.CALLS_COOKIE_NAME, value: process.env.CALLS_COOKIE_A, url: origin }]);
+const page = await context.newPage();
+await page.addInitScript((wedging) => {
+ const Native = window.RTCPeerConnection;
+ window.__pcs = new Set();
+ // The wedge: every screen receiver gets a pass-through transform as it
+ // arrives (WebKit and Chromium both take one only before it starts),
+ // and __wedge(true) has them all swallow every frame.
+ let worker = null;
+ const transforms = [];
+ const work = () => {
+ if (!worker) {
+ const code = [
+ 'let drop = false;',
+ 'onmessage = (m) => { drop = !!m.data; };',
+ 'onrtctransform = (e) => {',
+ ' e.transformer.readable.pipeThrough(new TransformStream({ transform(f, c) { if (!drop) c.enqueue(f); } }))',
+ ' .pipeTo(e.transformer.writable);',
+ '};',
+ ].join('\n');
+ worker = new Worker(URL.createObjectURL(new Blob([code], { type: 'text/javascript' })));
+ }
+ return worker;
+ };
+ window.__wedge = (on) => { work().postMessage(!!on); return transforms.length; };
+ window.RTCPeerConnection = class extends Native {
+ constructor(...args) {
+ super(...args);
+ window.__pcs.add(this);
+ this.addEventListener('track', (e) => {
+ const tx = e.transceiver;
+ if (!wedging || !tx || tx.receiver.track.kind !== 'video' || tx.direction !== 'recvonly') return;
+ try {
+ tx.receiver.transform = new RTCRtpScriptTransform(work(), {});
+ transforms.push(tx);
+ } catch {}
+ });
+ }
+ };
+ // What the screen's tile paints: frames presented
+ // (requestVideoFrameCallback) and the element's own clock, read off the
+ // element that is showing the screen whatever the room does to it.
+ window.__painted = { frames: 0, el: null };
+ const arm = (el) => {
+ if (window.__painted.el === el || !el.requestVideoFrameCallback) return;
+ window.__painted.el = el;
+ const step = () => {
+ if (window.__painted.el !== el) return;
+ window.__painted.frames += 1;
+ el.requestVideoFrameCallback(step);
+ };
+ el.requestVideoFrameCallback(step);
+ };
+ setInterval(() => {
+ for (const el of document.querySelectorAll('video')) {
+ const tile = el.closest('[data-tile]');
+ if (tile && /#share$/.test(tile.dataset.tile || '')) arm(el);
+ }
+ }, 250);
+}, scenario === 'wedge');
+
+let native;
+let sample = null;
+let exited = false;
+const wait = async (predicate, label, seconds = 40) => {
+ const until = Date.now() + seconds * 1000;
+ while (Date.now() < until) {
+ if (exited) throw new Error('native executable exited');
+ if (await predicate()) return;
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ throw new Error(label + ': ' + JSON.stringify(sample && sample.stats));
+};
+
+// The browser's screen, from its own connection: the inbound video whose
+// mid is a recvonly transceiver's (the camera's is sendrecv).
+const screen = () => page.evaluate(async () => {
+ const out = { stats: null, painted: window.__painted.frames, time: 0, stalled: [], tile: false };
+ const el = window.__painted.el;
+ if (el && el.isConnected) {
+ out.time = el.currentTime;
+ out.tile = true;
+ out.paused = el.paused;
+ out.size = el.videoWidth + 'x' + el.videoHeight;
+ }
+ for (const pc of window.__pcs) {
+ if (pc.connectionState === 'closed') continue;
+ const mids = new Set(pc.getTransceivers()
+ .filter((t) => t.receiver.track && t.receiver.track.kind === 'video' && t.direction === 'recvonly' && t.currentDirection !== 'stopped')
+ .map((t) => t.mid));
+ const all = await pc.getStats();
+ for (const r of all.values()) {
+ if (r.type === 'inbound-rtp' && r.kind === 'video' && !mids.has(r.mid)) out.camera = r.framesDecoded || 0;
+ if (r.type === 'candidate-pair' && r.nominated && r.state === 'succeeded') out.inKbps = Math.round((r.availableIncomingBitrate || 0) / 1000);
+ if (r.type !== 'inbound-rtp' || r.kind !== 'video' || !mids.has(r.mid)) continue;
+ const c = r.codecId && all.get(r.codecId);
+ out.codec = c ? c.mimeType + ' ' + (c.sdpFmtpLine || '') : '';
+ out.stats = { mid: r.mid, packets: r.packetsReceived || 0, received: r.framesReceived || 0, decoded: r.framesDecoded || 0,
+ dropped: r.framesDropped || 0, keyframes: r.keyFramesDecoded || 0, freezes: r.freezeCount || 0,
+ width: r.frameWidth || 0, height: r.frameHeight || 0, decoder: r.decoderImplementation || '',
+ pli: r.pliCount || 0, fps: r.framesPerSecond || 0, assembled: r.framesAssembledFromMultiplePackets };
+ }
+ }
+ const s = window.meet.state();
+ out.screenWatch = s.screenWatch || null;
+ return out;
+});
+
+class Skip extends Error {}
+let nudge = null;
+const stallLines = [];
+try {
+ page.on('pageerror', (e) => console.log('page error', String(e)));
+ page.on('console', (m) => {
+ const text = m.text();
+ if (!/^calls: /.test(text)) return;
+ if (/screen/.test(text)) {
+ console.log(`[${engine}] ${text}`);
+ if (/stalled here: reporting it/.test(text)) stallLines.push(text);
+ }
+ });
+ await page.goto(`${origin}/m/${room}`);
+ await page.waitForFunction(() => !!window.meet);
+ native = spawn(binary, [], { stdio: ['pipe', 'pipe', 'pipe'] });
+ native.on('exit', () => { exited = true; });
+ native.stdin.write(process.env.CALLS_NATIVE_INPUT + '\n');
+ createInterface({ input: native.stdout }).on('line', (text) => {
+ try {
+ const value = JSON.parse(text);
+ if (value.stats) sample = value;
+ } catch {}
+ });
+ native.stderr.resume();
+ nudge = setInterval(() => { page.mouse.click(5, 300).catch(() => {}); }, 2000);
+ await wait(() => sample && sample.stats.framesDecoded > 15, 'the app decodes the browser');
+ native.stdin.write(`screen-mode ${process.env.SCREEN_MODE || 'balanced'}\n`);
+ if (scenario === 'wedge' && engine !== 'chromium') {
+ console.log(`SKIP wedge on ${engine}: its encoded transform does not take hold of a started receiver`);
+ throw new Skip();
+ }
+ const moving = scenario === 'motion' || scenario === 'encoder';
+ native.stdin.write(moving ? 'screen-motion\n' : scenario === 'slow' ? 'screen-still 5\n' : 'screen-still 0\n');
+ await wait(() => sample && sample.sharingScreen === true, 'the app says it is sharing');
+ await wait(async () => {
+ const s = await screen();
+ return s.stats && s.stats.decoded > 2;
+ }, `${engine} decodes the app’s screen`);
+ console.log('screen codec ' + (await screen()).codec);
+ console.log(`PASS ${engine} decodes the app’s screen (${scenario}, ${process.env.SCREEN_MODE || 'balanced'})`);
+
+ const w = (sample && sample.stats) || {};
+ const ladder = () => {
+ const s = (sample && sample.stats) || {};
+ return { reports: s.screenStallReports || 0, keyframes: s.screenWatchdogKeyframes || 0,
+ rebuilds: s.screenWatchdogRebuilds || 0, reshares: s.screenWatchdogReshares || 0, failures: s.screenWatchdogFailures || 0 };
+ };
+ const start = ladder();
+ let prev = await screen();
+ let paintedQuiet = 0;
+ let longestPaintedQuiet = 0;
+ const watch = async (seconds, label) => {
+ for (let i = 0; i < seconds; i += 1) {
+ await new Promise((r) => setTimeout(r, 1000));
+ const now = await screen();
+ const a = now.stats || {};
+ const b = prev.stats || {};
+ const same = a.mid === b.mid;
+ const d = (k) => (same ? (a[k] || 0) - (b[k] || 0) : 'new ' + (a[k] || 0));
+ const painted = now.painted - prev.painted;
+ paintedQuiet = painted > 0 ? 0 : paintedQuiet + 1;
+ longestPaintedQuiet = Math.max(longestPaintedQuiet, paintedQuiet);
+ const s = (sample && sample.stats) || {};
+ if (verbose || i % 5 === 4 || painted === 0) {
+ console.log(`${label} t=${i + 1}s mid ${a.mid} ${a.width}x${a.height} ${a.decoder} | packets +${d('packets')} received +${d('received')} ` +
+ `decoded +${d('decoded')} dropped +${d('dropped')} keyframes +${d('keyframes')} freezes ${a.freezes} pli ${a.pli} | ` +
+ `painted +${painted} clock +${(now.time - prev.time).toFixed(2)} ${now.size || ''} | app sent ${s.screenSendWidth}x${s.screenSendHeight} ` +
+ `fps ${(s.screenSendFpsTenths || 0) / 10} limit ${s.screenLimitation} target ${Math.round((s.screenTargetBitrate || 0) / 1000)}k ` +
+ `sent ${Math.round((s.screenSentBitrate || 0) / 1000)}k captured ${s.screenFramesCaptured} encoded ${s.screenFramesEncoded} sentFrames ${s.screenFramesSent} | camera +${(now.camera || 0) - (prev.camera || 0)} | ladder ${JSON.stringify(ladder())}`);
+ }
+ prev = now;
+ }
+ };
+
+ if (scenario === 'encoder') {
+ await watch(10, 'before');
+ native.stdin.write('screen-encoder-stall\n');
+ await watch(12, 'stopped');
+ const reported = ladder().reports - start.reports;
+ const mended = (sample && sample.stats.screenWatchdogKeyframes) || 0;
+ console.log(`the app's own watch: ${JSON.stringify(ladder())}, keyframes asked ${mended}`);
+ const base = (await screen()).painted;
+ await wait(async () => (await screen()).painted > base + 10, `${engine} paints the screen again with nobody sharing again`, 30);
+ if (asserting) assert.equal(ladder().reshares - start.reshares, 0, 'mended without a share again');
+ console.log(`PASS ${engine}: a screen that stopped leaving was mended (reports ${reported})`);
+ } else if (scenario === 'wedge') {
+ await watch(8, 'before');
+ const n = await page.evaluate(() => window.__wedge(true));
+ console.log(`wedged ${n} screen receiver(s)`);
+ await watch(14, 'wedged');
+ const reported = ladder().reports - start.reports;
+ if (asserting) assert.ok(reported >= 1, `the wedged screen is reported (${reported})`);
+ console.log(`PASS ${engine}: a genuine stall is still reported (${reported})`);
+ await page.evaluate(() => window.__wedge(false));
+ const base = (await screen()).painted;
+ await wait(async () => (await screen()).painted > base + 2, `${engine} paints the screen again once the wedge lifts`, 30);
+ const cleared = async () => !stallLines.length || (await page.evaluate(() => !(window.meet.state().screenStalled || []).length));
+ await wait(cleared, 'the report clears', 20);
+ console.log(`PASS ${engine}: the wedged screen recovered`);
+ } else {
+ await watch(SECONDS, scenario);
+ const end = ladder();
+ const reports = end.reports - start.reports;
+ console.log(`${engine} ${scenario}: ${reports} stall report(s) at the app, ladder ${JSON.stringify(end)}; ` +
+ `longest stretch with nothing painted ${longestPaintedQuiet} s; reported here ${stallLines.length}`);
+ if (asserting) {
+ assert.equal(reports, 0, `a ${scenario} screen that is being painted is never reported stalled (${reports})`);
+ assert.equal(end.rebuilds - start.rebuilds + end.reshares - start.reshares, 0, 'nothing was rebuilt or shared again');
+ }
+ console.log(`PASS ${engine} ${scenario}: no stall reported, nothing rebuilt`);
+ }
+ void w;
+ clearInterval(nudge);
+ native.stdin.write('leave\n');
+ await new Promise((r) => setTimeout(r, 1000));
+} catch (err) {
+ if (!(err instanceof Skip)) {
+ console.log('FAIL ' + (err && err.message ? err.message : String(err)));
+ process.exitCode = 1;
+ }
+} finally {
+ if (nudge) clearInterval(nudge);
+ if (native && !exited) native.kill();
+ await browser.close();
+}
diff --git a/test/browser/room-quality.test.mjs b/test/browser/room-quality.test.mjs
index cab399c..4b61626 100644
--- a/test/browser/room-quality.test.mjs
+++ b/test/browser/room-quality.test.mjs
@@ -230,6 +230,21 @@ test('the screen ladder and the mending by person, and only what happened', () =
assert.deepEqual(p.events, { cantHearSeconds: 2.5, noSoundFromUs: true });
});
+test('the screen stalls judged here, with what the statistics said, and steps held back as a loop', () => {
+ const now = q.qualityReading(walk(1), classify);
+ const report = q.qualityReport({
+ seconds: 30,
+ client: { app: 'web' },
+ peers: [{ id: PEER, prev: null, now, ladder: { keyframes: 1, rebuilds: 0, reshares: 0, failures: 1, damped: 1 },
+ reattaches: 0, stalls: { stalls: 2, noPackets: 2, undecoded: 0 } }],
+ });
+ const p = report.peers[0];
+ assert.deepEqual(p.out.screen, { keyframes: 1, failures: 1, damped: 1 });
+ assert.deepEqual(p.in.screen, Object.assign({}, p.in.screen, { stalls: 2, stallsNoPackets: 2 }));
+ assert.equal(p.in.screen.stallsUndecoded, undefined, 'none is left out');
+ assert.equal(p.in.screen.reattaches, undefined);
+});
+
// ── the notices ──────────────────────────────────────────────────────
test('the notices: counted once each time they appear, timed while they show', () => {
diff --git a/test/browser/room-screen.test.mjs b/test/browser/room-screen.test.mjs
index 1aa5403..9dfb996 100644
--- a/test/browser/room-screen.test.mjs
+++ b/test/browser/room-screen.test.mjs
@@ -44,6 +44,7 @@ function liftConst(name) {
const CONSTS = [
'SCREEN_STALL_AFTER', 'SCREEN_STALL_GIVE_UP', 'SCREEN_REATTACH_AFTER', 'SCREEN_REBUILD_AFTER',
'SCREEN_RESHARE_AFTER', 'SCREEN_GIVE_UP_AFTER', 'SCREEN_REBUILD_EVERY',
+ 'SCREEN_LOOP_WITHIN', 'SCREEN_LOOP_LIMIT', 'SCREEN_LOOP_REST',
].map(liftConst).join('\n');
const build = (name) =>
// eslint-disable-next-line no-new-func
@@ -53,6 +54,7 @@ const judgeScreen = build('judgeScreen');
const recoveringWords = build('recoveringWords');
const reattachDue = build('reattachDue');
const escalateShare = build('escalateShare');
+const shareRestored = build('shareRestored');
const readingMoved = new Function(lift(src, 'readingSummary') + '\n' + lift(src, 'readingMoved') + '; return readingMoved;')();
// eslint-disable-next-line no-new-func
const noticeWords = new Function(lift(src, 'recoveringWords') + '\n' + lift(src, 'noticeWords') + '; return noticeWords;')();
@@ -110,7 +112,7 @@ function ladder(from, to, reported, opts = {}) {
for (let t = from; t < to; t++) {
const now = t * 1000;
if (!reported(t)) {
- rec.stage = '';
+ if (rec.stage) shareRestored(rec, now);
continue;
}
const owed = opts.owed ? opts.owed(t) : true;
@@ -138,8 +140,23 @@ test('rebuilds and shares again are rationed', () => {
const first = ladder(0, 20, (t) => t >= 3 && t < 12);
const second = ladder(20, 50, (t) => t >= 25 && t < 34, { rec: first.rec, resharedAt: first.resharedAt });
assert.deepEqual(second.out, [[31, 'reshare']], 'no second rebuild inside a minute');
- const third = ladder(80, 120, (t) => t >= 85, { rec: second.rec, resharedAt: second.resharedAt });
- assert.deepEqual(third.out, [[91, 'rebuild'], [101, 'failed']], 'and no second share again inside five');
+ // More than two minutes after the last restore, so not a loop.
+ const third = ladder(160, 200, (t) => t >= 165, { rec: second.rec, resharedAt: second.resharedAt });
+ assert.deepEqual(third.out, [[171, 'rebuild'], [181, 'failed']], 'and no second share again inside five');
+});
+
+test('a restart that mends it only briefly is not taken again for ten minutes', () => {
+ // Paul to Farshad in Safari, 2026-10-21: a report of nine seconds every
+ // forty. The first is rebuilt, the second shared again; the third is
+ // the second in a row to come back soon after a restart restored it.
+ const { out, rec } = ladder(0, 600, (t) => t % 40 >= 3 && t % 40 < 12);
+ const restarts = out.filter(([, a]) => a === 'rebuild' || a === 'reshare');
+ assert.deepEqual(restarts, [[9, 'rebuild'], [49, 'reshare']]);
+ assert.ok(out.some(([t, a]) => t === 89 && a === 'damped'), JSON.stringify(out));
+ assert.ok(out.every(([t, a]) => t < 89 || a === 'damped'), 'nothing but held back, while it lasts');
+ // Ten minutes on, the whole ladder again.
+ const later = ladder(700, 760, (t) => t >= 705, { rec });
+ assert.deepEqual(later.out.slice(0, 1), [[711, 'rebuild']]);
});
test('nothing sent is nothing to escalate', () => {