Merge origin/main (39eb304: Safari screen stall fix, 0.4.12) into fix/auto-ice-restart
Their spec section took 15.27, so this branch's becomes 15.28, and every reference this branch added is renumbered. Quality tally: both sets of steps kept (damped, encoderStall, stall; autoRestart, autoRebuild).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
38 files changed,
+1,323
−125
Makefile+7 −5callscore/client.go+3 −3callscore/client_test.go+1 −1cmd/quality-summary/main.go+213 −11cmd/quality-summary/main_test.go+78 −0docs/superpowers/specs/2026-09-07-meet-design.md+82 −4internal/calls/hub/hub.go+2 −2internal/calls/quality.go+47 −1internal/calls/static/room.js+102 −23internal/calls/stream.go+1 −1internal/callstest/client_test.go+1 −1internal/callstest/harness_test.go+1 −1internal/callstest/native_browser_test.go+42 −0internal/callstest/native_ice_test.go+1 −1internal/callstest/quality_test.go+46 −1native/apple/Sources/CallsInterop/Interop.swift+13 −2native/apple/Sources/CallsInterop/SyntheticVideo.swift+52 −4native/apple/Sources/CallsKit/Call.swift+17 −12native/apple/Sources/CallsKit/ConnectionRecovery.swift+2 −2native/apple/Sources/CallsKit/Media.swift+28 −13native/apple/Sources/CallsKit/QualityReport.swift+39 −5native/apple/Sources/CallsKit/ScreenSendPolicy.swift+64 −4native/apple/Sources/CallsKit/ScreenWatchdog.swift+67 −2native/apple/Sources/CallsKit/Wire.swift+1 −1native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift+2 −2native/apple/Tests/CallsKitTests/ScreenSendTests.swift+31 −0native/apple/Tests/CallsKitTests/ScreenWatchdogTests.swift+31 −2native/bridge/bridge.go+2 −2protocol/client.go+5 −5protocol/messages.go+2 −2protocol/quality.go+12 −1test/browser/call.mjs+3 −3test/browser/native-ice.mjs+2 −2test/browser/native-screen-receivers.mjs+285 −0test/browser/room-mute.test.mjs+2 −2test/browser/room-quality.test.mjs+15 −0test/browser/room-recovery.test.mjs+1 −1test/browser/room-screen.test.mjs+20 −3
diff --git a/Makefile b/Makefile| index 367aaa0..09e2561 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -189,16 +189,18 @@ 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, and spec §15.27's |
| +# Two apps in one call, sharing screens to each other, and spec §15.28's |
| # connection that never comes up (TestNativeMacIceRecovery). Separate from |
| # native-browser because two unsigned apps on one Mac do not reliably |
| # connect, which looks like the macOS firewall: see TestNativeMacScreenShare. |
diff --git a/callscore/client.go b/callscore/client.go| index 7b409ff..13ec43f 100644 |
| --- a/callscore/client.go |
| +++ b/callscore/client.go |
| @@ -6,10 +6,10 @@ import ( |
| "amadan.net/oficina/calls/protocol" |
| ) |
| -// The app this core is running in, as spec §15.27 has every app say on |
| +// The app this core is running in, as spec §15.28 has every app say on |
| // its requests (protocol.ClientHeader): "mac 0.4.12". Set once by the |
| // host before it joins; nothing is sent until it has been, which is how |
| -// an app from before §15.27 looks to the server, and the server calls |
| +// an app from before §15.28 looks to the server, and the server calls |
| // that "native". |
| var client struct { |
| sync.Mutex |
| @@ -38,7 +38,7 @@ func ClientLabel() string { |
| } |
| // RefreshICE asks the core for a fresh /ice answer now rather than at the |
| -// schedule's time (spec §15.27: a connection about to be restarted on |
| +// schedule's time (spec §15.28: a connection about to be restarted on |
| // relay credentials that are due for renewal renews them first). The |
| // answer arrives as the usual "ice" event; nothing happens before |
| // admission, as for any fetch. |
diff --git a/callscore/client_test.go b/callscore/client_test.go| index 4d71653..fb47251 100644 |
| --- a/callscore/client_test.go |
| +++ b/callscore/client_test.go |
| @@ -33,7 +33,7 @@ func TestSetClient(t *testing.T) { |
| } |
| // Every request the core makes says which app it is, once set; and says |
| -// nothing before, as an app from before §15.27 does. |
| +// nothing before, as an app from before §15.28 does. |
| func TestRequestsCarryTheClient(t *testing.T) { |
| t.Cleanup(func() { client.label = "" }) |
| var got []string |
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 68d8632..7b184b3 100644 |
| --- a/docs/superpowers/specs/2026-09-07-meet-design.md |
| +++ b/docs/superpowers/specs/2026-09-07-meet-design.md |
| @@ -768,7 +768,7 @@ offer. This is what lets either side add a screen track or restart ICE |
| without an offer-request message. All candidates trickle as `candidate` |
| messages. A connection that reaches `failed` shows the tile as "could |
| not connect" with a retry that restarts ICE; nothing is silently spun. |
| -(Since §15.27 a connection that fails is restarted and rebuilt on its |
| +(Since §15.28 a connection that fails is restarted and rebuilt on its |
| own first, and "could not connect" waits a minute.) |
| ### 5.2 ICE servers from the platform |
| @@ -2904,7 +2904,84 @@ 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 §5.1, §5.3, §4.6, §15.23, §15.26 — a connection that stops working is mended, and an old app is named (2026-10-21) |
| +### 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. |
| + |
| +### 15.28 §5.1, §5.3, §4.6, §15.23, §15.26 — a connection that stops working is mended, and an old app is named (2026-10-21) |
| **Why.** 21 October, about 14:41 UTC: Paul, on the Mac app (0.4.10) and |
| sharing his screen; Farshad, in the call from Safari, left and came back |
| @@ -2933,8 +3010,9 @@ it 29–42 s after the block, by accident. In Chromium the same accident is |
| — a person with no camera, or theirs turned off — nothing did, and the pair |
| stayed down for the two minutes the scenario waited. The incident's own |
| quality lines cannot say which it was: the Mac app on the far side sent |
| -none, and `carlos logs` now prints a line's top-level fields only, not its |
| -`report` member, so `cmd/quality-summary` reads nothing from it. |
| +none, and Paul's say only, at 14:41:26, `remotes=2` and `reconnecting=1` |
| +(`carlos logs` prints a line's top-level fields, not its `report` |
| +member, so the per-peer path and packets are not readable after the fact). |
| **Decision: the recovery.** Per remote peer, across that pair's |
| connections (a rebuild is the same episode), the apps' `ConnectionRecovery` |
diff --git a/internal/calls/hub/hub.go b/internal/calls/hub/hub.go| index 6507b2a..ffd9892 100644 |
| --- a/internal/calls/hub/hub.go |
| +++ b/internal/calls/hub/hub.go |
| @@ -104,7 +104,7 @@ type Participation struct { |
| // (§15.19), nil until it makes one. It lives and dies with the |
| // participation, so a resume keeps it and a fresh join starts unknown. |
| Media *MediaState |
| - // Client is what the participation was opened from (§15.27, |
| + // Client is what the participation was opened from (§15.28, |
| // protocol.ClientFor): "mac 0.4.12", "native", or "" for a browser. |
| // Set once, by the stream that opened it; carried in every roster. |
| Client string |
| @@ -260,7 +260,7 @@ func (h *Hub) Open(sqid, session string, personID int64, name string, kind Kind) |
| } |
| // SetClient records what a participation this session has just opened |
| -// was opened from (§15.27). Only a well-formed value is kept, and only on |
| +// was opened from (§15.28). Only a well-formed value is kept, and only on |
| // a participation not yet admitted, so the roster that admits it is the |
| // first to carry it and no roster ever changes it. |
| func (h *Hub) SetClient(sqid, session string, peer PeerID, client string) { |
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 242522e..82a46ac 100644 |
| --- a/internal/calls/static/room.js |
| +++ b/internal/calls/static/room.js |
| @@ -321,6 +321,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: |
| @@ -335,7 +346,7 @@ |
| const RECONNECT_AUDIO_AFTER = 2000; |
| const RECONNECT_HOLD = 1000; |
| const RECONNECT_EVERY = 200; |
| - // §15.27 (2026-10-21): a connection that stops working is mended without |
| + // §15.28 (2026-10-21): a connection that stops working is mended without |
| // anyone asking. ICE failed, disconnected RECOVER_DISCONNECTED_AFTER, or |
| // never connected RECOVER_CONNECT_AFTER after the connection was made is |
| // trouble; attempts follow RECOVER_BACKOFF and then RECOVER_EVERY: an ICE |
| @@ -352,7 +363,7 @@ |
| const RECOVER_FOLLOW = 3000; |
| const RECOVER_NOTICE_AFTER = 60000; |
| const RECOVER_FLAP = 60000; |
| - // §15.27: the oldest app that does not break a call for the people in |
| + // §15.28: the oldest app that does not break a call for the people in |
| // it with it (protocol.MinNativeVersion carries the reason). |
| const MIN_NATIVE_VERSION = '0.4.2'; |
| // §15.24 (2026-10-01), "<name> is connecting and can't hear you yet": |
| @@ -433,7 +444,7 @@ |
| // §15.19: peer id -> {muted, cameraOff}, for the peers that have |
| // reported. A peer absent here is unknown and is drawn as neither. |
| const remoteMedia = new Map(); |
| - // §15.27: peer id -> what their participation was opened from, as the |
| + // §15.28: peer id -> what their participation was opened from, as the |
| // roster says ("mac 0.4.12", "native", or '' for a browser); peer id -> |
| // the recovery record of their connections; and, for the gate only, |
| // until when every ICE candidate either way is pointed at nothing. |
| @@ -467,14 +478,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(); |
| @@ -1898,7 +1915,7 @@ |
| pending: [], |
| descSeq: 0, |
| gen: g, |
| - // §15.27, what the recovery reads: when this connection was made, |
| + // §15.28, what the recovery reads: when this connection was made, |
| // when the far side last restarted ICE on it (an offer with a new |
| // username fragment), the fragment it is on, and whether a |
| // description refused to apply. |
| @@ -2006,7 +2023,7 @@ |
| pc.addEventListener('connectionstatechange', () => { |
| if (pcs.get(id) !== entry) return; |
| // Whether it has failed for long enough to say so is the |
| - // recovery's verdict (§15.27), not this event's. |
| + // recovery's verdict (§15.28), not this event's. |
| renderTiles(); |
| }); |
| @@ -2409,7 +2426,7 @@ |
| await entry.pc.setRemoteDescription(desc); |
| entry.ignoreOffer = false; |
| entry.descSeq = msg.seq || entry.descSeq; |
| - // §15.27: a new username fragment is the far side restarting ICE. |
| + // §15.28: a new username fragment is the far side restarting ICE. |
| const m = /(?:^|\r\n)a=ice-ufrag:([^\r\n]+)/.exec(desc.sdp || ''); |
| const ufrag = m ? m[1] : ''; |
| if (ufrag && entry.remoteUfrag && ufrag !== entry.remoteUfrag) entry.remoteRestartAt = Date.now(); |
| @@ -2424,7 +2441,7 @@ |
| send(msg.from, 'answer', { description: describe(entry.pc.localDescription) }); |
| } catch { |
| // A description that will not apply leaves the pair to its |
| - // recovery (§15.27) rather than throwing into the event handler. |
| + // recovery (§15.28) rather than throwing into the event handler. |
| entry.errored = true; |
| } |
| } |
| @@ -4455,7 +4472,7 @@ |
| for (const rp of roster.peers || []) { |
| if (!rp || !rp.peer) continue; |
| if (rp.peer !== state.peer) { |
| - // §15.27: and what their participation was opened from. |
| + // §15.28: and what their participation was opened from. |
| clients.set(rp.peer, rp.client || ''); |
| learnMedia(rp.peer, rp.media); |
| continue; |
| @@ -4643,6 +4660,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; |
| @@ -4666,7 +4692,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; |
| } |
| @@ -4693,12 +4724,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); |
| @@ -4710,6 +4744,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'); |
| @@ -5085,7 +5126,7 @@ |
| autoRestarts: 0, autoRebuilds: 0 }; |
| } |
| - // qualityCount counts one of the recovery's steps toward a peer (§15.27) |
| + // qualityCount counts one of the recovery's steps toward a peer (§15.28) |
| // into the window's events: autoRestarts or autoRebuilds. |
| function qualityCount(id, key) { |
| let p = qualityEvents.peers.get(id); |
| @@ -5157,17 +5198,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; |
| @@ -5208,7 +5254,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; |
| @@ -5272,12 +5318,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]; |
| @@ -5447,7 +5495,7 @@ |
| } |
| // --------------------------------------------------------------- |
| - // A connection that stops working is mended (§15.27, 2026-10-21) |
| + // A connection that stops working is mended (§15.28, 2026-10-21) |
| // --------------------------------------------------------------- |
| // |
| // Paul, on the Mac app and sharing, saw "Reconnecting to Farshad (Mac)…" |
| @@ -5887,11 +5935,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; |
| @@ -5914,6 +5978,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; |
| } |
| @@ -7158,7 +7230,7 @@ |
| // "even through the relay" is a claim about this instance, and |
| // data-relay is where the server states it. |
| // peerNote is the tile's note: tileNote's sentence about the connection, |
| - // and §15.27's about their app when that is worth saying. Alone, that |
| + // and §15.28's about their app when that is worth saying. Alone, that |
| // one is about their app and not this connection, so it comes without |
| // the Retry. |
| function peerNote(id, entry) { |
| @@ -7353,7 +7425,7 @@ |
| return; |
| } |
| // A note is a sentence, with the Retry beside it, or {text, retry} for |
| - // one that has nothing to retry (§15.27's note about someone's app). |
| + // one that has nothing to retry (§15.28's note about someone's app). |
| const note = noteText && typeof noteText === 'object' ? noteText : { text: noteText || '', retry: !!noteText }; |
| const show = !!note.text; |
| t.note.hidden = !show; |
| @@ -8377,7 +8449,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))); |
| } |
| @@ -8548,13 +8627,13 @@ |
| qualityEveryForTest(ms) { |
| qualityEvery = Math.max(QUALITY_EVERY_MIN, Math.min(Number(ms) || QUALITY_EVERY, QUALITY_EVERY)); |
| }, |
| - // §15.27, for the gate: every ICE candidate this tab sends or receives |
| + // §15.28, for the gate: every ICE candidate this tab sends or receives |
| // leads nowhere for `ms` (at most five minutes), so its connections |
| // fail and only the recovery mends them. |
| blockIceForTest(ms) { |
| iceBlockUntil = Date.now() + Math.max(0, Math.min(Number(ms) || 0, 300000)); |
| }, |
| - // §15.27, for the gate: the recovery switched off (false) and on, so a |
| + // §15.28, for the gate: the recovery switched off (false) and on, so a |
| // scenario can stand in for a client from before it. |
| recoveryForTest(on) { |
| recoveryOn = !!on; |
| @@ -8591,7 +8670,7 @@ |
| shareRecovery, |
| // §15.22: what the ladder and the receiver's own mending have done. |
| shareRecoveries: Object.assign({ reattaches: screenReattaches }, shareCounts), |
| - // §15.27: each connection's recovery — trying, failing for a |
| + // §15.28: each connection's recovery — trying, failing for a |
| // minute, attempts this episode, restarts and rebuilds — the |
| // totals, the gate's block, and the peers' clients as the roster |
| // has them. |
diff --git a/internal/calls/stream.go b/internal/calls/stream.go| index af71c6d..9f02474 100644 |
| --- a/internal/calls/stream.go |
| +++ b/internal/calls/stream.go |
| @@ -285,7 +285,7 @@ func (a *app) stream(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| sub, peer = res.Sub, res.Peer |
| - // §15.27: which app, at which version, for the people in the call. |
| + // §15.28: which app, at which version, for the people in the call. |
| a.hub.SetClient(sqid, session, peer, protocol.ClientFor(r.Header.Get(protocol.ClientHeader), r.UserAgent())) |
| first = append(first, hub.Message{Type: hub.TypeHello, Peer: peer, Boot: a.hub.Boot(), Report: res.ReportToken}) |
| } |
diff --git a/internal/callstest/client_test.go b/internal/callstest/client_test.go| index d717a8d..e0c2738 100644 |
| --- a/internal/callstest/client_test.go |
| +++ b/internal/callstest/client_test.go |
| @@ -6,7 +6,7 @@ import ( |
| "time" |
| ) |
| -// Spec §15.27: every roster names what each peer's participation was |
| +// Spec §15.28: every roster names what each peer's participation was |
| // opened from — an app's own "<app> <version>" header, "native" for an |
| // app from before it (the Go HTTP client's agent and no header), nothing |
| // for a browser — and the `peer` event that admits a newcomer carries it. |
diff --git a/internal/callstest/harness_test.go b/internal/callstest/harness_test.go| index 3598aeb..a3753fa 100644 |
| --- a/internal/callstest/harness_test.go |
| +++ b/internal/callstest/harness_test.go |
| @@ -314,7 +314,7 @@ type client struct { |
| x *harness |
| cookies map[string]*http.Cookie |
| // streamHeaders, when set, go on the client's stream GETs in place of |
| - // the browser's user agent the stream otherwise sends (§15.27 reads |
| + // the browser's user agent the stream otherwise sends (§15.28 reads |
| // the app's header and the Go HTTP client's agent there). |
| streamHeaders map[string]string |
| } |
diff --git a/internal/callstest/native_browser_test.go b/internal/callstest/native_browser_test.go| index 9e3325d..967c520 100644 |
| --- a/internal/callstest/native_browser_test.go |
| +++ b/internal/callstest/native_browser_test.go |
| @@ -1019,3 +1019,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/native_ice_test.go b/internal/callstest/native_ice_test.go| index 2f1afbd..9d3e6cf 100644 |
| --- a/internal/callstest/native_ice_test.go |
| +++ b/internal/callstest/native_ice_test.go |
| @@ -115,7 +115,7 @@ func TestNativeMacIceRecovery(t *testing.T) { |
| // The connection does not come up while the block lasts. For its |
| // first fifty seconds nothing worse than "Reconnecting to …" is said; |
| - // past a minute (spec §15.27) the failure notice is, and for an app |
| + // past a minute (spec §15.28) the failure notice is, and for an app |
| // that does not say its version, that it may be old. |
| const failure = "A participant’s media could not connect." |
| oldPeer := oldBinary || mode == "old-peer" |
diff --git a/internal/callstest/quality_test.go b/internal/callstest/quality_test.go| index 321a690..268f3a0 100644 |
| --- a/internal/callstest/quality_test.go |
| +++ b/internal/callstest/quality_test.go |
| @@ -237,7 +237,13 @@ func TestQualityReportsShareACallTagAndNameNothing(t *testing.T) { |
| t.Errorf("line[%q] = %v (%T), want %v", k, a[k], a[k], want) |
| } |
| } |
| - // §15.27: the connection's own recovery toward that peer. |
| + // 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) |
| + } |
| + } |
| + // §15.28: the connection's own recovery toward that peer. |
| if ev, _ := peers[0].(map[string]any)["events"].(map[string]any); ev["autoRestarts"] != 2.0 || ev["autoRebuilds"] != 1.0 { |
| t.Errorf("the recovery's counts are not in the line: %v", ev) |
| } |
| @@ -611,3 +617,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 d5b1794..9dbdbc3 100644 |
| --- a/native/apple/Sources/CallsInterop/Interop.swift |
| +++ b/native/apple/Sources/CallsInterop/Interop.swift |
| @@ -133,7 +133,7 @@ struct Input: Decodable { |
| if let ms = ProcessInfo.processInfo.environment["CALLS_TEST_ICE_BLOCK_MS"].flatMap(Double.init), ms > 0 { |
| call.blockICEForTest(ms: ms) |
| } |
| - // §15.27: the stand-in for an app from before it, which neither mends |
| + // §15.28: the stand-in for an app from before it, which neither mends |
| // its connections nor says which app it is; and the version this |
| // bundle-less executable says it is otherwise. |
| if ProcessInfo.processInfo.environment["CALLS_AUTO_RECOVERY"] == "0" { Call.autoRecovery = false } |
| @@ -245,6 +245,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 ") { |
| @@ -369,7 +380,7 @@ struct Input: Decodable { |
| // The call's status line, word for word ("A participant's media |
| // could not connect." among them). |
| "status": call.status, |
| - // Each remote peer's client as the roster has it (§15.27). |
| + // Each remote peer's client as the roster has it (§15.28). |
| "clients": Dictionary( |
| uniqueKeysWithValues: (call.state?.peers ?? []).filter { $0.peer != call.state?.peer }.map { |
| ($0.peer, $0.client ?? "") |
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 7824395..beffa0a 100644 |
| --- a/native/apple/Sources/CallsKit/Call.swift |
| +++ b/native/apple/Sources/CallsKit/Call.swift |
| @@ -94,7 +94,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| @Published public private(set) var reconnecting = false |
| @Published public private(set) var reconnectingPeers: Set<String> = [] |
| /// A connection that stops working is mended without anyone asking (spec |
| - /// §15.27): each remote peer's recovery, the restarts waiting on a fresh |
| + /// §15.28): each remote peer's recovery, the restarts waiting on a fresh |
| /// `/ice` answer, and the peers whose connection has been failing for a |
| /// minute, which is when "A participant's media could not connect." is |
| /// said (and their tile may say their app is old). |
| @@ -103,9 +103,9 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| @Published public private(set) var failingPeers: Set<String> = [] |
| private var autoRestartsTotal: UInt64 = 0 |
| private var autoRebuildsTotal: UInt64 = 0 |
| - /// Off only for the gate's stand-in for an app from before §15.27. |
| + /// Off only for the gate's stand-in for an app from before §15.28. |
| @_spi(Fixtures) public static var autoRecovery = true |
| - /// Whether this app says which it is (§15.27); off only for the same |
| + /// Whether this app says which it is (§15.28); off only for the same |
| /// stand-in. `clientVersion` stands in for a bundle that has none (the |
| /// interop executable). |
| @_spi(Fixtures) public static var sendsClientInfo = true |
| @@ -383,7 +383,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| if let old { await Task.detached { old.leave() }.value } |
| guard epoch == joiningEpoch else { throw CancellationError() } |
| let listener = Events(call: self, epoch: epoch) |
| - // §15.27: which app this is, on every request the core makes. |
| + // §15.28: which app this is, on every request the core makes. |
| if Self.sendsClientInfo { |
| let info = QualityClientInfo.current() |
| if let version = info.version ?? Self.clientVersion { _ = BridgeSetClientInfo(info.app, version) } |
| @@ -790,7 +790,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| joining: nowJoining.contains(person.peer), shown: connectingPeers.contains(person.peer), |
| reconnecting: reconnectingPeers.contains(person.peer)) |
| remotePeakSinceSample = max(remotePeakSinceSample, reading.peak) |
| - // §15.27: and what their app is, when that is worth saying. |
| + // §15.28: and what their app is, when that is worth saying. |
| var notices = said.notices |
| if let old = ClientVersion.notice( |
| name: person.name, client: person.client, failing: failingPeers.contains(person.peer)) |
| @@ -845,14 +845,14 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| /// What the status line says while admitted: "Reconnecting…" for the |
| /// whole call (§15.23), the failure notice once a connection has been |
| - /// failing for a minute (§15.27), or that all is well. |
| + /// failing for a minute (§15.28), or that all is well. |
| private var admittedStatus: String { |
| if reconnecting { return ReconnectWords.call } |
| if !failingPeers.isEmpty { return Self.failureWords } |
| return "In the meeting" |
| } |
| - /// One look by every connection's recovery (spec §15.27), and whatever it |
| + /// One look by every connection's recovery (spec §15.28), and whatever it |
| /// asks for. Returns the peers it is trying to mend now, whose tiles say |
| /// "Reconnecting to …". |
| private func watchRecovery(now: Double, state: RoomState) -> Set<String> { |
| @@ -890,7 +890,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| return trying |
| } |
| - /// §15.27's restart, after fresh relay credentials when the ones in hand |
| + /// §15.28's restart, after fresh relay credentials when the ones in hand |
| /// are due for renewal (§5.3): a restart onto a credential the relay is |
| /// about to stop honouring would only fail again. |
| private func recoveryRestart(_ peer: String, attempt: Int) { |
| @@ -908,7 +908,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| media.restartICE(peer) |
| } |
| - /// §15.27's rebuild: the hub's pair reset (§4.6), which gives both sides |
| + /// §15.28's rebuild: the hub's pair reset (§4.6), which gives both sides |
| /// a new generation and so a new connection, exactly as a leave and a |
| /// join did — for this one person, and keeping the call. |
| private func recoveryRebuild(_ peer: String, attempt: Int) { |
| @@ -1038,7 +1038,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| floor = config.iceServers.isEmpty |
| if let state { media.reconcile(state: state, ice: config) } |
| if renewing { |
| - // §15.27: recovery restarts that waited for this answer go now, on |
| + // §15.28: recovery restarts that waited for this answer go now, on |
| // whichever connections the renewal itself did not restart. |
| let restarted = media.updateICE(config) |
| for peer in restartsAwaitingICE.subtracting(restarted) { media.restartICE(peer) } |
| @@ -1172,7 +1172,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( |
| @@ -1268,6 +1268,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() |
| @@ -1408,7 +1411,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| values["iceConnectedPeers"] = UInt64(iceConnectedPeers) |
| values["iceFailedPeers"] = UInt64(iceFailedPeers) |
| values["iceBlockMangled"] = ICETestBlock.mangled |
| - // §15.27: the recovery's restarts and rebuilds so far, and the people |
| + // §15.28: the recovery's restarts and rebuilds so far, and the people |
| // it is trying to mend now, and has been for a minute. |
| values["autoRestarts"] = autoRestartsTotal |
| values["autoRebuilds"] = autoRebuildsTotal |
| @@ -1580,6 +1583,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/ConnectionRecovery.swift b/native/apple/Sources/CallsKit/ConnectionRecovery.swift| index 3777a66..483874a 100644 |
| --- a/native/apple/Sources/CallsKit/ConnectionRecovery.swift |
| +++ b/native/apple/Sources/CallsKit/ConnectionRecovery.swift |
| @@ -1,7 +1,7 @@ |
| import Foundation |
| /// A connection that stops working is mended without anyone asking (spec |
| -/// §15.27, 2026-10-21). |
| +/// §15.28, 2026-10-21). |
| /// |
| /// Paul, on the Mac app and sharing his screen, saw "Reconnecting to Farshad |
| /// (Mac)…" and "A participant's media could not connect" when Farshad moved |
| @@ -157,7 +157,7 @@ struct ConnectionRecovery: Equatable { |
| } |
| } |
| -/// "Farshad is on an old version of Calls" (spec §15.27): what a tile says |
| +/// "Farshad is on an old version of Calls" (spec §15.28): what a tile says |
| /// about the app at the other end, from the roster's `client`. |
| enum ClientVersion { |
| /// The oldest app that does not break a call for the people in it with |
diff --git a/native/apple/Sources/CallsKit/Media.swift b/native/apple/Sources/CallsKit/Media.swift| index ba38a33..31a1c74 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. |
| @@ -306,7 +312,7 @@ import LiveKitWebRTC |
| return restarted |
| } |
| - /// Each connection as ConnectionRecovery reads it (spec §15.27): its ICE |
| + /// Each connection as ConnectionRecovery reads it (spec §15.28): its ICE |
| /// state as the delegate last reported it, when it was made, which side |
| /// leads, its last remote offer, and whether a step on it threw. No hop |
| /// into WebRTC: all of it is kept on the main actor as it happens. |
| @@ -318,7 +324,7 @@ import LiveKitWebRTC |
| } |
| } |
| - /// §15.27's ICE restart, for one connection, on the list it holds now. |
| + /// §15.28's ICE restart, for one connection, on the list it holds now. |
| func restartICE(_ peer: String) { peers[peer]?.recoveryRestart() } |
| /// The five audio-health fields, gathered alongside the byte counts. |
| /// |
| @@ -584,7 +590,7 @@ struct PeerAudioReading: Equatable, Sendable { |
| // but could not make yet, because it was in the middle of another. |
| private var screenTx: RTCRtpTransceiver? |
| private var owesOffer = false |
| - // §15.27, what ConnectionRecovery reads: when this connection was made, |
| + // §15.28, what ConnectionRecovery reads: when this connection was made, |
| // its ICE state as the delegate last said, when a remote offer was last |
| // applied, and whether a negotiation step on it threw. |
| let builtAt = ProcessInfo.processInfo.systemUptime |
| @@ -703,12 +709,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) |
| @@ -859,7 +874,7 @@ struct PeerAudioReading: Equatable, Sendable { |
| await previous?.value |
| guard let self, !self.closed, !Task.isCancelled else { return } |
| do { try await action() } catch { |
| - // §15.27: a step that threw leaves this connection to its recovery |
| + // §15.28: a step that threw leaves this connection to its recovery |
| // (an ICE restart, then a rebuild), which says so if it lasts. |
| guard !self.closed else { return } |
| if !self.errored { CallLog.info("connection to \(self.id.prefix(6)): a negotiation step failed: \(error.localizedDescription)") } |
| @@ -911,7 +926,7 @@ struct PeerAudioReading: Equatable, Sendable { |
| } else { |
| // A candidate refused is not a connection broken: one from the |
| // generation before an ICE restart is refused as a matter of |
| - // course. ICE says whether the connection works (§15.27). |
| + // course. ICE says whether the connection works (§15.28). |
| do { try await self.add(candidate) } catch {} |
| } |
| return |
| @@ -1001,7 +1016,7 @@ struct PeerAudioReading: Equatable, Sendable { |
| return restart |
| } |
| - /// §15.27: an ICE restart because this connection is not working, on the |
| + /// §15.28: an ICE restart because this connection is not working, on the |
| /// list it holds now (`updateICE` has handed it every list since it was |
| /// made). An offer of this side's still waiting for its answer is rolled |
| /// back first, because an outstanding offer is the one thing that keeps |
| @@ -1159,7 +1174,7 @@ struct PeerAudioReading: Equatable, Sendable { |
| nonisolated func peerConnection( |
| _ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState |
| ) { |
| - // §15.27: kept for ConnectionRecovery, which decides what a failure |
| + // §15.28: kept for ConnectionRecovery, which decides what a failure |
| // means and when it is worth saying. |
| let state: ConnectionRecovery.ICE |
| switch newState { |
diff --git a/native/apple/Sources/CallsKit/QualityReport.swift b/native/apple/Sources/CallsKit/QualityReport.swift| index 195fd80..1856d39 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 { |
| @@ -166,7 +175,7 @@ public struct QualityPeerEvents: Encodable, Equatable, Sendable { |
| public var noSoundFromUs: Bool? |
| public var audioBlocked: Bool? |
| public var screenStalled: Bool? |
| - /// §15.27: ICE restarts and rebuilds this app's recovery made. |
| + /// §15.28: ICE restarts and rebuilds this app's recovery made. |
| public var autoRestarts: Double? |
| public var autoRebuilds: Double? |
| } |
| @@ -446,7 +455,15 @@ 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, autoRestart, autoRebuild } |
| + public enum Step: Sendable { |
| + case keyframe, rebuild, reshare, failure, reattach, damped, encoderStall |
| + /// The connection's own recovery (§15.28). |
| + case autoRestart, autoRebuild |
| + /// 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 |
| @@ -461,7 +478,12 @@ public struct QualityEventTally: Equatable, Sendable { |
| var reshares = 0 |
| var failures = 0 |
| var reattaches = 0 |
| - /// The connection's own recovery (§15.27). |
| + var damped = 0 |
| + var encoderStalls = 0 |
| + var stalls = 0 |
| + var stallsNoPackets = 0 |
| + var stallsUndecoded = 0 |
| + /// The connection's own recovery (§15.28). |
| var autoRestarts = 0 |
| var autoRebuilds = 0 |
| } |
| @@ -513,6 +535,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 |
| + } |
| case .autoRestart: peers[peer, default: Peer()].autoRestarts += 1 |
| case .autoRebuild: peers[peer, default: Peer()].autoRebuilds += 1 |
| } |
| @@ -617,20 +646,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/Sources/CallsKit/Wire.swift b/native/apple/Sources/CallsKit/Wire.swift| index 2c5930a..7f4157a 100644 |
| --- a/native/apple/Sources/CallsKit/Wire.swift |
| +++ b/native/apple/Sources/CallsKit/Wire.swift |
| @@ -9,7 +9,7 @@ public struct RosterPeer: Decodable, Identifiable { |
| /// §15.19). Nil is unknown — a client that predates the report, or one |
| /// that has not made it yet — and is shown as neither muted nor off. |
| public let media: PeerMedia? |
| - /// What their participation was opened from (spec §15.27): "mac 0.4.12", |
| + /// What their participation was opened from (spec §15.28): "mac 0.4.12", |
| /// "native" for an app from before that, nil for a browser or a server |
| /// from before it. |
| public let client: String? |
diff --git a/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift b/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift| index 3ff2146..be78e70 100644 |
| --- a/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift |
| +++ b/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift |
| @@ -3,7 +3,7 @@ import XCTest |
| @testable import CallsKit |
| /// A connection that stops working is mended without anyone asking (spec |
| -/// §15.27, 2026-10-21): when it counts as broken, the backoff, the |
| +/// §15.28, 2026-10-21): when it counts as broken, the backoff, the |
| /// escalation to a rebuild, who acts, and when the failure is said. |
| final class ConnectionRecoveryTests: XCTestCase { |
| private typealias Look = ConnectionRecovery.Look |
| @@ -161,7 +161,7 @@ final class ConnectionRecoveryTests: XCTestCase { |
| "Farshad is on an old version of Calls — ask them to update") |
| XCTAssertNil(ClientVersion.notice(name: "Farshad", client: "mac 0.4.2", failing: true)) |
| XCTAssertNil(ClientVersion.notice(name: "Farshad", client: "mac 0.4.12", failing: true)) |
| - // No version at all: an app from before §15.27, only worth a word |
| + // No version at all: an app from before §15.28, only worth a word |
| // once the connection to it has been failing. |
| XCTAssertNil(ClientVersion.notice(name: "Farshad", client: "native", failing: false)) |
| XCTAssertEqual( |
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/native/bridge/bridge.go b/native/bridge/bridge.go| index 7c0f8f5..eca9ad9 100644 |
| --- a/native/bridge/bridge.go |
| +++ b/native/bridge/bridge.go |
| @@ -108,12 +108,12 @@ func (c *Client) Send(typ, to string, generation int64, payload string) error { |
| } |
| func (c *Client) Leave() { c.room.Leave() } |
| -// RefreshICE asks for a fresh /ice answer now (spec §15.27), delivered as |
| +// RefreshICE asks for a fresh /ice answer now (spec §15.28), delivered as |
| // the usual "ice" event. |
| func (c *Client) RefreshICE() { c.room.RefreshICE() } |
| // SetClientInfo is the app and its version, said on every request the |
| -// core makes (spec §15.27), so the people in a call can tell when |
| +// core makes (spec §15.28), so the people in a call can tell when |
| // someone's app is too old. Call it before NewClient; false is refused. |
| func SetClientInfo(app, version string) bool { return callscore.SetClient(app, version) } |
| func (c *Client) Close() { c.room.Close() } |
diff --git a/protocol/client.go b/protocol/client.go| index e955f83..e722ab3 100644 |
| --- a/protocol/client.go |
| +++ b/protocol/client.go |
| @@ -5,7 +5,7 @@ import ( |
| "strings" |
| ) |
| -// The client a participation was opened from (spec §15.27, 2026-10-21): |
| +// The client a participation was opened from (spec §15.28, 2026-10-21): |
| // which app, at which version, so that the people in a call can tell |
| // someone their app is too old to talk to theirs. |
| @@ -15,18 +15,18 @@ const ClientHeader = "X-Calls-Client" |
| // ClientNative is the roster's client for an app that did not say which it |
| // is: the core's requests carry Go's default user agent and no |
| -// ClientHeader, which is every app from before §15.27. |
| +// ClientHeader, which is every app from before §15.28. |
| const ClientNative = "native" |
| // MinNativeVersion is the oldest app version that does not break a call |
| -// for the people it is in it with (spec §15.27). Before 0.4.2 an app |
| +// for the people it is in it with (spec §15.28). Before 0.4.2 an app |
| // restarted ICE on every connection on every /ice answer — twelve times |
| // an hour, each one a pause for the screen and camera (§15.21) — and |
| // sent a Mac screen to browsers at a size their H.264 level refused, so |
| // the browser's picture froze for seconds at a time. Everything the wire |
| // needs to recover a connection — `pair` and generations (§4.6), answering |
| // an ICE restart, ignoring keys it does not know — every app has had |
| -// since the rename (0.2), and the recovery of §15.27 needs nothing of the |
| +// since the rename (0.2), and the recovery of §15.28 needs nothing of the |
| // far side but those. |
| const MinNativeVersion = "0.4.2" |
| @@ -100,7 +100,7 @@ func CompareVersions(a, b string) int { |
| // ClientFor is the roster's client for a request: the app's own header |
| // when it is well formed, ClientNative for a request from the Go HTTP |
| -// client with none (an app from before §15.27), and "" otherwise — a |
| +// client with none (an app from before §15.28), and "" otherwise — a |
| // browser, or a header that is not one this server can read. |
| func ClientFor(header, userAgent string) string { |
| if header != "" { |
diff --git a/protocol/messages.go b/protocol/messages.go| index d549f3b..8b9618b 100644 |
| --- a/protocol/messages.go |
| +++ b/protocol/messages.go |
| @@ -115,9 +115,9 @@ type RosterPeer struct { |
| // copies the pointer, so a change replaces it. |
| Media *MediaState `json:"media,omitempty"` |
| // Client is what the peer's participation was opened from (spec |
| - // §15.27): "mac 0.4.12", "iphone 0.4.12" or "ipad 0.4.12" for an app |
| + // §15.28): "mac 0.4.12", "iphone 0.4.12" or "ipad 0.4.12" for an app |
| // that says (ClientHeader), "native" for an app that does not — every |
| - // app from before §15.27, recognised by the Go HTTP client's own user |
| + // app from before §15.28, recognised by the Go HTTP client's own user |
| // agent — and absent for a browser, or anything else. Set once, at |
| // open, by the server; a peer cannot set another's. |
| Client string `json:"client,omitempty"` |
diff --git a/protocol/quality.go b/protocol/quality.go| index 869bcf2..4e79e49 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. |
| @@ -174,7 +185,7 @@ type PeerEvents struct { |
| NoSoundFromUs bool `json:"noSoundFromUs,omitempty"` // they listed this client |
| AudioBlocked bool `json:"audioBlocked,omitempty"` // they said their browser blocked sound |
| ScreenStalled bool `json:"screenStalled,omitempty"` // this client reported their screen stalled (§15.21) |
| - // The connection's own recovery (§15.27) during the window: ICE |
| + // The connection's own recovery (§15.28) during the window: ICE |
| // restarts this client made on its own, and times it had the pair |
| // rebuilt from nothing (a `reset`). Older servers drop both. |
| AutoRestarts *float64 `json:"autoRestarts,omitempty"` |
diff --git a/test/browser/call.mjs b/test/browser/call.mjs| index 550934b..f40e349 100644 |
| --- a/test/browser/call.mjs |
| +++ b/test/browser/call.mjs |
| @@ -430,7 +430,7 @@ function state(page) { |
| // are still in their first moments and the words are showing. |
| hearingList: s.hearingList, |
| connecting: s.connecting, |
| - // §15.27: each connection's recovery, the totals, the gate's own |
| + // §15.28: each connection's recovery, the totals, the gate's own |
| // block, the peers' clients and every tile's note, word for word; |
| // and §15.23's words. |
| recovery: s.recovery, |
| @@ -3151,13 +3151,13 @@ const run = { |
| await ctxB.close(); |
| }, |
| - // §15.27, the incident of 2026-10-21 in browsers: A and B in a call, B |
| + // §15.28, the incident of 2026-10-21 in browsers: A and B in a call, B |
| // leaves, A's ICE is blocked (every candidate it sends or receives |
| // pointed at nothing) and C — the same person as B — comes back. Nothing |
| // exchanged during the block is any use afterwards, so the pair is |
| // mended only by fresh candidates. Nobody presses Retry; A has to decode |
| // C again on its own. ICE_RECOVER_OFF=c switches C's recovery off (a |
| - // client from before §15.27, which A must mend alone); =both switches off |
| + // client from before §15.28, which A must mend alone); =both switches off |
| // both, the 0.4.10 baseline, and expects the pair to stay down. |
| // |
| // Both cameras are off unless ICE_RECOVER_CAMERA=on. With a camera |
diff --git a/test/browser/native-ice.mjs b/test/browser/native-ice.mjs| index ef3c964..4df4870 100644 |
| --- a/test/browser/native-ice.mjs |
| +++ b/test/browser/native-ice.mjs |
| @@ -1,4 +1,4 @@ |
| -// native-ice.mjs — spec §15.27 between the Mac app and a browser: a |
| +// native-ice.mjs — spec §15.28 between the Mac app and a browser: a |
| // connection that cannot come up for a while (ICETestBlock, the app's |
| // every candidate either way pointed at nothing) is mended once the path |
| // is back, with nobody pressing anything. Driven by TestNativeMacIceBrowser. |
| @@ -6,7 +6,7 @@ |
| // node native-ice.mjs <origin> <room> <interop binary> <case> |
| // |
| // case "both": both sides are this release. "app-old": the app neither |
| -// mends nor says its version (an app from before §15.27), so the browser |
| +// mends nor says its version (an app from before §15.28), so the browser |
| // mends it alone, and once a minute has passed says the app may be old. |
| // "web-old": the browser's recovery is off, so the app mends it alone. |
| // The browser's camera is off: its own camera watch (§15.16) resets a pair |
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-mute.test.mjs b/test/browser/room-mute.test.mjs| index ba84ae9..9cf47d6 100644 |
| --- a/test/browser/room-mute.test.mjs |
| +++ b/test/browser/room-mute.test.mjs |
| @@ -171,7 +171,7 @@ function reporter({ admitted = true, local = { muted: false, cameraOff: false }, |
| '\nlet mediaExtras = true;' + |
| '\nlet audioBlocked = false;' + |
| '\nlet screenStalled = [];' + |
| - // §15.27: rosterMedia also records each peer's client. |
| + // §15.28: rosterMedia also records each peer's client. |
| '\nconst clients = env.clients = new Map();' + |
| '\nconst noSoundList = () => env.noSound;' + |
| '\nconst hearingList = () => env.heard;' + |
| @@ -195,7 +195,7 @@ function reporter({ admitted = true, local = { muted: false, cameraOff: false }, |
| return { ...made, sent, env }; |
| } |
| -test('a roster records each other peer\'s client, and a browser as none (§15.27)', () => { |
| +test('a roster records each other peer\'s client, and a browser as none (§15.28)', () => { |
| const r = reporter(); |
| r.rosterMedia({ peers: [{ peer: 'me', client: 'mac 0.4.12' }, { peer: 'bea', client: 'native' }, { peer: 'cal' }] }); |
| assert.deepEqual(Array.from(r.env.clients), [['bea', 'native'], ['cal', '']]); |
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-recovery.test.mjs b/test/browser/room-recovery.test.mjs| index 5a89330..62d10a1 100644 |
| --- a/test/browser/room-recovery.test.mjs |
| +++ b/test/browser/room-recovery.test.mjs |
| @@ -1,5 +1,5 @@ |
| // room-recovery.test.mjs — a connection that stops working is mended |
| -// without anyone asking (spec §15.27, 2026-10-21), gated without a browser. |
| +// without anyone asking (spec §15.28, 2026-10-21), gated without a browser. |
| // |
| // node --test test/browser/room-recovery.test.mjs |
| // |
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', () => { |